mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-26 22:57:32 +00:00
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:
@@ -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);
|
||||
});
|
||||
}
|
||||
@@ -1,4 +1,6 @@
|
||||
import { currentTimestampKysely } from '../dialect/kysely-functions';
|
||||
import { resolveEngine } from '../engine';
|
||||
import { writeTransaction } from '../engine/write-transaction';
|
||||
import { Addons } from '../entities/Addons.entity';
|
||||
import { AppSettings } from '../entities/AppSettings.entity';
|
||||
import { DocumentProviders } from '../entities/DocumentProviders.entity';
|
||||
@@ -420,7 +422,10 @@ export class DemoRepository {
|
||||
|
||||
/**
|
||||
* Writes the demo's addon states in one transaction, so a reset that fails
|
||||
* halfway does not leave half the shelf switched. One UPDATE per shelf and
|
||||
* halfway does not leave half the shelf switched. The transaction takes the
|
||||
* engine's write lock (`writeTransaction`), as a `UnitOfWork` one does: the
|
||||
* seed and the reset run outside the Nest container, so the engine is the
|
||||
* one the environment names. One UPDATE per shelf and
|
||||
* state (generic inherited `nativeUpdate` over `id IN (...)`, the statement
|
||||
* `setEnabled` issues for one row) and one upsert for all the switches
|
||||
* (`AppSettingsRepository#setValue`'s), however long the lists are. A named
|
||||
@@ -430,7 +435,7 @@ export class DemoRepository {
|
||||
async applyAddonStates(states: DemoAddonStates): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
const switches = Object.entries(states.appSettings).map(([key, value]) => ({ key, value }));
|
||||
await this.em.transactional(async () => {
|
||||
await writeTransaction(this.em, resolveEngine(), async () => {
|
||||
const addons = this.em.getRepository(Addons);
|
||||
await addons.nativeUpdate({ id: { $in: [...states.addons.on] } }, { enabled: true });
|
||||
await addons.nativeUpdate({ id: { $in: [...states.addons.off] } }, { enabled: false });
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { isMissingTableError } from '../dialect/driver-errors';
|
||||
import type { EntityManager } from '@mikro-orm/core';
|
||||
|
||||
/**
|
||||
@@ -39,24 +38,20 @@ export class MaintenanceRepository {
|
||||
* `plugin_oauth_tokens`, `plugin_oauth_state`), called inside the erasure's
|
||||
* own `UnitOfWork.transactional(...)`.
|
||||
*
|
||||
* A table that does not exist (a slimmed-down test schema) is skipped; any
|
||||
* other failure propagates. Each statement runs in its own savepoint, since
|
||||
* on Postgres a failed statement aborts the whole transaction it is in.
|
||||
* `em.getTransactionContext()` hands the statement the open transaction's
|
||||
* connection, which a bare `execute()` would wait on forever.
|
||||
* The three tables come with the migrations on both engines, so a failure
|
||||
* here is a real one and propagates, rolling the erasure back. (A table
|
||||
* missing from a slimmed-down test schema used to be skipped in a savepoint
|
||||
* of its own; there is no such schema any more, and the savepoint was a
|
||||
* transaction outside `UnitOfWork`.) `getTransactionContext()` hands the
|
||||
* statement the open transaction's connection, which a bare `execute()`
|
||||
* would wait on forever.
|
||||
*/
|
||||
async deletePluginUserData(userId: number): Promise<void> {
|
||||
this.validateRequestContext();
|
||||
for (const table of ['plugin_user_config', 'plugin_oauth_tokens', 'plugin_oauth_state']) {
|
||||
try {
|
||||
await this.em.transactional((em) =>
|
||||
em
|
||||
.getConnection()
|
||||
.execute(`DELETE FROM ${table} WHERE user_id = ?`, [userId], 'run', em.getTransactionContext()),
|
||||
);
|
||||
} catch (err: unknown) {
|
||||
if (!isMissingTableError(err)) throw err;
|
||||
}
|
||||
await this.em
|
||||
.getConnection()
|
||||
.execute(`DELETE FROM ${table} WHERE user_id = ?`, [userId], 'run', this.em.getTransactionContext());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -90,12 +90,11 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
|
||||
* separately-awaited calls — two concurrent `meta.set` calls for two
|
||||
* DIFFERENT new keys on the same (plugin, entity) could both read
|
||||
* `count < max` before either's write landed, so a 100-key cap let a live
|
||||
* burst land 130 rows. The three run in one transaction, which keeps them
|
||||
* together on SQLite's single writer. On Postgres two transactions on two
|
||||
* pool connections both read the same count, and only the engine's write
|
||||
* lock, which `UnitOfWork` takes, puts them one after the other, so the
|
||||
* caller runs this inside `UnitOfWork.transactional` (`MetaRpc#set`), and
|
||||
* the transaction here becomes a savepoint of that one. Returns whether the
|
||||
* burst land 130 rows. The three run in the caller's
|
||||
* `UnitOfWork.transactional` (`MetaRpc#set`), whose write lock puts two of
|
||||
* them one after the other on either engine; a transaction of its own here
|
||||
* would not take that lock on Postgres, where two pool connections would
|
||||
* both read the same count. Returns whether the
|
||||
* write happened; `false` means a NEW key was blocked by the cap (the
|
||||
* caller maps that to `BadParams`, same message as before).
|
||||
*/
|
||||
@@ -107,14 +106,12 @@ export class PluginEntityMetadataRepository extends TrekRepository<PluginEntityM
|
||||
value: string,
|
||||
maxKeys: number,
|
||||
): Promise<boolean> {
|
||||
return this.getEntityManager().transactional(async () => {
|
||||
const exists = (await this.findValue(pluginId, entityType, entityId, key)) !== null;
|
||||
if (!exists) {
|
||||
const n = await this.countForEntity(pluginId, entityType, entityId);
|
||||
if (n >= maxKeys) return false;
|
||||
}
|
||||
await this.upsertValue(pluginId, entityType, entityId, key, value);
|
||||
return true;
|
||||
});
|
||||
const exists = (await this.findValue(pluginId, entityType, entityId, key)) !== null;
|
||||
if (!exists) {
|
||||
const n = await this.countForEntity(pluginId, entityType, entityId);
|
||||
if (n >= maxKeys) return false;
|
||||
}
|
||||
await this.upsertValue(pluginId, entityType, entityId, key, value);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,22 +137,20 @@ export class PluginScheduledTasksRepository extends TrekRepository<PluginSchedul
|
||||
* `PluginEntityMetadataRepository.upsertValueCapped` (must-land 2): two
|
||||
* concurrent `scheduler.set` calls for two different new task names on the
|
||||
* same plugin could both read `count < max` before either's write landed
|
||||
* (live: 130 rows on a 100 cap). One transaction keeps them together on
|
||||
* SQLite; on Postgres the caller runs it inside `UnitOfWork.transactional`
|
||||
* (`HostSurfaceRpc#schedulerSet`), whose write lock keeps them together
|
||||
* there, for the reason `upsertValueCapped`'s docstring gives. Returns
|
||||
* (live: 130 rows on a 100 cap). The caller runs it inside
|
||||
* `UnitOfWork.transactional` (`HostSurfaceRpc#schedulerSet`), whose write
|
||||
* lock keeps them together on either engine, for the reason
|
||||
* `upsertValueCapped`'s docstring gives. Returns
|
||||
* whether the write happened; `false` means a NEW task name was blocked by
|
||||
* the cap.
|
||||
*/
|
||||
async upsertTaskCapped(input: PluginScheduledTaskUpsertInput, maxTasks: number): Promise<boolean> {
|
||||
return this.getEntityManager().transactional(async () => {
|
||||
const exists = await this.existsForPluginAndName(input.plugin_id, input.name);
|
||||
if (!exists) {
|
||||
const n = await this.countForPlugin(input.plugin_id);
|
||||
if (n >= maxTasks) return false;
|
||||
}
|
||||
await this.upsertTask(input);
|
||||
return true;
|
||||
});
|
||||
const exists = await this.existsForPluginAndName(input.plugin_id, input.name);
|
||||
if (!exists) {
|
||||
const n = await this.countForPlugin(input.plugin_id);
|
||||
if (n >= maxTasks) return false;
|
||||
}
|
||||
await this.upsertTask(input);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { DatabaseEngine } from '../../db/engine';
|
||||
import { writeTransaction } from '../../db/engine/write-transaction';
|
||||
import { DATABASE_ENGINE } from './database-engine.module';
|
||||
import { EntityManager } from '@mikro-orm/core';
|
||||
import { Inject, Injectable } from '@nestjs/common';
|
||||
@@ -23,7 +24,10 @@ import { Inject, Injectable } from '@nestjs/common';
|
||||
* 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.
|
||||
* write lock (`DatabaseEngine.serializeWrites`, through `writeTransaction`),
|
||||
* which keeps that guarantee. No other transaction is opened under src/
|
||||
* (ESLint, `trek/transactions-through-unit-of-work`), so a check read
|
||||
* inside one of these is never raced by a write outside the lock.
|
||||
*/
|
||||
@Injectable()
|
||||
export class UnitOfWork {
|
||||
@@ -33,9 +37,6 @@ export class UnitOfWork {
|
||||
) {}
|
||||
|
||||
transactional<T>(fn: () => Promise<T>): Promise<T> {
|
||||
return this.em.transactional(async (em) => {
|
||||
await this.engine.serializeWrites(em);
|
||||
return fn();
|
||||
});
|
||||
return writeTransaction(this.em, this.engine, () => fn());
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user