-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcreateQueryCostMiddleware.js
More file actions
327 lines (286 loc) · 10.1 KB
/
createQueryCostMiddleware.js
File metadata and controls
327 lines (286 loc) · 10.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import { parse, print } from "graphql";
import { trace, SpanStatusCode } from "@opentelemetry/api"
const { DEBUG } = process.env;
const FLATTENED_FIELDS_NO_DEPTH = new Set([
"nodes", "edges", // default GraphQL
"keys", "aggregates", "groupedAggregates", // plugin fields
"speeds", "splits", "blocks", "amountBlocks", "amountCheckpoints",
"amountFinishes", "numRecords", "points", "totalPoints", "worldRecords",
]);
function getArgValue(valueNode) {
switch (valueNode.kind) {
case "IntValue":
return parseInt(valueNode.value, 10);
case "FloatValue":
return parseFloat(valueNode.value);
case "StringValue":
return valueNode.value;
case "BooleanValue":
return valueNode.value;
default:
return undefined; // ignore variables or complex values
}
}
function getPaginationMultiplier(args, defaultSize) {
const firstArg = args.find((arg) => arg.name.value === "first");
const lastArg = args.find((arg) => arg.name.value === "last");
const first = firstArg ? getArgValue(firstArg.value) : undefined;
const last = lastArg ? getArgValue(lastArg.value) : undefined;
return first ?? last ?? defaultSize;
}
function shouldIncreaseDepth(fieldName) {
return (
!FLATTENED_FIELDS_NO_DEPTH.has(fieldName) && !fieldName.startsWith("__")
);
}
function isManyToMany(fieldName) {
const parts = fieldName.split("By");
return parts.length > 1 && parts[0].endsWith("s");
}
function isCollectionField(fieldName, args) {
if (FLATTENED_FIELDS_NO_DEPTH.has(fieldName)) return false;
const hasPaginationArgs = args.some(
(arg) => arg.name.value === "first" || arg.name.value === "last"
);
const isPlural = fieldName.endsWith("s");
return hasPaginationArgs || isPlural || isManyToMany(fieldName);
}
function containsIntrospectionField(selections) {
for (const sel of selections) {
if (sel.kind === "Field") {
const name = sel.name.value;
if (name === "__schema" || name === "__type") {
return true;
}
} else if (sel.selectionSet) {
if (containsIntrospectionField(sel.selectionSet.selections)) {
return true;
}
}
}
return false;
}
/**
* Recursively estimates cost of GraphQL selections including fragment handling.
* @param {import('graphql').SelectionNode[]} selections
* @param {number} depth
* @param {number} parentMultiplier
* @param {Record<string, import('graphql').FragmentDefinitionNode>} fragments
* @param {Set<string>} visitedFragments
* @param {number} defaultCollectionSize
*/
function estimateSelectionsCost(
selections,
depth = 1,
parentMultiplier = 1,
fragments = {},
visitedFragments = new Set(),
defaultCollectionSize = 1000
) {
let cost = 0;
for (const selection of selections) {
switch (selection.kind) {
case "Field": {
const fieldName = selection.name.value;
const args = selection.arguments ?? [];
const isCollection = isCollectionField(fieldName, args);
const multiplier = isCollection
? getPaginationMultiplier(args, defaultCollectionSize)
: 1;
const totalMultiplier = parentMultiplier * Math.log2(multiplier + 1);
// Only apply depth multiplier if not a flattened field (or the wrapping pagination fields)
const effectiveDepth = shouldIncreaseDepth(fieldName)
? depth
: depth - 1;
if (DEBUG) {
console.warn(
`Estimating cost for field "${fieldName}" at depth ${depth} with multiplier ${totalMultiplier} (effective depth: ${effectiveDepth})`
);
}
cost += totalMultiplier * Math.max(1, effectiveDepth);
if (selection.selectionSet) {
cost += estimateSelectionsCost(
selection.selectionSet.selections,
effectiveDepth + 1,
totalMultiplier,
fragments,
visitedFragments,
defaultCollectionSize
);
}
break;
}
case "FragmentSpread": {
const fragName = selection.name.value;
if (!visitedFragments.has(fragName)) {
visitedFragments.add(fragName);
const fragment = fragments[fragName];
if (fragment) {
cost += estimateSelectionsCost(
fragment.selectionSet.selections,
depth,
parentMultiplier,
fragments,
visitedFragments,
defaultCollectionSize
);
}
visitedFragments.delete(fragName);
}
break;
}
case "InlineFragment": {
cost += estimateSelectionsCost(
selection.selectionSet.selections,
depth,
parentMultiplier,
fragments,
visitedFragments,
defaultCollectionSize
);
break;
}
}
}
return cost;
}
/**
* Entry point: parses document, collects fragments, and calculates total cost.
* @param {import('graphql').DocumentNode} document
* @param {string} [operationName]
* @param {number} defaultCollectionSize
*/
function estimateQueryCost(document, operationName, defaultCollectionSize = 1000) {
const fragments = Object.create(null);
for (const def of document.definitions) {
if (def.kind === "FragmentDefinition") {
fragments[def.name.value] = def;
}
}
let totalCost = 0;
const namedOperation = document.definitions.find(
def => def.kind === "OperationDefinition" && def.name?.value === operationName
);
// If operationName is specified, only calculate cost for that operation
if (operationName && namedOperation) {
totalCost += estimateSelectionsCost(
namedOperation.selectionSet.selections,
1,
1,
fragments,
new Set(),
defaultCollectionSize
);
} else {
// select the operation set in the operationName of the request body
for (const def of document.definitions) {
if (def.kind === "OperationDefinition") {
totalCost += estimateSelectionsCost(
def.selectionSet.selections,
1,
1,
fragments,
new Set(),
defaultCollectionSize
);
}
}
}
return Math.ceil(totalCost);
}
/**
* Koa middleware to estimate GraphQL query cost and reject if above maxCost.
* @param {number} maxCost
* @param {number} defaultCollectionSize
*/
export function createQueryCostMiddleware(
maxCost = 5000,
defaultCollectionSize = 100
) {
/**
* @param {import('koa').Context} ctx - The Koa request/response context object.
* @param {() => Promise<void>} next - The next middleware function in the Koa stack.
* @returns {Promise<void>} Resolves when the middleware chain completes.
*/
return async (ctx, next) => {
if (
ctx.method !== "POST" ||
ctx.path !== "/" || // adjust path as needed
!ctx.request.body?.query
) {
return next();
}
const startTime = performance.now();
const tracer = trace.getTracer(process.env.OPENTELEMETRY_SERVICE_NAME || "postgraphile")
const { operationName, query, variables } = ctx.request.body;
return tracer.startActiveSpan("GraphQL Query Cost Estimation", async (span) => {
let document;
try {
document = parse(query, {
noLocation: true, // Disable location info for performance
allowLegacySDLEmptyFields: false,
allowLegacySDLImplementsInterfaces: false,
});
} catch (err) {
ctx.status = 400;
ctx.body = {
errors: [
{ message: "Invalid GraphQL Syntax", details: err.message },
],
};
return;
}
// Ignore introspection queries
for (const def of document.definitions) {
if (
def.kind === "OperationDefinition" &&
containsIntrospectionField(def.selectionSet.selections)
) {
return next();
}
}
const totalCost = estimateQueryCost(document, operationName, defaultCollectionSize);
const graphQL = print(document);
ctx.set("X-Query-Cost", String(totalCost));
if (DEBUG) {
console.warn(
`Estimated cost for operation "${operationName || "default"}": ${totalCost}`
);
}
const endTime = performance.now();
const elapsedTime = `${(endTime - startTime).toFixed(2)}ms`;
span.setAttribute(`graphql.queryCost.cost`, totalCost);
span.setAttribute(`graphql.queryCost.query`, graphQL);
span.setAttribute(`graphql.queryCost.operationName`, operationName);
span.setAttribute(`graphql.queryCost.elapsedTime`, elapsedTime);
span.setAttribute(`graphql.queryCost.exceeded`, totalCost > maxCost);
if (variables) {
// map variables to a single variable per attribute (e.g `graphql.variables.hash`)
span.setAttributes(Object.entries(variables).reduce((acc, [key, value]) => {
acc[`graphql.queryCost.variables.${key}`] = JSON.stringify(value);
return acc;
}, {}));
}
if (totalCost > maxCost) {
ctx.status = 400;
ctx.body = {
errors: [
{
message: `Query Cost Exceeded`,
details: `Estimated cost: ${totalCost} > ${maxCost}. Optimsise your query by using pagination, reducing field depth and limiting requested fields per selection to fetch only the data you need.`,
},
],
};
span.setStatus({
code: SpanStatusCode.ERROR,
message: `Query cost exceeded: ${totalCost} > ${maxCost}`
});
span.end();
return;
}
span.setStatus({ code: SpanStatusCode.OK});
await next();
span.end();
});
};
}