fix(backup): back up and restore through an injected database port

Backup, restore and the demo reset each handled the SQLite file
themselves: backup.impl closed and reinitialized the connection, built
MaintenanceRepository with new, and assumed the database was
data/travel.db. That tied the whole chain to one local file and hid two
bugs.

They now go through DATABASE_BACKUP, a port declared in the shared
database kernel (snapshot, verify, keep a copy before a restore, replace).
SqliteDatabaseBackup implements it with what the code did before:
VACUUM INTO for a consistent copy, and a close, copy, sidecar drop,
rename and reopen through DatabaseLifecycle for a restore. BackupService
injects it and hands it to backup.impl. The demo reset and the baseline
save use the same port; the first baseline is saved by DemoResetJob once
the app is up, because the boot-time seed runs before anything can be
injected. Another engine can plug in a logical dump behind the port.

Fixes on the way:

- The backup and the restore ignored TREK_DB_FILE. The backup looked for
  data/travel.db and, with the database elsewhere, silently left it out
  of the archive; the restore wrote data/travel.db and never replaced
  the live database. Both now use DatabaseLifecycle.file, the path the
  connection runs on, and the pre-restore copy sits next to it.
- A failed VACUUM INTO fell back to archiving the live WAL-mode file
  without a word, the torn copy the snapshot exists to prevent. The
  backup now fails: nothing is archived or committed, the existing
  backups are untouched, a partial snapshot is removed, and the log says
  why. A missing database file and a failed checkpoint are logged too.
This commit is contained in:
Maurice
2026-10-08 15:25:52 +02:00
parent 8ede0dab9e
commit 0aa5b36661
26 changed files with 1029 additions and 473 deletions
+1 -1
View File
@@ -42,7 +42,7 @@ Nest owns everything. Every domain is a DI module under `src/nest/<domain>/` (`c
- **Scheduling**: `src/nest/scheduling/` (`CronRegistrarService`) is the one way to schedule a cron. Jobs are `*.job.ts` providers in their owning domain. The registrar refuses to schedule under `NODE_ENV=test` (an integration test pins it). **Never use a `@Cron` decorator** — it bypasses that gate.
- **Plugins** (`src/nest/plugins/`): the child-process runtime (`supervisor/`, `runtime/plugin-host-entry.ts`, `protocol/envelope.ts`) is **intentionally not Nest** — it is the security boundary. `host/rpc-host.ts` registers an RPC method at spawn only if the plugin holds the unlocking permission (registration = authorization). Install-time gates live in `install/`; the manifest's `trek` version range fails closed, and `TREK_PLUGINS_IGNORE_TREK_RANGE` downgrades that to a warning. The protocol tables in `protocol/envelope.ts` (+ `src/plugin-event-sink.ts`) are **generated** into `plugin-sdk/` and `shared/` — run `gen:plugin-facts` after touching them and commit the output. `runtime/egress-policy.ts` is a hand-kept mirror guarded by a parity test in `plugin-sdk/`; change both sides together.
- **Storage**: `src/nest/storage/` is the upload driver abstraction (local / S3 / mirror behind one interface, with an admin surface and a usage job). Domain services never touch the filesystem or the S3 SDK directly.
- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and `reopen()` swaps in a new handle and migrates it. `DatabaseLifecycle.file` is the one resolved path (`TREK_DB_FILE` or `data/travel.db`). MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot; anything it cannot map refuses the boot. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
- **DB** (`src/db/`): `better-sqlite3`, WAL, FK on. `database.ts` only holds the connection and applies pragmas. It does not build a schema, and importing it opens nothing (the first reader does). The connection's lifecycle belongs to the `DatabaseLifecycle` provider (`nest/database/database-lifecycle.service.ts`): `buildApp()` opens it through `open()` (which binds the ORM to later swaps and runs the schema bootstrap below), the shutdown closes it through `close()`, and a restore or the demo reset swaps the file only through the database backup port, `DATABASE_BACKUP` (`nest/database/database-backup.interface.ts`; the SQLite implementation is `nest/backup/sqlite-database-backup.ts`: `VACUUM INTO` snapshot, close, atomic file swap, `reopen()`). The port works on `DatabaseLifecycle.file`, the one resolved path (`TREK_DB_FILE` or `data/travel.db`), and a snapshot that fails fails the backup rather than archiving the live file. `MaintenanceRepository` is a provider (`MaintenanceModule`), injected, never built with `new` in `src/`. MikroORM's migrations (`db/migrations/`) are the only schema source, **including for tests**: the hand-kept `schema.ts`/`migrations.ts`/`seeds.ts` builders and the parity test that guarded them are gone. Seeding is the MikroORM seeders in `db/seeders/`, applied by `db/orm.ts` from `buildApp()` before anything reads. An install the retired positional runner migrated (a `schema_version` row, no `mikro_orm_migrations` rows) is baselined by `db/legacy-baseline.ts`: the migrations whose `Legacy migration step N` docstring is ≤ its version are recorded as executed (never replayed) in the same transaction as the migrator run, while the baseline migration itself still runs first, as the legacy runner's `createTables()` did on every boot; anything it cannot map refuses the boot. Before a boot applies pending migrations to a file database that holds anything, `db/pre-migrate-snapshot.ts` writes a `VACUUM INTO` copy next to it (`pre-migrate-<schema>-<time>.db`, `<schema>` being `legacy-<schema_version>` or the last recorded migration's timestamp; the newest `TREK_DB_PRE_MIGRATE_SNAPSHOT_KEEP` stay) and the newer-database refusal names the matching copy; a copy that cannot be written refuses the boot unless `TREK_DB_PRE_MIGRATE_SNAPSHOT=false`. It is off under `NODE_ENV=test` unless a suite sets that variable to true, and a restore's re-bootstrap skips it (the archive is the copy). After the migrator, `db/email-case-index.ts` creates the case-insensitive unique index on `users.email` that its migration had to defer on an install holding two accounts whose emails differ only in case (flag `email_case_index_pending`). `db/orm-driver.ts` binds the ORM to that same connection instead of opening a second one — with `:memory:` under test, a second connection is a second, empty database. Every read and write goes through a repository in `db/repositories/` (each extends the shared `TrekRepository` base in `db/repositories/_shared/`, which validates the request context before delegating to MikroORM) and, for multi-statement writes, `UnitOfWork.transactional(...)` (`nest/database/unit-of-work.ts`, provided by the global `OrmModule`) — there is no `DatabaseService`/`DatabaseModule` to inject any more. Entrypoints outside an HTTP request — an MCP tool call, a plugin RPC dispatch, a WebSocket message, a cron job, boot-time seeding, a backup restore — open one explicitly with `withRequestContext()` (`nest/database/request-context.ts`), since only the pathless `mikroOrmRequestContext` middleware `buildApp()` mounts (with `@mikro-orm/nestjs`'s own `registerRequestContext` turned off in `app.module.ts`, UPLOADS-P16) forks an `EntityManager` per HTTP request. `NODE_ENV=test` ⇒ isolated `:memory:` DB per vitest worker, opened from a snapshot `tests/global-setup.ts` migrates once per run; `TREK_DB_FILE` ⇒ explicit file DB (Playwright harness).
## Rules for new code
@@ -16,12 +16,12 @@ import type { EntityManager } from '@mikro-orm/core';
* order) is the correct tool, not a shortcut around it.
*
* Provided through Nest DI by `MaintenanceModule` (`nest/database/`), a
* factory over the context-resolving global `EntityManager`; the readiness
* probe and `UserCleanupService` inject it. `backup.impl.ts` and
* `demo/demo-reset.ts` still build one over the request's EntityManager until
* they move behind an injected provider of their own. The class stays free of
* Nest decorators like every other file under `db/`, so a test can still
* build one over its own `EntityManager`.
* factory over the context-resolving global `EntityManager`; its consumers
* inject it: the readiness probe, `UserCleanupService` and the SQLite backup
* port (`SqliteDatabaseBackup`), which the backup, the restore and the demo
* reset all go through. The class stays free of Nest decorators like every
* other file under `db/`, so a test can still build one over its own
* `EntityManager`.
*/
export class MaintenanceRepository {
constructor(private readonly em: EntityManager) {}
@@ -45,13 +45,10 @@ export class MaintenanceRepository {
/**
* `PRAGMA wal_checkpoint(TRUNCATE)` — rendered text pinned, identical to
* the legacy `db.exec('PRAGMA wal_checkpoint(TRUNCATE)')` it replaces at
* three call sites: `backup.impl.ts#createBackup` (BK1), `demo-reset.ts`'s
* `resetDemoUser` (DMR3) and `saveBaseline` (DMR3's dup) — one shared
* method, three callers, not three near-duplicate raw statements. Flushes
* the WAL into the main db file before a snapshot/copy; every call site
* treats it as best-effort (wrapped in a swallowing try/catch by the
* caller), matching the legacy shape exactly.
* the legacy `db.exec('PRAGMA wal_checkpoint(TRUNCATE)')` it replaces.
* Reached through the backup port's `checkpoint()`, which the backup
* (BK1) and the demo reset (DMR3) call. Flushes the WAL into the main db
* file before a snapshot or a swap; every caller treats it as best effort.
*/
async walCheckpoint(): Promise<void> {
this.validateRequestContext();
@@ -61,7 +58,7 @@ export class MaintenanceRepository {
/**
* `` VACUUM INTO '<path>' `` — rendered text pinned, identical to the
* legacy `` db.exec(`VACUUM INTO '${dbSnap.replaceAll("'", "''")}'`) ``
* (BK2, `backup.impl.ts#createBackup`): single quotes in `path` are
* (BK2, reached through the backup port's `snapshot()`): single quotes in `path` are
* escaped by doubling, the same escaping the legacy statement used — a
* consistent point-in-time snapshot under concurrent writers, with no
* MikroORM/Kysely equivalent.
@@ -86,8 +83,8 @@ export class MaintenanceRepository {
* open `UnitOfWork.transactional(...)` (`deleteUserCompletely`'s
* transaction). `Connection#execute(query, params, method, ctx)`'s `ctx`
* defaults to the plain (non-transactional) Kysely client when omitted —
* `walCheckpoint`/`vacuumInto` always omit it because their two callers
* (`backup.impl.ts`, `demo-reset.ts`) never run inside a transaction, but
* `walCheckpoint`/`vacuumInto` always omit it because their callers
* (the backup port) never run inside a transaction, but
* omitting it here deadlocked: this repo's `better-sqlite3` connection is
* single-connection/single-writer, the open transaction holds it for its
* whole lifetime, and a bare `execute()` tries to check out that SAME
+40 -54
View File
@@ -2,29 +2,19 @@ import fs from 'fs';
import path from 'path';
import { RequestContext, type EntityManager } from '@mikro-orm/core';
import { readEnv } from '../app-config';
import { closeDb, getRawConnection, reinitialize } from '../db/database';
import { DemoRepository, type DemoAdminCredentialsRow, type DemoInstanceKeyRow } from '../db/repositories/DemoRepository';
import { MaintenanceRepository } from '../db/repositories/MaintenanceRepository';
import type { DatabaseBackupStrategy } from '../nest/database/database-backup.interface';
const dataDir = path.join(__dirname, '../../data');
const baselinePath = path.join(dataDir, 'travel-baseline.db');
// Where the live DB actually is. database.ts honours TREK_DB_FILE, so hardcoding
// data/travel.db here would copy the baseline over an unrelated file and leave
// the database we just closed untouched. The open connection knows its own path —
// read off the raw handle (the same accessor the ORM driver binds), not the `db`
// Proxy, and before `closeDb()` drops it.
function liveDbPath(): string {
return getRawConnection().name;
}
/**
* The active fork's `EntityManager`, resolved via `RequestContext.getEntityManager()`
* — the same static accessor MikroORM's own per-request middleware and
* `CronRegistrarService`'s `wrappedTick` populate. `demo-seed.ts` and this
* file are plain function modules, not Nest providers, so neither can take
* an `EntityManager` by constructor injection the way `DatabaseService`/
* `CronRegistrarService` do — this is their equivalent choke point. Throws
* an `EntityManager` by constructor injection the way `CronRegistrarService`
* does; this is their equivalent choke point. Throws
* its own clear error — never MikroORM's generic "global EntityManager"
* wording — matching `CronRegistrarService.runOnBoot`'s own fail-closed
* shape: a direct call to `resetDemoUser`/`saveBaseline`/`seedDemoData`
@@ -40,14 +30,21 @@ export function requireEntityManager(): EntityManager {
return em;
}
async function resetDemoUser(): Promise<void> {
/**
* Puts the live database back to the saved baseline, keeping the admin's
* credentials and the instance API keys from the current one.
*
* The database steps go through the backup port, the same one an admin restore
* uses: it knows where the live database is (so `TREK_DB_FILE` is honoured),
* closes the connection, swaps the baseline in atomically and reopens it.
*/
async function resetDemoUser(database: DatabaseBackupStrategy): Promise<void> {
if (!fs.existsSync(baselinePath)) {
console.log('[Demo Reset] No baseline found, skipping. Admin must save baseline first.');
return;
}
const dbPath = liveDbPath();
if (dbPath === ':memory:') {
if (!database.canSnapshot()) {
console.log('[Demo Reset] In-memory database, nothing to restore.');
return;
}
@@ -58,7 +55,6 @@ async function resetDemoUser(): Promise<void> {
// whole tick — since no swap has happened yet at this point.
const preSwapEm = requireEntityManager();
const demo = new DemoRepository(preSwapEm);
const maintenance = new MaintenanceRepository(preSwapEm);
// Save admin's current credentials and API keys (these should survive the reset)
// NOTE: different default than demo-seed (admin@trek.app) — pinned legacy quirk.
@@ -80,35 +76,27 @@ async function resetDemoUser(): Promise<void> {
console.error('[Demo Reset] Failed to read instance API keys:', e instanceof Error ? e.message : e);
}
// Flush WAL to main DB file. DMR3 — raw-by-nature exactly like backup's
// BK1, converted onto the SAME shared `MaintenanceRepository.walCheckpoint()`
// backup's own createBackup uses — it runs BEFORE the close/reopen below,
// so it never waits on R3's spike at all.
// Flush the WAL into the main file before the connection closes. Best effort.
try {
await maintenance.walCheckpoint();
} catch (e) {}
// Close DB connection
closeDb();
// Restore baseline
try {
fs.copyFileSync(baselinePath, dbPath);
// Remove WAL/SHM files if they exist (stale from old connection)
try { fs.unlinkSync(dbPath + '-wal'); } catch (e) {}
try { fs.unlinkSync(dbPath + '-shm'); } catch (e) {}
} catch (e: unknown) {
console.error('[Demo Reset] Failed to restore baseline:', e instanceof Error ? e.message : e);
await reinitialize();
return;
await database.checkpoint();
} catch {
/* the swap below does not depend on it */
}
// Reinitialize DB connection with restored baseline
await reinitialize();
// Close, swap the baseline in, reopen. The reopen runs even when the swap
// fails, so the instance is never left without a connection.
let reopenError: unknown;
try {
({ reopenError } = await database.replace(baselinePath));
} catch (e: unknown) {
console.error('[Demo Reset] Failed to restore baseline:', e instanceof Error ? e.message : e);
return;
}
if (reopenError) throw reopenError;
// R3's ruling, applied regardless of the spike's specific finding: the
// post-reopen writes (DMR5/DMR6) run inside a FRESH request context,
// opened AFTER reinitialize() resolves — never the pre-swap fork above,
// opened AFTER the reopen resolves, never the pre-swap fork above,
// even though the spike found the pre-swap fork would also still resolve
// correctly post-swap (task-0-report.md §7 — "appears to work in the
// spike's specific test shape" is not the same guarantee as "correct by
@@ -142,24 +130,22 @@ async function resetDemoUser(): Promise<void> {
console.log('[Demo Reset] Database restored from baseline');
}
async function saveBaseline(): Promise<void> {
const dbPath = liveDbPath();
if (dbPath === ':memory:') {
/**
* Saves the current database as the baseline the hourly reset returns to.
*
* A snapshot through the backup port, written beside the baseline and renamed
* over it, so a failed save leaves the previous baseline intact.
*/
async function saveBaseline(database: DatabaseBackupStrategy): Promise<void> {
if (!database.canSnapshot()) {
console.log('[Demo] In-memory database, no baseline to save.');
return;
}
const em = requireEntityManager();
const maintenance = new MaintenanceRepository(em);
// Flush WAL so baseline file is self-contained. DMR3's dup — the SAME
// shared `MaintenanceRepository.walCheckpoint()` `resetDemoUser`/backup's
// `createBackup` use, not a second near-duplicate raw statement.
try {
await maintenance.walCheckpoint();
} catch (e) {}
fs.copyFileSync(dbPath, baselinePath);
const pending = baselinePath + '.tmp';
fs.rmSync(pending, { force: true });
await database.snapshot(pending);
fs.renameSync(pending, baselinePath);
console.log('[Demo] Baseline saved');
}
+3 -6
View File
@@ -4,7 +4,7 @@ import { DEMO_PASS } from '../nest/common/demo';
import { DemoRepository, type NewDemoPlaceRow } from '../db/repositories/DemoRepository';
// Static like in demo-reset.job.ts: the module top is inert, everything that
// touches the database happens inside the functions.
import { saveBaseline, hasBaseline, requireEntityManager } from './demo-reset';
import { requireEntityManager } from './demo-reset';
// D6 (task-2-review.md's controller ruling / non-HTTP caller table): this runs
// from `runSchemaBootstrap` before `app.init()`, outside any request context, but
@@ -63,11 +63,8 @@ async function seedDemoData(): Promise<{ adminId: number; demoId: number }> {
console.log('[Demo] Seeding example trips...');
await seedExampleTrips(demo, adminId, demoId);
// Auto-save baseline after first seed
if (!hasBaseline()) {
await saveBaseline();
}
// The first baseline is saved once the app is up, by DemoResetJob, through
// the injected backup port this boot-time seed has no access to.
return { adminId, demoId };
}
+7 -4
View File
@@ -88,10 +88,13 @@ better-sqlite3 singleton — folded into `integrations/`. An ESLint
`no-restricted-imports` rule now refuses any import of a `services/` path, because
the directory disappearing is not what keeps it gone: it grew one reasonable file
at a time. Backup made the same trip earlier: `services/backupService.ts` is
`nest/backup/backup.impl.ts`, imported only by its own domain, and it stays a
module of free functions rather than becoming methods because the restore path
closes and reinitializes the core DB handle — rewriting that shape in the same
step as the move would make a regression there impossible to bisect.
`nest/backup/backup.impl.ts`, imported only by its own domain. It is still a
module of free functions, but it no longer closes or reopens the core DB handle
itself: `BackupService` hands it the injected database backup port
(`DATABASE_BACKUP`, `SqliteDatabaseBackup`), which snapshots and swaps the file
through `DatabaseLifecycle`, the provider that owns the connection. The demo
reset goes through the same port. Another engine plugs in there, with a logical
dump in place of `VACUUM INTO` and the file swap.
Note that the trip-access and `canEdit` methods on the domain services are **not**
dead weight waiting for a guard: their callers are overwhelmingly the `*.mcp.ts`
+5 -3
View File
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';
import { InjectRepository } from '@mikro-orm/nestjs';
import bcrypt from 'bcryptjs';
import crypto from 'crypto';
@@ -17,6 +17,7 @@ import { invalidateMcpSessions } from '../../mcp';
import { emitUserDeleted } from '../../plugin-user-lifecycle';
import { maybe_encrypt_api_key, decrypt_api_key } from '../common/crypto/apiKeyCrypto';
import { avatarUrl } from '../common/avatarUrl';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
import { prepareLlmAddonConfigForWrite, maskLlmAddonConfig } from '../llm-parse/llm-config';
import { getPhotoProviderConfig } from '../memories/memories.helpers';
import { validatePassword } from '../common/passwordPolicy';
@@ -128,6 +129,7 @@ export class AdminService {
private readonly userCleanup: UserCleanupService,
private readonly realtime: RealtimeService,
private readonly uow: UnitOfWork,
@Inject(DATABASE_BACKUP) private readonly database: DatabaseBackupStrategy,
) {}
// ── User CRUD ──────────────────────────────────────────────────────────────
@@ -421,8 +423,8 @@ export class AdminService {
}
try {
// Lazy require: demo-reset is a demo-only module.
const { saveBaseline } = require('../../demo/demo-reset');
await saveBaseline();
const { saveBaseline } = require('../../demo/demo-reset') as typeof import('../../demo/demo-reset');
await saveBaseline(this.database);
return { message: 'Demo baseline saved. Hourly resets will restore to this state.' };
} catch (err: unknown) {
console.error(err);
+32 -12
View File
@@ -1,38 +1,58 @@
import { Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { Inject, Injectable, type OnApplicationBootstrap } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
import { logInfo, logError } from '../audit/audit-log.logger';
import { RuntimeEnvService } from '../app-config/runtime-env.service';
import { CronRegistrarService } from '../scheduling/cron-registrar.service';
import { resetDemoUser } from '../../demo/demo-reset';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
import { withRequestContext } from '../database/request-context';
import { hasBaseline, resetDemoUser, saveBaseline } from '../../demo/demo-reset';
/**
* Demo mode: hourly reset of demo user data (moved from src/scheduler.ts).
* Gated on DEMO_MODE at bootstrap — parity: toggling it always required a
* restart — and scheduled in the server-local zone (the old cron.schedule call
* passed no timezone). demo-reset is a static import: its module top is
* side-effect-free, and the dangerous closeDb/reinitialize sequence stays
* inside resetDemoUser, called at tick time.
* side-effect-free, and the close/swap/reopen sequence runs inside
* resetDemoUser at tick time, through the injected backup port.
*
* It also saves the first baseline, on a demo boot that has none. That used to
* happen inside the boot-time demo seed, which runs before the container can
* hand anything in; here the port is injected like everywhere else.
*/
@Injectable()
export class DemoResetJob implements OnApplicationBootstrap {
constructor(
private readonly runtimeEnv: RuntimeEnvService,
private readonly registrar: CronRegistrarService,
@Inject(DATABASE_BACKUP) private readonly database: DatabaseBackupStrategy,
private readonly em: EntityManager,
) {}
onApplicationBootstrap(): void {
if (!this.registrar.isEnabled() || !this.runtimeEnv.isDemoMode()) return;
// D6: resetDemoUser is all raw better-sqlite3 (see demo-reset.ts) — no
// repository read today — but the tick already runs inside a request context
// regardless, via CronRegistrarService's one wrapper around every onTick.
this.registrar.register('demo-reset', '0 * * * *', () => void this.tick(), { timezone: 'none' });
logInfo('Demo hourly reset scheduled');
async onApplicationBootstrap(): Promise<void> {
if (!this.runtimeEnv.isDemoMode()) return;
if (this.registrar.isEnabled()) {
// D6: the tick runs inside a request context, via CronRegistrarService's
// one wrapper around every onTick.
this.registrar.register('demo-reset', '0 * * * *', () => void this.tick(), { timezone: 'none' });
logInfo('Demo hourly reset scheduled');
}
if (!hasBaseline()) await this.saveFirstBaseline();
}
async tick(): Promise<void> {
try {
await resetDemoUser();
await resetDemoUser(this.database);
} catch (err: unknown) {
logError(`Demo reset: ${err instanceof Error ? err.message : err}`);
}
}
/** Boot runs outside any request, so the snapshot gets its own context. */
private async saveFirstBaseline(): Promise<void> {
try {
await withRequestContext({ em: this.em }, () => saveBaseline(this.database));
} catch (err: unknown) {
logError(`Demo baseline: ${err instanceof Error ? err.message : err}`);
}
}
}
+65 -119
View File
@@ -3,12 +3,10 @@ import path from 'path';
import { pipeline } from 'node:stream/promises';
import { readEnv } from '../../app-config';
import fs from 'fs';
import { RequestContext } from '@mikro-orm/core';
import { closeDb, reinitialize } from '../../db/database';
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
import { logInfo, logWarn } from '../audit/audit-log.logger';
import { logError, logWarn } from '../audit/audit-log.logger';
import type { DatabaseBackupStrategy } from '../database/database-backup.interface';
import { VALID_INTERVALS } from './auto-backup.settings';
import { checkBackupDatabase, extractBackupArchive } from './backup-archive';
import { extractBackupArchive } from './backup-archive';
import { invalidatePermissionsCache } from '../permissions/permissions-cache';
import { pluginsCodeRoot, pluginsDataRoot } from '../plugins/paths';
import { stageExtractedPluginTrees, applyStagedRestoreNow } from '../plugins/plugin-backup';
@@ -21,6 +19,20 @@ import { StorageInvalidKeyError } from '../storage/storage.types';
// Paths
// ---------------------------------------------------------------------------
/**
* What a backup and a restore work with: the storage facade for the archives
* and the uploads, and the database port for the database itself. BackupService
* injects both and hands them in.
*/
export interface BackupDeps {
storage: StorageService;
database: DatabaseBackupStrategy;
}
const describeError = (err: unknown): string => (err instanceof Error ? err.message : String(err));
// The scratch and key directory. The database itself may live elsewhere
// (TREK_DB_FILE); the database port knows where.
const dataDir = path.join(__dirname, '../../../data');
const PRECOMPRESSED = /\.(jpe?g|png|webp|gif|heic|heif|avif|mp4|mov|m4v|webm|pdf|zip|gz)$/i;
@@ -157,7 +169,10 @@ export const BACKUP_UPLOAD_CATEGORIES = ['files', 'journey', 'covers', 'avatars'
* only auto-backup-*.zip, and the admin panel badges them as automatic. Manual
* backups keep the default.
*/
export async function createBackup(storage: StorageService, prefix: 'backup' | 'auto-backup' = 'backup'): Promise<BackupInfo> {
export async function createBackup(
{ storage, database }: BackupDeps,
prefix: 'backup' | 'auto-backup' = 'backup',
): Promise<BackupInfo> {
const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19);
const filename = `${prefix}-${timestamp}.zip`;
// All staging lives in the backups backend's own spool: same volume as the
@@ -176,26 +191,13 @@ export async function createBackup(storage: StorageService, prefix: 'backup' | '
const stagingDir = path.join(spoolDir, `staging-${prefix}-${timestamp}`);
try {
// BK1 (R1): PRAGMA wal_checkpoint(TRUNCATE), rendered text pinned,
// through the shared MaintenanceRepository.walCheckpoint() — the SAME
// method demo-reset.ts's resetDemoUser/saveBaseline use, on the ORM's
// own bound driver connection rather than the legacy `db` proxy. Still
// best-effort: the swallowing try/catch matches the legacy shape.
// Flush the WAL first, so the snapshot below has less to copy from it.
// Best effort: the snapshot is consistent either way.
try {
const em = RequestContext.getEntityManager();
if (em) {
await new MaintenanceRepository(em).walCheckpoint();
} else {
// Plan 3i Task 4 fix wave (should-land 7): this used to fail
// silently exactly like a real checkpoint failure would — no signal
// distinguished "no request context around this run" (a
// mis-wired caller; legacy always snapshotted) from "the checkpoint
// itself errored" (best-effort, fine to swallow). Loud enough to
// show up in the backup's own logs, still non-fatal: the fallback
// (archive the live file) is unchanged.
logWarn('Backup: no EntityManager available, skipping the WAL checkpoint before snapshot');
}
} catch (e) {}
await database.checkpoint();
} catch (e) {
logWarn(`Backup: the WAL checkpoint before the snapshot failed (${describeError(e)}), taking the snapshot anyway`);
}
// Enumerate the archived categories up front (the archiver reads entries
// lazily during finalize(), so the promise executor below must stay
@@ -230,43 +232,29 @@ export async function createBackup(storage: StorageService, prefix: 'backup' | '
}
}
// BK2 (R1): VACUUM INTO '<path>', rendered text pinned, through the
// shared MaintenanceRepository.vacuumInto() — computed HERE, before the
// promise executor below, for the same reason the uploadEntries
// enumeration above already is: the archiver reads entries lazily during
// finalize(), so the executor itself must stay synchronous, and
// `await`ing the snapshot requires an async boundary the executor
// (constructed with a plain, non-async callback) cannot have. The
// fallback-to-live-file behaviour on failure is unchanged — only WHERE
// the async snapshot attempt runs, not what it does.
const dbPath = path.join(dataDir, 'travel.db');
const dbExists = fs.existsSync(dbPath);
let dbToArchive = dbPath;
if (dbExists) {
// Archive a point-in-time snapshot, not the live file. The archiver reads entries
// lazily during finalize(), so a WAL auto-checkpoint writing pages back into
// travel.db mid-stream would tear the archived copy — and the -wal that would make
// it recoverable isn't in the zip. VACUUM INTO takes a consistent snapshot even
// under concurrent writes — the same guarantee the plugin DBs get below.
// Archive a point-in-time snapshot, never the live file. The archiver reads
// entries lazily during finalize(), so a WAL auto-checkpoint writing pages
// back into the live file mid-stream would tear the archived copy, and the
// -wal that would make it recoverable is not in the zip. Taken HERE, before
// the promise executor below, because the executor must stay synchronous.
//
// A snapshot that fails fails the backup. It used to fall back to archiving
// the live file, which is exactly the torn copy the snapshot exists to
// prevent, and it did so without a word in the log. Now nothing is
// archived, nothing is committed to the backups store (the finally below
// removes the half-built spool), the existing backups stay as they were,
// and the reason is logged.
const hasDatabase = database.canSnapshot();
if (hasDatabase) {
fs.rmSync(dbSnap, { force: true });
try {
if (fs.existsSync(dbSnap)) fs.rmSync(dbSnap, { force: true });
const em = RequestContext.getEntityManager();
if (!em) {
// Plan 3i Task 4 fix wave (should-land 7): same distinction as
// BK1 above — without this, a backup silently archiving the LIVE
// travel.db (the exact WAL-tear risk this whole snapshot exists to
// avoid) left no trace anywhere. The fallback itself is unchanged
// (parity with legacy, which always had SOME db to archive).
logWarn('Backup: no EntityManager available, archiving the live travel.db instead of a VACUUM INTO snapshot');
throw new Error('no EntityManager available for VACUUM INTO');
}
await new MaintenanceRepository(em).vacuumInto(dbSnap);
dbToArchive = dbSnap;
await database.snapshot(dbSnap);
} catch (e) {
// Snapshot failed (disk/lock/missing context) — fall back to the
// checkpointed live file rather than drop the core DB from the
// backup entirely.
logError(`Backup: could not take a snapshot of the database at ${database.location()} (${describeError(e)}). No backup was written.`);
throw new Error(`Database snapshot failed: ${describeError(e)}`, { cause: e });
}
} else {
logWarn(`Backup: no database file at ${database.location()}, this backup holds no database`);
}
await new Promise<void>((resolve, reject) => {
@@ -283,8 +271,8 @@ export async function createBackup(storage: StorageService, prefix: 'backup' | '
archive.pipe(output);
if (dbExists) {
archive.file(dbToArchive, { name: 'travel.db' });
if (hasDatabase) {
archive.file(dbSnap, { name: database.archiveEntry });
}
// Bundle the at-rest encryption key so the backup is self-contained: the
@@ -309,7 +297,7 @@ export async function createBackup(storage: StorageService, prefix: 'backup' | '
// copy of the user data a plugin holds, so it belongs in the backup. Checkpoint
// every open handle first (the host keeps them open in WAL mode) so the archived
// .db files are complete snapshots and not missing recent commits stranded in a
// -wal sidecar — the same treatment travel.db gets above.
// -wal sidecar, the same treatment the core database gets above.
const pdata = pluginsDataRoot();
if (fs.existsSync(pdata)) {
// Archive a consistent point-in-time snapshot, not the live files: the archiver
@@ -380,8 +368,8 @@ export interface RestoreResult {
/** Restore a zip that already sits in the backups store, reading it through
* the storage facade (primary-local in v1; a remote backend downloads to
* tempDir via withLocalFile — the seam is in place, resumability is not). */
export function restoreBackup(storage: StorageService, filename: string): Promise<RestoreResult> {
return storage.withLocalFile('backups', filename, (zipPath) => restoreFromZip(storage, zipPath));
export function restoreBackup(deps: BackupDeps, filename: string): Promise<RestoreResult> {
return deps.storage.withLocalFile('backups', filename, (zipPath) => restoreFromZip(deps, zipPath));
}
const isBackupCategory = (dir: string): dir is (typeof BACKUP_UPLOAD_CATEGORIES)[number] =>
@@ -421,54 +409,27 @@ export async function rehydrateUploads(storage: StorageService, extractedUploads
}
}
/**
* A copy of the database a restore is about to replace, next to it in data/.
* The swap below deletes the current file, and a restore of the wrong archive
* used to leave nothing to go back to. Best effort: a database broken enough to
* need the restore may not snapshot, and that must not block the recovery.
*/
async function snapshotBeforeRestore(): Promise<void> {
const target = path.join(dataDir, `pre-restore-${Date.now()}.db`);
try {
const em = RequestContext.getEntityManager();
if (!em) throw new Error('no EntityManager available for VACUUM INTO');
await new MaintenanceRepository(em).vacuumInto(target);
logInfo(`Restore: the replaced database was kept as ${target}`);
} catch (err) {
logWarn(`Restore: could not keep a copy of the current database (${err instanceof Error ? err.message : String(err)})`);
}
}
export async function restoreFromZip(storage: StorageService, zipPath: string): Promise<RestoreResult> {
export async function restoreFromZip({ storage, database }: BackupDeps, zipPath: string): Promise<RestoreResult> {
const extractDir = path.join(dataDir, `restore-${Date.now()}`);
let reinitFailed: unknown = null;
let reinitFailed: unknown;
try {
const refused = await extractBackupArchive(zipPath, extractDir);
if (refused) return { success: false, ...refused };
const unreadable = checkBackupDatabase(extractDir);
const unreadable = database.verify(extractDir);
if (unreadable) {
fs.rmSync(extractDir, { recursive: true, force: true });
return { success: false, ...unreadable };
}
const extractedDb = path.join(extractDir, 'travel.db');
await snapshotBeforeRestore();
closeDb();
await database.keepCopyBeforeRestore();
try {
const dbDest = path.join(dataDir, 'travel.db');
// Swap the core DB atomically: copy the restored DB to a temp file on the SAME
// filesystem, drop the old -wal/-shm sidecars (they belong to the DB being replaced
// and would corrupt the new one if left), then rename into place. A rename is atomic,
// so a crash mid-swap leaves either the old or the new travel.db intact — never the
// deleted-and-not-yet-copied gap that a plain unlink-then-copy could leave.
const dbTmp = dbDest + '.restore-tmp';
fs.copyFileSync(extractedDb, dbTmp);
for (const ext of ['-wal', '-shm']) {
try { fs.unlinkSync(dbDest + ext); } catch (e) {}
}
fs.renameSync(dbTmp, dbDest);
// Closes the connection, swaps the database in and reopens it, migrating
// the restored file forward. The reopen runs even when the swap throws; a
// reopen failure comes back here instead of propagating, because the
// files already landed and that has to be reported as "restart required".
({ reopenError: reinitFailed } = await database.replace(path.join(extractDir, database.archiveEntry)));
// Restore the bundled at-rest encryption key (if the archive carries one)
// so the restored DB's encrypted secrets can be decrypted. Only the file
@@ -480,34 +441,19 @@ export async function restoreFromZip(storage: StorageService, zipPath: string):
fs.copyFileSync(extractedEncKey, path.join(dataDir, '.encryption_key'));
}
} finally {
// Reopening the DB must always run (even if the copy above threw) so the
// process is never left without a connection. Capture a reopen failure
// instead of letting it propagate as a generic error — a backup whose
// files already landed on disk but whose connection failed to reopen
// needs to be reported as "restart required", not swallowed.
try {
// Awaited: reopening also migrates the restored file, which may be an
// older backup, and rebuilds the ORM's cached connection.
await reinitialize();
} catch (reinitErr) {
reinitFailed = reinitErr;
}
// The restored DB has different permission-override rows from
// the pre-restore DB, but our process-local permissions cache
// still holds the pre-restore state. Any request using a cached
// permission would decide against the wrong grants until the
// next restart. Dropping the cache forces a fresh read.
// D6: no repository read happens on this path today — invalidation is a
// plain function, not a DB call — so no withRequestContext is owed here yet.
// The domain phase that gives this restore path a repository read (Plan 3's
// admin/backup cluster) must wrap it then; see task-2-review.md's non-HTTP
// caller table.
// D6: no repository read happens on this path today (invalidation is a
// plain function, not a DB call), so no withRequestContext is owed here.
invalidatePermissionsCache();
}
if (!reinitFailed) {
// The registry reads storage.* app_settings through the DB handle that
// was just closed and reopened above — reload it now, AFTER reinitialize()
// was just closed and reopened above. Reload it now, AFTER the reopen
// and BEFORE any byte moves, so rehydrated uploads land where the RESTORED
// config says rather than the stale pre-restore one (audit #4). Skipped
// entirely when reopen failed: with no live DB handle the registry has
@@ -541,7 +487,7 @@ export async function restoreFromZip(storage: StorageService, zipPath: string):
// an un-staged tree there would be gone for good with no recovery path.
try {
stageExtractedPluginTrees(extractDir);
// Quiesce regardless of whether trees were staged: the restored travel.db carries
// Quiesce regardless of whether trees were staged: the restored database carries
// a different `plugins` table, so any plugin still running with its pre-restore
// identity/grants is now a ghost — invisible in the restored UI, unstoppable short
// of a process restart. applyStagedRestoreNow closes those handles; the tree swap
+4
View File
@@ -10,6 +10,7 @@ import { AppConfigModule } from '../app-config/app-config.module';
import { StorageModule } from '../storage/storage.module';
import { StorageService } from '../storage/storage.service';
import { MAX_BACKUP_UPLOAD_SIZE } from './backup.impl';
import { DatabaseBackupModule } from './database-backup.module';
/**
* Multer options for the restore upload. The uploaded zip is a restore INPUT,
@@ -32,6 +33,9 @@ export function buildBackupUploadOptions(storage: StorageService): MulterOptions
imports: [
AppConfigModule,
AuditModule,
// Global, so the admin domain sees the port too; imported here because the
// backup domain is what it belongs to.
DatabaseBackupModule,
SchedulingModule,
StorageModule,
MulterModule.registerAsync({
+19 -10
View File
@@ -1,26 +1,35 @@
import { Injectable } from '@nestjs/common';
import { Inject, Injectable } from '@nestjs/common';
import type { Response } from 'express';
import { StorageService } from '../storage/storage.service';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
import * as svc from './backup.impl';
/**
* The backup domain's injectable face.
*
* The implementation moved here from src/services/backupService.ts with the code
* unchanged, and stays a module rather than becoming methods on this class: the zip
* packing and the restore path close and reinitialize the core DB handle, which is the
* single most dangerous sequence in the server. Rewriting its shape and moving it in
* one step would make a regression there impossible to bisect. The DB-lifecycle
* question is deliberately the LAST step of this fold, not part of the move.
* unchanged, and stays a module rather than becoming methods on this class. What
* made that the cautious choice was that the zip packing and the restore path
* closed and reinitialized the core DB handle themselves. They no longer do:
* every database step goes through the injected backup port
* (`DATABASE_BACKUP`, `SqliteDatabaseBackup` today), which owns the snapshot and
* the swap, and through it `DatabaseLifecycle`, which owns the connection.
*/
@Injectable()
export class BackupService {
constructor(private readonly storage: StorageService) {}
private readonly deps: svc.BackupDeps;
constructor(
private readonly storage: StorageService,
@Inject(DATABASE_BACKUP) database: DatabaseBackupStrategy,
) {
this.deps = { storage, database };
}
listBackups() { return svc.listBackups(this.storage); }
createBackup(prefix?: 'backup' | 'auto-backup') { return svc.createBackup(this.storage, prefix); }
restoreFromZip(zipPath: string) { return svc.restoreFromZip(this.storage, zipPath); }
restoreBackup(filename: string) { return svc.restoreBackup(this.storage, filename); }
createBackup(prefix?: 'backup' | 'auto-backup') { return svc.createBackup(this.deps, prefix); }
restoreFromZip(zipPath: string) { return svc.restoreFromZip(this.deps, zipPath); }
restoreBackup(filename: string) { return svc.restoreBackup(this.deps, filename); }
deleteBackup(filename: string) { return svc.deleteBackup(this.storage, filename); }
isValidBackupFilename(filename: string) { return svc.isValidBackupFilename(filename); }
@@ -0,0 +1,22 @@
import { Global, Module } from '@nestjs/common';
import { DATABASE_BACKUP } from '../database/database-backup.interface';
import { DatabaseLifecycleModule } from '../database/database-lifecycle.module';
import { MaintenanceModule } from '../database/maintenance.module';
import { SqliteDatabaseBackup } from './sqlite-database-backup';
/**
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use.
*
* Global because its consumers sit in two domains that must not depend on each
* other: the backup domain itself and the admin domain (the demo reset job and
* the baseline route). They inject the token from the shared database kernel
* and never import this file. `BackupModule` imports it, which is what puts it
* in the application.
*/
@Global()
@Module({
imports: [DatabaseLifecycleModule, MaintenanceModule],
providers: [SqliteDatabaseBackup, { provide: DATABASE_BACKUP, useExisting: SqliteDatabaseBackup }],
exports: [DATABASE_BACKUP],
})
export class DatabaseBackupModule {}
@@ -0,0 +1,111 @@
import fs from 'fs';
import path from 'path';
import { Injectable } from '@nestjs/common';
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
import { DatabaseLifecycle } from '../database/database-lifecycle.service';
import type { DatabaseBackupRefusal, DatabaseBackupStrategy } from '../database/database-backup.interface';
import { logInfo, logWarn } from '../audit/audit-log.logger';
import { checkBackupDatabase } from './backup-archive';
const describeError = (err: unknown): string => (err instanceof Error ? err.message : String(err));
/**
* The backup port for the one engine TREK runs on: a SQLite file.
*
* Every step is what `backup.impl.ts` and `demo/demo-reset.ts` did inline
* before the port existed. A snapshot is `VACUUM INTO`, which takes a
* consistent copy even under concurrent writers. A restore closes the
* connection, swaps the file by copy and rename (a crash mid-swap leaves the
* old or the new file, never neither), drops the old `-wal`/`-shm` sidecars,
* and reopens through `DatabaseLifecycle`, which migrates the restored file
* forward.
*
* The file is always `DatabaseLifecycle.file`, the path the connection was
* opened on, so `TREK_DB_FILE` moves the backup, the restore and the demo reset
* along with the database.
*/
@Injectable()
export class SqliteDatabaseBackup implements DatabaseBackupStrategy {
readonly archiveEntry = 'travel.db';
constructor(
private readonly lifecycle: DatabaseLifecycle,
private readonly maintenance: MaintenanceRepository,
) {}
location(): string {
return this.lifecycle.file;
}
canSnapshot(): boolean {
const file = this.lifecycle.file;
return file !== ':memory:' && fs.existsSync(file);
}
async checkpoint(): Promise<void> {
await this.maintenance.walCheckpoint();
}
async snapshot(target: string): Promise<void> {
try {
await this.maintenance.vacuumInto(target);
} catch (err) {
// A VACUUM INTO that failed part-way (a full disk) can leave a truncated
// file behind. Nothing may mistake it for a copy.
fs.rmSync(target, { force: true });
throw err;
}
}
verify(extractDir: string): DatabaseBackupRefusal | null {
return checkBackupDatabase(extractDir);
}
/**
* A copy of the database a restore is about to replace, next to it. The swap
* deletes the current file, and a restore of the wrong archive used to leave
* nothing to go back to.
*/
async keepCopyBeforeRestore(): Promise<string | null> {
const target = path.join(path.dirname(this.lifecycle.file), `pre-restore-${Date.now()}.db`);
try {
await this.snapshot(target);
logInfo(`Restore: the replaced database was kept as ${target}`);
return target;
} catch (err) {
logWarn(`Restore: could not keep a copy of the current database (${describeError(err)})`);
return null;
}
}
async replace(source: string): Promise<{ reopenError: unknown }> {
const dest = this.lifecycle.file;
this.lifecycle.close();
let reopenError: unknown = null;
try {
// Copy to a temp file on the SAME filesystem, drop the old sidecars (they
// belong to the database being replaced and would corrupt the new one),
// then rename into place. The rename is atomic.
const tmp = dest + '.restore-tmp';
fs.copyFileSync(source, tmp);
for (const ext of ['-wal', '-shm']) {
try {
fs.unlinkSync(dest + ext);
} catch {
/* no sidecar to drop */
}
}
fs.renameSync(tmp, dest);
} finally {
// Reopening must always run, even when the swap threw, so the process is
// never left without a connection. A reopen failure is reported, not
// thrown: the files already landed and the caller has to say "restart".
try {
await this.lifecycle.reopen();
} catch (err) {
reopenError = err;
}
}
return { reopenError };
}
}
@@ -0,0 +1,76 @@
/**
* How a backup, a restore and the demo reset get at the core database, without
* knowing which engine holds it.
*
* The admin backup (`nest/backup/backup.impl.ts`), its restore, and the demo
* baseline save and hourly reset (`demo/demo-reset.ts`) all go through this
* port. The only implementation today is `SqliteDatabaseBackup`
* (`nest/backup/`), which does what those paths always did: `VACUUM INTO` for a
* consistent copy of the file, a file swap under a closed connection for a
* restore. An engine that is not one local file would plug in here with a
* logical dump and load instead.
*
* Lives in the shared database kernel, not in the backup domain, so the admin
* domain (the demo reset job, the baseline route) can inject it without
* importing the backup domain.
*/
export interface DatabaseBackupStrategy {
/** The name the database takes inside a backup archive. */
readonly archiveEntry: string;
/**
* Where the live database is, for log lines. The file path for SQLite; it
* names no file only for the in-memory database the test suites run on.
*/
location(): string;
/** Whether there is a database this strategy can copy. False for an in-memory one. */
canSnapshot(): boolean;
/**
* Flushes what the engine keeps beside its main store (SQLite's WAL) into it.
* Best effort for every caller: a failure leaves the snapshot consistent, just
* slower to take.
*/
checkpoint(): Promise<void>;
/**
* Writes a consistent, point-in-time copy of the live database to `target`,
* which must not exist yet. Throws when no complete copy could be written,
* and then leaves nothing at `target`.
*/
snapshot(target: string): Promise<void>;
/**
* Checks an unpacked archive's database before anything is replaced. Returns
* null when it can be restored, or the refusal in the restore route's words.
*/
verify(extractDir: string): DatabaseBackupRefusal | null;
/**
* Keeps a copy of the database a restore is about to replace. Best effort: a
* database broken enough to need the restore may not copy, and that must not
* block the recovery. Resolves with where the copy went, or null.
*/
keepCopyBeforeRestore(): Promise<string | null>;
/**
* Puts `source` (a database this strategy wrote or verified) in place of the
* live one, then reopens the connection, migrating it forward. The reopen
* runs even when the swap throws, so the process is never left without a
* connection; the swap's error is rethrown after it.
*
* Resolves with `reopenError` set when the new database landed but the
* connection could not be reopened: the caller reports "restart required".
*/
replace(source: string): Promise<{ reopenError: unknown }>;
}
/** A refusal in the restore route's own words and status. */
export interface DatabaseBackupRefusal {
error: string;
status: number;
}
/** Injection token for the active `DatabaseBackupStrategy`. */
export const DATABASE_BACKUP = Symbol('DATABASE_BACKUP');
@@ -10,12 +10,15 @@ import { runSchemaBootstrap } from '../../db/orm';
*
* The handle itself still lives in `db/database.ts`, because the ORM's bound
* driver (`db/orm-driver.ts`) reads it on every connect and the test suites
* replace that module wholesale with `vi.mock`. What moved here is the
* decision about WHEN it opens and closes: `buildApp()` opens through this and
* the shutdown closes through this. Nothing opens the database at import any
* more; the first connect does, and this provider makes it explicit. The
* restore and the demo reset still call the module's `closeDb()`/`reinitialize()`
* themselves until they move onto `close()`/`reopen()`.
* replace that module wholesale with `vi.mock`. What moved here is every
* decision about WHEN it opens and closes: `buildApp()` opens through this,
* a restore and the demo reset close and reopen through this (via the backup
* port), and the shutdown closes through this. Nothing opens the database at
* import any more; the first connect does, and this provider makes it explicit.
*
* Only the SQLite file engine exists today. The engine specific parts (the file
* path, the swap) are confined to `file` and to the backup port's SQLite
* implementation, so another engine changes this provider and that one class.
*/
@Injectable()
export class DatabaseLifecycle {
+5 -1
View File
@@ -106,6 +106,7 @@ vi.mock('../../src/nest/notifications/notification-preferences.service', async (
});
import { AdminModule } from '../../src/nest/admin/admin.module';
import { DatabaseBackupModule } from '../../src/nest/backup/database-backup.module';
// The admin surface is no longer one module: oidc, the account defaults and the admin
// preference matrix moved to the domains that own them, so the app has to assemble
// them too or those routes 404 here while working in production.
@@ -122,7 +123,10 @@ describe('Admin e2e (real auth + admin guard + temp SQLite)', () => {
let app: Awaited<ReturnType<typeof build>>;
async function build() {
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), RealtimeModule, AdminModule, OidcModule, SettingsModule, NotificationsModule] }).compile();
// DatabaseBackupModule is global and lives in the backup domain, which the
// app imports through BackupModule; the admin surface injects its port for
// the demo baseline and reset, so a harness without BackupModule adds it.
const moduleRef = await Test.createTestingModule({ imports: [await TestUnitOfWorkModule.forRoot(db), await createTestMikroOrmModule(db), DatabaseBackupModule, RealtimeModule, AdminModule, OidcModule, SettingsModule, NotificationsModule] }).compile();
const nest = moduleRef.createNestApplication();
nest.use(cookieParser());
// Mirror the production APP_PIPE (app.module.ts): DTO-typed bodies validate
@@ -3,6 +3,8 @@ import request from 'supertest';
import type { INestApplication } from '@nestjs/common';
import { buildApp } from '../../src/bootstrap';
import { DatabaseLifecycle } from '../../src/nest/database/database-lifecycle.service';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../../src/nest/database/database-backup.interface';
import { SqliteDatabaseBackup } from '../../src/nest/backup/sqlite-database-backup';
/**
* The core database's lifecycle, owned by the DatabaseLifecycle provider, on a
@@ -11,8 +13,8 @@ import { DatabaseLifecycle } from '../../src/nest/database/database-lifecycle.se
* The connection used to open as a side effect of importing db/database.ts and
* was closed and reopened through module functions the restore and the demo
* reset called directly. buildApp() now opens it through the provider, which
* also binds the ORM to later swaps, and closes and reopens it through the
* same provider. Unmocked on purpose: under NODE_ENV=test the
* also binds the ORM to later swaps; the backup port closes and reopens it
* through the same provider. Unmocked on purpose: under NODE_ENV=test the
* module opens a copy of the migrated schema snapshot, and every reopen opens a
* pristine copy again, which is all these cases need.
*/
@@ -52,4 +54,13 @@ describe('the database connection lifecycle under buildApp()', () => {
const up = await request(app.getHttpServer()).get('/api/health/ready');
expect(up.status).toBe(200);
});
it('LIFECYCLE-003: the backup port the container hands out is the SQLite one, on the file the connection runs on', () => {
const port = app.get<DatabaseBackupStrategy>(DATABASE_BACKUP);
expect(port).toBeInstanceOf(SqliteDatabaseBackup);
expect(port.location()).toBe(app.get(DatabaseLifecycle).file);
// The in-memory test database has no file to copy.
expect(port.canSnapshot()).toBe(false);
});
});
+43 -65
View File
@@ -47,7 +47,14 @@ const dbMock = vi.hoisted(() => ({
reinitialize: vi.fn(),
}));
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn() }));
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn() }));
// What Nest injects into the backup port: the WAL checkpoint and the VACUUM
// INTO snapshot. Stubbed, because a real VACUUM INTO would bypass the fs mock.
const maintenanceStub = vi.hoisted(() => ({
walCheckpoint: vi.fn(async () => {}),
vacuumInto: vi.fn(async (_target: string) => {}),
}));
vi.mock('fs', () => ({ default: fsMock, ...fsMock }));
vi.mock('node:fs', () => ({ default: fsMock, ...fsMock }));
@@ -62,39 +69,25 @@ vi.mock('../../src/config', () => ({
}));
import path from 'node:path';
import type Database from 'better-sqlite3';
import { AutoBackupJob } from '../../src/nest/backup/auto-backup.job';
import { createBackup } from '../../src/nest/backup/backup.impl';
import { SqliteDatabaseBackup } from '../../src/nest/backup/sqlite-database-backup';
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';
import { createTestOrm } from '../helpers/test-orm';
import { withRequestContext } from '../../src/nest/database/request-context';
import { MaintenanceRepository } from '../../src/db/repositories/MaintenanceRepository';
import type { DatabaseLifecycle } from '../../src/nest/database/database-lifecycle.service';
import type { MaintenanceRepository } from '../../src/db/repositories/MaintenanceRepository';
const liveDb = path.join(__dirname, '../../data', 'travel.db');
/**
* `createSnapshotTestDb()` (db-mock.ts) reads the schema snapshot through
* schema-snapshot.ts's own `fs` import, which resolves to `fsMock` here — 'fs'/
* 'node:fs' are mocked wholesale above for the archiver assertions, so that read
* would silently return null instead of the real snapshot. Rather than weaken
* the snapshot helper itself, point the three fs calls it needs at the real
* filesystem just long enough to build the db: every test in this file sets its
* own fsMock.existsSync/readFileSync behaviour before it matters (scheduledRun()
* overwrites readFileSync before the job ever ticks), so this doesn't leak.
*/
async function testDbFromSnapshot(): Promise<Database.Database> {
const realFs = await vi.importActual<typeof import('node:fs')>('node:fs');
fsMock.existsSync.mockImplementation(realFs.existsSync as never);
fsMock.readdirSync.mockImplementation(realFs.readdirSync as never);
fsMock.readFileSync.mockImplementation(realFs.readFileSync as never);
const { createSnapshotTestDb } = await import('../helpers/db-mock');
return createSnapshotTestDb();
}
/** The backup port BackupService injects: the real SQLite one over stubs. */
const database = new SqliteDatabaseBackup(
{ file: liveDb, close: vi.fn(), reopen: vi.fn() } as unknown as DatabaseLifecycle,
maintenanceStub as unknown as MaintenanceRepository,
);
// createBackup receives StorageService as a parameter (BackupService injects
// it). fs is mocked wholesale here, so a plain stub stands in for the backups
// createBackup receives StorageService and the database port as parameters
// (BackupService injects them). 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() {
@@ -131,8 +124,11 @@ 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. 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,
// BackupService: the storage stub and the database port go in first.
{
createBackup: (prefix?: 'backup' | 'auto-backup') =>
createBackup({ storage: storageStub as unknown as StorageService, database }, prefix),
} as unknown as BackupService,
registrar as unknown as CronRegistrarService,
storageStub as unknown as StorageService,
);
@@ -177,47 +173,29 @@ describe('auto-backup run', () => {
});
it('archives a VACUUM INTO snapshot, never the live travel.db', async () => {
// Plan 3i Task 4 fix wave: BK2 now runs through
// `MaintenanceRepository.vacuumInto()` on a resolved `RequestContext`
// EntityManager (backup.impl.ts), not the raw `db.exec` this test used
// to spy on — that assertion went stale and silently stopped proving
// anything the moment BK2 moved off the legacy `db` proxy: with no
// request context around the tick, `RequestContext.getEntityManager()`
// returned null, createBackup silently fell back to archiving the LIVE
// file (the exact bug this suite's own header describes), and
// `dbMock.db.exec` was simply never called — a false green.
// A real (throwaway) ORM over a real test DB supplies that
// EntityManager; `vacuumInto` itself is spied and stubbed so no real
// VACUUM INTO touches disk (fs is mocked wholesale above, but
// better-sqlite3's native VACUUM INTO would bypass that mock).
//
// Built before the test's own fsMock.existsSync stub below: building the
// snapshot db temporarily points fsMock's fs calls at the real
// filesystem (see testDbFromSnapshot's own comment), so this test's stub
// has to land after, not be clobbered by it.
const maintDb: Database.Database = await testDbFromSnapshot();
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'));
stubArchiver();
const testOrm = await createTestOrm(maintDb);
const vacuumIntoSpy = vi.spyOn(MaintenanceRepository.prototype, 'vacuumInto').mockResolvedValue(undefined);
const walCheckpointSpy = vi.spyOn(MaintenanceRepository.prototype, 'walCheckpoint').mockResolvedValue(undefined);
try {
await withRequestContext(testOrm.orm, () => scheduledRun()());
// Assertions run BEFORE the spies are restored: `mockRestore()` also
// clears recorded calls (same as `mockReset()`), so checking after
// cleanup would always read an empty call list.
expect(vacuumIntoSpy).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/travel-snap-auto-backup-'));
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
} finally {
vacuumIntoSpy.mockRestore();
walCheckpointSpy.mockRestore();
await testOrm.close();
maintDb.close();
}
await scheduledRun()();
expect(maintenanceStub.vacuumInto).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/travel-snap-auto-backup-'));
const dbEntry = archiveMock.file.mock.calls.find(([, opts]) => opts?.name === 'travel.db');
expect(dbEntry).toBeDefined();
expect(dbEntry?.[0]).toContain('/stub/spool/travel-snap-auto-backup-');
expect(dbEntry?.[0]).not.toBe(liveDb);
});
it('a snapshot that fails fails the run and archives nothing, instead of zipping the live file', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db') || String(p).endsWith('backup-settings.json'));
stubArchiver();
maintenanceStub.vacuumInto.mockRejectedValueOnce(new Error('database is locked'));
await scheduledRun()();
expect(archiveMock.file).not.toHaveBeenCalled();
expect(storageStub.put).not.toHaveBeenCalled();
expect(logMock.logError).toHaveBeenCalledWith(expect.stringContaining('could not take a snapshot of the database'));
expect(logMock.logError).toHaveBeenCalledWith('Auto-Backup: Database snapshot failed: database is locked');
});
it('bundles the at-rest encryption key', async () => {
+79 -47
View File
@@ -1,30 +1,25 @@
/**
* demo-reset's DB path.
* demo-reset's database file.
*
* demo-reset closes the live connection, copies the baseline over the database
* file and reopens. It used to compute that file itself as data/travel.db, which
* is wrong the moment TREK_DB_FILE moves the database elsewhere: the baseline
* lands on an unrelated file and the real database is never reset. The path has
* to come from the connection that database.ts actually opened, so what these
* cases assert is which file each copy names.
* demo-reset closes the live connection, puts the baseline in place of the
* database file and reopens. It used to compute that file itself as
* data/travel.db, which is wrong the moment TREK_DB_FILE moves the database
* elsewhere: the baseline lands on an unrelated file and the real database is
* never reset. Both directions go through the database backup port now, the
* same one an admin restore uses, and the port takes the file from
* `DatabaseLifecycle.file`, the path the connection runs on. So what these
* cases assert is which file each step names.
*
* demo-reset reads that path off `getRawConnection()` (a static import of
* ../db/database since the Plan 4 review's m1 — it used to runtime-require the
* `db` Proxy), so the module is mocked below with a handle stub that only has a
* `name`. The file system is spied rather than written to, because the
* The port is the real `SqliteDatabaseBackup` over a lifecycle stand-in (the
* file, close, reopen) and a MaintenanceRepository stand-in (checkpoint,
* VACUUM INTO). The file system is spied rather than written to, because the
* baseline path is fixed at data/travel-baseline.db and a developer running a
* demo instance has a real one sitting there.
*
* Plan 3i Task 3: `resetDemoUser`/`saveBaseline` now read/write through
* `DemoRepository`/`MaintenanceRepository`, which resolve an `EntityManager`
* via `RequestContext.getEntityManager()` — independent of the
* `getRawConnection`/`closeDb`/`reinitialize` stub below (that stub covers only the
* connection-lifecycle calls this file still makes). Every call here runs
* inside `withRequestContext(orm.orm, ...)`, bound to a REAL (empty) test
* database, so the credential/instance-key reads resolve to nothing found
* (no admin/app_settings row seeded) and the restore-writes are skipped —
* this file's own assertions are about the FILE path, not the row data,
* which DEMORESET-CRED below covers separately.
* `resetDemoUser` still reads the admin credentials and instance keys through
* `DemoRepository` before the swap, so every call runs inside
* `withRequestContext` over a real (empty) test database: the reads find
* nothing and the restore-writes are skipped.
*/
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import fs from 'node:fs';
@@ -33,37 +28,38 @@ import type Database from 'better-sqlite3';
import { createSnapshotTestDb } from '../../helpers/db-mock';
import { createTestOrm } from '../../helpers/test-orm';
import { withRequestContext } from '../../../src/nest/database/request-context';
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
import type { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import { resetDemoUser, saveBaseline } from '../../../src/demo/demo-reset';
const LIVE_DB = path.join(path.sep, 'srv', 'trek', 'custom-name.db');
const { handleStub, databaseModule } = vi.hoisted(() => {
const handleStub = { name: '' };
return {
handleStub,
databaseModule: { getRawConnection: () => handleStub, closeDb: vi.fn(), reinitialize: vi.fn(async () => {}) },
};
});
vi.mock('../../../src/db/database', () => databaseModule);
const BASELINE = path.resolve(__dirname, '..', '..', '..', 'data', 'travel-baseline.db');
import { resetDemoUser, saveBaseline } from '../../../src/demo/demo-reset';
describe('demo-reset DB path', () => {
let copyFileSync: ReturnType<typeof vi.spyOn>;
let renameSync: ReturnType<typeof vi.spyOn>;
let ormDb: Database.Database;
let lifecycle: { file: string; close: ReturnType<typeof vi.fn>; reopen: ReturnType<typeof vi.fn> };
let maintenance: { walCheckpoint: ReturnType<typeof vi.fn>; vacuumInto: ReturnType<typeof vi.fn> };
let database: SqliteDatabaseBackup;
beforeEach(async () => {
handleStub.name = LIVE_DB;
beforeEach(() => {
vi.spyOn(console, 'log').mockImplementation(() => undefined);
vi.spyOn(console, 'error').mockImplementation(() => undefined);
// Built before the existsSync spy below is installed: createSnapshotTestDb()
// reads the schema snapshot through schema-snapshot.ts's own fs.existsSync
// (locating the migrations dir to key the snapshot file), which the spy
// would otherwise answer `false` for every path except BASELINE.
// would otherwise answer `false` for every path except the two below.
ormDb = createSnapshotTestDb();
copyFileSync = vi.spyOn(fs, 'copyFileSync').mockImplementation(() => undefined);
renameSync = vi.spyOn(fs, 'renameSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'unlinkSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'existsSync').mockImplementation(((p: fs.PathLike) => String(p) === BASELINE) as typeof fs.existsSync);
vi.spyOn(fs, 'rmSync').mockImplementation(() => undefined);
vi.spyOn(fs, 'existsSync').mockImplementation(((p: fs.PathLike) => String(p) === BASELINE || String(p) === LIVE_DB) as typeof fs.existsSync);
lifecycle = { file: LIVE_DB, close: vi.fn(), reopen: vi.fn(async () => {}) };
maintenance = { walCheckpoint: vi.fn(async () => {}), vacuumInto: vi.fn(async () => {}) };
database = new SqliteDatabaseBackup(lifecycle as unknown as DatabaseLifecycle, maintenance as unknown as MaintenanceRepository);
});
afterEach(() => {
@@ -76,24 +72,60 @@ describe('demo-reset DB path', () => {
return await withRequestContext(orm.orm, fn);
}
it('DEMORESET-001: saves the baseline from the file the connection has open', async () => {
await withCtx(() => saveBaseline());
expect(copyFileSync).toHaveBeenCalledWith(LIVE_DB, BASELINE);
it('DEMORESET-001: saves the baseline as a snapshot of the file the connection has open, renamed into place', async () => {
await withCtx(() => saveBaseline(database));
// Written beside the baseline first, so a failed save cannot leave half a
// baseline where the previous good one was.
expect(maintenance.vacuumInto).toHaveBeenCalledWith(BASELINE + '.tmp');
expect(renameSync).toHaveBeenCalledWith(BASELINE + '.tmp', BASELINE);
});
it('DEMORESET-002: restores the baseline onto that same file, not data/travel.db', async () => {
await withCtx(() => resetDemoUser());
expect(copyFileSync).toHaveBeenCalledWith(BASELINE, LIVE_DB);
const order: string[] = [];
lifecycle.close.mockImplementation(() => order.push('close'));
copyFileSync.mockImplementation(() => { order.push('copy'); });
lifecycle.reopen.mockImplementation(async () => { order.push('reopen'); });
await withCtx(() => resetDemoUser(database));
expect(copyFileSync).toHaveBeenCalledWith(BASELINE, LIVE_DB + '.restore-tmp');
expect(renameSync).toHaveBeenCalledWith(LIVE_DB + '.restore-tmp', LIVE_DB);
// Closed before the copy and reopened after it — copying over an open
// SQLite file is how a database ends up half of each.
expect(databaseModule.closeDb).toHaveBeenCalled();
expect(databaseModule.reinitialize).toHaveBeenCalled();
expect(order).toEqual(['close', 'copy', 'reopen']);
expect(maintenance.walCheckpoint).toHaveBeenCalled();
});
it('DEMORESET-003: an in-memory database is left alone rather than copied around', async () => {
handleStub.name = ':memory:';
await withCtx(() => saveBaseline());
await withCtx(() => resetDemoUser());
lifecycle.file = ':memory:';
await withCtx(() => saveBaseline(database));
await withCtx(() => resetDemoUser(database));
expect(copyFileSync).not.toHaveBeenCalled();
expect(maintenance.vacuumInto).not.toHaveBeenCalled();
expect(lifecycle.close).not.toHaveBeenCalled();
});
it('DEMORESET-004: a baseline save that fails keeps the previous baseline', async () => {
maintenance.vacuumInto.mockRejectedValueOnce(new Error('database or disk is full'));
await expect(withCtx(() => saveBaseline(database))).rejects.toThrow('database or disk is full');
expect(renameSync).not.toHaveBeenCalled();
});
it('DEMORESET-005: a swap that fails is logged, and the connection is reopened anyway', async () => {
copyFileSync.mockImplementation(() => { throw new Error('EACCES'); });
await expect(withCtx(() => resetDemoUser(database))).resolves.toBeUndefined();
expect(lifecycle.reopen).toHaveBeenCalled();
expect(renameSync).not.toHaveBeenCalled();
expect(console.error).toHaveBeenCalledWith('[Demo Reset] Failed to restore baseline:', 'EACCES');
});
it('DEMORESET-006: a reopen that fails after the swap is not swallowed', async () => {
lifecycle.reopen.mockRejectedValueOnce(new Error('database is locked'));
await expect(withCtx(() => resetDemoUser(database))).rejects.toThrow('database is locked');
});
});
+46 -9
View File
@@ -7,16 +7,22 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
const logMock = vi.hoisted(() => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
const { resetDemoUserMock } = vi.hoisted(() => ({ resetDemoUserMock: vi.fn() }));
const { resetDemoUserMock, saveBaselineMock, hasBaselineMock } = vi.hoisted(() => ({
resetDemoUserMock: vi.fn(),
saveBaselineMock: vi.fn(async () => {}),
hasBaselineMock: vi.fn(() => true),
}));
vi.mock('../../../src/nest/audit/audit-log.logger', () => logMock);
vi.mock('../../../src/demo/demo-reset', () => ({ resetDemoUser: resetDemoUserMock, saveBaseline: vi.fn(), hasBaseline: vi.fn() }));
vi.mock('../../../src/demo/demo-reset', () => ({ resetDemoUser: resetDemoUserMock, saveBaseline: saveBaselineMock, hasBaseline: hasBaselineMock }));
import { VersionCheckJob } from '../../../src/nest/admin/version-check.job';
import { DemoResetJob } from '../../../src/nest/admin/demo-reset.job';
import type { AdminService } from '../../../src/nest/admin/admin.service';
import type { RuntimeEnvService } from '../../../src/nest/app-config/runtime-env.service';
import type { CronRegistrarService } from '../../../src/nest/scheduling/cron-registrar.service';
import type { DatabaseBackupStrategy } from '../../../src/nest/database/database-backup.interface';
import type { EntityManager } from '@mikro-orm/core';
function registrarStub(enabled = true) {
return {
@@ -26,7 +32,10 @@ function registrarStub(enabled = true) {
};
}
beforeEach(() => vi.clearAllMocks());
beforeEach(() => {
vi.clearAllMocks();
hasBaselineMock.mockReturnValue(true);
});
describe('VersionCheckJob', () => {
it('AJOB-001 — registers the daily 9 AM cron, with no boot log (parity)', () => {
@@ -55,26 +64,32 @@ describe('VersionCheckJob', () => {
});
describe('DemoResetJob', () => {
// The injected backup port is only handed through to demo-reset (mocked
// above), so a sentinel is enough. The EntityManager is what the first
// baseline's request context forks from.
const database = { __sentinel: 'database' } as unknown as DatabaseBackupStrategy;
const em = { fork: vi.fn(() => ({})) } as unknown as EntityManager;
function make(demo: boolean, enabled = true) {
const registrar = registrarStub(enabled);
const runtimeEnv = { isDemoMode: () => demo } as RuntimeEnvService;
return { job: new DemoResetJob(runtimeEnv, registrar as unknown as CronRegistrarService), registrar };
return { job: new DemoResetJob(runtimeEnv, registrar as unknown as CronRegistrarService, database, em), registrar };
}
it('AJOB-004 — registers the hourly server-local cron and logs the banner when demo mode is on', () => {
it('AJOB-004 — registers the hourly server-local cron and logs the banner when demo mode is on', async () => {
const { job, registrar } = make(true);
job.onApplicationBootstrap();
await job.onApplicationBootstrap();
expect(registrar.register).toHaveBeenCalledWith('demo-reset', '0 * * * *', expect.any(Function), { timezone: 'none' });
expect(logMock.logInfo).toHaveBeenCalledWith('Demo hourly reset scheduled');
});
it('AJOB-005 — stays silent when demo mode is off or the gate is closed', () => {
it('AJOB-005 — stays silent when demo mode is off or the gate is closed', async () => {
const off = make(false);
off.job.onApplicationBootstrap();
await off.job.onApplicationBootstrap();
expect(off.registrar.register).not.toHaveBeenCalled();
const gated = make(true, false);
gated.job.onApplicationBootstrap();
await gated.job.onApplicationBootstrap();
expect(gated.registrar.register).not.toHaveBeenCalled();
expect(logMock.logInfo).not.toHaveBeenCalled();
});
@@ -83,9 +98,31 @@ describe('DemoResetJob', () => {
const { job } = make(true);
await job.tick();
expect(resetDemoUserMock).toHaveBeenCalledTimes(1);
expect(resetDemoUserMock).toHaveBeenCalledWith(database);
resetDemoUserMock.mockImplementation(() => { throw new Error('baseline gone'); });
expect(() => job.tick()).not.toThrow();
expect(logMock.logError).toHaveBeenCalledWith('Demo reset: baseline gone');
});
it('AJOB-007: a demo boot without a baseline saves the first one through the port, gate or not', async () => {
hasBaselineMock.mockReturnValue(false);
const { job } = make(true, false);
await job.onApplicationBootstrap();
expect(saveBaselineMock).toHaveBeenCalledWith(database);
});
it('AJOB-008: an existing baseline is left alone, and so is a non-demo boot', async () => {
await make(true).job.onApplicationBootstrap();
hasBaselineMock.mockReturnValue(false);
await make(false).job.onApplicationBootstrap();
expect(saveBaselineMock).not.toHaveBeenCalled();
});
it('AJOB-009: a first baseline that cannot be saved is logged, not thrown into the boot', async () => {
hasBaselineMock.mockReturnValue(false);
saveBaselineMock.mockRejectedValueOnce(new Error('database or disk is full'));
await expect(make(true).job.onApplicationBootstrap()).resolves.toBeUndefined();
expect(logMock.logError).toHaveBeenCalledWith('Demo baseline: database or disk is full');
});
});
+20 -10
View File
@@ -112,6 +112,7 @@ import { createTestJourneyShareTokensRepo } from '../../helpers/journey-share-re
import { createTestPushSubscriptionsRepo } from '../../helpers/notifications-repos';
import { createTestBudgetSettlementsRepo } from '../../helpers/budget-repos';
import { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import type { DatabaseBackupStrategy } from '../../../src/nest/database/database-backup.interface';
const realtime = new RealtimeService();
@@ -128,6 +129,15 @@ let auth: AuthService;
let svc: AdminService;
let mcpTokensRepo: McpTokensRepository;
let auditLogRepo: AuditLogRepository;
// The database backup port AdminService injects for the demo baseline route.
// Its snapshot fails, which is the failure ADMIN-SVC-095 needs the real
// saveBaseline() to meet.
const databaseBackupStub = {
canSnapshot: () => true,
snapshot: async () => {
throw new Error('database or disk is full');
},
} as unknown as DatabaseBackupStrategy;
beforeAll(async () => {
webauthn = new WebauthnConfigService(await createTestAppSettingsRepo(testDb));
permissions = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
@@ -163,6 +173,7 @@ beforeAll(async () => {
userCleanup,
realtime,
await createTestUnitOfWork(testDb),
databaseBackupStub,
);
});
@@ -428,16 +439,15 @@ describe('saveDemoBaseline', () => {
// it, so a copy failure (proven live in task-4-review.md with a real
// EISDIR from fs.copyFileSync) went nowhere — the route answered 200 and
// the rejection later surfaced as an unhandled rejection that crashed the
// process. This suite's dynamic require()s of demo-reset.ts (and, inside
// it, db/database.ts) bypass this file's top-of-file vi.mock, same
// documented limitation as ADMIN-SVC-051 — so instead of mocking, this
// test lets the REAL saveBaseline() run with no RequestContext
// established, which deterministically rejects at its own
// requireEntityManager() guard: the same "the copy failed" shape a real
// EISDIR would produce, without touching the filesystem. Awaiting that
// rejection (the fix) means the service's own try/catch converts it into
// the legacy 500 body, and this test resolving cleanly (not hanging, no
// unhandledRejection) is itself proof the rejection was actually caught.
// process. This suite's dynamic require()s of demo-reset.ts bypass this
// file's top-of-file vi.mock, same documented limitation as ADMIN-SVC-051,
// so the REAL saveBaseline() runs here, against the injected database port
// whose snapshot rejects (`databaseBackupStub` above): the same "the save
// failed" shape a full disk would produce, without touching the
// filesystem. Awaiting that rejection (the fix) means the service's own
// try/catch converts it into the legacy 500 body, and this test resolving
// cleanly (not hanging, no unhandledRejection) is itself proof the
// rejection was actually caught.
it('ADMIN-SVC-095 — a failed baseline save is awaited and answers the legacy 500, not an unhandled rejection', async () => {
vi.stubEnv('DEMO_MODE', 'true');
const result = await saveDemoBaseline();
@@ -88,6 +88,7 @@ import { createTestJourneyShareTokensRepo } from '../../helpers/journey-share-re
import { createTestPushSubscriptionsRepo } from '../../helpers/notifications-repos';
import { createTestBudgetSettlementsRepo } from '../../helpers/budget-repos';
import { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import type { DatabaseBackupStrategy } from '../../../src/nest/database/database-backup.interface';
const realtime = new RealtimeService();
@@ -102,6 +103,8 @@ let permissions: PermissionsService;
let userCleanup: UserCleanupService;
let auth: AuthService;
let svc: AdminService;
// The demo baseline route's database port; nothing here reaches it.
const databaseBackupStub = {} as unknown as DatabaseBackupStrategy;
beforeAll(async () => {
webauthn = new WebauthnConfigService(await createTestAppSettingsRepo(testDb));
permissions = new PermissionsService(await createTestAppSettingsRepo(testDb), await createTestUnitOfWork(testDb));
@@ -135,6 +138,7 @@ beforeAll(async () => {
userCleanup,
realtime,
await createTestUnitOfWork(testDb),
databaseBackupStub,
);
});
const checkAndNotifyVersion = () => svc.checkAndNotifyVersion();
@@ -214,20 +214,23 @@ describe('BackupService (wrapper)', () => {
// The impl module is fully mocked above, so an empty sentinel stands in for
// the injected StorageService — the wrapper's job is passing it through.
const storage = { __sentinel: 'storage' } as unknown as import('../../../src/nest/storage/storage.service').StorageService;
const wrapper = new RealBackupService(storage);
// Same for the injected database port: a backup and a restore get it next to
// the storage, everything else does not need it.
const database = { __sentinel: 'database' } as unknown as import('../../../src/nest/database/database-backup.interface').DatabaseBackupStrategy;
const wrapper = new RealBackupService(storage, database);
it('forwards every call straight to the legacy backup service', async () => {
expect(await wrapper.listBackups()).toEqual([{ filename: 'svc.zip' }]);
expect(backupSvc.listBackups).toHaveBeenCalledWith(storage);
await expect(wrapper.createBackup()).resolves.toEqual({ filename: 'svc.zip', size: 5 });
expect(backupSvc.createBackup).toHaveBeenCalled();
await expect(wrapper.createBackup('auto-backup')).resolves.toEqual({ filename: 'svc.zip', size: 5 });
expect(backupSvc.createBackup).toHaveBeenCalledWith({ storage, database }, 'auto-backup');
await expect(wrapper.restoreFromZip('/tmp/a.zip')).resolves.toEqual({ success: true });
expect(backupSvc.restoreFromZip).toHaveBeenCalledWith(storage, '/tmp/a.zip');
expect(backupSvc.restoreFromZip).toHaveBeenCalledWith({ storage, database }, '/tmp/a.zip');
await expect(wrapper.restoreBackup('svc.zip')).resolves.toEqual({ success: true });
expect(backupSvc.restoreBackup).toHaveBeenCalledWith(storage, 'svc.zip');
expect(backupSvc.restoreBackup).toHaveBeenCalledWith({ storage, database }, 'svc.zip');
await wrapper.deleteBackup('svc.zip');
expect(backupSvc.deleteBackup).toHaveBeenCalledWith(storage, 'svc.zip');
+181 -99
View File
@@ -2,7 +2,7 @@
* Unit tests for backupService.
* Covers BACKUP-031 to BACKUP-060.
*/
import { describe, it, expect, vi, beforeEach, onTestFinished } from 'vitest';
import { describe, it, expect, vi, beforeEach } from 'vitest';
// ---------------------------------------------------------------------------
// Hoisted mocks — must be defined before any vi.mock() calls
@@ -55,18 +55,10 @@ const dbMock = vi.hoisted(() => ({
isOwner: vi.fn(),
}));
// Plan 3i Task 3 (R1): BK1/BK2 (the WAL checkpoint, the VACUUM INTO
// snapshot) now go through MaintenanceRepository, resolved via
// RequestContext.getEntityManager() — a real static accessor this unit-test
// file does not mock (it boots neither a real MikroORM nor a real Nest
// request), so it genuinely returns `undefined` here, the same as it would
// for any caller outside a request context. `maintenanceRepoMock` proves the
// NEGATIVE: the two `if (em)`/`if (!em) throw` guards correctly detect the
// missing context and take the best-effort/fallback path WITHOUT ever
// constructing MaintenanceRepository — not a spy standing in for a real
// snapshot (that positive case is `MaintenanceRepository.test.ts`'s own
// unit coverage, plus the real ORM/request-context boot in
// `tests/e2e/backup.e2e.test.ts`).
// The database port's SQLite implementation is built for real below with this
// stand-in for the MaintenanceRepository Nest injects into it: the WAL
// checkpoint and the VACUUM INTO snapshot are what a backup and a restore ask
// of it. The real statements are MaintenanceRepository.test.ts's coverage.
const maintenanceRepoMock = vi.hoisted(() => ({
walCheckpoint: vi.fn().mockResolvedValue(undefined),
vacuumInto: vi.fn().mockResolvedValue(undefined),
@@ -75,11 +67,6 @@ const maintenanceRepoMock = vi.hoisted(() => ({
const logMock = vi.hoisted(() => ({ logInfo: vi.fn(), logError: vi.fn(), logWarn: vi.fn(), logDebug: vi.fn() }));
vi.mock('../../../src/db/database', () => dbMock);
vi.mock('../../../src/db/repositories/MaintenanceRepository', () => ({
MaintenanceRepository: vi.fn().mockImplementation(function () {
return maintenanceRepoMock;
}),
}));
vi.mock('../../../src/nest/audit/audit-log.logger', () => logMock);
vi.mock('../../../src/config', () => ({
JWT_SECRET: 'test-secret',
@@ -105,6 +92,41 @@ import {
sendBackupToResponse,
} from '../../../src/nest/backup/backup.impl';
import type { StorageService } from '../../../src/nest/storage/storage.service';
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
import type { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import path from 'node:path';
// ---------------------------------------------------------------------------
// The database port. The real SqliteDatabaseBackup over a lifecycle stand-in:
// closing and reopening go to the mocked db/database module (so the closeDb/
// reinitialize assertions below keep pinning the swap), and the database file
// is whatever `liveDb.file` says, data/travel.db unless a case moves it the
// way TREK_DB_FILE does.
// ---------------------------------------------------------------------------
const DEFAULT_LIVE_DB = path.join(__dirname, '../../../data/travel.db');
const liveDb = { file: DEFAULT_LIVE_DB };
beforeEach(() => {
liveDb.file = DEFAULT_LIVE_DB;
});
const lifecycleStub = {
get file() {
return liveDb.file;
},
close: () => dbMock.closeDb(),
reopen: async () => {
await dbMock.reinitialize();
},
} as unknown as DatabaseLifecycle;
function deps(storage: StorageService) {
return {
storage,
database: new SqliteDatabaseBackup(lifecycleStub, maintenanceRepoMock as unknown as MaintenanceRepository),
};
}
// ---------------------------------------------------------------------------
// Storage stub — backup.impl functions receive StorageService as a parameter
@@ -380,7 +402,7 @@ describe('BACKUP-036 createBackup', () => {
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(2048) });
const result = await createBackup(storage);
const result = await createBackup(deps(storage));
expect(result.filename).toMatch(/^backup-.*\.zip$/);
expect(result.size).toBe(2048);
@@ -408,7 +430,7 @@ describe('BACKUP-036 createBackup', () => {
}),
});
await createBackup(storage);
await createBackup(deps(storage));
expect(storage.getLocalPathOrNull).toHaveBeenCalledWith('files', 'a.pdf');
expect(storage.getLocalPathOrNull).toHaveBeenCalledWith('journey', 'thumbs/x.jpg');
@@ -446,7 +468,7 @@ describe('BACKUP-036 createBackup', () => {
}),
});
await createBackup(storage);
await createBackup(deps(storage));
expect(storage.getLocalPathOrNull).toHaveBeenCalledWith('files', 'remote.pdf');
expect(storage.getStream).toHaveBeenCalledWith('files', 'remote.pdf');
@@ -478,7 +500,7 @@ describe('BACKUP-036 createBackup', () => {
archiverMock.mockReturnValue(archiverInstanceMock);
const storage = stubStorage();
await expect(createBackup(storage)).rejects.toThrow('ENOENT');
await expect(createBackup(deps(storage))).rejects.toThrow('ENOENT');
expect(storage.put).not.toHaveBeenCalled();
});
@@ -492,7 +514,7 @@ describe('BACKUP-036 createBackup', () => {
health: vi.fn(() => ({ replicaFailures: [{ backend: 'nas-backups', key: 'backup-x.zip', error: 'EIO' }] })),
});
const result = await createBackup(storage);
const result = await createBackup(deps(storage));
expect(result.filename).toMatch(/^backup-.*\.zip$/);
expect(storage.put).toHaveBeenCalledOnce();
@@ -511,7 +533,7 @@ describe('BACKUP-036 createBackup', () => {
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(2048) });
await createBackup(storage);
await createBackup(deps(storage));
// the consistent snapshot of the data tree is archived under plugins-data/
expect(archiverInstanceMock.directory).toHaveBeenCalledWith(expect.stringContaining('plugins-snap'), 'plugins-data');
@@ -522,21 +544,30 @@ describe('BACKUP-036 createBackup', () => {
expect(archiverInstanceMock.directory).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/plugins-snap-backup-'), 'plugins-data');
});
it('BACKUP-036b — a missing request context (no EntityManager) is swallowed, best-effort, same as a WAL checkpoint failure (non-critical)', async () => {
// Plan 3i Task 3: BK1 resolves RequestContext.getEntityManager() — a
// real, unmocked static accessor here — which is genuinely `undefined`
// outside a request context (this suite boots no Nest app), so
// MaintenanceRepository is never even constructed; the backup must still
// succeed either way, matching the legacy `db.exec` throw case's own
// "should not throw" guarantee.
it('BACKUP-036b: a failed WAL checkpoint is logged and the backup still goes ahead (best effort)', async () => {
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
maintenanceRepoMock.walCheckpoint.mockRejectedValueOnce(new Error('database is locked'));
const storage = stubStorage({ stat: statOf(512) });
const result = await createBackup(storage);
const result = await createBackup(deps(storage));
expect(result).toHaveProperty('filename');
expect(result.size).toBe(512);
expect(maintenanceRepoMock.walCheckpoint).not.toHaveBeenCalled();
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('WAL checkpoint before the snapshot failed (database is locked)'));
});
it('BACKUP-036t: a failure that is not an Error is still named in the log and the thrown error', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db'));
setupArchiveSuccess();
maintenanceRepoMock.walCheckpoint.mockRejectedValueOnce('SQLITE_BUSY');
maintenanceRepoMock.vacuumInto.mockRejectedValueOnce('SQLITE_FULL');
const storage = stubStorage({ stat: statOf(512) });
await expect(createBackup(deps(storage))).rejects.toThrow('Database snapshot failed: SQLITE_FULL');
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('(SQLITE_BUSY)'));
expect(storage.put).not.toHaveBeenCalled();
});
it('BACKUP-036c — archiver error cleans up the spool staging, skips put and re-throws', async () => {
@@ -552,46 +583,81 @@ describe('BACKUP-036 createBackup', () => {
archiverMock.mockReturnValue(archiverInstanceMock);
const storage = stubStorage();
await expect(createBackup(storage)).rejects.toThrow('disk full');
await expect(createBackup(deps(storage))).rejects.toThrow('disk full');
// 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; falls back to archiving the live file when no EntityManager is available for the VACUUM INTO snapshot', async () => {
// Plan 3i Task 3 (R1): the positive "snapshots into the spool" case (a
// real EntityManager, VACUUM INTO succeeding) is `MaintenanceRepository
// .test.ts`'s own unit coverage (MAINTREPO-002/003) plus the real
// request-context boot in `tests/e2e/backup.e2e.test.ts` — this
// heavily-mocked unit-test file boots no Nest app, so
// RequestContext.getEntityManager() is genuinely `undefined` here,
// exercising the SAME fallback path a real disk/lock VACUUM INTO
// failure would: MaintenanceRepository is never constructed, and the
// checkpointed live file is archived instead of a missing snapshot.
it('BACKUP-036d: archives a VACUUM INTO snapshot of the database, never the live file', async () => {
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db'));
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
await createBackup(storage);
await createBackup(deps(storage));
expect(maintenanceRepoMock.vacuumInto).not.toHaveBeenCalled();
expect(maintenanceRepoMock.walCheckpoint).toHaveBeenCalled();
expect(maintenanceRepoMock.vacuumInto).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/travel-snap-backup-'));
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringMatching(/travel\.db$/),
expect.stringContaining('/stub/spool/travel-snap-backup-'),
{ name: 'travel.db' },
);
expect(archiverInstanceMock.file).not.toHaveBeenCalledWith(
expect.stringContaining('travel-snap-backup-'),
expect.anything(),
expect(archiverInstanceMock.file).not.toHaveBeenCalledWith(DEFAULT_LIVE_DB, expect.anything());
// The scratch snapshot goes with the rest of the spool.
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('travel-snap-backup-'), { force: true });
});
it('BACKUP-036q: a failed VACUUM INTO fails the backup: no live file archived, nothing committed, said in the log', async () => {
// This used to fall back to archiving the live WAL-mode file without a
// word: the torn copy the snapshot exists to prevent, passed off as a
// good backup.
fsMock.existsSync.mockImplementation((p: string) => String(p).endsWith('travel.db'));
setupArchiveSuccess();
maintenanceRepoMock.vacuumInto.mockRejectedValueOnce(new Error('database or disk is full'));
const storage = stubStorage({ stat: statOf(1024) });
await expect(createBackup(deps(storage))).rejects.toThrow('Database snapshot failed: database or disk is full');
// Nothing was archived and nothing reached the backups store, so the
// existing backups are exactly what they were.
expect(archiverMock).not.toHaveBeenCalled();
expect(archiverInstanceMock.file).not.toHaveBeenCalled();
expect(storage.put).not.toHaveBeenCalled();
// A partial snapshot and the spool are cleaned up.
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('travel-snap-backup-'), { force: true });
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('zip-build-backup-'), { force: true });
expect(logMock.logError).toHaveBeenCalledWith(expect.stringContaining('could not take a snapshot of the database'));
expect(logMock.logError).toHaveBeenCalledWith(expect.stringContaining('No backup was written'));
});
it('BACKUP-036r: backs up the database the connection runs on when TREK_DB_FILE moves it out of data/', async () => {
// The old code looked for data/travel.db only: with the database elsewhere
// the backup silently held no database at all.
liveDb.file = path.join(path.sep, 'srv', 'trek', 'custom-name.db');
fsMock.existsSync.mockImplementation((p: string) => p === liveDb.file);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
await createBackup(deps(storage));
expect(maintenanceRepoMock.vacuumInto).toHaveBeenCalledWith(expect.stringContaining('/stub/spool/travel-snap-backup-'));
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringContaining('/stub/spool/travel-snap-backup-'),
{ name: 'travel.db' },
);
// Plan 3i Task 4 fix wave (should-land 7): the missing-EntityManager
// fallback used to be entirely silent — same swallowed shape as a real
// disk/lock VACUUM INTO failure, with no way for an operator to tell
// "archived the live file because no request context wrapped this run"
// apart from any other reason. Both guards (BK1's checkpoint skip, BK2's
// snapshot skip) now log a warning; the fallback itself is unchanged.
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('skipping the WAL checkpoint'));
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('archiving the live travel.db instead of a VACUUM INTO snapshot'));
});
it('BACKUP-036s: no database file to copy is said in the log, not passed over in silence', async () => {
fsMock.existsSync.mockReturnValue(false);
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
await createBackup(deps(storage));
expect(maintenanceRepoMock.vacuumInto).not.toHaveBeenCalled();
expect(archiverInstanceMock.file).not.toHaveBeenCalledWith(expect.anything(), { name: 'travel.db' });
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('this backup holds no database'));
});
it('BACKUP-036e — excludes the re-derivable photo caches nested under photos/', async () => {
@@ -607,7 +673,7 @@ describe('BACKUP-036 createBackup', () => {
}),
});
await createBackup(storage);
await createBackup(deps(storage));
expect(archiverInstanceMock.file).toHaveBeenCalledWith('/stub/local/path', { name: 'uploads/photos/flat.jpg', store: true });
const names = archiverInstanceMock.file.mock.calls.map(c => c[1]?.name as string);
@@ -625,7 +691,7 @@ describe('BACKUP-036 createBackup', () => {
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
await createBackup(storage);
await createBackup(deps(storage));
expect(archiverInstanceMock.glob).not.toHaveBeenCalled();
const listed = (storage.list as ReturnType<typeof vi.fn>).mock.calls.map(c => c[0] as string);
@@ -641,7 +707,7 @@ describe('BACKUP-036 createBackup', () => {
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
await createBackup(storage);
await createBackup(deps(storage));
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringContaining('.encryption_key'),
@@ -658,7 +724,7 @@ describe('BACKUP-036 createBackup', () => {
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
await createBackup(storage);
await createBackup(deps(storage));
expect(archiverInstanceMock.file).not.toHaveBeenCalledWith(
expect.stringContaining('.encryption_key'),
@@ -666,22 +732,18 @@ describe('BACKUP-036 createBackup', () => {
);
});
it('BACKUP-036i — the auto-backup prefix names the zip (the scratch snapshot naming, `travel-snap-auto-backup-*`, is MaintenanceRepository.test.ts\'s own coverage)', async () => {
it('BACKUP-036i: the auto-backup prefix names the zip and the scratch snapshot', async () => {
// 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'));
setupArchiveSuccess();
const storage = stubStorage({ stat: statOf(1024) });
const result = await createBackup(storage, 'auto-backup');
const result = await createBackup(deps(storage), 'auto-backup');
expect(result.filename).toMatch(/^auto-backup-.*\.zip$/);
// No real EntityManager in this unit-test file (see BACKUP-036d) — the
// VACUUM INTO snapshot falls back to the live file, same as the default
// prefix's case; the auto-backup-specific behaviour this test pins is
// the zip/put naming, not the (unreachable here) snapshot path.
expect(archiverInstanceMock.file).toHaveBeenCalledWith(
expect.stringMatching(/travel\.db$/),
expect.stringContaining('travel-snap-auto-backup-'),
{ name: 'travel.db' },
);
expect(storage.put).toHaveBeenCalledWith('backups', result.filename, {
@@ -742,7 +804,7 @@ describe('BACKUP-038 restoreFromZip', () => {
});
fsMock.rmSync.mockReturnValue(undefined);
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result.success).toBe(false);
expect(result.error).toMatch(/travel\.db not found/i);
@@ -754,7 +816,7 @@ describe('BACKUP-038 restoreFromZip', () => {
files: [{ uncompressedSize: 6 * 1024 * 1024 * 1024 }], // 6 GB > 5 GB cap
});
const result = await restoreFromZip(stubStorage(), '/data/tmp/bomb.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/bomb.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -824,7 +886,7 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
it('BACKUP-061a — refuses an entry whose path escapes the archive root (zip-slip)', async () => {
unzipperMock.Open.file.mockResolvedValueOnce({ files: [zipEntry('../../etc/passwd')] });
const result = await restoreFromZip(stubStorage(), '/data/tmp/slip.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/slip.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -842,7 +904,7 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
it.runIf(process.platform === 'win32')('BACKUP-061b — a drive-letter entry path is refused the same way', async () => {
unzipperMock.Open.file.mockResolvedValueOnce({ files: [zipEntry('C:/Windows/system32/evil.dll')] });
const result = await restoreFromZip(stubStorage(), '/data/tmp/abs.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/abs.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -856,7 +918,7 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
// What happens after extraction is BACKUP-042..045's business; this case only
// cares that the directory entry never reached the writer.
await restoreFromZip(stubStorage(), '/data/tmp/dirs.zip').catch(() => undefined);
await restoreFromZip(deps(stubStorage()), '/data/tmp/dirs.zip').catch(() => undefined);
expect(fsMock.createWriteStream).toHaveBeenCalledTimes(1);
});
@@ -868,7 +930,7 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
lying.uncompressedSize = 8;
unzipperMock.Open.file.mockResolvedValueOnce({ files: [lying] });
const result = await restoreFromZip(stubStorage(), '/data/tmp/liar.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/liar.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -896,7 +958,7 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
// A corrupt stream is NOT dressed up as a 400 "too large": it leaves the function
// as a throw, which is what makes the controller answer 500 rather than telling the
// admin their perfectly-sized backup is over the cap.
await expect(restoreFromZip(stubStorage(), '/data/tmp/corrupt.zip')).rejects.toThrow('corrupt deflate stream');
await expect(restoreFromZip(deps(stubStorage()), '/data/tmp/corrupt.zip')).rejects.toThrow('corrupt deflate stream');
expect(fsMock.rmSync).toHaveBeenCalledWith(expect.stringContaining('restore-'), { recursive: true, force: true });
});
@@ -921,7 +983,7 @@ describe('BACKUP-061 restoreFromZip extraction', () => {
});
const storage = stubStorage();
const result = await restoreFromZip(storage, '/data/tmp/ok.zip');
const result = await restoreFromZip(deps(storage), '/data/tmp/ok.zip');
// The files already landed, so this is neither a success nor a plain failure: the
// admin has to restart, and the message has to say so.
@@ -1120,7 +1182,7 @@ describe('BACKUP-042 restoreFromZip — integrity check fails', () => {
return fakeDbInstance;
});
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -1157,7 +1219,7 @@ describe('BACKUP-043 restoreFromZip — missing required table', () => {
return fakeDbInstance;
});
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -1183,7 +1245,7 @@ describe('BACKUP-044 restoreFromZip — Database constructor throws (invalid SQL
throw new Error('file is not a database');
});
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result.success).toBe(false);
expect(result.status).toBe(400);
@@ -1234,7 +1296,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
fsMock.copyFileSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
// The uploaded database is checked through the shared opener, read-only and
@@ -1259,7 +1321,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
return true;
});
await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(callOrder.indexOf('closeDb')).toBeLessThan(callOrder.indexOf('copyFileSync'));
});
@@ -1267,9 +1329,6 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
it('BACKUP-045g: keeps a copy of the database it replaces, before closing it', async () => {
setupSuccessfulExtraction();
setupAllTablesPresent();
const { RequestContext } = await import('@mikro-orm/core');
const em = vi.spyOn(RequestContext, 'getEntityManager').mockReturnValue({} as never);
onTestFinished(() => em.mockRestore());
const callOrder: string[] = [];
maintenanceRepoMock.vacuumInto.mockImplementation(async (target: string) => { callOrder.push(`vacuum:${target}`); });
@@ -1278,25 +1337,48 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
fsMock.rmSync.mockReturnValue(undefined);
fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads'));
await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(callOrder[0]).toMatch(/^vacuum:.*pre-restore-\d+\.db$/);
expect(callOrder.indexOf('closeDb')).toBeGreaterThan(0);
expect(logMock.logInfo).toHaveBeenCalledWith(expect.stringContaining('the replaced database was kept as'));
});
it('BACKUP-045i: swaps the archive into the database the connection runs on when TREK_DB_FILE moves it', async () => {
// The restore used to write data/travel.db whatever TREK_DB_FILE said: the
// live database was never replaced and the restore reported success.
setupSuccessfulExtraction();
setupAllTablesPresent();
liveDb.file = path.join(path.sep, 'srv', 'trek', 'custom-name.db');
maintenanceRepoMock.vacuumInto.mockResolvedValue(undefined);
fsMock.unlinkSync.mockReturnValue(undefined);
fsMock.copyFileSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads') && !String(p).endsWith('.encryption_key'));
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
const tmp = liveDb.file + '.restore-tmp';
expect(fsMock.copyFileSync).toHaveBeenCalledWith(expect.stringMatching(/restore-\d+[\\/]travel\.db$/), tmp);
expect(fsMock.renameSync).toHaveBeenCalledWith(tmp, liveDb.file);
expect(fsMock.unlinkSync).toHaveBeenCalledWith(liveDb.file + '-wal');
expect(fsMock.copyFileSync).not.toHaveBeenCalledWith(expect.anything(), DEFAULT_LIVE_DB + '.restore-tmp');
// The safety copy sits next to that database too.
expect(maintenanceRepoMock.vacuumInto).toHaveBeenCalledWith(
expect.stringMatching(/[\\/]srv[\\/]trek[\\/]pre-restore-\d+\.db$/),
);
});
it('BACKUP-045h: a database that cannot be copied does not block the restore', async () => {
setupSuccessfulExtraction();
setupAllTablesPresent();
const { RequestContext } = await import('@mikro-orm/core');
const em = vi.spyOn(RequestContext, 'getEntityManager').mockReturnValue({} as never);
onTestFinished(() => em.mockRestore());
maintenanceRepoMock.vacuumInto.mockRejectedValueOnce(new Error('database disk image is malformed'));
fsMock.unlinkSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
fsMock.existsSync.mockImplementation((p: string) => !String(p).includes('uploads'));
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result.success).toBe(true);
expect(logMock.logWarn).toHaveBeenCalledWith(expect.stringContaining('could not keep a copy of the current database'));
@@ -1318,7 +1400,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
});
fsMock.rmSync.mockReturnValue(undefined);
await expect(restoreFromZip(stubStorage(), '/data/tmp/upload.zip')).rejects.toThrow('disk full');
await expect(restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip')).rejects.toThrow('disk full');
expect(dbMock.reinitialize).toHaveBeenCalled();
});
@@ -1337,7 +1419,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
fsMock.copyFileSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
// Key copied from the extract dir into the live data dir.
@@ -1361,7 +1443,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
fsMock.copyFileSync.mockReturnValue(undefined);
fsMock.rmSync.mockReturnValue(undefined);
const result = await restoreFromZip(stubStorage(), '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(stubStorage()), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
expect(fsMock.copyFileSync).not.toHaveBeenCalledWith(
@@ -1398,7 +1480,7 @@ describe('BACKUP-045 restoreFromZip — full success path (no uploads)', () => {
put: vi.fn(async () => { callOrder.push('put:rehydrate'); }),
});
const result = await restoreFromZip(storage, '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(storage), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
expect(callOrder).toEqual(['reinitialize', 'reloadConfig', 'put:rehydrate']);
@@ -1481,7 +1563,7 @@ describe('BACKUP-046 restoreFromZip — uploads rehydration through storage', ()
}),
});
const result = await restoreFromZip(storage, '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(storage), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
// wipe: bare keys deleted in every archived category, nested keys never
@@ -1514,7 +1596,7 @@ describe('BACKUP-046 restoreFromZip — uploads rehydration through storage', ()
}),
});
const result = await restoreFromZip(storage, '/data/tmp/upload.zip');
const result = await restoreFromZip(deps(storage), '/data/tmp/upload.zip');
expect(result).toEqual({ success: true });
// unknown top-level dir + top-level file + invalid key: all skipped, warned
@@ -1535,7 +1617,7 @@ describe('BACKUP-046 restoreFromZip — uploads rehydration through storage', ()
put: vi.fn(async () => { throw new Error('ENOSPC: no space left'); }),
});
await expect(restoreFromZip(storage, '/data/tmp/upload.zip')).rejects.toThrow('ENOSPC');
await expect(restoreFromZip(deps(storage), '/data/tmp/upload.zip')).rejects.toThrow('ENOSPC');
// the DB reopen still ran (finally) — the process is never left closed
expect(dbMock.reinitialize).toHaveBeenCalled();
});
@@ -1555,7 +1637,7 @@ describe('BACKUP-063 restoreBackup', () => {
withLocalFile: vi.fn(async () => ({ success: true })),
});
await expect(restoreBackup(storage, 'backup-2026-01-01T00-00-00.zip')).resolves.toEqual({ success: true });
await expect(restoreBackup(deps(storage), 'backup-2026-01-01T00-00-00.zip')).resolves.toEqual({ success: true });
expect(storage.withLocalFile).toHaveBeenCalledWith('backups', 'backup-2026-01-01T00-00-00.zip', expect.any(Function));
});
@@ -1566,7 +1648,7 @@ describe('BACKUP-063 restoreBackup', () => {
unzipperMock.Open.file.mockResolvedValue({ files: [] });
const storage = stubStorage();
const result = await restoreBackup(storage, 'backup-2026-01-01T00-00-00.zip');
const result = await restoreBackup(deps(storage), 'backup-2026-01-01T00-00-00.zip');
expect(result).toEqual({ success: false, error: 'Invalid backup: travel.db not found', status: 400 });
});
@@ -0,0 +1,217 @@
/**
* SqliteDatabaseBackup: the database backup port for a SQLite file.
*
* The snapshot and the swap run for real here, against a database file in a
* temp directory: a VACUUM INTO through the real MaintenanceRepository, and the
* copy, sidecar removal and rename of a restore. Only the connection lifecycle
* is a stand-in, because closing and reopening the process's own connection is
* DatabaseLifecycle's business (tests/unit/nest/database/).
*/
import fs from 'node:fs';
import os from 'node:os';
import path from 'node:path';
import Database from 'better-sqlite3';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const logMock = vi.hoisted(() => ({ LOG_LEVEL: 'error', logInfo: vi.fn(), logWarn: vi.fn(), logError: vi.fn(), logDebug: vi.fn() }));
vi.mock('../../../src/nest/audit/audit-log.logger', () => logMock);
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
import { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
import { withRequestContext } from '../../../src/nest/database/request-context';
import { createTestOrm, type TestOrm } from '../../helpers/test-orm';
let dir: string;
let liveFile: string;
let lifecycle: { file: string; close: ReturnType<typeof vi.fn>; reopen: ReturnType<typeof vi.fn> };
function maintenanceStub() {
return { walCheckpoint: vi.fn(async () => {}), vacuumInto: vi.fn(async (_target: string) => {}) };
}
function portWith(maintenance: { walCheckpoint: unknown; vacuumInto: unknown }): SqliteDatabaseBackup {
return new SqliteDatabaseBackup(lifecycle as unknown as DatabaseLifecycle, maintenance as unknown as MaintenanceRepository);
}
function writeDb(file: string, label: string): void {
const db = new Database(file);
db.exec('CREATE TABLE marker (label TEXT NOT NULL)');
db.prepare('INSERT INTO marker (label) VALUES (?)').run(label);
db.close();
}
function readLabel(file: string): string {
const db = new Database(file, { readonly: true });
try {
return (db.prepare('SELECT label FROM marker').get() as { label: string }).label;
} finally {
db.close();
}
}
beforeEach(() => {
vi.clearAllMocks();
dir = fs.mkdtempSync(path.join(os.tmpdir(), 'trek-sqlite-backup-'));
liveFile = path.join(dir, 'live.db');
lifecycle = { file: liveFile, close: vi.fn(), reopen: vi.fn(async () => {}) };
});
afterEach(() => {
fs.rmSync(dir, { recursive: true, force: true });
});
describe('SqliteDatabaseBackup', () => {
it('SQLBK-001: names the archive entry travel.db and reports the file the connection runs on', () => {
const port = portWith(maintenanceStub());
expect(port.archiveEntry).toBe('travel.db');
expect(port.location()).toBe(liveFile);
});
it('SQLBK-002: can snapshot an existing file, never the in-memory database or a missing file', () => {
const port = portWith(maintenanceStub());
expect(port.canSnapshot()).toBe(false);
writeDb(liveFile, 'live');
expect(port.canSnapshot()).toBe(true);
lifecycle.file = ':memory:';
expect(port.canSnapshot()).toBe(false);
});
it('SQLBK-003: the checkpoint is the WAL checkpoint', async () => {
const maintenance = maintenanceStub();
await portWith(maintenance).checkpoint();
expect(maintenance.walCheckpoint).toHaveBeenCalledTimes(1);
});
describe('snapshot, through the real VACUUM INTO', () => {
let live: Database.Database;
let orm: TestOrm;
beforeEach(async () => {
writeDb(liveFile, 'live');
live = new Database(liveFile);
live.exec('PRAGMA journal_mode = WAL');
orm = await createTestOrm(live);
});
afterEach(async () => {
await orm.close();
live.close();
});
it('SQLBK-004: writes a consistent copy of the live database', async () => {
// A write that sits in the WAL only: VACUUM INTO still carries it.
live.prepare('UPDATE marker SET label = ?').run('after');
const target = path.join(dir, 'copy.db');
const port = portWith(new MaintenanceRepository(orm.em));
await withRequestContext(orm.orm, () => port.snapshot(target));
expect(readLabel(target)).toBe('after');
});
it('SQLBK-005: a VACUUM INTO that fails rejects and leaves nothing at the target', async () => {
const target = path.join(dir, 'missing-dir', 'copy.db');
const port = portWith(new MaintenanceRepository(orm.em));
await expect(withRequestContext(orm.orm, () => port.snapshot(target))).rejects.toThrow();
expect(fs.existsSync(target)).toBe(false);
});
});
it('SQLBK-006: a partial file a failed snapshot left behind is removed before the error goes on', async () => {
const target = path.join(dir, 'partial.db');
const maintenance = maintenanceStub();
maintenance.vacuumInto.mockImplementationOnce(async (to: string) => {
fs.writeFileSync(to, 'half a database');
throw new Error('database or disk is full');
});
await expect(portWith(maintenance).snapshot(target)).rejects.toThrow('database or disk is full');
expect(fs.existsSync(target)).toBe(false);
});
it('SQLBK-007: verify refuses an unpacked archive without a database', () => {
expect(portWith(maintenanceStub()).verify(dir)).toEqual({ error: 'Invalid backup: travel.db not found', status: 400 });
});
it('SQLBK-008: keeps a copy of the database a restore replaces next to it, and says where', async () => {
const maintenance = maintenanceStub();
const kept = await portWith(maintenance).keepCopyBeforeRestore();
expect(kept).not.toBeNull();
expect(path.dirname(kept as string)).toBe(dir);
expect(path.basename(kept as string)).toMatch(/^pre-restore-\d+\.db$/);
expect(maintenance.vacuumInto).toHaveBeenCalledWith(kept);
expect(logMock.logInfo).toHaveBeenCalledWith(`Restore: the replaced database was kept as ${kept}`);
});
it('SQLBK-009: a copy that cannot be kept does not block the restore', async () => {
const maintenance = maintenanceStub();
maintenance.vacuumInto.mockRejectedValueOnce('database disk image is malformed');
await expect(portWith(maintenance).keepCopyBeforeRestore()).resolves.toBeNull();
expect(logMock.logWarn).toHaveBeenCalledWith('Restore: could not keep a copy of the current database (database disk image is malformed)');
});
describe('replace', () => {
it('SQLBK-010: closes, swaps the file in by rename, drops the old sidecars and reopens', async () => {
writeDb(liveFile, 'live');
const source = path.join(dir, 'restored.db');
writeDb(source, 'restored');
const liveBytes = fs.readFileSync(liveFile);
const sourceBytes = fs.readFileSync(source);
fs.writeFileSync(liveFile + '-wal', 'stale wal');
fs.writeFileSync(liveFile + '-shm', 'stale shm');
// Which database sits at the live path at each step, told by its bytes:
// no handle is opened on a file whose sidecars are deliberately stale.
const which = () => {
const now = fs.readFileSync(liveFile);
if (now.equals(liveBytes)) return 'live';
return now.equals(sourceBytes) ? 'restored' : 'other';
};
const order: string[] = [];
lifecycle.close.mockImplementation(() => order.push(`close:${which()}`));
lifecycle.reopen.mockImplementation(async () => {
order.push(`reopen:${which()}`);
});
const result = await portWith(maintenanceStub()).replace(source);
expect(result).toEqual({ reopenError: null });
expect(order).toEqual(['close:live', 'reopen:restored']);
expect(fs.existsSync(liveFile + '-wal')).toBe(false);
expect(fs.existsSync(liveFile + '-shm')).toBe(false);
expect(fs.existsSync(liveFile + '.restore-tmp')).toBe(false);
// The source stays: it belongs to the caller (an unpacked archive, the demo baseline).
expect(readLabel(source)).toBe('restored');
});
it('SQLBK-011: a reopen that fails after the swap is reported, not thrown', async () => {
writeDb(liveFile, 'live');
const source = path.join(dir, 'restored.db');
writeDb(source, 'restored');
const failure = new Error('database is locked');
lifecycle.reopen.mockRejectedValueOnce(failure);
const result = await portWith(maintenanceStub()).replace(source);
expect(result.reopenError).toBe(failure);
expect(readLabel(liveFile)).toBe('restored');
});
it('SQLBK-012: a swap that fails still reopens, leaves the live file as it was and rethrows', async () => {
writeDb(liveFile, 'live');
await expect(portWith(maintenanceStub()).replace(path.join(dir, 'does-not-exist.db'))).rejects.toThrow(/ENOENT/);
expect(lifecycle.close).toHaveBeenCalledTimes(1);
expect(lifecycle.reopen).toHaveBeenCalledTimes(1);
expect(readLabel(liveFile)).toBe('live');
});
});
});
+4 -2
View File
@@ -14,7 +14,7 @@ A backup is a ZIP archive with these entries:
| Entry | Contents |
|---|---|
| `travel.db` | The full SQLite database |
| `travel.db` | The full SQLite database, as a consistent snapshot taken while TREK keeps running (writes during the backup cannot tear it) |
| `uploads/` | All uploaded attachments, covers, and avatars (default location — see [Admin: Storage](Admin-Storage)) |
| `plugins-data/` | Each installed plugin's own database + files (present only if plugins are installed) |
| `plugins-code/` | The installed plugin code, so a restore is self-contained (dev-linked plugins are skipped) |
@@ -25,6 +25,8 @@ A backup is a ZIP archive with these entries:
Click **Create Backup** in the Backup tab. The server creates the ZIP and makes it available for download. Up to 3 manual backups can be created per hour per IP address (rate-limit window: 1 hour).
If the database snapshot cannot be taken (a full disk, for example), the backup fails: the server log says why, no new file appears in the list, and the existing backups stay as they were. TREK never falls back to zipping the live database file, which could hold a half-written state.
You can also **Download** or delete any existing backup from the list. Deleting asks first in TREK's own dialog (**Delete backup "name"?**).
## Restoring a backup
@@ -42,7 +44,7 @@ Before restoring, TREK runs integrity checks on the uploaded database:
2. **Required tables present** — confirms the file contains `users`, `trips`, `trip_members`, `places`, and `days`. Files missing any of these are rejected as not being a valid TREK backup.
3. **Not from a newer TREK**: a backup whose database a newer release migrated is refused with `This backup was made by a newer TREK version. Update TREK before restoring it.` Restoring it would leave this version unable to start.
The database being replaced is kept as `data/pre-restore-<time>.db`, so a restore of the wrong archive can be undone by hand. Delete these copies once you no longer need them.
The database being replaced is kept as `pre-restore-<time>.db` next to it (in `data/` on a standard install), so a restore of the wrong archive can be undone by hand. Delete these copies once you no longer need them.
Either way, TREK asks first in a **Restore Backup?** dialog that names the file, warns that all current data (trips, places, users, uploads) will be permanently replaced, and suggests creating a backup of the current state first. **Yes, restore** starts it; when it is done the page reloads.
+2 -2
View File
@@ -52,9 +52,9 @@ The baseline is the snapshot the hourly reset restores to. The admin can update
**Endpoint:** `POST /api/admin/save-demo-baseline`
In the admin panel, a **Demo Baseline** card sits above the tabs while demo mode is on; its **Save Baseline** button calls this endpoint. The baseline captures the current state of the database, trip data, settings and encrypted API keys included, so demo features (maps, photos, weather) continue to work after each reset.
In the admin panel, a **Demo Baseline** card sits above the tabs while demo mode is on; its **Save Baseline** button calls this endpoint. The baseline captures the current state of the database, trip data, settings and encrypted API keys included, so demo features (maps, photos, weather) continue to work after each reset. It is written as a consistent snapshot and only then put in place of the previous baseline, so a save that fails leaves the previous one intact.
On first start with demo mode active, TREK seeds three example trips (Tokyo & Kyoto, Barcelona Long Weekend, New York City) owned by the admin and shared with the demo user, then saves the initial baseline automatically.
On first start with demo mode active, TREK seeds three example trips (Tokyo & Kyoto, Barcelona Long Weekend, New York City) owned by the admin and shared with the demo user. Once the server is up, a demo start that finds no baseline saves the initial one automatically.
## Limitations