diff --git a/cspell.yml b/cspell.yml index e8aa73355..8bc4a231c 100644 --- a/cspell.yml +++ b/cspell.yml @@ -4,6 +4,7 @@ ignoreRegExpList: - /[a-z]{2,}'s/ words: # Terms of art + - deprioritization - endianness - interoperation - monospace diff --git a/spec/Section 3 -- Type System.md b/spec/Section 3 -- Type System.md index bb0d50b35..83d7dfcbd 100644 --- a/spec/Section 3 -- Type System.md +++ b/spec/Section 3 -- Type System.md @@ -794,8 +794,9 @@ And will yield the subset of each object type queried: When querying an Object, the resulting mapping of fields are conceptually ordered in the same order in which they were encountered during execution, excluding fragments for which the type does not apply and fields or fragments -that are skipped via `@skip` or `@include` directives. This ordering is -correctly produced when using the {CollectFields()} algorithm. +that are skipped via `@skip` or `@include` directives or temporarily skipped via +`@defer`. This ordering is correctly produced when using the {CollectFields()} +algorithm. Response serialization formats capable of representing ordered maps should maintain this ordering. Serialization formats which can only represent unordered @@ -1941,6 +1942,11 @@ by a validator, executor, or client tool such as a code generator. GraphQL implementations should provide the `@skip` and `@include` directives. +GraphQL implementations are not required to implement the `@defer` and `@stream` +directives. If either or both of these directives are implemented, they must be +implemented according to this specification. GraphQL implementations that do not +support these directives must not make them available via introspection. + GraphQL implementations that support the type system definition language must provide the `@deprecated` directive if representing deprecated portions of the schema. @@ -2161,3 +2167,99 @@ to the relevant IETF specification. ```graphql example scalar UUID @specifiedBy(url: "https://tools.ietf.org/html/rfc4122") ``` + +### @defer + +```graphql +directive @defer( + label: String + if: Boolean! = true +) on FRAGMENT_SPREAD | INLINE_FRAGMENT +``` + +The `@defer` directive may be provided for fragment spreads and inline fragments +to inform the executor to delay the execution of the current fragment to +indicate deprioritization of the current fragment. A query with `@defer` +directive will cause the request to potentially return multiple responses, where +non-deferred data is delivered in the initial response and data deferred is +delivered in a subsequent response. `@include` and `@skip` take precedence over +`@defer`. + +```graphql example +query myQuery($shouldDefer: Boolean) { + user { + name + ...someFragment @defer(label: "someLabel", if: $shouldDefer) + } +} +fragment someFragment on User { + id + profile_picture { + uri + } +} +``` + +#### @defer Arguments + +- `if: Boolean! = true` - When `true`, fragment _should_ be deferred (See + [related note](#note-088b7)). When `false`, fragment will not be deferred and + data will be included in the initial response. Defaults to `true` when + omitted. +- `label: String` - May be used by GraphQL clients to identify the data from + responses and associate it with the corresponding defer directive. If + provided, the GraphQL service must add it to the corresponding payload. + `label` must be unique label across all `@defer` and `@stream` directives in a + document. `label` must not be provided as a variable. + +### @stream + +```graphql +directive @stream( + label: String + if: Boolean! = true + initialCount: Int = 0 +) on FIELD +``` + +The `@stream` directive may be provided for a field of `List` type so that the +backend can leverage technology such as asynchronous iterators to provide a +partial list in the initial response, and additional list items in subsequent +responses. `@include` and `@skip` take precedence over `@stream`. + +```graphql example +query myQuery($shouldStream: Boolean) { + user { + friends(first: 10) { + nodes @stream(label: "friendsStream", initialCount: 5, if: $shouldStream) + } + } +} +``` + +#### @stream Arguments + +- `if: Boolean! = true` - When `true`, field _should_ be streamed (See + [related note](#note-088b7)). When `false`, the field will not be streamed and + all list items will be included in the initial response. Defaults to `true` + when omitted. +- `label: String` - May be used by GraphQL clients to identify the data from + responses and associate it with the corresponding stream directive. If + provided, the GraphQL service must add it to the corresponding payload. + `label` must be unique label across all `@defer` and `@stream` directives in a + document. `label` must not be provided as a variable. +- `initialCount: Int` - The number of list items the service should return as + part of the initial response. If omitted, defaults to `0`. A field error will + be raised if the value of this argument is less than `0`. + +Note: The ability to defer and/or stream parts of a response can have a +potentially significant impact on application performance. Developers generally +need clear, predictable control over their application's performance. It is +highly recommended that GraphQL services honor the `@defer` and `@stream` +directives on each execution. However, the specification allows advanced use +cases where the service can determine that it is more performant to not defer +and/or stream. Therefore, GraphQL clients _must_ be able to process a response +that ignores the `@defer` and/or `@stream` directives. This also applies to the +`initialCount` argument on the `@stream` directive. Clients _must_ be able to +process a streamed response that contains a different number of initial list +items than what was specified in the `initialCount` argument. diff --git a/spec/Section 5 -- Validation.md b/spec/Section 5 -- Validation.md index dceec126b..c99824c58 100644 --- a/spec/Section 5 -- Validation.md +++ b/spec/Section 5 -- Validation.md @@ -422,6 +422,7 @@ FieldsInSetCanMerge(set): {set} including visiting fragments and inline fragments. - Given each pair of members {fieldA} and {fieldB} in {fieldsForName}: - {SameResponseShape(fieldA, fieldB)} must be true. + - {SameStreamDirective(fieldA, fieldB)} must be true. - If the parent types of {fieldA} and {fieldB} are equal or if either is not an Object Type: - {fieldA} and {fieldB} must have identical field names. @@ -455,6 +456,16 @@ SameResponseShape(fieldA, fieldB): - If {SameResponseShape(subfieldA, subfieldB)} is false, return false. - Return true. +SameStreamDirective(fieldA, fieldB): + +- If neither {fieldA} nor {fieldB} has a directive named `stream`. + - Return true. +- If both {fieldA} and {fieldB} have a directive named `stream`. + - Let {streamA} be the directive named `stream` on {fieldA}. + - Let {streamB} be the directive named `stream` on {fieldB}. + - If {streamA} and {streamB} have identical sets of arguments, return true. +- Return false. + **Explanatory Text** If multiple field selections with the same response names are encountered during @@ -463,7 +474,7 @@ unambiguous. Therefore any two field selections which might both be encountered for the same object are only valid if they are equivalent. During execution, the simultaneous execution of fields with the same response -name is accomplished by {MergeSelectionSets()} and {CollectFields()}. +name is accomplished by {CollectSubfields()}. For simple hand-written GraphQL, this rule is obviously a clear developer error, however nested fragments can make this difficult to detect manually. @@ -1517,6 +1528,174 @@ query ($foo: Boolean = true, $bar: Boolean = false) { } ``` +### Defer And Stream Directives Are Used On Valid Root Field + +**Formal Specification** + +- For every {directive} in a document. +- Let {directiveName} be the name of {directive}. +- Let {mutationType} be the root Mutation type in {schema}. +- Let {subscriptionType} be the root Subscription type in {schema}. +- If {directiveName} is "defer" or "stream": + - The parent type of {directive} must not be {mutationType} or + {subscriptionType}. + +**Explanatory Text** + +The defer and stream directives are not allowed to be used on root fields of the +mutation or subscription type. + +For example, the following document will not pass validation because `@defer` +has been used on a root mutation field: + +```raw graphql counter-example +mutation { + ... @defer { + mutationField + } +} +``` + +### Defer And Stream Directives Are Used On Valid Operations + +**Formal Specification** + +- Let {subscriptionFragments} be the empty set. +- For each {operation} in a document: + - If {operation} is a subscription operation: + - Let {fragments} be every fragment referenced by that {operation} + transitively. + - For each {fragment} in {fragments}: + - Let {fragmentName} be the name of {fragment}. + - Add {fragmentName} to {subscriptionFragments}. +- For every {directive} in a document: + - If {directiveName} is not "defer" or "stream": + - Continue to the next {directive}. + - Let {ancestor} be the ancestor operation or fragment definition of + {directive}. + - If {ancestor} is a fragment definition: + - If the fragment name of {ancestor} is not present in + {subscriptionFragments}: + - Continue to the next {directive}. + - If {ancestor} is not a subscription operation: + - Continue to the next {directive}. + - Let {if} be the argument named "if" on {directive}. + - {if} must be defined. + - Let {argumentValue} be the value passed to {if}. + - {argumentValue} must be a variable, or the boolean value "false". + +**Explanatory Text** + +The defer and stream directives can not be used to defer or stream data in +subscription operations. If these directives appear in a subscription operation +they must be disabled using the "if" argument. This rule will not permit any +defer or stream directives on a subscription operation that cannot be disabled +using the "if" argument. + +For example, the following document will not pass validation because `@defer` +has been used in a subscription operation with no "if" argument defined: + +```raw graphql counter-example +subscription sub { + newMessage { + ... @defer { + body + } + } +} +``` + +### Defer And Stream Directive Labels Are Unique + +**Formal Specification** + +- Let {labelValues} be an empty set. +- For every {directive} in the document: + - Let {directiveName} be the name of {directive}. + - If {directiveName} is "defer" or "stream": + - For every {argument} in {directive}: + - Let {argumentName} be the name of {argument}. + - Let {argumentValue} be the value passed to {argument}. + - If {argumentName} is "label": + - {argumentValue} must not be a variable. + - {argumentValue} must not be present in {labelValues}. + - Append {argumentValue} to {labelValues}. + +**Explanatory Text** + +The `@defer` and `@stream` directives each accept an argument "label". This +label may be used by GraphQL clients to uniquely identify response payloads. If +a label is passed, it must not be a variable and it must be unique within all +other `@defer` and `@stream` directives in the document. + +For example the following document is valid: + +```graphql example +{ + dog { + ...fragmentOne + ...fragmentTwo @defer(label: "dogDefer") + } + pets @stream(label: "petStream") { + name + } +} + +fragment fragmentOne on Dog { + name +} + +fragment fragmentTwo on Dog { + owner { + name + } +} +``` + +For example, the following document will not pass validation because the same +label is used in different `@defer` and `@stream` directives.: + +```raw graphql counter-example +{ + dog { + ...fragmentOne @defer(label: "MyLabel") + } + pets @stream(label: "MyLabel") { + name + } +} + +fragment fragmentOne on Dog { + name +} +``` + +### Stream Directives Are Used On List Fields + +**Formal Specification** + +- For every {directive} in a document. +- Let {directiveName} be the name of {directive}. +- If {directiveName} is "stream": + - Let {adjacent} be the AST node the directive affects. + - {adjacent} must be a List type. + +**Explanatory Text** + +GraphQL directive locations do not provide enough granularity to distinguish the +type of fields used in a GraphQL document. Since the stream directive is only +valid on list fields, an additional validation rule must be used to ensure it is +used correctly. + +For example, the following document will only pass validation if `field` is +defined as a List type in the associated schema. + +```graphql counter-example +query { + field @stream(initialCount: 0) +} +``` + ## Variables ### Variable Uniqueness diff --git a/spec/Section 6 -- Execution.md b/spec/Section 6 -- Execution.md index 28862ea89..5613664c2 100644 --- a/spec/Section 6 -- Execution.md +++ b/spec/Section 6 -- Execution.md @@ -31,6 +31,10 @@ request is determined by the result of executing this operation according to the ExecuteRequest(schema, document, operationName, variableValues, initialValue): +Note: the execution assumes implementing language supports coroutines. +Alternatively, the socket can provide a write buffer pointer to allow +{ExecuteRequest()} to directly write payloads into the buffer. + - Let {operation} be the result of {GetOperation(document, operationName)}. - Let {coercedVariableValues} be the result of {CoerceVariableValues(schema, operation, variableValues)}. @@ -131,12 +135,8 @@ ExecuteQuery(query, schema, variableValues, initialValue): - Let {queryType} be the root Query type in {schema}. - Assert: {queryType} is an Object type. - Let {selectionSet} be the top level Selection Set in {query}. -- Let {data} be the result of running {ExecuteSelectionSet(selectionSet, - queryType, initialValue, variableValues)} _normally_ (allowing - parallelization). -- Let {errors} be the list of all _field error_ raised while executing the - selection set. -- Return an unordered map containing {data} and {errors}. +- Return {ExecuteRootSelectionSet(variableValues, initialValue, queryType, + selectionSet)}. ### Mutation @@ -153,11 +153,8 @@ ExecuteMutation(mutation, schema, variableValues, initialValue): - Let {mutationType} be the root Mutation type in {schema}. - Assert: {mutationType} is an Object type. - Let {selectionSet} be the top level Selection Set in {mutation}. -- Let {data} be the result of running {ExecuteSelectionSet(selectionSet, - mutationType, initialValue, variableValues)} _serially_. -- Let {errors} be the list of all _field error_ raised while executing the - selection set. -- Return an unordered map containing {data} and {errors}. +- Return {ExecuteRootSelectionSet(variableValues, initialValue, mutationType, + selectionSet, true)}. ### Subscription @@ -259,10 +256,11 @@ CreateSourceEventStream(subscription, schema, variableValues, initialValue): - Let {groupedFieldSet} be the result of {CollectFields(subscriptionType, selectionSet, variableValues)}. - If {groupedFieldSet} does not have exactly one entry, raise a _request error_. -- Let {fields} be the value of the first entry in {groupedFieldSet}. -- Let {fieldName} be the name of the first entry in {fields}. Note: This value - is unaffected if an alias is used. -- Let {field} be the first entry in {fields}. +- Let {fieldDetailsList} be the value of the first entry in {groupedFieldSet}. +- Let {fieldDetails} be the first entry in {fieldDetailsList}. +- Let {node} be the corresponding entry on {fieldDetails}. +- Let {fieldName} be the name of {node}. Note: This value is unaffected if an + alias is used. - Let {argumentValues} be the result of {CoerceArgumentValues(subscriptionType, field, variableValues)} - Let {fieldStream} be the result of running @@ -301,15 +299,13 @@ ExecuteSubscriptionEvent(subscription, schema, variableValues, initialValue): - Let {subscriptionType} be the root Subscription type in {schema}. - Assert: {subscriptionType} is an Object type. - Let {selectionSet} be the top level Selection Set in {subscription}. -- Let {data} be the result of running {ExecuteSelectionSet(selectionSet, - subscriptionType, initialValue, variableValues)} _normally_ (allowing - parallelization). -- Let {errors} be the list of all _field error_ raised while executing the - selection set. -- Return an unordered map containing {data} and {errors}. +- Return {ExecuteRootSelectionSet(variableValues, initialValue, + subscriptionType, selectionSet)}. Note: The {ExecuteSubscriptionEvent()} algorithm is intentionally similar to -{ExecuteQuery()} since this is how each event result is produced. +{ExecuteQuery()} since this is how each event result is produced. Incremental +delivery, however, is not supported within {ExecuteSubscriptionEvent()} and will +result in a _field error_. #### Unsubscribe @@ -322,44 +318,743 @@ Unsubscribe(responseStream): - Cancel {responseStream} -## Executing Selection Sets +## Executing the Root Selection Set + +To execute the root selection set, the object value being evaluated and the +object type need to be known, as well as whether it must be executed serially, +or may be executed in parallel. + +Executing the root selection set works similarly for queries (parallel), +mutations (serial), and subscriptions (where it is executed for each event in +the underlying Source Stream). + +First, the selection set is turned into a field plan; then, we execute this +field plan, which may yield one or more incremental results, as specified by the +{YieldIncrementalResults()} algorithm. If an operation contains `@defer` or +`@stream` directives, we return the Subsequent Result stream in addition to the +initial response. Otherwise, we return just the initial result. + +ExecuteRootSelectionSet(variableValues, initialValue, objectType, selectionSet, +serial): + +- Let {incrementalResults} be the result of + {YieldIncrementalResults(variableValues, initialValue, objectType, + selectionSet, serial)}. +- Wait for the first result in {incrementalResults} to be available. +- Let {initialResult} be that result. +- Let {initialResponse} and {ids} be the result of + {GetInitialResponse(initialResult)}. +- Let {subsequentResponses} be the result of running + {MapSubsequentResultToResponse(incrementalResult, ids)}. +- Return {initialResponse} and {subsequentResponses}. + +MapSubsequentResultToResponse(subsequentResultStream, originalIds): + +- Let {ids} be a new unordered map containing all of the entries in + {originalIds}. +- Return a new event stream {subsequentResponseStream} which yields events as + follows: +- For each {result} on {subsequentResultStream}: + - Let {response} and {ids} be the result of {GetSubsequentPayload(update, + ids)}. + - Yield an event containing {response}. +- When {subsequentResultStream} completes: complete this event stream. + +GetInitialResponse(initialResult): + +- Let {newPendingResults} be entry for {pending} on {initialResult}. +- Let {pending} and {ids} be the result of {GetPending(pending)}. +- Let {data} and {errors} be the corresponding entries on {initialResult}. +- Let {initialResponse} be an unordered map containing {data} and {errors}. +- If {pending} is not empty: + - Set the corresponding entry on {payload} to {pending}. + - Set the entry for {hasNext} on {payload} to {true}. +- Return {initialResponse} and {ids}. + +GetPending(newPendingResults, originalIds): + +- Let {ids} be a new unordered map containing all of the entries in + {originalIds}. +- Initialize {pending} to an empty list. +- For each {newPendingResult} in {newPendingResults}: + - Let {path} and {label} be the corresponding entries on {newPendingResult}. + - Let {id} be a unique identifier for this {newPendingResult}. + - Set the entry for {newPendingResult} in {ids} to {id}. + - Let {pendingEntry} be an unordered map containing {path}, {label}, and {id}. + - Append {pendingEntry} to {pending}. +- Return {pending} and {ids}. + +GetSubsequentResponse(update, originalIds): + +- Let {newPendingResults} be entry for {pending} on {update}. +- Let {pending} and {ids} be the result of {GetPending(pending, originalIds)}. +- Initialize {incremental} and {completed} to empty lists. +- For each {completedEntry} in {completed} on {update}: + - Let {newCompletedEntry} be a new empty unordered map. + - Let {pendingResult} be the corresponding entry on {completedEntry}. + - Let {id} be the entry for {pendingResult} on {ids}. + - Remove the entry on {ids} for {pendingResult}. + - Set the corresponding entry on {newCompletedEntry} to {id}. + - Let {errors} be the corresponding entry on {completedEntry}. + - If {errors} is defined, set the corresponding entry on {newCompletedEntry} + to {errors}. + - Append {newCompletedEntry} to {completed}. +- For each {incrementalResult} in {incremental} on {update}: + - If {incrementalResult} represents completion of Stream Items: + - Let {stream} be the corresponding entry on {incrementalResult}. + - Let {id} be the corresponding entry on {ids} for {stream}. + - Let {items} and {errors} be the corresponding entries on + {incrementalResult}. + - Let {incrementalEntry} be an unordered map containing {id}, {items}, and + {errors}. + - Otherwise: + - Let {id} and {subPath} be the result of calling + {GetIdAndSubPath(incrementalResult, ids)}. + - Let {data} and {errors} be the corresponding entries on + {incrementalResult}. + - Let {incrementalEntry} be an unordered map containing {id}, {data}, and + {errors}. + - Append {incrementalEntry} to {incremental}. +- Let {hasNext} be {false} if {ids} is empty, otherwise {true}. +- Let {payload} be an unordered map containing {hasNext}. +- If {pending} is not empty, set the corresponding entry on {payload} to + {pending}. +- If {incremental} is not empty, set the corresponding entry on {payload} to + {incremental}. +- If {completed} is not empty, set the corresponding entry on {payload} to + {completed}. +- Return {ids} and {payload}. + +GetIdAndSubPath(deferredResult, ids): + +- Initialize {releasedFragments} to an empty list. +- Let {deferredFragments} be the corresponding entry on {deferredResult}. +- For each {deferredFragment} in {deferredFragments}: + - Let {id} be the entry for {deferredFragment} on {ids}. + - If {id} is defined, append {deferredFragment} to {releasedFragments}. +- Let {currentFragment} be the first member of {releasedFragments}. +- Let {currentPath} be the entry for {path} on {firstDeferredFragment}. +- Let {currentPathLength} be the length of {currentPath}. +- For each remaining {deferredFragment} within {deferredFragments}. + - Let {path} be the corresponding entry on {deferredFragment}. + - Let {pathLength} be the length of {path}. + - If {pathLength} is larger than {currentPathLength}: + - Set {currentPathLength} to {pathLength}. + - Set {currentFragment} to {deferredFragment}. +- Let {id} be the entry on {ids} for {currentFragment}. +- If {id} is not defined, return. +- Let {path} be the corresponding entry on {currentFragment}. +- Let {subPath} be the subset of {path}, omitting the first {currentPathLength} + entries. +- Return {id} and {subPath}. -To execute a selection set, the object value being evaluated and the object type -need to be known, as well as whether it must be executed serially, or may be -executed in parallel. +### Field Collection -First, the selection set is turned into a grouped field set; then, each -represented field in the grouped field set produces an entry into a response -map. +Before execution, selection set(s) are converted to a field plan via a two-step +process. In the first step, selections are converted into a grouped field set by +calling {CollectFields()}. Each entry in a grouped field set is a list of Field +Details records describing all fields that share a response key (the alias if +defined, otherwise the field name). This ensures all fields with the same +response key (including those in referenced fragments) are executed at the same +time. -ExecuteSelectionSet(selectionSet, objectType, objectValue, variableValues): +A Field Details record is a structure containing: + +- {node}: the field node itself. +- {deferUsage}: the Defer Usage record corresponding to the deferred fragment + enclosing this field, not defined if the field was not deferred. + +Defer Usage records contain information derived from the presence of a `@defer` +directive on a fragment and are structures containing: + +- {label}: value of the corresponding argument to the `@defer` directive. +- {parentDeferUsage}: the parent Defer Usage record corresponding to the + deferred fragment enclosing this deferred fragment, not defined if this Defer + Usage record is deferred directly by the initial result. + +As an example, collecting the fields of this selection set would return field +details related to two instances of the field `a` and one of field `b`: + +```graphql example +{ + a { + subfield1 + } + ...ExampleFragment +} + +fragment ExampleFragment on Query { + a { + subfield2 + } + b +} +``` + +The depth-first-search order of the field groups produced by {CollectFields()} +is maintained through execution, ensuring that fields appear in the executed +response in a stable and predictable order. + +CollectFields(objectType, selectionSet, variableValues, deferUsage, +visitedFragments): + +- If {visitedFragments} is not provided, initialize it to the empty set. +- Initialize {groupedFields} to an empty ordered map of lists. +- Initialize {newDeferUsages} to an empty list. +- For each {selection} in {selectionSet}: + - If {selection} provides the directive `@skip`, let {skipDirective} be that + directive. + - If {skipDirective}'s {if} argument is {true} or is a variable in + {variableValues} with the value {true}, continue with the next {selection} + in {selectionSet}. + - If {selection} provides the directive `@include`, let {includeDirective} be + that directive. + - If {includeDirective}'s {if} argument is not {true} and is not a variable + in {variableValues} with the value {true}, continue with the next + {selection} in {selectionSet}. + - If {selection} is a {Field}: + - Let {responseKey} be the response key of {selection} (the alias if + defined, otherwise the field name). + - Let {fieldDetails} be a new Field Details record created from {selection} + and {deferUsage}. + - Let {groupForResponseKey} be the list in {groupedFields} for + {responseKey}; if no such list exists, create it as an empty list. + - Append {fieldDetails} to the {groupForResponseKey}. + - If {selection} is a {FragmentSpread}: + - Let {fragmentSpreadName} be the name of {selection}. + - If {fragmentSpreadName} provides the directive `@defer` and its {if} + argument is not {false} and is not a variable in {variableValues} with the + value {false}: + - Let {deferDirective} be that directive. + - If this execution is for a subscription operation, raise a _field + error_. + - If {deferDirective} is not defined: + - If {fragmentSpreadName} is in {visitedFragments}, continue with the next + {selection} in {selectionSet}. + - Add {fragmentSpreadName} to {visitedFragments}. + - Let {fragment} be the Fragment in the current Document whose name is + {fragmentSpreadName}. + - If no such {fragment} exists, continue with the next {selection} in + {selectionSet}. + - Let {fragmentType} be the type condition on {fragment}. + - If {DoesFragmentTypeApply(objectType, fragmentType)} is false, continue + with the next {selection} in {selectionSet}. + - Let {fragmentSelectionSet} be the top-level selection set of {fragment}. + - If {deferDirective} is defined: + - Let {label} be the value or the variable to {deferDirective}'s {label} + argument. + - Let {fragmentDeferUsage} be a new Defer Usage record created from + {label} and {deferUsage}. + - Append {fragmentDeferUsage} to {newDeferUsages}. + - Otherwise: + - Let {fragmentDeferUsage} be {deferUsage}. + - Let {fragmentGroupedFieldSet} and {fragmentNewDeferUsages} be the result + of calling {CollectFields(objectType, fragmentSelectionSet, + variableValues, fragmentDeferUsage, visitedFragments)}. + - For each {fragmentGroup} in {fragmentGroupedFieldSet}: + - Let {responseKey} be the response key shared by all fields in + {fragmentGroup}. + - Let {groupForResponseKey} be the list in {groupedFields} for + {responseKey}; if no such list exists, create it as an empty list. + - Append all items in {fragmentGroup} to {groupForResponseKey}. + - Append all items in {fragmentNewDeferUsages} to {newDeferUsages}. + - If {selection} is an {InlineFragment}: + - Let {fragmentType} be the type condition on {selection}. + - If {fragmentType} is not {null} and {DoesFragmentTypeApply(objectType, + fragmentType)} is false, continue with the next {selection} in + {selectionSet}. + - Let {fragmentSelectionSet} be the top-level selection set of {selection}. + - If {InlineFragment} provides the directive `@defer` and its {if} argument + is not {false} and is not a variable in {variableValues} with the value + {false}: + - Let {deferDirective} be that directive. + - If this execution is for a subscription operation, raise a _field + error_. + - If {deferDirective} is defined: + - Let {label} be the value or the variable to {deferDirective}'s {label} + argument. + - Let {fragmentDeferUsage} be a new Defer Usage record created from + {label} and {deferUsage}. + - Add {fragmentDeferUsage} to {newDeferUsages}. + - Otherwise: + - Let {fragmentDeferUsage} be {deferUsage}. + - Let {fragmentGroupedFieldSet} and {fragmentNewDeferUsages} be the result + of calling {CollectFields(objectType, fragmentSelectionSet, + variableValues, fragmentDeferUsage, visitedFragments)}. + - For each {fragmentGroup} in {fragmentGroupedFieldSet}: + - Let {responseKey} be the response key shared by all fields in + {fragmentGroup}. + - Let {groupForResponseKey} be the list in {groupedFields} for + {responseKey}; if no such list exists, create it as an empty list. + - Append all items in {fragmentGroup} to {groupForResponseKey}. + - Append all items in {fragmentNewDeferUsages} to {newDeferUsages}. +- Return {groupedFields} and {newDeferUsages}. + +DoesFragmentTypeApply(objectType, fragmentType): + +- If {fragmentType} is an Object Type: + - if {objectType} and {fragmentType} are the same type, return {true}, + otherwise return {false}. +- If {fragmentType} is an Interface Type: + - if {objectType} is an implementation of {fragmentType}, return {true} + otherwise return {false}. +- If {fragmentType} is a Union: + - if {objectType} is a possible type of {fragmentType}, return {true} + otherwise return {false}. + +Note: The steps in {CollectFields()} evaluating the `@skip` and `@include` +directives may be applied in either order since they apply commutatively. + +### Field Plan Generation + +In the second step, the original grouped field set is converted into a field +plan via analysis of the Field Details. + +A Field Plan record is a structure containing: + +- {groupedFieldSet}: the grouped field set for the current result. +- {newGroupedFieldSets}: an unordered map containing additional grouped field + sets for related to previously encountered Defer Usage records. The map is + keyed by the unique set of Defer Usage records to which these new grouped + field sets belong. (See below for an explanation of why these additional + grouped field sets may be required.) +- {newGroupedFieldSetsRequiringDeferral}: a map containing additional grouped + field sets for new incremental results relating to the newly encountered + deferred fragments. The map is keyed by the set of Defer Usage records to + which these new grouped field sets belong. + +Additional grouped field sets are constructed carefully so as to ensure that +each field is executed exactly once and so that fields are grouped according to +the set of deferred fragments that include them. + +Deferred grouped field sets do not always require initiating deferral. For +example, when a parent field is deferred by multiple fragments, deferral is +initiated on the parent field. New grouped field sets for child fields will be +created if the child fields are not all present in all of the deferred +fragments, but these new grouped field sets, while representing deferred fields, +do not require additional deferral. The produced field plan will also retain +this information. + +BuildFieldPlan(groupedFieldSet, parentDeferUsages): + +- If {parentDeferUsages} is not provided, initialize it to the empty set. +- Initialize {originalGroupedFieldSet} to an empty ordered map. +- Initialize {newGroupedFieldSets} to an empty unordered map. +- Initialize {newGroupedFieldSetsRequiringDeferral} to an empty unordered map. +- For each {responseKey} and {groupForResponseKey} of {groupedFieldSet}: + - Let {deferUsageSet} be the result of + {GetDeferUsageSet(groupForResponseKey)}. + - If {IsSameSet(deferUsageSet, parentDeferUsages)} is {true}: + - Let {groupedFieldSet} be {originalGroupedFieldSet}. + - Otherwise: + - Let {groupedFieldSets} be {newGroupedFieldSetsRequiringDeferral} if + {ShouldInitiateDefer(deferUsageSet, parentDeferUsages)} is {true}, + otherwise let it be {newGroupedFieldSets}: + - For each {key} in {groupedFieldSets}: + - If {IsSameSet(key, deferUsageSet)} is {true}: + - Let {groupedFieldSet} be the map in {groupedFieldSets} for {key}. + - If {groupedFieldSet} is not defined: + - Initialize {groupedFieldSet} to an empty ordered map. + - Set the entry for {deferUsageSet} in {groupedFieldSets} to + {groupedFieldSet}. + - Set the entry for {responseKey} in {originalGroupedFieldSet} to + {groupForResponseKey}. +- Let {fieldPlan} be a new Field Plan record created from + {originalGroupedFieldSet}, {newGroupedFieldSets}, and + {newGroupedFieldSetsRequiringDeferral}. +- Return {fieldPlan}. + +GetDeferUsageSet(fieldDetailsList): + +- Initialize {deferUsageSet} to the empty set. +- Let {inInitialResult} be {false}. +- For each {fieldDetails} in {fieldDetailsList}: + - Let {deferUsage} be the corresponding entry on {fieldDetails}. + - If {deferUsage} is not defined: + - Let {inInitialResult} be {true}. + - Continue to the next {fieldDetails} in {fieldDetailsList}. + - Add {deferUsage} to {deferUsageSet}. +- If {inInitialResult} is true, reset {deferUsageSet} to the empty set; + otherwise, let {deferUsageSet} be the result of + {FilterDeferUsages(deferUsageSet)}. +- Return {deferUsageSet}. + +FilterDeferUsages(deferUsages): + +- Initialize {filteredDeferUsages} to the empty set. +- For each {deferUsage} in {deferUsages}: + - Let {ancestors} be the result of {GetAncestors(deferUsage)}. + - For each {ancestor} of {ancestors}: + - If {ancestor} is in {deferUsages}. + - Continue to the next {deferUsage} in {deferUsages}. + - Add {deferUsage} to {filteredDeferUsages}. +- Return {filteredDeferUsages}. + +GetAncestors(deferUsage): + +- Initialize {ancestors} to an empty list. +- Let {parentDeferUsage} be the corresponding entry on {deferUsage}. +- If {parentDeferUsage} is not defined, return {ancestors}. +- Append {parentDeferUsage} to {ancestors}. +- Append all the items in {GetAncestors(parentDeferUsage)} to {ancestors}. +- Return {ancestors}. + +ShouldInitiateDefer(deferUsageSet, parentDeferUsageSet): + +- For each {deferUsage} in {deferUsageSet}: + - If {parentDeferUsageSet} does not contain {deferUsage}: + - Return {true}. +- Return {false}. + +IsSameSet(setA, setB): + +- If the size of setA is not equal to the size of setB: + - Return {false}. +- For each {item} in {setA}: + - If {setB} does not contain {item}: + - Return {false}. +- Return {true}. + +### Yielding Incremental Results + +The procedure for yielding incremental results is specified by the +{YieldIncrementalResults()} algorithm. + +YieldIncrementalResults(variableValues, initialValue, objectType, selectionSet, +serial): + +- Let {initialFuture} be the future result of + {ExecuteInitialResult(variableValues, initialValue, objectType, selectionSet, + serial)}. +- Initiate {initialFuture}. +- Initialize {pendingFutures} to a set containing {initialFuture}. +- Initialize {pendingResults} and {unsent} to the empty set. +- Initialize {newPendingResultsByFragment}, {pendingFuturesByFragment}, and + {completedFuturesByFragment} to empty unordered maps. +- Repeat the following steps: + - If none of the futures in {pendingFutures} have completed: + - If {incremental} or {completed} is not empty: + - If {pendingResults} is empty, let {hasNext} be {false}, otherwise let it + be {true}. + - Let {incrementalResult} be a new unordered map containing {pending}, + {incremental}, {completed} and {hasNext}. + - Yield {incrementalResult}. + - If {hasNext} is {false}, complete this incremental result stream and + return. + - For each {future} in {newFutures}: + - Initialize {future} if it has not yet been initialized. + - Add {future} to {pendingFutures}. + - Reset {newFutures} to the empty set. + - Reset {pending}, {incremental}, and {completed} to empty lists. + - Wait for any futures within {pendingFutures} to complete. + - Let {completedFutures} be the futures in {pendingFutures} that have + completed. + - For each {future} in {completedFutures}: + - Remove {future} from {pendingFutures}. + - Let {result} be the result of {future}. + - If {result} represents the Initial Result: + - Let {data} and {errors} be the corresponding entries on {result}. + - Otherwise, if {result} incrementally completes a Stream: + - Let {stream}, {items}, and {errors} be the corresponding entries on + {result}. + - If {items} is not defined, the stream has asynchronously ended: + - Let {completedEntry} be an empty unordered map. + - Set the entry for {pendingResult} on {completedEntry} to {stream}. + - Append {completedEntry} to {completed}. + - Remove {stream} from {pendingResults}. + - Otherwise, if {items} is {null}: + - Let {completedEntry} be an unordered map containing {errors}. + - Set the entry for {pendingResult} on {completedEntry} to {stream}. + - Append {completedEntry} to {completed}. + - Remove {stream} from {pendingResults}. + - Otherwise: + - Append {streamItems} to {incremental}. + - Otherwise: + - Let {deferredFragments}, {data}, and {errors} be the corresponding + entries on {result}. + - If {data} is {null}: + - For each {deferredFragment} in {deferredFragments}: + - If {deferredFragment} is not contained by {pendingResults}, continue + to the next {deferredFragment} in {deferredFragments}. + - Let {completedEntry} be an unordered map containing {errors}. + - Set the entry for {pendingResult} on {completedEntry} to + {deferredFragment}. + - Append {completedEntry} to {completed}. + - Remove {deferredFragment} from {pendingResults}. + - Otherwise: + - For each {deferredFragment} in {deferredFragments}: + - If {deferredFragment} is not contained by {pendingResults}, continue + to the next {deferredFragment} in {deferredFragments}. + - Let {completedFuturesForFragment} be the entry for + {deferredFragment} in {completedFuturesByFragment}; if no such list + exists, create it as an empty list. + - Append {future} to {completedFuturesForFragment}. + - Add {future} to {unsent}. + - Let {pendingFuturesForFragment} be the entry for {deferredFragment} + in {pendingFuturesByFragment}. + - If the size of {completedFuturesForFragment} is equal to the size of + {pendingFuturesForFragment}: + - Let {fragmentNewFutures}, {fragmentPending}, + {fragmentIncremental}, and {fragmentCompleted}, be the result of + {CompleteFragment(deferredFragment, completedFuturesForFragment, + pendingFuturesForFragment, newPendingResultsByFragment, + completedFuturesByFragment, unsent)}. + - Add all items in {fragmentNewFutures} to {newFutures}. + - For each {pendingResult} in {fragmentPending}: + - Append {pendingResult} to {pending}. + - Add {pendingResult} to {pendingResults}. + - For each {fragmentResult} in {fragmentIncremental}: + - Remove {fragmentResult} from {unsent}. + - For each {completedEntry} in {completed}: + - Let {pendingResult} be the corresponding entry on + {completedEntry}. + - Remove {pendingResult} from {pendingResults}. + - For each {result} in {incremental}: + - Let {newPendingResults} and {futures} be the corresponding entries on + {incremental}. + - For each {future} of {futures}: If {future} represents completion of + Stream Items: + - Add {future} to {newFutures}. + - Otherwise: + - Let {deferredFragments} be the Deferred Fragments completed by + {future}. + - For each {deferredFragment} in {deferredFragments}: + - Let {pendingFuturesForFragment} be the entry for + {deferredFragment} in {pendingFuturesByFragment}; if no such list + exists, create it as an empty list. + - Append {future} to {pendingFuturesForFragment}. + - If {deferredFragment} is contained by {pendingResults}: + - Add {future} to {newFutures}. + - For each {newPendingResult} of {newPendingResults}: + - If {newPendingResult} represents a Stream: + - Append {newPendingResult} to {pending}. + - Add {newPendingResult} to {pendingResults}. + - Otherwise: + - Let {pendingFuturesForFragment} be the entry for {newPendingResult} + in {pendingFuturesByFragment}; if no such list exists, continue to + the next {newPendingResult} of {newPendingResults}. + - Let {parent} be the corresponding entry on {newPendingResult}. + - If {parent} is not defined or {pendingResults} does not contain + {parent}: + - Append {newPendingResult} to {pending}. + - Add {newPendingResult} to {pendingResults}. + - For each {future} in {pendingFuturesForFragment}: + - Add {future} to {newFutures}. + - Otherwise: + - Let {newPendingResultsForFragment} be the entry for {parent} in + {newPendingResultsByFragment}; if no such list exists, create it + as an empty list. + - Append {newPendingResult} to {newPendingResultsForFragment}. + +ExecuteInitialResult(variableValues, initialValue, objectType, selectionSet, +serial): + +- If {serial} is not provided, initialize it to {false}. +- Let {groupedFieldSet} and {newDeferUsages} be the result of + {CollectFields(objectType, selectionSet, variableValues)}. +- Let {fieldPlan} be the result of {BuildFieldPlan(groupedFieldSet)}. +- Let {data}, {newPendingResults}, and {futures} be the result of + {ExecuteFieldPlan(newDeferUsages, fieldPlan, objectType, initialValue, + variableValues, serial)}. +- Let {errors} be the list of all _field error_ raised while executing the + {groupedFieldSet}. +- Let {initialResult} be an unordered map consisting of {data}, {errors}, + {newPendingResults}, and {futures}. +- Return {initialResult}. + +CompleteFragment(deferredFragment, completedFuturesForFragment, +pendingFuturesByFragment, newPendingResultsByFragment, +completedFuturesByFragment, unsent): + +- Initialize {newFutures} to the empty set. +- Initialize {pending}, {incremental}, and {completed} to empty lists. +- Let {completedEntry} be an empty unordered map. +- Set the entry for {pendingResult} on {completedEntry} to {deferredFragment}. +- Append {completedEntry} to {completed}. +- For each {future} in {completedFuturesForFragment}: + - If {future} is in {unsent}: + - Let {result} be the result of {future}. + - Append {result} to {incremental}. +- Let {newPendingResultsForFragment} be the entry for {deferredFragment} in + {newPendingResultsByFragment}. +- For each {deferredFragment} in {newPendingResultsForFragment}: + - Let {fragmentPendingFuturesForFragment} be the entry for {deferredFragment} + in {pendingFuturesByFragment}; if no such list exists, continue to the next + {deferredFragment} in {newPendingResultsForFragment}. + - Append {deferredFragment} to {pending}. + - Let {fragmentCompletedFuturesForFragment} be the entry for + {deferredFragment} in {completedFuturesByFragment}. + - If the size of {fragmentCompletedFuturesForFragment} is equal to the size of + {fragmentPendingFuturesForFragment}: + - Let {fragmentNewFutures}, {fragmentPending}, {fragmentIncremental}, and + {fragmentCompleted}, be the result of {CompleteFragment(deferredFragment, + resultsForFragment, pendingFuturesByFragment, newPendingResultsByFragment, + resultsByFragment, unsent)}. + - Add all items in {fragmentNewFutures} to {newFutures}. + - Append all items in {fragmentPending} to {pending}. + - Append all items in {fragmentIncremental} to {incremental}. + - Append all items in {fragmentCompleted} to {completed}. + - Otherwise: + - For each {future} in {fragmentPendingFuturesForFragment}: + - If {completedFuturesForFragment} does not contain {future}: + - Add {future} to {newFutures}. +- Return {newFutures}, {pending}, {incremental}, and {completed}. + +## Executing a Field Plan + +To execute a field plan, the object value being evaluated and the object type +need to be known, as well as whether the non-deferred grouped field set must be +executed serially, or may be executed in parallel. + +ExecuteFieldPlan(newDeferUsages, fieldPlan, objectType, objectValue, +variableValues, serial, path, deferUsageSet, deferMap): + +- If {path} is not provided, initialize it to an empty list. +- Let {groupedFieldSet}, {newGroupedFieldSets}, {newDeferUsages}, and + {newGroupedFieldSetsRequiringDeferral} be the corresponding entries on + {fieldPlan}. +- Let {newPendingResults} and {newDeferMap} be the result of + {GetNewDeferredFragments(newDeferUsages, path, deferMap)}. +- Allowing for parallelization, perform the following steps: + - Let {data}, {newPendingResults}, and {nestedFutures} be the result of + running {ExecuteGroupedFieldSet(groupedFieldSet, objectType, objectValue, + variableValues, path, deferUsageSet, newDeferMap)} _serially_ if {serial} is + {true}, _normally_ (allowing parallelization) otherwise. + - Let {supplementalFutures} be the result of + {ExecuteDeferredGroupedFieldSets(objectType, objectValue, variableValues, + newGroupedFieldSets, true, path, newDeferMap)}. + - Let {deferredFutures} be the result of + {ExecuteDeferredGroupedFieldSets(objectType, objectValue, variableValues, + newGroupedFieldSets, false, path, newDeferMap)}. +- Let {futures} be a list containing all members of {supplementalFutures} and + {deferredFutures}. +- Append all items in {nestedNewPendingResults} and {nestedFutures} to + {newPendingResults} and {futures}. +- Return {data}, {newPendingResults}, and {futures}. + +GetNewDeferredFragments(newDeferUsages, path, deferMap): + +- If {newDeferUsages} is empty: + - Return {deferMap}. +- Initialize {newDeferredFragments} to an empty list. +- Let {newDeferMap} be a new unordered map of Defer Usage records to Deferred + Fragment records containing all of the entries in {deferMap}. +- For each {deferUsage} in {newDeferUsages}: + - Let {parentDeferUsage} be the corresponding entry on {deferUsage}. + - Let {parent} be the entry in {deferMap} for {parentDeferUsage}. + - Let {label} be the corresponding entry on {deferUsage}. + - Let {newDeferredFragment} be an unordered map containing {parent}, {path} + and {label}. + - Append {newDeferredFragment} to {newDeferredFragments}. + - Set the entry for {deferUsage} in {newDeferMap} to {newDeferredFragment}. +- Return {newDeferredFragments} and {newDeferMap}. + +ExecuteDeferredGroupedFieldSets(objectType, objectValue, variableValues, +newGroupedFieldSets, supplemental, path, deferMap): + +- Initialize {futures} to an empty list. +- For each {deferUsageSet} and {groupedFieldSet} in {newGroupedFieldSets}: + - Let {deferredFragments} be an empty list. + - For each {deferUsage} in {deferUsageSet}: + - Let {deferredFragment} be the entry for {deferUsage} in {deferMap}. + - Append {deferredFragment} to {deferredFragments}. + - Let {future} represent the future execution of + {ExecuteDeferredGroupedFieldSet(groupedFieldSet, objectType, objectValue, + variableValues, deferredFragments, path, deferUsageSet, deferMap)}, + incrementally completing {deferredFragments}. + - Let {deferredFragments} be the list of Deferred Fragments incrementally + completed by {future}. + - If {supplemental} is {true} and any Deferred Fragment in + {deferredFragments} has been released as pending, initiate {future}. + - Otherwise, initiate {future} as soon as any Deferred Fragment in + {deferredFragments} is released as pending, or, if early execution of + deferred fields is desired, following any implementation specific deferral + of further execution. + - Append {future} to {futures}. +- Return {futures}. + +ExecuteDeferredGroupedFieldSet(groupedFieldSet, objectType, objectValue, +variableValues, path, deferUsageSet, deferMap): + +- Let {data}, {newPendingResults}, and {futures} be the result of running + {ExecuteGroupedFieldSet(groupedFieldSet, objectType, objectValue, + variableValues, path, deferUsageSet, deferMap)} _normally_ (allowing + parallelization). +- Let {errors} be the list of all _field error_ raised while executing the + {groupedFieldSet}. +- Let {deferredResult} be an unordered map containing {path}, + {deferredFragments}, {data}, {errors}, {newPendingResults}, and {futures}. +- Return {deferredResult}. + +## Executing a Grouped Field Set + +To execute a grouped field set, the object value being evaluated and the object +type need to be known, as well as whether it must be executed serially, or may +be executed in parallel. + +Each represented field in the grouped field set produces an entry into a +response map. + +ExecuteGroupedFieldSet(groupedFieldSet, objectType, objectValue, variableValues, +path, deferUsageSet, deferMap): -- Let {groupedFieldSet} be the result of {CollectFields(objectType, - selectionSet, variableValues)}. - Initialize {resultMap} to an empty ordered map. +- Initialize {newPendingResults} and {futures} to empty lists. - For each {groupedFieldSet} as {responseKey} and {fields}: - Let {fieldName} be the name of the first entry in {fields}. Note: This value is unaffected if an alias is used. - Let {fieldType} be the return type defined for the field {fieldName} of {objectType}. - If {fieldType} is defined: - - Let {responseValue} be {ExecuteField(objectType, objectValue, fieldType, - fields, variableValues)}. + - Let {responseValue}, {fieldNewPendingResults}, and {fieldFutures} be the + result of {ExecuteField(objectType, objectValue, fieldType, fields, + variableValues, path)}. - Set {responseValue} as the value for {responseKey} in {resultMap}. -- Return {resultMap}. + - Append all items in {fieldNewPendingResults} and {fieldFutures} to + {newPendingResults} and {futures}, respectively. +- Return {resultMap}, {newPendingResults}, and {futures}. Note: {resultMap} is ordered by which fields appear first in the operation. This -is explained in greater detail in the Field Collection section below. +is explained in greater detail in the Field Collection section above. **Errors and Non-Null Fields** -If during {ExecuteSelectionSet()} a field with a non-null {fieldType} raises a -_field error_ then that error must propagate to this entire selection set, +If during {ExecuteGroupedFieldSet()} a field with a non-null {fieldType} raises +a _field error_ then that error must propagate to this entire selection set, either resolving to {null} if allowed or further propagated to a parent field. If this occurs, any sibling fields which have not yet executed or have not yet yielded a value may be cancelled to avoid unnecessary work. +Additionally, Subsequent Result records must not be yielded if their path points +to a location that has resolved to {null} due to propagation of a field error. +If these subsequent results have not yet executed or have not yet yielded a +value they may also be cancelled to avoid unnecessary work. + +For example, assume the field `alwaysThrows` is a `Non-Null` type that always +raises a field error: + +```graphql example +{ + myObject { + ... @defer { + name + } + alwaysThrows + } +} +``` + +In this case, only one response should be sent. The result of the fragment +tagged with the `@defer` directive should be ignored and its execution, if +initiated, may be cancelled. + +```json example +{ + "data": { "myObject": null } +} +``` + Note: See [Handling Field Errors](#sec-Handling-Field-Errors) for more about this behavior. @@ -459,111 +1154,9 @@ A correct executor must generate the following result for that selection set: } ``` -### Field Collection - -Before execution, the selection set is converted to a grouped field set by -calling {CollectFields()}. Each entry in the grouped field set is a list of -fields that share a response key (the alias if defined, otherwise the field -name). This ensures all fields with the same response key (including those in -referenced fragments) are executed at the same time. - -As an example, collecting the fields of this selection set would collect two -instances of the field `a` and one of field `b`: - -```graphql example -{ - a { - subfield1 - } - ...ExampleFragment -} - -fragment ExampleFragment on Query { - a { - subfield2 - } - b -} -``` - -The depth-first-search order of the field groups produced by {CollectFields()} -is maintained through execution, ensuring that fields appear in the executed -response in a stable and predictable order. - -CollectFields(objectType, selectionSet, variableValues, visitedFragments): - -- If {visitedFragments} is not provided, initialize it to the empty set. -- Initialize {groupedFields} to an empty ordered map of lists. -- For each {selection} in {selectionSet}: - - If {selection} provides the directive `@skip`, let {skipDirective} be that - directive. - - If {skipDirective}'s {if} argument is {true} or is a variable in - {variableValues} with the value {true}, continue with the next {selection} - in {selectionSet}. - - If {selection} provides the directive `@include`, let {includeDirective} be - that directive. - - If {includeDirective}'s {if} argument is not {true} and is not a variable - in {variableValues} with the value {true}, continue with the next - {selection} in {selectionSet}. - - If {selection} is a {Field}: - - Let {responseKey} be the response key of {selection} (the alias if - defined, otherwise the field name). - - Let {groupForResponseKey} be the list in {groupedFields} for - {responseKey}; if no such list exists, create it as an empty list. - - Append {selection} to the {groupForResponseKey}. - - If {selection} is a {FragmentSpread}: - - Let {fragmentSpreadName} be the name of {selection}. - - If {fragmentSpreadName} is in {visitedFragments}, continue with the next - {selection} in {selectionSet}. - - Add {fragmentSpreadName} to {visitedFragments}. - - Let {fragment} be the Fragment in the current Document whose name is - {fragmentSpreadName}. - - If no such {fragment} exists, continue with the next {selection} in - {selectionSet}. - - Let {fragmentType} be the type condition on {fragment}. - - If {DoesFragmentTypeApply(objectType, fragmentType)} is false, continue - with the next {selection} in {selectionSet}. - - Let {fragmentSelectionSet} be the top-level selection set of {fragment}. - - Let {fragmentGroupedFieldSet} be the result of calling - {CollectFields(objectType, fragmentSelectionSet, variableValues, - visitedFragments)}. - - For each {fragmentGroup} in {fragmentGroupedFieldSet}: - - Let {responseKey} be the response key shared by all fields in - {fragmentGroup}. - - Let {groupForResponseKey} be the list in {groupedFields} for - {responseKey}; if no such list exists, create it as an empty list. - - Append all items in {fragmentGroup} to {groupForResponseKey}. - - If {selection} is an {InlineFragment}: - - Let {fragmentType} be the type condition on {selection}. - - If {fragmentType} is not {null} and {DoesFragmentTypeApply(objectType, - fragmentType)} is false, continue with the next {selection} in - {selectionSet}. - - Let {fragmentSelectionSet} be the top-level selection set of {selection}. - - Let {fragmentGroupedFieldSet} be the result of calling - {CollectFields(objectType, fragmentSelectionSet, variableValues, - visitedFragments)}. - - For each {fragmentGroup} in {fragmentGroupedFieldSet}: - - Let {responseKey} be the response key shared by all fields in - {fragmentGroup}. - - Let {groupForResponseKey} be the list in {groupedFields} for - {responseKey}; if no such list exists, create it as an empty list. - - Append all items in {fragmentGroup} to {groupForResponseKey}. -- Return {groupedFields}. - -DoesFragmentTypeApply(objectType, fragmentType): - -- If {fragmentType} is an Object Type: - - if {objectType} and {fragmentType} are the same type, return {true}, - otherwise return {false}. -- If {fragmentType} is an Interface Type: - - if {objectType} is an implementation of {fragmentType}, return {true} - otherwise return {false}. -- If {fragmentType} is a Union: - - if {objectType} is a possible type of {fragmentType}, return {true} - otherwise return {false}. - -Note: The steps in {CollectFields()} evaluating the `@skip` and `@include` -directives may be applied in either order since they apply commutatively. +When subsections contain a `@stream` or `@defer` directive, these subsections +are no longer required to execute serially. Execution of the deferred or +streamed sections of the subsection may be executed in parallel. ## Executing Fields @@ -573,16 +1166,19 @@ coerces any provided argument values, then resolves a value for the field, and finally completes that value either by recursively executing another selection set or coercing a scalar value. -ExecuteField(objectType, objectValue, fieldType, fields, variableValues): +ExecuteField(objectType, objectValue, fieldType, fieldDetailsList, +variableValues, path, deferUsageSet, deferMap): -- Let {field} be the first entry in {fields}. -- Let {fieldName} be the field name of {field}. +- Let {fieldDetails} be the first entry in {fieldDetailsList}. +- Let {node} be the corresponding entry on {fieldDetails}. +- Let {fieldName} be the field name of {node}. +- Append {fieldName} to {path}. - Let {argumentValues} be the result of {CoerceArgumentValues(objectType, field, variableValues)} - Let {resolvedValue} be {ResolveFieldValue(objectType, objectValue, fieldName, argumentValues)}. - Return the result of {CompleteValue(fieldType, fields, resolvedValue, - variableValues)}. + variableValues, path, deferUsageSet, deferMap)}. ### Coercing Field Arguments @@ -651,6 +1247,12 @@ As an example, this might accept the {objectType} `Person`, the {field} {"soulMate"}, and the {objectValue} representing John Lennon. It would be expected to yield the value representing Yoko Ono. +List values are resolved similarly. For example, {ResolveFieldValue} might also +accept the {objectType} `MusicBand`, the {field} {"members"}, and the +{objectValue} representing the Beatles. It would be expected to yield a +collection of values representing John Lennon, Paul McCartney, Ringo Starr and +George Harrison. + ResolveFieldValue(objectType, objectValue, fieldName, argumentValues): - Let {resolver} be the internal function provided by {objectType} for @@ -661,30 +1263,76 @@ ResolveFieldValue(objectType, objectValue, fieldName, argumentValues): Note: It is common for {resolver} to be asynchronous due to relying on reading an underlying database or networked service to produce a value. This necessitates the rest of a GraphQL executor to handle an asynchronous execution -flow. +flow. In addition, an implementation for collections may leverage asynchronous +iterators or asynchronous generators provided by many programming languages. +This may be particularly helpful when used in conjunction with the `@stream` +directive. ### Value Completion After resolving the value for a field, it is completed by ensuring it adheres to the expected return type. If the return type is another Object type, then the -field execution process continues recursively. +field execution process continues recursively. If the return type is a List +type, each member of the resolved collection is completed using the same value +completion process. In the case where `@stream` is specified on a field of list +type, value completion iterates over the collection until the number of items +yielded items satisfies `initialCount` specified on the `@stream` directive. -CompleteValue(fieldType, fields, result, variableValues): +CompleteValue(fieldType, fieldDetailsList, result, variableValues, path, +deferUsageSet, deferMap): - If the {fieldType} is a Non-Null type: - Let {innerType} be the inner type of {fieldType}. - - Let {completedResult} be the result of calling {CompleteValue(innerType, - fields, result, variableValues)}. + - Let {completedResult}, {newPendingResults}, and {futures} be the result of + calling {CompleteValue(innerType, fields, result, variableValues, path)}. - If {completedResult} is {null}, raise a _field error_. - - Return {completedResult}. + - Return {completedResult}, {newPendingResults}, and {futures}. - If {result} is {null} (or another internal value similar to {null} such as {undefined}), return {null}. - If {fieldType} is a List type: + - Initialize {newPendingResults} and {futures} to empty lists. - If {result} is not a collection of values, raise a _field error_. + - Let {field} be the first entry in {fields}. - Let {innerType} be the inner type of {fieldType}. - - Return a list where each list item is the result of calling - {CompleteValue(innerType, fields, resultItem, variableValues)}, where - {resultItem} is each item in {result}. + - If {field} provides the directive `@stream` and its {if} argument is not + {false} and is not a variable in {variableValues} with the value {false} and + {innerType} is the outermost return type of the list type defined for + {field}: + - Let {streamDirective} be that directive. + - If this execution is for a subscription operation, raise a _field error_. + - Let {initialCount} be the value or variable provided to + {streamDirective}'s {initialCount} argument. + - If {initialCount} is less than zero, raise a _field error_. + - Let {label} be the value or variable provided to {streamDirective}'s + {label} argument. + - Let {iterator} be an iterator for {result}. + - Let {items} be an empty list. + - Let {index} be zero. + - While {result} is not closed: + - If {streamDirective} is defined and {index} is greater than or equal to + {initialCount}: + - Let {stream} be an unordered map containing {path} and {label}. + - Let {streamFieldDetails} be the result of + {GetStreamFieldDetailsList(fieldDetailsList)}. + - Let {future} represent the future execution of + {ExecuteStreamField(stream, iterator, streamFieldDetailsList, index, + innerType, variableValues)}. + - If early execution of streamed fields is desired: + - Following any implementation specific deferral of further execution, + initiate {future}. + - Append {future} to {futures}. + - Return {items}, {newPendingResults}, and {futures}. + - Wait for the next item from {result} via the {iterator}. + - If an item is not retrieved because of an error, raise a _field error_. + - Let {item} be the item retrieved from {result}. + - Let {itemPath} be {path} with {index} appended. + - Let {completedItem}, {itemNewPendingResults}, and {itemFutures} be the + result of calling {CompleteValue(innerType, fields, item, variableValues, + itemPath)}. + - Append {completedItem} to {items}. + - Append all items in {itemNewPendingResults}, and {itemFutures} to + {newPendingResults}, and {futures}, respectively. + - Return {items}, {newPendingResults}, and {futures}. - If {fieldType} is a Scalar or Enum type: - Return the result of {CoerceResult(fieldType, result)}. - If {fieldType} is an Object, Interface, or Union type: @@ -692,10 +1340,48 @@ CompleteValue(fieldType, fields, result, variableValues): - Let {objectType} be {fieldType}. - Otherwise if {fieldType} is an Interface or Union type. - Let {objectType} be {ResolveAbstractType(fieldType, result)}. - - Let {subSelectionSet} be the result of calling {MergeSelectionSets(fields)}. - - Return the result of evaluating {ExecuteSelectionSet(subSelectionSet, - objectType, result, variableValues)} _normally_ (allowing for - parallelization). + - Let {groupedFieldSet} and {newDeferUsages} be the result of calling + {CollectSubfields(objectType, fieldDetailsList, variableValues)}. + - Let {fieldPlan} be the result of {BuildFieldPlan(groupedFieldSet, + deferUsageSet)}. + - Return the result of {ExecuteFieldPlan(newDeferUsages, fieldPlan, + objectType, result, variableValues, false, path, deferUsageSet, deferMap)}. + +GetStreamFieldDetailsList(fieldDetailsList): + +- Let {streamFields} be an empty list. +- For each {fieldDetails} in {fieldDetailsList}: + - Let {node} be the corresponding entry on {fieldDetails}. + - Let {newFieldDetails} be a new Field Details record created from {node}. + - Append {newFieldDetails} to {streamFields}. +- Return {streamFields}. + +#### Execute Stream Field + +ExecuteStreamField(stream, iterator, fieldDetailsList, index, innerType, +variableValues): + +- Let {path} be the corresponding entry on {stream}. +- Let {itemPath} be {path} with {index} appended. +- Wait for the next item from {iterator}. +- If {iterator} is closed, complete this data stream and return. +- Let {item} be the next item retrieved via {iterator}. +- Let {nextIndex} be {index} plus one. +- Let {completedItem}, {newPendingResults}, and {futures} be the result of + {CompleteValue(innerType, fields, item, variableValues, itemPath)}. +- Initialize {items} to an empty list. +- Append {completedItem} to {items}. +- Let {errors} be the list of all _field error_ raised while completing the + item. +- Let {future} represent the future execution of {ExecuteStreamField(stream, + path, iterator, fieldDetailsList, nextIndex, innerType, variableValues)}. +- If early execution of streamed fields is desired: + - Following any implementation specific deferral of further execution, + initiate {future}. +- Append {future} to {futures}. +- Let {streamedItems} be an unordered map containing {stream}, {items} {errors}, + {newPendingResults}, and {futures}. +- Return {streamedItem}. **Coercing Results** @@ -740,9 +1426,9 @@ ResolveAbstractType(abstractType, objectValue): **Merging Selection Sets** -When more than one field of the same name is executed in parallel, their -selection sets are merged together when completing the value in order to -continue execution of the sub-selection sets. +When more than one field of the same name is executed in parallel, during value +completion their selection sets are collected together to produce a single +grouped field set in order to continue execution of the sub-selection sets. An example operation illustrating parallel fields with the same name with sub-selections. @@ -761,14 +1447,22 @@ sub-selections. After resolving the value for `me`, the selection sets are merged together so `firstName` and `lastName` can be resolved for one value. -MergeSelectionSets(fields): +CollectSubfields(objectType, fieldDetailsList, variableValues): -- Let {selectionSet} be an empty list. -- For each {field} in {fields}: +- Initialize {groupedFieldSet} to an empty ordered map of lists. +- Initialize {newDeferUsages} to an empty list. +- For each {fieldDetails} in {fieldDetailsList}: + - Let {field} and {deferUsage} be the corresponding entries on {fieldDetails}. - Let {fieldSelectionSet} be the selection set of {field}. - If {fieldSelectionSet} is null or empty, continue to the next field. - - Append all selections in {fieldSelectionSet} to {selectionSet}. -- Return {selectionSet}. + - Let {subGroupedFieldSet} and {subNewDeferUsages} be the result of + {CollectFields(objectType, fieldSelectionSet, variableValues, deferUsage)}. + - For each {subGroupedFieldSet} as {responseKey} and {subfields}: + - Let {groupForResponseKey} be the list in {groupedFieldSet} for + {responseKey}; if no such list exists, create it as an empty list. + - Append all fields in {subfields} to {groupForResponseKey}. + - Append all defer usages in {subNewDeferUsages} to {newDeferUsages}. +- Return {groupedFieldSet}. ### Handling Field Errors @@ -803,6 +1497,160 @@ resolves to {null}, then the entire list must resolve to {null}. If the `List` type is also wrapped in a `Non-Null`, the field error continues to propagate upwards. +When a field error is raised inside `ExecuteDeferredGroupedFieldSet` or +`ExecuteStreamField`, the defer and stream payloads act as error boundaries. +That is, the null resulting from a `Non-Null` type cannot propagate outside of +the boundary of the defer or stream payload. + +If a field error is raised while executing the selection set of a fragment with +the `defer` directive, causing a {null} to propagate to the object containing +this fragment, the {null} should not be sent to the client, as this will +overwrite existing data. In this case, the associated Defer Payload's +`completed` entry must include the causative errors, whose presence indicated +the failure of the payload to be included within the final reconcilable object. + +For example, assume the `month` field is a `Non-Null` type that raises a field +error: + +```graphql example +{ + birthday { + ... @defer(label: "monthDefer") { + month + } + ... @defer(label: "yearDefer") { + year + } + } +} +``` + +Response 1, the initial response is sent: + +```json example +{ + "data": { "birthday": {} }, + "pending": [ + { "path": ["birthday"], "label": "monthDefer" } + { "path": ["birthday"], "label": "yearDefer" } + ], + "hasNext": true +} +``` + +Response 2, the defer payload for label "monthDefer" is completed with errors. +Incremental data cannot be sent, as this would overwrite previously sent values. + +```json example +{ + "completed": [ + { + "path": ["birthday"], + "label": "monthDefer", + "errors": [...] + } + ], + "hasNext": false +} +``` + +Response 3, the defer payload for label "yearDefer" is sent. The data in this +payload is unaffected by the previous null error. + +```json example +{ + "incremental": [ + { + "path": ["birthday"], + "data": { "year": "2022" } + } + ], + "completed": [ + { + "path": ["birthday"], + "label": "yearDefer" + } + ], + "hasNext": false +} +``` + +If the `stream` directive is present on a list field with a Non-Nullable inner +type, and a field error has caused a {null} to propagate to the list item, the +{null} similarly should not be sent to the client, as this will overwrite +existing data. In this case, the associated Stream's `completed` entry must +include the causative errors, whose presence indicated the failure of the stream +to complete successfully. For example, assume the `films` field is a `List` type +with an `Non-Null` inner type. In this case, the second list item raises a field +error: + +```graphql example +{ + films @stream(initialCount: 1) +} +``` + +Response 1, the initial response is sent: + +```json example +{ + "data": { "films": ["A New Hope"] }, + "pending": [{ "path": ["films"] }], + "hasNext": true +} +``` + +Response 2, the stream is completed with errors. Incremental data cannot be +sent, as this would overwrite previously sent values. + +```json example +{ + "completed": [ + { + "path": ["films"], + "errors": [...], + } + ], + "hasNext": false +} +``` + +In this alternative example, assume the `films` field is a `List` type without a +`Non-Null` inner type. In this case, the second list item also raises a field +error: + +```graphql example +{ + films @stream(initialCount: 1) +} +``` + +Response 1, the initial response is sent: + +```json example +{ + "data": { "films": ["A New Hope"] }, + "hasNext": true +} +``` + +Response 2, the first stream payload is sent; the stream is not completed. The +{items} entry has been set to a list containing {null}, as this {null} has only +propagated as high as the list item. + +```json example +{ + "incremental": [ + { + "path": ["films", 1], + "items": [null], + "errors": [...], + } + ], + "hasNext": true +} +``` + If all fields from the root of the request to the source of the field error return `Non-Null` types, then the {"data"} entry in the response should be {null}. diff --git a/spec/Section 7 -- Response.md b/spec/Section 7 -- Response.md index 8dcd9234c..45d24a59e 100644 --- a/spec/Section 7 -- Response.md +++ b/spec/Section 7 -- Response.md @@ -10,7 +10,7 @@ the case that any _field error_ was raised on a field and was replaced with ## Response Format -A response to a GraphQL request must be a map. +A response to a GraphQL request must be a map or a response stream of maps. If the request raised any errors, the response map must contain an entry with key `errors`. The value of this entry is described in the "Errors" section. If @@ -22,14 +22,40 @@ key `data`. The value of this entry is described in the "Data" section. If the request failed before execution, due to a syntax error, missing information, or validation error, this entry must not be present. +When the response of the GraphQL operation is a response stream, the first value +will be the initial response. All subsequent values may contain an `incremental` +entry, containing a list of Defer or Stream payloads. + +The `label` and `path` entries on Defer and Stream payloads are used by clients +to identify the `@defer` or `@stream` directive from the GraphQL operation that +triggered this response to be included in an `incremental` entry on a value +returned by the response stream. When a label is provided, the combination of +these two entries will be unique across all Defer and Stream payloads returned +in the response stream. + +If the response of the GraphQL operation is a response stream, each response map +must contain an entry with key `hasNext`. The value of this entry is `true` for +all but the last response in the stream. The value of this entry is `false` for +the last response of the stream. This entry must not be present for GraphQL +operations that return a single response map. + +The GraphQL service may determine there are no more values in the response +stream after a previous value with `hasNext` equal to `true` has been emitted. +In this case the last value in the response stream should be a map without +`data` and `incremental` entries, and a `hasNext` entry with a value of `false`. + The response map may also contain an entry with key `extensions`. This entry, if set, must have a map as its value. This entry is reserved for implementors to extend the protocol however they see fit, and hence there are no additional -restrictions on its contents. +restrictions on its contents. When the response of the GraphQL operation is a +response stream, implementors may send subsequent response maps containing only +`hasNext` and `extensions` entries. Defer and Stream payloads may also contain +an entry with the key `extensions`, also reserved for implementors to extend the +protocol however they see fit. To ensure future changes to the protocol do not break existing services and clients, the top level response map must not contain any entries other than the -three described above. +five described above. Note: When `errors` is present in the response, it may be helpful for it to appear first when serialized to make it more clear when errors are present in a @@ -107,14 +133,8 @@ syntax element. If an error can be associated to a particular field in the GraphQL result, it must contain an entry with the key `path` that details the path of the response field which experienced the error. This allows clients to identify whether a -`null` result is intentional or caused by a runtime error. - -This field should be a list of path segments starting at the root of the -response and ending with the field associated with the error. Path segments that -represent fields should be strings, and path segments that represent list -indices should be 0-indexed integers. If the error happens in an aliased field, -the path to the error should use the aliased name, since it represents a path in -the response, not in the request. +`null` result is intentional or caused by a runtime error. The value of this +field is described in the [Path](#sec-Path) section. For example, if fetching one of the friends' names fails in the following operation: @@ -244,6 +264,172 @@ discouraged. } ``` +### Incremental Delivery + +The `pending` entry in the response is a non-empty list of references to pending +Defer or Stream results. If the response of the GraphQL operation is a response +stream, this field should appear on the initial and possibly subsequent +payloads. + +The `incremental` entry in the response is a non-empty list of data fulfilling +Defer or Stream results. If the response of the GraphQL operation is a response +stream, this field may appear on the subsequent payloads. + +The `completed` entry in the response is a non-empty list of references to +completed Defer or Stream results. + +For example, a query containing both defer and stream: + +```graphql example +query { + person(id: "cGVvcGxlOjE=") { + ...HomeWorldFragment @defer(label: "homeWorldDefer") + name + films @stream(initialCount: 1, label: "filmsStream") { + title + } + } +} +fragment HomeWorldFragment on Person { + homeWorld { + name + } +} +``` + +The response stream might look like: + +Response 1, the initial response does not contain any deferred or streamed +results. + +```json example +{ + "data": { + "person": { + "name": "Luke Skywalker", + "films": [{ "title": "A New Hope" }] + } + }, + "pending": [ + { "path": ["person"], "label": "homeWorldDefer" }, + { "path": ["person", "films"], "label": "filmStream" } + ], + "hasNext": true +} +``` + +Response 2, contains the defer payload and the first stream payload. + +```json example +{ + "incremental": [ + { + "path": ["person"], + "data": { "homeWorld": { "name": "Tatooine" } } + }, + { + "path": ["person", "films"], + "items": [{ "title": "The Empire Strikes Back" }] + } + ], + "completed": [{ "path": ["person"], "label": "homeWorldDefer" }], + "hasNext": true +} +``` + +Response 3, contains the final stream payload. In this example, the underlying +iterator does not close synchronously so {hasNext} is set to {true}. If this +iterator did close synchronously, {hasNext} would be set to {false} and this +would be the final response. + +```json example +{ + "incremental": [ + { + "path": ["person", "films"], + "items": [{ "title": "Return of the Jedi" }] + } + ], + "hasNext": true +} +``` + +Response 4, contains no incremental payloads. {hasNext} set to {false} indicates +the end of the response stream. This response is sent when the underlying +iterator of the `films` field closes. + +```json example +{ + "completed": [{ "path": ["person", "films"], "label": "filmStream" }], + "hasNext": false +} +``` + +#### Streamed data + +Streamed data may appear as an item in the `incremental` entry of a response. +Streamed data is the result of an associated `@stream` directive in the +operation. A stream payload must contain `items` and `path` entries and may +contain `errors`, and `extensions` entries. + +##### Items + +The `items` entry in a stream payload is a list of results from the execution of +the associated @stream directive. This output will be a list of the same type of +the field with the associated `@stream` directive. If an error has caused a +`null` to bubble up to a field higher than the list field with the associated +`@stream` directive, then the stream will complete with errors. + +#### Deferred data + +Deferred data is a map that may appear as an item in the `incremental` entry of +a response. Deferred data is the result of an associated `@defer` directive in +the operation. A defer payload must contain `data` and `path` entries and may +contain `errors`, and `extensions` entries. + +##### Data + +The `data` entry in a Defer payload will be of the type of a particular field in +the GraphQL result. The adjacent `path` field will contain the path segments of +the field this data is associated with. If an error has caused a `null` to +bubble up to a field higher than the field that contains the fragment with the +associated `@defer` directive, then the fragment will complete with errors. + +#### Path + +A `path` field allows for the association to a particular field in a GraphQL +result. This field should be a list of path segments starting at the root of the +response and ending with the field to be associated with. Path segments that +represent fields should be strings, and path segments that represent list +indices should be 0-indexed integers. If the path is associated to an aliased +field, the path should use the aliased name, since it represents a path in the +response, not in the request. + +When the `path` field is present on a Stream payload, it indicates that the +`items` field represents the partial result of the list field containing the +corresponding `@stream` directive. All but the non-final path segments must +refer to the location of the list field containing the corresponding `@stream` +directive. The final segment of the path list must be a 0-indexed integer. This +integer indicates that this result is set at a range, where the beginning of the +range is at the index of this integer, and the length of the range is the length +of the data. + +When the `path` field is present on a Defer payload, it indicates that the +`data` field represents the result of the fragment containing the corresponding +`@defer` directive. The path segments must point to the location of the result +of the field containing the associated `@defer` directive. + +When the `path` field is present on an "Error result", it indicates the response +field which experienced the error. + +#### Label + +Stream and Defer payloads may contain a string field `label`. This `label` is +the same label passed to the `@defer` or `@stream` directive associated with the +response. This allows clients to identify which `@defer` or `@stream` directive +is associated with this value. `label` will not be present if the corresponding +`@defer` or `@stream` directive is not passed a `label` argument. + ## Serialization Format GraphQL does not require a specific serialization format. However, clients