Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat: Integration Fabric P1 — ordering, fairness, DLQ redrive, and handover (#570)
Yudhi Armyndharisef4b1e675dfd
diff --git a/.env.example b/.env.exampleindex 44b8c1d66..472300dd2 100644--- a/.env.example+++ b/.env.example@@ -222,6 +222,13 @@ RATE_LIMIT_MEDIUM_LIMIT=100 # max requests per window# RATE_LIMIT_LONG_TTL=3600000 # 1h window (default)# RATE_LIMIT_LONG_LIMIT=1000+# Per-instance fairness cap on the Integration Fabric ingress route (POST /api/ingress/:pluginId/:instanceId/*).+# Providers deliver every tenant's webhooks from one shared egress IP, so this is keyed on+# (pluginId, instanceId) instead of IP — a noisy tenant gets 429'd without throttling its neighbors.+# Independent of, and in addition to, the IP-keyed tiers above.+# INGRESS_INSTANCE_LIMIT=120 # max requests per instance per window (default 120)+# INGRESS_INSTANCE_TTL=60000 # window in ms (default 60000 = 60s)+# =============================================================================# MCP (Model Context Protocol) — Agent / AI-assistant tool server# =============================================================================diff --git a/docs/15-project-roadmap.md b/docs/15-project-roadmap.mdindex e883b0db2..a3dbe17da 100644--- a/docs/15-project-roadmap.md+++ b/docs/15-project-roadmap.md@@ -591,13 +591,13 @@ architecture and design rationale):| Phase | Scope | Status || ----- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------ || P0 | Core substrate: inbound webhook RPC, `@Public` ingress endpoint with HMAC-over-raw-body verification, plugin-instance primitive, normalized send capability, identity/dedup/DLQ tables, ingress queue. SDK v1 frozen. | ✅ Merged (internal substrate) |-| P1 | Scale-correctness: per-conversation FIFO ordering, per-instance fairness, DLQ redrive, bot/human handover, operator provisioning. | 📋 Planned |-| P2 | First adapter (helpdesk inbox) shipped as a marketplace plugin — closes #553 end-to-end. | 📋 Planned |+| P1 | Scale-correctness: per-conversation FIFO ordering, per-instance fairness, DLQ redrive, bot/human handover. | ✅ Merged (internal substrate) |+| P2 | Operator provisioning (mint plugin instances and secrets, dashboard) + the first adapter (helpdesk inbox) shipped as a marketplace plugin — closes #553 end-to-end. | 📋 Planned || P3 | Second adapter (chatbot flow builder) — validates the substrate generalizes. | 📋 Planned || P4 | Developer experience: SDK reference docs, compatibility test suite, secret rotation, multi-node routing. | 📋 Planned |-> **P0 is an internal foundation, not a user-facing feature yet.** The ingress flow requires an operator-> provisioning step (minting a plugin instance and its secret) that lands in P1; until then it is+> **P0 and P1 are an internal foundation, not a user-facing feature yet.** The ingress flow requires an+> operator provisioning step (minting a plugin instance and its secret) that lands in P2; until then it is> reachable only by direct configuration. The public SDK reference and the first ready-to-use adapter> arrive in P2–P4.diff --git a/docs/25-integration-fabric.md b/docs/25-integration-fabric.mdindex a9853b59d..e9aaf09af 100644--- a/docs/25-integration-fabric.md+++ b/docs/25-integration-fabric.md@@ -169,12 +169,13 @@ actually be exercised end to end. Until then this document and the manifest type## 25.9 Phasing and statusSee [15 - Project Roadmap](./15-project-roadmap.md) for the full phase table. In brief: **P0** (this-substrate) is merged as an internal foundation; **P1** adds scale-correctness and operator provisioning;-**P2–P3** ship the first adapters as marketplace plugins; **P4** covers developer experience (SDK+substrate) is merged as an internal foundation; **P1** adds scale-correctness (per-conversation ordering,+per-instance fairness, DLQ redrive, handover); **P2** adds operator provisioning and ships the first+adapter as a marketplace plugin; **P3** ships a second adapter; **P4** covers developer experience (SDKreference, compatibility suite, secret rotation, multi-node routing).-> **P0 is not a user-facing feature yet.** The ingress flow requires an operator provisioning step-> (minting a plugin instance and its secret) that lands in P1; until then it is reachable only by direct+> **P0 and P1 are not a user-facing feature yet.** The ingress flow requires an operator provisioning step+> (minting a plugin instance and its secret) that lands in P2; until then it is reachable only by direct> configuration.---diff --git a/src/config/env.validation.ts b/src/config/env.validation.tsindex 42d668afd..afaaf2784 100644--- a/src/config/env.validation.ts+++ b/src/config/env.validation.ts@@ -87,6 +87,7 @@ export function validateEnv(config: EnvConfig): EnvConfig {'DATABASE_POOL_SIZE','REDIS_CONNECT_TIMEOUT_MS','MAX_CONCURRENT_SESSIONS', // 0 = unlimited+ 'INGRESS_INSTANCE_TTL',]) {checkNonNegativeInt(key);}@@ -102,7 +103,13 @@ export function validateEnv(config: EnvConfig): EnvConfig {errors.push(`${key} must be a positive integer (got "${raw}")`);}};- for (const key of ['RATE_LIMIT_SHORT_LIMIT', 'RATE_LIMIT_MEDIUM_LIMIT', 'RATE_LIMIT_LONG_LIMIT', 'WEBHOOK_TIMEOUT']) {+ for (const key of [+ 'RATE_LIMIT_SHORT_LIMIT',+ 'RATE_LIMIT_MEDIUM_LIMIT',+ 'RATE_LIMIT_LONG_LIMIT',+ 'WEBHOOK_TIMEOUT',+ 'INGRESS_INSTANCE_LIMIT',+ ]) {checkPositiveInt(key);}diff --git a/src/core/plugins/conversation-send-facade.spec.ts b/src/core/plugins/conversation-send-facade.spec.tsindex b86ee31a6..b5443c434 100644--- a/src/core/plugins/conversation-send-facade.spec.ts+++ b/src/core/plugins/conversation-send-facade.spec.ts@@ -1,8 +1,22 @@import { buildConversationSendFacade } from './conversation-send-facade';+import { PluginCapabilityError } from './plugin.interfaces';describe('conversation.send facade', () => {const manifest = (perms: string[]) => ({ id: 'chatwoot', permissions: perms, sessions: ['*'] });+ it('throws PluginCapabilityError when sessionId is missing', async () => {+ const facade = buildConversationSendFacade({+ manifest: manifest(['conversation:send']) as never,+ assertPermission: () => undefined,+ assertSessionAllowed: jest.fn(),+ resolveChatId: () => Promise.resolve('[email protected]'),+ runGuarded: (_events: string[], run: () => Promise<unknown>) => run(),+ sendText: jest.fn(),+ reply: jest.fn(),+ } as never);+ await expect(facade.send({ type: 'text', text: 'x', chatId: 'c' })).rejects.toThrow(PluginCapabilityError);+ });+it('throws PluginCapabilityError when conversation:send is not granted', async () => {const facade = buildConversationSendFacade({manifest: manifest([]) as never,diff --git a/src/core/plugins/conversation-send-facade.ts b/src/core/plugins/conversation-send-facade.tsindex 9ab905cab..eeb30c64a 100644--- a/src/core/plugins/conversation-send-facade.ts+++ b/src/core/plugins/conversation-send-facade.ts@@ -1,4 +1,9 @@-import { ConversationSendEnvelope, PluginCapabilityPermission, PluginManifest } from './plugin.interfaces';+import {+ ConversationSendEnvelope,+ PluginCapabilityError,+ PluginCapabilityPermission,+ PluginManifest,+} from './plugin.interfaces';export interface ConversationSendDeps {manifest: PluginManifest;@@ -22,7 +27,7 @@ export function buildConversationSendFacade(deps: ConversationSendDeps) {async send(env: ConversationSendEnvelope): Promise<unknown> {deps.assertPermission(deps.manifest, PluginCapabilityPermission.CONVERSATION_SEND);const sessionId = env.sessionId;- if (!sessionId) throw new Error('conversation.send: sessionId is required');+ if (!sessionId) throw new PluginCapabilityError('conversation.send: sessionId is required');deps.assertSessionAllowed(deps.manifest, sessionId);const chatId = env.chatId ?? (await deps.resolveChatId(env));// Only text/reply are wired in P0; media types are additive in a later minor.diff --git a/src/core/plugins/handover-gate.spec.ts b/src/core/plugins/handover-gate.spec.tsnew file mode 100644index 000000000..aa48632d2--- /dev/null+++ b/src/core/plugins/handover-gate.spec.ts@@ -0,0 +1,16 @@+import { shouldDispatchInbound } from './handover-gate';++describe('shouldDispatchInbound', () => {+ it('dispatches when there is no mapping (bot is default)', () => {+ expect(shouldDispatchInbound(null)).toBe(true);+ });+ it('dispatches for a bot conversation', () => {+ expect(shouldDispatchInbound({ handoverState: 'bot' } as never)).toBe(true);+ });+ it('does NOT dispatch to the bot for a human-handled conversation', () => {+ expect(shouldDispatchInbound({ handoverState: 'human' } as never)).toBe(false);+ });+ it('does NOT dispatch for a closed conversation', () => {+ expect(shouldDispatchInbound({ handoverState: 'closed' } as never)).toBe(false);+ });+});diff --git a/src/core/plugins/handover-gate.ts b/src/core/plugins/handover-gate.tsnew file mode 100644index 000000000..dc2182c1d--- /dev/null+++ b/src/core/plugins/handover-gate.ts@@ -0,0 +1,7 @@+import { ConversationMapping } from '../../modules/integration/entities/conversation-mapping.entity';++// The core deterministically stops the bot when a human has taken over (or the conversation is+// closed). Default (no mapping yet) = bot, so a brand-new conversation still reaches the adapter.+export function shouldDispatchInbound(mapping: Pick<ConversationMapping, 'handoverState'> | null): boolean {+ return !mapping || mapping.handoverState === 'bot';+}diff --git a/src/core/plugins/plugin-loader.service.ts b/src/core/plugins/plugin-loader.service.tsindex d50465164..896cb30a2 100644--- a/src/core/plugins/plugin-loader.service.ts+++ b/src/core/plugins/plugin-loader.service.ts@@ -14,6 +14,7 @@ import {PluginMessagingCapability,PluginNetCapability,PluginConversationsCapability,+ PluginHandoverCapability,PluginInstance,PluginStatus,PluginContext,@@ -29,6 +30,7 @@ import { WorkerThreadChannel } from './sandbox/worker-thread-channel';import { dispatchCapabilityVerb } from './sandbox/capability-router';import { PluginLogLevel } from './sandbox/protocol';import { buildConversationSendFacade } from './conversation-send-facade';+import { shouldDispatchInbound } from './handover-gate';import { makeOnWebhookSubscribe } from './webhook-subscribe.util';import { INGRESS_DISPATCH_TIMEOUT_MS } from '../../modules/integration/integration.constants';import type { MessageService } from '../../modules/message/message.service';@@ -765,6 +767,30 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {// Per-session activation gate: a session-scoped plugin only sees events for the sessions// it is activated for. Pass-through (don't dispatch into the worker) otherwise.if (!this.isHookActive(plugin, hookCtx.sessionId)) return { continue: true };+ // Handover gate: once a human has taken over (or closed) a conversation, the bot stops+ // seeing its inbound messages. Scoped to message:received only — every other hook event is+ // unaffected. Best-effort + fail-open: a lookup failure (or an event/mapping shape the gate+ // can't resolve) must never block a normal message from reaching the adapter.+ if (event === 'message:received') {+ try {+ const chatId = (hookCtx.data as { chatId?: string } | undefined)?.chatId;+ if (chatId && hookCtx.sessionId) {+ const mapping = await this.getConversationMappingService().findForChat(+ hookCtx.sessionId,+ chatId,+ pluginId,+ );+ if (!shouldDispatchInbound(mapping)) return { continue: true };+ }+ } catch (error) {+ this.logger.debug(`Handover gate lookup failed for plugin ${pluginId}; dispatching normally`, {+ pluginId,+ event,+ error: error instanceof Error ? error.message : String(error),+ action: 'handover_gate_fail_open',+ });+ }+ }return liveHost.dispatchHook({event,@@ -952,6 +978,26 @@ export class PluginLoaderService implements OnModuleInit, OnModuleDestroy {sendText: (sessionId, opts) => this.getMessageService().sendText(sessionId, opts),reply: (sessionId, opts) => this.getMessageService().reply(sessionId, opts),} satisfies Parameters<typeof buildConversationSendFacade>[0]) satisfies PluginConversationsCapability,+ handover: {+ set: async (key, state) => {+ // Same gate as conversation.send: flipping handover is part of owning the conversation, so+ // it reuses CONVERSATION_SEND rather than adding a new permission.+ this.assertPermission(plugin.manifest, PluginCapabilityPermission.CONVERSATION_SEND);+ this.assertSessionAllowed(plugin.manifest, key.sessionId);+ const mapping = await this.getConversationMappingService().get({+ sessionId: key.sessionId,+ chatId: key.chatId,+ pluginId: plugin.manifest.id,+ instanceId: key.instanceId,+ });+ if (!mapping) {+ throw new PluginCapabilityError(+ `Plugin ${plugin.manifest.id}: no conversation mapping for session ${key.sessionId} / chat ${key.chatId} / instance ${key.instanceId}`,+ );+ }+ await this.getConversationMappingService().setHandover(mapping.id, state);+ },+ } satisfies PluginHandoverCapability,};}diff --git a/src/core/plugins/plugin.interfaces.ts b/src/core/plugins/plugin.interfaces.tsindex dacae1c26..7ce22b9fd 100644--- a/src/core/plugins/plugin.interfaces.ts+++ b/src/core/plugins/plugin.interfaces.ts@@ -7,6 +7,7 @@ import { HookManager, HookEvent, HookHandler } from '../hooks';import type { MessageResponseDto } from '../../modules/message/dto';import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';import type { PluginNetRequestInit, PluginNetResponse } from './plugin-net';+import type { HandoverState } from '../../modules/integration/entities/conversation-mapping.entity';// ============================================================================// Plugin Types@@ -284,6 +285,14 @@ export interface PluginConversationsCapability {send(env: ConversationSendEnvelope): Promise<unknown>;}+/**+ * Flip a mapped conversation's handover state. Reuses the `conversation:send` permission — flipping+ * handover is part of owning the conversation, not a distinct capability grant.+ */+export interface PluginHandoverCapability {+ set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;+}+// ============================================================================// Plugin Context (passed to plugin on initialization)// ============================================================================@@ -319,6 +328,9 @@ export interface PluginContext {// Normalized outbound send, translated to MessageService. Requires `conversation:send`.conversations: PluginConversationsCapability;++ // Flip a mapped conversation's bot/human/closed handover state. Requires `conversation:send`.+ handover: PluginHandoverCapability;}export interface PluginLogger {diff --git a/src/core/plugins/sandbox/capability-router.spec.ts b/src/core/plugins/sandbox/capability-router.spec.tsindex 906dc6406..7043a2784 100644--- a/src/core/plugins/sandbox/capability-router.spec.ts+++ b/src/core/plugins/sandbox/capability-router.spec.ts@@ -25,6 +25,9 @@ function makeContext() {conversations: {send: jest.fn().mockResolvedValue({ id: 'm3' }),},+ handover: {+ set: jest.fn().mockResolvedValue(undefined),+ },};}diff --git a/src/core/plugins/sandbox/capability-router.ts b/src/core/plugins/sandbox/capability-router.tsindex ddb321b71..1bffaf3af 100644--- a/src/core/plugins/sandbox/capability-router.ts+++ b/src/core/plugins/sandbox/capability-router.ts@@ -1,10 +1,14 @@import { ConversationSendEnvelope, PluginContext } from '../plugin.interfaces';+import { HandoverState } from '../../../modules/integration/entities/conversation-mapping.entity';/** The subset of the plugin context a sandboxed plugin reaches across the bridge. */export type CapabilityContext = Pick<PluginContext, 'messages' | 'engine' | 'storage' | 'net'> & {conversations: {send(env: ConversationSendEnvelope): Promise<unknown>;};+ handover: {+ set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;+ };};/**@@ -49,6 +53,11 @@ export async function dispatchCapabilityVerb(return context.net.fetch(s(0), args[1] as Parameters<typeof context.net.fetch>[1]);case 'conversation.send':return context.conversations.send(args[0] as ConversationSendEnvelope);+ case 'handover.set':+ return context.handover.set(+ args[0] as { sessionId: string; chatId: string; instanceId: string },+ args[1] as HandoverState,+ );default:throw new Error(`Unknown capability verb: ${verb}`);}diff --git a/src/core/plugins/sandbox/handover-set.spec.ts b/src/core/plugins/sandbox/handover-set.spec.tsnew file mode 100644index 000000000..08c512c58--- /dev/null+++ b/src/core/plugins/sandbox/handover-set.spec.ts@@ -0,0 +1,8 @@+import { dispatchCapabilityVerb } from './capability-router';++it('routes handover.set to context.handover.set with (key, state)', async () => {+ const set = jest.fn().mockResolvedValue(undefined);+ const key = { sessionId: 's', chatId: 'c', instanceId: 'i' };+ await dispatchCapabilityVerb({ handover: { set } } as never, 'handover.set', [key, 'human']);+ expect(set).toHaveBeenCalledWith(key, 'human');+});diff --git a/src/core/plugins/sandbox/worker-capability.ts b/src/core/plugins/sandbox/worker-capability.tsindex 501b20755..2c7328143 100644--- a/src/core/plugins/sandbox/worker-capability.ts+++ b/src/core/plugins/sandbox/worker-capability.ts@@ -1,5 +1,6 @@import { WorkerToHostMessage, HostToWorkerMessage } from './protocol';import { ConversationSendEnvelope } from '../plugin.interfaces';+import { HandoverState } from '../../../modules/integration/entities/conversation-mapping.entity';/*** Worker-side correlation for capability calls. Each `call` posts a `cap` request and resolves when@@ -53,6 +54,9 @@ export interface SandboxCapabilityContext {conversations: {send(env: ConversationSendEnvelope): Promise<unknown>;};+ handover: {+ set(key: { sessionId: string; chatId: string; instanceId: string }, state: HandoverState): Promise<unknown>;+ };}/** Build the proxy capability context handed to a sandboxed plugin in the worker. */@@ -82,5 +86,8 @@ export function buildSandboxContext(client: WorkerCapabilityClient): SandboxCapaconversations: {send: env => client.call('conversation.send', [env]),},+ handover: {+ set: (key, state) => client.call('handover.set', [key, state]),+ },};}diff --git a/src/modules/integration/conversation-mapping.service.ts b/src/modules/integration/conversation-mapping.service.tsindex addb38888..ead7959d3 100644--- a/src/modules/integration/conversation-mapping.service.ts+++ b/src/modules/integration/conversation-mapping.service.ts@@ -30,6 +30,13 @@ export class ConversationMappingService {return this.repo.findOne({ where: key });}+ // Handover-gate lookup: any mapped instance for this plugin's chat, without resolving a specific+ // instanceId at message time. The gate only needs "is THIS plugin's chat handed over?" — if a plugin+ // has multiple instances mapped to the same chat, they share handover intent for this purpose.+ findForChat(sessionId: string, chatId: string, pluginId: string): Promise<ConversationMapping | null> {+ return this.repo.findOne({ where: { sessionId, chatId, pluginId } });+ }+getByProvider(pluginId: string,instanceId: string,diff --git a/src/modules/integration/ingress-enqueue.service.spec.ts b/src/modules/integration/ingress-enqueue.service.spec.tsnew file mode 100644index 000000000..a0876b15f--- /dev/null+++ b/src/modules/integration/ingress-enqueue.service.spec.ts@@ -0,0 +1,61 @@+import { IngressEnqueueService } from './ingress-enqueue.service';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { ConfigService } from '@nestjs/config';++describe('IngressEnqueueService', () => {+ const data = {+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ deliveryId: 'd1',+ sessionId: 'sess-1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ };++ let loader: jest.Mocked<Partial<PluginLoaderService>>;+ let config: jest.Mocked<Partial<ConfigService>>;+ let queue: { add: jest.Mock };++ beforeEach(() => {+ loader = { dispatchWebhookForInstance: jest.fn().mockResolvedValue(undefined) };+ config = { get: jest.fn() };+ queue = { add: jest.fn().mockResolvedValue(undefined) };+ });++ it('adds a job to the ingress queue with the given jobId when queueing is enabled and a queue is present', async () => {+ (config.get as jest.Mock).mockReturnValue(true);+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);++ await svc.enqueue(data, 'd1');++ expect(queue.add).toHaveBeenCalledWith('ingress', data, { jobId: 'd1' });+ expect(loader.dispatchWebhookForInstance).not.toHaveBeenCalled();+ });++ it('dispatches inline when queueing is disabled, even if a queue instance is present', async () => {+ (config.get as jest.Mock).mockReturnValue(false);+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, queue as never);++ await svc.enqueue(data, 'd1');++ expect(queue.add).not.toHaveBeenCalled();+ expect(loader.dispatchWebhookForInstance).toHaveBeenCalledWith(data);+ });++ it('dispatches inline when no queue instance is injected (QUEUE_ENABLED unset)', async () => {+ (config.get as jest.Mock).mockReturnValue(true);+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, undefined);++ await svc.enqueue(data, 'd1');++ expect(loader.dispatchWebhookForInstance).toHaveBeenCalledWith(data);+ });++ it('swallows an inline dispatch error and logs it rather than throwing (row already persisted for redrive)', async () => {+ (loader.dispatchWebhookForInstance as jest.Mock).mockRejectedValue(new Error('boom'));+ (config.get as jest.Mock).mockReturnValue(false);+ const svc = new IngressEnqueueService(loader as PluginLoaderService, config as ConfigService, undefined);++ await expect(svc.enqueue(data, 'd1')).resolves.toBeUndefined();+ });+});diff --git a/src/modules/integration/ingress-enqueue.service.ts b/src/modules/integration/ingress-enqueue.service.tsnew file mode 100644index 000000000..cf00b5595--- /dev/null+++ b/src/modules/integration/ingress-enqueue.service.ts@@ -0,0 +1,53 @@+import { Injectable, Optional } from '@nestjs/common';+import { ConfigService } from '@nestjs/config';+import { InjectQueue } from '@nestjs/bullmq';+import { Queue } from 'bullmq';+import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';+import { IngressJobData } from '../queue/processors/ingress.processor';+import { QUEUE_NAMES } from '../queue/queue-names';+import { createLogger } from '../../common/services/logger.service';++/**+ * 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.+ */+@Injectable()+export class IngressEnqueueService {+ private readonly logger = createLogger('IngressEnqueueService');++ constructor(+ private readonly loader: PluginLoaderService,+ private readonly config: ConfigService,+ @Optional() @InjectQueue(QUEUE_NAMES.INGRESS) private readonly ingressQueue?: Queue<IngressJobData>,+ ) {}++ async enqueue(data: IngressJobData, jobId: string): Promise<void> {+ const queueEnabled = this.config.get<boolean>('queue.enabled', false);+ const useQueue = queueEnabled && !!this.ingressQueue;++ if (useQueue && this.ingressQueue) {+ // jobId = deliveryId gives BullMQ exactly-once enqueue semantics.+ await this.ingressQueue.add('ingress', data, { jobId });+ return;+ }+ // Queue disabled: dispatch inline AFTER the ingress_events row was persisted+ // (persist-before-dispatch still holds), mirroring the webhook direct-delivery fallback.+ try {+ await this.loader.dispatchWebhookForInstance(data);+ } catch (err) {+ // A duplicate delivery already 200s before this point, so a failure here is a real+ // dispatch error. Log and swallow: the row is durably persisted for a later redrive,+ // and the provider still gets its 202 (at-least-once, like the webhook fallback).+ this.logger.error('Inline ingress dispatch failed', err instanceof Error ? err.message : String(err), {+ pluginId: data.pluginId,+ instanceId: data.instanceId,+ route: data.route,+ deliveryId: data.deliveryId,+ action: 'ingress_inline_dispatch_failed',+ });+ }+ }+}diff --git a/src/modules/integration/ingress.controller.ts b/src/modules/integration/ingress.controller.tsindex 7bbd4a9b5..797b8b7ca 100644--- a/src/modules/integration/ingress.controller.ts+++ b/src/modules/integration/ingress.controller.ts@@ -1,7 +1,8 @@-import { All, Controller, Param, Query, Req, Res } from '@nestjs/common';+import { All, Controller, Param, Query, Req, Res, UseGuards } from '@nestjs/common';import type { Request, Response } from 'express';import { Public } from '../auth/decorators/auth.decorators';import { IngressService } from './ingress.service';+import { InstanceThrottlerGuard } from './instance-throttler.guard';// @Public so the global ApiKeyGuard early-returns (providers can't present an API key), but NOT// @SkipThrottle — the global IP throttle stays as a coarse guard (per-instance fairness is P1).@@ -15,6 +16,15 @@ export class IngressController {// Express 5 (path-to-regexp v8) has no bare `*` — Nest's route converter rewrites it to the named// wildcard `*path`, so the trailing segments land in req.params.path (an array), not req.params[0].+ //+ // InstanceThrottlerGuard runs IN ADDITION to the global per-IP ProxyAwareThrottlerGuard (an+ // APP_GUARD, so it still applies here) — two independent buckets, keyed differently, both enforced.+ // Its limit/ttl (INGRESS_INSTANCE_LIMIT / INGRESS_INSTANCE_TTL) are read directly by the guard+ // itself, NOT via @Throttle: @Throttle metadata is reflected on the route and read by every+ // ThrottlerGuard subclass that walks a tier of that name, including the global per-IP guard — so a+ // route-level override here would silently retarget the global guard's tolerance too. See+ // InstanceThrottlerGuard's onModuleInit for how it keeps its tier fully independent.+ @UseGuards(InstanceThrottlerGuard)@All(':pluginId/:instanceId/*path')async receive(@Param('pluginId') pluginId: string,diff --git a/src/modules/integration/instance-throttler.guard.spec.ts b/src/modules/integration/instance-throttler.guard.spec.tsnew file mode 100644index 000000000..5f29cc76f--- /dev/null+++ b/src/modules/integration/instance-throttler.guard.spec.ts@@ -0,0 +1,26 @@+import { InstanceThrottlerGuard } from './instance-throttler.guard';++describe('InstanceThrottlerGuard', () => {+ it('keys the bucket on (pluginId, instanceId) from the route params, not the client IP', async () => {+ const guard = Object.create(InstanceThrottlerGuard.prototype) as InstanceThrottlerGuard & {+ getTracker(req: unknown): Promise<string>;+ };+ const req = { params: { pluginId: 'chatwoot', instanceId: 'acct1' }, ip: '203.0.113.9' };+ await expect(guard.getTracker(req)).resolves.toBe('ingress:chatwoot:acct1');+ });++ it('falls back to the client IP when params are missing (defensive)', async () => {+ const guard = Object.create(InstanceThrottlerGuard.prototype) as InstanceThrottlerGuard & {+ getTracker(req: unknown): Promise<string>;+ };+ await expect(guard.getTracker({ params: {}, ip: '203.0.113.9' })).resolves.toContain('203.0.113.9');+ });++ it('falls back to the client IP when only one of pluginId/instanceId is present', async () => {+ const guard = Object.create(InstanceThrottlerGuard.prototype) as InstanceThrottlerGuard & {+ getTracker(req: unknown): Promise<string>;+ };+ const req = { params: { pluginId: 'chatwoot' }, ip: '203.0.113.9' };+ await expect(guard.getTracker(req)).resolves.toContain('203.0.113.9');+ });+});diff --git a/src/modules/integration/instance-throttler.guard.ts b/src/modules/integration/instance-throttler.guard.tsnew file mode 100644index 000000000..bc273feb1--- /dev/null+++ b/src/modules/integration/instance-throttler.guard.ts@@ -0,0 +1,45 @@+import { Injectable } from '@nestjs/common';+import { ProxyAwareThrottlerGuard } from '../../common/security/proxy-aware-throttler.guard';++/**+ * Rate-limit bucket keyed on the ingress route's (pluginId, instanceId) instead of the client IP.+ *+ * Providers (Chatwoot, Meta, etc.) deliver every tenant's webhooks from the SAME egress IP, so the+ * global `ProxyAwareThrottlerGuard` — keyed on IP — lumps all instances into one bucket: a noisy+ * tenant on one instance would rate-limit every other instance sharing that provider's IP. Keying on+ * the instance instead sheds a single misbehaving `(pluginId, instanceId)` at the edge before it fills+ * the shared ingress queue, without punishing its neighbors.+ *+ * Applied alongside (not instead of) the global IP guard — see ingress.controller.ts. It deliberately+ * does NOT use `@Throttle()` to size its limit: `@Throttle` metadata is reflected on the route/handler+ * and is read by EVERY `ThrottlerGuard` instance that walks a tier of that name — including the global+ * per-IP guard, which shares the exact same `short`/`medium`/`long` tier list from the one process-wide+ * `ThrottlerModule.forRootAsync` config. Overriding one of those tiers here would silently retarget the+ * global guard's tolerance for this route too (proven by an earlier version of this guard's e2e test:+ * a second, unrelated instance got 429'd purely for sharing the test client's IP with a throttled one).+ * Instead, `onModuleInit` below replaces `this.throttlers` with a single self-contained tier that only+ * this guard instance evaluates, so its limit is fully independent of the global guard's tiers.+ */+@Injectable()+export class InstanceThrottlerGuard extends ProxyAwareThrottlerGuard {+ async onModuleInit(): Promise<void> {+ await super.onModuleInit();+ this.throttlers = [+ {+ name: 'instance',+ limit: Number(process.env.INGRESS_INSTANCE_LIMIT ?? 120),+ ttl: Number(process.env.INGRESS_INSTANCE_TTL ?? 60000),+ },+ ];+ }++ protected async getTracker(req: Record<string, unknown>): Promise<string> {+ const params = (req.params ?? {}) as { pluginId?: string; instanceId?: string };+ if (params.pluginId && params.instanceId) {+ return `ingress:${params.pluginId}:${params.instanceId}`;+ }+ // Defensive fallback: params should always be present on the ingress route, but if this guard+ // is ever reused elsewhere (or Nest fails to populate params), don't silently share one bucket.+ return super.getTracker(req);+ }+}diff --git a/src/modules/integration/integration.module.ts b/src/modules/integration/integration.module.tsindex 0cc966216..cac9667ee 100644--- a/src/modules/integration/integration.module.ts+++ b/src/modules/integration/integration.module.ts@@ -1,87 +1,47 @@import { Module } from '@nestjs/common';import { TypeOrmModule } from '@nestjs/typeorm';-import { ConfigService } from '@nestjs/config';-import { getQueueToken } from '@nestjs/bullmq';-import { Queue } from 'bullmq';import { PluginInstance } from './entities/plugin-instance.entity';import { IngressEvent } from './entities/ingress-event.entity';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';import { PluginInstanceService } from './plugin-instance.service';import { IngressEventService } from './ingress-event.service';import { IngressService, IngressRouteDescriptor } from './ingress.service';import { IngressController } from './ingress.controller';+import { IngressEnqueueService } from './ingress-enqueue.service';+import { RedriveService } from './redrive.service';+import { RedriveController } from './redrive.controller';import { PluginLoaderService } from '../../core/plugins/plugin-loader.service';-import { IngressJobData } from '../queue/processors/ingress.processor';-import { QUEUE_NAMES } from '../queue/queue-names';-import { createLogger } from '../../common/services/logger.service';--// The ingress queue token. The queue provider only exists when QueueModule is imported-// (QUEUE_ENABLED=true); otherwise this token has no value and the factory below falls back to inline-// dispatch — mirroring WebhookService's direct-delivery fallback.-const INGRESS_QUEUE_TOKEN = getQueueToken(QUEUE_NAMES.INGRESS);/*** Wires the @Public ingress HTTP surface: instance/event persistence services and the fast-ack* IngressService, whose deps are built by a factory so the pure pipeline stays DI-free and testable.- * The optional ingress queue is resolved by token — present only under QUEUE_ENABLED — and the- * factory picks enqueue-vs-inline exactly like the webhook producer. PluginLoaderService is @Global- * (PluginsModule), so it injects without importing that module.+ * 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.*/@Module({- imports: [TypeOrmModule.forFeature([PluginInstance, IngressEvent], 'data')],- controllers: [IngressController],+ imports: [TypeOrmModule.forFeature([PluginInstance, IngressEvent, IntegrationDeliveryFailure], 'data')],+ controllers: [IngressController, RedriveController],providers: [PluginInstanceService,IngressEventService,+ IngressEnqueueService,+ RedriveService,{provide: IngressService,- // The queue token is OPTIONAL: without QUEUE_ENABLED there is no provider for it, and a required- // dependency would fail to resolve at boot. Optional → undefined, and the factory falls back to inline.- inject: [- PluginInstanceService,- IngressEventService,- PluginLoaderService,- ConfigService,- { token: INGRESS_QUEUE_TOKEN, optional: true },- ],+ inject: [PluginInstanceService, IngressEventService, PluginLoaderService, IngressEnqueueService],useFactory: (instances: PluginInstanceService,events: IngressEventService,loader: PluginLoaderService,- config: ConfigService,- ingressQueue?: Queue<IngressJobData>,+ ingressEnqueue: IngressEnqueueService,) => {- const logger = createLogger('IngressService');- const queueEnabled = config.get<boolean>('queue.enabled', false);- const useQueue = queueEnabled && !!ingressQueue;-return new IngressService({instances: { resolve: (pluginId, instanceId) => instances.resolve(pluginId, instanceId) },manifestRoute: (pluginId, route): IngressRouteDescriptor | undefined =>loader.getPlugin(pluginId)?.manifest.ingress?.find(r => r.route === route),events: { recordOrSkip: input => events.recordOrSkip(input) },- enqueue: async (data, jobId) => {- if (useQueue && ingressQueue) {- // jobId = deliveryId gives BullMQ exactly-once enqueue semantics.- await ingressQueue.add('ingress', data, { jobId });- return;- }- // Queue disabled: dispatch inline AFTER the ingress_events row was persisted- // (persist-before-dispatch still holds), mirroring the webhook direct-delivery fallback.- try {- await loader.dispatchWebhookForInstance(data);- } catch (err) {- // A duplicate delivery already 200s before this point, so a failure here is a real- // dispatch error. Log and swallow: the row is durably persisted for a later redrive,- // and the provider still gets its 202 (at-least-once, like the webhook fallback).- logger.error('Inline ingress dispatch failed', err instanceof Error ? err.message : String(err), {- pluginId: data.pluginId,- instanceId: data.instanceId,- route: data.route,- deliveryId: data.deliveryId,- action: 'ingress_inline_dispatch_failed',- });- }- },+ enqueue: (data, jobId) => ingressEnqueue.enqueue(data, jobId),now: () => Date.now(),});},diff --git a/src/modules/integration/ordering-lock.spec.ts b/src/modules/integration/ordering-lock.spec.tsnew file mode 100644index 000000000..65941e534--- /dev/null+++ b/src/modules/integration/ordering-lock.spec.ts@@ -0,0 +1,92 @@+import { KeyedAsyncLock, orderingKeyFor } from './ordering-lock';+import { IngressJobData } from '../queue/processors/ingress.processor';++describe('KeyedAsyncLock', () => {+ it('serializes runs sharing a key, preserving FIFO order', async () => {+ const lock = new KeyedAsyncLock();+ const order: number[] = [];+ const mk = (n: number, delay: number) =>+ lock.run('k', async () => {+ await new Promise(r => setTimeout(r, delay));+ order.push(n);+ });+ // Same key: even though 1 is slower, 1 must finish before 2 starts (FIFO by enqueue order).+ await Promise.all([mk(1, 20), mk(2, 1)]);+ expect(order).toEqual([1, 2]);+ });++ it('runs different keys concurrently', async () => {+ const lock = new KeyedAsyncLock();+ let concurrent = 0;+ let maxConcurrent = 0;+ const mk = (k: string) =>+ lock.run(k, async () => {+ concurrent++;+ maxConcurrent = Math.max(maxConcurrent, concurrent);+ await new Promise(r => setTimeout(r, 10));+ concurrent--;+ });+ await Promise.all([mk('a'), mk('b'), mk('c')]);+ expect(maxConcurrent).toBeGreaterThan(1);+ });++ it('releases the key even when the guarded fn throws', async () => {+ const lock = new KeyedAsyncLock();+ await expect(+ // eslint-disable-next-line @typescript-eslint/require-await -- fn must match () => Promise<T>+ lock.run('k', async () => {+ throw new Error('boom');+ }),+ ).rejects.toThrow('boom');+ // The key must be free again for the next run.+ // eslint-disable-next-line @typescript-eslint/require-await -- fn must match () => Promise<T>+ await expect(lock.run('k', async () => 'ok')).resolves.toBe('ok');+ });+});++describe('orderingKeyFor', () => {+ function job(overrides: Partial<IngressJobData> = {}): IngressJobData {+ return {+ pluginId: 'chatwoot',+ instanceId: 'acct1',+ route: 'chatwoot',+ deliveryId: 'd1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ ...overrides,+ };+ }++ it('keys on instanceId + providerConversationId when present', () => {+ expect(orderingKeyFor(job({ providerConversationId: 'c1' }))).toBe('acct1:c1');+ });++ it('two jobs with the same providerConversationId share a key', () => {+ const a = orderingKeyFor(job({ deliveryId: 'd1', providerConversationId: 'c1' }));+ const b = orderingKeyFor(job({ deliveryId: 'd2', providerConversationId: 'c1' }));+ expect(a).toBe(b);+ });++ it('two jobs with different providerConversationId do not share a key', () => {+ const a = orderingKeyFor(job({ providerConversationId: 'c1' }));+ const b = orderingKeyFor(job({ providerConversationId: 'c2' }));+ expect(a).not.toBe(b);+ });++ it('falls back to a per-instance key when providerConversationId is absent', () => {+ expect(orderingKeyFor(job())).toBe('instance:acct1');+ });++ it('two jobs with no providerConversationId on the same instance share the fallback key', () => {+ const a = orderingKeyFor(job({ deliveryId: 'd1' }));+ const b = orderingKeyFor(job({ deliveryId: 'd2' }));+ expect(a).toBe(b);+ });++ it('never keys on deliveryId', () => {+ const a = orderingKeyFor(job({ deliveryId: 'd1', providerConversationId: 'c1' }));+ const b = orderingKeyFor(job({ deliveryId: 'd2', providerConversationId: 'c1' }));+ expect(a).not.toContain('d1');+ expect(a).not.toContain('d2');+ expect(a).toBe(b);+ });+});diff --git a/src/modules/integration/ordering-lock.ts b/src/modules/integration/ordering-lock.tsnew file mode 100644index 000000000..815e73223--- /dev/null+++ b/src/modules/integration/ordering-lock.ts@@ -0,0 +1,32 @@+import { IngressJobData } from '../queue/processors/ingress.processor';++// Single-node, in-process keyed lock: a chain of promises per key. The ordering key is a plain+// string (no closures) so a distributed lock (e.g. Redis redlock / SET NX PX) can replace this+// verbatim once ingress runs on more than one node.+export class KeyedAsyncLock {+ private readonly tails = new Map<string, Promise<unknown>>();++ run<T>(key: string, fn: () => Promise<T>): Promise<T> {+ const prev = this.tails.get(key) ?? Promise.resolve();+ // Chain fn after prev; swallow prev's rejection so one failure doesn't poison the chain.+ const next = prev.catch(() => undefined).then(fn);+ this.tails.set(key, next);+ // Clean up the map entry once this is the tail and it settles, to avoid unbounded growth.+ void next+ .catch(() => undefined)+ .finally(() => {+ if (this.tails.get(key) === next) this.tails.delete(key);+ });+ return next;+ }+}++// Key on the CONVERSATION, never the deliveryId (a delivery-unique key would serialize nothing).+// providerConversationId is populated host-side when the plugin manifest declares a conversationId+// pointer; absent it, we serialize per instance — correct (never reorders within a conversation) but+// coarse. Per-instance fallback is the lazy-correct default; the conversation key unlocks+// intra-instance parallelism once the manifest declares the pointer.+export function orderingKeyFor(job: IngressJobData): string {+ if (job.providerConversationId) return `${job.instanceId}:${job.providerConversationId}`;+ return `instance:${job.instanceId}`;+}diff --git a/src/modules/integration/redrive.controller.ts b/src/modules/integration/redrive.controller.tsnew file mode 100644index 000000000..8b459651e--- /dev/null+++ b/src/modules/integration/redrive.controller.ts@@ -0,0 +1,16 @@+import { Controller, Param, Post } from '@nestjs/common';+import { RedriveService } from './redrive.service';++// NOT @Public — this is an operator action guarded by the global ApiKeyGuard (X-API-Key header).+@Controller('integration/instances')+export class RedriveController {+ constructor(private readonly redrive: RedriveService) {}++ @Post(':pluginId/:instanceId/redrive')+ redriveInstance(+ @Param('pluginId') pluginId: string,+ @Param('instanceId') instanceId: string,+ ): Promise<{ redriven: number }> {+ return this.redrive.redriveInstance(pluginId, instanceId);+ }+}diff --git a/src/modules/integration/redrive.service.spec.ts b/src/modules/integration/redrive.service.spec.tsnew file mode 100644index 000000000..267aaaabd--- /dev/null+++ b/src/modules/integration/redrive.service.spec.ts@@ -0,0 +1,107 @@+import { RedriveService } from './redrive.service';+import { IngressEnqueueService } from './ingress-enqueue.service';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { Repository } from 'typeorm';++describe('RedriveService', () => {+ let repo: jest.Mocked<Partial<Repository<IntegrationDeliveryFailure>>>;+ let ingressEnqueue: jest.Mocked<Partial<IngressEnqueueService>>;++ beforeEach(() => {+ repo = { find: jest.fn(), update: jest.fn().mockResolvedValue(undefined) };+ ingressEnqueue = { enqueue: jest.fn().mockResolvedValue(undefined) };+ });++ function makeSvc(): RedriveService {+ return new RedriveService(repo as Repository<IntegrationDeliveryFailure>, ingressEnqueue as IngressEnqueueService);+ }++ it('re-enqueues non-redriven inbound failures for an instance and marks them redriven', async () => {+ const rows = [+ {+ id: 'f1',+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ deliveryId: 'd1',+ payload: {+ route: 'chatwoot',+ providerConversationId: 'conv-1',+ ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ },+ sessionId: 's',+ redriven: false,+ },+ {+ id: 'f2',+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ deliveryId: 'd2',+ payload: { route: 'chatwoot', ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' } },+ sessionId: 's',+ redriven: false,+ },+ ];+ (repo.find as jest.Mock).mockResolvedValue(rows);+ const svc = makeSvc();++ const res = await svc.redriveInstance('p', 'i');++ expect(res.redriven).toBe(2);+ expect(ingressEnqueue.enqueue).toHaveBeenCalledTimes(2);+ expect(ingressEnqueue.enqueue).toHaveBeenNthCalledWith(+ 1,+ {+ pluginId: 'p',+ instanceId: 'i',+ route: 'chatwoot',+ deliveryId: 'd1',+ sessionId: 's',+ providerConversationId: 'conv-1',+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ },+ 'redrive:f1',+ );+ expect(repo.update).toHaveBeenCalledWith({ id: 'f1' }, { redriven: true });+ expect(repo.update).toHaveBeenCalledWith({ id: 'f2' }, { redriven: true });+ });++ it('queries only non-redriven inbound rows for the instance and returns 0 when none are found', async () => {+ (repo.find as jest.Mock).mockResolvedValue([]);+ const svc = makeSvc();++ const res = await svc.redriveInstance('p', 'i');++ expect(repo.find).toHaveBeenCalledWith({+ where: { pluginId: 'p', instanceId: 'i', direction: 'inbound', redriven: false },+ });+ expect(res.redriven).toBe(0);+ expect(ingressEnqueue.enqueue).not.toHaveBeenCalled();+ expect(repo.update).not.toHaveBeenCalled();+ });++ it('falls back to the failure row id as deliveryId when deliveryId is null', async () => {+ const rows = [+ {+ id: 'f3',+ direction: 'inbound',+ pluginId: 'p',+ instanceId: 'i',+ deliveryId: null,+ payload: { route: 'chatwoot', ingress: { headers: {}, query: {}, body: '{}', rawBody: '{}' } },+ sessionId: null,+ redriven: false,+ },+ ];+ (repo.find as jest.Mock).mockResolvedValue(rows);+ const svc = makeSvc();++ await svc.redriveInstance('p', 'i');++ expect(ingressEnqueue.enqueue).toHaveBeenCalledWith(+ expect.objectContaining({ deliveryId: 'f3', sessionId: undefined }),+ 'redrive:f3',+ );+ });+});diff --git a/src/modules/integration/redrive.service.ts b/src/modules/integration/redrive.service.tsnew file mode 100644index 000000000..f31a8c5ed--- /dev/null+++ b/src/modules/integration/redrive.service.ts@@ -0,0 +1,49 @@+import { Injectable } from '@nestjs/common';+import { InjectRepository } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import { IntegrationDeliveryFailure } from './entities/integration-delivery-failure.entity';+import { IngressEnqueueService } from './ingress-enqueue.service';+import { IngressJobData } from '../queue/processors/ingress.processor';++// The ingress processor persists the full ingress payload on the DLQ row as+// { route, providerConversationId?, ingress: <headers/query/body/rawBody> }, so redrive is+// self-contained: it reads stored.ingress back out and re-enqueues without re-reading ingress_events.+interface StoredDlqPayload {+ route?: string;+ providerConversationId?: string;+ ingress?: IngressJobData['payload'];+}++@Injectable()+export class RedriveService {+ constructor(+ @InjectRepository(IntegrationDeliveryFailure, 'data') private readonly repo: Repository<IntegrationDeliveryFailure>,+ private readonly ingressEnqueue: IngressEnqueueService,+ ) {}++ async redriveInstance(pluginId: string, instanceId: string): Promise<{ redriven: number }> {+ const rows = await this.repo.find({ where: { pluginId, instanceId, direction: 'inbound', redriven: false } });++ let redriven = 0;+ for (const row of rows) {+ const stored = (row.payload ?? {}) as StoredDlqPayload;+ // Re-mint a jobId so BullMQ accepts the replay even if the original jobId lingers.+ const jobId = `redrive:${row.id}`;+ await this.ingressEnqueue.enqueue(+ {+ pluginId,+ instanceId,+ route: stored.route ?? '',+ deliveryId: row.deliveryId ?? row.id,+ sessionId: row.sessionId ?? undefined,+ providerConversationId: stored.providerConversationId,+ payload: stored.ingress as IngressJobData['payload'],+ },+ jobId,+ );+ await this.repo.update({ id: row.id }, { redriven: true });+ redriven++;+ }+ return { redriven };+ }+}diff --git a/src/modules/queue/processors/ingress.processor.spec.ts b/src/modules/queue/processors/ingress.processor.spec.tsindex dc6c848e2..bda682fb3 100644--- a/src/modules/queue/processors/ingress.processor.spec.ts+++ b/src/modules/queue/processors/ingress.processor.spec.ts@@ -1,4 +1,5 @@import { IngressProcessor } from './ingress.processor';+import { KeyedAsyncLock } from '../../integration/ordering-lock';function job(overrides = {}) {return {@@ -36,4 +37,78 @@ describe('IngressProcessor', () => {);expect(hooks.execute).toHaveBeenCalledWith('ingress:error', expect.anything(), expect.anything());});++ it('rethrows on a non-final attempt without recording a DLQ row or firing ingress:error', async () => {+ const loader = { dispatchWebhookForInstance: jest.fn().mockRejectedValue(new Error('boom')) };+ const failures = { save: jest.fn().mockResolvedValue(undefined) };+ const hooks = { execute: jest.fn().mockResolvedValue({ continue: true }) };+ const proc = new IngressProcessor(loader as never, failures as never, hooks as never);+ await expect(proc.process(job({ attemptsMade: 0, opts: { attempts: 3 } }))).rejects.toThrow('boom');+ expect(failures.save).not.toHaveBeenCalled();+ expect(hooks.execute).not.toHaveBeenCalled();+ });++ it('serializes two jobs for the same conversation and parallelizes different ones', async () => {+ const started: string[] = [];+ const finished: string[] = [];+ const loader = {+ dispatchWebhookForInstance: jest.fn(async (d: { deliveryId: string }) => {+ started.push(d.deliveryId);+ await new Promise(r => setTimeout(r, d.deliveryId === 'same-1' ? 20 : 1));+ finished.push(d.deliveryId);+ }),+ };+ const proc = new IngressProcessor(loader as never, { save: jest.fn() } as never, { execute: jest.fn() } as never);+ const mk = (deliveryId: string, convo: string) =>+ proc.process({+ data: {+ pluginId: 'p',+ instanceId: 'i',+ route: 'r',+ deliveryId,+ providerConversationId: convo,+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ },+ attemptsMade: 0,+ opts: { attempts: 3 },+ } as never);+ await Promise.all([mk('same-1', 'c1'), mk('same-2', 'c1')]);+ // Same conversation → same-1 finishes before same-2 starts.+ expect(finished.indexOf('same-1')).toBeLessThan(started.indexOf('same-2'));+ });++ it('parallelizes jobs for different conversations', async () => {+ let concurrent = 0;+ let maxConcurrent = 0;+ const loader = {+ dispatchWebhookForInstance: jest.fn(async () => {+ concurrent++;+ maxConcurrent = Math.max(maxConcurrent, concurrent);+ await new Promise(r => setTimeout(r, 10));+ concurrent--;+ }),+ };+ const proc = new IngressProcessor(loader as never, { save: jest.fn() } as never, { execute: jest.fn() } as never);+ const mk = (deliveryId: string, convo: string) =>+ proc.process({+ data: {+ pluginId: 'p',+ instanceId: 'i',+ route: 'r',+ deliveryId,+ providerConversationId: convo,+ payload: { headers: {}, query: {}, body: '{}', rawBody: '{}' },+ },+ attemptsMade: 0,+ opts: { attempts: 3 },+ } as never);+ await Promise.all([mk('d1', 'c1'), mk('d2', 'c2'), mk('d3', 'c3')]);+ expect(maxConcurrent).toBeGreaterThan(1);+ });+});++describe('KeyedAsyncLock import sanity', () => {+ it('is exported from the integration module for processor injection', () => {+ expect(new KeyedAsyncLock()).toBeInstanceOf(KeyedAsyncLock);+ });});diff --git a/src/modules/queue/processors/ingress.processor.ts b/src/modules/queue/processors/ingress.processor.tsindex ac20a30d2..a9058628f 100644--- a/src/modules/queue/processors/ingress.processor.ts+++ b/src/modules/queue/processors/ingress.processor.ts@@ -3,11 +3,12 @@ import { Job } from 'bullmq';import { InjectRepository } from '@nestjs/typeorm';import { Repository } from 'typeorm';import { QUEUE_NAMES } from '../queue-names';-import { workerConnectionOptions } from '../redis-connection';+import { workerConnectionOptions, ingressWorkerConcurrency } from '../redis-connection';import { IntegrationDeliveryFailure } from '../../integration/entities/integration-delivery-failure.entity';import { PluginLoaderService } from '../../../core/plugins/plugin-loader.service';import { HookManager } from '../../../core/hooks';import { createLogger } from '../../../common/services/logger.service';+import { KeyedAsyncLock, orderingKeyFor } from '../../integration/ordering-lock';export interface IngressJobData {pluginId: string;@@ -17,16 +18,18 @@ export interface IngressJobData {sessionId?: string;// Best-effort provider conversation id, extracted host-side from the manifest's conversationId// pointer. Undefined when the route declares no pointer — the per-conversation ordering lock then- // serializes per instance. Carried unused today (concurrency=1) so the scale phase needs no re-plumb.+ // serializes per instance instead (see orderingKeyFor in ../../integration/ordering-lock).providerConversationId?: string;payload: { headers: Record<string, string>; query: Record<string, string>; body: string; rawBody: string };}-// concurrency 1 by design: per-conversation FIFO ordering is refined to a keyed advisory lock in a-// later phase; a single worker keeps ordering correct-by-default until that lock exists.-@Processor(QUEUE_NAMES.INGRESS, { connection: workerConnectionOptions(), concurrency: 1 })+// Ordering within a conversation is guaranteed by the KeyedAsyncLock wrapping dispatch below, so the+// worker no longer needs concurrency 1 to stay correct-by-default; raising it parallelizes unrelated+// conversations instead of head-of-line-blocking every inbound event behind the slowest one.+@Processor(QUEUE_NAMES.INGRESS, { connection: workerConnectionOptions(), concurrency: ingressWorkerConcurrency() })export class IngressProcessor extends WorkerHost {private readonly logger = createLogger('IngressProcessor');+ private readonly lock = new KeyedAsyncLock();constructor(private readonly loader: PluginLoaderService,@@ -40,7 +43,7 @@ export class IngressProcessor extends WorkerHost {async process(job: Job<IngressJobData>): Promise<void> {const d = job.data;try {- await this.loader.dispatchWebhookForInstance(d);+ await this.lock.run(orderingKeyFor(d), () => this.loader.dispatchWebhookForInstance(d));} catch (err) {const errorMessage = err instanceof Error ? err.message : String(err);const isFinalAttempt = job.attemptsMade + 1 >= (job.opts.attempts ?? 1);diff --git a/src/modules/queue/queue.module.ts b/src/modules/queue/queue.module.tsindex e39eceff5..439adbfe9 100644--- a/src/modules/queue/queue.module.ts+++ b/src/modules/queue/queue.module.ts@@ -64,6 +64,10 @@ export { QUEUE_NAMES } from './queue-names';name: QUEUE_NAMES.WEBHOOK,adapter: BullMQAdapter,}),+ BullBoardModule.forFeature({+ name: QUEUE_NAMES.INGRESS,+ adapter: BullMQAdapter,+ }),],providers: [WebhookProcessor, IngressProcessor],exports: [BullModule],diff --git a/src/modules/queue/redis-connection.ts b/src/modules/queue/redis-connection.tsindex 598ad4fc9..e59204bde 100644--- a/src/modules/queue/redis-connection.ts+++ b/src/modules/queue/redis-connection.ts@@ -43,3 +43,18 @@ export function webhookWorkerConcurrency(): number {const parsed = parseInt(process.env.WEBHOOK_WORKER_CONCURRENCY || '', 10);return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_WEBHOOK_WORKER_CONCURRENCY;}++/** Default number of ingress events the Worker processes in parallel. */+const DEFAULT_INGRESS_WORKER_CONCURRENCY = 10;++/**+ * Ingress Worker concurrency. Ordering within a conversation is now guaranteed by the+ * per-conversation KeyedAsyncLock in the processor, not by a single-worker queue, so raising+ * concurrency here parallelizes unrelated conversations instead of head-of-line-blocking every+ * inbound event behind the slowest one. Override via INGRESS_WORKER_CONCURRENCY; a+ * non-positive/garbage value falls back to the default.+ */+export function ingressWorkerConcurrency(): number {+ const parsed = parseInt(process.env.INGRESS_WORKER_CONCURRENCY || '', 10);+ return Number.isInteger(parsed) && parsed > 0 ? parsed : DEFAULT_INGRESS_WORKER_CONCURRENCY;+}diff --git a/test/ingress-instance-throttle.e2e-spec.ts b/test/ingress-instance-throttle.e2e-spec.tsnew file mode 100644index 000000000..35072bae4--- /dev/null+++ b/test/ingress-instance-throttle.e2e-spec.ts@@ -0,0 +1,141 @@+// archiver v8 is ESM-only and is pulled in transitively via the @Global StorageModule when+// AppModule boots; stub it so ts-jest (CommonJS) can load the module graph.+jest.mock('archiver', () => ({ TarArchive: jest.fn() }));++// Set BEFORE AppModule is imported: InstanceThrottlerGuard reads these directly in its onModuleInit+// (a lifecycle hook that runs once at boot), not per-request, so they must be in place before the+// Nest testing module is compiled below.+process.env.INGRESS_INSTANCE_LIMIT = '3';+process.env.INGRESS_INSTANCE_TTL = '60000';++import { createHmac, randomBytes } from 'node:crypto';+import { readFileSync } from 'node:fs';+import { join } from 'node:path';+import { Test, TestingModule } from '@nestjs/testing';+import { INestApplication, ValidationPipe } from '@nestjs/common';+import { getRepositoryToken } from '@nestjs/typeorm';+import { Repository } from 'typeorm';+import request from 'supertest';+import { App } from 'supertest/types';+import { json, urlencoded, Request } from 'express';+import { AppModule } from './../src/app.module';+import { PluginLoaderService } from './../src/core/plugins/plugin-loader.service';+import { PluginInstance } from './../src/modules/integration/entities/plugin-instance.entity';++/**+ * Deterministic proof that InstanceThrottlerGuard actually enforces its per-route limit, and that two+ * different instances get independent buckets (a noisy tenant doesn't starve its neighbor). Uses its+ * own low INGRESS_INSTANCE_LIMIT (3) set before AppModule boots, rather than the shared e2e app in+ * integration-fabric.e2e-spec.ts, so hammering past the limit is fast and doesn't perturb the golden+ * 202/401 coverage there (which relies on the default limit of 120 never being hit).+ */+describe('Ingress per-instance fairness throttle (e2e)', () => {+ let app: INestApplication<App>;+ let instanceRepo: Repository<PluginInstance>;++ const secret = randomBytes(32).toString('hex');+ const raw = readFileSync(+ join(__dirname, '../src/modules/integration/__fixtures__/chatwoot-message_created.json'),+ 'utf8',+ );+ const sig = 'sha256=' + createHmac('sha256', secret).update(raw).digest('hex');++ const ingressManifestRoute = {+ route: 'chatwoot',+ mode: 'async' as const,+ verify: 'core' as const,+ maxBodyBytes: 262144,+ signature: {+ scheme: 'hmac-sha256' as const,+ header: 'X-Chatwoot-Signature',+ contentTemplate: '{rawBody}',+ encoding: 'hex' as const,+ prefix: 'sha256=',+ },+ dedupHeader: 'x-chatwoot-delivery',+ };++ beforeAll(async () => {+ const moduleFixture: TestingModule = await Test.createTestingModule({+ imports: [AppModule],+ }).compile();++ app = moduleFixture.createNestApplication();+ app.setGlobalPrefix('api');+ app.useGlobalPipes(new ValidationPipe({ whitelist: true, transform: true }));+ app.use(+ json({+ verify: (req: Request & { rawBody?: Buffer }, _res, buf) => {+ req.rawBody = buf;+ },+ }),+ );+ app.use(urlencoded({ extended: true }));+ await app.init();++ instanceRepo = app.get(getRepositoryToken(PluginInstance, 'data'));++ const loader = app.get(PluginLoaderService);+ const realGetPlugin = loader.getPlugin.bind(loader);+ jest.spyOn(loader, 'getPlugin').mockImplementation((pluginId: string) => {+ if (pluginId === 'chatwoot') {+ return { manifest: { ingress: [ingressManifestRoute] } } as unknown as ReturnType<typeof loader.getPlugin>;+ }+ return realGetPlugin(pluginId);+ });+ jest.spyOn(loader, 'dispatchWebhookForInstance').mockResolvedValue(undefined);++ for (const instanceId of ['acct1', 'acct2']) {+ await instanceRepo.save(+ instanceRepo.create({+ id: `chatwoot:${instanceId}`,+ pluginId: 'chatwoot',+ instanceId,+ secret,+ enabled: true,+ sessionScope: 'sess-1',+ verifyToken: null,+ config: null,+ }),+ );+ }+ });++ afterAll(async () => {+ try {+ await app?.close();+ } catch {+ /* ignore teardown-only multi-datasource quirk */+ }+ });++ const send = (instanceId: string, deliveryId: string) =>+ request(app.getHttpServer())+ .post(`/api/ingress/chatwoot/${instanceId}/chatwoot`)+ .set('X-Chatwoot-Signature', sig)+ .set('X-Chatwoot-Delivery', deliveryId)+ .set('Content-Type', 'application/json')+ .send(raw);++ it('429s the Nth+1 request within the TTL, and does not starve a different instance', async () => {+ // INGRESS_INSTANCE_LIMIT=3: the first 3 requests on acct1 succeed, the 4th is shed at the edge.+ for (let i = 0; i < 3; i++) {+ const res = await send('acct1', `acct1-${i}`);+ expect(res.status).toBe(202);+ }++ const blocked = await send('acct1', 'acct1-overflow');+ expect(blocked.status).toBe(429);+ // ThrottlerGuard runs as a guard, before the handler, so it throws ThrottlerException before the+ // controller's @Res() is ever reached — the header is set on the real response object directly+ // from the guard layer and the global exception filter formats the 429 body. Confirm both survive+ // the @Res() route (not just the status code).+ expect(blocked.headers['retry-after-instance']).toBeDefined();+ expect(blocked.body).toMatchObject({ statusCode: 429 });++ // A different (pluginId, instanceId) shares the provider's egress IP but gets an independent+ // bucket — it must NOT be affected by acct1 having just been throttled.+ const other = await send('acct2', 'acct2-0');+ expect(other.status).toBe(202);+ });+});