refactor(server): move the auto-backup cron into the backup domain

This commit is contained in:
jubnl
2026-08-10 21:33:48 +02:00
parent 399bbda0fa
commit c63d6430af
14 changed files with 406 additions and 312 deletions
-3
View File
@@ -9,7 +9,6 @@ import fs from 'node:fs';
import http from 'node:http';
import type { INestApplication } from '@nestjs/common';
import { buildApp } from './bootstrap';
import { BackupService } from './nest/backup/backup.service';
import { PlacePhotoCacheService } from './nest/place-photos/place-photo-cache.service';
import { AirtrailSyncService } from './nest/integrations/airtrail-sync.service';
@@ -94,7 +93,6 @@ const onListen = () => {
// handed them here, from the app buildApp() already initialised, rather than
// reaching for src/services at call time.
scheduler.setSchedulerDeps({
backups: nestApp.get(BackupService),
// The container singleton, not a fresh instance: the in-flight dedup and the
// known-on-disk set only work if the whole process shares one.
placePhotos: nestApp.get(PlacePhotoCacheService),
@@ -103,7 +101,6 @@ const onListen = () => {
// belongs at boot.
airtrail: nestApp.get(AirtrailSyncService),
});
scheduler.start();
scheduler.startTripReminders();
scheduler.startTodoReminders();
scheduler.startVersionCheck();
+84
View File
@@ -0,0 +1,84 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
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 { parseAutoBackupBody } from './backup.impl';
import {
buildCronExpression,
cleanupOldBackups,
loadSettings,
saveSettings,
type BackupSettings,
} from './auto-backup.settings';
/**
* The auto-backup cron, in the domain that owns it (moved from
* src/scheduler.ts). The job is dynamic: its expression comes from
* data/backup-settings.json, so saving new settings re-arms it via start() —
* the same method onApplicationBootstrap uses, replacing the old
* scheduler.start() restart that backup.impl reached out of the container for.
*/
@Injectable()
export class AutoBackupJob implements OnApplicationBootstrap {
constructor(
private readonly backup: BackupService,
private readonly registrar: CronRegistrarService,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled()) return;
this.start();
}
/** (Re)arm the cron from the settings file — also the restart path after a settings save. */
start(): void {
const settings = loadSettings();
if (!settings.enabled) {
this.registrar.unregister('auto-backup');
logInfo('Auto-Backup disabled');
return;
}
const expression = buildCronExpression(settings);
const tz = readEnv().app.tz || 'UTC';
const armed = this.registrar.register('auto-backup', expression, () => this.runBackup());
if (armed) {
logInfo(`Auto-Backup scheduled: ${settings.interval} (${expression}), tz: ${tz}, retention: ${settings.keep_days === 0 ? 'forever' : settings.keep_days + ' days'}`);
}
}
async runBackup(): Promise<void> {
try {
// Same archive the admin panel builds, only under the auto-backup name: it
// snapshots travel.db with VACUUM INTO instead of archiving the live file
// (the archiver reads its entries during finalize, so a WAL auto-checkpoint
// landing in between tears the copy), and it carries .encryption_key and the
// plugin trees — without the key a scheduled backup cannot be decrypted on
// another install.
const { filename } = await this.backup.createBackup('auto-backup');
logInfo(`Auto-Backup created: ${filename}`);
} catch (err: unknown) {
// createBackup removes its own half-written zip before rethrowing.
logError(`Auto-Backup: ${err instanceof Error ? err.message : err}`);
return;
}
const settings = loadSettings();
if (settings.keep_days > 0) {
cleanupOldBackups(settings.keep_days);
}
}
getAutoSettings(): { settings: BackupSettings; timezone: string } {
const tz = readEnv().app.tz || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
return { settings: loadSettings(), timezone: tz };
}
updateAutoSettings(body: Record<string, unknown>): BackupSettings {
const settings = parseAutoBackupBody(body);
saveSettings(settings);
this.start();
return settings;
}
}
@@ -0,0 +1,88 @@
import path from 'node:path';
import fs from 'node:fs';
import { logInfo, logError } from '../audit/audit-log.logger';
/**
* 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.
*/
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'];
const VALID_DAYS_OF_WEEK = new Set([0, 1, 2, 3, 4, 5, 6]); // 0=Sunday
const VALID_HOURS = new Set(Array.from({ length: 24 }, (_, i) => i));
export interface BackupSettings {
enabled: boolean;
interval: string;
keep_days: number;
hour: number;
day_of_week: number;
day_of_month: number;
}
export function buildCronExpression(settings: BackupSettings): string {
const hour = VALID_HOURS.has(settings.hour) ? settings.hour : 2;
const dow = VALID_DAYS_OF_WEEK.has(settings.day_of_week) ? settings.day_of_week : 0;
const dom = settings.day_of_month >= 1 && settings.day_of_month <= 28 ? settings.day_of_month : 1;
switch (settings.interval) {
case 'hourly': return '0 * * * *';
case 'daily': return `0 ${hour} * * *`;
case 'weekly': return `0 ${hour} * * ${dow}`;
case 'monthly': return `0 ${hour} ${dom} * *`;
default: return `0 ${hour} * * *`;
}
}
function getDefaults(): BackupSettings {
return { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 };
}
export function loadSettings(): BackupSettings {
let settings = getDefaults();
try {
if (fs.existsSync(settingsFile)) {
const saved = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
settings = { ...settings, ...saved };
}
} catch {
/* corrupt settings file — fall back to the defaults */
}
return settings;
}
export function saveSettings(settings: BackupSettings): void {
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2));
}
function autoBackupTimestampMs(filename: string): number | null {
// auto-backup-2026-04-27T00-00-00.zip → 2026-04-27T00:00:00
const stamp = filename.slice('auto-backup-'.length, -'.zip'.length);
const iso = stamp.replace(/T(\d{2})-(\d{2})-(\d{2})$/, 'T$1:$2:$3');
const ms = Date.parse(iso);
return Number.isNaN(ms) ? null : ms;
}
export function cleanupOldBackups(keepDays: number, now: number = Date.now()): 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;
if (ageMs < cutoff) {
fs.unlinkSync(filePath);
logInfo(`Auto-Backup old backup deleted: ${file}`);
}
}
} catch (err: unknown) {
logError(`Auto-Backup cleanup: ${err instanceof Error ? err.message : err}`);
}
}
+8 -3
View File
@@ -20,6 +20,7 @@ import fs from 'fs';
import { readEnv } from '../../app-config';
import type { User } from '../../types';
import { BackupService } from './backup.service';
import { AutoBackupJob } from './auto-backup.job';
import { JwtAuthGuard } from '../auth/jwt-auth.guard';
import { AdminGuard } from '../auth/admin.guard';
import { CurrentUser } from '../auth/current-user.decorator';
@@ -49,7 +50,11 @@ const UPLOAD = {
@Controller('api/backup')
@UseGuards(JwtAuthGuard, AdminGuard)
export class BackupController {
constructor(private readonly backup: BackupService, private readonly audit: AuditService) {}
constructor(
private readonly backup: BackupService,
private readonly audit: AuditService,
private readonly autoBackup: AutoBackupJob,
) {}
@Get('list')
list() {
@@ -135,7 +140,7 @@ export class BackupController {
@Get('auto-settings')
autoSettings() {
try {
return this.backup.getAutoSettings();
return this.autoBackup.getAutoSettings();
} catch (err) {
console.error('[backup] GET auto-settings:', err);
throw new HttpException({ error: 'Could not load backup settings' }, 500);
@@ -145,7 +150,7 @@ export class BackupController {
@Put('auto-settings')
updateAutoSettings(@CurrentUser() user: User, @Body() body: AutoBackupSettingsDto, @Req() req: Request) {
try {
const settings = this.backup.updateAutoSettings(body || {});
const settings = this.autoBackup.updateAutoSettings(body || {});
this.audit.writeAudit({ userId: user.id, action: 'backup.auto_settings', ip: getClientIp(req), details: { enabled: settings.enabled, interval: settings.interval, keep_days: settings.keep_days } });
return { settings };
} catch (err) {
+3 -19
View File
@@ -5,7 +5,7 @@ import { readEnv } from '../../app-config';
import fs from 'fs';
import Database from 'better-sqlite3';
import { db, closeDb, reinitialize } from '../../db/database';
import * as scheduler from '../../scheduler';
import { VALID_INTERVALS } from './auto-backup.settings';
import { invalidatePermissionsCache } from '../permissions/permissions.bridge';
import { pluginsCodeRoot, pluginsDataRoot } from '../plugins/paths';
import { stageExtractedPluginTrees, applyStagedRestoreNow } from '../plugins/plugin-backup';
@@ -66,7 +66,7 @@ export function parseAutoBackupBody(body: Record<string, unknown>): {
const enabled = body.enabled === true || body.enabled === 'true' || body.enabled === 1;
const rawInterval = body.interval;
const interval =
typeof rawInterval === 'string' && scheduler.VALID_INTERVALS.includes(rawInterval)
typeof rawInterval === 'string' && VALID_INTERVALS.includes(rawInterval)
? rawInterval
: 'daily';
const keep_days = Math.max(0, parseIntField(body.keep_days, 7));
@@ -146,7 +146,7 @@ export function listBackups(): BackupInfo[] {
/**
* Writes a full backup zip and returns its BackupInfo.
*
* `prefix` picks the filename scheme. The scheduler passes 'auto-backup' because
* `prefix` picks the filename scheme. AutoBackupJob passes 'auto-backup' because
* everything downstream tells the two apart by name: cleanupOldBackups() prunes
* only auto-backup-*.zip, and the admin panel badges them as automatic. Manual
* backups keep the default.
@@ -478,22 +478,6 @@ export async function restoreFromZip(zipPath: string): Promise<RestoreResult> {
}
}
// ---------------------------------------------------------------------------
// Auto-backup settings
// ---------------------------------------------------------------------------
export function getAutoSettings(): { settings: ReturnType<typeof scheduler.loadSettings>; timezone: string } {
const tz = readEnv().app.tz || Intl.DateTimeFormat().resolvedOptions().timeZone || 'UTC';
return { settings: scheduler.loadSettings(), timezone: tz };
}
export function updateAutoSettings(body: Record<string, unknown>): ReturnType<typeof parseAutoBackupBody> {
const settings = parseAutoBackupBody(body);
scheduler.saveSettings(settings);
scheduler.start();
return settings;
}
// ---------------------------------------------------------------------------
// Delete backup
// ---------------------------------------------------------------------------
+4 -2
View File
@@ -1,11 +1,13 @@
import { Module } from '@nestjs/common';
import { BackupController } from './backup.controller';
import { BackupService } from './backup.service';
import { AutoBackupJob } from './auto-backup.job';
import { AuditModule } from '../audit/audit.module';
import { SchedulingModule } from '../scheduling/scheduling.module';
@Module({
imports: [AuditModule],
imports: [AuditModule, SchedulingModule],
controllers: [BackupController],
providers: [BackupService],
providers: [BackupService, AutoBackupJob],
})
export class BackupModule {}
-2
View File
@@ -16,8 +16,6 @@ export class BackupService {
listBackups() { return svc.listBackups(); }
createBackup(prefix?: 'backup' | 'auto-backup') { return svc.createBackup(prefix); }
restoreFromZip(zipPath: string) { return svc.restoreFromZip(zipPath); }
getAutoSettings() { return svc.getAutoSettings(); }
updateAutoSettings(body: Record<string, unknown>) { return svc.updateAutoSettings(body); }
deleteBackup(filename: string) { return svc.deleteBackup(filename); }
isValidBackupFilename(filename: string) { return svc.isValidBackupFilename(filename); }
+5 -133
View File
@@ -1,78 +1,20 @@
import cron, { type ScheduledTask } from 'node-cron';
import { readEnv } from './app-config';
import path from 'node:path';
import fs from 'node:fs';
import { logInfo, logError } from './nest/audit/audit-log.logger';
const dataDir = path.join(__dirname, '../data');
const backupsDir = path.join(dataDir, 'backups');
const settingsFile = path.join(dataDir, 'backup-settings.json');
const VALID_INTERVALS = ['hourly', 'daily', 'weekly', 'monthly'];
const VALID_DAYS_OF_WEEK = new Set([0, 1, 2, 3, 4, 5, 6]); // 0=Sunday
const VALID_HOURS = new Set(Array.from({length: 24}, (_, i) => i));
interface BackupSettings {
enabled: boolean;
interval: string;
keep_days: number;
hour: number;
day_of_week: number;
day_of_month: number;
}
export function buildCronExpression(settings: BackupSettings): string {
const hour = VALID_HOURS.has(settings.hour) ? settings.hour : 2;
const dow = VALID_DAYS_OF_WEEK.has(settings.day_of_week) ? settings.day_of_week : 0;
const dom = settings.day_of_month >= 1 && settings.day_of_month <= 28 ? settings.day_of_month : 1;
switch (settings.interval) {
case 'hourly': return '0 * * * *';
case 'daily': return `0 ${hour} * * *`;
case 'weekly': return `0 ${hour} * * ${dow}`;
case 'monthly': return `0 ${hour} ${dom} * *`;
default: return `0 ${hour} * * *`;
}
}
let currentTask: ScheduledTask | null = null;
function getDefaults(): BackupSettings {
return { enabled: false, interval: 'daily', keep_days: 7, hour: 2, day_of_week: 0, day_of_month: 1 };
}
function loadSettings(): BackupSettings {
let settings = getDefaults();
try {
if (fs.existsSync(settingsFile)) {
const saved = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
settings = { ...settings, ...saved };
}
} catch (e) {}
return settings;
}
function saveSettings(settings: BackupSettings): void {
if (!fs.existsSync(dataDir)) fs.mkdirSync(dataDir, { recursive: true });
fs.writeFileSync(settingsFile, JSON.stringify(settings, null, 2));
}
/**
* What the scheduler needs from the Nest container.
*
* The shapes are structural on purpose: the scheduler names the capability it
* wants, never the provider class. Importing BackupService here would drag in
* src/nest/backup → src/nest/backup/backup.impl → src/scheduler and put the
* cycle straight back — the same cycle the lazy `await import()` in runBackup
* existed to dodge.
* wants, never the provider class — importing a provider class here would pull
* its module graph into a file that must stay loadable without a container
* (which is what the unit tests rely on).
*
* index.ts fills this in from the container after buildApp(), the way
* bootstrap.ts hands the /mcp handler its registry. Nothing here is resolved at
* import time, so the scheduler stays loadable without a container (which is
* what its unit tests rely on).
* import time.
*/
export interface SchedulerDeps {
backups: { createBackup(prefix?: 'backup' | 'auto-backup'): Promise<{ filename: string }> };
placePhotos: { sweepOrphans(): number };
airtrail: { runAirtrailSync(): Promise<void> };
}
@@ -84,75 +26,6 @@ export function setSchedulerDeps(next: SchedulerDeps): void {
deps = next;
}
async function runBackup(): Promise<void> {
try {
// Same archive the admin panel builds, only under the auto-backup name: it
// snapshots travel.db with VACUUM INTO instead of archiving the live file
// (the archiver reads its entries during finalize, so a WAL auto-checkpoint
// landing in between tears the copy), and it carries .encryption_key and the
// plugin trees — without the key a scheduled backup cannot be decrypted on
// another install.
if (!deps) {
logError('Auto-Backup: skipped, the scheduler was started without its container dependencies');
return;
}
const { filename } = await deps.backups.createBackup('auto-backup');
logInfo(`Auto-Backup created: ${filename}`);
} catch (err: unknown) {
// createBackup removes its own half-written zip before rethrowing.
logError(`Auto-Backup: ${err instanceof Error ? err.message : err}`);
return;
}
const settings = loadSettings();
if (settings.keep_days > 0) {
cleanupOldBackups(settings.keep_days);
}
}
function autoBackupTimestampMs(filename: string): number | null {
// auto-backup-2026-04-27T00-00-00.zip → 2026-04-27T00:00:00
const stamp = filename.slice('auto-backup-'.length, -'.zip'.length);
const iso = stamp.replace(/T(\d{2})-(\d{2})-(\d{2})$/, 'T$1:$2:$3');
const ms = Date.parse(iso);
return Number.isNaN(ms) ? null : ms;
}
export function cleanupOldBackups(keepDays: number, now: number = Date.now()): 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;
if (ageMs < cutoff) {
fs.unlinkSync(filePath);
logInfo(`Auto-Backup old backup deleted: ${file}`);
}
}
} catch (err: unknown) {
logError(`Auto-Backup cleanup: ${err instanceof Error ? err.message : err}`);
}
}
function start(): void {
if (currentTask) {
currentTask.stop();
currentTask = null;
}
const settings = loadSettings();
if (!settings.enabled) {
logInfo('Auto-Backup disabled');
return;
}
const expression = buildCronExpression(settings);
const tz = readEnv().app.tz || 'UTC';
currentTask = cron.schedule(expression, runBackup, { timezone: tz });
logInfo(`Auto-Backup scheduled: ${settings.interval} (${expression}), tz: ${tz}, retention: ${settings.keep_days === 0 ? 'forever' : settings.keep_days + ' days'}`);
}
// Demo mode: hourly reset of demo user data
let demoTask: ScheduledTask | null = null;
@@ -447,7 +320,6 @@ function startAirTrailSync(): void {
}
function stop(): void {
if (currentTask) { currentTask.stop(); currentTask = null; }
if (demoTask) { demoTask.stop(); demoTask = null; }
if (reminderTask) { reminderTask.stop(); reminderTask = null; }
if (versionCheckTask) { versionCheckTask.stop(); versionCheckTask = null; }
@@ -457,4 +329,4 @@ function stop(): void {
if (airtrailSyncTask) { airtrailSyncTask.stop(); airtrailSyncTask = null; }
}
export { start, stop, startDemoReset, startTripReminders, startTodoReminders, startVersionCheck, startIdempotencyCleanup, purgeExpiredIdempotencyKeys, startTrekPhotoCacheCleanup, startPlacePhotoCacheCleanup, startAirTrailSync, loadSettings, saveSettings, VALID_INTERVALS };
export { stop, startDemoReset, startTripReminders, startTodoReminders, startVersionCheck, startIdempotencyCleanup, purgeExpiredIdempotencyKeys, startTrekPhotoCacheCleanup, startPlacePhotoCacheCleanup, startAirTrailSync };