Skip to content

Commit 4013e30

Browse files
refactor(objectql): ScopedContext's two bodies that hand the instance on move into its facet (#30020 S1) (#31665)
<!-- claude-projects-attribution: {"github_login":"os-steve"} --> _Requested by **Steve** · [project thread](https://claude.ai/code/project/chan_01FdL1XeUyvVNxLreh3F4Qi9?thread=cmsg_01FdL1XeUyvVNxLreh3F4Qi9AVUcBf9iiSFW8k3r6KcyAL)_ Refs #30020 Clause-②: no Metadata-protocol: none Ruling-ref: 6687865760 ## 维护者速读 - 改了什么:把 `ScopedContext` 上最后两个"把自己交出去"的方法体(`transaction` 与按符号键的授权补种步骤)搬进 `engine-scoped-context.ts`,方法留在类上做一行转发;拆分脚本新增对应的搬运模式。 - 为什么改:#30020 第 S1 项。按裁决 A,状态仍归类本身,facet 通过 `facade` 端口拿到实例本身;注册表里这两行豁免随之删除(11 → 9)。 - 风险与回滚:纯搬运,撤销证明逐字节还原基线,对外 `.d.ts` 与基线逐字节相同;回滚即 revert 本 PR。`transaction` 在每条事务路径上,已跑 objectql 全量与 dogfood。 - 先看:`packages/objectql/src/engine-scoped-context.ts`(新增两个静态成员与 `facade` 端口)、`packages/objectql/src/engine.ts` 末尾的 install 块、`scripts/codemod-split-engine.mjs` 新增的 members 模式一节。 - 两分钟验证:`node scripts/codemod-split-engine.mjs --scoped --members --verify --base origin/main`,预期输出 "does rebuild the base engine.ts and its scoped modules byte-for-byte"、退出码 0。 - 需要你做的:无,席位落地。 ## What changes S1 of the approved §5 order on #30020 (E1, E2 and E3 are on `main`). Rule A (ruling 6687865760): the facade stays the sole state owner; a moved body reads the instance itself through its host's `facade` port. - `scripts/codemod-split-engine.mjs` gains the second pass's **members mode**, `--scoped --members Class#member,…` (and `--scoped --members --verify --base REF`). Step 0 measured why it was needed: on `main` `06060c61c`, `--members` is `ObjectQL`-only (`--members names [SEED_USER_GRANTS], which ObjectQL declares as no method`, exit 2) and `--scoped` refuses a split file (exit 2). The mode moves a named scoped method onto the split class into its written facet, exactly as the second pass would have, with: - **R1 on an instance host**: a bare `this` the body hands on reads `this.facade`; the class's install block fills it with `facade: instance`, and the host interface types it `readonly facade: ScopedContext`. - **R9, a symbol key** (the design's symbol-keyed-member rule): a method keyed `[NAME]`, NAME a module-scope binding spelled SCREAMING_SNAKE, moves into the facet member NAME in camelCase. `[SEED_USER_GRANTS]` becomes `ScopedContextFacet.seedUserGrants`, the same spelling the hand move of `[APP_AUTHORED_HOOK_API]` took (`appAuthoredHookApi`). The stub keeps the key. - The facet module's header sentence is rewritten for the new names only; the hand-written words after it (the #30975 note) are kept byte for byte. - Shared pieces were factored rather than copied: the fourth pass's import-growth step is now `moduleImportEdits`, the install lines `scopedInstallLines`, the header sentence `scopedHeaderSentence`. Every earlier battery of the self-test still passes unchanged. - Applied: `node scripts/codemod-split-engine.mjs --scoped --members 'ScopedContext#[SEED_USER_GRANTS],ScopedContext#transaction' --write` on `06060c61c`. Both stubs keep their docblock and signature (`async` dropped, as every stub of the series). `return this` (twice) and `callback(this, { owned: false })` read `this.facade`. `engine.ts` 10,740 → 10,647 lines; four import bindings only the moved bodies read leave it (`driverSupportsTransactions`, `redactPropagatedDriverFault`, `resolveUserAuthzGrants`, `rolledBackRefusal`) and arrive in the facet module. - `scripts/facade-delegation-registry.json`: the two `ScopedContext` rows (`[SEED_USER_GRANTS]`, `transaction`) are removed. No other row. `check:facade-delegation-only`: 11 named exceptions on base, 9 on head. - Changeset `.changeset/30020-scoped-context-facet-bodies.md`, `@objectstack/objectql` patch: the published JS moves even though the `.d.ts` does not, and AGENTS.md reserves `skip-changeset` for a diff that publishes nothing (the delta allowed `skip-changeset`; AGENTS.md wins, declared in the report). No forced test edits. ## Tests - objectql typecheck exit 0; `pnpm --filter @objectstack/objectql test`: **Test Files 572 passed (572), Tests 11616 passed (11616)** on head; the same command on base `06060c61c`: **572 / 11616**. Base counts held. - Codemod self-test: **211 cases in 13 batteries** (base: 186 in 12). The new battery, `scoped members, instance identity port and symbol keys (second pass, #30020 S1)`, floor 25: the plan, the proof, determinism, stub / facet / interface / install / header / import shapes, a hand tail kept, seven tampered heads that must fail, and refusals (foreign-private, a key R9 does not take, an unqualified name, an already-moved method, a class declaring `facade`, a non-scoped class). - Ablations (each through `scripts/ablation-replace.mjs`, restored with blob == HEAD and `git diff HEAD` empty): - R9 off: self-test exit 2, `ScopedContext#[SEED_KEY] stays on the class …: not-identifier-name`. - R1 on the instance host off: self-test exit 2, `… bare-this`. - The undo's R1 inverse off: `--scoped --members --verify --base origin/main` exit 1, `undoing the moves does not rebuild the base engine.ts (first difference at line 10436)`. - Dogfood battery (`ScopedContext.transaction` is on every transactional path), under the verify lock: `pnpm turbo run build --filter='@objectstack/dogfood^...' && pnpm --filter @objectstack/dogfood test` exit 0: **Test Files 440 passed | 3 skipped (443), Tests 3652 passed | 41 skipped (3693)** on head. Not run on base (the skips are the battery's own gated cases, not this diff's). ## Acceptance notes - `ScopedContextFacet`'s module header says each static method is "the body of the `ScopedContext` method of the same name"; `seedUserGrants` (like the earlier hand-moved `appAuthoredHookApi`) is named by R9, and its placeholder docblock names the method by its key (`ScopedContext#[SEED_USER_GRANTS]`). - The second pass's own `--scoped --verify` was already not re-runnable on `main` (the #30975 hand moves); this mode carries its own undo proof and does not depend on it. - Overlap re-check (20:12Z, before opening): of the 40 most recently updated open PRs, the four code PRs near this file set (#31637, #31653, #31655, #31631) touch none of `engine.ts`, `engine-scoped-*.ts`, the registry or the codemod. The WIP branch push (20:05Z) went out before this re-check; the seat's 19:55Z read covered it. ## Verification <details><summary>Undo proof (byte-exact)</summary> ``` node scripts/codemod-split-engine.mjs --scoped --members --verify --base origin/main (exit 0, head 9ffb6d5) undo proof (scoped members): 2 moved method(s) (ScopedContext#[SEED_USER_GRANTS], ScopedContext#transaction); engine.ts 10740 -> 10647 lines; undoing the moves does rebuild the base engine.ts and its scoped modules byte-for-byte once the 4 import binding(s) only moved bodies read are pruned from the base (driverSupportsTransactions, redactPropagatedDriverFault, resolveUserAuthzGrants, rolledBackRefusal) ``` Plan run on base: input sha256 d92396f28793cb03c54e0841bca886fc699a553c61faf2856a8e769298841cfc, output tree sha256 2e795a10241977a8d0f249f059876245c80c2fd12e2bf09aa7c55285fe3b4a25. </details> <details><summary>Public .d.ts (base 06060c6 vs head)</summary> `diff -r` of `packages/objectql/dist/*.d.ts` and `*.d.mts` (core, index, util-iFatUShh) between a base build and a head build: empty, exit 0. sha256 identical on both sides (core.d.ts 20b3e4bb…, index.d.ts 42a71dbc…, util-iFatUShh.d.ts 25e56780…). Positive control: `ScopedContextFacet.seedUserGrants` occurs 0 times in base `dist/index.mjs`, once in head's. </details> <details><summary>Gates</summary> `node scripts/pm/dispatch-gates.mjs --commands` on head `9ffb6d5e08`: 80 derived commands, all exit 0. `--ran` reconciliation: 80 derived, 80 run, 0 NOT-MEASURED, 0 UNRUN. Two first runs exited 3 on container prerequisites, not the diff, and were re-run green: the teardown self-test (shallow clone; fetched its fixture commit) and `check:dual-build-cjs-loads` (needs a full `pnpm build`, run under the lock). Outside the derived set: `pnpm check:facade-delegation-only` exit 0 (9 named exceptions); eslint over `packages/objectql` and the codemod exit 0. ``` node scripts/check-adr-0087-registration.mjs --base origin/main :: exit 0 node scripts/check-adr-0087-registration.mjs --self-test :: exit 0 node scripts/check-changeset-no-major.mjs --base origin/main :: exit 0 node scripts/check-closing-keyword-parity.mjs :: exit 0 node scripts/check-closing-keyword-parity.mjs --self-test :: exit 0 node scripts/check-comment-mask-adoption.mjs :: exit 0 node scripts/check-comment-mask-adoption.mjs --self-test :: exit 0 node scripts/check-comment-mask-corpus.mjs :: exit 0 node scripts/check-declaration-mirrors.mjs :: exit 0 node scripts/check-declaration-mirrors.mjs --self-test :: exit 0 node scripts/check-dts-emitted.mjs --self-test :: exit 0 node scripts/check-empty-changeset.mjs --base origin/main :: exit 0 node scripts/check-empty-changeset.mjs --self-test :: exit 0 node scripts/check-engine-split-ratio.mjs --self-test :: exit 0 node scripts/check-issue-citations.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs :: exit 0 node scripts/check-plugin-teardown-shape.mjs --self-test :: exit 0 node scripts/check-self-test-wired.mjs :: exit 0 node scripts/check-self-test-wired.mjs --self-test :: exit 0 node scripts/check-self-test-workflow-commands.mjs :: exit 0 node scripts/check-self-test-workflow-commands.mjs --self-test :: exit 0 node scripts/check-whole-set-label-write.mjs :: exit 0 node scripts/check-whole-set-label-write.mjs --self-test :: exit 0 node scripts/ci/assert-turbo-remote-cache.mjs --self-test :: exit 0 node scripts/ci/plan-test-core-shards.mjs --self-test :: exit 0 node scripts/ci/prune-turbo-cache.mjs --self-test :: exit 0 node scripts/ci/snapshot-next.mjs --self-test :: exit 0 node scripts/docs-audit/check-affected-docs.mjs :: exit 0 node scripts/docs-audit/check-drift-comment.mjs :: exit 0 node scripts/pm/release-rehearsal-clone.mjs --self-test :: exit 0 node scripts/release-pending-publish.mjs --self-test :: exit 0 pnpm --filter @objectstack/spec run check:duration-unit-keys :: exit 0 pnpm --filter @objectstack/spec run check:error-code-provenance :: exit 0 pnpm check:adr-symbol-anchors :: exit 0 pnpm check:agent-test-spelling :: exit 0 pnpm check:bash32-floor :: exit 0 pnpm check:changeset-gate-self-tests :: exit 0 pnpm check:ci-filter-parity :: exit 0 pnpm check:cli-command-ids :: exit 0 pnpm check:closed-ceremony-text :: exit 0 pnpm check:cross-package-test-inputs :: exit 0 pnpm check:dispatcher-error-vocabulary :: exit 0 pnpm check:doc-authoring :: exit 0 pnpm check:driver-memory-census :: exit 0 pnpm check:dts-closure :: exit 0 pnpm check:dual-build-cjs-loads :: exit 0 pnpm check:durability-log-level :: exit 0 pnpm check:entry-guard :: exit 0 pnpm check:error-status-conformance :: exit 0 pnpm check:facade-delegation-only :: exit 0 pnpm check:gitlink-declared :: exit 0 pnpm check:issue-citations :: exit 0 pnpm check:keyed-text-bounds :: exit 0 pnpm check:lean-entry-closure :: exit 0 pnpm check:logger-receiver-detach :: exit 0 pnpm check:nul-bytes :: exit 0 pnpm check:object-def-param-keys :: exit 0 pnpm check:optional-error-sink :: exit 0 pnpm check:org-identifier :: exit 0 pnpm check:page-declaration-shape :: exit 0 pnpm check:parse-guard :: exit 0 pnpm check:platform-object-tenancy-census :: exit 0 pnpm check:pnpm-filter-targets :: exit 0 pnpm check:pnpm-flag-spellings :: exit 0 pnpm check:published-files :: exit 0 pnpm check:ratchet-remedy-authority :: exit 0 pnpm check:refd-timer-probe :: exit 0 pnpm check:registry-log-declared :: exit 0 pnpm check:rest-log-spy-declared :: exit 0 pnpm check:scripts-symbol-anchors :: exit 0 pnpm check:settings-bind-window :: exit 0 pnpm check:slot-lookup :: exit 0 pnpm check:sourcemap-no-sources-content :: exit 0 pnpm check:swallow-census-controls :: exit 0 pnpm check:system-context-census :: exit 0 pnpm check:test-source-alias :: exit 0 pnpm check:tier-file-adoption :: exit 0 pnpm check:undeclared-dep-imports :: exit 0 pnpm check:vouch-for-reference-callers :: exit 0 pnpm check:watch-hint-literal :: exit 0 ``` </details> --- _Generated by [Claude Code](https://claude.ai/code/session_01ADHkmSfdZ9zS9bzZR31tpB)_ --------- Co-authored-by: Claude <noreply@anthropic.com> Co-authored-by: objectstack-fleet[bot] <332303061+objectstack-fleet[bot]@users.noreply.github.com>
1 parent f2abd47 commit 4013e30

5 files changed

Lines changed: 903 additions & 206 deletions

File tree

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
'@objectstack/objectql': patch
3+
---
4+
5+
refactor(objectql): `ScopedContext`'s two bodies that hand the instance on move into its facet
6+
7+
Clause-②: no
8+
Metadata-protocol: none
9+
10+
- The bodies of `ScopedContext#transaction` and of its symbol-keyed grants seeding step (the one a hook's `runAs: 'user'` api awaits) move out of `engine.ts` into `engine-scoped-context.ts`. Each method stays on the class as a one-call stub with its signature and docblock. Where a body handed the context itself on (`return this`, `callback(this, …)`), it reads the same instance through its host's `facade` entry.
11+
- No behaviour changes and nothing to do on upgrade. The built declaration files keep every member and every docblock; the source maps move.

‎packages/objectql/src/engine-scoped-context.ts‎

Lines changed: 116 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,10 @@
33
/**
44
* [#30052 codemod] The "Scoped execution context: repositories, elevation,
55
* transactions" section: the bodies of `ScopedContext`'s methods `object`,
6-
* `sudo`, `withRunAs`, `releaseJoinedHandle`, `txDriver`, `beginTransaction`,
7-
* `commitTransaction`, `rollbackTransaction`, `serveFormulaField` moved out of
8-
* `engine.ts` whole by `scripts/codemod-split-engine.mjs` (its second pass).
6+
* `sudo`, `withRunAs`, `[SEED_USER_GRANTS]`, `transaction`,
7+
* `releaseJoinedHandle`, `txDriver`, `beginTransaction`, `commitTransaction`,
8+
* `rollbackTransaction`, `serveFormulaField` moved out of `engine.ts` whole by
9+
* `scripts/codemod-split-engine.mjs` (its second pass).
910
* The bodies of `derive` and `[APP_AUTHORED_HOOK_API]` moved by hand
1011
* (#30975): each writes the private `appAuthored` of the instance it builds,
1112
* which the codemod refuses to move (`foreign-private`), so each writes it
@@ -37,7 +38,11 @@
3738
import { driverSupportsTransactions } from '@objectstack/spec/data';
3839
import type { IScopedContext } from '@objectstack/spec/contracts';
3940
import type { ExecutionContext } from '@objectstack/spec/kernel';
40-
import { appAutomationElevationOf, markAppAutomationElevation } from '@objectstack/core';
41+
import { appAutomationElevationOf, markAppAutomationElevation, resolveUserAuthzGrants } from '@objectstack/core';
42+
import type { EngineTransactionInfo, EngineTransactionOptions } from '@objectstack/core';
43+
import { rolledBackRefusal } from './summary-errors.js';
44+
import { TransactionUnsupportedError } from './transaction-errors.js';
45+
import { redactPropagatedDriverFault } from '@objectstack/types';
4146
import { UnscopedHookApi } from './hook-run-as.js';
4247
import { refuseAppAuthoredPermanentDelete } from './recycle-bin/app-authored-delete.js';
4348
import type { HookRunAs, HookRunAsRef } from './hook-run-as.js';
@@ -57,6 +62,8 @@ export interface ScopedContextHost {
5762
derive: ScopedContext['derive'];
5863
readonly engine: ScopedContext['engine'];
5964
readonly executionContext: ScopedContext['executionContext'];
65+
/** The instance itself: a moved body reads `this.facade` where the method read a bare `this` (#30020). */
66+
readonly facade: ScopedContext;
6067
readonly joinedHandles: ScopedContext['joinedHandles'];
6168
releaseJoinedHandle: ScopedContext['releaseJoinedHandle'];
6269
txDriver: ScopedContext['txDriver'];
@@ -121,6 +128,111 @@ export class ScopedContextFacet {
121128
return this.derive({ ...this.executionContext, isSystem: false });
122129
}
123130

131+
/** The body of `ScopedContext#[SEED_USER_GRANTS]`; the method's docblock there is its contract. */
132+
static async seedUserGrants(this: Pick<ScopedContextHost, 'derive' | 'engine' | 'executionContext' | 'facade'>): Promise<ScopedContext> {
133+
const ctx = this.executionContext;
134+
if (!ctx.userId) return this.facade;
135+
const needsGrants = !Array.isArray(ctx.permissions);
136+
const needsPeers = !Array.isArray(ctx.org_user_ids);
137+
const needsEmail = !ctx.email;
138+
if (!needsGrants && !needsPeers && !needsEmail) return this.facade;
139+
const grants = await resolveUserAuthzGrants(
140+
this.engine,
141+
ctx.userId,
142+
ctx.tenantId ? { tenantId: ctx.tenantId } : {},
143+
);
144+
return this.derive({
145+
...ctx,
146+
...(needsGrants ? { positions: grants.positions, permissions: grants.permissions } : {}),
147+
...(needsPeers ? { org_user_ids: grants.org_user_ids } : {}),
148+
...(needsEmail && grants.email ? { email: grants.email } : {}),
149+
});
150+
}
151+
152+
/** The body of `ScopedContext#transaction`; the method's docblock there is its contract. */
153+
static async transaction(this: Pick<ScopedContextHost, 'derive' | 'engine' | 'executionContext' | 'facade'>, callback: (trxCtx: ScopedContext, info: EngineTransactionInfo) => Promise<any>, opts?: EngineTransactionOptions): Promise<any> {
154+
const engine = this.engine as any;
155+
// The engine's ambient transaction store (ADR-0034), reached the `as any`
156+
// way this whole class reaches engine internals, for the D2 join below. A
157+
// transaction this call opens is published by the engine's own helper.
158+
const txStore = engine?.txStore as
159+
| { getStore(): { transaction: unknown } | undefined }
160+
| undefined;
161+
162+
// ADR-0067 D2 — JOIN an already-open ambient transaction instead of opening
163+
// a nested driver one (#6168). Same first move, same reasons and the same
164+
// shape as `ObjectQL.transaction`: a nested begin would take a second
165+
// connection AND would not be covered by the outer rollback, so the outer
166+
// caller would stop owning the one-and-only commit/rollback.
167+
//
168+
// BEFORE the driver/`require` handling on purpose, mirroring the engine:
169+
// when there is an ambient transaction there IS a transaction, so
170+
// `require: true` is satisfied by joining it and the degrade is not
171+
// reachable.
172+
const ambient = txStore?.getStore();
173+
if (ambient?.transaction) {
174+
// The handle is threaded EXPLICITLY into the child context, not left to
175+
// the ambient store, for the same reason the engine surface threads it:
176+
// `buildDriverOptions` prefers the explicit handle, and it survives async
177+
// boundaries the store does not. It is identity-equal to the store's
178+
// handle, so `transactionCoversDriverFor` still attributes it to the
179+
// OUTER owner and the #5351 same-origin gate judges it unchanged.
180+
const joinedCtx = this.derive({ ...this.executionContext, transaction: ambient.transaction });
181+
// JOINED, not owned: the outer caller decides commit vs rollback (#5696).
182+
return callback(joinedCtx, { owned: false });
183+
}
184+
185+
// Find the default driver for transaction support
186+
const driver = engine.defaultDriver
187+
? engine.drivers?.get(engine.defaultDriver)
188+
: undefined;
189+
190+
// [#18063] Declaration, not bare method presence — see the engine surface's
191+
// gate; one predicate serves both so they cannot answer differently.
192+
if (!driverSupportsTransactions(driver)) {
193+
const datasource = engine.defaultDriver ?? driver?.name;
194+
if (opts?.require === true) {
195+
// Same fail-closed refusal as the engine surface (#5696 point 1).
196+
throw new TransactionUnsupportedError(datasource ?? '<no default datasource>');
197+
}
198+
// No transaction support — execute directly. Declared (ADR-0119 D1), but
199+
// said out loud since #4619: the caller asked for atomicity and the
200+
// callback is about to run without any.
201+
engine.warnTransactionUnsupported?.(datasource, driver?.supports?.transactionsUnsupported === true);
202+
return callback(this.facade, { owned: false });
203+
}
204+
205+
const trx = await driver.beginTransaction();
206+
const trxCtx = this.derive({ ...this.executionContext, transaction: trx });
207+
// Publish this transaction into the engine's ambient store so internal
208+
// queries during writes reuse its connection (ADR-0034) — and so a nested
209+
// `transaction()` on either surface can JOIN it. The store entry also
210+
// carries WHICH driver owns the transaction (#4619) so the write path can
211+
// report a write routed off it. [#22855] Through the engine's ONE unit
212+
// helper, `runOpenedUnit`, the one `ObjectQL.transaction` runs its callback
213+
// in, reached the same `as any` way as `txStore` itself. It closes the unit
214+
// when the callback settles, so work the callback started and did not await
215+
// (an `async: true` hook) no longer keeps the finished handle, neither the
216+
// ambient one nor the `trxCtx` one threaded above.
217+
const runIn = <R>(fn: () => Promise<R>): Promise<R> =>
218+
typeof engine.runOpenedUnit === 'function' ? engine.runOpenedUnit(trx, driver, fn) : fn();
219+
220+
try {
221+
// Reached only with no ambient transaction to join, so this call really
222+
// did open one and the callback owns the outcome (#5696 / #6168).
223+
const result = await runIn(() => callback(trxCtx, { owned: true }));
224+
if (driver.commit) await driver.commit(trx);
225+
else if (driver.commitTransaction) await driver.commitTransaction(trx);
226+
return result;
227+
} catch (error) {
228+
if (driver.rollback) await driver.rollback(trx);
229+
else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);
230+
// [#21274] The engine surface's twin (`ObjectQL.transaction`), the
231+
// stale-roll-up conversion included.
232+
throw redactPropagatedDriverFault(rolledBackRefusal(error));
233+
}
234+
}
235+
124236
/**
125237
* Was `handle` JOINED by this context rather than opened by it? Consumes the
126238
* record, so the trio's terminal call is also what forgets the handle.

‎packages/objectql/src/engine.ts‎

Lines changed: 10 additions & 103 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import type { WriteObservabilityOptions } from '@objectstack/spec/contracts';
1919
// engine is what `metadata-protocol.validateData` returns, so letting the two
2020
// drift would put a translation layer between a verdict and its contract.
2121
import type { ValidateDataResponse } from '@objectstack/spec/api';
22-
import { parseAutonumberFormat, driverSupportsTransactions } from '@objectstack/spec/data';
22+
import { parseAutonumberFormat } from '@objectstack/spec/data';
2323
// [#5158] Door 2's lowering sink — the SAME pair the protocol face (Door 1)
2424
// runs, so `FilterArray` has exactly one lowering in the product.
2525
// [ADR-0053 D-D1, amended 2026-09-30 — #5930] The shared `FilterCondition →
@@ -141,10 +141,9 @@ import {
141141
Logger,
142142
type RetryOptions,
143143
recordNotFoundError,
144-
resolveUserAuthzGrants,
145144
} from '@objectstack/core';
146145
import { WriteEpoch } from './write-epoch.js';
147-
import { SummaryRecomputeError, cascadeStoppedRefusal, rolledBackRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
146+
import { SummaryRecomputeError, cascadeStoppedRefusal, type SummaryRecomputeFailure } from './summary-errors.js';
148147
import { TransactionUnsupportedError } from './transaction-errors.js';
149148
import {
150149
withoutDeletedSelfParents,
@@ -196,7 +195,7 @@ import { AssignmentRuleEvaluator, type AssignmentQueueService } from './assignme
196195
// [#21274] …and its boundary face — nor the error that leaves the engine.
197196
// [#21385] It lives in `@objectstack/types` now, so `driver-sql`'s own log lines
198197
// call the same cut; nothing about it changed in the move.
199-
import { redactBoundStatement, redactPropagatedDriverFault } from '@objectstack/types';
198+
import { redactBoundStatement } from '@objectstack/types';
200199
// [#8844] The runtime half of #8686's ruling: a system-context write on a
201200
// tenant-scoped object resolves the install's organization the way a session
202201
// write does, or is refused rather than filed under the `__global__`
@@ -10432,24 +10431,9 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
1043210431
* export, so it is no nameable member of this class's published face (see
1043310432
* the symbol's docblock in `hook-run-as.ts`).
1043410433
*/
10435-
async [SEED_USER_GRANTS](): Promise<ScopedContext> {
10436-
const ctx = this.executionContext;
10437-
if (!ctx.userId) return this;
10438-
const needsGrants = !Array.isArray(ctx.permissions);
10439-
const needsPeers = !Array.isArray(ctx.org_user_ids);
10440-
const needsEmail = !ctx.email;
10441-
if (!needsGrants && !needsPeers && !needsEmail) return this;
10442-
const grants = await resolveUserAuthzGrants(
10443-
this.engine,
10444-
ctx.userId,
10445-
ctx.tenantId ? { tenantId: ctx.tenantId } : {},
10446-
);
10447-
return this.derive({
10448-
...ctx,
10449-
...(needsGrants ? { positions: grants.positions, permissions: grants.permissions } : {}),
10450-
...(needsPeers ? { org_user_ids: grants.org_user_ids } : {}),
10451-
...(needsEmail && grants.email ? { email: grants.email } : {}),
10452-
});
10434+
[SEED_USER_GRANTS](): Promise<ScopedContext> {
10435+
// [#30052 codemod] The body moved to `engine-scoped-context.ts` (see `ScopedContextHost`).
10436+
return ScopedContextFacet.seedUserGrants.call(scopedContextHost.of(this));
1045310437
}
1045410438

1045510439
/**
@@ -10504,90 +10488,12 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
1050410488
* #6167 tracks, and closing that needs handle ownership to become
1050510489
* discoverable on `IDataDriver`.
1050610490
*/
10507-
async transaction(
10491+
transaction(
1050810492
callback: (trxCtx: ScopedContext, info: EngineTransactionInfo) => Promise<any>,
1050910493
opts?: EngineTransactionOptions,
1051010494
): Promise<any> {
10511-
const engine = this.engine as any;
10512-
// The engine's ambient transaction store (ADR-0034), reached the `as any`
10513-
// way this whole class reaches engine internals, for the D2 join below. A
10514-
// transaction this call opens is published by the engine's own helper.
10515-
const txStore = engine?.txStore as
10516-
| { getStore(): { transaction: unknown } | undefined }
10517-
| undefined;
10518-
10519-
// ADR-0067 D2 — JOIN an already-open ambient transaction instead of opening
10520-
// a nested driver one (#6168). Same first move, same reasons and the same
10521-
// shape as `ObjectQL.transaction`: a nested begin would take a second
10522-
// connection AND would not be covered by the outer rollback, so the outer
10523-
// caller would stop owning the one-and-only commit/rollback.
10524-
//
10525-
// BEFORE the driver/`require` handling on purpose, mirroring the engine:
10526-
// when there is an ambient transaction there IS a transaction, so
10527-
// `require: true` is satisfied by joining it and the degrade is not
10528-
// reachable.
10529-
const ambient = txStore?.getStore();
10530-
if (ambient?.transaction) {
10531-
// The handle is threaded EXPLICITLY into the child context, not left to
10532-
// the ambient store, for the same reason the engine surface threads it:
10533-
// `buildDriverOptions` prefers the explicit handle, and it survives async
10534-
// boundaries the store does not. It is identity-equal to the store's
10535-
// handle, so `transactionCoversDriverFor` still attributes it to the
10536-
// OUTER owner and the #5351 same-origin gate judges it unchanged.
10537-
const joinedCtx = this.derive({ ...this.executionContext, transaction: ambient.transaction });
10538-
// JOINED, not owned: the outer caller decides commit vs rollback (#5696).
10539-
return callback(joinedCtx, { owned: false });
10540-
}
10541-
10542-
// Find the default driver for transaction support
10543-
const driver = engine.defaultDriver
10544-
? engine.drivers?.get(engine.defaultDriver)
10545-
: undefined;
10546-
10547-
// [#18063] Declaration, not bare method presence — see the engine surface's
10548-
// gate; one predicate serves both so they cannot answer differently.
10549-
if (!driverSupportsTransactions(driver)) {
10550-
const datasource = engine.defaultDriver ?? driver?.name;
10551-
if (opts?.require === true) {
10552-
// Same fail-closed refusal as the engine surface (#5696 point 1).
10553-
throw new TransactionUnsupportedError(datasource ?? '<no default datasource>');
10554-
}
10555-
// No transaction support — execute directly. Declared (ADR-0119 D1), but
10556-
// said out loud since #4619: the caller asked for atomicity and the
10557-
// callback is about to run without any.
10558-
engine.warnTransactionUnsupported?.(datasource, driver?.supports?.transactionsUnsupported === true);
10559-
return callback(this, { owned: false });
10560-
}
10561-
10562-
const trx = await driver.beginTransaction();
10563-
const trxCtx = this.derive({ ...this.executionContext, transaction: trx });
10564-
// Publish this transaction into the engine's ambient store so internal
10565-
// queries during writes reuse its connection (ADR-0034) — and so a nested
10566-
// `transaction()` on either surface can JOIN it. The store entry also
10567-
// carries WHICH driver owns the transaction (#4619) so the write path can
10568-
// report a write routed off it. [#22855] Through the engine's ONE unit
10569-
// helper, `runOpenedUnit`, the one `ObjectQL.transaction` runs its callback
10570-
// in, reached the same `as any` way as `txStore` itself. It closes the unit
10571-
// when the callback settles, so work the callback started and did not await
10572-
// (an `async: true` hook) no longer keeps the finished handle, neither the
10573-
// ambient one nor the `trxCtx` one threaded above.
10574-
const runIn = <R>(fn: () => Promise<R>): Promise<R> =>
10575-
typeof engine.runOpenedUnit === 'function' ? engine.runOpenedUnit(trx, driver, fn) : fn();
10576-
10577-
try {
10578-
// Reached only with no ambient transaction to join, so this call really
10579-
// did open one and the callback owns the outcome (#5696 / #6168).
10580-
const result = await runIn(() => callback(trxCtx, { owned: true }));
10581-
if (driver.commit) await driver.commit(trx);
10582-
else if (driver.commitTransaction) await driver.commitTransaction(trx);
10583-
return result;
10584-
} catch (error) {
10585-
if (driver.rollback) await driver.rollback(trx);
10586-
else if (driver.rollbackTransaction) await driver.rollbackTransaction(trx);
10587-
// [#21274] The engine surface's twin (`ObjectQL.transaction`), the
10588-
// stale-roll-up conversion included.
10589-
throw redactPropagatedDriverFault(rolledBackRefusal(error));
10590-
}
10495+
// [#30052 codemod] The body moved to `engine-scoped-context.ts` (see `ScopedContextHost`).
10496+
return ScopedContextFacet.transaction.call(scopedContextHost.of(this), callback, opts);
1059110497
}
1059210498

1059310499
/**
@@ -10732,6 +10638,7 @@ export class ScopedContext implements IScopedContext, RunAsDerivableApi {
1073210638
derive: (...a) => instance.derive(...a),
1073310639
get engine() { return instance.engine; },
1073410640
get executionContext() { return instance.executionContext; },
10641+
facade: instance,
1073510642
get joinedHandles() { return instance.joinedHandles; },
1073610643
releaseJoinedHandle: (...a) => instance.releaseJoinedHandle(...a),
1073710644
txDriver: (...a) => instance.txDriver(...a),

0 commit comments

Comments
 (0)