Debian Codegraph @

cylc/flow/network/graphql.py

raw
1 # THIS FILE IS PART OF THE CYLC WORKFLOW ENGINE.
2 # Copyright (C) NIWA & British Crown (Met Office) & Contributors.
3 #
4 # This program is free software: you can redistribute it and/or modify
5 # it under the terms of the GNU General Public License as published by
6 # the Free Software Foundation, either version 3 of the License, or
7 # (at your option) any later version.
8 #
9 # This program is distributed in the hope that it will be useful,
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 # GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License
15 # along with this program. If not, see <http://www.gnu.org/licenses/>.
16 """
17
18 GraphQL Middleware defined here also.
19
20 """
21
22 from inspect import isclass
23 import logging
24 from typing import (
25 Any, Awaitable, Callable, TypeVar, Tuple, Dict, Union, cast
26 )
27
28 from graphene.utils.str_converters import to_snake_case
29 from graphql import (
30 ExecutionContext,
31 TypeInfo,
32 TypeInfoVisitor,
33 Visitor,
34 visit,
35 get_named_type,
36 is_introspection_type,
37 value_from_ast_untyped
38 )
39 from graphql.pyutils import AwaitableOrValue, is_awaitable
40
41 from cylc.flow.network.schema import NODE_MAP
42
43
44 logger = logging.getLogger(__name__)
45
46 STRIP_ARG = 'strip_null'
47 NULL_VALUE = None
48 EMPTY_VALUES: Tuple[list, dict] = ([], {})
49 STRIP_OPS = {'query', 'subscription'}
50
51 U = TypeVar("U")
52
53
54 def grow_tree(tree, path, leaves=None):
55 """Additively grows tree with leaves at terminal of new branch.
56
57 Given existing dictionary, it follows the new path from root through
58 existing trunk and without clobbering existing leaves when encountered.
59
60 Args:
61 tree (dict): Existing or new dictionary/tree.
62 path (list): List of keys from root to branch end.
63 leaves (dict, optional):
64 Dictionary of information to put at path end.
65
66 Returns:
67 None
68 """
69 tree_loc = [tree, {}]
70 for loc, key in enumerate(path):
71 if key in tree_loc[loc % 2]: # noqa: SIM401
72 tree_loc[(loc + 1) % 2] = tree_loc[loc % 2][key]
73 else:
74 tree_loc[loc % 2][key] = tree_loc[(loc + 1) % 2]
75 tree_loc[loc % 2] = {}
76 if leaves:
77 tree_loc[len(path) % 2].update({'leaves': leaves})
78
79
80 def instantiate_middleware(middlewares):
81 """Take iterable of middlewares and instantiate.
82
83 Middleware instantiated here will not be shared amongst
84 subscriptions/queries.
85
86 """
87 for middleware in middlewares:
88 if isclass(middleware):
89 yield middleware()
90 continue
91 yield middleware
92
93
94 async def async_callback(
95 callback: Callable[[U], AwaitableOrValue[U]],
96 result: AwaitableOrValue[U],
97 ) -> U:
98 """Await result and apply callback."""
99 result = callback(await cast('Awaitable[Any]', result))
100 return await result if is_awaitable(result) else result # type: ignore
101
102
103 def async_next(
104 callback: Callable[[U], AwaitableOrValue[U]],
105 result: AwaitableOrValue[U],
106 ) -> AwaitableOrValue[U]:
107 """Reduce the given potentially awaitable values using a callback function.
108
109 If the callback does not return an awaitable, then this function will also
110 not return an awaitable.
111 """
112 if is_awaitable(result):
113 return async_callback(callback, result)
114 else:
115 return callback(cast('U', result))
116
117
118 def null_setter(result):
119 """Set type to null if result is empty/null-like."""
120 # Only set empty parents to null.
121 try:
122 if result in EMPTY_VALUES:
123 return NULL_VALUE
124 except TypeError:
125 # If field is a repeated composite field convert to list.
126 if not result:
127 return NULL_VALUE
128 return result
129
130
131 # Is possible to not use middleware and do all the filtering here.
132 # However, middleware allows for argument of the request doc to set.
133 def strip_null(data):
134 """Recursively strip data structure of nulls."""
135 if isinstance(data, dict):
136 return {
137 key: strip_null(val)
138 for key, val in data.items()
139 if val is not NULL_VALUE
140 }
141 if isinstance(data, list):
142 return [
143 strip_null(val)
144 for val in data
145 if val is not NULL_VALUE
146 ]
147 return data
148
149
150 class CylcVisitor(Visitor):
151 """Traverse graphql document/query to find an argument in a given state.
152
153 Find whether an argument is set to a specific value anywhere in the
154 document (i.e. 'strip_null' set to 'True'), and stop on the first
155 occurrence.
156 """
157 def __init__(self, type_info, variable_values, doc_arg) -> None:
158 super().__init__()
159 self.type_info = type_info
160 self.variable_values = variable_values
161 self.doc_arg = doc_arg
162 self.arg_flag = False
163
164 def enter(self, node, key, parent, path, ancestors):
165 if (
166 node.kind == 'argument'
167 and node.name.value in self.doc_arg
168 and self.doc_arg[node.name.value] == value_from_ast_untyped(
169 node.value,
170 self.variable_values
171 )
172 ):
173 self.arg_flag = True
174 return self.BREAK
175 return self.IDLE
176
177 def leave(self, node, key, parent, path, ancestors):
178 return self.IDLE
179
180
181 class CylcExecutionContext(ExecutionContext):
182
183 def execute_operation(
184 self, operation, root_value
185 ) -> AwaitableOrValue[Union[Dict[str, Any], Any, None]]:
186 """Execute the GraphQL document, and apply requested stipping.
187
188 Search request document to determine if 'stripNull: true' is set
189 as and argument. It can not be done in the middleware, as they
190 can have awaitables and is prior to validation.
191 """
192 result = super().execute_operation(operation, root_value)
193
194 # Traverse the document stop if found
195 type_info = TypeInfo(self.schema)
196 cylc_visitor = CylcVisitor(
197 type_info,
198 self.variable_values,
199 {
200 'stripNull': True
201 }
202 )
203 visit(
204 self.operation,
205 TypeInfoVisitor(
206 type_info,
207 cylc_visitor
208 ),
209 None
210 )
211 if cylc_visitor.arg_flag:
212 return async_next(strip_null, result) # type: ignore
213 return result
214
215
216 # -- Middleware --
217
218 class IgnoreFieldMiddleware:
219 """Set to null/None type undesired field values for stripping."""
220
221 def __init__(self):
222 self.args_tree = {}
223 self.tree_paths = set()
224 self.field_sets = {}
225
226 def resolve(self, next_, root, info, **args):
227 """Middleware resolver; handles field according to operation."""
228 # GraphiQL introspection is 'query' but not async
229 if is_introspection_type(get_named_type(info.return_type)):
230 return next_(root, info, **args)
231
232 if info.operation.operation.value in STRIP_OPS:
233 path_list = info.path.as_list()
234 path_string = f'{path_list}'
235 parent_path_string = f'{path_list[:-1:]}'
236 # Needed for child fields that resolve without args.
237 # Store arguments of parents as leaves of schema tree from path
238 # to respective field.
239 # no need to regrow the tree on every subscription push/delta
240 if args and path_string not in self.tree_paths:
241 grow_tree(self.args_tree, path_list, args)
242 self.tree_paths.add(path_string)
243 if STRIP_ARG not in args:
244 branch = self.args_tree
245 for section in path_list:
246 if section not in branch:
247 break
248 branch = branch[section]
249 # Only set if present on branch section
250 if 'leaves' in branch and STRIP_ARG in branch['leaves']:
251 args[STRIP_ARG] = branch['leaves'][STRIP_ARG]
252
253 # Now flag empty fields as null for stripping
254 if args.get(STRIP_ARG, False):
255 field_name = to_snake_case(info.field_name)
256
257 # Clear field set so recreated via first child field,
258 # as path may be a parent.
259 # Done here as parent may be in NODE_MAP
260 if path_string in self.field_sets:
261 del self.field_sets[path_string]
262
263 # Avoid using the protobuf default if field isn't set.
264 if (
265 hasattr(root, 'ListFields')
266 and hasattr(root, field_name)
267 and get_named_type(info.return_type).name not in NODE_MAP
268 ):
269
270 # Gather fields set in root
271 stamp = getattr(root, 'stamp', '')
272 if (
273 parent_path_string not in self.field_sets
274 or self.field_sets[
275 parent_path_string]['stamp'] != stamp
276 ):
277 self.field_sets[parent_path_string] = {
278 'stamp': stamp,
279 'fields': {
280 field.name
281 for field, _ in root.ListFields()
282 }
283 }
284
285 if (
286 parent_path_string in self.field_sets
287 and field_name not in self.field_sets[
288 parent_path_string]['fields']
289 ):
290 return None
291 # Do not resolve subfields of an empty type
292 # by setting as null in parent/root.
293 elif isinstance(root, dict) and field_name in root:
294 field_value = root[field_name]
295 if (
296 field_value in EMPTY_VALUES
297 or (
298 hasattr(field_value, 'ListFields')
299 and not field_value.ListFields()
300 )
301 ):
302 return None
303 return async_next(null_setter, next_(root, info, **args))
304
305 return next_(root, info, **args)