Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

fix(session): retry a transient launch failure once instead of stranding the session

Yudhi Armyndharisb611daed14c4
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 30d395939..3dac967d5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- A transient session-launch failure (dead page at initialize, a database hiccup) gets one bounded retry that keeps the claim held; adopt and boot auto-start used to release the claim and leave the session down until a restart.
- The twelve hand-rolled "Session is not started" guards in the session service route through the engine registry's `require()` (wire contract unchanged), and three routes drop an OpenAPI 404 declaration no code path can produce.
- import-data restores an active session status from the backup as `disconnected` (scoped to claimable rows; a notice counts them), so migrated sessions are startable without a process restart.
- The engine parity gate reads any single-quoted throw literal (a parenthesized site like sendText(customPreview) escaped the identifier-only regex), rejects construction sites it cannot see (template literals, variable arguments, literals naming no method), and pins conditional refusals in an explicit list; docs/29 states the refinements.
diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.ts
index c5f86e986..dfc3ca965 100644
--- a/src/modules/session/session.service.spec.ts
+++ b/src/modules/session/session.service.spec.ts
@@ -9,9 +9,11 @@ import {
ConflictException,
BadRequestException,
BadGatewayException,
+ GatewayTimeoutException,
HttpException,
HttpStatus,
} from '@nestjs/common';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
import { ConfigService } from '@nestjs/config';
import { SessionService, AUTOSTART_THROTTLE_MS } from './session.service';
import { ACK_RECONCILE_DELAY_MS } from './message-projector.service';
@@ -876,6 +878,45 @@ describe('SessionService', () => {
expect((caught as HttpException).getStatus()).toBe(HttpStatus.GATEWAY_TIMEOUT);
});
+ it('retries a transient launch failure once and keeps the claim held', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);
+ // First launch dies on a dead page (EngineTransportError - infrastructure, not the session);
+ // the single retry goes through, so the session survives what used to need a process restart.
+ mockEngine.initialize
+ .mockRejectedValueOnce(new EngineTransportError('Protocol error: Target closed'))
+ .mockResolvedValueOnce(undefined);
+
+ await expect(service.start('sess-uuid-1')).resolves.toBeDefined();
+
+ expect(mockEngine.initialize).toHaveBeenCalledTimes(2);
+ });
+
+ it('gives up after the single retry and surfaces the failure (no unbounded loop)', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);
+ mockEngine.initialize.mockRejectedValue(new EngineTransportError('Protocol error: Target closed'));
+
+ await expect(service.start('sess-uuid-1')).rejects.toBeInstanceOf(EngineTransportError);
+ expect(mockEngine.initialize).toHaveBeenCalledTimes(2);
+ });
+
+ it('does NOT retry a 504 auth timeout: the account/proxy answer propagates immediately', async () => {
+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);
+ mockEngine.initialize.mockRejectedValue(new GatewayTimeoutException('auth timeout'));
+
+ // The lifecycle re-wraps the timeout into its own 504 HttpException; the pinned behavior is
+ // the status and that the launch was NOT retried.
+ const caught = await service.start('sess-uuid-1').catch((e: unknown) => e);
+ expect(caught).toBeInstanceOf(HttpException);
+ expect((caught as HttpException).getStatus()).toBe(HttpStatus.GATEWAY_TIMEOUT);
+ expect(mockEngine.initialize).toHaveBeenCalledTimes(1);
+ });
+
it('allows a fresh start after the previous one completed (reservation is cleared)', async () => {
(repository.findOne as jest.Mock).mockResolvedValue(createMockSession());
(repository.update as jest.Mock).mockResolvedValue({ affected: 1 });
diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.ts
index 0f95872cd..023acb8f2 100644
--- a/src/modules/session/session.service.ts
+++ b/src/modules/session/session.service.ts
@@ -13,6 +13,7 @@ import { InjectRepository, InjectDataSource } from '@nestjs/typeorm';
import { Repository, In, Not, IsNull, DataSource, FindManyOptions } from 'typeorm';
import { QueryDeepPartialEntity } from 'typeorm/query-builder/QueryPartialEntity';
import { setTimeout } from 'node:timers/promises';
+import { EngineTransportError } from '../../common/errors/engine-transport.error';
import { Session, SessionStatus } from './entities/session.entity';
import { CreateSessionDto, SessionConfigResponseDto, UpdateSessionConfigDto } from './dto';
import { EngineRegistry } from '../../engine/engine-registry.service';
@@ -29,6 +30,28 @@ import { IWhatsAppEngine, ChatSummary, ChatState } from '../../engine/interfaces
import { createLogger } from '../../common/services/logger.service';
import { HookManager } from '../../core/hooks';
+/** Stagger before the single transient-launch retry; short - the claim is held while it waits. */
+const SESSION_START_RETRY_DELAY_MS = 2_000;
+
+/**
+ * A launch failure worth one retry: infrastructure said "not now" (a 5xx, a transport death, a
+ * database error while persisting status), not the session or the caller being refused. HTTP 4xx
+ * and the documented 409 not-ready are deliberate answers, and a lost-claim ConflictException is a
+ * real conflict.
+ */
+function isTransientLaunchFailure(error: unknown): boolean {
+ // EngineTransportError (503) is the one mapped HTTP shape that means infrastructure died
+ // mid-launch (dead page/socket at initialize). Every OTHER HttpException is a deliberate
+ // answer: the 409 not-ready family reflects session state, the 504 auth-timeout family
+ // reflects the account/proxy, and a 4xx is a refusal.
+ if (error instanceof EngineTransportError) return true;
+ // TypeORM QueryFailedError and driver errors carry no HttpException shape.
+ return (
+ error instanceof Error &&
+ /connection|ECONNREFUSED|ETIMEDOUT|EAI_AGAIN|SQLITE_BUSY|terminating connection/i.test(error.message)
+ );
+}
+
/** Pause between sequential auto-start launches so a burst of Chromium boots does not spike the host. */
export const AUTOSTART_THROTTLE_MS = 2_000;
@@ -408,7 +431,7 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
throw new ConflictException(`Session ${id} is running on another node`);
}
try {
- return await this.engineLifecycle.start(id);
+ return await this.startWithTransientRetry(id);
} catch (error) {
// 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
@@ -419,6 +442,39 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat
}
}
+ /**
+ * One bounded retry for a TRANSIENT launch failure (a database hiccup while persisting the
+ * initial status, a transport blip while the adapter boots). A transient failure during adopt or
+ * boot auto-start used to release the claim and end the story: nothing ever retried, so the
+ * session stayed down until some process restarted. The retry keeps the claim held (the outer
+ * catch only runs when this gives up), and re-claims it if the retry window outlived the lease -
+ * a lapsed claim must not turn the retry into a 409.
+ *
+ * Bounded to one retry on a short stagger: a persistent failure is a real fault, and an
+ * 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): Promise<Session> {
+ try {
+ return await this.engineLifecycle.start(id);
+ } catch (error) {
+ if (!isTransientLaunchFailure(error)) throw error;
+ this.logger.warn(`Transient launch failure for session ${id}; retrying once`, {
+ sessionId: id,
+ action: 'session_start_transient_retry',
+ error: error instanceof Error ? error.message : String(error),
+ });
+ await setTimeout(SESSION_START_RETRY_DELAY_MS);
+ // The lease may have lapsed while the first attempt ran; the retry must keep holding the
+ // claim, never 409 on the session it already owns.
+ if (this.ownership && !(await this.ownership.claim(id))) {
+ await this.findOne(id);
+ throw new ConflictException(`Session ${id} is running on another node`);
+ }
+ return this.engineLifecycle.start(id);
+ }
+ }
+
async stop(id: string): Promise<Session> {
// Synchronous stop-mark before the awaited fence — see delete() for why.
this.engineLifecycle.markStopping(id);