mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-04 18:04:18 +00:00
refactor(db): open the database through a DatabaseLifecycle provider
db/database.ts opened the connection as a side effect of being imported, so the moment anything reached it the database was open. index.ts had to defer loading the app until a first-boot restore was done, and nothing in the container decided when the connection opened or closed. The module now opens the connection on first use and opens nothing at import. A connection closed on purpose (a restore, the shutdown) stays closed until it is reopened, as before. The new DatabaseLifecycle provider owns the decisions: buildApp() opens through it, which also binds the ORM to later swaps (the hook attachOrm used to register) and runs the schema bootstrap in the same order as before, and the shutdown closes through it. Its file property is the one resolved database path. The module keeps every export, so the test suites that replace it with vi.mock keep working; buildDbMock gains the new openDb.
This commit is contained in:
+53
-40
@@ -6,49 +6,57 @@ import { readSchemaSnapshot } from './schema-snapshot';
|
||||
|
||||
import type Database from 'better-sqlite3';
|
||||
|
||||
// In test mode each vitest worker gets an isolated in-memory DB so that
|
||||
// parallel forks can't race on the same file or share migration state.
|
||||
const isTest = readEnv().app.isTest;
|
||||
const dbPath = resolveDbPath();
|
||||
|
||||
let _db: Database.Database | null = null;
|
||||
/**
|
||||
* Set by `closeDb()`, cleared by `openDb()`. A handle that was never opened is
|
||||
* opened on first use; one that was closed on purpose (a restore swapping the
|
||||
* file, the shutdown) stays closed until somebody reopens it, so nothing can
|
||||
* quietly reconnect to a file that is being replaced.
|
||||
*/
|
||||
let closedOnPurpose = false;
|
||||
|
||||
/**
|
||||
* Opens the connection and applies the pragmas. It deliberately does NOT build
|
||||
* the schema: migrations and seeding are MikroORM's job now and run from
|
||||
* `db/orm.ts` during `buildApp()`, because the migrator is async and this
|
||||
* function is called at module load.
|
||||
* the schema: migrations and seeding are MikroORM's job and run from
|
||||
* `db/orm.ts` when `DatabaseLifecycle.open()` (`nest/database/`) is called by
|
||||
* `buildApp()`, because the migrator is async.
|
||||
*
|
||||
* The one exception is test mode, where there is no `buildApp()` to hook into
|
||||
* for the handful of suites that use this singleton directly. Those open a copy
|
||||
* of a schema snapshot the vitest global setup migrated once for the whole run.
|
||||
* Nothing calls this at import any more. The first reader opens it: in
|
||||
* production that is the ORM's first connect inside `NestFactory.create()`,
|
||||
* which is still after `index.ts` ran a first-boot restore. Opening an open
|
||||
* connection is a no-op.
|
||||
*
|
||||
* In test mode there is no `buildApp()` for the handful of suites that use this
|
||||
* singleton directly, so those open a copy of a schema snapshot the vitest
|
||||
* global setup migrated once for the whole run.
|
||||
*/
|
||||
function initDb(): void {
|
||||
if (_db) {
|
||||
try {
|
||||
_db.exec('PRAGMA wal_checkpoint(TRUNCATE)');
|
||||
} catch (e) {}
|
||||
try {
|
||||
_db.close();
|
||||
} catch (e) {}
|
||||
_db = null;
|
||||
}
|
||||
|
||||
const snapshot = isTest ? readSchemaSnapshot() : null;
|
||||
_db = openDatabase(snapshot ?? dbPath);
|
||||
function openDb(): void {
|
||||
if (_db) return;
|
||||
// Resolved here rather than at import, so loading the module touches neither
|
||||
// the environment nor the data directory.
|
||||
const dbPath = resolveDbPath();
|
||||
const snapshot = readEnv().app.isTest ? readSchemaSnapshot() : null;
|
||||
const handle = openDatabase(snapshot ?? dbPath);
|
||||
// Ahead of the journal switch now: changing journal_mode needs an exclusive
|
||||
// lock, which a sibling process (reset-admin, the rotation script) may hold.
|
||||
_db.exec('PRAGMA busy_timeout = 5000');
|
||||
const durability = applyDurabilityPragmas(_db);
|
||||
_db.exec('PRAGMA foreign_keys = ON');
|
||||
// Reported so an operator can see whether their setting took — the test DB is
|
||||
handle.exec('PRAGMA busy_timeout = 5000');
|
||||
const durability = applyDurabilityPragmas(handle);
|
||||
handle.exec('PRAGMA foreign_keys = ON');
|
||||
_db = handle;
|
||||
closedOnPurpose = false;
|
||||
// Reported so an operator can see whether their setting took. The test DB is
|
||||
// :memory: and has no journal file, so there is nothing to report there.
|
||||
if (dbPath !== ':memory:') {
|
||||
console.log(`[DB] journal_mode=${durability.journalMode}, synchronous=${durability.synchronous}`);
|
||||
}
|
||||
}
|
||||
|
||||
initDb();
|
||||
/** The open handle, opening it on first use. Throws while it is closed on purpose. */
|
||||
function current(): Database.Database {
|
||||
if (!_db && !closedOnPurpose) openDb();
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
return _db;
|
||||
}
|
||||
|
||||
/**
|
||||
* The live better-sqlite3 handle, for the MikroORM dialect in `orm-driver.ts`.
|
||||
@@ -58,8 +66,7 @@ initDb();
|
||||
* The driver calls this on every connect so it always binds the current handle.
|
||||
*/
|
||||
function getRawConnection(): Database.Database {
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
return _db;
|
||||
return current();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -80,12 +87,12 @@ function getRawConnection(): Database.Database {
|
||||
*/
|
||||
const db = new Proxy({} as Database.Database, {
|
||||
get(_, prop: string | symbol) {
|
||||
if (!_db) throw new Error('Database connection is not available (restore in progress?)');
|
||||
const val = (_db as unknown as Record<string | symbol, unknown>)[prop];
|
||||
return typeof val === 'function' ? val.bind(_db) : val;
|
||||
const handle = current();
|
||||
const val = (handle as unknown as Record<string | symbol, unknown>)[prop];
|
||||
return typeof val === 'function' ? val.bind(handle) : val;
|
||||
},
|
||||
set(_, prop: string | symbol, val: unknown) {
|
||||
(_db as unknown as Record<string | symbol, unknown>)[prop] = val;
|
||||
(current() as unknown as Record<string | symbol, unknown>)[prop] = val;
|
||||
return true;
|
||||
},
|
||||
});
|
||||
@@ -119,8 +126,9 @@ async function runDemoSeed(): Promise<void> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Lets `db/orm.ts` rebuild the ORM's connection when this module swaps handles,
|
||||
* without this module importing the ORM (which imports this module back).
|
||||
* Lets `DatabaseLifecycle` (`nest/database/`) rebuild the ORM's connection when
|
||||
* this module swaps handles, without this module importing the ORM (which
|
||||
* imports this module back).
|
||||
*/
|
||||
let onReinitialize: (() => Promise<void>) | null = null;
|
||||
function registerReinitializeHook(hook: () => Promise<void>): void {
|
||||
@@ -136,6 +144,7 @@ function closeDb(): void {
|
||||
_db.close();
|
||||
} catch (e) {}
|
||||
_db = null;
|
||||
closedOnPurpose = true;
|
||||
console.log('[DB] Database connection closed');
|
||||
}
|
||||
}
|
||||
@@ -144,13 +153,17 @@ function closeDb(): void {
|
||||
* Reopens the connection after a restore has swapped the file underneath us.
|
||||
*
|
||||
* Async now, because bringing a restored backup up to date means running the
|
||||
* migrations, and the hook also has to rebuild the ORM's Kysely client — it
|
||||
* migrations, and the hook also has to rebuild the ORM's Kysely client: it
|
||||
* cached the handle this function is about to replace.
|
||||
*
|
||||
* Production code reaches this through `DatabaseLifecycle.reopen()`; the export
|
||||
* stays for the suites that drive the swap directly and for the mock factories
|
||||
* that stub it.
|
||||
*/
|
||||
async function reinitialize(): Promise<void> {
|
||||
console.log('[DB] Reinitializing database connection after restore...');
|
||||
if (_db) closeDb();
|
||||
initDb();
|
||||
openDb();
|
||||
if (onReinitialize) await onReinitialize();
|
||||
console.log('[DB] Database reinitialized successfully');
|
||||
}
|
||||
@@ -167,4 +180,4 @@ async function reinitialize(): Promise<void> {
|
||||
// exported — see its own docstring above for why (~190 test files' static
|
||||
// typecheck, not a production `src/` need).
|
||||
|
||||
export { db, closeDb, reinitialize, getRawConnection, registerReinitializeHook, runDemoSeed };
|
||||
export { db, openDb, closeDb, reinitialize, getRawConnection, registerReinitializeHook, runDemoSeed };
|
||||
|
||||
+4
-24
@@ -1,5 +1,5 @@
|
||||
import mikroOrmConfig from '../mikro-orm.config';
|
||||
import { registerReinitializeHook, runDemoSeed } from './database';
|
||||
import { runDemoSeed } from './database';
|
||||
import { ensureEmailCaseIndex } from './email-case-index';
|
||||
import { migrateToHead, NO_SAFETY_NET } from './legacy-baseline';
|
||||
import { preMigrateSnapshot } from './pre-migrate-snapshot';
|
||||
@@ -25,7 +25,7 @@ import { MikroORM as SqliteMikroORM } from '@mikro-orm/sqlite';
|
||||
* class's own `readonly` form while a direct `init()` yields the mutable one;
|
||||
* nothing here reads that parameter.
|
||||
*/
|
||||
type AnyOrm = MikroORM<
|
||||
export type AnyOrm = MikroORM<
|
||||
IDatabaseDriver,
|
||||
EntityManager<IDatabaseDriver>,
|
||||
readonly (string | EntityClass<AnyEntity> | EntitySchema)[]
|
||||
@@ -57,8 +57,8 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
|
||||
//
|
||||
// Plan 3c Task 0b (R9): wrapping the call HERE, the one place
|
||||
// `runSchemaBootstrap` already has `orm` in scope, covers BOTH of
|
||||
// `runDemoSeed`'s real call sites at once (`bootstrap.ts`'s initial boot
|
||||
// and `attachOrm`'s restore hook below, both of which only ever reach
|
||||
// `runDemoSeed`'s real call sites at once (`DatabaseLifecycle.open()` at
|
||||
// boot and its restore hook in `reopen()`, both of which only ever reach
|
||||
// `runDemoSeed` through this function) with no second wrapper to keep in
|
||||
// sync.
|
||||
//
|
||||
@@ -72,26 +72,6 @@ export async function runSchemaBootstrap(orm: AnyOrm, { snapshot = true }: { sna
|
||||
await withRequestContext(orm, () => runDemoSeed());
|
||||
}
|
||||
|
||||
/**
|
||||
* Binds the ORM to this process's connection lifecycle.
|
||||
*
|
||||
* A restore swaps the SQLite file and reopens the raw handle; Kysely caches
|
||||
* whatever handle it was given, so without this the ORM would keep talking to a
|
||||
* closed connection. Closing and reconnecting sends the driver back through
|
||||
* `createKyselyDialect()`, which picks up the new handle — and the restored file
|
||||
* may be an older backup, so it gets migrated forward too.
|
||||
*/
|
||||
export function attachOrm(orm: AnyOrm): void {
|
||||
registerReinitializeHook(async () => {
|
||||
const connection = orm.em.getConnection();
|
||||
// The handle is owned and closed by `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();
|
||||
await runSchemaBootstrap(orm, { snapshot: false });
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* An ORM instance outside Nest, for the vitest global setup that builds the
|
||||
* schema snapshot. Production uses the container-owned one from
|
||||
|
||||
@@ -6,10 +6,10 @@ import path from 'path';
|
||||
/**
|
||||
* A migrated-but-empty database, serialised once per test run.
|
||||
*
|
||||
* Migrations are async and `database.ts::initDb()` is not — it runs at module
|
||||
* load, long before anything can await. Most suites do not care (they mock the
|
||||
* module or build their own database), but a handful use the singleton directly
|
||||
* and need a schema to be there the moment they import it.
|
||||
* Migrations are async and `database.ts::openDb()` is not: it runs on the
|
||||
* connection's first read, which cannot await. Most suites do not care (they
|
||||
* mock the module or build their own database), but a handful use the
|
||||
* singleton directly and need a schema to be there the moment they touch it.
|
||||
*
|
||||
* So the vitest global setup migrates one database for the whole run and writes
|
||||
* it here; every worker opens a copy. `better-sqlite3` deserialises a 1.5 MiB
|
||||
|
||||
Reference in New Issue
Block a user