fix(audit): audit rows are native inserts, not a unit-of-work flush; closed test ORMs

This commit is contained in:
jubnl
2026-09-22 12:56:03 +02:00
parent b0905f9867
commit 86c558cdd6
10 changed files with 78 additions and 36 deletions
@@ -1,4 +1,4 @@
import type { AuditLog } from '../entities/AuditLog.entity';
import { AuditLog } from '../entities/AuditLog.entity';
import { type AssertRowKeys } from './_shared/rows';
import { EntityRepository } from '@mikro-orm/sql';
@@ -19,14 +19,8 @@ export interface AuditLogRow {
const _auditLogRowKeys: AssertRowKeys<AuditLogRow, AuditLog> = true;
/** The column set `insert` writes; `id`/`created_at` are generated. */
export interface NewAuditLogRow {
user_id: number | null;
action: string;
resource: string | null;
details: string | null;
ip: string | null;
}
/** The column set `insertEntry` writes; `id`/`created_at` are generated. */
export type NewAuditLogRow = Omit<AuditLogRow, 'id' | 'created_at'>;
// Reserved for Plan 3i (`admin.service.ts`'s paginated read of the same
// table): `listPage(limit, offset): Promise<AuditLogPageRow[]>` (a `qb()`
@@ -41,9 +35,19 @@ export class AuditLogRepository extends EntityRepository<AuditLog> {
*
* Best-effort, fire-and-forget, exactly like the caller
* (`AuditService.writeAudit`, wrapped in an outer try/catch that never
* throws): no `refresh`, nothing read back — the generated `id` and
* `created_at` (left to the column's `DEFAULT CURRENT_TIMESTAMP`) are
* never used afterward.
* throws): no `refresh`, nothing the caller reads — MikroORM appends
* `RETURNING id, created_at` for the defaults, but `insertEntry` resolves
* `void`.
*
* A native `em.insert()`, not `create()` + `flush()`: `flush()` commits
* the *whole* unit of work of the request's `EntityManager`, not just this
* row — with ~98 call sites for `writeAudit`, one of them firing before
* every MCP tool handler runs, an unrelated pending change elsewhere in
* the same request would be committed early by an audit write, and the
* outer try/catch that makes this best-effort would swallow whatever that
* flush raised. `em.insert()` fires a single native INSERT with no side
* effects on the context/identity map — the same fire-and-forget
* semantics as the legacy `dbs.run(INSERT …)` autocommit statement.
*
* Named `insertEntry`, not `insert`: `EntityRepository` (`@mikro-orm/core`)
* already declares a native `insert(data, options?): Promise<Primary<Entity>>`
@@ -53,13 +57,12 @@ export class AuditLogRepository extends EntityRepository<AuditLog> {
* inserts `createDay`/`createNote` rather than `create`.
*/
async insertEntry(entry: NewAuditLogRow): Promise<void> {
const row = this.create({
await this.getEntityManager().insert(AuditLog, {
user: entry.user_id,
action: entry.action,
resource: entry.resource,
details: entry.details,
ip: entry.ip,
});
await this.getEntityManager().persist(row).flush();
}
}