Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): handle a disconnect again when its row read fails

Yudhi Armyndharis67eaba1842d1
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d0bc61bac..e5580f6ef 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -125,6 +125,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- Print the startup banner's API Docs URL only when Swagger is served, so a production boot no longer points at a `404`.
- Decode numeric and common named character references in a Baileys link preview's title and description, so `’` and `é` no longer reach the recipient as written.
- Log an error at whatsapp-web.js start when the message-id backport is only partly applied, naming the files it did not reach.
+- Handle an engine disconnect again when the session row read fails, so the session reconnects instead of staying registered with no reconnect armed.
### Documentation
diff --git a/src/modules/session/session-engine-lifecycle-races.spec.ts b/src/modules/session/session-engine-lifecycle-races.spec.ts
index f1b5ae8e4..cc34b798b 100644
--- a/src/modules/session/session-engine-lifecycle-races.spec.ts
+++ b/src/modules/session/session-engine-lifecycle-races.spec.ts
@@ -385,6 +385,53 @@ describe('SessionEngineLifecycle races', () => {
});
});
+ // The engine reports DISCONNECTED itself, so the liveness watchdog never probes it again, and it stays
+ // registered with its lease renewed: a disconnect whose row read fails once is not handled again by anything.
+ describe('a disconnect whose session read fails', () => {
+ afterEach(() => jest.useRealTimers());
+
+ const disconnectWithFailedRead = async (): Promise<{
+ engine: Record<string, jest.Mock>;
+ state: ReconnectState;
+ }> => {
+ await lifecycle.start(ID);
+ const engine = (engineFactory.create.mock.results[0] as { value: Record<string, jest.Mock> }).value;
+ const callbacks = (engine.initialize.mock.calls as [EngineEventCallbacks][])[0][0];
+ const state = internals.reconnectStates.get(ID)!;
+ jest.useFakeTimers({ doNotFake: ['setImmediate', 'nextTick', 'queueMicrotask'] });
+ repository.findOne.mockRejectedValueOnce(new Error('SQLITE_BUSY: database is locked'));
+
+ callbacks.onDisconnected?.('NAVIGATION');
+ await flush();
+ return { engine, state };
+ };
+
+ it('handles the disconnect again, so a reconnect is armed once the read succeeds', async () => {
+ const { engine, state } = await disconnectWithFailedRead();
+ expect(state.attempts).toBe(0);
+ expect(state.timer).not.toBeNull();
+
+ jest.advanceTimersByTime(state.baseDelay);
+ await flush();
+
+ expect(state.attempts).toBe(1);
+ expect(state.timer).not.toBeNull();
+ expect(internals.engines.get(ID)).toBe(engine);
+ });
+
+ it('does not read again once a stop has retired the engine', async () => {
+ const { state } = await disconnectWithFailedRead();
+ await lifecycle.stop(ID);
+ const reads = repository.findOne.mock.calls.length;
+
+ jest.advanceTimersByTime(state.baseDelay * 2);
+ await flush();
+
+ expect(repository.findOne.mock.calls.length).toBe(reads);
+ expect(internals.reconnectStates.has(ID)).toBe(false);
+ });
+ });
+
describe('a reconnect attempt failing while the next one tears its engine down', () => {
it('leaves the episode to the later attempt instead of arming another over it', async () => {
const state: ReconnectState = { attempts: 1, timer: null, maxAttempts: 5, baseDelay: 5000 };
diff --git a/src/modules/session/session-engine-lifecycle.service.ts b/src/modules/session/session-engine-lifecycle.service.ts
index 7e46f8119..8d79e2a06 100644
--- a/src/modules/session/session-engine-lifecycle.service.ts
+++ b/src/modules/session/session-engine-lifecycle.service.ts
@@ -1045,6 +1045,9 @@ export class SessionEngineLifecycle {
sessionId: id,
action: 'reconnect_schedule_error',
});
+ // Nothing else revisits this disconnect: the engine reports DISCONNECTED itself, so the liveness
+ // watchdog skips it, and it stays registered with its lease renewed. Read again shortly.
+ this.retryDisconnectAfterFailedRead(id, engine, reason);
return;
}
// A session deleted just before this ran has nothing left to reconnect; skip it.
@@ -1125,6 +1128,21 @@ export class SessionEngineLifecycle {
this.scheduleReconnect(id, session);
}
+ /**
+ * Handle a disconnect again after its session read failed. The retry sits on the episode's reconnect
+ * timer, so every control that cancels a reconnect (stop, delete, logout, shutdown) cancels it too, and
+ * it re-enters handleEngineDisconnected, whose fences end it once the engine is no longer the live one.
+ * It repeats at the base reconnect delay until the read answers.
+ */
+ private retryDisconnectAfterFailedRead(id: string, engine: IWhatsAppEngine, reason: string): void {
+ const state = this.reconnectStates.get(id);
+ if (!state || state.timer || this.closed || this.shutdownService?.isShuttingDown()) return;
+ state.timer = setTimeout(() => {
+ state.timer = null;
+ void this.handleEngineDisconnected(id, engine, reason);
+ }, state.baseDelay);
+ }
+
private scheduleReconnect(id: string, session: Session): void {
// Don't launch a fresh engine (Chromium) mid-shutdown: a disconnect during the drain window would
// otherwise schedule a reconnect that races the shutdown teardown and could orphan a browser.