Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

refactor(storage): share the orphaned-media reconciliation sweep

Yudhi Armyndharis0691fd5c18b9
diff --git a/src/common/storage/orphan-sweep.ts b/src/common/storage/orphan-sweep.ts
new file mode 100644
index 000000000..60158d609
--- /dev/null
+++ b/src/common/storage/orphan-sweep.ts
@@ -0,0 +1,89 @@
+import { StorageService } from './storage.service';
+
+/**
+ * One reconciliation pass over a storage prefix: delete files no row references, but only after the
+ * sweep has seen them unreferenced for at least the grace window. Shared by the stores that keep
+ * media blobs alongside DB rows (status store, chat-media archive) and share one bucket — each
+ * caller scopes itself to its own prefix and never touches the other's files.
+ *
+ * First-seen is tracked in the caller-owned `firstSeenAt` map (epoch ms per unreferenced key), so a
+ * restart simply restarts the grace clock (fails safe) and a file mid-write is never reaped. The map
+ * is pruned to the keys still orphaned at the end of the pass, so it cannot grow unbounded.
+ *
+ * Files are enumerated with iterateFiles(), NOT listFiles(): listFiles() truncates at
+ * STORAGE_LIST_MAX_FILES (a per-call DoS guard, not a completeness contract), which would strand
+ * every orphan past the cap.
+ *
+ * Returns the number of files deleted. The summary log stays with the caller (each sweep reports in
+ * its own wording); a failed delete is reported through `onDeleteFailed` and retried on a later pass.
+ */
+export async function sweepOrphanedFiles(options: {
+ storage: Pick<StorageService, 'iterateFiles' | 'deleteFile'>;
+ /** Storage key prefix this sweep owns; files not under it are never touched. */
+ prefix: string;
+ /** Grace window (ms) before an unreferenced file is deleted. */
+ graceMs: number;
+ /** Timestamp the pass runs at (epoch ms). */
+ now: number;
+ /** Caller-owned first-sighting map (epoch ms per unreferenced key); mutated in place. */
+ firstSeenAt: Map<string, number>;
+ /**
+ * Resolve which of the given keys are still referenced by a row. May return a superset (e.g. one
+ * whole-set query when the referenced set is small and bounded) — only membership is read.
+ */
+ referencedAmong: (keys: string[]) => Promise<ReadonlySet<string | undefined>>;
+ /**
+ * Bound on the keys per referencedAmong call. Set it when the referenced set can grow without
+ * bound: reconciling in chunks keeps each lookup an indexed query over a bounded key list instead
+ * of materialising every key and every referenced row at once. Unset = one call with the whole
+ * enumeration.
+ */
+ chunkSize?: number;
+ /** Caller-worded warning for a delete that failed; the file stays for the next pass. */
+ onDeleteFailed: (key: string, error: unknown) => void;
+}): Promise<number> {
+ const { storage, prefix, graceMs, now, firstSeenAt, referencedAmong, onDeleteFailed } = options;
+ let removed = 0;
+ // Keys still unreferenced at the end of THIS pass; drives the bookkeeping prune below. Bounded by
+ // the orphan count (normally ~0), not by the size of the store.
+ const stillOrphaned = new Set<string>();
+
+ let chunk: string[] = [];
+ const flush = async (): Promise<void> => {
+ if (chunk.length === 0) return;
+ const referenced = await referencedAmong(chunk);
+ for (const file of chunk) {
+ if (referenced.has(file)) {
+ firstSeenAt.delete(file);
+ continue;
+ }
+ stillOrphaned.add(file);
+ const firstSeen = firstSeenAt.get(file) ?? now;
+ firstSeenAt.set(file, firstSeen);
+ if (now - firstSeen < graceMs) continue;
+ try {
+ await storage.deleteFile(file);
+ firstSeenAt.delete(file);
+ stillOrphaned.delete(file);
+ removed += 1;
+ } catch (err) {
+ onDeleteFailed(file, err);
+ }
+ }
+ chunk = [];
+ };
+
+ for await (const file of storage.iterateFiles(prefix)) {
+ if (!file.startsWith(prefix)) continue;
+ chunk.push(file);
+ if (options.chunkSize !== undefined && chunk.length >= options.chunkSize) await flush();
+ }
+ await flush();
+
+ // Drop bookkeeping for anything not still orphaned this pass — the file is gone, or a row now
+ // references it. Keyed off the orphan set rather than a full listing so this stays bounded too.
+ for (const key of [...firstSeenAt.keys()]) {
+ if (!stillOrphaned.has(key)) firstSeenAt.delete(key);
+ }
+ return removed;
+}
diff --git a/src/modules/chat-media/chat-media-archive.service.ts b/src/modules/chat-media/chat-media-archive.service.ts
index db65dfc35..d670f8c30 100644
--- a/src/modules/chat-media/chat-media-archive.service.ts
+++ b/src/modules/chat-media/chat-media-archive.service.ts
@@ -5,6 +5,7 @@ import { In, IsNull, LessThan, Not, Repository } from 'typeorm';
import { randomUUID } from 'crypto';
import { Message } from '../message/entities/message.entity';
import { StorageService } from '../../common/storage/storage.service';
+import { sweepOrphanedFiles } from '../../common/storage/orphan-sweep';
import { createLogger } from '../../common/services/logger.service';
/** Storage key prefix owned by the chat-media archive; the media bucket is shared with statuses. */
@@ -259,54 +260,24 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {
*/
async sweepOrphanedMedia(now: number = Date.now()): Promise<number> {
const graceMs = this.configService.get<number>('chatMedia.orphanGraceMs', DEFAULT_ORPHAN_GRACE_MS);
- let removed = 0;
- // Keys still unreferenced at the end of THIS pass. Bounded by the orphan count (normally ~0),
- // not by the size of the store, so it can safely drive the bookkeeping prune below.
- const stillOrphaned = new Set<string>();
-
- // Reconciled in chunks rather than as two whole-store sets. iterateFiles streams (listFiles
- // truncates at STORAGE_LIST_MAX_FILES, which would strand every orphan past the cap), but
- // collecting every key AND every archived row into memory would undo that: with the default
- // TTL of 0 the archive grows without bound, so a mature gateway would spend an hourly spike
- // holding millions of key strings. Each chunk asks the DB only which of ITS keys are
- // referenced — an indexed lookup over a bounded id list.
- let chunk: string[] = [];
- const flush = async (): Promise<void> => {
- if (chunk.length === 0) return;
- const rows = await this.repository.find({ where: { mediaPath: In(chunk) }, select: { mediaPath: true } });
- const referenced = new Set(rows.map(row => row.mediaPath));
- for (const file of chunk) {
- if (referenced.has(file)) {
- this.orphanFirstSeenAt.delete(file);
- continue;
- }
- stillOrphaned.add(file);
- const firstSeenAt = this.orphanFirstSeenAt.get(file) ?? now;
- this.orphanFirstSeenAt.set(file, firstSeenAt);
- if (now - firstSeenAt < graceMs) continue;
- try {
- await this.storageService.deleteFile(file);
- this.orphanFirstSeenAt.delete(file);
- stillOrphaned.delete(file);
- removed += 1;
- } catch (err) {
- this.logger.warn(`Failed to delete orphaned chat media ${file}`, { error: String(err) });
- }
- }
- chunk = [];
- };
-
- for await (const file of this.storageService.iterateFiles(CHAT_MEDIA_PREFIX)) {
- if (!file.startsWith(CHAT_MEDIA_PREFIX)) continue;
- chunk.push(file);
- if (chunk.length >= SWEEP_CHUNK_SIZE) await flush();
- }
- await flush();
- // Drop bookkeeping for anything not still orphaned this pass — the file is gone, or a row now
- // references it. Keyed off the orphan set rather than a full listing so this stays bounded too.
- for (const key of [...this.orphanFirstSeenAt.keys()]) {
- if (!stillOrphaned.has(key)) this.orphanFirstSeenAt.delete(key);
- }
+ // Reconciled in chunks rather than as two whole-store sets: with the default TTL of 0 the
+ // archive grows without bound, so collecting every key AND every archived row into memory would
+ // turn the hourly sweep into a memory spike. Each chunk asks the DB only which of ITS keys are
+ // referenced — an indexed lookup over a bounded key list.
+ const removed = await sweepOrphanedFiles({
+ storage: this.storageService,
+ prefix: CHAT_MEDIA_PREFIX,
+ graceMs,
+ now,
+ firstSeenAt: this.orphanFirstSeenAt,
+ chunkSize: SWEEP_CHUNK_SIZE,
+ referencedAmong: async keys => {
+ const rows = await this.repository.find({ where: { mediaPath: In(keys) }, select: { mediaPath: true } });
+ return new Set(rows.map(row => row.mediaPath));
+ },
+ onDeleteFailed: (file, err) =>
+ this.logger.warn(`Failed to delete orphaned chat media ${file}`, { error: String(err) }),
+ });
if (removed > 0) this.logger.log(`Chat media orphan sweep removed ${removed} file(s)`);
return removed;
}
diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.ts
index 268464eba..e62b85dc3 100644
--- a/src/modules/status-store/status-store.service.ts
+++ b/src/modules/status-store/status-store.service.ts
@@ -7,6 +7,7 @@ import { StatusUpdate } from './entities/status-update.entity';
import type { IncomingStatus } from './incoming-status';
import type { Status } from '../../engine/interfaces/whatsapp-engine.interface';
import { StorageService } from '../../common/storage/storage.service';
+import { sweepOrphanedFiles } from '../../common/storage/orphan-sweep';
import { isUniqueConstraintError } from '../../common/utils/unique-constraint.util';
import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';
import { userPart } from '../../engine/identity/wa-id';
@@ -345,42 +346,24 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {
*/
async sweepOrphanedMedia(now: number = Date.now()): Promise<number> {
const graceMs = this.configService.get<number>('status.orphanGraceMs', DEFAULT_ORPHAN_GRACE_MS);
- // Stream via iterateFiles: listFiles() truncates at STORAGE_LIST_MAX_FILES (a per-call DoS
- // guard, not a completeness contract), which would strand every orphan past the cap. Scope the
- // walk to the statuses/ prefix so dropping that cap does not pull the whole media store — chat
- // media shares this bucket — through the iterator and its dedupe set.
- const files: string[] = [];
- for await (const file of this.storageService.iterateFiles(STATUS_MEDIA_PREFIX)) {
- if (file.startsWith(STATUS_MEDIA_PREFIX)) files.push(file);
- }
- const rows = await this.repository.find({
- where: { mediaPath: Not(IsNull()) },
- select: { mediaPath: true },
+ // The referenced set is bounded by the 24h TTL, so a single whole-set query is the cheap shape
+ // here (no chunking) — unlike the chat-media archive, whose rows can accumulate without bound.
+ const removed = await sweepOrphanedFiles({
+ storage: this.storageService,
+ prefix: STATUS_MEDIA_PREFIX,
+ graceMs,
+ now,
+ firstSeenAt: this.orphanFirstSeenAt,
+ referencedAmong: async () => {
+ const rows = await this.repository.find({
+ where: { mediaPath: Not(IsNull()) },
+ select: { mediaPath: true },
+ });
+ return new Set(rows.map(row => row.mediaPath));
+ },
+ onDeleteFailed: (file, err) =>
+ this.logger.warn(`Failed to delete orphaned status media ${file}`, { error: String(err) }),
});
- const referenced = new Set(rows.map(row => row.mediaPath));
-
- let removed = 0;
- const present = new Set(files);
- for (const file of files) {
- if (referenced.has(file)) {
- this.orphanFirstSeenAt.delete(file);
- continue;
- }
- const firstSeenAt = this.orphanFirstSeenAt.get(file) ?? now;
- this.orphanFirstSeenAt.set(file, firstSeenAt);
- if (now - firstSeenAt < graceMs) continue;
- try {
- await this.storageService.deleteFile(file);
- this.orphanFirstSeenAt.delete(file);
- removed += 1;
- } catch (err) {
- this.logger.warn(`Failed to delete orphaned status media ${file}`, { error: String(err) });
- }
- }
- // Drop bookkeeping for files that are gone so the map can't grow unbounded.
- for (const key of [...this.orphanFirstSeenAt.keys()]) {
- if (!present.has(key)) this.orphanFirstSeenAt.delete(key);
- }
if (removed > 0) this.logger.log(`Status media orphan sweep removed ${removed} file(s)`);
return removed;
}