refactor(backup): create backup through per-category storage enumeration

This commit is contained in:
jubnl
2026-08-17 07:13:15 +02:00
parent e4109db9f6
commit 4b8c6013a6
4 changed files with 213 additions and 271 deletions
+48 -42
View File
@@ -38,10 +38,6 @@ export const MAX_BACKUP_DECOMPRESSED_SIZE = backupEnv.maxDecompressedMb * 1024 *
// Helpers
// ---------------------------------------------------------------------------
export function ensureBackupsDir(): void {
if (!fs.existsSync(backupsDir)) fs.mkdirSync(backupsDir, { recursive: true });
}
export function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
@@ -156,6 +152,11 @@ export async function listBackups(storage: StorageService): Promise<BackupInfo[]
// Create backup
// ---------------------------------------------------------------------------
/** The categories a backup archives — everything else under uploads/ is a
* re-derivable cache (photos-google, photos-trek) or not uploads at all
* (backups). Restore's rehydration walks the same list. */
export const BACKUP_UPLOAD_CATEGORIES = ['files', 'journey', 'covers', 'avatars', 'places', 'photos'] as const;
/**
* Writes a full backup zip and returns its BackupInfo.
*
@@ -164,23 +165,44 @@ export async function listBackups(storage: StorageService): Promise<BackupInfo[]
* only auto-backup-*.zip, and the admin panel badges them as automatic. Manual
* backups keep the default.
*/
export async function createBackup(prefix: 'backup' | 'auto-backup' = 'backup'): Promise<BackupInfo> {
ensureBackupsDir();
export async function createBackup(storage: StorageService, prefix: 'backup' | 'auto-backup' = 'backup'): Promise<BackupInfo> {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const filename = `${prefix}-${timestamp}.zip`;
const outputPath = path.join(backupsDir, filename);
// The scratch names carry the prefix too: a scheduled run and a manual one that
// start in the same second would otherwise share a snapshot path, and the first
// to finish would delete the other's staging copy mid-archive.
const pdataSnap = path.join(backupsDir, `.plugins-snap-${prefix}-${timestamp}`);
const dbSnap = path.join(backupsDir, `.travel-snap-${prefix}-${timestamp}.db`);
// All staging lives in the backups backend's own spool: same volume as the
// destination (the put commit stays an atomic rename) and crash leftovers are
// reaped by LocalDriver's boot spool-cleanup. The scratch names carry the
// prefix too: a scheduled run and a manual one that start in the same second
// would otherwise share a snapshot path, and the first to finish would delete
// the other's staging copy mid-archive.
const spoolDir = storage.spoolDirFor('backups');
const zipSpool = path.join(spoolDir, `zip-build-${prefix}-${timestamp}`);
const pdataSnap = path.join(spoolDir, `plugins-snap-${prefix}-${timestamp}`);
const dbSnap = path.join(spoolDir, `travel-snap-${prefix}-${timestamp}.db`);
try {
try { db.exec('PRAGMA wal_checkpoint(TRUNCATE)'); } catch (e) {}
// Enumerate the archived categories up front (the archiver reads entries
// lazily during finalize(), so the promise executor below must stay
// synchronous). Everything NOT in BACKUP_UPLOAD_CATEGORIES is excluded by
// construction: the re-derivable caches (photos-google in both
// TREK_PLACE_PHOTO_DIR modes, photos-trek) and backups itself are never
// enumerated, which is what makes the same-dir-misconfig guard (#1358)
// structural instead of pattern-based.
const uploadEntries: { absPath: string; name: string }[] = [];
for (const category of BACKUP_UPLOAD_CATEGORIES) {
for await (const obj of storage.list(category)) {
// In mode A the google/trek caches nest under the photos/ prefix — the
// category walk would sweep them back in without this skip.
if (category === 'photos' && (obj.key.startsWith('google/') || obj.key.startsWith('trek/'))) continue;
await storage.withLocalFile(category, obj.key, async (absPath) => {
uploadEntries.push({ absPath, name: `uploads/${category}/${obj.key}` });
});
}
}
await new Promise<void>((resolve, reject) => {
const output = fs.createWriteStream(outputPath);
const output = fs.createWriteStream(zipSpool);
const archive = archiver('zip', { zlib: { level: 9 } });
output.on('close', resolve);
@@ -218,28 +240,7 @@ export async function createBackup(prefix: 'backup' | 'auto-backup' = 'backup'):
archive.file(encKeyPath, { name: '.encryption_key' });
}
if (fs.existsSync(uploadsDir)) {
// Exclude the place-photo and trek-memory caches: both are re-derivable
// (re-fetched on demand, keyed on stable ids) and would otherwise dominate
// backup size. Restores self-heal — the cache dirs are recreated at startup.
//
// Also exclude backups/ and restore-*/: these live under data/, not uploads/,
// but when an install maps data and uploads to the SAME directory (a
// misconfiguration, but a catastrophic one) the glob would otherwise sweep
// every prior backup zip into the new archive — each run embedding all
// previous runs, so size compounds without bound (see issue #1358). Ignoring
// them keeps the backup bounded regardless of how the volumes are mounted.
archive.glob(
'**/*',
{
cwd: uploadsDir,
ignore: ['photos/google/**', 'photos/trek/**', 'backups/**', 'restore-*/**'],
nodir: true,
dot: true,
},
{ prefix: 'uploads' },
);
}
for (const entry of uploadEntries) archive.file(entry.absPath, { name: entry.name });
// Plugin data — each plugin's own SQLite file and any blobs. This is the ONLY
// copy of the user data a plugin holds, so it belongs in the backup. Checkpoint
@@ -275,21 +276,26 @@ export async function createBackup(prefix: 'backup' | 'auto-backup' = 'backup'):
archive.finalize();
});
const stat = fs.statSync(outputPath);
// The commit — and, under a mirror backend, the replica fan-out point.
await storage.put('backups', filename, { tmpPath: zipSpool });
const stat = await storage.stat('backups', filename);
if (!stat) throw new Error(`Backup vanished after commit: ${filename}`);
return {
filename,
size: stat.size,
sizeText: formatSize(stat.size),
created_at: stat.birthtime.toISOString(),
created_at: new Date(stat.mtimeMs).toISOString(),
};
} catch (err: unknown) {
console.error('Backup error:', err);
if (fs.existsSync(outputPath)) fs.unlinkSync(outputPath);
throw err;
} finally {
// The snapshots were staging copies for the archiver only; drop them once streaming is
// done (the await above resolves on the output stream's 'close', so the archive is
// complete).
// put commits by rename, so on success the zip spool file is already gone;
// on failure these clean the half-built staging. The destination needs no
// unlink anymore — nothing lands there until put succeeds. (The await on
// the build promise resolves on the output stream's 'close', so the
// snapshots are no longer being read.)
fs.rmSync(zipSpool, { force: true });
fs.rmSync(pdataSnap, { recursive: true, force: true });
fs.rmSync(dbSnap, { force: true });
}
+1 -1
View File
@@ -18,7 +18,7 @@ export class BackupService {
constructor(private readonly storage: StorageService) {}
listBackups() { return svc.listBackups(this.storage); }
createBackup(prefix?: 'backup' | 'auto-backup') { return svc.createBackup(prefix); }
createBackup(prefix?: 'backup' | 'auto-backup') { return svc.createBackup(this.storage, prefix); }
restoreFromZip(zipPath: string) { return svc.restoreFromZip(zipPath); }
deleteBackup(filename: string) { return svc.deleteBackup(this.storage, filename); }
+29 -6
View File
@@ -65,10 +65,29 @@ import path from 'node:path';
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
import { createBackup } from '../../src/nest/backup/backup.impl';
import type { BackupService } from '../../src/nest/backup/backup.service';
import type { StorageService } from '../../src/nest/storage/storage.service';
import type { CronRegistrarService } from '../../src/nest/scheduling/cron-registrar.service';
const liveDb = path.join(__dirname, '../../data', 'travel.db');
// createBackup receives StorageService as a parameter (BackupService injects
// it). fs is mocked wholesale here, so a plain stub stands in for the backups
// backend: staging under /stub/spool, empty category listings, put/stat succeed.
const storageStub = vi.hoisted(() => ({}) as Record<string, unknown>);
function resetStorageStub() {
Object.assign(storageStub, {
spoolDirFor: vi.fn(() => '/stub/spool'),
tempDir: vi.fn(() => '/stub/tmp'),
list: vi.fn(async function* () {}),
withLocalFile: vi.fn(async (_c: string, _k: string, fn: (p: string) => Promise<unknown>) => fn('/stub/local/path')),
put: vi.fn(async () => {}),
stat: vi.fn(async (_c: string, key: string) => ({ key, size: 4096, mtimeMs: Date.parse('2026-04-27T02:00:00Z') })),
exists: vi.fn(async () => true),
delete: vi.fn(async () => {}),
});
}
resetStorageStub();
interface Registered {
name: string;
expr: string;
@@ -88,8 +107,9 @@ function makeJob() {
};
const job = new AutoBackupJob(
// The same wiring the container does, with the real service function behind
// it — the run below is still the production code path.
{ createBackup } as unknown as BackupService,
// it — the run below is still the production code path. The forward mirrors
// 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,
);
return { job, registered, registrar };
@@ -140,7 +160,7 @@ describe('auto-backup run', () => {
expect(dbMock.db.exec).toHaveBeenCalledWith(expect.stringContaining('VACUUM INTO'));
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('.travel-snap-auto-backup-');
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
});
@@ -178,9 +198,12 @@ describe('auto-backup run', () => {
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: disk full');
expect(logMock.logInfo).not.toHaveBeenCalledWith(expect.stringContaining('Auto-Backup created'));
expect(fsMock.unlinkSync).toHaveBeenCalledWith(expect.stringContaining('auto-backup-'));
// the snapshot scratch file is cleaned up too, and retention never runs
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('.travel-snap-auto-backup-'), { force: true });
// nothing was committed (put commits by rename only on success); the
// half-built zip spool and snapshot scratch are cleaned up, and retention
// never runs
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();
});
});
+135 -222
View File
@@ -321,244 +321,198 @@ describe('BACKUP-036 createBackup', () => {
vi.clearAllMocks();
});
it('BACKUP-036a — happy path: creates zip and returns BackupInfo', async () => {
// Set up fs mocks
fsMock.existsSync.mockImplementation((p: string) => {
// backupsDir exists, dbPath does not (skip DB file), uploadsDir does not exist
return false;
});
fsMock.mkdirSync.mockReturnValue(undefined);
// Mock WriteStream with event emitter behaviour
/** Wires the write-stream + archiver mocks so finalize() resolves the build. */
function setupArchiveSuccess() {
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
// Mock archiver instance
archiverInstanceMock.on.mockImplementation((event: string, cb: Function) => {
// noop — no error
});
fsMock.createWriteStream.mockReturnValue({
on: vi.fn((event: string, cb: Function) => { writableEvents[event] = cb; }),
} as never);
archiverInstanceMock.on.mockImplementation(() => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
// Trigger 'close' on the output stream to resolve the Promise
if (writableEvents['close']) writableEvents['close']();
});
archiverInstanceMock.finalize.mockImplementation(() => { writableEvents['close']?.(); });
archiverMock.mockReturnValue(archiverInstanceMock);
return writableEvents;
}
fsMock.statSync.mockReturnValue({ size: 2048, birthtime: new Date('2026-04-06T12:00:00Z') });
/** storage.stat stub for the post-put BackupInfo read. */
const statOf = (size: number, mtimeMs = Date.parse('2026-04-06T12:00:00Z')) =>
vi.fn(async (_c: string, key: string) => ({ key, size, mtimeMs }));
const result = await createBackup();
/** storage.list stub keyed by category. */
const listByCategory = (map: Record<string, Array<{ key: string; size?: number; mtimeMs?: number }>>) =>
vi.fn((category: string) =>
(async function* () {
for (const e of map[category] ?? []) yield { size: 1, mtimeMs: 0, ...e };
})(),
);
it('BACKUP-036a — happy path: builds in the backups spool, commits via put, returns BackupInfo', async () => {
// No travel.db, no enc key, no plugin roots.
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(2048) });
const result = await createBackup(storage);
expect(result).toHaveProperty('filename');
expect(result.filename).toMatch(/^backup-.*\.zip$/);
expect(result.size).toBe(2048);
expect(result.sizeText).toBe('2.0 KB');
expect(result).toHaveProperty('created_at');
expect(result.created_at).toBe('2026-04-06T12:00:00.000Z');
expect(archiverMock).toHaveBeenCalledWith('zip', { zlib: { level: 9 } });
expect(archiverInstanceMock.pipe).toHaveBeenCalled();
expect(archiverInstanceMock.finalize).toHaveBeenCalled();
// The zip is built in the backups backend's spool, then committed via put.
expect(fsMock.createWriteStream).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/zip-build-backup-'));
expect(storage.put).toHaveBeenCalledWith('backups', result.filename, {
tmpPath: expect.stringContaining('/stub/spool/zip-build-backup-'),
});
expect(storage.stat).toHaveBeenCalledWith('backups', result.filename);
});
it('BACKUP-036j — archives category objects under the legacy uploads/ entry names via withLocalFile', async () => {
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
const storage = stubStorage({
stat: statOf(1024),
list: listByCategory({
files: [{ key: 'a.pdf' }],
journey: [{ key: 'thumbs/x.jpg' }],
}),
});
await createBackup(storage);
expect(storage.withLocalFile).toHaveBeenCalledWith('files', 'a.pdf', expect.any(Function));
expect(storage.withLocalFile).toHaveBeenCalledWith('journey', 'thumbs/x.jpg', expect.any(Function));
expect(archiverInstanceMock.file).toHaveBeenCalledWith('/stub/local/path', { name: 'uploads/files/a.pdf' });
expect(archiverInstanceMock.file).toHaveBeenCalledWith('/stub/local/path', { name: 'uploads/journey/thumbs/x.jpg' });
});
it('BACKUP-036m — a mirror replica failure surfaced via health never fails the request', async () => {
// Mirror semantics: put succeeds against the primary; replica failures are
// recorded on health(), not thrown. createBackup must still return its info.
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
const storage = stubStorage({
stat: statOf(1024),
health: vi.fn(() => ({ replicaFailures: [{ backend: 'nas-backups', key: 'backup-x.zip', error: 'EIO' }] })),
});
const result = await createBackup(storage);
expect(result.filename).toMatch(/^backup-.*\.zip$/);
expect(storage.put).toHaveBeenCalledOnce();
});
it('BACKUP-036p — archives the plugin data + code trees when present, skipping dev-links', async () => {
// Only the plugin roots exist (db/uploads absent → skipped).
fsMock.existsSync.mockImplementation((p: string) => String(p).includes('plugins'));
fsMock.mkdirSync.mockReturnValue(undefined);
// Two plugin code dirs: 'notes' is real, 'devlink' resolves outside the root.
// The plugin-data snapshot reads with { withFileTypes: true }; hand it Dirent-likes there.
const dirent = (name: string) => ({ name, isDirectory: () => true });
fsMock.readdirSync.mockImplementation((_p: string, opts?: { withFileTypes?: boolean }) =>
(opts?.withFileTypes ? [dirent('notes'), dirent('devlink')] : ['notes', 'devlink']) as never);
fsMock.realpathSync.mockImplementation((p: string) => (String(p).endsWith('devlink') ? '/somewhere/else/devlink' : p));
fsMock.statSync.mockReturnValue({ size: 2048, birthtime: new Date('2026-04-06T12:00:00Z'), isDirectory: () => true } as never);
fsMock.statSync.mockReturnValue({ isDirectory: () => true } as never);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(2048) });
const writableEvents: Record<string, Function> = {};
fsMock.createWriteStream.mockReturnValue({ on: vi.fn((e: string, cb: Function) => { writableEvents[e] = cb; }) } as never);
archiverInstanceMock.on.mockImplementation(() => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => { writableEvents['close']?.(); });
archiverMock.mockReturnValue(archiverInstanceMock);
await createBackup();
await createBackup(storage);
// the consistent snapshot of the data tree is archived under plugins-data/
expect(archiverInstanceMock.directory).toHaveBeenCalledWith(expect.stringContaining('plugins-snap'), 'plugins-data');
// the real code dir is archived, the dev-link is skipped
expect(archiverInstanceMock.directory).toHaveBeenCalledWith(expect.stringContaining('notes'), 'plugins-code/notes');
expect(archiverInstanceMock.directory).not.toHaveBeenCalledWith(expect.anything(), 'plugins-code/devlink');
// the snapshot staging lives in the backups spool
expect(archiverInstanceMock.directory).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/plugins-snap-backup-'), 'plugins-data');
});
it('BACKUP-036b — WAL checkpoint error is swallowed (non-critical)', async () => {
// db.exec throws on WAL checkpoint
dbMock.db.exec.mockImplementationOnce(() => { throw new Error('WAL checkpoint failed'); });
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
fsMock.existsSync.mockReturnValue(false);
fsMock.mkdirSync.mockReturnValue(undefined);
archiverInstanceMock.on.mockImplementation((_event: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 512, birthtime: new Date('2026-04-06T12:00:00Z') });
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(512) });
// Should not throw even though WAL checkpoint failed
const result = await createBackup();
const result = await createBackup(storage);
expect(result).toHaveProperty('filename');
expect(result.size).toBe(512);
});
it('BACKUP-036c — archiver error cleans up partial file and re-throws', async () => {
it('BACKUP-036c — archiver error cleans up the spool staging, skips put and re-throws', async () => {
fsMock.existsSync.mockReturnValue(false);
fsMock.mkdirSync.mockReturnValue(undefined);
const writableEvents: Record<string, Function> = {};
const archiveEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
archiverInstanceMock.on.mockImplementation((event: string, cb: Function) => {
archiveEvents[event] = cb;
});
fsMock.createWriteStream.mockReturnValue({ on: vi.fn() } as never);
archiverInstanceMock.on.mockImplementation((event: string, cb: Function) => { archiveEvents[event] = cb; });
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
// Simulate archive error instead of success
if (archiveEvents['error']) archiveEvents['error'](new Error('disk full'));
archiveEvents['error']?.(new Error('disk full'));
});
archiverMock.mockReturnValue(archiverInstanceMock);
const storage = stubStorage();
// The output file "exists" after partial write so cleanup runs
fsMock.existsSync.mockImplementation((p: string) => {
// Return true only when checking the output path (ends with .zip)
return String(p).endsWith('.zip');
});
fsMock.unlinkSync.mockReturnValue(undefined);
await expect(createBackup(storage)).rejects.toThrow('disk full');
await expect(createBackup()).rejects.toThrow('disk full');
// Partial file should have been removed
expect(fsMock.unlinkSync).toHaveBeenCalled();
// Nothing is committed; the half-built spool file is removed in the finally.
expect(storage.put).not.toHaveBeenCalled();
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('zip-build-backup-'), { force: true });
});
it('BACKUP-036d — includes travel.db when it exists', async () => {
fsMock.existsSync.mockImplementation((p: string) => {
// backupsDir does not need to be created (exists), dbPath exists, no uploads
if (String(p).endsWith('travel.db')) return true;
return false;
});
fsMock.mkdirSync.mockReturnValue(undefined);
it('BACKUP-036d — includes travel.db when it exists, snapshotted into the spool', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db'));
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
await createBackup();
await createBackup(storage);
// the core DB is snapshotted (VACUUM INTO) and archived under the name travel.db
expect(dbMock.db.exec).toHaveBeenCalledWith(expect.stringContaining('VACUUM INTO'));
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.any(String),
expect.stringContaining('/stub/spool/travel-snap-backup-'),
{ name: 'travel.db' }
);
});
it('BACKUP-036e — includes uploads but excludes the re-derivable photo caches', async () => {
fsMock.existsSync.mockImplementation((p: string) => {
if (String(p).endsWith('uploads')) return true;
return false;
});
fsMock.mkdirSync.mockReturnValue(undefined);
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
it('BACKUP-036e — excludes the re-derivable photo caches nested under photos/', async () => {
// In mode A the google/trek caches live inside the photos/ prefix, so the
// category walk must skip them. (In mode B photos-google is a separate
// category that is simply never enumerated — no extra branch needed.)
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
const storage = stubStorage({
stat: statOf(1024),
list: listByCategory({
photos: [{ key: 'flat.jpg' }, { key: 'google/g.jpg' }, { key: 'trek/t.bin' }],
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
await createBackup(storage);
await createBackup();
expect(archiverInstanceMock.glob).toHaveBeenCalledWith(
'**/*',
expect.objectContaining({
cwd: expect.stringContaining('uploads'),
ignore: ['photos/google/**', 'photos/trek/**', 'backups/**', 'restore-*/**'],
}),
{ prefix: 'uploads' },
);
// The re-derivable caches must not be archived verbatim.
expect(archiverInstanceMock.directory).not.toHaveBeenCalled();
expect(archiverInstanceMock.file).toHaveBeenCalledWith('/stub/local/path', { name: 'uploads/photos/flat.jpg' });
const names = archiverInstanceMock.file.mock.calls.map(c => c[1]?.name as string);
expect(names.some(n => n?.includes('google/'))).toBe(false);
expect(names.some(n => n?.includes('trek/'))).toBe(false);
// Only the archived categories are ever listed — the excludes are structural.
expect(storage.withLocalFile).toHaveBeenCalledTimes(1);
});
it('BACKUP-036h — never sweeps backups/ or restore-* into the archive (issue #1358)', async () => {
// Regression guard: when data and uploads map to the same directory, the
// uploads glob would otherwise pick up the backups/ dir and recursively
// embed every prior backup zip, compounding size without bound.
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('uploads'));
fsMock.mkdirSync.mockReturnValue(undefined);
it('BACKUP-036h — only category prefixes are ever archived; backups/ and restore-* are structurally out (issue #1358)', async () => {
// The uploads/** glob is gone: even when data and uploads map to the same
// directory, enumeration only ever walks the six archived categories, so
// prior backup zips and restore-* staging can never be swept into the zip.
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
await createBackup(storage);
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
await createBackup();
const globCall = archiverInstanceMock.glob.mock.calls.at(-1);
const ignore: string[] = globCall?.[1]?.ignore ?? [];
expect(ignore).toContain('backups/**');
expect(ignore).toContain('restore-*/**');
expect(archiverInstanceMock.glob).not.toHaveBeenCalled();
const listed = (storage.list as ReturnType<typeof vi.fn>).mock.calls.map(c => c[0] as string);
expect(listed.sort()).toEqual(['avatars', 'covers', 'files', 'journey', 'photos', 'places']);
expect(listed).not.toContain('backups');
});
it('BACKUP-036f — bundles .encryption_key when present and ENCRYPTION_KEY env is unset', async () => {
@@ -566,26 +520,10 @@ describe('BACKUP-036 createBackup', () => {
delete process.env.ENCRYPTION_KEY;
try {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('.encryption_key'));
fsMock.mkdirSync.mockReturnValue(undefined);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
await createBackup();
await createBackup(storage);
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringContaining('.encryption_key'),
@@ -599,26 +537,10 @@ describe('BACKUP-036 createBackup', () => {
it('BACKUP-036g — does NOT bundle .encryption_key when ENCRYPTION_KEY env is set', async () => {
// setup.ts sets process.env.ENCRYPTION_KEY, so the env is the source of truth.
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('.encryption_key'));
fsMock.mkdirSync.mockReturnValue(undefined);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
const writableEvents: Record<string, Function> = {};
const fakeWriteStream = {
on: vi.fn((event: string, cb: Function) => {
writableEvents[event] = cb;
}),
};
fsMock.createWriteStream.mockReturnValue(fakeWriteStream);
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
await createBackup();
await createBackup(storage);
expect(archiverInstanceMock.file).not.toHaveBeenCalledWith(
expect.stringContaining('.encryption_key'),
@@ -630,28 +552,19 @@ describe('BACKUP-036 createBackup', () => {
// The scheduler passes 'auto-backup' so retention and the admin panel can
// still tell scheduled archives apart by filename.
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db'));
fsMock.mkdirSync.mockReturnValue(undefined);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
const writableEvents: Record<string, Function> = {};
fsMock.createWriteStream.mockReturnValue({
on: vi.fn((event: string, cb: Function) => { writableEvents[event] = cb; }),
} as never);
archiverInstanceMock.on.mockImplementation((_e: string, _cb: Function) => {});
archiverInstanceMock.pipe.mockReturnValue(undefined);
archiverInstanceMock.finalize.mockImplementation(() => {
if (writableEvents['close']) writableEvents['close']();
});
archiverMock.mockReturnValue(archiverInstanceMock);
fsMock.statSync.mockReturnValue({ size: 1024, birthtime: new Date('2026-04-06T12:00:00Z') });
const result = await createBackup('auto-backup');
const result = await createBackup(storage, 'auto-backup');
expect(result.filename).toMatch(/^auto-backup-.*\.zip$/);
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringContaining('.travel-snap-auto-backup-'),
expect.stringContaining('travel-snap-auto-backup-'),
{ name: 'travel.db' },
);
expect(storage.put).toHaveBeenCalledWith('backups', result.filename, {
tmpPath: expect.stringContaining('zip-build-auto-backup-'),
});
});
});