mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-23 21:33:19 +00:00
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:
@@ -1,14 +1,15 @@
|
||||
import { describeError } from '../common/describe-error';
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* port. Each engine has an adapter in `nest/backup/`, chosen by the engine in
|
||||
* use: SQLite copies the file (`VACUUM INTO`) and swaps it under a closed
|
||||
* connection; Postgres dumps and restores it with pg_dump and pg_restore. The
|
||||
* two adapters answer every method the same way, so the callers do not branch.
|
||||
*
|
||||
* 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
|
||||
@@ -42,10 +43,11 @@ export interface DatabaseBackupStrategy {
|
||||
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.
|
||||
* Checks an unpacked archive's database before anything is replaced. Resolves
|
||||
* when it can be restored; otherwise throws a DomainError (status 400) that
|
||||
* carries the refusal in the restore route's words.
|
||||
*/
|
||||
verify(extractDir: string): DatabaseBackupRefusal | null;
|
||||
verify(extractDir: string): Promise<void>;
|
||||
|
||||
/**
|
||||
* Keeps a copy of the database a restore is about to replace. Best effort: a
|
||||
@@ -67,7 +69,7 @@ export interface DatabaseBackupStrategy {
|
||||
replace(source: string): Promise<{ reopenError: unknown }>;
|
||||
}
|
||||
|
||||
/** A refusal in the restore route's own words and status. */
|
||||
/** A refusal in the restore route's own words and status, as `verify` reports it. */
|
||||
export interface DatabaseBackupRefusal {
|
||||
error: string;
|
||||
status: number;
|
||||
@@ -76,8 +78,6 @@ export interface DatabaseBackupRefusal {
|
||||
/** Injection token for the active `DatabaseBackupStrategy`. */
|
||||
export const DATABASE_BACKUP = Symbol('DATABASE_BACKUP');
|
||||
|
||||
const describeError = (err: unknown): string => (err instanceof Error ? err.message : String(err));
|
||||
|
||||
/**
|
||||
* Thrown by `replace` when the swap failed and the reopen that always follows
|
||||
* failed too. The process is left without a database connection until a
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
import { readEnv, type DbSettings } from '../../app-config';
|
||||
import { resolveEngine, type DatabaseEngine } from '../../db/engine';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/** `readEnv().db`, read once per container: what decides which engine runs and its settings. */
|
||||
export const DATABASE_SETTINGS = Symbol('DATABASE_SETTINGS');
|
||||
|
||||
/**
|
||||
* The one `DatabaseEngine` of this process. Every injector (the lifecycle, the
|
||||
* unit of work, the backup port and its adapters) gets this instance, so the
|
||||
* state an engine keeps (Postgres's reopen hook) is the same wherever it is used.
|
||||
*/
|
||||
export const DATABASE_ENGINE = Symbol('DATABASE_ENGINE');
|
||||
|
||||
/**
|
||||
* Provides the engine and its settings. Not global: each module that needs
|
||||
* the engine imports it, and Nest keeps one instance per container.
|
||||
*/
|
||||
@Module({
|
||||
providers: [
|
||||
{ provide: DATABASE_SETTINGS, useFactory: (): DbSettings => readEnv().db },
|
||||
{
|
||||
provide: DATABASE_ENGINE,
|
||||
useFactory: (db: DbSettings): DatabaseEngine => resolveEngine(db),
|
||||
inject: [DATABASE_SETTINGS],
|
||||
},
|
||||
],
|
||||
exports: [DATABASE_SETTINGS, DATABASE_ENGINE],
|
||||
})
|
||||
export class DatabaseEngineModule {}
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DatabaseEngineModule } from './database-engine.module';
|
||||
import { DatabaseLifecycle } from './database-lifecycle.service';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
@@ -6,5 +7,5 @@ import { Module } from '@nestjs/common';
|
||||
* import it by name, so a partial test harness that never touches the
|
||||
* connection lifecycle does not have to supply the `MikroORM` it injects.
|
||||
*/
|
||||
@Module({ providers: [DatabaseLifecycle], exports: [DatabaseLifecycle] })
|
||||
@Module({ imports: [DatabaseEngineModule], providers: [DatabaseLifecycle], exports: [DatabaseLifecycle] })
|
||||
export class DatabaseLifecycleModule {}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import { closeDb, getRawConnection, registerReinitializeHook, reinitialize } from '../../db/database';
|
||||
import { resolveDbPath } from '../../db/db-path';
|
||||
import { runSchemaBootstrap } from '../../db/orm';
|
||||
import type { DatabaseEngine } from '../../db/engine';
|
||||
import { DATABASE_ENGINE } from './database-engine.module';
|
||||
import { MikroORM } from '@mikro-orm/core';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* The one owner of the core database connection's lifecycle: open, close and
|
||||
@@ -13,18 +13,21 @@ import { Injectable } from '@nestjs/common';
|
||||
* 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.
|
||||
* port), and the shutdown closes through this. The ORM's first connect is what
|
||||
* actually opens the file; this provider makes that step 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.
|
||||
* What differs by engine (a file to open or not, how a reopen reaches the ORM)
|
||||
* is the engine's (`db/engine/`), the one `DATABASE_ENGINE` provides: this
|
||||
* provider decides when, the engine decides how.
|
||||
*/
|
||||
@Injectable()
|
||||
export class DatabaseLifecycle {
|
||||
private readonly reopenListeners: Array<() => Promise<void>> = [];
|
||||
|
||||
constructor(private readonly orm: MikroORM) {}
|
||||
constructor(
|
||||
private readonly orm: MikroORM,
|
||||
@Inject(DATABASE_ENGINE) private readonly engine: DatabaseEngine,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* The database file this process runs on, resolved the one way every caller
|
||||
@@ -36,31 +39,29 @@ export class DatabaseLifecycle {
|
||||
}
|
||||
|
||||
/**
|
||||
* Opens the connection, binds the ORM to its later swaps and brings the schema
|
||||
* to head (legacy baseline, migrations, the deferred index, seeders, demo
|
||||
* seed, in that order: see `db/orm.ts`). Called once by `buildApp()`, before
|
||||
* anything reads the database.
|
||||
* Opens the connection, points the engine's reopen at the ORM and brings the
|
||||
* schema to head (on SQLite: legacy baseline, migrations, the deferred index,
|
||||
* seeders, demo seed, in that order, see `db/orm.ts`; on Postgres: the
|
||||
* baseline or the migrations after it, then the same seeding). Called once
|
||||
* by `buildApp()`, before anything reads the database.
|
||||
*/
|
||||
async open(): Promise<void> {
|
||||
// Normally a no-op: the ORM's first connect inside NestFactory.create()
|
||||
// already opened it. Said here so the boot does not depend on that.
|
||||
getRawConnection();
|
||||
registerReinitializeHook(() => this.rebindOrm());
|
||||
await runSchemaBootstrap(this.orm);
|
||||
this.engine.open(this.orm, () => this.afterReopen());
|
||||
await this.engine.schemaBootstrap(this.orm, { snapshot: true });
|
||||
}
|
||||
|
||||
/** Checkpoints and closes the connection. A closed connection stays closed until `reopen()`. */
|
||||
close(): void {
|
||||
closeDb();
|
||||
this.engine.close();
|
||||
}
|
||||
|
||||
/**
|
||||
* Reopens the connection after its file was replaced, rebuilds the ORM's
|
||||
* cached client around the new handle and migrates the new file forward (a
|
||||
* restored backup may predate this release).
|
||||
* Reopens the connection after the database was replaced. The engine points
|
||||
* the ORM at the new database first; then `afterReopen` migrates it forward
|
||||
* and runs the listeners.
|
||||
*/
|
||||
async reopen(): Promise<void> {
|
||||
await reinitialize();
|
||||
await this.engine.reopen();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,19 +79,12 @@ export class DatabaseLifecycle {
|
||||
}
|
||||
|
||||
/**
|
||||
* Kysely caches whatever handle it was given, so without this the ORM would
|
||||
* keep talking to the closed one. Closing and reconnecting sends the driver
|
||||
* back through `createKyselyDialect()`, which picks up the new handle.
|
||||
* What follows a reopen once the engine has pointed the ORM at the reopened
|
||||
* database. No pre-migrate snapshot: the file was just unpacked from an
|
||||
* archive that is still there to go back to.
|
||||
*/
|
||||
private async rebindOrm(): Promise<void> {
|
||||
const connection = this.orm.em.getConnection();
|
||||
// The handle is owned and closed by `db/database.ts`; the bound driver's
|
||||
// `destroy()` is a no-op (see `orm-driver.ts`), so this close never reaches it.
|
||||
await connection.close(true);
|
||||
await connection.connect();
|
||||
// No pre-migrate snapshot: the file was just unpacked from an archive that
|
||||
// is still there to go back to.
|
||||
await runSchemaBootstrap(this.orm, { snapshot: false });
|
||||
private async afterReopen(): Promise<void> {
|
||||
await this.engine.schemaBootstrap(this.orm, { snapshot: false });
|
||||
for (const listener of this.reopenListeners) await listener();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,14 +1,16 @@
|
||||
import { SqliteMaintenance } from '../../db/engine/sqlite/sqlite-maintenance';
|
||||
import { MaintenanceRepository } from '../../db/repositories/MaintenanceRepository';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import { Module } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* Provides `MaintenanceRepository`, the home of the few whole-database
|
||||
* statements no entity can express (the readiness ping, the WAL checkpoint,
|
||||
* `VACUUM INTO`, the plugin-table erasure).
|
||||
* statements no entity can express (the readiness ping, the plugin-table
|
||||
* erasure), and `SqliteMaintenance`, the SQLite file's own (the WAL
|
||||
* checkpoint, `VACUUM INTO`).
|
||||
*
|
||||
* A factory over the context-resolving global `EntityManager`, the same one
|
||||
* Nest injects into every service, so the repository resolves the request or
|
||||
* Factories over the context-resolving global `EntityManager`, the same one
|
||||
* Nest injects into every service, so each resolves the request or
|
||||
* transaction fork that is active when a method runs. The class itself stays
|
||||
* free of Nest, like every other file under `db/`.
|
||||
*/
|
||||
@@ -19,7 +21,12 @@ import { Module } from '@nestjs/common';
|
||||
useFactory: (em: EntityManager) => new MaintenanceRepository(em),
|
||||
inject: [EntityManager],
|
||||
},
|
||||
{
|
||||
provide: SqliteMaintenance,
|
||||
useFactory: (em: EntityManager) => new SqliteMaintenance(em),
|
||||
inject: [EntityManager],
|
||||
},
|
||||
],
|
||||
exports: [MaintenanceRepository],
|
||||
exports: [MaintenanceRepository, SqliteMaintenance],
|
||||
})
|
||||
export class MaintenanceModule {}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import { DatabaseEngineModule } from './database-engine.module';
|
||||
import { UnitOfWork } from './unit-of-work';
|
||||
import { Global, Module } from '@nestjs/common';
|
||||
|
||||
@@ -10,10 +11,11 @@ import { Global, Module } from '@nestjs/common';
|
||||
* (`Test.createTestingModule({ imports: [DatabaseModule, ...] })`)
|
||||
* with no ORM in the container: a provider there that injects the core
|
||||
* `EntityManager` fails every one of them at `compile()`, because Nest
|
||||
* instantiates providers eagerly. Nothing is imported here — the
|
||||
* `EntityManager` token comes from `MikroOrmModule.forRoot`, whose
|
||||
* `MikroOrmCoreModule` is itself `@Global()`.
|
||||
* instantiates providers eagerly. The `EntityManager` token comes from
|
||||
* `MikroOrmModule.forRoot`, whose
|
||||
* `MikroOrmCoreModule` is itself `@Global()`. It imports `DatabaseEngineModule`,
|
||||
* the engine the unit of work serializes its writes through.
|
||||
*/
|
||||
@Global()
|
||||
@Module({ providers: [UnitOfWork], exports: [UnitOfWork] })
|
||||
@Module({ imports: [DatabaseEngineModule], providers: [UnitOfWork], exports: [UnitOfWork] })
|
||||
export class OrmModule {}
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import type { DatabaseEngine } from '../../db/engine';
|
||||
import { DATABASE_ENGINE } from './database-engine.module';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import { Injectable } from '@nestjs/common';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
|
||||
/**
|
||||
* The one way a service opens a transaction.
|
||||
@@ -17,12 +19,23 @@ import { Injectable } from '@nestjs/common';
|
||||
*
|
||||
* Never awaits network I/O inside: the SQLite connection is one Kysely client
|
||||
* with a mutex, and an open transaction holds it for every other request.
|
||||
*
|
||||
* The services read `MAX(...) + 1` inside these transactions on the strength
|
||||
* of SQLite's single writer. On Postgres a pool of connections would let two
|
||||
* of them read the same MAX, so every transaction first takes the engine's
|
||||
* write lock (`DatabaseEngine.serializeWrites`), which keeps that guarantee.
|
||||
*/
|
||||
@Injectable()
|
||||
export class UnitOfWork {
|
||||
constructor(private readonly em: EntityManager) {}
|
||||
constructor(
|
||||
private readonly em: EntityManager,
|
||||
@Inject(DATABASE_ENGINE) private readonly engine: DatabaseEngine,
|
||||
) {}
|
||||
|
||||
transactional<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return this.em.transactional(() => fn());
|
||||
return this.em.transactional(async (em) => {
|
||||
await this.engine.serializeWrites(em);
|
||||
return fn();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user