Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

3.9 KB
Raw Blame
import { PluginCapabilityAudit } from '../../../db/entities/PluginCapabilityAudit.entity';
import type { PluginCapabilityAuditRepository } from '../../../db/repositories/PluginCapabilityAudit.repository';
import type { PluginRpcRegistry } from '../../../nest-rpc/rpc-kit/registry';
import { PluginRpcRegistryService } from '../../../nest-rpc/rpc-kit/registry.service';
import { appendAudit } from './plugin-audit';
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';

/** Routes inter-plugin calls/events; supplied by PluginRuntimeService (owns the supervisor). */
export interface PluginCallRouter {
  callPlugin(
    callerId: string,
    targetId: string,
    fn: string,
    args: unknown,
    actingUserId: number | undefined,
  ): Promise<unknown>;
  emitPluginEvent(sourceId: string, event: string, payload: unknown): Promise<void>;
}

/**
 * Builds a plugin's capability host (#plugins, M1).
 *
 * This used to be a 900-line wiring sheet: every privileged domain service was
 * 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 data store, the
 * inter-plugin router bound with this plugin as the caller, and the audit sink.
 */
@Injectable()
export class PluginRpcHostFactory {
  constructor(
    @InjectRepository(PluginCapabilityAudit) private readonly audit: PluginCapabilityAuditRepository,
    // 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,
      {
        // Resolve the data handle lazily on every access rather than capturing it once.
        // disable()/uninstall() drop the entry from `running` BEFORE awaiting the kill
        // grace and calling dispose(), so a re-enable in that window builds a NEW host.
        // A captured handle would let the OLD host's dispose() close the DB out from
        // 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.
        // 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, 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),
        emitPluginEvent: (event, payload) => router.emitPluginEvent(id, event, payload),
        audit: (entry) => appendAudit(this.audit, entry),
      },
      this.registry,
    );
  }
}