Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): hand the claim back when the last overlapping start leaves
Yudhi Armyndharis6632df95a9d1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0bd809932..37e98406b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -47,6 +47,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- Bound each webhook and ingress queue command at 2 s once Redis has connected, so a Redis that stops answering falls back to direct delivery and inline dispatch instead of holding every dispatch and ingress request.- Answer `400` for a send route's `chatId` or a bulk `batchId` over 255 characters, where PostgreSQL answered `500` once the value passed its index entry limit.- MCP tools refuse a `chatId`, `fromChatId` or `toChatId` over 255 characters, as the send routes do, where PostgreSQL answered an internal tool error.+- A start that fails while another start of the same session is in flight leaves the claim to that start, so its engine is no longer left on a row no node holds.- Index ingress dead letters by delivery id, so the reconciler's per-delivery checks stop scanning every dead letter of an instance; the first boot builds the index.- Replay stranded ingress events past one whose stored payload is not valid JSON, instead of failing every sweep on it.- Hand a chat back to the bot when the plugin instance that took it over is deleted, instead of silencing every other plugin on it.diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex 7d8f94dce..b7a605aa2 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -1687,6 +1687,51 @@ describe('SessionService', () => {expect(desired()).toBe('stopped');});+ // Two overlapping starts of one session: the first fails before launching while the second has already+ // written its claim, and handing the claim back then left the second's engine on a row no node held.+ it('start() leaves the claim to a second start in flight when the first one fails', async () => {+ const ownership = withOwnership();+ let finishFirstClaim: () => void = () => undefined;+ ownership.claim+ .mockImplementationOnce(() => new Promise<boolean>(resolve => (finishFirstClaim = () => resolve(true))))+ .mockResolvedValue(true);+ let launchSecond: () => void = () => undefined;+ // The second start's claim resolves at once, so it reaches the engine launch before the first.+ jest+ .spyOn(lifecycle, 'start')+ .mockImplementationOnce(+ () => new Promise<Session>(resolve => (launchSecond = () => resolve(createMockSession()))),+ )+ .mockRejectedValueOnce(new BadRequestException('refused'));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);++ const first = service.start('sess-uuid-1').catch((error: unknown) => error);+ const second = service.start('sess-uuid-1');+ await new Promise(resolve => setImmediate(resolve));+ finishFirstClaim();+ expect(await first).toBeInstanceOf(BadRequestException);++ expect(ownership.release).not.toHaveBeenCalled();+ launchSecond();+ await second;+ // Nothing runs here once the last start is out, so the claim is handed back then, once.+ expect(ownership.release).toHaveBeenCalledTimes(1);+ });++ it('start() hands the claim back once when two overlapping starts both fail', async () => {+ const ownership = withOwnership();+ jest.spyOn(lifecycle, 'start').mockRejectedValue(new BadRequestException('refused'));+ jest.spyOn(lifecycle, 'isEngineActive').mockReturnValue(false);++ const outcomes = await Promise.all([+ service.start('sess-uuid-1').catch((error: unknown) => error),+ service.start('sess-uuid-1').catch((error: unknown) => error),+ ]);++ expect(outcomes.every(outcome => outcome instanceof BadRequestException)).toBe(true);+ expect(ownership.release).toHaveBeenCalledTimes(1);+ });+it('start() releases the claim when the launch fails and nothing stays alive here', async () => {const ownership = withOwnership();jest.spyOn(lifecycle, 'start').mockRejectedValue(new Error('engine init failed'));diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 8c3bf6c16..2dd73d06c 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -150,6 +150,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat* or not.*/private readonly startReservations = new Map<string, number>();+ /** Ids whose claim a failed start left to another start in flight; the last start out hands it back. */+ private readonly releaseOwed = new Set<string>();constructor(@InjectRepository(Session, 'data')@@ -694,8 +696,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatreturn await this.claimAndStart(id, explicit);} finally {const left = (this.startReservations.get(id) ?? 1) - 1;- if (left > 0) this.startReservations.set(id, left);- else this.startReservations.delete(id);+ if (left > 0) {+ this.startReservations.set(id, left);+ } else {+ this.startReservations.delete(id);+ if (this.releaseOwed.delete(id)) await this.releaseUnlessEngineActive(id);+ }}}@@ -962,6 +968,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicatif (!this.ownership || this.engineLifecycle.isEngineActive(id)) {return;}+ // Another start of the id is in flight and may have written the claim since: clearing it now would+ // leave the engine that start launches on a row no node holds. The start that leaves last decides.+ if ((this.startReservations.get(id) ?? 0) > 1) {+ this.releaseOwed.add(id);+ return;+ }+ this.releaseOwed.delete(id);await this.ownership.release(id);}