@ocap/gql 1.31.7 → 1.31.9

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
@@ -28,3 +28,68 @@ const handler = createFetchHandler({ resolver, introspection: false, graphiql: f
28
28
  It enforces the same guards as `createHttpHandler` (query depth, batch size, 100kb body cap, introspection/GraphiQL
29
29
  off unless enabled). `process.env.NODE_ENV` is usually unset on Workers, so pass `introspection` / `graphiql`
30
30
  explicitly there.
31
+
32
+ ## Slow request and event loop stall logs
33
+
34
+ Both lines go to `console.warn` (the chain's `error.log`). Neither ever contains argument values or variables, and
35
+ responses are byte-identical with the logs on or off.
36
+
37
+ | Env var | Option | Default | Meaning |
38
+ |---|---|---|---|
39
+ | `GQL_SLOW_LOG_MS` | `slowLogMs` | `2000` | Log a request when `queuedMs + totalMs` reaches this many ms. `0` turns off both logs and creates no timer. |
40
+ | `GQL_STALL_LOG_MS` | `stallLogMs` | `GQL_SLOW_LOG_MS` | Log an event loop stall when the probe timer fires this many ms late (minimum 20). `0` turns off only the stall log. |
41
+ | `GQL_SQL_TIMING` | `sqlTiming` | on for Bun / Workers / Node >= 24, off for Node 22 | Per root field SQLite time (`sql*` fields) in the slow-request log, via `AsyncLocalStorage`. `1` forces it on, `0` off. See below for the cost on Node 22. |
42
+
43
+ `[gql] slow request {...}` (example values below are illustrative):
44
+
45
+ - `queuedMs`: from the adapter receiving the request until the engine started on it, body read included. Time spent
46
+ before Node hands the request to the adapter (the socket is not read while the loop is blocked) is not visible
47
+ here; the stall line covers it.
48
+ - `totalMs` = `parseMs` + `executeMs` + `serializeMs`.
49
+ - `sqlMs` / `sqlQueries`: SQLite execution time and statement count of all root fields (sum of the fields' `sqlSumMs`
50
+ / `sqlQueries`). SQLite runs on the main thread, so `sqlMs` is within `executeMs`; the rest of `executeMs` is
51
+ JavaScript (graphql-js, resolver formatting) and waiting.
52
+ - `fields.<rootField>`: `count` aliases; `wallSumMs`/`wallMaxMs` (wall time per alias; aliases of one batch run
53
+ interleaved, so the sum overlaps and can exceed `executeMs`); `sqlSumMs`/`sqlMaxMs`/`sqlQueries` (SQLite execution
54
+ time of all aliases / of the slowest alias, and statement count); `rows` (total length of the returned lists, e.g.
55
+ `transactions`); `shapes` (aliases bucketed by argument shape, at most 8 buckets plus `other`, each with `count`,
56
+ `rows`, `sqlMs`).
57
+ - SQL time is measured where the statements run (#1891): `@ocap/indexdb-sqlite` and `@ocap/statedb-sqlite` time the
58
+ synchronous part of every Kysely `executeQuery` (better-sqlite3 / bun:sqlite run the whole statement there) and add
59
+ it to the alias that issued it, found through an `AsyncLocalStorage` the handler runs each root field call in
60
+ (`@ocap/util/lib/sql-timing`). It counts statements after any number of `await`s, and never counts one statement
61
+ twice; a statement whose result several aliases share (a cache) counts for the alias that started it, and work that
62
+ outlives its field is not counted. The `sql*` fields are left out when SQL timing is off (below), when the runtime
63
+ has no `AsyncLocalStorage`, or when no SQLite backend in the process is timed: the Durable Object backend is not
64
+ (Workers freeze clocks during synchronous work).
65
+ - SQL timing on or off: `GQL_SQL_TIMING` (option `sqlTiming`) `1`/`true` forces it on, `0`/`false` off. Unset, it is
66
+ on where `AsyncLocalStorage` is cheap: Bun, Workers, Node >= 24 (AsyncContextFrame; off again with
67
+ `--no-async-context-frame`) and Node 22/23 started with `--experimental-async-context-frame`; it is **off on Node 22
68
+ by default**. There `AsyncLocalStorage` uses async_hooks: after the first request every promise in the process pays
69
+ for a hook, inside requests and outside them (the tx pipeline too). Measured on Node 22.23 + better-sqlite3 with the
70
+ production assembly, one process per setting (medians of 30): a 30-alias `listTransactions` batch 76.6 / 77.4 ms
71
+ with `GQL_SQL_TIMING=0` / `1` (SQL-bound, no visible change), but 3e5 bare `await`s outside any request 13.3 ms →
72
+ 52.5 ms (about 4x). On Node 24.15 the same numbers are 75.9 / 76.2 ms and 13.5 / 13.3 ms. Turning it on on Node 22
73
+ is a trade: accurate per-field SQL time for slower promise-heavy code everywhere in the process.
74
+ - Removed in this version: `syncSumMs`/`syncMaxMs` and the shapes' `syncMs` (1.31.8). They timed only the resolver
75
+ call up to its first `await`, but Kysely awaits its connection before every statement, so they never included the
76
+ SQL (an 11 s `listTransactions` on beta reported `syncSumMs: 2`). Use `sqlSumMs`/`sqlMaxMs`/`sqlMs` instead.
77
+ - A shape key lists the argument names present, then `size=<paging.size>` when `paging` is given and
78
+ `start=`/`end=` when `timeFilter` is given, each one of `absent`, `empty` (`""`), `null-string` (`"null"`), `null`,
79
+ `date` or `invalid`.
80
+
81
+ ```
82
+ [gql] slow request {"queuedMs":3,"totalMs":448,"parseMs":2,"executeMs":441,"serializeMs":5,"status":200,"responseChars":189199,"queryChars":38700,"operationName":null,"topLevel":30,"selections":1140,"aliases":30,"numericAliases":0,"errors":0,"sqlMs":396,"sqlQueries":75,"fields":{"listTransactions":{"count":30,"wallSumMs":6612,"wallMaxMs":440,"sqlSumMs":396,"sqlMaxMs":31,"sqlQueries":75,"rows":600,"shapes":{"accountFilter,paging,timeFilter|size=20|start=null-string|end=absent":{"count":30,"rows":600,"sqlMs":396}}}},"userAgent":"ArcWallet/5.10.9 ..."}
83
+ ```
84
+
85
+ `[gql] event loop stall {...}` is written when the probe timer (an unref'd interval, started on the first request,
86
+ never on Cloudflare Workers) fires at least `GQL_STALL_LOG_MS` late. `maxMs` is how late it fired and `windowStart`
87
+ when the stalled window began. `inFlight` (at most 20, `inFlightTotal` counts all) lists the requests in flight and
88
+ those that finished inside the window: a request whose resolvers block synchronously has always finished by the
89
+ time a timer can run, so `phase: "done"` with a large `execMs` is the usual culprit, and `phase: "reading"` entries
90
+ are requests that waited behind it. `fields` maps root field names to alias counts; names the schema does not resolve (field existence is not
91
+ validated) are summed under `unknown` and never written out.
92
+
93
+ ```
94
+ [gql] event loop stall {"maxMs":1210,"windowStart":"2026-11-18T01:06:12.104Z","thresholdMs":500,"inFlightTotal":2,"inFlight":[{"phase":"done","ageMs":1213,"execMs":1209,"operationName":null,"topLevel":30,"selections":1140,"aliases":30,"fields":{"listTransactions":30},"userAgent":"ArcWallet/5.10.9 ..."},{"phase":"reading","ageMs":2,"userAgent":"ArcWallet/5.10.9 ..."}]}
95
+ ```
package/esm/http.d.mts CHANGED
@@ -35,29 +35,107 @@ interface HttpHandlerOptions {
35
35
  maxTotalSelections?: number;
36
36
  maxAliases?: number;
37
37
  /**
38
- * Requests whose parse + execute + serialize time reaches this many ms are reported to `onSlowRequest`.
39
- * Falls back to `GQL_SLOW_LOG_MS`, then 2000. 0 disables the timing entirely.
38
+ * Requests whose queued + parse + execute + serialize time reaches this many ms are reported to `onSlowRequest`.
39
+ * Falls back to `GQL_SLOW_LOG_MS`, then 2000. 0 disables the timing entirely, the event loop stall monitor included.
40
40
  */
41
41
  slowLogMs?: number;
42
42
  /** Receives slow-request reports. Defaults to one `console.warn('[gql] slow request', json)` line. */
43
43
  onSlowRequest?: (report: SlowRequestReport) => void;
44
+ /**
45
+ * Report an event loop stall when a timer probe fires this many ms late (#1743). Falls back to `GQL_STALL_LOG_MS`,
46
+ * then to `slowLogMs`; values below 20 are raised to 20. 0 disables the monitor; so does `slowLogMs: 0`. The probe timer starts on the first request,
47
+ * is unref'd, and is never created on Cloudflare Workers (frozen clocks there make drift meaningless).
48
+ */
49
+ stallLogMs?: number;
50
+ /** Receives stall reports. Defaults to one `console.warn('[gql] event loop stall', json)` line. */
51
+ onEventLoopStall?: (report: EventLoopStallReport) => void;
52
+ /**
53
+ * Per root field SQLite time in the slow-request log (#1891; needs `AsyncLocalStorage`). Falls back to
54
+ * `GQL_SQL_TIMING` (`1`/`true` on, `0`/`false` off), then to `isCheapAsyncContextRuntime()`: on for Bun, Workers,
55
+ * Node >= 24 and Node started with `--experimental-async-context-frame`; off on older Node, where the first
56
+ * `AsyncLocalStorage#run` turns on async_hooks promise hooks for the whole process and slows every `await`.
57
+ * Ignored when `slowLogMs` is 0.
58
+ */
59
+ sqlTiming?: boolean;
60
+ }
61
+ /**
62
+ * Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
63
+ * then `size=<paging.size>` when `paging` is present and `start=`/`end=` categories when `timeFilter` is present:
64
+ * `absent`, `empty` (""), `null-string` ("null"), `null`, `date` (parses as a date) or `invalid`. No argument value
65
+ * other than the integer `paging.size` is ever part of the key.
66
+ */
67
+ interface SlowRequestShapeStat {
68
+ count: number;
69
+ /** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
70
+ rows: number;
71
+ /** SQLite execution time of the statements the aliases of this bucket ran (see `SlowRequestFieldStat.sqlSumMs`). */
72
+ sqlMs?: number;
44
73
  }
45
74
  /**
46
75
  * Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
47
76
  * awaits interleave, so a field's wall time also covers the other fields running alongside it: `wallMaxMs` is at
48
- * most `executeMs`, and `wallSumMs` can exceed it. Use `count` to see what the batch was made of and `executeMs`
49
- * for how long the event loop was busy.
77
+ * most `executeMs`, and `wallSumMs` can exceed it.
78
+ *
79
+ * `sqlSumMs` / `sqlMaxMs` / `sqlQueries` (#1891) are measured at the SQLite execution layer: every statement the
80
+ * indexdb / statedb SQLite backends execute on behalf of an alias, however many awaits before it, adds its
81
+ * synchronous execution time to that alias (attribution via `AsyncLocalStorage`). SQLite runs on the main thread
82
+ * and statements never overlap, so these do not double count: their sum over all fields (the report's `sqlMs`) stays
83
+ * within `executeMs`. A statement whose promise is shared by several aliases (a cache) counts once, for the alias
84
+ * that started it. Absent when SQL timing is off (`sqlTiming` / `GQL_SQL_TIMING`, default off on Node < 24), the runtime
85
+ * has no `AsyncLocalStorage`, or no SQLite backend in the process is timed.
50
86
  */
51
87
  interface SlowRequestFieldStat {
52
88
  count: number;
53
89
  wallSumMs: number;
54
90
  wallMaxMs: number;
91
+ /** SQLite execution time of all aliases of this field. */
92
+ sqlSumMs?: number;
93
+ /** Largest SQLite execution time of a single alias. */
94
+ sqlMaxMs?: number;
95
+ /** Statements executed by all aliases of this field. */
96
+ sqlQueries?: number;
97
+ /** Rows returned over all aliases (sum of list payload lengths). */
98
+ rows: number;
99
+ /** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
100
+ shapes: Record<string, SlowRequestShapeStat>;
101
+ }
102
+ /** One request that was in flight (or finished) during a stalled probe window. Never carries argument values. */
103
+ interface StallInFlightEntry {
104
+ /** `reading`: body not yet parsed; `running`: parse/execute/serialize; `done`: finished inside the window. */
105
+ phase: 'reading' | 'running' | 'done';
106
+ /** ms since the adapter received the request (at report time, or until it finished). */
107
+ ageMs: number;
108
+ /** ms since the engine started on it (until report time, or until it finished). */
109
+ execMs?: number;
110
+ operationName?: string | null;
111
+ topLevel?: number;
112
+ selections?: number;
113
+ aliases?: number;
114
+ /** Root field name -> number of aliases selecting it; names the schema does not resolve are summed as `unknown`. */
115
+ fields?: Record<string, number>;
116
+ userAgent?: string;
117
+ }
118
+ /** `[gql] event loop stall` report: the probe timer fired `maxMs` late in the window starting at `windowStart`. */
119
+ interface EventLoopStallReport {
120
+ maxMs: number;
121
+ windowStart: string;
122
+ thresholdMs: number;
123
+ inFlightTotal: number;
124
+ /** In-flight requests plus the ones that finished inside the window (the likely culprit), at most 20. */
125
+ inFlight: StallInFlightEntry[];
55
126
  }
56
127
  /**
57
128
  * Shape-only description of a slow request. Never carries argument values or variables: addresses
58
129
  * and other inputs stay in the access log, which already records the client and time.
59
130
  */
60
131
  interface SlowRequestReport {
132
+ /**
133
+ * ms from the adapter receiving the request until the engine started on it, body read included. Time a request
134
+ * spends before Node hands it to the adapter (socket not read while the loop is blocked) is not visible here;
135
+ * the stall line covers it.
136
+ */
137
+ queuedMs: number;
138
+ /** parse + execute + serialize; the request is logged when `queuedMs + totalMs >= slowLogMs`. */
61
139
  totalMs: number;
62
140
  parseMs: number;
63
141
  executeMs: number;
@@ -71,9 +149,36 @@ interface SlowRequestReport {
71
149
  aliases: number;
72
150
  numericAliases: number;
73
151
  errors: number;
152
+ /**
153
+ * SQLite execution time of all root fields (sum of `fields.*.sqlSumMs`), within `executeMs`; the rest of
154
+ * `executeMs` is JavaScript (graphql-js, resolver formatting) and waiting. Absent like the fields' `sql*`.
155
+ */
156
+ sqlMs?: number;
157
+ /** Statements executed by all root fields. */
158
+ sqlQueries?: number;
74
159
  fields: Record<string, SlowRequestFieldStat>;
75
160
  userAgent?: string;
76
161
  }
162
+ /** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
163
+ declare const SQL_TIMING_KEY: unique symbol;
164
+ /** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
165
+ declare const SQL_TIMING_BACKEND_KEY: unique symbol;
166
+ interface AsyncContextRuntime {
167
+ bun?: boolean;
168
+ workers?: boolean;
169
+ /** `process.versions.node` */
170
+ nodeVersion?: string;
171
+ execArgv?: readonly string[];
172
+ /** `NODE_OPTIONS` */
173
+ nodeOptions?: string;
174
+ }
175
+ /**
176
+ * Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
177
+ * after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
178
+ * loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
179
+ * Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
180
+ */
181
+ declare const isCheapAsyncContextRuntime: (rt?: AsyncContextRuntime) => boolean;
77
182
  /**
78
183
  * Transport-agnostic view of an incoming GraphQL request, so the same engine serves express (`createHttpHandler`)
79
184
  * and fetch-native runtimes such as Cloudflare Workers (`createFetchHandler`).
@@ -88,6 +193,8 @@ interface GqlRequestLike {
88
193
  body?: unknown;
89
194
  /** Read the raw body as utf-8, rejecting with `status: 413` above `limit` bytes. */
90
195
  readBody: (limit: number) => Promise<string>;
196
+ /** `performance.now()` when the adapter received the request; defaults to the engine's own start. */
197
+ receivedAt?: number;
91
198
  }
92
199
  /** Transport-agnostic response produced by the engine. */
93
200
  interface GqlResponseLike {
@@ -115,4 +222,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
115
222
  */
116
223
  declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
117
224
  //#endregion
118
- export { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
225
+ export { AsyncContextRuntime, EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };
package/esm/http.mjs CHANGED
@@ -216,11 +216,17 @@ const resolvers = [
216
216
  dataKey: ["estimate"]
217
217
  }
218
218
  ];
219
+ /** resolver fns whose rows reach the client only through the GraphQL `IndexedTransaction` type */
220
+ const TX_PROJECTION_FNS = new Set(["listTransactions", "listAssetTransactions"]);
219
221
  const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
220
222
  acc[fn] = async (args, ctx) => {
221
223
  const res = await wrapResolver(fn, dataKey, () => {
222
224
  const method = resolver[fn];
223
- if (typeof method === "function") return method.call(resolver, args, formatContext(ctx));
225
+ if (typeof method === "function") {
226
+ const resolverCtx = formatContext(ctx);
227
+ if (TX_PROJECTION_FNS.has(fn)) resolverCtx.graphqlTxProjection = true;
228
+ return method.call(resolver, args, resolverCtx);
229
+ }
224
230
  return null;
225
231
  });
226
232
  if (fn === "sendTx") {
@@ -254,18 +260,69 @@ const defaultSlowRequestHandler = (report) => {
254
260
  console.warn("[gql] slow request", JSON.stringify(report));
255
261
  };
256
262
  const nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
257
- /** Root field names the operation selects (fragments followed one level deep, bounded). */
258
- const collectRootFieldNames = (documentAST, operationName) => {
259
- const names = /* @__PURE__ */ new Set();
263
+ /** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
264
+ const SQL_TIMING_KEY = Symbol.for("@ocap/sql-timing");
265
+ /** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
266
+ const SQL_TIMING_BACKEND_KEY = Symbol.for("@ocap/sql-timing/backend");
267
+ const currentAsyncContextRuntime = () => {
268
+ const proc = typeof process !== "undefined" ? process : void 0;
269
+ return {
270
+ bun: typeof proc?.versions?.bun === "string",
271
+ workers: typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers",
272
+ nodeVersion: proc?.versions?.node,
273
+ execArgv: Array.isArray(proc?.execArgv) ? proc.execArgv : [],
274
+ nodeOptions: typeof process !== "undefined" ? process.env?.NODE_OPTIONS : void 0
275
+ };
276
+ };
277
+ /**
278
+ * Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
279
+ * after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
280
+ * loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
281
+ * Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
282
+ */
283
+ const isCheapAsyncContextRuntime = (rt = currentAsyncContextRuntime()) => {
284
+ if (rt.bun || rt.workers) return true;
285
+ if (!rt.nodeVersion) return false;
286
+ const flags = new Set([...rt.execArgv || [], ...(rt.nodeOptions || "").split(/\s+/).filter(Boolean)]);
287
+ if (flags.has("--no-async-context-frame") || flags.has("--no-experimental-async-context-frame")) return false;
288
+ if (Number.parseInt(rt.nodeVersion, 10) >= 24) return true;
289
+ return flags.has("--experimental-async-context-frame") || flags.has("--async-context-frame");
290
+ };
291
+ /**
292
+ * The process-wide `AsyncLocalStorage` the SQLite backends read (#1891), created on first use and published under
293
+ * `globalThis[SQL_TIMING_KEY]`; null when the runtime has none (then the report has no `sql*` fields). Only called
294
+ * when the slow-request log is on, so `slowLogMs: 0` never creates it.
295
+ */
296
+ const getSqlTimingContext = () => {
297
+ const g = globalThis;
298
+ const existing = g[SQL_TIMING_KEY];
299
+ if (existing && typeof existing.run === "function") return existing;
300
+ try {
301
+ const getBuiltin = typeof process !== "undefined" ? process.getBuiltinModule : void 0;
302
+ const Als = globalThis.AsyncLocalStorage ?? (typeof getBuiltin === "function" ? getBuiltin("node:async_hooks")?.AsyncLocalStorage : void 0);
303
+ if (typeof Als !== "function") return null;
304
+ const ctx = new Als();
305
+ g[SQL_TIMING_KEY] = ctx;
306
+ return ctx;
307
+ } catch {
308
+ return null;
309
+ }
310
+ };
311
+ /**
312
+ * Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
313
+ * each named fragment counted once, bounded).
314
+ */
315
+ const collectRootFieldCounts = (documentAST, operationName, maxFragmentDepth = MAX_QUERY_DEPTH * 2) => {
316
+ const names = /* @__PURE__ */ new Map();
260
317
  const op = getOperationAST(documentAST, operationName || void 0);
261
318
  if (!op) return names;
262
319
  const fragments = /* @__PURE__ */ new Map();
263
320
  for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition") fragments.set(def.name.value, def.selectionSet.selections);
264
321
  const seen = /* @__PURE__ */ new Set();
265
322
  const walk = (selections, depth) => {
266
- for (const sel of selections) if (sel.kind === "Field") names.add(sel.name.value);
267
- else if (depth < 8 && sel.kind === "InlineFragment") walk(sel.selectionSet.selections, depth + 1);
268
- else if (depth < 8 && sel.kind === "FragmentSpread" && !seen.has(sel.name.value)) {
323
+ for (const sel of selections) if (sel.kind === "Field") names.set(sel.name.value, (names.get(sel.name.value) || 0) + 1);
324
+ else if (depth < maxFragmentDepth && sel.kind === "InlineFragment") walk(sel.selectionSet.selections, depth + 1);
325
+ else if (depth < maxFragmentDepth && sel.kind === "FragmentSpread" && !seen.has(sel.name.value)) {
269
326
  seen.add(sel.name.value);
270
327
  walk(fragments.get(sel.name.value) || [], depth + 1);
271
328
  }
@@ -274,6 +331,126 @@ const collectRootFieldNames = (documentAST, operationName) => {
274
331
  return names;
275
332
  };
276
333
  const headerValue = (v) => Array.isArray(v) ? v[0] : v;
334
+ const MAX_SHAPES_PER_FIELD = 8;
335
+ const MAX_STALL_ENTRIES = 20;
336
+ const MAX_RECENT_DONE = 64;
337
+ const MIN_STALL_LOG_MS = 20;
338
+ const timeCategory = (v) => {
339
+ if (v === void 0) return "absent";
340
+ if (v === null) return "null";
341
+ if (typeof v !== "string") return "invalid";
342
+ if (v === "") return "empty";
343
+ if (v === "null") return "null-string";
344
+ return Number.isNaN(Date.parse(v)) ? "invalid" : "date";
345
+ };
346
+ /**
347
+ * Shape key of one root field call's coerced arguments (see `SlowRequestShapeStat`). graphql-js only puts schema
348
+ * argument names in `args`, so the key never contains client-chosen strings; values are reduced to categories.
349
+ */
350
+ const describeArgShape = (args) => {
351
+ if (args == null || typeof args !== "object") return "-";
352
+ const a = args;
353
+ const names = Object.keys(a).filter((k) => a[k] !== void 0).sort();
354
+ let key = names.length ? names.join(",") : "-";
355
+ if ("paging" in a && a.paging !== void 0) {
356
+ const size = a.paging === null ? void 0 : a.paging.size;
357
+ let sizeCat;
358
+ if (a.paging === null) sizeCat = "null";
359
+ else if (size === void 0) sizeCat = "absent";
360
+ else if (typeof size === "number" && Number.isInteger(size) && size >= 0 && size <= 1e6) sizeCat = String(size);
361
+ else sizeCat = "invalid";
362
+ key += `|size=${sizeCat}`;
363
+ }
364
+ if ("timeFilter" in a && a.timeFilter !== void 0) if (a.timeFilter === null || typeof a.timeFilter !== "object") key += "|time=null";
365
+ else {
366
+ const t = a.timeFilter;
367
+ key += `|start=${timeCategory(t.startDateTime)}|end=${timeCategory(t.endDateTime)}`;
368
+ }
369
+ return key;
370
+ };
371
+ /** Total length of the list payloads (`transactions`, `assets`, ...) in a wrapped resolver result. */
372
+ const countRows = (out) => {
373
+ if (out == null || typeof out !== "object") return 0;
374
+ let rows = 0;
375
+ for (const [k, v] of Object.entries(out)) if (k !== "page" && Array.isArray(v)) rows += v.length;
376
+ return rows;
377
+ };
378
+ const defaultStallHandler = (report) => {
379
+ console.warn("[gql] event loop stall", JSON.stringify(report));
380
+ };
381
+ /**
382
+ * Timer drift probe: an unref'd interval measures how late it fires. A tick that is `>= thresholdMs` late means the
383
+ * loop was blocked between the previous tick and now; the requests whose lifetime overlaps that window are listed,
384
+ * including those that already finished (a request whose resolvers block synchronously is always done by the time
385
+ * any timer runs). `perf_hooks.monitorEventLoopDelay` only yields a histogram, not the stall's window, so it cannot
386
+ * attribute the stall; the probe also works on every runtime that has timers.
387
+ */
388
+ const createStallMonitor = (requestedMs, report, rootValue) => {
389
+ const thresholdMs = Math.max(MIN_STALL_LOG_MS, requestedMs);
390
+ const active = /* @__PURE__ */ new Set();
391
+ let recentDone = [];
392
+ let timer = null;
393
+ const intervalMs = Math.max(10, Math.min(100, Math.floor(thresholdMs / 2)));
394
+ let lastTick = 0;
395
+ const summarize = (rec, now) => {
396
+ const end = rec.finishedAt ?? now;
397
+ const entry = {
398
+ phase: rec.finishedAt !== void 0 ? "done" : rec.startedAt !== void 0 ? "running" : "reading",
399
+ ageMs: Math.round(end - rec.receivedAt)
400
+ };
401
+ if (rec.startedAt !== void 0) entry.execMs = Math.round(end - rec.startedAt);
402
+ if (rec.documentAST) {
403
+ entry.operationName = rec.operationName ? rec.operationName.slice(0, 100) : null;
404
+ entry.topLevel = countTopLevelSelections(rec.documentAST, Number.MAX_SAFE_INTEGER);
405
+ const { fields: selections, aliases } = countTotalSelectionsAndAliases(rec.documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
406
+ entry.selections = selections;
407
+ entry.aliases = aliases;
408
+ const fields = Object.create(null);
409
+ for (const [name, n] of collectRootFieldCounts(rec.documentAST, rec.operationName ?? null)) {
410
+ const key = Object.hasOwn(rootValue, name) ? name : "unknown";
411
+ fields[key] = (fields[key] || 0) + n;
412
+ }
413
+ entry.fields = fields;
414
+ }
415
+ const ua = headerValue(rec.headers["user-agent"]);
416
+ if (ua) entry.userAgent = ua.slice(0, 160);
417
+ return entry;
418
+ };
419
+ const tick = () => {
420
+ const now = nowMs();
421
+ const lateMs = now - lastTick - intervalMs;
422
+ const windowStartedAt = lastTick;
423
+ lastTick = now;
424
+ if (lateMs >= thresholdMs) try {
425
+ const overlapping = [...recentDone.filter((r) => r.finishedAt >= windowStartedAt), ...active].sort((a, b) => a.receivedAt - b.receivedAt);
426
+ report({
427
+ maxMs: Math.round(lateMs),
428
+ windowStart: new Date(Date.now() - (now - windowStartedAt)).toISOString(),
429
+ thresholdMs,
430
+ inFlightTotal: overlapping.length,
431
+ inFlight: overlapping.slice(0, MAX_STALL_ENTRIES).map((r) => summarize(r, now))
432
+ });
433
+ } catch {}
434
+ recentDone = [];
435
+ };
436
+ return {
437
+ begin(rec) {
438
+ if (!timer) {
439
+ lastTick = nowMs();
440
+ timer = setInterval(tick, intervalMs);
441
+ timer.unref?.();
442
+ }
443
+ active.add(rec);
444
+ },
445
+ end(rec) {
446
+ rec.finishedAt = nowMs();
447
+ active.delete(rec);
448
+ recentDone.push(rec);
449
+ if (recentDone.length > MAX_RECENT_DONE) recentDone.shift();
450
+ }
451
+ };
452
+ };
453
+ const canProbeEventLoop = () => typeof setInterval === "function" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers");
277
454
  /**
278
455
  * Read the raw express request body as a utf-8 string, enforcing the size limit.
279
456
  * Mirrors express-graphql's parseBody behavior for the subset of content
@@ -816,9 +993,11 @@ const parseEnvBoolean = (raw) => {
816
993
  if (normalized === "1" || normalized === "true") return true;
817
994
  if (normalized === "0" || normalized === "false") return false;
818
995
  };
819
- const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, graphiql = parseEnvBoolean(process.env.GQL_GRAPHIQL ?? process.env.GRAPHQL_GRAPHIQL) ?? process.env.NODE_ENV !== "production", introspection = parseEnvBoolean(process.env.GQL_INTROSPECTION ?? process.env.GRAPHQL_INTROSPECTION) ?? process.env.NODE_ENV !== "production", showStack = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test", maxQueryDepth = MAX_QUERY_DEPTH, maxTotalSelections = parseEnvPositiveInt(process.env.GQL_MAX_TOTAL_SELECTIONS) ?? MAX_TOTAL_SELECTIONS, maxAliases = parseEnvPositiveInt(process.env.GQL_MAX_ALIASES) ?? MAX_ALIASES, slowLogMs = parseEnvPositiveInt(process.env.GQL_SLOW_LOG_MS) ?? DEFAULT_SLOW_LOG_MS, onSlowRequest = defaultSlowRequestHandler }) => {
996
+ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, graphiql = parseEnvBoolean(process.env.GQL_GRAPHIQL ?? process.env.GRAPHQL_GRAPHIQL) ?? process.env.NODE_ENV !== "production", introspection = parseEnvBoolean(process.env.GQL_INTROSPECTION ?? process.env.GRAPHQL_INTROSPECTION) ?? process.env.NODE_ENV !== "production", showStack = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test", maxQueryDepth = MAX_QUERY_DEPTH, maxTotalSelections = parseEnvPositiveInt(process.env.GQL_MAX_TOTAL_SELECTIONS) ?? MAX_TOTAL_SELECTIONS, maxAliases = parseEnvPositiveInt(process.env.GQL_MAX_ALIASES) ?? MAX_ALIASES, slowLogMs = parseEnvPositiveInt(process.env.GQL_SLOW_LOG_MS) ?? DEFAULT_SLOW_LOG_MS, onSlowRequest = defaultSlowRequestHandler, stallLogMs = parseEnvPositiveInt(process.env.GQL_STALL_LOG_MS) ?? slowLogMs, onEventLoopStall = defaultStallHandler, sqlTiming: sqlTimingEnabled = parseEnvBoolean(process.env.GQL_SQL_TIMING) ?? isCheapAsyncContextRuntime() }) => {
820
997
  const schema = buildSchema(schemaSource);
821
998
  const rootValue = createResolvers(resolver);
999
+ const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
1000
+ const sqlTiming = slowLogMs > 0 && sqlTimingEnabled ? getSqlTimingContext() : null;
822
1001
  const formatGraphQLError = (err) => {
823
1002
  onError(err);
824
1003
  const includeStack = showStack && process.env.NODE_ENV !== "production";
@@ -852,7 +1031,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
852
1031
  headers: { "content-type": "text/html; charset=utf-8" },
853
1032
  body: html
854
1033
  });
855
- return async (req, contextValue) => {
1034
+ const run = async (req, contextValue, rec) => {
856
1035
  if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
857
1036
  let params;
858
1037
  try {
@@ -866,6 +1045,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
866
1045
  return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
867
1046
  }
868
1047
  const startedAt = slowLogMs > 0 ? nowMs() : 0;
1048
+ if (rec) rec.startedAt = startedAt;
869
1049
  const { query: normalizedQuery, prefix: aliasPrefix, aliasMap } = normalizeNumericFieldAliases(params.query);
870
1050
  const formatError = (err) => restoreNumericAliasesInFormattedError(formatGraphQLError(err), aliasPrefix, aliasMap);
871
1051
  let documentAST;
@@ -897,27 +1077,67 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
897
1077
  const operationAST = getOperationAST(documentAST, params.operationName || void 0);
898
1078
  if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
899
1079
  }
1080
+ if (rec) {
1081
+ rec.documentAST = documentAST;
1082
+ rec.operationName = params.operationName;
1083
+ }
900
1084
  const fieldStats = /* @__PURE__ */ new Map();
901
1085
  let requestRoot = rootValue;
902
1086
  if (slowLogMs > 0) {
903
1087
  requestRoot = Object.create(rootValue);
904
- for (const name of collectRootFieldNames(documentAST, params.operationName)) {
1088
+ const fragmentDepthCap = Math.max(maxQueryDepth, MAX_QUERY_DEPTH) * 2;
1089
+ for (const name of collectRootFieldCounts(documentAST, params.operationName, fragmentDepthCap).keys()) {
1090
+ if (!Object.hasOwn(rootValue, name)) continue;
905
1091
  const fn = rootValue[name];
906
1092
  if (typeof fn !== "function") continue;
907
1093
  requestRoot[name] = async (...args) => {
1094
+ let shape = "other";
1095
+ try {
1096
+ shape = describeArgShape(args[0]);
1097
+ } catch {}
1098
+ const sink = {
1099
+ sqlMs: 0,
1100
+ sqlQueries: 0
1101
+ };
1102
+ const call = () => fn.apply(rootValue, args);
908
1103
  const t = nowMs();
1104
+ let rows = 0;
909
1105
  try {
910
- return await fn(...args);
1106
+ const out = await (sqlTiming ? sqlTiming.run(sink, call) : call());
1107
+ try {
1108
+ rows = countRows(out);
1109
+ } catch {}
1110
+ return out;
911
1111
  } finally {
912
1112
  const ms = nowMs() - t;
1113
+ sink.closed = true;
913
1114
  const s = fieldStats.get(name) || {
914
1115
  count: 0,
915
1116
  wallSumMs: 0,
916
- wallMaxMs: 0
1117
+ wallMaxMs: 0,
1118
+ sqlSumMs: 0,
1119
+ sqlMaxMs: 0,
1120
+ sqlQueries: 0,
1121
+ rows: 0,
1122
+ shapes: Object.create(null)
917
1123
  };
918
1124
  s.count += 1;
919
1125
  s.wallSumMs += ms;
920
1126
  if (ms > s.wallMaxMs) s.wallMaxMs = ms;
1127
+ s.sqlSumMs = s.sqlSumMs + sink.sqlMs;
1128
+ if (sink.sqlMs > s.sqlMaxMs) s.sqlMaxMs = sink.sqlMs;
1129
+ s.sqlQueries = s.sqlQueries + sink.sqlQueries;
1130
+ s.rows += rows;
1131
+ if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
1132
+ const b = s.shapes[shape] || {
1133
+ count: 0,
1134
+ rows: 0,
1135
+ sqlMs: 0
1136
+ };
1137
+ b.count += 1;
1138
+ b.rows += rows;
1139
+ b.sqlMs = b.sqlMs + sink.sqlMs;
1140
+ s.shapes[shape] = b;
921
1141
  fieldStats.set(name, s);
922
1142
  }
923
1143
  };
@@ -945,16 +1165,45 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
945
1165
  const response = sendJSON(status, formattedResult);
946
1166
  const finishedAt = nowMs();
947
1167
  const totalMs = finishedAt - startedAt;
948
- if (totalMs >= slowLogMs) try {
1168
+ const queuedMs = rec ? Math.max(0, startedAt - rec.receivedAt) : 0;
1169
+ if (totalMs + queuedMs >= slowLogMs) try {
949
1170
  const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
950
1171
  const round = (n) => Math.round(n);
951
- const fields = {};
952
- for (const [name, s] of fieldStats) fields[name] = {
953
- count: s.count,
954
- wallSumMs: round(s.wallSumMs),
955
- wallMaxMs: round(s.wallMaxMs)
956
- };
1172
+ const fields = Object.create(null);
1173
+ const reportSql = sqlTiming !== null && globalThis[SQL_TIMING_BACKEND_KEY] === true;
1174
+ let sqlMs = 0;
1175
+ let sqlQueries = 0;
1176
+ for (const [name, s] of fieldStats) {
1177
+ const shapes = Object.create(null);
1178
+ for (const [k, b] of Object.entries(s.shapes)) shapes[k] = reportSql ? {
1179
+ count: b.count,
1180
+ rows: b.rows,
1181
+ sqlMs: round(b.sqlMs)
1182
+ } : {
1183
+ count: b.count,
1184
+ rows: b.rows
1185
+ };
1186
+ sqlMs += s.sqlSumMs;
1187
+ sqlQueries += s.sqlQueries;
1188
+ fields[name] = reportSql ? {
1189
+ count: s.count,
1190
+ wallSumMs: round(s.wallSumMs),
1191
+ wallMaxMs: round(s.wallMaxMs),
1192
+ sqlSumMs: round(s.sqlSumMs),
1193
+ sqlMaxMs: round(s.sqlMaxMs),
1194
+ sqlQueries: s.sqlQueries,
1195
+ rows: s.rows,
1196
+ shapes
1197
+ } : {
1198
+ count: s.count,
1199
+ wallSumMs: round(s.wallSumMs),
1200
+ wallMaxMs: round(s.wallMaxMs),
1201
+ rows: s.rows,
1202
+ shapes
1203
+ };
1204
+ }
957
1205
  onSlowRequest({
1206
+ queuedMs: round(queuedMs),
958
1207
  totalMs: round(totalMs),
959
1208
  parseMs: round(executeStartedAt - startedAt),
960
1209
  executeMs: round(executedAt - executeStartedAt),
@@ -968,18 +1217,36 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
968
1217
  aliases,
969
1218
  numericAliases: aliasMap ? aliasMap.size : 0,
970
1219
  errors: result.errors ? result.errors.length : 0,
1220
+ ...reportSql ? {
1221
+ sqlMs: round(sqlMs),
1222
+ sqlQueries
1223
+ } : {},
971
1224
  fields,
972
1225
  userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160)
973
1226
  });
974
1227
  } catch {}
975
1228
  return response;
976
1229
  };
1230
+ if (slowLogMs <= 0) return (req, contextValue) => run(req, contextValue, null);
1231
+ return async (req, contextValue) => {
1232
+ const rec = {
1233
+ receivedAt: req.receivedAt ?? nowMs(),
1234
+ headers: req.headers
1235
+ };
1236
+ stallMonitor?.begin(rec);
1237
+ try {
1238
+ return await run(req, contextValue, rec);
1239
+ } finally {
1240
+ stallMonitor?.end(rec);
1241
+ }
1242
+ };
977
1243
  };
978
1244
  /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
979
1245
  const createHttpHandler = (options) => {
980
1246
  const engine = createGraphQLEngine(options);
981
1247
  return async (req, res) => {
982
1248
  const result = await engine({
1249
+ receivedAt: nowMs(),
983
1250
  method: req.method,
984
1251
  url: req.url,
985
1252
  headers: req.headers,
@@ -1024,12 +1291,14 @@ const readFetchBody = async (request, limit) => {
1024
1291
  const createFetchHandler = (options) => {
1025
1292
  const engine = createGraphQLEngine(options);
1026
1293
  return async (request) => {
1294
+ const receivedAt = nowMs();
1027
1295
  const headers = {};
1028
1296
  request.headers.forEach((value, key) => {
1029
1297
  headers[key.toLowerCase()] = value;
1030
1298
  });
1031
1299
  const url = new URL(request.url);
1032
1300
  const result = await engine({
1301
+ receivedAt,
1033
1302
  method: request.method,
1034
1303
  url: `${url.pathname}${url.search}`,
1035
1304
  headers,
@@ -1046,4 +1315,4 @@ const createFetchHandler = (options) => {
1046
1315
  };
1047
1316
 
1048
1317
  //#endregion
1049
- export { createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
1318
+ export { SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };