Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
perf: index webhooks.sessionId (dispatch lookup was a full table scan) (#647)
Yudhi Armyndharis9a0b7926d559
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9d2b4efba..55711e9b0 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+- **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).- **`POST /infra/import-data` no longer swallows a genuine database error while clearing tables.** The table-clearing step tolerated only a genuinely-absent table but previously used a blanket catch, so an I/O/lock error (or an aborted transaction) could let a restore commit a *merged* rather than *replaced* dataset on SQLite. Such errors now surface and roll the whole import back (a real fault returns a `500` carrying the actual cause); the intended tolerance for a missing table is preserved.diff --git a/src/database/add-webhooks-sessionid-index.spec.ts b/src/database/add-webhooks-sessionid-index.spec.tsnew file mode 100644index 000000000..c44071cc1--- /dev/null+++ b/src/database/add-webhooks-sessionid-index.spec.ts@@ -0,0 +1,50 @@+// NOTE: kept OUT of src/database/migrations/ on purpose — the TypeORM migrations glob+// (`migrations/*{.ts,.js}`) would otherwise load this spec as a migration under ts-node+// (the CLI datasource / start:dev) and crash on `describe`.+import { AddWebhooksSessionIdIndex1782200000000 } from './migrations/1782200000000-AddWebhooksSessionIdIndex';++function makeQueryRunner(type: string, hasWebhooks = true) {+ const query = jest.fn(() => Promise.resolve(undefined));+ return {+ connection: { options: { type } },+ hasTable: jest.fn((t: string) => Promise.resolve(t === 'webhooks' && hasWebhooks)),+ query,+ };+}++const sqlOf = (qr: ReturnType<typeof makeQueryRunner>): string[] =>+ qr.query.mock.calls.map(call => String((call as unknown[])[0]));++describe('AddWebhooksSessionIdIndex migration', () => {+ const migration = new AddWebhooksSessionIdIndex1782200000000();++ it('creates an IF-NOT-EXISTS index on webhooks.sessionId', async () => {+ const qr = makeQueryRunner('sqlite');+ await migration.up(qr as never);+ expect(sqlOf(qr).join('\n')).toMatch(+ /CREATE INDEX IF NOT EXISTS "IDX_webhooks_sessionId" ON "webhooks" \("sessionId"\)/,+ );+ });++ it('lifts the statement_timeout on Postgres only (never on SQLite)', async () => {+ const pg = makeQueryRunner('postgres');+ await migration.up(pg as never);+ expect(sqlOf(pg).some(s => /SET LOCAL statement_timeout = 0/.test(s))).toBe(true);++ const sqlite = makeQueryRunner('sqlite');+ await migration.up(sqlite as never);+ expect(sqlOf(sqlite).some(s => /SET LOCAL/.test(s))).toBe(false);+ });++ it('is a no-op when the webhooks table does not exist (fresh DB mid-bootstrap)', async () => {+ const qr = makeQueryRunner('sqlite', /* hasWebhooks */ false);+ await migration.up(qr as never);+ expect(sqlOf(qr).some(s => /CREATE INDEX/.test(s))).toBe(false);+ });++ it('drops the index on down()', async () => {+ const qr = makeQueryRunner('sqlite');+ await migration.down(qr as never);+ expect(sqlOf(qr).join('\n')).toMatch(/DROP INDEX IF EXISTS "IDX_webhooks_sessionId"/);+ });+});diff --git a/src/database/migrations/1782200000000-AddWebhooksSessionIdIndex.ts b/src/database/migrations/1782200000000-AddWebhooksSessionIdIndex.tsnew file mode 100644index 000000000..59af0c1a6--- /dev/null+++ b/src/database/migrations/1782200000000-AddWebhooksSessionIdIndex.ts@@ -0,0 +1,28 @@+import { MigrationInterface, QueryRunner } from 'typeorm';++/**+ * Index `webhooks.sessionId`. The webhook dispatch path looks up a session's active webhooks by+ * sessionId on EVERY emitted event (WebhookService.findBySession → `find({ where: { sessionId } })`),+ * so without this index each dispatch was a full scan of the webhooks table. The FK column carried no+ * index — the entity's `@ManyToOne`/`@JoinColumn` does not create one.+ *+ * Hand-authored because `synchronize` is off for the 'data' connection. Idempotent + cross-dialect.+ */+export class AddWebhooksSessionIdIndex1782200000000 implements MigrationInterface {+ name = 'AddWebhooksSessionIdIndex1782200000000';++ public async up(queryRunner: QueryRunner): Promise<void> {+ if (queryRunner.connection.options.type === 'postgres') {+ // Lift the runtime pool's statement_timeout (app.module.ts) for THIS transaction so a CREATE INDEX+ // over a large webhooks table at boot is never aborted. SET LOCAL auto-reverts at COMMIT; SQLite+ // rejects it syntactically, hence the guard.+ await queryRunner.query('SET LOCAL statement_timeout = 0');+ }+ if (!(await queryRunner.hasTable('webhooks'))) return;+ await queryRunner.query(`CREATE INDEX IF NOT EXISTS "IDX_webhooks_sessionId" ON "webhooks" ("sessionId")`);+ }++ public async down(queryRunner: QueryRunner): Promise<void> {+ await queryRunner.query(`DROP INDEX IF EXISTS "IDX_webhooks_sessionId"`);+ }+}diff --git a/src/modules/webhook/entities/webhook.entity.ts b/src/modules/webhook/entities/webhook.entity.tsindex 4207cf00a..aac0a9a02 100644--- a/src/modules/webhook/entities/webhook.entity.ts+++ b/src/modules/webhook/entities/webhook.entity.ts@@ -1,6 +1,7 @@import {Entity,Column,+ Index,PrimaryGeneratedColumn,CreateDateColumn,UpdateDateColumn,@@ -19,6 +20,9 @@ export class Webhook {// varchar (not uuid) to match the authoritative migration DDL and sessions.id; the data connection// runs synchronize:false, so a 'uuid' decorator here would only mislead schema diffs / a stray sync.+ // Indexed: the dispatch path filters webhooks by sessionId on every emitted event (see the+ // AddWebhooksSessionIdIndex migration, which creates the index on migration-managed DBs).+ @Index('IDX_webhooks_sessionId')@Column({ type: 'varchar' })sessionId: string;