Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(infra): spend the export media budget newest-first for bulk batches too
Yudhi Armyndharisc78dc3c9ea8f
diff --git a/.env.example b/.env.exampleindex 346efc8f4..ea70da14a 100644--- a/.env.example+++ b/.env.example@@ -377,9 +377,9 @@ WEBHOOK_SSRF_PROTECT=true# # payload is exported as the omitted marker and a bulk-batch# # entry simply loses its base64, because an# # unbounded export produces a backup the import refuses with 413-# # (it rides BODY_SIZE_LIMIT, 25mb by default). Spent on the-# # newest messages first, so a budget that cannot hold-# # everything keeps the most recent media. A URL-referenced+# # (it rides BODY_SIZE_LIMIT, 25mb by default). Spent newest-first+# # within each table, so a budget that cannot hold everything+# # keeps the most recent media. A URL-referenced# # payload is never counted or dropped — it is a pointer, not# # bytes, whatever the case of its scheme. 0 omits every payload.# STORE_EPHEMERAL_MESSAGES=true # Set to false to skip persisting and dispatching incomingdiff --git a/docs/06-api-specification.md b/docs/06-api-specification.mdindex 0a884ed0d..5e16ee0d6 100644--- a/docs/06-api-specification.md+++ b/docs/06-api-specification.md@@ -5000,7 +5000,7 @@ Export every row of the 14 migration tables from the Data DB as JSON. Read-only,**Auth:** API key (ADMIN)-> **Inline media is carried up to a budget, then omitted.** `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one export may hold, counted across both `messages` and `messageBatches`. It is spent on the newest messages first, so an export that cannot carry everything keeps the most recent media rather than whatever the database happened to return first. An over-budget payload on a `messages` row arrives as the omitted marker — `{ mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits when an inbound payload exceeds `MEDIA_DOWNLOAD_MAX_BYTES` — so those messages restore without their pictures. A `messageBatches` entry carries no marker: it simply loses its `base64` and keeps `url`, `mimetype` and `caption`, which is the shape a batch already has once it reaches a terminal state. Without the bound, one 50 MiB attachment becomes 66 MiB of base64 and exceeds the import's own request-body limit (`BODY_SIZE_LIMIT`, 25mb by default), producing a backup this gateway refuses to restore with `413`.+> **Inline media is carried up to a budget, then omitted.** `EXPORT_INLINE_MEDIA_BUDGET_BYTES` (8 MiB of encoded base64 by default) bounds how much inline media one export may hold, counted across both `messages` and `messageBatches`. Within each of those tables it is spent newest-first — messages by `timestamp`, batches by `created_at` — so an export that cannot carry everything keeps the most recent media rather than whatever the database happened to return first. Messages are served before batches, so a long history can exhaust the budget before any batch is reached. An over-budget payload on a `messages` row arrives as the omitted marker — `{ mimetype, filename?, omitted: true, sizeBytes }`, the same shape the engine emits when an inbound payload exceeds `MEDIA_DOWNLOAD_MAX_BYTES` — so those messages restore without their pictures. A `messageBatches` entry carries no marker: it simply loses its `base64` and keeps `url`, `mimetype` and `caption`, which is the shape a batch already has once it reaches a terminal state. Without the bound, one 50 MiB attachment becomes 66 MiB of base64 and exceeds the import's own request-body limit (`BODY_SIZE_LIMIT`, 25mb by default), producing a backup this gateway refuses to restore with `413`.>> A **URL-referenced** payload is never counted or dropped: `metadata.media.data` holds either base64 or the URL a send was given, and a URL is a pointer worth a few dozen bytes. The scheme is matched case-insensitively, as both engine adapters do when they fetch it.>diff --git a/src/modules/infra/infra-data.controller.spec.ts b/src/modules/infra/infra-data.controller.spec.tsindex 8cf5f6a6b..5076452fe 100644--- a/src/modules/infra/infra-data.controller.spec.ts+++ b/src/modules/infra/infra-data.controller.spec.ts@@ -786,6 +786,53 @@ describe('InfraDataController.importData round-trips export-data (no silent mess});});+ it('spends the export budget on the newest bulk batch first', async () => {+ // Same defect the `messages` pass was fixed for: `SELECT *` has no ORDER BY, so on SQLite the+ // batches arrive oldest-first and an exhausted budget keeps the stalest run's payloads.+ const olderPayload = Buffer.from('o'.repeat(600)).toString('base64');+ const newerPayload = Buffer.from('n'.repeat(600)).toString('base64');+ await seedSession('s1');+ const seedBatch = async (id: string, createdAt: string, base64: string): Promise<void> => {+ await ds.getRepository(MessageBatch).save(+ ds.getRepository(MessageBatch).create({+ id,+ batchId: `BATCH-${id}`,+ sessionId: 's1',+ status: BatchStatus.PROCESSING,+ messages: [{ chatId: 'c1', type: 'image', content: { image: { base64, mimetype: 'image/png' } } }] as never,+ options: null as never,+ progress: null as never,+ results: null as never,+ currentIndex: 0,+ startedAt: null,+ completedAt: null,+ }),+ );+ // `created_at` is a @CreateDateColumn, so it cannot be seeded through the entity.+ await ds.query(`UPDATE message_batches SET created_at = ? WHERE id = ?`, [createdAt, id]);+ };+ // Inserted oldest-first, which is also how SQLite hands them back.+ await seedBatch('b-older', '2026-01-01T00:00:00.000Z', olderPayload);+ await seedBatch('b-newer', '2026-06-01T00:00:00.000Z', newerPayload);++ const batchImage = (+ dump: Awaited<ReturnType<typeof controller.exportData>>,+ id: string,+ ): Record<string, unknown> => {+ const row = dump.tables.messageBatches.find(r => r.id === id);+ const msgs = (typeof row?.messages === 'string' ? JSON.parse(row.messages) : row?.messages) as Array<{+ content: { image: Record<string, unknown> };+ }>;+ return msgs[0].content.image;+ };++ await withBudget(Buffer.byteLength(newerPayload, 'utf8'), async () => {+ const dump = await controller.exportData();+ expect(batchImage(dump, 'b-newer')).toEqual({ base64: newerPayload, mimetype: 'image/png' });+ expect(batchImage(dump, 'b-older')).not.toHaveProperty('base64');+ });+ });+it('round-trips plugin instances + integration delivery failures (Integration Fabric + DLQ)', async () => {await seedSession('s1');await ds.getRepository(PluginInstance).save(diff --git a/src/modules/infra/infra-data.controller.ts b/src/modules/infra/infra-data.controller.tsindex 3136bb87e..0891804c9 100644--- a/src/modules/infra/infra-data.controller.ts+++ b/src/modules/infra/infra-data.controller.ts@@ -168,12 +168,19 @@ function isMediaPointer(data: string): boolean {}/**- * Sort key for the media budget: newest first, so a budget that cannot hold everything keeps the- * most recent media. `Number(null)` is 0, which sorts an undated row last — the least worth keeping.+ * Order rows so the media budget is spent newest-first, keeping the most recent media when it cannot+ * hold everything. `SELECT *` carries no ORDER BY: rows arrive in rowid order on SQLite — oldest+ * first, the exact inverse of what a backup wants — and in physical-tuple order on Postgres, which+ * routine UPDATEs reshuffle, so two exports of an unchanged DB need not agree. Sorts a COPY, leaving+ * the exported array's own order untouched. A row with no usable timestamp sorts last, as the least+ * worth spending the budget on.*/-function newestFirstKey(row: MessageRow): number {- const timestamp = Number(row.timestamp);- return Number.isFinite(timestamp) ? timestamp : 0;+function newestFirst<T>(rows: readonly T[], at: (row: T) => number): T[] {+ const key = (row: T): number => {+ const value = at(row);+ return Number.isFinite(value) ? value : 0;+ };+ return [...rows].sort((a, b) => key(b) - key(a));}/** Spends the shared budget. Returns true when this payload does not fit and must be dropped. */@@ -364,16 +371,13 @@ export class InfraDataController {for (const row of messages) {delete row.body_ts;}- // Spend the budget newest-first. `SELECT *` carries no ORDER BY, so rows arrive in rowid order on- // SQLite — oldest first, so an exhausted budget would keep the oldest photos and omit every recent- // one — and in physical-tuple order on Postgres, which routine UPDATEs (ack, edits, reactions,- // archive pointers) reshuffle, so two exports of an unchanged DB need not agree on which media- // they carry. Sorting a COPY leaves the exported array's own order untouched.- for (const row of [...messages].sort((a, b) => newestFirstKey(b) - newestFirstKey(a))) {+ for (const row of newestFirst(messages, row => Number(row.timestamp))) {stripInlineMediaPayload(row, exceedsBudget);}const messageBatches = await queryOptionalTable<MessageBatchRow>('message_batches');- for (const row of messageBatches) {+ // Batches spend what the messages left, and by the same newest-first rule: a run left PROCESSING+ // keeps its payloads indefinitely, so a stale one must not outbid a current one.+ for (const row of newestFirst(messageBatches, row => Date.parse(row.created_at))) {stripBatchInlineMedia(row, exceedsBudget);}const templates = await queryOptionalTable<TemplateRow>('templates');