Skip to content

Commit a9af64b

Browse files
committed
add defer/stream support for subscriptions
1 parent 7d92217 commit a9af64b

File tree

4 files changed

+355
-19
lines changed

4 files changed

+355
-19
lines changed
Lines changed: 145 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,145 @@
1+
import { expect } from 'chai';
2+
import { describe, it } from 'mocha';
3+
4+
import { flattenAsyncIterable } from '../flattenAsyncIterable';
5+
6+
describe('flattenAsyncIterable', () => {
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 = flattenAsyncIterable(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 = flattenAsyncIterable(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 = flattenAsyncIterable(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); /* c8 ignore start */
80+
// Not reachable, early return
81+
yield await Promise.resolve(2.2);
82+
})(),
83+
);
84+
// Not reachable, early return
85+
yield await Promise.resolve(3);
86+
}
87+
/* c8 ignore stop */
88+
89+
const doubles = flattenAsyncIterable(source());
90+
91+
expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
92+
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
93+
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });
94+
95+
// Early return
96+
expect(await doubles.return()).to.deep.equal({
97+
value: undefined,
98+
done: true,
99+
});
100+
101+
// Subsequent next calls
102+
expect(await doubles.next()).to.deep.equal({
103+
value: undefined,
104+
done: true,
105+
});
106+
expect(await doubles.next()).to.deep.equal({
107+
value: undefined,
108+
done: true,
109+
});
110+
});
111+
112+
it('allows throwing errors from a nested async generator', async () => {
113+
async function* source() {
114+
yield await Promise.resolve(1);
115+
yield await Promise.resolve(2);
116+
yield await Promise.resolve(
117+
(async function* nested(): AsyncGenerator<number, void, void> {
118+
yield await Promise.resolve(2.1); /* c8 ignore start */
119+
// Not reachable, early return
120+
yield await Promise.resolve(2.2);
121+
})(),
122+
);
123+
// Not reachable, early return
124+
yield await Promise.resolve(3);
125+
}
126+
/* c8 ignore stop */
127+
128+
const doubles = flattenAsyncIterable(source());
129+
130+
expect(await doubles.next()).to.deep.equal({ value: 1, done: false });
131+
expect(await doubles.next()).to.deep.equal({ value: 2, done: false });
132+
expect(await doubles.next()).to.deep.equal({ value: 2.1, done: false });
133+
134+
// Throw error
135+
let caughtError;
136+
try {
137+
await doubles.throw('ouch'); /* c8 ignore start */
138+
// Not reachable, always throws
139+
/* c8 ignore stop */
140+
} catch (e) {
141+
caughtError = e;
142+
}
143+
expect(caughtError).to.equal('ouch');
144+
});
145+
});

src/execution/__tests__/subscribe-test.ts

Lines changed: 154 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -84,17 +84,22 @@ const emailSchema = new GraphQLSchema({
8484
}),
8585
});
8686

87-
function createSubscription(pubsub: SimplePubSub<Email>) {
87+
function createSubscription(
88+
pubsub: SimplePubSub<Email>,
89+
variableValues?: { readonly [variable: string]: unknown },
90+
) {
8891
const document = parse(`
89-
subscription ($priority: Int = 0) {
92+
subscription ($priority: Int = 0, $shouldDefer: Boolean = false) {
9093
importantEmail(priority: $priority) {
9194
email {
9295
from
9396
subject
9497
}
95-
inbox {
96-
unread
97-
total
98+
... @defer(if: $shouldDefer) {
99+
inbox {
100+
unread
101+
total
102+
}
98103
}
99104
}
100105
}
@@ -124,7 +129,12 @@ function createSubscription(pubsub: SimplePubSub<Email>) {
124129
}),
125130
};
126131

127-
return subscribe({ schema: emailSchema, document, rootValue: data });
132+
return subscribe({
133+
schema: emailSchema,
134+
document,
135+
rootValue: data,
136+
variableValues,
137+
});
128138
}
129139

130140
const DummyQueryType = new GraphQLObjectType({
@@ -638,6 +648,144 @@ describe('Subscription Publish Phase', () => {
638648
});
639649
});
640650

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

src/execution/execute.ts

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@ import {
5252
collectFields,
5353
collectSubfields as _collectSubfields,
5454
} from './collectFields';
55+
import { flattenAsyncIterable } from './flattenAsyncIterable';
5556
import { mapAsyncIterable } from './mapAsyncIterable';
5657
import {
5758
getArgumentValues,
@@ -1399,19 +1400,11 @@ function mapSourceToResponse(
13991400
// the GraphQL specification. The `execute` function provides the
14001401
// "ExecuteSubscriptionEvent" algorithm, as it is nearly identical to the
14011402
// "ExecuteQuery" algorithm, for which `execute` is also used.
1402-
return mapAsyncIterable(resultOrStream, (payload: unknown) => {
1403-
const executionResult = executeImpl(
1404-
buildPerEventExecutionContext(exeContext, payload),
1405-
);
1406-
/* c8 ignore next 6 */
1407-
// TODO: implement support for defer/stream in subscriptions
1408-
if (isAsyncIterable(executionResult)) {
1409-
throw new Error(
1410-
'TODO: implement support for defer/stream in subscriptions',
1411-
);
1412-
}
1413-
return executionResult as PromiseOrValue<ExecutionResult>;
1414-
});
1403+
return flattenAsyncIterable<ExecutionResult, AsyncExecutionResult>(
1404+
mapAsyncIterable(resultOrStream, (payload: unknown) =>
1405+
executeImpl(buildPerEventExecutionContext(exeContext, payload)),
1406+
),
1407+
);
14151408
}
14161409

14171410
/**

0 commit comments

Comments
 (0)