diff --git a/packages/server-core/src/plugin/server-plugins.ts b/packages/server-core/src/plugin/server-plugins.ts index 83c53b9c..665619ad 100644 --- a/packages/server-core/src/plugin/server-plugins.ts +++ b/packages/server-core/src/plugin/server-plugins.ts @@ -11,7 +11,7 @@ import { import type { Contract, Implementation, RpcRouter } from '@nanoforge-dev/editor-rpc'; import type { RequestContext } from '../session/auth'; -import type { LocatedPlugin } from './plugin-sources'; +import type { LocatedPlugin, PluginSourceKind } from './plugin-sources'; /** Server-side services a plugin server entry may use. */ export interface ServerPluginServices { @@ -40,6 +40,14 @@ export interface ServerPluginModule { export const pluginNamespace = (name: string) => `plugin.${name}`; +/** Which copy of a plugin wins when several sources hold it (later sources shadow earlier ones). */ +const SOURCE_RANK: Record = { + bundled: 0, + installed: 1, + project: 2, + dev: 3, +}; + interface ActiveServerPlugin { readonly plugin: LocatedPlugin; readonly module: ServerPluginModule; @@ -49,9 +57,27 @@ interface ActiveServerPlugin { /** Runs `entry.server` of enabled plugins inside the editor server (trusted plugins). */ export class ServerPluginHost implements Disposable { private readonly _active = new Map(); - /** Activations in progress: a second request for the same plugin waits for the first one. */ - private readonly _activating = new Map>(); - /** Plugins a project's copy of the same name replaced, run again when that copy stops. */ + /** + * The last activation asked for, per name: a request for the same folder shares it, one for + * another copy runs after it. Requests apply in order, except that a running copy of a higher + * source (`SOURCE_RANK`) keeps running over one asked for later, which becomes its shadowed copy. + * `project`: a project copy is somewhere in the chain, or may run again if the copy fails (a + * project sync waits for it). + */ + private readonly _activating = new Map< + string, + { dir: string; project: boolean; done: Promise } + >(); + /** + * The project plugins the last `syncProject` wanted, and its count: a project copy asked for + * before it and not wanted by it never starts (its project closed meanwhile). + */ + private _project = { sync: 0, dirs: new Set() }; + /** + * Plugins a copy of the same name and a higher source replaced, run again when that copy stops. + * shortcut: one per name (a dev copy over a project copy over an installed one forgets the + * installed one), keep a stack if that case shows up. + */ private readonly _shadowed = new Map(); constructor( @@ -72,58 +98,115 @@ export class ServerPluginHost implements Disposable { this._active.get(name)?.plugin.dir === plugin.dir ) return Promise.resolve(); - let activating = this._activating.get(name); - if (!activating) { - activating = this._replace(plugin).finally(() => this._activating.delete(name)); - this._activating.set(name, activating); - } - return activating; + const pending = this._activating.get(name); + if (pending?.dir === plugin.dir) return pending.done; + const { sync } = this._project; + const done = (pending?.done ?? Promise.resolve()) + .then(() => (this._outdated(plugin, sync) ? undefined : this._replace(plugin))) + .finally(() => { + if (this._activating.get(name)?.done === done) this._activating.delete(name); + }); + this._activating.set(name, { + dir: plugin.dir, + project: + plugin.source === 'project' || + pending?.project === true || + this._active.get(name)?.plugin.source === 'project' || + this._shadowed.get(name)?.source === 'project', + done, + }); + return done; } /** * Runs the server entries of exactly these project plugins (those the editor enabled for the * open project) and stops every other project plugin's, those of a previous project included. - * A plugin a project copy had replaced runs again. + * A plugin a project copy had replaced runs again. A newer call takes over: this one stops. */ async syncProject(plugins: readonly LocatedPlugin[]): Promise { const wanted = new Set(plugins.map((plugin) => plugin.dir)); + const sync = this._project.sync + 1; + this._project = { sync, dirs: wanted }; + const names = new Set(plugins.map((plugin) => plugin.manifest?.name)); + /** shortcut: a hung project activate holds every later sync; add a timeout if that shows up. */ + await Promise.all( + [...this._activating] + .filter(([name, pending]) => pending.project || names.has(name)) + .map(([, pending]) => pending.done), + ); + if (this._project.sync !== sync) return; + for (const [name, shadowed] of [...this._shadowed]) { + if (shadowed.source === 'project' && !wanted.has(shadowed.dir)) this._shadowed.delete(name); + } for (const [name, active] of [...this._active]) { + if (this._project.sync !== sync) return; if (active.plugin.source === 'project' && !wanted.has(active.plugin.dir)) await this.deactivate(name); } - for (const plugin of plugins) await this.activate(plugin); + for (const plugin of plugins) { + if (this._project.sync !== sync) return; + await this.activate(plugin); + } } /** * Stops a plugin's server entry; with `dir`, only when the running copy is that folder's. A - * plugin a stopped project copy had replaced runs again. + * plugin the stopped copy had replaced runs again. shortcut: updating an installed copy that + * shadows a bundled one starts the bundled copy for a moment (this restores it, the next `activate` + * replaces it); skip the restore during an update if that ever matters. */ async deactivate(name: string, dir?: string): Promise { if (dir && this._shadowed.get(name)?.dir === dir) this._shadowed.delete(name); const stopped = await this._stop(name, dir); - const shadowed = stopped?.source === 'project' ? this._shadowed.get(name) : undefined; + if (!stopped) return; + const shadowed = this._shadowed.get(name); this._shadowed.delete(name); if (shadowed) await this.activate(shadowed); } + /** + * Stops every server entry; no shadowed copy runs again. `_stop` logs its own errors. + * shortcut: an activation still pending for a name not yet active is not stopped (it can start + * after this); cancel pending activations if the host is ever disposed before shutdown. + */ dispose(): void { - for (const name of [...this._active.keys()]) { - this.deactivate(name).catch((error: unknown) => - this._logs.getLogger(`${name}(server)`).error('Server entry failed to deactivate', error), - ); - } + this._shadowed.clear(); + for (const name of [...this._active.keys()]) void this._stop(name); } - /** Activates a plugin, stopping first another copy of the same name (it shadows it). */ + /** Whether a project copy asked for during sync `sync` is no longer wanted. */ + private _outdated(plugin: LocatedPlugin, sync: number): boolean { + return ( + plugin.source === 'project' && + sync !== this._project.sync && + !this._project.dirs.has(plugin.dir) + ); + } + + /** + * Activates a plugin, stopping first another copy of the same name: the lower source of the two + * becomes the shadowed copy (a copy asked for under a higher one waits behind it). + */ private async _replace(plugin: LocatedPlugin): Promise { const name = plugin.manifest!.name; const current = this._active.get(name); + if (current?.plugin.dir === plugin.dir) return; + if (current && SOURCE_RANK[current.plugin.source] > SOURCE_RANK[plugin.source]) { + this._shadowed.set(name, plugin); + return; + } if (current) { - if (plugin.source === 'project' && current.plugin.source !== 'project') + if (SOURCE_RANK[plugin.source] > SOURCE_RANK[current.plugin.source]) this._shadowed.set(name, current.plugin); await this._stop(name, undefined, false); } await this._activate(plugin); + const shadowed = this._shadowed.get(name); + if (shadowed && !this._active.has(name)) { + this._shadowed.delete(name); + if (shadowed.source !== 'project' || this._project.dirs.has(shadowed.dir)) + await this._activate(shadowed); + } } /** @@ -131,15 +214,16 @@ export class ServerPluginHost implements Disposable { * an activation in progress finish first (not from inside that activation). */ private async _stop(name: string, dir?: string, wait = true): Promise { - if (wait) await this._activating.get(name); + if (wait) await this._activating.get(name)?.done; const active = this._active.get(name); if (!active || (dir && active.plugin.dir !== dir)) return undefined; this._active.delete(name); try { await active.module.deactivate?.(); - } finally { - active.store.dispose(); + } catch (error) { + this._logs.getLogger(`${name}(server)`).error('Server entry failed to deactivate', error); } + this._dispose(name, active.store); return active.plugin; } @@ -176,8 +260,19 @@ export class ServerPluginHost implements Disposable { this._active.set(manifest.name, { plugin, module, store }); logger.info('Server entry activated'); } catch (error) { - store.dispose(); + this._dispose(manifest.name, store); logger.error('Server entry failed to activate', error); } } + + /** Disposes a server entry's subscriptions: one that throws is logged, never stops the caller. */ + private _dispose(name: string, store: DisposableStore): void { + try { + store.dispose(); + } catch (error) { + this._logs + .getLogger(`${name}(server)`) + .error('Server entry failed to dispose its subscriptions', error); + } + } } diff --git a/packages/server-core/test/plugin/server-plugins.spec.ts b/packages/server-core/test/plugin/server-plugins.spec.ts new file mode 100644 index 00000000..3deaf5c6 --- /dev/null +++ b/packages/server-core/test/plugin/server-plugins.spec.ts @@ -0,0 +1,370 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import { afterEach, beforeEach, describe, expect, it } from 'vitest'; + +import { type LogEntry, LoggerService, type PluginManifest } from '@nanoforge-dev/editor-kernel'; +import { RpcRouter } from '@nanoforge-dev/editor-rpc'; + +import type { LocatedPlugin, PluginSourceKind } from '../../src/plugin/plugin-sources'; +import { ServerPluginHost } from '../../src/plugin/server-plugins'; +import type { RequestContext } from '../../src/session/auth'; + +/** What the fixture server entries did, in order (`