@ocap/gql 1.31.8 → 1.32.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +34 -5
- package/esm/http.d.mts +67 -9
- package/esm/http.mjs +169 -43
- package/esm/index.d.mts +2 -2
- package/esm/index.mjs +2 -2
- package/lib/http.cjs +171 -42
- package/lib/http.d.cts +67 -9
- 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,45 @@ 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
|
+
- `clientIp` / `host` / `cfRay` / `userAgent` (#1922): where the request came from, so a slow line can be matched
|
|
58
|
+
with the access log. `clientIp` follows `@ocap/util/lib/client-ip`: the headers in `CHAIN_CLIENT_IP_HEADERS`
|
|
59
|
+
(default `x-real-ip`; `cf-connecting-ip` for a Cloudflare Tunnel node), read only when the TCP peer is a loopback
|
|
60
|
+
address, else the socket address. `createFetchHandler` (Workers) always uses `cf-connecting-ip`, then `x-real-ip`. `host` is
|
|
61
|
+
capped at 160 chars, `cfRay` at 64; absent headers are omitted. Stall entries carry `clientIp` and `userAgent`.
|
|
62
|
+
- SQL time is measured where the statements run (#1891): `@ocap/indexdb-sqlite` and `@ocap/statedb-sqlite` time the
|
|
63
|
+
synchronous part of every Kysely `executeQuery` (better-sqlite3 / bun:sqlite run the whole statement there) and add
|
|
64
|
+
it to the alias that issued it, found through an `AsyncLocalStorage` the handler runs each root field call in
|
|
65
|
+
(`@ocap/util/lib/sql-timing`). It counts statements after any number of `await`s, and never counts one statement
|
|
66
|
+
twice; a statement whose result several aliases share (a cache) counts for the alias that started it, and work that
|
|
67
|
+
outlives its field is not counted. The `sql*` fields are left out when SQL timing is off (below), when the runtime
|
|
68
|
+
has no `AsyncLocalStorage`, or when no SQLite backend in the process is timed: the Durable Object backend is not
|
|
69
|
+
(Workers freeze clocks during synchronous work).
|
|
70
|
+
- SQL timing on or off: `GQL_SQL_TIMING` (option `sqlTiming`) `1`/`true` forces it on, `0`/`false` off. Unset, it is
|
|
71
|
+
on where `AsyncLocalStorage` is cheap: Bun, Workers, Node >= 24 (AsyncContextFrame; off again with
|
|
72
|
+
`--no-async-context-frame`) and Node 22/23 started with `--experimental-async-context-frame`; it is **off on Node 22
|
|
73
|
+
by default**. There `AsyncLocalStorage` uses async_hooks: after the first request every promise in the process pays
|
|
74
|
+
for a hook, inside requests and outside them (the tx pipeline too). Measured on Node 22.23 + better-sqlite3 with the
|
|
75
|
+
production assembly, one process per setting (medians of 30): a 30-alias `listTransactions` batch 76.6 / 77.4 ms
|
|
76
|
+
with `GQL_SQL_TIMING=0` / `1` (SQL-bound, no visible change), but 3e5 bare `await`s outside any request 13.3 ms →
|
|
77
|
+
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
|
|
78
|
+
is a trade: accurate per-field SQL time for slower promise-heavy code everywhere in the process.
|
|
79
|
+
- Removed in this version: `syncSumMs`/`syncMaxMs` and the shapes' `syncMs` (1.31.8). They timed only the resolver
|
|
80
|
+
call up to its first `await`, but Kysely awaits its connection before every statement, so they never included the
|
|
81
|
+
SQL (an 11 s `listTransactions` on beta reported `syncSumMs: 2`). Use `sqlSumMs`/`sqlMaxMs`/`sqlMs` instead.
|
|
53
82
|
- A shape key lists the argument names present, then `size=<paging.size>` when `paging` is given and
|
|
54
83
|
`start=`/`end=` when `timeFilter` is given, each one of `absent`, `empty` (`""`), `null-string` (`"null"`), `null`,
|
|
55
84
|
`date` or `invalid`.
|
|
56
85
|
|
|
57
86
|
```
|
|
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,"
|
|
87
|
+
[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
88
|
```
|
|
60
89
|
|
|
61
90
|
`[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
|
@@ -14,12 +14,15 @@ interface WrapResolverResult {
|
|
|
14
14
|
}
|
|
15
15
|
declare const wrapResolver: (_name: string, keys: string | string[], callback: () => Promise<ResolverResult | null> | ResolverResult | null | string) => Promise<WrapResolverResult>;
|
|
16
16
|
interface RequestContext {
|
|
17
|
-
headers?: Record<string, string>;
|
|
17
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
18
18
|
ip?: string;
|
|
19
19
|
_remoteAddress?: string;
|
|
20
20
|
connection?: {
|
|
21
21
|
remoteAddress?: string;
|
|
22
22
|
};
|
|
23
|
+
socket?: {
|
|
24
|
+
remoteAddress?: string;
|
|
25
|
+
};
|
|
23
26
|
}
|
|
24
27
|
declare const formatContext: (ctx?: RequestContext) => IResolverContext;
|
|
25
28
|
type Resolver = IResolver;
|
|
@@ -49,6 +52,14 @@ interface HttpHandlerOptions {
|
|
|
49
52
|
stallLogMs?: number;
|
|
50
53
|
/** Receives stall reports. Defaults to one `console.warn('[gql] event loop stall', json)` line. */
|
|
51
54
|
onEventLoopStall?: (report: EventLoopStallReport) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Per root field SQLite time in the slow-request log (#1891; needs `AsyncLocalStorage`). Falls back to
|
|
57
|
+
* `GQL_SQL_TIMING` (`1`/`true` on, `0`/`false` off), then to `isCheapAsyncContextRuntime()`: on for Bun, Workers,
|
|
58
|
+
* Node >= 24 and Node started with `--experimental-async-context-frame`; off on older Node, where the first
|
|
59
|
+
* `AsyncLocalStorage#run` turns on async_hooks promise hooks for the whole process and slows every `await`.
|
|
60
|
+
* Ignored when `slowLogMs` is 0.
|
|
61
|
+
*/
|
|
62
|
+
sqlTiming?: boolean;
|
|
52
63
|
}
|
|
53
64
|
/**
|
|
54
65
|
* Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
|
|
@@ -60,22 +71,32 @@ interface SlowRequestShapeStat {
|
|
|
60
71
|
count: number;
|
|
61
72
|
/** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
|
|
62
73
|
rows: number;
|
|
63
|
-
/**
|
|
64
|
-
|
|
74
|
+
/** SQLite execution time of the statements the aliases of this bucket ran (see `SlowRequestFieldStat.sqlSumMs`). */
|
|
75
|
+
sqlMs?: number;
|
|
65
76
|
}
|
|
66
77
|
/**
|
|
67
78
|
* Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
|
|
68
79
|
* 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
|
-
*
|
|
80
|
+
* most `executeMs`, and `wallSumMs` can exceed it.
|
|
81
|
+
*
|
|
82
|
+
* `sqlSumMs` / `sqlMaxMs` / `sqlQueries` (#1891) are measured at the SQLite execution layer: every statement the
|
|
83
|
+
* indexdb / statedb SQLite backends execute on behalf of an alias, however many awaits before it, adds its
|
|
84
|
+
* synchronous execution time to that alias (attribution via `AsyncLocalStorage`). SQLite runs on the main thread
|
|
85
|
+
* and statements never overlap, so these do not double count: their sum over all fields (the report's `sqlMs`) stays
|
|
86
|
+
* within `executeMs`. A statement whose promise is shared by several aliases (a cache) counts once, for the alias
|
|
87
|
+
* that started it. Absent when SQL timing is off (`sqlTiming` / `GQL_SQL_TIMING`, default off on Node < 24), the runtime
|
|
88
|
+
* has no `AsyncLocalStorage`, or no SQLite backend in the process is timed.
|
|
72
89
|
*/
|
|
73
90
|
interface SlowRequestFieldStat {
|
|
74
91
|
count: number;
|
|
75
92
|
wallSumMs: number;
|
|
76
93
|
wallMaxMs: number;
|
|
77
|
-
|
|
78
|
-
|
|
94
|
+
/** SQLite execution time of all aliases of this field. */
|
|
95
|
+
sqlSumMs?: number;
|
|
96
|
+
/** Largest SQLite execution time of a single alias. */
|
|
97
|
+
sqlMaxMs?: number;
|
|
98
|
+
/** Statements executed by all aliases of this field. */
|
|
99
|
+
sqlQueries?: number;
|
|
79
100
|
/** Rows returned over all aliases (sum of list payload lengths). */
|
|
80
101
|
rows: number;
|
|
81
102
|
/** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
|
|
@@ -96,6 +117,8 @@ interface StallInFlightEntry {
|
|
|
96
117
|
/** Root field name -> number of aliases selecting it; names the schema does not resolve are summed as `unknown`. */
|
|
97
118
|
fields?: Record<string, number>;
|
|
98
119
|
userAgent?: string;
|
|
120
|
+
/** Client address as resolved by `@ocap/util/lib/client-ip` (#1922). */
|
|
121
|
+
clientIp?: string;
|
|
99
122
|
}
|
|
100
123
|
/** `[gql] event loop stall` report: the probe timer fired `maxMs` late in the window starting at `windowStart`. */
|
|
101
124
|
interface EventLoopStallReport {
|
|
@@ -131,9 +154,42 @@ interface SlowRequestReport {
|
|
|
131
154
|
aliases: number;
|
|
132
155
|
numericAliases: number;
|
|
133
156
|
errors: number;
|
|
157
|
+
/**
|
|
158
|
+
* SQLite execution time of all root fields (sum of `fields.*.sqlSumMs`), within `executeMs`; the rest of
|
|
159
|
+
* `executeMs` is JavaScript (graphql-js, resolver formatting) and waiting. Absent like the fields' `sql*`.
|
|
160
|
+
*/
|
|
161
|
+
sqlMs?: number;
|
|
162
|
+
/** Statements executed by all root fields. */
|
|
163
|
+
sqlQueries?: number;
|
|
134
164
|
fields: Record<string, SlowRequestFieldStat>;
|
|
135
165
|
userAgent?: string;
|
|
166
|
+
/** Client address as resolved by `@ocap/util/lib/client-ip` (#1922); joins the line with the access log. */
|
|
167
|
+
clientIp?: string;
|
|
168
|
+
/** `Host` header, at most 160 chars. */
|
|
169
|
+
host?: string;
|
|
170
|
+
/** Cloudflare `cf-ray` request id, at most 64 chars; absent when the request did not pass Cloudflare. */
|
|
171
|
+
cfRay?: string;
|
|
172
|
+
}
|
|
173
|
+
/** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
|
|
174
|
+
declare const SQL_TIMING_KEY: unique symbol;
|
|
175
|
+
/** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
|
|
176
|
+
declare const SQL_TIMING_BACKEND_KEY: unique symbol;
|
|
177
|
+
interface AsyncContextRuntime {
|
|
178
|
+
bun?: boolean;
|
|
179
|
+
workers?: boolean;
|
|
180
|
+
/** `process.versions.node` */
|
|
181
|
+
nodeVersion?: string;
|
|
182
|
+
execArgv?: readonly string[];
|
|
183
|
+
/** `NODE_OPTIONS` */
|
|
184
|
+
nodeOptions?: string;
|
|
136
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
|
|
188
|
+
* after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
|
|
189
|
+
* loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
|
|
190
|
+
* Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
|
|
191
|
+
*/
|
|
192
|
+
declare const isCheapAsyncContextRuntime: (rt?: AsyncContextRuntime) => boolean;
|
|
137
193
|
/**
|
|
138
194
|
* Transport-agnostic view of an incoming GraphQL request, so the same engine serves express (`createHttpHandler`)
|
|
139
195
|
* and fetch-native runtimes such as Cloudflare Workers (`createFetchHandler`).
|
|
@@ -150,6 +206,8 @@ interface GqlRequestLike {
|
|
|
150
206
|
readBody: (limit: number) => Promise<string>;
|
|
151
207
|
/** `performance.now()` when the adapter received the request; defaults to the engine's own start. */
|
|
152
208
|
receivedAt?: number;
|
|
209
|
+
/** Client address resolved by the adapter (`@ocap/util/lib/client-ip`), reported in the slow / stall lines. */
|
|
210
|
+
clientIp?: string;
|
|
153
211
|
}
|
|
154
212
|
/** Transport-agnostic response produced by the engine. */
|
|
155
213
|
interface GqlResponseLike {
|
|
@@ -177,4 +235,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
|
|
|
177
235
|
*/
|
|
178
236
|
declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
|
|
179
237
|
//#endregion
|
|
180
|
-
export { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
|
|
238
|
+
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
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import schemaSource from "@ocap/schema";
|
|
2
|
+
import { resolveClientIp } from "@ocap/util/lib/client-ip";
|
|
2
3
|
import { GraphQLError, NoSchemaIntrospectionCustomRule, buildSchema, execute, getOperationAST, parse, validate } from "graphql";
|
|
3
4
|
import get from "lodash/get.js";
|
|
4
5
|
|
|
@@ -7,7 +8,7 @@ const wrapResolver = async (_name, keys, callback) => {
|
|
|
7
8
|
const result = await callback();
|
|
8
9
|
const resultsMap = {};
|
|
9
10
|
if (Array.isArray(keys)) keys.forEach((key) => {
|
|
10
|
-
resultsMap[key] = result[key];
|
|
11
|
+
resultsMap[key] = result ? result[key] : null;
|
|
11
12
|
});
|
|
12
13
|
else resultsMap[keys] = result;
|
|
13
14
|
return {
|
|
@@ -16,18 +17,28 @@ const wrapResolver = async (_name, keys, callback) => {
|
|
|
16
17
|
...resultsMap
|
|
17
18
|
};
|
|
18
19
|
};
|
|
20
|
+
function readHeaderCaseInsensitive(headers, targetLower) {
|
|
21
|
+
if (!headers) return void 0;
|
|
22
|
+
if (Object.prototype.hasOwnProperty.call(headers, targetLower)) return headers[targetLower];
|
|
23
|
+
for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === targetLower) return v;
|
|
24
|
+
}
|
|
19
25
|
const formatContext = (ctx = {}) => {
|
|
26
|
+
const featureSwitch = {};
|
|
27
|
+
const gasStakeHeaders = {
|
|
28
|
+
token: get(ctx, "headers[x-gas-payer-sig]", ""),
|
|
29
|
+
pk: get(ctx, "headers[x-gas-payer-pk]", "")
|
|
30
|
+
};
|
|
31
|
+
const request = {
|
|
32
|
+
userAgent: get(ctx, "headers.user-agent"),
|
|
33
|
+
ip: resolveClientIp(ctx) || "-",
|
|
34
|
+
id: get(ctx, "headers[x-request-id]") || get(ctx, "headers[X-Request-ID]") || "-"
|
|
35
|
+
};
|
|
36
|
+
const forwardedHop = readHeaderCaseInsensitive(ctx.headers, "x-ocap-forwarded-hop");
|
|
20
37
|
return {
|
|
21
|
-
featureSwitch
|
|
22
|
-
gasStakeHeaders
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
},
|
|
26
|
-
request: {
|
|
27
|
-
userAgent: get(ctx, "headers.user-agent"),
|
|
28
|
-
ip: get(ctx, "headers.x-real-ip") || ctx.ip || ctx._remoteAddress || ctx.connection?.remoteAddress || "-",
|
|
29
|
-
id: get(ctx, "headers[x-request-id]") || get(ctx, "headers[X-Request-ID]") || "-"
|
|
30
|
-
}
|
|
38
|
+
featureSwitch,
|
|
39
|
+
gasStakeHeaders,
|
|
40
|
+
request,
|
|
41
|
+
...forwardedHop !== void 0 ? { forwardedHop } : {}
|
|
31
42
|
};
|
|
32
43
|
};
|
|
33
44
|
const resolvers = [
|
|
@@ -139,9 +150,17 @@ const resolvers = [
|
|
|
139
150
|
fn: "getLedgerEntry",
|
|
140
151
|
dataKey: "entry"
|
|
141
152
|
},
|
|
153
|
+
{
|
|
154
|
+
fn: "getLedgerInfo",
|
|
155
|
+
dataKey: "info"
|
|
156
|
+
},
|
|
142
157
|
{
|
|
143
158
|
fn: "getMerkleProof",
|
|
144
|
-
dataKey: [
|
|
159
|
+
dataKey: [
|
|
160
|
+
"proof",
|
|
161
|
+
"checkpoint",
|
|
162
|
+
"entryHashV2From"
|
|
163
|
+
]
|
|
145
164
|
},
|
|
146
165
|
{
|
|
147
166
|
fn: "getTokenDistribution",
|
|
@@ -216,11 +235,17 @@ const resolvers = [
|
|
|
216
235
|
dataKey: ["estimate"]
|
|
217
236
|
}
|
|
218
237
|
];
|
|
238
|
+
/** resolver fns whose rows reach the client only through the GraphQL `IndexedTransaction` type */
|
|
239
|
+
const TX_PROJECTION_FNS = new Set(["listTransactions", "listAssetTransactions"]);
|
|
219
240
|
const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
|
|
220
241
|
acc[fn] = async (args, ctx) => {
|
|
221
242
|
const res = await wrapResolver(fn, dataKey, () => {
|
|
222
243
|
const method = resolver[fn];
|
|
223
|
-
if (typeof method === "function")
|
|
244
|
+
if (typeof method === "function") {
|
|
245
|
+
const resolverCtx = formatContext(ctx);
|
|
246
|
+
if (TX_PROJECTION_FNS.has(fn)) resolverCtx.graphqlTxProjection = true;
|
|
247
|
+
return method.call(resolver, args, resolverCtx);
|
|
248
|
+
}
|
|
224
249
|
return null;
|
|
225
250
|
});
|
|
226
251
|
if (fn === "sendTx") {
|
|
@@ -254,6 +279,54 @@ const defaultSlowRequestHandler = (report) => {
|
|
|
254
279
|
console.warn("[gql] slow request", JSON.stringify(report));
|
|
255
280
|
};
|
|
256
281
|
const nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
282
|
+
/** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
|
|
283
|
+
const SQL_TIMING_KEY = Symbol.for("@ocap/sql-timing");
|
|
284
|
+
/** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
|
|
285
|
+
const SQL_TIMING_BACKEND_KEY = Symbol.for("@ocap/sql-timing/backend");
|
|
286
|
+
const currentAsyncContextRuntime = () => {
|
|
287
|
+
const proc = typeof process !== "undefined" ? process : void 0;
|
|
288
|
+
return {
|
|
289
|
+
bun: typeof proc?.versions?.bun === "string",
|
|
290
|
+
workers: typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers",
|
|
291
|
+
nodeVersion: proc?.versions?.node,
|
|
292
|
+
execArgv: Array.isArray(proc?.execArgv) ? proc.execArgv : [],
|
|
293
|
+
nodeOptions: typeof process !== "undefined" ? process.env?.NODE_OPTIONS : void 0
|
|
294
|
+
};
|
|
295
|
+
};
|
|
296
|
+
/**
|
|
297
|
+
* Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
|
|
298
|
+
* after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
|
|
299
|
+
* loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
|
|
300
|
+
* Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
|
|
301
|
+
*/
|
|
302
|
+
const isCheapAsyncContextRuntime = (rt = currentAsyncContextRuntime()) => {
|
|
303
|
+
if (rt.bun || rt.workers) return true;
|
|
304
|
+
if (!rt.nodeVersion) return false;
|
|
305
|
+
const flags = new Set([...rt.execArgv || [], ...(rt.nodeOptions || "").split(/\s+/).filter(Boolean)]);
|
|
306
|
+
if (flags.has("--no-async-context-frame") || flags.has("--no-experimental-async-context-frame")) return false;
|
|
307
|
+
if (Number.parseInt(rt.nodeVersion, 10) >= 24) return true;
|
|
308
|
+
return flags.has("--experimental-async-context-frame") || flags.has("--async-context-frame");
|
|
309
|
+
};
|
|
310
|
+
/**
|
|
311
|
+
* The process-wide `AsyncLocalStorage` the SQLite backends read (#1891), created on first use and published under
|
|
312
|
+
* `globalThis[SQL_TIMING_KEY]`; null when the runtime has none (then the report has no `sql*` fields). Only called
|
|
313
|
+
* when the slow-request log is on, so `slowLogMs: 0` never creates it.
|
|
314
|
+
*/
|
|
315
|
+
const getSqlTimingContext = () => {
|
|
316
|
+
const g = globalThis;
|
|
317
|
+
const existing = g[SQL_TIMING_KEY];
|
|
318
|
+
if (existing && typeof existing.run === "function") return existing;
|
|
319
|
+
try {
|
|
320
|
+
const getBuiltin = typeof process !== "undefined" ? process.getBuiltinModule : void 0;
|
|
321
|
+
const Als = globalThis.AsyncLocalStorage ?? (typeof getBuiltin === "function" ? getBuiltin("node:async_hooks")?.AsyncLocalStorage : void 0);
|
|
322
|
+
if (typeof Als !== "function") return null;
|
|
323
|
+
const ctx = new Als();
|
|
324
|
+
g[SQL_TIMING_KEY] = ctx;
|
|
325
|
+
return ctx;
|
|
326
|
+
} catch {
|
|
327
|
+
return null;
|
|
328
|
+
}
|
|
329
|
+
};
|
|
257
330
|
/**
|
|
258
331
|
* Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
|
|
259
332
|
* each named fragment counted once, bounded).
|
|
@@ -277,6 +350,15 @@ const collectRootFieldCounts = (documentAST, operationName, maxFragmentDepth = M
|
|
|
277
350
|
return names;
|
|
278
351
|
};
|
|
279
352
|
const headerValue = (v) => Array.isArray(v) ? v[0] : v;
|
|
353
|
+
/** `host` / `cfRay` of the slow-request line; header values are client-controlled, so they are length-capped. */
|
|
354
|
+
const sourceHeaders = (headers) => {
|
|
355
|
+
const host = headerValue(headers.host);
|
|
356
|
+
const cfRay = headerValue(headers["cf-ray"]);
|
|
357
|
+
return {
|
|
358
|
+
...host ? { host: host.slice(0, 160) } : {},
|
|
359
|
+
...cfRay ? { cfRay: cfRay.slice(0, 64) } : {}
|
|
360
|
+
};
|
|
361
|
+
};
|
|
280
362
|
const MAX_SHAPES_PER_FIELD = 8;
|
|
281
363
|
const MAX_STALL_ENTRIES = 20;
|
|
282
364
|
const MAX_RECENT_DONE = 64;
|
|
@@ -360,6 +442,7 @@ const createStallMonitor = (requestedMs, report, rootValue) => {
|
|
|
360
442
|
}
|
|
361
443
|
const ua = headerValue(rec.headers["user-agent"]);
|
|
362
444
|
if (ua) entry.userAgent = ua.slice(0, 160);
|
|
445
|
+
if (rec.clientIp) entry.clientIp = rec.clientIp;
|
|
363
446
|
return entry;
|
|
364
447
|
};
|
|
365
448
|
const tick = () => {
|
|
@@ -939,10 +1022,11 @@ const parseEnvBoolean = (raw) => {
|
|
|
939
1022
|
if (normalized === "1" || normalized === "true") return true;
|
|
940
1023
|
if (normalized === "0" || normalized === "false") return false;
|
|
941
1024
|
};
|
|
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 }) => {
|
|
1025
|
+
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
1026
|
const schema = buildSchema(schemaSource);
|
|
944
1027
|
const rootValue = createResolvers(resolver);
|
|
945
1028
|
const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
|
|
1029
|
+
const sqlTiming = slowLogMs > 0 && sqlTimingEnabled ? getSqlTimingContext() : null;
|
|
946
1030
|
const formatGraphQLError = (err) => {
|
|
947
1031
|
onError(err);
|
|
948
1032
|
const includeStack = showStack && process.env.NODE_ENV !== "production";
|
|
@@ -1040,47 +1124,48 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1040
1124
|
try {
|
|
1041
1125
|
shape = describeArgShape(args[0]);
|
|
1042
1126
|
} catch {}
|
|
1127
|
+
const sink = {
|
|
1128
|
+
sqlMs: 0,
|
|
1129
|
+
sqlQueries: 0
|
|
1130
|
+
};
|
|
1131
|
+
const call = () => fn.apply(rootValue, args);
|
|
1043
1132
|
const t = nowMs();
|
|
1044
|
-
let syncMs = 0;
|
|
1045
1133
|
let rows = 0;
|
|
1046
1134
|
try {
|
|
1047
|
-
|
|
1048
|
-
try {
|
|
1049
|
-
pending = fn.apply(rootValue, args);
|
|
1050
|
-
} finally {
|
|
1051
|
-
syncMs = nowMs() - t;
|
|
1052
|
-
}
|
|
1053
|
-
const out = await pending;
|
|
1135
|
+
const out = await (sqlTiming ? sqlTiming.run(sink, call) : call());
|
|
1054
1136
|
try {
|
|
1055
1137
|
rows = countRows(out);
|
|
1056
1138
|
} catch {}
|
|
1057
1139
|
return out;
|
|
1058
1140
|
} finally {
|
|
1059
1141
|
const ms = nowMs() - t;
|
|
1142
|
+
sink.closed = true;
|
|
1060
1143
|
const s = fieldStats.get(name) || {
|
|
1061
1144
|
count: 0,
|
|
1062
1145
|
wallSumMs: 0,
|
|
1063
1146
|
wallMaxMs: 0,
|
|
1064
|
-
|
|
1065
|
-
|
|
1147
|
+
sqlSumMs: 0,
|
|
1148
|
+
sqlMaxMs: 0,
|
|
1149
|
+
sqlQueries: 0,
|
|
1066
1150
|
rows: 0,
|
|
1067
1151
|
shapes: Object.create(null)
|
|
1068
1152
|
};
|
|
1069
1153
|
s.count += 1;
|
|
1070
1154
|
s.wallSumMs += ms;
|
|
1071
1155
|
if (ms > s.wallMaxMs) s.wallMaxMs = ms;
|
|
1072
|
-
s.
|
|
1073
|
-
if (
|
|
1156
|
+
s.sqlSumMs = s.sqlSumMs + sink.sqlMs;
|
|
1157
|
+
if (sink.sqlMs > s.sqlMaxMs) s.sqlMaxMs = sink.sqlMs;
|
|
1158
|
+
s.sqlQueries = s.sqlQueries + sink.sqlQueries;
|
|
1074
1159
|
s.rows += rows;
|
|
1075
1160
|
if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
|
|
1076
1161
|
const b = s.shapes[shape] || {
|
|
1077
1162
|
count: 0,
|
|
1078
1163
|
rows: 0,
|
|
1079
|
-
|
|
1164
|
+
sqlMs: 0
|
|
1080
1165
|
};
|
|
1081
1166
|
b.count += 1;
|
|
1082
1167
|
b.rows += rows;
|
|
1083
|
-
b.
|
|
1168
|
+
b.sqlMs = b.sqlMs + sink.sqlMs;
|
|
1084
1169
|
s.shapes[shape] = b;
|
|
1085
1170
|
fieldStats.set(name, s);
|
|
1086
1171
|
}
|
|
@@ -1101,32 +1186,62 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1101
1186
|
} catch (contextError) {
|
|
1102
1187
|
return sendJSON(400, { errors: [formatAnyError(contextError)] });
|
|
1103
1188
|
}
|
|
1104
|
-
const
|
|
1189
|
+
const responseData = aliasMap && result.data != null ? restoreNumericAliasesInData(result.data, aliasMap) : result.data;
|
|
1190
|
+
const formattedResult = { data: responseData };
|
|
1105
1191
|
if (result.errors && result.errors.length > 0) formattedResult.errors = result.errors.map(formatError);
|
|
1106
1192
|
const status = result.data == null ? 500 : 200;
|
|
1107
|
-
|
|
1193
|
+
const extraHeaders = {};
|
|
1194
|
+
const forwardedHop = readHeaderCaseInsensitive(req.headers, "x-ocap-forwarded-hop");
|
|
1195
|
+
const sentTxHash = responseData?.sendTx?.hash;
|
|
1196
|
+
if (forwardedHop !== void 0 && typeof sentTxHash === "string" && sentTxHash && (!result.errors || result.errors.length === 0)) {
|
|
1197
|
+
const signFn = resolver.signForwardedSendTxReceipt;
|
|
1198
|
+
if (typeof signFn === "function") {
|
|
1199
|
+
const signedReceipt = await signFn.call(resolver, sentTxHash);
|
|
1200
|
+
if (signedReceipt?.signature && signedReceipt?.proposer) {
|
|
1201
|
+
extraHeaders["X-Ocap-Forward-Receipt-Sig"] = signedReceipt.signature;
|
|
1202
|
+
extraHeaders["X-Ocap-Forward-Proposer"] = signedReceipt.proposer;
|
|
1203
|
+
}
|
|
1204
|
+
if (signedReceipt?.commitProof) extraHeaders["X-Ocap-Forward-Commit-Proof"] = signedReceipt.commitProof;
|
|
1205
|
+
}
|
|
1206
|
+
}
|
|
1207
|
+
if (slowLogMs <= 0) return sendJSON(status, formattedResult, extraHeaders);
|
|
1108
1208
|
const executedAt = nowMs();
|
|
1109
|
-
const response = sendJSON(status, formattedResult);
|
|
1209
|
+
const response = sendJSON(status, formattedResult, extraHeaders);
|
|
1110
1210
|
const finishedAt = nowMs();
|
|
1111
1211
|
const totalMs = finishedAt - startedAt;
|
|
1112
1212
|
const queuedMs = rec ? Math.max(0, startedAt - rec.receivedAt) : 0;
|
|
1113
1213
|
if (totalMs + queuedMs >= slowLogMs) try {
|
|
1114
1214
|
const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
|
|
1115
1215
|
const round = (n) => Math.round(n);
|
|
1116
|
-
const fields =
|
|
1216
|
+
const fields = Object.create(null);
|
|
1217
|
+
const reportSql = sqlTiming !== null && globalThis[SQL_TIMING_BACKEND_KEY] === true;
|
|
1218
|
+
let sqlMs = 0;
|
|
1219
|
+
let sqlQueries = 0;
|
|
1117
1220
|
for (const [name, s] of fieldStats) {
|
|
1118
1221
|
const shapes = Object.create(null);
|
|
1119
|
-
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = {
|
|
1222
|
+
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = reportSql ? {
|
|
1120
1223
|
count: b.count,
|
|
1121
1224
|
rows: b.rows,
|
|
1122
|
-
|
|
1225
|
+
sqlMs: round(b.sqlMs)
|
|
1226
|
+
} : {
|
|
1227
|
+
count: b.count,
|
|
1228
|
+
rows: b.rows
|
|
1123
1229
|
};
|
|
1124
|
-
|
|
1230
|
+
sqlMs += s.sqlSumMs;
|
|
1231
|
+
sqlQueries += s.sqlQueries;
|
|
1232
|
+
fields[name] = reportSql ? {
|
|
1233
|
+
count: s.count,
|
|
1234
|
+
wallSumMs: round(s.wallSumMs),
|
|
1235
|
+
wallMaxMs: round(s.wallMaxMs),
|
|
1236
|
+
sqlSumMs: round(s.sqlSumMs),
|
|
1237
|
+
sqlMaxMs: round(s.sqlMaxMs),
|
|
1238
|
+
sqlQueries: s.sqlQueries,
|
|
1239
|
+
rows: s.rows,
|
|
1240
|
+
shapes
|
|
1241
|
+
} : {
|
|
1125
1242
|
count: s.count,
|
|
1126
1243
|
wallSumMs: round(s.wallSumMs),
|
|
1127
1244
|
wallMaxMs: round(s.wallMaxMs),
|
|
1128
|
-
syncSumMs: round(s.syncSumMs),
|
|
1129
|
-
syncMaxMs: round(s.syncMaxMs),
|
|
1130
1245
|
rows: s.rows,
|
|
1131
1246
|
shapes
|
|
1132
1247
|
};
|
|
@@ -1146,8 +1261,14 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1146
1261
|
aliases,
|
|
1147
1262
|
numericAliases: aliasMap ? aliasMap.size : 0,
|
|
1148
1263
|
errors: result.errors ? result.errors.length : 0,
|
|
1264
|
+
...reportSql ? {
|
|
1265
|
+
sqlMs: round(sqlMs),
|
|
1266
|
+
sqlQueries
|
|
1267
|
+
} : {},
|
|
1149
1268
|
fields,
|
|
1150
|
-
userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160)
|
|
1269
|
+
userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160),
|
|
1270
|
+
...req.clientIp ? { clientIp: req.clientIp } : {},
|
|
1271
|
+
...sourceHeaders(req.headers)
|
|
1151
1272
|
});
|
|
1152
1273
|
} catch {}
|
|
1153
1274
|
return response;
|
|
@@ -1156,7 +1277,8 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1156
1277
|
return async (req, contextValue) => {
|
|
1157
1278
|
const rec = {
|
|
1158
1279
|
receivedAt: req.receivedAt ?? nowMs(),
|
|
1159
|
-
headers: req.headers
|
|
1280
|
+
headers: req.headers,
|
|
1281
|
+
clientIp: req.clientIp
|
|
1160
1282
|
};
|
|
1161
1283
|
stallMonitor?.begin(rec);
|
|
1162
1284
|
try {
|
|
@@ -1176,7 +1298,8 @@ const createHttpHandler = (options) => {
|
|
|
1176
1298
|
url: req.url,
|
|
1177
1299
|
headers: req.headers,
|
|
1178
1300
|
body: req.body,
|
|
1179
|
-
readBody: (limit) => readRawBody(req, limit)
|
|
1301
|
+
readBody: (limit) => readRawBody(req, limit),
|
|
1302
|
+
clientIp: resolveClientIp(req) || void 0
|
|
1180
1303
|
}, req);
|
|
1181
1304
|
res.statusCode = result.status;
|
|
1182
1305
|
for (const [name, value] of Object.entries(result.headers)) res.setHeader(name, value);
|
|
@@ -1208,6 +1331,7 @@ const readFetchBody = async (request, limit) => {
|
|
|
1208
1331
|
}
|
|
1209
1332
|
return text + decoder.decode();
|
|
1210
1333
|
};
|
|
1334
|
+
const FETCH_CLIENT_IP_HEADERS = ["cf-connecting-ip", "x-real-ip"];
|
|
1211
1335
|
/**
|
|
1212
1336
|
* Fetch-native adapter (Cloudflare Workers / Durable Objects, Deno, Bun): `(Request) => Promise<Response>`.
|
|
1213
1337
|
* Same engine, same guards (depth limit, batch guard, introspection off in production, 100kb body cap) as
|
|
@@ -1222,15 +1346,17 @@ const createFetchHandler = (options) => {
|
|
|
1222
1346
|
headers[key.toLowerCase()] = value;
|
|
1223
1347
|
});
|
|
1224
1348
|
const url = new URL(request.url);
|
|
1349
|
+
const clientIp = resolveClientIp({ headers }, { headers: FETCH_CLIENT_IP_HEADERS }) || void 0;
|
|
1225
1350
|
const result = await engine({
|
|
1226
1351
|
receivedAt,
|
|
1227
1352
|
method: request.method,
|
|
1228
1353
|
url: `${url.pathname}${url.search}`,
|
|
1229
1354
|
headers,
|
|
1230
|
-
readBody: (limit) => readFetchBody(request, limit)
|
|
1355
|
+
readBody: (limit) => readFetchBody(request, limit),
|
|
1356
|
+
clientIp
|
|
1231
1357
|
}, {
|
|
1232
1358
|
headers,
|
|
1233
|
-
ip:
|
|
1359
|
+
ip: clientIp
|
|
1234
1360
|
});
|
|
1235
1361
|
return new Response(result.body, {
|
|
1236
1362
|
status: result.status,
|
|
@@ -1240,4 +1366,4 @@ const createFetchHandler = (options) => {
|
|
|
1240
1366
|
};
|
|
1241
1367
|
|
|
1242
1368
|
//#endregion
|
|
1243
|
-
export { createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
|
|
1369
|
+
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
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
const require_rolldown_runtime = require('./_virtual/rolldown_runtime.cjs');
|
|
2
2
|
let _ocap_schema = require("@ocap/schema");
|
|
3
3
|
_ocap_schema = require_rolldown_runtime.__toESM(_ocap_schema);
|
|
4
|
+
let _ocap_util_lib_client_ip = require("@ocap/util/lib/client-ip");
|
|
4
5
|
let graphql = require("graphql");
|
|
5
6
|
let lodash_get = require("lodash/get");
|
|
6
7
|
lodash_get = require_rolldown_runtime.__toESM(lodash_get);
|
|
@@ -10,7 +11,7 @@ const wrapResolver = async (_name, keys, callback) => {
|
|
|
10
11
|
const result = await callback();
|
|
11
12
|
const resultsMap = {};
|
|
12
13
|
if (Array.isArray(keys)) keys.forEach((key) => {
|
|
13
|
-
resultsMap[key] = result[key];
|
|
14
|
+
resultsMap[key] = result ? result[key] : null;
|
|
14
15
|
});
|
|
15
16
|
else resultsMap[keys] = result;
|
|
16
17
|
return {
|
|
@@ -19,18 +20,28 @@ const wrapResolver = async (_name, keys, callback) => {
|
|
|
19
20
|
...resultsMap
|
|
20
21
|
};
|
|
21
22
|
};
|
|
23
|
+
function readHeaderCaseInsensitive(headers, targetLower) {
|
|
24
|
+
if (!headers) return void 0;
|
|
25
|
+
if (Object.prototype.hasOwnProperty.call(headers, targetLower)) return headers[targetLower];
|
|
26
|
+
for (const [k, v] of Object.entries(headers)) if (k.toLowerCase() === targetLower) return v;
|
|
27
|
+
}
|
|
22
28
|
const formatContext = (ctx = {}) => {
|
|
29
|
+
const featureSwitch = {};
|
|
30
|
+
const gasStakeHeaders = {
|
|
31
|
+
token: (0, lodash_get.default)(ctx, "headers[x-gas-payer-sig]", ""),
|
|
32
|
+
pk: (0, lodash_get.default)(ctx, "headers[x-gas-payer-pk]", "")
|
|
33
|
+
};
|
|
34
|
+
const request = {
|
|
35
|
+
userAgent: (0, lodash_get.default)(ctx, "headers.user-agent"),
|
|
36
|
+
ip: (0, _ocap_util_lib_client_ip.resolveClientIp)(ctx) || "-",
|
|
37
|
+
id: (0, lodash_get.default)(ctx, "headers[x-request-id]") || (0, lodash_get.default)(ctx, "headers[X-Request-ID]") || "-"
|
|
38
|
+
};
|
|
39
|
+
const forwardedHop = readHeaderCaseInsensitive(ctx.headers, "x-ocap-forwarded-hop");
|
|
23
40
|
return {
|
|
24
|
-
featureSwitch
|
|
25
|
-
gasStakeHeaders
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
},
|
|
29
|
-
request: {
|
|
30
|
-
userAgent: (0, lodash_get.default)(ctx, "headers.user-agent"),
|
|
31
|
-
ip: (0, lodash_get.default)(ctx, "headers.x-real-ip") || ctx.ip || ctx._remoteAddress || ctx.connection?.remoteAddress || "-",
|
|
32
|
-
id: (0, lodash_get.default)(ctx, "headers[x-request-id]") || (0, lodash_get.default)(ctx, "headers[X-Request-ID]") || "-"
|
|
33
|
-
}
|
|
41
|
+
featureSwitch,
|
|
42
|
+
gasStakeHeaders,
|
|
43
|
+
request,
|
|
44
|
+
...forwardedHop !== void 0 ? { forwardedHop } : {}
|
|
34
45
|
};
|
|
35
46
|
};
|
|
36
47
|
const resolvers = [
|
|
@@ -142,9 +153,17 @@ const resolvers = [
|
|
|
142
153
|
fn: "getLedgerEntry",
|
|
143
154
|
dataKey: "entry"
|
|
144
155
|
},
|
|
156
|
+
{
|
|
157
|
+
fn: "getLedgerInfo",
|
|
158
|
+
dataKey: "info"
|
|
159
|
+
},
|
|
145
160
|
{
|
|
146
161
|
fn: "getMerkleProof",
|
|
147
|
-
dataKey: [
|
|
162
|
+
dataKey: [
|
|
163
|
+
"proof",
|
|
164
|
+
"checkpoint",
|
|
165
|
+
"entryHashV2From"
|
|
166
|
+
]
|
|
148
167
|
},
|
|
149
168
|
{
|
|
150
169
|
fn: "getTokenDistribution",
|
|
@@ -219,11 +238,17 @@ const resolvers = [
|
|
|
219
238
|
dataKey: ["estimate"]
|
|
220
239
|
}
|
|
221
240
|
];
|
|
241
|
+
/** resolver fns whose rows reach the client only through the GraphQL `IndexedTransaction` type */
|
|
242
|
+
const TX_PROJECTION_FNS = new Set(["listTransactions", "listAssetTransactions"]);
|
|
222
243
|
const createResolvers = (resolver) => resolvers.reduce((acc, { fn, dataKey }) => {
|
|
223
244
|
acc[fn] = async (args, ctx) => {
|
|
224
245
|
const res = await wrapResolver(fn, dataKey, () => {
|
|
225
246
|
const method = resolver[fn];
|
|
226
|
-
if (typeof method === "function")
|
|
247
|
+
if (typeof method === "function") {
|
|
248
|
+
const resolverCtx = formatContext(ctx);
|
|
249
|
+
if (TX_PROJECTION_FNS.has(fn)) resolverCtx.graphqlTxProjection = true;
|
|
250
|
+
return method.call(resolver, args, resolverCtx);
|
|
251
|
+
}
|
|
227
252
|
return null;
|
|
228
253
|
});
|
|
229
254
|
if (fn === "sendTx") {
|
|
@@ -257,6 +282,54 @@ const defaultSlowRequestHandler = (report) => {
|
|
|
257
282
|
console.warn("[gql] slow request", JSON.stringify(report));
|
|
258
283
|
};
|
|
259
284
|
const nowMs = () => typeof performance !== "undefined" ? performance.now() : Date.now();
|
|
285
|
+
/** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
|
|
286
|
+
const SQL_TIMING_KEY = Symbol.for("@ocap/sql-timing");
|
|
287
|
+
/** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
|
|
288
|
+
const SQL_TIMING_BACKEND_KEY = Symbol.for("@ocap/sql-timing/backend");
|
|
289
|
+
const currentAsyncContextRuntime = () => {
|
|
290
|
+
const proc = typeof process !== "undefined" ? process : void 0;
|
|
291
|
+
return {
|
|
292
|
+
bun: typeof proc?.versions?.bun === "string",
|
|
293
|
+
workers: typeof navigator !== "undefined" && navigator.userAgent === "Cloudflare-Workers",
|
|
294
|
+
nodeVersion: proc?.versions?.node,
|
|
295
|
+
execArgv: Array.isArray(proc?.execArgv) ? proc.execArgv : [],
|
|
296
|
+
nodeOptions: typeof process !== "undefined" ? process.env?.NODE_OPTIONS : void 0
|
|
297
|
+
};
|
|
298
|
+
};
|
|
299
|
+
/**
|
|
300
|
+
* Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
|
|
301
|
+
* after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
|
|
302
|
+
* loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
|
|
303
|
+
* Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
|
|
304
|
+
*/
|
|
305
|
+
const isCheapAsyncContextRuntime = (rt = currentAsyncContextRuntime()) => {
|
|
306
|
+
if (rt.bun || rt.workers) return true;
|
|
307
|
+
if (!rt.nodeVersion) return false;
|
|
308
|
+
const flags = new Set([...rt.execArgv || [], ...(rt.nodeOptions || "").split(/\s+/).filter(Boolean)]);
|
|
309
|
+
if (flags.has("--no-async-context-frame") || flags.has("--no-experimental-async-context-frame")) return false;
|
|
310
|
+
if (Number.parseInt(rt.nodeVersion, 10) >= 24) return true;
|
|
311
|
+
return flags.has("--experimental-async-context-frame") || flags.has("--async-context-frame");
|
|
312
|
+
};
|
|
313
|
+
/**
|
|
314
|
+
* The process-wide `AsyncLocalStorage` the SQLite backends read (#1891), created on first use and published under
|
|
315
|
+
* `globalThis[SQL_TIMING_KEY]`; null when the runtime has none (then the report has no `sql*` fields). Only called
|
|
316
|
+
* when the slow-request log is on, so `slowLogMs: 0` never creates it.
|
|
317
|
+
*/
|
|
318
|
+
const getSqlTimingContext = () => {
|
|
319
|
+
const g = globalThis;
|
|
320
|
+
const existing = g[SQL_TIMING_KEY];
|
|
321
|
+
if (existing && typeof existing.run === "function") return existing;
|
|
322
|
+
try {
|
|
323
|
+
const getBuiltin = typeof process !== "undefined" ? process.getBuiltinModule : void 0;
|
|
324
|
+
const Als = globalThis.AsyncLocalStorage ?? (typeof getBuiltin === "function" ? getBuiltin("node:async_hooks")?.AsyncLocalStorage : void 0);
|
|
325
|
+
if (typeof Als !== "function") return null;
|
|
326
|
+
const ctx = new Als();
|
|
327
|
+
g[SQL_TIMING_KEY] = ctx;
|
|
328
|
+
return ctx;
|
|
329
|
+
} catch {
|
|
330
|
+
return null;
|
|
331
|
+
}
|
|
332
|
+
};
|
|
260
333
|
/**
|
|
261
334
|
* Root field name -> number of selections of it in the operation (fragments followed up to `maxFragmentDepth`,
|
|
262
335
|
* each named fragment counted once, bounded).
|
|
@@ -280,6 +353,15 @@ const collectRootFieldCounts = (documentAST, operationName, maxFragmentDepth = M
|
|
|
280
353
|
return names;
|
|
281
354
|
};
|
|
282
355
|
const headerValue = (v) => Array.isArray(v) ? v[0] : v;
|
|
356
|
+
/** `host` / `cfRay` of the slow-request line; header values are client-controlled, so they are length-capped. */
|
|
357
|
+
const sourceHeaders = (headers) => {
|
|
358
|
+
const host = headerValue(headers.host);
|
|
359
|
+
const cfRay = headerValue(headers["cf-ray"]);
|
|
360
|
+
return {
|
|
361
|
+
...host ? { host: host.slice(0, 160) } : {},
|
|
362
|
+
...cfRay ? { cfRay: cfRay.slice(0, 64) } : {}
|
|
363
|
+
};
|
|
364
|
+
};
|
|
283
365
|
const MAX_SHAPES_PER_FIELD = 8;
|
|
284
366
|
const MAX_STALL_ENTRIES = 20;
|
|
285
367
|
const MAX_RECENT_DONE = 64;
|
|
@@ -363,6 +445,7 @@ const createStallMonitor = (requestedMs, report, rootValue) => {
|
|
|
363
445
|
}
|
|
364
446
|
const ua = headerValue(rec.headers["user-agent"]);
|
|
365
447
|
if (ua) entry.userAgent = ua.slice(0, 160);
|
|
448
|
+
if (rec.clientIp) entry.clientIp = rec.clientIp;
|
|
366
449
|
return entry;
|
|
367
450
|
};
|
|
368
451
|
const tick = () => {
|
|
@@ -942,10 +1025,11 @@ const parseEnvBoolean = (raw) => {
|
|
|
942
1025
|
if (normalized === "1" || normalized === "true") return true;
|
|
943
1026
|
if (normalized === "0" || normalized === "false") return false;
|
|
944
1027
|
};
|
|
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 }) => {
|
|
1028
|
+
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
1029
|
const schema = (0, graphql.buildSchema)(_ocap_schema.default);
|
|
947
1030
|
const rootValue = createResolvers(resolver);
|
|
948
1031
|
const stallMonitor = slowLogMs > 0 && stallLogMs > 0 && canProbeEventLoop() ? createStallMonitor(stallLogMs, onEventLoopStall, rootValue) : null;
|
|
1032
|
+
const sqlTiming = slowLogMs > 0 && sqlTimingEnabled ? getSqlTimingContext() : null;
|
|
949
1033
|
const formatGraphQLError = (err) => {
|
|
950
1034
|
onError(err);
|
|
951
1035
|
const includeStack = showStack && process.env.NODE_ENV !== "production";
|
|
@@ -1043,47 +1127,48 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1043
1127
|
try {
|
|
1044
1128
|
shape = describeArgShape(args[0]);
|
|
1045
1129
|
} catch {}
|
|
1130
|
+
const sink = {
|
|
1131
|
+
sqlMs: 0,
|
|
1132
|
+
sqlQueries: 0
|
|
1133
|
+
};
|
|
1134
|
+
const call = () => fn.apply(rootValue, args);
|
|
1046
1135
|
const t = nowMs();
|
|
1047
|
-
let syncMs = 0;
|
|
1048
1136
|
let rows = 0;
|
|
1049
1137
|
try {
|
|
1050
|
-
|
|
1051
|
-
try {
|
|
1052
|
-
pending = fn.apply(rootValue, args);
|
|
1053
|
-
} finally {
|
|
1054
|
-
syncMs = nowMs() - t;
|
|
1055
|
-
}
|
|
1056
|
-
const out = await pending;
|
|
1138
|
+
const out = await (sqlTiming ? sqlTiming.run(sink, call) : call());
|
|
1057
1139
|
try {
|
|
1058
1140
|
rows = countRows(out);
|
|
1059
1141
|
} catch {}
|
|
1060
1142
|
return out;
|
|
1061
1143
|
} finally {
|
|
1062
1144
|
const ms = nowMs() - t;
|
|
1145
|
+
sink.closed = true;
|
|
1063
1146
|
const s = fieldStats.get(name) || {
|
|
1064
1147
|
count: 0,
|
|
1065
1148
|
wallSumMs: 0,
|
|
1066
1149
|
wallMaxMs: 0,
|
|
1067
|
-
|
|
1068
|
-
|
|
1150
|
+
sqlSumMs: 0,
|
|
1151
|
+
sqlMaxMs: 0,
|
|
1152
|
+
sqlQueries: 0,
|
|
1069
1153
|
rows: 0,
|
|
1070
1154
|
shapes: Object.create(null)
|
|
1071
1155
|
};
|
|
1072
1156
|
s.count += 1;
|
|
1073
1157
|
s.wallSumMs += ms;
|
|
1074
1158
|
if (ms > s.wallMaxMs) s.wallMaxMs = ms;
|
|
1075
|
-
s.
|
|
1076
|
-
if (
|
|
1159
|
+
s.sqlSumMs = s.sqlSumMs + sink.sqlMs;
|
|
1160
|
+
if (sink.sqlMs > s.sqlMaxMs) s.sqlMaxMs = sink.sqlMs;
|
|
1161
|
+
s.sqlQueries = s.sqlQueries + sink.sqlQueries;
|
|
1077
1162
|
s.rows += rows;
|
|
1078
1163
|
if (!s.shapes[shape] && Object.keys(s.shapes).length >= MAX_SHAPES_PER_FIELD) shape = "other";
|
|
1079
1164
|
const b = s.shapes[shape] || {
|
|
1080
1165
|
count: 0,
|
|
1081
1166
|
rows: 0,
|
|
1082
|
-
|
|
1167
|
+
sqlMs: 0
|
|
1083
1168
|
};
|
|
1084
1169
|
b.count += 1;
|
|
1085
1170
|
b.rows += rows;
|
|
1086
|
-
b.
|
|
1171
|
+
b.sqlMs = b.sqlMs + sink.sqlMs;
|
|
1087
1172
|
s.shapes[shape] = b;
|
|
1088
1173
|
fieldStats.set(name, s);
|
|
1089
1174
|
}
|
|
@@ -1104,32 +1189,62 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1104
1189
|
} catch (contextError) {
|
|
1105
1190
|
return sendJSON(400, { errors: [formatAnyError(contextError)] });
|
|
1106
1191
|
}
|
|
1107
|
-
const
|
|
1192
|
+
const responseData = aliasMap && result.data != null ? restoreNumericAliasesInData(result.data, aliasMap) : result.data;
|
|
1193
|
+
const formattedResult = { data: responseData };
|
|
1108
1194
|
if (result.errors && result.errors.length > 0) formattedResult.errors = result.errors.map(formatError);
|
|
1109
1195
|
const status = result.data == null ? 500 : 200;
|
|
1110
|
-
|
|
1196
|
+
const extraHeaders = {};
|
|
1197
|
+
const forwardedHop = readHeaderCaseInsensitive(req.headers, "x-ocap-forwarded-hop");
|
|
1198
|
+
const sentTxHash = responseData?.sendTx?.hash;
|
|
1199
|
+
if (forwardedHop !== void 0 && typeof sentTxHash === "string" && sentTxHash && (!result.errors || result.errors.length === 0)) {
|
|
1200
|
+
const signFn = resolver.signForwardedSendTxReceipt;
|
|
1201
|
+
if (typeof signFn === "function") {
|
|
1202
|
+
const signedReceipt = await signFn.call(resolver, sentTxHash);
|
|
1203
|
+
if (signedReceipt?.signature && signedReceipt?.proposer) {
|
|
1204
|
+
extraHeaders["X-Ocap-Forward-Receipt-Sig"] = signedReceipt.signature;
|
|
1205
|
+
extraHeaders["X-Ocap-Forward-Proposer"] = signedReceipt.proposer;
|
|
1206
|
+
}
|
|
1207
|
+
if (signedReceipt?.commitProof) extraHeaders["X-Ocap-Forward-Commit-Proof"] = signedReceipt.commitProof;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
if (slowLogMs <= 0) return sendJSON(status, formattedResult, extraHeaders);
|
|
1111
1211
|
const executedAt = nowMs();
|
|
1112
|
-
const response = sendJSON(status, formattedResult);
|
|
1212
|
+
const response = sendJSON(status, formattedResult, extraHeaders);
|
|
1113
1213
|
const finishedAt = nowMs();
|
|
1114
1214
|
const totalMs = finishedAt - startedAt;
|
|
1115
1215
|
const queuedMs = rec ? Math.max(0, startedAt - rec.receivedAt) : 0;
|
|
1116
1216
|
if (totalMs + queuedMs >= slowLogMs) try {
|
|
1117
1217
|
const { fields: selections, aliases } = countTotalSelectionsAndAliases(documentAST, Number.MAX_SAFE_INTEGER, Number.MAX_SAFE_INTEGER);
|
|
1118
1218
|
const round = (n) => Math.round(n);
|
|
1119
|
-
const fields =
|
|
1219
|
+
const fields = Object.create(null);
|
|
1220
|
+
const reportSql = sqlTiming !== null && globalThis[SQL_TIMING_BACKEND_KEY] === true;
|
|
1221
|
+
let sqlMs = 0;
|
|
1222
|
+
let sqlQueries = 0;
|
|
1120
1223
|
for (const [name, s] of fieldStats) {
|
|
1121
1224
|
const shapes = Object.create(null);
|
|
1122
|
-
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = {
|
|
1225
|
+
for (const [k, b] of Object.entries(s.shapes)) shapes[k] = reportSql ? {
|
|
1123
1226
|
count: b.count,
|
|
1124
1227
|
rows: b.rows,
|
|
1125
|
-
|
|
1228
|
+
sqlMs: round(b.sqlMs)
|
|
1229
|
+
} : {
|
|
1230
|
+
count: b.count,
|
|
1231
|
+
rows: b.rows
|
|
1126
1232
|
};
|
|
1127
|
-
|
|
1233
|
+
sqlMs += s.sqlSumMs;
|
|
1234
|
+
sqlQueries += s.sqlQueries;
|
|
1235
|
+
fields[name] = reportSql ? {
|
|
1236
|
+
count: s.count,
|
|
1237
|
+
wallSumMs: round(s.wallSumMs),
|
|
1238
|
+
wallMaxMs: round(s.wallMaxMs),
|
|
1239
|
+
sqlSumMs: round(s.sqlSumMs),
|
|
1240
|
+
sqlMaxMs: round(s.sqlMaxMs),
|
|
1241
|
+
sqlQueries: s.sqlQueries,
|
|
1242
|
+
rows: s.rows,
|
|
1243
|
+
shapes
|
|
1244
|
+
} : {
|
|
1128
1245
|
count: s.count,
|
|
1129
1246
|
wallSumMs: round(s.wallSumMs),
|
|
1130
1247
|
wallMaxMs: round(s.wallMaxMs),
|
|
1131
|
-
syncSumMs: round(s.syncSumMs),
|
|
1132
|
-
syncMaxMs: round(s.syncMaxMs),
|
|
1133
1248
|
rows: s.rows,
|
|
1134
1249
|
shapes
|
|
1135
1250
|
};
|
|
@@ -1149,8 +1264,14 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1149
1264
|
aliases,
|
|
1150
1265
|
numericAliases: aliasMap ? aliasMap.size : 0,
|
|
1151
1266
|
errors: result.errors ? result.errors.length : 0,
|
|
1267
|
+
...reportSql ? {
|
|
1268
|
+
sqlMs: round(sqlMs),
|
|
1269
|
+
sqlQueries
|
|
1270
|
+
} : {},
|
|
1152
1271
|
fields,
|
|
1153
|
-
userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160)
|
|
1272
|
+
userAgent: headerValue(req.headers["user-agent"])?.slice(0, 160),
|
|
1273
|
+
...req.clientIp ? { clientIp: req.clientIp } : {},
|
|
1274
|
+
...sourceHeaders(req.headers)
|
|
1154
1275
|
});
|
|
1155
1276
|
} catch {}
|
|
1156
1277
|
return response;
|
|
@@ -1159,7 +1280,8 @@ const createGraphQLEngine = ({ resolver = {}, onError = defaultErrorHandler, gra
|
|
|
1159
1280
|
return async (req, contextValue) => {
|
|
1160
1281
|
const rec = {
|
|
1161
1282
|
receivedAt: req.receivedAt ?? nowMs(),
|
|
1162
|
-
headers: req.headers
|
|
1283
|
+
headers: req.headers,
|
|
1284
|
+
clientIp: req.clientIp
|
|
1163
1285
|
};
|
|
1164
1286
|
stallMonitor?.begin(rec);
|
|
1165
1287
|
try {
|
|
@@ -1179,7 +1301,8 @@ const createHttpHandler = (options) => {
|
|
|
1179
1301
|
url: req.url,
|
|
1180
1302
|
headers: req.headers,
|
|
1181
1303
|
body: req.body,
|
|
1182
|
-
readBody: (limit) => readRawBody(req, limit)
|
|
1304
|
+
readBody: (limit) => readRawBody(req, limit),
|
|
1305
|
+
clientIp: (0, _ocap_util_lib_client_ip.resolveClientIp)(req) || void 0
|
|
1183
1306
|
}, req);
|
|
1184
1307
|
res.statusCode = result.status;
|
|
1185
1308
|
for (const [name, value] of Object.entries(result.headers)) res.setHeader(name, value);
|
|
@@ -1211,6 +1334,7 @@ const readFetchBody = async (request, limit) => {
|
|
|
1211
1334
|
}
|
|
1212
1335
|
return text + decoder.decode();
|
|
1213
1336
|
};
|
|
1337
|
+
const FETCH_CLIENT_IP_HEADERS = ["cf-connecting-ip", "x-real-ip"];
|
|
1214
1338
|
/**
|
|
1215
1339
|
* Fetch-native adapter (Cloudflare Workers / Durable Objects, Deno, Bun): `(Request) => Promise<Response>`.
|
|
1216
1340
|
* Same engine, same guards (depth limit, batch guard, introspection off in production, 100kb body cap) as
|
|
@@ -1225,15 +1349,17 @@ const createFetchHandler = (options) => {
|
|
|
1225
1349
|
headers[key.toLowerCase()] = value;
|
|
1226
1350
|
});
|
|
1227
1351
|
const url = new URL(request.url);
|
|
1352
|
+
const clientIp = (0, _ocap_util_lib_client_ip.resolveClientIp)({ headers }, { headers: FETCH_CLIENT_IP_HEADERS }) || void 0;
|
|
1228
1353
|
const result = await engine({
|
|
1229
1354
|
receivedAt,
|
|
1230
1355
|
method: request.method,
|
|
1231
1356
|
url: `${url.pathname}${url.search}`,
|
|
1232
1357
|
headers,
|
|
1233
|
-
readBody: (limit) => readFetchBody(request, limit)
|
|
1358
|
+
readBody: (limit) => readFetchBody(request, limit),
|
|
1359
|
+
clientIp
|
|
1234
1360
|
}, {
|
|
1235
1361
|
headers,
|
|
1236
|
-
ip:
|
|
1362
|
+
ip: clientIp
|
|
1237
1363
|
});
|
|
1238
1364
|
return new Response(result.body, {
|
|
1239
1365
|
status: result.status,
|
|
@@ -1243,9 +1369,12 @@ const createFetchHandler = (options) => {
|
|
|
1243
1369
|
};
|
|
1244
1370
|
|
|
1245
1371
|
//#endregion
|
|
1372
|
+
exports.SQL_TIMING_BACKEND_KEY = SQL_TIMING_BACKEND_KEY;
|
|
1373
|
+
exports.SQL_TIMING_KEY = SQL_TIMING_KEY;
|
|
1246
1374
|
exports.createFetchHandler = createFetchHandler;
|
|
1247
1375
|
exports.createHttpHandler = createHttpHandler;
|
|
1248
1376
|
exports.createResolvers = createResolvers;
|
|
1249
1377
|
exports.formatContext = formatContext;
|
|
1378
|
+
exports.isCheapAsyncContextRuntime = isCheapAsyncContextRuntime;
|
|
1250
1379
|
exports.normalizeNumericFieldAliases = normalizeNumericFieldAliases;
|
|
1251
1380
|
exports.wrapResolver = wrapResolver;
|
package/lib/http.d.cts
CHANGED
|
@@ -14,12 +14,15 @@ interface WrapResolverResult {
|
|
|
14
14
|
}
|
|
15
15
|
declare const wrapResolver: (_name: string, keys: string | string[], callback: () => Promise<ResolverResult | null> | ResolverResult | null | string) => Promise<WrapResolverResult>;
|
|
16
16
|
interface RequestContext {
|
|
17
|
-
headers?: Record<string, string>;
|
|
17
|
+
headers?: Record<string, string | string[] | undefined>;
|
|
18
18
|
ip?: string;
|
|
19
19
|
_remoteAddress?: string;
|
|
20
20
|
connection?: {
|
|
21
21
|
remoteAddress?: string;
|
|
22
22
|
};
|
|
23
|
+
socket?: {
|
|
24
|
+
remoteAddress?: string;
|
|
25
|
+
};
|
|
23
26
|
}
|
|
24
27
|
declare const formatContext: (ctx?: RequestContext) => IResolverContext;
|
|
25
28
|
type Resolver = IResolver;
|
|
@@ -49,6 +52,14 @@ interface HttpHandlerOptions {
|
|
|
49
52
|
stallLogMs?: number;
|
|
50
53
|
/** Receives stall reports. Defaults to one `console.warn('[gql] event loop stall', json)` line. */
|
|
51
54
|
onEventLoopStall?: (report: EventLoopStallReport) => void;
|
|
55
|
+
/**
|
|
56
|
+
* Per root field SQLite time in the slow-request log (#1891; needs `AsyncLocalStorage`). Falls back to
|
|
57
|
+
* `GQL_SQL_TIMING` (`1`/`true` on, `0`/`false` off), then to `isCheapAsyncContextRuntime()`: on for Bun, Workers,
|
|
58
|
+
* Node >= 24 and Node started with `--experimental-async-context-frame`; off on older Node, where the first
|
|
59
|
+
* `AsyncLocalStorage#run` turns on async_hooks promise hooks for the whole process and slows every `await`.
|
|
60
|
+
* Ignored when `slowLogMs` is 0.
|
|
61
|
+
*/
|
|
62
|
+
sqlTiming?: boolean;
|
|
52
63
|
}
|
|
53
64
|
/**
|
|
54
65
|
* Aliases of one root field that share an argument shape. The shape key lists the argument names present (sorted),
|
|
@@ -60,22 +71,32 @@ interface SlowRequestShapeStat {
|
|
|
60
71
|
count: number;
|
|
61
72
|
/** Rows returned: total length of the list payloads (e.g. `transactions`) over the aliases in this bucket. */
|
|
62
73
|
rows: number;
|
|
63
|
-
/**
|
|
64
|
-
|
|
74
|
+
/** SQLite execution time of the statements the aliases of this bucket ran (see `SlowRequestFieldStat.sqlSumMs`). */
|
|
75
|
+
sqlMs?: number;
|
|
65
76
|
}
|
|
66
77
|
/**
|
|
67
78
|
* Per root field stats inside one request. graphql-js starts every root field of a batch in the same tick and their
|
|
68
79
|
* 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
|
-
*
|
|
80
|
+
* most `executeMs`, and `wallSumMs` can exceed it.
|
|
81
|
+
*
|
|
82
|
+
* `sqlSumMs` / `sqlMaxMs` / `sqlQueries` (#1891) are measured at the SQLite execution layer: every statement the
|
|
83
|
+
* indexdb / statedb SQLite backends execute on behalf of an alias, however many awaits before it, adds its
|
|
84
|
+
* synchronous execution time to that alias (attribution via `AsyncLocalStorage`). SQLite runs on the main thread
|
|
85
|
+
* and statements never overlap, so these do not double count: their sum over all fields (the report's `sqlMs`) stays
|
|
86
|
+
* within `executeMs`. A statement whose promise is shared by several aliases (a cache) counts once, for the alias
|
|
87
|
+
* that started it. Absent when SQL timing is off (`sqlTiming` / `GQL_SQL_TIMING`, default off on Node < 24), the runtime
|
|
88
|
+
* has no `AsyncLocalStorage`, or no SQLite backend in the process is timed.
|
|
72
89
|
*/
|
|
73
90
|
interface SlowRequestFieldStat {
|
|
74
91
|
count: number;
|
|
75
92
|
wallSumMs: number;
|
|
76
93
|
wallMaxMs: number;
|
|
77
|
-
|
|
78
|
-
|
|
94
|
+
/** SQLite execution time of all aliases of this field. */
|
|
95
|
+
sqlSumMs?: number;
|
|
96
|
+
/** Largest SQLite execution time of a single alias. */
|
|
97
|
+
sqlMaxMs?: number;
|
|
98
|
+
/** Statements executed by all aliases of this field. */
|
|
99
|
+
sqlQueries?: number;
|
|
79
100
|
/** Rows returned over all aliases (sum of list payload lengths). */
|
|
80
101
|
rows: number;
|
|
81
102
|
/** Aliases bucketed by argument shape, at most `MAX_SHAPES_PER_FIELD` keys plus `other`. */
|
|
@@ -96,6 +117,8 @@ interface StallInFlightEntry {
|
|
|
96
117
|
/** Root field name -> number of aliases selecting it; names the schema does not resolve are summed as `unknown`. */
|
|
97
118
|
fields?: Record<string, number>;
|
|
98
119
|
userAgent?: string;
|
|
120
|
+
/** Client address as resolved by `@ocap/util/lib/client-ip` (#1922). */
|
|
121
|
+
clientIp?: string;
|
|
99
122
|
}
|
|
100
123
|
/** `[gql] event loop stall` report: the probe timer fired `maxMs` late in the window starting at `windowStart`. */
|
|
101
124
|
interface EventLoopStallReport {
|
|
@@ -131,9 +154,42 @@ interface SlowRequestReport {
|
|
|
131
154
|
aliases: number;
|
|
132
155
|
numericAliases: number;
|
|
133
156
|
errors: number;
|
|
157
|
+
/**
|
|
158
|
+
* SQLite execution time of all root fields (sum of `fields.*.sqlSumMs`), within `executeMs`; the rest of
|
|
159
|
+
* `executeMs` is JavaScript (graphql-js, resolver formatting) and waiting. Absent like the fields' `sql*`.
|
|
160
|
+
*/
|
|
161
|
+
sqlMs?: number;
|
|
162
|
+
/** Statements executed by all root fields. */
|
|
163
|
+
sqlQueries?: number;
|
|
134
164
|
fields: Record<string, SlowRequestFieldStat>;
|
|
135
165
|
userAgent?: string;
|
|
166
|
+
/** Client address as resolved by `@ocap/util/lib/client-ip` (#1922); joins the line with the access log. */
|
|
167
|
+
clientIp?: string;
|
|
168
|
+
/** `Host` header, at most 160 chars. */
|
|
169
|
+
host?: string;
|
|
170
|
+
/** Cloudflare `cf-ray` request id, at most 64 chars; absent when the request did not pass Cloudflare. */
|
|
171
|
+
cfRay?: string;
|
|
172
|
+
}
|
|
173
|
+
/** Must equal `SQL_TIMING_KEY` of `@ocap/util/lib/sql-timing` (a test checks it); kept here so gql has no util dep. */
|
|
174
|
+
declare const SQL_TIMING_KEY: unique symbol;
|
|
175
|
+
/** Set by `instrumentSqlTiming` (`SQL_TIMING_BACKEND_KEY` in `@ocap/util/lib/sql-timing`) once a backend is timed. */
|
|
176
|
+
declare const SQL_TIMING_BACKEND_KEY: unique symbol;
|
|
177
|
+
interface AsyncContextRuntime {
|
|
178
|
+
bun?: boolean;
|
|
179
|
+
workers?: boolean;
|
|
180
|
+
/** `process.versions.node` */
|
|
181
|
+
nodeVersion?: string;
|
|
182
|
+
execArgv?: readonly string[];
|
|
183
|
+
/** `NODE_OPTIONS` */
|
|
184
|
+
nodeOptions?: string;
|
|
136
185
|
}
|
|
186
|
+
/**
|
|
187
|
+
* Whether `AsyncLocalStorage` costs nothing outside the code that uses it. Node < 24 implements it with async_hooks:
|
|
188
|
+
* after the first `run()` every promise in the process pays for a hook (measured on Node 22.23: a bare `await`
|
|
189
|
+
* loop ~2.8x slower, also outside any request). Node 24 (AsyncContextFrame, unless `--no-async-context-frame`),
|
|
190
|
+
* Node 22/23 with `--experimental-async-context-frame`, Bun and Workers do not have that cost.
|
|
191
|
+
*/
|
|
192
|
+
declare const isCheapAsyncContextRuntime: (rt?: AsyncContextRuntime) => boolean;
|
|
137
193
|
/**
|
|
138
194
|
* Transport-agnostic view of an incoming GraphQL request, so the same engine serves express (`createHttpHandler`)
|
|
139
195
|
* and fetch-native runtimes such as Cloudflare Workers (`createFetchHandler`).
|
|
@@ -150,6 +206,8 @@ interface GqlRequestLike {
|
|
|
150
206
|
readBody: (limit: number) => Promise<string>;
|
|
151
207
|
/** `performance.now()` when the adapter received the request; defaults to the engine's own start. */
|
|
152
208
|
receivedAt?: number;
|
|
209
|
+
/** Client address resolved by the adapter (`@ocap/util/lib/client-ip`), reported in the slow / stall lines. */
|
|
210
|
+
clientIp?: string;
|
|
153
211
|
}
|
|
154
212
|
/** Transport-agnostic response produced by the engine. */
|
|
155
213
|
interface GqlResponseLike {
|
|
@@ -177,4 +235,4 @@ declare const createHttpHandler: (options: HttpHandlerOptions) => RequestHandler
|
|
|
177
235
|
*/
|
|
178
236
|
declare const createFetchHandler: (options: HttpHandlerOptions) => (request: globalThis.Request) => Promise<globalThis.Response>;
|
|
179
237
|
//#endregion
|
|
180
|
-
export { EventLoopStallReport, GqlRequestLike, GqlResponseLike, HttpHandlerOptions, type Resolver, SlowRequestFieldStat, SlowRequestReport, SlowRequestShapeStat, StallInFlightEntry, createFetchHandler, createHttpHandler, createResolvers, formatContext, normalizeNumericFieldAliases, wrapResolver };
|
|
238
|
+
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.
|
|
6
|
+
"version": "1.32.0",
|
|
7
7
|
"description": "Resolver middleware for ocap adapters",
|
|
8
8
|
"type": "module",
|
|
9
9
|
"main": "./lib/index.cjs",
|
|
@@ -51,8 +51,9 @@
|
|
|
51
51
|
],
|
|
52
52
|
"license": "MIT",
|
|
53
53
|
"dependencies": {
|
|
54
|
-
"@arcblock/ws": "1.
|
|
55
|
-
"@ocap/schema": "1.
|
|
54
|
+
"@arcblock/ws": "1.32.0",
|
|
55
|
+
"@ocap/schema": "1.32.0",
|
|
56
|
+
"@ocap/util": "1.32.0",
|
|
56
57
|
"graphql": "^16.13.2",
|
|
57
58
|
"lodash": "^4.17.23"
|
|
58
59
|
},
|