Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(session): keep a create's transaction out of another's
Yudhi Armyndharisad045b0d5da7
diff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 710b8ac08..afdc2d439 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -634,7 +634,7 @@ whichever proxy they go through.Like every other session route, this returns the `SessionResponseDto` shape (via `fromEntity`), so `config`, `proxyUrl` and `proxyType` are stripped and `lastActiveAt` appears as `lastActive`. Newly created `status` is `created`. Masked proxy details come only from `GET /api/sessions/{sessionId}/proxy`.-**Errors:** `400` validation (bad `name`/`proxyUrl`/`proxyType`, or an extra non-whitelisted field) · `401` · `403` key lacks OPERATOR role, `proxyUrl` set by a key below ADMIN, or the key is restricted to specific sessions · `409` session name already exists+**Errors:** `400` validation (bad `name`/`proxyUrl`/`proxyType`, or an extra non-whitelisted field) · `401` · `403` key lacks OPERATOR role, `proxyUrl` set by a key below ADMIN, or the key is restricted to specific sessions · `409` session name already exists · `503` on SQLite, another database transaction stayed open for 10 s (nothing is stored; retry)#### POST /api/sessions/:sessionId/startdiff --git a/openapi.json b/openapi.jsonindex 3eb866b4f..dd4991684 100644--- a/openapi.json+++ b/openapi.json@@ -661,6 +661,16 @@}}}+ },+ "503": {+ "description": "On SQLite, another database transaction stayed open for 10 s; nothing was stored, so retry.",+ "content": {+ "application/json": {+ "schema": {+ "$ref": "#/components/schemas/ErrorResponse"+ }+ }+ }}},"summary": "Create a new WhatsApp session",diff --git a/src/modules/session/session-content-lifetime.spec.ts b/src/modules/session/session-content-lifetime.spec.tsindex d90242e95..a2647b683 100644--- a/src/modules/session/session-content-lifetime.spec.ts+++ b/src/modules/session/session-content-lifetime.spec.ts@@ -848,4 +848,72 @@ describe('Session content lifetime', () => {},);});++ // Both creates pass the name check, so one loses on the unique index. On SQLite, begun in the same turn of the+ // event loop, the loser's transaction would be a savepoint in the winner's, or the reverse.+ describe('two creates of one name begun in the same turn', () => {+ let sessions: SessionService;++ beforeEach(() => {+ const attach = { attachTo: (session: Session) => session } as never;+ const unused = {} as never;+ sessions = new SessionService(+ db.getRepository(Session),+ unused,+ db,+ engines,+ unused,+ attach,+ attach,+ unused,+ hooks,+ unused,+ unused,+ );+ });++ // Over this range the second begins before, during and after the first one's transaction.+ it('store one session and refuse the other', async () => {+ for (let steps = 0; steps <= 40; steps += 1) {+ const name = `twin-${steps}`;+ const second = async () => {+ for (let i = 0; i < steps; i += 1) await Promise.resolve();+ return sessions.create({ name });+ };+ const outcomes = await Promise.all(+ [sessions.create({ name }), second()].map(create =>+ create.then(+ () => 'created',+ (error: unknown) => (error instanceof ConflictException ? 'refused' : String(error)),+ ),+ ),+ );+ const stored = await db.getRepository(Session).countBy({ name });+ expect({ steps, outcomes: outcomes.sort(), stored }).toEqual({+ steps,+ outcomes: ['created', 'refused'],+ stored: 1,+ });+ }+ });++ (process.env.DATABASE_TYPE === 'postgres' ? it.skip : it)(+ 'refuses with 503 and stores nothing when a transaction beside it stays open',+ async () => {+ const other = db.createQueryRunner();+ await other.connect();+ await other.startTransaction();+ const start = Date.now();+ let calls = 0;+ const clock = jest.spyOn(Date, 'now').mockImplementation(() => start + FOREIGN_TRANSACTION_WAIT_MS * calls++);++ await expect(sessions.create({ name: 'held' })).rejects.toThrow(ServiceUnavailableException);+ clock.mockRestore();+ await other.commitTransaction();+ await other.release();++ expect(await db.getRepository(Session).countBy({ name: 'held' })).toBe(0);+ },+ );+ });});diff --git a/src/modules/session/session.controller.ts b/src/modules/session/session.controller.tsindex e763dd2cc..0f086d67d 100644--- a/src/modules/session/session.controller.ts+++ b/src/modules/session/session.controller.ts@@ -101,6 +101,10 @@ export class SessionController {})@ApiResponse({ status: 400, description: 'Validation failed, or the body carries a field the DTO does not declare.' })@ApiResponse({ status: 409, description: 'Session name already exists' })+ @ApiResponse({+ status: 503,+ description: 'On SQLite, another database transaction stayed open for 10 s; nothing was stored, so retry.',+ })async create(@Body() dto: CreateSessionDto, @CurrentApiKey() apiKey?: ApiKey): Promise<SessionResponseDto> {// A session proxy carries the session's egress, including the gateway's fetches of caller-supplied// URLs, so choosing one is a deployment decision: ADMIN only, like PATCH :sessionId/proxy. Thediff --git a/src/modules/session/session.service.ts b/src/modules/session/session.service.tsindex 9d2b73bd4..db960f5ad 100644--- a/src/modules/session/session.service.ts+++ b/src/modules/session/session.service.ts@@ -52,6 +52,7 @@ import { SessionOwnershipService } from './session-ownership.service';import { paginate, ListOptions, resolveListWindow } from '../../common/utils/paginate';import { ListingMemo } from '../../common/utils/listing-memo';import { isTransientDbError, isUniqueViolation } from '../../common/utils/db-errors';+import { awaitNoOpenTransaction } from '../../common/utils/shared-connection';import { resolveFeatureFlags } from '../../config/feature-flags';import { IWhatsAppEngine, ChatSummary, ChatState } from '../../engine/interfaces/whatsapp-engine.interface';import { createLogger } from '../../common/services/logger.service';@@ -431,6 +432,13 @@ export class SessionService implements OnModuleDestroy, OnModuleInit, OnApplicat// The findOne pre-check above is a fast path for the common case, but it's a check-then-insert// TOCTOU: two concurrent same-name creates both pass it, then one hits the name UNIQUE constraint.// Translate that violation to a 409 (matching the pre-check) instead of leaking a raw 500.+ // On SQLite every caller shares one connection: opened beside another caller's transaction, this one would be a+ // savepoint in it or carry that one's writes, and either rollback could undo what the other had answered for.+ if (!(await awaitNoOpenTransaction(this.dataSource))) {+ throw new ServiceUnavailableException(+ `Session '${dto.name}' was not created: another database transaction stayed open. Retry the create.`,+ );+ }let saved: Session;try {saved = await this.dataSource.transaction(async manager => {