import type { PrismaService } from '../prisma/prisma.service'; import type { StorageService, StoredObject } from '../Storage/storage.service'; import { ReconcileService } from './reconcile.service'; import { reconcileOptions } from './reconcile-options'; const key = 'originals/11111111-1111-4111-8111-111111111111/22222222-2222-4222-8222-222222222222'; const now = new Date('2026-11-09T12:00:00Z'); const old = new Date(now.getTime() - 601000); const fresh = new Date(now.getTime() - 599000); function fixture(objects: StoredObject[] = [{ key, lastModified: old }]) { const tx = { $executeRaw: jest.fn().mockResolvedValue(0), $queryRaw: jest.fn().mockResolvedValue([{ locked: true }]), attachment: { findUnique: jest.fn().mockResolvedValue(null) }, directUpload: { findUnique: jest.fn().mockResolvedValue(null) }, }; const prisma = { $queryRaw: jest.fn().mockResolvedValue([{ '?column?': 1 }]), $transaction: jest.fn( async (callback: (value: typeof tx) => Promise) => callback(tx), ), attachment: { findMany: jest.fn().mockResolvedValue([]) }, directUpload: { updateMany: jest.fn().mockResolvedValue({ count: 0 }) }, }; const storage = { ready: jest.fn().mockResolvedValue(undefined), objects: jest.fn(async function* (prefix: string) { if (prefix === 'staging/') return; yield* objects; }), stat: jest.fn().mockResolvedValue({ key, lastModified: old }), remove: jest.fn().mockResolvedValue(undefined), }; const emit = jest.fn(); const service = new ReconcileService( prisma as unknown as PrismaService, storage as unknown as StorageService, emit, ); const run = (apply = true) => service.run({ apply, graceSeconds: 600, prefix: 'originals/' }, now); return { tx, prisma, storage, emit, run }; } describe('attachment reconciliation', () => { it('reports old orphans in dry-run without removing bytes', async () => { const f = fixture(); expect(await f.run(false)).toMatchObject({ orphanCandidates: 1, deletedObjects: 0, }); expect(f.storage.remove).not.toHaveBeenCalled(); expect(f.emit).toHaveBeenCalledWith({ event: 'orphan_candidate', objectKey: key, }); }); it('deletes an old orphan and safely handles another pass after it is gone', async () => { const f = fixture(); expect(await f.run()).toMatchObject({ deletedObjects: 1 }); f.storage.stat.mockResolvedValue(null); expect(await f.run()).toMatchObject({ deletedObjects: 0 }); expect(f.storage.remove).toHaveBeenCalledTimes(1); }); it('keeps fresh objects, unknown keys and objects with no trusted timestamp', async () => { const f = fixture([ { key, lastModified: fresh }, { key: 'originals/manual.txt', lastModified: old }, { key }, ]); expect(await f.run()).toMatchObject({ freshObjects: 2, unknownObjects: 1, deletedObjects: 0, }); expect(f.prisma.$transaction).not.toHaveBeenCalled(); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('does not delete objects referenced by metadata', async () => { const f = fixture(); f.tx.attachment.findUnique.mockResolvedValue({ id: 'published' }); expect(await f.run()).toMatchObject({ referencedObjects: 1, deletedObjects: 0, }); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('skips an object locked by an active uploader or another cleaner', async () => { const f = fixture(); f.tx.$queryRaw.mockResolvedValue([{ locked: false }]); expect(await f.run()).toMatchObject({ lockedObjects: 1, deletedObjects: 0, }); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('rechecks current S3 age instead of trusting an old LIST result', async () => { const f = fixture(); f.storage.stat.mockResolvedValue({ key, lastModified: fresh }); expect(await f.run()).toMatchObject({ freshObjects: 1, deletedObjects: 0 }); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('rechecks metadata immediately before deletion', async () => { const f = fixture(); f.tx.attachment.findUnique .mockResolvedValueOnce(null) .mockResolvedValueOnce({ id: 'published' }); expect(await f.run()).toMatchObject({ referencedObjects: 1, deletedObjects: 0, }); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('aborts before contacting S3 if the DB is unavailable', async () => { const f = fixture(); f.prisma.$queryRaw.mockRejectedValue(new Error('DB unavailable')); await expect(f.run()).rejects.toThrow('DB unavailable'); expect(f.storage.ready).not.toHaveBeenCalled(); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('does not delete when the DB fails after the S3 age check', async () => { const f = fixture(); f.tx.attachment.findUnique .mockResolvedValueOnce(null) .mockRejectedValueOnce(new Error('DB unavailable')); await expect(f.run()).rejects.toThrow('DB unavailable'); expect(f.storage.remove).not.toHaveBeenCalled(); }); it('does not treat S3 failure as a missing object or successful cleanup', async () => { const f = fixture(); f.storage.stat.mockRejectedValue(new Error('S3 unavailable')); await expect(f.run()).rejects.toThrow('S3 unavailable'); expect(f.storage.remove).not.toHaveBeenCalled(); expect(f.emit).not.toHaveBeenCalled(); }); it('reports missing bytes without deleting metadata', async () => { const f = fixture([]); f.prisma.attachment.findMany.mockResolvedValue([ { id: 'published', objectKey: key }, ]); f.storage.stat.mockResolvedValue(null); expect(await f.run()).toMatchObject({ missingObjects: 1, deletedObjects: 0, }); expect(f.emit).toHaveBeenCalledWith({ event: 'missing_object', objectKey: key, attachmentId: 'published', }); expect(f.storage.remove).not.toHaveBeenCalled(); }); }); describe('reconciliation CLI options', () => { it('defaults to dry-run with a ten-minute grace and one-minute interval', () => { expect(reconcileOptions([], {})).toMatchObject({ apply: false, watch: false, graceSeconds: 600, intervalSeconds: 60, }); }); it('accepts explicit apply and a scope limited to one chat', () => { expect( reconcileOptions( ['--apply', '--prefix', key.slice(0, key.lastIndexOf('/') + 1)], { ORPHAN_GRACE_SECONDS: '1200' }, ), ).toMatchObject({ apply: true, graceSeconds: 1200 }); }); it.each(['0', '-1', '1.5', 'NaN', '999999999999'])( 'rejects invalid grace %s', (value) => { expect(() => reconcileOptions([], { ORPHAN_GRACE_SECONDS: value }), ).toThrow(); }, ); it('rejects unsafe prefixes and conflicting modes', () => { expect(() => reconcileOptions(['--prefix', 'other/'], {})).toThrow(); expect(() => reconcileOptions(['--apply', '--dry-run'], {})).toThrow(); expect(() => reconcileOptions(['--unknown'], {})).toThrow(); }); });