graphql-complexity 0.4.2__tar.gz → 1.1.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.1.0}/LICENSE +1 -1
- graphql_complexity-1.1.0/PKG-INFO +105 -0
- graphql_complexity-1.1.0/README.md +77 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/pyproject.toml +8 -7
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/__init__.py +8 -2
- graphql_complexity-1.1.0/src/graphql_complexity/estimators/__init__.py +11 -0
- graphql_complexity-1.1.0/src/graphql_complexity/estimators/arguments.py +44 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/estimators/directive.py +2 -2
- graphql_complexity-1.1.0/src/graphql_complexity/evaluator/complexity.py +42 -0
- graphql_complexity-1.1.0/src/graphql_complexity/evaluator/explain.py +307 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/evaluator/nodes.py +8 -7
- graphql_complexity-1.1.0/src/graphql_complexity/evaluator/utils.py +43 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/evaluator/visitor.py +7 -4
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/extensions/strawberry_graphql.py +8 -3
- graphql_complexity-0.4.2/PKG-INFO +0 -911
- graphql_complexity-0.4.2/README.md +0 -884
- 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.1.0}/src/graphql_complexity/config.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/estimators/base.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/estimators/simple.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/evaluator/__init__.py +0 -0
- {graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/extensions/__init__.py +0 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: graphql_complexity
|
|
3
|
+
Version: 1.1.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: Programming Language :: Python :: 3.15
|
|
21
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
22
|
+
Provides-Extra: strawberry-graphql
|
|
23
|
+
Requires-Dist: graphql-core (>=3.2.3,<4.0.0)
|
|
24
|
+
Requires-Dist: strawberry-graphql (>=0.291.3,<0.335.0) ; extra == "strawberry-graphql"
|
|
25
|
+
Project-URL: Repository, https://github.com/Checho3388/graphql-complexity
|
|
26
|
+
Description-Content-Type: text/markdown
|
|
27
|
+
|
|
28
|
+
[](https://github.com/Checho3388/graphql-complexity/raw/main/.github/logo.png)
|
|
29
|
+
|
|
30
|
+
# GraphQL Complexity
|
|
31
|
+
|
|
32
|
+
[](https://github.com/Checho3388/graphql-complexity/actions/workflows/python-build.yml)
|
|
33
|
+
[](https://pypi.org/project/graphql-complexity/)
|
|
34
|
+
[](https://codecov.io/gh/Checho3388/graphql-complexity)
|
|
35
|
+
[](https://pepy.tech/project/graphql-complexity)
|
|
36
|
+
[](https://pypi.org/project/graphql-complexity/)
|
|
37
|
+
[](https://opensource.org/licenses/MIT)
|
|
38
|
+
|
|
39
|
+
Python library to compute the complexity of a GraphQL operation. Protect your API from expensive queries and potential DoS attacks by calculating complexity before execution.
|
|
40
|
+
|
|
41
|
+
🎮 **Try it live:** [graphql-complexity playground](https://graphql-complexity-playground-production.up.railway.app/)
|
|
42
|
+
📖 **Full docs:** [graphql-complexity.readthedocs.io](https://graphql-complexity.readthedocs.io)
|
|
43
|
+
|
|
44
|
+
---
|
|
45
|
+
|
|
46
|
+
## Installation
|
|
47
|
+
|
|
48
|
+
```bash
|
|
49
|
+
pip install graphql-complexity
|
|
50
|
+
|
|
51
|
+
# With Strawberry GraphQL support
|
|
52
|
+
pip install graphql-complexity[strawberry-graphql]
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Quick Start
|
|
56
|
+
|
|
57
|
+
```python
|
|
58
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
59
|
+
from graphql import build_schema
|
|
60
|
+
|
|
61
|
+
schema = build_schema("""
|
|
62
|
+
type User {
|
|
63
|
+
id: ID!
|
|
64
|
+
name: String!
|
|
65
|
+
}
|
|
66
|
+
type Query {
|
|
67
|
+
user: User
|
|
68
|
+
}
|
|
69
|
+
""")
|
|
70
|
+
|
|
71
|
+
complexity = get_complexity(
|
|
72
|
+
query="query { user { id name } }",
|
|
73
|
+
schema=schema,
|
|
74
|
+
estimator=SimpleEstimator(complexity=1),
|
|
75
|
+
)
|
|
76
|
+
|
|
77
|
+
if complexity > 10:
|
|
78
|
+
raise Exception(f"Query is too complex: {complexity}")
|
|
79
|
+
```
|
|
80
|
+
|
|
81
|
+
## Estimators
|
|
82
|
+
|
|
83
|
+
| Estimator | Description |
|
|
84
|
+
|---|---|
|
|
85
|
+
| `SimpleEstimator` | Assigns a constant cost to every field |
|
|
86
|
+
| `DirectivesEstimator` | Reads cost from `@complexity(value: N)` schema directives |
|
|
87
|
+
| `ArgumentsEstimator` | Multiplies cost by a numeric/list argument (e.g. `limit`, `ids`) |
|
|
88
|
+
| Custom | Subclass `ComplexityEstimator` and implement `get_field_complexity` |
|
|
89
|
+
|
|
90
|
+
See the [estimators docs](https://graphql-complexity.readthedocs.io/en/latest/guides/estimators.html) for full reference and examples.
|
|
91
|
+
|
|
92
|
+
## Integrations
|
|
93
|
+
|
|
94
|
+
See the [integrations docs](https://graphql-complexity.readthedocs.io/en/latest/guides/integrations.html) for examples
|
|
95
|
+
about how this library integrates with `strawberry`, `FastAPI`, `Flask` and `graphene-django`.
|
|
96
|
+
|
|
97
|
+
|
|
98
|
+
## Credits
|
|
99
|
+
|
|
100
|
+
Estimators idea was heavily inspired by [graphql-query-complexity](https://github.com/slicknode/graphql-query-complexity).
|
|
101
|
+
|
|
102
|
+
## License
|
|
103
|
+
|
|
104
|
+
[MIT](LICENSE)
|
|
105
|
+
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
[](https://github.com/Checho3388/graphql-complexity/raw/main/.github/logo.png)
|
|
2
|
+
|
|
3
|
+
# GraphQL Complexity
|
|
4
|
+
|
|
5
|
+
[](https://github.com/Checho3388/graphql-complexity/actions/workflows/python-build.yml)
|
|
6
|
+
[](https://pypi.org/project/graphql-complexity/)
|
|
7
|
+
[](https://codecov.io/gh/Checho3388/graphql-complexity)
|
|
8
|
+
[](https://pepy.tech/project/graphql-complexity)
|
|
9
|
+
[](https://pypi.org/project/graphql-complexity/)
|
|
10
|
+
[](https://opensource.org/licenses/MIT)
|
|
11
|
+
|
|
12
|
+
Python library to compute the complexity of a GraphQL operation. Protect your API from expensive queries and potential DoS attacks by calculating complexity before execution.
|
|
13
|
+
|
|
14
|
+
🎮 **Try it live:** [graphql-complexity playground](https://graphql-complexity-playground-production.up.railway.app/)
|
|
15
|
+
📖 **Full docs:** [graphql-complexity.readthedocs.io](https://graphql-complexity.readthedocs.io)
|
|
16
|
+
|
|
17
|
+
---
|
|
18
|
+
|
|
19
|
+
## Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
22
|
+
pip install graphql-complexity
|
|
23
|
+
|
|
24
|
+
# With Strawberry GraphQL support
|
|
25
|
+
pip install graphql-complexity[strawberry-graphql]
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
## Quick Start
|
|
29
|
+
|
|
30
|
+
```python
|
|
31
|
+
from graphql_complexity import get_complexity, SimpleEstimator
|
|
32
|
+
from graphql import build_schema
|
|
33
|
+
|
|
34
|
+
schema = build_schema("""
|
|
35
|
+
type User {
|
|
36
|
+
id: ID!
|
|
37
|
+
name: String!
|
|
38
|
+
}
|
|
39
|
+
type Query {
|
|
40
|
+
user: User
|
|
41
|
+
}
|
|
42
|
+
""")
|
|
43
|
+
|
|
44
|
+
complexity = get_complexity(
|
|
45
|
+
query="query { user { id name } }",
|
|
46
|
+
schema=schema,
|
|
47
|
+
estimator=SimpleEstimator(complexity=1),
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
if complexity > 10:
|
|
51
|
+
raise Exception(f"Query is too complex: {complexity}")
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
## Estimators
|
|
55
|
+
|
|
56
|
+
| Estimator | Description |
|
|
57
|
+
|---|---|
|
|
58
|
+
| `SimpleEstimator` | Assigns a constant cost to every field |
|
|
59
|
+
| `DirectivesEstimator` | Reads cost from `@complexity(value: N)` schema directives |
|
|
60
|
+
| `ArgumentsEstimator` | Multiplies cost by a numeric/list argument (e.g. `limit`, `ids`) |
|
|
61
|
+
| Custom | Subclass `ComplexityEstimator` and implement `get_field_complexity` |
|
|
62
|
+
|
|
63
|
+
See the [estimators docs](https://graphql-complexity.readthedocs.io/en/latest/guides/estimators.html) for full reference and examples.
|
|
64
|
+
|
|
65
|
+
## Integrations
|
|
66
|
+
|
|
67
|
+
See the [integrations docs](https://graphql-complexity.readthedocs.io/en/latest/guides/integrations.html) for examples
|
|
68
|
+
about how this library integrates with `strawberry`, `FastAPI`, `Flask` and `graphene-django`.
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
## Credits
|
|
72
|
+
|
|
73
|
+
Estimators idea was heavily inspired by [graphql-query-complexity](https://github.com/slicknode/graphql-query-complexity).
|
|
74
|
+
|
|
75
|
+
## License
|
|
76
|
+
|
|
77
|
+
[MIT](LICENSE)
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[tool.poetry]
|
|
2
2
|
name = "graphql_complexity"
|
|
3
|
-
version = "
|
|
3
|
+
version = "1.1.0"
|
|
4
4
|
description = "A python library that provides complexity calculation helpers for GraphQL"
|
|
5
5
|
authors = ["Checho3388 <ezequiel.grondona@gmail.com>"]
|
|
6
6
|
packages = [
|
|
@@ -10,7 +10,7 @@ repository = "https://github.com/Checho3388/graphql-complexity"
|
|
|
10
10
|
license = "MIT"
|
|
11
11
|
readme = "README.md"
|
|
12
12
|
classifiers = [
|
|
13
|
-
"Development Status ::
|
|
13
|
+
"Development Status :: 5 - Production/Stable",
|
|
14
14
|
"Intended Audience :: Developers",
|
|
15
15
|
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
16
16
|
"License :: OSI Approved :: MIT License",
|
|
@@ -25,17 +25,18 @@ keywords = ["graphql", "complexity", "query", "mutation", "subscription"]
|
|
|
25
25
|
[tool.poetry.dependencies]
|
|
26
26
|
python = "^3.10"
|
|
27
27
|
graphql-core = "^3.2.3"
|
|
28
|
-
strawberry-graphql = "
|
|
28
|
+
strawberry-graphql = ">=0.291.3,<0.335.0"
|
|
29
29
|
|
|
30
30
|
[tool.poetry.extras]
|
|
31
31
|
strawberry-graphql = ["strawberry-graphql"]
|
|
32
32
|
|
|
33
33
|
[tool.poetry.group.dev.dependencies]
|
|
34
|
-
pytest = "
|
|
35
|
-
mypy = "
|
|
36
|
-
black = "
|
|
37
|
-
pytest-cov = "
|
|
34
|
+
pytest = ">=8.1,<10"
|
|
35
|
+
mypy = ">=1.8,<3.0"
|
|
36
|
+
black = ">=24.2,<27.0"
|
|
37
|
+
pytest-cov = ">=4.1,<8.0"
|
|
38
38
|
flake8 = "^7.0.0"
|
|
39
|
+
pytest-benchmark = ">=4,<6"
|
|
39
40
|
|
|
40
41
|
[build-system]
|
|
41
42
|
requires = ["poetry-core"]
|
|
@@ -1,14 +1,20 @@
|
|
|
1
1
|
from graphql_complexity.evaluator.complexity import get_complexity
|
|
2
|
+
from graphql_complexity.evaluator.explain import explain_complexity, ExplanationResult, FieldExplanation
|
|
2
3
|
|
|
3
4
|
from .estimators import (
|
|
5
|
+
ArgumentsEstimator,
|
|
4
6
|
ComplexityEstimator,
|
|
5
7
|
DirectivesEstimator,
|
|
6
|
-
SimpleEstimator
|
|
8
|
+
SimpleEstimator,
|
|
7
9
|
)
|
|
8
10
|
|
|
9
11
|
__all__ = [
|
|
10
12
|
"get_complexity",
|
|
11
|
-
"
|
|
13
|
+
"explain_complexity",
|
|
14
|
+
"ExplanationResult",
|
|
15
|
+
"FieldExplanation",
|
|
16
|
+
"ArgumentsEstimator",
|
|
12
17
|
"ComplexityEstimator",
|
|
13
18
|
"DirectivesEstimator",
|
|
19
|
+
"SimpleEstimator",
|
|
14
20
|
]
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from .base import ComplexityEstimator
|
|
2
|
+
from .arguments import ArgumentsEstimator
|
|
3
|
+
from .directive import DirectivesEstimator
|
|
4
|
+
from .simple import SimpleEstimator
|
|
5
|
+
|
|
6
|
+
__all__ = [
|
|
7
|
+
"ArgumentsEstimator",
|
|
8
|
+
"ComplexityEstimator",
|
|
9
|
+
"DirectivesEstimator",
|
|
10
|
+
"SimpleEstimator",
|
|
11
|
+
]
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
from graphql import IntValueNode, ListValueNode
|
|
2
|
+
from graphql_complexity.estimators.base import ComplexityEstimator
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
class ArgumentsEstimator(ComplexityEstimator):
|
|
6
|
+
"""
|
|
7
|
+
Estimates complexity by multiplying a base value by
|
|
8
|
+
numeric argument values (e.g. first, limit, ids).
|
|
9
|
+
|
|
10
|
+
Usage:
|
|
11
|
+
estimator = ArgumentsEstimator(
|
|
12
|
+
multipliers=["limit", "first", "ids"],
|
|
13
|
+
default_complexity=1,
|
|
14
|
+
)
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
def __init__(
|
|
18
|
+
self,
|
|
19
|
+
multipliers: list[str],
|
|
20
|
+
default_complexity: int = 1,
|
|
21
|
+
):
|
|
22
|
+
self.multipliers = multipliers
|
|
23
|
+
self.default_complexity = default_complexity
|
|
24
|
+
|
|
25
|
+
def get_field_complexity(self, node, type_info, path) -> int:
|
|
26
|
+
multiplier = self._get_multiplier(node)
|
|
27
|
+
return self.default_complexity * multiplier
|
|
28
|
+
|
|
29
|
+
def _get_multiplier(self, node) -> int:
|
|
30
|
+
for arg in node.arguments or []:
|
|
31
|
+
if arg.name.value in self.multipliers:
|
|
32
|
+
value = self._extract_value(arg.value)
|
|
33
|
+
if value is not None:
|
|
34
|
+
return value
|
|
35
|
+
return 1
|
|
36
|
+
|
|
37
|
+
def _extract_value(self, value_node) -> int | None:
|
|
38
|
+
# limit: 10 → 10
|
|
39
|
+
if isinstance(value_node, IntValueNode):
|
|
40
|
+
return int(value_node.value)
|
|
41
|
+
# ids: ["a", "b", "c"] → 3 (length of list)
|
|
42
|
+
if isinstance(value_node, ListValueNode):
|
|
43
|
+
return len(value_node.values)
|
|
44
|
+
return None
|
{graphql_complexity-0.4.2 → graphql_complexity-1.1.0}/src/graphql_complexity/estimators/directive.py
RENAMED
|
@@ -16,11 +16,11 @@ class DirectivesVisitor(Visitor):
|
|
|
16
16
|
super().__init__()
|
|
17
17
|
|
|
18
18
|
def enter_field_definition(self, node, key, parent, path, ancestors):
|
|
19
|
-
for directive in node.directives:
|
|
19
|
+
for directive in node.directives or ():
|
|
20
20
|
if directive.name.value == self.directive_name:
|
|
21
21
|
complexity = next(
|
|
22
22
|
arg.value.value
|
|
23
|
-
for arg in directive.arguments
|
|
23
|
+
for arg in directive.arguments or ()
|
|
24
24
|
if arg.name.value == DIRECTIVE_ESTIMATOR_FIELD_COMPLEXITY_NAME
|
|
25
25
|
)
|
|
26
26
|
self._collector[node.name.value] = int(complexity)
|
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from functools import lru_cache
|
|
4
|
+
from typing import TYPE_CHECKING
|
|
5
|
+
|
|
6
|
+
from graphql import DocumentNode, TypeInfo, TypeInfoVisitor, parse, visit
|
|
7
|
+
|
|
8
|
+
from .visitor import ComplexityVisitor
|
|
9
|
+
|
|
10
|
+
if TYPE_CHECKING:
|
|
11
|
+
from graphql import GraphQLSchema
|
|
12
|
+
from . import nodes
|
|
13
|
+
from ..config import Config
|
|
14
|
+
from ..estimators import ComplexityEstimator
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
@lru_cache(maxsize=256)
|
|
18
|
+
def _parse_cached(query: str) -> DocumentNode:
|
|
19
|
+
return parse(query)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def get_complexity(query: str | DocumentNode, schema: GraphQLSchema, estimator: ComplexityEstimator, config: Config = None) -> int:
|
|
23
|
+
"""Calculate the complexity of a query using the provided estimator."""
|
|
24
|
+
tree = build_complexity_tree(query, schema, estimator, config)
|
|
25
|
+
|
|
26
|
+
return tree.evaluate()
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def build_complexity_tree(
|
|
30
|
+
query: str | DocumentNode,
|
|
31
|
+
schema: GraphQLSchema,
|
|
32
|
+
estimator: ComplexityEstimator,
|
|
33
|
+
config: Config | None = None,
|
|
34
|
+
) -> nodes.ComplexityNode:
|
|
35
|
+
"""Calculate the complexity of a query using the provided estimator."""
|
|
36
|
+
ast = query if isinstance(query, DocumentNode) else _parse_cached(query)
|
|
37
|
+
type_info = TypeInfo(schema)
|
|
38
|
+
|
|
39
|
+
visitor = ComplexityVisitor(estimator=estimator, type_info=type_info, config=config)
|
|
40
|
+
visit(ast, TypeInfoVisitor(type_info, visitor))
|
|
41
|
+
|
|
42
|
+
return visitor.complexity_tree
|
|
@@ -0,0 +1,307 @@
|
|
|
1
|
+
"""Explain module for GraphQL complexity calculations.
|
|
2
|
+
|
|
3
|
+
This module provides functionality to explain how complexity calculations are performed,
|
|
4
|
+
including which estimator was used and a detailed breakdown of the calculation.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
import dataclasses
|
|
9
|
+
from typing import TYPE_CHECKING, Any
|
|
10
|
+
|
|
11
|
+
from graphql import TypeInfo, TypeInfoVisitor, parse, visit
|
|
12
|
+
|
|
13
|
+
from . import nodes
|
|
14
|
+
from .visitor import ComplexityVisitor
|
|
15
|
+
from ..estimators.simple import SimpleEstimator
|
|
16
|
+
from ..estimators.directive import DirectivesEstimator
|
|
17
|
+
|
|
18
|
+
if TYPE_CHECKING:
|
|
19
|
+
from graphql import GraphQLSchema
|
|
20
|
+
from ..config import Config
|
|
21
|
+
from ..estimators import ComplexityEstimator
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclasses.dataclass
|
|
25
|
+
class FieldExplanation:
|
|
26
|
+
"""Explanation for a single field's complexity."""
|
|
27
|
+
field_path: str
|
|
28
|
+
field_name: str
|
|
29
|
+
node_type: str
|
|
30
|
+
field_complexity: int
|
|
31
|
+
children_complexity: int
|
|
32
|
+
total_complexity: int
|
|
33
|
+
multiplier: int | None = None # For list fields
|
|
34
|
+
details: dict[str, Any] = dataclasses.field(default_factory=dict)
|
|
35
|
+
|
|
36
|
+
def __str__(self) -> str:
|
|
37
|
+
result = f"{self.field_path} ({self.node_type})"
|
|
38
|
+
if self.multiplier:
|
|
39
|
+
result += f" [multiplier: {self.multiplier}]"
|
|
40
|
+
result += f"\n Field complexity: {self.field_complexity}"
|
|
41
|
+
if self.children_complexity:
|
|
42
|
+
result += f"\n Children complexity: {self.children_complexity}"
|
|
43
|
+
if self.multiplier:
|
|
44
|
+
result += f" × {self.multiplier} = {self.children_complexity * self.multiplier}"
|
|
45
|
+
result += f"\n Total: {self.total_complexity}"
|
|
46
|
+
return result
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
@dataclasses.dataclass
|
|
50
|
+
class ExplanationResult:
|
|
51
|
+
"""Complete explanation of a complexity calculation."""
|
|
52
|
+
total_complexity: int
|
|
53
|
+
estimator_name: str
|
|
54
|
+
estimator_details: dict[str, Any]
|
|
55
|
+
tree_representation: str
|
|
56
|
+
field_breakdown: list[FieldExplanation]
|
|
57
|
+
query: str
|
|
58
|
+
|
|
59
|
+
def __str__(self) -> str:
|
|
60
|
+
"""Return a human-readable explanation."""
|
|
61
|
+
lines = [
|
|
62
|
+
"=" * 80,
|
|
63
|
+
"GraphQL Complexity Explanation",
|
|
64
|
+
"=" * 80,
|
|
65
|
+
"",
|
|
66
|
+
f"Total Complexity: {self.total_complexity}",
|
|
67
|
+
"",
|
|
68
|
+
"Estimator Used:",
|
|
69
|
+
f" Name: {self.estimator_name}",
|
|
70
|
+
]
|
|
71
|
+
|
|
72
|
+
if self.estimator_details:
|
|
73
|
+
lines.append(" Details:")
|
|
74
|
+
for key, value in self.estimator_details.items():
|
|
75
|
+
lines.append(f" {key}: {value}")
|
|
76
|
+
|
|
77
|
+
lines.extend([
|
|
78
|
+
"",
|
|
79
|
+
"Complexity Tree:",
|
|
80
|
+
"-" * 80,
|
|
81
|
+
self.tree_representation,
|
|
82
|
+
"",
|
|
83
|
+
"Field-by-Field Breakdown:",
|
|
84
|
+
"-" * 80,
|
|
85
|
+
])
|
|
86
|
+
|
|
87
|
+
for field_exp in self.field_breakdown:
|
|
88
|
+
lines.append(str(field_exp))
|
|
89
|
+
lines.append("")
|
|
90
|
+
|
|
91
|
+
lines.append("=" * 80)
|
|
92
|
+
return "\n".join(lines)
|
|
93
|
+
|
|
94
|
+
def to_dict(self) -> dict[str, Any]:
|
|
95
|
+
"""Convert to a dictionary representation."""
|
|
96
|
+
return {
|
|
97
|
+
"total_complexity": self.total_complexity,
|
|
98
|
+
"estimator": {
|
|
99
|
+
"name": self.estimator_name,
|
|
100
|
+
"details": self.estimator_details,
|
|
101
|
+
},
|
|
102
|
+
"tree": self.tree_representation,
|
|
103
|
+
"breakdown": [
|
|
104
|
+
{
|
|
105
|
+
"path": field.field_path,
|
|
106
|
+
"name": field.field_name,
|
|
107
|
+
"type": field.node_type,
|
|
108
|
+
"field_complexity": field.field_complexity,
|
|
109
|
+
"children_complexity": field.children_complexity,
|
|
110
|
+
"total_complexity": field.total_complexity,
|
|
111
|
+
"multiplier": field.multiplier,
|
|
112
|
+
"details": field.details,
|
|
113
|
+
}
|
|
114
|
+
for field in self.field_breakdown
|
|
115
|
+
],
|
|
116
|
+
"query": self.query,
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def _extract_estimator_details(estimator: ComplexityEstimator) -> dict[str, Any]:
|
|
121
|
+
"""Extract details about the estimator being used."""
|
|
122
|
+
details = {}
|
|
123
|
+
|
|
124
|
+
if isinstance(estimator, SimpleEstimator):
|
|
125
|
+
# Access the private complexity constant through name mangling
|
|
126
|
+
details["complexity_constant"] = estimator._SimpleEstimator__complexity_constant
|
|
127
|
+
elif isinstance(estimator, DirectivesEstimator):
|
|
128
|
+
details["directive_name"] = estimator._DirectivesEstimator__directive_name
|
|
129
|
+
details["missing_complexity"] = estimator._DirectivesEstimator__missing_complexity
|
|
130
|
+
details["complexity_map"] = estimator._DirectivesEstimator__complexity_map
|
|
131
|
+
else:
|
|
132
|
+
details["type"] = type(estimator).__name__
|
|
133
|
+
|
|
134
|
+
return details
|
|
135
|
+
|
|
136
|
+
|
|
137
|
+
def _extract_field_breakdown(
|
|
138
|
+
node: nodes.ComplexityNode,
|
|
139
|
+
path: str = "",
|
|
140
|
+
breakdown: list[FieldExplanation] | None = None
|
|
141
|
+
) -> list[FieldExplanation]:
|
|
142
|
+
"""Extract field-by-field breakdown from the complexity tree."""
|
|
143
|
+
if breakdown is None:
|
|
144
|
+
breakdown = []
|
|
145
|
+
|
|
146
|
+
# Skip root node in the path
|
|
147
|
+
if isinstance(node, nodes.RootNode) and not path:
|
|
148
|
+
current_path = ""
|
|
149
|
+
else:
|
|
150
|
+
current_path = f"{path}.{node.name}" if path else node.name
|
|
151
|
+
|
|
152
|
+
# Calculate complexities
|
|
153
|
+
if isinstance(node, (nodes.Field, nodes.ListField)):
|
|
154
|
+
children_complexity = sum(child.evaluate() for child in node.children)
|
|
155
|
+
|
|
156
|
+
if isinstance(node, nodes.ListField):
|
|
157
|
+
multiplier = node.count
|
|
158
|
+
total_complexity = node.complexity + multiplier * children_complexity
|
|
159
|
+
field_explanation = FieldExplanation(
|
|
160
|
+
field_path=current_path,
|
|
161
|
+
field_name=node.name,
|
|
162
|
+
node_type="ListField",
|
|
163
|
+
field_complexity=node.complexity,
|
|
164
|
+
children_complexity=children_complexity,
|
|
165
|
+
total_complexity=total_complexity,
|
|
166
|
+
multiplier=multiplier,
|
|
167
|
+
)
|
|
168
|
+
else:
|
|
169
|
+
total_complexity = node.complexity + children_complexity
|
|
170
|
+
field_explanation = FieldExplanation(
|
|
171
|
+
field_path=current_path,
|
|
172
|
+
field_name=node.name,
|
|
173
|
+
node_type="Field",
|
|
174
|
+
field_complexity=node.complexity,
|
|
175
|
+
children_complexity=children_complexity,
|
|
176
|
+
total_complexity=total_complexity,
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
breakdown.append(field_explanation)
|
|
180
|
+
elif isinstance(node, nodes.FragmentSpreadNode):
|
|
181
|
+
field_explanation = FieldExplanation(
|
|
182
|
+
field_path=current_path,
|
|
183
|
+
field_name=node.name,
|
|
184
|
+
node_type="FragmentSpread",
|
|
185
|
+
field_complexity=0,
|
|
186
|
+
children_complexity=node.evaluate(),
|
|
187
|
+
total_complexity=node.evaluate(),
|
|
188
|
+
details={"fragment_name": node.name},
|
|
189
|
+
)
|
|
190
|
+
breakdown.append(field_explanation)
|
|
191
|
+
elif isinstance(node, nodes.SkippedField):
|
|
192
|
+
field_explanation = FieldExplanation(
|
|
193
|
+
field_path=current_path,
|
|
194
|
+
field_name=node.name,
|
|
195
|
+
node_type="SkippedField",
|
|
196
|
+
field_complexity=0,
|
|
197
|
+
children_complexity=0,
|
|
198
|
+
total_complexity=0,
|
|
199
|
+
details={"reason": "Field was skipped due to @skip or @include directive"},
|
|
200
|
+
)
|
|
201
|
+
breakdown.append(field_explanation)
|
|
202
|
+
elif isinstance(node, nodes.MetaField):
|
|
203
|
+
field_explanation = FieldExplanation(
|
|
204
|
+
field_path=current_path,
|
|
205
|
+
field_name=node.name,
|
|
206
|
+
node_type="MetaField",
|
|
207
|
+
field_complexity=0,
|
|
208
|
+
children_complexity=0,
|
|
209
|
+
total_complexity=0,
|
|
210
|
+
details={"reason": "Meta fields like __typename have zero complexity"},
|
|
211
|
+
)
|
|
212
|
+
breakdown.append(field_explanation)
|
|
213
|
+
|
|
214
|
+
# Recursively process children
|
|
215
|
+
for child in node.children:
|
|
216
|
+
_extract_field_breakdown(child, current_path, breakdown)
|
|
217
|
+
|
|
218
|
+
return breakdown
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def explain_complexity(
|
|
222
|
+
query: str,
|
|
223
|
+
schema: GraphQLSchema,
|
|
224
|
+
estimator: ComplexityEstimator,
|
|
225
|
+
config: Config = None
|
|
226
|
+
) -> ExplanationResult:
|
|
227
|
+
"""
|
|
228
|
+
Explain how the complexity of a GraphQL query is calculated.
|
|
229
|
+
|
|
230
|
+
This function provides detailed information about:
|
|
231
|
+
- Which estimator was used and its configuration
|
|
232
|
+
- The complexity tree structure
|
|
233
|
+
- Field-by-field breakdown showing how each field contributes to total complexity
|
|
234
|
+
- The final total complexity
|
|
235
|
+
|
|
236
|
+
Args:
|
|
237
|
+
query: The GraphQL query string to analyze
|
|
238
|
+
schema: The GraphQL schema
|
|
239
|
+
estimator: The complexity estimator to use
|
|
240
|
+
config: Optional configuration for complexity calculation
|
|
241
|
+
|
|
242
|
+
Returns:
|
|
243
|
+
ExplanationResult containing detailed explanation of the complexity calculation
|
|
244
|
+
|
|
245
|
+
Example:
|
|
246
|
+
>>> from graphql import build_schema
|
|
247
|
+
>>> from graphql_complexity import SimpleEstimator
|
|
248
|
+
>>> from graphql_complexity.evaluator.explain import explain_complexity
|
|
249
|
+
>>>
|
|
250
|
+
>>> schema = build_schema('''
|
|
251
|
+
... type Query {
|
|
252
|
+
... user: User
|
|
253
|
+
... }
|
|
254
|
+
... type User {
|
|
255
|
+
... id: ID!
|
|
256
|
+
... name: String!
|
|
257
|
+
... }
|
|
258
|
+
... ''')
|
|
259
|
+
>>>
|
|
260
|
+
>>> query = '''
|
|
261
|
+
... query {
|
|
262
|
+
... user {
|
|
263
|
+
... id
|
|
264
|
+
... name
|
|
265
|
+
... }
|
|
266
|
+
... }
|
|
267
|
+
... '''
|
|
268
|
+
>>>
|
|
269
|
+
>>> explanation = explain_complexity(
|
|
270
|
+
... query=query,
|
|
271
|
+
... schema=schema,
|
|
272
|
+
... estimator=SimpleEstimator(complexity=10)
|
|
273
|
+
... )
|
|
274
|
+
>>>
|
|
275
|
+
>>> print(explanation)
|
|
276
|
+
>>> # or access specific parts:
|
|
277
|
+
>>> print(f"Total: {explanation.total_complexity}")
|
|
278
|
+
>>> print(f"Estimator: {explanation.estimator_name}")
|
|
279
|
+
"""
|
|
280
|
+
# Build the complexity tree
|
|
281
|
+
ast = parse(query)
|
|
282
|
+
type_info = TypeInfo(schema)
|
|
283
|
+
visitor = ComplexityVisitor(estimator=estimator, type_info=type_info, config=config)
|
|
284
|
+
visit(ast, TypeInfoVisitor(type_info, visitor))
|
|
285
|
+
tree = visitor.complexity_tree
|
|
286
|
+
|
|
287
|
+
# Extract estimator information
|
|
288
|
+
estimator_name = type(estimator).__name__
|
|
289
|
+
estimator_details = _extract_estimator_details(estimator)
|
|
290
|
+
|
|
291
|
+
# Get tree representation
|
|
292
|
+
tree_representation = tree.describe()
|
|
293
|
+
|
|
294
|
+
# Get field breakdown
|
|
295
|
+
field_breakdown = _extract_field_breakdown(tree)
|
|
296
|
+
|
|
297
|
+
# Calculate total complexity
|
|
298
|
+
total_complexity = tree.evaluate()
|
|
299
|
+
|
|
300
|
+
return ExplanationResult(
|
|
301
|
+
total_complexity=total_complexity,
|
|
302
|
+
estimator_name=estimator_name,
|
|
303
|
+
estimator_details=estimator_details,
|
|
304
|
+
tree_representation=tree_representation,
|
|
305
|
+
field_breakdown=field_breakdown,
|
|
306
|
+
query=query,
|
|
307
|
+
)
|