graphql-complexity 0.3.2__tar.gz → 1.0.0__tar.gz
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.
- graphql_complexity-1.0.0/PKG-INFO +1129 -0
- graphql_complexity-1.0.0/README.md +1102 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/pyproject.toml +5 -3
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/__init__.py +8 -2
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/config.py +1 -1
- graphql_complexity-1.0.0/src/graphql_complexity/estimators/__init__.py +11 -0
- graphql_complexity-1.0.0/src/graphql_complexity/estimators/arguments.py +44 -0
- graphql_complexity-1.0.0/src/graphql_complexity/evaluator/complexity.py +42 -0
- graphql_complexity-1.0.0/src/graphql_complexity/evaluator/explain.py +307 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/evaluator/nodes.py +16 -16
- graphql_complexity-1.0.0/src/graphql_complexity/evaluator/utils.py +43 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/evaluator/visitor.py +7 -4
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/extensions/strawberry_graphql.py +10 -5
- graphql_complexity-0.3.2/PKG-INFO +0 -188
- graphql_complexity-0.3.2/README.md +0 -163
- graphql_complexity-0.3.2/src/graphql_complexity/estimators/__init__.py +0 -5
- graphql_complexity-0.3.2/src/graphql_complexity/evaluator/complexity.py +0 -29
- graphql_complexity-0.3.2/src/graphql_complexity/evaluator/utils.py +0 -32
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/LICENSE +0 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/estimators/base.py +0 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/estimators/directive.py +0 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/estimators/simple.py +0 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/evaluator/__init__.py +0 -0
- {graphql_complexity-0.3.2 → graphql_complexity-1.0.0}/src/graphql_complexity/extensions/__init__.py +0 -0
|
@@ -0,0 +1,1129 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: graphql_complexity
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: A python library that provides complexity calculation helpers for GraphQL
|
|
5
|
+
License: MIT
|
|
6
|
+
License-File: LICENSE
|
|
7
|
+
Keywords: graphql,complexity,query,mutation,subscription
|
|
8
|
+
Author: Checho3388
|
|
9
|
+
Author-email: ezequiel.grondona@gmail.com
|
|
10
|
+
Requires-Python: >=3.10,<4.0
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
|
+
Classifier: Intended Audience :: Developers
|
|
13
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
14
|
+
Classifier: Programming Language :: Python :: 3
|
|
15
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.14
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
21
|
+
Provides-Extra: strawberry-graphql
|
|
22
|
+
Requires-Dist: graphql-core (>=3.2.3,<4.0.0)
|
|
23
|
+
Requires-Dist: strawberry-graphql (>=0.291.3,<0.292.0) ; extra == "strawberry-graphql"
|
|
24
|
+
Project-URL: Repository, https://github.com/Checho3388/graphql-complexity
|
|
25
|
+
Description-Content-Type: text/markdown
|
|
26
|
+
|
|
27
|
+
[](https://github.com/Checho3388/graphql-complexity/raw/main/.github/logo.png)
|
|
28
|
+
|
|
29
|
+
# GraphQL Complexity
|
|
30
|
+
|
|
31
|
+
Welcome to GraphQL-Complexity! This Python library provides functionality to compute the complexity of a GraphQL operation, contributing to better understanding and optimization of your GraphQL APIs. This library is designed to be stable, robust, and highly useful for developers working with GraphQL.
|
|
32
|
+
|
|
33
|
+
[](https://github.com/Checho3388/graphql-complexity/actions/workflows/python-build.yml/badge.svg)
|
|
34
|
+
[](https://pypi.org/project/graphql-complexity/)
|
|
35
|
+
[](https://codecov.io/gh/Checho3388/graphql-complexity)
|
|
36
|
+
[](https://pepy.tech/project/graphql-complexity)
|
|
37
|
+
[](https://pypi.org/project/graphql-complexity/)
|
|
38
|
+
[](https://opensource.org/licenses/MIT)
|
|
39
|
+
|
|
40
|
+
## ✨ Why GraphQL Complexity?
|
|
41
|
+
|
|
42
|
+
Protect your GraphQL API from expensive queries and potential DoS attacks by calculating query complexity before execution.
|
|
43
|
+
|
|
44
|
+
Watch the library live in our demo playground [here](https://graphql-complexity-playground-production.up.railway.app/) .
|
|
45
|
+
|
|
46
|
+
## Features
|
|
47
|
+
|
|
48
|
+
* Compute complexity of GraphQL queries
|
|
49
|
+
* Multiple built-in estimators for complexity computation
|
|
50
|
+
* Customizable estimators for specific use cases
|
|
51
|
+
* Support for Strawberry GraphQL library
|
|
52
|
+
|
|
53
|
+
## Table of Contents
|
|
54
|
+
|
|
55
|
+
* [Installation](#installation-quick-start)
|
|
56
|
+
* [Getting Started](#getting-started)
|
|
57
|
+
* [Estimators](#estimators)
|
|
58
|
+
* [SimpleEstimator](#simpleestimator)
|
|
59
|
+
* [DirectivesEstimator](#directivesestimator)
|
|
60
|
+
* [ArgumentsEstimator](#argumentsestimator)
|
|
61
|
+
* [Custom Estimator](#custom-estimator)
|
|
62
|
+
* [Advanced Examples](#advanced-examples)
|
|
63
|
+
* [Handling Fragments](#handling-fragments)
|
|
64
|
+
* [Complex Nested Queries](#complex-nested-queries)
|
|
65
|
+
* [Working with Arguments](#working-with-arguments)
|
|
66
|
+
* [Combining Multiple Estimators](#combining-multiple-estimators)
|
|
67
|
+
* [Framework Integration](#framework-integration)
|
|
68
|
+
* [Strawberry GraphQL](#strawberry-graphql)
|
|
69
|
+
* [Django Integration](#django-integration)
|
|
70
|
+
* [FastAPI Integration](#fastapi-integration)
|
|
71
|
+
* [Flask Integration](#flask-integration)
|
|
72
|
+
* [Real-World Use Cases](#real-world-use-cases)
|
|
73
|
+
* [Credits](#credits)
|
|
74
|
+
|
|
75
|
+
## Installation (Quick Start)
|
|
76
|
+
|
|
77
|
+
You can install the library via pip:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install graphql-complexity
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
For Strawberry GraphQL integration, use the following command:
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pip install graphql-complexity[strawberry-graphql]
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## Getting Started
|
|
90
|
+
|
|
91
|
+
Create a file named `complexity.py` with the following content:
|
|
92
|
+
|
|
93
|
+
```python
|
|
94
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
95
|
+
from graphql import build_schema
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
schema = build_schema("""
|
|
99
|
+
type User {
|
|
100
|
+
id: ID!
|
|
101
|
+
name: String!
|
|
102
|
+
}
|
|
103
|
+
type Query {
|
|
104
|
+
user: User
|
|
105
|
+
}
|
|
106
|
+
""")
|
|
107
|
+
|
|
108
|
+
query = """
|
|
109
|
+
query SomeQuery {
|
|
110
|
+
user {
|
|
111
|
+
id
|
|
112
|
+
name
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
"""
|
|
116
|
+
|
|
117
|
+
complexity = get_complexity(
|
|
118
|
+
query=query,
|
|
119
|
+
schema=schema,
|
|
120
|
+
estimator=SimpleEstimator(complexity=10)
|
|
121
|
+
)
|
|
122
|
+
if complexity > 10:
|
|
123
|
+
raise Exception("Query is too complex")
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
The library exposes the method `get_complexity` with the algorithm to compute the complexity of a GraphQL operation.
|
|
127
|
+
The algorithm visits each node of the query and computes the complexity of each field using an **estimator**.
|
|
128
|
+
|
|
129
|
+
### Understanding Complexity Calculations with `explain_complexity`
|
|
130
|
+
|
|
131
|
+
The library provides an `explain_complexity` function that offers detailed insights into how complexity is calculated. This debugging tool returns the inner details that led to the final complexity value, making it invaluable for:
|
|
132
|
+
|
|
133
|
+
- **Debugging expensive queries** - Identify which fields contribute most to complexity
|
|
134
|
+
- **Comparing different queries** - Understand why one query is more expensive than another
|
|
135
|
+
- **Learning the library** - See exactly how the estimator evaluates each field
|
|
136
|
+
- **Tuning estimators** - Fine-tune your complexity configuration
|
|
137
|
+
|
|
138
|
+
```python
|
|
139
|
+
from graphql_complexity import explain_complexity, SimpleEstimator
|
|
140
|
+
from graphql import build_schema
|
|
141
|
+
|
|
142
|
+
schema = build_schema("""
|
|
143
|
+
type User {
|
|
144
|
+
id: ID!
|
|
145
|
+
name: String!
|
|
146
|
+
posts: [Post!]!
|
|
147
|
+
}
|
|
148
|
+
type Post {
|
|
149
|
+
id: ID!
|
|
150
|
+
title: String!
|
|
151
|
+
}
|
|
152
|
+
type Query {
|
|
153
|
+
user: User
|
|
154
|
+
}
|
|
155
|
+
""")
|
|
156
|
+
|
|
157
|
+
query = """
|
|
158
|
+
query {
|
|
159
|
+
user {
|
|
160
|
+
id
|
|
161
|
+
name
|
|
162
|
+
posts {
|
|
163
|
+
id
|
|
164
|
+
title
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
"""
|
|
169
|
+
|
|
170
|
+
explanation = explain_complexity(
|
|
171
|
+
query=query,
|
|
172
|
+
schema=schema,
|
|
173
|
+
estimator=SimpleEstimator(complexity=5)
|
|
174
|
+
)
|
|
175
|
+
|
|
176
|
+
print(explanation)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
**Example Output:**
|
|
180
|
+
|
|
181
|
+
```
|
|
182
|
+
================================================================================
|
|
183
|
+
GraphQL Complexity Explanation
|
|
184
|
+
================================================================================
|
|
185
|
+
|
|
186
|
+
Total Complexity: 35
|
|
187
|
+
|
|
188
|
+
Estimator Used:
|
|
189
|
+
Name: SimpleEstimator
|
|
190
|
+
Details:
|
|
191
|
+
complexity_constant: 5
|
|
192
|
+
|
|
193
|
+
Complexity Tree:
|
|
194
|
+
--------------------------------------------------------------------------------
|
|
195
|
+
root (RootNode) = 35
|
|
196
|
+
user (Field) = 35
|
|
197
|
+
id (Field) = 5
|
|
198
|
+
name (Field) = 5
|
|
199
|
+
posts (ListField) = 25
|
|
200
|
+
id (Field) = 5
|
|
201
|
+
title (Field) = 5
|
|
202
|
+
|
|
203
|
+
Field-by-Field Breakdown:
|
|
204
|
+
--------------------------------------------------------------------------------
|
|
205
|
+
user (Field)
|
|
206
|
+
Field complexity: 5
|
|
207
|
+
Children complexity: 30
|
|
208
|
+
Total: 35
|
|
209
|
+
|
|
210
|
+
user.id (Field)
|
|
211
|
+
Field complexity: 5
|
|
212
|
+
Children complexity: 0
|
|
213
|
+
Total: 5
|
|
214
|
+
|
|
215
|
+
user.name (Field)
|
|
216
|
+
Field complexity: 5
|
|
217
|
+
Children complexity: 0
|
|
218
|
+
Total: 5
|
|
219
|
+
|
|
220
|
+
user.posts (ListField) [multiplier: 1]
|
|
221
|
+
Field complexity: 5
|
|
222
|
+
Children complexity: 10
|
|
223
|
+
Total: 25
|
|
224
|
+
|
|
225
|
+
user.posts.id (Field)
|
|
226
|
+
Field complexity: 5
|
|
227
|
+
Children complexity: 0
|
|
228
|
+
Total: 5
|
|
229
|
+
|
|
230
|
+
user.posts.title (Field)
|
|
231
|
+
Field complexity: 5
|
|
232
|
+
Children complexity: 0
|
|
233
|
+
Total: 5
|
|
234
|
+
|
|
235
|
+
================================================================================
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
The explanation shows:
|
|
239
|
+
- **Total Complexity**: The final calculated value
|
|
240
|
+
- **Estimator Details**: Which estimator was used and its configuration
|
|
241
|
+
- **Complexity Tree**: A hierarchical view of how complexity accumulates
|
|
242
|
+
- **Field Breakdown**: Per-field analysis showing how each field contributes to the total
|
|
243
|
+
|
|
244
|
+
## Estimators
|
|
245
|
+
|
|
246
|
+
GraphQL-Complexity provides various built-in estimators for computing query complexity:
|
|
247
|
+
|
|
248
|
+
### SimpleEstimator
|
|
249
|
+
|
|
250
|
+
Estimate fields complexity based on constants for complexity and multiplier. This assigns a constant
|
|
251
|
+
complexity value to each field and multiplies it by another constant, which is propagated along the depth of the query.
|
|
252
|
+
|
|
253
|
+
```python
|
|
254
|
+
from graphql_complexity import SimpleEstimator
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
estimator = SimpleEstimator(complexity=2)
|
|
258
|
+
```
|
|
259
|
+
|
|
260
|
+
### DirectivesEstimator
|
|
261
|
+
|
|
262
|
+
Define fields complexity using schema directives. This assigns a complexity value to each field and multiplies it
|
|
263
|
+
by the depth of the query. It also supports the @complexity directive to assign a custom complexity value to a field.
|
|
264
|
+
|
|
265
|
+
```python
|
|
266
|
+
from graphql_complexity import DirectivesEstimator
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
schema = """
|
|
270
|
+
directive @complexity(
|
|
271
|
+
value: Int!
|
|
272
|
+
) on FIELD_DEFINITION
|
|
273
|
+
|
|
274
|
+
type Query {
|
|
275
|
+
oneField: String @complexity(value: 5)
|
|
276
|
+
otherField: String @complexity(value: 1)
|
|
277
|
+
withoutDirective: String
|
|
278
|
+
}
|
|
279
|
+
"""
|
|
280
|
+
|
|
281
|
+
estimator = DirectivesEstimator(schema)
|
|
282
|
+
```
|
|
283
|
+
|
|
284
|
+
### ArgumentsEstimator
|
|
285
|
+
|
|
286
|
+
Estimate complexity by multiplying a base value by a numeric argument (e.g. `limit`, `first`, `ids`).
|
|
287
|
+
This is useful when your API exposes pagination or batch arguments that directly drive the cost of a field.
|
|
288
|
+
|
|
289
|
+
- **Int argument** — the integer value is used as the multiplier (`limit: 10` → ×10).
|
|
290
|
+
- **List argument** — the length of the list is used as the multiplier (`ids: ["a","b","c"]` → ×3).
|
|
291
|
+
- **No matching argument** — the field gets `default_complexity` (multiplier of 1).
|
|
292
|
+
|
|
293
|
+
```python
|
|
294
|
+
from graphql_complexity import ArgumentsEstimator, get_complexity
|
|
295
|
+
from graphql import build_schema
|
|
296
|
+
|
|
297
|
+
schema = build_schema("""
|
|
298
|
+
type Query {
|
|
299
|
+
users(limit: Int): [User!]!
|
|
300
|
+
usersByIds(ids: [ID!]): [User!]!
|
|
301
|
+
}
|
|
302
|
+
type User {
|
|
303
|
+
id: ID!
|
|
304
|
+
name: String!
|
|
305
|
+
}
|
|
306
|
+
""")
|
|
307
|
+
|
|
308
|
+
estimator = ArgumentsEstimator(
|
|
309
|
+
multipliers=["limit", "ids"],
|
|
310
|
+
default_complexity=1,
|
|
311
|
+
)
|
|
312
|
+
|
|
313
|
+
# users(limit: 50) → complexity 50
|
|
314
|
+
complexity = get_complexity(
|
|
315
|
+
query="query { users(limit: 50) { id name } }",
|
|
316
|
+
schema=schema,
|
|
317
|
+
estimator=estimator,
|
|
318
|
+
)
|
|
319
|
+
print(complexity) # 52 (users=50, id=1, name=1)
|
|
320
|
+
|
|
321
|
+
# usersByIds(ids: ["a","b","c"]) → complexity 3
|
|
322
|
+
complexity = get_complexity(
|
|
323
|
+
query='query { usersByIds(ids: ["a", "b", "c"]) { id } }',
|
|
324
|
+
schema=schema,
|
|
325
|
+
estimator=estimator,
|
|
326
|
+
)
|
|
327
|
+
print(complexity) # 4 (usersByIds=3, id=1)
|
|
328
|
+
```
|
|
329
|
+
|
|
330
|
+
### Custom estimator
|
|
331
|
+
|
|
332
|
+
Custom estimators can be defined to compute the complexity of a field using the `ComplexityEstimator` interface.
|
|
333
|
+
|
|
334
|
+
```python
|
|
335
|
+
from graphql_complexity import ComplexityEstimator
|
|
336
|
+
|
|
337
|
+
|
|
338
|
+
class CustomEstimator(ComplexityEstimator):
|
|
339
|
+
def get_field_complexity(self, node, type_info, path) -> int:
|
|
340
|
+
if node.name.value == "specificField":
|
|
341
|
+
return 100
|
|
342
|
+
return 1
|
|
343
|
+
```
|
|
344
|
+
|
|
345
|
+
## Advanced Examples
|
|
346
|
+
|
|
347
|
+
### Handling Fragments
|
|
348
|
+
|
|
349
|
+
GraphQL fragments allow you to reuse query parts. Here's how complexity is calculated for queries with fragments:
|
|
350
|
+
|
|
351
|
+
```python
|
|
352
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
353
|
+
from graphql import build_schema
|
|
354
|
+
|
|
355
|
+
schema = build_schema("""
|
|
356
|
+
type User {
|
|
357
|
+
id: ID!
|
|
358
|
+
name: String!
|
|
359
|
+
email: String!
|
|
360
|
+
posts: [Post!]!
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
type Post {
|
|
364
|
+
id: ID!
|
|
365
|
+
title: String!
|
|
366
|
+
content: String!
|
|
367
|
+
author: User!
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
type Query {
|
|
371
|
+
user(id: ID!): User
|
|
372
|
+
users: [User!]!
|
|
373
|
+
}
|
|
374
|
+
""")
|
|
375
|
+
|
|
376
|
+
# Query with named fragment
|
|
377
|
+
query = """
|
|
378
|
+
query GetUsers {
|
|
379
|
+
users {
|
|
380
|
+
...UserFields
|
|
381
|
+
posts {
|
|
382
|
+
...PostFields
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
fragment UserFields on User {
|
|
388
|
+
id
|
|
389
|
+
name
|
|
390
|
+
email
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
fragment PostFields on Post {
|
|
394
|
+
id
|
|
395
|
+
title
|
|
396
|
+
content
|
|
397
|
+
}
|
|
398
|
+
"""
|
|
399
|
+
|
|
400
|
+
complexity = get_complexity(
|
|
401
|
+
query=query,
|
|
402
|
+
schema=schema,
|
|
403
|
+
estimator=SimpleEstimator(complexity=1)
|
|
404
|
+
)
|
|
405
|
+
print(f"Query complexity: {complexity}")
|
|
406
|
+
```
|
|
407
|
+
|
|
408
|
+
### Complex Nested Queries
|
|
409
|
+
|
|
410
|
+
When dealing with nested relationships, complexity can grow exponentially. Here's how to handle it:
|
|
411
|
+
|
|
412
|
+
```python
|
|
413
|
+
from graphql_complexity import get_complexity, DirectivesEstimator
|
|
414
|
+
from graphql import build_schema
|
|
415
|
+
|
|
416
|
+
schema = build_schema("""
|
|
417
|
+
directive @complexity(
|
|
418
|
+
value: Int!
|
|
419
|
+
) on FIELD_DEFINITION
|
|
420
|
+
|
|
421
|
+
type Organization {
|
|
422
|
+
id: ID!
|
|
423
|
+
name: String!
|
|
424
|
+
teams: [Team!]! @complexity(value: 5)
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
type Team {
|
|
428
|
+
id: ID!
|
|
429
|
+
name: String!
|
|
430
|
+
members: [User!]! @complexity(value: 3)
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
type User {
|
|
434
|
+
id: ID!
|
|
435
|
+
name: String!
|
|
436
|
+
email: String!
|
|
437
|
+
tasks: [Task!]! @complexity(value: 2)
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
type Task {
|
|
441
|
+
id: ID!
|
|
442
|
+
title: String!
|
|
443
|
+
description: String!
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
type Query {
|
|
447
|
+
organization(id: ID!): Organization
|
|
448
|
+
}
|
|
449
|
+
""")
|
|
450
|
+
|
|
451
|
+
# Deeply nested query
|
|
452
|
+
query = """
|
|
453
|
+
query GetOrgStructure {
|
|
454
|
+
organization(id: "1") {
|
|
455
|
+
id
|
|
456
|
+
name
|
|
457
|
+
teams {
|
|
458
|
+
id
|
|
459
|
+
name
|
|
460
|
+
members {
|
|
461
|
+
id
|
|
462
|
+
name
|
|
463
|
+
email
|
|
464
|
+
tasks {
|
|
465
|
+
id
|
|
466
|
+
title
|
|
467
|
+
description
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
"""
|
|
474
|
+
|
|
475
|
+
estimator = DirectivesEstimator(schema)
|
|
476
|
+
complexity = get_complexity(query=query, schema=schema, estimator=estimator)
|
|
477
|
+
|
|
478
|
+
# Set a reasonable limit
|
|
479
|
+
MAX_COMPLEXITY = 100
|
|
480
|
+
if complexity > MAX_COMPLEXITY:
|
|
481
|
+
raise Exception(f"Query too complex: {complexity} > {MAX_COMPLEXITY}")
|
|
482
|
+
```
|
|
483
|
+
|
|
484
|
+
### Working with Arguments
|
|
485
|
+
|
|
486
|
+
Field arguments can significantly impact query complexity, especially with pagination. The built-in `ArgumentsEstimator` handles the common case where a numeric argument (like `first` or `limit`) or a list argument (like `ids`) directly drives the cost of a field:
|
|
487
|
+
|
|
488
|
+
```python
|
|
489
|
+
from graphql_complexity import ArgumentsEstimator, get_complexity
|
|
490
|
+
from graphql import build_schema
|
|
491
|
+
|
|
492
|
+
schema = build_schema("""
|
|
493
|
+
type Product {
|
|
494
|
+
id: ID!
|
|
495
|
+
name: String!
|
|
496
|
+
price: Float!
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
type Query {
|
|
500
|
+
products(first: Int, offset: Int): [Product!]!
|
|
501
|
+
product(id: ID!): Product
|
|
502
|
+
}
|
|
503
|
+
""")
|
|
504
|
+
|
|
505
|
+
estimator = ArgumentsEstimator(multipliers=["first"], default_complexity=1)
|
|
506
|
+
|
|
507
|
+
query = """
|
|
508
|
+
query GetProducts {
|
|
509
|
+
products(first: 50) {
|
|
510
|
+
id
|
|
511
|
+
name
|
|
512
|
+
price
|
|
513
|
+
}
|
|
514
|
+
}
|
|
515
|
+
"""
|
|
516
|
+
|
|
517
|
+
complexity = get_complexity(query=query, schema=schema, estimator=estimator)
|
|
518
|
+
print(f"Query complexity with pagination: {complexity}")
|
|
519
|
+
# products(first: 50) → 50, id/name/price → 1 each → total: 53
|
|
520
|
+
```
|
|
521
|
+
|
|
522
|
+
For more fine-grained control (e.g. capping limits or applying field-specific multipliers), use a [Custom Estimator](#custom-estimator) instead.
|
|
523
|
+
|
|
524
|
+
### Combining Multiple Estimators
|
|
525
|
+
|
|
526
|
+
You can create sophisticated complexity analysis by combining estimators:
|
|
527
|
+
|
|
528
|
+
```python
|
|
529
|
+
from graphql_complexity import (
|
|
530
|
+
ComplexityEstimator,
|
|
531
|
+
SimpleEstimator,
|
|
532
|
+
DirectivesEstimator,
|
|
533
|
+
get_complexity
|
|
534
|
+
)
|
|
535
|
+
from graphql import build_schema
|
|
536
|
+
|
|
537
|
+
schema = build_schema("""
|
|
538
|
+
directive @complexity(value: Int!) on FIELD_DEFINITION
|
|
539
|
+
|
|
540
|
+
type User {
|
|
541
|
+
id: ID!
|
|
542
|
+
name: String!
|
|
543
|
+
expensiveComputation: String! @complexity(value: 50)
|
|
544
|
+
posts: [Post!]!
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
type Post {
|
|
548
|
+
id: ID!
|
|
549
|
+
title: String!
|
|
550
|
+
}
|
|
551
|
+
|
|
552
|
+
type Query {
|
|
553
|
+
user(id: ID!): User
|
|
554
|
+
users: [User!]!
|
|
555
|
+
}
|
|
556
|
+
""")
|
|
557
|
+
|
|
558
|
+
class CompositeEstimator(ComplexityEstimator):
|
|
559
|
+
"""Combines multiple estimation strategies"""
|
|
560
|
+
|
|
561
|
+
def __init__(self):
|
|
562
|
+
self.directive_estimator = DirectivesEstimator(schema)
|
|
563
|
+
self.simple_estimator = SimpleEstimator(complexity=1)
|
|
564
|
+
|
|
565
|
+
def get_field_complexity(self, node, type_info, path) -> int:
|
|
566
|
+
# First, try directive-based estimation
|
|
567
|
+
directive_complexity = self.directive_estimator.get_field_complexity(
|
|
568
|
+
node, type_info, path
|
|
569
|
+
)
|
|
570
|
+
|
|
571
|
+
# If directive provides a value, use it
|
|
572
|
+
if directive_complexity > 1:
|
|
573
|
+
return directive_complexity
|
|
574
|
+
|
|
575
|
+
# Otherwise, fall back to simple estimation
|
|
576
|
+
return self.simple_estimator.get_field_complexity(node, type_info, path)
|
|
577
|
+
|
|
578
|
+
query = """
|
|
579
|
+
query GetUserData {
|
|
580
|
+
user(id: "1") {
|
|
581
|
+
id
|
|
582
|
+
name
|
|
583
|
+
expensiveComputation
|
|
584
|
+
posts {
|
|
585
|
+
id
|
|
586
|
+
title
|
|
587
|
+
}
|
|
588
|
+
}
|
|
589
|
+
}
|
|
590
|
+
"""
|
|
591
|
+
|
|
592
|
+
complexity = get_complexity(
|
|
593
|
+
query=query,
|
|
594
|
+
schema=schema,
|
|
595
|
+
estimator=CompositeEstimator()
|
|
596
|
+
)
|
|
597
|
+
print(f"Combined estimator complexity: {complexity}")
|
|
598
|
+
```
|
|
599
|
+
|
|
600
|
+
## Framework Integration
|
|
601
|
+
|
|
602
|
+
### Strawberry GraphQL
|
|
603
|
+
|
|
604
|
+
The library is compatible with [strawberry-graphql](https://pypi.org/project/strawberry-graphql/).
|
|
605
|
+
Use the following command to install the library with Strawberry support:
|
|
606
|
+
|
|
607
|
+
```bash
|
|
608
|
+
poetry install --extras strawberry-graphql
|
|
609
|
+
```
|
|
610
|
+
|
|
611
|
+
To use the library with Strawberry GraphQL, use the `build_complexity_extension` method to build the complexity
|
|
612
|
+
extension and add it to the schema. This method receives an estimator and returns a complexity extension that can be added to the schema.
|
|
613
|
+
|
|
614
|
+
```python
|
|
615
|
+
import strawberry
|
|
616
|
+
from graphql_complexity import SimpleEstimator
|
|
617
|
+
from graphql_complexity.extensions.strawberry_graphql import build_complexity_extension
|
|
618
|
+
|
|
619
|
+
|
|
620
|
+
@strawberry.type
|
|
621
|
+
class Query:
|
|
622
|
+
@strawberry.field()
|
|
623
|
+
def hello_world(self) -> str:
|
|
624
|
+
return "Hello world!"
|
|
625
|
+
|
|
626
|
+
extension = build_complexity_extension(estimator=SimpleEstimator())
|
|
627
|
+
schema = strawberry.Schema(query=Query, extensions=[extension])
|
|
628
|
+
|
|
629
|
+
schema.execute_sync("query { helloWorld }")
|
|
630
|
+
```
|
|
631
|
+
|
|
632
|
+
The `build_complexity_extension` method accepts an estimator as optional argument giving the possibility to use one
|
|
633
|
+
of the built-in estimators or a custom estimator.
|
|
634
|
+
|
|
635
|
+
### Django Integration
|
|
636
|
+
|
|
637
|
+
Integrate complexity analysis with Django and Graphene:
|
|
638
|
+
|
|
639
|
+
```python
|
|
640
|
+
# myapp/complexity.py
|
|
641
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
642
|
+
from graphql import GraphQLError
|
|
643
|
+
|
|
644
|
+
|
|
645
|
+
class ComplexityMiddleware:
|
|
646
|
+
def __init__(self, max_complexity=1000):
|
|
647
|
+
self.max_complexity = max_complexity
|
|
648
|
+
self.estimator = SimpleEstimator(complexity=1)
|
|
649
|
+
|
|
650
|
+
def resolve(self, next, root, info, **args):
|
|
651
|
+
# Calculate complexity on first field resolution
|
|
652
|
+
if not hasattr(info.context, '_complexity_checked'):
|
|
653
|
+
try:
|
|
654
|
+
complexity = get_complexity(
|
|
655
|
+
query=info.operation.loc.source.body,
|
|
656
|
+
schema=info.schema,
|
|
657
|
+
estimator=self.estimator
|
|
658
|
+
)
|
|
659
|
+
|
|
660
|
+
if complexity > self.max_complexity:
|
|
661
|
+
raise GraphQLError(
|
|
662
|
+
f"Query is too complex: {complexity}. "
|
|
663
|
+
f"Maximum allowed complexity: {self.max_complexity}"
|
|
664
|
+
)
|
|
665
|
+
|
|
666
|
+
info.context._complexity_checked = True
|
|
667
|
+
info.context._query_complexity = complexity
|
|
668
|
+
|
|
669
|
+
except Exception as e:
|
|
670
|
+
raise GraphQLError(f"Complexity analysis failed: {str(e)}")
|
|
671
|
+
|
|
672
|
+
return next(root, info, **args)
|
|
673
|
+
|
|
674
|
+
|
|
675
|
+
# settings.py
|
|
676
|
+
GRAPHENE = {
|
|
677
|
+
'MIDDLEWARE': [
|
|
678
|
+
'myapp.complexity.ComplexityMiddleware',
|
|
679
|
+
],
|
|
680
|
+
}
|
|
681
|
+
```
|
|
682
|
+
|
|
683
|
+
### FastAPI Integration
|
|
684
|
+
|
|
685
|
+
Use complexity analysis with FastAPI and Strawberry:
|
|
686
|
+
|
|
687
|
+
```python
|
|
688
|
+
from fastapi import FastAPI
|
|
689
|
+
from strawberry.fastapi import GraphQLRouter
|
|
690
|
+
import strawberry
|
|
691
|
+
from graphql_complexity import SimpleEstimator
|
|
692
|
+
from graphql_complexity.extensions.strawberry_graphql import build_complexity_extension
|
|
693
|
+
|
|
694
|
+
|
|
695
|
+
@strawberry.type
|
|
696
|
+
class User:
|
|
697
|
+
id: strawberry.ID
|
|
698
|
+
name: str
|
|
699
|
+
email: str
|
|
700
|
+
|
|
701
|
+
|
|
702
|
+
@strawberry.type
|
|
703
|
+
class Query:
|
|
704
|
+
@strawberry.field
|
|
705
|
+
def user(self, id: strawberry.ID) -> User:
|
|
706
|
+
return User(id=id, name="John Doe", email="john@example.com")
|
|
707
|
+
|
|
708
|
+
@strawberry.field
|
|
709
|
+
def users(self) -> list[User]:
|
|
710
|
+
return [
|
|
711
|
+
User(id="1", name="John Doe", email="john@example.com"),
|
|
712
|
+
User(id="2", name="Jane Smith", email="jane@example.com"),
|
|
713
|
+
]
|
|
714
|
+
|
|
715
|
+
|
|
716
|
+
# Configure complexity limit
|
|
717
|
+
MAX_COMPLEXITY = 1000
|
|
718
|
+
extension = build_complexity_extension(
|
|
719
|
+
estimator=SimpleEstimator(complexity=1),
|
|
720
|
+
max_complexity=MAX_COMPLEXITY
|
|
721
|
+
)
|
|
722
|
+
|
|
723
|
+
schema = strawberry.Schema(query=Query, extensions=[extension])
|
|
724
|
+
graphql_app = GraphQLRouter(schema)
|
|
725
|
+
|
|
726
|
+
app = FastAPI()
|
|
727
|
+
app.include_router(graphql_app, prefix="/graphql")
|
|
728
|
+
```
|
|
729
|
+
|
|
730
|
+
### Flask Integration
|
|
731
|
+
|
|
732
|
+
Integrate with Flask-GraphQL:
|
|
733
|
+
|
|
734
|
+
```python
|
|
735
|
+
from flask import Flask, request, jsonify
|
|
736
|
+
from flask_graphql import GraphQLView
|
|
737
|
+
from graphql import build_schema, GraphQLError
|
|
738
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
739
|
+
|
|
740
|
+
|
|
741
|
+
app = Flask(__name__)
|
|
742
|
+
|
|
743
|
+
schema = build_schema("""
|
|
744
|
+
type User {
|
|
745
|
+
id: ID!
|
|
746
|
+
name: String!
|
|
747
|
+
email: String!
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
type Query {
|
|
751
|
+
user(id: ID!): User
|
|
752
|
+
users: [User!]!
|
|
753
|
+
}
|
|
754
|
+
""")
|
|
755
|
+
|
|
756
|
+
MAX_COMPLEXITY = 1000
|
|
757
|
+
estimator = SimpleEstimator(complexity=1)
|
|
758
|
+
|
|
759
|
+
|
|
760
|
+
def validate_complexity(query_string):
|
|
761
|
+
"""Validate query complexity before execution"""
|
|
762
|
+
try:
|
|
763
|
+
complexity = get_complexity(
|
|
764
|
+
query=query_string,
|
|
765
|
+
schema=schema,
|
|
766
|
+
estimator=estimator
|
|
767
|
+
)
|
|
768
|
+
|
|
769
|
+
if complexity > MAX_COMPLEXITY:
|
|
770
|
+
raise GraphQLError(
|
|
771
|
+
f"Query exceeds complexity limit. "
|
|
772
|
+
f"Query complexity: {complexity}, Max allowed: {MAX_COMPLEXITY}"
|
|
773
|
+
)
|
|
774
|
+
|
|
775
|
+
return complexity
|
|
776
|
+
except Exception as e:
|
|
777
|
+
raise GraphQLError(f"Complexity validation error: {str(e)}")
|
|
778
|
+
|
|
779
|
+
|
|
780
|
+
class ComplexityGraphQLView(GraphQLView):
|
|
781
|
+
def dispatch_request(self):
|
|
782
|
+
# Get the query from request
|
|
783
|
+
data = request.get_json()
|
|
784
|
+
query = data.get('query', '')
|
|
785
|
+
|
|
786
|
+
# Validate complexity
|
|
787
|
+
try:
|
|
788
|
+
complexity = validate_complexity(query)
|
|
789
|
+
# Store complexity in request context for logging
|
|
790
|
+
request.query_complexity = complexity
|
|
791
|
+
except GraphQLError as e:
|
|
792
|
+
return jsonify({'errors': [{'message': str(e)}]}), 400
|
|
793
|
+
|
|
794
|
+
# Proceed with normal GraphQL execution
|
|
795
|
+
return super().dispatch_request()
|
|
796
|
+
|
|
797
|
+
|
|
798
|
+
app.add_url_rule(
|
|
799
|
+
'/graphql',
|
|
800
|
+
view_func=ComplexityGraphQLView.as_view(
|
|
801
|
+
'graphql',
|
|
802
|
+
schema=schema,
|
|
803
|
+
graphiql=True
|
|
804
|
+
)
|
|
805
|
+
)
|
|
806
|
+
|
|
807
|
+
|
|
808
|
+
if __name__ == '__main__':
|
|
809
|
+
app.run(debug=True)
|
|
810
|
+
```
|
|
811
|
+
|
|
812
|
+
## 🍳 Recipes
|
|
813
|
+
|
|
814
|
+
### 1. Reject a query before execution
|
|
815
|
+
|
|
816
|
+
The most common pattern — block expensive queries before they hit your resolvers.
|
|
817
|
+
|
|
818
|
+
```python
|
|
819
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
820
|
+
|
|
821
|
+
MAX_COMPLEXITY = 10
|
|
822
|
+
|
|
823
|
+
def execute_query(schema, query):
|
|
824
|
+
complexity = get_complexity(
|
|
825
|
+
query=query,
|
|
826
|
+
schema=schema,
|
|
827
|
+
estimator=SimpleEstimator(complexity=1)
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
if complexity > MAX_COMPLEXITY:
|
|
831
|
+
raise Exception(f"Query too complex ({complexity}). Max allowed: {MAX_COMPLEXITY}")
|
|
832
|
+
|
|
833
|
+
return schema.execute(query)
|
|
834
|
+
```
|
|
835
|
+
|
|
836
|
+
-----
|
|
837
|
+
|
|
838
|
+
### 2. Set different limits per user role
|
|
839
|
+
|
|
840
|
+
Give trusted users more headroom without opening the door to abuse.
|
|
841
|
+
|
|
842
|
+
```python
|
|
843
|
+
COMPLEXITY_LIMITS = {
|
|
844
|
+
"anonymous": 5,
|
|
845
|
+
"authenticated": 15,
|
|
846
|
+
"admin": 50,
|
|
847
|
+
}
|
|
848
|
+
|
|
849
|
+
def execute_query(schema, query, user_role="anonymous"):
|
|
850
|
+
complexity = get_complexity(
|
|
851
|
+
query=query,
|
|
852
|
+
schema=schema,
|
|
853
|
+
estimator=SimpleEstimator(complexity=1)
|
|
854
|
+
)
|
|
855
|
+
|
|
856
|
+
limit = COMPLEXITY_LIMITS.get(user_role, 5)
|
|
857
|
+
|
|
858
|
+
if complexity > limit:
|
|
859
|
+
raise Exception(f"Query too complex ({complexity}). Max allowed for {user_role}: {limit}")
|
|
860
|
+
|
|
861
|
+
return schema.execute(query)
|
|
862
|
+
```
|
|
863
|
+
|
|
864
|
+
-----
|
|
865
|
+
|
|
866
|
+
### 3. Log complexity without blocking
|
|
867
|
+
|
|
868
|
+
Useful when rolling out complexity limits gradually — monitor first, enforce later.
|
|
869
|
+
|
|
870
|
+
```python
|
|
871
|
+
import logging
|
|
872
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
873
|
+
|
|
874
|
+
logger = logging.getLogger(__name__)
|
|
875
|
+
WARN_THRESHOLD = 10
|
|
876
|
+
|
|
877
|
+
def execute_query(schema, query):
|
|
878
|
+
complexity = get_complexity(
|
|
879
|
+
query=query,
|
|
880
|
+
schema=schema,
|
|
881
|
+
estimator=SimpleEstimator(complexity=1)
|
|
882
|
+
)
|
|
883
|
+
|
|
884
|
+
if complexity > WARN_THRESHOLD:
|
|
885
|
+
logger.warning(f"High complexity query detected: {complexity}")
|
|
886
|
+
|
|
887
|
+
# Always execute — no blocking yet
|
|
888
|
+
return schema.execute(query)
|
|
889
|
+
```
|
|
890
|
+
|
|
891
|
+
> **Tip:** Use this pattern in production for a week to understand your traffic’s complexity distribution before choosing your enforcement threshold.
|
|
892
|
+
|
|
893
|
+
## Real-World Use Cases
|
|
894
|
+
|
|
895
|
+
### E-commerce Platform
|
|
896
|
+
|
|
897
|
+
Protect your e-commerce API from expensive queries:
|
|
898
|
+
|
|
899
|
+
```python
|
|
900
|
+
from graphql_complexity import ComplexityEstimator, get_complexity
|
|
901
|
+
from graphql import build_schema
|
|
902
|
+
|
|
903
|
+
schema = build_schema("""
|
|
904
|
+
directive @complexity(value: Int!) on FIELD_DEFINITION
|
|
905
|
+
|
|
906
|
+
type Product {
|
|
907
|
+
id: ID!
|
|
908
|
+
name: String!
|
|
909
|
+
description: String!
|
|
910
|
+
price: Float!
|
|
911
|
+
reviews: [Review!]! @complexity(value: 10)
|
|
912
|
+
relatedProducts: [Product!]! @complexity(value: 15)
|
|
913
|
+
}
|
|
914
|
+
|
|
915
|
+
type Review {
|
|
916
|
+
id: ID!
|
|
917
|
+
rating: Int!
|
|
918
|
+
comment: String!
|
|
919
|
+
author: User!
|
|
920
|
+
}
|
|
921
|
+
|
|
922
|
+
type User {
|
|
923
|
+
id: ID!
|
|
924
|
+
name: String!
|
|
925
|
+
orders: [Order!]! @complexity(value: 20)
|
|
926
|
+
}
|
|
927
|
+
|
|
928
|
+
type Order {
|
|
929
|
+
id: ID!
|
|
930
|
+
items: [Product!]!
|
|
931
|
+
total: Float!
|
|
932
|
+
}
|
|
933
|
+
|
|
934
|
+
type Query {
|
|
935
|
+
product(id: ID!): Product
|
|
936
|
+
products(limit: Int, offset: Int): [Product!]!
|
|
937
|
+
}
|
|
938
|
+
""")
|
|
939
|
+
|
|
940
|
+
# This query would be too expensive
|
|
941
|
+
expensive_query = """
|
|
942
|
+
query ExpensiveQuery {
|
|
943
|
+
products(limit: 100) {
|
|
944
|
+
id
|
|
945
|
+
name
|
|
946
|
+
reviews {
|
|
947
|
+
author {
|
|
948
|
+
orders {
|
|
949
|
+
items {
|
|
950
|
+
relatedProducts {
|
|
951
|
+
reviews {
|
|
952
|
+
comment
|
|
953
|
+
}
|
|
954
|
+
}
|
|
955
|
+
}
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
"""
|
|
962
|
+
|
|
963
|
+
# Reasonable query
|
|
964
|
+
reasonable_query = """
|
|
965
|
+
query ReasonableQuery {
|
|
966
|
+
product(id: "123") {
|
|
967
|
+
id
|
|
968
|
+
name
|
|
969
|
+
price
|
|
970
|
+
description
|
|
971
|
+
}
|
|
972
|
+
}
|
|
973
|
+
"""
|
|
974
|
+
```
|
|
975
|
+
|
|
976
|
+
### Social Media API
|
|
977
|
+
|
|
978
|
+
Rate limit complex social graph queries:
|
|
979
|
+
|
|
980
|
+
```python
|
|
981
|
+
from graphql_complexity import ComplexityEstimator, get_complexity
|
|
982
|
+
from graphql import build_schema
|
|
983
|
+
|
|
984
|
+
schema = build_schema("""
|
|
985
|
+
directive @complexity(value: Int!) on FIELD_DEFINITION
|
|
986
|
+
|
|
987
|
+
type User {
|
|
988
|
+
id: ID!
|
|
989
|
+
username: String!
|
|
990
|
+
followers: [User!]! @complexity(value: 10)
|
|
991
|
+
following: [User!]! @complexity(value: 10)
|
|
992
|
+
posts: [Post!]! @complexity(value: 5)
|
|
993
|
+
}
|
|
994
|
+
|
|
995
|
+
type Post {
|
|
996
|
+
id: ID!
|
|
997
|
+
content: String!
|
|
998
|
+
author: User!
|
|
999
|
+
likes: [User!]! @complexity(value: 5)
|
|
1000
|
+
comments: [Comment!]! @complexity(value: 3)
|
|
1001
|
+
}
|
|
1002
|
+
|
|
1003
|
+
type Comment {
|
|
1004
|
+
id: ID!
|
|
1005
|
+
text: String!
|
|
1006
|
+
author: User!
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
type Query {
|
|
1010
|
+
user(id: ID!): User
|
|
1011
|
+
feed(limit: Int): [Post!]!
|
|
1012
|
+
}
|
|
1013
|
+
""")
|
|
1014
|
+
|
|
1015
|
+
|
|
1016
|
+
class SocialMediaEstimator(ComplexityEstimator):
|
|
1017
|
+
"""Custom estimator for social media queries"""
|
|
1018
|
+
|
|
1019
|
+
def get_field_complexity(self, node, type_info, path) -> int:
|
|
1020
|
+
field_name = node.name.value
|
|
1021
|
+
|
|
1022
|
+
# Heavy penalty for deeply nested social graphs
|
|
1023
|
+
depth = len(path)
|
|
1024
|
+
depth_penalty = 2 ** depth if depth > 3 else 1
|
|
1025
|
+
|
|
1026
|
+
# Base costs
|
|
1027
|
+
costs = {
|
|
1028
|
+
'followers': 10,
|
|
1029
|
+
'following': 10,
|
|
1030
|
+
'posts': 5,
|
|
1031
|
+
'likes': 5,
|
|
1032
|
+
'comments': 3,
|
|
1033
|
+
'feed': 8,
|
|
1034
|
+
}
|
|
1035
|
+
|
|
1036
|
+
base_cost = costs.get(field_name, 1)
|
|
1037
|
+
return base_cost * depth_penalty
|
|
1038
|
+
|
|
1039
|
+
|
|
1040
|
+
# Example: Preventing graph explosion
|
|
1041
|
+
problematic_query = """
|
|
1042
|
+
query DeepSocialGraph {
|
|
1043
|
+
user(id: "1") {
|
|
1044
|
+
followers {
|
|
1045
|
+
following {
|
|
1046
|
+
posts {
|
|
1047
|
+
likes {
|
|
1048
|
+
followers {
|
|
1049
|
+
# This gets exponentially expensive!
|
|
1050
|
+
username
|
|
1051
|
+
}
|
|
1052
|
+
}
|
|
1053
|
+
}
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
}
|
|
1057
|
+
}
|
|
1058
|
+
"""
|
|
1059
|
+
```
|
|
1060
|
+
|
|
1061
|
+
### Analytics Dashboard
|
|
1062
|
+
|
|
1063
|
+
Manage complexity for data-heavy analytics queries:
|
|
1064
|
+
|
|
1065
|
+
```python
|
|
1066
|
+
from graphql_complexity import ComplexityEstimator, get_complexity
|
|
1067
|
+
from graphql import build_schema
|
|
1068
|
+
from datetime import datetime
|
|
1069
|
+
|
|
1070
|
+
schema = build_schema("""
|
|
1071
|
+
directive @complexity(value: Int!) on FIELD_DEFINITION
|
|
1072
|
+
|
|
1073
|
+
type Analytics {
|
|
1074
|
+
pageViews: Int! @complexity(value: 5)
|
|
1075
|
+
uniqueVisitors: Int! @complexity(value: 5)
|
|
1076
|
+
averageSessionDuration: Float! @complexity(value: 10)
|
|
1077
|
+
conversionRate: Float! @complexity(value: 15)
|
|
1078
|
+
revenueByDay: [DailyRevenue!]! @complexity(value: 20)
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
type DailyRevenue {
|
|
1082
|
+
date: String!
|
|
1083
|
+
amount: Float!
|
|
1084
|
+
transactions: Int!
|
|
1085
|
+
}
|
|
1086
|
+
|
|
1087
|
+
type Query {
|
|
1088
|
+
analytics(
|
|
1089
|
+
startDate: String!
|
|
1090
|
+
endDate: String!
|
|
1091
|
+
granularity: String
|
|
1092
|
+
): Analytics @complexity(value: 10)
|
|
1093
|
+
}
|
|
1094
|
+
""")
|
|
1095
|
+
|
|
1096
|
+
|
|
1097
|
+
def calculate_analytics_complexity(query: str, date_range_days: int) -> int:
|
|
1098
|
+
"""Calculate complexity based on date range"""
|
|
1099
|
+
base_complexity = get_complexity(
|
|
1100
|
+
query=query,
|
|
1101
|
+
schema=schema,
|
|
1102
|
+
estimator=SimpleEstimator(complexity=1)
|
|
1103
|
+
)
|
|
1104
|
+
|
|
1105
|
+
# Multiply by date range (more days = more expensive)
|
|
1106
|
+
range_multiplier = max(1, date_range_days / 7) # Weekly baseline
|
|
1107
|
+
|
|
1108
|
+
return int(base_complexity * range_multiplier)
|
|
1109
|
+
```
|
|
1110
|
+
|
|
1111
|
+
## Credits
|
|
1112
|
+
|
|
1113
|
+
Estimators idea was heavily inspired by [graphql-query-complexity](https://github.com/slicknode/graphql-query-complexity).
|
|
1114
|
+
|
|
1115
|
+
## About
|
|
1116
|
+
|
|
1117
|
+
Python library to compute the complexity of a GraphQL operation
|
|
1118
|
+
|
|
1119
|
+
### Topics
|
|
1120
|
+
|
|
1121
|
+
[python](https://github.com/topics/python)
|
|
1122
|
+
[graphql](https://github.com/topics/graphql)
|
|
1123
|
+
[strawberry](https://github.com/topics/strawberry)
|
|
1124
|
+
[graphql-core](https://github.com/topics/graphql-core)
|
|
1125
|
+
|
|
1126
|
+
### License
|
|
1127
|
+
|
|
1128
|
+
[MIT license](LICENSE)
|
|
1129
|
+
|