Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(chat-media): keep the archive sweeps running while archiving is off
Yudhi Armyndharis1d9fdeea86e8
diff --git a/.env.example b/.env.exampleindex e291d9b7e..74c8a7ab3 100644--- a/.env.example+++ b/.env.example@@ -459,9 +459,9 @@ WEBHOOK_SSRF_PROTECT=true# require archiving. The inline copy is KEPT, so archiving roughly doubles storage for media under# the cap — hence off by default.# CHAT_MEDIA_ARCHIVE_ENABLED=false # default false-# Extend archiving to media this account SENT (needs CHAT_MEDIA_ARCHIVE_ENABLED=true; the retention-# purge and orphan sweep only run while that is on). Doubles storage again for the outbound half,-# and buys nothing for a URL-based send, whose row stores the URL rather than any bytes.+# Extend archiving to media this account SENT (needs CHAT_MEDIA_ARCHIVE_ENABLED=true). Doubles+# storage again for the outbound half, and buys nothing for a URL-based send, whose row stores the+# URL rather than any bytes.# CHAT_MEDIA_ARCHIVE_OUTBOUND=false # default false# Per-file cap on archived chat media. Media above it is simply not archived; the message row and# its inline copy are unaffected. A non-positive/garbage value falls back.diff --git a/CHANGELOG.md b/CHANGELOG.mdindex dd240fb60..240d819c6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -20,6 +20,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0- A webhook's `lastTriggeredAt` is published as a nullable date-time string instead of an object, so a client generated from the contract no longer rejects both of the values the field actually carries. The response itself is unchanged.- The group-list and status routes no longer appear twice in the OpenAPI contract under different path-parameter names, so a client generated from it gets one method per endpoint; the parameters are now `sessionId` and `id`. The URLs themselves are unchanged.- A bare `@SkipThrottle()` no longer leaves a route throttled: it writes one metadata key the guard never read, so `/api/metrics` and the `/api/health*` probes were rate-limited despite being documented as exempt, and a 429 on readiness reads as unhealthy to every configured probe. Those four routes are also `@Public()`, so the global IP limit was the only one reaching them and they now carry none — rate-limit them at your proxy if they are internet-facing.+- The chat-media retention purge and orphan sweep now run while `CHAT_MEDIA_ARCHIVE_ENABLED` is off; previously turning archiving off stopped both, leaving files past their TTL and crash-leftover orphans in the store indefinitely. Note the consequence for a deployment that has archiving off: the orphan sweep now deletes any file under the `chat-media/` prefix that no message row references, once it has been unreferenced for the grace window (`CHAT_MEDIA_ORPHAN_GRACE_MS`, default 1h). A file a surviving row points at is never touched.### Securitydiff --git a/src/config/configuration.ts b/src/config/configuration.tsindex 556d68695..c0b7ba4a6 100644--- a/src/config/configuration.ts+++ b/src/config/configuration.ts@@ -374,10 +374,10 @@ export default () => ({chatMedia: {// Off by default: archiving doubles storage for media under the cap, since the inline copy stays.archiveEnabled: process.env.CHAT_MEDIA_ARCHIVE_ENABLED === 'true',- // Extend archiving to media this account SENT. A sub-flag rather than a mode of its own, so the- // retention purge and orphan sweep — which only run while archiving is enabled — are guaranteed- // to be maintaining whatever it writes. Off by default because it doubles storage again for the- // outbound half, and because a URL-based send stores no bytes to archive in the first place.+ // Extend archiving to media this account SENT. A sub-flag rather than a mode of its own, so what+ // it writes lands under the same prefix and is maintained by the same retention purge and orphan+ // sweep. Off by default because it doubles storage again for the outbound half, and because a+ // URL-based send stores no bytes to archive in the first place.archiveOutbound: process.env.CHAT_MEDIA_ARCHIVE_OUTBOUND === 'true',// Per-file cap on archived chat media (default 25 MiB). Media above it is simply not archived —// the message row and its inline copy are unaffected.diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.tsindex 290581d72..0d08fca52 100644--- a/src/modules/chat-media/chat-media-archive.service.spec.ts+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts@@ -400,19 +400,46 @@ describe('ChatMediaArchiveService', () => {});describe('sweep scheduling', () => {- it('schedules no timers while archiving is off', () => {+ const backdate = (id: string, daysAgo: number): Promise<unknown> =>+ repository.query('UPDATE messages SET createdAt = ? WHERE id = ?', [+ new Date(Date.now() - daysAgo * 24 * 60 * 60 * 1000).toISOString(),+ id,+ ]);++ it('schedules both sweeps even while archiving is off', () => {const setInterval = jest.spyOn(global, 'setInterval');const svc = build();svc.onModuleInit();- // With the archive off no row can hold a mediaPath, so both sweeps would be recurring- // no-op walks of a store they must never touch.- expect(setInterval).not.toHaveBeenCalled();+ // The flag gates the WRITER, not the store. Turning it off on a deployment that has been+ // archiving leaves every file and every pointer in place, so the maintenance the sweeps+ // perform — TTL expiry and orphan reclamation — is exactly what still has work to do.+ expect(setInterval).toHaveBeenCalledTimes(2);svc.onModuleDestroy();setInterval.mockRestore();});+ it('still expires an archived file past its TTL while archiving is off', async () => {+ const row = await saveRow({ mimetype: 'image/png', data: PNG.toString('base64') });+ const key = await enabled().archive(row);+ await backdate(row.id, 10);++ expect(await build({ 'chatMedia.ttlDays': 7 }).purgeExpired(Date.now())).toBe(1);++ await expect(storageService.getFile(key!)).rejects.toThrow();+ expect((await repository.findOneByOrFail({ id: row.id })).mediaPath).toBeNull();+ });++ it('still reaps an unreferenced archive file while archiving is off', async () => {+ await storageService.putFile(`${CHAT_MEDIA_PREFIX}sess-1/orphan.png`, PNG);+ const svc = build({ 'chatMedia.orphanGraceMs': 0 });++ expect(await svc.sweepOrphanedMedia(Date.now())).toBe(1);++ await expect(storageService.getFile(`${CHAT_MEDIA_PREFIX}sess-1/orphan.png`)).rejects.toThrow();+ });+it('schedules both sweeps once archiving is on, and clears them on destroy', () => {const setInterval = jest.spyOn(global, 'setInterval');const clearInterval = jest.spyOn(global, 'clearInterval');diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.tsindex 340b7873a..db65dfc35 100644--- a/src/modules/chat-media/chat-media-archive.service.ts+++ b/src/modules/chat-media/chat-media-archive.service.ts@@ -56,10 +56,12 @@ interface InlineMedia {* cap: the inline copy is deliberately left in place, since the dashboard renders from it and* stripping it would break the response contract.*- * Two recurring sweeps run only while archiving is enabled: a retention purge (when- * `CHAT_MEDIA_ARCHIVE_TTL_DAYS` is non-zero) that clears files past their TTL along with the- * columns pointing at them, and an hourly reconciliation sweep that reaps files no row references —- * the crash leftovers of the narrow window between a file write and its row update.+ * Two recurring sweeps run regardless of that flag, which gates the writer rather than the store: a+ * retention purge (when `CHAT_MEDIA_ARCHIVE_TTL_DAYS` is non-zero) that clears files past their TTL+ * along with the columns pointing at them, and an hourly reconciliation sweep that reaps files no+ * row references — the crash leftovers of the narrow window between a file write and its row+ * update. Files and pointers written while the flag was on outlive it being turned off, so the+ * maintenance they need does not stop with the writer.*/@Injectable()export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {@@ -81,10 +83,6 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {}onModuleInit(): void {- // Both sweeps exist only to maintain archived files. With archiving off no row can hold a- // mediaPath, so scheduling them would be a recurring no-op walk of the store.- if (!this.enabled) return;-const runPurge = (): void => {this.purgeExpired(Date.now()).catch(err =>this.logger.error('Chat media purge failed', err instanceof Error ? err.stack : String(err)),diff --git a/src/modules/message/entities/message.entity.ts b/src/modules/message/entities/message.entity.tsindex 492bdced6..a2bee17b4 100644--- a/src/modules/message/entities/message.entity.ts+++ b/src/modules/message/entities/message.entity.ts@@ -90,7 +90,7 @@ export class Message {/*** Storage key of this message's archived media, or null when nothing was archived — which is the- * case for every row while `CHAT_MEDIA_ARCHIVE_ENABLED` is off (the default), for non-media+ * case for every row written while `CHAT_MEDIA_ARCHIVE_ENABLED` is off (the default), for non-media* messages, and for media above the archive cap. Independent of the inline base64 copy in* `metadata.media`, which is unaffected by archiving.*/