import { Injectable, Logger, OnModuleDestroy, OnModuleInit, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import type { AppConfig } from '../config/app-config.schema.js'; import { MetricsService } from '../metrics/metrics.service.js'; import { ObjectStorage } from '../storage/object-storage.js'; import { AttachmentsRepository } from './attachments.repository.js'; const SWEEP_BATCH = 100; /** * Removes unfinished uploads (pending past expiry + grace) and rows whose * deletion was claimed but never finished. A live upload is never touched: * its expiry is a hard request deadline and the grace period is far longer. */ @Injectable() export class AttachmentSweeper implements OnModuleInit, OnModuleDestroy { private readonly logger = new Logger(AttachmentSweeper.name); private timer: NodeJS.Timeout | undefined; private running = false; constructor( private readonly config: ConfigService, private readonly repository: AttachmentsRepository, private readonly storage: ObjectStorage, private readonly metrics: MetricsService, ) {} onModuleInit(): void { const interval = this.config.getOrThrow('ATTACHMENT_SWEEP_INTERVAL_MS'); if (interval <= 0) return; this.timer = setInterval(() => { if (this.running) return; this.running = true; this.sweepOnce() .catch((error: unknown) => { this.logger.warn( `Sweep failed: ${error instanceof Error ? error.message : 'unknown error'}`, ); }) .finally(() => { this.running = false; }); }, interval); this.timer.unref(); } onModuleDestroy(): void { if (this.timer) clearInterval(this.timer); this.timer = undefined; } async sweepOnce(): Promise<{ claimed: number; deleted: number }> { const claimed = await this.repository.claimExpired( this.config.getOrThrow('ATTACHMENT_SWEEP_GRACE_SECONDS'), SWEEP_BATCH, ); let deleted = 0; for (const item of claimed) { try { await this.storage.delete(item.object_key); await this.repository.deleteClaimed(item.id); deleted += 1; this.metrics.increment('attachments.sweep.deleted'); } catch (error) { this.metrics.increment('attachments.sweep.error'); this.logger.warn( `Sweep of attachment ${item.id} failed: ${error instanceof Error ? error.message : 'unknown error'}`, ); } } return { claimed: claimed.length, deleted }; } }