Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(db): Postgres uuid DEFAULT for integration tables + Postgres migration CI (#648)
Yudhi Armyndharisd72d10b2f87a
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 65c635159..b2b1bc387 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -66,6 +66,50 @@ jobs:files: ./coverage/lcov.infofail_ci_if_error: false+ test-postgres:+ name: Test (PostgreSQL migrations)+ runs-on: ubuntu-latest+ services:+ postgres:+ image: postgres:16-alpine+ env:+ POSTGRES_USER: openwa+ POSTGRES_PASSWORD: openwa+ POSTGRES_DB: openwa+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U openwa"+ --health-interval 10s+ --health-timeout 5s+ --health-retries 5+ steps:+ - uses: actions/checkout@v7++ - name: Setup Node.js+ uses: actions/setup-node@v6+ with:+ node-version: ${{ env.NODE_VERSION }}+ cache: 'npm'++ - name: Install dependencies+ run: npm ci++ - name: Build (compiles the data migrations to dist/)+ run: npm run build++ # Applies the full data-migration chain to a real Postgres and asserts every generated-uuid PK+ # has a DB DEFAULT — the dialect gap SQLite-only tests can't see.+ - name: Migrate + uuid-default smoke against PostgreSQL+ run: npm run test:pg-smoke+ env:+ DATABASE_TYPE: postgres+ DATABASE_HOST: localhost+ DATABASE_PORT: '5432'+ DATABASE_USERNAME: openwa+ DATABASE_PASSWORD: openwa+ DATABASE_NAME: openwa+dashboard:name: Dashboardruns-on: ubuntu-latestdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 55711e9b0..a41004241 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,6 +19,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Fixed+- **The Integration Fabric now works on PostgreSQL.** `conversation_mappings` and `integration_delivery_failures` declared `@PrimaryGeneratedColumn('uuid')` ids but their columns were created without a Postgres `DEFAULT gen_random_uuid()`, so on PostgreSQL every first insert failed with a `NOT NULL` violation on `id` — breaking the plugin conversation-mapping upsert (e.g. the Chatwoot handover) and the ingress dead-letter write. SQLite was unaffected because its driver mints the uuid client-side, which is why it went unnoticed. A forward-only migration adds the default (no-op on SQLite). A new CI job now applies the full migration chain against a real PostgreSQL and asserts every generated-uuid primary key has a database default, so this dialect gap can't recur.- **Indexed `webhooks.sessionId`.** The webhook dispatch path looks up a session's active webhooks by `sessionId` on every emitted event, so on a busy session this was a full table scan of the `webhooks` table per event (the foreign-key column carried no index). A cross-dialect index migration — plus the matching entity index — makes the lookup index-backed.- **Boot now rejects a non-canonical boolean feature flag instead of silently disabling the feature.** `QUEUE_ENABLED`, `MCP_ENABLED`, and `SERVE_DASHBOARD` are read with an exact `=== 'true'` / `!== 'false'` comparison, so a typo (`True`, `1`, `yes`) or a stray trailing space/CR (a Windows-edited env file forwarded verbatim by `docker run --env-file`) silently (dis)abled the feature with zero diagnostics. These are now validated at startup and boot fails fast naming the offending key. ⚠️ **Behavior change:** a deployment currently booting with such a value (e.g. `QUEUE_ENABLED=1`) will now refuse to start until corrected to `true`/`false`/unset — including `SERVE_DASHBOARD=0`/`no`, which was silently serving the dashboard and will now correctly disable it once set to `false`.- **A fatal uncaught exception is now written to the structured log** (with its stack and origin) before the process exits, instead of only a raw stack on stderr that the log pipeline missed. This is observe-only: the crash-and-restart posture is unchanged (the container restart policy still fires and the process never continues on corrupted post-exception state).diff --git a/package.json b/package.jsonindex d380a8a37..4356e76d8 100644--- a/package.json+++ b/package.json@@ -34,6 +34,7 @@"test:cov": "jest --coverage","test:debug": "node --inspect-brk -r tsconfig-paths/register -r ts-node/register node_modules/.bin/jest --runInBand","test:e2e": "jest --config ./test/jest-e2e.json",+ "test:pg-smoke": "node scripts/pg-uuid-smoke.js","typeorm": "typeorm-ts-node-commonjs","typeorm:prod": "typeorm","migration:create": "npm run typeorm -- migration:create src/database/migrations/$npm_config_name",diff --git a/scripts/pg-uuid-smoke.js b/scripts/pg-uuid-smoke.jsnew file mode 100644index 000000000..a05b92889--- /dev/null+++ b/scripts/pg-uuid-smoke.js@@ -0,0 +1,67 @@+/* eslint-disable */+// PostgreSQL migration + uuid-default smoke. CI runs this against a throwaway postgres:16 service:+// it applies the FULL data-migration chain from scratch (previously never exercised on Postgres in CI)+// and asserts every generated-uuid primary key has a DB-side DEFAULT. Without one, a+// `@PrimaryGeneratedColumn('uuid')` insert fails on Postgres with a NOT NULL violation (23502) — the+// exact failure SQLite hides, because its driver mints the uuid client-side.+//+// Runs against the compiled migrations in dist/ (so it matches `migration:run:prod`); `npm run build`+// first. Configured from DATABASE_* env vars.+require('reflect-metadata');+const path = require('path');+const { DataSource } = require('typeorm');++// @PrimaryColumn tables: their `id` is supplied by the application, so it legitimately has NO DB default.+// Everything else with an `id` column is expected to be a generated-uuid PK that MUST carry a default.+const APP_GENERATED_ID_TABLES = ['ingress_events', 'plugin_instances'];++async function main() {+ const ds = new DataSource({+ type: 'postgres',+ 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',+ migrations: [path.join(__dirname, '..', 'dist', 'database', 'migrations', '*.js')],+ });++ await ds.initialize();+ const ran = await ds.runMigrations();+ console.log(`Applied ${ran.length} data migrations to PostgreSQL from scratch.`);++ // Auto-coverage: any `id` column with no DEFAULT that isn't an app-generated PK is a uuid-PK table+ // missing gen_random_uuid(). This catches current AND future tables without a maintained list.+ const noDefaultRows = await ds.query(+ `SELECT table_name FROM information_schema.columns+ WHERE table_schema = 'public' AND column_name = 'id' AND column_default IS NULL`,+ );+ const offenders = noDefaultRows+ .map((r) => r.table_name)+ .filter((t) => t !== 'migrations' && !APP_GENERATED_ID_TABLES.includes(t));++ // Belt-and-suspenders: positively assert the two tables this migration set fixes carry a default.+ for (const t of ['conversation_mappings', 'integration_delivery_failures']) {+ const rows = await ds.query(+ `SELECT column_default FROM information_schema.columns WHERE table_name = $1 AND column_name = 'id'`,+ [t],+ );+ if (!rows.length || rows[0].column_default == null) offenders.push(`${t} (expected a default, found none)`);+ }++ await ds.destroy();++ const unique = [...new Set(offenders)];+ if (unique.length) {+ console.error('\n❌ Generated-uuid PK column(s) missing a Postgres DEFAULT — inserts will fail (23502):');+ for (const t of unique) console.error(' - ' + t);+ console.error('\nFix: add `ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar` in a Postgres-only migration.');+ process.exit(1);+ }+ console.log('✅ Migration chain applied cleanly and every generated-uuid PK has a Postgres DEFAULT.');+}++main().catch((err) => {+ console.error(err);+ process.exit(1);+});diff --git a/src/database/add-integration-uuid-defaults.spec.ts b/src/database/add-integration-uuid-defaults.spec.tsnew file mode 100644index 000000000..b45c8cea0--- /dev/null+++ b/src/database/add-integration-uuid-defaults.spec.ts@@ -0,0 +1,68 @@+// NOTE: kept OUT of src/database/migrations/ on purpose — the TypeORM migrations glob+// (`migrations/*{.ts,.js}`) would otherwise load this spec as a migration and crash on `describe`.+import { AddIntegrationUuidDefaults1782300000000 } from './migrations/1782300000000-AddIntegrationUuidDefaults';++const TABLES = ['conversation_mappings', 'integration_delivery_failures'];++function makeQueryRunner(type: string, existingTables: Set<string>, versionNum = 150000, extInstalled = false) {+ const query = jest.fn((sql: string) => {+ const s = String(sql);+ if (/server_version_num/i.test(s)) return Promise.resolve([{ num: versionNum }]);+ if (/pg_extension/i.test(s)) return Promise.resolve(extInstalled ? [{ ok: 1 }] : []);+ return Promise.resolve(undefined);+ });+ return {+ connection: { options: { type } },+ hasTable: jest.fn((t: string) => Promise.resolve(existingTables.has(t))),+ query,+ };+}++const sqlOf = (qr: ReturnType<typeof makeQueryRunner>): string[] =>+ qr.query.mock.calls.map(call => String((call as unknown[])[0]));++describe('AddIntegrationUuidDefaults migration', () => {+ const migration = new AddIntegrationUuidDefaults1782300000000();++ it('is a no-op on SQLite — issues no query and never probes tables', async () => {+ const qr = makeQueryRunner('sqlite', new Set(TABLES));+ await migration.up(qr as never);+ expect(qr.query).not.toHaveBeenCalled();+ expect(qr.hasTable).not.toHaveBeenCalled();+ });++ it('sets gen_random_uuid() DEFAULT on both integration tables on PG 13+ (no pgcrypto touched)', async () => {+ const qr = makeQueryRunner('postgres', new Set(TABLES), 150000);+ await migration.up(qr as never);+ const sql = sqlOf(qr).join('\n');+ for (const t of TABLES) {+ expect(sql).toContain(`ALTER TABLE "${t}" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar`);+ }+ expect(sql).not.toMatch(/CREATE EXTENSION/i); // core built-in on 13++ });++ it('ensures pgcrypto on PG <= 12 before setting the defaults', async () => {+ const qr = makeQueryRunner('postgres', new Set(TABLES), 120000, /* extInstalled */ false);+ await migration.up(qr as never);+ expect(sqlOf(qr).some(s => /CREATE EXTENSION IF NOT EXISTS pgcrypto/i.test(s))).toBe(true);+ });++ it('skips a table that does not exist (partial schema)', async () => {+ const qr = makeQueryRunner('postgres', new Set(['conversation_mappings']), 150000);+ await migration.up(qr as never);+ const sql = sqlOf(qr).join('\n');+ expect(sql).toContain('ALTER TABLE "conversation_mappings"');+ expect(sql).not.toContain('ALTER TABLE "integration_delivery_failures"');+ });++ it('drops the defaults on down() (Postgres only)', async () => {+ const pg = makeQueryRunner('postgres', new Set(TABLES));+ await migration.down(pg as never);+ for (const t of TABLES) {+ expect(sqlOf(pg).join('\n')).toContain(`ALTER TABLE "${t}" ALTER COLUMN "id" DROP DEFAULT`);+ }+ const sqlite = makeQueryRunner('sqlite', new Set(TABLES));+ await migration.down(sqlite as never);+ expect(sqlite.query).not.toHaveBeenCalled();+ });+});diff --git a/src/database/migrations/1782300000000-AddIntegrationUuidDefaults.ts b/src/database/migrations/1782300000000-AddIntegrationUuidDefaults.tsnew file mode 100644index 000000000..efc8d1155--- /dev/null+++ b/src/database/migrations/1782300000000-AddIntegrationUuidDefaults.ts@@ -0,0 +1,67 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Adds the `gen_random_uuid()::varchar` DEFAULT to the two Integration Fabric tables whose `id` columns+ * were created without one.+ *+ * Why this is needed:+ * `conversation_mappings` and `integration_delivery_failures` both use `@PrimaryGeneratedColumn('uuid')`,+ * but `AddIntegrationFabric` (1781900000000) created their `id` columns as bare `varchar PRIMARY KEY+ * NOT NULL` with no DEFAULT — and, being added after `AddUuidDefaultsForPostgres` (1779235200000),+ * they were never in that migration's 4-table list. On Postgres the TypeORM driver emits+ * `INSERT ... VALUES (DEFAULT, ...)` for a uuid-strategy PK and relies on a DB-side default, so every+ * first insert failed with `null value in column "id" ... violates not-null constraint` (23502) —+ * breaking the Chatwoot handover upsert and the ingress dead-letter write on Postgres only. SQLite is+ * unaffected (its driver mints the uuid), which is why it went unnoticed.+ *+ * A NEW forward-only migration is the correct fix (the earlier defaults migration has already run on+ * live DBs). It mirrors that migration's version-gate: `gen_random_uuid()` is a core built-in on+ * PostgreSQL 13+, and lives in pgcrypto on PG <= 12. No-op on SQLite.+ */+export class AddIntegrationUuidDefaults1782300000000 implements MigrationInterface {+ name = 'AddIntegrationUuidDefaults1782300000000';++ private readonly tables = ['conversation_mappings', 'integration_delivery_failures'];++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (queryRunner.connection.options.type !== 'postgres') return;++ // Probe the server version with a non-erroring catalog query (a caught SQL exception would poison the+ // migration transaction). Only touch pgcrypto on PG <= 12; on 13+ gen_random_uuid() is core and+ // CREATE EXTENSION — a privilege managed Postgres often withholds — is avoided entirely.+ const versionRows = (await queryRunner.query(`SELECT current_setting('server_version_num')::int AS num`)) as+ { num: number | string }[] | undefined;+ const versionNum = Number(versionRows?.[0]?.num ?? 0);++ if (versionNum > 0 && versionNum < 130000) {+ const installed = (await queryRunner.query(`SELECT 1 FROM pg_extension WHERE extname = 'pgcrypto'`)) as+ unknown[] | undefined;+ if (!installed?.length) {+ try {+ await queryRunner.query(`CREATE EXTENSION IF NOT EXISTS pgcrypto`);+ } catch (err) {+ throw new Error(+ `PostgreSQL ${versionNum} (< 13) needs the pgcrypto extension for gen_random_uuid(), but it is ` ++ `not installed and this database role cannot create it. Have a superuser run ` ++ `"CREATE EXTENSION pgcrypto;" once, then restart.`,+ { cause: err },+ );+ }+ }+ }++ for (const table of this.tables) {+ if (!(await queryRunner.hasTable(table))) continue;+ await queryRunner.query(`ALTER TABLE "${table}" ALTER COLUMN "id" SET DEFAULT gen_random_uuid()::varchar`);+ }+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ if (queryRunner.connection.options.type !== 'postgres') return;++ for (const table of this.tables) {+ if (!(await queryRunner.hasTable(table))) continue;+ await queryRunner.query(`ALTER TABLE "${table}" ALTER COLUMN "id" DROP DEFAULT`);+ }+ }+}