Relay
@defer and @stream with Relay
On this page
Relay compiles @defer, @stream and @stream_connection, but its network layer reads neither incremental format a server sends. It expects flat payloads: each deferred or streamed payload carries its own label and path, and each streamed item is a payload of its own, at [...listPath, index]. It ends an operation when the Observable completes, and never reads hasNext. So the fetch function converts: this page is that converter, as this site runs it.
Asking for the format
gratos-server sends two incremental formats (see GraphQL over HTTP). This site asks for graphql 17's, which runs a field selected both deferred and not once, where the 2022 format runs it twice. It offers the 2022 one at a lower quality, so the app still works against a server without graphql 17's format, and it picks the converter from the response's Content-Type:
export const converterFor = (contentType: string | null): Converter =>
contentType !== null && /;\s*incrementalspec="?v0\.2"?\s*(;|$)/i.test(contentType)
? createConverter()
: toRelayPayloads;The fetch function is otherwise plain: it posts the operation by its persisted id (see Persisted queries), hands Relay each converted payload as it arrives, and aborts the request when Relay unsubscribes, which is what cancels the work on the server (the resolvers see the client leave):
export const readResponse = async (
response: Response,
next: (payload: GraphQLSingularResponse) => void,
onFailure: (failure: Failure) => void = () => {},
): Promise<void> => {
const convert = converterFor(response.headers.get("content-type"));
for await (const text of readParts(response)) {
const { payloads, failures, done } = convert(parseJson(text));
for (const payload of payloads) {
next(payload);
}
for (const failure of failures) {
onFailure(failure);
}
if (done) {
return;
}
}
throw new Error("The response ended before its last part (hasNext: false).");
};What the server sends
The playground shows a response before any conversion: each payload as gratos-server sent it, in graphql 17's format, numbered, with the time it arrived. This query defers a page's related pages, with a @defer that has no label. Relay needs one (relay-compiler adds it), and graphql-js supplies none, so the playground reads the body itself and never runs this converter:
query RelatedPages {
page(slug: "relay-converter") {
title
... @defer {
related(first: 3) {
edges {
node {
title
}
}
}
}
}
}The first payload holds the title and announces the deferred fragment in pending; the next one sends its data by that fragment's id, in incremental, and closes it in completed, with hasNext: false. A streamed list sends its first initialCount items in the first payload, and the rest in incremental[].items, here one payload per item:
query Changelog {
changelog(first: 3) {
edges @stream(initialCount: 1) {
node {
package
version
}
}
}
}The converter
graphql 17's format announces each deferred fragment and each stream once, in pending: [{ id, path, label }], sends their data by id (incremental: [{ id, data, subPath? }], or incremental: [{ id, items }] for a stream), and says when each one is done, in completed: [{ id, errors? }]. A field selected both deferred and not is sent once, where the initial payload has it.
Relay wants the flat payloads instead, so the converter keeps the response's data as it grows: the initial data, each fragment's data merged at its path and subPath, each streamed item appended to its list. Then:
- each streamed item is a payload at once, at
[...listPath, index]; - a deferred fragment is one payload once it is completed (its data may arrive in several entries), holding the data at its path so far;
- a fragment that failed is a payload too, with data, so that Relay keeps going (see below);
hasNext: falseis returned asdone, and the fetch function completes the Observable.
A converter keeps state across the parts of one response, so each response gets its own:
export const createConverter = (): Converter => {
const pending = new Map<string, Pending>();
let tree: JsonValue = {};What each part converts to:
export interface Converted {
/** The Relay payloads the part holds, in order: every patch first, then each failure. */
readonly payloads: Array<GraphQLSingularResponse>;
/**
* What failed in the part, for the app to log. A failed deferred fragment is also in
* `payloads` (its errors as field errors); a failed stream has no field Relay can hold its
* errors on, so it is only here: its list keeps the items that arrived. So is a null streamed
* item, at its own path, with the errors that nulled it.
*/
readonly failures: ReadonlyArray<Failure>;
/** True once the response has no more parts: the caller completes. */
readonly done: boolean;
}Because the deferred payload lacks the fields the initial payload already sent, Relay must be told it may: deferDeduplicatedFields: true on the environment. Relay 21's TypeScript declarations do not have the option yet, so the app declares it in a config type of its own:
export interface RelayConfig extends EnvironmentConfig {
readonly deferDeduplicatedFields: boolean;
}When a deferred fragment fails
A fragment whose non-null field fails is reported in completed[].errors, possibly in a part with no incremental at all, and one part can hold both a failed fragment and a successful sibling's patch. Relay rejects a payload that has errors and no data, and ends the operation on it, so the converter emits every patch of the part first, then the failure as a payload for the fragment's label and path, with data, and with its errors as field errors:
// A stream's errors have no field to sit on; a fragment's are field errors (see above).
if (!isJsonList(value)) {
failed.push(failurePayload(at, value, [...errors, ...errorsBelow(at.path)]));
}The data is what the fragment's path holds so far, with only the field each error names set to null. Relay stores each error on that field, so the component reads the failure with @catch, as it reads any field error. The converter's tests read a deferred field so, from the page their recorded payloads come from:
fragment fixture_readingTime on FixturePage {
readingTime @catch(to: RESULT)
}Four limits stay. A failed stream has no field Relay can hold its errors on (nulling the list would drop the items that arrived), so its list keeps those items and the failure goes only to the fetch function's onFailure. A null streamed item gets no payload, because Relay 21 links a record at an item's index and cannot store a null there. Relay drops a caught server error's message before it hands the error to a component. And a failure below an object no part has sent nulls that object.
@stream_connection
@stream_connection is @connection with its edges streamed: relay-compiler turns it into edges @stream and a deferred pageInfo, and the converter delivers each edge as it arrives. The changelog uses it, and its "Show more" pages through usePaginationFragment, whose refetch query streams the same way:
changelog(first: $first, after: $after)
@stream_connection(key: "changelogEntries_changelog", initial_count: 1) {
edges {
node {
id
package
version
html
}
}
}The SSR render needs none of this to arrive in stages: the server loader waits for every payload, then hands them to Relay at once (see Server rendering). On a client navigation, each part renders as it comes: a docs page's related pages after the page, and the changelog's entries one by one.