lighthouse-graphql 0.8.2 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +152 -1
- data/docs/authorization.md +5 -1
- data/docs/configuration.md +71 -3
- data/docs/custom-directives.md +22 -0
- data/docs/defer.md +352 -0
- data/docs/directives.md +102 -0
- data/docs/events.md +30 -1
- data/docs/filtering-and-ordering.md +488 -0
- data/docs/getting-started.md +1 -1
- data/docs/performance.md +9 -0
- data/docs/resolvers.md +14 -2
- data/docs/testing.md +99 -0
- data/lib/lighthouse/complexity.rb +4 -2
- data/lib/lighthouse/config.rb +28 -11
- data/lib/lighthouse/contracts/field_resolver.rb +32 -0
- data/lib/lighthouse/contracts/search_builder.rb +16 -0
- data/lib/lighthouse/controller.rb +94 -18
- data/lib/lighthouse/defer.rb +114 -0
- data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +1 -0
- data/lib/lighthouse/directive_resolvers/all_resolver.rb +30 -1
- data/lib/lighthouse/directive_resolvers/argument_binding.rb +1 -3
- data/lib/lighthouse/directive_resolvers/association_resolvers.rb +1 -0
- data/lib/lighthouse/directive_resolvers/base.rb +99 -49
- data/lib/lighthouse/directive_resolvers/builder_applier.rb +24 -18
- data/lib/lighthouse/directive_resolvers/can_resolvers.rb +28 -2
- data/lib/lighthouse/directive_resolvers/count_resolver.rb +1 -0
- data/lib/lighthouse/directive_resolvers/field_resolver.rb +4 -0
- data/lib/lighthouse/directive_resolvers/find_resolver.rb +31 -16
- data/lib/lighthouse/directive_resolvers/first_resolver.rb +6 -3
- data/lib/lighthouse/directive_resolvers/global_id_types.rb +1 -2
- data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +2 -0
- data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +27 -4
- data/lib/lighthouse/directive_resolvers/throttle_resolver.rb +17 -6
- data/lib/lighthouse/directives/arguments/base.rb +14 -0
- data/lib/lighthouse/directives/arguments/filters.rb +6 -0
- data/lib/lighthouse/directives/arguments/more_filters.rb +3 -0
- data/lib/lighthouse/directives/arguments/search.rb +34 -0
- data/lib/lighthouse/directives/arguments/soft_deletes.rb +11 -0
- data/lib/lighthouse/directives/model_directive.rb +1 -1
- data/lib/lighthouse/directives/registry.rb +1 -1
- data/lib/lighthouse/events/execution_trace.rb +6 -1
- data/lib/lighthouse/events/lifecycle.rb +2 -1
- data/lib/lighthouse/events.rb +9 -0
- data/lib/lighthouse/field_resolver_stack.rb +22 -21
- data/lib/lighthouse/graphql/version.rb +1 -1
- data/lib/lighthouse/incremental/body.rb +76 -0
- data/lib/lighthouse/incremental/defer_directive.rb +34 -0
- data/lib/lighthouse/incremental/delivery.rb +94 -0
- data/lib/lighthouse/incremental/document.rb +242 -0
- data/lib/lighthouse/incremental/gone.rb +6 -0
- data/lib/lighthouse/incremental/legacy.rb +75 -0
- data/lib/lighthouse/incremental/multipart.rb +76 -0
- data/lib/lighthouse/incremental/plan.rb +249 -0
- data/lib/lighthouse/incremental/rules.rb +116 -0
- data/lib/lighthouse/incremental/run.rb +302 -0
- data/lib/lighthouse/incremental/serializer.rb +37 -0
- data/lib/lighthouse/incremental/state.rb +204 -0
- data/lib/lighthouse/incremental/stream_directive.rb +41 -0
- data/lib/lighthouse/incremental/stream_trace.rb +93 -0
- data/lib/lighthouse/incremental/tree.rb +68 -0
- data/lib/lighthouse/namespaces.rb +2 -0
- data/lib/lighthouse/nested_mutations/belongs_to_operations.rb +2 -2
- data/lib/lighthouse/operations.rb +6 -2
- data/lib/lighthouse/pagination.rb +61 -15
- data/lib/lighthouse/persisted_queries.rb +53 -8
- data/lib/lighthouse/rb_lighthouse.rb +34 -0
- data/lib/lighthouse/resolve_info.rb +7 -1
- data/lib/lighthouse/search/auto.rb +21 -0
- data/lib/lighthouse/search/enhancer.rb +127 -0
- data/lib/lighthouse/search/field_check.rb +171 -0
- data/lib/lighthouse/search/pg_search.rb +76 -0
- data/lib/lighthouse/search/query.rb +35 -0
- data/lib/lighthouse/search/result.rb +181 -0
- data/lib/lighthouse/search/searchkick.rb +292 -0
- data/lib/lighthouse/search/searchkick_index.rb +54 -0
- data/lib/lighthouse/search/searchkick_options.rb +74 -0
- data/lib/lighthouse/search.rb +78 -0
- data/lib/lighthouse/support/argument_walk.rb +81 -0
- data/lib/lighthouse/support/count.rb +16 -0
- data/lib/lighthouse/support/failures.rb +28 -0
- data/lib/lighthouse/support/memo.rb +72 -0
- data/lib/lighthouse/support/model_resolver.rb +24 -0
- data/lib/lighthouse/support/relations.rb +31 -0
- data/lib/lighthouse/support/soft_deletes.rb +42 -8
- data/lib/lighthouse/testing.rb +81 -0
- data/sig/lighthouse/controller.rbs +34 -1
- data/sig/lighthouse/directives.rbs +46 -5
- data/sig/lighthouse/events.rbs +7 -0
- data/sig/lighthouse/graphql.rbs +117 -0
- data/sig/lighthouse/search.rbs +132 -0
- data/sig/lighthouse.rbs +69 -1
- metadata +38 -1
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'set'
|
|
4
|
+
|
|
5
|
+
# The rules @defer and @stream follow, checked for every query of a schema that
|
|
6
|
+
# uses Defer however it runs: streamed, answered whole to a JSON client, through
|
|
7
|
+
# `schema.execute`, in a batch. A graphql-ruby query analyzer (Defer.use installs
|
|
8
|
+
# it), so a query that breaks them gets the errors and no data, as a validation
|
|
9
|
+
# error would. The analyzer sees the selected operation with its fragment spreads
|
|
10
|
+
# inlined: a named fragment is checked where it is spread, under the operation and
|
|
11
|
+
# the type it runs on.
|
|
12
|
+
#
|
|
13
|
+
# From the specification draft (section 5.7), with PHP Lighthouse's message where it has one:
|
|
14
|
+
#
|
|
15
|
+
# - `label` is a String literal, not a variable, and no two directives of the
|
|
16
|
+
# document share it (every operation and fragment of it, as a validation rule
|
|
17
|
+
# would see them, not only those of the operation that runs);
|
|
18
|
+
# - @defer and @stream are not used on a root mutation field, whose fields must run
|
|
19
|
+
# one after the other ("The @defer directive cannot be used on a root mutation
|
|
20
|
+
# field.", as PHP Lighthouse words it), whether the fragment is inline or named;
|
|
21
|
+
# - in a subscription, they are disabled with `if: false`, or a variable that is false;
|
|
22
|
+
# - @stream is on a list field.
|
|
23
|
+
#
|
|
24
|
+
# A query whose text names neither directive, or whose document (given as one) has
|
|
25
|
+
# neither, is not walked (`analyze?`). A named fragment spread at several places is
|
|
26
|
+
# checked at each, and an error reported once a directive.
|
|
27
|
+
class Lighthouse::GraphQL::Incremental::Rules < GraphQL::Analysis::Analyzer
|
|
28
|
+
def initialize(subject)
|
|
29
|
+
super
|
|
30
|
+
@errors = []
|
|
31
|
+
@reported = Set.new
|
|
32
|
+
@definitions = Lighthouse::GraphQL::Incremental::Document::Definitions.new(subject.schema)
|
|
33
|
+
end
|
|
34
|
+
|
|
35
|
+
# The text the query was given (graphql-ruby's Query#query_string would print a document given
|
|
36
|
+
# instead): the names defer and stream in it first, the document's walk only where it has one.
|
|
37
|
+
def analyze?
|
|
38
|
+
text = query.instance_variable_get(:@query_string)
|
|
39
|
+
return false if text.is_a?(String) && !Lighthouse::GraphQL::Incremental::Document::INCREMENTAL.match?(text)
|
|
40
|
+
|
|
41
|
+
Lighthouse::GraphQL::Incremental::Document.incremental?(query.document)
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
# The fragment's type is on the visitor's stack already: the selection set's is the one below it.
|
|
45
|
+
def on_enter_inline_fragment(node, _parent, visitor)
|
|
46
|
+
check(node, 'defer', visitor.parent_type_definition)
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# Called before the visitor enters the fragment's type.
|
|
50
|
+
def on_enter_fragment_spread(node, _parent, visitor)
|
|
51
|
+
check(node, 'defer', visitor.type_definition)
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
def on_enter_field(node, _parent, visitor)
|
|
55
|
+
stream = check(node, 'stream', visitor.parent_type_definition) or return
|
|
56
|
+
field = visitor.field_definition
|
|
57
|
+
error(stream, 'The @stream directive must be used on a list field.') if field && !field.type.list?
|
|
58
|
+
end
|
|
59
|
+
|
|
60
|
+
def result = labels + @errors
|
|
61
|
+
|
|
62
|
+
private
|
|
63
|
+
|
|
64
|
+
# The node's directive `name`, checked where it is; nil without one. `parent_type`: the type of
|
|
65
|
+
# the selection set the node is in.
|
|
66
|
+
def check(node, name, parent_type)
|
|
67
|
+
directive = node.directives.find { |candidate| candidate.name == name } or return nil
|
|
68
|
+
error(directive, "The @#{name} directive cannot be used on a root mutation field.") if mutation_root?(parent_type)
|
|
69
|
+
check_subscription(directive)
|
|
70
|
+
directive
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def mutation_root?(type)
|
|
74
|
+
!type.nil? && type == query.schema.root_type_for_operation('mutation')
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# A subscription's directive is disabled: `if: false`, or a variable that is false here (the draft
|
|
78
|
+
# allows a variable, and forbids incremental delivery in a subscription, so a true one is refused).
|
|
79
|
+
def check_subscription(directive)
|
|
80
|
+
return unless query.selected_operation.operation_type == 'subscription'
|
|
81
|
+
return if query.arguments_for(directive, @definitions[directive.name])[:if] == false
|
|
82
|
+
|
|
83
|
+
error(directive, "The @#{directive.name} directive must be disabled with `if: false` in a subscription.")
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# The errors of the labels of the whole document, in its order.
|
|
87
|
+
def labels
|
|
88
|
+
seen = {}
|
|
89
|
+
directives(query.document.definitions).filter_map do |directive|
|
|
90
|
+
label = directive.arguments.find { |argument| argument.name == 'label' }&.value
|
|
91
|
+
variable = label.is_a?(::GraphQL::Language::Nodes::VariableIdentifier)
|
|
92
|
+
next failure(directive, "The label of @#{directive.name} must be a String literal, not a variable.") if variable
|
|
93
|
+
next unless label.is_a?(String) # none, or null: no label
|
|
94
|
+
next failure(directive, "The label \"#{label}\" is used by more than one @defer or @stream in the document.") if seen.key?(label)
|
|
95
|
+
|
|
96
|
+
seen[label] = true
|
|
97
|
+
nil
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Every @defer and @stream of the definitions, each fragment definition once (it is one).
|
|
102
|
+
def directives(definitions)
|
|
103
|
+
[].tap do |found|
|
|
104
|
+
definitions.select { |definition| definition.respond_to?(:selections) }.each do |definition|
|
|
105
|
+
Lighthouse::GraphQL::Incremental::Document.visit_directives(definition.selections) { |directive, _| found << directive }
|
|
106
|
+
end
|
|
107
|
+
end
|
|
108
|
+
end
|
|
109
|
+
|
|
110
|
+
# An error, once for a node.
|
|
111
|
+
def error(node, message)
|
|
112
|
+
@errors << failure(node, message) if @reported.add?([node.object_id, message])
|
|
113
|
+
end
|
|
114
|
+
|
|
115
|
+
def failure(node, message) = ::GraphQL::AnalysisError.new(message, ast_node: node)
|
|
116
|
+
end
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# One operation, run in as many passes as @defer asks for.
|
|
4
|
+
#
|
|
5
|
+
# run = Lighthouse::GraphQL::Incremental::Run.new(schema, query, variables: {}, context: {}).start
|
|
6
|
+
# run.result # the first pass, as `schema.execute` answers it
|
|
7
|
+
# run.deferred? # fragments are pending
|
|
8
|
+
# run.each_payload { |payload| ... } # the initial payload, then one per round
|
|
9
|
+
#
|
|
10
|
+
# `start` runs the client's document as it came, through the schema's `execute` (an
|
|
11
|
+
# app's own too), parsed once, as a GraphQL::Query whose `query_string` is the client's: validation, analysis
|
|
12
|
+
# (complexity, depth, and Rules, which checks @defer and @stream), listeners and
|
|
13
|
+
# tracing see what they would without @defer. DeferDirective leaves the deferred
|
|
14
|
+
# fragments out of the execution, and State keeps them.
|
|
15
|
+
#
|
|
16
|
+
# Then it goes in rounds, as PHP Lighthouse's Defer: each round runs every
|
|
17
|
+
# fragment pending, on the object it was found on, as Plan cuts them into units
|
|
18
|
+
# (GraphQL::Query::Partial), all in one `schema.multiplex` so the Dataloader batches
|
|
19
|
+
# across them (and in a pass after it, those Plan plans below the object fields they
|
|
20
|
+
# resolve), and is one payload; the fragments they hold are announced in it, and
|
|
21
|
+
# make the next round. A field resolves once: what the response already holds is not
|
|
22
|
+
# run again, and a mutation does not run again (PHP Lighthouse runs the whole
|
|
23
|
+
# query again each round).
|
|
24
|
+
#
|
|
25
|
+
# PHP Lighthouse's limits, 0 for none: past Config.defer_max_nested_fields rounds,
|
|
26
|
+
# or once Config.defer_max_execution_ms milliseconds have gone since the first
|
|
27
|
+
# pass started, the round that runs is the last: the fragments it holds run
|
|
28
|
+
# where they stand, and its lists are answered whole.
|
|
29
|
+
#
|
|
30
|
+
# A client that does not stream is answered by `schema.execute`, the whole
|
|
31
|
+
# response at once, as the specification allows.
|
|
32
|
+
#
|
|
33
|
+
# The payloads are the draft's (Serializer); with `format: :legacy`, the client is sent each in
|
|
34
|
+
# Apollo's older format instead (Legacy).
|
|
35
|
+
class Lighthouse::GraphQL::Incremental::Run
|
|
36
|
+
State = Lighthouse::GraphQL::Incremental::State
|
|
37
|
+
Serializer = Lighthouse::GraphQL::Incremental::Serializer
|
|
38
|
+
|
|
39
|
+
attr_reader :result
|
|
40
|
+
|
|
41
|
+
# `options`: `schema.execute`'s (variables:, operation_name:, context:, ...). `format`: the
|
|
42
|
+
# payloads' (:draft, or :legacy for Apollo's older one).
|
|
43
|
+
def initialize(schema, query_string, format: :draft, **options)
|
|
44
|
+
@schema = schema
|
|
45
|
+
@query_string = query_string
|
|
46
|
+
@options = options
|
|
47
|
+
@queue = []
|
|
48
|
+
@announced = []
|
|
49
|
+
@pendings = {}
|
|
50
|
+
@legacy = Lighthouse::GraphQL::Incremental::Legacy.new(@pendings) if format == :legacy
|
|
51
|
+
@next_id = 0
|
|
52
|
+
@running = []
|
|
53
|
+
@round = 0
|
|
54
|
+
@errors = []
|
|
55
|
+
@open = {}
|
|
56
|
+
@found = Set.new
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# Runs the first pass. The block, if given, gets what ends the operation (`finish`): the first
|
|
60
|
+
# pass's result when nothing is deferred, at once; else the whole response, once the last
|
|
61
|
+
# payload is out (or `finish` is called).
|
|
62
|
+
def start(&finished)
|
|
63
|
+
seconds = Lighthouse::Config.defer_max_execution_ms / 1000.0
|
|
64
|
+
@deadline = clock + seconds if seconds.positive?
|
|
65
|
+
@result = execute
|
|
66
|
+
@finished = finished
|
|
67
|
+
@streams = deferred?
|
|
68
|
+
finish unless @streams
|
|
69
|
+
self
|
|
70
|
+
end
|
|
71
|
+
|
|
72
|
+
# Fragments are pending: the response goes in more than one payload.
|
|
73
|
+
def deferred?
|
|
74
|
+
!@queue.empty?
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# The initial payload, then each later one, until `hasNext` is false. A later payload that
|
|
78
|
+
# fails, to run or to be written (the block raised: its app values did not encode), ends the
|
|
79
|
+
# stream with a last payload, which completes, with an error, every id the client was sent and
|
|
80
|
+
# has not seen completed, then raises again. A first payload that fails raises, nothing being
|
|
81
|
+
# sent. `finish` is the caller's, once it has closed the stream (PersistedQueries.incremental
|
|
82
|
+
# calls it once its block is done), so the operation ends after the response does.
|
|
83
|
+
#
|
|
84
|
+
# A client that went away (Gone, raised by the block) stops it: nothing more is written, and
|
|
85
|
+
# the operation ends with what the client was sent. An error of the app's stays the error
|
|
86
|
+
# raised, even if the client has gone by the time its last payload is written.
|
|
87
|
+
def each_payload(&block)
|
|
88
|
+
@streaming = true
|
|
89
|
+
first(&block)
|
|
90
|
+
until @queue.empty?
|
|
91
|
+
begin
|
|
92
|
+
emit(next_payload, &block)
|
|
93
|
+
rescue Lighthouse::GraphQL::Incremental::Gone
|
|
94
|
+
raise
|
|
95
|
+
rescue StandardError => e
|
|
96
|
+
fail_stream(e, &block)
|
|
97
|
+
end
|
|
98
|
+
end
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# The whole response as the client put it together: the data and the errors of every payload
|
|
102
|
+
# it was sent (the first pass's first), the first pass's extensions. When nothing was sent: an
|
|
103
|
+
# empty Hash if the client left before the first payload, the error the JSON path would answer
|
|
104
|
+
# (Internal server error) if that payload failed.
|
|
105
|
+
def response
|
|
106
|
+
return @refused ? { 'errors' => [{ 'message' => 'Internal server error' }] } : {} if @streaming && !@delivered
|
|
107
|
+
|
|
108
|
+
first = @result.to_h
|
|
109
|
+
{ 'data' => @sent || first['data'], 'errors' => (first['errors'].to_a + @errors).presence, 'extensions' => first['extensions'] }.compact
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# The first payload, as the client is sent it (each_payload yields this one first): one that
|
|
113
|
+
# does not encode can be refused before anything is sent.
|
|
114
|
+
def first_payload = @first_payload ||= formatted(initial_payload)
|
|
115
|
+
|
|
116
|
+
# The first payload could not be sent (it did not encode, so nothing was): the operation
|
|
117
|
+
# ends as one that failed (`response`).
|
|
118
|
+
def refuse! = (@streaming = @refused = true)
|
|
119
|
+
|
|
120
|
+
# Calls the block `start` was given, once: with the first pass's result when nothing was
|
|
121
|
+
# deferred, else with the response so far.
|
|
122
|
+
def finish
|
|
123
|
+
finished = @finished
|
|
124
|
+
@finished = nil
|
|
125
|
+
finished&.call(@streams ? response : @result)
|
|
126
|
+
end
|
|
127
|
+
|
|
128
|
+
private
|
|
129
|
+
|
|
130
|
+
# The initial payload: one that fails, but for a client gone, is refused (`response`).
|
|
131
|
+
def first(&block)
|
|
132
|
+
emit(initial_payload, formatted: first_payload, &block)
|
|
133
|
+
rescue StandardError => e
|
|
134
|
+
@refused = !e.is_a?(Lighthouse::GraphQL::Incremental::Gone)
|
|
135
|
+
raise
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
# The first pass is the schema's `execute`, as the JSON path runs a query (an app's own
|
|
139
|
+
# `execute` too, with what it adds to the context): graphql-ruby parses the query once,
|
|
140
|
+
# through the schema's trace, and answers one that does not parse. A State goes in the
|
|
141
|
+
# context of a query that may use @defer or @stream (Document::INCREMENTAL, on the text: a
|
|
142
|
+
# false positive costs an unused State), and reads the document of the query it finds there
|
|
143
|
+
# (State#bind). An `execute` that runs the query without that context, or answers no
|
|
144
|
+
# GraphQL::Query::Result, defers nothing: the response comes whole.
|
|
145
|
+
def execute
|
|
146
|
+
@state = State.new if Lighthouse::GraphQL::Incremental::Document::INCREMENTAL.match?(@query_string.to_s) && traced?
|
|
147
|
+
result = running { @schema.execute(@query_string, **@options.except(:context), context: query_context) }
|
|
148
|
+
query = result.query if result.respond_to?(:query)
|
|
149
|
+
@state = nil unless query.is_a?(::GraphQL::Query) && query.context[State::CONTEXT_KEY].equal?(@state)
|
|
150
|
+
return result unless @state
|
|
151
|
+
|
|
152
|
+
@state.bind(query)
|
|
153
|
+
@tree = Lighthouse::GraphQL::Incremental::Tree.new(result.to_h['data'])
|
|
154
|
+
announce(@state.drain(query))
|
|
155
|
+
result
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
# The app's context, as it gave it; with the State, a copy of it, so that its Hash is left
|
|
159
|
+
# as it was.
|
|
160
|
+
def query_context
|
|
161
|
+
context = @options[:context]
|
|
162
|
+
@state ? (context || {}).merge(State::CONTEXT_KEY => @state) : context
|
|
163
|
+
end
|
|
164
|
+
|
|
165
|
+
# What Schema.execute hands its multiplex of the query's context: a new Hash each time, where
|
|
166
|
+
# graphql-ruby puts the multiplex's dataloader and trace, so each round gets its own.
|
|
167
|
+
def multiplex_context
|
|
168
|
+
context = @options[:context] || {}
|
|
169
|
+
{ backtrace: context[:backtrace], tracers: context[:tracers], trace: context[:trace], dataloader: context[:dataloader],
|
|
170
|
+
trace_mode: context[:trace_mode] }
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
# Does the trace the request runs with hold StreamTrace (in every mode, unless the app gave a
|
|
174
|
+
# trace class of its own that leaves out the schema's trace modules)? Without it nothing is
|
|
175
|
+
# streamed: the response comes whole.
|
|
176
|
+
def traced?
|
|
177
|
+
context = @options[:context] || {}
|
|
178
|
+
trace = context[:trace] || @schema.trace_class_for(context[:trace_mode] || @schema.default_trace_mode, build: true)
|
|
179
|
+
(trace.is_a?(Module) ? trace : trace.class).include?(Lighthouse::GraphQL::Incremental::StreamTrace)
|
|
180
|
+
end
|
|
181
|
+
|
|
182
|
+
# Runs a multiplex with the State in StreamTrace's fiber-local RUNNING.
|
|
183
|
+
def running
|
|
184
|
+
previous = Thread.current[Lighthouse::GraphQL::Incremental::StreamTrace::RUNNING]
|
|
185
|
+
Thread.current[Lighthouse::GraphQL::Incremental::StreamTrace::RUNNING] = @state
|
|
186
|
+
yield
|
|
187
|
+
ensure
|
|
188
|
+
Thread.current[Lighthouse::GraphQL::Incremental::StreamTrace::RUNNING] = previous
|
|
189
|
+
end
|
|
190
|
+
|
|
191
|
+
# The next round: every pending fragment and list, run together.
|
|
192
|
+
def next_payload
|
|
193
|
+
@round += 1
|
|
194
|
+
@state.deferring = deferring?
|
|
195
|
+
@running = @queue
|
|
196
|
+
@queue = []
|
|
197
|
+
plan = Lighthouse::GraphQL::Incremental::Plan.new(@result.query, @state, @tree)
|
|
198
|
+
units, partials, responses = passes(plan)
|
|
199
|
+
outcome = Lighthouse::GraphQL::Incremental::Delivery.new(@state, @tree).call(units, partials, responses)
|
|
200
|
+
@unsent = outcome.errors
|
|
201
|
+
found(plan, units, partials, outcome.failed)
|
|
202
|
+
completed = @running.map { |pending| { 'id' => pending.id, 'errors' => outcome.failed[pending] }.compact }
|
|
203
|
+
Serializer.subsequent(incremental: outcome.incremental, completed: completed, extensions: outcome.extensions,
|
|
204
|
+
pending: @announced, has_next: deferred?)
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# The round's units, their partials and their responses: each pass's, until Plan has no more.
|
|
208
|
+
def passes(plan)
|
|
209
|
+
units = plan.units(@running)
|
|
210
|
+
all = [[], [], []]
|
|
211
|
+
until units.empty?
|
|
212
|
+
partials = units.map { |unit| unit.partial(@result.query, @state) }
|
|
213
|
+
responses = run(partials)
|
|
214
|
+
[units, partials, responses].each_with_index { |list, index| all[index].concat(list) }
|
|
215
|
+
units = plan.follow(units, responses)
|
|
216
|
+
end
|
|
217
|
+
all
|
|
218
|
+
end
|
|
219
|
+
|
|
220
|
+
# Announce the fragments the round found, but those found only in fragments that `failed`: by
|
|
221
|
+
# Plan, in the fragments `parents`, and by each unit's Partial, in those the unit serves.
|
|
222
|
+
def found(plan, units, partials, failed)
|
|
223
|
+
@announced = []
|
|
224
|
+
lost = ->(pendings) { pendings.all? { |pending| failed.key?(pending) } }
|
|
225
|
+
found = @state.drain(plan).reject { |pending| lost.call(pending.parents) }
|
|
226
|
+
units.each_with_index do |unit, index|
|
|
227
|
+
drained = @state.drain(partials[index])
|
|
228
|
+
found.concat(drained) unless lost.call(unit.pendings)
|
|
229
|
+
end
|
|
230
|
+
announce(found)
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
# May the fragments of this round defer the fragments they hold? Not past the limits:
|
|
234
|
+
# with defer_max_nested_fields 1, the first round resolves everything left.
|
|
235
|
+
def deferring?
|
|
236
|
+
max = Lighthouse::Config.defer_max_nested_fields
|
|
237
|
+
return false if max.positive? && @round >= max
|
|
238
|
+
|
|
239
|
+
@deadline.nil? || clock < @deadline
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
def clock = Process.clock_gettime(Process::CLOCK_MONOTONIC)
|
|
243
|
+
|
|
244
|
+
# The responses of the partials, run in one multiplex so the Dataloader batches across them.
|
|
245
|
+
# The first pass analyzed the whole document: no max_complexity again, which analysis
|
|
246
|
+
# cannot apply to a Partial.
|
|
247
|
+
def run(partials)
|
|
248
|
+
running { @schema.multiplex(partials, context: multiplex_context, max_complexity: nil).map(&:to_h) }
|
|
249
|
+
end
|
|
250
|
+
|
|
251
|
+
# Give the fragments found their ids, and queue them: each once at a path (a fragment spread
|
|
252
|
+
# twice on an object, or found by two units, is deferred once). Those whose object an error
|
|
253
|
+
# nulled out of the response are dropped.
|
|
254
|
+
def announce(found)
|
|
255
|
+
found.each do |pending|
|
|
256
|
+
next unless present?(pending.path) && @found.add?([pending.node.object_id, pending.path])
|
|
257
|
+
|
|
258
|
+
pending.id = @next_id.to_s
|
|
259
|
+
@pendings[pending.id] = pending
|
|
260
|
+
@next_id += 1
|
|
261
|
+
@queue << pending
|
|
262
|
+
@announced << pending
|
|
263
|
+
end
|
|
264
|
+
end
|
|
265
|
+
|
|
266
|
+
# Does `path` lead to a value in the response's data so far?
|
|
267
|
+
def present?(path) = @tree.present?(path)
|
|
268
|
+
|
|
269
|
+
# Yields a payload, as the client is sent it (`formatted`), and keeps what the client was sent:
|
|
270
|
+
# the ids it has not seen completed, the data and the errors.
|
|
271
|
+
# A failure's payload sends no data (`data: false`).
|
|
272
|
+
def emit(payload, data: true, formatted: formatted(payload))
|
|
273
|
+
yield formatted
|
|
274
|
+
@delivered = true
|
|
275
|
+
payload['pending'].to_a.each { |entry| @open[entry['id']] = true }
|
|
276
|
+
payload['completed'].to_a.each { |entry| @open.delete(entry['id']) }
|
|
277
|
+
@sent = @tree&.snapshot if data
|
|
278
|
+
@errors.concat(@unsent.to_a)
|
|
279
|
+
@unsent = nil
|
|
280
|
+
end
|
|
281
|
+
|
|
282
|
+
# The first payload, in the draft's format.
|
|
283
|
+
def initial_payload = @initial_payload ||= Serializer.initial(@result, @announced, has_next: deferred?)
|
|
284
|
+
|
|
285
|
+
# The draft's payload as the client reads it.
|
|
286
|
+
def formatted(payload) = @legacy ? @legacy.convert(payload) : payload
|
|
287
|
+
|
|
288
|
+
# A stream that failed ends with a last payload, in which every id still open completes, with an
|
|
289
|
+
# error; then `error` is raised again, whether or not the client could be sent that payload.
|
|
290
|
+
def fail_stream(error, &block)
|
|
291
|
+
errors = [{ 'message' => 'Internal server error' }]
|
|
292
|
+
@unsent = errors
|
|
293
|
+
completed = @open.keys.map { |id| { 'id' => id, 'errors' => errors } }
|
|
294
|
+
payload = Serializer.subsequent(incremental: [], completed: completed, pending: [], has_next: false)
|
|
295
|
+
begin
|
|
296
|
+
emit(payload, data: false, &block)
|
|
297
|
+
rescue Lighthouse::GraphQL::Incremental::Gone
|
|
298
|
+
nil
|
|
299
|
+
end
|
|
300
|
+
raise error
|
|
301
|
+
end
|
|
302
|
+
end
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# The payloads of an incremental response, in the format of the specification
|
|
4
|
+
# draft (graphql-spec PR #1110, section 7). The only place that knows it: if the
|
|
5
|
+
# draft changes, this file does.
|
|
6
|
+
#
|
|
7
|
+
# The first payload is the result of the first pass, plus `pending` (one entry,
|
|
8
|
+
# with a string `id`, for every fragment that will follow) and `hasNext`. Each
|
|
9
|
+
# later one has `incremental` (the data of a fragment, or the items of a stream,
|
|
10
|
+
# under their `id`), `completed` (the ids that are done, with their `errors` when
|
|
11
|
+
# they failed), the `pending` it announces, and `hasNext`. The last has
|
|
12
|
+
# `hasNext: false`.
|
|
13
|
+
module Lighthouse::GraphQL::Incremental::Serializer
|
|
14
|
+
module_function
|
|
15
|
+
|
|
16
|
+
# `result`: the first pass's response Hash.
|
|
17
|
+
def initial(result, pending, has_next:)
|
|
18
|
+
result.to_h.merge('pending' => pending.map { |entry| pending_entry(entry) }, 'hasNext' => has_next)
|
|
19
|
+
end
|
|
20
|
+
|
|
21
|
+
# `incremental`: Hashes with an `id` and `data` or `items` (and `errors`, `extensions`);
|
|
22
|
+
# `completed`: Hashes with an `id` (and `errors`); `extensions`: the payload's own.
|
|
23
|
+
def subsequent(incremental:, completed:, pending:, has_next:, extensions: {})
|
|
24
|
+
payload = {}
|
|
25
|
+
payload['pending'] = pending.map { |entry| pending_entry(entry) } unless pending.empty?
|
|
26
|
+
payload['incremental'] = incremental unless incremental.empty?
|
|
27
|
+
payload['completed'] = completed unless completed.empty?
|
|
28
|
+
payload['extensions'] = extensions unless extensions.empty?
|
|
29
|
+
payload['hasNext'] = has_next
|
|
30
|
+
payload
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
# An entry of `pending`: the Hash it is answered with. A label that was not given is left out.
|
|
34
|
+
def pending_entry(entry)
|
|
35
|
+
{ 'id' => entry.id, 'path' => entry.path, 'label' => entry.label }.compact
|
|
36
|
+
end
|
|
37
|
+
end
|
|
@@ -0,0 +1,204 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'set'
|
|
4
|
+
|
|
5
|
+
# What one request's incremental delivery knows while it runs, kept in the
|
|
6
|
+
# context (CONTEXT_KEY): the client's Document, the fragments @defer and the
|
|
7
|
+
# lists @stream left pending, whether they may still be deferred, and the
|
|
8
|
+
# objects the fragments will need (StreamTrace keeps them).
|
|
9
|
+
#
|
|
10
|
+
# graphql-ruby asks DeferDirective.include? (and StreamDirective.resolve) with a
|
|
11
|
+
# directive's arguments, not its AST node. It takes those arguments from
|
|
12
|
+
# GraphQL::Query#arguments_for, which caches them per node and query: State maps
|
|
13
|
+
# the arguments object back to its node (`directive_for`), so the document is never
|
|
14
|
+
# rewritten to tell fragments apart. Arguments it does not know (were that cache to
|
|
15
|
+
# change) defer nothing: the fragment runs where it stands.
|
|
16
|
+
class Lighthouse::GraphQL::Incremental::State
|
|
17
|
+
CONTEXT_KEY = :lighthouse_incremental
|
|
18
|
+
MISSING = Object.new.freeze
|
|
19
|
+
|
|
20
|
+
# A deferred fragment waiting to run on `object` (the application value, not graphql-ruby's
|
|
21
|
+
# wrapper) of the object type `type`, at `path` of the response, found by a round's Plan in the
|
|
22
|
+
# fragments `parents`; or, for the list `field` of `holder` (of the object type `type`), the
|
|
23
|
+
# items of a streamed list that the response left out (`object`), which start at index
|
|
24
|
+
# `offset` and run `selections`. `node`: the fragment, or the @stream directive. `id` is its
|
|
25
|
+
# string id in `pending` entries, set once announced.
|
|
26
|
+
Pending = Struct.new(:node, :object, :type, :path, :label, :id, :offset, :selections, :field, :parents, :holder,
|
|
27
|
+
keyword_init: true) do
|
|
28
|
+
def stream? = !field.nil?
|
|
29
|
+
|
|
30
|
+
# A stream's list type, nullable.
|
|
31
|
+
def list_type = field.type.non_null? ? field.type.of_type : field.type
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# false once a limit is reached (Run): every fragment then runs where it stands,
|
|
35
|
+
# and every list is answered whole, as PHP Lighthouse's `shouldDeferFurther`.
|
|
36
|
+
attr_accessor :deferring
|
|
37
|
+
|
|
38
|
+
# The operation's GraphQL::Query, whose document State reads: the first query that asks it to
|
|
39
|
+
# defer or stream (that of the first pass, which runs first), or the one Run gives.
|
|
40
|
+
def bind(query)
|
|
41
|
+
@query = query if @query.nil?
|
|
42
|
+
end
|
|
43
|
+
|
|
44
|
+
def initialize
|
|
45
|
+
@deferring = true
|
|
46
|
+
@recorded = {}.compare_by_identity
|
|
47
|
+
@answers = {}.compare_by_identity
|
|
48
|
+
@needed = Set.new
|
|
49
|
+
@keys = Set.new
|
|
50
|
+
@objects = {}
|
|
51
|
+
@offsets = {}.compare_by_identity
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
# The client's document, as Document reads it.
|
|
55
|
+
def document
|
|
56
|
+
@document ||= Lighthouse::GraphQL::Incremental::Document.new(@query.schema, @query.document, @query.selected_operation)
|
|
57
|
+
end
|
|
58
|
+
|
|
59
|
+
# A stream's Partial (`query`) runs items of the list at `path`, counted from 0, that are at
|
|
60
|
+
# `positions` of the response's list.
|
|
61
|
+
def offset(query, path, positions)
|
|
62
|
+
@offsets[query] = [path.size, positions]
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
# `path` as a path of the response: in a stream's Partial, its items' indices count from the
|
|
66
|
+
# list's first item. Everything keyed or answered by path goes through it.
|
|
67
|
+
def absolute(query, path)
|
|
68
|
+
size, positions = @offsets[query]
|
|
69
|
+
return path unless positions && path[size].is_a?(Integer)
|
|
70
|
+
|
|
71
|
+
path.dup.tap { |copy| copy[size] = positions[copy[size]] }
|
|
72
|
+
end
|
|
73
|
+
|
|
74
|
+
# true when the fragment of the @defer whose `arguments` graphql-ruby evaluates is deferred
|
|
75
|
+
# on `object` (graphql-ruby's wrapper): the caller leaves it out. false when it runs where
|
|
76
|
+
# it stands. A fragment gathered twice on one object (spread twice) is deferred once.
|
|
77
|
+
def defer(object, arguments, context)
|
|
78
|
+
return false unless @deferring
|
|
79
|
+
|
|
80
|
+
query = context.query
|
|
81
|
+
bind(query)
|
|
82
|
+
fragment = directive_for(query, 'defer', arguments)&.then { |directive| document.owner(directive) }
|
|
83
|
+
return false unless fragment && document.included?(fragment, query) && document.applies?(fragment, object.class, query)
|
|
84
|
+
|
|
85
|
+
path = absolute(query, context[:current_path])
|
|
86
|
+
found(query, Pending.new(node: fragment, object: object.object, type: object.class, path: path, label: arguments[:label]))
|
|
87
|
+
true
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# true when the list `field` whose @stream has `arguments` streams: `items` (what is left of
|
|
91
|
+
# the list after the `initialCount` the first response has) will follow, with the selections
|
|
92
|
+
# every declaration of the field gives them. `parent`: the wrapper of the field's object.
|
|
93
|
+
def stream(parent, arguments, items, context, field)
|
|
94
|
+
return false unless @deferring
|
|
95
|
+
|
|
96
|
+
query = context.query
|
|
97
|
+
bind(query)
|
|
98
|
+
directive = directive_for(query, 'stream', arguments) or return false
|
|
99
|
+
path = absolute(query, context[:current_path])
|
|
100
|
+
selections = document.merged(directive, path, parent.class, query, @deferring) or return false
|
|
101
|
+
|
|
102
|
+
record(query, Pending.new(node: directive, object: items, type: parent.class, path: path, label: arguments[:label],
|
|
103
|
+
offset: arguments[:initial_count], selections: selections, field: field, holder: parent.object))
|
|
104
|
+
end
|
|
105
|
+
|
|
106
|
+
# A stream's Partial (`query`) runs the field of `node` again, on the list's object, without its
|
|
107
|
+
# resolver: StreamTrace answers it with the `items` left to stream (`answer`).
|
|
108
|
+
def stand_in(query, node, items)
|
|
109
|
+
(@answers[query] ||= {}.compare_by_identity)[node] = items
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# The items that answer the field of `ast_node` in `query`, if it stands in for a stream's.
|
|
113
|
+
def answer(query, ast_node)
|
|
114
|
+
@answers[query]&.fetch(ast_node, MISSING) || MISSING
|
|
115
|
+
end
|
|
116
|
+
|
|
117
|
+
# A deferred fragment `query` found (or a round's Plan, as `defer` would have). Run announces a
|
|
118
|
+
# fragment once at a path, however many times it is found there.
|
|
119
|
+
def found(query, pending)
|
|
120
|
+
need(pending.node, pending.path)
|
|
121
|
+
record(query, pending)
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# The pending fragments and lists `query` found (the GraphQL::Query of the first pass, a
|
|
125
|
+
# GraphQL::Query::Partial of a later one, or a round's Plan), forgotten once drained, with
|
|
126
|
+
# what State knew of `query`.
|
|
127
|
+
def drain(query)
|
|
128
|
+
@offsets.delete(query)
|
|
129
|
+
@answers.delete(query)
|
|
130
|
+
@recorded.delete(query) || []
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# StreamTrace: the value the field of `ast_node` resolved to in `query`, if a pending fragment
|
|
134
|
+
# of this request may need it.
|
|
135
|
+
def keep(query, ast_node, value)
|
|
136
|
+
return unless @keys.include?(ast_node.alias || ast_node.name) && query.context[CONTEXT_KEY].equal?(self)
|
|
137
|
+
|
|
138
|
+
path = query.context[:current_path]
|
|
139
|
+
@objects[absolute(query, path)] = value if @needed.include?(path.grep_v(Integer))
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# The value kept at `path`, or MISSING.
|
|
143
|
+
def object_at(path) = @objects.fetch(path, MISSING)
|
|
144
|
+
|
|
145
|
+
private
|
|
146
|
+
|
|
147
|
+
# The directive node `arguments` were evaluated for, in `query`: the one directive of the
|
|
148
|
+
# document with those values, evaluated once for the request; where several share them, the
|
|
149
|
+
# one whose arguments `query` cached are these (Query#arguments_for). nil if none: whatever
|
|
150
|
+
# it is, it then defers nothing.
|
|
151
|
+
def directive_for(query, name, arguments)
|
|
152
|
+
candidates = values[name][arguments.keyword_arguments] or return nil
|
|
153
|
+
return candidates.first if candidates.one?
|
|
154
|
+
|
|
155
|
+
definition = document.directive(name)
|
|
156
|
+
candidates.find { |directive| query.arguments_for(directive, definition).equal?(arguments) }
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
# The document's @defer and @stream, by name, then by the values of their arguments.
|
|
160
|
+
def values
|
|
161
|
+
@values ||= %w[defer stream].to_h do |name|
|
|
162
|
+
definition = document.directive(name)
|
|
163
|
+
[name, document.directives(name).group_by { |directive| @query.arguments_for(directive, definition).keyword_arguments }]
|
|
164
|
+
end
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
def record(query, pending)
|
|
168
|
+
(@recorded[query] ||= []) << pending
|
|
169
|
+
true
|
|
170
|
+
end
|
|
171
|
+
|
|
172
|
+
# The object fields a fragment selects, at any depth (as response paths without list indices
|
|
173
|
+
# from its object): the round that runs it needs the objects those resolved to when the rest
|
|
174
|
+
# of the query asked for them too.
|
|
175
|
+
def need(fragment, path)
|
|
176
|
+
base = path.grep_v(Integer)
|
|
177
|
+
relative(fragment).each do |relative|
|
|
178
|
+
@needed << (base + relative)
|
|
179
|
+
@keys << relative.last
|
|
180
|
+
end
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
# The fragment's object fields, walked once a request.
|
|
184
|
+
def relative(fragment)
|
|
185
|
+
(@relative ||= {}.compare_by_identity)[fragment] ||= object_fields(document.selections(fragment), [], [])
|
|
186
|
+
end
|
|
187
|
+
|
|
188
|
+
# `spreads`: the named fragments around the walk, which a cycle would spread again. A fragment
|
|
189
|
+
# spread at several places is walked at each.
|
|
190
|
+
def object_fields(selections, prefix, spreads)
|
|
191
|
+
selections.flat_map do |selection|
|
|
192
|
+
case selection
|
|
193
|
+
when ::GraphQL::Language::Nodes::Field
|
|
194
|
+
next [] if selection.selections.empty?
|
|
195
|
+
|
|
196
|
+
own = prefix + [selection.alias || selection.name]
|
|
197
|
+
[own] + object_fields(selection.selections, own, spreads)
|
|
198
|
+
when ::GraphQL::Language::Nodes::FragmentSpread
|
|
199
|
+
spreads.include?(selection.name) ? [] : object_fields(document.selections(selection), prefix, spreads + [selection.name])
|
|
200
|
+
else object_fields(selection.selections, prefix, spreads)
|
|
201
|
+
end
|
|
202
|
+
end
|
|
203
|
+
end
|
|
204
|
+
end
|