feat(db): request-context and unit-of-work helpers for the ORM, with concurrency tests

This commit is contained in:
jubnl
2026-09-21 10:01:36 +02:00
parent 443dc35c03
commit d7f39916d5
7 changed files with 212 additions and 5 deletions
+4
View File
@@ -26,6 +26,7 @@ import { TrekExceptionFilter } from './common/trek-exception.filter';
import { ZodValidationPipe } from './common/zod-validation.pipe';
import { ConfigModule } from './config/config.module';
import { DatabaseModule } from './database/database.module';
import { OrmModule } from './database/orm.module';
import { DayNotesModule } from './day-notes/day-notes.module';
import { DaysModule } from './days/days.module';
import { DocSyncModule } from './doc-sync/doc-sync.module';
@@ -151,6 +152,9 @@ import { APP_FILTER, APP_GUARD, APP_INTERCEPTOR, APP_PIPE } from '@nestjs/core';
LlmParseModule,
ManagedExtModule,
MikroOrmModule.forRoot(mikroOrmConfig),
// Not part of DatabaseModule: 41 e2e suites compose that module without the
// ORM, and an EntityManager-dependent provider there fails their containers.
OrmModule,
],
providers: [
// Default-deny: a route is authenticated unless it carries @Public() or
+18
View File
@@ -0,0 +1,18 @@
import { Global, Module } from '@nestjs/common';
import { UnitOfWork } from './unit-of-work';
/**
* The ORM-side container module: the home of providers that depend on MikroORM
* itself rather than on the raw better-sqlite3 handle `DatabaseModule` owns.
*
* Deliberately separate from `DatabaseModule`, which 41 e2e suites compose
* standalone (`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()`.
*/
@Global()
@Module({ providers: [UnitOfWork], exports: [UnitOfWork] })
export class OrmModule {}
@@ -0,0 +1,16 @@
import { RequestContext, type MikroORM } from '@mikro-orm/core';
/**
* A request-scoped EntityManager for work that no HTTP request wraps.
*
* `@mikro-orm/nestjs` forks an EntityManager per HTTP request through its
* middleware; everything else — an MCP tool call, a plugin RPC dispatch, a
* WebSocket message, a cron job, the boot-time seeders, a backup restore — has
* no such wrapper, and with `allowGlobalContext` left at its safe default the
* ORM refuses to run a query there. This is the one helper those entrypoints
* call. It is deliberately a function and not a decorator so a call site can
* pass the ORM it was given rather than reach for a global.
*/
export function withRequestContext<T>(orm: MikroORM, fn: () => T): T {
return RequestContext.create(orm.em, fn);
}
+28
View File
@@ -0,0 +1,28 @@
import { Injectable } from '@nestjs/common';
import { EntityManager } from '@mikro-orm/core';
/**
* The one way a service opens a transaction.
*
* Wraps `em.transactional()` with its default `NESTED` propagation: a call made
* while a transaction is open becomes a savepoint, which is what better-sqlite3's
* nested `transaction()` did and what the services were written against.
*
* Repositories injected by Nest (and the test helper's `t.repo`) resolve the
* transactional fork through MikroORM's TransactionContext, so nothing has to
* be passed down. A manually forked EntityManager does not: `fork()` defaults
* to `useContext: false`, so its `getContext()` returns itself, and a repository
* built on it would write outside the transaction, on a second connection the
* transaction is holding.
*
* 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.
*/
@Injectable()
export class UnitOfWork {
constructor(private readonly em: EntityManager) {}
transactional<T>(fn: () => Promise<T>): Promise<T> {
return this.em.transactional(() => fn());
}
}