Free, Open Source, Self-Hosted WhatsApp API Gateway
TypeScript apibotgatewayself-hostedwhatsappwhatsapp-apiwhatsapp-automationwhatsapp-botwhatsapp-gatewaywhatsapp-gateway-apiwhatsapp-webwhatsapp-web-api
fix(media): keep orphan sweeps from overlapping
Yudhi Armyndharis063d7c6764d4
diff --git a/src/common/utils/guarded-interval.spec.ts b/src/common/utils/guarded-interval.spec.tsnew file mode 100644index 000000000..e4f7c450e--- /dev/null+++ b/src/common/utils/guarded-interval.spec.ts@@ -0,0 +1,73 @@+import { startGuardedInterval } from './guarded-interval';++describe('startGuardedInterval', () => {+ beforeEach(() => jest.useFakeTimers());+ afterEach(() => jest.useRealTimers());++ it('runs the task at once and then on every interval', async () => {+ const task = jest.fn().mockResolvedValue(undefined);+ const stop = startGuardedInterval(task, 1000, jest.fn());+ expect(task).toHaveBeenCalledTimes(1);++ await jest.advanceTimersByTimeAsync(3000);++ expect(task).toHaveBeenCalledTimes(4);+ stop();+ });++ it('skips a tick while the previous run is still going, and resumes once it ends', async () => {+ let finish!: () => void;+ const task = jest+ .fn()+ .mockImplementationOnce(() => new Promise<void>(resolve => (finish = resolve)))+ .mockResolvedValue(undefined);+ const stop = startGuardedInterval(task, 1000, jest.fn());++ await jest.advanceTimersByTimeAsync(5000);+ expect(task).toHaveBeenCalledTimes(1);++ finish();+ await jest.advanceTimersByTimeAsync(1000);+ expect(task).toHaveBeenCalledTimes(2);+ stop();+ });++ it('hands a failed run to onError, keeps the schedule, and frees the next tick', async () => {+ const failure = new Error('bucket gone');+ const task = jest.fn().mockRejectedValueOnce(failure).mockResolvedValue(undefined);+ const onError = jest.fn();+ const stop = startGuardedInterval(task, 1000, onError);++ await jest.advanceTimersByTimeAsync(1000);++ expect(onError).toHaveBeenCalledTimes(1);+ expect(onError).toHaveBeenCalledWith(failure);+ expect(task).toHaveBeenCalledTimes(2);+ stop();+ });++ it('treats a task that throws before returning a promise as a failed run', async () => {+ const failure = new Error('sync throw');+ const task = jest.fn(() => {+ throw failure;+ });+ const onError = jest.fn();+ const stop = startGuardedInterval(task, 1000, onError);++ await jest.advanceTimersByTimeAsync(1000);++ expect(onError).toHaveBeenCalledWith(failure);+ expect(task).toHaveBeenCalledTimes(2);+ stop();+ });++ it('stops scheduling when stopped', async () => {+ const task = jest.fn().mockResolvedValue(undefined);+ const stop = startGuardedInterval(task, 1000, jest.fn());+ stop();++ await jest.advanceTimersByTimeAsync(5000);++ expect(task).toHaveBeenCalledTimes(1);+ });+});diff --git a/src/common/utils/guarded-interval.ts b/src/common/utils/guarded-interval.tsnew file mode 100644index 000000000..6885b120c--- /dev/null+++ b/src/common/utils/guarded-interval.ts@@ -0,0 +1,28 @@+/**+ * Run a maintenance task now and then every `intervalMs`, one run at a time: a tick that finds the+ * previous run still going is skipped rather than stacked on top of it, so a pass that outlasts its+ * interval (a large bucket, a slow database) never multiplies its own load. A failed run is handed to+ * `onError` and does not stop the schedule. The timer does not keep the process alive.+ *+ * Returns the function that stops the schedule; a run already in progress finishes.+ */+export function startGuardedInterval(+ task: () => Promise<unknown>,+ intervalMs: number,+ onError: (error: unknown) => void,+): () => void {+ let running = false;+ const run = (): void => {+ if (running) return;+ running = true;+ // An async wrapper, so a task that throws before its first await is a failed run like any other,+ // and still starts synchronously.+ void (async () => task())()+ .catch(onError)+ .finally(() => (running = false));+ };+ run();+ const timer = setInterval(run, intervalMs);+ timer.unref?.();+ return () => clearInterval(timer);+}diff --git a/src/modules/chat-media/chat-media-archive.service.spec.ts b/src/modules/chat-media/chat-media-archive.service.spec.tsindex a812974d4..bee128482 100644--- a/src/modules/chat-media/chat-media-archive.service.spec.ts+++ b/src/modules/chat-media/chat-media-archive.service.spec.ts@@ -923,6 +923,32 @@ describe('ChatMediaArchiveService', () => {}});+ it('skips an orphan sweep tick while the previous sweep is still running', async () => {+ jest.useFakeTimers({ doNotFake: ['setImmediate', 'nextTick'] });+ const svc = build({ 'chatMedia.orphanSweepIntervalMs': 60_000 });+ let release: () => void = () => undefined;+ const sweep = jest+ .spyOn(svc, 'sweepOrphanedMedia')+ .mockImplementationOnce(() => new Promise<number>(resolve => (release = () => resolve(0))))+ .mockResolvedValue(0);+ const purge = jest.spyOn(svc, 'purgeExpired').mockResolvedValue(0);+ try {+ svc.onModuleInit();+ await jest.advanceTimersByTimeAsync(60_000);+ await jest.advanceTimersByTimeAsync(60_000);+ expect(sweep).toHaveBeenCalledTimes(1);++ release();+ await jest.advanceTimersByTimeAsync(60_000);+ expect(sweep).toHaveBeenCalledTimes(2);+ } finally {+ svc.onModuleDestroy();+ release();+ [sweep, purge].forEach(spy => spy.mockRestore());+ jest.useRealTimers();+ }+ });+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 81a844dc4..a592ab06b 100644--- a/src/modules/chat-media/chat-media-archive.service.ts+++ b/src/modules/chat-media/chat-media-archive.service.ts@@ -6,6 +6,7 @@ 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 { startGuardedInterval } from '../../common/utils/guarded-interval';import { extFromMimetype } from '../../common/media/mime-ext';import { createLogger } from '../../common/services/logger.service';@@ -61,14 +62,12 @@ interface InlineMedia {@Injectable()export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('ChatMediaArchiveService');- private purgeTimer?: ReturnType<typeof setInterval>;- private orphanSweepTimer?: ReturnType<typeof setInterval>;+ /** Stops the retention purge and the orphan sweep; set while the service is running. */+ private stopMaintenance: Array<() => void> = [];/** First sweep sighting (epoch ms) of each unreferenced archive file, for the grace window. */private readonly orphanFirstSeenAt = new Map<string, number>();/** Last row id the retention purge walked past; the next run resumes after it. */private purgeCursor?: string;- /** A purge is still running, so the next tick is skipped rather than stacked on top of it. */- private purging = false;constructor(@InjectRepository(Message, 'data')@@ -87,34 +86,27 @@ export class ChatMediaArchiveService implements OnModuleInit, OnModuleDestroy {}onModuleInit(): void {- const runPurge = (): void => {- if (this.purging) return;- this.purging = true;- this.purgeExpired(Date.now())- .catch(err => this.logger.error('Chat media purge failed', err instanceof Error ? err.stack : String(err)))- .finally(() => (this.purging = false));- };- runPurge(); // sweep once at startup- this.purgeTimer = setInterval(runPurge, PURGE_INTERVAL_MS);- this.purgeTimer.unref?.();-- const runOrphanSweep = (): void => {- this.sweepOrphanedMedia(Date.now()).catch(err =>- this.logger.error('Chat media orphan sweep failed', err instanceof Error ? err.stack : String(err)),- );- };- runOrphanSweep(); // the first pass only records first-seen; nothing is deleted before the grace window+ const failed = (what: string) => (err: unknown) =>+ this.logger.error(`${what} failed`, err instanceof Error ? err.stack : String(err));const sweepIntervalMs = this.configService.get<number>('chatMedia.orphanSweepIntervalMs',DEFAULT_ORPHAN_SWEEP_INTERVAL_MS,);- this.orphanSweepTimer = setInterval(runOrphanSweep, sweepIntervalMs);- this.orphanSweepTimer.unref?.();+ this.stopMaintenance = [+ // Once at startup, then on a timer; a pass that outlasts its interval is not stacked on.+ startGuardedInterval(() => this.purgeExpired(Date.now()), PURGE_INTERVAL_MS, failed('Chat media purge')),+ // The first pass only records first-seen; nothing is deleted before the grace window.+ startGuardedInterval(+ () => this.sweepOrphanedMedia(Date.now()),+ sweepIntervalMs,+ failed('Chat media orphan sweep'),+ ),+ ];}onModuleDestroy(): void {- if (this.purgeTimer) clearInterval(this.purgeTimer);- if (this.orphanSweepTimer) clearInterval(this.orphanSweepTimer);+ for (const stop of this.stopMaintenance) stop();+ this.stopMaintenance = [];}/**diff --git a/src/modules/status-store/status-store.service.spec.ts b/src/modules/status-store/status-store.service.spec.tsindex ea2cd7e16..03bf4ce75 100644--- a/src/modules/status-store/status-store.service.spec.ts+++ b/src/modules/status-store/status-store.service.spec.ts@@ -952,7 +952,38 @@ describe('StatusStoreService onModuleInit/onModuleDestroy (sweep scheduling)', (}});- it('runs the orphan sweep once at startup and on its own (slower) cadence, cleared on destroy', () => {+ it('skips an orphan sweep tick while the previous sweep is still running', async () => {+ const { repo, storage } = mockDeps();+ const service = new StatusStoreService(+ repo,+ storage,+ fakeConfigService({ 'status.orphanSweepIntervalMs': 60_000 }),+ );++ jest.useFakeTimers();+ let release: () => void = () => undefined;+ jest.spyOn(service, 'purgeExpired').mockResolvedValue(0);+ const sweepSpy = jest+ .spyOn(service, 'sweepOrphanedMedia')+ .mockImplementationOnce(() => new Promise<number>(resolve => (release = () => resolve(0))))+ .mockResolvedValue(0);+ try {+ service.onModuleInit();+ await jest.advanceTimersByTimeAsync(60_000);+ await jest.advanceTimersByTimeAsync(60_000);+ expect(sweepSpy).toHaveBeenCalledTimes(1);++ release();+ await jest.advanceTimersByTimeAsync(60_000);+ expect(sweepSpy).toHaveBeenCalledTimes(2);+ } finally {+ service.onModuleDestroy();+ release();+ jest.useRealTimers();+ }+ });++ it('runs the orphan sweep once at startup and on its own (slower) cadence, cleared on destroy', async () => {const { repo, storage } = mockDeps();const service = new StatusStoreService(repo, storage, fakeConfigService());@@ -964,21 +995,21 @@ describe('StatusStoreService onModuleInit/onModuleDestroy (sweep scheduling)', (// The TTL purge fires every 15 min; the orphan sweep only on its own 1h interval.sweepSpy.mockClear();- jest.advanceTimersByTime(15 * 60 * 1000);+ await jest.advanceTimersByTimeAsync(15 * 60 * 1000);expect(sweepSpy).not.toHaveBeenCalled();- jest.advanceTimersByTime(45 * 60 * 1000);+ await jest.advanceTimersByTimeAsync(45 * 60 * 1000);expect(sweepSpy).toHaveBeenCalledTimes(1);service.onModuleDestroy();sweepSpy.mockClear();- jest.advanceTimersByTime(60 * 60 * 1000);+ await jest.advanceTimersByTimeAsync(60 * 60 * 1000);expect(sweepSpy).not.toHaveBeenCalled();} finally {jest.useRealTimers();}});- it('honors a configured status.orphanSweepIntervalMs override', () => {+ it('honors a configured status.orphanSweepIntervalMs override', async () => {const { repo, storage } = mockDeps();const service = new StatusStoreService(repo,@@ -991,7 +1022,7 @@ describe('StatusStoreService onModuleInit/onModuleDestroy (sweep scheduling)', (const sweepSpy = jest.spyOn(service, 'sweepOrphanedMedia').mockResolvedValue(0);service.onModuleInit();sweepSpy.mockClear();- jest.advanceTimersByTime(5 * 60 * 1000);+ await jest.advanceTimersByTimeAsync(5 * 60 * 1000);expect(sweepSpy).toHaveBeenCalledTimes(1);service.onModuleDestroy();} finally {diff --git a/src/modules/status-store/status-store.service.ts b/src/modules/status-store/status-store.service.tsindex ee2d4cca8..4877c34ba 100644--- a/src/modules/status-store/status-store.service.ts+++ b/src/modules/status-store/status-store.service.ts@@ -8,6 +8,7 @@ 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 { startGuardedInterval } from '../../common/utils/guarded-interval';import { extFromMimetype } from '../../common/media/mime-ext';import { isUniqueViolation } from '../../common/utils/db-errors';import { LidMappingStoreService } from '../../engine/identity/lid-mapping-store.service';@@ -48,14 +49,12 @@ const STATUS_MEDIA_PREFIX = 'statuses/';@Injectable()export class StatusStoreService implements OnModuleInit, OnModuleDestroy {private readonly logger = createLogger('StatusStoreService');- private purgeTimer?: ReturnType<typeof setInterval>;- private orphanSweepTimer?: ReturnType<typeof setInterval>;+ /** Stops the TTL purge and the orphan sweep; set while the service is running. */+ private stopMaintenance: Array<() => void> = [];/** First sweep sighting (epoch ms) of each unreferenced status media file, for the grace window. */private readonly orphanFirstSeenAt = new Map<string, number>();/** Last row id the TTL purge walked past; the next run resumes after it. */private purgeCursor?: string;- /** A purge is still running, so the next tick is skipped rather than stacked on top of it. */- private purging = false;constructor(@InjectRepository(StatusUpdate, 'data')@@ -68,34 +67,27 @@ export class StatusStoreService implements OnModuleInit, OnModuleDestroy {) {}onModuleInit(): void {- const runPurge = (): void => {- if (this.purging) return;- this.purging = true;- this.purgeExpired(Date.now())- .catch(err => this.logger.error('Status purge failed', err instanceof Error ? err.stack : String(err)))- .finally(() => (this.purging = false));- };- runPurge(); // sweep once at startup- this.purgeTimer = setInterval(runPurge, PURGE_INTERVAL_MS);- this.purgeTimer.unref?.();-- const runOrphanSweep = (): void => {- this.sweepOrphanedMedia(Date.now()).catch(err =>- this.logger.error('Status media orphan sweep failed', err instanceof Error ? err.stack : String(err)),- );- };- runOrphanSweep(); // the first pass only records first-seen; nothing is deleted before the grace window+ const failed = (what: string) => (err: unknown) =>+ this.logger.error(`${what} failed`, err instanceof Error ? err.stack : String(err));const sweepIntervalMs = this.configService.get<number>('status.orphanSweepIntervalMs',DEFAULT_ORPHAN_SWEEP_INTERVAL_MS,);- this.orphanSweepTimer = setInterval(runOrphanSweep, sweepIntervalMs);- this.orphanSweepTimer.unref?.();+ this.stopMaintenance = [+ // Once at startup, then on a timer; a pass that outlasts its interval is not stacked on.+ startGuardedInterval(() => this.purgeExpired(Date.now()), PURGE_INTERVAL_MS, failed('Status purge')),+ // The first pass only records first-seen; nothing is deleted before the grace window.+ startGuardedInterval(+ () => this.sweepOrphanedMedia(Date.now()),+ sweepIntervalMs,+ failed('Status media orphan sweep'),+ ),+ ];}onModuleDestroy(): void {- if (this.purgeTimer) clearInterval(this.purgeTimer);- if (this.orphanSweepTimer) clearInterval(this.orphanSweepTimer);+ for (const stop of this.stopMaintenance) stop();+ this.stopMaintenance = [];}/**