Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): retry a launch that failed on a locked database
Yudhi Armyndharis558b215f843f
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0137f21c3..918b90203 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 session launch that fails on a locked database is retried. The classifier looked for `SQLITE_BUSY` in the error message while the driver carries it on `code`, so the session stayed down until a restart.- Meta-hosted ids (`@hosted`, `@hosted.lid`) normalize to the dialect they name. They parsed as unknown before, so a chat surfaced with kind `unknown` and the same id was then refused with a `400` on any write.## [0.21.0] - 2026-08-18diff --git a/src/modules/session/session.service.spec.ts b/src/modules/session/session.service.spec.tsindex dfc3ca965..657f619d6 100644--- a/src/modules/session/session.service.spec.ts+++ b/src/modules/session/session.service.spec.ts@@ -3,7 +3,7 @@ import { SessionRestrictionStore } from './session-restriction-store.service';import { PresenceStore } from './presence-store.service';import { Test, TestingModule } from '@nestjs/testing';import { getRepositoryToken, getDataSourceToken } from '@nestjs/typeorm';-import { Repository, DataSource, In } from 'typeorm';+import { Repository, DataSource, In, QueryFailedError } from 'typeorm';import {NotFoundException,ConflictException,@@ -893,6 +893,50 @@ describe('SessionService', () => {expect(mockEngine.initialize).toHaveBeenCalledTimes(2);});+ /**+ * The shape better-sqlite3 actually throws under write contention: the token lives on `code`,+ * and the message reads `database is locked`. TypeORM copies the driver's own properties onto+ * QueryFailedError and rewrites the message to `SqliteError: database is locked`, so the token+ * appears in neither message. A classifier matching `SQLITE_BUSY` as text cannot fire on either.+ */+ const sqliteBusy = (): QueryFailedError => {+ const driverError = Object.assign(new Error('database is locked'), {+ name: 'SqliteError',+ code: 'SQLITE_BUSY',+ });+ return new QueryFailedError('UPDATE sessions SET status = ?', [], driverError);+ };++ it('retries a locked-database launch failure, which no message text reveals', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);+ const busy = sqliteBusy();+ // The premise of reading `code`: the token is absent from every message on this error.+ expect(busy.message).not.toContain('SQLITE_BUSY');+ expect(busy.driverError.message).not.toContain('SQLITE_BUSY');+ expect((busy as unknown as { code: string }).code).toBe('SQLITE_BUSY');++ mockEngine.initialize.mockRejectedValueOnce(busy).mockResolvedValueOnce(undefined);++ await expect(service.start('sess-uuid-1')).resolves.toBeDefined();+ expect(mockEngine.initialize).toHaveBeenCalledTimes(2);+ });++ it('does NOT retry a malformed query, which carries a different driver code', async () => {+ (repository.findOne as jest.Mock).mockResolvedValue(createMockSession());+ (repository.update as jest.Mock).mockResolvedValue({ affected: 1 });+ (engineFactory.create as jest.Mock).mockClear().mockReturnValue(mockEngine);+ const driverError = Object.assign(new Error('no such column: nope'), {+ name: 'SqliteError',+ code: 'SQLITE_ERROR',+ });+ mockEngine.initialize.mockRejectedValue(new QueryFailedError('SELECT nope', [], driverError));++ await expect(service.start('sess-uuid-1')).rejects.toBeInstanceOf(QueryFailedError);+ expect(mockEngine.initialize).toHaveBeenCalledTimes(1);+ });+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 });diff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex a7911bc4d..f0cce08ea 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -34,6 +34,17 @@ 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;+/**+ * Driver codes meaning "locked, try again", not "your query is wrong".+ *+ * These are unreachable through the message regex below, which is why the code is read separately.+ * better-sqlite3 reports lock contention as `code: 'SQLITE_BUSY'` with the message `database is+ * locked`, and TypeORM's QueryFailedError copies the driver's own properties onto itself while+ * rewriting the message to `SqliteError: database is locked`. So the code survives the wrap and the+ * token never appears in any message: matching `SQLITE_BUSY` as text could not fire on either shape.+ */+const TRANSIENT_DB_CODES = new Set(['SQLITE_BUSY', 'SQLITE_LOCKED']);+/*** 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@@ -49,10 +60,10 @@ function isTransientLaunchFailure(error: unknown): boolean {if (error instanceof EngineTransportError) return true;if (error instanceof HttpException) return false;// TypeORM QueryFailedError and driver errors carry no HttpException shape.- return (- error instanceof Error &&- /connection|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|SQLITE_BUSY|terminating connection/i.test(error.message)- );+ if (!(error instanceof Error)) return false;+ const code: unknown = (error as { code?: unknown }).code;+ if (typeof code === 'string' && TRANSIENT_DB_CODES.has(code)) return true;+ return /connection|ECONNREFUSED|ECONNRESET|ETIMEDOUT|EAI_AGAIN|terminating connection/i.test(error.message);}/** Pause between sequential auto-start launches so a burst of Chromium boots does not spike the host. */