Skip to content

Commit

Permalink
upgrade executor to non-duplicating incremental delivery format
Browse files Browse the repository at this point in the history
includes granular options to allow for prior branching format
  • Loading branch information
yaacovCR committed Jul 28, 2024
1 parent f9dca5b commit 903dead
Show file tree
Hide file tree
Showing 30 changed files with 6,614 additions and 1,528 deletions.
14 changes: 14 additions & 0 deletions .changeset/fifty-bobcats-jog.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
---
'@graphql-tools/executor': major
'@graphql-tools/utils': minor
---

Upgrade to non-duplicating Incremental Delivery format

## Description

GraphQL Incremental Delivery is moving to a [new response format without duplication](https://github.com/graphql/defer-stream-wg/discussions/69).

This PR updates the executor within graphql-tools to follow the new format, a BREAKING CHANGE.

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.
4 changes: 2 additions & 2 deletions packages/delegate/src/defaultMergedResolver.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ import {
responsePathAsArray,
SelectionSetNode,
} from 'graphql';
import { getResponseKeyFromInfo, isPromise } from '@graphql-tools/utils';
import { createDeferred, DelegationPlanLeftOver, getPlanLeftOverFromParent } from './leftOver.js';
import { createDeferred, getResponseKeyFromInfo, isPromise } from '@graphql-tools/utils';
import { DelegationPlanLeftOver, getPlanLeftOverFromParent } from './leftOver.js';
import {
getSubschema,
getUnpathedErrors,
Expand Down
17 changes: 1 addition & 16 deletions packages/delegate/src/leftOver.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,8 @@
import { FieldNode } from 'graphql';
import { Deferred } from '@graphql-tools/utils';
import { Subschema } from './Subschema.js';
import { DelegationPlanBuilder, ExternalObject } from './types.js';

export type Deferred<T = unknown> = PromiseWithResolvers<T>;

// TODO: Remove this after Node 22
export function createDeferred<T>(): Deferred<T> {
if (Promise.withResolvers) {
return Promise.withResolvers();
}
let resolve: (value: T | PromiseLike<T>) => void;
let reject: (error: unknown) => void;
const promise = new Promise<T>((_resolve, _reject) => {
resolve = _resolve;
reject = _reject;
});
return { promise, resolve: resolve!, reject: reject! };
}

export interface DelegationPlanLeftOver {
unproxiableFieldNodes: Array<FieldNode>;
nonProxiableSubschemas: Array<Subschema>;
Expand Down
17 changes: 17 additions & 0 deletions packages/executor/src/execution/AccumulatorMap.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* ES6 Map with additional `add` method to accumulate items.
*/
export class AccumulatorMap<K, T> extends Map<K, Array<T>> {
get [Symbol.toStringTag]() {
return 'AccumulatorMap';
}

add(key: K, item: T): void {
const group = this.get(key);
if (group === undefined) {
this.set(key, [item]);
} else {
group.push(item);
}
}
}
25 changes: 25 additions & 0 deletions packages/executor/src/execution/BoxedPromiseOrValue.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { isPromise } from '@graphql-tools/utils';
import type { MaybePromise } from '@graphql-tools/utils';

/**
* A BoxedPromiseOrValue is a container for a value or promise where the value
* will be updated when the promise resolves.
*
* A BoxedPromiseOrValue may only be used with promises whose possible
* rejection has already been handled, otherwise this will lead to unhandled
* promise rejections.
*
* @internal
* */
export class BoxedPromiseOrValue<T> {
value: MaybePromise<T>;

constructor(value: MaybePromise<T>) {
this.value = value;
if (isPromise(value)) {
value.then(resolved => {
this.value = resolved;
});
}
}
}
294 changes: 294 additions & 0 deletions packages/executor/src/execution/IncrementalGraph.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,294 @@
import type { GraphQLError } from 'graphql';
import { createDeferred, isPromise } from '@graphql-tools/utils';
import { BoxedPromiseOrValue } from './BoxedPromiseOrValue.js';
import { invariant } from './invariant.js';
import type {
CompletedExecutionGroup,
DeferredFragmentRecord,
DeliveryGroup,
IncrementalDataRecord,
IncrementalDataRecordResult,
PendingExecutionGroup,
StreamItemRecord,
StreamRecord,
SuccessfulExecutionGroup,
} from './types.js';
import { isDeferredFragmentRecord, isPendingExecutionGroup } from './types.js';

/**
* @internal
*/
export class IncrementalGraph {
private _rootNodes: Set<DeliveryGroup>;

private _completedQueue: Array<IncrementalDataRecordResult>;
private _nextQueue: Array<(iterable: Iterable<IncrementalDataRecordResult> | undefined) => void>;

constructor() {
this._rootNodes = new Set();
this._completedQueue = [];
this._nextQueue = [];
}

getNewPending(
incrementalDataRecords: ReadonlyArray<IncrementalDataRecord>,
): ReadonlyArray<DeliveryGroup> {
const initialResultChildren = new Set<DeliveryGroup>();
this._addIncrementalDataRecords(incrementalDataRecords, undefined, initialResultChildren);
return this._promoteNonEmptyToRoot(initialResultChildren);
}

addCompletedSuccessfulExecutionGroup(successfulExecutionGroup: SuccessfulExecutionGroup): void {
const { pendingExecutionGroup, incrementalDataRecords } = successfulExecutionGroup;

const deferredFragmentRecords = pendingExecutionGroup.deferredFragmentRecords;

for (const deferredFragmentRecord of deferredFragmentRecords) {
const { pendingExecutionGroups, successfulExecutionGroups } = deferredFragmentRecord;
pendingExecutionGroups.delete(successfulExecutionGroup.pendingExecutionGroup);
successfulExecutionGroups.add(successfulExecutionGroup);
}

if (incrementalDataRecords !== undefined) {
this._addIncrementalDataRecords(incrementalDataRecords, deferredFragmentRecords);
}
}

*currentCompletedBatch(): Generator<IncrementalDataRecordResult> {
let completed;
while ((completed = this._completedQueue.shift()) !== undefined) {
yield completed;
}
if (this._rootNodes.size === 0) {
for (const resolve of this._nextQueue) {
resolve(undefined);
}
}
}

nextCompletedBatch(): Promise<Iterable<IncrementalDataRecordResult> | undefined> {
const { promise, resolve } = createDeferred<
Iterable<IncrementalDataRecordResult> | undefined
>();
this._nextQueue.push(resolve);
return promise;
}

abort(): void {
for (const resolve of this._nextQueue) {
resolve(undefined);
}
}

hasNext(): boolean {
return this._rootNodes.size > 0;
}

completeDeferredFragment(deferredFragmentRecord: DeferredFragmentRecord):
| {
newPending: ReadonlyArray<DeliveryGroup>;
successfulExecutionGroups: ReadonlyArray<SuccessfulExecutionGroup>;
}
| undefined {
if (
!this._rootNodes.has(deferredFragmentRecord) ||
deferredFragmentRecord.pendingExecutionGroups.size > 0
) {
return;
}
const successfulExecutionGroups = Array.from(deferredFragmentRecord.successfulExecutionGroups);
this._rootNodes.delete(deferredFragmentRecord);
for (const successfulExecutionGroup of successfulExecutionGroups) {
for (const otherDeferredFragmentRecord of successfulExecutionGroup.pendingExecutionGroup
.deferredFragmentRecords) {
otherDeferredFragmentRecord.successfulExecutionGroups.delete(successfulExecutionGroup);
}
}
const newPending = this._promoteNonEmptyToRoot(deferredFragmentRecord.children);
return { newPending, successfulExecutionGroups };
}

removeDeferredFragment(deferredFragmentRecord: DeferredFragmentRecord): boolean {
if (!this._rootNodes.has(deferredFragmentRecord)) {
return false;
}
this._rootNodes.delete(deferredFragmentRecord);
return true;
}

removeStream(streamRecord: StreamRecord): void {
this._rootNodes.delete(streamRecord);
}

private _addIncrementalDataRecords(
incrementalDataRecords: ReadonlyArray<IncrementalDataRecord>,
parents: ReadonlyArray<DeferredFragmentRecord> | undefined,
initialResultChildren?: Set<DeliveryGroup> | undefined,
): void {
for (const incrementalDataRecord of incrementalDataRecords) {
if (isPendingExecutionGroup(incrementalDataRecord)) {
for (const deferredFragmentRecord of incrementalDataRecord.deferredFragmentRecords) {
this._addDeferredFragment(deferredFragmentRecord, initialResultChildren);
deferredFragmentRecord.pendingExecutionGroups.add(incrementalDataRecord);
}
if (this._hasPendingFragment(incrementalDataRecord)) {
this._onExecutionGroup(incrementalDataRecord);
}
} else if (parents === undefined) {
invariant(initialResultChildren !== undefined);
initialResultChildren.add(incrementalDataRecord);
} else {
for (const parent of parents) {
this._addDeferredFragment(parent, initialResultChildren);
parent.children.add(incrementalDataRecord);
}
}
}
}

private _promoteNonEmptyToRoot(
maybeEmptyNewPending: Set<DeliveryGroup>,
): ReadonlyArray<DeliveryGroup> {
const newPending: Array<DeliveryGroup> = [];
for (const deliveryGroup of maybeEmptyNewPending) {
if (isDeferredFragmentRecord(deliveryGroup)) {
if (deliveryGroup.pendingExecutionGroups.size > 0) {
deliveryGroup.setAsPending();
for (const pendingExecutionGroup of deliveryGroup.pendingExecutionGroups) {
if (!this._hasPendingFragment(pendingExecutionGroup)) {
this._onExecutionGroup(pendingExecutionGroup);
}
}
this._rootNodes.add(deliveryGroup);
newPending.push(deliveryGroup);
continue;
}
for (const child of deliveryGroup.children) {
maybeEmptyNewPending.add(child);
}
} else {
this._rootNodes.add(deliveryGroup);
newPending.push(deliveryGroup);

this._onStreamItems(deliveryGroup);
}
}
return newPending;
}

private _hasPendingFragment(pendingExecutionGroup: PendingExecutionGroup): boolean {
return pendingExecutionGroup.deferredFragmentRecords.some(deferredFragmentRecord =>
this._rootNodes.has(deferredFragmentRecord),
);
}

private _addDeferredFragment(
deferredFragmentRecord: DeferredFragmentRecord,
deliveryGroups: Set<DeliveryGroup> | undefined,
): void {
if (this._rootNodes.has(deferredFragmentRecord)) {
return;
}
const parent = deferredFragmentRecord.parent;
if (parent === undefined) {
invariant(deliveryGroups !== undefined);
deliveryGroups.add(deferredFragmentRecord);
return;
}
parent.children.add(deferredFragmentRecord);
this._addDeferredFragment(parent, deliveryGroups);
}

private _onExecutionGroup(pendingExecutionGroup: PendingExecutionGroup): void {
const result = (pendingExecutionGroup.result as BoxedPromiseOrValue<CompletedExecutionGroup>)
.value;
if (isPromise(result)) {
result.then(resolved => this._enqueue(resolved));
} else {
this._enqueue(result);
}
}

private async _onStreamItems(streamRecord: StreamRecord): Promise<void> {
let items: Array<unknown> = [];
let errors: Array<GraphQLError> = [];
let incrementalDataRecords: Array<IncrementalDataRecord> = [];
const streamItemQueue = streamRecord.streamItemQueue;
let streamItemRecord: StreamItemRecord | undefined;
while ((streamItemRecord = streamItemQueue.shift()) !== undefined) {
let result =
streamItemRecord instanceof BoxedPromiseOrValue
? streamItemRecord.value
: streamItemRecord().value;
if (isPromise(result)) {
if (items.length > 0) {
this._enqueue({
streamRecord,
result:
// TODO add additional test case or rework for coverage
errors.length > 0 /* c8 ignore start */
? { items, errors } /* c8 ignore stop */
: { items },
incrementalDataRecords,
});
items = [];
errors = [];
incrementalDataRecords = [];
}
result = await result;
// wait an additional tick to coalesce resolving additional promises
// within the queue
await Promise.resolve();
}
if (result.item === undefined) {
if (items.length > 0) {
this._enqueue({
streamRecord,
result: errors.length > 0 ? { items, errors } : { items },
incrementalDataRecords,
});
}
this._enqueue(
result.errors === undefined
? { streamRecord }
: {
streamRecord,
errors: result.errors,
},
);
return;
}
items.push(result.item);
if (result.errors !== undefined) {
errors.push(...result.errors);
}
if (result.incrementalDataRecords !== undefined) {
incrementalDataRecords.push(...result.incrementalDataRecords);
}
}
}

private *_yieldCurrentCompletedIncrementalData(
first: IncrementalDataRecordResult,
): Generator<IncrementalDataRecordResult> {
yield first;
let completed;
while ((completed = this._completedQueue.shift()) !== undefined) {
yield completed;
}
if (this._rootNodes.size === 0) {
for (const resolve of this._nextQueue) {
resolve(undefined);
}
}
}

private _enqueue(completed: IncrementalDataRecordResult): void {
const next = this._nextQueue.shift();
if (next !== undefined) {
next(this._yieldCurrentCompletedIncrementalData(completed));
return;
}
this._completedQueue.push(completed);
}
}
Loading

0 comments on commit 903dead

Please sign in to comment.