Skip to content

Commit 7eb3ec0

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

File tree

4 files changed

+352
-20
lines changed

4 files changed

+352
-20
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/subscription/__tests__/subscribe-test.ts

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

82-
function createSubscription(pubsub: SimplePubSub<Email>) {
82+
function createSubscription(
83+
pubsub: SimplePubSub<Email>,
84+
variableValues?: { readonly [variable: string]: unknown },
85+
) {
8386
const document = parse(`
84-
subscription ($priority: Int = 0) {
87+
subscription ($priority: Int = 0, $shouldDefer: Boolean = false) {
8588
importantEmail(priority: $priority) {
8689
email {
8790
from
8891
subject
8992
}
90-
inbox {
91-
unread
92-
total
93+
... @defer(if: $shouldDefer) {
94+
inbox {
95+
unread
96+
total
97+
}
9398
}
9499
}
95100
}
@@ -119,7 +124,12 @@ function createSubscription(pubsub: SimplePubSub<Email>) {
119124
}),
120125
};
121126

122-
return subscribe({ schema: emailSchema, document, rootValue: data });
127+
return subscribe({
128+
schema: emailSchema,
129+
document,
130+
rootValue: data,
131+
variableValues,
132+
});
123133
}
124134

125135
async function expectPromise(promise: Promise<unknown>) {
@@ -616,6 +626,136 @@ describe('Subscription Publish Phase', () => {
616626
});
617627
});
618628

629+
it('produces additional payloads for subscriptions with @defer', async () => {
630+
const pubsub = new SimplePubSub<Email>();
631+
const subscription = await createSubscription(pubsub, {
632+
shouldDefer: true,
633+
});
634+
invariant(isAsyncIterable(subscription));
635+
// Wait for the next subscription payload.
636+
const payload = subscription.next();
637+
638+
// A new email arrives!
639+
expect(
640+
pubsub.emit({
641+
from: 'yuzhi@graphql.org',
642+
subject: 'Alright',
643+
message: 'Tests are good',
644+
unread: true,
645+
}),
646+
).to.equal(true);
647+
648+
// The previously waited on payload now has a value.
649+
expect(await payload).to.deep.equal({
650+
done: false,
651+
value: {
652+
data: {
653+
importantEmail: {
654+
email: {
655+
from: 'yuzhi@graphql.org',
656+
subject: 'Alright',
657+
},
658+
},
659+
},
660+
hasNext: true,
661+
},
662+
});
663+
664+
// Wait for the next payload from @defer
665+
expect(await subscription.next()).to.deep.equal({
666+
done: false,
667+
value: {
668+
data: {
669+
inbox: {
670+
unread: 1,
671+
total: 2,
672+
},
673+
},
674+
path: ['importantEmail'],
675+
hasNext: false,
676+
},
677+
});
678+
679+
// Another new email arrives, after all incrementally delivered payloads are received.
680+
expect(
681+
pubsub.emit({
682+
from: 'hyo@graphql.org',
683+
subject: 'Tools',
684+
message: 'I <3 making things',
685+
unread: true,
686+
}),
687+
).to.equal(true);
688+
689+
// The next waited on payload will have a value.
690+
expect(await subscription.next()).to.deep.equal({
691+
done: false,
692+
value: {
693+
data: {
694+
importantEmail: {
695+
email: {
696+
from: 'hyo@graphql.org',
697+
subject: 'Tools',
698+
},
699+
},
700+
},
701+
hasNext: true,
702+
},
703+
});
704+
705+
// Another new email arrives, before the incrementally delivered payloads from the last email was received.
706+
expect(
707+
pubsub.emit({
708+
from: 'adam@graphql.org',
709+
subject: 'Important',
710+
message: 'Read me please',
711+
unread: true,
712+
}),
713+
).to.equal(true);
714+
715+
// Deferred payload from previous event is received.
716+
expect(await subscription.next()).to.deep.equal({
717+
done: false,
718+
value: {
719+
data: {
720+
inbox: {
721+
unread: 2,
722+
total: 3,
723+
},
724+
},
725+
path: ['importantEmail'],
726+
hasNext: false,
727+
},
728+
});
729+
730+
// Next payload from last event
731+
expect(await subscription.next()).to.deep.equal({
732+
done: false,
733+
value: {
734+
data: {
735+
importantEmail: {
736+
email: {
737+
from: 'adam@graphql.org',
738+
subject: 'Important',
739+
},
740+
},
741+
},
742+
hasNext: true,
743+
},
744+
});
745+
746+
// The client disconnects before the deferred payload is consumed.
747+
expect(await subscription.return()).to.deep.equal({
748+
done: true,
749+
value: undefined,
750+
});
751+
752+
// Awaiting a subscription after closing it results in completed results.
753+
expect(await subscription.next()).to.deep.equal({
754+
done: true,
755+
value: undefined,
756+
});
757+
});
758+
619759
it('produces a payload when there are multiple events', async () => {
620760
const pubsub = new SimplePubSub<Email>();
621761
const subscription = await createSubscription(pubsub);
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)