turbine-orm 0.92.0 → 0.93.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.
@@ -0,0 +1,86 @@
1
+ /**
2
+ * turbine-orm, the `turbine:query` tracing channel.
3
+ *
4
+ * Every statement that emits a `$on('query')` event, and the transaction
5
+ * control and `$notify` statements Turbine sends on its own (which emit none),
6
+ * is published on the Node `diagnostics_channel` tracing channel named
7
+ * {@link QUERY_CHANNEL}, so a tracer or APM agent can turn Turbine queries
8
+ * into spans without any setup in the application: it subscribes to the
9
+ * channel, and the application never passes it a client.
10
+ *
11
+ * The events follow the TracingChannel lifecycle for an async call: `start`
12
+ * and `end` when the statement is handed to the driver, then `error` (on
13
+ * failure), `asyncStart` and `asyncEnd` when it settles. All five carry the
14
+ * same context object, so a subscriber can key its own state on it. `start`
15
+ * runs in the caller's async context, so the active span there is the
16
+ * statement's parent.
17
+ *
18
+ * The context never carries a bound parameter value: `sql` is the
19
+ * parametrized text Turbine built (`$1`, `$2`, ...), without the `sqlComment`,
20
+ * and `paramCount` is how many values were bound. Result rows are not
21
+ * attached either. That is why the events are published directly rather than
22
+ * through `tracePromise`, which would put the driver result on the context.
23
+ * A consequence: stores bound with `bindStore` are not entered, so read the
24
+ * caller's async context in the `start` subscriber instead.
25
+ *
26
+ * Cost without a subscriber: one `hasSubscribers` read per statement, and no
27
+ * object is built. The channel is looked up once, through
28
+ * `process.getBuiltinModule`, so no Node builtin is imported statically and
29
+ * the edge entry stays builtin-free. Where that function is missing (Node
30
+ * before 20.16 or 22.3, edge runtimes) nothing is published.
31
+ */
32
+ /** The tracing channel name. Subscribe with `diagnostics_channel.tracingChannel('turbine:query')`. */
33
+ export declare const QUERY_CHANNEL = "turbine:query";
34
+ /**
35
+ * The `operation` of a transaction-control statement Turbine sends on its own:
36
+ * `BEGIN`, `COMMIT`, `ROLLBACK`, savepoints and `sessionContext` settings. Its
37
+ * `model` is `'$raw'`, the `RAW_QUERY_MODEL` of query-events.ts (not imported:
38
+ * query-events.ts imports this module).
39
+ */
40
+ export declare const TRANSACTION_CONTROL_OPERATION = "$transaction";
41
+ /**
42
+ * The context object published on every `turbine:query` event. `rowCount` and
43
+ * `durationMs` are set before `asyncStart`, and `error` before the `error`
44
+ * event; the start events see only the identity fields.
45
+ */
46
+ export interface QueryChannelContext {
47
+ /** The table, or `'$raw'` for raw SQL and transaction control. */
48
+ model: string;
49
+ /** The entry point: `findMany`, `create`, `raw`, `$queryRaw` ..., or `'$transaction'` for transaction control. */
50
+ operation: string;
51
+ /** The parametrized statement, never its values, and without the `sqlComment`. */
52
+ sql: string;
53
+ /** How many values were bound to `sql`. */
54
+ paramCount: number;
55
+ /** Rows returned or affected. 0 for a failed statement. */
56
+ rowCount?: number;
57
+ /** Wall time of the statement, in ms. In a pipeline, the batch's time split evenly across its statements. */
58
+ durationMs?: number;
59
+ /** The error the caller receives, on failure. */
60
+ error?: Error;
61
+ /** `'pipeline'` or `'transaction'` for a statement sent as part of a batch. */
62
+ batch?: 'pipeline' | 'transaction';
63
+ /** Set on a failed first attempt of a read that Turbine sent once more on a fresh connection. */
64
+ retried?: true;
65
+ }
66
+ /** True when something subscribes to `turbine:query`. */
67
+ export declare function queryChannelActive(): boolean;
68
+ /**
69
+ * Publish `start` and `end` for a statement about to be sent, and return the
70
+ * context to settle with {@link settleQueryTrace}. Undefined, and nothing
71
+ * built, when nobody subscribes. Never throws.
72
+ */
73
+ export declare function startQueryTrace(model: string, operation: string, sql: string, paramCount: number, batch?: 'pipeline' | 'transaction'): QueryChannelContext | undefined;
74
+ /**
75
+ * Publish `error` (on failure), `asyncStart` and `asyncEnd` for a statement
76
+ * started with {@link startQueryTrace}. A no-op for an undefined context.
77
+ * Never throws.
78
+ */
79
+ export declare function settleQueryTrace(context: QueryChannelContext | undefined, rowCount: number, durationMs: number, error?: Error, retried?: boolean): void;
80
+ /**
81
+ * Run a statement Turbine sends on its own (transaction control, `$notify`)
82
+ * with a `turbine:query` trace around it. `run` should throw the error the
83
+ * caller receives, so the trace carries that one. Without a subscriber it is
84
+ * `run()` and nothing else.
85
+ */
86
+ export declare function traceStatement<R>(operation: string, sql: string, paramCount: number, run: () => Promise<R>): Promise<R>;
@@ -0,0 +1,143 @@
1
+ /**
2
+ * turbine-orm, the `turbine:query` tracing channel.
3
+ *
4
+ * Every statement that emits a `$on('query')` event, and the transaction
5
+ * control and `$notify` statements Turbine sends on its own (which emit none),
6
+ * is published on the Node `diagnostics_channel` tracing channel named
7
+ * {@link QUERY_CHANNEL}, so a tracer or APM agent can turn Turbine queries
8
+ * into spans without any setup in the application: it subscribes to the
9
+ * channel, and the application never passes it a client.
10
+ *
11
+ * The events follow the TracingChannel lifecycle for an async call: `start`
12
+ * and `end` when the statement is handed to the driver, then `error` (on
13
+ * failure), `asyncStart` and `asyncEnd` when it settles. All five carry the
14
+ * same context object, so a subscriber can key its own state on it. `start`
15
+ * runs in the caller's async context, so the active span there is the
16
+ * statement's parent.
17
+ *
18
+ * The context never carries a bound parameter value: `sql` is the
19
+ * parametrized text Turbine built (`$1`, `$2`, ...), without the `sqlComment`,
20
+ * and `paramCount` is how many values were bound. Result rows are not
21
+ * attached either. That is why the events are published directly rather than
22
+ * through `tracePromise`, which would put the driver result on the context.
23
+ * A consequence: stores bound with `bindStore` are not entered, so read the
24
+ * caller's async context in the `start` subscriber instead.
25
+ *
26
+ * Cost without a subscriber: one `hasSubscribers` read per statement, and no
27
+ * object is built. The channel is looked up once, through
28
+ * `process.getBuiltinModule`, so no Node builtin is imported statically and
29
+ * the edge entry stays builtin-free. Where that function is missing (Node
30
+ * before 20.16 or 22.3, edge runtimes) nothing is published.
31
+ */
32
+ /** The tracing channel name. Subscribe with `diagnostics_channel.tracingChannel('turbine:query')`. */
33
+ export const QUERY_CHANNEL = 'turbine:query';
34
+ /**
35
+ * The `operation` of a transaction-control statement Turbine sends on its own:
36
+ * `BEGIN`, `COMMIT`, `ROLLBACK`, savepoints and `sessionContext` settings. Its
37
+ * `model` is `'$raw'`, the `RAW_QUERY_MODEL` of query-events.ts (not imported:
38
+ * query-events.ts imports this module).
39
+ */
40
+ export const TRANSACTION_CONTROL_OPERATION = '$transaction';
41
+ let channel;
42
+ function queryChannel() {
43
+ if (channel !== undefined)
44
+ return channel;
45
+ channel = null;
46
+ try {
47
+ const proc = globalThis.process;
48
+ const dc = proc?.getBuiltinModule?.('node:diagnostics_channel');
49
+ channel = dc?.tracingChannel?.(QUERY_CHANNEL) ?? null;
50
+ }
51
+ catch {
52
+ channel = null;
53
+ }
54
+ return channel;
55
+ }
56
+ function subscribed(c) {
57
+ // TracingChannel#hasSubscribers is Node 22+ and 20.13+; older ones check each channel.
58
+ if (typeof c.hasSubscribers === 'boolean')
59
+ return c.hasSubscribers;
60
+ return (c.start.hasSubscribers ||
61
+ c.end.hasSubscribers ||
62
+ c.asyncStart.hasSubscribers ||
63
+ c.asyncEnd.hasSubscribers ||
64
+ c.error.hasSubscribers);
65
+ }
66
+ /** True when something subscribes to `turbine:query`. */
67
+ export function queryChannelActive() {
68
+ const c = queryChannel();
69
+ return c !== null && subscribed(c);
70
+ }
71
+ /**
72
+ * Publish `start` and `end` for a statement about to be sent, and return the
73
+ * context to settle with {@link settleQueryTrace}. Undefined, and nothing
74
+ * built, when nobody subscribes. Never throws.
75
+ */
76
+ export function startQueryTrace(model, operation, sql, paramCount, batch) {
77
+ const c = queryChannel();
78
+ if (c === null || !subscribed(c))
79
+ return undefined;
80
+ const context = { model, operation, sql, paramCount };
81
+ if (batch !== undefined)
82
+ context.batch = batch;
83
+ try {
84
+ c.start.publish(context);
85
+ c.end.publish(context);
86
+ }
87
+ catch {
88
+ // A subscriber problem must not fail the statement.
89
+ }
90
+ return context;
91
+ }
92
+ /**
93
+ * Publish `error` (on failure), `asyncStart` and `asyncEnd` for a statement
94
+ * started with {@link startQueryTrace}. A no-op for an undefined context.
95
+ * Never throws.
96
+ */
97
+ export function settleQueryTrace(context, rowCount, durationMs, error, retried) {
98
+ if (context === undefined)
99
+ return;
100
+ const c = queryChannel();
101
+ if (c === null)
102
+ return;
103
+ context.rowCount = rowCount;
104
+ context.durationMs = durationMs;
105
+ if (retried)
106
+ context.retried = true;
107
+ try {
108
+ if (error !== undefined) {
109
+ context.error = error;
110
+ c.error.publish(context);
111
+ }
112
+ c.asyncStart.publish(context);
113
+ c.asyncEnd.publish(context);
114
+ }
115
+ catch {
116
+ // A subscriber problem must not fail the statement.
117
+ }
118
+ }
119
+ /**
120
+ * Run a statement Turbine sends on its own (transaction control, `$notify`)
121
+ * with a `turbine:query` trace around it. `run` should throw the error the
122
+ * caller receives, so the trace carries that one. Without a subscriber it is
123
+ * `run()` and nothing else.
124
+ */
125
+ export function traceStatement(operation, sql, paramCount, run) {
126
+ const trace = startQueryTrace('$raw', operation, sql, paramCount);
127
+ if (trace === undefined)
128
+ return run();
129
+ return settleAround(trace, run);
130
+ }
131
+ async function settleAround(trace, run) {
132
+ const start = performance.now();
133
+ try {
134
+ const result = await run();
135
+ const rows = result?.rowCount;
136
+ settleQueryTrace(trace, typeof rows === 'number' ? rows : 0, performance.now() - start);
137
+ return result;
138
+ }
139
+ catch (err) {
140
+ settleQueryTrace(trace, 0, performance.now() - start, err instanceof Error ? err : new Error(String(err)));
141
+ throw err;
142
+ }
143
+ }
@@ -30,6 +30,7 @@
30
30
  */
31
31
  import { AsyncLocalStorage } from 'node:async_hooks';
32
32
  import { ValidationError } from './errors.js';
33
+ import { settleQueryTrace, startQueryTrace } from './query-channel.js';
33
34
  /**
34
35
  * The `model` reported for statements that are not tied to one table: `raw`,
35
36
  * `sql`, the transaction-scoped `raw` / `rawQuery`, and prisma-compat's
@@ -105,15 +106,18 @@ export function deferredIdentity(tag) {
105
106
  * success. `minified-events.test.ts` runs this module through that minifier.
106
107
  */
107
108
  export async function runReportedStatement(sink, identity, sql, params, run, wrap) {
109
+ const trace = startQueryTrace(identity.model, identity.action, sql, params.length, identity.batch);
108
110
  const start = performance.now();
109
111
  const report = (rows, error) => {
112
+ const duration = performance.now() - start;
113
+ settleQueryTrace(trace, rows, duration, error);
110
114
  if (!sink)
111
115
  return;
112
116
  emitStatementEvent(sink, {
113
117
  ...identity,
114
118
  sql,
115
119
  params,
116
- duration: performance.now() - start,
120
+ duration,
117
121
  rows,
118
122
  ...(error === undefined ? {} : { error }),
119
123
  });
@@ -38,6 +38,7 @@
38
38
  */
39
39
  import { AsyncLocalStorage } from 'node:async_hooks';
40
40
  import { DeadlockError, LockNotAvailableError, SerializationFailureError, TransactionRolledBackError, ValidationError, wrapPgError, } from './errors.js';
41
+ import { TRANSACTION_CONTROL_OPERATION, traceStatement } from './query-channel.js';
41
42
  import { findTransactionControl, mayHoldTransactionControl, } from './transaction-control.js';
42
43
  /** The key a transaction-scoped pool carries its {@link TransactionState} under. */
43
44
  export const TRANSACTION_STATE = Symbol.for('turbine-orm.transactionState');
@@ -492,14 +493,14 @@ export class TransactionState {
492
493
  */
493
494
  async control(sql) {
494
495
  this.assertOpen();
495
- await this.send(async () => {
496
+ await this.send(() => traceStatement(TRANSACTION_CONTROL_OPERATION, sql, 0, async () => {
496
497
  try {
497
498
  await this.client.query(sql);
498
499
  }
499
500
  catch (err) {
500
501
  throw wrapPgError(err);
501
502
  }
502
- });
503
+ }));
503
504
  }
504
505
  }
505
506
  /** The state carried by a transaction-scoped pool, or undefined for any other pool. */
@@ -536,15 +537,18 @@ export function withSavepoint(pool, operation) {
536
537
  * result, so the check is inert for them.
537
538
  */
538
539
  export async function commitTransaction(client, commitSql, firstFailure, api = '$transaction') {
539
- let result;
540
- try {
541
- result = await client.query(commitSql);
542
- }
543
- catch (err) {
544
- throw wrapPgError(err);
545
- }
546
- if (commitWasRolledBack(result))
547
- throw rolledBackError(firstFailure, 'transaction', api);
540
+ // The rolled-back check is inside the trace: a COMMIT answered with ROLLBACK is a failed COMMIT.
541
+ await traceStatement(TRANSACTION_CONTROL_OPERATION, commitSql, 0, async () => {
542
+ let result;
543
+ try {
544
+ result = await client.query(commitSql);
545
+ }
546
+ catch (err) {
547
+ throw wrapPgError(err);
548
+ }
549
+ if (commitWasRolledBack(result))
550
+ throw rolledBackError(firstFailure, 'transaction', api);
551
+ });
548
552
  }
549
553
  /** Whether a COMMIT result reports that the server rolled the transaction back. */
550
554
  export function commitWasRolledBack(result) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "turbine-orm",
3
- "version": "0.92.0",
3
+ "version": "0.93.0",
4
4
  "description": "Postgres-native TypeScript ORM, runs on Neon, Vercel Postgres, Cloudflare, Supabase. Streaming cursors, typed errors, single-query nested relations. One dependency, no WASM engine",
5
5
  "type": "module",
6
6
  "//exports": "Each subpath declares its types PER CONDITION. A single shared top-level \"types\" resolves to the ESM declarations for `require` too, which is TS1479 (\"is an ES module ... cannot be require()d\") for any CJS consumer on moduleResolution node16/nodenext. The require condition points at dist/cjs, which ships its own {\"type\":\"commonjs\"} package.json, so those declarations are CJS declarations. Gated in CI by publint + @arethetypeswrong/cli + a real .cts consumer typecheck (see the package-types job in ci.yml).",
@@ -165,6 +165,7 @@
165
165
  "lint:fix": "biome check --write src/",
166
166
  "format": "biome format --write src/",
167
167
  "check:error-codes": "tsx scripts/check-error-codes.ts",
168
+ "gen:capabilities": "tsx scripts/gen-capability-table.ts",
168
169
  "//check:error-prefix": "No message reaching a TurbineError may hand-write a `[turbine] ` prefix. formatErrorMessage prepends `[TURBINE_EXXX] ` unless the message already opens with that exact tag, and a hand-written `[turbine] ` never matches one, so the two stacked on roughly 355 of the package's throw sites. A prefix rule looks unnecessary because formatErrorMessage guarantees the [CODE] tag: true, and not the failure mode, which is the INTERACTION between the automatic tag and a manual one. Diagnostics that no code tag ever touches (console calls, stream writes, Studio HTTP bodies) keep the prefix and are named in the script's DIAGNOSTIC_SINKS.",
169
170
  "check:error-prefix": "node scripts/check-error-prefix.mjs",
170
171
  "check:changelog": "node scripts/check-changelog-headings.mjs",