-
Notifications
You must be signed in to change notification settings - Fork 579
GraphQL over SSE distinct connection mode #2463
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Closed
Closed
Changes from all commits
Commits
Show all changes
16 commits
Select commit
Hold shift + click to select a range
5eed2dc
graphql-sse mode
enisdenjo 4dc9beb
always 200
enisdenjo 281f822
refactor and test for pings
enisdenjo 5a3bb5b
todo single connections mode
enisdenjo 237f204
remove duplicate test
enisdenjo 64294de
prefer is better wording
enisdenjo d6b9c2e
changeset
enisdenjo 92bad34
improve note
enisdenjo 08ecf6f
add js extension to import
enisdenjo cb002dc
use expected processresult
enisdenjo be437c7
legacySse flag
enisdenjo b9c3050
legacySse flag in spec
enisdenjo 8c12e9e
legacy is true by default
enisdenjo 4165bab
increase timeout
enisdenjo 02d0524
correct use result processor
enisdenjo 9a84cea
document
enisdenjo File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,5 @@ | ||
--- | ||
'graphql-yoga': minor | ||
--- | ||
|
||
Support GraphQL over SSE distinct connection mode |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,188 @@ | ||
import { createSchema, createYoga } from '../src/index.js' | ||
import { createClient } from 'graphql-sse' | ||
|
||
describe('GraphQL over SSE', () => { | ||
const schema = createSchema({ | ||
typeDefs: /* GraphQL */ ` | ||
type Query { | ||
hello: String! | ||
} | ||
type Subscription { | ||
greetings: String! | ||
waitForPings: String! | ||
} | ||
`, | ||
resolvers: { | ||
Query: { | ||
async hello() { | ||
return 'world' | ||
}, | ||
}, | ||
Subscription: { | ||
greetings: { | ||
async *subscribe() { | ||
for (const hi of ['Hi', 'Bonjour', 'Hola', 'Ciao', 'Zdravo']) { | ||
yield { greetings: hi } | ||
} | ||
}, | ||
}, | ||
waitForPings: { | ||
// eslint-disable-next-line require-yield | ||
async *subscribe() { | ||
// a ping is issued every 100ms, wait for a few and just return | ||
await new Promise((resolve) => setTimeout(resolve, 100 * 3 + 50)) | ||
return | ||
}, | ||
}, | ||
}, | ||
}, | ||
}) | ||
|
||
const yoga = createYoga({ | ||
schema, | ||
legacySse: false, | ||
maskedErrors: false, | ||
}) | ||
|
||
describe('Distinct connections mode', () => { | ||
test('should issue pings while connected', async () => { | ||
const res = await yoga.fetch( | ||
'http://yoga/graphql?query=subscription{waitForPings}', | ||
{ | ||
headers: { | ||
accept: 'text/event-stream', | ||
}, | ||
}, | ||
) | ||
expect(res.ok).toBeTruthy() | ||
await expect(res.text()).resolves.toMatchInlineSnapshot(` | ||
": | ||
|
||
: | ||
|
||
: | ||
|
||
event: complete | ||
|
||
" | ||
`) | ||
}) | ||
|
||
it('should support single result operations', async () => { | ||
const client = createClient({ | ||
url: 'http://yoga/graphql', | ||
fetchFn: yoga.fetch, | ||
abortControllerImpl: yoga.fetchAPI.AbortController, | ||
singleConnection: false, // distinct connection mode | ||
retryAttempts: 0, | ||
}) | ||
|
||
await expect( | ||
new Promise((resolve, reject) => { | ||
let result: unknown | ||
client.subscribe( | ||
{ | ||
query: /* GraphQL */ ` | ||
{ | ||
hello | ||
} | ||
`, | ||
}, | ||
{ | ||
next: (msg) => (result = msg), | ||
error: reject, | ||
complete: () => resolve(result), | ||
}, | ||
) | ||
}), | ||
).resolves.toMatchInlineSnapshot(` | ||
{ | ||
"data": { | ||
"hello": "world", | ||
}, | ||
} | ||
`) | ||
|
||
client.dispose() | ||
}) | ||
|
||
it('should support streaming operations', async () => { | ||
const client = createClient({ | ||
url: 'http://yoga/graphql', | ||
fetchFn: yoga.fetch, | ||
abortControllerImpl: yoga.fetchAPI.AbortController, | ||
singleConnection: false, // distinct connection mode | ||
retryAttempts: 0, | ||
}) | ||
|
||
await expect( | ||
new Promise((resolve, reject) => { | ||
const msgs: unknown[] = [] | ||
client.subscribe( | ||
{ | ||
query: /* GraphQL */ ` | ||
subscription { | ||
greetings | ||
} | ||
`, | ||
}, | ||
{ | ||
next: (msg) => msgs.push(msg), | ||
error: reject, | ||
complete: () => resolve(msgs), | ||
}, | ||
) | ||
}), | ||
).resolves.toMatchInlineSnapshot(` | ||
[ | ||
{ | ||
"data": { | ||
"greetings": "Hi", | ||
}, | ||
}, | ||
{ | ||
"data": { | ||
"greetings": "Bonjour", | ||
}, | ||
}, | ||
{ | ||
"data": { | ||
"greetings": "Hola", | ||
}, | ||
}, | ||
{ | ||
"data": { | ||
"greetings": "Ciao", | ||
}, | ||
}, | ||
{ | ||
"data": { | ||
"greetings": "Zdravo", | ||
}, | ||
}, | ||
] | ||
`) | ||
|
||
client.dispose() | ||
}) | ||
|
||
it('should report errors through the stream', async () => { | ||
const res = await yoga.fetch('http://yoga/graphql?query={nope}', { | ||
headers: { | ||
accept: 'text/event-stream', | ||
}, | ||
}) | ||
expect(res.ok).toBeTruthy() | ||
await expect(res.text()).resolves.toMatchInlineSnapshot(` | ||
"event: next | ||
data: {"errors":[{"message":"Cannot query field \\"nope\\" on type \\"Query\\".","locations":[{"line":1,"column":2}]}]} | ||
|
||
event: complete | ||
|
||
" | ||
`) | ||
}) | ||
}) | ||
|
||
it.todo('Single connections mode') | ||
}) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
91 changes: 91 additions & 0 deletions
91
packages/graphql-yoga/src/plugins/resultProcessor/graphql-sse.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,91 @@ | ||
import { ExecutionResult } from 'graphql' | ||
import { isAsyncIterable } from '@envelop/core' | ||
|
||
import { getResponseInitByRespectingErrors } from '../../error.js' | ||
import { FetchAPI, MaybeArray } from '../../types.js' | ||
import { ResultProcessorInput } from '../types.js' | ||
import { jsonStringifyResultWithoutInternals } from './stringify.js' | ||
|
||
export function processGraphQLSSEResult( | ||
result: ResultProcessorInput, | ||
fetchAPI: FetchAPI, | ||
): Response { | ||
// TODO: implement "single connection mode" | ||
|
||
let pingerMs = 12_000 | ||
|
||
// for testing the pings, reduce the timeout significantly | ||
if (globalThis.process?.env?.NODE_ENV === 'test') { | ||
pingerMs = 100 | ||
} | ||
|
||
const headersInit = { | ||
'Content-Type': 'text/event-stream', | ||
Connection: 'keep-alive', | ||
'Cache-Control': 'no-cache', | ||
'Content-Encoding': 'none', | ||
} | ||
|
||
const responseInit = getResponseInitByRespectingErrors( | ||
result, | ||
headersInit, | ||
// as per the GraphQL over SSE spec, operation errors must be reported | ||
// through the stream and the response head should always be 200: OK | ||
true, | ||
) | ||
|
||
let iterator: AsyncIterator<MaybeArray<ExecutionResult>> | ||
let pinger: ReturnType<typeof setInterval> | ||
const textEncoder = new fetchAPI.TextEncoder() | ||
const readableStream = new fetchAPI.ReadableStream({ | ||
start(controller) { | ||
// ping client every 12 seconds to keep the connection alive | ||
pinger = setInterval(() => { | ||
if (controller.desiredSize) { | ||
controller.enqueue(textEncoder.encode(':\n\n')) | ||
} else { | ||
// TODO: why disable pinger when no desired size? | ||
clearInterval(pinger) | ||
} | ||
}, pingerMs) | ||
|
||
if (isAsyncIterable(result)) { | ||
iterator = result[Symbol.asyncIterator]() | ||
} else { | ||
let finished = false | ||
iterator = { | ||
next: () => { | ||
if (finished) { | ||
return Promise.resolve({ done: true, value: null }) | ||
} | ||
finished = true | ||
return Promise.resolve({ done: false, value: result }) | ||
}, | ||
} | ||
} | ||
}, | ||
async pull(controller) { | ||
const { done, value } = await iterator.next() | ||
if (value != null) { | ||
controller.enqueue( | ||
textEncoder.encode( | ||
`event: next\ndata: ${jsonStringifyResultWithoutInternals( | ||
value, | ||
)}\n\n`, | ||
), | ||
) | ||
} | ||
if (done) { | ||
clearInterval(pinger) | ||
controller.enqueue(textEncoder.encode('event: complete\n\n')) | ||
controller.close() | ||
} | ||
}, | ||
async cancel(e) { | ||
clearInterval(pinger) | ||
await iterator.return?.(e) | ||
}, | ||
}) | ||
|
||
return new fetchAPI.Response(readableStream, responseInit) | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We should add a comment explaining this flag