@ocap/gql 1.31.8 → 1.31.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +29 -5
- package/esm/http.d.mts +53 -8
- package/esm/http.mjs +98 -23
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/lib/http.cjs +100 -22
- package/lib/http.d.cts +53 -8
- package/lib/index.cjs +3 -0
- package/lib/index.d.cts +2 -2
- package/package.json +4 -3
package/README.md
CHANGED
|
@@ -38,6 +38,7 @@ responses are byte-identical with the logs on or off.
|
|
|
38
38
|
|---|---|---|---|
|
|
39
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
40
|
| `GQL_STALL_LOG_MS` | `stallLogMs` | `GQL_SLOW_LOG_MS` | Log an event loop stall when the probe timer fires this many ms late (minimum 20). `0` turns off only the stall log. |
|
|
41
|
+
| `GQL_SQL_TIMING` | `sqlTiming` | on for Bun / Workers / Node >= 24, off for Node 22 | Per root field SQLite time (`sql*` fields) in the slow-request log, via `AsyncLocalStorage`. `1` forces it on, `0` off. See below for the cost on Node 22. |
|
|
41
42
|
|
|
42
43
|
`[gql] slow request {...}` (example values below are illustrative):
|
|
43
44
|
|
|
@@ -45,17 +46,40 @@ responses are byte-identical with the logs on or off.
|
|
|
45
46
|
before Node hands the request to the adapter (the socket is not read while the loop is blocked) is not visible
|
|
46
47
|
here; the stall line covers it.
|
|
47
48
|
- `totalMs` = `parseMs` + `executeMs` + `serializeMs`.
|
|
49
|
+
- `sqlMs` / `sqlQueries`: SQLite execution time and statement count of all root fields (sum of the fields' `sqlSumMs`
|
|
50
|
+
/ `sqlQueries`). SQLite runs on the main thread, so `sqlMs` is within `executeMs`; the rest of `executeMs` is
|
|
51
|
+
JavaScript (graphql-js, resolver formatting) and waiting.
|
|
48
52
|
- `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`); `
|
|
50
|
-
|
|
51
|
-
`
|
|
52
|
-
|
|
53
|
+
interleaved, so the sum overlaps and can exceed `executeMs`); `sqlSumMs`/`sqlMaxMs`/`sqlQueries` (SQLite execution
|
|
54
|
+
time of all aliases / of the slowest alias, and statement count); `rows` (total length of the returned lists, e.g.
|
|
55
|
+
`transactions`); `shapes` (aliases bucketed by argument shape, at most 8 buckets plus `other`, each with `count`,
|
|
56
|
+
`rows`, `sqlMs`).
|
|
57
|
+
- SQL time is measured where the statements run (#1891): `@ocap/indexdb-sqlite` and `@ocap/statedb-sqlite` time the
|
|
58
|
+
synchronous part of every Kysely `executeQuery` (better-sqlite3 / bun:sqlite run the whole statement there) and add
|
|
59
|
+
it to the alias that issued it, found through an `AsyncLocalStorage` the handler runs each root field call in
|
|
60
|
+
(`@ocap/util/lib/sql-timing`). It counts statements after any number of `await`s, and never counts one statement
|
|
61
|
+
twice; a statement whose result several aliases share (a cache) counts for the alias that started it, and work that
|
|
62
|
+
outlives its field is not counted. The `sql*` fields are left out when SQL timing is off (below), when the runtime
|
|
63
|
+
has no `AsyncLocalStorage`, or when no SQLite backend in the process is timed: the Durable Object backend is not
|
|
64
|
+
(Workers freeze clocks during synchronous work).
|
|
65
|
+
- SQL timing on or off: `GQL_SQL_TIMING` (option `sqlTiming`) `1`/`true` forces it on, `0`/`false` off. Unset, it is
|
|
66
|
+
on where `AsyncLocalStorage` is cheap: Bun, Workers, Node >= 24 (AsyncContextFrame; off again with
|
|
67
|
+
`--no-async-context-frame`) and Node 22/23 started with `--experimental-async-context-frame`; it is **off on Node 22
|
|
68
|
+
by default**. There `AsyncLocalStorage` uses async_hooks: after the first request every promise in the process pays
|
|
69
|
+
for a hook, inside requests and outside them (the tx pipeline too). Measured on Node 22.23 + better-sqlite3 with the
|
|
70
|
+
production assembly, one process per setting (medians of 30): a 30-alias `listTransactions` batch 76.6 / 77.4 ms
|
|
71
|
+
with `GQL_SQL_TIMING=0` / `1` (SQL-bound, no visible change), but 3e5 bare `await`s outside any request 13.3 ms →
|
|
72
|
+
52.5 ms (about 4x). On Node 24.15 the same numbers are 75.9 / 76.2 ms and 13.5 / 13.3 ms. Turning it on on Node 22
|
|
73
|
+
is a trade: accurate per-field SQL time for slower promise-heavy code everywhere in the process.
|
|
74
|
+
- Removed in this version: `syncSumMs`/`syncMaxMs` and the shapes' `syncMs` (1.31.8). They timed only the resolver
|
|
75
|
+
call up to its first `await`, but Kysely awaits its connection before every statement, so they never included the
|
|
76
|
+
SQL (an 11 s `listTransactions` on beta reported `syncSumMs: 2`). Use `sqlSumMs`/`sqlMaxMs`/`sqlMs` instead.
|
|
53
77
|
- A shape key lists the argument names present, then `size=<paging.size>` when `paging` is given and
|
|
54
78
|
`start=`/`end=` when `timeFilter` is given, each one of `absent`, `empty` (`""`), `null-string` (`"null"`), `null`,
|
|
55
79
|
`date` or `invalid`.
|
|
56
80
|
|
|
57
81
|
```
|
|
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,"
|
|
82
|
+
[gql] slow request {"queuedMs":3,"totalMs":448,"parseMs":2,"executeMs":441,"serializeMs":5,"status":200,"responseChars":189199,"queryChars":38700,"operationName":null,"topLevel":30,"selections":1140,"aliases":30,"numericAliases":0,"errors":0,"sqlMs":396,"sqlQueries":75,"fields":{"listTransactions":{"count":30,"wallSumMs":6612,"wallMaxMs":440,"sqlSumMs":396,"sqlMaxMs":31,"sqlQueries":75,"rows":600,"shapes":{"accountFilter,paging,timeFilter|size=20|start=null-string|end=absent":{"count":30,"rows":600,"sqlMs":396}}}},"userAgent":"ArcWallet/5.10.9 ..."}
|
|
59
83
|
```
|
|
60
84
|
|
|
61
85
|
`[gql] event loop stall {...}` is written when the probe timer (an unref'd interval, started on the first request,
|
package/esm/http.d.mts
CHANGED
|
@@ -49,6 +49,14 @@ interface HttpHandlerOptions {
|
|
|
49
49
|
stallLogMs?: number;
|
|
50
50
|
/** Receives stall reports. Defaults to one `console.warn('[gql] event loop stall', json)` line. */
|
|
51
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;
|
|
52
60
|
}
|
|
53
61
|
/**
|
|
54
62
|
* Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
|
|
@@ -60,22 +68,32 @@ interface SlowRequestShapeStat {
|
|
|
60
68
|
count: number;
|
|
61
69
|
/** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
|
|
62
70
|
rows: number;
|
|
63
|
-
/**
|
|
64
|
-
|
|
71
|
+
/** SQLite execution time of the statements the aliases of this bucket ran (see `SlowRequestFieldStat.sqlSumMs`). */
|
|
72
|
+
sqlMs?: number;
|
|
65
73
|
}
|
|
66
74
|
/**
|
|
67
75
|
* Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
|
|
68
76
|
* awaits interleave, so a field's wall time also covers the other fields running alongside it: `wallMaxMs` is at
|
|
69
|
-
* most `executeMs`, and `wallSumMs` can exceed it.
|
|
70
|
-
*
|
|
71
|
-
*
|
|
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.
|
|
72
86
|
*/
|
|
73
87
|
interface SlowRequestFieldStat {
|
|
74
88
|
count: number;
|
|
75
89
|
wallSumMs: number;
|
|
76
90
|
wallMaxMs: number;
|
|
77
|
-
|
|
78
|
-
|
|
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;
|
|
79
97
|
/** Rows returned over all aliases (sum of list payload lengths). */
|
|
80
98
|
rows: number;
|
|
81
99
|
/** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
|
|
@@ -131,9 +149,36 @@ interface SlowRequestReport {
|
|
|
131
149
|
aliases: number;
|
|
132
150
|
numericAliases: number;
|
|
133
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;
|
|
134
159
|
fields: Record<string, SlowRequestFieldStat>;
|
|
135
160
|
userAgent?: string;
|
|
136
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;
|
|
137
182
|
/**
|
|
138
183
|
* Transport-agnostic view of an incoming GraphQL request, so the same engine serves express (`createHttpHandler`)
|
|
139
184
|
* and fetch-native runtimes such as Cloudflare Workers (`createFetchHandler`).
|
|
@@ -177,4 +222,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
|
|
|
177
222
|
*/
|
|
178
223
|
declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
|
|
179
224
|
//#endregion
|
|
180
|
-
export { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
|
|
225
|
+
export { AsyncContextRuntime, EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };
|
package/esm/http.mjs
CHANGED
|
@@ -216,11 +216,17 @@ const resolvers = [
|
|
|
216
216
|
dataKey: ["estimate"]
|
|
217
217
|
}
|
|
218
218
|
];
|
|
219
|
+
/** resolver fns whose rows reach the client only through the GraphQL `IndexedTransaction` type */
|
|
220
|
+
const TX_PROJECTION_FNS = new Set(["listTransactions", "listAssetTransactions"]);
|
|
219
221
|
const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
|
|
220
222
|
acc[fn] = async (args, ctx) => {
|
|
221
223
|
const res = await wrapResolver(fn, dataKey, () => {
|
|
222
224
|
const method = resolver[fn];
|
|
223
|
-
if (typeof method === "function")
|
|
225
|
+
if (typeof method === "function") {
|
|
226
|
+
const resolverCtx = formatContext(ctx);
|
|
227
|
+
if (TX_PROJECTION_FNS.has(fn)) resolverCtx.graphqlTxProjection = true;
|
|
228
|
+
return method.call(resolver, args, resolverCtx);
|
|
229
|
+
}
|
|
224
230
|
return null;
|
|
225
231
|
});
|
|
226
232
|
if (fn === "sendTx") {
|
|
@@ -254,6 +260,54 @@ const defaultSlowRequestHandler = (report) => {
|
|
|
254
260
|
console.warn("[gql] slow request", JSON.stringify(report));
|
|
255
261
|
};
|
|
256
262
|
const nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
263
|
+
/** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
|
|
264
|
+
const SQL_TIMING_KEY = Symbol.for("@ocap/sql-timing");
|
|
265
|
+
/** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
|
|
266
|
+
const SQL_TIMING_BACKEND_KEY = Symbol.for("@ocap/sql-timing/backend");
|
|
267
|
+
const currentAsyncContextRuntime = () => {
|
|
268
|
+
const proc = typeof process !== "undefined" ? process : void 0;
|
|
269
|
+
return {
|
|
270
|
+
bun: typeof proc?.versions?.bun === "string",
|
|
271
|
+
workers: typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers",
|
|
272
|
+
nodeVersion: proc?.versions?.node,
|
|
273
|
+
execArgv: Array.isArray(proc?.execArgv) ? proc.execArgv : [],
|
|
274
|
+
nodeOptions: typeof process !== "undefined" ? process.env?.NODE_OPTIONS : void 0
|
|
275
|
+
};
|
|
276
|
+
};
|
|
277
|
+
/**
|
|
278
|
+
* Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
|
|
279
|
+
* after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
|
|
280
|
+
* loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
|
|
281
|
+
* Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
|
|
282
|
+
*/
|
|
283
|
+
const isCheapAsyncContextRuntime = (rt = currentAsyncContextRuntime()) => {
|
|
284
|
+
if (rt.bun || rt.workers) return true;
|
|
285
|
+
if (!rt.nodeVersion) return false;
|
|
286
|
+
const flags = new Set([...rt.execArgv || [], ...(rt.nodeOptions || "").split(/\s+/).filter(Boolean)]);
|
|
287
|
+
if (flags.has("--no-async-context-frame") || flags.has("--no-experimental-async-context-frame")) return false;
|
|
288
|
+
if (Number.parseInt(rt.nodeVersion, 10) >= 24) return true;
|
|
289
|
+
return flags.has("--experimental-async-context-frame") || flags.has("--async-context-frame");
|
|
290
|
+
};
|
|
291
|
+
/**
|
|
292
|
+
* The process-wide `AsyncLocalStorage` the SQLite backends read (#1891), created on first use and published under
|
|
293
|
+
* `globalThis[SQL_TIMING_KEY]`; null when the runtime has none (then the report has no `sql*` fields). Only called
|
|
294
|
+
* when the slow-request log is on, so `slowLogMs: 0` never creates it.
|
|
295
|
+
*/
|
|
296
|
+
const getSqlTimingContext = () => {
|
|
297
|
+
const g = globalThis;
|
|
298
|
+
const existing = g[SQL_TIMING_KEY];
|
|
299
|
+
if (existing && typeof existing.run === "function") return existing;
|
|
300
|
+
try {
|
|
301
|
+
const getBuiltin = typeof process !== "undefined" ? process.getBuiltinModule : void 0;
|
|
302
|
+
const Als = globalThis.AsyncLocalStorage ?? (typeof getBuiltin === "function" ? getBuiltin("node:async_hooks")?.AsyncLocalStorage : void 0);
|
|
303
|
+
if (typeof Als !== "function") return null;
|
|
304
|
+
const ctx = new Als();
|
|
305
|
+
g[SQL_TIMING_KEY] = ctx;
|
|
306
|
+
return ctx;
|
|
307
|
+
} catch {
|
|
308
|
+
return null;
|
|
309
|
+
}
|
|
310
|
+
};
|
|
257
311
|
/**
|
|
258
312
|
* Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
|
|
259
313
|
* each named fragment counted once, bounded).
|
|
@@ -939,10 +993,11 @@ const parseEnvBoolean = (raw) => {
|
|
|
939
993
|
if (normalized === "1" || normalized === "true") return true;
|
|
940
994
|
if (normalized === "0" || normalized === "false") return false;
|
|
941
995
|
};
|
|
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 }) => {
|
|
996
|
+
const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, graphiql = parseEnvBoolean(process.env.GQL_GRAPHIQL ?? process.env.GRAPHQL_GRAPHIQL) ?? process.env.NODE_ENV !== "production", introspection = parseEnvBoolean(process.env.GQL_INTROSPECTION ?? process.env.GRAPHQL_INTROSPECTION) ?? process.env.NODE_ENV !== "production", showStack = process.env.NODE_ENV === "development" || process.env.NODE_ENV === "test", maxQueryDepth = MAX_QUERY_DEPTH, maxTotalSelections = parseEnvPositiveInt(process.env.GQL_MAX_TOTAL_SELECTIONS) ?? MAX_TOTAL_SELECTIONS, maxAliases = parseEnvPositiveInt(process.env.GQL_MAX_ALIASES) ?? MAX_ALIASES, slowLogMs = parseEnvPositiveInt(process.env.GQL_SLOW_LOG_MS) ?? DEFAULT_SLOW_LOG_MS, onSlowRequest = defaultSlowRequestHandler, stallLogMs = parseEnvPositiveInt(process.env.GQL_STALL_LOG_MS) ?? slowLogMs, onEventLoopStall = defaultStallHandler, sqlTiming: sqlTimingEnabled = parseEnvBoolean(process.env.GQL_SQL_TIMING) ?? isCheapAsyncContextRuntime() }) => {
|
|
943
997
|
const schema = buildSchema(schemaSource);
|
|
944
998
|
const rootValue = createResolvers(resolver);
|
|
945
999
|
const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
|
|
1000
|
+
const sqlTiming = slowLogMs > 0 && sqlTimingEnabled ? getSqlTimingContext() : null;
|
|
946
1001
|
const formatGraphQLError = (err) => {
|
|
947
1002
|
onError(err);
|
|
948
1003
|
const includeStack = showStack && process.env.NODE_ENV !== "production";
|
|
@@ -1040,47 +1095,48 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1040
1095
|
try {
|
|
1041
1096
|
shape = describeArgShape(args[0]);
|
|
1042
1097
|
} catch {}
|
|
1098
|
+
const sink = {
|
|
1099
|
+
sqlMs: 0,
|
|
1100
|
+
sqlQueries: 0
|
|
1101
|
+
};
|
|
1102
|
+
const call = () => fn.apply(rootValue, args);
|
|
1043
1103
|
const t = nowMs();
|
|
1044
|
-
let syncMs = 0;
|
|
1045
1104
|
let rows = 0;
|
|
1046
1105
|
try {
|
|
1047
|
-
|
|
1048
|
-
try {
|
|
1049
|
-
pending = fn.apply(rootValue, args);
|
|
1050
|
-
} finally {
|
|
1051
|
-
syncMs = nowMs() - t;
|
|
1052
|
-
}
|
|
1053
|
-
const out = await pending;
|
|
1106
|
+
const out = await (sqlTiming ? sqlTiming.run(sink, call) : call());
|
|
1054
1107
|
try {
|
|
1055
1108
|
rows = countRows(out);
|
|
1056
1109
|
} catch {}
|
|
1057
1110
|
return out;
|
|
1058
1111
|
} finally {
|
|
1059
1112
|
const ms = nowMs() - t;
|
|
1113
|
+
sink.closed = true;
|
|
1060
1114
|
const s = fieldStats.get(name) || {
|
|
1061
1115
|
count: 0,
|
|
1062
1116
|
wallSumMs: 0,
|
|
1063
1117
|
wallMaxMs: 0,
|
|
1064
|
-
|
|
1065
|
-
|
|
1118
|
+
sqlSumMs: 0,
|
|
1119
|
+
sqlMaxMs: 0,
|
|
1120
|
+
sqlQueries: 0,
|
|
1066
1121
|
rows: 0,
|
|
1067
1122
|
shapes: Object.create(null)
|
|
1068
1123
|
};
|
|
1069
1124
|
s.count += 1;
|
|
1070
1125
|
s.wallSumMs += ms;
|
|
1071
1126
|
if (ms > s.wallMaxMs) s.wallMaxMs = ms;
|
|
1072
|
-
s.
|
|
1073
|
-
if (
|
|
1127
|
+
s.sqlSumMs = s.sqlSumMs + sink.sqlMs;
|
|
1128
|
+
if (sink.sqlMs > s.sqlMaxMs) s.sqlMaxMs = sink.sqlMs;
|
|
1129
|
+
s.sqlQueries = s.sqlQueries + sink.sqlQueries;
|
|
1074
1130
|
s.rows += rows;
|
|
1075
1131
|
if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
|
|
1076
1132
|
const b = s.shapes[shape] || {
|
|
1077
1133
|
count: 0,
|
|
1078
1134
|
rows: 0,
|
|
1079
|
-
|
|
1135
|
+
sqlMs: 0
|
|
1080
1136
|
};
|
|
1081
1137
|
b.count += 1;
|
|
1082
1138
|
b.rows += rows;
|
|
1083
|
-
b.
|
|
1139
|
+
b.sqlMs = b.sqlMs + sink.sqlMs;
|
|
1084
1140
|
s.shapes[shape] = b;
|
|
1085
1141
|
fieldStats.set(name, s);
|
|
1086
1142
|
}
|
|
@@ -1113,20 +1169,35 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1113
1169
|
if (totalMs + queuedMs >= slowLogMs) try {
|
|
1114
1170
|
const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
|
|
1115
1171
|
const round = (n) => Math.round(n);
|
|
1116
|
-
const fields =
|
|
1172
|
+
const fields = Object.create(null);
|
|
1173
|
+
const reportSql = sqlTiming !== null && globalThis[SQL_TIMING_BACKEND_KEY] === true;
|
|
1174
|
+
let sqlMs = 0;
|
|
1175
|
+
let sqlQueries = 0;
|
|
1117
1176
|
for (const [name, s] of fieldStats) {
|
|
1118
1177
|
const shapes = Object.create(null);
|
|
1119
|
-
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = {
|
|
1178
|
+
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = reportSql ? {
|
|
1120
1179
|
count: b.count,
|
|
1121
1180
|
rows: b.rows,
|
|
1122
|
-
|
|
1181
|
+
sqlMs: round(b.sqlMs)
|
|
1182
|
+
} : {
|
|
1183
|
+
count: b.count,
|
|
1184
|
+
rows: b.rows
|
|
1123
1185
|
};
|
|
1124
|
-
|
|
1186
|
+
sqlMs += s.sqlSumMs;
|
|
1187
|
+
sqlQueries += s.sqlQueries;
|
|
1188
|
+
fields[name] = reportSql ? {
|
|
1189
|
+
count: s.count,
|
|
1190
|
+
wallSumMs: round(s.wallSumMs),
|
|
1191
|
+
wallMaxMs: round(s.wallMaxMs),
|
|
1192
|
+
sqlSumMs: round(s.sqlSumMs),
|
|
1193
|
+
sqlMaxMs: round(s.sqlMaxMs),
|
|
1194
|
+
sqlQueries: s.sqlQueries,
|
|
1195
|
+
rows: s.rows,
|
|
1196
|
+
shapes
|
|
1197
|
+
} : {
|
|
1125
1198
|
count: s.count,
|
|
1126
1199
|
wallSumMs: round(s.wallSumMs),
|
|
1127
1200
|
wallMaxMs: round(s.wallMaxMs),
|
|
1128
|
-
syncSumMs: round(s.syncSumMs),
|
|
1129
|
-
syncMaxMs: round(s.syncMaxMs),
|
|
1130
1201
|
rows: s.rows,
|
|
1131
1202
|
shapes
|
|
1132
1203
|
};
|
|
@@ -1146,6 +1217,10 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1146
1217
|
aliases,
|
|
1147
1218
|
numericAliases: aliasMap ? aliasMap.size : 0,
|
|
1148
1219
|
errors: result.errors ? result.errors.length : 0,
|
|
1220
|
+
...reportSql ? {
|
|
1221
|
+
sqlMs: round(sqlMs),
|
|
1222
|
+
sqlQueries
|
|
1223
|
+
} : {},
|
|
1149
1224
|
fields,
|
|
1150
1225
|
userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160)
|
|
1151
1226
|
});
|
|
@@ -1240,4 +1315,4 @@ const createFetchHandler = (options) => {
|
|
|
1240
1315
|
};
|
|
1241
1316
|
|
|
1242
1317
|
//#endregion
|
|
1243
|
-
export { createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
|
|
1318
|
+
export { SQL_TIMING_BACKEND_KEY, SQL_TIMING_KEY, createFetchHandler, createHttpHandler, createResolvers, formatContext, isCheapAsyncContextRuntime, normalizeNumericFieldAliases, wrapResolver };
|
package/esm/index.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, 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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, 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")
|
|
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,6 +263,54 @@ 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();
|
|
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
|
+
};
|
|
260
314
|
/**
|
|
261
315
|
* Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
|
|
262
316
|
* each named fragment counted once, bounded).
|
|
@@ -942,10 +996,11 @@ const parseEnvBoolean = (raw) => {
|
|
|
942
996
|
if (normalized === "1" || normalized === "true") return true;
|
|
943
997
|
if (normalized === "0" || normalized === "false") return false;
|
|
944
998
|
};
|
|
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 }) => {
|
|
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() }) => {
|
|
946
1000
|
const schema = (0, graphql.buildSchema)(_ocap_schema.default);
|
|
947
1001
|
const rootValue = createResolvers(resolver);
|
|
948
1002
|
const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
|
|
1003
|
+
const sqlTiming = slowLogMs > 0 && sqlTimingEnabled ? getSqlTimingContext() : null;
|
|
949
1004
|
const formatGraphQLError = (err) => {
|
|
950
1005
|
onError(err);
|
|
951
1006
|
const includeStack = showStack && process.env.NODE_ENV !== "production";
|
|
@@ -1043,47 +1098,48 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1043
1098
|
try {
|
|
1044
1099
|
shape = describeArgShape(args[0]);
|
|
1045
1100
|
} catch {}
|
|
1101
|
+
const sink = {
|
|
1102
|
+
sqlMs: 0,
|
|
1103
|
+
sqlQueries: 0
|
|
1104
|
+
};
|
|
1105
|
+
const call = () => fn.apply(rootValue, args);
|
|
1046
1106
|
const t = nowMs();
|
|
1047
|
-
let syncMs = 0;
|
|
1048
1107
|
let rows = 0;
|
|
1049
1108
|
try {
|
|
1050
|
-
|
|
1051
|
-
try {
|
|
1052
|
-
pending = fn.apply(rootValue, args);
|
|
1053
|
-
} finally {
|
|
1054
|
-
syncMs = nowMs() - t;
|
|
1055
|
-
}
|
|
1056
|
-
const out = await pending;
|
|
1109
|
+
const out = await (sqlTiming ? sqlTiming.run(sink, call) : call());
|
|
1057
1110
|
try {
|
|
1058
1111
|
rows = countRows(out);
|
|
1059
1112
|
} catch {}
|
|
1060
1113
|
return out;
|
|
1061
1114
|
} finally {
|
|
1062
1115
|
const ms = nowMs() - t;
|
|
1116
|
+
sink.closed = true;
|
|
1063
1117
|
const s = fieldStats.get(name) || {
|
|
1064
1118
|
count: 0,
|
|
1065
1119
|
wallSumMs: 0,
|
|
1066
1120
|
wallMaxMs: 0,
|
|
1067
|
-
|
|
1068
|
-
|
|
1121
|
+
sqlSumMs: 0,
|
|
1122
|
+
sqlMaxMs: 0,
|
|
1123
|
+
sqlQueries: 0,
|
|
1069
1124
|
rows: 0,
|
|
1070
1125
|
shapes: Object.create(null)
|
|
1071
1126
|
};
|
|
1072
1127
|
s.count += 1;
|
|
1073
1128
|
s.wallSumMs += ms;
|
|
1074
1129
|
if (ms > s.wallMaxMs) s.wallMaxMs = ms;
|
|
1075
|
-
s.
|
|
1076
|
-
if (
|
|
1130
|
+
s.sqlSumMs = s.sqlSumMs + sink.sqlMs;
|
|
1131
|
+
if (sink.sqlMs > s.sqlMaxMs) s.sqlMaxMs = sink.sqlMs;
|
|
1132
|
+
s.sqlQueries = s.sqlQueries + sink.sqlQueries;
|
|
1077
1133
|
s.rows += rows;
|
|
1078
1134
|
if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
|
|
1079
1135
|
const b = s.shapes[shape] || {
|
|
1080
1136
|
count: 0,
|
|
1081
1137
|
rows: 0,
|
|
1082
|
-
|
|
1138
|
+
sqlMs: 0
|
|
1083
1139
|
};
|
|
1084
1140
|
b.count += 1;
|
|
1085
1141
|
b.rows += rows;
|
|
1086
|
-
b.
|
|
1142
|
+
b.sqlMs = b.sqlMs + sink.sqlMs;
|
|
1087
1143
|
s.shapes[shape] = b;
|
|
1088
1144
|
fieldStats.set(name, s);
|
|
1089
1145
|
}
|
|
@@ -1116,20 +1172,35 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1116
1172
|
if (totalMs + queuedMs >= slowLogMs) try {
|
|
1117
1173
|
const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
|
|
1118
1174
|
const round = (n) => Math.round(n);
|
|
1119
|
-
const fields =
|
|
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;
|
|
1120
1179
|
for (const [name, s] of fieldStats) {
|
|
1121
1180
|
const shapes = Object.create(null);
|
|
1122
|
-
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = {
|
|
1181
|
+
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = reportSql ? {
|
|
1123
1182
|
count: b.count,
|
|
1124
1183
|
rows: b.rows,
|
|
1125
|
-
|
|
1184
|
+
sqlMs: round(b.sqlMs)
|
|
1185
|
+
} : {
|
|
1186
|
+
count: b.count,
|
|
1187
|
+
rows: b.rows
|
|
1126
1188
|
};
|
|
1127
|
-
|
|
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
|
+
} : {
|
|
1128
1201
|
count: s.count,
|
|
1129
1202
|
wallSumMs: round(s.wallSumMs),
|
|
1130
1203
|
wallMaxMs: round(s.wallMaxMs),
|
|
1131
|
-
syncSumMs: round(s.syncSumMs),
|
|
1132
|
-
syncMaxMs: round(s.syncMaxMs),
|
|
1133
1204
|
rows: s.rows,
|
|
1134
1205
|
shapes
|
|
1135
1206
|
};
|
|
@@ -1149,6 +1220,10 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1149
1220
|
aliases,
|
|
1150
1221
|
numericAliases: aliasMap ? aliasMap.size : 0,
|
|
1151
1222
|
errors: result.errors ? result.errors.length : 0,
|
|
1223
|
+
...reportSql ? {
|
|
1224
|
+
sqlMs: round(sqlMs),
|
|
1225
|
+
sqlQueries
|
|
1226
|
+
} : {},
|
|
1152
1227
|
fields,
|
|
1153
1228
|
userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160)
|
|
1154
1229
|
});
|
|
@@ -1243,9 +1318,12 @@ const createFetchHandler = (options) => {
|
|
|
1243
1318
|
};
|
|
1244
1319
|
|
|
1245
1320
|
//#endregion
|
|
1321
|
+
exports.SQL_TIMING_BACKEND_KEY = SQL_TIMING_BACKEND_KEY;
|
|
1322
|
+
exports.SQL_TIMING_KEY = SQL_TIMING_KEY;
|
|
1246
1323
|
exports.createFetchHandler = createFetchHandler;
|
|
1247
1324
|
exports.createHttpHandler = createHttpHandler;
|
|
1248
1325
|
exports.createResolvers = createResolvers;
|
|
1249
1326
|
exports.formatContext = formatContext;
|
|
1327
|
+
exports.isCheapAsyncContextRuntime = isCheapAsyncContextRuntime;
|
|
1250
1328
|
exports.normalizeNumericFieldAliases = normalizeNumericFieldAliases;
|
|
1251
1329
|
exports.wrapResolver = wrapResolver;
|
package/lib/http.d.cts
CHANGED
|
@@ -49,6 +49,14 @@ interface HttpHandlerOptions {
|
|
|
49
49
|
stallLogMs?: number;
|
|
50
50
|
/** Receives stall reports. Defaults to one `console.warn('[gql] event loop stall', json)` line. */
|
|
51
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;
|
|
52
60
|
}
|
|
53
61
|
/**
|
|
54
62
|
* Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
|
|
@@ -60,22 +68,32 @@ interface SlowRequestShapeStat {
|
|
|
60
68
|
count: number;
|
|
61
69
|
/** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
|
|
62
70
|
rows: number;
|
|
63
|
-
/**
|
|
64
|
-
|
|
71
|
+
/** SQLite execution time of the statements the aliases of this bucket ran (see `SlowRequestFieldStat.sqlSumMs`). */
|
|
72
|
+
sqlMs?: number;
|
|
65
73
|
}
|
|
66
74
|
/**
|
|
67
75
|
* Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
|
|
68
76
|
* awaits interleave, so a field's wall time also covers the other fields running alongside it: `wallMaxMs` is at
|
|
69
|
-
* most `executeMs`, and `wallSumMs` can exceed it.
|
|
70
|
-
*
|
|
71
|
-
*
|
|
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.
|
|
72
86
|
*/
|
|
73
87
|
interface SlowRequestFieldStat {
|
|
74
88
|
count: number;
|
|
75
89
|
wallSumMs: number;
|
|
76
90
|
wallMaxMs: number;
|
|
77
|
-
|
|
78
|
-
|
|
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;
|
|
79
97
|
/** Rows returned over all aliases (sum of list payload lengths). */
|
|
80
98
|
rows: number;
|
|
81
99
|
/** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
|
|
@@ -131,9 +149,36 @@ interface SlowRequestReport {
|
|
|
131
149
|
aliases: number;
|
|
132
150
|
numericAliases: number;
|
|
133
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;
|
|
134
159
|
fields: Record<string, SlowRequestFieldStat>;
|
|
135
160
|
userAgent?: string;
|
|
136
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;
|
|
137
182
|
/**
|
|
138
183
|
* Transport-agnostic view of an incoming GraphQL request, so the same engine serves express (`createHttpHandler`)
|
|
139
184
|
* and fetch-native runtimes such as Cloudflare Workers (`createFetchHandler`).
|
|
@@ -177,4 +222,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
|
|
|
177
222
|
*/
|
|
178
223
|
declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
|
|
179
224
|
//#endregion
|
|
180
|
-
export { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, 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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, 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 { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, 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/package.json
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
"publishConfig": {
|
|
4
4
|
"access": "public"
|
|
5
5
|
},
|
|
6
|
-
"version": "1.31.
|
|
6
|
+
"version": "1.31.9",
|
|
7
7
|
"description": "Resolver middleware for ocap adapters",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"main": "./lib/index.cjs",
|
|
@@ -51,12 +51,13 @@
|
|
|
51
51
|
],
|
|
52
52
|
"license": "MIT",
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@arcblock/ws": "1.31.
|
|
55
|
-
"@ocap/schema": "1.31.
|
|
54
|
+
"@arcblock/ws": "1.31.9",
|
|
55
|
+
"@ocap/schema": "1.31.9",
|
|
56
56
|
"graphql": "^16.13.2",
|
|
57
57
|
"lodash": "^4.17.23"
|
|
58
58
|
},
|
|
59
59
|
"devDependencies": {
|
|
60
|
+
"@ocap/util": "1.31.9",
|
|
60
61
|
"@types/express": "^4.17.23",
|
|
61
62
|
"@types/lodash": "^4.17.13",
|
|
62
63
|
"express": "^4.22.1"
|