Skip to content

Commit 903dead

Browse files
committed
upgrade executor to non-duplicating incremental delivery format
includes granular options to allow for prior branching format
1 parent f9dca5b commit 903dead

30 files changed

Lines changed: 6614 additions & 1528 deletions

.changeset/fifty-bobcats-jog.md

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
---
2+
'@graphql-tools/executor': major
3+
'@graphql-tools/utils': minor
4+
---
5+
6+
Upgrade to non-duplicating Incremental Delivery format
7+
8+
## Description
9+
10+
GraphQL Incremental Delivery is moving to a [new response format without duplication](https://github.com/graphql/defer-stream-wg/discussions/69).
11+
12+
This PR updates the executor within graphql-tools to follow the new format, a BREAKING CHANGE.
13+
14+
Incremental Delivery has now been disabled for subscriptions, also a BREAKING CHANGE. The GraphQL Working Group has decided to disable incremental delivery support for subscriptions (1) to gather more information about use cases and (2) explore how to interleaving the incremental response streams generated from different source events into one overall subscription response stream.

packages/delegate/src/defaultMergedResolver.ts

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,8 @@ import {
55
responsePathAsArray,
66
SelectionSetNode,
77
} from 'graphql';
8-
import { getResponseKeyFromInfo, isPromise } from '@graphql-tools/utils';
9-
import { createDeferred, DelegationPlanLeftOver, getPlanLeftOverFromParent } from './leftOver.js';
8+
import { createDeferred, getResponseKeyFromInfo, isPromise } from '@graphql-tools/utils';
9+
import { DelegationPlanLeftOver, getPlanLeftOverFromParent } from './leftOver.js';
1010
import {
1111
getSubschema,
1212
getUnpathedErrors,

packages/delegate/src/leftOver.ts

Lines changed: 1 addition & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,23 +1,8 @@
11
import { FieldNode } from 'graphql';
2+
import { Deferred } from '@graphql-tools/utils';
23
import { Subschema } from './Subschema.js';
34
import { DelegationPlanBuilder, ExternalObject } from './types.js';
45

5-
export type Deferred<T = unknown> = PromiseWithResolvers<T>;
6-
7-
// TODO: Remove this after Node 22
8-
export function createDeferred<T>(): Deferred<T> {
9-
if (Promise.withResolvers) {
10-
return Promise.withResolvers();
11-
}
12-
let resolve: (value: T | PromiseLike<T>) => void;
13-
let reject: (error: unknown) => void;
14-
const promise = new Promise<T>((_resolve, _reject) => {
15-
resolve = _resolve;
16-
reject = _reject;
17-
});
18-
return { promise, resolve: resolve!, reject: reject! };
19-
}
20-
216
export interface DelegationPlanLeftOver {
227
unproxiableFieldNodes: Array<FieldNode>;
238
nonProxiableSubschemas: Array<Subschema>;
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
/**
2+
* ES6 Map with additional `add` method to accumulate items.
3+
*/
4+
export class AccumulatorMap<K, T> extends Map<K, Array<T>> {
5+
get [Symbol.toStringTag]() {
6+
return 'AccumulatorMap';
7+
}
8+
9+
add(key: K, item: T): void {
10+
const group = this.get(key);
11+
if (group === undefined) {
12+
this.set(key, [item]);
13+
} else {
14+
group.push(item);
15+
}
16+
}
17+
}
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
import { isPromise } from '@graphql-tools/utils';
2+
import type { MaybePromise } from '@graphql-tools/utils';
3+
4+
/**
5+
* A BoxedPromiseOrValue is a container for a value or promise where the value
6+
* will be updated when the promise resolves.
7+
*
8+
* A BoxedPromiseOrValue may only be used with promises whose possible
9+
* rejection has already been handled, otherwise this will lead to unhandled
10+
* promise rejections.
11+
*
12+
* @internal
13+
* */
14+
export class BoxedPromiseOrValue<T> {
15+
value: MaybePromise<T>;
16+
17+
constructor(value: MaybePromise<T>) {
18+
this.value = value;
19+
if (isPromise(value)) {
20+
value.then(resolved => {
21+
this.value = resolved;
22+
});
23+
}
24+
}
25+
}
Lines changed: 294 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,294 @@
1+
import type { GraphQLError } from 'graphql';
2+
import { createDeferred, isPromise } from '@graphql-tools/utils';
3+
import { BoxedPromiseOrValue } from './BoxedPromiseOrValue.js';
4+
import { invariant } from './invariant.js';
5+
import type {
6+
CompletedExecutionGroup,
7+
DeferredFragmentRecord,
8+
DeliveryGroup,
9+
IncrementalDataRecord,
10+
IncrementalDataRecordResult,
11+
PendingExecutionGroup,
12+
StreamItemRecord,
13+
StreamRecord,
14+
SuccessfulExecutionGroup,
15+
} from './types.js';
16+
import { isDeferredFragmentRecord, isPendingExecutionGroup } from './types.js';
17+
18+
/**
19+
* @internal
20+
*/
21+
export class IncrementalGraph {
22+
private _rootNodes: Set<DeliveryGroup>;
23+
24+
private _completedQueue: Array<IncrementalDataRecordResult>;
25+
private _nextQueue: Array<(iterable: Iterable<IncrementalDataRecordResult> | undefined) => void>;
26+
27+
constructor() {
28+
this._rootNodes = new Set();
29+
this._completedQueue = [];
30+
this._nextQueue = [];
31+
}
32+
33+
getNewPending(
34+
incrementalDataRecords: ReadonlyArray<IncrementalDataRecord>,
35+
): ReadonlyArray<DeliveryGroup> {
36+
const initialResultChildren = new Set<DeliveryGroup>();
37+
this._addIncrementalDataRecords(incrementalDataRecords, undefined, initialResultChildren);
38+
return this._promoteNonEmptyToRoot(initialResultChildren);
39+
}
40+
41+
addCompletedSuccessfulExecutionGroup(successfulExecutionGroup: SuccessfulExecutionGroup): void {
42+
const { pendingExecutionGroup, incrementalDataRecords } = successfulExecutionGroup;
43+
44+
const deferredFragmentRecords = pendingExecutionGroup.deferredFragmentRecords;
45+
46+
for (const deferredFragmentRecord of deferredFragmentRecords) {
47+
const { pendingExecutionGroups, successfulExecutionGroups } = deferredFragmentRecord;
48+
pendingExecutionGroups.delete(successfulExecutionGroup.pendingExecutionGroup);
49+
successfulExecutionGroups.add(successfulExecutionGroup);
50+
}
51+
52+
if (incrementalDataRecords !== undefined) {
53+
this._addIncrementalDataRecords(incrementalDataRecords, deferredFragmentRecords);
54+
}
55+
}
56+
57+
*currentCompletedBatch(): Generator<IncrementalDataRecordResult> {
58+
let completed;
59+
while ((completed = this._completedQueue.shift()) !== undefined) {
60+
yield completed;
61+
}
62+
if (this._rootNodes.size === 0) {
63+
for (const resolve of this._nextQueue) {
64+
resolve(undefined);
65+
}
66+
}
67+
}
68+
69+
nextCompletedBatch(): Promise<Iterable<IncrementalDataRecordResult> | undefined> {
70+
const { promise, resolve } = createDeferred<
71+
Iterable<IncrementalDataRecordResult> | undefined
72+
>();
73+
this._nextQueue.push(resolve);
74+
return promise;
75+
}
76+
77+
abort(): void {
78+
for (const resolve of this._nextQueue) {
79+
resolve(undefined);
80+
}
81+
}
82+
83+
hasNext(): boolean {
84+
return this._rootNodes.size > 0;
85+
}
86+
87+
completeDeferredFragment(deferredFragmentRecord: DeferredFragmentRecord):
88+
| {
89+
newPending: ReadonlyArray<DeliveryGroup>;
90+
successfulExecutionGroups: ReadonlyArray<SuccessfulExecutionGroup>;
91+
}
92+
| undefined {
93+
if (
94+
!this._rootNodes.has(deferredFragmentRecord) ||
95+
deferredFragmentRecord.pendingExecutionGroups.size > 0
96+
) {
97+
return;
98+
}
99+
const successfulExecutionGroups = Array.from(deferredFragmentRecord.successfulExecutionGroups);
100+
this._rootNodes.delete(deferredFragmentRecord);
101+
for (const successfulExecutionGroup of successfulExecutionGroups) {
102+
for (const otherDeferredFragmentRecord of successfulExecutionGroup.pendingExecutionGroup
103+
.deferredFragmentRecords) {
104+
otherDeferredFragmentRecord.successfulExecutionGroups.delete(successfulExecutionGroup);
105+
}
106+
}
107+
const newPending = this._promoteNonEmptyToRoot(deferredFragmentRecord.children);
108+
return { newPending, successfulExecutionGroups };
109+
}
110+
111+
removeDeferredFragment(deferredFragmentRecord: DeferredFragmentRecord): boolean {
112+
if (!this._rootNodes.has(deferredFragmentRecord)) {
113+
return false;
114+
}
115+
this._rootNodes.delete(deferredFragmentRecord);
116+
return true;
117+
}
118+
119+
removeStream(streamRecord: StreamRecord): void {
120+
this._rootNodes.delete(streamRecord);
121+
}
122+
123+
private _addIncrementalDataRecords(
124+
incrementalDataRecords: ReadonlyArray<IncrementalDataRecord>,
125+
parents: ReadonlyArray<DeferredFragmentRecord> | undefined,
126+
initialResultChildren?: Set<DeliveryGroup> | undefined,
127+
): void {
128+
for (const incrementalDataRecord of incrementalDataRecords) {
129+
if (isPendingExecutionGroup(incrementalDataRecord)) {
130+
for (const deferredFragmentRecord of incrementalDataRecord.deferredFragmentRecords) {
131+
this._addDeferredFragment(deferredFragmentRecord, initialResultChildren);
132+
deferredFragmentRecord.pendingExecutionGroups.add(incrementalDataRecord);
133+
}
134+
if (this._hasPendingFragment(incrementalDataRecord)) {
135+
this._onExecutionGroup(incrementalDataRecord);
136+
}
137+
} else if (parents === undefined) {
138+
invariant(initialResultChildren !== undefined);
139+
initialResultChildren.add(incrementalDataRecord);
140+
} else {
141+
for (const parent of parents) {
142+
this._addDeferredFragment(parent, initialResultChildren);
143+
parent.children.add(incrementalDataRecord);
144+
}
145+
}
146+
}
147+
}
148+
149+
private _promoteNonEmptyToRoot(
150+
maybeEmptyNewPending: Set<DeliveryGroup>,
151+
): ReadonlyArray<DeliveryGroup> {
152+
const newPending: Array<DeliveryGroup> = [];
153+
for (const deliveryGroup of maybeEmptyNewPending) {
154+
if (isDeferredFragmentRecord(deliveryGroup)) {
155+
if (deliveryGroup.pendingExecutionGroups.size > 0) {
156+
deliveryGroup.setAsPending();
157+
for (const pendingExecutionGroup of deliveryGroup.pendingExecutionGroups) {
158+
if (!this._hasPendingFragment(pendingExecutionGroup)) {
159+
this._onExecutionGroup(pendingExecutionGroup);
160+
}
161+
}
162+
this._rootNodes.add(deliveryGroup);
163+
newPending.push(deliveryGroup);
164+
continue;
165+
}
166+
for (const child of deliveryGroup.children) {
167+
maybeEmptyNewPending.add(child);
168+
}
169+
} else {
170+
this._rootNodes.add(deliveryGroup);
171+
newPending.push(deliveryGroup);
172+
173+
this._onStreamItems(deliveryGroup);
174+
}
175+
}
176+
return newPending;
177+
}
178+
179+
private _hasPendingFragment(pendingExecutionGroup: PendingExecutionGroup): boolean {
180+
return pendingExecutionGroup.deferredFragmentRecords.some(deferredFragmentRecord =>
181+
this._rootNodes.has(deferredFragmentRecord),
182+
);
183+
}
184+
185+
private _addDeferredFragment(
186+
deferredFragmentRecord: DeferredFragmentRecord,
187+
deliveryGroups: Set<DeliveryGroup> | undefined,
188+
): void {
189+
if (this._rootNodes.has(deferredFragmentRecord)) {
190+
return;
191+
}
192+
const parent = deferredFragmentRecord.parent;
193+
if (parent === undefined) {
194+
invariant(deliveryGroups !== undefined);
195+
deliveryGroups.add(deferredFragmentRecord);
196+
return;
197+
}
198+
parent.children.add(deferredFragmentRecord);
199+
this._addDeferredFragment(parent, deliveryGroups);
200+
}
201+
202+
private _onExecutionGroup(pendingExecutionGroup: PendingExecutionGroup): void {
203+
const result = (pendingExecutionGroup.result as BoxedPromiseOrValue<CompletedExecutionGroup>)
204+
.value;
205+
if (isPromise(result)) {
206+
result.then(resolved => this._enqueue(resolved));
207+
} else {
208+
this._enqueue(result);
209+
}
210+
}
211+
212+
private async _onStreamItems(streamRecord: StreamRecord): Promise<void> {
213+
let items: Array<unknown> = [];
214+
let errors: Array<GraphQLError> = [];
215+
let incrementalDataRecords: Array<IncrementalDataRecord> = [];
216+
const streamItemQueue = streamRecord.streamItemQueue;
217+
let streamItemRecord: StreamItemRecord | undefined;
218+
while ((streamItemRecord = streamItemQueue.shift()) !== undefined) {
219+
let result =
220+
streamItemRecord instanceof BoxedPromiseOrValue
221+
? streamItemRecord.value
222+
: streamItemRecord().value;
223+
if (isPromise(result)) {
224+
if (items.length > 0) {
225+
this._enqueue({
226+
streamRecord,
227+
result:
228+
// TODO add additional test case or rework for coverage
229+
errors.length > 0 /* c8 ignore start */
230+
? { items, errors } /* c8 ignore stop */
231+
: { items },
232+
incrementalDataRecords,
233+
});
234+
items = [];
235+
errors = [];
236+
incrementalDataRecords = [];
237+
}
238+
result = await result;
239+
// wait an additional tick to coalesce resolving additional promises
240+
// within the queue
241+
await Promise.resolve();
242+
}
243+
if (result.item === undefined) {
244+
if (items.length > 0) {
245+
this._enqueue({
246+
streamRecord,
247+
result: errors.length > 0 ? { items, errors } : { items },
248+
incrementalDataRecords,
249+
});
250+
}
251+
this._enqueue(
252+
result.errors === undefined
253+
? { streamRecord }
254+
: {
255+
streamRecord,
256+
errors: result.errors,
257+
},
258+
);
259+
return;
260+
}
261+
items.push(result.item);
262+
if (result.errors !== undefined) {
263+
errors.push(...result.errors);
264+
}
265+
if (result.incrementalDataRecords !== undefined) {
266+
incrementalDataRecords.push(...result.incrementalDataRecords);
267+
}
268+
}
269+
}
270+
271+
private *_yieldCurrentCompletedIncrementalData(
272+
first: IncrementalDataRecordResult,
273+
): Generator<IncrementalDataRecordResult> {
274+
yield first;
275+
let completed;
276+
while ((completed = this._completedQueue.shift()) !== undefined) {
277+
yield completed;
278+
}
279+
if (this._rootNodes.size === 0) {
280+
for (const resolve of this._nextQueue) {
281+
resolve(undefined);
282+
}
283+
}
284+
}
285+
286+
private _enqueue(completed: IncrementalDataRecordResult): void {
287+
const next = this._nextQueue.shift();
288+
if (next !== undefined) {
289+
next(this._yieldCurrentCompletedIncrementalData(completed));
290+
return;
291+
}
292+
this._completedQueue.push(completed);
293+
}
294+
}

0 commit comments

Comments
 (0)