diff --git a/.changeset/35149-trio-handle-closed.md b/.changeset/35149-trio-handle-closed.md new file mode 100644 index 00000000000..b3ae0c477a3 --- /dev/null +++ b/.changeset/35149-trio-handle-closed.md @@ -0,0 +1,10 @@ +--- +'@objectstack/objectql': patch +--- + +fix(objectql): a trio transaction handle that committed or rolled back reads as closed, as a closed `transaction()` unit handle does + +Clause-②: no +Metadata-protocol: none + +`ScopedContext`'s discrete `beginTransaction` / `commitTransaction` / `rollbackTransaction` trio (the sandbox runner's `ctx.api.transaction`) now marks its handle closed when it commits or rolls it back, instead of only dropping the handle's owner record. The engine's closed-handle check answers `true` for it, so work that still carries the handle afterwards runs outside any transaction, on its own connection, exactly as late work carrying a closed `transaction()` unit handle already did. Before, such a handle read as an unattributed one: a late write routed to another datasource was handed the dead foreign handle, and a late write on the same datasource was handed the finished handle. `openTransactionKind` answers `'none'` for a closed trio handle, where it answered `'separate'`. A driver that hands out the same handle object on a later `beginTransaction` gets it back open. diff --git a/packages/objectql/src/engine-execute-transactions.ts b/packages/objectql/src/engine-execute-transactions.ts index 9ed8195b6c3..abff61612cf 100644 --- a/packages/objectql/src/engine-execute-transactions.ts +++ b/packages/objectql/src/engine-execute-transactions.ts @@ -77,20 +77,38 @@ import type { ObjectQL } from './engine.js'; */ const trioTransactionScopes = new WeakMap(); +/** + * [#35149] The handles the trio opened and has since committed or rolled back. + * The engine's `isClosedUnitHandle` answers `true` for them, as it does for a + * `transaction()` unit whose callback settled (#22855), so every reader of a + * threaded handle treats one as absent: work that still carries it runs + * unenrolled. Dropping the owner record alone left such a handle unattributed, + * and a late write routed to another datasource was handed the dead handle. + * Weak, for the reason the owner record is. + */ +const closedTrioHandles = new WeakSet(); + /** [#35028] Record the owner of a handle the trio just opened. A primitive handle cannot key it and stays unattributed. */ export function recordTrioTransactionScope(handle: unknown, scope: TransactionScope): void { if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) { trioTransactionScopes.set(handle, scope); + // [#35149] A driver that hands the same object out again opened it again. + closedTrioHandles.delete(handle); } } -/** [#35028] Forget a trio handle's owner: its commit or rollback closed it. */ -export function forgetTrioTransactionScope(handle: unknown): void { +/** [#35149] Close a handle the trio opened: its commit or rollback ended it. A handle it never opened is left as it was. */ +export function closeTrioTransactionScope(handle: unknown): void { if (handle !== null && (typeof handle === 'object' || typeof handle === 'function')) { - trioTransactionScopes.delete(handle); + if (trioTransactionScopes.delete(handle)) closedTrioHandles.add(handle); } } +/** [#35149] Did the trio open `handle` and since commit or roll it back? */ +export function isClosedTrioHandle(handle: unknown): boolean { + return handle !== null && (typeof handle === 'object' || typeof handle === 'function') && closedTrioHandles.has(handle); +} + /** [#35028] The owner of an open trio handle, or `undefined` for any other handle. */ export function trioTransactionScopeOf(handle: unknown): TransactionScope | undefined { if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return undefined; diff --git a/packages/objectql/src/engine-scoped-context.ts b/packages/objectql/src/engine-scoped-context.ts index 68808d82a76..8b54c194839 100644 --- a/packages/objectql/src/engine-scoped-context.ts +++ b/packages/objectql/src/engine-scoped-context.ts @@ -44,7 +44,7 @@ import { appAutomationElevationOf, markAppAutomationElevation, resolveUserAuthzG import type { EngineTransactionInfo, EngineTransactionOptions } from '@objectstack/core'; import { rolledBackRefusal } from './summary-errors.js'; import { TransactionUnsupportedError } from './transaction-errors.js'; -import { forgetTrioTransactionScope, recordTrioTransactionScope } from './engine-execute-transactions.js'; +import { closeTrioTransactionScope, recordTrioTransactionScope } from './engine-execute-transactions.js'; import { redactPropagatedDriverFault } from '@objectstack/types'; import { UnscopedHookApi } from './hook-run-as.js'; import { newUnitCommitQueue, openTrioCommitQueue, runOutsideOpenUnits, runOutsideOpenUnitsOnCommit, settleTrioCommitQueue, settleUnitCommitQueue, type UNIT_ROLLED_BACK } from './unit-detach.js'; @@ -372,7 +372,7 @@ export class ScopedContextFacet { if (driver.commit) await driver.commit(handle); else if (driver.commitTransaction) await driver.commitTransaction(handle); } finally { - forgetTrioTransactionScope(handle); + closeTrioTransactionScope(handle); } settleTrioCommitQueue(handle, true); } @@ -388,7 +388,7 @@ export class ScopedContextFacet { if (driver.rollback) await driver.rollback(handle); else if (driver.rollbackTransaction) await driver.rollbackTransaction(handle); } finally { - forgetTrioTransactionScope(handle); + closeTrioTransactionScope(handle); } } diff --git a/packages/objectql/src/engine-transaction-same-origin.test.ts b/packages/objectql/src/engine-transaction-same-origin.test.ts index e77b8563d61..70f9a6ed441 100644 --- a/packages/objectql/src/engine-transaction-same-origin.test.ts +++ b/packages/objectql/src/engine-transaction-same-origin.test.ts @@ -37,6 +37,7 @@ import type { Hook } from '@objectstack/spec/data'; import { ObjectQL, ScopedContext } from './engine.js'; import { bindHooksToEngine } from './hook-binder.js'; import { CrossDatasourceTransactionWriteError } from './transaction-errors.js'; +import { openTransactionKind } from './open-transaction.js'; interface Recorded { level: 'debug' | 'info' | 'warn' | 'error'; @@ -686,24 +687,29 @@ describe('a handle the ScopedContext trio opened is attributed to its owner (#35 expect(ledgerDb.writes.map((w: RecordedWrite) => w.op)).toEqual(['create']); }); - it('forgets the owner once the trio commits — the record does not outlive the handle', async () => { + it('treats the handle as closed once the trio commits — a late cross-datasource write runs unenrolled', async () => { const { engine, ledgerDb } = await splitEngine(); const { scoped, handle } = await openTrio(engine); await scoped.commitTransaction(handle); - // A closed handle threaded back in is no open trio transaction: it is - // judged as any unattributed handle is (the declared limit above). + // [#35149] A closed handle threaded back in is no handle, as a closed + // `transaction()` unit's is (#22855): the write is not refused, and it + // runs outside any transaction. Before #35149 the commit only dropped the + // owner record, so the handle read as an unattributed one and the dead + // `primary` handle was handed to `ledger_db`. await engine.insert('ledger', { name: 'after commit' }, { context: { transaction: handle } } as any); expect(ledgerDb.writes).toHaveLength(1); + expect(ledgerDb.writes[0].transaction).toBeUndefined(); }); - it('forgets the owner once the trio rolls back, too', async () => { + it('treats the handle as closed once the trio rolls back, too', async () => { const { engine, ledgerDb } = await splitEngine(); const { scoped, handle } = await openTrio(engine); await scoped.rollbackTransaction(handle); await engine.insert('ledger', { name: 'after rollback' }, { context: { transaction: handle } } as any); expect(ledgerDb.writes).toHaveLength(1); + expect(ledgerDb.writes[0].transaction).toBeUndefined(); }); it('lets an async afterFind run, detached from the open trio handle, write a business object on another datasource', async () => { @@ -773,3 +779,87 @@ describe('a handle the ScopedContext trio opened is attributed to its owner (#35 }); }); }); + +// --------------------------------------------------------------------------- +// (g) A closed trio handle is no handle — as a closed transaction() unit's is (#35149) +// --------------------------------------------------------------------------- + +describe('a trio handle closes as a transaction() unit handle does (#35149)', () => { + /** The engine's own reading of a threaded handle (`isClosedUnitHandle`), the one every write and read path acts on. */ + const isClosed = (engine: ObjectQL, handle: unknown): boolean => (engine as any).isClosedUnitHandle(handle); + + async function openTrio(engine: ObjectQL) { + const scoped = (engine as any).createContext({ userId: 'u1' }) as ScopedContext; + const opened = await scoped.beginTransaction(); + expect(opened, 'precondition: the default driver opens transactions').not.toBeNull(); + expect(opened!.owned, 'precondition: the trio opened this handle, it did not join one').toBe(true); + return { scoped, ctx: opened!.ctx as any, handle: opened!.handle }; + } + + it('gives a late cross-datasource write the same answer under a committed trio handle as under a closed unit handle', async () => { + const { engine, ledgerDb } = await splitEngine(); + let unitHandle: unknown; + await engine.transaction(async (trxCtx: any) => { unitHandle = trxCtx?.transaction; }); + expect(unitHandle, 'precondition: transaction() threads its handle into the callback').toBeDefined(); + const { scoped, handle } = await openTrio(engine); + await scoped.commitTransaction(handle); + + expect(isClosed(engine, unitHandle)).toBe(true); + expect(isClosed(engine, handle)).toBe(true); + await engine.insert('ledger', { name: 'late, closed unit' }, { context: { transaction: unitHandle } } as any); + await engine.insert('ledger', { name: 'late, committed trio' }, { context: { transaction: handle } } as any); + expect(ledgerDb.writes.map((w: RecordedWrite) => w.transaction)).toEqual([undefined, undefined]); + }); + + it('runs a late same-datasource write unenrolled too, never on the dead handle', async () => { + const { engine, primary } = await splitEngine(); + const { scoped, handle } = await openTrio(engine); + await scoped.rollbackTransaction(handle); + + expect(isClosed(engine, handle)).toBe(true); + await engine.insert('thing', { name: 'after rollback' }, { context: { transaction: handle } } as any); + expect(primary.writes).toHaveLength(1); + expect(primary.writes[0].transaction).toBeUndefined(); + }); + + it('CONTROL: an open trio handle still enrolls, and a cross-datasource business write under it is still refused', async () => { + const { engine, primary, ledgerDb } = await splitEngine(); + const { scoped, handle } = await openTrio(engine); + + expect(isClosed(engine, handle)).toBe(false); + await engine.insert('thing', { name: 'in the trio' }, { context: { transaction: handle } } as any); + expect(primary.writes[0].transaction).toBe(handle); + const err = await rejection( + engine.insert('ledger', { name: 'refused' }, { context: { transaction: handle } } as any), + ); + expect(err.code).toBe('ERR_CROSS_DATASOURCE_TRANSACTION_WRITE'); + expect(ledgerDb.writes).toHaveLength(0); + await scoped.commitTransaction(handle); + expect(isClosed(engine, handle)).toBe(true); + }); + + it('answers the body doors\' question the same way: separate while open, none once committed', async () => { + const { engine } = await splitEngine(); + const { scoped, handle } = await openTrio(engine); + + expect(openTransactionKind(engine, handle)).toBe('separate'); + await scoped.commitTransaction(handle); + expect(openTransactionKind(engine, handle)).toBe('none'); + }); + + it('reads a handle the driver hands out again as open on its next begin', async () => { + const { engine, primary } = await splitEngine(); + const shared = { __trx: 'primary, reused' }; + primary.beginTransaction = async () => shared; + const first = await openTrio(engine); + await first.scoped.commitTransaction(first.handle); + expect(isClosed(engine, shared)).toBe(true); + + const second = await openTrio(engine); + expect(second.handle).toBe(shared); + expect(isClosed(engine, shared)).toBe(false); + await second.ctx.object('thing').insert({ name: 'on the reopened handle' }); + expect(primary.writes[0].transaction).toBe(shared); + await second.scoped.commitTransaction(shared); + }); +}); diff --git a/packages/objectql/src/engine-transactions-section.ts b/packages/objectql/src/engine-transactions-section.ts index 20d4b0047f3..d97e0bdaefb 100644 --- a/packages/objectql/src/engine-transactions-section.ts +++ b/packages/objectql/src/engine-transactions-section.ts @@ -35,6 +35,7 @@ import type { EngineTransactionInfo, EngineTransactionOptions, IDataDriver } fro import { rollbackFailedRefusal, rolledBackRefusal } from './summary-errors.js'; import { TransactionUnsupportedError } from './transaction-errors.js'; import { isDetachedUnitHandle, newUnitCommitQueue, settleUnitCommitQueue, type UnitCommitQueue } from './unit-detach.js'; +import { isClosedTrioHandle } from './engine-execute-transactions.js'; import type { TransactionScope } from './engine-top-level.js'; import type { ObjectQL } from './engine.js'; @@ -181,13 +182,15 @@ export class TransactionsSectionFacet { * [#22855] Is `handle` a unit {@link runOpenedUnit} published whose callback * has since settled? [#33651] Or one the current run was detached from — an * `async: true` hook's run, which starts outside every unit open at its - * dispatch (`unit-detach.ts`), primitive handles included. + * dispatch (`unit-detach.ts`), primitive handles included. [#35149] Or one + * `ScopedContext`'s discrete trio opened and has since committed or rolled + * back (`isClosedTrioHandle`), so the two kinds of handle close alike. */ static isClosedUnitHandle(this: Pick, handle: unknown): boolean { if (isDetachedUnitHandle(handle)) return true; if (handle === null || (typeof handle !== 'object' && typeof handle !== 'function')) return false; const entry = this.openedUnits.get(handle); - return entry !== undefined && entry.transaction === undefined; + return entry !== undefined ? entry.transaction === undefined : isClosedTrioHandle(handle); } /**