Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(bulk): reap only the batches this process was driving

Yudhi Armyndharisbcb4d56db62f
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 85c259cbf..e588e2f39 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -25,10 +25,17 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
Existing rows read as unclaimed, so a single-process deployment behaves exactly as before.
- This is ownership only. Request routing, fencing on every lifecycle path, cross-process bulk-batch
- state and WebSocket fan-out are not done, so **one API instance per session-data volume remains
- the supported topology** — `docs/13-horizontal-scaling.md` states precisely what is and is not in
- place.
+ Bulk-send batches follow the same ownership. The boot reaper marked every `PROCESSING` batch
+ `FAILED`, which on a second replica meant declaring a peer's in-flight batches failed while they
+ were still sending — the caller told the send failed, the messages going out regardless. A batch
+ is only ever driven by the process holding its session's engine, so the reaper now acts only on
+ batches whose session this node may claim. A data import reports the sessions it could not
+ reconcile because another node is running them, rather than returning cleanly over engines it
+ never touched.
+
+ Request routing, fencing on the remaining lifecycle paths and WebSocket fan-out are still not
+ done, so **one API instance per session-data volume remains the supported topology** —
+ `docs/13-horizontal-scaling.md` states precisely what is and is not in place.
- **Voice status.** `POST /api/sessions/:sessionId/status/send-voice` posts an audio status as a
diff --git a/docs/13-horizontal-scaling.md b/docs/13-horizontal-scaling.md
index fbf9ac715..9606c6bef 100644
--- a/docs/13-horizontal-scaling.md
+++ b/docs/13-horizontal-scaling.md
@@ -14,13 +14,20 @@
> does not depend on one. `NODE_ID` names the process; it defaults to the hostname and must
> be stable across restarts.
>
+> Bulk-send batches follow the same rule. A batch is only ever driven by the process
+> holding its session's engine, so a booting replica now reaps only the batches whose
+> sessions it may claim, instead of declaring a peer's in-flight batches FAILED while they
+> are still sending. A data import likewise reports the sessions it could not reconcile
+> because another node is running them.
+>
> **What does not exist yet, and is why one replica is still the answer.** Live engine state
> (browser + WebSocket + reconnect/error state) still lives in an in-memory `Map` in
> `EngineRegistry`, and there is **no request routing** — a call that lands on a replica
-> which does not own the session cannot serve it. Not every lifecycle path is fenced.
-> `BulkMessageService` keeps batch state in process and its boot reaper does not distinguish
-> a peer's in-flight batches from its own. There is **no** Socket.IO Redis adapter, so a
-> WebSocket client connected to one replica does not receive events raised on another.
+> which does not own the session cannot serve it. Not every lifecycle path is fenced: the
+> liveness watchdog and reconnect timers still act on whatever is in the local registry.
+> `BulkMessageService` keeps its live batch state in process, so a takeover cannot resume a
+> batch — only fail it. There is **no** Socket.IO Redis adapter, so a WebSocket client
+> connected to one replica does not receive events raised on another.
>
> Everything below (node affinity, `replicas: 3`) remains a **design sketch** until those
> land.
diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.ts
index 3d356630d..9612920e3 100644
--- a/src/modules/infra/infra-data.controller.ts
+++ b/src/modules/infra/infra-data.controller.ts
@@ -11,6 +11,7 @@ import { AuditService } from '../audit/audit.service';
import { AuditAction } from '../audit/entities/audit-log.entity';
import { SessionService } from '../session/session.service';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
+import { SessionOwnershipService } from '../session/session-ownership.service';
import type {
MigrationTables,
TableCounts,
@@ -58,6 +59,10 @@ export class InfraDataController {
private readonly sessionService?: SessionService,
@Optional()
private readonly lidMappingStore?: LidMappingStoreService,
+ // Same trailing-@Optional convention as the services above: provided by the app, omitted by the
+ // direct-construction unit tests, and every use is `?.`-guarded.
+ @Optional()
+ private readonly ownership?: SessionOwnershipService,
) {}
@Get('export-data')
@@ -273,6 +278,20 @@ export class InfraDataController {
// failures that make the replace partial and therefore require a rollback.
const notices: string[] = [];
+ // `getActiveSessionIds` reads this process's own engine registry, so an engine another node is
+ // running is invisible here and cannot be stopped from this request — there is no cross-process
+ // control channel. Left unsaid, a clean response would read as "every orphan was reconciled".
+ // Say it instead: the operator is the only one who can act on it.
+ const heldElsewhere = (await this.ownership?.heldByOtherNodes()) ?? [];
+ if (heldElsewhere.length > 0) {
+ restartRequired = true;
+ notices.push(
+ `${heldElsewhere.length} session(s) are running on another node and could not be reconciled from ` +
+ `this request: ${heldElsewhere.join(', ')}. Their engines may still write into the restored ` +
+ `tables — stop those nodes before relying on this import.`,
+ );
+ }
+
if (orphanedEngines.length > 0 && data.stopOrphans && this.sessionService) {
// Stop the orphans inside this request, BEFORE the transaction opens. destroyEngineSafely's
// per-engine 10s deadline bounds the worst case (a stuck Chromium cannot wedge the import); the
diff --git a/src/modules/message/bulk-message.service.spec.ts b/src/modules/message/bulk-message.service.spec.ts
index 7010d470d..c7f075f20 100644
--- a/src/modules/message/bulk-message.service.spec.ts
+++ b/src/modules/message/bulk-message.service.spec.ts
@@ -15,6 +15,7 @@ import { EngineRegistry } from '../../engine/engine-registry.service';
import type { IWhatsAppEngine } from '../../engine/interfaces/whatsapp-engine.interface';
import { MessageService } from './message.service';
import { SendPacingService } from './send-pacing.service';
+import { SessionOwnershipService } from '../session/session-ownership.service';
import { HookManager } from '../../core/hooks';
import { SsrfBlockedError } from '../../common/security/ssrf-guard';
@@ -106,6 +107,73 @@ describe('BulkMessageService.onApplicationBootstrap', () => {
await service.onApplicationBootstrap();
expect(repo.save).not.toHaveBeenCalled();
});
+
+ /**
+ * A batch is only ever driven by the process holding its session's engine, so on a second replica
+ * "PROCESSING" does not mean "abandoned". Reaping a peer's batch tells the caller their send
+ * failed while the messages continue going out — a wrong answer about work that is still running.
+ */
+ describe('with another node in play', () => {
+ /** Rebuild the service with an ownership service that owns only `ownedSessionIds`. */
+ const withOwnership = async (ownedSessionIds: string[]): Promise<BulkMessageService> => {
+ const module: TestingModule = await Test.createTestingModule({
+ providers: [
+ BulkMessageService,
+ { provide: getRepositoryToken(MessageBatch, 'data'), useValue: repo },
+ EngineRegistry,
+ { provide: MessageService, useValue: { saveOutgoingMessage: jest.fn() } },
+ { provide: SendPacingService, useValue: { assertSendAllowed: jest.fn().mockResolvedValue(undefined) } },
+ {
+ provide: HookManager,
+ useValue: {
+ execute: jest
+ .fn()
+ .mockImplementation((_e: string, d: unknown) => Promise.resolve({ continue: true, data: d })),
+ },
+ },
+ {
+ provide: SessionOwnershipService,
+ useValue: {
+ claimable: jest.fn((ids: string[]) => Promise.resolve(ids.filter(id => ownedSessionIds.includes(id)))),
+ },
+ },
+ ],
+ }).compile();
+ return module.get<BulkMessageService>(BulkMessageService);
+ };
+
+ it('leaves a batch alone when its session belongs to another node', async () => {
+ const peers = { id: 'b1', sessionId: 'peer-session', status: BatchStatus.PROCESSING } as MessageBatch;
+ repo.find.mockResolvedValue([peers]);
+
+ await (await withOwnership([])).onApplicationBootstrap();
+
+ expect(peers.status).toBe(BatchStatus.PROCESSING);
+ expect(repo.save).not.toHaveBeenCalled();
+ });
+
+ it('still reaps a batch whose session this node may claim', async () => {
+ const mine = { id: 'b2', sessionId: 'my-session', status: BatchStatus.PROCESSING } as MessageBatch;
+ repo.find.mockResolvedValue([mine]);
+
+ await (await withOwnership(['my-session'])).onApplicationBootstrap();
+
+ expect(mine.status).toBe(BatchStatus.FAILED);
+ expect(repo.save).toHaveBeenCalledWith(mine);
+ });
+
+ it('reaps only its own when both are present', async () => {
+ const mine = { id: 'b2', sessionId: 'my-session', status: BatchStatus.PROCESSING } as MessageBatch;
+ const peers = { id: 'b1', sessionId: 'peer-session', status: BatchStatus.PROCESSING } as MessageBatch;
+ repo.find.mockResolvedValue([mine, peers]);
+
+ await (await withOwnership(['my-session'])).onApplicationBootstrap();
+
+ expect(mine.status).toBe(BatchStatus.FAILED);
+ expect(peers.status).toBe(BatchStatus.PROCESSING);
+ expect(repo.save).toHaveBeenCalledTimes(1);
+ });
+ });
});
/** Regression lock: an SSRF block (which names the internal host/IP) must not be stored verbatim. */
diff --git a/src/modules/message/bulk-message.service.ts b/src/modules/message/bulk-message.service.ts
index 89028a20d..ed91815a3 100644
--- a/src/modules/message/bulk-message.service.ts
+++ b/src/modules/message/bulk-message.service.ts
@@ -1,4 +1,11 @@
-import { Injectable, Logger, BadRequestException, NotFoundException, OnApplicationBootstrap } from '@nestjs/common';
+import {
+ Injectable,
+ Logger,
+ BadRequestException,
+ NotFoundException,
+ Optional,
+ OnApplicationBootstrap,
+} from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { In, Not, QueryDeepPartialEntity, Repository } from 'typeorm';
import { createHash, randomUUID } from 'crypto';
@@ -14,6 +21,7 @@ import { MessageStatus } from './entities/message.entity';
import { EngineRegistry } from '../../engine/engine-registry.service';
import { MessageService } from './message.service';
import { SendPacingService } from './send-pacing.service';
+import { SessionOwnershipService } from '../session/session-ownership.service';
import { HookManager } from '../../core/hooks';
import { assertBase64WithinMediaCap, stripBase64DataUri } from './media-cap.util';
import { SsrfBlockedError, SSRF_BLOCKED_CLIENT_MESSAGE } from '../../common/security/ssrf-guard';
@@ -91,6 +99,11 @@ export class BulkMessageService implements OnApplicationBootstrap {
private readonly messageService: MessageService,
private readonly hookManager: HookManager,
private readonly pacing: SendPacingService,
+ // Trailing @Optional, matching the convention used elsewhere here: the running app always
+ // provides it, while direct-construction unit tests omit it and every batch then reads as this
+ // node's — which is exactly a single-process deployment.
+ @Optional()
+ private readonly ownership?: SessionOwnershipService,
) {}
/**
@@ -98,9 +111,17 @@ export class BulkMessageService implements OnApplicationBootstrap {
* previous (crashed/restarted) process — this fresh process is not driving it, so it would
* otherwise be stuck in PROCESSING forever. Mark it FAILED. Auto-resume is intentionally NOT
* done here: resuming risks re-sending messages already delivered before the crash.
+ *
+ * "A previous process" is not the same as "any process". A batch is only ever driven by whichever
+ * process holds its session's engine, so a batch belongs to a peer exactly when its session does.
+ * Without that distinction a booting replica declares a live peer's in-flight batches FAILED
+ * while they are still sending — the caller is told the send failed, and the messages go out
+ * anyway. Batch ownership follows session ownership rather than being tracked separately,
+ * because the two cannot diverge: only the engine holder can send.
*/
async onApplicationBootstrap(): Promise<void> {
- const orphaned = await this.batchRepository.find({ where: { status: BatchStatus.PROCESSING } });
+ const processing = await this.batchRepository.find({ where: { status: BatchStatus.PROCESSING } });
+ const orphaned = await this.ownedByThisNode(processing);
for (const batch of orphaned) {
batch.status = BatchStatus.FAILED;
this.stripBatchMediaPayloads(batch.messages);
@@ -111,6 +132,21 @@ export class BulkMessageService implements OnApplicationBootstrap {
`Marked ${orphaned.length} orphaned PROCESSING batch(es) FAILED on startup (interrupted by a restart)`,
);
}
+ const skipped = processing.length - orphaned.length;
+ if (skipped > 0) {
+ this.logger.log(`Left ${skipped} PROCESSING batch(es) alone: their sessions are held by another node`);
+ }
+ }
+
+ /**
+ * Narrow to the batches this process may act on. With no ownership service — a single-process
+ * deployment, or a directly-constructed unit test — every batch qualifies, which is the behaviour
+ * that existed before ownership was recorded at all.
+ */
+ private async ownedByThisNode(batches: MessageBatch[]): Promise<MessageBatch[]> {
+ if (!this.ownership || batches.length === 0) return batches;
+ const claimable = new Set(await this.ownership.claimable([...new Set(batches.map(b => b.sessionId))]));
+ return batches.filter(batch => claimable.has(batch.sessionId));
}
async createBatch(sessionId: string, dto: SendBulkMessageDto): Promise<MessageBatch> {
diff --git a/src/modules/session/session-ownership.service.spec.ts b/src/modules/session/session-ownership.service.spec.ts
index 1f1d9b83f..caaf78cee 100644
--- a/src/modules/session/session-ownership.service.spec.ts
+++ b/src/modules/session/session-ownership.service.spec.ts
@@ -207,6 +207,28 @@ describe('SessionOwnershipService', () => {
});
});
+ /**
+ * Drives an operator-facing warning during a data import: this process can only stop its own
+ * engines, so a session running elsewhere has to be named rather than quietly counted as handled.
+ */
+ describe('sessions held elsewhere', () => {
+ it('names sessions another node holds on a live lease', async () => {
+ const mine = await seed();
+ const peers = await seed();
+ await service('node-a').claim(mine.id);
+ await service('node-b').claim(peers.id);
+
+ await expect(service('node-a').heldByOtherNodes()).resolves.toEqual([peers.id]);
+ });
+
+ it('ignores unclaimed sessions and lapsed claims, which nobody is running', async () => {
+ await seed();
+ await seed({ nodeId: 'node-b', leaseExpiresAt: new Date(Date.now() - 1_000) });
+
+ await expect(service('node-a').heldByOtherNodes()).resolves.toEqual([]);
+ });
+ });
+
describe('node identity', () => {
it('falls back to the hostname when nothing is configured, and never to the pid', () => {
const bare = new SessionOwnershipService(sessions);
diff --git a/src/modules/session/session-ownership.service.ts b/src/modules/session/session-ownership.service.ts
index 55666f367..d96b18ac4 100644
--- a/src/modules/session/session-ownership.service.ts
+++ b/src/modules/session/session-ownership.service.ts
@@ -174,6 +174,22 @@ export class SessionOwnershipService {
return session.leaseExpiresAt != null && session.leaseExpiresAt > now;
}
+ /**
+ * Session ids another node currently holds on a live lease.
+ *
+ * For operations that can only act on this process's own engines and would otherwise report
+ * success over work they never touched.
+ */
+ async heldByOtherNodes(now = new Date()): Promise<string[]> {
+ const rows = await this.sessions
+ .createQueryBuilder('session')
+ .select('session.id', 'id')
+ .where('"nodeId" IS NOT NULL AND "nodeId" <> :me', { me: this.nodeId })
+ .andWhere('"leaseExpiresAt" > :now', { now: DateTransformer.to(now) })
+ .getRawMany<{ id: string }>();
+ return rows.map(row => row.id);
+ }
+
/** Test seam: what this process currently believes it holds. */
ownedIds(): string[] {
return [...this.owned];
diff --git a/src/modules/session/session.module.ts b/src/modules/session/session.module.ts
index 0e0b94970..48a2d890b 100644
--- a/src/modules/session/session.module.ts
+++ b/src/modules/session/session.module.ts
@@ -32,6 +32,6 @@ import { ChatMediaModule } from '../chat-media/chat-media.module';
SessionOwnershipService,
MessageProjector,
],
- exports: [SessionService, MessageProjector],
+ exports: [SessionService, MessageProjector, SessionOwnershipService],
})
export class SessionModule {}