@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/esm/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver } from "./http.mjs";
1
+ import { AsyncContextRuntime, EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver } from "./http.mjs";
2
2
  import { Server } from "node:http";
3
3
  import { TIndexedAccountState, TIndexedAssetState, TIndexedDelegationState, TIndexedFactoryState, TIndexedRollupBlock, TIndexedRollupState, TIndexedStakeState, TIndexedTokenState, TIndexedTransaction } from "@ocap/types";
4
4
  import { Express } from "express";
@@ -39,4 +39,4 @@ declare const createSocketHandler: ({
39
39
  wsOptions
40
40
  }: SocketHandlerOptions) => Server;
41
41
  //#endregion
42
- export { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, normalizeNumericFieldAliases, wrapResolver };
42
+ export { AsyncContextRuntime, EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };
package/esm/index.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import { createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver } from "./http.mjs";
1
+ import { SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver } from "./http.mjs";
2
2
  import createWebsocketServer from "./ws.mjs";
3
3
  import { createServer } from "node:http";
4
4
 
@@ -13,4 +13,4 @@ const createSocketHandler = ({ app, indexdb, wsOptions }) => {
13
13
  };
14
14
 
15
15
  //#endregion
16
- export { createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, normalizeNumericFieldAliases, wrapResolver };
16
+ export { SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };
package/lib/http.cjs CHANGED
@@ -219,11 +219,17 @@ const resolvers = [
219
219
  dataKey: ["estimate"]
220
220
  }
221
221
  ];
222
+ /** resolver fns whose rows reach the client only through the GraphQL `IndexedTransaction` type */
223
+ const TX_PROJECTION_FNS = new Set(["listTransactions", "listAssetTransactions"]);
222
224
  const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
223
225
  acc[fn] = async (args, ctx) => {
224
226
  const res = await wrapResolver(fn, dataKey, () => {
225
227
  const method = resolver[fn];
226
- if (typeof method === "function") return method.call(resolver, args, formatContext(ctx));
228
+ if (typeof method === "function") {
229
+ const resolverCtx = formatContext(ctx);
230
+ if (TX_PROJECTION_FNS.has(fn)) resolverCtx.graphqlTxProjection = true;
231
+ return method.call(resolver, args, resolverCtx);
232
+ }
227
233
  return null;
228
234
  });
229
235
  if (fn === "sendTx") {
@@ -257,18 +263,69 @@ const defaultSlowRequestHandler = (report) => {
257
263
  console.warn("[gql] slow request", JSON.stringify(report));
258
264
  };
259
265
  const nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
260
- /** Root field names the operation selects (fragments followed one level deep, bounded). */
261
- const collectRootFieldNames = (documentAST, operationName) => {
262
- const names = /* @__PURE__ */ new Set();
266
+ /** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
267
+ const SQL_TIMING_KEY = Symbol.for("@ocap/sql-timing");
268
+ /** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
269
+ const SQL_TIMING_BACKEND_KEY = Symbol.for("@ocap/sql-timing/backend");
270
+ const currentAsyncContextRuntime = () => {
271
+ const proc = typeof process !== "undefined" ? process : void 0;
272
+ return {
273
+ bun: typeof proc?.versions?.bun === "string",
274
+ workers: typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers",
275
+ nodeVersion: proc?.versions?.node,
276
+ execArgv: Array.isArray(proc?.execArgv) ? proc.execArgv : [],
277
+ nodeOptions: typeof process !== "undefined" ? process.env?.NODE_OPTIONS : void 0
278
+ };
279
+ };
280
+ /**
281
+ * Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
282
+ * after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
283
+ * loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
284
+ * Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
285
+ */
286
+ const isCheapAsyncContextRuntime = (rt = currentAsyncContextRuntime()) => {
287
+ if (rt.bun || rt.workers) return true;
288
+ if (!rt.nodeVersion) return false;
289
+ const flags = new Set([...rt.execArgv || [], ...(rt.nodeOptions || "").split(/\s+/).filter(Boolean)]);
290
+ if (flags.has("--no-async-context-frame") || flags.has("--no-experimental-async-context-frame")) return false;
291
+ if (Number.parseInt(rt.nodeVersion, 10) >= 24) return true;
292
+ return flags.has("--experimental-async-context-frame") || flags.has("--async-context-frame");
293
+ };
294
+ /**
295
+ * The process-wide `AsyncLocalStorage` the SQLite backends read (#1891), created on first use and published under
296
+ * `globalThis[SQL_TIMING_KEY]`; null when the runtime has none (then the report has no `sql*` fields). Only called
297
+ * when the slow-request log is on, so `slowLogMs: 0` never creates it.
298
+ */
299
+ const getSqlTimingContext = () => {
300
+ const g = globalThis;
301
+ const existing = g[SQL_TIMING_KEY];
302
+ if (existing && typeof existing.run === "function") return existing;
303
+ try {
304
+ const getBuiltin = typeof process !== "undefined" ? process.getBuiltinModule : void 0;
305
+ const Als = globalThis.AsyncLocalStorage ?? (typeof getBuiltin === "function" ? getBuiltin("node:async_hooks")?.AsyncLocalStorage : void 0);
306
+ if (typeof Als !== "function") return null;
307
+ const ctx = new Als();
308
+ g[SQL_TIMING_KEY] = ctx;
309
+ return ctx;
310
+ } catch {
311
+ return null;
312
+ }
313
+ };
314
+ /**
315
+ * Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
316
+ * each named fragment counted once, bounded).
317
+ */
318
+ const collectRootFieldCounts = (documentAST, operationName, maxFragmentDepth = MAX_QUERY_DEPTH * 2) => {
319
+ const names = /* @__PURE__ */ new Map();
263
320
  const op = (0, graphql.getOperationAST)(documentAST, operationName || void 0);
264
321
  if (!op) return names;
265
322
  const fragments = /* @__PURE__ */ new Map();
266
323
  for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition") fragments.set(def.name.value, def.selectionSet.selections);
267
324
  const seen = /* @__PURE__ */ new Set();
268
325
  const walk = (selections, depth) => {
269
- for (const sel of selections) if (sel.kind === "Field") names.add(sel.name.value);
270
- else if (depth < 8 && sel.kind === "InlineFragment") walk(sel.selectionSet.selections, depth + 1);
271
- else if (depth < 8 && sel.kind === "FragmentSpread" && !seen.has(sel.name.value)) {
326
+ for (const sel of selections) if (sel.kind === "Field") names.set(sel.name.value, (names.get(sel.name.value) || 0) + 1);
327
+ else if (depth < maxFragmentDepth && sel.kind === "InlineFragment") walk(sel.selectionSet.selections, depth + 1);
328
+ else if (depth < maxFragmentDepth && sel.kind === "FragmentSpread" && !seen.has(sel.name.value)) {
272
329
  seen.add(sel.name.value);
273
330
  walk(fragments.get(sel.name.value) || [], depth + 1);
274
331
  }
@@ -277,6 +334,126 @@ const collectRootFieldNames = (documentAST, operationName) => {
277
334
  return names;
278
335
  };
279
336
  const headerValue = (v) => Array.isArray(v) ? v[0] : v;
337
+ const MAX_SHAPES_PER_FIELD = 8;
338
+ const MAX_STALL_ENTRIES = 20;
339
+ const MAX_RECENT_DONE = 64;
340
+ const MIN_STALL_LOG_MS = 20;
341
+ const timeCategory = (v) => {
342
+ if (v === void 0) return "absent";
343
+ if (v === null) return "null";
344
+ if (typeof v !== "string") return "invalid";
345
+ if (v === "") return "empty";
346
+ if (v === "null") return "null-string";
347
+ return Number.isNaN(Date.parse(v)) ? "invalid" : "date";
348
+ };
349
+ /**
350
+ * Shape key of one root field call's coerced arguments (see `SlowRequestShapeStat`). graphql-js only puts schema
351
+ * argument names in `args`, so the key never contains client-chosen strings; values are reduced to categories.
352
+ */
353
+ const describeArgShape = (args) => {
354
+ if (args == null || typeof args !== "object") return "-";
355
+ const a = args;
356
+ const names = Object.keys(a).filter((k) => a[k] !== void 0).sort();
357
+ let key = names.length ? names.join(",") : "-";
358
+ if ("paging" in a && a.paging !== void 0) {
359
+ const size = a.paging === null ? void 0 : a.paging.size;
360
+ let sizeCat;
361
+ if (a.paging === null) sizeCat = "null";
362
+ else if (size === void 0) sizeCat = "absent";
363
+ else if (typeof size === "number" && Number.isInteger(size) && size >= 0 && size <= 1e6) sizeCat = String(size);
364
+ else sizeCat = "invalid";
365
+ key += `|size=${sizeCat}`;
366
+ }
367
+ if ("timeFilter" in a && a.timeFilter !== void 0) if (a.timeFilter === null || typeof a.timeFilter !== "object") key += "|time=null";
368
+ else {
369
+ const t = a.timeFilter;
370
+ key += `|start=${timeCategory(t.startDateTime)}|end=${timeCategory(t.endDateTime)}`;
371
+ }
372
+ return key;
373
+ };
374
+ /** Total length of the list payloads (`transactions`, `assets`, ...) in a wrapped resolver result. */
375
+ const countRows = (out) => {
376
+ if (out == null || typeof out !== "object") return 0;
377
+ let rows = 0;
378
+ for (const [k, v] of Object.entries(out)) if (k !== "page" && Array.isArray(v)) rows += v.length;
379
+ return rows;
380
+ };
381
+ const defaultStallHandler = (report) => {
382
+ console.warn("[gql] event loop stall", JSON.stringify(report));
383
+ };
384
+ /**
385
+ * Timer drift probe: an unref'd interval measures how late it fires. A tick that is `>= thresholdMs` late means the
386
+ * loop was blocked between the previous tick and now; the requests whose lifetime overlaps that window are listed,
387
+ * including those that already finished (a request whose resolvers block synchronously is always done by the time
388
+ * any timer runs). `perf_hooks.monitorEventLoopDelay` only yields a histogram, not the stall's window, so it cannot
389
+ * attribute the stall; the probe also works on every runtime that has timers.
390
+ */
391
+ const createStallMonitor = (requestedMs, report, rootValue) => {
392
+ const thresholdMs = Math.max(MIN_STALL_LOG_MS, requestedMs);
393
+ const active = /* @__PURE__ */ new Set();
394
+ let recentDone = [];
395
+ let timer = null;
396
+ const intervalMs = Math.max(10, Math.min(100, Math.floor(thresholdMs / 2)));
397
+ let lastTick = 0;
398
+ const summarize = (rec, now) => {
399
+ const end = rec.finishedAt ?? now;
400
+ const entry = {
401
+ phase: rec.finishedAt !== void 0 ? "done" : rec.startedAt !== void 0 ? "running" : "reading",
402
+ ageMs: Math.round(end - rec.receivedAt)
403
+ };
404
+ if (rec.startedAt !== void 0) entry.execMs = Math.round(end - rec.startedAt);
405
+ if (rec.documentAST) {
406
+ entry.operationName = rec.operationName ? rec.operationName.slice(0, 100) : null;
407
+ entry.topLevel = countTopLevelSelections(rec.documentAST, Number.MAX_SAFE_INTEGER);
408
+ const { fields: selections, aliases } = countTotalSelectionsAndAliases(rec.documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
409
+ entry.selections = selections;
410
+ entry.aliases = aliases;
411
+ const fields = Object.create(null);
412
+ for (const [name, n] of collectRootFieldCounts(rec.documentAST, rec.operationName ?? null)) {
413
+ const key = Object.hasOwn(rootValue, name) ? name : "unknown";
414
+ fields[key] = (fields[key] || 0) + n;
415
+ }
416
+ entry.fields = fields;
417
+ }
418
+ const ua = headerValue(rec.headers["user-agent"]);
419
+ if (ua) entry.userAgent = ua.slice(0, 160);
420
+ return entry;
421
+ };
422
+ const tick = () => {
423
+ const now = nowMs();
424
+ const lateMs = now - lastTick - intervalMs;
425
+ const windowStartedAt = lastTick;
426
+ lastTick = now;
427
+ if (lateMs >= thresholdMs) try {
428
+ const overlapping = [...recentDone.filter((r) => r.finishedAt >= windowStartedAt), ...active].sort((a, b) => a.receivedAt - b.receivedAt);
429
+ report({
430
+ maxMs: Math.round(lateMs),
431
+ windowStart: new Date(Date.now() - (now - windowStartedAt)).toISOString(),
432
+ thresholdMs,
433
+ inFlightTotal: overlapping.length,
434
+ inFlight: overlapping.slice(0, MAX_STALL_ENTRIES).map((r) => summarize(r, now))
435
+ });
436
+ } catch {}
437
+ recentDone = [];
438
+ };
439
+ return {
440
+ begin(rec) {
441
+ if (!timer) {
442
+ lastTick = nowMs();
443
+ timer = setInterval(tick, intervalMs);
444
+ timer.unref?.();
445
+ }
446
+ active.add(rec);
447
+ },
448
+ end(rec) {
449
+ rec.finishedAt = nowMs();
450
+ active.delete(rec);
451
+ recentDone.push(rec);
452
+ if (recentDone.length > MAX_RECENT_DONE) recentDone.shift();
453
+ }
454
+ };
455
+ };
456
+ const canProbeEventLoop = () => typeof setInterval === "function" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers");
280
457
  /**
281
458
  * Read the raw express request body as a utf-8 string, enforcing the size limit.
282
459
  * Mirrors express-graphql's parseBody behavior for the subset of content
@@ -819,9 +996,11 @@ const parseEnvBoolean = (raw) => {
819
996
  if (normalized === "1" || normalized === "true") return true;
820
997
  if (normalized === "0" || normalized === "false") return false;
821
998
  };
822
- 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 }) => {
999
+ 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() }) => {
823
1000
  const schema = (0, graphql.buildSchema)(_ocap_schema.default);
824
1001
  const rootValue = createResolvers(resolver);
1002
+ const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
1003
+ const sqlTiming = slowLogMs > 0 && sqlTimingEnabled ? getSqlTimingContext() : null;
825
1004
  const formatGraphQLError = (err) => {
826
1005
  onError(err);
827
1006
  const includeStack = showStack && process.env.NODE_ENV !== "production";
@@ -855,7 +1034,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
855
1034
  headers: { "content-type": "text/html; charset=utf-8" },
856
1035
  body: html
857
1036
  });
858
- return async (req, contextValue) => {
1037
+ const run = async (req, contextValue, rec) => {
859
1038
  if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
860
1039
  let params;
861
1040
  try {
@@ -869,6 +1048,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
869
1048
  return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
870
1049
  }
871
1050
  const startedAt = slowLogMs > 0 ? nowMs() : 0;
1051
+ if (rec) rec.startedAt = startedAt;
872
1052
  const { query: normalizedQuery, prefix: aliasPrefix, aliasMap } = normalizeNumericFieldAliases(params.query);
873
1053
  const formatError = (err) => restoreNumericAliasesInFormattedError(formatGraphQLError(err), aliasPrefix, aliasMap);
874
1054
  let documentAST;
@@ -900,27 +1080,67 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
900
1080
  const operationAST = (0, graphql.getOperationAST)(documentAST, params.operationName || void 0);
901
1081
  if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
902
1082
  }
1083
+ if (rec) {
1084
+ rec.documentAST = documentAST;
1085
+ rec.operationName = params.operationName;
1086
+ }
903
1087
  const fieldStats = /* @__PURE__ */ new Map();
904
1088
  let requestRoot = rootValue;
905
1089
  if (slowLogMs > 0) {
906
1090
  requestRoot = Object.create(rootValue);
907
- for (const name of collectRootFieldNames(documentAST, params.operationName)) {
1091
+ const fragmentDepthCap = Math.max(maxQueryDepth, MAX_QUERY_DEPTH) * 2;
1092
+ for (const name of collectRootFieldCounts(documentAST, params.operationName, fragmentDepthCap).keys()) {
1093
+ if (!Object.hasOwn(rootValue, name)) continue;
908
1094
  const fn = rootValue[name];
909
1095
  if (typeof fn !== "function") continue;
910
1096
  requestRoot[name] = async (...args) => {
1097
+ let shape = "other";
1098
+ try {
1099
+ shape = describeArgShape(args[0]);
1100
+ } catch {}
1101
+ const sink = {
1102
+ sqlMs: 0,
1103
+ sqlQueries: 0
1104
+ };
1105
+ const call = () => fn.apply(rootValue, args);
911
1106
  const t = nowMs();
1107
+ let rows = 0;
912
1108
  try {
913
- return await fn(...args);
1109
+ const out = await (sqlTiming ? sqlTiming.run(sink, call) : call());
1110
+ try {
1111
+ rows = countRows(out);
1112
+ } catch {}
1113
+ return out;
914
1114
  } finally {
915
1115
  const ms = nowMs() - t;
1116
+ sink.closed = true;
916
1117
  const s = fieldStats.get(name) || {
917
1118
  count: 0,
918
1119
  wallSumMs: 0,
919
- wallMaxMs: 0
1120
+ wallMaxMs: 0,
1121
+ sqlSumMs: 0,
1122
+ sqlMaxMs: 0,
1123
+ sqlQueries: 0,
1124
+ rows: 0,
1125
+ shapes: Object.create(null)
920
1126
  };
921
1127
  s.count += 1;
922
1128
  s.wallSumMs += ms;
923
1129
  if (ms > s.wallMaxMs) s.wallMaxMs = ms;
1130
+ s.sqlSumMs = s.sqlSumMs + sink.sqlMs;
1131
+ if (sink.sqlMs > s.sqlMaxMs) s.sqlMaxMs = sink.sqlMs;
1132
+ s.sqlQueries = s.sqlQueries + sink.sqlQueries;
1133
+ s.rows += rows;
1134
+ if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
1135
+ const b = s.shapes[shape] || {
1136
+ count: 0,
1137
+ rows: 0,
1138
+ sqlMs: 0
1139
+ };
1140
+ b.count += 1;
1141
+ b.rows += rows;
1142
+ b.sqlMs = b.sqlMs + sink.sqlMs;
1143
+ s.shapes[shape] = b;
924
1144
  fieldStats.set(name, s);
925
1145
  }
926
1146
  };
@@ -948,16 +1168,45 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
948
1168
  const response = sendJSON(status, formattedResult);
949
1169
  const finishedAt = nowMs();
950
1170
  const totalMs = finishedAt - startedAt;
951
- if (totalMs >= slowLogMs) try {
1171
+ const queuedMs = rec ? Math.max(0, startedAt - rec.receivedAt) : 0;
1172
+ if (totalMs + queuedMs >= slowLogMs) try {
952
1173
  const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
953
1174
  const round = (n) => Math.round(n);
954
- const fields = {};
955
- for (const [name, s] of fieldStats) fields[name] = {
956
- count: s.count,
957
- wallSumMs: round(s.wallSumMs),
958
- wallMaxMs: round(s.wallMaxMs)
959
- };
1175
+ const fields = Object.create(null);
1176
+ const reportSql = sqlTiming !== null && globalThis[SQL_TIMING_BACKEND_KEY] === true;
1177
+ let sqlMs = 0;
1178
+ let sqlQueries = 0;
1179
+ for (const [name, s] of fieldStats) {
1180
+ const shapes = Object.create(null);
1181
+ for (const [k, b] of Object.entries(s.shapes)) shapes[k] = reportSql ? {
1182
+ count: b.count,
1183
+ rows: b.rows,
1184
+ sqlMs: round(b.sqlMs)
1185
+ } : {
1186
+ count: b.count,
1187
+ rows: b.rows
1188
+ };
1189
+ sqlMs += s.sqlSumMs;
1190
+ sqlQueries += s.sqlQueries;
1191
+ fields[name] = reportSql ? {
1192
+ count: s.count,
1193
+ wallSumMs: round(s.wallSumMs),
1194
+ wallMaxMs: round(s.wallMaxMs),
1195
+ sqlSumMs: round(s.sqlSumMs),
1196
+ sqlMaxMs: round(s.sqlMaxMs),
1197
+ sqlQueries: s.sqlQueries,
1198
+ rows: s.rows,
1199
+ shapes
1200
+ } : {
1201
+ count: s.count,
1202
+ wallSumMs: round(s.wallSumMs),
1203
+ wallMaxMs: round(s.wallMaxMs),
1204
+ rows: s.rows,
1205
+ shapes
1206
+ };
1207
+ }
960
1208
  onSlowRequest({
1209
+ queuedMs: round(queuedMs),
961
1210
  totalMs: round(totalMs),
962
1211
  parseMs: round(executeStartedAt - startedAt),
963
1212
  executeMs: round(executedAt - executeStartedAt),
@@ -971,18 +1220,36 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
971
1220
  aliases,
972
1221
  numericAliases: aliasMap ? aliasMap.size : 0,
973
1222
  errors: result.errors ? result.errors.length : 0,
1223
+ ...reportSql ? {
1224
+ sqlMs: round(sqlMs),
1225
+ sqlQueries
1226
+ } : {},
974
1227
  fields,
975
1228
  userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160)
976
1229
  });
977
1230
  } catch {}
978
1231
  return response;
979
1232
  };
1233
+ if (slowLogMs <= 0) return (req, contextValue) => run(req, contextValue, null);
1234
+ return async (req, contextValue) => {
1235
+ const rec = {
1236
+ receivedAt: req.receivedAt ?? nowMs(),
1237
+ headers: req.headers
1238
+ };
1239
+ stallMonitor?.begin(rec);
1240
+ try {
1241
+ return await run(req, contextValue, rec);
1242
+ } finally {
1243
+ stallMonitor?.end(rec);
1244
+ }
1245
+ };
980
1246
  };
981
1247
  /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
982
1248
  const createHttpHandler = (options) => {
983
1249
  const engine = createGraphQLEngine(options);
984
1250
  return async (req, res) => {
985
1251
  const result = await engine({
1252
+ receivedAt: nowMs(),
986
1253
  method: req.method,
987
1254
  url: req.url,
988
1255
  headers: req.headers,
@@ -1027,12 +1294,14 @@ const readFetchBody = async (request, limit) => {
1027
1294
  const createFetchHandler = (options) => {
1028
1295
  const engine = createGraphQLEngine(options);
1029
1296
  return async (request) => {
1297
+ const receivedAt = nowMs();
1030
1298
  const headers = {};
1031
1299
  request.headers.forEach((value, key) => {
1032
1300
  headers[key.toLowerCase()] = value;
1033
1301
  });
1034
1302
  const url = new URL(request.url);
1035
1303
  const result = await engine({
1304
+ receivedAt,
1036
1305
  method: request.method,
1037
1306
  url: `${url.pathname}${url.search}`,
1038
1307
  headers,
@@ -1049,9 +1318,12 @@ const createFetchHandler = (options) => {
1049
1318
  };
1050
1319
 
1051
1320
  //#endregion
1321
+ exports.SQL_TIMING_BACKEND_KEY = SQL_TIMING_BACKEND_KEY;
1322
+ exports.SQL_TIMING_KEY = SQL_TIMING_KEY;
1052
1323
  exports.createFetchHandler = createFetchHandler;
1053
1324
  exports.createHttpHandler = createHttpHandler;
1054
1325
  exports.createResolvers = createResolvers;
1055
1326
  exports.formatContext = formatContext;
1327
+ exports.isCheapAsyncContextRuntime = isCheapAsyncContextRuntime;
1056
1328
  exports.normalizeNumericFieldAliases = normalizeNumericFieldAliases;
1057
1329
  exports.wrapResolver = wrapResolver;
package/lib/http.d.cts 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/lib/index.cjs CHANGED
@@ -14,10 +14,13 @@ const createSocketHandler = ({ app, indexdb, wsOptions }) => {
14
14
  };
15
15
 
16
16
  //#endregion
17
+ exports.SQL_TIMING_BACKEND_KEY = require_http.SQL_TIMING_BACKEND_KEY;
18
+ exports.SQL_TIMING_KEY = require_http.SQL_TIMING_KEY;
17
19
  exports.createFetchHandler = require_http.createFetchHandler;
18
20
  exports.createHttpHandler = require_http.createHttpHandler;
19
21
  exports.createResolvers = require_http.createResolvers;
20
22
  exports.createSocketHandler = createSocketHandler;
21
23
  exports.formatContext = require_http.formatContext;
24
+ exports.isCheapAsyncContextRuntime = require_http.isCheapAsyncContextRuntime;
22
25
  exports.normalizeNumericFieldAliases = require_http.normalizeNumericFieldAliases;
23
26
  exports.wrapResolver = require_http.wrapResolver;
package/lib/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver } from "./http.cjs";
1
+ import { AsyncContextRuntime, EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver } from "./http.cjs";
2
2
  import { TIndexedAccountState, TIndexedAssetState, TIndexedDelegationState, TIndexedFactoryState, TIndexedRollupBlock, TIndexedRollupState, TIndexedStakeState, TIndexedTokenState, TIndexedTransaction } from "@ocap/types";
3
3
  import { Express } from "express";
4
4
  import { Server } from "node:http";
@@ -39,4 +39,4 @@ declare const createSocketHandler: ({
39
39
  wsOptions
40
40
  }: SocketHandlerOptions) => Server;
41
41
  //#endregion
42
- export { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, normalizeNumericFieldAliases, wrapResolver };
42
+ export { AsyncContextRuntime, EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };