mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-21 11:36:05 +00:00
feat(plugins): store plugin data on the engine TREK runs on
PLUGIN_DATA binds the plugin data backend to the engine (the same
{ sqlite, postgres }[engine.id] binding the backup port uses): the SQLite
file per plugin, unchanged, or the Postgres schema per plugin. The host
opens a plugin's store through it and an uninstall that deletes data erases
through it, which drops the schema on Postgres. Nothing outside db/engine
asks which engine runs.
A plugin's SQL is passed through as written, so a plugin needs to know the
dialect: db.engine (db:own) answers 'sqlite' or 'postgres', and the SDK
exposes it as ctx.db.engine(), in the mock host (dbEngine option) and in
dev. The plugin facts are regenerated and the SDK goes to 1.10.0.
The Postgres lane's PGPLUG suite installs, uses and erases plugin data on
Postgres and shows that a plugin reaches neither TREK's users table nor
another plugin's schema.
This commit is contained in:
@@ -37,7 +37,7 @@ export class PluginRpcRegistryService extends PluginRpcRegistry implements OnMod
|
||||
* Separate from validate() because the two answer different questions: this one is
|
||||
* about discovery (which providers were found, and once each), validate() is about
|
||||
* the surface being complete and correctly declared. Keeping them apart lets the
|
||||
* discovery behaviour be tested without assembling all 113 methods first.
|
||||
* discovery behaviour be tested without assembling all 115 methods first.
|
||||
*/
|
||||
scanProviders(): void {
|
||||
// A provider can be wrapped once per module that lists it, so dedupe by instance
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import type { PluginDataDb } from '../../nest/plugins/host/plugin-data.service';
|
||||
import type { PluginDataStore } from '../../nest/plugins/host/plugin-data.service';
|
||||
import type { HookKey, HookPermission, KnownMethod, UnconditionalMethod } from '../../nest/plugins/protocol/envelope';
|
||||
|
||||
/**
|
||||
@@ -18,7 +18,7 @@ import type { HookKey, HookPermission, KnownMethod, UnconditionalMethod } from '
|
||||
export interface PluginRpcContext {
|
||||
readonly pluginId: string;
|
||||
readonly actingUserId: number | undefined;
|
||||
readonly data: PluginDataDb;
|
||||
readonly data: PluginDataStore;
|
||||
/**
|
||||
* The inter-plugin capabilities. PER HOST, like everything else on this context:
|
||||
* the router that backs them is created per plugin and binds THIS plugin as the
|
||||
|
||||
@@ -0,0 +1,109 @@
|
||||
import type { DbSettings } from '../../../app-config';
|
||||
import type { EngineId } from '../../../app-config/db-settings';
|
||||
import { postgresTarget, type DatabaseEngine } from '../../../db/engine';
|
||||
import type { PluginDataStore } from '../../../db/engine/plugin-data';
|
||||
import {
|
||||
dropPluginSchema,
|
||||
PluginDataSlots,
|
||||
pluginDataSlots,
|
||||
PostgresPluginDataStore,
|
||||
} from '../../../db/engine/postgres/plugin-data-store';
|
||||
import { DATABASE_ENGINE, DATABASE_SETTINGS } from '../../database/database-engine.module';
|
||||
import { pluginDataDir } from '../paths';
|
||||
import { PluginDataDb, removePluginData } from './plugin-data.service';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import type { AbstractSqlConnection } from '@mikro-orm/sql';
|
||||
import { Inject, Injectable, type Provider } from '@nestjs/common';
|
||||
|
||||
import type { Kysely } from 'kysely';
|
||||
import fs from 'node:fs';
|
||||
|
||||
/**
|
||||
* Where plugins keep their own data (`db:own`), bound to the engine TREK runs
|
||||
* on (`PLUGIN_DATA`): a SQLite file per plugin beside TREK's own file, or a
|
||||
* schema per plugin in TREK's Postgres database, so a Postgres install
|
||||
* writes no SQLite file to the data volume. The host opens a plugin's store
|
||||
* through it and erases a plugin's data through it on uninstall.
|
||||
*/
|
||||
export interface PluginDataBackend {
|
||||
/** The engine a plugin's SQL runs on, which `db.engine` tells the plugin. */
|
||||
readonly engine: EngineId;
|
||||
/** A store for the plugin `pluginId`, opened on first use. */
|
||||
open(pluginId: string): PluginDataStore;
|
||||
/** Deletes everything the plugin `pluginId` stored: its database and its data directory. */
|
||||
erase(pluginId: string): Promise<void>;
|
||||
}
|
||||
|
||||
export const PLUGIN_DATA = Symbol('PLUGIN_DATA');
|
||||
|
||||
/** Each plugin's own SQLite file under the plugin data directory (`plugin-data.service.ts`). */
|
||||
@Injectable()
|
||||
export class SqlitePluginDataBackend implements PluginDataBackend {
|
||||
readonly engine = 'sqlite' as const;
|
||||
|
||||
open(pluginId: string): PluginDataStore {
|
||||
return new PluginDataDb(pluginId);
|
||||
}
|
||||
|
||||
async erase(pluginId: string): Promise<void> {
|
||||
removePluginData(pluginId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Each plugin's own schema in TREK's Postgres database
|
||||
* (`db/engine/postgres/plugin-data-store.ts`), reached through the ORM's
|
||||
* pool. The plugin's data directory is still created, for the files a plugin
|
||||
* keeps beside its database, and it is what marks a plugin uninstalled with
|
||||
* its data kept (the erasure queue reads it).
|
||||
*/
|
||||
@Injectable()
|
||||
export class PostgresPluginDataBackend implements PluginDataBackend {
|
||||
readonly engine = 'postgres' as const;
|
||||
/** Shared by every plugin's store; made on first use, since on SQLite this provider is built but never used. */
|
||||
private slots: PluginDataSlots | null = null;
|
||||
|
||||
constructor(
|
||||
private readonly orm: MikroORM,
|
||||
@Inject(DATABASE_SETTINGS) private readonly settings: DbSettings,
|
||||
) {}
|
||||
|
||||
open(pluginId: string): PluginDataStore {
|
||||
fs.mkdirSync(pluginDataDir(pluginId), { recursive: true });
|
||||
return new PostgresPluginDataStore(pluginId, this.client(), this.sharedSlots());
|
||||
}
|
||||
|
||||
async erase(pluginId: string): Promise<void> {
|
||||
await dropPluginSchema(this.client(), pluginId);
|
||||
removePluginData(pluginId);
|
||||
}
|
||||
|
||||
private sharedSlots(): PluginDataSlots {
|
||||
if (this.slots === null) {
|
||||
const target = postgresTarget(this.settings);
|
||||
if (!target) throw new Error('The Postgres plugin data store was used without TREK_DB_URL.');
|
||||
this.slots = new PluginDataSlots(pluginDataSlots(target.poolMax));
|
||||
}
|
||||
return this.slots;
|
||||
}
|
||||
|
||||
/** The Kysely client on the ORM's pool. */
|
||||
private client(): Kysely<object> {
|
||||
return (this.orm.em.getConnection() as AbstractSqlConnection).getClient<object>();
|
||||
}
|
||||
}
|
||||
|
||||
/** The two backends, and `PLUGIN_DATA` bound to the one for the engine in use. */
|
||||
export const PLUGIN_DATA_PROVIDERS: Provider[] = [
|
||||
SqlitePluginDataBackend,
|
||||
PostgresPluginDataBackend,
|
||||
{
|
||||
provide: PLUGIN_DATA,
|
||||
useFactory: (
|
||||
engine: DatabaseEngine,
|
||||
sqlite: SqlitePluginDataBackend,
|
||||
postgres: PostgresPluginDataBackend,
|
||||
): PluginDataBackend => ({ sqlite, postgres })[engine.id],
|
||||
inject: [DATABASE_ENGINE, SqlitePluginDataBackend, PostgresPluginDataBackend],
|
||||
},
|
||||
];
|
||||
@@ -1,4 +1,5 @@
|
||||
import { openDatabase } from '../../../db/connection';
|
||||
import { PLUGIN_DATA_CAPS, type PluginDataStore } from '../../../db/engine/plugin-data';
|
||||
import { pluginDataDir, pluginDbFile, pluginsDataRoot } from '../paths';
|
||||
import { splitAfterSemicolons } from './sql-script';
|
||||
|
||||
@@ -6,8 +7,13 @@ import type { Database as Db, Statement } from 'better-sqlite3';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
// The port, re-exported for the RPC kit, which may import from this file only (eslint.config.mjs).
|
||||
export type { PluginDataStore };
|
||||
|
||||
/**
|
||||
* A plugin's own sqlite database (#plugins, db:own). The HOST owns the handle;
|
||||
* A plugin's own sqlite database (#plugins, db:own): the SQLite side of the
|
||||
* `PluginDataStore` port (`db/engine/plugin-data.ts`; the Postgres side is a
|
||||
* schema per plugin, `db/engine/postgres/plugin-data-store.ts`). The HOST owns the handle;
|
||||
* the plugin child never gets a path or a connection — it can only reach this
|
||||
* through RPC (db.exec / db.query / db.migrate). Because it is a SEPARATE FILE,
|
||||
* containment is a filesystem fact: the plugin physically cannot read trek.db,
|
||||
@@ -19,7 +25,7 @@ import path from 'node:path';
|
||||
* script are held to a time budget (below).
|
||||
*/
|
||||
|
||||
const MAX_SQL_LENGTH = 100_000;
|
||||
const MAX_SQL_LENGTH = PLUGIN_DATA_CAPS.maxSqlLength;
|
||||
// RECURSIVE is the one construct that generates unbounded rows/CPU independent of
|
||||
// the (capped) data size — a `WITH RECURSIVE …` can spin the synchronous host
|
||||
// forever even with an empty database, which neither the size quota nor the
|
||||
@@ -39,11 +45,11 @@ const TX_CONTROL = /^\s*(BEGIN|COMMIT|ROLLBACK|SAVEPOINT|RELEASE|END)\b/i;
|
||||
// the file (writes past it fail SQLITE_FULL, contained to the plugin) and bounds
|
||||
// the worst-case scan cost. Result sets are additionally row-capped below so a
|
||||
// recursive CTE / cartesian product can't materialize an unbounded array.
|
||||
const QUOTA_BYTES = 256 * 1024 * 1024;
|
||||
const MAX_ROWS = 100_000;
|
||||
const QUOTA_BYTES = PLUGIN_DATA_CAPS.quotaBytes;
|
||||
const MAX_ROWS = PLUGIN_DATA_CAPS.maxRows;
|
||||
// Cap statements per atomic batch so a single tx() can't monopolise the synchronous
|
||||
// host — generous for real write batches, far below anything abusive.
|
||||
const MAX_TX_OPS = 100;
|
||||
const MAX_TX_OPS = PLUGIN_DATA_CAPS.maxTxOps;
|
||||
// Wall-clock budget for one query(), one whole tx() batch or one exec() script.
|
||||
// better-sqlite3 has no interrupt or progress handler, so the budget is checked
|
||||
// between the rows a statement yields and between the statements of a batch or a
|
||||
@@ -55,7 +61,7 @@ const MAX_TX_OPS = 100;
|
||||
// and the plugin-sdk README says so. migrate() is left unbudgeted on purpose: a
|
||||
// migration is stopped part of the way only to fail the same way on every later
|
||||
// start, which leaves a plugin that cannot update its schema at all.
|
||||
const TIME_BUDGET_MS = 2_000;
|
||||
const TIME_BUDGET_MS = PLUGIN_DATA_CAPS.timeBudgetMs;
|
||||
// What better-sqlite3 throws from prepare() for a statement cut off before its end:
|
||||
// in an exec() script, a trigger body whose semicolon split it.
|
||||
const INCOMPLETE_INPUT = 'incomplete input';
|
||||
@@ -90,9 +96,10 @@ export function checkpointAllPluginDataDbs(): void {
|
||||
}
|
||||
}
|
||||
|
||||
export class PluginDataDb {
|
||||
export class PluginDataDb implements PluginDataStore {
|
||||
private db: Db;
|
||||
readonly pluginId: string;
|
||||
readonly engine = 'sqlite' as const;
|
||||
private readonly limits: PluginDataLimits;
|
||||
|
||||
constructor(pluginId: string, limits: Partial<PluginDataLimits> = {}) {
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import type { PluginDataStore } from '../../../db/engine/plugin-data';
|
||||
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
|
||||
import { DailyBudget, DEFAULT_DAILY_BUDGET } from './daily-budget';
|
||||
import { PluginDataDb } from './plugin-data.service';
|
||||
import type { PluginDataBackend } from './plugin-data.backend';
|
||||
|
||||
/**
|
||||
* Process-wide plugin host state, deliberately module-level (NOT a Nest
|
||||
@@ -17,9 +18,14 @@ import { PluginDataDb } from './plugin-data.service';
|
||||
* to the database that no test can substitute.
|
||||
*/
|
||||
|
||||
const dataDbs = new Map<string, PluginDataDb>();
|
||||
const dataDbs = new Map<string, PluginDataStore>();
|
||||
|
||||
export function getPluginDataDb(id: string): PluginDataDb {
|
||||
/**
|
||||
* The open data store of plugin `id`, opened through `backend` (the one
|
||||
* `PLUGIN_DATA` binds to the engine) when there is none or the cached one was
|
||||
* closed.
|
||||
*/
|
||||
export function getPluginDataDb(id: string, backend: PluginDataBackend): PluginDataStore {
|
||||
let d = dataDbs.get(id);
|
||||
// A cached handle can be CLOSED without being evicted: the supervisor's terminal
|
||||
// failure paths (activation timeout / load-error / crash auto-disable) call
|
||||
@@ -27,7 +33,7 @@ export function getPluginDataDb(id: string): PluginDataDb {
|
||||
// plain admin re-enable would then reuse the closed handle and every db.* call
|
||||
// would throw 'database connection is not open'. Recreate when the handle is shut.
|
||||
if (!d || !d.isOpen()) {
|
||||
d = new PluginDataDb(id);
|
||||
d = backend.open(id);
|
||||
dataDbs.set(id, d);
|
||||
}
|
||||
return d;
|
||||
|
||||
@@ -3,7 +3,8 @@ import type { PluginCapabilityAuditRepository } from '../../../db/repositories/P
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import { PluginRpcRegistryService } from '../../../nest-rpc/rpc-kit/registry.service';
|
||||
import { appendAudit } from './plugin-audit';
|
||||
import { getPluginDataDb } from './plugin-host-state';
|
||||
import { PLUGIN_DATA, type PluginDataBackend } from './plugin-data.backend';
|
||||
import { closePluginDataDb, getPluginDataDb } from './plugin-host-state';
|
||||
import { PluginRpcHost } from './rpc-host';
|
||||
import { InjectRepository } from '@mikro-orm/nestjs';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
@@ -27,7 +28,7 @@ export interface PluginCallRouter {
|
||||
* injected here and handed to the router as a closure. The domains now own their own
|
||||
* plugin surface — one `@PluginController()` provider per domain, discovered at boot
|
||||
* by PluginRpcRegistryService — so all that is left is the three things that are
|
||||
* genuinely per-plugin and belong to nobody else: the plugin's own sqlite handle, the
|
||||
* genuinely per-plugin and belong to nobody else: the plugin's own data store, the
|
||||
* inter-plugin router bound with this plugin as the caller, and the audit sink.
|
||||
*/
|
||||
@Injectable()
|
||||
@@ -37,9 +38,18 @@ export class PluginRpcHostFactory {
|
||||
// Injected by its concrete token, held as the base class: a no-Nest test can then
|
||||
// hand in a createTestPluginRegistry() built from the instances it cares about.
|
||||
@Inject(PluginRpcRegistryService) private readonly registry: PluginRpcRegistry,
|
||||
// Where a plugin's own data lives: a SQLite file, or a schema in TREK's Postgres database.
|
||||
@Inject(PLUGIN_DATA) private readonly pluginData: PluginDataBackend,
|
||||
) {}
|
||||
|
||||
/** Closes plugin `id`'s data store and deletes everything it stored (uninstall with "delete data"). */
|
||||
async erasePluginData(id: string): Promise<void> {
|
||||
closePluginDataDb(id);
|
||||
await this.pluginData.erase(id);
|
||||
}
|
||||
|
||||
create(id: string, granted: ReadonlySet<string>, router: PluginCallRouter): PluginRpcHost {
|
||||
const pluginData = this.pluginData;
|
||||
return new PluginRpcHost(
|
||||
id,
|
||||
granted,
|
||||
@@ -51,10 +61,11 @@ export class PluginRpcHostFactory {
|
||||
// under the NEW one (every db.* call then throws 'database connection is not
|
||||
// open'). Resolving per call means the new host always uses the current, open
|
||||
// handle — getPluginDataDb recreates one the moment a stale dispose closes it.
|
||||
// Safe because db.* is synchronous, so no call is ever mid-flight when a dispose
|
||||
// from another tick closes the handle.
|
||||
// On SQLite db.* is synchronous, so no call is ever mid-flight when a dispose
|
||||
// from another tick closes the handle; on Postgres a close only stops new calls,
|
||||
// and one already running finishes on its own pool connection.
|
||||
get data() {
|
||||
return getPluginDataDb(id);
|
||||
return getPluginDataDb(id, pluginData);
|
||||
},
|
||||
// The router binds this host's plugin id as the caller/source.
|
||||
callPlugin: (targetId, fn, args, actingUserId) => router.callPlugin(id, targetId, fn, args, actingUserId),
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import type { PluginDataStore } from '../../../db/engine/plugin-data';
|
||||
import { BadParams, ForbiddenResource } from '../../../nest-rpc/rpc-errors';
|
||||
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
|
||||
import {
|
||||
@@ -10,7 +11,6 @@ import {
|
||||
} from '../protocol/envelope';
|
||||
import { shapePluginOutput } from '../protocol/output-contract';
|
||||
import { auditResource, isAuditable } from './plugin-audit';
|
||||
import type { PluginDataDb } from './plugin-data.service';
|
||||
|
||||
// Both used to be declared here. They now live in rpc-errors.ts so decorated
|
||||
// *.rpc.ts handlers can throw them without importing the router, and are re-exported
|
||||
@@ -25,7 +25,7 @@ export { BadParams, ForbiddenResource };
|
||||
* plugin cannot "call it anyway" — there is no shared object, only messages, and
|
||||
* the host is the sole holder of the trek.db handle and the broadcast fns.
|
||||
*
|
||||
* The handlers themselves no longer live here. Every one of the 113 wire methods is
|
||||
* The handlers themselves no longer live here. Every one of the 115 wire methods is
|
||||
* a `@PluginMethod` / `@PluginOpenMethod` on a `@PluginController()` provider in its
|
||||
* own domain, and the registry binds the granted subset into the map below. What is
|
||||
* left is the part that was never domain-specific: build the map, dispatch into it,
|
||||
@@ -38,12 +38,12 @@ export { BadParams, ForbiddenResource };
|
||||
/** What the router needs that is neither a domain service nor a permission check. */
|
||||
export interface HostDeps {
|
||||
/**
|
||||
* The plugin's own sqlite (db:own). A GETTER on the factory side, resolved per
|
||||
* access: disable()/re-enable builds a NEW host while the old one's dispose() may
|
||||
* The plugin's own database (db:own): a SQLite file or a Postgres schema. A GETTER
|
||||
* on the factory side, resolved per access: disable()/re-enable builds a NEW host while the old one's dispose() may
|
||||
* still be closing the handle, so a captured one leaves the new host throwing
|
||||
* 'database connection is not open'.
|
||||
*/
|
||||
data: PluginDataDb;
|
||||
data: PluginDataStore;
|
||||
/** Call an export on another plugin (this host's plugin is the caller). Authorizes
|
||||
* the dependency edge + the target's `provides` allowlist, forwards the acting user. */
|
||||
callPlugin(targetId: string, fn: string, args: unknown, actingUserId: number | undefined): Promise<unknown>;
|
||||
|
||||
@@ -4,7 +4,8 @@ import { asArgs, asTxOps, str } from '../../../../nest-rpc/rpc-params';
|
||||
import { PluginUserSettingsService } from '../../plugin-user-settings.service';
|
||||
|
||||
/**
|
||||
* A plugin's OWN sqlite, plus the three methods the router registers unconditionally.
|
||||
* A plugin's OWN database (a SQLite file, or a schema of its own when TREK runs on
|
||||
* Postgres), plus the three methods the router registers unconditionally.
|
||||
*
|
||||
* Every method reads `ctx.data` fresh. It must never be captured in a field or a
|
||||
* closure: the handle is per plugin, and disable()/re-enable builds a new host while
|
||||
@@ -36,6 +37,12 @@ export class DbRpc {
|
||||
return ctx.data.tx(asTxOps(params.ops));
|
||||
}
|
||||
|
||||
/** The engine the plugin's SQL runs on, so a plugin can write the dialect it takes. */
|
||||
@PluginMethod('db.engine', { permission: 'db:own' })
|
||||
engine(_params: Record<string, unknown>, ctx: PluginRpcContext): unknown {
|
||||
return { engine: ctx.data.engine };
|
||||
}
|
||||
|
||||
/**
|
||||
* Inter-plugin call. No permission of its own: the router authorises it against
|
||||
* the declared dependency edge and the target's `provides` allowlist. The acting
|
||||
|
||||
@@ -53,7 +53,6 @@ import path from 'node:path';
|
||||
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
|
||||
import { closePluginDataDb } from './host/plugin-host-state';
|
||||
import { ForbiddenResource } from './host/rpc-host';
|
||||
import { removePluginData } from './host/plugin-data.service';
|
||||
import { isKnownPermission } from './protocol/envelope';
|
||||
import { discoverPlugins, type DiscoveryRepos } from './install/discovery';
|
||||
import { enqueueHookUserDataErasures } from './user-erasure-enqueue';
|
||||
@@ -1091,7 +1090,11 @@ export class PluginRuntimeService implements OnApplicationBootstrap, OnModuleDes
|
||||
// leave a plugin without its row but with its settings, grants or tasks, which a
|
||||
// later plugin reusing the id would inherit. The data dir goes after the commit.
|
||||
await this.uow.transactional(() => this.dropPluginRows(id, deleteData));
|
||||
if (deleteData) removePluginData(id);
|
||||
// The plugin's own database (a SQLite file, or its schema on Postgres) and its data dir.
|
||||
if (deleteData) {
|
||||
if (!this.hostFactory) throw new Error('PluginRpcHostFactory not provided: it is what erases the plugin data');
|
||||
await this.hostFactory.erasePluginData(id);
|
||||
}
|
||||
}
|
||||
|
||||
private async dropPluginRows(id: string, deleteData: boolean): Promise<void> {
|
||||
|
||||
@@ -30,6 +30,7 @@ import { BudgetModule } from '../budget/budget.module';
|
||||
import { CategoriesModule } from '../categories/categories.module';
|
||||
import { CollabModule } from '../collab/collab.module';
|
||||
import { CollectionsModule } from '../collections/collections.module';
|
||||
import { DatabaseEngineModule } from '../database/database-engine.module';
|
||||
import { DayNotesModule } from '../day-notes/day-notes.module';
|
||||
import { DaysModule } from '../days/days.module';
|
||||
import { FilesModule } from '../files/files.module';
|
||||
@@ -47,6 +48,7 @@ import { TripMembershipModule } from '../trip-membership/trip-membership.module'
|
||||
import { TripsModule } from '../trips/trips.module';
|
||||
import { VacayModule } from '../vacay/vacay.module';
|
||||
import { WeatherModule } from '../weather/weather.module';
|
||||
import { PLUGIN_DATA_PROVIDERS } from './host/plugin-data.backend';
|
||||
import { PluginRpcHostFactory } from './host/plugin-rpc-host.factory';
|
||||
import { DbRpc } from './host/rpc/db.rpc';
|
||||
import { HostSurfaceRpc } from './host/rpc/host-surface.rpc';
|
||||
@@ -153,8 +155,11 @@ import { DiscoveryModule } from '@nestjs/core';
|
||||
NotificationsModule,
|
||||
TripMembershipModule,
|
||||
JournalRpcModule,
|
||||
DatabaseEngineModule,
|
||||
],
|
||||
providers: [
|
||||
// Where plugins keep their own data, bound to the engine TREK runs on.
|
||||
...PLUGIN_DATA_PROVIDERS,
|
||||
PluginsService,
|
||||
PluginUserSettingsService,
|
||||
PluginRuntimeService,
|
||||
|
||||
@@ -59,6 +59,7 @@ export const KNOWN_METHODS = [
|
||||
'db.query',
|
||||
'db.migrate',
|
||||
'db.tx',
|
||||
'db.engine',
|
||||
'trips.getById',
|
||||
'trips.getPlaces',
|
||||
'trips.getReservations',
|
||||
@@ -194,6 +195,7 @@ export const METHOD_PERMISSION = {
|
||||
'db.query': 'db:own',
|
||||
'db.migrate': 'db:own',
|
||||
'db.tx': 'db:own',
|
||||
'db.engine': 'db:own',
|
||||
'trips.getById': 'db:read:trips',
|
||||
'trips.getPlaces': 'db:read:trips',
|
||||
'trips.getReservations': 'db:read:trips',
|
||||
|
||||
@@ -633,6 +633,7 @@ export const PLUGIN_METHOD_OUTPUT = {
|
||||
'db.query': HOST,
|
||||
'db.migrate': HOST,
|
||||
'db.tx': HOST,
|
||||
'db.engine': HOST,
|
||||
'trips.getById': row('trip'),
|
||||
'trips.getPlaces': rows('place'),
|
||||
'trips.getReservations': rows('reservation'),
|
||||
|
||||
@@ -24,6 +24,8 @@ export interface PluginContext {
|
||||
query<T = unknown>(sql: string, ...args: unknown[]): Promise<T[]>;
|
||||
exec(sql: string, ...args: unknown[]): Promise<{ changes: number }>;
|
||||
migrate(id: string, sql: string): Promise<{ applied: boolean }>;
|
||||
/** The engine your SQL runs on: 'sqlite' (the default), or 'postgres' when TREK runs on Postgres. */
|
||||
engine(): Promise<'sqlite' | 'postgres'>;
|
||||
/** Run several statements atomically on your OWN db — all commit or all roll
|
||||
* back. Each op is one statement; reads see the batch's own earlier writes.
|
||||
* A read returns `{ rows }`, a write `{ changes }`. Max 100 statements. */
|
||||
@@ -824,6 +826,7 @@ export function createPluginContext(
|
||||
exec: (sql, ...args) => t.rpc('db.exec', { sql, args }) as Promise<{ changes: number }>,
|
||||
migrate: (mid, sql) => t.rpc('db.migrate', { id: mid, sql }) as Promise<{ applied: boolean }>,
|
||||
tx: (ops) => t.rpc('db.tx', { ops }) as Promise<{ results: Array<{ changes?: number; rows?: unknown[] }> }>,
|
||||
engine: () => (t.rpc('db.engine', {}) as Promise<{ engine: 'sqlite' | 'postgres' }>).then((r) => r.engine),
|
||||
},
|
||||
trips: {
|
||||
getById: (tripId) => t.rpc('trips.getById', { tripId, _inv: invocationId }),
|
||||
|
||||
Reference in New Issue
Block a user