Debian Codegraph @

src/graphql/validation/validation_context.py

raw
1 from typing import Any, Callable, Dict, List, NamedTuple, Optional, Set, Union, cast
2
3 from ..error import GraphQLError
4 from ..language import (
5 DocumentNode,
6 FragmentDefinitionNode,
7 FragmentSpreadNode,
8 OperationDefinitionNode,
9 SelectionSetNode,
10 VariableNode,
11 Visitor,
12 VisitorAction,
13 visit,
14 )
15 from ..type import (
16 GraphQLArgument,
17 GraphQLCompositeType,
18 GraphQLDirective,
19 GraphQLEnumValue,
20 GraphQLField,
21 GraphQLInputType,
22 GraphQLOutputType,
23 GraphQLSchema,
24 )
25 from ..utilities import TypeInfo, TypeInfoVisitor
26
27 __all__ = [
28 "ASTValidationContext",
29 "SDLValidationContext",
30 "ValidationContext",
31 "VariableUsage",
32 "VariableUsageVisitor",
33 ]
34
35 NodeWithSelectionSet = Union[OperationDefinitionNode, FragmentDefinitionNode]
36
37
38 class VariableUsage(NamedTuple):
39 node: VariableNode
40 type: Optional[GraphQLInputType]
41 default_value: Any
42 parent_type: Optional[GraphQLInputType]
43
44
45 class VariableUsageVisitor(Visitor):
46 """Visitor adding all variable usages to a given list."""
47
48 usages: List[VariableUsage]
49
50 def __init__(self, type_info: TypeInfo):
51 super().__init__()
52 self.usages = []
53 self._append_usage = self.usages.append
54 self._type_info = type_info
55
56 def enter_variable_definition(self, *_args: Any) -> VisitorAction:
57 return self.SKIP
58
59 def enter_variable(self, node: VariableNode, *_args: Any) -> VisitorAction:
60 type_info = self._type_info
61 usage = VariableUsage(
62 node,
63 type_info.get_input_type(),
64 type_info.get_default_value(),
65 type_info.get_parent_input_type(),
66 )
67 self._append_usage(usage)
68 return None
69
70
71 class ASTValidationContext:
72 """Utility class providing a context for validation of an AST.
73
74 An instance of this class is passed as the context attribute to all Validators,
75 allowing access to commonly useful contextual information from within a validation
76 rule.
77 """
78
79 document: DocumentNode
80
81 _fragments: Optional[Dict[str, FragmentDefinitionNode]]
82 _fragment_spreads: Dict[SelectionSetNode, List[FragmentSpreadNode]]
83 _recursively_referenced_fragments: Dict[
84 OperationDefinitionNode, List[FragmentDefinitionNode]
85 ]
86
87 def __init__(
88 self, ast: DocumentNode, on_error: Callable[[GraphQLError], None]
89 ) -> None:
90 self.document = ast
91 self.on_error = on_error # type: ignore
92 self._fragments = None
93 self._fragment_spreads = {}
94 self._recursively_referenced_fragments = {}
95
96 def on_error(self, error: GraphQLError) -> None:
97 pass
98
99 def report_error(self, error: GraphQLError) -> None:
100 self.on_error(error)
101
102 def get_fragment(self, name: str) -> Optional[FragmentDefinitionNode]:
103 fragments = self._fragments
104 if fragments is None:
105 fragments = {
106 statement.name.value: statement
107 for statement in self.document.definitions
108 if isinstance(statement, FragmentDefinitionNode)
109 }
110
111 self._fragments = fragments
112 return fragments.get(name)
113
114 def get_fragment_spreads(self, node: SelectionSetNode) -> List[FragmentSpreadNode]:
115 spreads = self._fragment_spreads.get(node)
116 if spreads is None:
117 spreads = []
118 append_spread = spreads.append
119 sets_to_visit = [node]
120 append_set = sets_to_visit.append
121 pop_set = sets_to_visit.pop
122 while sets_to_visit:
123 visited_set = pop_set()
124 for selection in visited_set.selections:
125 if isinstance(selection, FragmentSpreadNode):
126 append_spread(selection)
127 else:
128 set_to_visit = cast(
129 NodeWithSelectionSet, selection
130 ).selection_set
131 if set_to_visit:
132 append_set(set_to_visit)
133 self._fragment_spreads[node] = spreads
134 return spreads
135
136 def get_recursively_referenced_fragments(
137 self, operation: OperationDefinitionNode
138 ) -> List[FragmentDefinitionNode]:
139 fragments = self._recursively_referenced_fragments.get(operation)
140 if fragments is None:
141 fragments = []
142 append_fragment = fragments.append
143 collected_names: Set[str] = set()
144 add_name = collected_names.add
145 nodes_to_visit = [operation.selection_set]
146 append_node = nodes_to_visit.append
147 pop_node = nodes_to_visit.pop
148 get_fragment = self.get_fragment
149 get_fragment_spreads = self.get_fragment_spreads
150 while nodes_to_visit:
151 visited_node = pop_node()
152 for spread in get_fragment_spreads(visited_node):
153 frag_name = spread.name.value
154 if frag_name not in collected_names:
155 add_name(frag_name)
156 fragment = get_fragment(frag_name)
157 if fragment:
158 append_fragment(fragment)
159 append_node(fragment.selection_set)
160 self._recursively_referenced_fragments[operation] = fragments
161 return fragments
162
163
164 class SDLValidationContext(ASTValidationContext):
165 """Utility class providing a context for validation of an SDL AST.
166
167 An instance of this class is passed as the context attribute to all Validators,
168 allowing access to commonly useful contextual information from within a validation
169 rule.
170 """
171
172 schema: Optional[GraphQLSchema]
173
174 def __init__(
175 self,
176 ast: DocumentNode,
177 schema: Optional[GraphQLSchema],
178 on_error: Callable[[GraphQLError], None],
179 ) -> None:
180 super().__init__(ast, on_error)
181 self.schema = schema
182
183
184 class ValidationContext(ASTValidationContext):
185 """Utility class providing a context for validation using a GraphQL schema.
186
187 An instance of this class is passed as the context attribute to all Validators,
188 allowing access to commonly useful contextual information from within a validation
189 rule.
190 """
191
192 schema: GraphQLSchema
193
194 _type_info: TypeInfo
195 _variable_usages: Dict[NodeWithSelectionSet, List[VariableUsage]]
196 _recursive_variable_usages: Dict[OperationDefinitionNode, List[VariableUsage]]
197
198 def __init__(
199 self,
200 schema: GraphQLSchema,
201 ast: DocumentNode,
202 type_info: TypeInfo,
203 on_error: Callable[[GraphQLError], None],
204 ) -> None:
205 super().__init__(ast, on_error)
206 self.schema = schema
207 self._type_info = type_info
208 self._variable_usages = {}
209 self._recursive_variable_usages = {}
210
211 def get_variable_usages(self, node: NodeWithSelectionSet) -> List[VariableUsage]:
212 usages = self._variable_usages.get(node)
213 if usages is None:
214 usage_visitor = VariableUsageVisitor(self._type_info)
215 visit(node, TypeInfoVisitor(self._type_info, usage_visitor))
216 usages = usage_visitor.usages
217 self._variable_usages[node] = usages
218 return usages
219
220 def get_recursive_variable_usages(
221 self, operation: OperationDefinitionNode
222 ) -> List[VariableUsage]:
223 usages = self._recursive_variable_usages.get(operation)
224 if usages is None:
225 get_variable_usages = self.get_variable_usages
226 usages = get_variable_usages(operation)
227 for fragment in self.get_recursively_referenced_fragments(operation):
228 usages.extend(get_variable_usages(fragment))
229 self._recursive_variable_usages[operation] = usages
230 return usages
231
232 def get_type(self) -> Optional[GraphQLOutputType]:
233 return self._type_info.get_type()
234
235 def get_parent_type(self) -> Optional[GraphQLCompositeType]:
236 return self._type_info.get_parent_type()
237
238 def get_input_type(self) -> Optional[GraphQLInputType]:
239 return self._type_info.get_input_type()
240
241 def get_parent_input_type(self) -> Optional[GraphQLInputType]:
242 return self._type_info.get_parent_input_type()
243
244 def get_field_def(self) -> Optional[GraphQLField]:
245 return self._type_info.get_field_def()
246
247 def get_directive(self) -> Optional[GraphQLDirective]:
248 return self._type_info.get_directive()
249
250 def get_argument(self) -> Optional[GraphQLArgument]:
251 return self._type_info.get_argument()
252
253 def get_enum_value(self) -> Optional[GraphQLEnumValue]:
254 return self._type_info.get_enum_value()