@ultimat3/db 30.9.0 → 31.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/CLAUDE.md +17 -9
- package/README.md +71 -22
- package/package.json +3 -2
- package/src/adapter.ts +9 -0
- package/src/attribution.ts +8 -9
- package/src/branch-errors.ts +24 -0
- package/src/branch.ts +2 -1
- package/src/check-ddl.ts +2 -2
- package/src/client.ts +7 -1
- package/src/db-diagnostics.ts +15 -4
- package/src/entity-shape.ts +20 -0
- package/src/errors.ts +4 -22
- package/src/expected-loop.ts +3 -3
- package/src/generate-partition-run.ts +97 -0
- package/src/generate-partition.ts +190 -0
- package/src/generate-snapshot.ts +9 -0
- package/src/generate.ts +6 -1
- package/src/index.ts +30 -99
- package/src/introspect.ts +23 -16
- package/src/invariant-ddl.ts +11 -10
- package/src/keyset.ts +26 -1
- package/src/pglite-branch.ts +2 -1
- package/src/pglite.ts +22 -55
- package/src/pool-sweep.ts +2 -3
- package/src/primary-key.ts +1 -2
- package/src/readonly-role.ts +41 -1
- package/src/same-tenant.ts +1 -1
- package/src/snapshot-parse.ts +12 -0
- package/src/sql.ts +21 -3
- package/src/statement-cancel.ts +86 -0
- package/src/statement-funnel.ts +8 -53
- package/src/statement-shape.ts +5 -3
- package/src/statement-span.ts +74 -18
- package/src/observe.ts +0 -90
package/src/statement-funnel.ts
CHANGED
|
@@ -1,25 +1,23 @@
|
|
|
1
1
|
// Single responsibility: the pooled driver's statement funnel — one statement on one handle, every
|
|
2
|
-
// driver failure typed on the way out, and the
|
|
2
|
+
// driver failure typed on the way out, traced and put on the bus by `traceStatement` on both
|
|
3
3
|
// settle paths. Split from `client.ts` at the file-size rule; `pglite.ts` holds the mirror pair
|
|
4
4
|
// (`send`/`statement`) for the embedded driver, and the two must keep answering the same way.
|
|
5
5
|
|
|
6
|
-
import {
|
|
6
|
+
import { callerStack } from '@ultimat3/core';
|
|
7
7
|
import { encodeBoundParameters } from './bound-parameters';
|
|
8
8
|
import type { BunSqlDriver } from './bun-sql';
|
|
9
9
|
import { refuseRolledBackCommit } from './commit-tag';
|
|
10
10
|
import { driverError } from './errors';
|
|
11
|
-
import { expectedQueryLoopReason } from './expected-loop';
|
|
12
|
-
import { statementObserver } from './observe';
|
|
13
11
|
import type { SqlFragment } from './sql';
|
|
14
12
|
import { statementExcerpt } from './statement-excerpt';
|
|
15
|
-
import {
|
|
13
|
+
import { traceStatement } from './statement-span';
|
|
16
14
|
|
|
17
15
|
export function rowsOf<T>(result: unknown): readonly T[] {
|
|
18
16
|
return Array.isArray(result) ? (result as readonly T[]) : [];
|
|
19
17
|
}
|
|
20
18
|
|
|
21
19
|
// The command tag only when it counted something, exactly like `rowsOf` in `pglite.ts` — one rule
|
|
22
|
-
// across both drivers, so `execute()` and the
|
|
20
|
+
// across both drivers, so `execute()` and the `db.statement` event cannot answer differently for the
|
|
23
21
|
// same statement depending on which database is behind them. A driver that tags a read `0` while
|
|
24
22
|
// returning rows would otherwise report 0 here and the row count there.
|
|
25
23
|
export function affectedBy(result: unknown): number {
|
|
@@ -59,55 +57,12 @@ async function sendOn(
|
|
|
59
57
|
}
|
|
60
58
|
|
|
61
59
|
/**
|
|
62
|
-
* The funnel — pooled and pinned statements both arrive here, which is why the
|
|
63
|
-
* off this one function and nowhere else.
|
|
64
|
-
* branch: no clock read, no span, no event object, and `sendOn` receives exactly the call `runOn`
|
|
65
|
-
* made before the seam existed (axiom 6).
|
|
60
|
+
* The funnel — pooled and pinned statements both arrive here, which is why the span and the
|
|
61
|
+
* `db.statement` event hang off this one function and nowhere else (`traceStatement`).
|
|
66
62
|
*/
|
|
67
|
-
export
|
|
63
|
+
export function runOn(
|
|
68
64
|
driver: Pick<BunSqlDriver, 'unsafe'>,
|
|
69
65
|
fragment: SqlFragment,
|
|
70
66
|
): Promise<unknown> {
|
|
71
|
-
|
|
72
|
-
if (observer === undefined) return sendOn(driver, fragment);
|
|
73
|
-
// Read here, not by the consumer: the scope is gone by the time a per-request detector judges
|
|
74
|
-
// what it collected, so the reason has to be captured with the statement it defends.
|
|
75
|
-
const expected = expectedQueryLoopReason();
|
|
76
|
-
// Same moment, same argument: `postgresRepo` is several frames and a microtask above this one,
|
|
77
|
-
// and what it knows — the entity and the operation — is what turns fifty identical `select`s
|
|
78
|
-
// into "50× findById on members". Absent for hand-written SQL, a migration, a health probe.
|
|
79
|
-
const attribution = statementAttribution();
|
|
80
|
-
const started = performance.now();
|
|
81
|
-
let result: unknown;
|
|
82
|
-
try {
|
|
83
|
-
// The span wraps the send and nothing else, so its duration is the statement's and the
|
|
84
|
-
// observer's own work is not charged to the database.
|
|
85
|
-
result = await withStatementSpan(fragment.text, () => sendOn(driver, fragment));
|
|
86
|
-
} catch (error) {
|
|
87
|
-
// A statement that failed is still a statement: fifty identical timeouts are an N+1 of
|
|
88
|
-
// timeouts. The error is already `X_DB_UNAVAILABLE`, so the event carries what the caller
|
|
89
|
-
// is about to be thrown — and an observer that throws here replaces it, which is why
|
|
90
|
-
// `observe.ts` says a reporting-only observer must not throw.
|
|
91
|
-
observer.onStatement({
|
|
92
|
-
text: fragment.text,
|
|
93
|
-
values: fragment.values,
|
|
94
|
-
durationMs: performance.now() - started,
|
|
95
|
-
rows: 0,
|
|
96
|
-
error,
|
|
97
|
-
attribution,
|
|
98
|
-
expected,
|
|
99
|
-
});
|
|
100
|
-
throw error;
|
|
101
|
-
}
|
|
102
|
-
// Outside the `try` deliberately: a throw from `onStatement` is the observer's, not the
|
|
103
|
-
// database's, and catching it above would report a statement that succeeded as failed.
|
|
104
|
-
observer.onStatement({
|
|
105
|
-
text: fragment.text,
|
|
106
|
-
values: fragment.values,
|
|
107
|
-
durationMs: performance.now() - started,
|
|
108
|
-
rows: affectedBy(result),
|
|
109
|
-
attribution,
|
|
110
|
-
expected,
|
|
111
|
-
});
|
|
112
|
-
return result;
|
|
67
|
+
return traceStatement(fragment, () => sendOn(driver, fragment), affectedBy, callerStack());
|
|
113
68
|
}
|
package/src/statement-shape.ts
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
// Single responsibility: what shape a statement is — the verb it opens with, whether that verb
|
|
2
2
|
// writes, and the identity repeated statements are counted under. Two detectors above this package
|
|
3
3
|
// group statements by that identity (`x dev`'s ledger, the `statements` test fixture) and a third
|
|
4
|
-
// names spans from the same verb, so the rule lives once, next to the `
|
|
4
|
+
// names spans from the same verb, so the rule lives once, next to the `DbStatementEvent` it reads.
|
|
5
5
|
// Nothing here counts anything: a threshold is a verdict's, and a verdict is `@ultimat3/entity`'s.
|
|
6
6
|
|
|
7
|
-
import type {
|
|
7
|
+
import type { DbStatementEvent } from '@ultimat3/core';
|
|
8
8
|
|
|
9
9
|
const LEADING_WORD = /^[A-Za-z]+/;
|
|
10
10
|
const WHITESPACE = /\s+/g;
|
|
@@ -51,7 +51,9 @@ export function statementKind(text: string): 'read' | 'write' {
|
|
|
51
51
|
* own text, already `$n`-parameterized by `sql()`, with whitespace collapsed so a builder that
|
|
52
52
|
* indents differently between two calls is still one shape rather than two.
|
|
53
53
|
*/
|
|
54
|
-
export function statementFingerprint(
|
|
54
|
+
export function statementFingerprint(
|
|
55
|
+
event: Pick<DbStatementEvent, 'text' | 'attribution'>,
|
|
56
|
+
): string {
|
|
55
57
|
const attribution = event.attribution;
|
|
56
58
|
if (attribution !== undefined) return `${attribution.entity}.${attribution.op}`;
|
|
57
59
|
return event.text.replace(WHITESPACE, ' ').trim();
|
package/src/statement-span.ts
CHANGED
|
@@ -1,22 +1,19 @@
|
|
|
1
|
-
// Single responsibility:
|
|
2
|
-
//
|
|
3
|
-
//
|
|
4
|
-
//
|
|
5
|
-
//
|
|
1
|
+
// Single responsibility: what one statement is to the rest of the process — a `db.<verb>` client
|
|
2
|
+
// span carrying OTel's stable database attributes, opened for EVERY statement (production has DB
|
|
3
|
+
// spans, not only `x dev`), and one `db.statement` event on the instrumentation bus once it has
|
|
4
|
+
// settled. Both drivers' funnels (`statement-funnel.ts`, `pglite.ts`) call `traceStatement` and
|
|
5
|
+
// nothing else, so the two cannot answer differently for the same statement.
|
|
6
6
|
|
|
7
|
-
import { withSpan } from '@ultimat3/core';
|
|
7
|
+
import { instrument, SEMCONV, SEMCONV_VALUES, subscribed, withSpan } from '@ultimat3/core';
|
|
8
|
+
import { statementAttribution } from './attribution';
|
|
9
|
+
import { expectedQueryLoopReason } from './expected-loop';
|
|
10
|
+
import type { SqlFragment } from './sql';
|
|
8
11
|
import { statementVerb } from './statement-shape';
|
|
9
12
|
|
|
10
|
-
/**
|
|
11
|
-
* OTel's name for the statement itself. Exported because it is a contract across two packages, not
|
|
12
|
-
* a local constant: `packages/cli/src/dev-traces.ts` reads it as a span's detail, so a rename that
|
|
13
|
-
* only landed here would leave the timeline grouping span names again with every test still green.
|
|
14
|
-
*/
|
|
15
|
-
export const STATEMENT_ATTRIBUTE = 'db.statement';
|
|
16
|
-
|
|
17
13
|
/**
|
|
18
14
|
* `db.select`, `db.insert`, `db.begin` — low cardinality on purpose, so the flame reads at a glance
|
|
19
|
-
* and a trace backend can still aggregate by name.
|
|
15
|
+
* and a trace backend can still aggregate by name. `x dev`'s recorder reads the panel's kind off
|
|
16
|
+
* the `db.` prefix. The full text rides on the span as `db.query.text`, never in its name.
|
|
20
17
|
*
|
|
21
18
|
* The verb is `statement-shape.ts`'s, the same read the N+1 detectors classify a statement with: a
|
|
22
19
|
* text with no leading word is `db.statement` here and a read there, one scanner and two labels.
|
|
@@ -28,13 +25,72 @@ export function statementSpanName(text: string): string {
|
|
|
28
25
|
|
|
29
26
|
/**
|
|
30
27
|
* Wraps the send, so the span's duration is the statement's and a failure is recorded on it rather
|
|
31
|
-
* than inferred from the gap after it. `client` is the OTel kind — the
|
|
32
|
-
*
|
|
33
|
-
*
|
|
28
|
+
* than inferred from the gap after it. `client` is the OTel kind (`INSTRUMENT_EVENTS`) — the
|
|
29
|
+
* database is the remote peer. The text is parameterised (`$1..$n`); bound values never ride a
|
|
30
|
+
* span. `db.collection.name` is not set: naming the table would need a second SQL reading.
|
|
34
31
|
*/
|
|
35
32
|
export function withStatementSpan<T>(text: string, send: () => Promise<T>): Promise<T> {
|
|
33
|
+
const verb = statementVerb(text);
|
|
36
34
|
return withSpan(statementSpanName(text), send, {
|
|
37
35
|
kind: 'client',
|
|
38
|
-
attributes: {
|
|
36
|
+
attributes: {
|
|
37
|
+
[SEMCONV.dbSystemName]: SEMCONV_VALUES.dbSystemPostgres,
|
|
38
|
+
[SEMCONV.dbQueryText]: text,
|
|
39
|
+
...(verb === '' ? {} : { [SEMCONV.dbOperationName]: verb.toUpperCase() }),
|
|
40
|
+
},
|
|
41
|
+
});
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* The funnel's shell: the span always, the `db.statement` event only while somebody subscribes. A
|
|
46
|
+
* production boot always has one — `subscribeSemconvMetrics` records the duration histogram — so a
|
|
47
|
+
* statement there costs a clock read, a scope read, one event object and one histogram record;
|
|
48
|
+
* with no subscriber at all it is one map read (axiom 6).
|
|
49
|
+
*
|
|
50
|
+
* A subscriber's throw is contained by the bus and never reaches the caller. The success-path emit
|
|
51
|
+
* still sits OUTSIDE the `try`, so no emit could ever report a statement that succeeded as failed.
|
|
52
|
+
*/
|
|
53
|
+
export async function traceStatement<R>(
|
|
54
|
+
fragment: SqlFragment,
|
|
55
|
+
send: () => Promise<R>,
|
|
56
|
+
rows: (result: R) => number,
|
|
57
|
+
/**
|
|
58
|
+
* `callerStack()` read at the funnel's ENTRY, before any queue or pool `await` — undefined, and
|
|
59
|
+
* nothing built, unless a holder turned `captureStatementStacks()` on (never production).
|
|
60
|
+
*/
|
|
61
|
+
callerStack: string | undefined,
|
|
62
|
+
): Promise<R> {
|
|
63
|
+
if (!subscribed('db.statement')) return withStatementSpan(fragment.text, send);
|
|
64
|
+
// Read here, not by the subscriber: the scopes are gone by the time a per-request detector
|
|
65
|
+
// judges what it collected, so the reason and the attribution travel with the statement.
|
|
66
|
+
const expected = expectedQueryLoopReason();
|
|
67
|
+
const attribution = statementAttribution();
|
|
68
|
+
const started = performance.now();
|
|
69
|
+
let result: R;
|
|
70
|
+
try {
|
|
71
|
+
result = await withStatementSpan(fragment.text, send);
|
|
72
|
+
} catch (error) {
|
|
73
|
+
// A failed statement is still a statement: fifty identical timeouts are an N+1 of timeouts.
|
|
74
|
+
instrument('db.statement', {
|
|
75
|
+
text: fragment.text,
|
|
76
|
+
values: fragment.values,
|
|
77
|
+
durationMs: performance.now() - started,
|
|
78
|
+
rows: 0,
|
|
79
|
+
error,
|
|
80
|
+
attribution,
|
|
81
|
+
expected,
|
|
82
|
+
callerStack,
|
|
83
|
+
});
|
|
84
|
+
throw error;
|
|
85
|
+
}
|
|
86
|
+
instrument('db.statement', {
|
|
87
|
+
text: fragment.text,
|
|
88
|
+
values: fragment.values,
|
|
89
|
+
durationMs: performance.now() - started,
|
|
90
|
+
rows: rows(result),
|
|
91
|
+
attribution,
|
|
92
|
+
expected,
|
|
93
|
+
callerStack,
|
|
39
94
|
});
|
|
95
|
+
return result;
|
|
40
96
|
}
|
package/src/observe.ts
DELETED
|
@@ -1,90 +0,0 @@
|
|
|
1
|
-
// Single responsibility: the seam a diagnostic hangs statements off. One installed observer,
|
|
2
|
-
// process-wide, read through one accessor — so the funnels every statement already passes through
|
|
3
|
-
// pay a single `undefined` check when nothing is installed (axiom 6). Nothing here knows what an
|
|
4
|
-
// entity, a request or a span is: `db` is tier 1 and the detector that consumes this is tier 5.
|
|
5
|
-
|
|
6
|
-
/**
|
|
7
|
-
* What the layer that compiled the statement knows and the driver cannot: which entity and which
|
|
8
|
-
* repository operation. It is the difference between "50× `select … where id = $1`" and "50×
|
|
9
|
-
* `findById` on `members`" in a diagnostic's report.
|
|
10
|
-
*
|
|
11
|
-
* Produced by `@ultimat3/entity`'s `postgresRepo` (tier 2, so importing this is downward): it is
|
|
12
|
-
* the last caller that still knows the entity and the operation by the time the SQL exists, and it
|
|
13
|
-
* declares both through `withStatementAttribution` (`attribution.ts`) around each repository call.
|
|
14
|
-
* Hand-written SQL, a migration, a health probe and the job queue's own statements are unattributed
|
|
15
|
-
* — nothing above them knows an entity to name — which is why the field is optional rather than
|
|
16
|
-
* required, and why a diagnostic must fall back to the statement text.
|
|
17
|
-
*/
|
|
18
|
-
export interface StatementAttribution {
|
|
19
|
-
/** Entity name as declared, e.g. `members` — never a table name. */
|
|
20
|
-
readonly entity: string;
|
|
21
|
-
/** Repository operation that compiled the statement, e.g. `findById`. */
|
|
22
|
-
readonly op: string;
|
|
23
|
-
}
|
|
24
|
-
|
|
25
|
-
/** One settled statement. Emitted after it resolved or rejected, never before it was sent. */
|
|
26
|
-
export interface StatementEvent {
|
|
27
|
-
/** The statement as sent, parameters still as `$1..$n`. Safe to log; values are separate. */
|
|
28
|
-
readonly text: string;
|
|
29
|
-
/** Bound parameters, in order. May carry user data — a consumer that logs must redact. */
|
|
30
|
-
readonly values: readonly unknown[];
|
|
31
|
-
/** Wall time from send to settle, from `performance.now()`. */
|
|
32
|
-
readonly durationMs: number;
|
|
33
|
-
/** Rows returned by a read, rows affected by a write, `0` when the statement threw. */
|
|
34
|
-
readonly rows: number;
|
|
35
|
-
/** The rejection, already wrapped as `X_DB_UNAVAILABLE` by the funnel. */
|
|
36
|
-
readonly error?: unknown;
|
|
37
|
-
/**
|
|
38
|
-
* Who compiled this statement, absent when nothing above the SQL knew — see
|
|
39
|
-
* `StatementAttribution`. Stamped by the funnel from the scope open at send time, for the same
|
|
40
|
-
* reason `expected` is: a diagnostic that judges a whole request runs long after every scope in
|
|
41
|
-
* it closed.
|
|
42
|
-
*/
|
|
43
|
-
readonly attribution?: StatementAttribution | undefined;
|
|
44
|
-
/**
|
|
45
|
-
* The reason of the innermost `expectedQueryLoop()` this statement was issued inside, absent
|
|
46
|
-
* outside every such scope. Stamped by the funnel at settle time rather than read later, because
|
|
47
|
-
* a diagnostic that judges a whole request at the end of it runs long after the scope closed. A
|
|
48
|
-
* detector counting repeats must not warn about these; everything that only measures — the span,
|
|
49
|
-
* the timeline, a metric — treats them like any other statement.
|
|
50
|
-
*/
|
|
51
|
-
readonly expected?: string | undefined;
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
/**
|
|
55
|
-
* A diagnostic. `onStatement` runs synchronously on the caller's stack once the statement has
|
|
56
|
-
* settled, so it must not await anything and must not issue SQL — a statement issued from here
|
|
57
|
-
* re-enters the funnel and observes itself.
|
|
58
|
-
*
|
|
59
|
-
* A throw propagates to whoever ran the statement, deliberately: strict test mode is an observer
|
|
60
|
-
* that fails the test the N+1 happened in, and swallowing here would make that impossible. An
|
|
61
|
-
* observer that only reports must therefore not throw.
|
|
62
|
-
*/
|
|
63
|
-
export interface StatementObserver {
|
|
64
|
-
onStatement(event: StatementEvent): void;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
let installed: StatementObserver | undefined;
|
|
68
|
-
|
|
69
|
-
/**
|
|
70
|
-
* Install the process-wide observer. `setStatementObserver(undefined)` uninstalls, which is the
|
|
71
|
-
* production state and the state every test must leave behind. The `setDbClient` shape, for the
|
|
72
|
-
* same reason: the thing being replaced is ambient, so the seam is a setter and not a parameter
|
|
73
|
-
* threaded through `db()`, `withTransaction()` and both drivers.
|
|
74
|
-
*
|
|
75
|
-
* One observer, not a list — a second registration replaces the first. A fan-out array would make
|
|
76
|
-
* "which diagnostic saw this statement" order-dependent, and the one consumer that needs several
|
|
77
|
-
* (the dev server) composes them itself, in its own order, where that order is reviewable.
|
|
78
|
-
*/
|
|
79
|
-
export function setStatementObserver(observer: StatementObserver | undefined): void {
|
|
80
|
-
installed = observer;
|
|
81
|
-
}
|
|
82
|
-
|
|
83
|
-
/**
|
|
84
|
-
* The installed observer, or `undefined` when there is none. Read once per statement and guarded
|
|
85
|
-
* at the call site rather than notified through a wrapper, so an uninstalled seam costs one
|
|
86
|
-
* property read and one branch — no event object is allocated for nobody to receive.
|
|
87
|
-
*/
|
|
88
|
-
export function statementObserver(): StatementObserver | undefined {
|
|
89
|
-
return installed;
|
|
90
|
-
}
|