Skip to content

armgit / TREK

Public Imported from GitHub
0

The most complete open-source travel planner: real-time collaboration, bookings, budgets, packing lists, journals, offline PWA, SSO and an AI-ready MCP server, with planet-wide place search and routing built in.

11.1 KB
Raw Blame
/**
 * 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, readdirSync, 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)), writesRestrictedScript()] });
    await expect(backup.verify(extract)).resolves.toBeUndefined();
  });

  it('PGBACKUP-002h: verify refuses a dump of another schema with a 400, leaving no work files, before a copy is kept', async () => {
    writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
    installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3)), writesRestrictedScript()] });
    installFakeTool(bin, 'psql', { snippets: [answersSchema('trek')] });
    expect(await refusal(backup.verify(extract))).toEqual({
      status: 400,
      message: 'The backup holds no TREK tables in the schema "trek"; nothing was replaced.',
    });
    expect(readdirSync(extract)).toEqual(['travel.pgdump']);
  });

  it('PGBACKUP-002i: replace runs the script verify prepared, without asking pg_restore again', async () => {
    const source = path.join(extract, 'travel.pgdump');
    writeFileSync(source, 'dump');
    installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3)), writesRestrictedScript()] });
    await backup.verify(extract);
    installFakeTool(bin, 'pg_restore', { snippets: [failsWith('pg_restore must not run again')] });
    await expect(backup.replace(source)).resolves.toEqual({ reopenError: null });
    expect(readdirSync(extract)).toEqual(['travel.pgdump']);
  });

  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.each([
    {
      id: 'PGBACKUP-002f',
      server: { privileged: true },
      message: /^TREK_DB_URL connects as a superuser or a member of a superuser role/,
    },
    {
      id: 'PGBACKUP-002g',
      server: { versionNum: '180001' },
      message: /^pg_restore is version 17, older than the PostgreSQL 18 server/,
    },
  ])('$id: verify refuses what the restore itself would refuse, before a copy is kept', async ({ server, message }) => {
    writeFileSync(path.join(extract, 'travel.pgdump'), 'dump');
    installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 3))] });
    installFakeTool(bin, 'psql', { snippets: [answersSchema('public', 'public', server)] });
    const refused = await refusal(backup.verify(extract));
    expect(refused.status).toBe(400);
    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/);
  });

  it('PGBACKUP-007: a kept copy (the demo baseline) passes only as a dump with TREK history this build knows', async () => {
    const copy = path.join(root, 'travel-baseline.pgdump');
    writeFileSync(copy, 'dump');
    installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(KNOWN.slice(0, 2))] });
    await expect(backup.checkCopy(copy)).resolves.toBeNull();

    const notADump = failsWith('pg_restore: error: input file does not appear to be a valid archive');
    installFakeTool(bin, 'pg_restore', { snippets: [notADump] });
    await expect(backup.checkCopy(copy)).resolves.toBe('Uploaded file is not a valid Postgres dump');

    installFakeTool(bin, 'pg_restore', { snippets: [listsMigrations(['Migration20990101000000_from_the_future'])] });
    await expect(backup.checkCopy(copy)).resolves.toMatch(/made by a newer TREK version/);
  });

  it('PGBACKUP-008: a dump pg_restore cannot read for its own reasons names the tool, not the file', async () => {
    const copy = path.join(root, 'travel.pgdump');
    writeFileSync(copy, 'dump');
    vi.spyOn(console, 'warn').mockImplementation(() => undefined);
    await expect(backup.checkCopy(copy)).resolves.toMatch(/^pg_restore was not found/);

    installFakeTool(bin, 'pg_restore', {
      snippets: [failsWith('pg_restore: error: unsupported version (1.16) in file header')],
    });
    await expect(backup.checkCopy(copy)).resolves.toMatch(/written by a newer pg_dump than the pg_restore/);
  });
});