Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(shutdown): keep one failed step from cancelling the rest
Yudhi Armyndharis98bc5e9851b6
diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex 33422e104..eaf7be187 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -1,3 +1,4 @@+import { ShutdownService } from '../../common/services/shutdown.service';import { Injectable, OnApplicationBootstrap, OnModuleInit, OnModuleDestroy, Optional } from '@nestjs/common';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';@@ -153,6 +154,10 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrap// that construct this service with the 4 prior args still compile; when absent, canonicalChatId// degrades to identity (no @lid resolution).@Optional() private readonly lidMappingStore?: LidMappingStoreService,+ // The gateway-wide drain flag. The loader's own `shuttingDown` flips only when PluginsModule is+ // destroyed, last of the global modules, so the boot restore would otherwise keep enabling plugins+ // through the grace and every earlier destroy stage.+ @Optional() private readonly shutdownService?: ShutdownService,) {// Same default the `plugins.dir` key is built from, so this fallback cannot drift away from the// tree PluginStorageService keeps the registry and each plugin's ctx.storage in.@@ -260,7 +265,7 @@ export class PluginLoaderService implements OnModuleInit, OnApplicationBootstrapp => !p.builtIn && this.pluginStorage.getPluginEntry(p.manifest.id)?.enabledByOperator === true,);for (let i = 0; i < restorable.length; i++) {- if (this.shuttingDown) {+ if (this.shuttingDown || this.shutdownService?.isShuttingDown()) {this.logger.log(`Plugin restore stopped at ${i} of ${restorable.length} plugin(s): shutting down`, {action: 'plugin_restore_aborted',});diff --git a/src/core/plugins/plugin-restore-on-boot.spec.ts b/src/core/plugins/plugin-restore-on-boot.spec.tsindex ce6696b01..5a7c76e7e 100644--- a/src/core/plugins/plugin-restore-on-boot.spec.ts+++ b/src/core/plugins/plugin-restore-on-boot.spec.ts@@ -4,6 +4,7 @@ import * as path from 'path';import { ConfigService } from '@nestjs/config';import { ModuleRef } from '@nestjs/core';import { PluginLoaderService } from './plugin-loader.service';+import type { ShutdownService } from '../../common/services/shutdown.service';import { PluginStorageService } from './plugin-storage.service';import { HookManager } from '../hooks';import { PluginStatus, PluginType, type PluginManifest } from './plugin.interfaces';@@ -178,6 +179,39 @@ describe('PluginLoaderService — restoring the operator enable decision across);});+ it('stops restoring plugins once the gateway starts draining, before its own module is destroyed', async () => {+ const second: PluginManifest = { ...manifest, id: 'ext-two', name: 'Ext Two' };+ const secondDir = path.join(tmpDir, 'plugins', second.id);+ fs.mkdirSync(secondDir, { recursive: true });+ fs.writeFileSync(path.join(secondDir, 'manifest.json'), JSON.stringify(second));+ fs.writeFileSync(path.join(secondDir, 'index.js'), 'module.exports = class {};');++ const storage2 = new PluginStorageService(config);+ // The drain flag flips at the signal; PluginsModule is destroyed last, long after.+ let draining = false;+ const shutdown = { isShuttingDown: () => draining };+ const loader2 = new PluginLoaderService(+ config,+ new HookManager(),+ storage2,+ {} as unknown as ModuleRef,+ undefined,+ shutdown as unknown as ShutdownService,+ );+ loader2.loadPlugin(pluginDir);+ loader2.loadPlugin(secondDir);+ storage2.setPluginEnabledByOperator(manifest.id, true);+ storage2.setPluginEnabledByOperator(second.id, true);+ const enable = jest.spyOn(loader2, 'enablePlugin').mockImplementation(() => {+ draining = true;+ return Promise.resolve();+ });++ await loader2.onApplicationBootstrap();++ expect(enable).toHaveBeenCalledTimes(1);+ });+it('does not treat the shutdown teardown as the operator disabling the plugin', async () => {// The regression that makes this whole design fragile: onModuleDestroy disables every enabled// plugin on the way out. If teardown cleared the intent, one graceful restart would erase it anddiff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 6a72408b0..7d8f94dce 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -10001,6 +10001,22 @@ describe('SessionService', () => {return ownership;};+ // A rejection here would make Nest skip every destroy hook after SessionModule's (webhook drain,+ // queue worker close, usage flush, plugin onDisable), and the claims lapse with their lease anyway.+ it('shuts down even when releasing the session claims fails', async () => {+ const ownership = withAutoStartOwnership();+ ownership.releaseAll.mockRejectedValueOnce(new Error('database is locked'));+ const warn = jest.spyOn((service as unknown as { logger: { warn: jest.Mock } }).logger, 'warn');++ await expect(service.onModuleDestroy()).resolves.toBeUndefined();++ expect(ownership.releaseAll).toHaveBeenCalledTimes(1);+ expect(warn).toHaveBeenCalledWith(+ expect.stringContaining('Could not release the session claims'),+ expect.objectContaining({ action: 'session_claim_release_failed', error: 'database is locked' }),+ );+ });+// An init stalled on an unreachable WhatsApp Web settles only at its deadline (>= 60s), past// the kill deadline; the destroy is what ends it, so it cannot wait behind the run.it('destroys the engine of a launch in flight instead of waiting for its init to settle', async () => {diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex e9a111b25..8c3bf6c16 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -386,7 +386,17 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// Released only after the engines are actually down, so a peer never claims a session this// process is still holding open. A start still in flight may own a browser the teardown could// not reach (one the bound above gave up on), so its claim is kept and lapses as after a hard kill.- await this.ownership?.releaseAll(this.startReservations.keys());+ // A failed release is logged and not thrown: a rejection here makes Nest skip every destroy hook+ // after this one (webhook drain, queue worker close, usage flush, plugin onDisable), and the claims+ // lapse with their lease anyway.+ try {+ await this.ownership?.releaseAll(this.startReservations.keys());+ } catch (error) {+ this.logger.warn('Could not release the session claims at shutdown; they lapse with their lease', {+ action: 'session_claim_release_failed',+ error: error instanceof Error ? error.message : String(error),+ });+ }}async create(dto: CreateSessionDto): Promise<Session> {