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
@@ -21,6 +21,7 @@
* filter itself (the disabled row is excluded) alongside the boolean coercion
* of the enabled row that remains.
*/
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
import { Addons } from '../../../src/db/entities/Addons.entity';
import { AppSettings } from '../../../src/db/entities/AppSettings.entity';
import { PhotoProviderFields } from '../../../src/db/entities/PhotoProviderFields.entity';
@@ -195,7 +196,7 @@ beforeEach(() => {
photoProviderFieldsRepo,
appSettingsRepo,
usersRepo,
new UnitOfWork(t.em),
new UnitOfWork(t.em, new SqliteEngine()),
);
});
+4 -4
View File
@@ -2,7 +2,7 @@
* Unit tests for backupService.
* Covers BACKUP-031 to BACKUP-060.
*/
import type { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import type { SqliteMaintenance } from '../../../src/db/engine/sqlite/sqlite-maintenance';
import {
formatSize,
parseIntField,
@@ -78,9 +78,9 @@ const dbMock = vi.hoisted(() => ({
}));
// The database port's SQLite implementation is built for real below with this
// stand-in for the MaintenanceRepository Nest injects into it: the WAL
// stand-in for the SqliteMaintenance 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.
// of it. The real statements are sqlite-maintenance.test.ts's coverage.
const maintenanceRepoMock = vi.hoisted(() => ({
walCheckpoint: vi.fn().mockResolvedValue(undefined),
vacuumInto: vi.fn().mockResolvedValue(undefined),
@@ -121,7 +121,7 @@ const lifecycleStub = {
function deps(storage: StorageService) {
return {
storage,
database: new SqliteDatabaseBackup(lifecycleStub, maintenanceRepoMock as unknown as MaintenanceRepository),
database: new SqliteDatabaseBackup(lifecycleStub, maintenanceRepoMock as unknown as SqliteMaintenance),
};
}
@@ -0,0 +1,85 @@
/**
* The restore step the two backup ports share (`database-swap.ts`): the swap,
* then a reopen that always runs, and how the two failures surface.
*/
import { keepRestoreCopy, replaceThenReopen } from '../../../../src/nest/backup/database-swap';
import { DatabaseConnectionLostError } from '../../../../src/nest/database/database-backup.interface';
import { describe, expect, it, vi } from 'vitest';
const ok = async () => undefined;
const fails = (error: unknown) => async () => {
throw error;
};
describe('replaceThenReopen', () => {
it('SWAP-001: a swap that lands and a reopen that works resolves with no reopen error', async () => {
const swap = vi.fn(ok);
const reopen = vi.fn(ok);
await expect(replaceThenReopen(swap, reopen)).resolves.toEqual({ reopenError: null });
expect(swap).toHaveBeenCalledTimes(1);
expect(reopen).toHaveBeenCalledTimes(1);
});
it('SWAP-002: a swap that lands and a reopen that fails resolves with the reopen error, so the caller says restart', async () => {
const lost = new Error('reconnect failed');
await expect(replaceThenReopen(ok, fails(lost))).resolves.toEqual({ reopenError: lost });
});
it('SWAP-003: a swap that fails still reopens, and its own error is rethrown', async () => {
const reopen = vi.fn(ok);
const swapError = new Error('rename failed');
await expect(replaceThenReopen(fails(swapError), reopen)).rejects.toBe(swapError);
expect(reopen).toHaveBeenCalledTimes(1);
});
it('SWAP-004: a swap and a reopen that both fail go up together, as DatabaseConnectionLostError', async () => {
const swapError = new Error('rename failed');
const reopenError = new Error('reconnect failed');
const thrown = await replaceThenReopen(fails(swapError), fails(reopenError)).catch((err: unknown) => err);
expect(thrown).toBeInstanceOf(DatabaseConnectionLostError);
expect((thrown as DatabaseConnectionLostError).swapError).toBe(swapError);
expect((thrown as DatabaseConnectionLostError).cause).toBe(reopenError);
});
it('SWAP-005: a step that throws undefined still counts as failed', async () => {
// A reopen that throws undefined is a failure: with a swap that also failed, the two go up as the lost connection.
await expect(replaceThenReopen(fails(new Error('rename failed')), fails(undefined))).rejects.toBeInstanceOf(
DatabaseConnectionLostError,
);
// A swap that throws undefined rethrows undefined, the same value the step threw.
await expect(replaceThenReopen(fails(undefined), ok)).rejects.toBeUndefined();
});
it('SWAP-006: a synchronous swap that throws is caught like an async one', async () => {
const swapError = new Error('copy failed');
const reopen = vi.fn(ok);
await expect(
replaceThenReopen(() => {
throw swapError;
}, reopen),
).rejects.toBe(swapError);
expect(reopen).toHaveBeenCalledTimes(1);
});
});
describe('keepRestoreCopy', () => {
it('SWAP-007: resolves with the target once the copy is written', async () => {
await expect(keepRestoreCopy('/data/pre-restore-1.db', ok)).resolves.toBe('/data/pre-restore-1.db');
});
it('SWAP-008: a copy that cannot be written resolves with null, so the restore goes on', async () => {
const warn = vi.spyOn(console, 'warn').mockImplementation(() => undefined);
try {
await expect(keepRestoreCopy('/data/pre-restore-2.db', fails(new Error('disk full')))).resolves.toBeNull();
} finally {
warn.mockRestore();
}
});
});
@@ -6,7 +6,16 @@
* calls this file makes. The plugin staging is the one seam stubbed, because
* it moves trees under the plugin roots of the machine running the tests.
*/
import { knownMigrationNames } from '../../../src/db/known-migrations';
import { BootRestoreError, restoreOnFirstBoot } from '../../../src/nest/backup/boot-restore';
import {
answersSchema,
answersTables,
installFakeTool,
listsMigrations,
touches,
writesRestrictedScript,
} from '../../helpers/fake-pg-tools';
import archiver from 'archiver';
import Database from 'better-sqlite3';
@@ -125,6 +134,62 @@ describe('restoreOnFirstBoot', () => {
expect(fs.existsSync(dbFile)).toBe(false);
});
describe('on Postgres', () => {
/**
* Stand-in client tools (tests/helpers/fake-pg-tools.ts): psql lists
* `tables` and marks `loaded` when it runs a restore; pg_restore lists a
* known migration as the dump's history, or writes a restricted script.
* Their arguments are pinned in pg-tools.test.ts.
*/
const postgresPlan = (archivePath: string, tables: string[] = []) => {
const bin = path.join(root, 'bin');
fs.mkdirSync(bin, { recursive: true });
installFakeTool(bin, 'psql', {
snippets: [answersSchema(), answersTables(tables), touches(path.join(root, 'loaded'))],
});
const migration = [...knownMigrationNames()][0];
installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations([migration]), writesRestrictedScript()] });
return {
archive: archivePath,
dbFile,
dataDir,
reclaimResetFile,
postgres: { url: 'postgres://trek:pw@db/trek', binDir: bin },
};
};
const loaded = () => fs.existsSync(path.join(root, 'loaded'));
it('BOOT-RESTORE-004b: a database holding tables is left alone, so a restart never rolls back', async () => {
const plan = postgresPlan(await archive({ 'travel.pgdump': 'dump' }), ['users', 'trips']);
const warn = vi.spyOn(console, 'warn').mockImplementation(() => {});
expect(await restoreOnFirstBoot(plan)).toEqual({ restored: false, reason: 'database-exists' });
expect(warn).toHaveBeenCalledWith(expect.stringContaining('the Postgres database (2 table(s))'));
expect(loaded()).toBe(false);
});
it("BOOT-RESTORE-004c: an empty database is loaded from the archive's dump, with its key and uploads", async () => {
const plan = postgresPlan(
await archive({ 'travel.pgdump': 'dump', '.encryption_key': 'b'.repeat(64), 'uploads/a.jpg': 'jpeg' }),
);
const out = await restoreOnFirstBoot(plan);
expect(out.restored).toBe(true);
expect(loaded()).toBe(true);
expect(fs.readFileSync(path.join(dataDir, '.encryption_key'), 'utf8')).toBe('b'.repeat(64));
expect(fs.existsSync(reclaimResetFile)).toBe(true);
expect(fs.existsSync(dbFile)).toBe(false);
});
it('BOOT-RESTORE-004d: a SQLite backup is refused before anything is loaded, leaving no scratch', async () => {
const plan = postgresPlan(await goodArchive());
await expect(restoreOnFirstBoot(plan)).rejects.toThrow(
'RESTORE_FROM_BACKUP: This backup holds a SQLite database, which cannot be restored into a Postgres database.',
);
expect(loaded()).toBe(false);
expect(fs.existsSync(reclaimResetFile)).toBe(false);
expect(fs.readdirSync(dataDir).filter((f) => f.startsWith('restore-boot-'))).toEqual([]);
});
});
it('BOOT-RESTORE-005: an archive without a database is refused and leaves no scratch behind', async () => {
const zipPath = await archive({ 'notes.txt': 'hello' });
await expect(restoreOnFirstBoot({ archive: zipPath, dbFile, dataDir, reclaimResetFile })).rejects.toThrow(
@@ -0,0 +1,29 @@
/**
* DatabaseEngineModule: one engine per container, shared by every injector.
*/
import {
DatabaseEngineModule,
DATABASE_ENGINE,
DATABASE_SETTINGS,
} from '../../../../src/nest/database/database-engine.module';
import { Test } from '@nestjs/testing';
import { describe, expect, it } from 'vitest';
describe('DatabaseEngineModule', () => {
it('ENGINE-DI-001: provides one engine instance, so state an engine keeps is the same wherever it is injected', async () => {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseEngineModule] }).compile();
const engine = moduleRef.get(DATABASE_ENGINE);
expect(moduleRef.get(DATABASE_ENGINE)).toBe(engine);
expect(engine.id).toBe('sqlite');
});
it('ENGINE-DI-002: the settings are read from the environment once and the engine is resolved from them', async () => {
const moduleRef = await Test.createTestingModule({ imports: [DatabaseEngineModule] }).compile();
const settings = moduleRef.get(DATABASE_SETTINGS);
expect(settings.engine).toBe('sqlite');
expect(moduleRef.get(DATABASE_SETTINGS)).toBe(settings);
});
});
@@ -7,6 +7,8 @@
* baseline depends on) and that the ORM is rebuilt around a reopened handle.
* The real open, migrate and reopen run in tests/integration/database-lifecycle.test.ts.
*/
import { PostgresEngine } from '../../../../src/db/engine/postgres/postgres-engine';
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
import { DatabaseLifecycle } from '../../../../src/nest/database/database-lifecycle.service';
import type { MikroORM } from '@mikro-orm/core';
@@ -15,6 +17,9 @@ import os from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
/** The settings a Postgres process would read from TREK_DB_URL, given directly rather than through the environment. */
const POSTGRES = { engine: 'postgres' as const, url: 'postgres://trek:pw@db/trek', poolMax: 10 };
const { dbMock, ormMock, calls } = vi.hoisted(() => {
const calls: string[] = [];
return {
@@ -66,15 +71,15 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-001: open() opens the connection, binds the ORM to later swaps, then brings the schema to head', async () => {
const { orm } = ormStub();
await new DatabaseLifecycle(orm).open();
await new DatabaseLifecycle(orm, new SqliteEngine()).open();
expect(calls).toEqual(['getRawConnection', 'registerReinitializeHook', 'runSchemaBootstrap:{}']);
expect(ormMock.runSchemaBootstrap).toHaveBeenCalledWith(orm);
expect(calls).toEqual(['getRawConnection', 'registerReinitializeHook', 'runSchemaBootstrap:{"snapshot":true}']);
expect(ormMock.runSchemaBootstrap).toHaveBeenCalledWith(orm, { snapshot: true });
});
it('DBLIFE-002: the hook open() registers rebuilds the ORM client and migrates the new file without a pre-migrate copy', async () => {
const { orm, connection } = ormStub();
await new DatabaseLifecycle(orm).open();
await new DatabaseLifecycle(orm, new SqliteEngine()).open();
const hook = dbMock.registerReinitializeHook.mock.calls[0][0];
calls.length = 0;
@@ -86,7 +91,7 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-007: listeners registered with onReopened run after the schema bootstrap of a reopen, in order', async () => {
const { orm } = ormStub();
const lifecycle = new DatabaseLifecycle(orm);
const lifecycle = new DatabaseLifecycle(orm, new SqliteEngine());
lifecycle.onReopened(async () => {
calls.push('listener:first');
});
@@ -110,7 +115,7 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-008: a listener that throws fails the reopen, so a listener must contain its own failures', async () => {
const { orm } = ormStub();
const lifecycle = new DatabaseLifecycle(orm);
const lifecycle = new DatabaseLifecycle(orm, new SqliteEngine());
lifecycle.onReopened(async () => {
throw new Error('listener broke');
});
@@ -120,8 +125,33 @@ describe('DatabaseLifecycle', () => {
await expect(hook()).rejects.toThrow('listener broke');
});
it('DBLIFE-009: on Postgres a reopen keeps the pool and only migrates, so it never waits on a connection lent to a job', async () => {
const bootstrap = vi
.spyOn(PostgresEngine.prototype, 'schemaBootstrap')
.mockImplementation(async (_orm, options) => {
calls.push(`schemaBootstrap:${JSON.stringify(options)}`);
});
try {
const { orm, connection } = ormStub();
const lifecycle = new DatabaseLifecycle(orm, new PostgresEngine(POSTGRES));
lifecycle.onReopened(async () => {
calls.push('listener');
});
await lifecycle.open();
calls.length = 0;
await lifecycle.reopen();
expect(connection.close).not.toHaveBeenCalled();
expect(connection.connect).not.toHaveBeenCalled();
expect(calls).toEqual(['schemaBootstrap:{"snapshot":false}', 'listener']);
} finally {
bootstrap.mockRestore();
}
});
it('DBLIFE-003: close() and reopen() go through the connection module', async () => {
const lifecycle = new DatabaseLifecycle(ormStub().orm);
const lifecycle = new DatabaseLifecycle(ormStub().orm, new SqliteEngine());
lifecycle.close();
await lifecycle.reopen();
@@ -132,7 +162,9 @@ describe('DatabaseLifecycle', () => {
it('DBLIFE-004: a reopen that fails is not swallowed', async () => {
dbMock.reinitialize.mockRejectedValueOnce(new Error('database is locked'));
await expect(new DatabaseLifecycle(ormStub().orm).reopen()).rejects.toThrow('database is locked');
await expect(new DatabaseLifecycle(ormStub().orm, new SqliteEngine()).reopen()).rejects.toThrow(
'database is locked',
);
});
describe('file', () => {
@@ -145,7 +177,7 @@ describe('DatabaseLifecycle', () => {
});
it('DBLIFE-005: is the in-memory database under test', () => {
expect(new DatabaseLifecycle(ormStub().orm).file).toBe(':memory:');
expect(new DatabaseLifecycle(ormStub().orm, new SqliteEngine()).file).toBe(':memory:');
});
it('DBLIFE-006: is TREK_DB_FILE when it is set, the one path the connection, the backup and the restore share', () => {
@@ -154,7 +186,7 @@ describe('DatabaseLifecycle', () => {
vi.stubEnv('NODE_ENV', 'production');
vi.stubEnv('TREK_DB_FILE', file);
expect(new DatabaseLifecycle(ormStub().orm).file).toBe(file);
expect(new DatabaseLifecycle(ormStub().orm, new SqliteEngine()).file).toBe(file);
});
});
});
@@ -1,3 +1,4 @@
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
import { Users } from '../../../../src/db/entities/Users.entity';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
import { createSnapshotTestDb } from '../../../helpers/db-mock';
@@ -29,7 +30,7 @@ let uow: UnitOfWork;
beforeAll(async () => {
t = await createTestOrm(testDb);
uow = new UnitOfWork(t.em);
uow = new UnitOfWork(t.em, new SqliteEngine());
});
beforeEach(() => {
resetTestDb(testDb);
@@ -1,3 +1,4 @@
import { SqliteEngine } from '../../../../src/db/engine/sqlite/sqlite-engine';
import { Days } from '../../../../src/db/entities/Days.entity';
import type { DaysRepository } from '../../../../src/db/repositories/Days.repository';
import { UnitOfWork } from '../../../../src/nest/database/unit-of-work';
@@ -25,7 +26,7 @@ let days: DaysRepository;
*/
beforeAll(async () => {
t = await createTestOrm(testDb);
uow = new UnitOfWork(t.em);
uow = new UnitOfWork(t.em, new SqliteEngine());
days = t.repo(Days);
});
beforeEach(() => {
+3 -2
View File
@@ -11,6 +11,7 @@
import { ADDON_IDS } from '../../../src/addons';
import { getMcpSafeUrl } from '../../../src/app-config';
import { db as testDb } from '../../../src/db/database';
import { SqliteEngine } from '../../../src/db/engine/sqlite/sqlite-engine';
import { AuditLog } from '../../../src/db/entities/AuditLog.entity';
import { OauthClients } from '../../../src/db/entities/OauthClients.entity';
import { OauthConsents } from '../../../src/db/entities/OauthConsents.entity';
@@ -132,7 +133,7 @@ beforeAll(async () => {
consentsRepo,
addonsStub,
new AuditService(auditLogRepo, usersRepo),
new UnitOfWork(t.em),
new UnitOfWork(t.em, new SqliteEngine()),
cimdStub,
);
});
@@ -1446,7 +1447,7 @@ describe('module-scoped OAuth state', () => {
consentsRepo,
addonsStub,
new AuditService(auditLogRepo, usersRepo),
new UnitOfWork(t.em),
new UnitOfWork(t.em, new SqliteEngine()),
cimdStub,
);
expect((await secondInstance.consumeAuthCode(code))?.userId).toBe(42);
@@ -0,0 +1,172 @@
/**
* PostgresDatabaseBackup: the backup port on a Postgres database, over
* stand-in pg_dump, pg_restore and psql tools (TREK_DB_PG_BIN_DIR, built by
* tests/helpers/fake-pg-tools.ts) and a stand-in DatabaseLifecycle. The tools'
* own arguments are pinned in tests/unit/db/engine/postgres/pg-tools.test.ts.
*/
import { deriveDb } from '../../../src/app-config/derive';
import { resolveEngine } from '../../../src/db/engine';
import { knownMigrationNames } from '../../../src/db/known-migrations';
import type { DataPathsService } from '../../../src/nest/app-config/data-paths.service';
import { PostgresDatabaseBackup } from '../../../src/nest/backup/postgres-database-backup';
import { DomainError } from '../../../src/nest/common/domain-error';
import { DatabaseConnectionLostError } from '../../../src/nest/database/database-backup.interface';
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
import {
answersSchema,
failsWith,
installFakeTool,
listsMigrations,
writesFile,
writesRestrictedScript,
} from '../../helpers/fake-pg-tools';
import { existsSync, mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
const KNOWN = [...knownMigrationNames()].sort();
let root: string;
let bin: string;
let extract: string;
let reopen: ReturnType<typeof vi.fn>;
let backup: PostgresDatabaseBackup;
/** The adapter over the settings a process reads from these variables, with stand-ins for the lifecycle and the data directory. */
function postgresBackup(env: Record<string, string>): PostgresDatabaseBackup {
const db = deriveDb(env);
return new PostgresDatabaseBackup(
{ reopen } as unknown as DatabaseLifecycle,
{ dataDir: root } as unknown as DataPathsService,
resolveEngine(db),
db,
);
}
beforeEach(() => {
root = mkdtempSync(path.join(tmpdir(), 'trek-pg-backup-'));
bin = path.join(root, 'bin');
extract = path.join(root, 'extract');
mkdirSync(bin);
mkdirSync(extract);
installFakeTool(bin, 'psql', { snippets: [answersSchema()] });
reopen = vi.fn(async () => undefined);
backup = postgresBackup({ TREK_DB_URL: 'postgresql://trek:pw@db/trek', TREK_DB_PG_BIN_DIR: bin });
});
afterEach(() => {
vi.unstubAllEnvs();
vi.restoreAllMocks();
rmSync(root, { recursive: true, force: true });
});
async function refusal(promise: Promise<unknown>): Promise<{ status: number; message: string }> {
const error = await promise.then(
() => null,
(err: unknown) => err,
);
expect(error).toBeInstanceOf(DomainError);
return { status: (error as DomainError).getStatus(), message: (error as DomainError).publicMessage };
}
describe('PostgresDatabaseBackup', () => {
it('PGBACKUP-001: a snapshot is a pg_dump; a failed one leaves nothing that could pass for a copy', async () => {
expect(backup.archiveEntry).toBe('travel.pgdump');
expect(backup.canSnapshot()).toBe(true);
await expect(backup.checkpoint()).resolves.toBeUndefined();
installFakeTool(bin, 'pg_dump', { snippets: [writesFile('dump')] });
await backup.snapshot(path.join(root, 'a.pgdump'));
expect(existsSync(path.join(root, 'a.pgdump'))).toBe(true);
installFakeTool(bin, 'pg_dump', { snippets: [writesFile('partial'), failsWith('connection refused')] });
await expect(backup.snapshot(path.join(root, 'b.pgdump'))).rejects.toThrow('pg_dump failed: connection refused');
expect(existsSync(path.join(root, 'b.pgdump'))).toBe(false);
expect(existsSync(path.join(root, 'b.pgdump.partial'))).toBe(false);
});
it('PGBACKUP-002: verify accepts a TREK dump this build knows', async () => {
writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3))] });
await expect(backup.verify(extract)).resolves.toBeUndefined();
});
it('PGBACKUP-002a: verify refuses an archive without a TREK dump in it', async () => {
expect(await refusal(backup.verify(extract))).toEqual({
status: 400,
message: 'Invalid backup: travel.pgdump not found',
});
});
it.each([
{
id: 'PGBACKUP-002b',
setup: () => writeFileSync(path.join(extract, 'travel.db'), 'sqlite'),
message: /holds a SQLite database/,
},
{
id: 'PGBACKUP-002c',
setup: () => {
writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
installFakeTool(bin, 'pg_restore', {
snippets: [listsMigrations([...KNOWN, 'Migration29990101000000_from_the_future'])],
});
},
message: /made by a newer TREK version/,
},
{
id: 'PGBACKUP-002d',
setup: () => {
writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations([])] });
},
message: /holds no TREK migration history/,
},
{
id: 'PGBACKUP-002e',
setup: () => {
writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
installFakeTool(bin, 'pg_restore', { snippets: [failsWith('pg_restore: error: not a valid archive')] });
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
},
message: 'Uploaded file is not a valid Postgres dump',
},
])('$id: verify refuses a dump TREK cannot restore', async ({ setup, message }) => {
setup();
const refused = await refusal(backup.verify(extract));
if (typeof message === 'string') expect(refused.message).toBe(message);
else expect(refused.message).toMatch(message);
});
it('PGBACKUP-003: keeps a dump of the database a restore replaces, or says it could not', async () => {
vi.spyOn(console, 'log').mockImplementation(() => undefined);
vi.spyOn(console, 'warn').mockImplementation(() => undefined);
installFakeTool(bin, 'pg_dump', { snippets: [writesFile('dump')] });
const kept = await backup.keepCopyBeforeRestore();
expect(kept).toMatch(/pre-restore-\d+\.pgdump$/);
expect(existsSync(kept as string)).toBe(true);
installFakeTool(bin, 'pg_dump', { snippets: [failsWith('connection refused')] });
await expect(backup.keepCopyBeforeRestore()).resolves.toBeNull();
});
it('PGBACKUP-004: replace restores, then reopens; a reopen failure is reported, not thrown', async () => {
installFakeTool(bin, 'pg_restore', { snippets: [writesRestrictedScript()] });
await expect(backup.replace(path.join(extract, 'travel.pgdump'))).resolves.toEqual({ reopenError: null });
expect(reopen).toHaveBeenCalledTimes(1);
const lost = new Error('reconnect failed');
reopen.mockRejectedValueOnce(lost);
await expect(backup.replace(path.join(extract, 'travel.pgdump'))).resolves.toEqual({ reopenError: lost });
});
it('PGBACKUP-005: a failed restore still reopens, and both failures surface when the reopen fails too', async () => {
installFakeTool(bin, 'pg_restore', { snippets: [failsWith('connection refused')] });
const source = path.join(extract, 'travel.pgdump');
await expect(backup.replace(source)).rejects.toThrow('pg_restore failed: connection refused');
expect(reopen).toHaveBeenCalledTimes(1);
reopen.mockRejectedValueOnce(new Error('reconnect failed'));
await expect(backup.replace(source)).rejects.toBeInstanceOf(DatabaseConnectionLostError);
});
it('PGBACKUP-006: names the database without its password, and refuses to run without TREK_DB_URL', async () => {
expect(backup.location()).toBe('Postgres postgresql://trek:***@db/trek');
await expect(postgresBackup({}).snapshot(path.join(root, 'c.pgdump'))).rejects.toThrow(/without TREK_DB_URL/);
});
});
@@ -2,13 +2,14 @@
* 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
* temp directory: a VACUUM INTO through the real SqliteMaintenance, 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 { MaintenanceRepository } from '../../../src/db/repositories/MaintenanceRepository';
import { SqliteMaintenance } from '../../../src/db/engine/sqlite/sqlite-maintenance';
import { SqliteDatabaseBackup } from '../../../src/nest/backup/sqlite-database-backup';
import { DomainError } from '../../../src/nest/common/domain-error';
import { DatabaseConnectionLostError } from '../../../src/nest/database/database-backup.interface';
import type { DatabaseLifecycle } from '../../../src/nest/database/database-lifecycle.service';
import { withRequestContext } from '../../../src/nest/database/request-context';
@@ -40,7 +41,7 @@ function maintenanceStub() {
function portWith(maintenance: { walCheckpoint: unknown; vacuumInto: unknown }): SqliteDatabaseBackup {
return new SqliteDatabaseBackup(
lifecycle as unknown as DatabaseLifecycle,
maintenance as unknown as MaintenanceRepository,
maintenance as unknown as SqliteMaintenance,
);
}
@@ -116,7 +117,7 @@ describe('SqliteDatabaseBackup', () => {
// test-sql-allow: the marker table is a bare fixture no entity maps; the write has to land in the WAL of this file.
live.prepare('UPDATE marker SET label = ?').run('after');
const target = path.join(dir, 'copy.db');
const port = portWith(new MaintenanceRepository(orm.em));
const port = portWith(new SqliteMaintenance(orm.em));
await withRequestContext(orm.orm, () => port.snapshot(target));
@@ -125,7 +126,7 @@ describe('SqliteDatabaseBackup', () => {
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));
const port = portWith(new SqliteMaintenance(orm.em));
await expect(withRequestContext(orm.orm, () => port.snapshot(target))).rejects.toThrow();
@@ -146,11 +147,16 @@ describe('SqliteDatabaseBackup', () => {
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-007: verify refuses an unpacked archive without a database, as a DomainError the restore route answers', async () => {
const refusal = await portWith(maintenanceStub())
.verify(dir)
.then(
() => null,
(err: unknown) => err,
);
expect(refusal).toBeInstanceOf(DomainError);
expect((refusal as DomainError).publicMessage).toBe('Invalid backup: travel.db not found');
expect((refusal as DomainError).getStatus()).toBe(400);
});
it('SQLBK-008: keeps a copy of the database a restore replaces next to it, and says where', async () => {