feat(db): run TREK on PostgreSQL

TREK runs on PostgreSQL when TREK_DB_URL is set, and on SQLite as before
otherwise: an engine port under src/db/engine, the dialect helpers under
src/db/dialect, a Postgres baseline for the migrations up to the cut,
pg_dump/pg_restore backups, a probe of every repository method against a
real server and a Postgres test lane in CI.
This commit is contained in:
Isaias Tavares
2026-11-05 01:15:21 -03:00
committed by Maurice
parent 17b47b38b9
commit 2e3762afe1
176 changed files with 6728 additions and 777 deletions
+10 -4
View File
@@ -4,7 +4,9 @@ import { UserSessions } from '../../db/entities/UserSessions.entity';
import type { CarriedUserSessionRow } from '../../db/repositories/UserSessions.repository';
import { dbNow } from '../../db/types';
import { logError, logWarn } from '../audit/audit-log.logger';
import type { DatabaseBackupStrategy } from '../database/database-backup.interface';
import { describeError } from '../common/describe-error';
import { DomainError } from '../common/domain-error';
import type { DatabaseBackupRefusal, DatabaseBackupStrategy } from '../database/database-backup.interface';
import { invalidatePermissionsCache } from '../permissions/permissions-cache';
import { snapshotAllPluginDataDbs } from '../plugins/host/plugin-data.service';
import { pluginsCodeRoot, pluginsDataRoot } from '../plugins/paths';
@@ -36,8 +38,6 @@ export interface BackupDeps {
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, encryptionKeyFile, reclaimResetFile } = resolveDataPaths();
@@ -467,6 +467,12 @@ async function restoreCarriedSessions(rows: readonly CarriedUserSessionRow[]): P
}
}
/** The restore route's refusal for a `verify` that threw one. Any other failure is not a refusal, and keeps propagating. */
function refusalOf(err: unknown): DatabaseBackupRefusal {
if (err instanceof DomainError) return { error: err.publicMessage, status: err.getStatus() };
throw err;
}
export async function restoreFromZip({ storage, database }: BackupDeps, zipPath: string): Promise<RestoreResult> {
const extractDir = path.join(dataDir, `restore-${Date.now()}`);
let reinitFailed: unknown;
@@ -474,7 +480,7 @@ export async function restoreFromZip({ storage, database }: BackupDeps, zipPath:
const refused = await extractBackupArchive(zipPath, extractDir);
if (refused) return { success: false, ...refused };
const unreadable = database.verify(extractDir);
const unreadable = await database.verify(extractDir).then(() => null, refusalOf);
if (unreadable) {
fs.rmSync(extractDir, { recursive: true, force: true });
return { success: false, ...unreadable };
+39 -9
View File
@@ -1,5 +1,7 @@
import { pgRestore, pgTableNames } from '../../db/engine/postgres/pg-tools';
import { stageExtractedPluginTrees } from '../plugins/plugin-backup';
import { checkBackupDatabase, extractBackupArchive, markReclaimResetPending } from './backup-archive';
import { checkPostgresDump, PG_ARCHIVE_ENTRY } from './postgres-database-backup';
import fs from 'fs';
import path from 'path';
@@ -47,6 +49,11 @@ export interface BootRestorePlan {
dataDir: string;
/** `data/.trek-reclaim-reset` (data-paths.ts), left before the database is put in place. */
reclaimResetFile: string;
/**
* Set when TREK runs on Postgres (TREK_DB_URL): the archive's dump is loaded
* into the database, which must hold no table yet, instead of `dbFile`.
*/
postgres?: { url: string; binDir: string | undefined };
}
export type BootRestoreOutcome =
@@ -56,11 +63,38 @@ export type BootRestoreOutcome =
export class BootRestoreError extends Error {}
/** A database is there already: on a file, the file; on Postgres, any table in its schema. */
async function existingDatabase(plan: BootRestorePlan): Promise<string | null> {
if (!plan.postgres) return fs.existsSync(plan.dbFile) ? plan.dbFile : null;
const tables = await pgTableNames(plan.postgres.url, plan.postgres.binDir);
return tables.length > 0 ? `the Postgres database (${tables.length} table(s))` : null;
}
/** Why the unpacked archive's database cannot be restored here, or null. */
async function checkArchiveDatabase(plan: BootRestorePlan, staging: string): Promise<string | null> {
if (plan.postgres) return checkPostgresDump(staging, plan.postgres.binDir);
return checkBackupDatabase(staging)?.error ?? null;
}
/** Puts the archive's database in place: renamed in beside the file, or loaded into Postgres in one transaction. */
async function putDatabaseInPlace(plan: BootRestorePlan, staging: string): Promise<void> {
if (plan.postgres) {
await pgRestore(plan.postgres.url, path.join(staging, PG_ARCHIVE_ENTRY), plan.postgres.binDir);
return;
}
fs.mkdirSync(path.dirname(plan.dbFile), { recursive: true });
// Copied in beside the target and renamed, so a crash leaves either nothing or a whole file.
const tmp = `${plan.dbFile}.restore-tmp`;
fs.copyFileSync(path.join(staging, 'travel.db'), tmp);
fs.renameSync(tmp, plan.dbFile);
}
export async function restoreOnFirstBoot(plan: BootRestorePlan): Promise<BootRestoreOutcome> {
if (!plan.archive) return { restored: false, reason: 'unset' };
if (fs.existsSync(plan.dbFile)) {
const existing = await existingDatabase(plan);
if (existing) {
console.warn(
`[restore] RESTORE_FROM_BACKUP is set, but ${plan.dbFile} already exists. The backup is only restored on a first start; remove the variable to silence this.`,
`[restore] RESTORE_FROM_BACKUP is set, but ${existing} already exists. The backup is only restored on a first start; remove the variable to silence this.`,
);
return { restored: false, reason: 'database-exists' };
}
@@ -73,20 +107,16 @@ export async function restoreOnFirstBoot(plan: BootRestorePlan): Promise<BootRes
const refused = await extractBackupArchive(plan.archive, staging);
if (refused) throw new BootRestoreError(`RESTORE_FROM_BACKUP: ${refused.error}`);
const unreadable = checkBackupDatabase(staging);
const unreadable = await checkArchiveDatabase(plan, staging);
if (unreadable) {
fs.rmSync(staging, { recursive: true, force: true });
throw new BootRestoreError(`RESTORE_FROM_BACKUP: ${unreadable.error}`);
throw new BootRestoreError(`RESTORE_FROM_BACKUP: ${unreadable}`);
}
// Storage reclaim drops what the restored database knew about its storage on
// the start that follows, even when the backup is this installation's own.
markReclaimResetPending(plan.reclaimResetFile);
fs.mkdirSync(path.dirname(plan.dbFile), { recursive: true });
// Copied in beside the target and renamed, so a crash leaves either nothing or a whole file.
const tmp = `${plan.dbFile}.restore-tmp`;
fs.copyFileSync(path.join(staging, 'travel.db'), tmp);
fs.renameSync(tmp, plan.dbFile);
await putDatabaseInPlace(plan, staging);
// The key the archive's secrets were encrypted with. An ENCRYPTION_KEY in the
// environment still wins over the file, exactly as on any other start.
@@ -1,11 +1,15 @@
import { DATABASE_BACKUP } from '../database/database-backup.interface';
import type { DatabaseEngine } from '../../db/engine';
import { DATABASE_BACKUP, type DatabaseBackupStrategy } from '../database/database-backup.interface';
import { DatabaseEngineModule, DATABASE_ENGINE } from '../database/database-engine.module';
import { DatabaseLifecycleModule } from '../database/database-lifecycle.module';
import { MaintenanceModule } from '../database/maintenance.module';
import { PostgresDatabaseBackup } from './postgres-database-backup';
import { SqliteDatabaseBackup } from './sqlite-database-backup';
import { Global, Module } from '@nestjs/common';
/**
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use.
* Binds the database backup port (`DATABASE_BACKUP`) to the engine in use
* (`TREK_DB_URL`, the one `DATABASE_ENGINE` provides).
*
* Global because its consumers sit in two domains: the backup domain itself
* and the admin domain (the demo reset job and the baseline route). Admin
@@ -19,8 +23,20 @@ import { Global, Module } from '@nestjs/common';
*/
@Global()
@Module({
imports: [DatabaseLifecycleModule, MaintenanceModule],
providers: [SqliteDatabaseBackup, { provide: DATABASE_BACKUP, useExisting: SqliteDatabaseBackup }],
imports: [DatabaseEngineModule, DatabaseLifecycleModule, MaintenanceModule],
providers: [
SqliteDatabaseBackup,
PostgresDatabaseBackup,
{
provide: DATABASE_BACKUP,
useFactory: (
engine: DatabaseEngine,
sqlite: SqliteDatabaseBackup,
postgres: PostgresDatabaseBackup,
): DatabaseBackupStrategy => ({ sqlite, postgres })[engine.id],
inject: [DATABASE_ENGINE, SqliteDatabaseBackup, PostgresDatabaseBackup],
},
],
exports: [DATABASE_BACKUP],
})
export class DatabaseBackupModule {}
+58
View File
@@ -0,0 +1,58 @@
import { logInfo, logWarn } from '../audit/audit-log.logger';
import { describeError } from '../common/describe-error';
import { DatabaseConnectionLostError } from '../database/database-backup.interface';
/** Whether a step ran to the end, and what it threw when it did not. */
interface Outcome {
failed: boolean;
error: unknown;
}
/** Runs `step` and records that it threw even when what it threw is undefined. */
async function settle(step: () => void | Promise<void>): Promise<Outcome> {
try {
await step();
return { failed: false, error: null };
} catch (error) {
return { failed: true, error };
}
}
/**
* The restore step both backup ports share. `swap` puts the new database in
* place; `reopen` always runs after it, so the process is never left without a
* connection. A failed swap rethrows its error, or a DatabaseConnectionLostError
* carrying both when the reopen failed too. A swap that landed resolves with the
* reopen's error, which the caller reports as "restart required".
*/
export async function replaceThenReopen(
swap: () => void | Promise<void>,
reopen: () => Promise<void>,
): Promise<{ reopenError: unknown }> {
const swapped = await settle(swap);
const reopened = await settle(reopen);
if (swapped.failed) {
if (reopened.failed) throw new DatabaseConnectionLostError(swapped.error, reopened.error);
throw swapped.error;
}
return { reopenError: reopened.failed ? reopened.error : null };
}
/**
* Keeps a copy of the database a restore is about to replace, at `target`. 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.
*/
export async function keepRestoreCopy(
target: string,
snapshot: (target: string) => Promise<void>,
): Promise<string | null> {
try {
await 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;
}
}
@@ -0,0 +1,127 @@
import type { DbSettings } from '../../app-config';
import { postgresTarget, type DatabaseEngine } from '../../db/engine';
import { pgDump, pgDumpMigrations, pgRestore } from '../../db/engine/postgres/pg-tools';
import { unknownMigrations } from '../../db/known-migrations';
import { DataPathsService } from '../app-config/data-paths.service';
import { logWarn } from '../audit/audit-log.logger';
import { describeError } from '../common/describe-error';
import { DomainError } from '../common/domain-error';
import type { DatabaseBackupStrategy } from '../database/database-backup.interface';
import { DATABASE_ENGINE, DATABASE_SETTINGS } from '../database/database-engine.module';
import { DatabaseLifecycle } from '../database/database-lifecycle.service';
import { keepRestoreCopy, replaceThenReopen } from './database-swap';
import { Inject, Injectable } from '@nestjs/common';
import fs from 'fs';
import path from 'path';
/** The name a Postgres database takes inside a backup archive: a pg_dump custom-format file. */
export const PG_ARCHIVE_ENTRY = 'travel.pgdump';
/**
* Why the database in an unpacked archive cannot be restored into a Postgres
* database, or null when it can: it must be a dump, carry TREK's migration
* history, and none this build does not know. Both restore paths ask it, the
* admin panel's and RESTORE_FROM_BACKUP's.
*/
export async function checkPostgresDump(extractDir: string, binDir: string | undefined): Promise<string | null> {
const dump = path.join(extractDir, PG_ARCHIVE_ENTRY);
if (!fs.existsSync(dump)) {
return fs.existsSync(path.join(extractDir, 'travel.db'))
? 'This backup holds a SQLite database, which cannot be restored into a Postgres database.'
: `Invalid backup: ${PG_ARCHIVE_ENTRY} not found`;
}
let executed: string[];
try {
executed = await pgDumpMigrations(dump, binDir);
} catch (err) {
logWarn(`Restore: the archive's database could not be read (${describeError(err)})`);
return 'Uploaded file is not a valid Postgres dump';
}
if (executed.length === 0) {
return 'The uploaded dump holds no TREK migration history. This does not appear to be a TREK backup.';
}
if (unknownMigrations(executed).length > 0) {
return 'This backup was made by a newer TREK version. Update TREK before restoring it.';
}
return null;
}
/**
* The backup port on a Postgres database: `pg_dump` and `pg_restore`
* (`db/engine/postgres/pg-tools.ts`), run by their absolute paths with the
* password in their environment.
*
* A snapshot is a custom-format dump, consistent on its own (pg_dump reads one
* snapshot of the database). A restore checks the dump first (it must be one,
* carry TREK's migration history, and none this build does not know), keeps a
* dump of the database it replaces, then clears the schema and loads the dump
* in one transaction (`pgRestore`), so a restore that fails leaves the database
* as it was and one that succeeds holds nothing a later migration added, and
* reopens through `DatabaseLifecycle`, which migrates the restored database
* forward. A backup of a SQLite install cannot be restored here.
*/
@Injectable()
export class PostgresDatabaseBackup implements DatabaseBackupStrategy {
readonly archiveEntry = PG_ARCHIVE_ENTRY;
/** The URL and the tools' directory; null on SQLite, where this provider is built but never called. */
private readonly target: ReturnType<typeof postgresTarget>;
constructor(
private readonly lifecycle: DatabaseLifecycle,
private readonly paths: DataPathsService,
@Inject(DATABASE_ENGINE) private readonly engine: DatabaseEngine,
@Inject(DATABASE_SETTINGS) settings: DbSettings,
) {
this.target = postgresTarget(settings);
}
private get connection(): { url: string; binDir: string | undefined } {
if (!this.target) throw new Error('The Postgres backup was used without TREK_DB_URL.');
return this.target;
}
location(): string {
return this.engine.describe();
}
/** A Postgres database is always there to copy; a missing pg_dump fails the snapshot, loudly. */
canSnapshot(): boolean {
return true;
}
async checkpoint(): Promise<void> {
// Postgres keeps nothing beside its store that a copy would need flushed.
}
/** pg_dump writes beside `target` and renames into place: a failed dump leaves nothing there. */
async snapshot(target: string): Promise<void> {
const { url, binDir } = this.connection;
await pgDump(url, target, binDir);
}
/** Throws a DomainError (400) with the refusal when the archive cannot be restored here, before anything is replaced. */
async verify(extractDir: string): Promise<void> {
const refusal = await checkPostgresDump(extractDir, this.connection.binDir);
if (refusal) throw new DomainError(400, refusal);
}
/** A dump of the database a restore is about to replace, in the data directory. */
keepCopyBeforeRestore(): Promise<string | null> {
const target = path.join(this.paths.dataDir, `pre-restore-${Date.now()}.pgdump`);
return keepRestoreCopy(target, (copy) => this.snapshot(copy));
}
replace(source: string): Promise<{ reopenError: unknown }> {
return replaceThenReopen(
async () => {
const { url, binDir } = this.connection;
// A rejection with no reason still has to fail the swap, so it is never swallowed.
await pgRestore(url, source, binDir).catch((err: unknown) => {
throw err ?? new Error('pg_restore failed');
});
},
() => this.lifecycle.reopen(),
);
}
}
@@ -1,29 +1,22 @@
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
import { logInfo, logWarn } from '../audit/audit-log.logger';
import {
DatabaseConnectionLostError,
type DatabaseBackupRefusal,
type DatabaseBackupStrategy,
} from '../database/database-backup.interface';
import { SqliteMaintenance } from '../../db/engine/sqlite/sqlite-maintenance';
import { DomainError } from '../common/domain-error';
import type { DatabaseBackupStrategy } from '../database/database-backup.interface';
import { DatabaseLifecycle } from '../database/database-lifecycle.service';
import { checkBackupDatabase } from './backup-archive';
import { keepRestoreCopy, replaceThenReopen } from './database-swap';
import { Injectable } from '@nestjs/common';
import fs from 'fs';
import path from 'path';
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.
* The backup port on a SQLite file, the engine TREK runs on by default.
*
* 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.
* 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
@@ -35,7 +28,7 @@ export class SqliteDatabaseBackup implements DatabaseBackupStrategy {
constructor(
private readonly lifecycle: DatabaseLifecycle,
private readonly maintenance: MaintenanceRepository,
private readonly maintenance: SqliteMaintenance,
) {}
location(): string {
@@ -62,66 +55,42 @@ export class SqliteDatabaseBackup implements DatabaseBackupStrategy {
}
}
verify(extractDir: string): DatabaseBackupRefusal | null {
return checkBackupDatabase(extractDir);
/** Throws a DomainError carrying the refusal when the archive's database cannot be restored here. */
async verify(extractDir: string): Promise<void> {
const refusal = checkBackupDatabase(extractDir);
if (refusal) throw new DomainError(refusal.status, refusal.error);
}
/**
* 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> {
/** A copy of the database a restore is about to replace, next to it: the swap deletes the current file. */
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;
}
return keepRestoreCopy(target, (copy) => this.snapshot(copy));
}
async replace(source: string): Promise<{ reopenError: unknown }> {
const dest = this.lifecycle.file;
this.lifecycle.close();
let swapFailed = false;
let swapError: 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);
} catch (err) {
swapFailed = true;
swapError = err;
}
// Reopening must always run, even when the swap threw, so the process is
// never left without a connection. After a swap that landed, a reopen
// failure is reported, not thrown: the files are in place and the caller
// has to say "restart". After a swap that failed, both errors go up
// together, because the swap's alone would hide that the connection is gone.
let reopenError: unknown = null;
try {
await this.lifecycle.reopen();
} catch (err) {
reopenError = err;
}
if (swapFailed) {
if (reopenError) throw new DatabaseConnectionLostError(swapError, reopenError);
throw swapError;
}
return { reopenError };
return replaceThenReopen(
() => swapFile(source, dest),
() => this.lifecycle.reopen(),
);
}
}
/**
* Puts `source` at `dest` by copying it to a temp file on the same filesystem
* and renaming it into place. The old sidecars go first: they belong to the
* database being replaced and would corrupt the new one.
*/
function swapFile(source: string, dest: string): void {
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);
}