|
| 1 | +// Copyright (c) 2026 ObjectStack. Licensed under the Apache-2.0 license. |
| 2 | + |
| 3 | +/** |
| 4 | + * [#25522 cut 7] The raw-command and transaction-routing bodies of `ObjectQL`, |
| 5 | + * moved out of `engine.ts` whole: `execute` (the driver a raw command goes to, |
| 6 | + * its two call shapes, and the redaction of a driver fault it propagates), |
| 7 | + * `warnTransactionUnsupported` (the once-per-driver report of ADR-0119's |
| 8 | + * declared degrade) and `enforceTransactionOrigin` (what a write routed to a |
| 9 | + * driver the open transaction does not cover gets: refused, or, for an |
| 10 | + * append-only system ledger under ADR-0057, executed outside it). |
| 11 | + * |
| 12 | + * A MOVE, not a redesign. Each exported function below is the body of the |
| 13 | + * `ObjectQL` method of the same name as it stood, re-indented one level and |
| 14 | + * otherwise unedited: the same driver-selection order, the same two refusals |
| 15 | + * before any command is sent, the same once-per-name warning and its two |
| 16 | + * causes, the same refusal before hooks run and the same once-per-transaction |
| 17 | + * debug line. Each method's docblock stays on the method in `engine.ts`, which |
| 18 | + * is still the contract. |
| 19 | + * |
| 20 | + * What stays in the class: `transaction`, because ADR-0119 cites it by |
| 21 | + * `engine.ts#transaction` and ADR-0067's join lives in it; `runOpenedUnit`, |
| 22 | + * `isClosedUnitHandle`, `newTransactionScope` and `datasourceNameOf`, whose |
| 23 | + * bodies are shorter than the host literal moving them would cost. |
| 24 | + * |
| 25 | + * ## How the moved bodies reach the class |
| 26 | + * |
| 27 | + * The shape #23050 set for `rest-server.ts` (its `data-action-routes.ts` |
| 28 | + * header carries the full reasoning), applied per method as |
| 29 | + * `engine-hook-dispatch.ts` applies it. The class keeps all three methods — |
| 30 | + * the published `.d.ts` lists each one's name and position, and `execute` is |
| 31 | + * public — and each body is one literal of exactly the |
| 32 | + * {@link ExecuteTransactionsHost} members that method reads, plus a `.call`. |
| 33 | + * The fields the bodies read (`drivers`, `defaultDriver`, `txStore`, |
| 34 | + * `transactionUnsupportedReported`, `logger`) go as GETTERS, so each read |
| 35 | + * happens when the body makes it: `registerDriver` changes the driver map and |
| 36 | + * the default, and a body sees whatever is installed at the moment it reads, |
| 37 | + * as it did. The methods they call (`getDriver`, `datasourceNameOf`, |
| 38 | + * `isSystemLedgerObject`) go as late-bound closures over the instance, so a |
| 39 | + * double or spy set on the engine is still the one a call reaches. |
| 40 | + * |
| 41 | + * This module imports the engine only as a TYPE, so there is no module cycle |
| 42 | + * at run time, and nothing re-exports it, so the published surface does not |
| 43 | + * move. |
| 44 | + */ |
| 45 | + |
| 46 | +import type { IDataDriver } from '@objectstack/core'; |
| 47 | +import { redactPropagatedDriverFault } from '@objectstack/types'; |
| 48 | +import { CrossDatasourceTransactionWriteError } from './transaction-errors.js'; |
| 49 | +import type { ObjectQL } from './engine.js'; |
| 50 | + |
| 51 | +/** |
| 52 | + * The `ObjectQL` members the functions below read — every one of them, and no |
| 53 | + * other; each function's `this` is the `Pick` of the members IT reads. Each is |
| 54 | + * typed AS the class member (an indexed access on the class), so a change to a |
| 55 | + * member's type on the class is a change here too, and naming a member the |
| 56 | + * class does not have is a compile error. See the module header for which |
| 57 | + * members are getters. |
| 58 | + */ |
| 59 | +export interface ExecuteTransactionsHost { |
| 60 | + readonly drivers: ObjectQL['drivers']; |
| 61 | + readonly defaultDriver: ObjectQL['defaultDriver']; |
| 62 | + readonly txStore: ObjectQL['txStore']; |
| 63 | + readonly transactionUnsupportedReported: ObjectQL['transactionUnsupportedReported']; |
| 64 | + readonly logger: ObjectQL['logger']; |
| 65 | + getDriver: ObjectQL['getDriver']; |
| 66 | + datasourceNameOf: ObjectQL['datasourceNameOf']; |
| 67 | + isSystemLedgerObject: ObjectQL['isSystemLedgerObject']; |
| 68 | +} |
| 69 | + |
| 70 | +/** The body of `ObjectQL#execute`; the method's docblock there is its contract. */ |
| 71 | +export async function execute( |
| 72 | + this: Pick<ExecuteTransactionsHost, 'getDriver' | 'drivers' | 'defaultDriver'>, |
| 73 | + command: any, |
| 74 | + options?: Record<string, any>, |
| 75 | +): Promise<any> { |
| 76 | + // Driver selection priority: |
| 77 | + // 1. options.object → route via getDriver(objectName) |
| 78 | + // 2. options.datasource → explicit driver name |
| 79 | + // 3. default driver (set via datasourceMapping or defaultDriver) |
| 80 | + // This lets system services (e.g. PackageService, AuditService) issue raw |
| 81 | + // SQL against the control-plane / default DB without having to know the |
| 82 | + // object name behind every CREATE TABLE / SELECT statement. |
| 83 | + let driver: IDataDriver | undefined; |
| 84 | + if (options?.object) { |
| 85 | + driver = this.getDriver(options.object); |
| 86 | + } else if (options?.datasource && this.drivers.has(options.datasource)) { |
| 87 | + driver = this.drivers.get(options.datasource); |
| 88 | + } else if (this.defaultDriver && this.drivers.has(this.defaultDriver)) { |
| 89 | + driver = this.drivers.get(this.defaultDriver); |
| 90 | + } else if (this.drivers.size === 1) { |
| 91 | + // Single registered driver — unambiguously the right one. |
| 92 | + driver = this.drivers.values().next().value; |
| 93 | + } |
| 94 | + |
| 95 | + if (!driver) { |
| 96 | + throw new Error( |
| 97 | + 'Execute requires options.object to select a driver, or a default driver to be configured. ' + |
| 98 | + 'Configure datasourceMapping with `default: true` or pass `{ object }` / `{ datasource }` in options.', |
| 99 | + ); |
| 100 | + } |
| 101 | + if (!driver.execute) { |
| 102 | + throw new Error('Selected driver does not implement execute()'); |
| 103 | + } |
| 104 | + |
| 105 | + // Support both call shapes: |
| 106 | + // execute('SELECT ...', { args: [...] }) |
| 107 | + // execute({ sql: 'SELECT ...', args: [...] }) |
| 108 | + let rawCommand: any = command; |
| 109 | + let params: any[] | undefined = options?.args ?? options?.params; |
| 110 | + if (command && typeof command === 'object' && !Array.isArray(command) && 'sql' in command) { |
| 111 | + rawCommand = command.sql; |
| 112 | + if (params === undefined) { |
| 113 | + params = command.args ?? command.params; |
| 114 | + } |
| 115 | + } |
| 116 | + |
| 117 | + // [#21274] A boundary outside the middleware seam: the raw command's |
| 118 | + // bound `params` are the caller's values, and the driver's refusal |
| 119 | + // carries the dialect error on its `cause`. |
| 120 | + // |
| 121 | + // [#21345] And the one door whose statement the engine did not compose: |
| 122 | + // it may open with a word the shared leak predicate does not list (a |
| 123 | + // common-table-expression form, a dialect's upsert or merge verb), so |
| 124 | + // the cut must not wait for the predicate to recognise it. The door |
| 125 | + // knows it sent a statement, and says so. |
| 126 | + try { |
| 127 | + return await driver.execute(rawCommand, params, options); |
| 128 | + } catch (e) { |
| 129 | + throw redactPropagatedDriverFault(e, { statementSent: true }); |
| 130 | + } |
| 131 | +} |
| 132 | + |
| 133 | +/** The body of `ObjectQL#warnTransactionUnsupported`; the method's docblock there is its contract. */ |
| 134 | +export function warnTransactionUnsupported( |
| 135 | + this: Pick<ExecuteTransactionsHost, 'transactionUnsupportedReported' | 'logger'>, |
| 136 | + datasource: string | undefined, |
| 137 | + declaredUnsupported = false, |
| 138 | +): void { |
| 139 | + const name = datasource ?? '<no default datasource>'; |
| 140 | + if (this.transactionUnsupportedReported.has(name)) return; |
| 141 | + this.transactionUnsupportedReported.add(name); |
| 142 | + // [#18063] The two reasons reach the same degrade and must not read the |
| 143 | + // same. Telling an operator a Turso REMOTE datasource "has no |
| 144 | + // beginTransaction" sends them looking for a missing method on a class that |
| 145 | + // publishes one; the fix for that reason is a different transport, not a |
| 146 | + // different driver. |
| 147 | + const cause = declaredUnsupported |
| 148 | + ? `driver '${name}' declares supports.transactionsUnsupported — its transport cannot carry a ` + |
| 149 | + 'transaction handle even though it inherits beginTransaction' |
| 150 | + : `driver '${name}' has no beginTransaction`; |
| 151 | + const remedy = declaredUnsupported |
| 152 | + ? 'Point this datasource at a transport that honours transactions (for libSQL: the local or ' + |
| 153 | + 'embedded-replica mode rather than the remote one), or have the caller fail ' |
| 154 | + : 'Register a driver that implements beginTransaction for this datasource, or have the caller fail '; |
| 155 | + this.logger.warn( |
| 156 | + `transaction() requested a transaction but ${cause} — ` + |
| 157 | + 'running WITHOUT transaction or rollback. Every write the callback makes commits as it executes, ' + |
| 158 | + 'so a later throw leaves the earlier ones PERSISTED even though the call rejects as if the whole ' + |
| 159 | + 'unit of work had been undone; no caller is told, and the records stay behind. ' + |
| 160 | + remedy + |
| 161 | + "closed itself when it cannot tolerate losing atomicity (batchData's atomic gate, ADR-0119 D4, is " + |
| 162 | + 'the pattern). Reported once per driver per engine instance.', |
| 163 | + { datasource: name, declaredUnsupported }, |
| 164 | + ); |
| 165 | +} |
| 166 | + |
| 167 | +/** The body of `ObjectQL#enforceTransactionOrigin`; the method's docblock there is its contract. */ |
| 168 | +export function enforceTransactionOrigin( |
| 169 | + this: Pick<ExecuteTransactionsHost, 'txStore' | 'datasourceNameOf' | 'isSystemLedgerObject' | 'logger'>, |
| 170 | + objectName: string, |
| 171 | + driver: IDataDriver, |
| 172 | + operation: 'insert' | 'update' | 'delete', |
| 173 | +): void { |
| 174 | + const scope = this.txStore.getStore()?.scope; |
| 175 | + // No engine-owned transaction in scope (or a handle threaded explicitly by |
| 176 | + // the sandbox trio, which this store never sees) — nothing to be outside |
| 177 | + // of. See `transactionCoversDriverFor` for why that limit is declared. |
| 178 | + if (!scope) return; |
| 179 | + // Identity, not name: this is about riding the same connection. |
| 180 | + if (driver === scope.driver) return; |
| 181 | + const target = this.datasourceNameOf(driver); |
| 182 | + |
| 183 | + if (!this.isSystemLedgerObject(objectName)) { |
| 184 | + throw new CrossDatasourceTransactionWriteError(objectName, operation, target, scope.datasource); |
| 185 | + } |
| 186 | + |
| 187 | + if (scope.reportedOutOfScope.has(target)) return; |
| 188 | + scope.reportedOutOfScope.add(target); |
| 189 | + this.logger.debug( |
| 190 | + `${operation} of '${objectName}' inside transaction() is routed to datasource '${target}' while the ` + |
| 191 | + `transaction is open on '${scope.datasource}' — executing it OUTSIDE the transaction, on its own ` + |
| 192 | + 'connection (ADR-0057 §3.6 system ledger — the one class carved out of the cross-datasource write ' + |
| 193 | + 'refusal). It commits independently and will ' + |
| 194 | + 'SURVIVE a rollback of this transaction: an audit/telemetry/event row may describe a write that was ' + |
| 195 | + 'undone. That is the decided direction of error for an append-only ledger — an extra reconcilable ' + |
| 196 | + 'row beats a missing row for a write that did commit. Said once per transaction per datasource.', |
| 197 | + { object: objectName, operation, datasource: target, transactionDatasource: scope.datasource }, |
| 198 | + ); |
| 199 | +} |
0 commit comments