import { Logger } from '@nestjs/common'; import { reconcile } from './attachments/reconciler'; import { PrismaService } from './db/prisma.service'; import { S3Service } from './storage/s3.service'; const DEFAULT_GRACE_SECONDS = 3600; const DEFAULT_INTERVAL_SECONDS = 300; const DEFAULT_STAGING_RETENTION_SECONDS = 86400; function option(name: string, fallback: number): number { const prefix = `--${name}=`; const raw = process.argv.find((arg) => arg.startsWith(prefix)); const value = raw ? Number(raw.slice(prefix.length)) : fallback; if (!Number.isInteger(value) || value < 0) { throw new Error(`--${name} must be a non-negative integer`); } return value; } async function main(): Promise { process.once('SIGTERM', () => process.exit(0)); process.once('SIGINT', () => process.exit(0)); const apply = process.argv.includes('--apply'); const loop = process.argv.includes('--loop'); const graceSeconds = option('grace-seconds', DEFAULT_GRACE_SECONDS); const intervalSeconds = option('interval-seconds', DEFAULT_INTERVAL_SECONDS); const stagingRetentionSeconds = option( 'staging-retention-seconds', Number(process.env.STAGING_RETENTION_SECONDS ?? DEFAULT_STAGING_RETENTION_SECONDS), ); const prisma = new PrismaService(); const s3 = new S3Service(); do { try { const report = await reconcile(prisma, s3, { apply, graceMs: graceSeconds * 1000, stagingRetentionMs: stagingRetentionSeconds * 1000, }); process.stdout.write(`${JSON.stringify(report)}\n`); } catch (error) { const reason = error instanceof Error ? error.name : 'unknown error'; Logger.error(`reconcile pass aborted: ${reason}`, 'Reconciler'); process.exitCode = loop ? 0 : 1; } if (loop) { await new Promise((resolve) => setTimeout(resolve, intervalSeconds * 1000)); } } while (loop); await prisma.$disconnect(); s3.onModuleDestroy(); } main().catch((error) => { Logger.error(error instanceof Error ? error.message : 'fatal error', 'Reconciler'); process.exit(1); });