lighthouse-graphql 0.8.2 → 0.9.1
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 +168 -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 +106 -0
- data/docs/events.md +30 -1
- data/docs/filtering-and-ordering.md +567 -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 +32 -3
- 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 +116 -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 +29 -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 +35 -0
- data/lib/lighthouse/resolve_info.rb +7 -1
- data/lib/lighthouse/schema_generator.rb +2 -0
- data/lib/lighthouse/search/auto.rb +26 -0
- data/lib/lighthouse/search/enhancer.rb +151 -0
- data/lib/lighthouse/search/field_check.rb +173 -0
- data/lib/lighthouse/search/pg_search.rb +146 -0
- data/lib/lighthouse/search/query.rb +54 -0
- data/lib/lighthouse/search/result.rb +181 -0
- data/lib/lighthouse/search/searchkick.rb +335 -0
- data/lib/lighthouse/search/searchkick_index.rb +54 -0
- data/lib/lighthouse/search/searchkick_options.rb +74 -0
- data/lib/lighthouse/search/together_check.rb +137 -0
- data/lib/lighthouse/search.rb +101 -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 +153 -0
- data/sig/lighthouse.rbs +77 -1
- metadata +39 -1
data/docs/testing.md
ADDED
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
# Testing
|
|
2
|
+
|
|
3
|
+
`Lighthouse::GraphQL::Testing` sends requests to the app's GraphQL endpoint from its tests, as PHP
|
|
4
|
+
Lighthouse's `MakesGraphQLRequests` does. Include it where Rails' integration session runs: an RSpec
|
|
5
|
+
request spec, or an `ActionDispatch::IntegrationTest`.
|
|
6
|
+
|
|
7
|
+
```ruby
|
|
8
|
+
# spec/rails_helper.rb
|
|
9
|
+
RSpec.configure do |config|
|
|
10
|
+
config.include Lighthouse::GraphQL::Testing, type: :request
|
|
11
|
+
end
|
|
12
|
+
|
|
13
|
+
# test/test_helper.rb
|
|
14
|
+
class ActionDispatch::IntegrationTest
|
|
15
|
+
include Lighthouse::GraphQL::Testing
|
|
16
|
+
end
|
|
17
|
+
```
|
|
18
|
+
|
|
19
|
+
Each request answers the response's parsed JSON body; `response` holds the response itself, as
|
|
20
|
+
after any request (its status, its headers). The requests go to `graphql_endpoint`, `/graphql`
|
|
21
|
+
unless a test overrides it.
|
|
22
|
+
|
|
23
|
+
## Queries and mutations
|
|
24
|
+
|
|
25
|
+
`graphql(query, variables = {}, extra_params: {}, headers: {})`, PHP Lighthouse's `graphQL`, posts
|
|
26
|
+
an operation as JSON:
|
|
27
|
+
|
|
28
|
+
```ruby
|
|
29
|
+
RSpec.describe 'Posts', type: :request do
|
|
30
|
+
it 'lists the posts' do
|
|
31
|
+
create(:post, title: 'Hello')
|
|
32
|
+
|
|
33
|
+
body = graphql(<<~GRAPHQL, { first: 10 })
|
|
34
|
+
query($first: Int!) { posts(first: $first) { data { title } } }
|
|
35
|
+
GRAPHQL
|
|
36
|
+
|
|
37
|
+
expect(body.dig('data', 'posts', 'data')).to eq([{ 'title' => 'Hello' }])
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
it 'signs the user in' do
|
|
41
|
+
body = graphql('{ me { name } }', headers: { 'Authorization' => "Bearer #{user.api_token}" })
|
|
42
|
+
|
|
43
|
+
expect(body.dig('data', 'me', 'name')).to eq(user.name)
|
|
44
|
+
end
|
|
45
|
+
end
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
`extra_params` goes with the query: `operationName`, or `extensions` (a persisted query).
|
|
49
|
+
`post_graphql(data, headers: {})`, PHP Lighthouse's `postGraphQL`, posts `data` as it is: an
|
|
50
|
+
operation's Hash, or a batch's Array of them.
|
|
51
|
+
|
|
52
|
+
## Uploads
|
|
53
|
+
|
|
54
|
+
`multipart_graphql(operations, map, files, headers: {})`, PHP Lighthouse's `multipartGraphQL`,
|
|
55
|
+
sends a [multipart request](uploads.md): the operations, the map from each file's key to the
|
|
56
|
+
variables it fills, and the files by key.
|
|
57
|
+
|
|
58
|
+
```ruby
|
|
59
|
+
file = Rack::Test::UploadedFile.new(file_fixture('avatar.png'), 'image/png')
|
|
60
|
+
|
|
61
|
+
body = multipart_graphql(
|
|
62
|
+
{ query: 'mutation($file: Upload!) { uploadAvatar(file: $file) { url } }', variables: { file: nil } },
|
|
63
|
+
{ '0' => ['variables.file'] },
|
|
64
|
+
{ '0' => file }
|
|
65
|
+
)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Introspection
|
|
69
|
+
|
|
70
|
+
`introspect` answers the response to graphql-ruby's introspection query; `introspect_type(name)`
|
|
71
|
+
and `introspect_directive(name)` the introspection of one type or directive, or nil when the
|
|
72
|
+
schema has none.
|
|
73
|
+
|
|
74
|
+
```ruby
|
|
75
|
+
expect(introspect_type('Post')['fields'].pluck('name')).to include('title')
|
|
76
|
+
expect(introspect_directive('defer')).to be_nil # without Lighthouse::GraphQL::Defer
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
## Deferred fields
|
|
80
|
+
|
|
81
|
+
`stream_graphql(query, variables = {}, extra_params: {}, headers: {})`, PHP Lighthouse's
|
|
82
|
+
`streamGraphQL`, posts a query with `@defer` or `@stream`, as a client that reads `multipart/mixed`
|
|
83
|
+
does, and answers each payload of the [streamed response](defer.md), in order: the first, then one
|
|
84
|
+
per round.
|
|
85
|
+
|
|
86
|
+
```ruby
|
|
87
|
+
it 'defers the author' do
|
|
88
|
+
initial, later = stream_graphql('{ posts(first: 1) { data { title ... @defer { author { name } } } } }')
|
|
89
|
+
|
|
90
|
+
expect(initial['data']['posts']['data']).to eq([{ 'title' => 'Hello' }])
|
|
91
|
+
expect(later['incremental'].first['data']).to eq('author' => { 'name' => 'Ana' })
|
|
92
|
+
expect(later['hasNext']).to be(false)
|
|
93
|
+
end
|
|
94
|
+
```
|
|
95
|
+
|
|
96
|
+
It sends `Accept: multipart/mixed` unless the headers say otherwise; Apollo's older format is
|
|
97
|
+
`headers: { 'Accept' => 'multipart/mixed;deferSpec=20220824' }`. A response that comes whole (the
|
|
98
|
+
query deferred nothing, or the schema does not use `Lighthouse::GraphQL::Defer`) raises
|
|
99
|
+
`Lighthouse::GraphQL::Testing::NotStreamed`.
|
|
@@ -59,9 +59,11 @@ module Lighthouse::GraphQL::Complexity
|
|
|
59
59
|
schema
|
|
60
60
|
end
|
|
61
61
|
|
|
62
|
-
# A query's score, once Analyzer has run on it; nil otherwise.
|
|
62
|
+
# A query's score, once Analyzer has run on it; nil otherwise. A GraphQL::Query::Partial (a
|
|
63
|
+
# deferred fragment's run, see Defer) copies the operation's context, but is not analyzed:
|
|
64
|
+
# the operation's score is reported once, with its first pass, and a Partial has none.
|
|
63
65
|
def query_complexity(query)
|
|
64
|
-
query.context[CONTEXT_KEY]
|
|
66
|
+
query.context[CONTEXT_KEY] if Lighthouse::Events.operation_query(query).equal?(query)
|
|
65
67
|
end
|
|
66
68
|
|
|
67
69
|
# graphql-ruby asks the field for its cost through `complexity_for`, which wins
|
data/lib/lighthouse/config.rb
CHANGED
|
@@ -29,10 +29,11 @@ module Lighthouse
|
|
|
29
29
|
persisted_queries_manifest persisted_queries_only on_error authenticated_user policy_user authorizer
|
|
30
30
|
feature_checker feature_actor
|
|
31
31
|
convert_empty_strings_to_null
|
|
32
|
-
soft_deletes
|
|
32
|
+
soft_deletes search
|
|
33
33
|
queue_broadcasts broadcast_queue
|
|
34
34
|
global_id
|
|
35
35
|
schema_output schema_log
|
|
36
|
+
defer_max_nested_fields defer_max_execution_ms
|
|
36
37
|
].freeze
|
|
37
38
|
|
|
38
39
|
class << self
|
|
@@ -135,6 +136,21 @@ module Lighthouse
|
|
|
135
136
|
@persisted_queries_store || Lighthouse::GraphQL::Caching.store
|
|
136
137
|
end
|
|
137
138
|
|
|
139
|
+
# @defer's limits (Defer, experimental), PHP Lighthouse's `defer.max_nested_fields` and
|
|
140
|
+
# `defer.max_execution_ms`; 0 (the default) is no limit. Past that many rounds of nested
|
|
141
|
+
# fragments, or that many milliseconds, what is left resolves in one last payload. Each is
|
|
142
|
+
# a count (Support::Count): a String of digits from ENV is its number, anything else raises.
|
|
143
|
+
def defer_max_nested_fields = @defer_max_nested_fields || 0
|
|
144
|
+
def defer_max_execution_ms = @defer_max_execution_ms || 0
|
|
145
|
+
|
|
146
|
+
def defer_max_nested_fields=(rounds)
|
|
147
|
+
@defer_max_nested_fields = Lighthouse::Support::Count.read(:defer_max_nested_fields, rounds)
|
|
148
|
+
end
|
|
149
|
+
|
|
150
|
+
def defer_max_execution_ms=(milliseconds)
|
|
151
|
+
@defer_max_execution_ms = Lighthouse::Support::Count.read(:defer_max_execution_ms, milliseconds)
|
|
152
|
+
end
|
|
153
|
+
|
|
138
154
|
# Pagination defaults, overridden by a directive's defaultCount / maxCount.
|
|
139
155
|
# Without a default count, paginated fields require `first`.
|
|
140
156
|
attr_accessor :pagination_default_count, :pagination_max_count
|
|
@@ -145,7 +161,8 @@ module Lighthouse
|
|
|
145
161
|
@transactional_mutations.nil? || @transactional_mutations
|
|
146
162
|
end
|
|
147
163
|
|
|
148
|
-
# Hook invoked when a directive/resolver
|
|
164
|
+
# Hook invoked when a directive/resolver reports an error (a filter that
|
|
165
|
+
# raised, which fails its field). Defaults to
|
|
149
166
|
# re-raising in test (so failures surface) and logging otherwise. Override
|
|
150
167
|
# via `Lighthouse.configure { |c| c.on_error = ->(e, ctx) { ... } }`.
|
|
151
168
|
def on_error
|
|
@@ -201,17 +218,17 @@ module Lighthouse
|
|
|
201
218
|
# is one for another column.
|
|
202
219
|
attr_accessor :soft_deletes
|
|
203
220
|
|
|
204
|
-
|
|
205
|
-
yield(self) if block_given?
|
|
206
|
-
end
|
|
221
|
+
# --- Full-text search (used by @search) ------------------------------------
|
|
207
222
|
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
223
|
+
# Teaches Lighthouse which engine searches a model: an adapter (see Lighthouse::Search
|
|
224
|
+
# for what it answers), such as `Lighthouse::Search::PgSearch.new` or
|
|
225
|
+
# `Lighthouse::Search::Searchkick.new`, or the app's own.
|
|
226
|
+
# Defaults to detecting Searchkick, then pg_search, per model (Search::Auto).
|
|
227
|
+
attr_accessor :search
|
|
211
228
|
|
|
212
|
-
def
|
|
213
|
-
|
|
214
|
-
|
|
229
|
+
def configure = (yield(self) if block_given?)
|
|
230
|
+
def [](key) = public_send(key)
|
|
231
|
+
def reset! = SETTINGS.each { |setting| instance_variable_set("@#{setting}", nil) }
|
|
215
232
|
end
|
|
216
233
|
|
|
217
234
|
# The callables the authorizer and on_error settings fall back to.
|
|
@@ -9,6 +9,38 @@ require_relative 'directive'
|
|
|
9
9
|
# and installs its resolver onto the field. Legacy resolvers fulfil this via
|
|
10
10
|
# `#define_resolver(target_type)`; clean directives implement `#resolve_field`
|
|
11
11
|
# returning a `#call(obj, args, ctx)` lambda.
|
|
12
|
+
#
|
|
13
|
+
# A @search on the field needs its resolver to apply it, which Search::FieldCheck
|
|
14
|
+
# asks the class when the schema is built. By default a resolver applies none,
|
|
15
|
+
# and the @search is a schema error. A class opts in with class methods:
|
|
16
|
+
#
|
|
17
|
+
# # It runs the field's argument filters, a relational search (pg_search) among
|
|
18
|
+
# # them: BaseDirectiveResolver#apply_where_filters, or resolve_info.enhance_builder.
|
|
19
|
+
# def self.applies_search? = true
|
|
20
|
+
#
|
|
21
|
+
# # It also takes the records an engine outside the database (Searchkick)
|
|
22
|
+
# # answers with, a Search::Result, on this field.
|
|
23
|
+
# def self.takes_search_results?(type, field_def, directive, root_kind) = true
|
|
12
24
|
module Lighthouse::Contracts::FieldResolver
|
|
13
25
|
include Lighthouse::Contracts::Directive
|
|
26
|
+
|
|
27
|
+
# The defaults: no search applied, no search result taken.
|
|
28
|
+
module SearchDefaults
|
|
29
|
+
def applies_search? = false
|
|
30
|
+
def takes_search_results?(_type, _field_def, _directive, _root_kind) = false
|
|
31
|
+
end
|
|
32
|
+
|
|
33
|
+
def self.included(base)
|
|
34
|
+
super
|
|
35
|
+
base.extend(SearchDefaults)
|
|
36
|
+
end
|
|
37
|
+
|
|
38
|
+
# Does the resolver class apply a search on its field? Not unless it says so,
|
|
39
|
+
# whether or not it includes the contract (a duck-typed `define_resolver` class).
|
|
40
|
+
def self.applies_search?(klass) = !!(klass.respond_to?(:applies_search?) && klass.applies_search?)
|
|
41
|
+
|
|
42
|
+
# Does it take an engine's Search::Result on this field?
|
|
43
|
+
def self.takes_search_results?(klass, type, field_def, directive, root_kind)
|
|
44
|
+
!!(klass.respond_to?(:takes_search_results?) && klass.takes_search_results?(type, field_def, directive, root_kind))
|
|
45
|
+
end
|
|
14
46
|
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require_relative 'directive'
|
|
4
|
+
|
|
5
|
+
# An argument directive that also writes to the full-text search, as PHP
|
|
6
|
+
# Lighthouse's ScoutBuilderDirective: when the client searches, the directives
|
|
7
|
+
# of the other arguments it sends narrow the Search::Query instead of the
|
|
8
|
+
# relation, if they include this contract (@eq, @trashed, @builder on an
|
|
9
|
+
# argument). Any other argument directive the client sends with a search is
|
|
10
|
+
# an error, because a search engine cannot apply it.
|
|
11
|
+
#
|
|
12
|
+
# Implementors, built with (arg_node, directive_node), provide
|
|
13
|
+
# `#handle_search_builder(query, value)` returning the query.
|
|
14
|
+
module Lighthouse::Contracts::SearchBuilder
|
|
15
|
+
include Lighthouse::Contracts::Directive
|
|
16
|
+
end
|
|
@@ -24,6 +24,11 @@ require 'json'
|
|
|
24
24
|
# Cache-Control header the selected fields' @cacheControl hints allow, renders
|
|
25
25
|
# the JSON and dispatches EndRequest. In development an error renders as JSON.
|
|
26
26
|
#
|
|
27
|
+
# When the schema uses Lighthouse::GraphQL::Defer, an operation that defers is
|
|
28
|
+
# streamed instead, as `multipart/mixed` parts (lighthouse_stream), unless the
|
|
29
|
+
# client's Accept header leaves them out: nothing else to set up, as PHP
|
|
30
|
+
# Lighthouse's DeferServiceProvider.
|
|
31
|
+
#
|
|
27
32
|
# A field's @throttle that renders past its limit (its `with:` method, or
|
|
28
33
|
# `head :too_many_requests`, rate_limit's default on Rails 7.2) ends the request
|
|
29
34
|
# with that response, as a before_action that renders does: the operation stops
|
|
@@ -52,13 +57,11 @@ module Lighthouse::GraphQL::Controller
|
|
|
52
57
|
if operations.is_a?(Array)
|
|
53
58
|
render json: lighthouse_batch(operations.map { |operation| lighthouse_hash(operation) })
|
|
54
59
|
else
|
|
55
|
-
|
|
56
|
-
Lighthouse::GraphQL::CacheControl.apply(response, result)
|
|
57
|
-
render json: result
|
|
60
|
+
lighthouse_respond(operations)
|
|
58
61
|
end
|
|
59
62
|
end
|
|
60
63
|
rescue StandardError => e
|
|
61
|
-
raise e unless
|
|
64
|
+
raise e unless lighthouse_render_development_error?(e)
|
|
62
65
|
|
|
63
66
|
lighthouse_development_error(e)
|
|
64
67
|
end
|
|
@@ -76,23 +79,94 @@ module Lighthouse::GraphQL::Controller
|
|
|
76
79
|
end
|
|
77
80
|
|
|
78
81
|
# `operation`: the request's parameters, or a multipart request's operation.
|
|
79
|
-
def lighthouse_operation(operation = params)
|
|
80
|
-
|
|
81
|
-
Lighthouse::GraphQL::PersistedQueries.execute(
|
|
82
|
-
graphql_schema,
|
|
83
|
-
query: operation[:query], extensions: operation[:extensions],
|
|
84
|
-
variables: graphql_variables(operation[:variables]), operation_name: operation[:operationName], context: lighthouse_context
|
|
85
|
-
)
|
|
82
|
+
def lighthouse_operation(operation = params, schema = graphql_schema)
|
|
83
|
+
Lighthouse::GraphQL::PersistedQueries.execute(schema, **lighthouse_arguments(operation))
|
|
86
84
|
end
|
|
87
85
|
|
|
88
86
|
# Each operation gets its own context: `schema.multiplex`'s `context:` is the
|
|
89
87
|
# multiplex's, which the queries' resolvers never see.
|
|
90
88
|
def lighthouse_batch(operations)
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
89
|
+
Lighthouse::GraphQL::PersistedQueries.multiplex(graphql_schema, operations.map { |operation| lighthouse_arguments(operation) })
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# What PersistedQueries runs an operation with: its query, extensions, variables and
|
|
93
|
+
# name, in the request's context.
|
|
94
|
+
def lighthouse_arguments(operation)
|
|
95
|
+
operation = operation.with_indifferent_access if operation.is_a?(Hash)
|
|
96
|
+
{ query: operation[:query], extensions: operation[:extensions], variables: graphql_variables(operation[:variables]),
|
|
97
|
+
operation_name: operation[:operationName], context: lighthouse_context }
|
|
98
|
+
end
|
|
99
|
+
|
|
100
|
+
# One operation: answered whole, or streamed (Defer) when it defers. The schema is resolved
|
|
101
|
+
# once, for both.
|
|
102
|
+
def lighthouse_respond(operation)
|
|
103
|
+
schema = graphql_schema
|
|
104
|
+
stream_type = lighthouse_stream_type(schema)
|
|
105
|
+
return lighthouse_incremental(operation, schema, stream_type) if stream_type
|
|
106
|
+
|
|
107
|
+
result = lighthouse_operation(operation, schema)
|
|
108
|
+
Lighthouse::GraphQL::CacheControl.apply(response, result)
|
|
109
|
+
render json: result
|
|
110
|
+
end
|
|
111
|
+
|
|
112
|
+
# The Content-Type of the response if it streams (Defer.stream_type), or nil when it comes
|
|
113
|
+
# whole: the schema does not use the plugin, the client leaves `multipart/mixed` out, or the
|
|
114
|
+
# request is a HEAD, whose response has no body.
|
|
115
|
+
def lighthouse_stream_type(schema)
|
|
116
|
+
return nil if request.head? || !Lighthouse::GraphQL::Defer.enabled?(schema)
|
|
117
|
+
|
|
118
|
+
Lighthouse::GraphQL::Defer.stream_type(request.headers['Accept'])
|
|
119
|
+
end
|
|
120
|
+
|
|
121
|
+
# Runs the operation's first pass (Incremental::Run), and renders it whole when no fragment
|
|
122
|
+
# is deferred (its operation ended), else streams it, in the format `stream_type` names.
|
|
123
|
+
def lighthouse_incremental(operation, schema, stream_type)
|
|
124
|
+
format = Lighthouse::GraphQL::Defer.legacy?(stream_type) ? :legacy : :draft
|
|
125
|
+
run = Lighthouse::GraphQL::PersistedQueries.incremental(schema, format: format, **lighthouse_arguments(operation))
|
|
126
|
+
return render json: run if run.is_a?(Hash)
|
|
127
|
+
return lighthouse_stream(run, stream_type) if run.deferred?
|
|
128
|
+
|
|
129
|
+
Lighthouse::GraphQL::CacheControl.apply(response, run.result)
|
|
130
|
+
render json: run.result
|
|
131
|
+
end
|
|
132
|
+
|
|
133
|
+
# The response of a run that defers: its payloads as `multipart/mixed` parts (not cacheable,
|
|
134
|
+
# whatever @cacheControl says), which Incremental::Body writes as the server sends the
|
|
135
|
+
# response, after the action. The first part is encoded here, so that an error of the app's
|
|
136
|
+
# values in it is answered as on the JSON path, nothing being sent: the operation then ends as
|
|
137
|
+
# one that failed. The body ends the operation, then the request (EndRequest, with the parts
|
|
138
|
+
# written as its response's body, kept only when something listens to it).
|
|
139
|
+
def lighthouse_stream(run, stream_type)
|
|
140
|
+
multipart = Lighthouse::GraphQL::Incremental::Multipart.new(keep: Lighthouse::Events.listening?(Lighthouse::Events::EndRequest))
|
|
141
|
+
first = lighthouse_first_part(run, multipart)
|
|
142
|
+
Lighthouse::GraphQL::Incremental::Multipart.headers(stream_type).each { |name, value| response.headers[name] = value }
|
|
143
|
+
ended = -> { Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(multipart.ended(response))) }
|
|
144
|
+
@lighthouse_body = Lighthouse::GraphQL::Incremental::Body.new(run, multipart, first, on_error: method(:lighthouse_report), on_end: ended)
|
|
145
|
+
request.env['rack.response_finished']&.push(->(*) { @lighthouse_body.finish })
|
|
146
|
+
self.response_body = @lighthouse_body
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
def lighthouse_first_part(run, multipart)
|
|
150
|
+
multipart.part(run.first_payload)
|
|
151
|
+
rescue StandardError
|
|
152
|
+
run.refuse!
|
|
153
|
+
run.finish
|
|
154
|
+
raise
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
# A streamed body ends the request itself, once it is done (Incremental::Body).
|
|
158
|
+
def lighthouse_streaming? = !@lighthouse_body.nil?
|
|
159
|
+
|
|
160
|
+
# An error that ended a streamed response on its way, which Incremental::Body handled: to
|
|
161
|
+
# Rails.error (where the JSON path's would go, through the executor or rescue_from), and the log.
|
|
162
|
+
def lighthouse_report(error)
|
|
163
|
+
lighthouse_log(error)
|
|
164
|
+
::Rails.error.report(error, handled: true, severity: :error) if defined?(::Rails) && ::Rails.respond_to?(:error)
|
|
165
|
+
end
|
|
166
|
+
|
|
167
|
+
# In development, an error that is not one Rails answers, before the response is on its way.
|
|
168
|
+
def lighthouse_render_development_error?(error)
|
|
169
|
+
defined?(::Rails) && ::Rails.env.development? && !rails_response?(error) && !response.committed?
|
|
96
170
|
end
|
|
97
171
|
|
|
98
172
|
# An error Rails answers with a status of its own (config.action_dispatch.rescue_responses):
|
|
@@ -101,9 +175,11 @@ module Lighthouse::GraphQL::Controller
|
|
|
101
175
|
::ActionDispatch::ExceptionWrapper.status_code_for_exception(error.class.name) != 500
|
|
102
176
|
end
|
|
103
177
|
|
|
178
|
+
# An error, with its backtrace, to the log.
|
|
179
|
+
def lighthouse_log(error) = logger&.error("#{error.class}: #{error.message}\n#{error.backtrace.to_a.join("\n")}")
|
|
180
|
+
|
|
104
181
|
def lighthouse_development_error(error)
|
|
105
|
-
|
|
106
|
-
logger.error(error.backtrace.join("\n"))
|
|
182
|
+
lighthouse_log(error)
|
|
107
183
|
|
|
108
184
|
render json: { errors: [{ message: error.message, backtrace: error.backtrace }], data: {} },
|
|
109
185
|
status: :internal_server_error
|
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# @defer and @stream: the fields of a fragment, and the items of a list, arrive after the rest of the response
|
|
4
|
+
# (experimental: the specification it follows is still a draft, see docs/defer.md). A graphql-ruby
|
|
5
|
+
# plugin, opted into in the schema class, as PHP Lighthouse's DeferServiceProvider is registered:
|
|
6
|
+
#
|
|
7
|
+
# class AppSchema < Lighthouse::GraphQL::RbLightHouse.get_schema(...)
|
|
8
|
+
# use GraphQL::Dataloader
|
|
9
|
+
# use Lighthouse::GraphQL::Defer
|
|
10
|
+
# end
|
|
11
|
+
#
|
|
12
|
+
# The plugin adds the directives to the schema (without it the schema has none, as the
|
|
13
|
+
# specification asks of a server that does not implement it), and installs Rules, the analyzer
|
|
14
|
+
# that checks them in every query. Lighthouse::GraphQL::Controller then streams the response of
|
|
15
|
+
# an operation that defers, as PHP Lighthouse does, unless the client's Accept header leaves out
|
|
16
|
+
# `multipart/mixed` (`Defer.stream_type`), in the format the client reads: the specification
|
|
17
|
+
# draft's, or Apollo's older one (`deferSpec=20220824`). Every other response comes whole.
|
|
18
|
+
# Run does the work; Document, State, Serializer, Legacy, Multipart and Body are its parts.
|
|
19
|
+
module Lighthouse::GraphQL::Defer
|
|
20
|
+
MULTIPART = 'multipart/mixed'
|
|
21
|
+
# The Accept parameter of Apollo's older format (Incremental::Legacy), and the Content-Type's.
|
|
22
|
+
LEGACY = 'deferspec'
|
|
23
|
+
LEGACY_TYPE = 'deferSpec=20220824'
|
|
24
|
+
# What a client names when it reads the specification draft's format.
|
|
25
|
+
FORMAT = 'incrementalspec=v0.2'
|
|
26
|
+
|
|
27
|
+
# A media range of an Accept header; `rank` orders them as preferred first.
|
|
28
|
+
MediaRange = Struct.new(:type, :params, :q, :index) do
|
|
29
|
+
def rank = [-q, index]
|
|
30
|
+
|
|
31
|
+
# Does the range cover the media type `name` (itself, its `type/*`, or `*/*`)?
|
|
32
|
+
def covers?(name) = type == name || type == '*/*' || (type.end_with?('/*') && name.start_with?(type.delete_suffix('*')))
|
|
33
|
+
|
|
34
|
+
# How specific the range is: a type, then `type/*`, then `*/*`.
|
|
35
|
+
def specificity = (type == '*/*' ? 0 : 1) + (type.end_with?('/*') ? 0 : 1)
|
|
36
|
+
|
|
37
|
+
# Does it name Apollo's older format?
|
|
38
|
+
def legacy? = params.any? { |param| param.start_with?(LEGACY) }
|
|
39
|
+
end
|
|
40
|
+
|
|
41
|
+
module_function
|
|
42
|
+
|
|
43
|
+
# The oldest graphql-ruby it runs on: GraphQL::Query::Partial#fragment_node (2.5.21), and a
|
|
44
|
+
# runtime that gives each list item run in a Dataloader job its own path (2.5.23), which the
|
|
45
|
+
# paths of the fragments and objects it keeps are read from (context[:current_path]).
|
|
46
|
+
GRAPHQL = '2.5.23'
|
|
47
|
+
|
|
48
|
+
# graphql-ruby's plugin hook: `use Lighthouse::GraphQL::Defer`.
|
|
49
|
+
def use(schema, **_options)
|
|
50
|
+
if Gem::Version.new(::GraphQL::VERSION) < Gem::Version.new(GRAPHQL)
|
|
51
|
+
raise Lighthouse::DefinitionError, "Lighthouse::GraphQL::Defer needs graphql-ruby #{GRAPHQL} or newer."
|
|
52
|
+
end
|
|
53
|
+
|
|
54
|
+
schema.directive(Lighthouse::GraphQL::Incremental::DeferDirective)
|
|
55
|
+
schema.directive(Lighthouse::GraphQL::Incremental::StreamDirective)
|
|
56
|
+
schema.query_analyzer(Lighthouse::GraphQL::Incremental::Rules)
|
|
57
|
+
schema.trace_with(Lighthouse::GraphQL::Incremental::StreamTrace)
|
|
58
|
+
schema.extend(Used)
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# What a schema class that uses the plugin is extended with, which its subclasses inherit.
|
|
62
|
+
module Used; end
|
|
63
|
+
|
|
64
|
+
# Does `schema` use the plugin? Decided once a schema class (Schema.directives builds a Hash on
|
|
65
|
+
# every call), as `use` marks it.
|
|
66
|
+
def enabled?(schema) = schema.is_a?(Used)
|
|
67
|
+
|
|
68
|
+
# The Content-Type of a streamed response to a client that sends `accept`, or nil when the
|
|
69
|
+
# client does not take one. As PHP Lighthouse, which streams whatever the client accepts, it is
|
|
70
|
+
# streamed to any client but one whose header leaves `multipart/mixed` out: no range covers
|
|
71
|
+
# it, or the most specific that does is at q=0 (`application/json` alone). The format is the
|
|
72
|
+
# specification draft's, or Apollo's older one when the client's preferred `multipart/mixed`
|
|
73
|
+
# range names it (`deferSpec=20220824`); the Content-Type names the format the client named.
|
|
74
|
+
def stream_type(accept)
|
|
75
|
+
type = Lighthouse::GraphQL::Incremental::Multipart::CONTENT_TYPE
|
|
76
|
+
return type if accept.to_s.strip.empty?
|
|
77
|
+
|
|
78
|
+
ranges = ranges(accept)
|
|
79
|
+
named = ranges.select { |range| range.type == MULTIPART }
|
|
80
|
+
return wildcard(type, ranges) if named.empty?
|
|
81
|
+
|
|
82
|
+
preferred = named.select { |range| range.q.positive? }.min_by(&:rank)
|
|
83
|
+
content_type(type, preferred) if preferred
|
|
84
|
+
end
|
|
85
|
+
|
|
86
|
+
# A header that names no multipart/mixed range: the most specific range that covers it decides.
|
|
87
|
+
def wildcard(type, ranges)
|
|
88
|
+
covering = ranges.select { |range| range.covers?(MULTIPART) }.max_by { |range| [range.specificity, range.q] }
|
|
89
|
+
type if covering&.q&.positive?
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# Is `content_type` (stream_type's) Apollo's older format?
|
|
93
|
+
def legacy?(content_type) = content_type.to_s.include?(LEGACY_TYPE)
|
|
94
|
+
|
|
95
|
+
def content_type(type, range)
|
|
96
|
+
return "#{type}; #{LEGACY_TYPE}" if range.legacy?
|
|
97
|
+
|
|
98
|
+
range.params.include?(FORMAT) ? "#{type}; incrementalSpec=v0.2" : type
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Each media range of the header: its type, its parameters (lowercase, but q) and its q.
|
|
102
|
+
# A range that is empty or not a media type (`type/subtype`) is skipped.
|
|
103
|
+
def ranges(accept)
|
|
104
|
+
accept.to_s.split(',').each_with_index.filter_map do |range, index|
|
|
105
|
+
type, *params = range.split(';').map { |part| part.strip.downcase }
|
|
106
|
+
next unless type&.match?(%r{\A[^/\s]+/[^/\s]+\z})
|
|
107
|
+
|
|
108
|
+
q = params.find { |param| param.start_with?('q=') }
|
|
109
|
+
MediaRange.new(type, params - [q], q ? q.delete_prefix('q=').to_f : 1.0, index)
|
|
110
|
+
end
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
private_class_method :content_type, :wildcard
|
|
114
|
+
end
|
|
@@ -5,6 +5,7 @@ require_relative 'builder_applier'
|
|
|
5
5
|
|
|
6
6
|
class Lighthouse::GraphQL::DirectiveResolvers::AggregateDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
|
|
7
7
|
def self.directive_name = 'aggregate'
|
|
8
|
+
def self.applies_search? = true
|
|
8
9
|
|
|
9
10
|
# An unknown function aggregates to null.
|
|
10
11
|
AGGREGATIONS = {
|
|
@@ -5,6 +5,8 @@ require_relative 'builder_applier'
|
|
|
5
5
|
|
|
6
6
|
class Lighthouse::GraphQL::DirectiveResolvers::AllDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
|
|
7
7
|
def self.directive_name = 'all'
|
|
8
|
+
def self.applies_search? = true
|
|
9
|
+
def self.takes_search_results?(*) = true
|
|
8
10
|
|
|
9
11
|
def self.definition
|
|
10
12
|
<<~GRAPHQL.chomp
|
|
@@ -31,18 +33,45 @@ class Lighthouse::GraphQL::DirectiveResolvers::AllDirectiveResolver < Lighthouse
|
|
|
31
33
|
private
|
|
32
34
|
|
|
33
35
|
def resolve_all(model_class, arguments, ctx)
|
|
36
|
+
args = arguments.respond_to?(:to_h) ? arguments.to_h : {}
|
|
37
|
+
return search_records(search_together(args, ctx), args, ctx) if searched_together
|
|
34
38
|
return [] unless model_class
|
|
35
39
|
|
|
36
|
-
# apply simple pagination args if present
|
|
37
|
-
args = arguments.respond_to?(:to_h) ? arguments.to_h : {}
|
|
38
40
|
relation = apply_scopes(model_class.all)
|
|
39
41
|
|
|
40
|
-
relation = apply_where_filters(relation, args, ctx)
|
|
42
|
+
relation = apply_where_filters(relation, args, ctx, search: :model)
|
|
43
|
+
return search_records(relation, args, ctx) if relation.is_a?(Lighthouse::Search::Result)
|
|
44
|
+
|
|
41
45
|
relation = relation.limit(args[:first]) if args[:first]
|
|
42
46
|
relation = relation.offset(args[:offset]) if args[:offset]
|
|
43
47
|
relation
|
|
44
48
|
end
|
|
45
49
|
|
|
50
|
+
# The records a search found: as many as the client asks for (`first`, an
|
|
51
|
+
# argument's @limit, which cuts them after), else every one; and an error next
|
|
52
|
+
# to them when fewer came back while more match (Search::Result::READ_LIMIT
|
|
53
|
+
# in one read, the result window).
|
|
54
|
+
def search_records(result, args, ctx)
|
|
55
|
+
wanted = [args[:first], limit_of(args)].compact.min
|
|
56
|
+
records = result.records(first: wanted, offset: args[:offset])
|
|
57
|
+
ctx.add_error(::GraphQL::ExecutionError.new(truncation(result, records, args[:offset] || 0))) if result.truncated? && ctx.respond_to?(:add_error)
|
|
58
|
+
records
|
|
59
|
+
end
|
|
60
|
+
|
|
61
|
+
# The client's @limit (without `builder: true`), when it is one LimitResolver can cut to.
|
|
62
|
+
def limit_of(args)
|
|
63
|
+
keyword = Lighthouse::GraphQL::DirectiveResolvers::LimitResolver.keyword(@field_def)
|
|
64
|
+
limit = args[keyword] if keyword
|
|
65
|
+
limit if limit.is_a?(Integer) && !limit.negative?
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
def truncation(result, records, offset)
|
|
69
|
+
read = Lighthouse::GraphQL::Pagination.covered(records)
|
|
70
|
+
window = ", and no further than its first #{result.result_window} matches (the index.max_result_window)" if result.result_window
|
|
71
|
+
"@all answered #{read} of the #{result.count - offset} matches the search finds from offset #{offset}: a search reads " \
|
|
72
|
+
"#{Lighthouse::Search::Result::READ_LIMIT} at most at once#{window}. Use @paginate, or `first` and `offset`, to read the others."
|
|
73
|
+
end
|
|
74
|
+
|
|
46
75
|
def extract_model_name
|
|
47
76
|
arg = @directive_node.arguments&.find { |a| a.name == 'model' }
|
|
48
77
|
return nil unless arg
|
|
@@ -25,9 +25,7 @@ class Lighthouse::GraphQL::DirectiveResolvers::ArgumentBinding
|
|
|
25
25
|
Lighthouse::Support::DirectiveArgs.literal(@directive, name)
|
|
26
26
|
end
|
|
27
27
|
|
|
28
|
-
def model?(klass)
|
|
29
|
-
defined?(::ActiveRecord::Base) && klass.is_a?(Class) && klass < ::ActiveRecord::Base
|
|
30
|
-
end
|
|
28
|
+
def model?(klass) = Lighthouse::Support::ModelResolver.model?(klass)
|
|
31
29
|
|
|
32
30
|
def call(klass, value, ctx)
|
|
33
31
|
bound = (klass.respond_to?(:call) ? klass : klass.new).call(value, ctx)
|
|
@@ -19,6 +19,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
|
|
|
19
19
|
CONDITION_DIRECTIVES = %w[whereConditions whereHasConditions].freeze
|
|
20
20
|
|
|
21
21
|
def self.collection? = false
|
|
22
|
+
def self.applies_search? = true
|
|
22
23
|
|
|
23
24
|
# The directive's SDL: `description`, then the arguments of a relationship —
|
|
24
25
|
# and, on a collection, the pagination ones.
|