Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): register plugin ports as aliases so hooks run once
Yudhi Armyndharis19dfff97a5b3
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a68428930..b96cf09a0 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,9 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- Session auto-start no longer runs twice at boot. The plugin port for `SessionService` was a factory returning+ the same instance, which made Nest dispatch its lifecycle hooks twice: two auto-start loops raced, each+ session logged `Auto-start failed` with `Session is already starting`, and the 2 s launch stagger was lost.- Baileys: requesting a pairing code before the session reaches `qr_ready` answers the documented 409 insteadof a 500 with a `Connection Closed` stack trace, the same guard the whatsapp-web.js engine already carried.Thanks @m7fz7.diff --git a/src/core/plugins/plugin-host-port-providers.spec.ts b/src/core/plugins/plugin-host-port-providers.spec.tsnew file mode 100644index 000000000..0ed06f668--- /dev/null+++ b/src/core/plugins/plugin-host-port-providers.spec.ts@@ -0,0 +1,82 @@+import {+ Injectable,+ Module,+ OnApplicationBootstrap,+ OnModuleDestroy,+ OnModuleInit,+ type Provider,+} from '@nestjs/common';+import { Test } from '@nestjs/testing';+import { PluginsModule } from './plugins.module';+import { IntegrationModule } from '../../modules/integration/integration.module';+import { MessageModule } from '../../modules/message/message.module';+import { SearchModule } from '../../modules/search/search.module';+import { SessionModule } from '../../modules/session/session.module';++/**+ * Every PLUGIN_*_PORT must be registered with `useExisting`, never a factory that returns the+ * service instance. Nest dispatches onModuleInit/onApplicationBootstrap/onModuleDestroy once per+ * non-alias provider, and only `useExisting` is an alias: a factory port ran SessionService's+ * hooks twice, launching two concurrent auto-start loops on every boot. The same applies to any other+ * factory that returns an injected instance (search.module.ts `SEARCH_BOOTSTRAP` returns the registry):+ * harmless while the target has no lifecycle hook, doubled the moment one is added.+ */+describe('plugin host port providers', () => {+ const MODULES = [PluginsModule, IntegrationModule, MessageModule, SearchModule, SessionModule];++ it('registers every PLUGIN_*_PORT as a useExisting alias', () => {+ const ports: string[] = [];+ for (const module of MODULES) {+ const providers = (Reflect.getMetadata('providers', module) as unknown[] | undefined) ?? [];+ for (const provider of providers) {+ if (typeof provider !== 'object' || provider === null || !('provide' in provider)) continue;+ const token = provider.provide;+ const name = typeof token === 'symbol' ? (token.description ?? '') : '';+ if (!/^PLUGIN_.*_PORT$/.test(name)) continue;+ ports.push(name);+ expect({ port: name, alias: 'useExisting' in provider, factory: 'useFactory' in provider }).toEqual({+ port: name,+ alias: true,+ factory: false,+ });+ }+ }+ expect(ports.sort()).toEqual([+ 'PLUGIN_CONVERSATION_MAPPING_PORT',+ 'PLUGIN_INSTANCE_PORT',+ 'PLUGIN_MESSAGE_PORT',+ 'PLUGIN_SEARCH_REGISTRY_PORT',+ 'PLUGIN_SESSION_PORT',+ ]);+ });++ // The same-instance factory shape ran every hook twice under @nestjs/core 11.1.29; only the alias+ // outcome is pinned here, since that is the guarantee the modules above rely on.+ it('runs lifecycle hooks once when the port is a useExisting alias', async () => {+ const PORT = Symbol('PORT');+ const calls = { init: 0, bootstrap: 0, destroy: 0 };++ @Injectable()+ class Hooked implements OnModuleInit, OnApplicationBootstrap, OnModuleDestroy {+ onModuleInit(): void {+ calls.init++;+ }+ onApplicationBootstrap(): void {+ calls.bootstrap++;+ }+ onModuleDestroy(): void {+ calls.destroy++;+ }+ }++ const port: Provider = { provide: PORT, useExisting: Hooked };+ @Module({ providers: [Hooked, port] })+ class Fixture {}+ const app = await Test.createTestingModule({ imports: [Fixture] }).compile();+ await app.init();+ expect(app.get(PORT)).toBe(app.get(Hooked));+ await app.close();++ expect(calls).toEqual({ init: 1, bootstrap: 1, destroy: 1 });+ });+});diff --git a/src/core/plugins/plugin-host-ports.ts b/src/core/plugins/plugin-host-ports.tsindex 546d671a5..9b9e6a050 100644--- a/src/core/plugins/plugin-host-ports.ts+++ b/src/core/plugins/plugin-host-ports.ts@@ -10,8 +10,9 @@ import type { HandoverState } from '../../modules/integration/entities/conversat* call, plus one for the automation reply path. Deliberately not whole-service mirrors: a reviewer* reads here what the plugin runtime can reach, nothing more.*- * The module that owns each service binds it to the port's token with an adapter provider- * (a `useFactory` closing over the real service). Core resolves the TOKEN at call time via+ * The module that owns each service binds it to the port's token with a `useExisting` alias (an+ * alias, not a factory returning the instance: Nest runs lifecycle hooks once per non-alias+ * provider, so a factory doubled the service's hooks). Core resolves the TOKEN at call time via* `ModuleRef.get(..., { strict: false })` — never the service class — so the deferral that breaks* the plugin provider cycle stays, while core/plugins itself imports no feature-module value and* the old lazy `require(...)` of feature-module paths is gone entirely.diff --git a/src/core/plugins/plugins.module.ts b/src/core/plugins/plugins.module.tsindex a47bad5e4..85d315953 100644--- a/src/core/plugins/plugins.module.ts+++ b/src/core/plugins/plugins.module.ts@@ -4,7 +4,7 @@ import { PluginLoaderService } from './plugin-loader.service';import { PluginStorageService } from './plugin-storage.service';import { ConversationMapping } from '../../modules/integration/entities/conversation-mapping.entity';import { ConversationMappingService } from '../../modules/integration/conversation-mapping.service';-import { PLUGIN_CONVERSATION_MAPPING_PORT, type PluginConversationMappingPort } from './plugin-host-ports';+import { PLUGIN_CONVERSATION_MAPPING_PORT } from './plugin-host-ports';@Global() // Make plugin services available everywhere@Module({@@ -16,11 +16,8 @@ import { PLUGIN_CONVERSATION_MAPPING_PORT, type PluginConversationMappingPort }PluginStorageService,PluginLoaderService,ConversationMappingService,- {- provide: PLUGIN_CONVERSATION_MAPPING_PORT,- useFactory: (mappings: ConversationMappingService): PluginConversationMappingPort => mappings,- inject: [ConversationMappingService],- },+ // An alias, not a factory, so lifecycle hooks are not dispatched twice on the same instance.+ { provide: PLUGIN_CONVERSATION_MAPPING_PORT, useExisting: ConversationMappingService },],exports: [PluginLoaderService, PluginStorageService],})diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsindex e8e94cd55..451eefc81 100644--- a/src/modules/integration/integration.module.ts+++ b/src/modules/integration/integration.module.ts@@ -16,7 +16,7 @@ import { IntegrationRetentionService } from './integration-retention.service';import { IntegrationInstanceController } from './integration-instance.controller';import { ScopeBindingService } from './scope-binding.service';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';-import { PLUGIN_INSTANCE_PORT, type PluginInstancePort } from '../../core/plugins/plugin-host-ports';+import { PLUGIN_INSTANCE_PORT } from '../../core/plugins/plugin-host-ports';import { EngineRegistry } from '../../engine/engine-registry.service';import { Session } from '../session/entities/session.entity';import { createLogger } from '../../common/services/logger.service';@@ -58,11 +58,8 @@ if (process.env.QUEUE_ENABLED === 'true') {IntegrationRetentionService,// Binds the core-owned plugin capability port to this module's service; resolved lazily by the// plugin runtime (PluginHostServices) so its provider cycle stays broken.- {- provide: PLUGIN_INSTANCE_PORT,- useFactory: (instances: PluginInstanceService): PluginInstancePort => instances,- inject: [PluginInstanceService],- },+ // An alias, not a factory, so lifecycle hooks are not dispatched twice on the same instance.+ { provide: PLUGIN_INSTANCE_PORT, useExisting: PluginInstanceService },{provide: IngressService,inject: [diff --git a/src/modules/message/message.module.ts b/src/modules/message/message.module.tsindex ea25671f6..1b0811e8f 100644--- a/src/modules/message/message.module.ts+++ b/src/modules/message/message.module.ts@@ -13,7 +13,7 @@ import { Message } from './entities/message.entity';import { Session } from '../session/entities/session.entity';import { SendPacingService } from './send-pacing.service';import { MessageBatch } from './entities/message-batch.entity';-import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/plugin-host-ports';+import { PLUGIN_MESSAGE_PORT } from '../../core/plugins/plugin-host-ports';@Module({imports: [@@ -33,11 +33,8 @@ import { PLUGIN_MESSAGE_PORT, type PluginMessagePort } from '../../core/plugins/// Binds the core-owned plugin capability port to this module's service. The plugin runtime// resolves the token lazily via ModuleRef (PluginHostServices), which keeps its provider cycle// broken; this adapter is how core reaches the service without importing it.- {- provide: PLUGIN_MESSAGE_PORT,- useFactory: (message: MessageService): PluginMessagePort => message,- inject: [MessageService],- },+ // An alias, not a factory, so lifecycle hooks are not dispatched twice on the same instance.+ { provide: PLUGIN_MESSAGE_PORT, useExisting: MessageService },],exports: [MessageService, BulkMessageService, SendPacingService],})diff --git a/src/modules/search/search.module.ts b/src/modules/search/search.module.tsindex aceacb907..a9d4fd8e2 100644--- a/src/modules/search/search.module.ts+++ b/src/modules/search/search.module.ts@@ -4,7 +4,7 @@ import { SearchController } from './search.controller';import { SearchService } from './search.service';import { SearchProviderRegistry } from './search-provider.registry';import { BuiltInFtsProvider } from './providers/builtin-fts.provider';-import { PLUGIN_SEARCH_REGISTRY_PORT, type PluginSearchRegistryPort } from '../../core/plugins/plugin-host-ports';+import { PLUGIN_SEARCH_REGISTRY_PORT } from '../../core/plugins/plugin-host-ports';/*** Wires the global search feature: the route (SearchController), the service layer (SearchService),@@ -51,11 +51,8 @@ export function bootstrapSearchProviders(// Binds the core-owned plugin capability port to this module's registry; resolved lazily by the// plugin runtime (PluginHostServices), which no-ops when this whole module is omitted// (SEARCH_ENABLED=false).- {- provide: PLUGIN_SEARCH_REGISTRY_PORT,- useFactory: (registry: SearchProviderRegistry): PluginSearchRegistryPort => registry,- inject: [SearchProviderRegistry],- },+ // An alias, not a factory, so lifecycle hooks are not dispatched twice on the same instance.+ { provide: PLUGIN_SEARCH_REGISTRY_PORT, useExisting: SearchProviderRegistry },],})export class SearchModule {}diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.tsindex 2d1d4cc8c..7555f8f1e 100644--- a/src/modules/session/session.module.ts+++ b/src/modules/session/session.module.ts@@ -18,7 +18,7 @@ import { WebhookModule } from '../webhook/webhook.module';import { StatusStoreModule } from '../status-store/status-store.module';import { ChatMediaModule } from '../chat-media/chat-media.module';import { AutomationModule } from '../automation/automation.module';-import { PLUGIN_SESSION_PORT, type PluginSessionPort } from '../../core/plugins/plugin-host-ports';+import { PLUGIN_SESSION_PORT } from '../../core/plugins/plugin-host-ports';@Module({// WebhookModule/StatusStoreModule/ChatMediaModule/AutomationModule do not import SessionModule@@ -44,12 +44,10 @@ import { PLUGIN_SESSION_PORT, type PluginSessionPort } from '../../core/plugins/SessionOwnershipService,MessageProjector,// Binds the core-owned plugin capability port to this module's service; resolved lazily by the- // plugin runtime (PluginHostServices) so its provider cycle stays broken.- {- provide: PLUGIN_SESSION_PORT,- useFactory: (session: SessionService): PluginSessionPort => session,- inject: [SessionService],- },+ // plugin runtime (PluginHostServices) so its provider cycle stays broken. An alias, not a+ // factory: Nest runs lifecycle hooks once per non-alias provider, so a factory that returned the+ // same instance ran SessionService's onModuleInit/onApplicationBootstrap/onModuleDestroy twice.+ { provide: PLUGIN_SESSION_PORT, useExisting: SessionService },],exports: [SessionService, MessageProjector, SessionOwnershipService],})