fix(db): take the write lock in every transaction that writes

UnitOfWork took the engine's write lock, but four repositories opened
transactions of their own: the demo addon set, the plugin user erasure's
savepoints, and the plugin metadata and scheduler cap checks. On Postgres
those ran beside the others on the pool.

writeTransaction (src/db/engine/write-transaction.ts) is now the one
transaction that writes: UnitOfWork wraps it, and the demo seed and reset,
which run outside the container, call it with the engine the environment
names. The capped plugin writes run in their caller's unit of work instead
of a transaction of their own, and the plugin erasure runs in the erasure's
transaction without savepoints, since its three tables come with the
migrations on both engines. lint:tx counts writeTransaction as a
transaction.
This commit is contained in:
Maurice
2026-11-17 14:14:29 +01:00
parent 981052224c
commit 61ea6b648c
9 changed files with 107 additions and 64 deletions
+30
View File
@@ -0,0 +1,30 @@
import type { DatabaseEngine } from './engine';
import type { EntityManager } from '@mikro-orm/core';
/**
* The one way TREK opens a transaction that writes: `em.transactional()` with
* its default `NESTED` propagation (a call inside an open transaction becomes
* a savepoint), whose first statement takes the engine's write lock
* (`DatabaseEngine.serializeWrites`).
*
* On SQLite the lock is free, since one connection already writes one
* transaction at a time. On Postgres a pool runs transactions side by side,
* and without the lock two of them would both read the same `MAX(...) + 1`,
* the same count under a cap or the same "not there yet" before an insert.
* With it, a check read inside the transaction still holds at its write.
*
* `UnitOfWork.transactional` is this for the Nest container; code that runs
* outside it (the demo seed and reset) calls it directly. ESLint
* (`trek/transactions-through-unit-of-work`) refuses any other transaction
* under src/ outside the engine and the boot-time schema files.
*/
export function writeTransaction<T>(
em: EntityManager,
engine: Pick<DatabaseEngine, 'serializeWrites'>,
fn: (em: EntityManager) => Promise<T>,
): Promise<T> {
return em.transactional(async (tx) => {
await engine.serializeWrites(tx);
return fn(tx);
});
}