Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): keep a stop that lands during an explicit start recorded

Yudhi Armyndharisafd60ecb236f
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index d98dfd91f..b310a4e80 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -8431,6 +8431,40 @@ describe('SessionService', () => {
}
});
+ // The stop's own write is a no-op on a row already marked stopped, so the start's clear that
+ // lands after it erased the stop, and the next boot relaunched a session left down by a stop.
+ it('a stop that finishes just before an explicit start clears the record keeps the session down', async () => {
+ const stopped = await sessions.save(
+ sessions.create({
+ name: 'cleared-late',
+ status: SessionStatus.DISCONNECTED,
+ phone: '628777',
+ config: {},
+ desiredState: 'stopped',
+ }),
+ );
+ (repository.findOne as jest.Mock).mockImplementation((opts: Parameters<Repository<Session>['findOne']>[0]) =>
+ sessions.findOne(opts),
+ );
+ let stopResult: Promise<unknown> | undefined;
+ (repository.update as jest.Mock).mockImplementation(
+ async (...args: Parameters<Repository<Session>['update']>) => {
+ const patch = args[1] as { desiredState?: unknown };
+ if (!stopResult && patch.desiredState === null) {
+ stopResult = service.stop(stopped.id);
+ await stopResult;
+ }
+ return sessions.update(...args);
+ },
+ );
+
+ await service.start(stopped.id, { explicit: true });
+
+ await expect(stopResult).resolves.toBeDefined();
+ expect(lifecycle.isEngineActive(stopped.id)).toBe(false);
+ expect((await sessions.findOneByOrFail({ id: stopped.id })).desiredState).toBe('stopped');
+ });
+
// The start that holds the reservation already cleared the stop; the refused one must not
// bring it back over the session that start is launching.
it('an explicit start refused by another explicit start leaves the stop cleared', async () => {
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 400004d1f..7c6300bc6 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -565,10 +565,12 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await this.findOne(id);
throw new ConflictException(`Session ${id} is running on another node`);
}
+ const stopRequestsBefore = this.stopRequests.get(id);
let session: Session;
try {
- session = await this.startWithTransientRetry(id, explicit);
+ session = await this.startWithTransientRetry(id, explicit, stopRequestsBefore);
} catch (error) {
+ await this.keepDownIfStoppedDuringStart(id, explicit, stopRequestsBefore);
// A failed or refused start must not leave the claim pinned here — the heartbeat would renew
// it and the session could never be started anywhere else. Released only when nothing is
// actually alive locally: an "already starting/started" refusal means this node genuinely
@@ -576,6 +578,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await this.releaseUnlessEngineActive(id);
throw error;
}
+ await this.keepDownIfStoppedDuringStart(id, explicit, stopRequestsBefore);
// A start retired by a concurrent stop() resolves normally but leaves no engine, and that stop
// skipped its release while this start still held the session. Hand the claim back here, or the
// row keeps naming this node until the lease lapses and a peer adopts the stopped session.
@@ -595,8 +598,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
* unbounded loop here would hold the concurrency slot hostage. HTTP-shaped refusals (409
* not-ready, 4xx) are NOT transient - they propagate immediately.
*/
- private async startWithTransientRetry(id: string, explicit: boolean): Promise<Session> {
- const stopRequestsBefore = this.stopRequests.get(id);
+ private async startWithTransientRetry(
+ id: string,
+ explicit: boolean,
+ stopRequestsBefore: number | undefined,
+ ): Promise<Session> {
try {
return await this.engineLifecycle.start(id, { explicit });
} catch (error) {
@@ -689,6 +695,30 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await this.sessionRepository.update(id, { desiredState: 'stopped' });
}
+ /**
+ * Re-record a stop an explicit start may have erased. The start clears the stop record with a
+ * write conditional on the row still reading 'stopped', and a stop's own write leaves that value
+ * unchanged, so a stop landing just before the clear was wiped from the row while its in-memory
+ * mark retired the start. The session was down, but the next boot would relaunch it. Any stop
+ * counted while the start ran and leaving no engine behind is the operator's last word. A failed
+ * write is logged rather than thrown: the start's own outcome still stands.
+ */
+ private async keepDownIfStoppedDuringStart(
+ id: string,
+ explicit: boolean,
+ stopRequestsBefore: number | undefined,
+ ): Promise<void> {
+ const stoppedMeanwhile = this.stopRequests.get(id) !== stopRequestsBefore;
+ if (!explicit || !stoppedMeanwhile || this.engineLifecycle.isEngineActive(id)) return;
+ await this.keepDown(id).catch((error: unknown) =>
+ this.logger.error(
+ 'Failed to record a stop that landed during a start',
+ error instanceof Error ? error.message : String(error),
+ { sessionId: id, action: 'start_keep_down_failed' },
+ ),
+ );
+ }
+
private markStopping(id: string): void {
this.stopRequests.set(id, (this.stopRequests.get(id) ?? 0) + 1);
this.engineLifecycle.markStopping(id);