Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): count a delete as running before it claims
Yudhi Armyndharisde61efa97d94
diff --git a/src/modules/session/session-delete-claim.spec.ts b/src/modules/session/session-delete-claim.spec.tsindex 8ab748a59..6007b2a61 100644--- a/src/modules/session/session-delete-claim.spec.ts+++ b/src/modules/session/session-delete-claim.spec.ts@@ -292,6 +292,47 @@ describe('A session deleted on one node while a peer shares the database', () =>expect(b.ownership.ownedIds()).toEqual([]);});+ it('keeps its claim when a stop on the same node ends while the delete reads the session', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED });+ const sessions = a.db.getRepository(Session);+ const findOne = sessions.findOne.bind(sessions);+ const reading = deferred();+ const read = deferred();+ // The delete's first row read, which comes after its claim.+ jest.spyOn(sessions, 'findOne').mockImplementationOnce(async (...args: Parameters<typeof findOne>) => {+ reading.resolve();+ await read.promise;+ return findOne(...args);+ });+ const reached = deferred();+ const release = deferred();+ a.hooks.execute.mockImplementation(async (event: string, data: unknown) => {+ if (event === 'session:deleted') {+ reached.resolve();+ await release.promise;+ }+ return { continue: true, data };+ });+ finish = release.resolve;+ deletion = a.service.delete(id);+ await reading.promise;++ await a.service.stop(id);+ expect((await findOne({ where: { id } }))?.nodeId).toBe('node-a');+ read.resolve();+ await reached.promise;+ await expect(b.service.start(id, { explicit: true })).rejects.toBeInstanceOf(ConflictException);+ expect(b.engines).toHaveLength(0);++ release.resolve();+ await deletion;+ await peerReceivesAMessage();++ expect(await rowsOf(id)).toEqual(gone);+ expect(a.ownership.ownedIds()).toEqual([]);+ expect(b.ownership.ownedIds()).toEqual([]);+ });+it('leaves a lapsed session to the deleting node when a peer looks for sessions to adopt', async () => {const id = await seed({ status: SessionStatus.READY, nodeId: 'node-c', leaseExpiresAt: lapsed() });await startHeldDelete(id);diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex 71d65f32e..2563b235e 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -251,13 +251,23 @@ export class SessionEngineControls {}/**- * True while a delete of the session runs: from just before its engine teardown until it returns or- * throws, credential purge included.+ * True while a delete of the session runs: from before SessionService.delete claims the session until it+ * returns or throws, credential purge included.*/isDeleting(id: string): boolean {return this.deleting.has(id);}+ /** Count a delete of the session as running until the returned call; see isDeleting. */+ holdDelete(id: string): () => void {+ this.deleting.set(id, (this.deleting.get(id) ?? 0) + 1);+ return () => {+ const running = (this.deleting.get(id) ?? 1) - 1;+ if (running > 0) this.deleting.set(id, running);+ else this.deleting.delete(id);+ };+ }+/** findOne-or-404 with the runtime-state projection, mirroring SessionService.findOne. */private async requireSession(id: string): Promise<Session> {const session = await this.sessionRepository.findOne({ where: { id } });@@ -800,7 +810,7 @@ export class SessionEngineControls {// rejected 409 from fence #2 leaves them intact (the session still exists).let parentDeleted = false;const writes = closeSessionWrites(this.host.dataSource(), id);- this.deleting.set(id, (this.deleting.get(id) ?? 0) + 1);+ const endDelete = this.holdDelete(id);try {// Stop engine if running — time-bounded + isolated so a stuck Chromium can't wedge the delete;@@ -921,9 +931,7 @@ export class SessionEngineControls {throw error;} finally {writes.release();- const running = (this.deleting.get(id) ?? 1) - 1;- if (running > 0) this.deleting.set(id, running);- else this.deleting.delete(id);+ endDelete();// Always clear the teardown mark so a later recreate/start with this id isn't suppressed. This// stop mark was set after fence #1, so clearing it on a rejected 409 only undoes what THIS// delete added — it does NOT touch reconnect timer / engine / last status / error / recoverydiff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex 2efa70f6c..b20051512 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -481,6 +481,11 @@ export class SessionEngineLifecycle {return this.controls.delete(id, hooks);}+ /** Delegate: SessionEngineControls.holdDelete. */+ holdDelete(id: string): () => void {+ return this.controls.holdDelete(id);+ }+/** Delegate: SessionEngineControls.shutdown. */shutdown(): Promise<void> {this.closed = true;diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 8d8baf5bb..d8155bda6 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -610,15 +610,23 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// COUNT, or delete()'s own requireSession — would let the mark land after that window. A mark// left behind when the fence refuses (409) is harmless and is cleared by the next start().this.markStopping(id);+ // Running from here, before the claim: a claim with nothing running behind it would read as idle to the+ // heartbeat, and a stop or a failed start here would hand it back while the rows are removed. It ends+ // before the claim is handed back.+ const endDelete = this.engineLifecycle.holdDelete(id);let claimed = false;try {- if (this.ownership) {- await this.assertNotHeldElsewhere(id);- await this.claimForDelete(id, this.ownership);- claimed = true;+ try {+ if (this.ownership) {+ await this.assertNotHeldElsewhere(id);+ await this.claimForDelete(id, this.ownership);+ claimed = true;+ }+ // A failed row read deleted nothing: the lifecycle drops the mark, and the count goes with it.+ await this.engineLifecycle.delete(id, { onReadFailed: () => this.uncountStopRequest(id) });+ } finally {+ endDelete();}- // A failed row read deleted nothing: the lifecycle drops the mark, and the count goes with it.- await this.engineLifecycle.delete(id, { onReadFailed: () => this.uncountStopRequest(id) });await this.releaseClaimBestEffort(id);this.stopRequests.delete(id);} catch (error) {