Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(plugins): coalesce concurrent disables of one plugin (#1833)
Yudhi Armyndharis5b4ad6db6447
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 6b1c0fb7c..400b0d20c 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -28,6 +28,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Run a plugin's `onDisable` once when shutdown, uninstall or an update overlaps a disable already in progress.- Answer `503` and keep the previous version when shutdown begins before an update of a plugin the operator switched on has applied.- Disable plugins whose enable is still running at shutdown, after the running ones, and refuse new plugin enables during teardown.- Refuse session starts with `503` once shutdown begins, including one already past its checks.diff --git a/docs/19-plugin-architecture.md b/docs/19-plugin-architecture.mdindex 3a4dad197..1db064263 100644--- a/docs/19-plugin-architecture.md+++ b/docs/19-plugin-architecture.md@@ -581,10 +581,13 @@ double-enable, and engines must match the configured active engine):sandboxed plugin, even if `onDisable` hangs or throws) and unregisters the plugin's hooks. `onModuleDestroy`disables every enabled plugin on graceful shutdown so stateful plugins can flush. Running plugins aredisabled first; then it waits for enables already in flight (a sandboxed enable is three 30 s-bounded-calls) and disables those plugins too. New enables are refused once teardown starts. `uninstallPlugin`-disables + unloads, drops the registry entry, and deletes the plugin's directory and its `ctx.storage`-data dir (built-ins are protected and cannot be uninstalled). The unload path dispatches `onUnload`:-for a sandboxed plugin it runs in the worker between `onDisable` and terminate (a plain disable does+calls) and disables those plugins too. New enables are refused once teardown starts. A disable that+arrives while the same plugin is still being disabled (shutdown overlapping a REST disable, an+uninstall or an update unload) joins the running teardown, so `onDisable` runs once; an unload that+joins this way gets no worker-side `onUnload`. `uninstallPlugin` disables + unloads, drops the+registry entry, and deletes the plugin's directory and its `ctx.storage` data dir (built-ins are+protected and cannot be uninstalled). The unload path dispatches `onUnload`: for a sandboxed plugin+it runs in the worker between `onDisable` and terminate (a plain disable doesNOT fire `onUnload` — disable is reversible and its cleanup hook is `onDisable`).**Context.** `createPluginContext` builds the `PluginContext` (§19.4): a per-plugin logger,diff --git a/src/core/plugins/plugin-lifecycle.ts b/src/core/plugins/plugin-lifecycle.tsindex 974202c40..016003901 100644--- a/src/core/plugins/plugin-lifecycle.ts+++ b/src/core/plugins/plugin-lifecycle.ts@@ -25,6 +25,8 @@ import { resolvePluginMainPath } from './plugin-paths';export class PluginLifecycle {/** Plugin ids whose enable() is in flight — a synchronous lock so concurrent enables can't double-run. */private readonly enabling = new Set<string>();+ /** In-flight disables by plugin id, so a concurrent disable joins the running teardown. */+ private readonly disabling = new Map<string, Promise<void>>();constructor(// The LOADER's logger, deliberately — lifecycle lines carry the PluginLoaderService tag, and@@ -136,6 +138,20 @@ export class PluginLifecycle {return; // Not enabled}+ // Status flips to DISABLED only after the teardown awaits, so a second disable arriving meanwhile+ // (shutdown overlapping a REST disable, an uninstall or an update unload) would pass the check+ // above and run onDisable again. Join the teardown already in flight instead. An unload that joins a plain+ // disable of a sandboxed plugin gets no onUnload, the same as unloading one already disabled.+ const inFlight = this.disabling.get(pluginId);+ if (inFlight) {+ return inFlight;+ }+ const disabling = this.teardown(pluginId, plugin, opts).finally(() => this.disabling.delete(pluginId));+ this.disabling.set(pluginId, disabling);+ return disabling;+ }++ private async teardown(pluginId: string, plugin: PluginInstance, opts?: { unload?: boolean }): Promise<void> {try {const host = this.sandboxHosts.get(pluginId);if (host) {diff --git a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts b/src/core/plugins/plugin-loader-sandbox-routing.spec.tsindex 74a529e9d..cda387f91 100644--- a/src/core/plugins/plugin-loader-sandbox-routing.spec.ts+++ b/src/core/plugins/plugin-loader-sandbox-routing.spec.ts@@ -126,6 +126,27 @@ describe('PluginLoaderService — sandbox tier routing', () => {expect((loader as unknown as { sandboxHosts: Map<string, unknown> }).sandboxHosts.has('p1')).toBe(false);});+ it('runs the worker onDisable and terminate once when shutdown overlaps a disable in flight', async () => {+ const loader = makeLoader();+ seed(loader, { builtIn: false, instance: null });+ await loader.enablePlugin('p1');+ const host = loader.hosts[0];+ let release!: () => void;+ const gate = new Promise<void>(resolve => (release = resolve));+ host.runLifecycle.mockClear().mockReturnValueOnce(gate);++ const disabling = loader.disablePlugin('p1');+ const destroying = loader.onModuleDestroy();+ release();+ await disabling;+ await destroying;++ expect(host.runLifecycle).toHaveBeenCalledTimes(1);+ expect(host.runLifecycle).toHaveBeenCalledWith('onDisable', expect.any(Number));+ expect(host.terminate).toHaveBeenCalledTimes(1);+ expect(pluginOf(loader).status).toBe(PluginStatus.DISABLED);+ });+it('dedups duplicate hook-subscribe from the worker so a flood cannot grow the host registry', async () => {const loader = makeLoader();seed(loader, { builtIn: false, instance: null });diff --git a/src/core/plugins/plugin-loader.service.spec.ts b/src/core/plugins/plugin-loader.service.spec.tsindex 1c3e45ef2..465c01fd9 100644--- a/src/core/plugins/plugin-loader.service.spec.ts+++ b/src/core/plugins/plugin-loader.service.spec.ts@@ -443,6 +443,42 @@ describe('PluginLoaderService — graceful shutdown (onModuleDestroy)', () => {expect(loader.getPlugin('slow-plg')?.status).toBe(PluginStatus.DISABLED);});+ it('joins a disable already in flight instead of running onDisable twice', async () => {+ let release!: () => void;+ const gate = new Promise<void>(resolve => (release = resolve));+ const onDisable = jest.fn(() => gate);+ loader.registerBuiltInPlugin(ext('busy-plg'), { onDisable });+ await loader.enablePlugin('busy-plg');++ const disabling = loader.disablePlugin('busy-plg');+ const destroying = loader.onModuleDestroy();+ release();+ await disabling;+ await destroying;++ expect(onDisable).toHaveBeenCalledTimes(1);+ expect(loader.getPlugin('busy-plg')?.status).toBe(PluginStatus.DISABLED);+ });++ it('joins the disable of an unload already in flight', async () => {+ let release!: () => void;+ const gate = new Promise<void>(resolve => (release = resolve));+ const onDisable = jest.fn(() => gate);+ const onUnload = jest.fn(() => Promise.resolve());+ loader.registerBuiltInPlugin(ext('gone-plg'), { onDisable, onUnload });+ await loader.enablePlugin('gone-plg');++ const unloading = loader.unloadPlugin('gone-plg');+ const destroying = loader.onModuleDestroy();+ release();+ await unloading;+ await destroying;++ expect(onDisable).toHaveBeenCalledTimes(1);+ expect(onUnload).toHaveBeenCalledTimes(1);+ expect(loader.getPlugin('gone-plg')).toBeUndefined();+ });+it('refuses an enable once teardown has begun', async () => {const onEnable = jest.fn(() => Promise.resolve());loader.registerBuiltInPlugin(ext('late-plg'), { onEnable });