@ocap/gql 1.31.7 → 1.31.8

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,44 @@ 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
+
42
+ `[gql] slow request {...}` (example values below are illustrative):
43
+
44
+ - `queuedMs`: from the adapter receiving the request until the engine started on it, body read included. Time spent
45
+ before Node hands the request to the adapter (the socket is not read while the loop is blocked) is not visible
46
+ here; the stall line covers it.
47
+ - `totalMs` = `parseMs` + `executeMs` + `serializeMs`.
48
+ - `fields.<rootField>`: `count` aliases; `wallSumMs`/`wallMaxMs` (wall time per alias; aliases of one batch run
49
+ interleaved, so the sum overlaps and can exceed `executeMs`); `syncSumMs`/`syncMaxMs` (time inside each resolver
50
+ call before it returns its promise: for the SQLite index this is the query itself, so the sum does not overlap);
51
+ `rows` (total length of the returned lists, e.g. `transactions`); `shapes` (aliases bucketed by argument shape, at
52
+ most 8 buckets plus `other`, each with `count`, `rows`, `syncMs`).
53
+ - A shape key lists the argument names present, then `size=<paging.size>` when `paging` is given and
54
+ `start=`/`end=` when `timeFilter` is given, each one of `absent`, `empty` (`""`), `null-string` (`"null"`), `null`,
55
+ `date` or `invalid`.
56
+
57
+ ```
58
+ [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,"fields":{"listTransactions":{"count":30,"wallSumMs":6612,"wallMaxMs":440,"syncSumMs":402,"syncMaxMs":31,"rows":600,"shapes":{"accountFilter,paging,timeFilter|size=20|start=null-string|end=absent":{"count":30,"rows":600,"syncMs":402}}}},"userAgent":"ArcWallet/5.10.9 ..."}
59
+ ```
60
+
61
+ `[gql] event loop stall {...}` is written when the probe timer (an unref'd interval, started on the first request,
62
+ never on Cloudflare Workers) fires at least `GQL_STALL_LOG_MS` late. `maxMs` is how late it fired and `windowStart`
63
+ when the stalled window began. `inFlight` (at most 20, `inFlightTotal` counts all) lists the requests in flight and
64
+ those that finished inside the window: a request whose resolvers block synchronously has always finished by the
65
+ time a timer can run, so `phase: "done"` with a large `execMs` is the usual culprit, and `phase: "reading"` entries
66
+ are requests that waited behind it. `fields` maps root field names to alias counts; names the schema does not resolve (field existence is not
67
+ validated) are summed under `unknown` and never written out.
68
+
69
+ ```
70
+ [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 ..."}]}
71
+ ```
package/esm/http.d.mts CHANGED
@@ -35,29 +35,89 @@ 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
+ /**
54
+ * Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
55
+ * then `size=<paging.size>` when `paging` is present and `start=`/`end=` categories when `timeFilter` is present:
56
+ * `absent`, `empty` (""), `null-string` ("null"), `null`, `date` (parses as a date) or `invalid`. No argument value
57
+ * other than the integer `paging.size` is ever part of the key.
58
+ */
59
+ interface SlowRequestShapeStat {
60
+ count: number;
61
+ /** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
62
+ rows: number;
63
+ /** Synchronous time inside the resolver calls of this bucket. */
64
+ syncMs: number;
44
65
  }
45
66
  /**
46
67
  * Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
47
68
  * 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.
69
+ * most `executeMs`, and `wallSumMs` can exceed it. `syncSumMs` / `syncMaxMs` only count the time spent inside the
70
+ * resolver call before it returns its promise (for the SQLite index this includes the query itself, not the
71
+ * per-row formatting that runs after the first await), so they do not overlap and their sum stays within `executeMs`.
50
72
  */
51
73
  interface SlowRequestFieldStat {
52
74
  count: number;
53
75
  wallSumMs: number;
54
76
  wallMaxMs: number;
77
+ syncSumMs: number;
78
+ syncMaxMs: number;
79
+ /** Rows returned over all aliases (sum of list payload lengths). */
80
+ rows: number;
81
+ /** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
82
+ shapes: Record<string, SlowRequestShapeStat>;
83
+ }
84
+ /** One request that was in flight (or finished) during a stalled probe window. Never carries argument values. */
85
+ interface StallInFlightEntry {
86
+ /** `reading`: body not yet parsed; `running`: parse/execute/serialize; `done`: finished inside the window. */
87
+ phase: 'reading' | 'running' | 'done';
88
+ /** ms since the adapter received the request (at report time, or until it finished). */
89
+ ageMs: number;
90
+ /** ms since the engine started on it (until report time, or until it finished). */
91
+ execMs?: number;
92
+ operationName?: string | null;
93
+ topLevel?: number;
94
+ selections?: number;
95
+ aliases?: number;
96
+ /** Root field name -> number of aliases selecting it; names the schema does not resolve are summed as `unknown`. */
97
+ fields?: Record<string, number>;
98
+ userAgent?: string;
99
+ }
100
+ /** `[gql] event loop stall` report: the probe timer fired `maxMs` late in the window starting at `windowStart`. */
101
+ interface EventLoopStallReport {
102
+ maxMs: number;
103
+ windowStart: string;
104
+ thresholdMs: number;
105
+ inFlightTotal: number;
106
+ /** In-flight requests plus the ones that finished inside the window (the likely culprit), at most 20. */
107
+ inFlight: StallInFlightEntry[];
55
108
  }
56
109
  /**
57
110
  * Shape-only description of a slow request. Never carries argument values or variables: addresses
58
111
  * and other inputs stay in the access log, which already records the client and time.
59
112
  */
60
113
  interface SlowRequestReport {
114
+ /**
115
+ * ms from the adapter receiving the request until the engine started on it, body read included. Time a request
116
+ * spends before Node hands it to the adapter (socket not read while the loop is blocked) is not visible here;
117
+ * the stall line covers it.
118
+ */
119
+ queuedMs: number;
120
+ /** parse + execute + serialize; the request is logged when `queuedMs + totalMs >= slowLogMs`. */
61
121
  totalMs: number;
62
122
  parseMs: number;
63
123
  executeMs: number;
@@ -88,6 +148,8 @@ interface GqlRequestLike {
88
148
  body?: unknown;
89
149
  /** Read the raw body as utf-8, rejecting with `status: 413` above `limit` bytes. */
90
150
  readBody: (limit: number) => Promise<string>;
151
+ /** `performance.now()` when the adapter received the request; defaults to the engine's own start. */
152
+ receivedAt?: number;
91
153
  }
92
154
  /** Transport-agnostic response produced by the engine. */
93
155
  interface GqlResponseLike {
@@ -115,4 +177,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
115
177
  */
116
178
  declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
117
179
  //#endregion
118
- export { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
180
+ export { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
package/esm/http.mjs CHANGED
@@ -254,18 +254,21 @@ const defaultSlowRequestHandler = (report) => {
254
254
  console.warn("[gql] slow request", JSON.stringify(report));
255
255
  };
256
256
  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();
257
+ /**
258
+ * Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
259
+ * each named fragment counted once, bounded).
260
+ */
261
+ const collectRootFieldCounts = (documentAST, operationName, maxFragmentDepth = MAX_QUERY_DEPTH * 2) => {
262
+ const names = /* @__PURE__ */ new Map();
260
263
  const op = getOperationAST(documentAST, operationName || void 0);
261
264
  if (!op) return names;
262
265
  const fragments = /* @__PURE__ */ new Map();
263
266
  for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition") fragments.set(def.name.value, def.selectionSet.selections);
264
267
  const seen = /* @__PURE__ */ new Set();
265
268
  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)) {
269
+ for (const sel of selections) if (sel.kind === "Field") names.set(sel.name.value, (names.get(sel.name.value) || 0) + 1);
270
+ else if (depth < maxFragmentDepth && sel.kind === "InlineFragment") walk(sel.selectionSet.selections, depth + 1);
271
+ else if (depth < maxFragmentDepth && sel.kind === "FragmentSpread" && !seen.has(sel.name.value)) {
269
272
  seen.add(sel.name.value);
270
273
  walk(fragments.get(sel.name.value) || [], depth + 1);
271
274
  }
@@ -274,6 +277,126 @@ const collectRootFieldNames = (documentAST, operationName) => {
274
277
  return names;
275
278
  };
276
279
  const headerValue = (v) => Array.isArray(v) ? v[0] : v;
280
+ const MAX_SHAPES_PER_FIELD = 8;
281
+ const MAX_STALL_ENTRIES = 20;
282
+ const MAX_RECENT_DONE = 64;
283
+ const MIN_STALL_LOG_MS = 20;
284
+ const timeCategory = (v) => {
285
+ if (v === void 0) return "absent";
286
+ if (v === null) return "null";
287
+ if (typeof v !== "string") return "invalid";
288
+ if (v === "") return "empty";
289
+ if (v === "null") return "null-string";
290
+ return Number.isNaN(Date.parse(v)) ? "invalid" : "date";
291
+ };
292
+ /**
293
+ * Shape key of one root field call's coerced arguments (see `SlowRequestShapeStat`). graphql-js only puts schema
294
+ * argument names in `args`, so the key never contains client-chosen strings; values are reduced to categories.
295
+ */
296
+ const describeArgShape = (args) => {
297
+ if (args == null || typeof args !== "object") return "-";
298
+ const a = args;
299
+ const names = Object.keys(a).filter((k) => a[k] !== void 0).sort();
300
+ let key = names.length ? names.join(",") : "-";
301
+ if ("paging" in a && a.paging !== void 0) {
302
+ const size = a.paging === null ? void 0 : a.paging.size;
303
+ let sizeCat;
304
+ if (a.paging === null) sizeCat = "null";
305
+ else if (size === void 0) sizeCat = "absent";
306
+ else if (typeof size === "number" && Number.isInteger(size) && size >= 0 && size <= 1e6) sizeCat = String(size);
307
+ else sizeCat = "invalid";
308
+ key += `|size=${sizeCat}`;
309
+ }
310
+ if ("timeFilter" in a && a.timeFilter !== void 0) if (a.timeFilter === null || typeof a.timeFilter !== "object") key += "|time=null";
311
+ else {
312
+ const t = a.timeFilter;
313
+ key += `|start=${timeCategory(t.startDateTime)}|end=${timeCategory(t.endDateTime)}`;
314
+ }
315
+ return key;
316
+ };
317
+ /** Total length of the list payloads (`transactions`, `assets`, ...) in a wrapped resolver result. */
318
+ const countRows = (out) => {
319
+ if (out == null || typeof out !== "object") return 0;
320
+ let rows = 0;
321
+ for (const [k, v] of Object.entries(out)) if (k !== "page" && Array.isArray(v)) rows += v.length;
322
+ return rows;
323
+ };
324
+ const defaultStallHandler = (report) => {
325
+ console.warn("[gql] event loop stall", JSON.stringify(report));
326
+ };
327
+ /**
328
+ * Timer drift probe: an unref'd interval measures how late it fires. A tick that is `>= thresholdMs` late means the
329
+ * loop was blocked between the previous tick and now; the requests whose lifetime overlaps that window are listed,
330
+ * including those that already finished (a request whose resolvers block synchronously is always done by the time
331
+ * any timer runs). `perf_hooks.monitorEventLoopDelay` only yields a histogram, not the stall's window, so it cannot
332
+ * attribute the stall; the probe also works on every runtime that has timers.
333
+ */
334
+ const createStallMonitor = (requestedMs, report, rootValue) => {
335
+ const thresholdMs = Math.max(MIN_STALL_LOG_MS, requestedMs);
336
+ const active = /* @__PURE__ */ new Set();
337
+ let recentDone = [];
338
+ let timer = null;
339
+ const intervalMs = Math.max(10, Math.min(100, Math.floor(thresholdMs / 2)));
340
+ let lastTick = 0;
341
+ const summarize = (rec, now) => {
342
+ const end = rec.finishedAt ?? now;
343
+ const entry = {
344
+ phase: rec.finishedAt !== void 0 ? "done" : rec.startedAt !== void 0 ? "running" : "reading",
345
+ ageMs: Math.round(end - rec.receivedAt)
346
+ };
347
+ if (rec.startedAt !== void 0) entry.execMs = Math.round(end - rec.startedAt);
348
+ if (rec.documentAST) {
349
+ entry.operationName = rec.operationName ? rec.operationName.slice(0, 100) : null;
350
+ entry.topLevel = countTopLevelSelections(rec.documentAST, Number.MAX_SAFE_INTEGER);
351
+ const { fields: selections, aliases } = countTotalSelectionsAndAliases(rec.documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
352
+ entry.selections = selections;
353
+ entry.aliases = aliases;
354
+ const fields = Object.create(null);
355
+ for (const [name, n] of collectRootFieldCounts(rec.documentAST, rec.operationName ?? null)) {
356
+ const key = Object.hasOwn(rootValue, name) ? name : "unknown";
357
+ fields[key] = (fields[key] || 0) + n;
358
+ }
359
+ entry.fields = fields;
360
+ }
361
+ const ua = headerValue(rec.headers["user-agent"]);
362
+ if (ua) entry.userAgent = ua.slice(0, 160);
363
+ return entry;
364
+ };
365
+ const tick = () => {
366
+ const now = nowMs();
367
+ const lateMs = now - lastTick - intervalMs;
368
+ const windowStartedAt = lastTick;
369
+ lastTick = now;
370
+ if (lateMs >= thresholdMs) try {
371
+ const overlapping = [...recentDone.filter((r) => r.finishedAt >= windowStartedAt), ...active].sort((a, b) => a.receivedAt - b.receivedAt);
372
+ report({
373
+ maxMs: Math.round(lateMs),
374
+ windowStart: new Date(Date.now() - (now - windowStartedAt)).toISOString(),
375
+ thresholdMs,
376
+ inFlightTotal: overlapping.length,
377
+ inFlight: overlapping.slice(0, MAX_STALL_ENTRIES).map((r) => summarize(r, now))
378
+ });
379
+ } catch {}
380
+ recentDone = [];
381
+ };
382
+ return {
383
+ begin(rec) {
384
+ if (!timer) {
385
+ lastTick = nowMs();
386
+ timer = setInterval(tick, intervalMs);
387
+ timer.unref?.();
388
+ }
389
+ active.add(rec);
390
+ },
391
+ end(rec) {
392
+ rec.finishedAt = nowMs();
393
+ active.delete(rec);
394
+ recentDone.push(rec);
395
+ if (recentDone.length > MAX_RECENT_DONE) recentDone.shift();
396
+ }
397
+ };
398
+ };
399
+ const canProbeEventLoop = () => typeof setInterval === "function" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers");
277
400
  /**
278
401
  * Read the raw express request body as a utf-8 string, enforcing the size limit.
279
402
  * Mirrors express-graphql's parseBody behavior for the subset of content
@@ -816,9 +939,10 @@ const parseEnvBoolean = (raw) => {
816
939
  if (normalized === "1" || normalized === "true") return true;
817
940
  if (normalized === "0" || normalized === "false") return false;
818
941
  };
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 }) => {
942
+ 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 }) => {
820
943
  const schema = buildSchema(schemaSource);
821
944
  const rootValue = createResolvers(resolver);
945
+ const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
822
946
  const formatGraphQLError = (err) => {
823
947
  onError(err);
824
948
  const includeStack = showStack && process.env.NODE_ENV !== "production";
@@ -852,7 +976,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
852
976
  headers: { "content-type": "text/html; charset=utf-8" },
853
977
  body: html
854
978
  });
855
- return async (req, contextValue) => {
979
+ const run = async (req, contextValue, rec) => {
856
980
  if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
857
981
  let params;
858
982
  try {
@@ -866,6 +990,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
866
990
  return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
867
991
  }
868
992
  const startedAt = slowLogMs > 0 ? nowMs() : 0;
993
+ if (rec) rec.startedAt = startedAt;
869
994
  const { query: normalizedQuery, prefix: aliasPrefix, aliasMap } = normalizeNumericFieldAliases(params.query);
870
995
  const formatError = (err) => restoreNumericAliasesInFormattedError(formatGraphQLError(err), aliasPrefix, aliasMap);
871
996
  let documentAST;
@@ -897,27 +1022,66 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
897
1022
  const operationAST = getOperationAST(documentAST, params.operationName || void 0);
898
1023
  if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
899
1024
  }
1025
+ if (rec) {
1026
+ rec.documentAST = documentAST;
1027
+ rec.operationName = params.operationName;
1028
+ }
900
1029
  const fieldStats = /* @__PURE__ */ new Map();
901
1030
  let requestRoot = rootValue;
902
1031
  if (slowLogMs > 0) {
903
1032
  requestRoot = Object.create(rootValue);
904
- for (const name of collectRootFieldNames(documentAST, params.operationName)) {
1033
+ const fragmentDepthCap = Math.max(maxQueryDepth, MAX_QUERY_DEPTH) * 2;
1034
+ for (const name of collectRootFieldCounts(documentAST, params.operationName, fragmentDepthCap).keys()) {
1035
+ if (!Object.hasOwn(rootValue, name)) continue;
905
1036
  const fn = rootValue[name];
906
1037
  if (typeof fn !== "function") continue;
907
1038
  requestRoot[name] = async (...args) => {
1039
+ let shape = "other";
1040
+ try {
1041
+ shape = describeArgShape(args[0]);
1042
+ } catch {}
908
1043
  const t = nowMs();
1044
+ let syncMs = 0;
1045
+ let rows = 0;
909
1046
  try {
910
- return await fn(...args);
1047
+ let pending;
1048
+ try {
1049
+ pending = fn.apply(rootValue, args);
1050
+ } finally {
1051
+ syncMs = nowMs() - t;
1052
+ }
1053
+ const out = await pending;
1054
+ try {
1055
+ rows = countRows(out);
1056
+ } catch {}
1057
+ return out;
911
1058
  } finally {
912
1059
  const ms = nowMs() - t;
913
1060
  const s = fieldStats.get(name) || {
914
1061
  count: 0,
915
1062
  wallSumMs: 0,
916
- wallMaxMs: 0
1063
+ wallMaxMs: 0,
1064
+ syncSumMs: 0,
1065
+ syncMaxMs: 0,
1066
+ rows: 0,
1067
+ shapes: Object.create(null)
917
1068
  };
918
1069
  s.count += 1;
919
1070
  s.wallSumMs += ms;
920
1071
  if (ms > s.wallMaxMs) s.wallMaxMs = ms;
1072
+ s.syncSumMs += syncMs;
1073
+ if (syncMs > s.syncMaxMs) s.syncMaxMs = syncMs;
1074
+ s.rows += rows;
1075
+ if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
1076
+ const b = s.shapes[shape] || {
1077
+ count: 0,
1078
+ rows: 0,
1079
+ syncMs: 0
1080
+ };
1081
+ b.count += 1;
1082
+ b.rows += rows;
1083
+ b.syncMs += syncMs;
1084
+ s.shapes[shape] = b;
921
1085
  fieldStats.set(name, s);
922
1086
  }
923
1087
  };
@@ -945,16 +1109,30 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
945
1109
  const response = sendJSON(status, formattedResult);
946
1110
  const finishedAt = nowMs();
947
1111
  const totalMs = finishedAt - startedAt;
948
- if (totalMs >= slowLogMs) try {
1112
+ const queuedMs = rec ? Math.max(0, startedAt - rec.receivedAt) : 0;
1113
+ if (totalMs + queuedMs >= slowLogMs) try {
949
1114
  const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
950
1115
  const round = (n) => Math.round(n);
951
1116
  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
- };
1117
+ for (const [name, s] of fieldStats) {
1118
+ const shapes = Object.create(null);
1119
+ for (const [k, b] of Object.entries(s.shapes)) shapes[k] = {
1120
+ count: b.count,
1121
+ rows: b.rows,
1122
+ syncMs: round(b.syncMs)
1123
+ };
1124
+ fields[name] = {
1125
+ count: s.count,
1126
+ wallSumMs: round(s.wallSumMs),
1127
+ wallMaxMs: round(s.wallMaxMs),
1128
+ syncSumMs: round(s.syncSumMs),
1129
+ syncMaxMs: round(s.syncMaxMs),
1130
+ rows: s.rows,
1131
+ shapes
1132
+ };
1133
+ }
957
1134
  onSlowRequest({
1135
+ queuedMs: round(queuedMs),
958
1136
  totalMs: round(totalMs),
959
1137
  parseMs: round(executeStartedAt - startedAt),
960
1138
  executeMs: round(executedAt - executeStartedAt),
@@ -974,12 +1152,26 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
974
1152
  } catch {}
975
1153
  return response;
976
1154
  };
1155
+ if (slowLogMs <= 0) return (req, contextValue) => run(req, contextValue, null);
1156
+ return async (req, contextValue) => {
1157
+ const rec = {
1158
+ receivedAt: req.receivedAt ?? nowMs(),
1159
+ headers: req.headers
1160
+ };
1161
+ stallMonitor?.begin(rec);
1162
+ try {
1163
+ return await run(req, contextValue, rec);
1164
+ } finally {
1165
+ stallMonitor?.end(rec);
1166
+ }
1167
+ };
977
1168
  };
978
1169
  /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
979
1170
  const createHttpHandler = (options) => {
980
1171
  const engine = createGraphQLEngine(options);
981
1172
  return async (req, res) => {
982
1173
  const result = await engine({
1174
+ receivedAt: nowMs(),
983
1175
  method: req.method,
984
1176
  url: req.url,
985
1177
  headers: req.headers,
@@ -1024,12 +1216,14 @@ const readFetchBody = async (request, limit) => {
1024
1216
  const createFetchHandler = (options) => {
1025
1217
  const engine = createGraphQLEngine(options);
1026
1218
  return async (request) => {
1219
+ const receivedAt = nowMs();
1027
1220
  const headers = {};
1028
1221
  request.headers.forEach((value, key) => {
1029
1222
  headers[key.toLowerCase()] = value;
1030
1223
  });
1031
1224
  const url = new URL(request.url);
1032
1225
  const result = await engine({
1226
+ receivedAt,
1033
1227
  method: request.method,
1034
1228
  url: `${url.pathname}${url.search}`,
1035
1229
  headers,
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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, 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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, normalizeNumericFieldAliases, wrapResolver };
package/lib/http.cjs CHANGED
@@ -257,18 +257,21 @@ const defaultSlowRequestHandler = (report) => {
257
257
  console.warn("[gql] slow request", JSON.stringify(report));
258
258
  };
259
259
  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();
260
+ /**
261
+ * Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
262
+ * each named fragment counted once, bounded).
263
+ */
264
+ const collectRootFieldCounts = (documentAST, operationName, maxFragmentDepth = MAX_QUERY_DEPTH * 2) => {
265
+ const names = /* @__PURE__ */ new Map();
263
266
  const op = (0, graphql.getOperationAST)(documentAST, operationName || void 0);
264
267
  if (!op) return names;
265
268
  const fragments = /* @__PURE__ */ new Map();
266
269
  for (const def of documentAST.definitions) if (def.kind === "FragmentDefinition") fragments.set(def.name.value, def.selectionSet.selections);
267
270
  const seen = /* @__PURE__ */ new Set();
268
271
  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)) {
272
+ for (const sel of selections) if (sel.kind === "Field") names.set(sel.name.value, (names.get(sel.name.value) || 0) + 1);
273
+ else if (depth < maxFragmentDepth && sel.kind === "InlineFragment") walk(sel.selectionSet.selections, depth + 1);
274
+ else if (depth < maxFragmentDepth && sel.kind === "FragmentSpread" && !seen.has(sel.name.value)) {
272
275
  seen.add(sel.name.value);
273
276
  walk(fragments.get(sel.name.value) || [], depth + 1);
274
277
  }
@@ -277,6 +280,126 @@ const collectRootFieldNames = (documentAST, operationName) => {
277
280
  return names;
278
281
  };
279
282
  const headerValue = (v) => Array.isArray(v) ? v[0] : v;
283
+ const MAX_SHAPES_PER_FIELD = 8;
284
+ const MAX_STALL_ENTRIES = 20;
285
+ const MAX_RECENT_DONE = 64;
286
+ const MIN_STALL_LOG_MS = 20;
287
+ const timeCategory = (v) => {
288
+ if (v === void 0) return "absent";
289
+ if (v === null) return "null";
290
+ if (typeof v !== "string") return "invalid";
291
+ if (v === "") return "empty";
292
+ if (v === "null") return "null-string";
293
+ return Number.isNaN(Date.parse(v)) ? "invalid" : "date";
294
+ };
295
+ /**
296
+ * Shape key of one root field call's coerced arguments (see `SlowRequestShapeStat`). graphql-js only puts schema
297
+ * argument names in `args`, so the key never contains client-chosen strings; values are reduced to categories.
298
+ */
299
+ const describeArgShape = (args) => {
300
+ if (args == null || typeof args !== "object") return "-";
301
+ const a = args;
302
+ const names = Object.keys(a).filter((k) => a[k] !== void 0).sort();
303
+ let key = names.length ? names.join(",") : "-";
304
+ if ("paging" in a && a.paging !== void 0) {
305
+ const size = a.paging === null ? void 0 : a.paging.size;
306
+ let sizeCat;
307
+ if (a.paging === null) sizeCat = "null";
308
+ else if (size === void 0) sizeCat = "absent";
309
+ else if (typeof size === "number" && Number.isInteger(size) && size >= 0 && size <= 1e6) sizeCat = String(size);
310
+ else sizeCat = "invalid";
311
+ key += `|size=${sizeCat}`;
312
+ }
313
+ if ("timeFilter" in a && a.timeFilter !== void 0) if (a.timeFilter === null || typeof a.timeFilter !== "object") key += "|time=null";
314
+ else {
315
+ const t = a.timeFilter;
316
+ key += `|start=${timeCategory(t.startDateTime)}|end=${timeCategory(t.endDateTime)}`;
317
+ }
318
+ return key;
319
+ };
320
+ /** Total length of the list payloads (`transactions`, `assets`, ...) in a wrapped resolver result. */
321
+ const countRows = (out) => {
322
+ if (out == null || typeof out !== "object") return 0;
323
+ let rows = 0;
324
+ for (const [k, v] of Object.entries(out)) if (k !== "page" && Array.isArray(v)) rows += v.length;
325
+ return rows;
326
+ };
327
+ const defaultStallHandler = (report) => {
328
+ console.warn("[gql] event loop stall", JSON.stringify(report));
329
+ };
330
+ /**
331
+ * Timer drift probe: an unref'd interval measures how late it fires. A tick that is `>= thresholdMs` late means the
332
+ * loop was blocked between the previous tick and now; the requests whose lifetime overlaps that window are listed,
333
+ * including those that already finished (a request whose resolvers block synchronously is always done by the time
334
+ * any timer runs). `perf_hooks.monitorEventLoopDelay` only yields a histogram, not the stall's window, so it cannot
335
+ * attribute the stall; the probe also works on every runtime that has timers.
336
+ */
337
+ const createStallMonitor = (requestedMs, report, rootValue) => {
338
+ const thresholdMs = Math.max(MIN_STALL_LOG_MS, requestedMs);
339
+ const active = /* @__PURE__ */ new Set();
340
+ let recentDone = [];
341
+ let timer = null;
342
+ const intervalMs = Math.max(10, Math.min(100, Math.floor(thresholdMs / 2)));
343
+ let lastTick = 0;
344
+ const summarize = (rec, now) => {
345
+ const end = rec.finishedAt ?? now;
346
+ const entry = {
347
+ phase: rec.finishedAt !== void 0 ? "done" : rec.startedAt !== void 0 ? "running" : "reading",
348
+ ageMs: Math.round(end - rec.receivedAt)
349
+ };
350
+ if (rec.startedAt !== void 0) entry.execMs = Math.round(end - rec.startedAt);
351
+ if (rec.documentAST) {
352
+ entry.operationName = rec.operationName ? rec.operationName.slice(0, 100) : null;
353
+ entry.topLevel = countTopLevelSelections(rec.documentAST, Number.MAX_SAFE_INTEGER);
354
+ const { fields: selections, aliases } = countTotalSelectionsAndAliases(rec.documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
355
+ entry.selections = selections;
356
+ entry.aliases = aliases;
357
+ const fields = Object.create(null);
358
+ for (const [name, n] of collectRootFieldCounts(rec.documentAST, rec.operationName ?? null)) {
359
+ const key = Object.hasOwn(rootValue, name) ? name : "unknown";
360
+ fields[key] = (fields[key] || 0) + n;
361
+ }
362
+ entry.fields = fields;
363
+ }
364
+ const ua = headerValue(rec.headers["user-agent"]);
365
+ if (ua) entry.userAgent = ua.slice(0, 160);
366
+ return entry;
367
+ };
368
+ const tick = () => {
369
+ const now = nowMs();
370
+ const lateMs = now - lastTick - intervalMs;
371
+ const windowStartedAt = lastTick;
372
+ lastTick = now;
373
+ if (lateMs >= thresholdMs) try {
374
+ const overlapping = [...recentDone.filter((r) => r.finishedAt >= windowStartedAt), ...active].sort((a, b) => a.receivedAt - b.receivedAt);
375
+ report({
376
+ maxMs: Math.round(lateMs),
377
+ windowStart: new Date(Date.now() - (now - windowStartedAt)).toISOString(),
378
+ thresholdMs,
379
+ inFlightTotal: overlapping.length,
380
+ inFlight: overlapping.slice(0, MAX_STALL_ENTRIES).map((r) => summarize(r, now))
381
+ });
382
+ } catch {}
383
+ recentDone = [];
384
+ };
385
+ return {
386
+ begin(rec) {
387
+ if (!timer) {
388
+ lastTick = nowMs();
389
+ timer = setInterval(tick, intervalMs);
390
+ timer.unref?.();
391
+ }
392
+ active.add(rec);
393
+ },
394
+ end(rec) {
395
+ rec.finishedAt = nowMs();
396
+ active.delete(rec);
397
+ recentDone.push(rec);
398
+ if (recentDone.length > MAX_RECENT_DONE) recentDone.shift();
399
+ }
400
+ };
401
+ };
402
+ const canProbeEventLoop = () => typeof setInterval === "function" && !(typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers");
280
403
  /**
281
404
  * Read the raw express request body as a utf-8 string, enforcing the size limit.
282
405
  * Mirrors express-graphql's parseBody behavior for the subset of content
@@ -819,9 +942,10 @@ const parseEnvBoolean = (raw) => {
819
942
  if (normalized === "1" || normalized === "true") return true;
820
943
  if (normalized === "0" || normalized === "false") return false;
821
944
  };
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 }) => {
945
+ 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 }) => {
823
946
  const schema = (0, graphql.buildSchema)(_ocap_schema.default);
824
947
  const rootValue = createResolvers(resolver);
948
+ const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
825
949
  const formatGraphQLError = (err) => {
826
950
  onError(err);
827
951
  const includeStack = showStack && process.env.NODE_ENV !== "production";
@@ -855,7 +979,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
855
979
  headers: { "content-type": "text/html; charset=utf-8" },
856
980
  body: html
857
981
  });
858
- return async (req, contextValue) => {
982
+ const run = async (req, contextValue, rec) => {
859
983
  if (req.method !== "GET" && req.method !== "POST") return sendJSON(405, { errors: [formatAnyError("GraphQL only supports GET and POST requests.")] }, { Allow: "GET, POST" });
860
984
  let params;
861
985
  try {
@@ -869,6 +993,7 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
869
993
  return sendJSON(400, { errors: [formatAnyError("Must provide query string.")] });
870
994
  }
871
995
  const startedAt = slowLogMs > 0 ? nowMs() : 0;
996
+ if (rec) rec.startedAt = startedAt;
872
997
  const { query: normalizedQuery, prefix: aliasPrefix, aliasMap } = normalizeNumericFieldAliases(params.query);
873
998
  const formatError = (err) => restoreNumericAliasesInFormattedError(formatGraphQLError(err), aliasPrefix, aliasMap);
874
999
  let documentAST;
@@ -900,27 +1025,66 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
900
1025
  const operationAST = (0, graphql.getOperationAST)(documentAST, params.operationName || void 0);
901
1026
  if (operationAST && operationAST.operation !== "query") return sendJSON(405, { errors: [formatAnyError(`Can only perform a ${operationAST.operation} operation from a POST request.`)] }, { Allow: "POST" });
902
1027
  }
1028
+ if (rec) {
1029
+ rec.documentAST = documentAST;
1030
+ rec.operationName = params.operationName;
1031
+ }
903
1032
  const fieldStats = /* @__PURE__ */ new Map();
904
1033
  let requestRoot = rootValue;
905
1034
  if (slowLogMs > 0) {
906
1035
  requestRoot = Object.create(rootValue);
907
- for (const name of collectRootFieldNames(documentAST, params.operationName)) {
1036
+ const fragmentDepthCap = Math.max(maxQueryDepth, MAX_QUERY_DEPTH) * 2;
1037
+ for (const name of collectRootFieldCounts(documentAST, params.operationName, fragmentDepthCap).keys()) {
1038
+ if (!Object.hasOwn(rootValue, name)) continue;
908
1039
  const fn = rootValue[name];
909
1040
  if (typeof fn !== "function") continue;
910
1041
  requestRoot[name] = async (...args) => {
1042
+ let shape = "other";
1043
+ try {
1044
+ shape = describeArgShape(args[0]);
1045
+ } catch {}
911
1046
  const t = nowMs();
1047
+ let syncMs = 0;
1048
+ let rows = 0;
912
1049
  try {
913
- return await fn(...args);
1050
+ let pending;
1051
+ try {
1052
+ pending = fn.apply(rootValue, args);
1053
+ } finally {
1054
+ syncMs = nowMs() - t;
1055
+ }
1056
+ const out = await pending;
1057
+ try {
1058
+ rows = countRows(out);
1059
+ } catch {}
1060
+ return out;
914
1061
  } finally {
915
1062
  const ms = nowMs() - t;
916
1063
  const s = fieldStats.get(name) || {
917
1064
  count: 0,
918
1065
  wallSumMs: 0,
919
- wallMaxMs: 0
1066
+ wallMaxMs: 0,
1067
+ syncSumMs: 0,
1068
+ syncMaxMs: 0,
1069
+ rows: 0,
1070
+ shapes: Object.create(null)
920
1071
  };
921
1072
  s.count += 1;
922
1073
  s.wallSumMs += ms;
923
1074
  if (ms > s.wallMaxMs) s.wallMaxMs = ms;
1075
+ s.syncSumMs += syncMs;
1076
+ if (syncMs > s.syncMaxMs) s.syncMaxMs = syncMs;
1077
+ s.rows += rows;
1078
+ if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
1079
+ const b = s.shapes[shape] || {
1080
+ count: 0,
1081
+ rows: 0,
1082
+ syncMs: 0
1083
+ };
1084
+ b.count += 1;
1085
+ b.rows += rows;
1086
+ b.syncMs += syncMs;
1087
+ s.shapes[shape] = b;
924
1088
  fieldStats.set(name, s);
925
1089
  }
926
1090
  };
@@ -948,16 +1112,30 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
948
1112
  const response = sendJSON(status, formattedResult);
949
1113
  const finishedAt = nowMs();
950
1114
  const totalMs = finishedAt - startedAt;
951
- if (totalMs >= slowLogMs) try {
1115
+ const queuedMs = rec ? Math.max(0, startedAt - rec.receivedAt) : 0;
1116
+ if (totalMs + queuedMs >= slowLogMs) try {
952
1117
  const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
953
1118
  const round = (n) => Math.round(n);
954
1119
  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
- };
1120
+ for (const [name, s] of fieldStats) {
1121
+ const shapes = Object.create(null);
1122
+ for (const [k, b] of Object.entries(s.shapes)) shapes[k] = {
1123
+ count: b.count,
1124
+ rows: b.rows,
1125
+ syncMs: round(b.syncMs)
1126
+ };
1127
+ fields[name] = {
1128
+ count: s.count,
1129
+ wallSumMs: round(s.wallSumMs),
1130
+ wallMaxMs: round(s.wallMaxMs),
1131
+ syncSumMs: round(s.syncSumMs),
1132
+ syncMaxMs: round(s.syncMaxMs),
1133
+ rows: s.rows,
1134
+ shapes
1135
+ };
1136
+ }
960
1137
  onSlowRequest({
1138
+ queuedMs: round(queuedMs),
961
1139
  totalMs: round(totalMs),
962
1140
  parseMs: round(executeStartedAt - startedAt),
963
1141
  executeMs: round(executedAt - executeStartedAt),
@@ -977,12 +1155,26 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
977
1155
  } catch {}
978
1156
  return response;
979
1157
  };
1158
+ if (slowLogMs <= 0) return (req, contextValue) => run(req, contextValue, null);
1159
+ return async (req, contextValue) => {
1160
+ const rec = {
1161
+ receivedAt: req.receivedAt ?? nowMs(),
1162
+ headers: req.headers
1163
+ };
1164
+ stallMonitor?.begin(rec);
1165
+ try {
1166
+ return await run(req, contextValue, rec);
1167
+ } finally {
1168
+ stallMonitor?.end(rec);
1169
+ }
1170
+ };
980
1171
  };
981
1172
  /** Express / connect adapter. Behavior is unchanged from the pre-split `createHttpHandler`. */
982
1173
  const createHttpHandler = (options) => {
983
1174
  const engine = createGraphQLEngine(options);
984
1175
  return async (req, res) => {
985
1176
  const result = await engine({
1177
+ receivedAt: nowMs(),
986
1178
  method: req.method,
987
1179
  url: req.url,
988
1180
  headers: req.headers,
@@ -1027,12 +1219,14 @@ const readFetchBody = async (request, limit) => {
1027
1219
  const createFetchHandler = (options) => {
1028
1220
  const engine = createGraphQLEngine(options);
1029
1221
  return async (request) => {
1222
+ const receivedAt = nowMs();
1030
1223
  const headers = {};
1031
1224
  request.headers.forEach((value, key) => {
1032
1225
  headers[key.toLowerCase()] = value;
1033
1226
  });
1034
1227
  const url = new URL(request.url);
1035
1228
  const result = await engine({
1229
+ receivedAt,
1036
1230
  method: request.method,
1037
1231
  url: `${url.pathname}${url.search}`,
1038
1232
  headers,
package/lib/http.d.cts CHANGED
@@ -35,29 +35,89 @@ 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
+ /**
54
+ * Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
55
+ * then `size=<paging.size>` when `paging` is present and `start=`/`end=` categories when `timeFilter` is present:
56
+ * `absent`, `empty` (""), `null-string` ("null"), `null`, `date` (parses as a date) or `invalid`. No argument value
57
+ * other than the integer `paging.size` is ever part of the key.
58
+ */
59
+ interface SlowRequestShapeStat {
60
+ count: number;
61
+ /** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
62
+ rows: number;
63
+ /** Synchronous time inside the resolver calls of this bucket. */
64
+ syncMs: number;
44
65
  }
45
66
  /**
46
67
  * Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
47
68
  * 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.
69
+ * most `executeMs`, and `wallSumMs` can exceed it. `syncSumMs` / `syncMaxMs` only count the time spent inside the
70
+ * resolver call before it returns its promise (for the SQLite index this includes the query itself, not the
71
+ * per-row formatting that runs after the first await), so they do not overlap and their sum stays within `executeMs`.
50
72
  */
51
73
  interface SlowRequestFieldStat {
52
74
  count: number;
53
75
  wallSumMs: number;
54
76
  wallMaxMs: number;
77
+ syncSumMs: number;
78
+ syncMaxMs: number;
79
+ /** Rows returned over all aliases (sum of list payload lengths). */
80
+ rows: number;
81
+ /** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
82
+ shapes: Record<string, SlowRequestShapeStat>;
83
+ }
84
+ /** One request that was in flight (or finished) during a stalled probe window. Never carries argument values. */
85
+ interface StallInFlightEntry {
86
+ /** `reading`: body not yet parsed; `running`: parse/execute/serialize; `done`: finished inside the window. */
87
+ phase: 'reading' | 'running' | 'done';
88
+ /** ms since the adapter received the request (at report time, or until it finished). */
89
+ ageMs: number;
90
+ /** ms since the engine started on it (until report time, or until it finished). */
91
+ execMs?: number;
92
+ operationName?: string | null;
93
+ topLevel?: number;
94
+ selections?: number;
95
+ aliases?: number;
96
+ /** Root field name -> number of aliases selecting it; names the schema does not resolve are summed as `unknown`. */
97
+ fields?: Record<string, number>;
98
+ userAgent?: string;
99
+ }
100
+ /** `[gql] event loop stall` report: the probe timer fired `maxMs` late in the window starting at `windowStart`. */
101
+ interface EventLoopStallReport {
102
+ maxMs: number;
103
+ windowStart: string;
104
+ thresholdMs: number;
105
+ inFlightTotal: number;
106
+ /** In-flight requests plus the ones that finished inside the window (the likely culprit), at most 20. */
107
+ inFlight: StallInFlightEntry[];
55
108
  }
56
109
  /**
57
110
  * Shape-only description of a slow request. Never carries argument values or variables: addresses
58
111
  * and other inputs stay in the access log, which already records the client and time.
59
112
  */
60
113
  interface SlowRequestReport {
114
+ /**
115
+ * ms from the adapter receiving the request until the engine started on it, body read included. Time a request
116
+ * spends before Node hands it to the adapter (socket not read while the loop is blocked) is not visible here;
117
+ * the stall line covers it.
118
+ */
119
+ queuedMs: number;
120
+ /** parse + execute + serialize; the request is logged when `queuedMs + totalMs >= slowLogMs`. */
61
121
  totalMs: number;
62
122
  parseMs: number;
63
123
  executeMs: number;
@@ -88,6 +148,8 @@ interface GqlRequestLike {
88
148
  body?: unknown;
89
149
  /** Read the raw body as utf-8, rejecting with `status: 413` above `limit` bytes. */
90
150
  readBody: (limit: number) => Promise<string>;
151
+ /** `performance.now()` when the adapter received the request; defaults to the engine's own start. */
152
+ receivedAt?: number;
91
153
  }
92
154
  /** Transport-agnostic response produced by the engine. */
93
155
  interface GqlResponseLike {
@@ -115,4 +177,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
115
177
  */
116
178
  declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
117
179
  //#endregion
118
- export { GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
180
+ export { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, 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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, 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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, createSocketHandler, formatContext, normalizeNumericFieldAliases, wrapResolver };
package/package.json CHANGED
@@ -3,7 +3,7 @@
3
3
  "publishConfig": {
4
4
  "access": "public"
5
5
  },
6
- "version": "1.31.7",
6
+ "version": "1.31.8",
7
7
  "description": "Resolver middleware for ocap adapters",
8
8
  "type": "module",
9
9
  "main": "./lib/index.cjs",
@@ -51,8 +51,8 @@
51
51
  ],
52
52
  "license": "MIT",
53
53
  "dependencies": {
54
- "@arcblock/ws": "1.31.7",
55
- "@ocap/schema": "1.31.7",
54
+ "@arcblock/ws": "1.31.8",
55
+ "@ocap/schema": "1.31.8",
56
56
  "graphql": "^16.13.2",
57
57
  "lodash": "^4.17.23"
58
58
  },