refactor(backup): auto-backup retention through storage

This commit is contained in:
jubnl
2026-08-17 07:29:22 +02:00
parent 3838277048
commit 633103a246
4 changed files with 105 additions and 82 deletions
+3 -1
View File
@@ -3,6 +3,7 @@ import { readEnv } from '../../app-config';
import { logInfo, logError } from '../audit/audit-log.logger';
import { BackupService } from './backup.service';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { StorageService } from '../storage/storage.service';
import { parseAutoBackupBody } from './backup.impl';
import {
buildCronExpression,
@@ -24,6 +25,7 @@ export class AutoBackupJob implements OnApplicationBootstrap {
constructor(
private readonly backup: BackupService,
private readonly registrar: CronRegistrarService,
private readonly storage: StorageService,
) {}
onApplicationBootstrap(): void {
@@ -66,7 +68,7 @@ export class AutoBackupJob implements OnApplicationBootstrap {
const settings = loadSettings();
if (settings.keep_days > 0) {
cleanupOldBackups(settings.keep_days);
await cleanupOldBackups(this.storage, settings.keep_days);
}
}
+13 -10
View File
@@ -1,16 +1,19 @@
import path from 'node:path';
import fs from 'node:fs';
import { logInfo, logError } from '../audit/audit-log.logger';
import type { StorageService } from '../storage/storage.service';
/**
* Auto-backup settings and retention — the pure half of the auto-backup cron
* (moved from src/scheduler.ts). Stays a plain module beside backup.impl.ts
* for the same reason that does: file I/O against data/backup-settings.json
* and data/backups, no container state. AutoBackupJob owns the scheduling.
* for the same reason that does: file I/O against data/backup-settings.json,
* no container state. AutoBackupJob owns the scheduling and passes its
* injected StorageService into cleanupOldBackups — retention addresses the
* backups category through the facade so expired archives leave mirror
* replicas too.
*/
const dataDir = path.join(__dirname, '../../../data');
const backupsDir = path.join(dataDir, 'backups');
const settingsFile = path.join(dataDir, 'backup-settings.json');
export const VALID_INTERVALS = ['hourly', 'daily', 'weekly', 'monthly'];
@@ -70,16 +73,16 @@ function autoBackupTimestampMs(filename: string): number | null {
return Number.isNaN(ms) ? null : ms;
}
export function cleanupOldBackups(keepDays: number, now: number = Date.now()): void {
export async function cleanupOldBackups(storage: StorageService, keepDays: number, now: number = Date.now()): Promise<void> {
try {
const cutoff = now - keepDays * 24 * 60 * 60 * 1000;
const files = fs.readdirSync(backupsDir).filter(f => f.startsWith('auto-backup-') && f.endsWith('.zip'));
for (const file of files) {
const filePath = path.join(backupsDir, file);
const ageMs = autoBackupTimestampMs(file) ?? fs.statSync(filePath).mtimeMs;
for await (const obj of storage.list('backups')) {
if (obj.key.includes('/')) continue; // list() recurses; retention is top-level-only like the readdir it replaces
if (!obj.key.startsWith('auto-backup-') || !obj.key.endsWith('.zip')) continue; // manual backup-*.zip is never auto-deleted
const ageMs = autoBackupTimestampMs(obj.key) ?? obj.mtimeMs;
if (ageMs < cutoff) {
fs.unlinkSync(filePath);
logInfo(`Auto-Backup old backup deleted: ${file}`);
await storage.delete('backups', obj.key); // fans out to mirror replicas too
logInfo(`Auto-Backup old backup deleted: ${obj.key}`);
}
}
} catch (err: unknown) {
+19 -7
View File
@@ -111,6 +111,7 @@ function makeJob() {
// BackupService: inject the storage stub as the first argument.
{ createBackup: (prefix?: 'backup' | 'auto-backup') => createBackup(storageStub as unknown as StorageService, prefix) } as unknown as BackupService,
registrar as unknown as CronRegistrarService,
storageStub as unknown as StorageService,
);
return { job, registered, registrar };
}
@@ -141,6 +142,7 @@ describe('auto-backup run', () => {
beforeEach(() => {
vi.clearAllMocks();
resetStorageStub();
// No ENCRYPTION_KEY in the env means the key file is the source of truth and
// has to travel with the backup.
delete process.env.ENCRYPTION_KEY;
@@ -178,15 +180,21 @@ describe('auto-backup run', () => {
it('keeps the auto-backup-*.zip naming so retention still prunes it', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('backup-settings.json'));
fsMock.readdirSync.mockReturnValue(['auto-backup-2020-01-01T02-00-00.zip'] as unknown as string[]);
// An expired scheduled archive sits in the backups category (retention
// lists through storage now); the category enumeration stays empty.
storageStub.list = vi.fn((category: string) =>
(async function* () {
if (category === 'backups') yield { key: 'auto-backup-2020-01-01T02-00-00.zip', size: 0, mtimeMs: 0 };
})(),
);
stubArchiver();
await scheduledRun()();
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringMatching(/^Auto-Backup created: auto-backup-[\dT-]+\.zip$/));
// cleanupOldBackups(keep_days) still runs after the archive and only sees
// files it can match by prefix
expect(fsMock.unlinkSync).toHaveBeenCalledWith(expect.stringContaining('auto-backup-2020-01-01T02-00-00.zip'));
// cleanupOldBackups(storage, keep_days) still runs after the archive and
// only prunes objects it can match by prefix — through storage.delete
expect(storageStub.delete).toHaveBeenCalledWith('backups', 'auto-backup-2020-01-01T02-00-00.zip');
});
it('logs the failure, drops the partial zip and skips retention', async () => {
@@ -204,13 +212,15 @@ describe('auto-backup run', () => {
expect(storageStub.put).not.toHaveBeenCalled();
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('zip-build-auto-backup-'), { force: true });
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('travel-snap-auto-backup-'), { force: true });
expect(fsMock.readdirSync).not.toHaveBeenCalled();
expect(storageStub.list).not.toHaveBeenCalledWith('backups');
expect(storageStub.delete).not.toHaveBeenCalled();
});
});
describe('auto-backup scheduling (AutoBackupJob.start)', () => {
beforeEach(() => {
vi.clearAllMocks();
resetStorageStub();
fsMock.existsSync.mockImplementation(() => false);
fsMock.readFileSync.mockReturnValue('{}');
});
@@ -272,13 +282,14 @@ describe('auto-backup scheduling (AutoBackupJob.start)', () => {
await (registered.at(-1)?.onTick as () => Promise<void>)();
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringContaining('Auto-Backup created'));
expect(fsMock.readdirSync).not.toHaveBeenCalled(); // cleanupOldBackups never ran
expect(storageStub.list).not.toHaveBeenCalledWith('backups'); // cleanupOldBackups never ran
expect(storageStub.delete).not.toHaveBeenCalled();
});
it('a non-Error rejection from createBackup is stringified into the failure log', async () => {
const broken = { createBackup: vi.fn().mockRejectedValue('plain string') } as unknown as BackupService;
const registrar = { isEnabled: vi.fn(() => true), register: vi.fn(() => true), unregister: vi.fn() };
const job = new AutoBackupJob(broken, registrar as unknown as CronRegistrarService);
const job = new AutoBackupJob(broken, registrar as unknown as CronRegistrarService, storageStub as unknown as StorageService);
await job.runBackup();
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: plain string');
});
@@ -309,6 +320,7 @@ describe('auto-backup scheduling (AutoBackupJob.start)', () => {
describe('BACKUP-047 updateAutoSettings', () => {
beforeEach(() => {
vi.clearAllMocks();
resetStorageStub();
fsMock.existsSync.mockImplementation(() => false);
fsMock.readFileSync.mockReturnValue('{}');
});
@@ -38,24 +38,15 @@ import {
saveSettings,
type BackupSettings,
} from '../../../src/nest/backup/auto-backup.settings';
import type { StorageService } from '../../../src/nest/storage/storage.service';
// readdirSync and statSync are overloaded in node:fs, and vi.mocked() picks the last
// overload (Dirent[] / BigIntStats) rather than the one the cleanup calls. These handles
// point at the very same mock functions from the factory above, pinned to the plain
// string[] / Stats signatures that cleanupOldBackups actually uses.
// The settings half still does file I/O; these handles pin the mock functions
// from the factory above to the plain signatures loadSettings/saveSettings use.
// (Retention no longer touches fs — it goes through StorageService.)
const existsSyncMock = fs.existsSync as unknown as Mock<(path: string) => boolean>;
const readFileSyncMock = fs.readFileSync as unknown as Mock<(path: string, enc: string) => string>;
const writeFileSyncMock = fs.writeFileSync as unknown as Mock<(path: string, data: string) => void>;
const mkdirSyncMock = fs.mkdirSync as unknown as Mock<(path: string, opts?: unknown) => void>;
const readdirSyncMock = fs.readdirSync as unknown as Mock<(path: string) => string[]>;
const statSyncMock = fs.statSync as unknown as Mock<(path: string) => fs.Stats>;
const unlinkSyncMock = fs.unlinkSync as unknown as Mock<(path: string) => void>;
// cleanupOldBackups reads nothing but mtimeMs off a stat result, so the stubs below stay
// deliberately partial instead of faking a whole fs.Stats.
function statStub(partial: Partial<fs.Stats>): fs.Stats {
return partial as fs.Stats;
}
function settings(overrides: Partial<BackupSettings> = {}): BackupSettings {
return {
@@ -196,76 +187,91 @@ describe('cleanupOldBackups', () => {
return `${prefix}-${stamp}.zip`;
}
beforeEach(() => {
readdirSyncMock.mockReset();
statSyncMock.mockReset();
unlinkSyncMock.mockReset();
statSyncMock.mockReturnValue(statStub({ mtime: new Date(), mtimeMs: NOW, birthtimeMs: NOW, size: 0 }));
});
/** Retention runs against the backups category through storage now. */
function storageWith(entries: Array<{ key: string; mtimeMs?: number }>): StorageService {
return {
list: vi.fn(async function* () {
for (const e of entries) yield { size: 0, mtimeMs: NOW, ...e };
}),
delete: vi.fn(async () => {}),
} as unknown as StorageService;
}
const deletedKeys = (s: StorageService) => (s.delete as Mock).mock.calls.map(([, key]) => key as string);
it('never deletes manual backup-*.zip files regardless of age', () => {
it('never deletes manual backup-*.zip files regardless of age', async () => {
const manual = isoFilename(365 * 5, 'backup');
const auto = isoFilename(0);
readdirSyncMock.mockReturnValue([manual, auto]);
cleanupOldBackups(7, NOW);
const deleted = unlinkSyncMock.mock.calls.map(([p]) => p);
expect(deleted.some(p => p.includes(manual))).toBe(false);
const storage = storageWith([{ key: manual }, { key: isoFilename(0) }]);
await cleanupOldBackups(storage, 7, NOW);
expect(deletedKeys(storage)).not.toContain(manual);
});
it('keeps auto-backups newer than retention', () => {
const recent = isoFilename(3);
readdirSyncMock.mockReturnValue([recent]);
cleanupOldBackups(7, NOW);
expect(unlinkSyncMock).not.toHaveBeenCalled();
it('keeps auto-backups newer than retention', async () => {
const storage = storageWith([{ key: isoFilename(3) }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('deletes auto-backups older than retention', () => {
it('deletes auto-backups older than retention', async () => {
const old = isoFilename(30);
readdirSyncMock.mockReturnValue([old]);
cleanupOldBackups(7, NOW);
expect(unlinkSyncMock).toHaveBeenCalledOnce();
const [calledPath] = unlinkSyncMock.mock.calls[0];
expect(calledPath).toContain(old);
const storage = storageWith([{ key: old }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).toHaveBeenCalledOnce();
expect(storage.delete).toHaveBeenCalledWith('backups', old);
});
it('overlayfs regression: birthtimeMs=0 does not delete a same-day backup', () => {
const fresh = isoFilename(0);
readdirSyncMock.mockReturnValue([fresh]);
statSyncMock.mockReturnValue(statStub({ birthtimeMs: 0, mtimeMs: NOW, mtime: new Date(NOW), size: 100 }));
cleanupOldBackups(7, NOW);
expect(unlinkSyncMock).not.toHaveBeenCalled();
it('ages by filename timestamp first: a fresh name survives a bogus epoch mtime (overlayfs regression)', async () => {
// On overlayfs the fs timestamps lie (birthtime 0); the filename stamp is
// authoritative. ObjectStat only carries mtimeMs — set it to epoch and the
// same-day filename must still win.
const storage = storageWith([{ key: isoFilename(0), mtimeMs: 0 }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('malformed filename falls back to mtimeMs: keeps recent file', () => {
readdirSyncMock.mockReturnValue(['auto-backup-garbage.zip']);
statSyncMock.mockReturnValue(statStub({ birthtimeMs: 0, mtimeMs: NOW - 1 * DAY, mtime: new Date(NOW - 1 * DAY), size: 0 }));
cleanupOldBackups(7, NOW);
expect(unlinkSyncMock).not.toHaveBeenCalled();
it('malformed filename falls back to mtimeMs: keeps recent file', async () => {
const storage = storageWith([{ key: 'auto-backup-garbage.zip', mtimeMs: NOW - 1 * DAY }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('malformed filename falls back to mtimeMs: deletes stale file', () => {
readdirSyncMock.mockReturnValue(['auto-backup-garbage.zip']);
statSyncMock.mockReturnValue(statStub({ birthtimeMs: 0, mtimeMs: NOW - 30 * DAY, mtime: new Date(NOW - 30 * DAY), size: 0 }));
cleanupOldBackups(7, NOW);
expect(unlinkSyncMock).toHaveBeenCalledOnce();
it('malformed filename falls back to mtimeMs: deletes stale file', async () => {
const storage = storageWith([{ key: 'auto-backup-garbage.zip', mtimeMs: NOW - 30 * DAY }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).toHaveBeenCalledOnce();
});
it('ignores non-zip files and does not crash', () => {
it('ignores non-zip files and does not crash', async () => {
const old = isoFilename(30);
readdirSyncMock.mockReturnValue([old, 'notes.txt']);
cleanupOldBackups(7, NOW);
const calls = unlinkSyncMock.mock.calls;
expect(calls.every(([p]) => !p.includes('notes.txt'))).toBe(true);
expect(calls.length).toBe(1);
const storage = storageWith([{ key: old }, { key: 'notes.txt', mtimeMs: 0 }]);
await cleanupOldBackups(storage, 7, NOW);
expect(deletedKeys(storage)).toEqual([old]);
});
it('swallows readdirSync errors without throwing', () => {
readdirSyncMock.mockImplementation(() => { throw new Error('ENOENT'); });
expect(() => cleanupOldBackups(7, NOW)).not.toThrow();
it('ignores nested keys (storage.list recurses; the legacy readdir was single-level)', async () => {
const storage = storageWith([{ key: `restore-123/${isoFilename(30)}`, mtimeMs: 0 }]);
await cleanupOldBackups(storage, 7, NOW);
expect(storage.delete).not.toHaveBeenCalled();
});
it('swallows non-Error throws without throwing (string rejection path)', () => {
readdirSyncMock.mockImplementation(() => { throw 'nope'; });
expect(() => cleanupOldBackups(7, NOW)).not.toThrow();
it('swallows storage list errors without throwing', async () => {
const storage = {
list: vi.fn(() => { throw new Error('ENOENT'); }),
delete: vi.fn(async () => {}),
} as unknown as StorageService;
await expect(cleanupOldBackups(storage, 7, NOW)).resolves.toBeUndefined();
});
it('swallows delete failures without throwing (mirror replica or fs error)', async () => {
const storage = storageWith([{ key: isoFilename(30) }]);
(storage.delete as Mock).mockRejectedValue(new Error('EACCES'));
await expect(cleanupOldBackups(storage, 7, NOW)).resolves.toBeUndefined();
});
it('swallows non-Error throws without throwing (string rejection path)', async () => {
const storage = {
list: vi.fn(() => { throw 'nope'; }),
delete: vi.fn(async () => {}),
} as unknown as StorageService;
await expect(cleanupOldBackups(storage, 7, NOW)).resolves.toBeUndefined();
});
});