-
-
Notifications
You must be signed in to change notification settings - Fork 132
/
execute.py
2828 lines (2443 loc) · 101 KB
/
execute.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"""GraphQL execution"""
from __future__ import annotations # Python < 3.10
from asyncio import Event, as_completed, ensure_future, gather, shield, sleep, wait_for
from collections.abc import Mapping
from contextlib import suppress
from typing import (
Any,
AsyncGenerator,
AsyncIterable,
AsyncIterator,
Awaitable,
Callable,
Dict,
Generator,
Iterable,
Iterator,
List,
NamedTuple,
Optional,
Sequence,
Set,
Tuple,
Type,
Union,
cast,
)
try:
from typing import TypedDict
except ImportError: # Python < 3.8
from typing_extensions import TypedDict
try:
from typing import TypeAlias, TypeGuard
except ImportError: # Python < 3.10
from typing_extensions import TypeAlias, TypeGuard
try: # only needed for Python < 3.11
# noinspection PyCompatibility
from asyncio.exceptions import TimeoutError
except ImportError: # Python < 3.7
from concurrent.futures import TimeoutError # type: ignore
from ..error import GraphQLError, GraphQLFormattedError, located_error
from ..language import (
DocumentNode,
FieldNode,
FragmentDefinitionNode,
OperationDefinitionNode,
OperationType,
)
from ..pyutils import (
AwaitableOrValue,
Path,
Undefined,
async_reduce,
inspect,
is_iterable,
)
from ..pyutils import is_awaitable as default_is_awaitable
from ..type import (
GraphQLAbstractType,
GraphQLField,
GraphQLFieldResolver,
GraphQLLeafType,
GraphQLList,
GraphQLObjectType,
GraphQLOutputType,
GraphQLResolveInfo,
GraphQLSchema,
GraphQLStreamDirective,
GraphQLTypeResolver,
assert_valid_schema,
is_abstract_type,
is_leaf_type,
is_list_type,
is_non_null_type,
is_object_type,
)
from .async_iterables import flatten_async_iterable, map_async_iterable
from .collect_fields import FieldsAndPatches, collect_fields, collect_subfields
from .middleware import MiddlewareManager
from .values import get_argument_values, get_directive_values, get_variable_values
ASYNC_DELAY = 1 / 512 # wait time in seconds for deferring execution
try: # pragma: no cover
anext # noqa: B018
except NameError: # pragma: no cover (Python < 3.10)
# noinspection PyShadowingBuiltins
async def anext(iterator: AsyncIterator) -> Any: # noqa: A001
"""Return the next item from an async iterator."""
return await iterator.__anext__()
__all__ = [
"ASYNC_DELAY",
"create_source_event_stream",
"default_field_resolver",
"default_type_resolver",
"execute",
"execute_sync",
"experimental_execute_incrementally",
"experimental_subscribe_incrementally",
"subscribe",
"AsyncPayloadRecord",
"DeferredFragmentRecord",
"StreamRecord",
"ExecutionResult",
"ExecutionContext",
"ExperimentalIncrementalExecutionResults",
"FormattedExecutionResult",
"FormattedIncrementalDeferResult",
"FormattedIncrementalResult",
"FormattedIncrementalStreamResult",
"FormattedInitialIncrementalExecutionResult",
"FormattedSubsequentIncrementalExecutionResult",
"IncrementalDeferResult",
"IncrementalResult",
"IncrementalStreamResult",
"InitialIncrementalExecutionResult",
"Middleware",
"SubsequentIncrementalExecutionResult",
]
# Terminology
#
# "Definitions" are the generic name for top-level statements in the document.
# Examples of this include:
# 1) Operations (such as a query)
# 2) Fragments
#
# "Operations" are a generic name for requests in the document.
# Examples of this include:
# 1) query,
# 2) mutation
#
# "Selections" are the definitions that can appear legally and at
# single level of the query. These include:
# 1) field references e.g "a"
# 2) fragment "spreads" e.g. "...c"
# 3) inline fragment "spreads" e.g. "...on Type { a }"
class FormattedExecutionResult(TypedDict, total=False):
"""Formatted execution result"""
data: Optional[Dict[str, Any]]
errors: List[GraphQLFormattedError]
extensions: Dict[str, Any]
class ExecutionResult:
"""The result of GraphQL execution.
- ``data`` is the result of a successful execution of the query.
- ``errors`` is included when any errors occurred as a non-empty list.
- ``extensions`` is reserved for adding non-standard properties.
"""
__slots__ = "data", "errors", "extensions"
data: Optional[Dict[str, Any]]
errors: Optional[List[GraphQLError]]
extensions: Optional[Dict[str, Any]]
def __init__(
self,
data: Optional[Dict[str, Any]] = None,
errors: Optional[List[GraphQLError]] = None,
extensions: Optional[Dict[str, Any]] = None,
) -> None:
self.data = data
self.errors = errors
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
ext = "" if self.extensions is None else f", extensions={self.extensions}"
return f"{name}(data={self.data!r}, errors={self.errors!r}{ext})"
def __iter__(self) -> Iterator[Any]:
return iter((self.data, self.errors))
@property
def formatted(self) -> FormattedExecutionResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedExecutionResult = {"data": self.data}
if self.errors is not None:
formatted["errors"] = [error.formatted for error in self.errors]
if self.extensions is not None:
formatted["extensions"] = self.extensions
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
if "extensions" not in other:
return other == {"data": self.data, "errors": self.errors}
return other == {
"data": self.data,
"errors": self.errors,
"extensions": self.extensions,
}
if isinstance(other, tuple):
if len(other) == 2:
return other == (self.data, self.errors)
return other == (self.data, self.errors, self.extensions)
return (
isinstance(other, self.__class__)
and other.data == self.data
and other.errors == self.errors
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
class FormattedIncrementalDeferResult(TypedDict, total=False):
"""Formatted incremental deferred execution result"""
data: Optional[Dict[str, Any]]
errors: List[GraphQLFormattedError]
path: List[Union[str, int]]
label: str
extensions: Dict[str, Any]
class IncrementalDeferResult:
"""Incremental deferred execution result"""
data: Optional[Dict[str, Any]]
errors: Optional[List[GraphQLError]]
path: Optional[List[Union[str, int]]]
label: Optional[str]
extensions: Optional[Dict[str, Any]]
__slots__ = "data", "errors", "path", "label", "extensions"
def __init__(
self,
data: Optional[Dict[str, Any]] = None,
errors: Optional[List[GraphQLError]] = None,
path: Optional[List[Union[str, int]]] = None,
label: Optional[str] = None,
extensions: Optional[Dict[str, Any]] = None,
) -> None:
self.data = data
self.errors = errors
self.path = path
self.label = label
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: List[str] = [f"data={self.data!r}, errors={self.errors!r}"]
if self.path:
args.append(f"path={self.path!r}")
if self.label:
args.append(f"label={self.label!r}")
if self.extensions:
args.append(f"extensions={self.extensions}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedIncrementalDeferResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedIncrementalDeferResult = {"data": self.data}
if self.errors is not None:
formatted["errors"] = [error.formatted for error in self.errors]
if self.path is not None:
formatted["path"] = self.path
if self.label is not None:
formatted["label"] = self.label
if self.extensions is not None:
formatted["extensions"] = self.extensions
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
return (
other.get("data") == self.data
and other.get("errors") == self.errors
and ("path" not in other or other["path"] == self.path)
and ("label" not in other or other["label"] == self.label)
and (
"extensions" not in other or other["extensions"] == self.extensions
)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (self.data, self.errors, self.path, self.label, self.extensions)[
:size
]
== other
)
return (
isinstance(other, self.__class__)
and other.data == self.data
and other.errors == self.errors
and other.path == self.path
and other.label == self.label
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
class FormattedIncrementalStreamResult(TypedDict, total=False):
"""Formatted incremental stream execution result"""
items: Optional[List[Any]]
errors: List[GraphQLFormattedError]
path: List[Union[str, int]]
label: str
extensions: Dict[str, Any]
class IncrementalStreamResult:
"""Incremental streamed execution result"""
items: Optional[List[Any]]
errors: Optional[List[GraphQLError]]
path: Optional[List[Union[str, int]]]
label: Optional[str]
extensions: Optional[Dict[str, Any]]
__slots__ = "items", "errors", "path", "label", "extensions"
def __init__(
self,
items: Optional[List[Any]] = None,
errors: Optional[List[GraphQLError]] = None,
path: Optional[List[Union[str, int]]] = None,
label: Optional[str] = None,
extensions: Optional[Dict[str, Any]] = None,
) -> None:
self.items = items
self.errors = errors
self.path = path
self.label = label
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: List[str] = [f"items={self.items!r}, errors={self.errors!r}"]
if self.path:
args.append(f"path={self.path!r}")
if self.label:
args.append(f"label={self.label!r}")
if self.extensions:
args.append(f"extensions={self.extensions}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedIncrementalStreamResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedIncrementalStreamResult = {"items": self.items}
if self.errors is not None:
formatted["errors"] = [error.formatted for error in self.errors]
if self.path is not None:
formatted["path"] = self.path
if self.label is not None:
formatted["label"] = self.label
if self.extensions is not None:
formatted["extensions"] = self.extensions
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
return (
other.get("items") == self.items
and other.get("errors") == self.errors
and ("path" not in other or other["path"] == self.path)
and ("label" not in other or other["label"] == self.label)
and (
"extensions" not in other or other["extensions"] == self.extensions
)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (self.items, self.errors, self.path, self.label, self.extensions)[
:size
]
== other
)
return (
isinstance(other, self.__class__)
and other.items == self.items
and other.errors == self.errors
and other.path == self.path
and other.label == self.label
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
FormattedIncrementalResult = Union[
FormattedIncrementalDeferResult, FormattedIncrementalStreamResult
]
IncrementalResult = Union[IncrementalDeferResult, IncrementalStreamResult]
class FormattedInitialIncrementalExecutionResult(TypedDict, total=False):
"""Formatted initial incremental execution result"""
data: Optional[Dict[str, Any]]
errors: List[GraphQLFormattedError]
hasNext: bool
incremental: List[FormattedIncrementalResult]
extensions: Dict[str, Any]
class InitialIncrementalExecutionResult:
"""Initial incremental execution result.
- ``has_next`` is True if a future payload is expected.
- ``incremental`` is a list of the results from defer/stream directives.
"""
data: Optional[Dict[str, Any]]
errors: Optional[List[GraphQLError]]
incremental: Optional[Sequence[IncrementalResult]]
has_next: bool
extensions: Optional[Dict[str, Any]]
__slots__ = "data", "errors", "has_next", "incremental", "extensions"
def __init__(
self,
data: Optional[Dict[str, Any]] = None,
errors: Optional[List[GraphQLError]] = None,
incremental: Optional[Sequence[IncrementalResult]] = None,
has_next: bool = False,
extensions: Optional[Dict[str, Any]] = None,
) -> None:
self.data = data
self.errors = errors
self.incremental = incremental
self.has_next = has_next
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: List[str] = [f"data={self.data!r}, errors={self.errors!r}"]
if self.incremental:
args.append(f"incremental[{len(self.incremental)}]")
if self.has_next:
args.append("has_next")
if self.extensions:
args.append(f"extensions={self.extensions}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedInitialIncrementalExecutionResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedInitialIncrementalExecutionResult = {"data": self.data}
if self.errors is not None:
formatted["errors"] = [error.formatted for error in self.errors]
if self.incremental:
formatted["incremental"] = [result.formatted for result in self.incremental]
formatted["hasNext"] = self.has_next
if self.extensions is not None:
formatted["extensions"] = self.extensions
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
return (
other.get("data") == self.data
and other.get("errors") == self.errors
and (
"incremental" not in other
or other["incremental"] == self.incremental
)
and ("hasNext" not in other or other["hasNext"] == self.has_next)
and (
"extensions" not in other or other["extensions"] == self.extensions
)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (
self.data,
self.errors,
self.incremental,
self.has_next,
self.extensions,
)[:size]
== other
)
return (
isinstance(other, self.__class__)
and other.data == self.data
and other.errors == self.errors
and other.incremental == self.incremental
and other.has_next == self.has_next
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
class FormattedSubsequentIncrementalExecutionResult(TypedDict, total=False):
"""Formatted subsequent incremental execution result"""
incremental: List[FormattedIncrementalResult]
hasNext: bool
extensions: Dict[str, Any]
class SubsequentIncrementalExecutionResult:
"""Subsequent incremental execution result.
- ``has_next`` is True if a future payload is expected.
- ``incremental`` is a list of the results from defer/stream directives.
"""
__slots__ = "has_next", "incremental", "extensions"
incremental: Optional[Sequence[IncrementalResult]]
has_next: bool
extensions: Optional[Dict[str, Any]]
def __init__(
self,
incremental: Optional[Sequence[IncrementalResult]] = None,
has_next: bool = False,
extensions: Optional[Dict[str, Any]] = None,
) -> None:
self.incremental = incremental
self.has_next = has_next
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: List[str] = []
if self.incremental:
args.append(f"incremental[{len(self.incremental)}]")
if self.has_next:
args.append("has_next")
if self.extensions:
args.append(f"extensions={self.extensions}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedSubsequentIncrementalExecutionResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedSubsequentIncrementalExecutionResult = {}
if self.incremental:
formatted["incremental"] = [result.formatted for result in self.incremental]
formatted["hasNext"] = self.has_next
if self.extensions is not None:
formatted["extensions"] = self.extensions
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
return (
("incremental" not in other or other["incremental"] == self.incremental)
and ("hasNext" in other and other["hasNext"] == self.has_next)
and (
"extensions" not in other or other["extensions"] == self.extensions
)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 4
and (
self.incremental,
self.has_next,
self.extensions,
)[:size]
== other
)
return (
isinstance(other, self.__class__)
and other.incremental == self.incremental
and other.has_next == self.has_next
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
class StreamArguments(NamedTuple):
"""Arguments of the stream directive"""
initial_count: int
label: Optional[str]
class ExperimentalIncrementalExecutionResults(NamedTuple):
"""Execution results when retrieved incrementally."""
initial_result: InitialIncrementalExecutionResult
subsequent_results: AsyncGenerator[SubsequentIncrementalExecutionResult, None]
Middleware: TypeAlias = Optional[Union[Tuple, List, MiddlewareManager]]
class ExecutionContext:
"""Data that must be available at all points during query execution.
Namely, schema of the type system that is currently executing, and the fragments
defined in the query document.
"""
schema: GraphQLSchema
fragments: Dict[str, FragmentDefinitionNode]
root_value: Any
context_value: Any
operation: OperationDefinitionNode
variable_values: Dict[str, Any]
field_resolver: GraphQLFieldResolver
type_resolver: GraphQLTypeResolver
subscribe_field_resolver: GraphQLFieldResolver
errors: List[GraphQLError]
subsequent_payloads: Dict[AsyncPayloadRecord, None] # used as ordered set
middleware_manager: Optional[MiddlewareManager]
is_awaitable: Callable[[Any], TypeGuard[Awaitable]] = staticmethod(
default_is_awaitable # type: ignore
)
def __init__(
self,
schema: GraphQLSchema,
fragments: Dict[str, FragmentDefinitionNode],
root_value: Any,
context_value: Any,
operation: OperationDefinitionNode,
variable_values: Dict[str, Any],
field_resolver: GraphQLFieldResolver,
type_resolver: GraphQLTypeResolver,
subscribe_field_resolver: GraphQLFieldResolver,
subsequent_payloads: Dict[AsyncPayloadRecord, None],
errors: List[GraphQLError],
middleware_manager: Optional[MiddlewareManager],
is_awaitable: Optional[Callable[[Any], bool]],
) -> None:
self.schema = schema
self.fragments = fragments
self.root_value = root_value
self.context_value = context_value
self.operation = operation
self.variable_values = variable_values
self.field_resolver = field_resolver
self.type_resolver = type_resolver
self.subscribe_field_resolver = subscribe_field_resolver
self.subsequent_payloads = subsequent_payloads
self.errors = errors
self.middleware_manager = middleware_manager
if is_awaitable:
self.is_awaitable = is_awaitable
self._canceled_iterators: Set[AsyncIterator] = set()
self._subfields_cache: Dict[Tuple, FieldsAndPatches] = {}
@classmethod
def build(
cls,
schema: GraphQLSchema,
document: DocumentNode,
root_value: Any = None,
context_value: Any = None,
raw_variable_values: Optional[Dict[str, Any]] = None,
operation_name: Optional[str] = None,
field_resolver: Optional[GraphQLFieldResolver] = None,
type_resolver: Optional[GraphQLTypeResolver] = None,
subscribe_field_resolver: Optional[GraphQLFieldResolver] = None,
middleware: Optional[Middleware] = None,
is_awaitable: Optional[Callable[[Any], bool]] = None,
) -> Union[List[GraphQLError], ExecutionContext]:
"""Build an execution context
Constructs a ExecutionContext object from the arguments passed to execute, which
we will pass throughout the other execution methods.
Throws a GraphQLError if a valid execution context cannot be created.
For internal use only.
"""
# If the schema used for execution is invalid, raise an error.
assert_valid_schema(schema)
operation: Optional[OperationDefinitionNode] = None
fragments: Dict[str, FragmentDefinitionNode] = {}
middleware_manager: Optional[MiddlewareManager] = None
if middleware is not None:
if isinstance(middleware, (list, tuple)):
middleware_manager = MiddlewareManager(*middleware)
elif isinstance(middleware, MiddlewareManager):
middleware_manager = middleware
else:
msg = (
"Middleware must be passed as a list or tuple of functions"
" or objects, or as a single MiddlewareManager object."
f" Got {inspect(middleware)} instead."
)
raise TypeError(msg)
for definition in document.definitions:
if isinstance(definition, OperationDefinitionNode):
if operation_name is None:
if operation:
return [
GraphQLError(
"Must provide operation name"
" if query contains multiple operations."
)
]
operation = definition
elif definition.name and definition.name.value == operation_name:
operation = definition
elif isinstance(definition, FragmentDefinitionNode):
fragments[definition.name.value] = definition
if not operation:
if operation_name is not None:
return [GraphQLError(f"Unknown operation named '{operation_name}'.")]
return [GraphQLError("Must provide an operation.")]
coerced_variable_values = get_variable_values(
schema,
operation.variable_definitions or (),
raw_variable_values or {},
max_errors=50,
)
if isinstance(coerced_variable_values, list):
return coerced_variable_values # errors
return cls(
schema,
fragments,
root_value,
context_value,
operation,
coerced_variable_values, # coerced values
field_resolver or default_field_resolver,
type_resolver or default_type_resolver,
subscribe_field_resolver or default_field_resolver,
{},
[],
middleware_manager,
is_awaitable,
)
@staticmethod
def build_response(
data: Optional[Dict[str, Any]], errors: List[GraphQLError]
) -> ExecutionResult:
"""Build response.
Given a completed execution context and data, build the (data, errors) response
defined by the "Response" section of the GraphQL spec.
"""
if not errors:
return ExecutionResult(data, None)
# Sort the error list in order to make it deterministic, since we might have
# been using parallel execution.
errors.sort(
key=lambda error: (error.locations or [], error.path or [], error.message)
)
return ExecutionResult(data, errors)
def build_per_event_execution_context(self, payload: Any) -> ExecutionContext:
"""Create a copy of the execution context for usage with subscribe events."""
return self.__class__(
self.schema,
self.fragments,
payload,
self.context_value,
self.operation,
self.variable_values,
self.field_resolver,
self.type_resolver,
self.subscribe_field_resolver,
{},
[],
self.middleware_manager,
self.is_awaitable,
)
def execute_operation(self) -> AwaitableOrValue[Dict[str, Any]]:
"""Execute an operation.
Implements the "Executing operations" section of the spec.
"""
schema = self.schema
operation = self.operation
root_type = schema.get_root_type(operation.operation)
if root_type is None:
msg = (
"Schema is not configured to execute"
f" {operation.operation.value} operation."
)
raise GraphQLError(msg, operation)
root_fields, patches = collect_fields(
schema,
self.fragments,
self.variable_values,
root_type,
operation.selection_set,
)
root_value = self.root_value
# noinspection PyTypeChecker
result = (
self.execute_fields_serially
if operation.operation == OperationType.MUTATION
else self.execute_fields
)(root_type, root_value, None, root_fields) # type: ignore
for patch in patches:
label, patch_fields = patch
self.execute_deferred_fragment(
root_type, root_value, patch_fields, label, None
)
return result
def execute_fields_serially(
self,
parent_type: GraphQLObjectType,
source_value: Any,
path: Optional[Path],
fields: Dict[str, List[FieldNode]],
) -> AwaitableOrValue[Dict[str, Any]]:
"""Execute the given fields serially.
Implements the "Executing selection sets" section of the spec
for fields that must be executed serially.
"""
is_awaitable = self.is_awaitable
def reducer(
results: Dict[str, Any], field_item: Tuple[str, List[FieldNode]]
) -> AwaitableOrValue[Dict[str, Any]]:
response_name, field_nodes = field_item
field_path = Path(path, response_name, parent_type.name)
result = self.execute_field(
parent_type, source_value, field_nodes, field_path
)
if result is Undefined:
return results
if is_awaitable(result):
# noinspection PyShadowingNames
async def set_result(
response_name: str,
awaitable_result: Awaitable,
) -> Dict[str, Any]:
results[response_name] = await awaitable_result
return results
return set_result(response_name, result)
results[response_name] = result
return results
# noinspection PyTypeChecker
return async_reduce(reducer, fields.items(), {})
def execute_fields(
self,
parent_type: GraphQLObjectType,
source_value: Any,
path: Optional[Path],
fields: Dict[str, List[FieldNode]],
async_payload_record: Optional[AsyncPayloadRecord] = None,
) -> AwaitableOrValue[Dict[str, Any]]:
"""Execute the given fields concurrently.
Implements the "Executing selection sets" section of the spec
for fields that may be executed in parallel.
"""
results = {}
is_awaitable = self.is_awaitable
awaitable_fields: List[str] = []
append_awaitable = awaitable_fields.append
for response_name, field_nodes in fields.items():
field_path = Path(path, response_name, parent_type.name)
result = self.execute_field(
parent_type, source_value, field_nodes, field_path, async_payload_record
)
if result is not Undefined:
results[response_name] = result
if is_awaitable(result):
append_awaitable(response_name)
# If there are no coroutines, we can just return the object.
if not awaitable_fields:
return results
# Otherwise, results is a map from field name to the result of resolving that
# field, which is possibly a coroutine object. Return a coroutine object that
# will yield this same map, but with any coroutines awaited in parallel and
# replaced with the values they yielded.
async def get_results() -> Dict[str, Any]:
if len(awaitable_fields) == 1:
# If there is only one field, avoid the overhead of parallelization.
field = awaitable_fields[0]
results[field] = await results[field]
else:
results.update(
zip(
awaitable_fields,
await gather(*(results[field] for field in awaitable_fields)),
)
)
return results
return get_results()
def execute_field(
self,
parent_type: GraphQLObjectType,
source: Any,
field_nodes: List[FieldNode],
path: Path,
async_payload_record: Optional[AsyncPayloadRecord] = None,
) -> AwaitableOrValue[Any]:
"""Resolve the field on the given source object.
Implements the "Executing fields" section of the spec.
In particular, this method figures out the value that the field returns by
calling its resolve function, then calls complete_value to await coroutine
objects, serialize scalars, or execute the sub-selection-set for objects.
"""
errors = async_payload_record.errors if async_payload_record else self.errors
field_name = field_nodes[0].name.value
field_def = self.schema.get_field(parent_type, field_name)
if not field_def:
return Undefined
return_type = field_def.type
resolve_fn = field_def.resolve or self.field_resolver
if self.middleware_manager:
resolve_fn = self.middleware_manager.get_field_resolver(resolve_fn)
info = self.build_resolve_info(field_def, field_nodes, parent_type, path)
# Get the resolve function, regardless of if its result is normal or abrupt
# (error).
try:
# Build a dictionary of arguments from the field.arguments AST, using the
# variables scope to fulfill any variable references.
args = get_argument_values(field_def, field_nodes[0], self.variable_values)
# Note that contrary to the JavaScript implementation, we pass the context
# value as part of the resolve info.
result = resolve_fn(source, info, **args)
if self.is_awaitable(result):
return self.complete_awaitable_value(
return_type, field_nodes, info, path, result, async_payload_record
)
completed = self.complete_value(
return_type, field_nodes, info, path, result, async_payload_record
)
if self.is_awaitable(completed):
# noinspection PyShadowingNames
async def await_completed() -> Any:
try:
return await completed
except Exception as raw_error:
error = located_error(raw_error, field_nodes, path.as_list())
handle_field_error(error, return_type, errors)
self.filter_subsequent_payloads(path, async_payload_record)
return None
return await_completed()
except Exception as raw_error:
error = located_error(raw_error, field_nodes, path.as_list())
handle_field_error(error, return_type, errors)
self.filter_subsequent_payloads(path, async_payload_record)
return None
return completed
def build_resolve_info(