Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
16 commits
Select commit Hold shift + click to select a range
e9f47ec
fix(server-core): log a server entry deactivate error instead of stop…
Exeloo Nov 23, 2026
0c29f11
test(server-core): cover the server plugin host and the project registry
Exeloo Nov 23, 2026
8c804b6
fix(server-core): keep the shadowed copy when a deactivate stops no s…
Exeloo Nov 23, 2026
a8d9c52
fix(server-core): run a plugin copy asked for while another copy of i…
Exeloo Nov 23, 2026
157a683
test(server-core): stop the server entries a test left running before…
Exeloo Nov 23, 2026
cda13a8
fix(server-core): log a server entry subscription dispose error inste…
Exeloo Nov 23, 2026
8389838
fix(server-core): never start a project plugin server entry asked for…
Exeloo Nov 23, 2026
5194179
fix(server-core): run the shadowed copy again when a project copy fai…
Exeloo Nov 23, 2026
59232c7
fix(server-core): keep a project plugin copy running when its install…
Exeloo Nov 23, 2026
48de06b
fix(server-core): stop an older project sync when a newer one starts
Exeloo Nov 23, 2026
1a42076
fix(server-core): wait only for project plugin activations before a p…
Exeloo Nov 23, 2026
fd1838d
fix(server-core): rank plugin sources so a dev copy keeps running ove…
Exeloo Nov 23, 2026
683472b
fix(server-core): run no shadowed plugin copy again when the host is …
Exeloo Nov 23, 2026
e39cb33
test(server-core): ask for another installed copy in the project copy…
Exeloo Nov 23, 2026
b85fea9
fix(server-core): wait for a project plugin copy queued behind anothe…
Exeloo Nov 23, 2026
dcd8b4f
fix(server-core): wait for a project plugin copy run again after a fa…
Exeloo Nov 23, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
145 changes: 120 additions & 25 deletions packages/server-core/src/plugin/server-plugins.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand Down Expand Up @@ -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<PluginSourceKind, number> = {
bundled: 0,
installed: 1,
project: 2,
dev: 3,
};

interface ActiveServerPlugin {
readonly plugin: LocatedPlugin;
readonly module: ServerPluginModule;
Expand All @@ -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<string, ActiveServerPlugin>();
/** Activations in progress: a second request for the same plugin waits for the first one. */
private readonly _activating = new Map<string, Promise<void>>();
/** 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<void> }
>();
/**
* 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<string>() };
/**
* 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<string, LocatedPlugin>();

constructor(
Expand All @@ -72,74 +98,132 @@ 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<void> {
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<void> {
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<void> {
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);
}
}

/**
* Stops a server entry; resolves with the plugin it was, or nothing when none ran. `wait`: let
* an activation in progress finish first (not from inside that activation).
*/
private async _stop(name: string, dir?: string, wait = true): Promise<LocatedPlugin | undefined> {
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;
}

Expand Down Expand Up @@ -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);
}
}
}
Loading
Loading