Skip to content

Commit 4d16c4d

Browse files
committed
add defer/stream support for subscriptions (#7)
# Conflicts: # src/subscription/subscribe.ts
1 parent 018a570 commit 4d16c4d

File tree

4 files changed

+348
-19
lines changed

4 files changed

+348
-19
lines changed
Lines changed: 141 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,141 @@
1+
import { expect } from 'chai';
2+
import { describe, it } from 'mocha';
3+
4+
import { flattenAsyncIterator } from '../flattenAsyncIterator';
5+
6+
describe('flattenAsyncIterator', () => {
7+
it('does not modify an already flat async generator', async () => {
8+
async function* source() {
9+
yield await Promise.resolve(1);
10+
yield await Promise.resolve(2);
11+
yield await Promise.resolve(3);
12+
}
13+
14+
const result = flattenAsyncIterator(source());
15+
16+
expect(await result.next()).to.deep.equal({ value: 1, done: false });
17+
expect(await result.next()).to.deep.equal({ value: 2, done: false });
18+
expect(await result.next()).to.deep.equal({ value: 3, done: false });
19+
expect(await result.next()).to.deep.equal({
20+
value: undefined,
21+
done: true,
22+
});
23+
});
24+
25+
it('does not modify an already flat async iterator', async () => {
26+
const items = [1, 2, 3];
27+
28+
const iterator: any = {
29+
[Symbol.asyncIterator]() {
30+
return this;
31+
},
32+
next() {
33+
return Promise.resolve({
34+
done: items.length === 0,
35+
value: items.shift(),
36+
});
37+
},
38+
};
39+
40+
const result = flattenAsyncIterator(iterator);
41+
42+
expect(await result.next()).to.deep.equal({ value: 1, done: false });
43+
expect(await result.next()).to.deep.equal({ value: 2, done: false });
44+
expect(await result.next()).to.deep.equal({ value: 3, done: false });
45+
expect(await result.next()).to.deep.equal({
46+
value: undefined,
47+
done: true,
48+
});
49+
});
50+
51+
it('flatten nested async generators', async () => {
52+
async function* source() {
53+
yield await Promise.resolve(1);
54+
yield await Promise.resolve(2);
55+
yield await Promise.resolve(
56+
(async function* nested(): AsyncGenerator<number, void, void> {
57+
yield await Promise.resolve(2.1);
58+
yield await Promise.resolve(2.2);
59+
})(),
60+
);
61+
yield await Promise.resolve(3);
62+
}
63+
64+
const doubles = flattenAsyncIterator(source());
65+
66+
const result = [];
67+
for await (const x of doubles) {
68+
result.push(x);
69+
}
70+
expect(result).to.deep.equal([1, 2, 2.1, 2.2, 3]);
71+
});
72+
73+
it('allows returning early from a nested async generator', async () => {
74+
async function* source() {
75+
yield await Promise.resolve(1);
76+
yield await Promise.resolve(2);
77+
yield await Promise.resolve(
78+
(async function* nested(): AsyncGenerator<number, void, void> {
79+
yield await Promise.resolve(2.1);
80+
// istanbul ignore next (Shouldn't be reached)
81+
yield await Promise.resolve(2.2);
82+
})(),
83+
);
84+
// istanbul ignore next (Shouldn't be reached)
85+
yield await Promise.resolve(3);
86+
}
87+
88+
const doubles = flattenAsyncIterator(source());
89+
90+
expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
91+
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
92+
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });
93+
94+
// Early return
95+
expect(await doubles.return()).to.deep.equal({
96+
value: undefined,
97+
done: true,
98+
});
99+
100+
// Subsequent next calls
101+
expect(await doubles.next()).to.deep.equal({
102+
value: undefined,
103+
done: true,
104+
});
105+
expect(await doubles.next()).to.deep.equal({
106+
value: undefined,
107+
done: true,
108+
});
109+
});
110+
111+
it('allows throwing errors from a nested async generator', async () => {
112+
async function* source() {
113+
yield await Promise.resolve(1);
114+
yield await Promise.resolve(2);
115+
yield await Promise.resolve(
116+
(async function* nested(): AsyncGenerator<number, void, void> {
117+
yield await Promise.resolve(2.1);
118+
// istanbul ignore next (Shouldn't be reached)
119+
yield await Promise.resolve(2.2);
120+
})(),
121+
);
122+
// istanbul ignore next (Shouldn't be reached)
123+
yield await Promise.resolve(3);
124+
}
125+
126+
const doubles = flattenAsyncIterator(source());
127+
128+
expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
129+
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
130+
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });
131+
132+
// Throw error
133+
let caughtError;
134+
try {
135+
await doubles.throw('ouch');
136+
} catch (e) {
137+
caughtError = e;
138+
}
139+
expect(caughtError).to.equal('ouch');
140+
});
141+
});

src/execution/__tests__/subscribe-test.ts

Lines changed: 146 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -80,17 +80,22 @@ const emailSchema = new GraphQLSchema({
8080
}),
8181
});
8282

83-
function createSubscription(pubsub: SimplePubSub<Email>) {
83+
function createSubscription(
84+
pubsub: SimplePubSub<Email>,
85+
variableValues?: { readonly [variable: string]: unknown },
86+
) {
8487
const document = parse(`
85-
subscription ($priority: Int = 0) {
88+
subscription ($priority: Int = 0, $shouldDefer: Boolean = false) {
8689
importantEmail(priority: $priority) {
8790
email {
8891
from
8992
subject
9093
}
91-
inbox {
92-
unread
93-
total
94+
... @defer(if: $shouldDefer) {
95+
inbox {
96+
unread
97+
total
98+
}
9499
}
95100
}
96101
}
@@ -120,7 +125,12 @@ function createSubscription(pubsub: SimplePubSub<Email>) {
120125
}),
121126
};
122127

123-
return subscribe({ schema: emailSchema, document, rootValue: data });
128+
return subscribe({
129+
schema: emailSchema,
130+
document,
131+
rootValue: data,
132+
variableValues,
133+
});
124134
}
125135

126136
async function expectPromise(promise: Promise<unknown>) {
@@ -665,6 +675,136 @@ describe('Subscription Publish Phase', () => {
665675
});
666676
});
667677

678+
it('produces additional payloads for subscriptions with @defer', async () => {
679+
const pubsub = new SimplePubSub<Email>();
680+
const subscription = await createSubscription(pubsub, {
681+
shouldDefer: true,
682+
});
683+
invariant(isAsyncIterable(subscription));
684+
// Wait for the next subscription payload.
685+
const payload = subscription.next();
686+
687+
// A new email arrives!
688+
expect(
689+
pubsub.emit({
690+
from: 'yuzhi@graphql.org',
691+
subject: 'Alright',
692+
message: 'Tests are good',
693+
unread: true,
694+
}),
695+
).to.equal(true);
696+
697+
// The previously waited on payload now has a value.
698+
expect(await payload).to.deep.equal({
699+
done: false,
700+
value: {
701+
data: {
702+
importantEmail: {
703+
email: {
704+
from: 'yuzhi@graphql.org',
705+
subject: 'Alright',
706+
},
707+
},
708+
},
709+
hasNext: true,
710+
},
711+
});
712+
713+
// Wait for the next payload from @defer
714+
expect(await subscription.next()).to.deep.equal({
715+
done: false,
716+
value: {
717+
data: {
718+
inbox: {
719+
unread: 1,
720+
total: 2,
721+
},
722+
},
723+
path: ['importantEmail'],
724+
hasNext: false,
725+
},
726+
});
727+
728+
// Another new email arrives, after all incrementally delivered payloads are received.
729+
expect(
730+
pubsub.emit({
731+
from: 'hyo@graphql.org',
732+
subject: 'Tools',
733+
message: 'I <3 making things',
734+
unread: true,
735+
}),
736+
).to.equal(true);
737+
738+
// The next waited on payload will have a value.
739+
expect(await subscription.next()).to.deep.equal({
740+
done: false,
741+
value: {
742+
data: {
743+
importantEmail: {
744+
email: {
745+
from: 'hyo@graphql.org',
746+
subject: 'Tools',
747+
},
748+
},
749+
},
750+
hasNext: true,
751+
},
752+
});
753+
754+
// Another new email arrives, before the incrementally delivered payloads from the last email was received.
755+
expect(
756+
pubsub.emit({
757+
from: 'adam@graphql.org',
758+
subject: 'Important',
759+
message: 'Read me please',
760+
unread: true,
761+
}),
762+
).to.equal(true);
763+
764+
// Deferred payload from previous event is received.
765+
expect(await subscription.next()).to.deep.equal({
766+
done: false,
767+
value: {
768+
data: {
769+
inbox: {
770+
unread: 2,
771+
total: 3,
772+
},
773+
},
774+
path: ['importantEmail'],
775+
hasNext: false,
776+
},
777+
});
778+
779+
// Next payload from last event
780+
expect(await subscription.next()).to.deep.equal({
781+
done: false,
782+
value: {
783+
data: {
784+
importantEmail: {
785+
email: {
786+
from: 'adam@graphql.org',
787+
subject: 'Important',
788+
},
789+
},
790+
},
791+
hasNext: true,
792+
},
793+
});
794+
795+
// The client disconnects before the deferred payload is consumed.
796+
expect(await subscription.return()).to.deep.equal({
797+
done: true,
798+
value: undefined,
799+
});
800+
801+
// Awaiting a subscription after closing it results in completed results.
802+
expect(await subscription.next()).to.deep.equal({
803+
done: true,
804+
value: undefined,
805+
});
806+
});
807+
668808
it('produces a payload when there are multiple events', async () => {
669809
const pubsub = new SimplePubSub<Email>();
670810
const subscription = await createSubscription(pubsub);

src/execution/flattenAsyncIterator.ts

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import { isAsyncIterable } from '../jsutils/isAsyncIterable';
2+
3+
type AsyncIterableOrGenerator<T> =
4+
| AsyncGenerator<T, void, void>
5+
| AsyncIterable<T>;
6+
7+
/**
8+
* Given an AsyncIterable that could potentially yield other async iterators,
9+
* flatten all yielded results into a single AsyncIterable
10+
*/
11+
export function flattenAsyncIterator<T, AT>(
12+
iterable: AsyncIterableOrGenerator<T | AsyncIterableOrGenerator<AT>>,
13+
): AsyncGenerator<T | AT, void, void> {
14+
const iteratorMethod = iterable[Symbol.asyncIterator];
15+
const iterator: any = iteratorMethod.call(iterable);
16+
let iteratorStack: Array<AsyncIterator<T>> = [iterator];
17+
18+
async function next(): Promise<IteratorResult<T | AT, void>> {
19+
const currentIterator = iteratorStack[0];
20+
if (!currentIterator) {
21+
return { value: undefined, done: true };
22+
}
23+
const result = await currentIterator.next();
24+
if (result.done) {
25+
iteratorStack.shift();
26+
return next();
27+
} else if (isAsyncIterable(result.value)) {
28+
const childIterator = result.value[
29+
Symbol.asyncIterator
30+
]() as AsyncIterator<T>;
31+
iteratorStack.unshift(childIterator);
32+
return next();
33+
}
34+
return result;
35+
}
36+
return {
37+
next,
38+
return() {
39+
iteratorStack = [];
40+
return iterator.return();
41+
},
42+
throw(error?: unknown): Promise<IteratorResult<T | AT>> {
43+
iteratorStack = [];
44+
return iterator.throw(error);
45+
},
46+
[Symbol.asyncIterator]() {
47+
return this;
48+
},
49+
};
50+
}

0 commit comments

Comments
 (0)