Debian Codegraph @

cylc/flow/network/graphql_subscribe.py

raw
1 # MIT License
2 #
3 # Copyright (c) GraphQL Contributors (GraphQL.js)
4 # Copyright (c) Syrus Akbary (GraphQL-core 2)
5 # Copyright (c) Christoph Zwerschke (GraphQL-core 3)
6 #
7 # Permission is hereby granted, free of charge, to any person obtaining a copy
8 # of this software and associated documentation files (the "Software"), to deal
9 # in the Software without restriction, including without limitation the rights
10 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 # copies of the Software, and to permit persons to whom the Software is
12 # furnished to do so, subject to the following conditions:
13 #
14 # The above copyright notice and this permission notice shall be included in
15 # all copies or substantial portions of the Software.
16 #
17 # ----------------------------------------------------------------------------
18 #
19 # The code in this file originates from graphql-core
20 # https://github.com/graphql-python/graphql-core/blob/v3.2.6/src/graphql/execution/subscribe.py
21 #
22 # It was modified to include `execution_context_class` and `middleware` in
23 # the execution of GraphQL subscriptions.
24 # This should not be necessary with some unspecified future releases as
25 # the head of graphql-core has these included.
26 #
27 # BACK COMPAT: graphql_subscribe.py
28 # FROM: graphql-core 3.2
29 # TO: graphql-core 3.3
30 # URL: https://github.com/cylc/cylc-flow/issues/6688
31
32
33 from inspect import isawaitable
34 from typing import (
35 TYPE_CHECKING,
36 Any,
37 AsyncIterable,
38 AsyncIterator,
39 Dict,
40 Optional,
41 Type,
42 Union,
43 )
44
45 from graphql.error import GraphQLError, located_error
46 from graphql.execution.collect_fields import collect_fields
47 from graphql.execution.execute import (
48 assert_valid_execution_arguments,
49 execute,
50 get_field_def,
51 ExecutionContext,
52 ExecutionResult,
53 Middleware,
54 )
55 from graphql.execution.values import get_argument_values
56 from graphql.pyutils import Path, inspect
57 from graphql.execution.map_async_iterator import MapAsyncIterator
58
59
60 if TYPE_CHECKING:
61 from graphql.language import DocumentNode
62 from graphql.type import GraphQLFieldResolver, GraphQLSchema
63
64
65 __all__ = ["subscribe", "create_source_event_stream"]
66
67
68 async def subscribe(
69 schema: 'GraphQLSchema',
70 document: 'DocumentNode',
71 root_value: Any = None,
72 context_value: Any = None,
73 variable_values: Optional[Dict[str, Any]] = None,
74 operation_name: Optional[str] = None,
75 field_resolver: 'Optional[GraphQLFieldResolver]' = None,
76 subscribe_field_resolver: 'Optional[GraphQLFieldResolver]' = None,
77 middleware: Optional[Middleware] = None,
78 execution_context_class: Optional[Type["ExecutionContext"]] = None,
79 subscribe_resolver_map: 'Optional[Dict[str, GraphQLFieldResolver]]' = None,
80 ) -> Union[AsyncIterator[ExecutionResult], ExecutionResult]:
81 """Create a GraphQL subscription.
82
83 Implements the "Subscribe" algorithm described in the GraphQL spec.
84
85 Returns a coroutine object which yields either an AsyncIterator
86 (if successful) or an ExecutionResult (client error). The coroutine will
87 raise an exception if a server error occurs.
88
89 If the client-provided arguments to this function do not result in a
90 compliant subscription, a GraphQL Response (ExecutionResult) with
91 descriptive errors and no data will be returned.
92
93 If the source stream could not be created due to faulty subscription
94 resolver logic or underlying systems, the coroutine object will yield a
95 single ExecutionResult containing ``errors`` and no ``data``.
96
97 If the operation succeeded, the coroutine will yield an AsyncIterator,
98 which yields a stream of ExecutionResults representing the response stream.
99 """
100 result_or_stream = await create_source_event_stream(
101 schema,
102 document,
103 root_value,
104 context_value,
105 variable_values,
106 operation_name,
107 subscribe_field_resolver,
108 middleware,
109 execution_context_class,
110 subscribe_resolver_map
111 )
112 if isinstance(result_or_stream, ExecutionResult):
113 return result_or_stream
114
115 async def map_source_to_response(payload: Any) -> ExecutionResult:
116 """Map source to response.
117
118 For each payload yielded from a subscription, map it over the normal
119 GraphQL :func:`~graphql.execute` function, with ``payload`` as the
120 ``root_value``. This implements the "MapSourceToResponseEvent"
121 algorithm described in the GraphQL specification. The
122 :func:`~graphql.execute` function provides the
123 "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
124 "ExecuteQuery" algorithm, for which :func:`~graphql.execute` is also
125 used.
126 """
127 result = execute(
128 schema,
129 document,
130 payload,
131 context_value,
132 variable_values,
133 operation_name,
134 field_resolver,
135 middleware=middleware,
136 execution_context_class=execution_context_class,
137 )
138 return await result if isawaitable(result) else result
139
140 # Map every source value to a ExecutionResult value as described above.
141 return MapAsyncIterator(result_or_stream, map_source_to_response)
142
143
144 async def create_source_event_stream(
145 schema: 'GraphQLSchema',
146 document: 'DocumentNode',
147 root_value: Any = None,
148 context_value: Any = None,
149 variable_values: Optional[Dict[str, Any]] = None,
150 operation_name: Optional[str] = None,
151 subscribe_field_resolver: 'Optional[GraphQLFieldResolver]' = None,
152 middleware: Optional[Middleware] = None,
153 execution_context_class: Optional[Type["ExecutionContext"]] = None,
154 subscribe_resolver_map: 'Optional[Dict[str, GraphQLFieldResolver]]' = None,
155 ) -> Union[AsyncIterable[Any], ExecutionResult]:
156 """Create source event stream
157
158 Implements the "CreateSourceEventStream" algorithm described in the GraphQL
159 specification, resolving the subscription source event stream.
160
161 Returns a coroutine that yields an AsyncIterable.
162
163 If the client-provided arguments to this function do not result in a
164 compliant subscription, a GraphQL Response (ExecutionResult) with
165 descriptive errors and no data will be returned.
166
167 If the source stream could not be created due to faulty subscription
168 resolver logic or underlying systems, the coroutine object will yield a
169 single ExecutionResult containing ``errors`` and no ``data``.
170
171 A source event stream represents a sequence of events, each of which
172 triggers a GraphQL execution for that event.
173
174 This may be useful when hosting the stateful subscription service in a
175 different process or machine than the stateless GraphQL execution engine,
176 or otherwise separating these two steps. For more on this, see the
177 "Supporting Subscriptions at Scale" information in the GraphQL spec.
178 """
179 # If arguments are missing or incorrectly typed, this is an internal
180 # developer mistake which should throw an early error.
181 assert_valid_execution_arguments(schema, document, variable_values)
182
183 if execution_context_class is None:
184 execution_context_class = ExecutionContext
185
186 # If a valid context cannot be created due to incorrect arguments,
187 # a "Response" with only errors is returned.
188 context = execution_context_class.build(
189 schema,
190 document,
191 root_value,
192 context_value,
193 variable_values,
194 operation_name,
195 subscribe_field_resolver=subscribe_field_resolver,
196 )
197
198 # Return early errors if execution context failed.
199 if isinstance(context, list):
200 return ExecutionResult(data=None, errors=context)
201
202 try:
203 event_stream = await execute_subscription(
204 context,
205 subscribe_resolver_map
206 )
207
208 # Assert field returned an event stream, otherwise yield an error.
209 if not isinstance(event_stream, AsyncIterable):
210 raise TypeError(
211 "Subscription field must return AsyncIterable."
212 f" Received: {inspect(event_stream)}."
213 )
214 return event_stream
215
216 except GraphQLError as error:
217 # Report it as an ExecutionResult, containing only errors and no data.
218 return ExecutionResult(data=None, errors=[error])
219
220
221 async def execute_subscription(
222 context: ExecutionContext,
223 subscribe_resolver_map: 'Optional[Dict[str, GraphQLFieldResolver]]' = None,
224 ) -> AsyncIterable[Any]:
225 schema = context.schema
226
227 root_type = schema.subscription_type
228 if root_type is None:
229 raise GraphQLError(
230 "Schema is not configured to execute subscription operation.",
231 context.operation,
232 )
233
234 root_fields = collect_fields(
235 schema,
236 context.fragments,
237 context.variable_values,
238 root_type,
239 context.operation.selection_set,
240 )
241 response_name, field_nodes = next(iter(root_fields.items()))
242 field_def = get_field_def(schema, root_type, field_nodes[0])
243
244 if not field_def:
245 field_name = field_nodes[0].name.value
246 raise GraphQLError(
247 f"The subscription field '{field_name}' is not defined.",
248 field_nodes
249 )
250
251 path = Path(None, response_name, root_type.name)
252 info = context.build_resolve_info(field_def, field_nodes, root_type, path)
253
254 # Call the `subscribe()` resolver or the default resolver to produce an
255 # AsyncIterable yielding raw payloads.
256 if subscribe_resolver_map is not None:
257 resolve_fn = subscribe_resolver_map.get(
258 info.field_name,
259 field_def.subscribe or context.subscribe_field_resolver
260 )
261 else:
262 resolve_fn = field_def.subscribe or context.subscribe_field_resolver
263
264 # Implements the "ResolveFieldEventStream" algorithm from GraphQL
265 # specification. It differs from "ResolveFieldValue" due to providing a
266 # different `resolveFn`.
267
268 try:
269 # Build a dictionary of arguments from the field.arguments AST, using
270 # the variables scope to fulfill any variable references.
271 args = get_argument_values(
272 field_def, field_nodes[0], context.variable_values)
273
274 event_stream = resolve_fn(context.root_value, info, **args)
275 if context.is_awaitable(event_stream):
276 event_stream = await event_stream
277 if isinstance(event_stream, Exception):
278 raise event_stream
279
280 return event_stream
281 except Exception as error:
282 raise located_error(error, field_nodes, path.as_list()) from error