Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
feat(db): serialize postgres boot migrations across replicas with an advisory lock
Yudhi Armyndharis091932f1bcab
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 01f81ff81..1e2a7b779 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -227,10 +227,11 @@ jobs:DATABASE_NAME: openwa# Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the- # STORED body_ts tsvector). The spec self-skips unless DATABASE_TYPE=postgres, so it is a no-op- # in the default test job and only executes here against the postgres:16 service.- - name: Postgres FTS provider spec- run: npx jest src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts+ # STORED body_ts tsvector) and the boot-migration advisory lock (two concurrent migrators on+ # one database). Both specs self-skip unless DATABASE_TYPE=postgres, so they are a no-op+ # in the default test job and only execute here against the postgres:16 service.+ - name: Postgres specs (FTS provider + boot-migration lock)+ run: npx jest src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.tsenv:DATABASE_TYPE: postgresDATABASE_HOST: localhostdiff --git a/.github/workflows/release.yml b/.github/workflows/release.ymlindex 92b31a5b8..df5333f81 100644--- a/.github/workflows/release.yml+++ b/.github/workflows/release.yml@@ -204,10 +204,11 @@ jobs:DATABASE_NAME: openwa# Runtime-proves BuiltInFtsProvider on Postgres (websearch_to_tsquery + ts_headline against the- # STORED body_ts tsvector). The spec self-skips unless DATABASE_TYPE=postgres, so it is a no-op- # in the default test job and only executes here against the postgres:16 service.- - name: Postgres FTS provider spec- run: npx jest src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts+ # STORED body_ts tsvector) and the boot-migration advisory lock (two concurrent migrators on+ # one database). Both specs self-skip unless DATABASE_TYPE=postgres, so they are a no-op+ # in the default test job and only execute here against the postgres:16 service.+ - name: Postgres specs (FTS provider + boot-migration lock)+ run: npx jest src/database/migrations/__tests__/1782400000000-AddMessagesFts.pg.spec.ts src/database/migrations/__tests__/pg-boot-migrations.pg.spec.tsenv:DATABASE_TYPE: postgresDATABASE_HOST: localhostdiff --git a/charts/openwa/values.yaml b/charts/openwa/values.yamlindex 2f0fe66eb..17bf37ea3 100644--- a/charts/openwa/values.yaml+++ b/charts/openwa/values.yaml@@ -3,6 +3,10 @@# happen. What is still process-local is the reason: API-key socket eviction, the WS# rate-limit buckets, the liveness watchdog and reconnect timers, and in-flight bulk# batches. See docs/13-horizontal-scaling.md.+# Postgres boot migrations no longer add a cross-replica hazard: replicas serialize them+# with a session-scoped advisory lock at startup, so simultaneous boots cannot race DDL+# against the shared migrations ledger. That part is enforced in-process, not by keeping+# replicaCount at 1 — the process-local state above is what still keeps it at 1.replicaCount: 1image:diff --git a/package-lock.json b/package-lock.jsonindex 8f517f48b..6bca1e51e 100644--- a/package-lock.json+++ b/package-lock.json@@ -63,6 +63,7 @@"@types/jest": "^30.0.0","@types/multer": "^2.2.0","@types/node": "^22",+ "@types/pg": "^8.21.0","@types/qrcode": "^1.5.5","@types/supertest": "^7.2.1","@types/tar-stream": "^3.1.4",@@ -4513,6 +4514,18 @@"undici-types": "~6.21.0"}},+ "node_modules/@types/pg": {+ "version": "8.21.0",+ "resolved": "https://registry.npmjs.org/@types/pg/-/pg-8.21.0.tgz",+ "integrity": "sha512-AYdtudzabjLZgVgRZmAnU8bAnVUXzuJX2IYHeSIiIHm68olD+LgQYCGWdtcNYnP0uq9c4S4NibVG3Ni7VbKW7Q==",+ "dev": true,+ "license": "MIT",+ "dependencies": {+ "@types/node": "*",+ "pg-protocol": "*",+ "pg-types": "^2.2.0"+ }+ },"node_modules/@types/qrcode": {"version": "1.5.6","resolved": "https://registry.npmjs.org/@types/qrcode/-/qrcode-1.5.6.tgz",diff --git a/package.json b/package.jsonindex 8971471b5..ba870a2d7 100644--- a/package.json+++ b/package.json@@ -119,6 +119,7 @@"@types/jest": "^30.0.0","@types/multer": "^2.2.0","@types/node": "^22",+ "@types/pg": "^8.21.0","@types/qrcode": "^1.5.5","@types/supertest": "^7.2.1","@types/tar-stream": "^3.1.4",diff --git a/src/app.module.ts b/src/app.module.tsindex 339cb7fb7..e0e2aee66 100644--- a/src/app.module.ts+++ b/src/app.module.ts@@ -9,6 +9,7 @@ import { RedisThrottlerStorage } from './common/throttler/redis-throttler.storagimport { createThrottlerRedisClient } from './common/throttler/throttler-redis.client';import configuration from './config/configuration';import { validateEnv } from './config/env.validation';+import { createBootDataSource } from './database/pg-boot-migrations';import { SessionModule } from './modules/session/session.module';import { MessageModule } from './modules/message/message.module';import { TemplateModule } from './modules/template/template.module';@@ -155,6 +156,10 @@ if (dashboardServingEnabled && dashboardBuildPresent) {name: 'data',imports: [ConfigModule],inject: [ConfigService],+ // The postgres branch runs its boot migrations under a cross-replica advisory lock inside+ // this factory (see pg-boot-migrations.ts) instead of TypeORM's unsynchronized built-in+ // migrationsRun; the sqlite branches keep the library's default construction + initialize.+ dataSourceFactory: createBootDataSource,useFactory: (configService: ConfigService) => {const dbType = configService.get<'sqlite' | 'postgres'>('dataDatabase.type', 'sqlite');const baseConfig = {@@ -198,7 +203,11 @@ if (dashboardServingEnabled && dashboardBuildPresent) {}: false,- // Never auto-sync Postgres in production; rely on migrations.+ // Never auto-sync Postgres in production; rely on migrations. Boot migrations execute+ // inside createBootDataSource (dataSourceFactory above) under the advisory lock — this+ // flag states the intent and remains the built-in fallback if that factory is ever+ // bypassed (the factory constructs the DataSource with migrationsRun:false and calls+ // runMigrations() itself while holding the lock).synchronize: configService.get<boolean>('dataDatabase.synchronize', false),migrationsRun: true,retryAttempts: 10,@@ -207,7 +216,7 @@ if (dashboardServingEnabled && dashboardBuildPresent) {max: configService.get<number>('dataDatabase.poolSize', 10),// Runtime query/pool timeouts so a stuck query or saturated pool fails fast instead of// hanging requests. statement_timeout bounds live runtime queries; the boot migrations- // (migrationsRun above) reset it to 0 per-transaction via SET LOCAL, so a long+ // reset it to 0 per-transaction via SET LOCAL, so a long// CREATE INDEX / backfill at boot is never aborted by it.statement_timeout: configService.get<number>('dataDatabase.statementTimeoutMs', 30000),idleTimeoutMillis: configService.get<number>('dataDatabase.idleTimeoutMs', 30000),diff --git a/src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts b/src/database/migrations/__tests__/pg-boot-migrations.pg.spec.tsnew file mode 100644index 000000000..5fab8a03e--- /dev/null+++ b/src/database/migrations/__tests__/pg-boot-migrations.pg.spec.ts@@ -0,0 +1,81 @@+/* istanbul ignore file -- PG-gated: only runs under DATABASE_TYPE=postgres (test-postgres CI job);+ skipped in the default test job, so its lines would be unread and skew the global coverage gate. */+import 'reflect-metadata';+import * as path from 'path';+import { DataSource, DataSourceOptions } from 'typeorm';+import { createBootDataSource } from '../../pg-boot-migrations';++/**+ * Postgres runtime coverage for the boot-migration advisory lock. Two "replicas" (independent+ * boot paths sharing nothing but the database) start migrating CONCURRENTLY; without the lock+ * both would see an empty migrations ledger and race DDL (duplicate tables / deadlocks). With the+ * lock, one applies the chain while the other blocks in pg_advisory_lock, then applies nothing.+ *+ * Gating: mirrors the repo's PG harness convention exactly (scripts/pg-uuid-smoke.js + the+ * "Test (PostgreSQL migrations)" CI job + 1782400000000-AddMessagesFts.pg.spec.ts) — skip the+ * whole suite unless DATABASE_TYPE=postgres is set; the CI job runs it against a postgres:16+ * service, locally it skips cleanly.+ */+const POSTGRES_ENABLED = process.env.DATABASE_TYPE === 'postgres';++(POSTGRES_ENABLED ? describe : describe.skip)('postgres boot migrations (advisory lock)', () => {+ const schema = process.env.POSTGRES_SCHEMA || 'public';+ const useCustomSearchPath = schema !== 'public';+ let admin: DataSource;++ const connectionOptions = {+ host: process.env.DATABASE_HOST || 'localhost',+ port: Number(process.env.DATABASE_PORT || 5432),+ username: process.env.DATABASE_USERNAME || 'openwa',+ password: process.env.DATABASE_PASSWORD || 'openwa',+ database: process.env.DATABASE_NAME || 'openwa',+ };++ // The exact options shape app.module.ts hands to createBootDataSource for the postgres data+ // connection: full migration chain, non-public schema via pg's startup search_path (see+ // pg-uuid-smoke.js for why the `options` parameter — not TypeORM's `schema` — is what routes+ // raw DDL to the schema).+ const bootMigratorOptions = (): DataSourceOptions => ({+ type: 'postgres',+ ...connectionOptions,+ migrations: [path.join(__dirname, '..', '*{.ts,.js}')],+ ...(useCustomSearchPath ? { extra: { options: `-c search_path=${schema},public` } } : {}),+ });++ beforeEach(async () => {+ admin = new DataSource({ type: 'postgres', ...connectionOptions });+ await admin.initialize();+ // Fresh schema each test: the CI job shares one service across steps, so wipe whatever the+ // pg-smoke step (or a previous test) left behind — tables AND the migrations ledger.+ await admin.query(`DROP SCHEMA IF EXISTS "${schema}" CASCADE`);+ await admin.query(`CREATE SCHEMA "${schema}"`);+ });++ afterEach(async () => {+ if (admin && admin.isInitialized) {+ await admin.destroy();+ }+ });++ it('serializes two concurrent boot migrators: both resolve, ledger holds one row per migration', async () => {+ // Promise.all starts both boot paths before either can finish — the exact race replicas+ // hit when a deployment scales up against one shared Postgres.+ const [a, b] = await Promise.all([+ createBootDataSource(bootMigratorOptions()),+ createBootDataSource(bootMigratorOptions()),+ ]);++ try {+ const expected = a.migrations.length; // the full chain, loaded from the same glob+ // Unqualified name: resolves through the same session search_path the ledger was written+ // under, exactly like the raw migration SQL.+ const ledger: Array<{ name: string }> = await a.query(`SELECT name FROM "migrations"`);+ expect(ledger).toHaveLength(expected);+ // No migration applied twice — the double-apply shape concurrent migrationsRun produces.+ expect(new Set(ledger.map(row => row.name)).size).toBe(expected);+ } finally {+ await a.destroy();+ await b.destroy();+ }+ }, 120_000);+});diff --git a/src/database/pg-boot-migrations.spec.ts b/src/database/pg-boot-migrations.spec.tsnew file mode 100644index 000000000..84a47bbcf--- /dev/null+++ b/src/database/pg-boot-migrations.spec.ts@@ -0,0 +1,178 @@+import { DataSource, DataSourceOptions } from 'typeorm';+import {+ AdvisoryLockClient,+ BootDataSourceDeps,+ POSTGRES_BOOT_MIGRATION_LOCK_KEYS,+ createBootDataSource,+} from './pg-boot-migrations';++// Protocol wiring of the boot-migration advisory lock: the lock must be taken BEFORE runMigrations+// starts and dropped after it finishes (on success AND on migration failure), and the DataSource+// handed back to Nest must never carry migrationsRun (it would re-run the chain unsynchronized).+// The pg client and the DataSource constructor are injected as fakes; the PG-gated companion spec+// (pg-boot-migrations.pg.spec.ts) proves the same protocol against a real Postgres.++const PG_OPTIONS: DataSourceOptions = {+ type: 'postgres',+ host: 'db',+ port: 5432,+ username: 'openwa',+ password: 'secret',+ database: 'openwa',+ // The app config still carries this; the factory takes over execution and must neutralize it.+ migrationsRun: true,+ migrationsTransactionMode: 'all',+ extra: { statement_timeout: 30000, connectionTimeoutMillis: 10000 },+};++describe('createBootDataSource (postgres boot migrations)', () => {+ // Fakes keep their inferred jest.Mock types (casts live only at the injection boundary) and+ // record every step in `calls`, so ordering is asserted on one linear trace.+ function makeFakes(runMigrations: () => Promise<unknown> = jest.fn()) {+ const calls: string[] = [];+ const dataSource = {+ initialize: jest.fn(() => {+ calls.push('initialize');+ return Promise.resolve();+ }),+ runMigrations: jest.fn(() => {+ calls.push('runMigrations');+ return runMigrations();+ }),+ destroy: jest.fn(() => {+ calls.push('destroy');+ return Promise.resolve();+ }),+ };+ const lockClient: AdvisoryLockClient = {+ connect: jest.fn(() => {+ calls.push('connect');+ return Promise.resolve();+ }),+ query: jest.fn((text: string) => {+ calls.push(text);+ return Promise.resolve();+ }),+ end: jest.fn(() => {+ calls.push('end');+ return Promise.resolve();+ }),+ };+ const deps: BootDataSourceDeps = {+ createDataSource: jest.fn(() => dataSource as unknown as DataSource),+ createLockClient: jest.fn(() => lockClient),+ };+ return { calls, dataSource, lockClient, deps };+ }++ it('initializes, then migrates strictly between advisory lock acquire and release', async () => {+ const { calls, dataSource, lockClient, deps } = makeFakes();++ const returned = await createBootDataSource(PG_OPTIONS, deps);++ expect(returned).toBe(dataSource);+ expect(calls).toEqual([+ 'initialize',+ 'connect',+ 'SELECT pg_advisory_lock($1, $2)',+ 'runMigrations',+ 'SELECT pg_advisory_unlock($1, $2)',+ 'end',+ ]);+ // Same key for acquire and release, in the (key1, key2) form.+ expect(lockClient.query).toHaveBeenNthCalledWith(1, 'SELECT pg_advisory_lock($1, $2)', [+ ...POSTGRES_BOOT_MIGRATION_LOCK_KEYS,+ ]);+ expect(lockClient.query).toHaveBeenNthCalledWith(2, 'SELECT pg_advisory_unlock($1, $2)', [+ ...POSTGRES_BOOT_MIGRATION_LOCK_KEYS,+ ]);+ // Migration execution preserves the built-in migrationsRun transaction mode, and the boot+ // error path (destroy) never fires on success.+ expect(dataSource.runMigrations).toHaveBeenCalledWith({ transaction: 'all' });+ expect(dataSource.destroy).not.toHaveBeenCalled();+ });++ it('constructs the DataSource with migrationsRun disabled and never mutates the config', async () => {+ const { deps } = makeFakes();++ await createBootDataSource(PG_OPTIONS, deps);++ expect(deps.createDataSource).toHaveBeenCalledWith({ ...PG_OPTIONS, migrationsRun: false });+ // The resolved config object itself is untouched — the flag stays as the built-in fallback.+ expect(PG_OPTIONS.migrationsRun).toBe(true);+ });++ it('builds the lock client without a statement timeout (pg_advisory_lock must survive the wait)', async () => {+ const { deps } = makeFakes();++ await createBootDataSource(PG_OPTIONS, deps);++ // statement_timeout applies to any command — including the lock wait — and a config value of 0+ // is dropped by pg as falsy, so the only correct disable is the startup `options` string.+ expect(deps.createLockClient).toHaveBeenCalledWith(+ expect.objectContaining({+ host: 'db',+ port: 5432,+ user: 'openwa',+ password: 'secret',+ database: 'openwa',+ connectionTimeoutMillis: 10000,+ options: '-c statement_timeout=0',+ }),+ );+ });++ it('releases the lock and surfaces the error when a migration fails', async () => {+ const failure = new Error('duplicate table: messages');+ const { calls, lockClient, deps } = makeFakes(jest.fn(() => Promise.reject(failure)));++ await expect(createBootDataSource(PG_OPTIONS, deps)).rejects.toBe(failure);++ // Failure semantics: the lock still gets released, the client returned, and the DataSource is+ // torn down exactly like DataSource.initialize()'s own migrate-step error path — a retrying+ // boot must not stack initialized pools of failed attempts.+ expect(calls).toEqual([+ 'initialize',+ 'connect',+ 'SELECT pg_advisory_lock($1, $2)',+ 'runMigrations',+ 'SELECT pg_advisory_unlock($1, $2)',+ 'end',+ 'destroy',+ ]);+ expect(lockClient.end).toHaveBeenCalledTimes(1);+ });++ it('tears the DataSource down when the lock client cannot connect', async () => {+ const { dataSource, lockClient, deps } = makeFakes();+ (lockClient.connect as jest.Mock).mockRejectedValue(new Error('connect ECONNREFUSED'));++ await expect(createBootDataSource(PG_OPTIONS, deps)).rejects.toThrow('ECONNREFUSED');++ expect(lockClient.query).not.toHaveBeenCalled();+ expect(lockClient.end).toHaveBeenCalledTimes(1);+ expect(dataSource.destroy).toHaveBeenCalledTimes(1);+ });++ it('keeps the default @nestjs/typeorm path for non-postgres options (no lock, no initialize)', async () => {+ const sqliteOptions: DataSourceOptions = { type: 'better-sqlite3', database: './data/openwa.sqlite' };+ const dataSource = {+ initialize: jest.fn(() => Promise.resolve()),+ runMigrations: jest.fn(() => Promise.resolve()),+ destroy: jest.fn(() => Promise.resolve()),+ };+ const deps: BootDataSourceDeps = {+ createDataSource: jest.fn(() => dataSource as unknown as DataSource),+ createLockClient: jest.fn(),+ };++ const returned = await createBootDataSource(sqliteOptions, deps);++ // Untouched options, uninitialized DataSource (the wrapper's initialize keeps running the+ // connection's own migrationsRun), and no advisory-lock client is ever built.+ expect(returned).toBe(dataSource);+ expect(deps.createDataSource).toHaveBeenCalledWith(sqliteOptions);+ expect(deps.createLockClient).not.toHaveBeenCalled();+ expect(dataSource.initialize).not.toHaveBeenCalled();+ });+});diff --git a/src/database/pg-boot-migrations.ts b/src/database/pg-boot-migrations.tsnew file mode 100644index 000000000..e3057208b--- /dev/null+++ b/src/database/pg-boot-migrations.ts@@ -0,0 +1,106 @@+import { Client, ClientConfig } from 'pg';+import { DataSource, DataSourceOptions } from 'typeorm';++// The postgres data connection runs its boot migrations while holding a session-scoped Postgres+// advisory lock, so replicas that boot at the same time serialize instead of racing DDL against+// the shared migrations ledger: the lock holder applies the chain while every other process waits+// inside pg_advisory_lock, then sees a filled ledger and applies nothing. This replaces TypeORM's+// built-in migrationsRun for that connection only (it has no cross-process serialization); the+// sqlite connections keep @nestjs/typeorm's default construction + initialize path unchanged.+//+// Lock key in the two-int4 form — exact in JavaScript (a single bigint key would exceed+// Number.MAX_SAFE_INTEGER). The values are fixed so every process and version agrees:+// 0x4f5741 = "OWA" in ASCII bytes 0x626f6f74 = "boot" in ASCII bytes+export const POSTGRES_BOOT_MIGRATION_LOCK_KEYS: readonly [number, number] = [0x4f5741, 0x626f6f74];++// Just the pg client surface used here; doubles as the mock seam for the unit spec. Function+// properties (not method signatures) — these are callback holders, nothing binds `this`.+export interface AdvisoryLockClient {+ connect: () => Promise<unknown>;+ query: (text: string, values?: unknown[]) => Promise<unknown>;+ end: () => Promise<unknown>;+}++// Test seams over the two constructions this module performs.+export interface BootDataSourceDeps {+ createDataSource?: (options: DataSourceOptions) => DataSource;+ createLockClient?: (config: ClientConfig) => AdvisoryLockClient;+}++type PostgresOptions = Extract<DataSourceOptions, { type: 'postgres' }>;++/**+ * dataSourceFactory for the 'data' connection. Postgres boot migrations execute here, under the+ * advisory lock, BEFORE the DataSource is handed to any provider — same ordering the built-in+ * migrationsRun gave (it finished inside DataSource.initialize()). Non-postgres options take+ * @nestjs/typeorm's default path: construct only, let the wrapper initialize as before. The+ * wrapper also skips its own initialize() for the postgres branch because the DataSource comes+ * back already initialized, and keeps applying retryAttempts/retryDelay to this whole factory.+ */+export async function createBootDataSource(+ options: DataSourceOptions | undefined,+ deps: BootDataSourceDeps = {},+): Promise<DataSource> {+ const createDataSource = deps.createDataSource ?? (opts => new DataSource(opts));+ const createLockClient = deps.createLockClient ?? (config => new Client(config));++ if (options?.type !== 'postgres') {+ // useFactory always resolves a full options object; the optional parameter is the library's+ // defensive typing, not a state this connection can actually boot in.+ return createDataSource(options as DataSourceOptions);+ }++ // This connection's migrations run HERE, under the lock — neutralize migrationsRun so the+ // DataSource itself never starts them unsynchronized inside initialize().+ const dataSource = createDataSource({ ...options, migrationsRun: false });+ try {+ await dataSource.initialize();+ const lockClient = createLockClient(lockClientConfig(options));+ try {+ await lockClient.connect();+ await lockClient.query('SELECT pg_advisory_lock($1, $2)', [...POSTGRES_BOOT_MIGRATION_LOCK_KEYS]);+ try {+ // Same transaction mode DataSource.initialize() passes for the built-in migrationsRun.+ await dataSource.runMigrations({ transaction: options.migrationsTransactionMode });+ } finally {+ // Session-scoped lock: even when the unlock call itself fails, end() below tears the+ // session — and with it the lock — down, so no crashed boot can leave it held.+ await lockClient+ .query('SELECT pg_advisory_unlock($1, $2)', [...POSTGRES_BOOT_MIGRATION_LOCK_KEYS])+ .catch(() => undefined);+ }+ } finally {+ await lockClient.end().catch(() => undefined);+ }+ } catch (error) {+ // Same failure handling as DataSource.initialize()'s own migrate step: never leave a+ // half-open DataSource behind (the boot retry loop would stack their pools). The error still+ // fails boot via the factory's rejection.+ await dataSource.destroy().catch(() => undefined);+ throw error;+ }+ return dataSource;+}++function lockClientConfig(options: PostgresOptions): ClientConfig {+ const extra = (options.extra ?? {}) as { connectionTimeoutMillis?: number };+ return {+ host: options.host,+ port: options.port,+ user: options.username,+ password: options.password,+ database: options.database,+ // Same ssl shape TypeORM's postgres driver forwards to pg; cast only because the two+ // packages type their TLS options independently.+ ssl: options.ssl as ClientConfig['ssl'],+ // Bound a stuck connect like the pool does (app.module's extra carries the same setting).+ connectionTimeoutMillis: extra.connectionTimeoutMillis ?? 10000,+ // This client's only statements are pg_advisory_lock/unlock, and statement_timeout applies to+ // ANY command — including the wait inside pg_advisory_lock — so it must be OFF here. A config+ // `statement_timeout: 0` would NOT do it: pg drops falsy values from the startup packet, so+ // disable it via the startup `options` string instead, which also overrides any role- or+ // database-level default the server may carry. (lock_timeout never applies to advisory locks,+ // so it needs no override.)+ options: '-c statement_timeout=0',+ };+}