cursedbelt-server 4.62.0 → 4.63.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.
@@ -13,6 +13,15 @@
13
13
  * below, which is the subset of Cloudflare's `D1Database` this driver actually calls — so
14
14
  * a real binding satisfies it without a cast, and the test suite can satisfy it with a
15
15
  * fake that has no `workerd` in sight.
16
+ *
17
+ * 🔴 **Every statement is timed here, the one seam each Worker's D1 passes through.** One that
18
+ * takes {@link D1_SLOW_MS} or more, or dies of D1's own failure (a reset for CPU, an overload),
19
+ * is reported as a `d1.slow` / `d1.failed` line ({@link D1StatementReport}) — an object, so
20
+ * Workers Logs indexes its fields. A statement past D1's 30-second CPU limit RESETS the database
21
+ * and fails every request in flight with it, and its own request can still end "ok": photos lost
22
+ * its timeline that way three times on 2026-11-06 before anyone could say which statement it was
23
+ * (forge task 4554). The line names it: its SQL (never its binds), wall time, D1's own duration
24
+ * and rows read.
16
25
  */
17
26
  import { type D1LikeDatabase } from './types.js';
18
27
  /** What D1 reports back about a statement. Its `meta` is richer than the local driver's. */
@@ -24,6 +33,30 @@ export interface D1BindingMeta {
24
33
  rows_written?: number;
25
34
  served_by?: string;
26
35
  }
36
+ /** What is reported about a statement that ran long or died of D1's own failure. Never its binds. */
37
+ export interface D1StatementReport {
38
+ event: 'd1.slow' | 'd1.failed';
39
+ /** Wall time from the call to its answer, in ms — queueing and the wire included. */
40
+ ms: number;
41
+ /** The statement, cut to {@link REPORTED_SQL_CHARS}; a batch's members joined by ` ;; `. */
42
+ sql: string;
43
+ /** D1's own execution time (`meta.duration`), when it answered. */
44
+ durationMs?: number;
45
+ rowsRead?: number;
46
+ rowsWritten?: number;
47
+ /** `d1.failed`: D1's message. */
48
+ error?: string;
49
+ }
50
+ export interface RemoteD1Options {
51
+ /** At or above this many ms (wall, or D1's own duration) a statement is reported. Default {@link D1_SLOW_MS}. */
52
+ slowMs?: number;
53
+ /** Where a report goes. Default `console.warn(report)`, which Workers Logs keeps as fields. */
54
+ report?: (report: D1StatementReport) => void;
55
+ /** The clock. Default `Date.now` — on a Worker it advances across the I/O a statement is. */
56
+ now?: () => number;
57
+ }
58
+ /** A second is slow for one statement: the reads this fleet is built on answer in tens of ms. */
59
+ export declare const D1_SLOW_MS = 1000;
27
60
  export interface D1BindingResult {
28
61
  results?: unknown[];
29
62
  success?: boolean;
@@ -52,8 +85,8 @@ export interface D1BindingLike {
52
85
  *
53
86
  * On a Worker this is constructed per request from `env.DB` — a binding is not a
54
87
  * connection and holds no state worth caching, so there is nothing to pool and nothing to
55
- * close.
88
+ * close. `options` tunes what a slow statement is and where its report goes (see the file's head).
56
89
  */
57
- export declare function createRemoteD1(binding: D1BindingLike): D1LikeDatabase;
90
+ export declare function createRemoteD1(binding: D1BindingLike, options?: RemoteD1Options): D1LikeDatabase;
58
91
  /** Re-exported so both drivers refuse an interactive transaction with one message. */
59
92
  export declare const refuseInteractiveTransaction: () => never;
@@ -13,10 +13,66 @@
13
13
  * below, which is the subset of Cloudflare's `D1Database` this driver actually calls — so
14
14
  * a real binding satisfies it without a cast, and the test suite can satisfy it with a
15
15
  * fake that has no `workerd` in sight.
16
+ *
17
+ * 🔴 **Every statement is timed here, the one seam each Worker's D1 passes through.** One that
18
+ * takes {@link D1_SLOW_MS} or more, or dies of D1's own failure (a reset for CPU, an overload),
19
+ * is reported as a `d1.slow` / `d1.failed` line ({@link D1StatementReport}) — an object, so
20
+ * Workers Logs indexes its fields. A statement past D1's 30-second CPU limit RESETS the database
21
+ * and fails every request in flight with it, and its own request can still end "ok": photos lost
22
+ * its timeline that way three times on 2026-11-06 before anyone could say which statement it was
23
+ * (forge task 4554). The line names it: its SQL (never its binds), wall time, D1's own duration
24
+ * and rows read.
16
25
  */
17
26
  import { assertBatchSize, assertCompoundSelectTerms, assertWithinLimits } from './limits.js';
18
27
  import { D1UnsupportedError, } from './types.js';
19
28
  import { makeMeta, normalizeBinds, normalizeRows, normalizeValue } from './values.js';
29
+ /** A second is slow for one statement: the reads this fleet is built on answer in tens of ms. */
30
+ export const D1_SLOW_MS = 1000;
31
+ const REPORTED_SQL_CHARS = 400;
32
+ /** D1's OWN failures — the database, not the statement: reset for CPU, overloaded, queued too long. */
33
+ const D1_OWN_FAILURE = /D1 DB|D1_RESET|exceeded its CPU time|overloaded/i;
34
+ /** Run one call to D1, reporting it when it is slow or D1 itself failed. The answer and any error pass through untouched. */
35
+ async function timed(timing, sql, call, metaOf = () => []) {
36
+ const start = timing.now();
37
+ const text = sql.length > REPORTED_SQL_CHARS ? `${sql.slice(0, REPORTED_SQL_CHARS)}…` : sql;
38
+ let answer;
39
+ try {
40
+ answer = await call();
41
+ }
42
+ catch (error) {
43
+ const ms = timing.now() - start;
44
+ const message = error instanceof Error ? error.message : String(error);
45
+ if (ms >= timing.slowMs || D1_OWN_FAILURE.test(message))
46
+ safely(timing, { event: 'd1.failed', ms, sql: text, error: message.slice(0, 300) });
47
+ throw error;
48
+ }
49
+ const ms = timing.now() - start;
50
+ const metas = metaOf(answer).filter((m) => m !== undefined);
51
+ const sum = (k) => (metas.some((m) => typeof m[k] === 'number') ? metas.reduce((n, m) => n + (m[k] ?? 0), 0) : undefined);
52
+ const durationMs = sum('duration');
53
+ if (ms >= timing.slowMs || (durationMs ?? 0) >= timing.slowMs) {
54
+ const report = { event: 'd1.slow', ms, sql: text };
55
+ if (durationMs !== undefined)
56
+ report.durationMs = durationMs;
57
+ const rowsRead = sum('rows_read');
58
+ const rowsWritten = sum('rows_written');
59
+ if (rowsRead !== undefined)
60
+ report.rowsRead = rowsRead;
61
+ if (rowsWritten !== undefined)
62
+ report.rowsWritten = rowsWritten;
63
+ safely(timing, report);
64
+ }
65
+ return answer;
66
+ }
67
+ /** A reporter that throws must never fail the statement it reports on. */
68
+ function safely(timing, report) {
69
+ try {
70
+ timing.report(report);
71
+ }
72
+ catch {
73
+ // The statement's own answer matters more than its telemetry line.
74
+ }
75
+ }
20
76
  /**
21
77
  * D1 reports a failed statement by RESOLVING with `success: false` in some paths rather
22
78
  * than rejecting, so a driver that only catches rejections reports a silent no-op as a
@@ -37,9 +93,11 @@ const toMeta = (res) => makeMeta({
37
93
  class RemoteStatement {
38
94
  stmt;
39
95
  sql;
40
- constructor(stmt, sql) {
96
+ timing;
97
+ constructor(stmt, sql, timing) {
41
98
  this.stmt = stmt;
42
99
  this.sql = sql;
100
+ this.timing = timing;
43
101
  }
44
102
  /** The underlying binding statement — how `batch()` reaches the real objects. */
45
103
  get binding() {
@@ -51,10 +109,10 @@ class RemoteStatement {
51
109
  // D1 accepts ArrayBuffer for BLOBs; `normalizeBind` has already reduced every blob
52
110
  // to a `Uint8Array`, so this is the one place that converts back out.
53
111
  const wire = params.map((p) => (p instanceof Uint8Array ? p.buffer.slice(p.byteOffset, p.byteOffset + p.byteLength) : p));
54
- return new RemoteStatement(this.stmt.bind(...wire), this.sql);
112
+ return new RemoteStatement(this.stmt.bind(...wire), this.sql, this.timing);
55
113
  }
56
114
  async first(column) {
57
- const row = await this.stmt.first(column);
115
+ const row = await timed(this.timing, this.sql, () => this.stmt.first(column));
58
116
  if (row === null || row === undefined)
59
117
  return null;
60
118
  if (column !== undefined)
@@ -62,7 +120,7 @@ class RemoteStatement {
62
120
  return normalizeRows([row])[0] ?? null;
63
121
  }
64
122
  async all() {
65
- const res = await this.stmt.all();
123
+ const res = await timed(this.timing, this.sql, () => this.stmt.all(), (r) => [r.meta]);
66
124
  assertSucceeded(res, this.sql);
67
125
  return {
68
126
  results: normalizeRows((res.results ?? [])),
@@ -71,12 +129,12 @@ class RemoteStatement {
71
129
  };
72
130
  }
73
131
  async run() {
74
- const res = await this.stmt.run();
132
+ const res = await timed(this.timing, this.sql, () => this.stmt.run(), (r) => [r.meta]);
75
133
  assertSucceeded(res, this.sql);
76
134
  return { results: [], success: true, meta: toMeta(res) };
77
135
  }
78
136
  async raw() {
79
- const rows = await this.stmt.raw();
137
+ const rows = await timed(this.timing, this.sql, () => this.stmt.raw());
80
138
  return rows.map((r) => r.map((v) => normalizeValue(v)));
81
139
  }
82
140
  }
@@ -85,26 +143,33 @@ class RemoteStatement {
85
143
  *
86
144
  * On a Worker this is constructed per request from `env.DB` — a binding is not a
87
145
  * connection and holds no state worth caching, so there is nothing to pool and nothing to
88
- * close.
146
+ * close. `options` tunes what a slow statement is and where its report goes (see the file's head).
89
147
  */
90
- export function createRemoteD1(binding) {
148
+ export function createRemoteD1(binding, options = {}) {
149
+ const timing = {
150
+ slowMs: options.slowMs ?? D1_SLOW_MS,
151
+ report: options.report ?? ((report) => console.warn(report)),
152
+ now: options.now ?? Date.now,
153
+ };
91
154
  return {
92
155
  flavor: 'd1',
93
156
  prepare(sql) {
94
157
  assertCompoundSelectTerms(sql);
95
- return new RemoteStatement(binding.prepare(sql), sql);
158
+ return new RemoteStatement(binding.prepare(sql), sql, timing);
96
159
  },
97
160
  async batch(statements) {
98
161
  assertBatchSize(statements.length);
162
+ const texts = [];
99
163
  const bindings = statements.map((s) => {
100
164
  const b = s.binding;
101
165
  if (!b) {
102
166
  throw new TypeError('batch() accepts only statements from this same D1 database — ' +
103
167
  'a local statement cannot run inside a D1 batch.');
104
168
  }
169
+ texts.push(s.sql);
105
170
  return b;
106
171
  });
107
- const results = await binding.batch(bindings);
172
+ const results = await timed(timing, texts.join(' ;; '), () => binding.batch(bindings), (rs) => rs.map((r) => r.meta));
108
173
  return results.map((res, i) => {
109
174
  assertSucceeded(res, `batch statement ${i + 1}`);
110
175
  return {
@@ -115,7 +180,7 @@ export function createRemoteD1(binding) {
115
180
  });
116
181
  },
117
182
  exec(sql) {
118
- return binding.exec(sql);
183
+ return timed(timing, sql, () => binding.exec(sql), (r) => [{ duration: r.duration }]);
119
184
  },
120
185
  };
121
186
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cursedbelt-server",
3
- "version": "4.62.0",
3
+ "version": "4.63.0",
4
4
  "license": "ISC",
5
5
  "type": "module",
6
6
  "description": "The app-facing Bun/Hono server tier of the cursedbelt split — storage, sharing, activity, guard, sync. React-free; cursedbelt-core below it.",
@@ -423,7 +423,7 @@
423
423
  "@node-rs/argon2": "^2.0.2",
424
424
  "@types/bun": "^1.3.14",
425
425
  "@types/node": "^24",
426
- "cursedbelt": "^5.109.0",
426
+ "cursedbelt": "^5.116.0",
427
427
  "hono": "4.12.28",
428
428
  "kysely": "^0.28.17",
429
429
  "kysely-bun-sqlite": "^0.4.0",
@@ -13,6 +13,15 @@
13
13
  * below, which is the subset of Cloudflare's `D1Database` this driver actually calls — so
14
14
  * a real binding satisfies it without a cast, and the test suite can satisfy it with a
15
15
  * fake that has no `workerd` in sight.
16
+ *
17
+ * 🔴 **Every statement is timed here, the one seam each Worker's D1 passes through.** One that
18
+ * takes {@link D1_SLOW_MS} or more, or dies of D1's own failure (a reset for CPU, an overload),
19
+ * is reported as a `d1.slow` / `d1.failed` line ({@link D1StatementReport}) — an object, so
20
+ * Workers Logs indexes its fields. A statement past D1's 30-second CPU limit RESETS the database
21
+ * and fails every request in flight with it, and its own request can still end "ok": photos lost
22
+ * its timeline that way three times on 2026-11-06 before anyone could say which statement it was
23
+ * (forge task 4554). The line names it: its SQL (never its binds), wall time, D1's own duration
24
+ * and rows read.
16
25
  */
17
26
 
18
27
  import { assertBatchSize, assertCompoundSelectTerms, assertWithinLimits } from './limits.js';
@@ -37,6 +46,80 @@ export interface D1BindingMeta {
37
46
  served_by?: string;
38
47
  }
39
48
 
49
+ /** What is reported about a statement that ran long or died of D1's own failure. Never its binds. */
50
+ export interface D1StatementReport {
51
+ event: 'd1.slow' | 'd1.failed';
52
+ /** Wall time from the call to its answer, in ms — queueing and the wire included. */
53
+ ms: number;
54
+ /** The statement, cut to {@link REPORTED_SQL_CHARS}; a batch's members joined by ` ;; `. */
55
+ sql: string;
56
+ /** D1's own execution time (`meta.duration`), when it answered. */
57
+ durationMs?: number;
58
+ rowsRead?: number;
59
+ rowsWritten?: number;
60
+ /** `d1.failed`: D1's message. */
61
+ error?: string;
62
+ }
63
+
64
+ export interface RemoteD1Options {
65
+ /** At or above this many ms (wall, or D1's own duration) a statement is reported. Default {@link D1_SLOW_MS}. */
66
+ slowMs?: number;
67
+ /** Where a report goes. Default `console.warn(report)`, which Workers Logs keeps as fields. */
68
+ report?: (report: D1StatementReport) => void;
69
+ /** The clock. Default `Date.now` — on a Worker it advances across the I/O a statement is. */
70
+ now?: () => number;
71
+ }
72
+
73
+ /** A second is slow for one statement: the reads this fleet is built on answer in tens of ms. */
74
+ export const D1_SLOW_MS = 1000;
75
+ const REPORTED_SQL_CHARS = 400;
76
+ /** D1's OWN failures — the database, not the statement: reset for CPU, overloaded, queued too long. */
77
+ const D1_OWN_FAILURE = /D1 DB|D1_RESET|exceeded its CPU time|overloaded/i;
78
+
79
+ interface Timing {
80
+ slowMs: number;
81
+ report: (report: D1StatementReport) => void;
82
+ now: () => number;
83
+ }
84
+
85
+ /** Run one call to D1, reporting it when it is slow or D1 itself failed. The answer and any error pass through untouched. */
86
+ async function timed<R>(timing: Timing, sql: string, call: () => Promise<R>, metaOf: (r: R) => (D1BindingMeta | undefined)[] = () => []): Promise<R> {
87
+ const start = timing.now();
88
+ const text = sql.length > REPORTED_SQL_CHARS ? `${sql.slice(0, REPORTED_SQL_CHARS)}…` : sql;
89
+ let answer: R;
90
+ try {
91
+ answer = await call();
92
+ } catch (error) {
93
+ const ms = timing.now() - start;
94
+ const message = error instanceof Error ? error.message : String(error);
95
+ if (ms >= timing.slowMs || D1_OWN_FAILURE.test(message)) safely(timing, { event: 'd1.failed', ms, sql: text, error: message.slice(0, 300) });
96
+ throw error;
97
+ }
98
+ const ms = timing.now() - start;
99
+ const metas = metaOf(answer).filter((m): m is D1BindingMeta => m !== undefined);
100
+ const sum = (k: 'duration' | 'rows_read' | 'rows_written') => (metas.some((m) => typeof m[k] === 'number') ? metas.reduce((n, m) => n + (m[k] ?? 0), 0) : undefined);
101
+ const durationMs = sum('duration');
102
+ if (ms >= timing.slowMs || (durationMs ?? 0) >= timing.slowMs) {
103
+ const report: D1StatementReport = { event: 'd1.slow', ms, sql: text };
104
+ if (durationMs !== undefined) report.durationMs = durationMs;
105
+ const rowsRead = sum('rows_read');
106
+ const rowsWritten = sum('rows_written');
107
+ if (rowsRead !== undefined) report.rowsRead = rowsRead;
108
+ if (rowsWritten !== undefined) report.rowsWritten = rowsWritten;
109
+ safely(timing, report);
110
+ }
111
+ return answer;
112
+ }
113
+
114
+ /** A reporter that throws must never fail the statement it reports on. */
115
+ function safely(timing: Timing, report: D1StatementReport): void {
116
+ try {
117
+ timing.report(report);
118
+ } catch {
119
+ // The statement's own answer matters more than its telemetry line.
120
+ }
121
+ }
122
+
40
123
  export interface D1BindingResult {
41
124
  results?: unknown[];
42
125
  success?: boolean;
@@ -83,7 +166,8 @@ const toMeta = (res: D1BindingResult) =>
83
166
  class RemoteStatement implements D1LikeStatement {
84
167
  constructor(
85
168
  private readonly stmt: D1BindingStatement,
86
- private readonly sql: string,
169
+ readonly sql: string,
170
+ private readonly timing: Timing,
87
171
  ) {}
88
172
 
89
173
  /** The underlying binding statement — how `batch()` reaches the real objects. */
@@ -97,18 +181,18 @@ class RemoteStatement implements D1LikeStatement {
97
181
  // D1 accepts ArrayBuffer for BLOBs; `normalizeBind` has already reduced every blob
98
182
  // to a `Uint8Array`, so this is the one place that converts back out.
99
183
  const wire = params.map((p) => (p instanceof Uint8Array ? p.buffer.slice(p.byteOffset, p.byteOffset + p.byteLength) : p));
100
- return new RemoteStatement(this.stmt.bind(...wire), this.sql);
184
+ return new RemoteStatement(this.stmt.bind(...wire), this.sql, this.timing);
101
185
  }
102
186
 
103
187
  async first<T = D1LikeRow>(column?: string): Promise<T | null> {
104
- const row = await this.stmt.first(column);
188
+ const row = await timed(this.timing, this.sql, () => this.stmt.first(column));
105
189
  if (row === null || row === undefined) return null;
106
190
  if (column !== undefined) return normalizeValue(row) as T;
107
191
  return normalizeRows<T>([row as Record<string, unknown>])[0] ?? null;
108
192
  }
109
193
 
110
194
  async all<T = D1LikeRow>(): Promise<D1LikeResult<T>> {
111
- const res = await this.stmt.all();
195
+ const res = await timed(this.timing, this.sql, () => this.stmt.all(), (r) => [r.meta]);
112
196
  assertSucceeded(res, this.sql);
113
197
  return {
114
198
  results: normalizeRows<T>((res.results ?? []) as Record<string, unknown>[]),
@@ -118,13 +202,13 @@ class RemoteStatement implements D1LikeStatement {
118
202
  }
119
203
 
120
204
  async run(): Promise<D1LikeResult<never>> {
121
- const res = await this.stmt.run();
205
+ const res = await timed(this.timing, this.sql, () => this.stmt.run(), (r) => [r.meta]);
122
206
  assertSucceeded(res, this.sql);
123
207
  return { results: [], success: true, meta: toMeta(res) };
124
208
  }
125
209
 
126
210
  async raw<V = D1LikeValue>(): Promise<V[][]> {
127
- const rows = await this.stmt.raw();
211
+ const rows = await timed(this.timing, this.sql, () => this.stmt.raw());
128
212
  return rows.map((r) => r.map((v) => normalizeValue(v) as V));
129
213
  }
130
214
  }
@@ -134,19 +218,25 @@ class RemoteStatement implements D1LikeStatement {
134
218
  *
135
219
  * On a Worker this is constructed per request from `env.DB` — a binding is not a
136
220
  * connection and holds no state worth caching, so there is nothing to pool and nothing to
137
- * close.
221
+ * close. `options` tunes what a slow statement is and where its report goes (see the file's head).
138
222
  */
139
- export function createRemoteD1(binding: D1BindingLike): D1LikeDatabase {
223
+ export function createRemoteD1(binding: D1BindingLike, options: RemoteD1Options = {}): D1LikeDatabase {
224
+ const timing: Timing = {
225
+ slowMs: options.slowMs ?? D1_SLOW_MS,
226
+ report: options.report ?? ((report) => console.warn(report)),
227
+ now: options.now ?? Date.now,
228
+ };
140
229
  return {
141
230
  flavor: 'd1',
142
231
 
143
232
  prepare(sql: string): D1LikeStatement {
144
233
  assertCompoundSelectTerms(sql);
145
- return new RemoteStatement(binding.prepare(sql), sql);
234
+ return new RemoteStatement(binding.prepare(sql), sql, timing);
146
235
  },
147
236
 
148
237
  async batch<T = D1LikeRow>(statements: D1LikeStatement[]): Promise<D1LikeResult<T>[]> {
149
238
  assertBatchSize(statements.length);
239
+ const texts: string[] = [];
150
240
  const bindings = statements.map((s) => {
151
241
  const b = (s as Partial<RemoteStatement>).binding;
152
242
  if (!b) {
@@ -155,9 +245,10 @@ export function createRemoteD1(binding: D1BindingLike): D1LikeDatabase {
155
245
  'a local statement cannot run inside a D1 batch.',
156
246
  );
157
247
  }
248
+ texts.push((s as RemoteStatement).sql);
158
249
  return b;
159
250
  });
160
- const results = await binding.batch(bindings);
251
+ const results = await timed(timing, texts.join(' ;; '), () => binding.batch(bindings), (rs) => rs.map((r) => r.meta));
161
252
  return results.map((res, i) => {
162
253
  assertSucceeded(res, `batch statement ${i + 1}`);
163
254
  return {
@@ -169,7 +260,7 @@ export function createRemoteD1(binding: D1BindingLike): D1LikeDatabase {
169
260
  },
170
261
 
171
262
  exec(sql: string): Promise<{ count: number; duration: number }> {
172
- return binding.exec(sql);
263
+ return timed(timing, sql, () => binding.exec(sql), (r) => [{ duration: r.duration }]);
173
264
  },
174
265
  };
175
266
  }
@@ -0,0 +1,108 @@
1
+ /**
2
+ * 🔴 A slow statement, or one D1 itself failed, is reported by the driver every Worker's D1 goes
3
+ * through — so the statement that resets a database is named in Workers Logs, not guessed at
4
+ * (photos, 2026-11-06, forge task 4554). A fast one, and an ordinary refusal, stay quiet.
5
+ */
6
+ import { Database } from 'bun:sqlite';
7
+ import { describe, expect, it } from 'bun:test';
8
+ import { createFakeD1Binding } from './fakeD1.js';
9
+ import { createRemoteD1, type D1BindingLike, type D1StatementReport } from './remote.js';
10
+
11
+ /** A binding whose every call takes `cost` ms of a clock the test owns, and can be made to throw. */
12
+ function slowBinding(cost: { ms: number; fail?: string; duration?: number }) {
13
+ const db = new Database(':memory:');
14
+ db.run('CREATE TABLE t (id INTEGER PRIMARY KEY, v TEXT)');
15
+ db.run("INSERT INTO t (v) VALUES ('a'), ('b')");
16
+ const real = createFakeD1Binding(db);
17
+ const clock = { now: 0 };
18
+ const step = async <R>(answer: () => Promise<R>): Promise<R> => {
19
+ clock.now += cost.ms;
20
+ if (cost.fail) throw new Error(cost.fail);
21
+ return answer();
22
+ };
23
+ const withDuration = (r: Awaited<ReturnType<ReturnType<D1BindingLike['prepare']>['all']>>) =>
24
+ cost.duration === undefined ? r : { ...r, meta: { ...r.meta, duration: cost.duration, rows_read: 2 } };
25
+ type Stmt = ReturnType<D1BindingLike['prepare']>;
26
+ const inner = new WeakMap<Stmt, Stmt>();
27
+ const wrap = (s: Stmt): Stmt => {
28
+ const w: Stmt = {
29
+ bind: (...v) => wrap(s.bind(...v)),
30
+ first: (c) => step(() => s.first(c)),
31
+ all: () => step(async () => withDuration(await s.all())),
32
+ run: () => step(async () => withDuration(await s.run())),
33
+ raw: () => step(() => s.raw()),
34
+ };
35
+ inner.set(w, s);
36
+ return w;
37
+ };
38
+ const binding: D1BindingLike = {
39
+ prepare: (sql) => wrap(real.prepare(sql)),
40
+ batch: (list) => step(() => real.batch(list.map((w) => inner.get(w) ?? w))),
41
+ exec: (sql) => step(() => real.exec(sql)),
42
+ };
43
+ const reports: D1StatementReport[] = [];
44
+ return { db: createRemoteD1(binding, { now: () => clock.now, report: (r) => reports.push(r) }), reports };
45
+ }
46
+
47
+ describe('the remote driver reports a slow or D1-failed statement', () => {
48
+ it('a fast statement says nothing', async () => {
49
+ const { db, reports } = slowBinding({ ms: 20 });
50
+ expect((await db.prepare('SELECT v FROM t WHERE id = ?').bind(1).all()).results).toEqual([{ v: 'a' }]);
51
+ expect(await db.prepare('SELECT v FROM t WHERE id = ?').bind(2).first('v')).toBe('b');
52
+ expect(reports).toEqual([]);
53
+ });
54
+
55
+ it('a statement past the threshold is reported with its SQL, never its binds, and still answers', async () => {
56
+ const { db, reports } = slowBinding({ ms: 1500, duration: 1400 });
57
+ const rows = await db.prepare('SELECT v FROM t WHERE v = ?').bind('secret-bind').all();
58
+ expect(rows.results).toEqual([]);
59
+ expect(reports).toEqual([{ event: 'd1.slow', ms: 1500, sql: 'SELECT v FROM t WHERE v = ?', durationMs: 1400, rowsRead: 2, rowsWritten: 0 }]);
60
+ expect(JSON.stringify(reports)).not.toContain('secret-bind');
61
+ });
62
+
63
+ it("D1's own duration past the threshold is reported even when the wall clock did not see it", async () => {
64
+ const { db, reports } = slowBinding({ ms: 0, duration: 2500 });
65
+ await db.prepare('SELECT v FROM t').all();
66
+ expect(reports.map((r) => [r.event, r.durationMs])).toEqual([['d1.slow', 2500]]);
67
+ });
68
+
69
+ it('a statement D1 reset for CPU is reported as failed, and the error still reaches the caller', async () => {
70
+ const fail = 'D1_ERROR: D1 DB exceeded its CPU time limit and was reset.';
71
+ const { db, reports } = slowBinding({ ms: 34_000, fail });
72
+ await expect(db.prepare('SELECT v FROM t').all()).rejects.toThrow(fail);
73
+ expect(reports).toEqual([{ event: 'd1.failed', ms: 34_000, sql: 'SELECT v FROM t', error: fail }]);
74
+ });
75
+
76
+ it('a request failed fast by a reset is reported too — the victims say when it happened', async () => {
77
+ const { db, reports } = slowBinding({ ms: 3, fail: 'D1_ERROR: D1 DB is overloaded. Too many requests queued.' });
78
+ await expect(db.prepare('UPDATE t SET v = ?').bind('x').run()).rejects.toThrow('overloaded');
79
+ expect(reports.map((r) => r.event)).toEqual(['d1.failed']);
80
+ });
81
+
82
+ it("an ordinary refusal (a constraint) is the caller's business and stays quiet", async () => {
83
+ const { db, reports } = slowBinding({ ms: 3, fail: 'D1_ERROR: UNIQUE constraint failed: t.id' });
84
+ await expect(db.prepare('INSERT INTO t (id, v) VALUES (1, ?)').bind('x').run()).rejects.toThrow('UNIQUE');
85
+ expect(reports).toEqual([]);
86
+ });
87
+
88
+ it('a slow batch is one report naming each member; a long statement is cut', async () => {
89
+ const { db, reports } = slowBinding({ ms: 1200 });
90
+ const long = `SELECT v FROM t WHERE v <> '${'x'.repeat(600)}'`;
91
+ await db.batch([db.prepare('UPDATE t SET v = ?').bind('y'), db.prepare(long)]);
92
+ expect(reports).toHaveLength(1);
93
+ expect(reports[0]?.sql.startsWith('UPDATE t SET v = ? ;; SELECT v FROM t')).toBe(true);
94
+ expect(reports[0]?.sql.length).toBe(401);
95
+ });
96
+
97
+ it('a reporter that throws never fails the statement', async () => {
98
+ const db0 = new Database(':memory:');
99
+ db0.run('CREATE TABLE t (v TEXT)');
100
+ let now = 0;
101
+ const binding = createFakeD1Binding(db0);
102
+ const db = createRemoteD1(
103
+ { ...binding, prepare: (sql) => { const s = binding.prepare(sql); return { ...s, bind: s.bind.bind(s), first: s.first.bind(s), raw: s.raw.bind(s), run: s.run.bind(s), all: async () => { now += 5000; return s.all(); } }; } },
104
+ { now: () => now, report: () => { throw new Error('the log is down'); } },
105
+ );
106
+ expect((await db.prepare('SELECT v FROM t').all()).results).toEqual([]);
107
+ });
108
+ });