@vibeorm/runtime 2.0.1 → 2.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -55,6 +55,8 @@ const adapter: DatabaseAdapter = {
55
55
 
56
56
  `toSqlExecutor({ adapter })` bridges an adapter to the `SqlExecutor` shape `@vibeorm/migrate` runs on.
57
57
 
58
+ `@vibeorm/runtime/adapter-kit` carries the transaction helpers every shipped adapter is built on, so a custom adapter does not re-implement them: savepoint naming (`createSavepointCounter`), the savepoint lifetime gate that serialises overlapping sibling `transaction()` calls on one connection (`createSavepointScope`, `runRootScope`, `runNestedSavepoint`, `scopeTurn`), and the transaction budget behind `TransactionOptions.deadline` (`validateTransactionDeadline`, `startTransactionBudget`, `engineStatementBudgetMs` and the typed refusals). The shipped adapters re-export them unchanged.
59
+
58
60
  ## Relation strategies
59
61
 
60
62
  ```ts
@@ -0,0 +1,20 @@
1
+ /**
2
+ * @vibeorm/runtime/adapter-kit — the transaction-safety helpers every driver
3
+ * adapter shares: savepoint naming, the savepoint lifetime gate (F14) and the
4
+ * transaction budget (EPIC 6).
5
+ *
6
+ * ONE copy. Each adapter imports from this subpath and re-exports the helpers
7
+ * it always offered, so a fix to the gate or the budget reaches every engine
8
+ * in the same change instead of six hand-synchronised files.
9
+ *
10
+ * Nothing here renders SQL or knows a driver: the gate runs the savepoint
11
+ * control statements through an `execute` the adapter injects, and the budget
12
+ * is a clock plus typed refusals.
13
+ */
14
+ export { createSavepointCounter, nextSavepointName } from "./savepoints.ts";
15
+ export type { SavepointCounter } from "./savepoints.ts";
16
+ export { createSavepointScope, runNestedSavepoint, runRootScope, scopeTurn } from "./savepoint-gate.ts";
17
+ export type { SavepointScope, SavepointState } from "./savepoint-gate.ts";
18
+ export { DEFAULT_DEADLINE_CLOCK, engineStatementBudgetMs, isTransactionDeadlineError, startTransactionBudget, transactionClosedError, transactionDeadlineError, transactionOutcomeUnknownError, validateTransactionDeadline, } from "./transaction-budget.ts";
19
+ export type { BudgetStage, DeadlineClock, TransactionBudget, TransactionOutcome } from "./transaction-budget.ts";
20
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/adapter-kit/index.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AAEH,OAAO,EAAE,sBAAsB,EAAE,iBAAiB,EAAE,MAAM,iBAAiB,CAAC;AAC5E,YAAY,EAAE,gBAAgB,EAAE,MAAM,iBAAiB,CAAC;AAExD,OAAO,EAAE,oBAAoB,EAAE,kBAAkB,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAC;AACxG,YAAY,EAAE,cAAc,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAE1E,OAAO,EACL,sBAAsB,EACtB,uBAAuB,EACvB,0BAA0B,EAC1B,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,EACxB,8BAA8B,EAC9B,2BAA2B,GAC5B,MAAM,yBAAyB,CAAC;AACjC,YAAY,EAAE,WAAW,EAAE,aAAa,EAAE,iBAAiB,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC"}
@@ -0,0 +1,247 @@
1
+ // @bun
2
+ // packages/runtime/src/adapter-kit/savepoints.ts
3
+ function createSavepointCounter() {
4
+ return { n: 0 };
5
+ }
6
+ function nextSavepointName(params) {
7
+ return `vibeorm_sp_${params.counter.n++}`;
8
+ }
9
+ // packages/runtime/src/adapter-kit/savepoint-gate.ts
10
+ import { AsyncLocalStorage } from "async_hooks";
11
+ var CURRENT = new AsyncLocalStorage;
12
+ function createSavepointScope() {
13
+ return { depth: 0, state: { counter: createSavepointCounter(), open: null } };
14
+ }
15
+ function runRootScope(params) {
16
+ return CURRENT.run(params.scope, params.body);
17
+ }
18
+ function scopeTurn(params) {
19
+ const open = params.scope.state.open;
20
+ if (mayProceed({ scope: params.scope, open }))
21
+ return;
22
+ return waitForTurn({ scope: params.scope });
23
+ }
24
+ async function runNestedSavepoint(params) {
25
+ const { scope, execute, body } = params;
26
+ const node = await acquire({ scope });
27
+ try {
28
+ if (execute !== undefined)
29
+ await execute(`SAVEPOINT ${node.name}`);
30
+ let result;
31
+ try {
32
+ result = await CURRENT.run(node.scope, () => body(node.scope));
33
+ } catch (error) {
34
+ await drainDescendants({ node });
35
+ if (execute !== undefined) {
36
+ try {
37
+ await execute(`ROLLBACK TO SAVEPOINT ${node.name}`);
38
+ } catch {}
39
+ }
40
+ throw error;
41
+ }
42
+ await drainDescendants({ node });
43
+ if (execute !== undefined)
44
+ await execute(`RELEASE SAVEPOINT ${node.name}`);
45
+ return result;
46
+ } finally {
47
+ closeNode({ node });
48
+ }
49
+ }
50
+ function mayProceed(params) {
51
+ const { scope, open } = params;
52
+ if (open === null)
53
+ return true;
54
+ if (open.scope === scope)
55
+ return true;
56
+ if (open.scope.depth < scope.depth)
57
+ return true;
58
+ return CURRENT.getStore() === open.scope;
59
+ }
60
+ async function waitForTurn(params) {
61
+ for (;; ) {
62
+ const open = params.scope.state.open;
63
+ if (open === null || mayProceed({ scope: params.scope, open }))
64
+ return;
65
+ await open.settled;
66
+ }
67
+ }
68
+ async function acquire(params) {
69
+ const { scope } = params;
70
+ for (;; ) {
71
+ const open = scope.state.open;
72
+ if (mayProceed({ scope, open }))
73
+ return pushNode({ scope, parent: open });
74
+ await open.settled;
75
+ }
76
+ }
77
+ function pushNode(params) {
78
+ const { scope, parent } = params;
79
+ const state = scope.state;
80
+ let settle = () => {
81
+ return;
82
+ };
83
+ const settled = new Promise((resolve) => {
84
+ settle = () => resolve();
85
+ });
86
+ const node = {
87
+ scope: { depth: (parent === null ? 0 : parent.scope.depth) + 1, state },
88
+ name: nextSavepointName({ counter: state.counter }),
89
+ parent,
90
+ settled,
91
+ settle
92
+ };
93
+ state.open = node;
94
+ return node;
95
+ }
96
+ function closeNode(params) {
97
+ const { node } = params;
98
+ const state = node.scope.state;
99
+ if (state.open === node)
100
+ state.open = node.parent;
101
+ node.settle();
102
+ }
103
+ async function drainDescendants(params) {
104
+ const state = params.node.scope.state;
105
+ for (;; ) {
106
+ const open = state.open;
107
+ if (open === null || open === params.node || open.scope.depth <= params.node.scope.depth)
108
+ return;
109
+ await open.settled;
110
+ }
111
+ }
112
+ // packages/runtime/src/adapter-kit/transaction-budget.ts
113
+ import { VibeError } from "@vibeorm/schema";
114
+ var DEFAULT_DEADLINE_CLOCK = () => Date.now();
115
+ function validateTransactionDeadline(params) {
116
+ const { options, support, provider } = params;
117
+ const deadline = options?.deadline;
118
+ if (deadline === undefined)
119
+ return;
120
+ if (support === "unsupported") {
121
+ throw new VibeError({
122
+ code: "VIBE_UNSUPPORTED_CAPABILITY",
123
+ message: `${provider} cannot enforce a transaction deadline \u2014 remove the \`deadline\` option`,
124
+ meta: { provider, feature: "transactionDeadline", supported: support }
125
+ });
126
+ }
127
+ if (!Number.isInteger(deadline.totalMs) || deadline.totalMs <= 0) {
128
+ throw new VibeError({
129
+ code: "VIBE_VALIDATION",
130
+ message: `transaction deadline \`totalMs\` must be a positive integer of milliseconds, received ${String(deadline.totalMs)}`,
131
+ meta: { provider, feature: "transactionDeadline", totalMs: deadline.totalMs }
132
+ });
133
+ }
134
+ const requested = deadline.enforcement ?? "between-statements";
135
+ if (requested === "cancel-running-statements" && support !== "cancel-running-statements") {
136
+ throw new VibeError({
137
+ code: "VIBE_UNSUPPORTED_CAPABILITY",
138
+ message: `${provider} cannot cancel a statement that is already running, so the requested ` + "`cancel-running-statements` deadline guarantee is refused rather than silently downgraded \u2014 " + 'ask for "between-statements" if a budget checked between statements is enough',
139
+ meta: { provider, feature: "transactionDeadline", requested, supported: support }
140
+ });
141
+ }
142
+ }
143
+ function startTransactionBudget(params) {
144
+ const { options, provider } = params;
145
+ const clock = params.clock ?? DEFAULT_DEADLINE_CLOCK;
146
+ const deadline = options?.deadline;
147
+ const totalMs = deadline === undefined ? null : deadline.totalMs;
148
+ const enforcement = deadline === undefined ? null : deadline.enforcement ?? "between-statements";
149
+ const expiresAt = totalMs === null ? null : clock() + totalMs;
150
+ let outcome = null;
151
+ const budget = {
152
+ enforcement,
153
+ totalMs,
154
+ statementTimeoutMs: options?.timeout ?? null,
155
+ remainingMs() {
156
+ return expiresAt === null ? null : Math.max(0, expiresAt - clock());
157
+ },
158
+ expired() {
159
+ return expiresAt !== null && clock() >= expiresAt;
160
+ },
161
+ assertUsable(assertParams) {
162
+ if (outcome !== null) {
163
+ throw transactionClosedError({ provider, outcome, stage: assertParams.stage });
164
+ }
165
+ if (expiresAt !== null && clock() >= expiresAt) {
166
+ throw transactionDeadlineError({
167
+ provider,
168
+ stage: assertParams.stage,
169
+ totalMs,
170
+ overdueMs: clock() - expiresAt
171
+ });
172
+ }
173
+ },
174
+ close(closeParams) {
175
+ if (outcome === null)
176
+ outcome = closeParams.outcome;
177
+ },
178
+ get outcome() {
179
+ return outcome;
180
+ }
181
+ };
182
+ return budget;
183
+ }
184
+ function engineStatementBudgetMs(params) {
185
+ const { budget } = params;
186
+ if (budget.enforcement !== "cancel-running-statements")
187
+ return null;
188
+ const remaining = budget.remainingMs();
189
+ if (remaining === null)
190
+ return null;
191
+ const totalBound = Math.max(1, Math.ceil(remaining));
192
+ return budget.statementTimeoutMs !== null && budget.statementTimeoutMs > 0 ? Math.min(totalBound, budget.statementTimeoutMs) : totalBound;
193
+ }
194
+ function transactionDeadlineError(params) {
195
+ const { provider, stage, totalMs, overdueMs } = params;
196
+ const what = stage === "commit" ? "the transaction was rolled back instead of committed" : "the statement was never sent and the transaction is being rolled back";
197
+ return new VibeError({
198
+ code: "VIBE_TRANSACTION",
199
+ message: `transaction deadline of ${totalMs} ms expired ${Math.max(0, Math.round(overdueMs))} ms ago \u2014 ${what}. ` + "Nothing is retried automatically: work the callback did outside the database may already have happened.",
200
+ meta: { provider, reason: "transaction-deadline", stage, totalMs, overdueMs: Math.max(0, Math.round(overdueMs)) }
201
+ });
202
+ }
203
+ function transactionClosedError(params) {
204
+ const { provider, outcome, stage } = params;
205
+ return new VibeError({
206
+ code: "VIBE_TRANSACTION",
207
+ message: `this transaction has already finished (${outcome}), so its client can no longer be used \u2014 ` + "a handle kept past the end of `$transaction` would run outside the transaction, on a connection " + "that now belongs to someone else",
208
+ meta: { provider, reason: "transaction-closed", outcome, stage }
209
+ });
210
+ }
211
+ function transactionOutcomeUnknownError(params) {
212
+ const { provider, totalMs, cause } = params;
213
+ return new VibeError({
214
+ code: "VIBE_TRANSACTION",
215
+ message: `transaction deadline of ${totalMs} ms expired and the rollback that should have cleaned up failed \u2014 ` + "the commit state of this transaction is UNKNOWN. It is not retried automatically; inspect the data " + "before deciding.",
216
+ meta: {
217
+ provider,
218
+ reason: "transaction-outcome-unknown",
219
+ outcome: "unknown",
220
+ totalMs,
221
+ rollbackFailed: true
222
+ },
223
+ cause
224
+ });
225
+ }
226
+ function isTransactionDeadlineError(error) {
227
+ const reason = error?.meta?.reason;
228
+ return reason === "transaction-deadline";
229
+ }
230
+ export {
231
+ validateTransactionDeadline,
232
+ transactionOutcomeUnknownError,
233
+ transactionDeadlineError,
234
+ transactionClosedError,
235
+ startTransactionBudget,
236
+ scopeTurn,
237
+ runRootScope,
238
+ runNestedSavepoint,
239
+ nextSavepointName,
240
+ isTransactionDeadlineError,
241
+ engineStatementBudgetMs,
242
+ createSavepointScope,
243
+ createSavepointCounter,
244
+ DEFAULT_DEADLINE_CLOCK
245
+ };
246
+
247
+ //# debugId=90A5C246EB2BA1E264756E2164756E21
@@ -0,0 +1,12 @@
1
+ {
2
+ "version": 3,
3
+ "sources": ["../src/adapter-kit/savepoints.ts", "../src/adapter-kit/savepoint-gate.ts", "../src/adapter-kit/transaction-budget.ts"],
4
+ "sourcesContent": [
5
+ "/**\n * Savepoint naming for nested transactions.\n *\n * v1 lesson (LEARNINGS.md): the counter is shared **by reference** across every\n * adapter created for one top-level transaction, so sibling and deeply nested\n * savepoints can never collide on a name.\n */\n\n/** Mutable counter shared by reference across one top-level transaction. */\nexport type SavepointCounter = { n: number };\n\n/** Fresh counter — one per top-level transaction. */\nexport function createSavepointCounter(): SavepointCounter {\n return { n: 0 };\n}\n\n/**\n * Allocate the next savepoint name (`vibeorm_sp_0`, `vibeorm_sp_1`, …) and\n * advance the shared counter. The name is an identifier by construction, so it\n * is safe to interpolate into `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` SQL.\n */\nexport function nextSavepointName(params: { counter: SavepointCounter }): string {\n return `vibeorm_sp_${params.counter.n++}`;\n}\n",
6
+ "/**\n * Savepoint lifetimes inside one top-level transaction (F14).\n *\n * A savepoint stack lives on ONE connection: `ROLLBACK TO SAVEPOINT s` undoes\n * everything done after `s`, including work a LATER savepoint already released.\n * Two `transaction()` callbacks opened from the same handle and overlapping in\n * time therefore share that one stack, and the earlier one's rollback silently\n * erases the later one's already committed work. Unique savepoint names do not\n * help — the names never collided, the lifetimes did.\n *\n * The rule enforced here, on every handle of a transaction:\n *\n * > A handle runs when nothing deeper than itself is open. Otherwise it waits\n * > for the innermost open savepoint to settle — unless the call is being made\n * > from INSIDE that savepoint's own callback, which is genuine nesting and\n * > proceeds immediately.\n *\n * The \"from inside\" test is an {@link AsyncLocalStorage} lookup, so the common\n * nesting shapes never wait on themselves: a child opened from its parent's\n * callback, and the parent handle used from within an open child's callback,\n * both proceed. Only genuinely concurrent siblings serialize.\n *\n * Not covered: a callback that awaits a sibling it did not start. That\n * arrangement asks for two savepoints to be open at once, which is exactly what\n * loses work; it now blocks instead. Deliberate — see the notes for this fix.\n */\n\nimport { AsyncLocalStorage } from \"node:async_hooks\";\nimport { type SavepointCounter, createSavepointCounter, nextSavepointName } from \"./savepoints.ts\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/**\n * One handle's position in the savepoint stack of a top-level transaction.\n * `state` is shared by reference across every handle of that transaction.\n */\nexport type SavepointScope = {\n /** Physical savepoint depth; 0 is the top-level transaction itself. */\n readonly depth: number;\n /** Shared state: name allocation plus the innermost open savepoint. */\n readonly state: SavepointState;\n};\n\n/** Mutable state shared by every scope of one top-level transaction. */\nexport type SavepointState = {\n /** Savepoint name counter (shared, so names never collide). */\n readonly counter: SavepointCounter;\n /** The innermost savepoint currently open, or `null` when none is. */\n open: OpenSavepoint | null;\n};\n\n/** An open savepoint: its handle, its name, and when it finished. */\ntype OpenSavepoint = {\n readonly scope: SavepointScope;\n readonly name: string;\n readonly parent: OpenSavepoint | null;\n readonly settled: Promise<void>;\n readonly settle: () => void;\n};\n\n/**\n * The savepoint whose callback the current async context is running inside.\n * This is the discriminator between genuine nesting (proceed) and an\n * overlapping sibling (wait).\n */\nconst CURRENT = new AsyncLocalStorage<SavepointScope>();\n\n// ─── Public API ───────────────────────────────────────────────────\n\n/** Fresh scope for one top-level transaction: depth 0, nothing open. */\nexport function createSavepointScope(): SavepointScope {\n return { depth: 0, state: { counter: createSavepointCounter(), open: null } };\n}\n\n/**\n * Run a top-level transaction callback inside its scope's async context, so\n * nested calls made from it can be told apart from calls made inside an open\n * child.\n */\nexport function runRootScope<T>(params: { scope: SavepointScope; body: () => Promise<T> }): Promise<T> {\n return CURRENT.run(params.scope, params.body);\n}\n\n/**\n * The wait a statement on `scope` owes before it may run, or `undefined` when\n * it may run now. Returning `undefined` keeps the uncontended path — nothing\n * deeper open — free of an extra promise and microtask.\n */\nexport function scopeTurn(params: { scope: SavepointScope }): Promise<void> | undefined {\n const open = params.scope.state.open;\n if (mayProceed({ scope: params.scope, open })) return undefined;\n return waitForTurn({ scope: params.scope });\n}\n\n/**\n * Open a nested savepoint under `scope`, run `body` inside it and release it —\n * rolling back to it if `body` throws, exactly as before this gate existed.\n *\n * `execute` runs the savepoint control SQL (already wrapped in the adapter's\n * own driver-error mapping). Omit it when the driver manages the savepoint\n * itself (bun:sql's `savepoint()`), in which case only the lifetime is gated.\n */\nexport async function runNestedSavepoint<T>(params: {\n readonly scope: SavepointScope;\n readonly execute?: (statement: string) => Promise<unknown> | unknown;\n readonly body: (scope: SavepointScope) => Promise<T>;\n}): Promise<T> {\n const { scope, execute, body } = params;\n const node = await acquire({ scope });\n try {\n if (execute !== undefined) await execute(`SAVEPOINT ${node.name}`);\n let result: T;\n try {\n result = await CURRENT.run(node.scope, () => body(node.scope));\n } catch (error) {\n // A descendant the callback started but never awaited must finish before\n // this savepoint may be rolled back — releasing out of order corrupts\n // the stack.\n await drainDescendants({ node });\n if (execute !== undefined) {\n // Best effort: never mask the original failure with a rollback failure.\n try {\n await execute(`ROLLBACK TO SAVEPOINT ${node.name}`);\n } catch {\n /* rollback is best-effort */\n }\n }\n throw error;\n }\n await drainDescendants({ node });\n if (execute !== undefined) await execute(`RELEASE SAVEPOINT ${node.name}`);\n return result;\n } finally {\n closeNode({ node });\n }\n}\n\n// ─── Internals ────────────────────────────────────────────────────\n\n/** Whether `scope` may act while `open` is the innermost open savepoint. */\nfunction mayProceed(params: { scope: SavepointScope; open: OpenSavepoint | null }): boolean {\n const { scope, open } = params;\n if (open === null) return true;\n // This handle IS the innermost open savepoint.\n if (open.scope === scope) return true;\n // This handle's own savepoint has already closed (a retained child handle):\n // it can only act at the connection's current depth, and waiting for a\n // shallower savepoint it does not own would never resolve.\n if (open.scope.depth < scope.depth) return true;\n // Genuine nesting: the call is being made from inside the open callback.\n return CURRENT.getStore() === open.scope;\n}\n\nasync function waitForTurn(params: { scope: SavepointScope }): Promise<void> {\n for (;;) {\n const open = params.scope.state.open;\n if (open === null || mayProceed({ scope: params.scope, open })) return;\n await open.settled;\n }\n}\n\n/**\n * Wait for this handle's turn and take it in the SAME synchronous step — the\n * check and the push must not be separated by an await, or two waiters woken\n * together would both open a savepoint.\n */\nasync function acquire(params: { scope: SavepointScope }): Promise<OpenSavepoint> {\n const { scope } = params;\n for (;;) {\n const open = scope.state.open;\n if (mayProceed({ scope, open })) return pushNode({ scope, parent: open });\n // `mayProceed` returns true for a null `open`, so this is never null here.\n await (open as OpenSavepoint).settled;\n }\n}\n\nfunction pushNode(params: { scope: SavepointScope; parent: OpenSavepoint | null }): OpenSavepoint {\n const { scope, parent } = params;\n const state = scope.state;\n let settle: () => void = () => undefined;\n const settled = new Promise<void>((resolve) => {\n settle = () => resolve();\n });\n // Physical depth follows the connection's stack, not the handle that opened\n // it: a savepoint opened from an outer handle inside a child's callback still\n // nests inside that child.\n const node: OpenSavepoint = {\n scope: { depth: (parent === null ? 0 : parent.scope.depth) + 1, state },\n name: nextSavepointName({ counter: state.counter }),\n parent,\n settled,\n settle,\n };\n state.open = node;\n return node;\n}\n\nfunction closeNode(params: { node: OpenSavepoint }): void {\n const { node } = params;\n const state = node.scope.state;\n if (state.open === node) state.open = node.parent;\n node.settle();\n}\n\n/** Wait out savepoints a callback opened below this node and never awaited. */\nasync function drainDescendants(params: { node: OpenSavepoint }): Promise<void> {\n const state = params.node.scope.state;\n for (;;) {\n const open = state.open;\n if (open === null || open === params.node || open.scope.depth <= params.node.scope.depth) return;\n await open.settled;\n }\n}\n",
7
+ "/**\n * Transaction budgets — the total-deadline clock and the handle-closure gate.\n *\n * ONE copy, shared by every adapter package through the\n * `@vibeorm/runtime/adapter-kit` subpath (like `savepoint-gate.ts`), so a\n * change here reaches all engines at once — a per-adapter copy would drift\n * into a silent per-engine behaviour difference.\n *\n * WHAT A DEADLINE IS, AND IS NOT\n *\n * `TransactionOptions.timeout` is unchanged: a PER-STATEMENT engine-side bound.\n * `TransactionOptions.deadline` is new and different — a TOTAL wall-clock bound\n * on one top-level transaction. Its clock starts immediately before `BEGIN` is\n * sent, so connection acquisition (which has its own budget on the pooled\n * adapters) is deliberately NOT counted.\n *\n * Enforcement is never `Promise.race` over a statement that keeps running:\n *\n * - `\"between-statements\"` (the default, and all six adapters can deliver it):\n * before every statement, every nested `transaction()` and the `COMMIT`, an\n * expired budget refuses. The statement is never sent and the transaction is\n * rolled back. A statement ALREADY IN FLIGHT is not interrupted.\n * - `\"cancel-running-statements\"` (postgres servers only): additionally hands\n * the engine the remaining budget as `statement_timeout`, so the SERVER\n * cancels an over-long statement. An adapter that cannot do this refuses the\n * request outright rather than quietly delivering the weaker level.\n *\n * JavaScript cannot forcibly stop a running callback. A callback that keeps\n * going past the deadline finds its later database calls refused; work it does\n * outside the database (an HTTP call, an SMS) is not stopped and cannot be.\n * There is no automatic retry: a deadline failure is terminal for that\n * transaction, because external side effects may already have happened.\n */\n\nimport { VibeError } from \"@vibeorm/schema\";\nimport type {\n TransactionDeadlineEnforcement,\n TransactionDeadlineSupport,\n TransactionOptions,\n} from \"../adapter.ts\";\n\n// ─── Types ────────────────────────────────────────────────────────\n\n/** Where a budget check happened, reported as `meta.stage`. */\nexport type BudgetStage = \"statement\" | \"nested\" | \"commit\";\n\n/**\n * What is known about a finished transaction. `\"unknown\"` is a first-class\n * outcome, not a failure to decide: when a rollback itself fails the commit\n * state genuinely cannot be asserted, and claiming \"rolled back\" would be a lie.\n */\nexport type TransactionOutcome = \"committed\" | \"rolled-back\" | \"unknown\";\n\n/** Wall clock, injectable so tests are deterministic instead of sleep-timed. */\nexport type DeadlineClock = () => number;\n\n/** The ambient clock, used whenever no seam is injected. */\nexport const DEFAULT_DEADLINE_CLOCK: DeadlineClock = (): number => Date.now();\n\n/**\n * One top-level transaction's budget. Nested savepoint handles share this\n * object BY REFERENCE — they never get an independent clock, connection or\n * session setting.\n */\nexport type TransactionBudget = {\n /** The enforcement level in force, or `null` when no deadline was requested. */\n readonly enforcement: TransactionDeadlineEnforcement | null;\n /** The requested total budget in milliseconds, or `null` when none was. */\n readonly totalMs: number | null;\n /** Existing per-statement limit, independent of the total deadline. Zero disables it. */\n readonly statementTimeoutMs: number | null;\n /** Milliseconds left (never negative), or `null` when no deadline is set. */\n remainingMs(): number | null;\n /** True only when a deadline is set and has passed. */\n expired(): boolean;\n /** Refuse a closed handle or an expired budget. Called BEFORE anything is sent. */\n assertUsable(params: { stage: BudgetStage }): void;\n /** Record the terminal outcome; the first call wins and later ones are ignored. */\n close(params: { outcome: TransactionOutcome }): void;\n /** The recorded outcome, or `null` while the transaction is still open. */\n readonly outcome: TransactionOutcome | null;\n};\n\n// ─── Validation (before BEGIN, before any write) ──────────────────\n\n/**\n * Check `options.deadline` against what this adapter can honestly deliver.\n * Called BEFORE `BEGIN` — a budget this engine cannot honour must never leave\n * a transaction open behind it.\n *\n * @throws VibeError `VIBE_VALIDATION` when `totalMs` is not a positive integer.\n * @throws VibeError `VIBE_UNSUPPORTED_CAPABILITY` when the requested\n * `enforcement` is stronger than `support` — refused, never silently degraded.\n */\nexport function validateTransactionDeadline(params: {\n options?: TransactionOptions;\n support: TransactionDeadlineSupport;\n provider: string;\n}): void {\n const { options, support, provider } = params;\n const deadline = options?.deadline;\n if (deadline === undefined) return;\n\n if (support === \"unsupported\") {\n throw new VibeError({\n code: \"VIBE_UNSUPPORTED_CAPABILITY\",\n message: `${provider} cannot enforce a transaction deadline — remove the \\`deadline\\` option`,\n meta: { provider, feature: \"transactionDeadline\", supported: support },\n });\n }\n\n if (!Number.isInteger(deadline.totalMs) || deadline.totalMs <= 0) {\n throw new VibeError({\n code: \"VIBE_VALIDATION\",\n message: `transaction deadline \\`totalMs\\` must be a positive integer of milliseconds, received ${String(deadline.totalMs)}`,\n meta: { provider, feature: \"transactionDeadline\", totalMs: deadline.totalMs },\n });\n }\n\n const requested: TransactionDeadlineEnforcement = deadline.enforcement ?? \"between-statements\";\n if (requested === \"cancel-running-statements\" && support !== \"cancel-running-statements\") {\n throw new VibeError({\n code: \"VIBE_UNSUPPORTED_CAPABILITY\",\n message:\n `${provider} cannot cancel a statement that is already running, so the requested ` +\n \"`cancel-running-statements` deadline guarantee is refused rather than silently downgraded — \" +\n 'ask for \"between-statements\" if a budget checked between statements is enough',\n meta: { provider, feature: \"transactionDeadline\", requested, supported: support },\n });\n }\n}\n\n// ─── The budget ───────────────────────────────────────────────────\n\n/**\n * Start the clock for one top-level transaction. Call it immediately before\n * `BEGIN`; {@link validateTransactionDeadline} must already have run.\n */\nexport function startTransactionBudget(params: {\n options?: TransactionOptions;\n provider: string;\n clock?: DeadlineClock;\n}): TransactionBudget {\n const { options, provider } = params;\n const clock = params.clock ?? DEFAULT_DEADLINE_CLOCK;\n const deadline = options?.deadline;\n const totalMs = deadline === undefined ? null : deadline.totalMs;\n const enforcement: TransactionDeadlineEnforcement | null =\n deadline === undefined ? null : (deadline.enforcement ?? \"between-statements\");\n const expiresAt = totalMs === null ? null : clock() + totalMs;\n let outcome: TransactionOutcome | null = null;\n\n const budget: TransactionBudget = {\n enforcement,\n totalMs,\n statementTimeoutMs: options?.timeout ?? null,\n remainingMs(): number | null {\n return expiresAt === null ? null : Math.max(0, expiresAt - clock());\n },\n expired(): boolean {\n return expiresAt !== null && clock() >= expiresAt;\n },\n assertUsable(assertParams: { stage: BudgetStage }): void {\n if (outcome !== null) {\n throw transactionClosedError({ provider, outcome, stage: assertParams.stage });\n }\n if (expiresAt !== null && clock() >= expiresAt) {\n throw transactionDeadlineError({\n provider,\n stage: assertParams.stage,\n totalMs: totalMs as number,\n overdueMs: clock() - expiresAt,\n });\n }\n },\n close(closeParams: { outcome: TransactionOutcome }): void {\n if (outcome === null) outcome = closeParams.outcome;\n },\n get outcome(): TransactionOutcome | null {\n return outcome;\n },\n };\n return budget;\n}\n\n/**\n * The engine-side bound for the NEXT statement, or `null` when the caller did\n * not buy `\"cancel-running-statements\"`. Floored at 1 ms: on postgres `0` means\n * \"no limit\", so a spent budget must never be handed over as a zero.\n */\nexport function engineStatementBudgetMs(params: { budget: TransactionBudget }): number | null {\n const { budget } = params;\n if (budget.enforcement !== \"cancel-running-statements\") return null;\n const remaining = budget.remainingMs();\n if (remaining === null) return null;\n const totalBound = Math.max(1, Math.ceil(remaining));\n return budget.statementTimeoutMs !== null && budget.statementTimeoutMs > 0\n ? Math.min(totalBound, budget.statementTimeoutMs) : totalBound;\n}\n\n// ─── Errors ───────────────────────────────────────────────────────\n\n/**\n * The refusal an expired budget raises. `VIBE_TRANSACTION` with a stable\n * `meta.reason` — no SQL text, no parameter values, no credentials.\n */\nexport function transactionDeadlineError(params: {\n provider: string;\n stage: BudgetStage;\n totalMs: number;\n overdueMs: number;\n}): VibeError {\n const { provider, stage, totalMs, overdueMs } = params;\n const what =\n stage === \"commit\"\n ? \"the transaction was rolled back instead of committed\"\n : \"the statement was never sent and the transaction is being rolled back\";\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n `transaction deadline of ${totalMs} ms expired ${Math.max(0, Math.round(overdueMs))} ms ago — ${what}. ` +\n \"Nothing is retried automatically: work the callback did outside the database may already have happened.\",\n meta: { provider, reason: \"transaction-deadline\", stage, totalMs, overdueMs: Math.max(0, Math.round(overdueMs)) },\n });\n}\n\n/**\n * The refusal an ESCAPED transaction handle raises — a transactional adapter\n * kept past the end of its transaction. Without this it would run on a\n * connection that is back in the pool, outside any transaction.\n */\nexport function transactionClosedError(params: {\n provider: string;\n outcome: TransactionOutcome;\n stage: BudgetStage;\n}): VibeError {\n const { provider, outcome, stage } = params;\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n `this transaction has already finished (${outcome}), so its client can no longer be used — ` +\n \"a handle kept past the end of `$transaction` would run outside the transaction, on a connection \" +\n \"that now belongs to someone else\",\n meta: { provider, reason: \"transaction-closed\", outcome, stage },\n });\n}\n\n/**\n * The stable typed outcome for \"the deadline expired and the rollback that was\n * supposed to clean up failed too\". Promising a rollback here would be false;\n * promising a retry would be worse.\n *\n * `cause` is the CAUSAL error (the deadline refusal), so the reason the\n * transaction was being abandoned survives. The rollback failure itself is\n * reported only as `meta.rollbackFailed`: a raw driver failure can carry\n * statement text, and this error is meant to be logged.\n */\nexport function transactionOutcomeUnknownError(params: {\n provider: string;\n totalMs: number;\n cause: unknown;\n}): VibeError {\n const { provider, totalMs, cause } = params;\n return new VibeError({\n code: \"VIBE_TRANSACTION\",\n message:\n `transaction deadline of ${totalMs} ms expired and the rollback that should have cleaned up failed — ` +\n \"the commit state of this transaction is UNKNOWN. It is not retried automatically; inspect the data \" +\n \"before deciding.\",\n meta: {\n provider,\n reason: \"transaction-outcome-unknown\",\n outcome: \"unknown\",\n totalMs,\n rollbackFailed: true,\n },\n cause,\n });\n}\n\n/** Whether `error` is this module's deadline refusal (used to pick the cleanup path). */\nexport function isTransactionDeadlineError(error: unknown): boolean {\n const reason = (error as { meta?: { reason?: unknown } } | null)?.meta?.reason;\n return reason === \"transaction-deadline\";\n}\n"
8
+ ],
9
+ "mappings": ";;AAYO,SAAS,sBAAsB,GAAqB;AAAA,EACzD,OAAO,EAAE,GAAG,EAAE;AAAA;AAQT,SAAS,iBAAiB,CAAC,QAA+C;AAAA,EAC/E,OAAO,cAAc,OAAO,QAAQ;AAAA;;ACKtC;AAsCA,IAAM,UAAU,IAAI;AAKb,SAAS,oBAAoB,GAAmB;AAAA,EACrD,OAAO,EAAE,OAAO,GAAG,OAAO,EAAE,SAAS,uBAAuB,GAAG,MAAM,KAAK,EAAE;AAAA;AAQvE,SAAS,YAAe,CAAC,QAAuE;AAAA,EACrG,OAAO,QAAQ,IAAI,OAAO,OAAO,OAAO,IAAI;AAAA;AAQvC,SAAS,SAAS,CAAC,QAA8D;AAAA,EACtF,MAAM,OAAO,OAAO,MAAM,MAAM;AAAA,EAChC,IAAI,WAAW,EAAE,OAAO,OAAO,OAAO,KAAK,CAAC;AAAA,IAAG;AAAA,EAC/C,OAAO,YAAY,EAAE,OAAO,OAAO,MAAM,CAAC;AAAA;AAW5C,eAAsB,kBAAqB,CAAC,QAI7B;AAAA,EACb,QAAQ,OAAO,SAAS,SAAS;AAAA,EACjC,MAAM,OAAO,MAAM,QAAQ,EAAE,MAAM,CAAC;AAAA,EACpC,IAAI;AAAA,IACF,IAAI,YAAY;AAAA,MAAW,MAAM,QAAQ,aAAa,KAAK,MAAM;AAAA,IACjE,IAAI;AAAA,IACJ,IAAI;AAAA,MACF,SAAS,MAAM,QAAQ,IAAI,KAAK,OAAO,MAAM,KAAK,KAAK,KAAK,CAAC;AAAA,MAC7D,OAAO,OAAO;AAAA,MAId,MAAM,iBAAiB,EAAE,KAAK,CAAC;AAAA,MAC/B,IAAI,YAAY,WAAW;A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AAS,MAAM;AAAA,EACjE,CAAC;AAAA;AAaI,SAAS,8BAA8B,CAAC,QAIjC;AAAA,EACZ,QAAQ,UAAU,SAAS,UAAU;AAAA,EACrC,OAAO,IAAI,UAAU;AAAA,IACnB,MAAM;AAAA,IACN,SACE,2BAA2B,mFAC3B,wGACA;AAAA,IACF,MAAM;AAAA,MACJ;AAAA,MACA,QAAQ;AAAA,MACR,SAAS;AAAA,MACT;AAAA,MACA,gBAAgB;AAAA,IAClB;AAAA,IACA;AAAA,EACF,CAAC;AAAA;AAII,SAAS,0BAA0B,CAAC,OAAyB;AAAA,EAClE,MAAM,SAAU,OAAkD,MAAM;AAAA,EACxE,OAAO,WAAW;AAAA;",
10
+ "debugId": "90A5C246EB2BA1E264756E2164756E21",
11
+ "names": []
12
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * Savepoint lifetimes inside one top-level transaction (F14).
3
+ *
4
+ * A savepoint stack lives on ONE connection: `ROLLBACK TO SAVEPOINT s` undoes
5
+ * everything done after `s`, including work a LATER savepoint already released.
6
+ * Two `transaction()` callbacks opened from the same handle and overlapping in
7
+ * time therefore share that one stack, and the earlier one's rollback silently
8
+ * erases the later one's already committed work. Unique savepoint names do not
9
+ * help — the names never collided, the lifetimes did.
10
+ *
11
+ * The rule enforced here, on every handle of a transaction:
12
+ *
13
+ * > A handle runs when nothing deeper than itself is open. Otherwise it waits
14
+ * > for the innermost open savepoint to settle — unless the call is being made
15
+ * > from INSIDE that savepoint's own callback, which is genuine nesting and
16
+ * > proceeds immediately.
17
+ *
18
+ * The "from inside" test is an {@link AsyncLocalStorage} lookup, so the common
19
+ * nesting shapes never wait on themselves: a child opened from its parent's
20
+ * callback, and the parent handle used from within an open child's callback,
21
+ * both proceed. Only genuinely concurrent siblings serialize.
22
+ *
23
+ * Not covered: a callback that awaits a sibling it did not start. That
24
+ * arrangement asks for two savepoints to be open at once, which is exactly what
25
+ * loses work; it now blocks instead. Deliberate — see the notes for this fix.
26
+ */
27
+ import { type SavepointCounter } from "./savepoints.ts";
28
+ /**
29
+ * One handle's position in the savepoint stack of a top-level transaction.
30
+ * `state` is shared by reference across every handle of that transaction.
31
+ */
32
+ export type SavepointScope = {
33
+ /** Physical savepoint depth; 0 is the top-level transaction itself. */
34
+ readonly depth: number;
35
+ /** Shared state: name allocation plus the innermost open savepoint. */
36
+ readonly state: SavepointState;
37
+ };
38
+ /** Mutable state shared by every scope of one top-level transaction. */
39
+ export type SavepointState = {
40
+ /** Savepoint name counter (shared, so names never collide). */
41
+ readonly counter: SavepointCounter;
42
+ /** The innermost savepoint currently open, or `null` when none is. */
43
+ open: OpenSavepoint | null;
44
+ };
45
+ /** An open savepoint: its handle, its name, and when it finished. */
46
+ type OpenSavepoint = {
47
+ readonly scope: SavepointScope;
48
+ readonly name: string;
49
+ readonly parent: OpenSavepoint | null;
50
+ readonly settled: Promise<void>;
51
+ readonly settle: () => void;
52
+ };
53
+ /** Fresh scope for one top-level transaction: depth 0, nothing open. */
54
+ export declare function createSavepointScope(): SavepointScope;
55
+ /**
56
+ * Run a top-level transaction callback inside its scope's async context, so
57
+ * nested calls made from it can be told apart from calls made inside an open
58
+ * child.
59
+ */
60
+ export declare function runRootScope<T>(params: {
61
+ scope: SavepointScope;
62
+ body: () => Promise<T>;
63
+ }): Promise<T>;
64
+ /**
65
+ * The wait a statement on `scope` owes before it may run, or `undefined` when
66
+ * it may run now. Returning `undefined` keeps the uncontended path — nothing
67
+ * deeper open — free of an extra promise and microtask.
68
+ */
69
+ export declare function scopeTurn(params: {
70
+ scope: SavepointScope;
71
+ }): Promise<void> | undefined;
72
+ /**
73
+ * Open a nested savepoint under `scope`, run `body` inside it and release it —
74
+ * rolling back to it if `body` throws, exactly as before this gate existed.
75
+ *
76
+ * `execute` runs the savepoint control SQL (already wrapped in the adapter's
77
+ * own driver-error mapping). Omit it when the driver manages the savepoint
78
+ * itself (bun:sql's `savepoint()`), in which case only the lifetime is gated.
79
+ */
80
+ export declare function runNestedSavepoint<T>(params: {
81
+ readonly scope: SavepointScope;
82
+ readonly execute?: (statement: string) => Promise<unknown> | unknown;
83
+ readonly body: (scope: SavepointScope) => Promise<T>;
84
+ }): Promise<T>;
85
+ export {};
86
+ //# sourceMappingURL=savepoint-gate.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"savepoint-gate.d.ts","sourceRoot":"","sources":["../../src/adapter-kit/savepoint-gate.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;GAyBG;AAGH,OAAO,EAAE,KAAK,gBAAgB,EAA6C,MAAM,iBAAiB,CAAC;AAInG;;;GAGG;AACH,MAAM,MAAM,cAAc,GAAG;IAC3B,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,uEAAuE;IACvE,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;CAChC,CAAC;AAEF,wEAAwE;AACxE,MAAM,MAAM,cAAc,GAAG;IAC3B,+DAA+D;IAC/D,QAAQ,CAAC,OAAO,EAAE,gBAAgB,CAAC;IACnC,sEAAsE;IACtE,IAAI,EAAE,aAAa,GAAG,IAAI,CAAC;CAC5B,CAAC;AAEF,qEAAqE;AACrE,KAAK,aAAa,GAAG;IACnB,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,QAAQ,CAAC,IAAI,EAAE,MAAM,CAAC;IACtB,QAAQ,CAAC,MAAM,EAAE,aAAa,GAAG,IAAI,CAAC;IACtC,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAC,IAAI,CAAC,CAAC;IAChC,QAAQ,CAAC,MAAM,EAAE,MAAM,IAAI,CAAC;CAC7B,CAAC;AAWF,wEAAwE;AACxE,wBAAgB,oBAAoB,IAAI,cAAc,CAErD;AAED;;;;GAIG;AACH,wBAAgB,YAAY,CAAC,CAAC,EAAE,MAAM,EAAE;IAAE,KAAK,EAAE,cAAc,CAAC;IAAC,IAAI,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,CAAA;CAAE,GAAG,OAAO,CAAC,CAAC,CAAC,CAErG;AAED;;;;GAIG;AACH,wBAAgB,SAAS,CAAC,MAAM,EAAE;IAAE,KAAK,EAAE,cAAc,CAAA;CAAE,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,SAAS,CAItF;AAED;;;;;;;GAOG;AACH,wBAAsB,kBAAkB,CAAC,CAAC,EAAE,MAAM,EAAE;IAClD,QAAQ,CAAC,KAAK,EAAE,cAAc,CAAC;IAC/B,QAAQ,CAAC,OAAO,CAAC,EAAE,CAAC,SAAS,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC;IACrE,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,cAAc,KAAK,OAAO,CAAC,CAAC,CAAC,CAAC;CACtD,GAAG,OAAO,CAAC,CAAC,CAAC,CA6Bb"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Savepoint naming for nested transactions.
3
+ *
4
+ * v1 lesson (LEARNINGS.md): the counter is shared **by reference** across every
5
+ * adapter created for one top-level transaction, so sibling and deeply nested
6
+ * savepoints can never collide on a name.
7
+ */
8
+ /** Mutable counter shared by reference across one top-level transaction. */
9
+ export type SavepointCounter = {
10
+ n: number;
11
+ };
12
+ /** Fresh counter — one per top-level transaction. */
13
+ export declare function createSavepointCounter(): SavepointCounter;
14
+ /**
15
+ * Allocate the next savepoint name (`vibeorm_sp_0`, `vibeorm_sp_1`, …) and
16
+ * advance the shared counter. The name is an identifier by construction, so it
17
+ * is safe to interpolate into `SAVEPOINT` / `RELEASE` / `ROLLBACK TO` SQL.
18
+ */
19
+ export declare function nextSavepointName(params: {
20
+ counter: SavepointCounter;
21
+ }): string;
22
+ //# sourceMappingURL=savepoints.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"savepoints.d.ts","sourceRoot":"","sources":["../../src/adapter-kit/savepoints.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,4EAA4E;AAC5E,MAAM,MAAM,gBAAgB,GAAG;IAAE,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE7C,qDAAqD;AACrD,wBAAgB,sBAAsB,IAAI,gBAAgB,CAEzD;AAED;;;;GAIG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE;IAAE,OAAO,EAAE,gBAAgB,CAAA;CAAE,GAAG,MAAM,CAE/E"}
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Transaction budgets — the total-deadline clock and the handle-closure gate.
3
+ *
4
+ * ONE copy, shared by every adapter package through the
5
+ * `@vibeorm/runtime/adapter-kit` subpath (like `savepoint-gate.ts`), so a
6
+ * change here reaches all engines at once — a per-adapter copy would drift
7
+ * into a silent per-engine behaviour difference.
8
+ *
9
+ * WHAT A DEADLINE IS, AND IS NOT
10
+ *
11
+ * `TransactionOptions.timeout` is unchanged: a PER-STATEMENT engine-side bound.
12
+ * `TransactionOptions.deadline` is new and different — a TOTAL wall-clock bound
13
+ * on one top-level transaction. Its clock starts immediately before `BEGIN` is
14
+ * sent, so connection acquisition (which has its own budget on the pooled
15
+ * adapters) is deliberately NOT counted.
16
+ *
17
+ * Enforcement is never `Promise.race` over a statement that keeps running:
18
+ *
19
+ * - `"between-statements"` (the default, and all six adapters can deliver it):
20
+ * before every statement, every nested `transaction()` and the `COMMIT`, an
21
+ * expired budget refuses. The statement is never sent and the transaction is
22
+ * rolled back. A statement ALREADY IN FLIGHT is not interrupted.
23
+ * - `"cancel-running-statements"` (postgres servers only): additionally hands
24
+ * the engine the remaining budget as `statement_timeout`, so the SERVER
25
+ * cancels an over-long statement. An adapter that cannot do this refuses the
26
+ * request outright rather than quietly delivering the weaker level.
27
+ *
28
+ * JavaScript cannot forcibly stop a running callback. A callback that keeps
29
+ * going past the deadline finds its later database calls refused; work it does
30
+ * outside the database (an HTTP call, an SMS) is not stopped and cannot be.
31
+ * There is no automatic retry: a deadline failure is terminal for that
32
+ * transaction, because external side effects may already have happened.
33
+ */
34
+ import { VibeError } from "@vibeorm/schema";
35
+ import type { TransactionDeadlineEnforcement, TransactionDeadlineSupport, TransactionOptions } from "../adapter.ts";
36
+ /** Where a budget check happened, reported as `meta.stage`. */
37
+ export type BudgetStage = "statement" | "nested" | "commit";
38
+ /**
39
+ * What is known about a finished transaction. `"unknown"` is a first-class
40
+ * outcome, not a failure to decide: when a rollback itself fails the commit
41
+ * state genuinely cannot be asserted, and claiming "rolled back" would be a lie.
42
+ */
43
+ export type TransactionOutcome = "committed" | "rolled-back" | "unknown";
44
+ /** Wall clock, injectable so tests are deterministic instead of sleep-timed. */
45
+ export type DeadlineClock = () => number;
46
+ /** The ambient clock, used whenever no seam is injected. */
47
+ export declare const DEFAULT_DEADLINE_CLOCK: DeadlineClock;
48
+ /**
49
+ * One top-level transaction's budget. Nested savepoint handles share this
50
+ * object BY REFERENCE — they never get an independent clock, connection or
51
+ * session setting.
52
+ */
53
+ export type TransactionBudget = {
54
+ /** The enforcement level in force, or `null` when no deadline was requested. */
55
+ readonly enforcement: TransactionDeadlineEnforcement | null;
56
+ /** The requested total budget in milliseconds, or `null` when none was. */
57
+ readonly totalMs: number | null;
58
+ /** Existing per-statement limit, independent of the total deadline. Zero disables it. */
59
+ readonly statementTimeoutMs: number | null;
60
+ /** Milliseconds left (never negative), or `null` when no deadline is set. */
61
+ remainingMs(): number | null;
62
+ /** True only when a deadline is set and has passed. */
63
+ expired(): boolean;
64
+ /** Refuse a closed handle or an expired budget. Called BEFORE anything is sent. */
65
+ assertUsable(params: {
66
+ stage: BudgetStage;
67
+ }): void;
68
+ /** Record the terminal outcome; the first call wins and later ones are ignored. */
69
+ close(params: {
70
+ outcome: TransactionOutcome;
71
+ }): void;
72
+ /** The recorded outcome, or `null` while the transaction is still open. */
73
+ readonly outcome: TransactionOutcome | null;
74
+ };
75
+ /**
76
+ * Check `options.deadline` against what this adapter can honestly deliver.
77
+ * Called BEFORE `BEGIN` — a budget this engine cannot honour must never leave
78
+ * a transaction open behind it.
79
+ *
80
+ * @throws VibeError `VIBE_VALIDATION` when `totalMs` is not a positive integer.
81
+ * @throws VibeError `VIBE_UNSUPPORTED_CAPABILITY` when the requested
82
+ * `enforcement` is stronger than `support` — refused, never silently degraded.
83
+ */
84
+ export declare function validateTransactionDeadline(params: {
85
+ options?: TransactionOptions;
86
+ support: TransactionDeadlineSupport;
87
+ provider: string;
88
+ }): void;
89
+ /**
90
+ * Start the clock for one top-level transaction. Call it immediately before
91
+ * `BEGIN`; {@link validateTransactionDeadline} must already have run.
92
+ */
93
+ export declare function startTransactionBudget(params: {
94
+ options?: TransactionOptions;
95
+ provider: string;
96
+ clock?: DeadlineClock;
97
+ }): TransactionBudget;
98
+ /**
99
+ * The engine-side bound for the NEXT statement, or `null` when the caller did
100
+ * not buy `"cancel-running-statements"`. Floored at 1 ms: on postgres `0` means
101
+ * "no limit", so a spent budget must never be handed over as a zero.
102
+ */
103
+ export declare function engineStatementBudgetMs(params: {
104
+ budget: TransactionBudget;
105
+ }): number | null;
106
+ /**
107
+ * The refusal an expired budget raises. `VIBE_TRANSACTION` with a stable
108
+ * `meta.reason` — no SQL text, no parameter values, no credentials.
109
+ */
110
+ export declare function transactionDeadlineError(params: {
111
+ provider: string;
112
+ stage: BudgetStage;
113
+ totalMs: number;
114
+ overdueMs: number;
115
+ }): VibeError;
116
+ /**
117
+ * The refusal an ESCAPED transaction handle raises — a transactional adapter
118
+ * kept past the end of its transaction. Without this it would run on a
119
+ * connection that is back in the pool, outside any transaction.
120
+ */
121
+ export declare function transactionClosedError(params: {
122
+ provider: string;
123
+ outcome: TransactionOutcome;
124
+ stage: BudgetStage;
125
+ }): VibeError;
126
+ /**
127
+ * The stable typed outcome for "the deadline expired and the rollback that was
128
+ * supposed to clean up failed too". Promising a rollback here would be false;
129
+ * promising a retry would be worse.
130
+ *
131
+ * `cause` is the CAUSAL error (the deadline refusal), so the reason the
132
+ * transaction was being abandoned survives. The rollback failure itself is
133
+ * reported only as `meta.rollbackFailed`: a raw driver failure can carry
134
+ * statement text, and this error is meant to be logged.
135
+ */
136
+ export declare function transactionOutcomeUnknownError(params: {
137
+ provider: string;
138
+ totalMs: number;
139
+ cause: unknown;
140
+ }): VibeError;
141
+ /** Whether `error` is this module's deadline refusal (used to pick the cleanup path). */
142
+ export declare function isTransactionDeadlineError(error: unknown): boolean;
143
+ //# sourceMappingURL=transaction-budget.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"transaction-budget.d.ts","sourceRoot":"","sources":["../../src/adapter-kit/transaction-budget.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAgCG;AAEH,OAAO,EAAE,SAAS,EAAE,MAAM,iBAAiB,CAAC;AAC5C,OAAO,KAAK,EACV,8BAA8B,EAC9B,0BAA0B,EAC1B,kBAAkB,EACnB,MAAM,eAAe,CAAC;AAIvB,+DAA+D;AAC/D,MAAM,MAAM,WAAW,GAAG,WAAW,GAAG,QAAQ,GAAG,QAAQ,CAAC;AAE5D;;;;GAIG;AACH,MAAM,MAAM,kBAAkB,GAAG,WAAW,GAAG,aAAa,GAAG,SAAS,CAAC;AAEzE,gFAAgF;AAChF,MAAM,MAAM,aAAa,GAAG,MAAM,MAAM,CAAC;AAEzC,4DAA4D;AAC5D,eAAO,MAAM,sBAAsB,EAAE,aAAwC,CAAC;AAE9E;;;;GAIG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,gFAAgF;IAChF,QAAQ,CAAC,WAAW,EAAE,8BAA8B,GAAG,IAAI,CAAC;IAC5D,2EAA2E;IAC3E,QAAQ,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IAChC,yFAAyF;IACzF,QAAQ,CAAC,kBAAkB,EAAE,MAAM,GAAG,IAAI,CAAC;IAC3C,6EAA6E;IAC7E,WAAW,IAAI,MAAM,GAAG,IAAI,CAAC;IAC7B,uDAAuD;IACvD,OAAO,IAAI,OAAO,CAAC;IACnB,mFAAmF;IACnF,YAAY,CAAC,MAAM,EAAE;QAAE,KAAK,EAAE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