Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): refuse a start when a stop lands during its claim

Yudhi Armyndharis3f31e81635ae
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index d50684f5b..fdd5d6981 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -1422,6 +1422,66 @@ describe('SessionService', () => {
return ownership;
};
+ /** A row whose desiredState follows the service's own writes, so a stop's keep-down is visible. */
+ const trackDesiredState = (): (() => string | null) => {
+ let desired: string | null = null;
+ (repository.findOne as jest.Mock).mockImplementation(() =>
+ Promise.resolve(createMockSession({ desiredState: desired as Session['desiredState'] })),
+ );
+ (repository.update as jest.Mock).mockImplementation((_where: unknown, patch: Record<string, unknown>) => {
+ if ('desiredState' in patch) desired = patch.desiredState as string | null;
+ return Promise.resolve({ affected: 1 });
+ });
+ return () => desired;
+ };
+
+ // The stop finished, released its claim and answered 200 while the start still waited on its
+ // claim; the start then launched the engine on the released claim and cleared the stop record.
+ it('start() refuses with 409 when a stop() lands while its claim is pending', async () => {
+ const ownership = withOwnership();
+ const desired = trackDesiredState();
+ let finishClaim: () => void = () => undefined;
+ ownership.claim.mockImplementationOnce(
+ () => new Promise<boolean>(resolve => (finishClaim = () => resolve(true))),
+ );
+
+ const starting = service.start('sess-uuid-1', { explicit: true });
+ const outcome = starting.catch((error: unknown) => error);
+ await service.stop('sess-uuid-1');
+ const releasesBefore = ownership.release.mock.calls.length;
+ finishClaim();
+
+ expect(await outcome).toBeInstanceOf(SessionStoppedException);
+ expect(mockEngine.initialize).not.toHaveBeenCalled();
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(false);
+ expect(desired()).toBe('stopped');
+ expect(ownership.release.mock.calls.length).toBeGreaterThan(releasesBefore);
+ });
+
+ it('start() does not retry a transient failure when a stop() lands while the re-claim is pending', async () => {
+ const ownership = withOwnership();
+ const desired = trackDesiredState();
+ (engineFactory.create as jest.Mock).mockReturnValue(mockEngine);
+ mockEngine.initialize.mockRejectedValueOnce(new EngineTransportError('Protocol error: Target closed'));
+ let finishClaim: () => void = () => undefined;
+ let reclaimed: () => void = () => undefined;
+ const reclaim = new Promise<void>(resolve => (reclaimed = resolve));
+ ownership.claim.mockResolvedValueOnce(true).mockImplementationOnce(() => {
+ reclaimed();
+ return new Promise<boolean>(resolve => (finishClaim = () => resolve(true)));
+ });
+
+ const outcome = service.start('sess-uuid-1', { explicit: true }).catch((error: unknown) => error);
+ await reclaim;
+ await service.stop('sess-uuid-1');
+ finishClaim();
+
+ expect(await outcome).toBeInstanceOf(EngineTransportError);
+ expect(mockEngine.initialize).toHaveBeenCalledTimes(1);
+ expect(lifecycle.isEngineActive('sess-uuid-1')).toBe(false);
+ expect(desired()).toBe('stopped');
+ });
+
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.ts
index ad0130820..7b31c0363 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -629,6 +629,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
private async claimAndStart(id: string, explicit: boolean): Promise<Session> {
+ // Read before the claim, so a stop that lands while the claim is pending counts against this start.
+ const stopRequestsBefore = this.stopRequests.get(id);
// Claimed before the engine is launched, never after: launching first and discovering the
// session belongs elsewhere would already have opened a second connection to the account.
if (this.ownership && !(await this.ownership.claim(id))) {
@@ -637,7 +639,6 @@ 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, stopRequestsBefore);
@@ -675,6 +676,11 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
explicit: boolean,
stopRequestsBefore: number | undefined,
): Promise<Session> {
+ // A stop that finished during the claim already released it and answered 200; the engine's own
+ // stop-mark check cannot tell its mark from a stale one, so the start is refused here.
+ if (this.stopRequests.get(id) !== stopRequestsBefore) {
+ throw new SessionStoppedException(`Session ${id} was stopped`);
+ }
try {
return await this.engineLifecycle.start(id, { explicit });
} catch (error) {
@@ -695,6 +701,8 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
await this.findOne(id);
throw new ConflictException(`Session ${id} is running on another node`);
}
+ // Checked again: a stop that landed during the re-claim has already released it.
+ if (this.stopRequests.get(id) !== stopRequestsBefore) throw error;
return this.engineLifecycle.start(id, { explicit });
}
}