@ultimat3/db 31.7.0 → 31.9.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/src/introspect.ts CHANGED
@@ -6,11 +6,12 @@
6
6
  import { nonAppRelations } from './app-relation';
7
7
  import { type DbClient, db } from './client';
8
8
  import type { PartitionInterval } from './entity-shape';
9
+ import type { IndexKeyParts } from './index-key-ddl';
10
+ import { type IndexKeyRow, indexesOf, indexRows } from './introspect-index';
9
11
  import {
10
12
  type CheckRow,
11
13
  type ColumnRow,
12
14
  type ForeignKeyRow,
13
- type IndexRow,
14
15
  notValidOf,
15
16
  onDeleteOf,
16
17
  type TriggerNameRow,
@@ -43,7 +44,12 @@ export interface ColumnDescription {
43
44
  readonly retired?: true | undefined;
44
45
  }
45
46
 
46
- export interface IndexDescription {
47
+ /**
48
+ * An index, as a snapshot records it and the catalog reads it. The four key parts past a plain
49
+ * column list (`IndexKeyParts`: expression, per-key directions, INCLUDE, operator class) are
50
+ * optional and absent on every index that has none, so no recorded snapshot changes shape.
51
+ */
52
+ export interface IndexDescription extends IndexKeyParts {
47
53
  readonly name: string;
48
54
  /**
49
55
  * Key columns in **index key order** — the order the planner sorts by, never `attnum`. An
@@ -278,41 +284,7 @@ export async function introspectSchema(
278
284
  order by c.table_name, c.ordinal_position
279
285
  `);
280
286
 
281
- // Ordered by the index's own key position, never by `attnum`: `indkey` IS the order the planner
282
- // sorts by, and a composite index on `(created_at, org_id)` whose columns were declared the
283
- // other way round came back reversed — a description that reads correct and compares wrong.
284
- // `indnkeyatts` drops INCLUDE payload columns, which are stored, not keyed.
285
- //
286
- // A LEFT join on `pg_attribute`: an expression key has `attnum = 0` and no attribute row, so an
287
- // inner join dropped it and `(id, lower(title))` read back as `(id)` — an index rebuilt by hand
288
- // with an extra expression key compared equal to the declared one. It is kept in its position
289
- // and MARKED by its parentheses, which no declared column name carries.
290
- const indexes = client.query<IndexRow>(sql`
291
- select
292
- t.relname as table_name,
293
- i.relname as index_name,
294
- ix.indisunique as is_unique,
295
- ix.indisprimary as is_primary,
296
- pg_get_expr(ix.indpred, ix.indrelid) as predicate,
297
- am.amname as method,
298
- array_agg(
299
- coalesce(a.attname::text, '(' || pg_get_indexdef(ix.indexrelid, k.ord::int, false) || ')')
300
- order by k.ord
301
- ) as columns,
302
- bool_and((ix.indoption[k.ord - 1] & 1) = 1) as descending
303
- from pg_class t
304
- join pg_namespace n on n.oid = t.relnamespace
305
- join pg_index ix on ix.indrelid = t.oid
306
- join pg_class i on i.oid = ix.indexrelid
307
- join pg_am am on am.oid = i.relam
308
- cross join lateral unnest(ix.indkey::smallint[]) with ordinality as k(attnum, ord)
309
- left join pg_attribute a on a.attrelid = t.oid and a.attnum = k.attnum and k.attnum > 0
310
- where n.nspname = ${schema} and t.relkind in ('r', 'p') and k.ord <= ix.indnkeyatts
311
- group by
312
- t.relname, i.relname, ix.indisunique, ix.indisprimary, ix.indpred, ix.indrelid,
313
- ix.indexrelid, am.amname
314
- order by t.relname, i.relname
315
- `);
287
+ const indexes = indexRows(client, schema);
316
288
 
317
289
  // `conkey` and `confkey` are unnested TOGETHER, by shared ordinality: they are two halves of one
318
290
  // ordered pairing, and matching each independently with `= any(...)` is a cross product — a
@@ -390,7 +362,7 @@ export function buildSchema(
390
362
  schema: string,
391
363
  excluded: readonly string[],
392
364
  columns: readonly ColumnRow[],
393
- indexes: readonly IndexRow[],
365
+ indexes: readonly IndexKeyRow[],
394
366
  foreignKeys: readonly ForeignKeyRow[],
395
367
  checks: readonly CheckRow[] = [],
396
368
  /** Absent leaves `triggerNames` off every table: nobody asked the catalog. */
@@ -404,20 +376,7 @@ export function buildSchema(
404
376
  .sort();
405
377
 
406
378
  const tables = names.map((name): TableDescription => {
407
- const tableIndexes = indexes
408
- .filter((row) => row.table_name === name)
409
- .map((row) => ({
410
- name: row.index_name,
411
- columns: [...row.columns],
412
- unique: row.is_unique,
413
- primary: row.is_primary,
414
- where: row.predicate,
415
- order: row.descending ? ('desc' as const) : null,
416
- // `exactOptionalPropertyTypes`: a row with no method is a stub's, and absent must stay
417
- // absent rather than becoming an explicit `undefined` a strict comparison can see.
418
- ...(row.method === undefined ? {} : { using: row.method }),
419
- }))
420
- .sort(byName);
379
+ const tableIndexes = indexesOf(indexes, name);
421
380
  return {
422
381
  schema,
423
382
  name,
@@ -0,0 +1,184 @@
1
+ // Single responsibility: decide whether a hand-written migration's `up` holds a live table still for
2
+ // a full scan — `set not null` with no validated check before it, or a non-concurrent index build —
3
+ // and raise `X_MIGRATION_LOCK_HEAVY` for it. `rolling.ts`'s shape and token stream: lexical, `up`
4
+ // only, a closed list, a marker to admit a deliberate one.
5
+
6
+ import { renderFixShellArg } from '@ultimat3/core';
7
+ import { NO_TRANSACTION_MARKER } from './concurrent-index';
8
+ import { DbError } from './errors';
9
+ import { hasMarkerLine } from './marker-line';
10
+ import { alteredTable, isWord, nameOf, qualifiedNameAt, subcommands, tokensOf } from './rolling';
11
+ import { statementExcerpt } from './statement-excerpt';
12
+ import { statementsOf } from './statement-split';
13
+
14
+ /** The line a migration carries when the lock is deliberate: a small table, a maintenance window. */
15
+ export const LOCK_HEAVY_MARKER = '-- lock-heavy: true';
16
+
17
+ const LOCK_HEAVY_COMMENT = /^--[ \t]*lock-heavy:[ \t]*true[ \t]*\r?\n?$/i;
18
+
19
+ /** The comments and blank space `statementsOf` carries in front of a statement's SQL. */
20
+ const LEADING_NOISE = /^(?:\s*(?:--[^\n]*|\/\*[\s\S]*?\*\/)\s*)+/;
21
+
22
+ /** Only spaces and tabs between `at` and the start of its line in `up` (or the file's start). */
23
+ function startsLine(up: string, at: number): boolean {
24
+ for (let index = at - 1; index >= 0; index -= 1) {
25
+ if (up[index] === '\n') return true;
26
+ if (up[index] !== ' ' && up[index] !== '\t') return false;
27
+ }
28
+ return true;
29
+ }
30
+
31
+ /**
32
+ * Whether the line directly above the statement's first SQL line is the marker, as a line of its
33
+ * own (`hasMarkerLine`). `at` is where the trimmed `statement` starts in `up`: a marker that is the
34
+ * statement's first line must start its line there too, or it trails the previous statement.
35
+ */
36
+ function markedAbove(up: string, statement: string, at: number): boolean {
37
+ const lines = (LEADING_NOISE.exec(statement)?.[0] ?? '').split('\n');
38
+ // The SQL must open its own line: `*/ create …` puts the line above inside the comment.
39
+ if (lines.length < 2 || (lines.at(-1) ?? '').trim() !== '') return false;
40
+ const above = lines.length - 2;
41
+ if (above === 0 && !startsLine(up, at)) return false;
42
+ return hasMarkerLine(`${lines[above] ?? ''}\n`, LOCK_HEAVY_COMMENT);
43
+ }
44
+
45
+ /**
46
+ * The migration id the rail judges after, exclusive: the release that shipped it. An applied
47
+ * migration cannot gain a marker (its checksum covers it), so judging history would turn an
48
+ * existing app red with no fix but rewriting it. The comparison `rollingSince` makes, with the
49
+ * bound fixed by the framework rather than opted into, since every app's next file can comply.
50
+ */
51
+ export const LOCK_HEAVY_SINCE = '20261113000000';
52
+
53
+ export const lockHeavyJudged = (id: string): boolean => id > LOCK_HEAVY_SINCE;
54
+
55
+ /** The closed list. Every other lock is either the generator's or too rare to earn a parser. */
56
+ export type LockHeavyKind = 'set-not-null' | 'create-index';
57
+
58
+ export interface LockHeavyStatement {
59
+ readonly kind: LockHeavyKind;
60
+ readonly table: string;
61
+ /** The column `set not null` names; `null` for an index build. */
62
+ readonly column: string | null;
63
+ /** The statement as written, on one line. */
64
+ readonly statement: string;
65
+ }
66
+
67
+ /**
68
+ * `create [temp|temporary|unlogged|materialized] table|view [if not exists] [schema.]t`: the
69
+ * relation no reader has yet, or none. A materialized view is here because `generate-view.ts`
70
+ * rebuilds one by drop + create and indexes it in the same file.
71
+ */
72
+ function createdTable(tokens: readonly string[]): string | undefined {
73
+ if (!isWord(tokens[0], 'create')) return undefined;
74
+ let at = 1;
75
+ if (['temp', 'temporary', 'unlogged'].some((word) => isWord(tokens[at], word))) at += 1;
76
+ if (isWord(tokens[at], 'materialized') && isWord(tokens[at + 1], 'view')) at += 1;
77
+ else if (!isWord(tokens[at], 'table')) return undefined;
78
+ at += 1;
79
+ if (isWord(tokens[at], 'if') && isWord(tokens[at + 1], 'not') && isWord(tokens[at + 2], 'exists'))
80
+ at += 3;
81
+ return qualifiedNameAt(tokens, at)?.name;
82
+ }
83
+
84
+ /**
85
+ * `create [unique] index …` without `concurrently` and not `on only`: the table it locks. `on only`
86
+ * builds an invalid index on a partitioned parent's own (empty) relation, the first of the
87
+ * concurrent partitioned form, so it scans nothing.
88
+ */
89
+ function blockingIndexTable(tokens: readonly string[]): string | undefined {
90
+ if (!isWord(tokens[0], 'create')) return undefined;
91
+ const at = isWord(tokens[1], 'unique') ? 2 : 1;
92
+ if (!isWord(tokens[at], 'index') || isWord(tokens[at + 1], 'concurrently')) return undefined;
93
+ const on = tokens.findIndex((token, index) => index > at && isWord(token, 'on'));
94
+ if (on < 0 || isWord(tokens[on + 1], 'only')) return undefined;
95
+ return qualifiedNameAt(tokens, on + 1)?.name;
96
+ }
97
+
98
+ /** `alter [column] c set not null`: the column, or none. */
99
+ function setNotNullColumn(part: readonly string[]): string | undefined {
100
+ if (!isWord(part[0], 'alter')) return undefined;
101
+ const at = isWord(part[1], 'column') ? 2 : 1;
102
+ const [name, set, not, nul] = part.slice(at, at + 4);
103
+ if (name === undefined || !isWord(set, 'set') || !isWord(not, 'not') || !isWord(nul, 'null'))
104
+ return undefined;
105
+ return nameOf(name);
106
+ }
107
+
108
+ /**
109
+ * Every statement in `up` that scans a table it did not create under a lock that stops writes, in
110
+ * apply order. A table created earlier in the same `up` has no rows yet. A `validate constraint` on
111
+ * the table earlier in the same `up` is the two-step form's second half: Postgres 12+ proves NOT
112
+ * NULL from a validated `check (c is not null)` and skips the scan. A statement with the marker on
113
+ * the line directly above it is admitted — that statement only, never the file.
114
+ */
115
+ export function lockHeavyStatements(up: string): readonly LockHeavyStatement[] {
116
+ const found: LockHeavyStatement[] = [];
117
+ const created = new Set<string>();
118
+ const validated = new Set<string>();
119
+ let cursor = 0;
120
+ for (const statement of statementsOf(up)) {
121
+ const at = up.indexOf(statement, cursor);
122
+ cursor = at < 0 ? cursor : at + statement.length;
123
+ const admitted = at >= 0 && markedAbove(up, statement, at);
124
+ const tokens = tokensOf(statement);
125
+ const table = createdTable(tokens);
126
+ if (table !== undefined) created.add(table);
127
+ const indexed = blockingIndexTable(tokens);
128
+ if (indexed !== undefined && !created.has(indexed) && !admitted) {
129
+ found.push({
130
+ kind: 'create-index',
131
+ table: indexed,
132
+ column: null,
133
+ statement: statementExcerpt(statement),
134
+ });
135
+ }
136
+ const altered = alteredTable(tokens);
137
+ if (altered === undefined) continue;
138
+ for (const part of subcommands(tokens.slice(altered.next))) {
139
+ if (isWord(part[0], 'validate')) validated.add(altered.table);
140
+ const column = setNotNullColumn(part);
141
+ if (
142
+ column === undefined ||
143
+ admitted ||
144
+ created.has(altered.table) ||
145
+ validated.has(altered.table)
146
+ )
147
+ continue;
148
+ found.push({
149
+ kind: 'set-not-null',
150
+ table: altered.table,
151
+ column,
152
+ statement: statementExcerpt(statement),
153
+ });
154
+ }
155
+ }
156
+ return found;
157
+ }
158
+
159
+ const STATED: Readonly<Record<LockHeavyKind, string>> = {
160
+ 'set-not-null': 'sets a column not null with no validated check before it',
161
+ 'create-index': 'builds an index without concurrently',
162
+ };
163
+
164
+ /** The two-step form for the kind, then the marker for a lock that is deliberate. */
165
+ function twoSteps(first: LockHeavyStatement): string {
166
+ const table = renderFixShellArg(first.table, '<table>');
167
+ if (first.kind === 'create-index')
168
+ return `create index concurrently … on "${table}" (…); # in a migration of its own whose first line is "${NO_TRANSACTION_MARKER}" — x db gen writes it so for an index whose entity does not say concurrently: false`;
169
+ const column = renderFixShellArg(first.column ?? '<column>', '<column>');
170
+ const check = `${table}_${column}_not_null`;
171
+ return (
172
+ `alter table "${table}" add constraint "${check}" check ("${column}" is not null) not valid; # ` +
173
+ `deploy, then a new migration: alter table "${table}" validate constraint "${check}"; alter table "${table}" alter column "${column}" set not null; alter table "${table}" drop constraint "${check}";`
174
+ );
175
+ }
176
+
177
+ /** The gate's finding over a committed file. One per migration, as `migrationRollingUnsafe` is. */
178
+ export const migrationLockHeavy = (file: string, first: LockHeavyStatement, more = 0): DbError =>
179
+ new DbError({
180
+ code: 'X_MIGRATION_LOCK_HEAVY',
181
+ cause: `${file} ${STATED[first.kind]}, so "${first.table}" stops taking writes for a full scan${more === 0 ? '' : ` (and ${more} more)`}: ${first.statement}`,
182
+ fix: `${twoSteps(first)} — a deliberate one: add the line "${LOCK_HEAVY_MARKER}" directly above that statement in ${file} before it is applied — it admits that statement only`,
183
+ meta: { file, kind: first.kind, table: first.table, column: first.column },
184
+ });
@@ -0,0 +1,154 @@
1
+ // Single responsibility: which of the few statements that move a pin's `statement_timeout` a text
2
+ // is — a transaction end, a savepoint verb, a RESET, a SET or a `set_config` — read from its
3
+ // leading words in ONE linear pass. Statement text is library input: no backtracking regex reads
4
+ // it, and a long statement stops being read after `PIN_WORDS_MAX` words.
5
+
6
+ /** More words than any statement recognised here has, so a bulk INSERT is dropped after a dozen. */
7
+ export const PIN_WORDS_MAX = 12;
8
+
9
+ export type PinStatement =
10
+ | { readonly kind: 'end' }
11
+ | { readonly kind: 'savepoint' | 'rollback-to' | 'release'; readonly name: string }
12
+ | { readonly kind: 'role-bound' }
13
+ | { readonly kind: 'set'; readonly value: string };
14
+
15
+ const PUNCTUATION = '=(),;';
16
+
17
+ function isSpace(code: number): boolean {
18
+ return code === 32 || (code >= 9 && code <= 13);
19
+ }
20
+
21
+ /** The index just past the quote closing the one at `start` (`''`/`""` escape it), or -1. */
22
+ function quotedEnd(text: string, start: number, quote: string): number {
23
+ let at = start + 1;
24
+ while (at < text.length) {
25
+ if (text[at] !== quote) at += 1;
26
+ else if (text[at + 1] === quote) at += 2;
27
+ else return at + 1;
28
+ }
29
+ return -1;
30
+ }
31
+
32
+ /**
33
+ * The words of `text`: a quoted identifier or literal whole, each of `= ( ) , ;` alone, any other
34
+ * run of non-space characters as one. One trailing `;` dropped. `undefined` past `PIN_WORDS_MAX`
35
+ * words or at an unterminated quote: neither is a statement this file recognises.
36
+ */
37
+ export function pinWords(text: string): readonly string[] | undefined {
38
+ const words: string[] = [];
39
+ let at = 0;
40
+ for (;;) {
41
+ while (at < text.length && isSpace(text.charCodeAt(at))) at += 1;
42
+ if (at >= text.length) break;
43
+ if (words.length === PIN_WORDS_MAX) return undefined;
44
+ const char = text[at] ?? '';
45
+ let end = at + 1;
46
+ if (char === '"' || char === "'") {
47
+ end = quotedEnd(text, at, char);
48
+ if (end === -1) return undefined;
49
+ } else if (!PUNCTUATION.includes(char)) {
50
+ while (end < text.length && !isSpace(text.charCodeAt(end))) {
51
+ const next = text[end] ?? '';
52
+ if (PUNCTUATION.includes(next) || next === '"' || next === "'") break;
53
+ end += 1;
54
+ }
55
+ }
56
+ words.push(text.slice(at, end));
57
+ at = end;
58
+ }
59
+ if (words.at(-1) === ';') words.pop();
60
+ return words;
61
+ }
62
+
63
+ const UNQUOTED_NAME = /^[a-z_][\w$]*$/i;
64
+
65
+ /** A savepoint name as the server compares it: unquoted folds to lower case, quoted is exact. */
66
+ function nameOf(word: string | undefined): string | undefined {
67
+ if (word === undefined) return undefined;
68
+ if (word.startsWith('"'))
69
+ return word.length > 2 ? word.slice(1, -1).replaceAll('""', '"') : undefined;
70
+ return UNQUOTED_NAME.test(word) ? word.toLowerCase() : undefined;
71
+ }
72
+
73
+ /** `[savepoint] name` as the last one or two words from `from`. */
74
+ function savepointAt(
75
+ words: readonly string[],
76
+ from: number,
77
+ optional: boolean,
78
+ ): string | undefined {
79
+ const at = optional && words[from]?.toLowerCase() === 'savepoint' ? from + 1 : from;
80
+ return at === words.length - 1 ? nameOf(words[at]) : undefined;
81
+ }
82
+
83
+ /** `rollback [work|transaction] to [savepoint] name`, or a bare transaction end. */
84
+ function rollbackOf(words: readonly string[]): PinStatement | undefined {
85
+ const at = ['work', 'transaction'].includes(words[1]?.toLowerCase() ?? '') ? 2 : 1;
86
+ if (at === words.length) return { kind: 'end' };
87
+ if (words[at]?.toLowerCase() !== 'to') return undefined;
88
+ const name = savepointAt(words, at + 1, true);
89
+ return name === undefined ? undefined : { kind: 'rollback-to', name };
90
+ }
91
+
92
+ /** `set [local|session] statement_timeout {=|to} value` — `default` is the role's. */
93
+ function setOf(words: readonly string[]): PinStatement | undefined {
94
+ const at = ['local', 'session'].includes(words[1]?.toLowerCase() ?? '') ? 2 : 1;
95
+ if (words[at]?.toLowerCase() !== 'statement_timeout' || words.length !== at + 3) return undefined;
96
+ if (!['=', 'to'].includes(words[at + 1]?.toLowerCase() ?? '')) return undefined;
97
+ const value = words[at + 2] ?? '';
98
+ return value.toLowerCase() === 'default' ? { kind: 'role-bound' } : { kind: 'set', value };
99
+ }
100
+
101
+ /** `select set_config('statement_timeout', 'value', true|false)`. */
102
+ function setConfigOf(words: readonly string[]): PinStatement | undefined {
103
+ const [, fn, open, key, , value, , local, close] = words;
104
+ const shape =
105
+ words.length === 9 &&
106
+ fn?.toLowerCase() === 'set_config' &&
107
+ open === '(' &&
108
+ key?.toLowerCase() === "'statement_timeout'" &&
109
+ words[4] === ',' &&
110
+ words[6] === ',' &&
111
+ ['true', 'false'].includes(local?.toLowerCase() ?? '') &&
112
+ close === ')' &&
113
+ value?.startsWith("'") === true;
114
+ return shape
115
+ ? { kind: 'set', value: (value ?? '').slice(1, -1).replaceAll("''", "'") }
116
+ : undefined;
117
+ }
118
+
119
+ export function pinStatement(text: string): PinStatement | undefined {
120
+ const words = pinWords(text);
121
+ if (words === undefined) return undefined;
122
+ const verb = words[0]?.toLowerCase();
123
+ switch (verb) {
124
+ case 'commit':
125
+ case 'end':
126
+ case 'abort': {
127
+ const tail = words[1]?.toLowerCase();
128
+ const bare =
129
+ words.length === 1 || (words.length === 2 && ['work', 'transaction'].includes(tail ?? ''));
130
+ return bare ? { kind: 'end' } : undefined;
131
+ }
132
+ case 'rollback':
133
+ return rollbackOf(words);
134
+ case 'savepoint': {
135
+ const name = savepointAt(words, 1, false);
136
+ return name === undefined ? undefined : { kind: 'savepoint', name };
137
+ }
138
+ case 'release': {
139
+ const name = savepointAt(words, 1, true);
140
+ return name === undefined ? undefined : { kind: 'release', name };
141
+ }
142
+ case 'reset': {
143
+ const what = words[1]?.toLowerCase();
144
+ const known = words.length === 2 && (what === 'statement_timeout' || what === 'all');
145
+ return known ? { kind: 'role-bound' } : undefined;
146
+ }
147
+ case 'set':
148
+ return setOf(words);
149
+ case 'select':
150
+ return setConfigOf(words);
151
+ default:
152
+ return undefined;
153
+ }
154
+ }
package/src/pool-gate.ts CHANGED
@@ -2,19 +2,29 @@
2
2
  // next one waits. `Bun.SQL` queues past `max` with no bound and publishes no occupancy, so this counts
3
3
  // in front of it: a statement and a pin each hold one slot, and a full pool refuses on one deadline.
4
4
 
5
- import type { Scheduler } from '@ultimat3/core';
5
+ import { isUltimateError, type Scheduler, throwIfAborted, tryUseContext } from '@ultimat3/core';
6
6
  import { type DbError, poolAcquireTimeout } from './errors';
7
7
  import type { PoolDemand } from './pool-gauge';
8
8
  import { unrefSchedule } from './pool-timer';
9
+ import { statementVerb } from './statement-shape';
10
+
11
+ /**
12
+ * How a queued waiter leaves early: when `signal` aborts, `reason()` is what it is refused with, or
13
+ * `undefined` to keep its place. Asked only once the waiter actually queues.
14
+ */
15
+ export interface QueueExit {
16
+ readonly signal: AbortSignal;
17
+ reason(): unknown;
18
+ }
9
19
 
10
20
  export interface PoolGate {
11
21
  /**
12
22
  * Take a slot. `undefined` when one was free, so the path that never waits pays no promise and
13
23
  * sends in the caller's own turn. Otherwise resolves `true` when the slot arrives, `false` when
14
- * this pool retired first, and rejects past `acquireTimeoutMs` (`X_DB_POOL_EXHAUSTED`). `0` waits
15
- * forever.
24
+ * this pool retired first, and rejects past `acquireTimeoutMs` (`X_DB_POOL_EXHAUSTED`) or with
25
+ * `exit`'s reason when its signal aborts first. `0` waits forever.
16
26
  */
17
- enter(acquireTimeoutMs: number): Promise<boolean> | undefined;
27
+ enter(acquireTimeoutMs: number, exit?: () => QueueExit | undefined): Promise<boolean> | undefined;
18
28
  /** Give a slot back. The oldest waiter inherits it, so a newcomer never overtakes the queue. */
19
29
  leave(): void;
20
30
  /** This pool is gone but the database may not be: everyone queued asks the next pool. */
@@ -29,19 +39,48 @@ export interface GatedPool {
29
39
  readonly demand: PoolDemand;
30
40
  }
31
41
 
42
+ /**
43
+ * Whether the scope's abort takes a queued waiter out — the rule `statement-cancel.ts` applies to a
44
+ * statement in flight, applied before it is sent. A coded reason (a deadline, a job's cancel) is
45
+ * somebody answered: any waiter leaves with that very error. An uncoded hang-up takes out a pooled
46
+ * `select` only, as core's `X_ABORTED`: a write or a pin keeps its place, since a click followed by a navigation must
47
+ * keep landing (`abandonment()`). A scope already aborted when it asks is not watched at all.
48
+ */
49
+ function scopeExit(statement: string | undefined): QueueExit | undefined {
50
+ const ctx = tryUseContext();
51
+ if (ctx === undefined || ctx.signal.aborted) return undefined;
52
+ const { signal } = ctx;
53
+ return {
54
+ signal,
55
+ reason() {
56
+ if (isUltimateError(signal.reason)) return signal.reason;
57
+ if (statement === undefined || statementVerb(statement) !== 'select') return undefined;
58
+ try {
59
+ throwIfAborted(ctx);
60
+ } catch (aborted) {
61
+ return aborted;
62
+ }
63
+ return undefined;
64
+ },
65
+ };
66
+ }
67
+
32
68
  /**
33
69
  * A slot on the current pool, counted from the ask: a statement queued behind a full pool is exactly
34
70
  * what `db_pool_waiting` reports. Answers the pool itself when a slot was free, so a caller checking
35
71
  * `instanceof Promise` sends in its own turn. A retirement during the wait re-asks the pool that
36
72
  * replaced it, with a fresh deadline: the work was never sent, so it can only be late, never doubled.
73
+ * `statement` is a pooled statement's text, `undefined` for a pin: its verb and the scope are read
74
+ * only once it queues, so the path that never waits pays neither (`scopeExit`).
37
75
  */
38
76
  export function takeSlot<P extends GatedPool>(
39
77
  connect: () => P,
40
78
  acquireTimeoutMs: number,
79
+ statement: string | undefined,
41
80
  ): P | Promise<P> {
42
81
  const asked = connect();
43
82
  asked.demand.enter();
44
- const wait = asked.gate.enter(acquireTimeoutMs);
83
+ const wait = asked.gate.enter(acquireTimeoutMs, () => scopeExit(statement));
45
84
  if (wait === undefined) return asked;
46
85
  return (async () => {
47
86
  let admitted: boolean;
@@ -53,7 +92,7 @@ export function takeSlot<P extends GatedPool>(
53
92
  }
54
93
  if (admitted) return asked;
55
94
  asked.demand.leave();
56
- return takeSlot(connect, acquireTimeoutMs);
95
+ return takeSlot(connect, acquireTimeoutMs, statement);
57
96
  })();
58
97
  }
59
98
 
@@ -65,7 +104,8 @@ export function freeSlot(pool: GatedPool): void {
65
104
 
66
105
  interface Waiter {
67
106
  readonly settle: (admitted: boolean) => void;
68
- readonly refuse: (reason: DbError) => void;
107
+ readonly refuse: (reason: unknown) => void;
108
+ /** Drops the deadline and the abort listener: called on every way out of the queue. */
69
109
  disarm: () => void;
70
110
  }
71
111
 
@@ -75,7 +115,7 @@ export function poolGate(max: number, schedule: Scheduler = unrefSchedule): Pool
75
115
  const waiting = new Set<Waiter>();
76
116
 
77
117
  return {
78
- enter(acquireTimeoutMs) {
118
+ enter(acquireTimeoutMs, exit) {
79
119
  // `leave` hands a slot over rather than freeing it, so a free slot means nobody is queued.
80
120
  if (out < max) {
81
121
  out += 1;
@@ -84,11 +124,26 @@ export function poolGate(max: number, schedule: Scheduler = unrefSchedule): Pool
84
124
  return new Promise<boolean>((settle, refuse) => {
85
125
  const waiter: Waiter = { settle, refuse, disarm: () => undefined };
86
126
  waiting.add(waiter);
87
- if (acquireTimeoutMs <= 0) return;
88
- waiter.disarm = schedule(() => {
89
- waiting.delete(waiter);
90
- refuse(poolAcquireTimeout(acquireTimeoutMs, max));
91
- }, acquireTimeoutMs);
127
+ const disarmTimer =
128
+ acquireTimeoutMs <= 0
129
+ ? undefined
130
+ : schedule(() => {
131
+ waiting.delete(waiter);
132
+ waiter.disarm();
133
+ refuse(poolAcquireTimeout(acquireTimeoutMs, max));
134
+ }, acquireTimeoutMs);
135
+ const leaving = exit?.();
136
+ const onAbort = (): void => {
137
+ const reason = leaving?.reason();
138
+ if (reason === undefined || !waiting.delete(waiter)) return;
139
+ waiter.disarm();
140
+ refuse(reason);
141
+ };
142
+ leaving?.signal.addEventListener('abort', onAbort, { once: true });
143
+ waiter.disarm = () => {
144
+ disarmTimer?.();
145
+ leaving?.signal.removeEventListener('abort', onAbort);
146
+ };
92
147
  });
93
148
  },
94
149
  leave() {