graphql-complexity 0.4.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-0.4.2 → graphql_complexity-1.0.0}/PKG-INFO +255 -37
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/README.md +253 -35
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/pyproject.toml +3 -2
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/__init__.py +8 -2
- 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.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/evaluator/nodes.py +8 -7
- graphql_complexity-1.0.0/src/graphql_complexity/evaluator/utils.py +43 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/evaluator/visitor.py +7 -4
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/extensions/strawberry_graphql.py +8 -3
- graphql_complexity-0.4.2/src/graphql_complexity/estimators/__init__.py +0 -5
- graphql_complexity-0.4.2/src/graphql_complexity/evaluator/complexity.py +0 -29
- graphql_complexity-0.4.2/src/graphql_complexity/evaluator/utils.py +0 -32
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/LICENSE +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/config.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/estimators/base.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/estimators/directive.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/estimators/simple.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/evaluator/__init__.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.0.0}/src/graphql_complexity/extensions/__init__.py +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: graphql_complexity
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 1.0.0
|
|
4
4
|
Summary: A python library that provides complexity calculation helpers for GraphQL
|
|
5
5
|
License: MIT
|
|
6
6
|
License-File: LICENSE
|
|
@@ -8,7 +8,7 @@ Keywords: graphql,complexity,query,mutation,subscription
|
|
|
8
8
|
Author: Checho3388
|
|
9
9
|
Author-email: ezequiel.grondona@gmail.com
|
|
10
10
|
Requires-Python: >=3.10,<4.0
|
|
11
|
-
Classifier: Development Status ::
|
|
11
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
12
12
|
Classifier: Intended Audience :: Developers
|
|
13
13
|
Classifier: License :: OSI Approved :: MIT License
|
|
14
14
|
Classifier: Programming Language :: Python :: 3
|
|
@@ -41,7 +41,7 @@ Welcome to GraphQL-Complexity! This Python library provides functionality to com
|
|
|
41
41
|
|
|
42
42
|
Protect your GraphQL API from expensive queries and potential DoS attacks by calculating query complexity before execution.
|
|
43
43
|
|
|
44
|
-
|
|
44
|
+
Watch the library live in our demo playground [here](https://graphql-complexity-playground-production.up.railway.app/) .
|
|
45
45
|
|
|
46
46
|
## Features
|
|
47
47
|
|
|
@@ -57,6 +57,7 @@ Protect your GraphQL API from expensive queries and potential DoS attacks by cal
|
|
|
57
57
|
* [Estimators](#estimators)
|
|
58
58
|
* [SimpleEstimator](#simpleestimator)
|
|
59
59
|
* [DirectivesEstimator](#directivesestimator)
|
|
60
|
+
* [ArgumentsEstimator](#argumentsestimator)
|
|
60
61
|
* [Custom Estimator](#custom-estimator)
|
|
61
62
|
* [Advanced Examples](#advanced-examples)
|
|
62
63
|
* [Handling Fragments](#handling-fragments)
|
|
@@ -125,6 +126,121 @@ if complexity > 10:
|
|
|
125
126
|
The library exposes the method `get_complexity` with the algorithm to compute the complexity of a GraphQL operation.
|
|
126
127
|
The algorithm visits each node of the query and computes the complexity of each field using an **estimator**.
|
|
127
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
|
+
|
|
128
244
|
## Estimators
|
|
129
245
|
|
|
130
246
|
GraphQL-Complexity provides various built-in estimators for computing query complexity:
|
|
@@ -165,6 +281,52 @@ type Query {
|
|
|
165
281
|
estimator = DirectivesEstimator(schema)
|
|
166
282
|
```
|
|
167
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
|
+
|
|
168
330
|
### Custom estimator
|
|
169
331
|
|
|
170
332
|
Custom estimators can be defined to compute the complexity of a field using the `ComplexityEstimator` interface.
|
|
@@ -321,12 +483,11 @@ if complexity > MAX_COMPLEXITY:
|
|
|
321
483
|
|
|
322
484
|
### Working with Arguments
|
|
323
485
|
|
|
324
|
-
Field arguments can significantly impact query complexity, especially with pagination:
|
|
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:
|
|
325
487
|
|
|
326
488
|
```python
|
|
327
|
-
from graphql_complexity import
|
|
328
|
-
from graphql import build_schema
|
|
329
|
-
from graphql.language import ast
|
|
489
|
+
from graphql_complexity import ArgumentsEstimator, get_complexity
|
|
490
|
+
from graphql import build_schema
|
|
330
491
|
|
|
331
492
|
schema = build_schema("""
|
|
332
493
|
type Product {
|
|
@@ -334,37 +495,14 @@ schema = build_schema("""
|
|
|
334
495
|
name: String!
|
|
335
496
|
price: Float!
|
|
336
497
|
}
|
|
337
|
-
|
|
498
|
+
|
|
338
499
|
type Query {
|
|
339
500
|
products(first: Int, offset: Int): [Product!]!
|
|
340
501
|
product(id: ID!): Product
|
|
341
502
|
}
|
|
342
503
|
""")
|
|
343
504
|
|
|
344
|
-
|
|
345
|
-
"""Custom estimator that considers pagination arguments"""
|
|
346
|
-
|
|
347
|
-
def get_field_complexity(self, node: FieldNode, type_info, path) -> int:
|
|
348
|
-
field_name = node.name.value
|
|
349
|
-
|
|
350
|
-
# Base complexity
|
|
351
|
-
base_complexity = 1
|
|
352
|
-
|
|
353
|
-
# Check for list/pagination arguments
|
|
354
|
-
if node.arguments:
|
|
355
|
-
for arg in node.arguments:
|
|
356
|
-
if arg.name.value == "first":
|
|
357
|
-
# Extract the limit value
|
|
358
|
-
if isinstance(arg.value, ast.IntValue):
|
|
359
|
-
limit = int(arg.value.value)
|
|
360
|
-
# Multiply complexity by the number of items requested
|
|
361
|
-
base_complexity *= min(limit, 100) # Cap at 100
|
|
362
|
-
|
|
363
|
-
# Apply higher base cost for lists
|
|
364
|
-
if field_name == "products":
|
|
365
|
-
base_complexity *= 5
|
|
366
|
-
|
|
367
|
-
return base_complexity
|
|
505
|
+
estimator = ArgumentsEstimator(multipliers=["first"], default_complexity=1)
|
|
368
506
|
|
|
369
507
|
query = """
|
|
370
508
|
query GetProducts {
|
|
@@ -376,14 +514,13 @@ query = """
|
|
|
376
514
|
}
|
|
377
515
|
"""
|
|
378
516
|
|
|
379
|
-
complexity = get_complexity(
|
|
380
|
-
query=query,
|
|
381
|
-
schema=schema,
|
|
382
|
-
estimator=ArgumentAwareEstimator()
|
|
383
|
-
)
|
|
517
|
+
complexity = get_complexity(query=query, schema=schema, estimator=estimator)
|
|
384
518
|
print(f"Query complexity with pagination: {complexity}")
|
|
519
|
+
# products(first: 50) → 50, id/name/price → 1 each → total: 53
|
|
385
520
|
```
|
|
386
521
|
|
|
522
|
+
For more fine-grained control (e.g. capping limits or applying field-specific multipliers), use a [Custom Estimator](#custom-estimator) instead.
|
|
523
|
+
|
|
387
524
|
### Combining Multiple Estimators
|
|
388
525
|
|
|
389
526
|
You can create sophisticated complexity analysis by combining estimators:
|
|
@@ -672,6 +809,87 @@ if __name__ == '__main__':
|
|
|
672
809
|
app.run(debug=True)
|
|
673
810
|
```
|
|
674
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
|
+
|
|
675
893
|
## Real-World Use Cases
|
|
676
894
|
|
|
677
895
|
### E-commerce Platform
|
|
@@ -15,7 +15,7 @@ Welcome to GraphQL-Complexity! This Python library provides functionality to com
|
|
|
15
15
|
|
|
16
16
|
Protect your GraphQL API from expensive queries and potential DoS attacks by calculating query complexity before execution.
|
|
17
17
|
|
|
18
|
-
|
|
18
|
+
Watch the library live in our demo playground [here](https://graphql-complexity-playground-production.up.railway.app/) .
|
|
19
19
|
|
|
20
20
|
## Features
|
|
21
21
|
|
|
@@ -31,6 +31,7 @@ Protect your GraphQL API from expensive queries and potential DoS attacks by cal
|
|
|
31
31
|
* [Estimators](#estimators)
|
|
32
32
|
* [SimpleEstimator](#simpleestimator)
|
|
33
33
|
* [DirectivesEstimator](#directivesestimator)
|
|
34
|
+
* [ArgumentsEstimator](#argumentsestimator)
|
|
34
35
|
* [Custom Estimator](#custom-estimator)
|
|
35
36
|
* [Advanced Examples](#advanced-examples)
|
|
36
37
|
* [Handling Fragments](#handling-fragments)
|
|
@@ -99,6 +100,121 @@ if complexity > 10:
|
|
|
99
100
|
The library exposes the method `get_complexity` with the algorithm to compute the complexity of a GraphQL operation.
|
|
100
101
|
The algorithm visits each node of the query and computes the complexity of each field using an **estimator**.
|
|
101
102
|
|
|
103
|
+
### Understanding Complexity Calculations with `explain_complexity`
|
|
104
|
+
|
|
105
|
+
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:
|
|
106
|
+
|
|
107
|
+
- **Debugging expensive queries** - Identify which fields contribute most to complexity
|
|
108
|
+
- **Comparing different queries** - Understand why one query is more expensive than another
|
|
109
|
+
- **Learning the library** - See exactly how the estimator evaluates each field
|
|
110
|
+
- **Tuning estimators** - Fine-tune your complexity configuration
|
|
111
|
+
|
|
112
|
+
```python
|
|
113
|
+
from graphql_complexity import explain_complexity, SimpleEstimator
|
|
114
|
+
from graphql import build_schema
|
|
115
|
+
|
|
116
|
+
schema = build_schema("""
|
|
117
|
+
type User {
|
|
118
|
+
id: ID!
|
|
119
|
+
name: String!
|
|
120
|
+
posts: [Post!]!
|
|
121
|
+
}
|
|
122
|
+
type Post {
|
|
123
|
+
id: ID!
|
|
124
|
+
title: String!
|
|
125
|
+
}
|
|
126
|
+
type Query {
|
|
127
|
+
user: User
|
|
128
|
+
}
|
|
129
|
+
""")
|
|
130
|
+
|
|
131
|
+
query = """
|
|
132
|
+
query {
|
|
133
|
+
user {
|
|
134
|
+
id
|
|
135
|
+
name
|
|
136
|
+
posts {
|
|
137
|
+
id
|
|
138
|
+
title
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
"""
|
|
143
|
+
|
|
144
|
+
explanation = explain_complexity(
|
|
145
|
+
query=query,
|
|
146
|
+
schema=schema,
|
|
147
|
+
estimator=SimpleEstimator(complexity=5)
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
print(explanation)
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
**Example Output:**
|
|
154
|
+
|
|
155
|
+
```
|
|
156
|
+
================================================================================
|
|
157
|
+
GraphQL Complexity Explanation
|
|
158
|
+
================================================================================
|
|
159
|
+
|
|
160
|
+
Total Complexity: 35
|
|
161
|
+
|
|
162
|
+
Estimator Used:
|
|
163
|
+
Name: SimpleEstimator
|
|
164
|
+
Details:
|
|
165
|
+
complexity_constant: 5
|
|
166
|
+
|
|
167
|
+
Complexity Tree:
|
|
168
|
+
--------------------------------------------------------------------------------
|
|
169
|
+
root (RootNode) = 35
|
|
170
|
+
user (Field) = 35
|
|
171
|
+
id (Field) = 5
|
|
172
|
+
name (Field) = 5
|
|
173
|
+
posts (ListField) = 25
|
|
174
|
+
id (Field) = 5
|
|
175
|
+
title (Field) = 5
|
|
176
|
+
|
|
177
|
+
Field-by-Field Breakdown:
|
|
178
|
+
--------------------------------------------------------------------------------
|
|
179
|
+
user (Field)
|
|
180
|
+
Field complexity: 5
|
|
181
|
+
Children complexity: 30
|
|
182
|
+
Total: 35
|
|
183
|
+
|
|
184
|
+
user.id (Field)
|
|
185
|
+
Field complexity: 5
|
|
186
|
+
Children complexity: 0
|
|
187
|
+
Total: 5
|
|
188
|
+
|
|
189
|
+
user.name (Field)
|
|
190
|
+
Field complexity: 5
|
|
191
|
+
Children complexity: 0
|
|
192
|
+
Total: 5
|
|
193
|
+
|
|
194
|
+
user.posts (ListField) [multiplier: 1]
|
|
195
|
+
Field complexity: 5
|
|
196
|
+
Children complexity: 10
|
|
197
|
+
Total: 25
|
|
198
|
+
|
|
199
|
+
user.posts.id (Field)
|
|
200
|
+
Field complexity: 5
|
|
201
|
+
Children complexity: 0
|
|
202
|
+
Total: 5
|
|
203
|
+
|
|
204
|
+
user.posts.title (Field)
|
|
205
|
+
Field complexity: 5
|
|
206
|
+
Children complexity: 0
|
|
207
|
+
Total: 5
|
|
208
|
+
|
|
209
|
+
================================================================================
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
The explanation shows:
|
|
213
|
+
- **Total Complexity**: The final calculated value
|
|
214
|
+
- **Estimator Details**: Which estimator was used and its configuration
|
|
215
|
+
- **Complexity Tree**: A hierarchical view of how complexity accumulates
|
|
216
|
+
- **Field Breakdown**: Per-field analysis showing how each field contributes to the total
|
|
217
|
+
|
|
102
218
|
## Estimators
|
|
103
219
|
|
|
104
220
|
GraphQL-Complexity provides various built-in estimators for computing query complexity:
|
|
@@ -139,6 +255,52 @@ type Query {
|
|
|
139
255
|
estimator = DirectivesEstimator(schema)
|
|
140
256
|
```
|
|
141
257
|
|
|
258
|
+
### ArgumentsEstimator
|
|
259
|
+
|
|
260
|
+
Estimate complexity by multiplying a base value by a numeric argument (e.g. `limit`, `first`, `ids`).
|
|
261
|
+
This is useful when your API exposes pagination or batch arguments that directly drive the cost of a field.
|
|
262
|
+
|
|
263
|
+
- **Int argument** — the integer value is used as the multiplier (`limit: 10` → ×10).
|
|
264
|
+
- **List argument** — the length of the list is used as the multiplier (`ids: ["a","b","c"]` → ×3).
|
|
265
|
+
- **No matching argument** — the field gets `default_complexity` (multiplier of 1).
|
|
266
|
+
|
|
267
|
+
```python
|
|
268
|
+
from graphql_complexity import ArgumentsEstimator, get_complexity
|
|
269
|
+
from graphql import build_schema
|
|
270
|
+
|
|
271
|
+
schema = build_schema("""
|
|
272
|
+
type Query {
|
|
273
|
+
users(limit: Int): [User!]!
|
|
274
|
+
usersByIds(ids: [ID!]): [User!]!
|
|
275
|
+
}
|
|
276
|
+
type User {
|
|
277
|
+
id: ID!
|
|
278
|
+
name: String!
|
|
279
|
+
}
|
|
280
|
+
""")
|
|
281
|
+
|
|
282
|
+
estimator = ArgumentsEstimator(
|
|
283
|
+
multipliers=["limit", "ids"],
|
|
284
|
+
default_complexity=1,
|
|
285
|
+
)
|
|
286
|
+
|
|
287
|
+
# users(limit: 50) → complexity 50
|
|
288
|
+
complexity = get_complexity(
|
|
289
|
+
query="query { users(limit: 50) { id name } }",
|
|
290
|
+
schema=schema,
|
|
291
|
+
estimator=estimator,
|
|
292
|
+
)
|
|
293
|
+
print(complexity) # 52 (users=50, id=1, name=1)
|
|
294
|
+
|
|
295
|
+
# usersByIds(ids: ["a","b","c"]) → complexity 3
|
|
296
|
+
complexity = get_complexity(
|
|
297
|
+
query='query { usersByIds(ids: ["a", "b", "c"]) { id } }',
|
|
298
|
+
schema=schema,
|
|
299
|
+
estimator=estimator,
|
|
300
|
+
)
|
|
301
|
+
print(complexity) # 4 (usersByIds=3, id=1)
|
|
302
|
+
```
|
|
303
|
+
|
|
142
304
|
### Custom estimator
|
|
143
305
|
|
|
144
306
|
Custom estimators can be defined to compute the complexity of a field using the `ComplexityEstimator` interface.
|
|
@@ -295,12 +457,11 @@ if complexity > MAX_COMPLEXITY:
|
|
|
295
457
|
|
|
296
458
|
### Working with Arguments
|
|
297
459
|
|
|
298
|
-
Field arguments can significantly impact query complexity, especially with pagination:
|
|
460
|
+
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:
|
|
299
461
|
|
|
300
462
|
```python
|
|
301
|
-
from graphql_complexity import
|
|
302
|
-
from graphql import build_schema
|
|
303
|
-
from graphql.language import ast
|
|
463
|
+
from graphql_complexity import ArgumentsEstimator, get_complexity
|
|
464
|
+
from graphql import build_schema
|
|
304
465
|
|
|
305
466
|
schema = build_schema("""
|
|
306
467
|
type Product {
|
|
@@ -308,37 +469,14 @@ schema = build_schema("""
|
|
|
308
469
|
name: String!
|
|
309
470
|
price: Float!
|
|
310
471
|
}
|
|
311
|
-
|
|
472
|
+
|
|
312
473
|
type Query {
|
|
313
474
|
products(first: Int, offset: Int): [Product!]!
|
|
314
475
|
product(id: ID!): Product
|
|
315
476
|
}
|
|
316
477
|
""")
|
|
317
478
|
|
|
318
|
-
|
|
319
|
-
"""Custom estimator that considers pagination arguments"""
|
|
320
|
-
|
|
321
|
-
def get_field_complexity(self, node: FieldNode, type_info, path) -> int:
|
|
322
|
-
field_name = node.name.value
|
|
323
|
-
|
|
324
|
-
# Base complexity
|
|
325
|
-
base_complexity = 1
|
|
326
|
-
|
|
327
|
-
# Check for list/pagination arguments
|
|
328
|
-
if node.arguments:
|
|
329
|
-
for arg in node.arguments:
|
|
330
|
-
if arg.name.value == "first":
|
|
331
|
-
# Extract the limit value
|
|
332
|
-
if isinstance(arg.value, ast.IntValue):
|
|
333
|
-
limit = int(arg.value.value)
|
|
334
|
-
# Multiply complexity by the number of items requested
|
|
335
|
-
base_complexity *= min(limit, 100) # Cap at 100
|
|
336
|
-
|
|
337
|
-
# Apply higher base cost for lists
|
|
338
|
-
if field_name == "products":
|
|
339
|
-
base_complexity *= 5
|
|
340
|
-
|
|
341
|
-
return base_complexity
|
|
479
|
+
estimator = ArgumentsEstimator(multipliers=["first"], default_complexity=1)
|
|
342
480
|
|
|
343
481
|
query = """
|
|
344
482
|
query GetProducts {
|
|
@@ -350,14 +488,13 @@ query = """
|
|
|
350
488
|
}
|
|
351
489
|
"""
|
|
352
490
|
|
|
353
|
-
complexity = get_complexity(
|
|
354
|
-
query=query,
|
|
355
|
-
schema=schema,
|
|
356
|
-
estimator=ArgumentAwareEstimator()
|
|
357
|
-
)
|
|
491
|
+
complexity = get_complexity(query=query, schema=schema, estimator=estimator)
|
|
358
492
|
print(f"Query complexity with pagination: {complexity}")
|
|
493
|
+
# products(first: 50) → 50, id/name/price → 1 each → total: 53
|
|
359
494
|
```
|
|
360
495
|
|
|
496
|
+
For more fine-grained control (e.g. capping limits or applying field-specific multipliers), use a [Custom Estimator](#custom-estimator) instead.
|
|
497
|
+
|
|
361
498
|
### Combining Multiple Estimators
|
|
362
499
|
|
|
363
500
|
You can create sophisticated complexity analysis by combining estimators:
|
|
@@ -646,6 +783,87 @@ if __name__ == '__main__':
|
|
|
646
783
|
app.run(debug=True)
|
|
647
784
|
```
|
|
648
785
|
|
|
786
|
+
## 🍳 Recipes
|
|
787
|
+
|
|
788
|
+
### 1. Reject a query before execution
|
|
789
|
+
|
|
790
|
+
The most common pattern — block expensive queries before they hit your resolvers.
|
|
791
|
+
|
|
792
|
+
```python
|
|
793
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
794
|
+
|
|
795
|
+
MAX_COMPLEXITY = 10
|
|
796
|
+
|
|
797
|
+
def execute_query(schema, query):
|
|
798
|
+
complexity = get_complexity(
|
|
799
|
+
query=query,
|
|
800
|
+
schema=schema,
|
|
801
|
+
estimator=SimpleEstimator(complexity=1)
|
|
802
|
+
)
|
|
803
|
+
|
|
804
|
+
if complexity > MAX_COMPLEXITY:
|
|
805
|
+
raise Exception(f"Query too complex ({complexity}). Max allowed: {MAX_COMPLEXITY}")
|
|
806
|
+
|
|
807
|
+
return schema.execute(query)
|
|
808
|
+
```
|
|
809
|
+
|
|
810
|
+
-----
|
|
811
|
+
|
|
812
|
+
### 2. Set different limits per user role
|
|
813
|
+
|
|
814
|
+
Give trusted users more headroom without opening the door to abuse.
|
|
815
|
+
|
|
816
|
+
```python
|
|
817
|
+
COMPLEXITY_LIMITS = {
|
|
818
|
+
"anonymous": 5,
|
|
819
|
+
"authenticated": 15,
|
|
820
|
+
"admin": 50,
|
|
821
|
+
}
|
|
822
|
+
|
|
823
|
+
def execute_query(schema, query, user_role="anonymous"):
|
|
824
|
+
complexity = get_complexity(
|
|
825
|
+
query=query,
|
|
826
|
+
schema=schema,
|
|
827
|
+
estimator=SimpleEstimator(complexity=1)
|
|
828
|
+
)
|
|
829
|
+
|
|
830
|
+
limit = COMPLEXITY_LIMITS.get(user_role, 5)
|
|
831
|
+
|
|
832
|
+
if complexity > limit:
|
|
833
|
+
raise Exception(f"Query too complex ({complexity}). Max allowed for {user_role}: {limit}")
|
|
834
|
+
|
|
835
|
+
return schema.execute(query)
|
|
836
|
+
```
|
|
837
|
+
|
|
838
|
+
-----
|
|
839
|
+
|
|
840
|
+
### 3. Log complexity without blocking
|
|
841
|
+
|
|
842
|
+
Useful when rolling out complexity limits gradually — monitor first, enforce later.
|
|
843
|
+
|
|
844
|
+
```python
|
|
845
|
+
import logging
|
|
846
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
847
|
+
|
|
848
|
+
logger = logging.getLogger(__name__)
|
|
849
|
+
WARN_THRESHOLD = 10
|
|
850
|
+
|
|
851
|
+
def execute_query(schema, query):
|
|
852
|
+
complexity = get_complexity(
|
|
853
|
+
query=query,
|
|
854
|
+
schema=schema,
|
|
855
|
+
estimator=SimpleEstimator(complexity=1)
|
|
856
|
+
)
|
|
857
|
+
|
|
858
|
+
if complexity > WARN_THRESHOLD:
|
|
859
|
+
logger.warning(f"High complexity query detected: {complexity}")
|
|
860
|
+
|
|
861
|
+
# Always execute — no blocking yet
|
|
862
|
+
return schema.execute(query)
|
|
863
|
+
```
|
|
864
|
+
|
|
865
|
+
> **Tip:** Use this pattern in production for a week to understand your traffic’s complexity distribution before choosing your enforcement threshold.
|
|
866
|
+
|
|
649
867
|
## Real-World Use Cases
|
|
650
868
|
|
|
651
869
|
### E-commerce Platform
|