-
-
Notifications
You must be signed in to change notification settings - Fork 138
/
Copy pathincremental_publisher.py
1317 lines (1128 loc) · 45.9 KB
/
incremental_publisher.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
"""Incremental Publisher"""
from __future__ import annotations
from asyncio import Event, ensure_future, gather, sleep
from contextlib import suppress
from typing import (
TYPE_CHECKING,
Any,
AsyncGenerator,
Awaitable,
Callable,
Collection,
Iterator,
NamedTuple,
Union,
)
try:
from typing import TypedDict
except ImportError: # Python < 3.8
from typing_extensions import TypedDict
from ..pyutils import RefSet
if TYPE_CHECKING:
from ..error import GraphQLError, GraphQLFormattedError
from ..pyutils import Path
from .collect_fields import GroupedFieldSet
__all__ = [
"ASYNC_DELAY",
"DeferredFragmentRecord",
"ExecutionResult",
"ExperimentalIncrementalExecutionResults",
"FormattedExecutionResult",
"FormattedIncrementalDeferResult",
"FormattedIncrementalResult",
"FormattedIncrementalStreamResult",
"FormattedInitialIncrementalExecutionResult",
"FormattedSubsequentIncrementalExecutionResult",
"IncrementalDataRecord",
"IncrementalDeferResult",
"IncrementalPublisher",
"IncrementalResult",
"IncrementalStreamResult",
"InitialIncrementalExecutionResult",
"InitialResultRecord",
"StreamItemsRecord",
"SubsequentIncrementalExecutionResult",
]
ASYNC_DELAY = 1 / 512 # wait time in seconds for deferring execution
suppress_key_error = suppress(KeyError)
class FormattedPendingResult(TypedDict, total=False):
"""Formatted pending execution result"""
id: str
path: list[str | int]
label: str
class PendingResult:
"""Pending execution result"""
id: str
path: list[str | int]
label: str | None
__slots__ = "id", "label", "path"
def __init__(
self,
id: str, # noqa: A002
path: list[str | int],
label: str | None = None,
) -> None:
self.id = id
self.path = path
self.label = label
def __repr__(self) -> str:
name = self.__class__.__name__
args: list[str] = [f"id={self.id!r}, path={self.path!r}"]
if self.label:
args.append(f"label={self.label!r}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedPendingResult:
"""Get pending result formatted according to the specification."""
formatted: FormattedPendingResult = {"id": self.id, "path": self.path}
if self.label is not None:
formatted["label"] = self.label
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
return (
other.get("id") == self.id
and (other.get("path") or None) == (self.path or None)
and (other.get("label") or None) == (self.label or None)
)
if isinstance(other, tuple):
size = len(other)
return 1 < size < 4 and (self.id, self.path, self.label)[:size] == other
return (
isinstance(other, self.__class__)
and other.id == self.id
and other.path == self.path
and other.label == self.label
)
def __ne__(self, other: object) -> bool:
return not self == other
class FormattedCompletedResult(TypedDict, total=False):
"""Formatted completed execution result"""
id: str
errors: list[GraphQLFormattedError]
class CompletedResult:
"""Completed execution result"""
id: str
errors: list[GraphQLError] | None
__slots__ = "errors", "id"
def __init__(
self,
id: str, # noqa: A002
errors: list[GraphQLError] | None = None,
) -> None:
self.id = id
self.errors = errors
def __repr__(self) -> str:
name = self.__class__.__name__
args: list[str] = [f"id={self.id!r}"]
if self.errors:
args.append(f"errors={self.errors!r}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedCompletedResult:
"""Get completed result formatted according to the specification."""
formatted: FormattedCompletedResult = {"id": self.id}
if self.errors is not None:
formatted["errors"] = [error.formatted for error in self.errors]
return formatted
def __eq__(self, other: object) -> bool:
if isinstance(other, dict):
return other.get("id") == self.id and (other.get("errors") or None) == (
self.errors or None
)
if isinstance(other, tuple):
size = len(other)
return 1 < size < 3 and (self.id, self.errors)[:size] == other
return (
isinstance(other, self.__class__)
and other.id == self.id
and other.errors == self.errors
)
def __ne__(self, other: object) -> bool:
return not self == other
class IncrementalUpdate(NamedTuple):
"""Incremental update"""
pending: list[PendingResult]
incremental: list[IncrementalResult]
completed: list[CompletedResult]
class FormattedExecutionResult(TypedDict, total=False):
"""Formatted execution result"""
data: dict[str, Any] | None
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: dict[str, Any] | None
errors: list[GraphQLError] | None
extensions: dict[str, Any] | None
def __init__(
self,
data: dict[str, Any] | None = None,
errors: list[GraphQLError] | None = None,
extensions: dict[str, Any] | None = 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!r}"
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):
return (
(other.get("data") == self.data)
and (other.get("errors") or None) == (self.errors or None)
and (other.get("extensions") or None) == (self.extensions or None)
)
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 FormattedInitialIncrementalExecutionResult(TypedDict, total=False):
"""Formatted initial incremental execution result"""
data: dict[str, Any] | None
errors: list[GraphQLFormattedError]
pending: list[FormattedPendingResult]
hasNext: bool
incremental: list[FormattedIncrementalResult]
extensions: dict[str, Any]
class InitialIncrementalExecutionResult:
"""Initial incremental execution result."""
data: dict[str, Any] | None
errors: list[GraphQLError] | None
pending: list[PendingResult]
has_next: bool
extensions: dict[str, Any] | None
__slots__ = "data", "errors", "extensions", "has_next", "pending"
def __init__(
self,
data: dict[str, Any] | None = None,
errors: list[GraphQLError] | None = None,
pending: list[PendingResult] | None = None,
has_next: bool = False,
extensions: dict[str, Any] | None = None,
) -> None:
self.data = data
self.errors = errors
self.pending = pending or []
self.has_next = has_next
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: list[str] = [f"data={self.data!r}"]
if self.errors:
args.append(f"errors={self.errors!r}")
if self.pending:
args.append(f"pending={self.pending!r}")
if self.has_next:
args.append("has_next")
if self.extensions:
args.append(f"extensions={self.extensions!r}")
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]
formatted["pending"] = [pending.formatted for pending in self.pending]
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") or None) == (self.errors or None)
and (other.get("pending") or None) == (self.pending or None)
and (other.get("hasNext") or None) == (self.has_next or None)
and (other.get("extensions") or None) == (self.extensions or None)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (
self.data,
self.errors,
self.pending,
self.has_next,
self.extensions,
)[:size]
== other
)
return (
isinstance(other, self.__class__)
and other.data == self.data
and other.errors == self.errors
and other.pending == self.pending
and other.has_next == self.has_next
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
class ExperimentalIncrementalExecutionResults(NamedTuple):
"""Execution results when retrieved incrementally."""
initial_result: InitialIncrementalExecutionResult
subsequent_results: AsyncGenerator[SubsequentIncrementalExecutionResult, None]
class FormattedIncrementalDeferResult(TypedDict, total=False):
"""Formatted incremental deferred execution result"""
data: dict[str, Any]
id: str
subPath: list[str | int]
errors: list[GraphQLFormattedError]
extensions: dict[str, Any]
class IncrementalDeferResult:
"""Incremental deferred execution result"""
data: dict[str, Any]
id: str
sub_path: list[str | int] | None
errors: list[GraphQLError] | None
extensions: dict[str, Any] | None
__slots__ = "data", "errors", "extensions", "id", "sub_path"
def __init__(
self,
data: dict[str, Any],
id: str, # noqa: A002
sub_path: list[str | int] | None = None,
errors: list[GraphQLError] | None = None,
extensions: dict[str, Any] | None = None,
) -> None:
self.data = data
self.id = id
self.sub_path = sub_path
self.errors = errors
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: list[str] = [f"data={self.data!r}, id={self.id!r}"]
if self.sub_path is not None:
args.append(f"sub_path={self.sub_path!r}")
if self.errors is not None:
args.append(f"errors={self.errors!r}")
if self.extensions is not None:
args.append(f"extensions={self.extensions!r}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedIncrementalDeferResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedIncrementalDeferResult = {
"data": self.data,
"id": self.id,
}
if self.sub_path is not None:
formatted["subPath"] = self.sub_path
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):
return (
other.get("data") == self.data
and other.get("id") == self.id
and (other.get("subPath") or None) == (self.sub_path or None)
and (other.get("errors") or None) == (self.errors or None)
and (other.get("extensions") or None) == (self.extensions or None)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (self.data, self.id, self.sub_path, self.errors, self.extensions)[
:size
]
== other
)
return (
isinstance(other, self.__class__)
and other.data == self.data
and other.id == self.id
and other.sub_path == self.sub_path
and other.errors == self.errors
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: list[Any]
id: str
subPath: list[str | int]
errors: list[GraphQLFormattedError]
extensions: dict[str, Any]
class IncrementalStreamResult:
"""Incremental streamed execution result"""
items: list[Any]
id: str
sub_path: list[str | int] | None
errors: list[GraphQLError] | None
extensions: dict[str, Any] | None
__slots__ = "errors", "extensions", "id", "items", "label", "sub_path"
def __init__(
self,
items: list[Any],
id: str, # noqa: A002
sub_path: list[str | int] | None = None,
errors: list[GraphQLError] | None = None,
extensions: dict[str, Any] | None = None,
) -> None:
self.items = items
self.id = id
self.sub_path = sub_path
self.errors = errors
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: list[str] = [f"items={self.items!r}, id={self.id!r}"]
if self.sub_path is not None:
args.append(f"sub_path={self.sub_path!r}")
if self.errors is not None:
args.append(f"errors={self.errors!r}")
if self.extensions is not None:
args.append(f"extensions={self.extensions!r}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedIncrementalStreamResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedIncrementalStreamResult = {
"items": self.items,
"id": self.id,
}
if self.sub_path is not None:
formatted["subPath"] = self.sub_path
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):
return (
other.get("items") == self.items
and other.get("id") == self.id
and (other.get("subPath", None) == (self.sub_path or None))
and (other.get("errors") or None) == (self.errors or None)
and (other.get("extensions", None) == (self.extensions or None))
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (self.items, self.id, self.sub_path, self.errors, self.extensions)[
:size
]
== other
)
return (
isinstance(other, self.__class__)
and other.items == self.items
and other.id == self.id
and other.sub_path == self.sub_path
and other.errors == self.errors
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
FormattedIncrementalResult = Union[
FormattedIncrementalDeferResult, FormattedIncrementalStreamResult
]
IncrementalResult = Union[IncrementalDeferResult, IncrementalStreamResult]
class FormattedSubsequentIncrementalExecutionResult(TypedDict, total=False):
"""Formatted subsequent incremental execution result"""
hasNext: bool
pending: list[FormattedPendingResult]
incremental: list[FormattedIncrementalResult]
completed: list[FormattedCompletedResult]
extensions: dict[str, Any]
class SubsequentIncrementalExecutionResult:
"""Subsequent incremental execution result."""
__slots__ = "completed", "extensions", "has_next", "incremental", "pending"
has_next: bool
pending: list[PendingResult] | None
incremental: list[IncrementalResult] | None
completed: list[CompletedResult] | None
extensions: dict[str, Any] | None
def __init__(
self,
has_next: bool = False,
pending: list[PendingResult] | None = None,
incremental: list[IncrementalResult] | None = None,
completed: list[CompletedResult] | None = None,
extensions: dict[str, Any] | None = None,
) -> None:
self.has_next = has_next
self.pending = pending or []
self.incremental = incremental
self.completed = completed
self.extensions = extensions
def __repr__(self) -> str:
name = self.__class__.__name__
args: list[str] = []
if self.has_next:
args.append("has_next")
if self.pending:
args.append(f"pending[{len(self.pending)}]")
if self.incremental:
args.append(f"incremental[{len(self.incremental)}]")
if self.completed:
args.append(f"completed[{len(self.completed)}]")
if self.extensions:
args.append(f"extensions={self.extensions!r}")
return f"{name}({', '.join(args)})"
@property
def formatted(self) -> FormattedSubsequentIncrementalExecutionResult:
"""Get execution result formatted according to the specification."""
formatted: FormattedSubsequentIncrementalExecutionResult = {}
formatted["hasNext"] = self.has_next
if self.pending:
formatted["pending"] = [result.formatted for result in self.pending]
if self.incremental:
formatted["incremental"] = [result.formatted for result in self.incremental]
if self.completed:
formatted["completed"] = [result.formatted for result in self.completed]
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("hasNext") or None) == (self.has_next or None)
and (other.get("pending") or None) == (self.pending or None)
and (other.get("incremental") or None) == (self.incremental or None)
and (other.get("completed") or None) == (self.completed or None)
and (other.get("extensions") or None) == (self.extensions or None)
)
if isinstance(other, tuple):
size = len(other)
return (
1 < size < 6
and (
self.has_next,
self.pending,
self.incremental,
self.completed,
self.extensions,
)[:size]
== other
)
return (
isinstance(other, self.__class__)
and other.has_next == self.has_next
and self.pending == other.pending
and other.incremental == self.incremental
and other.completed == self.completed
and other.extensions == self.extensions
)
def __ne__(self, other: object) -> bool:
return not self == other
class InitialResult(NamedTuple):
"""The state of the initial result"""
children: dict[IncrementalDataRecord, None]
is_completed: bool
class IncrementalPublisher:
"""Publish incremental results.
This class is used to publish incremental results to the client, enabling
semi-concurrent execution while preserving result order.
The internal publishing state is managed as follows:
``_released``: the set of Subsequent Result records that are ready to be sent to the
client, i.e. their parents have completed and they have also completed.
``_pending``: the set of Subsequent Result records that are definitely pending, i.e.
their parents have completed so that they can no longer be filtered. This includes
all Subsequent Result records in `released`, as well as the records that have not
yet completed.
Note: Instead of sets we use dicts (with values set to None) which preserve order
and thereby achieve more deterministic results.
"""
_next_id: int
_released: dict[SubsequentResultRecord, None]
_pending: dict[SubsequentResultRecord, None]
_resolve: Event | None
_tasks: set[Awaitable]
def __init__(self) -> None:
self._next_id = 0
self._released = {}
self._pending = {}
self._resolve = None # lazy initialization
self._tasks = set()
@staticmethod
def report_new_defer_fragment_record(
deferred_fragment_record: DeferredFragmentRecord,
parent_incremental_result_record: InitialResultRecord
| DeferredFragmentRecord
| StreamItemsRecord,
) -> None:
"""Report a new deferred fragment record."""
parent_incremental_result_record.children[deferred_fragment_record] = None
@staticmethod
def report_new_deferred_grouped_filed_set_record(
deferred_grouped_field_set_record: DeferredGroupedFieldSetRecord,
) -> None:
"""Report a new deferred grouped field set record."""
for (
deferred_fragment_record
) in deferred_grouped_field_set_record.deferred_fragment_records:
deferred_fragment_record._pending[deferred_grouped_field_set_record] = None # noqa: SLF001
deferred_fragment_record.deferred_grouped_field_set_records[
deferred_grouped_field_set_record
] = None
@staticmethod
def report_new_stream_items_record(
stream_items_record: StreamItemsRecord,
parent_incremental_data_record: IncrementalDataRecord,
) -> None:
"""Report a new stream items record."""
if isinstance(parent_incremental_data_record, DeferredGroupedFieldSetRecord):
for parent in parent_incremental_data_record.deferred_fragment_records:
parent.children[stream_items_record] = None
else:
parent_incremental_data_record.children[stream_items_record] = None
def complete_deferred_grouped_field_set(
self,
deferred_grouped_field_set_record: DeferredGroupedFieldSetRecord,
data: dict[str, Any],
) -> None:
"""Complete the given deferred grouped field set record with the given data."""
deferred_grouped_field_set_record.data = data
for (
deferred_fragment_record
) in deferred_grouped_field_set_record.deferred_fragment_records:
pending = deferred_fragment_record._pending # noqa: SLF001
del pending[deferred_grouped_field_set_record]
if not pending:
self.complete_deferred_fragment_record(deferred_fragment_record)
def mark_errored_deferred_grouped_field_set(
self,
deferred_grouped_field_set_record: DeferredGroupedFieldSetRecord,
error: GraphQLError,
) -> None:
"""Mark the given deferred grouped field set record as errored."""
for (
deferred_fragment_record
) in deferred_grouped_field_set_record.deferred_fragment_records:
deferred_fragment_record.errors.append(error)
self.complete_deferred_fragment_record(deferred_fragment_record)
def complete_deferred_fragment_record(
self, deferred_fragment_record: DeferredFragmentRecord
) -> None:
"""Complete the given deferred fragment record."""
self._release(deferred_fragment_record)
def complete_stream_items_record(
self,
stream_items_record: StreamItemsRecord,
items: list[Any],
) -> None:
"""Complete the given stream items record."""
stream_items_record.items = items
stream_items_record.is_completed = True
self._release(stream_items_record)
def mark_errored_stream_items_record(
self, stream_items_record: StreamItemsRecord, error: GraphQLError
) -> None:
"""Mark the given stream items record as errored."""
stream_items_record.stream_record.errors.append(error)
self.set_is_final_record(stream_items_record)
stream_items_record.is_completed = True
early_return = stream_items_record.stream_record.early_return
if early_return:
self._add_task(early_return())
self._release(stream_items_record)
@staticmethod
def set_is_final_record(stream_items_record: StreamItemsRecord) -> None:
"""Mark stream items record as final."""
stream_items_record.is_final_record = True
def set_is_completed_async_iterator(
self, stream_items_record: StreamItemsRecord
) -> None:
"""Mark async iterator for stream items as completed."""
stream_items_record.is_completed_async_iterator = True
self.set_is_final_record(stream_items_record)
def add_field_error(
self, incremental_data_record: IncrementalDataRecord, error: GraphQLError
) -> None:
"""Add a field error to the given incremental data record."""
incremental_data_record.errors.append(error)
def build_data_response(
self, initial_result_record: InitialResultRecord, data: dict[str, Any] | None
) -> ExecutionResult | ExperimentalIncrementalExecutionResults:
"""Build response for the given data."""
for child in initial_result_record.children:
if child.filtered:
continue
self._publish(child)
errors = initial_result_record.errors or None
if errors:
errors.sort(
key=lambda error: (
error.locations or [],
error.path or [],
error.message,
)
)
pending = self._pending
if pending:
pending_sources: RefSet[DeferredFragmentRecord | StreamRecord] = RefSet(
subsequent_result_record.stream_record
if isinstance(subsequent_result_record, StreamItemsRecord)
else subsequent_result_record
for subsequent_result_record in pending
)
return ExperimentalIncrementalExecutionResults(
initial_result=InitialIncrementalExecutionResult(
data,
errors,
pending=self._pending_sources_to_results(pending_sources),
has_next=True,
),
subsequent_results=self._subscribe(),
)
return ExecutionResult(data, errors)
def build_error_response(
self, initial_result_record: InitialResultRecord, error: GraphQLError
) -> ExecutionResult:
"""Build response for the given error."""
errors = initial_result_record.errors
errors.append(error)
# 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(None, errors)
def filter(
self,
null_path: Path | None,
erroring_incremental_data_record: IncrementalDataRecord,
) -> None:
"""Filter out the given erroring incremental data record."""
null_path_list = null_path.as_list() if null_path else []
streams: list[StreamRecord] = []
children = self._get_children(erroring_incremental_data_record)
descendants = self._get_descendants(children)
for child in descendants:
if not self._nulls_child_subsequent_result_record(child, null_path_list):
continue
child.filtered = True
if isinstance(child, StreamItemsRecord):
streams.append(child.stream_record)
early_returns = []
for stream in streams:
early_return = stream.early_return
if early_return:
early_returns.append(early_return())
if early_returns:
self._add_task(gather(*early_returns))
def _pending_sources_to_results(
self,
pending_sources: RefSet[DeferredFragmentRecord | StreamRecord],
) -> list[PendingResult]:
"""Convert pending sources to pending results."""
pending_results: list[PendingResult] = []
for pending_source in pending_sources:
pending_source.pending_sent = True
id_ = self._get_next_id()
pending_source.id = id_
pending_results.append(
PendingResult(id_, pending_source.path, pending_source.label)
)
return pending_results
def _get_next_id(self) -> str:
"""Get the next ID for pending results."""
id_ = self._next_id
self._next_id += 1
return str(id_)
async def _subscribe(
self,
) -> AsyncGenerator[SubsequentIncrementalExecutionResult, None]:
"""Subscribe to the incremental results."""
is_done = False
pending = self._pending
await sleep(0) # execute pending tasks
try:
while not is_done:
released = self._released
for item in released:
with suppress_key_error:
del pending[item]
self._released = {}
result = self._get_incremental_result(released)
if not self._pending:
is_done = True
if result is not None:
yield result
else:
resolve = self._resolve
if resolve is None:
self._resolve = resolve = Event()
await resolve.wait()
finally:
streams: list[StreamRecord] = []
descendants = self._get_descendants(pending)
for subsequent_result_record in descendants: # pragma: no cover
if isinstance(subsequent_result_record, StreamItemsRecord):
streams.append(subsequent_result_record.stream_record)
early_returns = []
for stream in streams: # pragma: no cover
early_return = stream.early_return
if early_return:
early_returns.append(early_return())
if early_returns: # pragma: no cover
await gather(*early_returns)
def _trigger(self) -> None:
"""Trigger the resolve event."""
resolve = self._resolve
if resolve is not None:
resolve.set()
self._resolve = Event()
def _introduce(self, item: SubsequentResultRecord) -> None:
"""Introduce a new IncrementalDataRecord."""
self._pending[item] = None
def _release(self, item: SubsequentResultRecord) -> None:
"""Release the given IncrementalDataRecord."""
if item in self._pending:
self._released[item] = None
self._trigger()
def _push(self, item: SubsequentResultRecord) -> None:
"""Push the given IncrementalDataRecord."""
self._released[item] = None
self._pending[item] = None
self._trigger()
def _get_incremental_result(
self, completed_records: Collection[SubsequentResultRecord]
) -> SubsequentIncrementalExecutionResult | None:
"""Get the incremental result with the completed records."""
update = self._process_pending(completed_records)
pending, incremental, completed = (
update.pending,
update.incremental,
update.completed,
)
has_next = bool(self._pending)
if not incremental and not completed and has_next:
return None
return SubsequentIncrementalExecutionResult(
has_next, pending or None, incremental or None, completed or None
)
def _process_pending(
self,
completed_records: Collection[SubsequentResultRecord],
) -> IncrementalUpdate:
"""Process the pending records."""
new_pending_sources: RefSet[DeferredFragmentRecord | StreamRecord] = RefSet()
incremental_results: list[IncrementalResult] = []
completed_results: list[CompletedResult] = []
to_result = self._completed_record_to_result
for subsequent_result_record in completed_records:
for child in subsequent_result_record.children:
if child.filtered:
continue
pending_source: DeferredFragmentRecord | StreamRecord = (