Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): retire a start waiting on its claim after a logout

Yudhi Armyndharisf64cfc2199be
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index 895a31298..8ec97dbf8 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -148,7 +148,7 @@ export interface StopHooks {
* withdraws the caller's stop request.
*/
onReadFailed?: () => void;
- /** forceKill() only: runs synchronously once there is an engine to kill; records the stop request. */
+ /** forceKill()/logout(): runs synchronously once there is an engine to retire. */
onEngineFound?: () => void;
/** forceKill() only: persist the stop with the caller's current ownership predicate. */
recordStop?: () => Promise<void>;
@@ -682,13 +682,17 @@ export class SessionEngineControls {
* the 502 path (the controller audits SESSION_LOGGED_OUT only after the service resolves). The
* operator can start the session and retry the logout.
*/
- async logout(id: string): Promise<Session> {
- const session = await this.requireSession(id);
+ async logout(id: string, hooks: StopHooks = {}): Promise<Session> {
+ const session = await this.requireSession(id).catch((error: unknown) => {
+ hooks.onReadFailed?.();
+ throw error;
+ });
const engine = this.engines.get(id);
if (!engine) {
throw new BadRequestException('Session is not started. Call POST /sessions/:sessionId/start first.');
}
+ hooks.onEngineFound?.();
// Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.
this.stoppingSessions.add(id);
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 8099251d9..27159b941 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -469,8 +469,8 @@ export class SessionEngineLifecycle {
}
/** Delegate: SessionEngineControls.logout. */
- logout(id: string): Promise<Session> {
- return this.controls.logout(id);
+ logout(id: string, hooks?: StopHooks): Promise<Session> {
+ return this.controls.logout(id, hooks);
}
/** Delegate: SessionEngineControls.forceKill. */
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index 0b44e38a9..f31f8adf8 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1951,6 +1951,48 @@ describe('SessionService', () => {
// The same race with a force-kill: the start sent while the engine still ran launched a new one
// once its claim resolved and cleared the stop record the kill had just written.
+ it.each([false, true])('retires a pending start after logout (incomplete: %s)', async incomplete => {
+ const ownership = withOwnership();
+ const desired = trackDesiredState();
+ registry.set('sess-uuid-1', mockEngine as never);
+ if (incomplete) mockEngine.logout.mockRejectedValueOnce(new Error('unlink unavailable'));
+ let finishClaim: () => void = () => undefined;
+ ownership.claim.mockImplementationOnce(
+ () =>
+ new Promise<boolean>(resolve => {
+ finishClaim = () => resolve(true);
+ }),
+ );
+ const outcome = service.start('sess-uuid-1', { explicit: true }).catch((error: unknown) => error);
+ if (incomplete) await expect(service.logout('sess-uuid-1')).rejects.toBeInstanceOf(BadGatewayException);
+ else await service.logout('sess-uuid-1');
+ finishClaim();
+
+ expect(await outcome).toBeInstanceOf(SessionStoppedException);
+ expect(engineFactory.create).not.toHaveBeenCalled();
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(false);
+ expect(desired()).toBeNull();
+ await service.start('sess-uuid-1', { explicit: true });
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(true);
+ });
+
+ it('keeps a pending start eligible when logout has no engine', async () => {
+ const ownership = withOwnership();
+ trackDesiredState();
+ let finishClaim: () => void = () => undefined;
+ ownership.claim.mockImplementationOnce(
+ () =>
+ new Promise<boolean>(resolve => {
+ finishClaim = () => resolve(true);
+ }),
+ );
+ const starting = service.start('sess-uuid-1', { explicit: true });
+ await expect(service.logout('sess-uuid-1')).rejects.toBeInstanceOf(BadRequestException);
+ finishClaim();
+ await starting;
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(true);
+ });
+
it('start() refuses with 409 when a forceKill() lands while its claim is pending', async () => {
const ownership = withOwnership();
const desired = trackDesiredState();
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index c08018c9a..58a5134c9 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -1068,8 +1068,21 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
/** See SessionEngineLifecycle.logout() for the full unlink/502 contract. */
async logout(id: string): Promise<Session> {
+ // A start still waiting on its claim yields to the logout rather than relaunching the session it just
+ // took down. Not recorded as a stop: logout clears the phone, which keeps the session out of auto-start.
+ let request: StopRequest | undefined;
+ const issue = (): StopRequest => (request ??= this.requestStop(id, 'stop'));
+ const withdraw = (): void => {
+ if (request) this.withdrawStop(request);
+ };
+ if (this.engines.get(id)) issue();
try {
- const session = await this.engineLifecycle.logout(id);
+ const session = await this.engineLifecycle.logout(id, {
+ onReadFailed: withdraw,
+ onEngineFound: () => {
+ issue();
+ },
+ });
// Torn down locally on the 200 path — hand the claim back the way stop() does.
await this.releaseAfterTeardown(id);
return session;
@@ -1077,8 +1090,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
// The 502-incomplete path tears the engine down, so its claim must not survive the call. A 400
// "not started" refusal changed nothing and keeps whatever claim there is: release() also
// clears a LAPSED foreign claim, which would take a crashed node's session out of takeover.
+ if (error instanceof BadRequestException) withdraw();
if (!(error instanceof BadRequestException)) await this.releaseAfterTeardown(id);
throw error;
+ } finally {
+ if (request) this.endStop(id, request);
}
}