diff --git a/.changeset/35167-insert-delete-unit-inside-middleware.md b/.changeset/35167-insert-delete-unit-inside-middleware.md new file mode 100644 index 00000000000..62de8a83b2f --- /dev/null +++ b/.changeset/35167-insert-delete-unit-inside-middleware.md @@ -0,0 +1,19 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): insert and delete open their own unit of work around the engine body, as update does + +Clause-②: no +Metadata-protocol: none + +An insert or delete opens its own unit of work when the object carries a metadata `before*` hook on that verb, or a blocking (`onError: abort`, the default) or conditioned metadata `after*` hook. The unit exists so that a refusal later in the write rolls back what the write's hooks wrote through `ctx.api`, the row included. Update moves that unit around the engine body only in this same release; insert and delete opened it around the whole write, the middleware chain included. All three verbs now follow one rule: the middleware chain, the authorization gate included, runs before the unit opens, and the hooks, the row write and the `after*` chain run inside it and still roll back together. + +What changes for an insert or delete on such an object: + +- On a single-connection store such as SQLite, a writer whose authorization gate or middleware is still running no longer holds the store's only connection, so other writers are no longer queued behind it. +- What a middleware does after `next()` now runs after the commit, as it already does for an update and for an insert or delete on an object with no such hook. A middleware that throws after `next()` no longer rolls the row back on a hooked object; it never did on any other object. + +This patch does not address the answer the loser of two concurrent deletes of one row gets. + +Nothing to change in an app. diff --git a/packages/objectql/src/engine-delete-and-aggregate.ts b/packages/objectql/src/engine-delete-and-aggregate.ts index 8e3eca7ce81..6d70adbe468 100644 --- a/packages/objectql/src/engine-delete-and-aggregate.ts +++ b/packages/objectql/src/engine-delete-and-aggregate.ts @@ -149,13 +149,19 @@ export interface DeleteAndAggregateHost { /** The bodies of the "Delete, count, aggregate and execute" section of `ObjectQL`: a stateless facet, called by the class's stubs. */ export class DeleteAndAggregateFacet { /** The body of `ObjectQL#delete`; the method's docblock there is its contract. */ - static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { + static async delete(this: Pick, object: string, options?: EngineDeleteOptions & RecycleBinDeleteObservability): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterDelete`, or a refusal after a `beforeDelete` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. - if (this.opensAfterAbortUnit('afterDelete', object, options?.context)) { - return this.inAfterAbortUnit(() => this.delete(object, options)); - } + // + // [#35167] As in `insert` and `update`: the unit opens around the ENGINE + // BODY (the executor below), never around the door, so the middleware + // chain — the authorization gate's reads, and whatever a middleware does + // after `next()` — runs outside it. Nothing between here and the executor + // writes; the cascade claim below is an in-memory marker. + const ownUnit = this.opensAfterAbortUnit('afterDelete', object, options?.context); + const inOwnUnit = (body: () => Promise): (() => Promise) => + ownUnit ? () => this.inAfterAbortUnit(body) : body; this.logger.debug('Delete operation starting', { object }); this.assertWriteAllowed(object, 'delete'); // [#8844] See the insert face — deleting the install's only organization @@ -225,7 +231,7 @@ export class DeleteAndAggregateFacet { opCtx.ast = { object, ...(options?.where !== undefined ? { where: options.where } : {}) } as QueryAST; } - await this.executeWithMiddleware(opCtx, async () => { + await this.executeWithMiddleware(opCtx, inOwnUnit(async () => { // [ADR-0139 D1] As in `update`: a leaf the middleware chain wrote into a // delete's predicate is refused at the executor's entry, before the // pre-image reads reach the driver. @@ -930,7 +936,7 @@ export class DeleteAndAggregateFacet { ); throw e; } - }); + })); return opCtx.result; } diff --git a/packages/objectql/src/engine-hook-dispatch.ts b/packages/objectql/src/engine-hook-dispatch.ts index 0f5f2ccdd30..abadc52c7aa 100644 --- a/packages/objectql/src/engine-hook-dispatch.ts +++ b/packages/objectql/src/engine-hook-dispatch.ts @@ -71,7 +71,13 @@ export interface HookDispatchHost { transaction: ObjectQL['transaction']; } -/** [#22782] The unit {@link opensAfterAbortUnit} asked for; `write` re-enters the door, which joins it. */ +/** + * [#22782] The unit {@link opensAfterAbortUnit} asked for. `write` is the write + * door's engine body — the executor `insert`, `update` and `delete` each hand + * the middleware chain (#35142, #35167) — so the chain, the authorization gate + * included, runs before the unit opens and after it closes, and the `before*` + * hooks' `ctx.api` writes, the row and the `after*` chain run inside it. + */ export async function inAfterAbortUnit( this: Pick, write: () => Promise, diff --git a/packages/objectql/src/engine-insert.ts b/packages/objectql/src/engine-insert.ts index 8a3d302a4f9..ec04835b3f6 100644 --- a/packages/objectql/src/engine-insert.ts +++ b/packages/objectql/src/engine-insert.ts @@ -324,13 +324,20 @@ export class InsertFacet { } /** The body of `ObjectQL#insert`; the method's docblock there is its contract. */ - static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { + static async insert(this: Pick, object: string, data: any | any[], options?: DataEngineInsertOptions & WriteObservabilityOptions): Promise { object = this.resolveObjectName(object); // [#22782, #34412] An aborting `afterInsert`, or a refusal after a `beforeInsert` hook's // `ctx.api` write, rolls this write back with it — see `opensAfterAbortUnit`. - if (this.opensAfterAbortUnit('afterInsert', object, options?.context)) { - return this.inAfterAbortUnit(() => this.insert(object, data, options)); - } + // + // [#35167] The unit opens around the ENGINE BODY (the executor below), as + // `update`'s does (#35142): the middleware chain runs first, outside it, as + // it does for an insert that opens no unit, so the authorization gate's + // reads do not hold a single-connection store's (SQLite) only connection + // while they run, and a middleware's work after `next()` runs after the + // commit on every object. Nothing between here and the executor writes. + const ownUnit = this.opensAfterAbortUnit('afterInsert', object, options?.context); + const inOwnUnit = (body: () => Promise): (() => Promise) => + ownUnit ? () => this.inAfterAbortUnit(body) : body; this.logger.debug('Insert operation starting', { object, isBatch: Array.isArray(data) }); this.assertWriteAllowed(object, 'insert'); // [#8844] The organization set is about to change. Dropped BEFORE the write @@ -366,7 +373,7 @@ export class InsertFacet { context: options?.context, }; - await this.executeWithMiddleware(opCtx, async () => { + await this.executeWithMiddleware(opCtx, inOwnUnit(async () => { // Resolve field `defaultValue`s (including the `current_user` and // `NOW()` tokens) // BEFORE the beforeInsert hook runs, so a hook that DERIVES one field @@ -1742,7 +1749,7 @@ export class InsertFacet { await this.releaseSecretHandles(object, writtenSecrets, opCtx.context, 'refused'); throw e; } - }); + })); return opCtx.result; } diff --git a/packages/objectql/src/engine-middleware-and-context.ts b/packages/objectql/src/engine-middleware-and-context.ts index 7b383d120cf..a191b63f1f2 100644 --- a/packages/objectql/src/engine-middleware-and-context.ts +++ b/packages/objectql/src/engine-middleware-and-context.ts @@ -203,11 +203,11 @@ export class MiddlewareAndContextFacet { * contract, so a handler reads `ctx.referentialCascadeDelete === true`. * * Reads {@link cascadeIssuedDeletes}, not the envelope (that field says why), - * and CLAIMS the token it matches. Called once per `delete()`, below the - * `afterDelete` unit re-entry (`opensAfterAbortUnit`): a call that re-enters - * itself returns before reaching here, so the claim is made by the inner - * call, the one that dispatches the hooks, and nothing later inside it can - * match the same token again. + * and CLAIMS the token it matches. Called once per `delete()`, before the + * middleware chain; no `delete()` re-enters itself (its `afterDelete` unit + * opens around the executor, `opensAfterAbortUnit`), so the claim is made by + * the call that dispatches the hooks, and nothing later inside it can match + * the same token again. */ static claimReferentialCascadeDelete(this: Pick, object: string, id: unknown): true | undefined { const issued = this.cascadeIssuedDeletes.getStore(); diff --git a/packages/objectql/src/engine-top-level.ts b/packages/objectql/src/engine-top-level.ts index ad3e0edd11b..b82f82e362a 100644 --- a/packages/objectql/src/engine-top-level.ts +++ b/packages/objectql/src/engine-top-level.ts @@ -101,15 +101,18 @@ export interface AdmittedValueShapeViolationTally { * in, and an in-engine audit hook depends on landing inside it. * * Four ordinary paths open such a unit around the dispatch: - * - the write door itself, when the object has a metadata-bound `after*` - * hook that can abort — blocking with `onError` `abort`, or carrying a - * `condition` — so that abort rolls the row back as `HookSchema.onError` - * says (#22782, #22856, `opensAfterAbortUnit`); + * - the write's own engine body, when the object has a metadata-bound + * `after*` hook that can abort — blocking with `onError` `abort`, or + * carrying a `condition` — so that abort rolls the row back as + * `HookSchema.onError` says (#22782, #22856, `opensAfterAbortUnit`). One + * rule for `insert`, `update` and `delete`: the unit opens around the + * executor, inside the middleware chain, so a middleware's work before + * and after `next()` runs outside it (#35142, #35167); * - a by-id {@link ObjectQL.delete} whose cascade is `'atomic'` — each * dependent's own `afterDelete` fires inside the wrap the parent opened, * and the parent's row removal can still refuse afterwards (#7413). The * PARENT's `afterDelete` is outside that wrap by construction (inside the - * door's own unit when the first path opened one); the cascaded + * write's own unit when the first path opened one); the cascaded * CHILDREN's are not; * - `runAtomicBatch` in `@objectstack/metadata-protocol` — * `batchData`/`deleteManyData` with `atomic: true` runs every member's diff --git a/packages/plugins/plugin-security/src/delete-unit-inside-middleware-sqlite.test.ts b/packages/plugins/plugin-security/src/delete-unit-inside-middleware-sqlite.test.ts new file mode 100644 index 00000000000..4231be6328a --- /dev/null +++ b/packages/plugins/plugin-security/src/delete-unit-inside-middleware-sqlite.test.ts @@ -0,0 +1,171 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35167] A `delete` that opens its after-abort unit opens it around the + * engine body, inside the middleware chain — the rule `update` follows since + * #35142, and `insert` beside it — over the REAL stack: `ObjectQL`, + * `SqlDriver` on better-sqlite3 `:memory:` (a single-connection pool) and + * `SecurityPlugin`'s authorization gate, whose by-id delete reads the row as + * the caller before `next()`. + * + * The concurrency cells park one writer's middleware chain — after the gate's + * reads, before `next()` — and ask whether a second writer's delete lands + * meanwhile. When the unit opened at the door, the parked writer already held + * the store's only connection in its `BEGIN`, so the second writer's whole + * delete, its gate reads included, waited for that commit: writers on a hooked + * object were serialised behind the gate. Now nothing holds the connection + * while a middleware runs, on a hooked object as on a plain one. Each writer + * deletes its own row, so neither is the other's loser: the loser's answer is + * a separate question this file does not ask. + * + * The last describe is the control: the unit still exists, and an aborting + * `afterDelete` still puts the row back with it (#22782, unchanged). + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; + +const SYS = { context: { isSystem: true } } as never; +const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; +const OBJ = 'uim_ticket'; +const ORG = 'org_uim'; +const A = 'usr_uim_a'; +const B = 'usr_uim_b'; +/** How long the second writer gets while the first one is parked. */ +const WINDOW_MS = 2_000; +const SET = PermissionSetSchema.parse({ + name: 'uim_member', + objects: { [OBJ]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}); +const SETS = [MEMBER_DEFAULT, SET]; +const memberOf = (userId: string) => ({ + userId, tenantId: ORG, positions: ['org_member'], permissions: [SET.name, 'member_default'], posture: 'MEMBER', +}); +/** What the `afterDelete` hook throws, asserted by identity. */ +const HOOK_REFUSAL = new Error('refused by the afterDelete hook'); +const QUIET = { debug() {}, info() {}, warn() {}, error() {} }; + +type HookShape = 'none' | 'beforeDelete' | 'afterDelete'; + +async function boot(hook: HookShape) { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.unit-inside-middleware', name: 'unit inside middleware', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [SysUser, SysOrganization, SysMember, SysUserPosition, SysUserPermissionSet, { + name: OBJ, label: 'Ticket', sharingModel: 'private', tenancy: { enabled: false }, + fields: { id: { name: 'id', type: 'text', primaryKey: true }, name: { name: 'name', type: 'text' } }, + }], + } as never); + await engine.syncSchemas(); + if (hook !== 'none') { + // A metadata-bound hook: its presence is what opens the after-abort unit — + // any `beforeDelete` (side-writing term), or a blocking `afterDelete` whose + // `onError` is `abort` (aborting term). The `afterDelete` refuses the row + // `tk_boom`, for the control below. + const bound = hook === 'afterDelete' + ? { + name: 'uim_after', object: OBJ, events: ['afterDelete'], onError: 'abort', + handler: (ctx: any) => { if (ctx.input?.id === 'tk_boom') throw HOOK_REFUSAL; }, + } + : { name: 'uim_touch', object: OBJ, events: ['beforeDelete'], handler: () => {} }; + bindHooksToEngine(engine as never, [bound as never], { packageId: 'app:uim', logger: QUIET as never }); + } + await engine.insert('sys_user', [A, B].map((id) => ({ id, name: id, email: `${id}@uim.test` })), SYS); + await engine.insert('sys_organization', [{ id: ORG, name: 'UIM', slug: 'uim' }], SYS); + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + type === 'permission' ? SETS.find((s) => s.name === name) ?? null : engine.getSchema(name) ?? null, + list: async () => SETS, + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: () => undefined, + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + wireEngineSecuritySource(engine, () => plugin); + // Registered after the security plugin's, so it runs after the gate's reads: + // a delete by `A` waits here, before `next()`, until the test releases it. + let release!: () => void; + const parked = new Promise((resolve) => { release = resolve; }); + let arrived!: () => void; + const arrival = new Promise((resolve) => { arrived = resolve; }); + engine.registerMiddleware((async (op: any, next: () => Promise) => { + if (op.operation === 'delete' && op.context?.userId === A) { arrived(); await parked; } + await next(); + }) as never, { object: OBJ }); + return { engine, release, arrival }; +} + +/** Seed a row straight through the driver, below every gate; a member deletes a row it created. */ +const seed = (engine: ObjectQL, id: string, owner: string) => + (engine as any).getDriver(OBJ).create(OBJ, { id, name: id, owner_id: owner, created_by: owner }); +const deleteAs = (engine: ObjectQL, user: string, id: string) => + engine.delete(OBJ, { where: { id }, context: memberOf(user) } as never); +const settledWithin = (p: Promise, ms: number) => + Promise.race([ + p.then(() => 'fulfilled', (e: unknown) => `rejected: ${(e as any)?.code ?? (e as Error)?.message}`), + new Promise((resolve) => setTimeout(() => resolve('still waiting'), ms)), + ]); + +const HOOK_LABEL: Record = { + none: 'no metadata delete hook (no unit)', + beforeDelete: 'a metadata beforeDelete hook (the unit opens)', + afterDelete: 'only a blocking metadata afterDelete hook (the unit opens)', +}; + +for (const hook of ['none', 'beforeDelete', 'afterDelete'] as const) { + describe(`[#35167] delete — ${HOOK_LABEL[hook]}`, () => { + it('a second writer\'s delete lands while the first one is parked in the middleware chain', async () => { + const { engine, release, arrival } = await boot(hook); + await seed(engine, 'tk_a', A); + await seed(engine, 'tk_b', B); + await seed(engine, 'tk_keep', B); + const first = deleteAs(engine, A, 'tk_a'); + // `first` settling before it parks fails the cell below, not the timeout. + await Promise.race([arrival, first.then(() => undefined, () => undefined)]); + const second = await settledWithin(deleteAs(engine, B, 'tk_b'), WINDOW_MS); + release(); + expect(second, 'the second delete, while the first is parked before next()').toBe('fulfilled'); + await expect(first).resolves.toBe(true); + const ids = ((await engine.find(OBJ, {} as never, SYS)) as any[]).map((r) => r.id).sort(); + expect(ids).toEqual(['tk_keep']); + }); + }); +} + +describe('[#35167] control — the unit around the engine body still rolls an aborted delete back', () => { + it('an afterDelete hook that throws leaves the row stored on SQLite', async () => { + const { engine, release } = await boot('afterDelete'); + release(); + await seed(engine, 'tk_boom', B); + await seed(engine, 'tk_ok', B); + const err = await deleteAs(engine, B, 'tk_boom').then(() => undefined, (e: unknown) => e); + expect(err, 'the afterDelete hook\'s own throw reaches the caller').toBe(HOOK_REFUSAL); + expect(await engine.findOne(OBJ, { where: { id: 'tk_boom' } } as never, SYS)).toMatchObject({ id: 'tk_boom' }); + await expect(deleteAs(engine, B, 'tk_ok')).resolves.toBe(true); + }); +}); diff --git a/packages/plugins/plugin-security/src/insert-unit-inside-middleware-sqlite.test.ts b/packages/plugins/plugin-security/src/insert-unit-inside-middleware-sqlite.test.ts new file mode 100644 index 00000000000..d9e33aa6b05 --- /dev/null +++ b/packages/plugins/plugin-security/src/insert-unit-inside-middleware-sqlite.test.ts @@ -0,0 +1,160 @@ +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. + +/** + * [#35167] An `insert` that opens its after-abort unit opens it around the + * engine body, inside the middleware chain — the rule `update` follows since + * #35142 — over the REAL stack: `ObjectQL`, `SqlDriver` on better-sqlite3 + * `:memory:` (a single-connection pool) and `SecurityPlugin`'s authorization + * gate. + * + * The concurrency cells park one writer's middleware chain — after the gate's + * reads, before `next()` — and ask whether a second writer's insert lands + * meanwhile. When the unit opened at the door, the parked writer already held + * the store's only connection in its `BEGIN`, so the second writer's whole + * insert, its gate reads included, waited for that commit: writers on a hooked + * object were serialised behind the gate. Now nothing holds the connection + * while a middleware runs, on a hooked object as on a plain one. + * + * The last describe is the control: the unit still exists, and an aborting + * `afterInsert` still rolls the row back with it (#22782, unchanged). + */ + +import { describe, it, expect, vi } from 'vitest'; +import { ObjectQL, bindHooksToEngine } from '@objectstack/objectql'; +import { SqlDriver } from '@objectstack/driver-sql'; +import { SysMember, SysOrganization, SysUser } from '@objectstack/platform-objects/identity'; +import { PermissionSetSchema } from '@objectstack/spec/security'; +import { SecurityPlugin } from './security-plugin.js'; +import { defaultPermissionSets } from './objects/default-permission-sets.js'; +import { SysUserPosition } from './objects/sys-user-position.object.js'; +import { SysUserPermissionSet } from './objects/sys-user-permission-set.object.js'; +import { wireEngineSecuritySource } from './engine-security-source.testkit.js'; + +const SYS = { context: { isSystem: true } } as never; +const MEMBER_DEFAULT = defaultPermissionSets.find((p) => p.name === 'member_default')!; +const OBJ = 'uim_ticket'; +const ORG = 'org_uim'; +const A = 'usr_uim_a'; +const B = 'usr_uim_b'; +/** How long the second writer gets while the first one is parked. */ +const WINDOW_MS = 2_000; +const SET = PermissionSetSchema.parse({ + name: 'uim_member', + objects: { [OBJ]: { allowRead: true, allowCreate: true, allowEdit: true, allowDelete: true } }, +}); +const SETS = [MEMBER_DEFAULT, SET]; +const memberOf = (userId: string) => ({ + userId, tenantId: ORG, positions: ['org_member'], permissions: [SET.name, 'member_default'], posture: 'MEMBER', +}); +/** What the `afterInsert` hook throws, asserted by identity. */ +const HOOK_REFUSAL = new Error('refused by the afterInsert hook'); +const QUIET = { debug() {}, info() {}, warn() {}, error() {} }; + +type HookShape = 'none' | 'beforeInsert' | 'afterInsert'; + +async function boot(hook: HookShape) { + const engine = new ObjectQL(); + engine.registerDriver( + new SqlDriver({ client: 'better-sqlite3', connection: { filename: ':memory:' }, useNullAsDefault: true }) as never, + true, + ); + await engine.init(); + engine.registerApp({ + id: 'com.objectstack.qa.unit-inside-middleware', name: 'unit inside middleware', version: '1.0.0', type: 'plugin', scope: 'system', + objects: [SysUser, SysOrganization, SysMember, SysUserPosition, SysUserPermissionSet, { + name: OBJ, label: 'Ticket', sharingModel: 'private', tenancy: { enabled: false }, + fields: { id: { name: 'id', type: 'text', primaryKey: true }, name: { name: 'name', type: 'text' } }, + }], + } as never); + await engine.syncSchemas(); + if (hook !== 'none') { + // A metadata-bound hook: its presence is what opens the after-abort unit — + // any `beforeInsert` (side-writing term), or a blocking `afterInsert` whose + // `onError` is `abort` (aborting term). The `afterInsert` refuses a row + // named `boom`, for the control below. + const bound = hook === 'afterInsert' + ? { + name: 'uim_after', object: OBJ, events: ['afterInsert'], onError: 'abort', + handler: (ctx: any) => { if (ctx.result?.name === 'boom') throw HOOK_REFUSAL; }, + } + : { name: 'uim_touch', object: OBJ, events: ['beforeInsert'], handler: () => {} }; + bindHooksToEngine(engine as never, [bound as never], { packageId: 'app:uim', logger: QUIET as never }); + } + await engine.insert('sys_user', [A, B].map((id) => ({ id, name: id, email: `${id}@uim.test` })), SYS); + await engine.insert('sys_organization', [{ id: ORG, name: 'UIM', slug: 'uim' }], SYS); + const services: Record = { + manifest: { register: vi.fn() }, + objectql: engine, + metadata: { + get: async (type: string, name: string) => + type === 'permission' ? SETS.find((s) => s.name === name) ?? null : engine.getSchema(name) ?? null, + list: async () => SETS, + }, + }; + const ctx = { + logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn(), debug: vi.fn() }, + registerService: () => undefined, + hook: () => undefined, + getService: (name: string) => { + if (!(name in services)) throw new Error(`service not registered: ${name}`); + return services[name]; + }, + }; + const plugin = new SecurityPlugin({ fallbackPermissionSet: 'member_default' }); + await plugin.init(ctx as never); + await plugin.start(ctx as never); + wireEngineSecuritySource(engine, () => plugin); + // Registered after the security plugin's, so it runs after the gate's reads: + // a write by `A` waits here, before `next()`, until the test releases it. + let release!: () => void; + const parked = new Promise((resolve) => { release = resolve; }); + let arrived!: () => void; + const arrival = new Promise((resolve) => { arrived = resolve; }); + engine.registerMiddleware((async (op: any, next: () => Promise) => { + if (op.operation === 'insert' && op.context?.userId === A) { arrived(); await parked; } + await next(); + }) as never, { object: OBJ }); + return { engine, release, arrival }; +} + +const insertAs = (engine: ObjectQL, user: string, id: string, name = id) => + engine.insert(OBJ, { id, name }, { context: memberOf(user) } as never); +const settledWithin = (p: Promise, ms: number) => + Promise.race([ + p.then(() => 'fulfilled', (e: unknown) => `rejected: ${(e as any)?.code ?? (e as Error)?.message}`), + new Promise((resolve) => setTimeout(() => resolve('still waiting'), ms)), + ]); + +const HOOK_LABEL: Record = { + none: 'no metadata insert hook (no unit)', + beforeInsert: 'a metadata beforeInsert hook (the unit opens)', + afterInsert: 'only a blocking metadata afterInsert hook (the unit opens)', +}; + +for (const hook of ['none', 'beforeInsert', 'afterInsert'] as const) { + describe(`[#35167] insert — ${HOOK_LABEL[hook]}`, () => { + it('a second writer\'s insert lands while the first one is parked in the middleware chain', async () => { + const { engine, release, arrival } = await boot(hook); + const first = insertAs(engine, A, 'tk_a'); + // `first` settling before it parks fails the cell below, not the timeout. + await Promise.race([arrival, first.then(() => undefined, () => undefined)]); + const second = await settledWithin(insertAs(engine, B, 'tk_b'), WINDOW_MS); + release(); + expect(second, 'the second insert, while the first is parked before next()').toBe('fulfilled'); + await expect(first).resolves.toMatchObject({ id: 'tk_a' }); + const ids = ((await engine.find(OBJ, {} as never, SYS)) as any[]).map((r) => r.id).sort(); + expect(ids).toEqual(['tk_a', 'tk_b']); + }); + }); +} + +describe('[#35167] control — the unit around the engine body still rolls an aborted insert back', () => { + it('an afterInsert hook that throws leaves no row on SQLite', async () => { + const { engine, release } = await boot('afterInsert'); + release(); + const err = await insertAs(engine, B, 'tk_boom', 'boom').then(() => undefined, (e: unknown) => e); + expect(err, 'the afterInsert hook\'s own throw reaches the caller').toBe(HOOK_REFUSAL); + expect(await engine.findOne(OBJ, { where: { id: 'tk_boom' } } as never, SYS)).toBeNull(); + await expect(insertAs(engine, B, 'tk_ok')).resolves.toMatchObject({ id: 'tk_ok' }); + }); +}); diff --git a/scripts/measure-durability-swallow-family.mjs b/scripts/measure-durability-swallow-family.mjs index 8b9cf82ada4..b601271cb92 100644 --- a/scripts/measure-durability-swallow-family.mjs +++ b/scripts/measure-durability-swallow-family.mjs @@ -549,19 +549,19 @@ const RESOLUTION_CONTROLS = [ + 'two apart — which is the whole reason this family reads the resolver instead of the output.', }, { - file: 'packages/objectql/src/engine-delete-and-aggregate.ts', - callee: 'delete', - fromClass: 'DeleteAndAggregateFacet', - resolvesIn: 'DeleteAndAggregateFacet', + file: 'packages/objectql/src/engine-insert.ts', + callee: 'insert', + fromClass: 'InsertFacet', + resolvesIn: 'InsertFacet', why: - 'The sharpest name in the vocabulary: `delete` is the callee the AWAITED discriminator exists to ' - + 'police. Its one `this.delete(...)` re-entry (the after-abort unit re-running the delete) moved ' - + 'out of `ObjectQL` in `engine.ts` with the body that holds it, into the facet module, where ' - + '`this` is the facet host and its `delete` is the class\'s stub, which calls the facet\'s own ' - + '`delete`. So the hop must land in `DeleteAndAggregateFacet`, the body the stub reaches, and in ' - + 'no other. The cross-class collision in `engine.ts` (`ObjectRepository` and `ScopedContext` ' - + 'declaring a method of an `ObjectQL` name) stays pinned by the `update` and `transaction` ' - + 'controls beside this one.', + 'A facet module calling the method its own body implements: `insertMany` is `this.insert(...)`, ' + + 'where `this` is the facet host and its `insert` is the class\'s stub, which calls the facet\'s own ' + + '`insert`. So the hop must land in `InsertFacet`, the body the stub reaches, and in no other. ' + + 'This control first pinned the same shape on `delete`, through the re-entry that reran a delete ' + + 'inside its after-abort unit; that re-entry is gone (the unit opens around the engine body, ' + + '#35167), and with it the file\'s only `this.delete(...)`. The cross-class collision in ' + + '`engine.ts` (`ObjectRepository` and `ScopedContext` declaring a method of an `ObjectQL` name) ' + + 'stays pinned by the `update` and `transaction` controls beside this one.', }, { file: 'packages/objectql/src/engine.ts', @@ -571,7 +571,7 @@ const RESOLUTION_CONTROLS = [ why: 'Third class in the same file: `ScopedContext` (line ~13469) also declares `transaction()`, and ' + 'it is the LAST one, so the flat index handed `ObjectQL`\'s own `this.transaction(...)` to a ' - + 'class it has no relationship with. Pinned separately from `update`/`delete` because it proves ' + + 'class it has no relationship with. Pinned separately from `update`/`insert` because it proves ' + 'the key is the OWNING CLASS and not "the second declaration".', }, {