Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): keep a start from launching into a removed session
Yudhi Armyndharisd5b7ea82ab97
diff --git a/src/modules/session/session-delete-claim.spec.ts b/src/modules/session/session-delete-claim.spec.tsindex 5412ee07a..7cfb54935 100644--- a/src/modules/session/session-delete-claim.spec.ts+++ b/src/modules/session/session-delete-claim.spec.ts@@ -1123,6 +1123,28 @@ describe('A session deleted on one node while a peer shares the database', () =>expect((await a.db.getRepository(Session).findOneByOrFail({ id })).desiredState).not.toBeNull();});+ // The session was stopped, so the delete's record changes nothing the start could read, and the failed delete+ // has dropped its stop mark by the time the start goes on.+ it('keeps a start from launching into a stopped session that a delete sent after it began removing', async () => {+ const id = await seed({ status: SessionStatus.DISCONNECTED, desiredState: 'stopped' });+ const fenced = deferred();+ const go = deferred();+ jest.spyOn(SessionLifecycleFences.prototype, 'awaitPendingTeardown').mockImplementationOnce(async () => {+ fenced.resolve();+ await go.promise;+ });+ const starting = a.service.start(id, { explicit: true });+ await fenced.promise;+ jest.spyOn(a.db, 'transaction').mockRejectedValueOnce(new Error('transaction timed out'));+ await expect(a.service.delete(id)).rejects.toThrow('transaction timed out');+ go.resolve();++ await expect(starting).rejects.toBeInstanceOf(SessionStoppedException);++ expect(a.engines).toHaveLength(0);+ expect((await a.db.getRepository(Session).findOneByOrFail({ id })).desiredState).not.toBeNull();+ });+it('refuses the delete and removes nothing when the claim cannot be written', async () => {const id = await seed({ status: SessionStatus.DISCONNECTED });await a.service.start(id, { explicit: true });diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.tsindex bd314c0a4..a284ca683 100644--- a/src/modules/session/session-engine-controls.ts+++ b/src/modules/session/session-engine-controls.ts@@ -300,8 +300,13 @@ export class SessionEngineControls {* `explicit` marks an operator's POST /start, the only start that may clear an operator's stop* (desiredState), and only a stop that was already on the row when it began. It clears it only* once past every refusal below, so a refused start leaves the stop exactly as it found it.+ * `stoppedSince` answers whether a stop or delete of the session issued after the caller's start+ * began still stands; the start yields to one, also when its mark is already gone.*/- async start(id: string, { explicit = false }: { explicit?: boolean } = {}): Promise<Session> {+ async start(+ id: string,+ { explicit = false, stoppedSince }: { explicit?: boolean; stoppedSince?: () => boolean } = {},+ ): Promise<Session> {// Reserve the slot SYNCHRONOUSLY at entry — before even the requireSession await. Two// near-simultaneous start() calls must not both pass the check and orphan an engine (the has()// -> engines.set() window spans the awaited hook below), and the infra import pre-flight@@ -386,9 +391,10 @@ export class SessionEngineControls {// but its record is on the row: only a POST /start sent to an already stopped session clears// it, and any other start yields to it with the mark put back. A stop from here on sets the// mark again and retires this start after its init. A launch that fails after the clear still- // counts as the start the operator asked for.+ // counts as the start the operator asked for. A delete issued since this start began that failed once it+ // began removing has dropped its mark and left a record this start may have read too: it still stands.const { desiredState } = await this.requireSession(id);- if (desiredState && (!explicit || !session.desiredState)) {+ if ((desiredState && (!explicit || !session.desiredState)) || stoppedSince?.()) {this.stoppingSessions.add(id);throw new SessionStoppedException(`Session ${id} was stopped`);}diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.tsindex b20051512..ebdc080b3 100644--- a/src/modules/session/session-engine-lifecycle.service.ts+++ b/src/modules/session/session-engine-lifecycle.service.ts@@ -457,7 +457,7 @@ export class SessionEngineLifecycle {// settlement profile the inline methods had (the Task-1 delegate rule above)./** Delegate: SessionEngineControls.start. */- start(id: string, options?: { explicit?: boolean }): Promise<Session> {+ start(id: string, options?: { explicit?: boolean; stoppedSince?: () => boolean }): Promise<Session> {return this.controls.start(id, options);}diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a86f81b4d..779100a85 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -928,8 +928,9 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}// Shutdown may have begun while the claim was pending; the stop clear and the hook must not run.this.refuseIfShuttingDown();+ const stoppedSince = (): boolean => this.stoppedSince(id, stopRequestsBefore);try {- return await this.engineLifecycle.start(id, { explicit });+ return await this.engineLifecycle.start(id, { explicit, stoppedSince });} catch (error) {if (!isTransientLaunchFailure(error)) throw error;this.logger.warn(`Transient launch failure for session ${id}; retrying once`, {@@ -961,7 +962,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat}// And shutdown may have begun during the re-claim; the stop clear and the hook must not run.this.refuseIfShuttingDown();- return await this.engineLifecycle.start(id, { explicit });+ return await this.engineLifecycle.start(id, { explicit, stoppedSince });} catch (retryError) {// The first attempt may have left FAILED, which the boot reset, auto-start and the takeover// sweep all skip, and shutdown refused the retry that would have overwritten it. Handed back