Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(integration): wire the ingress queue so QUEUE_ENABLED=true actually queues (#921)

Yudhi Armyndharis8644a497223c
diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.ts
index 76c0f7180..36cf1a50c 100644
--- a/src/modules/integration/ingress-enqueue.service.spec.ts
+++ b/src/modules/integration/ingress-enqueue.service.spec.ts
@@ -55,6 +55,42 @@ describe('IngressEnqueueService', () => {
expect(loader.dispatchWebhookForInstance).toHaveBeenCalledWith(data);
});
+ describe('onApplicationBootstrap (queue-wiring tripwire)', () => {
+ const ORIGINAL = process.env.QUEUE_ENABLED;
+
+ afterEach(() => {
+ if (ORIGINAL === undefined) delete process.env.QUEUE_ENABLED;
+ else process.env.QUEUE_ENABLED = ORIGINAL;
+ });
+
+ it('throws when QUEUE_ENABLED=true but no queue resolved (broken wiring must fail the boot)', () => {
+ process.env.QUEUE_ENABLED = 'true';
+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, undefined);
+
+ expect(() => svc.onApplicationBootstrap()).toThrow(
+ /QUEUE_ENABLED=true but the 'ingress-queue' BullMQ queue did not resolve/,
+ );
+ });
+
+ it('does not throw when QUEUE_ENABLED=true and the queue resolved', () => {
+ process.env.QUEUE_ENABLED = 'true';
+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);
+
+ expect(() => svc.onApplicationBootstrap()).not.toThrow();
+ });
+
+ it.each(['false', undefined])(
+ 'does not throw when QUEUE_ENABLED=%s and no queue resolved (inline is the contract)',
+ value => {
+ if (value === undefined) delete process.env.QUEUE_ENABLED;
+ else process.env.QUEUE_ENABLED = value;
+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, undefined);
+
+ expect(() => svc.onApplicationBootstrap()).not.toThrow();
+ },
+ );
+ });
+
it('swallows an inline dispatch error and returns outcome "failed" rather than throwing (row stays redrivable)', async () => {
(loader.dispatchWebhookForInstance as jest.Mock).mockRejectedValue(new Error('boom'));
(config.get as jest.Mock).mockReturnValue(false);
diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.ts
index 328345ce6..a275c1954 100644
--- a/src/modules/integration/ingress-enqueue.service.ts
+++ b/src/modules/integration/ingress-enqueue.service.ts
@@ -1,4 +1,4 @@
-import { Injectable, Optional } from '@nestjs/common';
+import { Injectable, OnApplicationBootstrap, Optional } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { InjectQueue } from '@nestjs/bullmq';
import { Queue } from 'bullmq';
@@ -64,11 +64,15 @@ export function buildIngressDeadLetterRow(data: IngressJobData, error?: string):
* Shared queue-or-inline enqueue for inbound ingress jobs. Extracted out of IngressService's DI
* factory (integration.module.ts) so RedriveService can reuse the exact same behavior when replaying
* DLQ rows: same queue.add args, same inline dispatch-after-persist fallback, same error swallow.
- * The ingress queue is OPTIONAL — it only exists as a provider under QUEUE_ENABLED (QueueModule) —
- * so a missing injection falls back to inline dispatch, mirroring WebhookService's direct fallback.
+ * The ingress queue stays @Optional so a queue-off boot (QUEUE_ENABLED unset/false) needs no
+ * QueueModule — and no Redis — at all; a missing injection then means inline dispatch, mirroring
+ * WebhookService's direct fallback. Under QUEUE_ENABLED=true, IntegrationModule imports QueueModule
+ * so the queue provider MUST resolve; onApplicationBootstrap below fails the boot if it did not, so
+ * a broken queue wiring crashes at startup instead of silently running inline forever (the queued
+ * dispatch contract — fast-ack, retries, ordered processing — would otherwise be dead with no signal).
*/
@Injectable()
-export class IngressEnqueueService {
+export class IngressEnqueueService implements OnApplicationBootstrap {
private readonly logger = createLogger('IngressEnqueueService');
constructor(
@@ -77,6 +81,19 @@ export class IngressEnqueueService {
@Optional() @InjectQueue(QUEUE_NAMES.INGRESS) private readonly ingressQueue?: Queue<IngressJobData>,
) {}
+ onApplicationBootstrap(): void {
+ // Reads the same module-eval signal as the conditional QueueModule imports (integration.module.ts /
+ // webhook.module.ts), not the runtime config, so the check guards exactly the wiring that should
+ // have happened at import time.
+ if (process.env.QUEUE_ENABLED === 'true' && !this.ingressQueue) {
+ throw new Error(
+ `QUEUE_ENABLED=true but the '${QUEUE_NAMES.INGRESS}' BullMQ queue did not resolve — ` +
+ 'IntegrationModule must import QueueModule (see the QUEUE_ENABLED conditional in integration.module.ts). ' +
+ 'Refusing to boot: ingress deliveries would silently dispatch inline, defeating the queued-dispatch contract.',
+ );
+ }
+ }
+
async enqueue(data: IngressJobData, jobId: string): Promise<EnqueueOutcome> {
const queueEnabled = this.config.get<boolean>('queue.enabled', false);
const useQueue = queueEnabled && !!this.ingressQueue;
diff --git a/src/modules/integration/integration-queue-wiring.spec.ts b/src/modules/integration/integration-queue-wiring.spec.ts
new file mode 100644
index 000000000..ed2b93fd0
--- /dev/null
+++ b/src/modules/integration/integration-queue-wiring.spec.ts
@@ -0,0 +1,184 @@
+/**
+ * Wiring coverage for the QUEUE_ENABLED-conditional QueueModule import in integration.module.ts.
+ *
+ * Background: @nestjs/bullmq registers queue providers (token `BullQueue_<name>`) as MODULE-scoped —
+ * a queue is only injectable into providers of a module that imports the module which registered it.
+ * app.module.ts and webhook.module.ts already import QueueModule conditionally, but that does NOT
+ * make the ingress queue visible inside IntegrationModule: without its own conditional import,
+ * IngressEnqueueService's @Optional() @InjectQueue(QUEUE_NAMES.INGRESS) silently resolves to
+ * undefined and every ingress delivery dispatches inline even with QUEUE_ENABLED=true (no fast-ack
+ * deferral, no retries, no ordering, empty Bull Board) with zero signal. These tests compile the
+ * REAL module graph and assert the queue actually reaches IngressEnqueueService.
+ *
+ * process.env.QUEUE_ENABLED is read at MODULE-EVAL time (the lazy-require conditional pattern shared
+ * with webhook.module.ts), so each test sets it BEFORE require()-ing the graph and runs in a fresh
+ * module registry (jest.resetModules()). Nothing from the app may be imported statically at the top
+ * of this file, and every class token inside one test must come from the same registry generation —
+ * DI compares classes by identity, so mixing generations silently breaks injection.
+ *
+ * bullmq's Queue opens an ioredis connection in its constructor and re-emits connection failures as
+ * 'error' events, which would crash a Redis-less unit run. The wiring under test (module graph,
+ * provider tokens, injection) lives entirely in @nestjs/common / @nestjs/bullmq, so only the Redis
+ * client classes are stubbed; every assertion below exercises the real DI machinery.
+ */
+jest.mock('bullmq', () => {
+ const actual = jest.requireActual<Record<string, unknown>>('bullmq');
+ class StubQueue {
+ readonly name: string;
+ constructor(name: string) {
+ this.name = name;
+ }
+ add = jest.fn().mockResolvedValue(undefined);
+ close = jest.fn().mockResolvedValue(undefined);
+ disconnect = jest.fn().mockResolvedValue(undefined);
+ }
+ class StubWorker {
+ close = jest.fn().mockResolvedValue(undefined);
+ }
+ return { ...actual, Queue: StubQueue, Worker: StubWorker };
+});
+
+import type { DynamicModule } from '@nestjs/common';
+
+/** Minimal shape of the stubbed BullMQ queue the assertions need. */
+interface QueueLike {
+ name: string;
+ add: jest.Mock;
+}
+
+describe('IntegrationModule queue wiring (QUEUE_ENABLED conditional)', () => {
+ const ORIGINAL = process.env.QUEUE_ENABLED;
+
+ afterEach(() => {
+ if (ORIGINAL === undefined) delete process.env.QUEUE_ENABLED;
+ else process.env.QUEUE_ENABLED = ORIGINAL;
+ jest.resetModules();
+ });
+
+ async function compileIntegrationModule(queueEnabled: 'true' | 'false') {
+ process.env.QUEUE_ENABLED = queueEnabled;
+ jest.resetModules();
+
+ // require() (not static import) so the module-eval QUEUE_ENABLED conditional sees the value set
+ // above; `as typeof import(...)` is type-only and keeps the typed-lint rules satisfied.
+ /* eslint-disable @typescript-eslint/no-require-imports */
+ const { Test } = require('@nestjs/testing') as typeof import('@nestjs/testing');
+ const { ConfigModule } = require('@nestjs/config') as typeof import('@nestjs/config');
+ const { ThrottlerModule } = require('@nestjs/throttler') as typeof import('@nestjs/throttler');
+ const { getDataSourceToken } = require('@nestjs/typeorm') as typeof import('@nestjs/typeorm');
+ const { getQueueToken } = require('@nestjs/bullmq') as typeof import('@nestjs/bullmq');
+ const configuration = (require('../../config/configuration') as typeof import('../../config/configuration'))
+ .default;
+ const { IntegrationModule } = require('./integration.module') as typeof import('./integration.module');
+ const { IngressEnqueueService } =
+ require('./ingress-enqueue.service') as typeof import('./ingress-enqueue.service');
+ const { HooksModule } = require('../../core/hooks/hooks.module') as typeof import('../../core/hooks/hooks.module');
+ const { PluginsModule } =
+ require('../../core/plugins/plugins.module') as typeof import('../../core/plugins/plugins.module');
+ const { AuditService } = require('../audit/audit.service') as typeof import('../audit/audit.service');
+ const { EventsGateway } = require('../events/events.gateway') as typeof import('../events/events.gateway');
+ const { QueueModule } = require('../queue/queue.module') as typeof import('../queue/queue.module');
+ const { QUEUE_NAMES } = require('../queue/queue-names') as typeof import('../queue/queue-names');
+ /* eslint-enable @typescript-eslint/no-require-imports */
+
+ // The @Global modules app.module.ts imports once (AuditModule/EventsModule), stubbed so this spec
+ // compiles IntegrationModule's real graph without booting HTTP/WS/DB. The 'data' DataSource stub
+ // feeds every TypeOrmModule.forFeature repository factory (entityMetadatas:[] → not a tree entity,
+ // type!=='mongodb' → plain getRepository).
+ const dataSourceStub = {
+ entityMetadatas: [],
+ options: { type: 'sqlite' },
+ getRepository: () => ({}),
+ };
+ const testGlobals: DynamicModule = {
+ module: class TestGlobalsModule {},
+ global: true,
+ providers: [
+ { provide: getDataSourceToken('data'), useValue: dataSourceStub },
+ { provide: AuditService, useValue: { record: jest.fn() } },
+ { provide: EventsGateway, useValue: {} },
+ ],
+ exports: [getDataSourceToken('data'), AuditService, EventsGateway],
+ };
+
+ const moduleRef = await Test.createTestingModule({
+ imports: [
+ ConfigModule.forRoot({ isGlobal: true, ignoreEnvFile: true, load: [configuration] }),
+ // InstanceThrottlerGuard (@UseGuards on the ingress controller) is container-instantiated at
+ // compile time; it needs the throttler options/storage app.module.ts normally provides.
+ ThrottlerModule.forRoot([{ name: 'instance', ttl: 60_000, limit: 120 }]),
+ HooksModule,
+ PluginsModule,
+ testGlobals,
+ IntegrationModule,
+ ],
+ }).compile();
+
+ return { moduleRef, getQueueToken, QUEUE_NAMES, QueueModule, IntegrationModule, IngressEnqueueService };
+ }
+
+ it('QUEUE_ENABLED=true: IntegrationModule imports QueueModule (module metadata)', async () => {
+ const { moduleRef, IntegrationModule, QueueModule } = await compileIntegrationModule('true');
+ try {
+ // MODULE_METADATA.IMPORTS === 'imports'; read via Reflect to avoid another registry-sensitive import.
+ const imports = Reflect.getMetadata('imports', IntegrationModule) as unknown[];
+ expect(imports).toContain(QueueModule);
+ } finally {
+ await moduleRef.close();
+ }
+ });
+
+ it('QUEUE_ENABLED=true: the ingress queue is INJECTED into IngressEnqueueService and enqueue() queues', async () => {
+ const { moduleRef, getQueueToken, QUEUE_NAMES, IngressEnqueueService } = await compileIntegrationModule('true');
+ try {
+ const queue = moduleRef.get<QueueLike>(getQueueToken(QUEUE_NAMES.INGRESS), { strict: false });
+ expect(queue).toBeDefined();
+ expect(queue.name).toBe(QUEUE_NAMES.INGRESS);
+
+ // The decisive assertion. moduleRef.get(token, {strict:false}) alone would ALSO pass pre-fix —
+ // webhook.module.ts imports QueueModule for its own scope, so the queue provider exists in the
+ // container either way. What was broken is the injection INTO IntegrationModule's provider; the
+ // tripwire reads that injected field, so it only stays silent when the wiring genuinely reached
+ // IntegrationModule (pre-fix it throws here even though the token resolves above).
+ const enqueue = moduleRef.get(IngressEnqueueService, { strict: false });
+ expect(() => enqueue.onApplicationBootstrap()).not.toThrow();
+
+ // ...and the full queued-dispatch contract holds: enqueue() hands the job to BullMQ (with the
+ // deliveryId as jobId) instead of falling back to inline dispatch.
+ const outcome = await enqueue.enqueue(
+ {
+ pluginId: 'chatwoot',
+ instanceId: 'acct1',
+ route: 'chatwoot',
+ deliveryId: 'd1',
+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },
+ },
+ 'd1',
+ );
+ expect(outcome).toEqual({ outcome: 'queued' });
+ expect(queue.add).toHaveBeenCalledWith(
+ 'ingress',
+ expect.objectContaining({ deliveryId: 'd1' }),
+ expect.objectContaining({ jobId: 'd1' }),
+ );
+ } finally {
+ await moduleRef.close();
+ }
+ });
+
+ it('QUEUE_ENABLED=false: the module boots queue-free (no queue import, no token, silent tripwire)', async () => {
+ const { moduleRef, getQueueToken, QUEUE_NAMES, IntegrationModule, QueueModule, IngressEnqueueService } =
+ await compileIntegrationModule('false');
+ try {
+ const imports = Reflect.getMetadata('imports', IntegrationModule) as unknown[];
+ expect(imports).not.toContain(QueueModule);
+ expect(() => moduleRef.get<QueueLike>(getQueueToken(QUEUE_NAMES.INGRESS), { strict: false })).toThrow();
+
+ const enqueue = moduleRef.get(IngressEnqueueService, { strict: false });
+ expect(enqueue).toBeDefined();
+ expect(() => enqueue.onApplicationBootstrap()).not.toThrow();
+ } finally {
+ await moduleRef.close();
+ }
+ });
+});
diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.ts
index 102aef248..576636844 100644
--- a/src/modules/integration/integration.module.ts
+++ b/src/modules/integration/integration.module.ts
@@ -1,4 +1,4 @@
-import { Module } from '@nestjs/common';
+import { Module, DynamicModule, Type } from '@nestjs/common';
import { TypeOrmModule, getRepositoryToken } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { PluginInstance } from './entities/plugin-instance.entity';
@@ -25,11 +25,26 @@ import { createLogger } from '../../common/services/logger.service';
* Queue-vs-inline enqueue is delegated to IngressEnqueueService (its own optional-queue injection),
* shared with RedriveService so a DLQ replay goes through the exact same path a live delivery would.
* PluginLoaderService is @Global (PluginsModule), so it injects without importing that module.
+ * QueueModule must be imported here (not only at the app root): @nestjs/bullmq queue providers are
+ * module-scoped, so IngressEnqueueService's @InjectQueue(QUEUE_NAMES.INGRESS) only resolves when this
+ * module imports the module that registered the queue. IngressEnqueueService fails fast at boot if
+ * QUEUE_ENABLED=true but the queue still did not resolve.
*/
+// Only import QueueModule if explicitly enabled to avoid Redis connection errors
+const queueModules: Array<Type | DynamicModule> = [];
+if (process.env.QUEUE_ENABLED === 'true') {
+ // eslint-disable-next-line @typescript-eslint/no-require-imports
+ const queueModule = require('../queue/queue.module') as {
+ QueueModule: Type;
+ };
+ queueModules.push(queueModule.QueueModule);
+}
+
@Module({
imports: [
SessionModule,
TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure], 'data'),
+ ...queueModules,
],
controllers: [IngressController, RedriveController, IntegrationInstanceController],
providers: [