Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): let stop and delete hook their session read

Yudhi Armyndharisdb8163379d56
diff --git a/src/modules/session/session-engine-controls.ts b/src/modules/session/session-engine-controls.ts
index f34686846..1299869b5 100644
--- a/src/modules/session/session-engine-controls.ts
+++ b/src/modules/session/session-engine-controls.ts
@@ -56,6 +56,14 @@ export class SessionStoppedException extends ConflictException {}
* lifecycle's dataSource on the instance after construction (logout-teardown-race.spec) and
* delete()'s transaction must observe the current one at call time.
*/
+/** Caller callbacks for stop()/delete(), run around the session read that opens each verb. */
+export interface StopHooks {
+ /** stop() only: runs once the session read succeeds and before any teardown; records the stop. */
+ afterRead?: () => Promise<void>;
+ /** Runs when the session read fails, after the stop mark is dropped: undoes the caller's request count. */
+ onReadFailed?: () => void;
+}
+
export interface SessionEngineControlsHost {
sessionRepository: Repository<Session>;
engineFactory: EngineFactory;
@@ -149,11 +157,12 @@ export class SessionEngineControls {
* that fails has retired nothing, so the mark must not outlive it: left on a running session, its
* next disconnect would never reconnect and start() would keep refusing it as already started.
*/
- private async requireSessionOrDropStopMark(id: string): Promise<Session> {
+ private async requireSessionOrDropStopMark(id: string, onReadFailed?: () => void): Promise<Session> {
try {
return await this.requireSession(id);
} catch (error) {
this.stoppingSessions.delete(id);
+ onReadFailed?.();
throw error;
}
}
@@ -336,8 +345,10 @@ export class SessionEngineControls {
}
}
- async stop(id: string): Promise<Session> {
- const session = await this.requireSessionOrDropStopMark(id);
+ async stop(id: string, hooks: StopHooks = {}): Promise<Session> {
+ const session = await this.requireSessionOrDropStopMark(id, hooks.onReadFailed);
+ // Recorded only once the row is known to exist, and before anything is torn down.
+ await hooks.afterRead?.();
// Mark as tearing down BEFORE cleanup so an in-flight reconnect can't resurrect it.
this.stoppingSessions.add(id);
@@ -574,8 +585,8 @@ export class SessionEngineControls {
return this.requireSession(id);
}
- async delete(id: string): Promise<void> {
- const session = await this.requireSessionOrDropStopMark(id);
+ async delete(id: string, hooks: StopHooks = {}): Promise<void> {
+ const session = await this.requireSessionOrDropStopMark(id, hooks.onReadFailed);
// FENCE #1 — fail-fast on an ALREADY-PENDING credential teardown for this session NAME, BEFORE
// any lifecycle mutation. A logout teardown that lost its deadline race is still running and ends
diff --git a/src/modules/session/session-engine-lifecycle-races.spec.ts b/src/modules/session/session-engine-lifecycle-races.spec.ts
index 99ca11d89..74002e950 100644
--- a/src/modules/session/session-engine-lifecycle-races.spec.ts
+++ b/src/modules/session/session-engine-lifecycle-races.spec.ts
@@ -236,6 +236,60 @@ describe('SessionEngineLifecycle races', () => {
});
});
+ describe('stop hooks', () => {
+ it('records the stop after the session read and before the teardown', async () => {
+ await lifecycle.start(ID);
+ const engine = (engineFactory.create.mock.results[0] as { value: Record<string, jest.Mock> }).value;
+ const order: string[] = [];
+ repository.findOne.mockImplementationOnce(() => {
+ order.push('read');
+ return Promise.resolve(session());
+ });
+ engine.disconnect.mockImplementation(() => {
+ order.push('teardown');
+ return Promise.resolve();
+ });
+
+ await lifecycle.stop(ID, {
+ afterRead: () => {
+ order.push('record');
+ return Promise.resolve();
+ },
+ });
+
+ expect(order).toEqual(['read', 'record', 'teardown']);
+ });
+
+ it('takes nothing down when recording the stop fails', async () => {
+ await lifecycle.start(ID);
+ const engine = (engineFactory.create.mock.results[0] as { value: Record<string, jest.Mock> }).value;
+
+ await expect(lifecycle.stop(ID, { afterRead: () => Promise.reject(new Error('SQLITE_BUSY')) })).rejects.toThrow(
+ 'SQLITE_BUSY',
+ );
+
+ expect(engine.disconnect).not.toHaveBeenCalled();
+ expect(internals.engines.has(ID)).toBe(true);
+ });
+
+ it.each([
+ [
+ 'stop',
+ (onReadFailed: () => void, afterRead: () => Promise<void>) => lifecycle.stop(ID, { afterRead, onReadFailed }),
+ ],
+ ['delete', (onReadFailed: () => void) => lifecycle.delete(ID, { onReadFailed })],
+ ])('%s() reports a failed session read and records nothing', async (_verb, call) => {
+ const onReadFailed = jest.fn();
+ const afterRead = jest.fn().mockResolvedValue(undefined);
+ repository.findOne.mockRejectedValueOnce(new Error('Connection terminated unexpectedly'));
+
+ await expect(call(onReadFailed, afterRead)).rejects.toThrow('Connection terminated unexpectedly');
+
+ expect(onReadFailed).toHaveBeenCalledTimes(1);
+ expect(afterRead).not.toHaveBeenCalled();
+ });
+ });
+
describe('engine-driven status writes', () => {
const rejectStatus = (status: SessionStatus): void => {
repository.update.mockImplementation((_id: unknown, patch: { status?: unknown }) =>
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 2bd81b0ce..851dec115 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -34,7 +34,7 @@ import {
SessionEngineEventWiring,
SessionEngineWiringHost,
} from './session-engine-event-wiring';
-import { SessionEngineControls } from './session-engine-controls';
+import { SessionEngineControls, type StopHooks } from './session-engine-controls';
import { SessionOwnershipService, nodeOwnsSession } from './session-ownership.service';
/**
@@ -436,8 +436,8 @@ export class SessionEngineLifecycle {
}
/** Delegate: SessionEngineControls.stop. */
- stop(id: string): Promise<Session> {
- return this.controls.stop(id);
+ stop(id: string, hooks?: StopHooks): Promise<Session> {
+ return this.controls.stop(id, hooks);
}
/** Delegate: SessionEngineControls.logout. */
@@ -451,8 +451,8 @@ export class SessionEngineLifecycle {
}
/** Delegate: SessionEngineControls.delete. */
- delete(id: string): Promise<void> {
- return this.controls.delete(id);
+ delete(id: string, hooks?: StopHooks): Promise<void> {
+ return this.controls.delete(id, hooks);
}
/** Delegate: SessionEngineControls.shutdown. */