| 1 |
from inspect import isawaitable |
| 2 |
from typing import ( |
| 3 |
Any, |
| 4 |
AsyncIterable, |
| 5 |
AsyncIterator, |
| 6 |
Dict, |
| 7 |
Optional, |
| 8 |
Union, |
| 9 |
) |
| 10 |
|
| 11 |
from ..error import GraphQLError, located_error |
| 12 |
from ..execution.collect_fields import collect_fields |
| 13 |
from ..execution.execute import ( |
| 14 |
assert_valid_execution_arguments, |
| 15 |
execute, |
| 16 |
get_field_def, |
| 17 |
ExecutionContext, |
| 18 |
ExecutionResult, |
| 19 |
) |
| 20 |
from ..execution.values import get_argument_values |
| 21 |
from ..language import DocumentNode |
| 22 |
from ..pyutils import Path, inspect |
| 23 |
from ..type import GraphQLFieldResolver, GraphQLSchema |
| 24 |
from .map_async_iterator import MapAsyncIterator |
| 25 |
|
| 26 |
__all__ = ["subscribe", "create_source_event_stream"] |
| 27 |
|
| 28 |
|
| 29 |
async def subscribe( |
| 30 |
schema: GraphQLSchema, |
| 31 |
document: DocumentNode, |
| 32 |
root_value: Any = None, |
| 33 |
context_value: Any = None, |
| 34 |
variable_values: Optional[Dict[str, Any]] = None, |
| 35 |
operation_name: Optional[str] = None, |
| 36 |
field_resolver: Optional[GraphQLFieldResolver] = None, |
| 37 |
subscribe_field_resolver: Optional[GraphQLFieldResolver] = None, |
| 38 |
max_coercion_errors: int = 50, |
| 39 |
) -> Union[AsyncIterator[ExecutionResult], ExecutionResult]: |
| 40 |
"""Create a GraphQL subscription. |
| 41 |
|
| 42 |
Implements the "Subscribe" algorithm described in the GraphQL spec. |
| 43 |
|
| 44 |
Returns a coroutine object which yields either an AsyncIterator (if successful) or |
| 45 |
an ExecutionResult (client error). The coroutine will raise an exception if a server |
| 46 |
error occurs. |
| 47 |
|
| 48 |
If the client-provided arguments to this function do not result in a compliant |
| 49 |
subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no |
| 50 |
data will be returned. |
| 51 |
|
| 52 |
If the source stream could not be created due to faulty subscription resolver logic |
| 53 |
or underlying systems, the coroutine object will yield a single ExecutionResult |
| 54 |
containing ``errors`` and no ``data``. |
| 55 |
|
| 56 |
If the operation succeeded, the coroutine will yield an AsyncIterator, which yields |
| 57 |
a stream of ExecutionResults representing the response stream. |
| 58 |
""" |
| 59 |
result_or_stream = await create_source_event_stream( |
| 60 |
schema, |
| 61 |
document, |
| 62 |
root_value, |
| 63 |
context_value, |
| 64 |
variable_values, |
| 65 |
operation_name, |
| 66 |
subscribe_field_resolver, |
| 67 |
max_coercion_errors, |
| 68 |
) |
| 69 |
if isinstance(result_or_stream, ExecutionResult): |
| 70 |
return result_or_stream |
| 71 |
|
| 72 |
async def map_source_to_response(payload: Any) -> ExecutionResult: |
| 73 |
"""Map source to response. |
| 74 |
|
| 75 |
For each payload yielded from a subscription, map it over the normal GraphQL |
| 76 |
:func:`~graphql.execute` function, with ``payload`` as the ``root_value``. |
| 77 |
This implements the "MapSourceToResponseEvent" algorithm described in the |
| 78 |
GraphQL specification. The :func:`~graphql.execute` function provides the |
| 79 |
"ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the |
| 80 |
"ExecuteQuery" algorithm, for which :func:`~graphql.execute` is also used. |
| 81 |
""" |
| 82 |
result = execute( |
| 83 |
schema, |
| 84 |
document, |
| 85 |
payload, |
| 86 |
context_value, |
| 87 |
variable_values, |
| 88 |
operation_name, |
| 89 |
field_resolver, |
| 90 |
) |
| 91 |
return await result if isawaitable(result) else result |
| 92 |
|
| 93 |
# Map every source value to a ExecutionResult value as described above. |
| 94 |
return MapAsyncIterator(result_or_stream, map_source_to_response) |
| 95 |
|
| 96 |
|
| 97 |
async def create_source_event_stream( |
| 98 |
schema: GraphQLSchema, |
| 99 |
document: DocumentNode, |
| 100 |
root_value: Any = None, |
| 101 |
context_value: Any = None, |
| 102 |
variable_values: Optional[Dict[str, Any]] = None, |
| 103 |
operation_name: Optional[str] = None, |
| 104 |
subscribe_field_resolver: Optional[GraphQLFieldResolver] = None, |
| 105 |
max_coercion_errors: int = 50, |
| 106 |
) -> Union[AsyncIterable[Any], ExecutionResult]: |
| 107 |
"""Create source event stream |
| 108 |
|
| 109 |
Implements the "CreateSourceEventStream" algorithm described in the GraphQL |
| 110 |
specification, resolving the subscription source event stream. |
| 111 |
|
| 112 |
Returns a coroutine that yields an AsyncIterable. |
| 113 |
|
| 114 |
If the client-provided arguments to this function do not result in a compliant |
| 115 |
subscription, a GraphQL Response (ExecutionResult) with descriptive errors and no |
| 116 |
data will be returned. |
| 117 |
|
| 118 |
If the source stream could not be created due to faulty subscription resolver logic |
| 119 |
or underlying systems, the coroutine object will yield a single ExecutionResult |
| 120 |
containing ``errors`` and no ``data``. |
| 121 |
|
| 122 |
A source event stream represents a sequence of events, each of which triggers a |
| 123 |
GraphQL execution for that event. |
| 124 |
|
| 125 |
This may be useful when hosting the stateful subscription service in a different |
| 126 |
process or machine than the stateless GraphQL execution engine, or otherwise |
| 127 |
separating these two steps. For more on this, see the "Supporting Subscriptions |
| 128 |
at Scale" information in the GraphQL spec. |
| 129 |
""" |
| 130 |
# If arguments are missing or incorrectly typed, this is an internal developer |
| 131 |
# mistake which should throw an early error. |
| 132 |
assert_valid_execution_arguments(schema, document, variable_values) |
| 133 |
|
| 134 |
# If a valid context cannot be created due to incorrect arguments, |
| 135 |
# a "Response" with only errors is returned. |
| 136 |
context = ExecutionContext.build( |
| 137 |
schema, |
| 138 |
document, |
| 139 |
root_value, |
| 140 |
context_value, |
| 141 |
variable_values, |
| 142 |
operation_name, |
| 143 |
subscribe_field_resolver=subscribe_field_resolver, |
| 144 |
max_coercion_errors=max_coercion_errors, |
| 145 |
) |
| 146 |
|
| 147 |
# Return early errors if execution context failed. |
| 148 |
if isinstance(context, list): |
| 149 |
return ExecutionResult(data=None, errors=context) |
| 150 |
|
| 151 |
try: |
| 152 |
event_stream = await execute_subscription(context) |
| 153 |
|
| 154 |
# Assert field returned an event stream, otherwise yield an error. |
| 155 |
if not isinstance(event_stream, AsyncIterable): |
| 156 |
raise TypeError( |
| 157 |
"Subscription field must return AsyncIterable." |
| 158 |
f" Received: {inspect(event_stream)}." |
| 159 |
) |
| 160 |
return event_stream |
| 161 |
|
| 162 |
except GraphQLError as error: |
| 163 |
# Report it as an ExecutionResult, containing only errors and no data. |
| 164 |
return ExecutionResult(data=None, errors=[error]) |
| 165 |
|
| 166 |
|
| 167 |
async def execute_subscription(context: ExecutionContext) -> AsyncIterable[Any]: |
| 168 |
schema = context.schema |
| 169 |
|
| 170 |
root_type = schema.subscription_type |
| 171 |
if root_type is None: |
| 172 |
raise GraphQLError( |
| 173 |
"Schema is not configured to execute subscription operation.", |
| 174 |
context.operation, |
| 175 |
) |
| 176 |
|
| 177 |
root_fields = collect_fields( |
| 178 |
schema, |
| 179 |
context.fragments, |
| 180 |
context.variable_values, |
| 181 |
root_type, |
| 182 |
context.operation.selection_set, |
| 183 |
) |
| 184 |
response_name, field_nodes = next(iter(root_fields.items())) |
| 185 |
field_def = get_field_def(schema, root_type, field_nodes[0]) |
| 186 |
|
| 187 |
if not field_def: |
| 188 |
field_name = field_nodes[0].name.value |
| 189 |
raise GraphQLError( |
| 190 |
f"The subscription field '{field_name}' is not defined.", field_nodes |
| 191 |
) |
| 192 |
|
| 193 |
path = Path(None, response_name, root_type.name) |
| 194 |
info = context.build_resolve_info(field_def, field_nodes, root_type, path) |
| 195 |
|
| 196 |
# Implements the "ResolveFieldEventStream" algorithm from GraphQL specification. |
| 197 |
# It differs from "ResolveFieldValue" due to providing a different `resolveFn`. |
| 198 |
|
| 199 |
try: |
| 200 |
# Build a dictionary of arguments from the field.arguments AST, using the |
| 201 |
# variables scope to fulfill any variable references. |
| 202 |
args = get_argument_values(field_def, field_nodes[0], context.variable_values) |
| 203 |
|
| 204 |
# Call the `subscribe()` resolver or the default resolver to produce an |
| 205 |
# AsyncIterable yielding raw payloads. |
| 206 |
resolve_fn = field_def.subscribe or context.subscribe_field_resolver |
| 207 |
|
| 208 |
event_stream = resolve_fn(context.root_value, info, **args) |
| 209 |
if context.is_awaitable(event_stream): |
| 210 |
event_stream = await event_stream |
| 211 |
if isinstance(event_stream, Exception): |
| 212 |
raise event_stream |
| 213 |
|
| 214 |
return event_stream |
| 215 |
except Exception as error: |
| 216 |
raise located_error(error, field_nodes, path.as_list()) |