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.
Files changed (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +168 -1
  3. data/docs/authorization.md +5 -1
  4. data/docs/configuration.md +71 -3
  5. data/docs/custom-directives.md +22 -0
  6. data/docs/defer.md +352 -0
  7. data/docs/directives.md +106 -0
  8. data/docs/events.md +30 -1
  9. data/docs/filtering-and-ordering.md +567 -0
  10. data/docs/getting-started.md +1 -1
  11. data/docs/performance.md +9 -0
  12. data/docs/resolvers.md +14 -2
  13. data/docs/testing.md +99 -0
  14. data/lib/lighthouse/complexity.rb +4 -2
  15. data/lib/lighthouse/config.rb +28 -11
  16. data/lib/lighthouse/contracts/field_resolver.rb +32 -0
  17. data/lib/lighthouse/contracts/search_builder.rb +16 -0
  18. data/lib/lighthouse/controller.rb +94 -18
  19. data/lib/lighthouse/defer.rb +114 -0
  20. data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +1 -0
  21. data/lib/lighthouse/directive_resolvers/all_resolver.rb +32 -3
  22. data/lib/lighthouse/directive_resolvers/argument_binding.rb +1 -3
  23. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +1 -0
  24. data/lib/lighthouse/directive_resolvers/base.rb +116 -49
  25. data/lib/lighthouse/directive_resolvers/builder_applier.rb +24 -18
  26. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +28 -2
  27. data/lib/lighthouse/directive_resolvers/count_resolver.rb +1 -0
  28. data/lib/lighthouse/directive_resolvers/field_resolver.rb +4 -0
  29. data/lib/lighthouse/directive_resolvers/find_resolver.rb +31 -16
  30. data/lib/lighthouse/directive_resolvers/first_resolver.rb +6 -3
  31. data/lib/lighthouse/directive_resolvers/global_id_types.rb +1 -2
  32. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +2 -0
  33. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +29 -4
  34. data/lib/lighthouse/directive_resolvers/throttle_resolver.rb +17 -6
  35. data/lib/lighthouse/directives/arguments/base.rb +14 -0
  36. data/lib/lighthouse/directives/arguments/filters.rb +6 -0
  37. data/lib/lighthouse/directives/arguments/more_filters.rb +3 -0
  38. data/lib/lighthouse/directives/arguments/search.rb +34 -0
  39. data/lib/lighthouse/directives/arguments/soft_deletes.rb +11 -0
  40. data/lib/lighthouse/directives/model_directive.rb +1 -1
  41. data/lib/lighthouse/directives/registry.rb +1 -1
  42. data/lib/lighthouse/events/execution_trace.rb +6 -1
  43. data/lib/lighthouse/events/lifecycle.rb +2 -1
  44. data/lib/lighthouse/events.rb +9 -0
  45. data/lib/lighthouse/field_resolver_stack.rb +22 -21
  46. data/lib/lighthouse/graphql/version.rb +1 -1
  47. data/lib/lighthouse/incremental/body.rb +76 -0
  48. data/lib/lighthouse/incremental/defer_directive.rb +34 -0
  49. data/lib/lighthouse/incremental/delivery.rb +94 -0
  50. data/lib/lighthouse/incremental/document.rb +242 -0
  51. data/lib/lighthouse/incremental/gone.rb +6 -0
  52. data/lib/lighthouse/incremental/legacy.rb +75 -0
  53. data/lib/lighthouse/incremental/multipart.rb +76 -0
  54. data/lib/lighthouse/incremental/plan.rb +249 -0
  55. data/lib/lighthouse/incremental/rules.rb +116 -0
  56. data/lib/lighthouse/incremental/run.rb +302 -0
  57. data/lib/lighthouse/incremental/serializer.rb +37 -0
  58. data/lib/lighthouse/incremental/state.rb +204 -0
  59. data/lib/lighthouse/incremental/stream_directive.rb +41 -0
  60. data/lib/lighthouse/incremental/stream_trace.rb +93 -0
  61. data/lib/lighthouse/incremental/tree.rb +68 -0
  62. data/lib/lighthouse/namespaces.rb +2 -0
  63. data/lib/lighthouse/nested_mutations/belongs_to_operations.rb +2 -2
  64. data/lib/lighthouse/operations.rb +6 -2
  65. data/lib/lighthouse/pagination.rb +61 -15
  66. data/lib/lighthouse/persisted_queries.rb +53 -8
  67. data/lib/lighthouse/rb_lighthouse.rb +35 -0
  68. data/lib/lighthouse/resolve_info.rb +7 -1
  69. data/lib/lighthouse/schema_generator.rb +2 -0
  70. data/lib/lighthouse/search/auto.rb +26 -0
  71. data/lib/lighthouse/search/enhancer.rb +151 -0
  72. data/lib/lighthouse/search/field_check.rb +173 -0
  73. data/lib/lighthouse/search/pg_search.rb +146 -0
  74. data/lib/lighthouse/search/query.rb +54 -0
  75. data/lib/lighthouse/search/result.rb +181 -0
  76. data/lib/lighthouse/search/searchkick.rb +335 -0
  77. data/lib/lighthouse/search/searchkick_index.rb +54 -0
  78. data/lib/lighthouse/search/searchkick_options.rb +74 -0
  79. data/lib/lighthouse/search/together_check.rb +137 -0
  80. data/lib/lighthouse/search.rb +101 -0
  81. data/lib/lighthouse/support/argument_walk.rb +81 -0
  82. data/lib/lighthouse/support/count.rb +16 -0
  83. data/lib/lighthouse/support/failures.rb +28 -0
  84. data/lib/lighthouse/support/memo.rb +72 -0
  85. data/lib/lighthouse/support/model_resolver.rb +24 -0
  86. data/lib/lighthouse/support/relations.rb +31 -0
  87. data/lib/lighthouse/support/soft_deletes.rb +42 -8
  88. data/lib/lighthouse/testing.rb +81 -0
  89. data/sig/lighthouse/controller.rbs +34 -1
  90. data/sig/lighthouse/directives.rbs +46 -5
  91. data/sig/lighthouse/events.rbs +7 -0
  92. data/sig/lighthouse/graphql.rbs +117 -0
  93. data/sig/lighthouse/search.rbs +153 -0
  94. data/sig/lighthouse.rbs +77 -1
  95. metadata +39 -1
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ # Requests to the app's GraphQL endpoint, for its tests: PHP Lighthouse's MakesGraphQLRequests.
6
+ # Include it where Rails' integration session runs (an RSpec request spec, an
7
+ # ActionDispatch::IntegrationTest):
8
+ #
9
+ # RSpec.configure { |config| config.include Lighthouse::GraphQL::Testing, type: :request }
10
+ #
11
+ # it 'lists the posts' do
12
+ # body = graphql('{ posts(first: 1) { data { title } } }')
13
+ # expect(body.dig('data', 'posts', 'data')).to eq([{ 'title' => 'Hello' }])
14
+ # end
15
+ #
16
+ # Each request answers the response's parsed JSON body (`response` holds the response itself, as
17
+ # after any request). The endpoint is `graphql_endpoint`, `/graphql` unless a test overrides it.
18
+ module Lighthouse::GraphQL::Testing
19
+ # A request that was to stream did not.
20
+ class NotStreamed < StandardError; end
21
+
22
+ # POSTs a query with its variables (and `extra_params`, `operationName` or `extensions`), as JSON.
23
+ def graphql(query, variables = {}, extra_params: {}, headers: {})
24
+ post_graphql(graphql_operation(query, variables, extra_params), headers: headers)
25
+ end
26
+
27
+ # POSTs `data` as JSON: an operation's Hash, or a batch's Array of them.
28
+ def post_graphql(data, headers: {})
29
+ post_graphql_json(data, headers)
30
+ response.parsed_body
31
+ end
32
+
33
+ # POSTs a multipart request (graphql-multipart-request-spec, MultipartRequest): `operations`,
34
+ # the `map` from each file's key to the variables it fills, and the files by key
35
+ # (Rack::Test::UploadedFile).
36
+ def multipart_graphql(operations, map, files, headers: {})
37
+ params = { 'operations' => operations.to_json, 'map' => map.to_json }.merge(files.transform_keys(&:to_s))
38
+ post graphql_endpoint, params: params, headers: headers
39
+ response.parsed_body
40
+ end
41
+
42
+ # The response to graphql-ruby's introspection query.
43
+ def introspect = graphql(::GraphQL::Introspection.query)
44
+
45
+ # The introspection of the type, or of the directive, named `name`; nil when the schema has none.
46
+ def introspect_type(name) = introspect_by_name('types', name)
47
+ def introspect_directive(name) = introspect_by_name('directives', name)
48
+
49
+ # POSTs a query whose response streams (@defer, @stream), and answers each of its payloads,
50
+ # in order: the first, then one per round. `Accept` is `multipart/mixed` unless the headers say
51
+ # otherwise (Apollo's older format: `multipart/mixed;deferSpec=20220824`). A response that did
52
+ # not stream (the query deferred nothing, or the schema does not use Lighthouse::GraphQL::Defer)
53
+ # raises NotStreamed.
54
+ def stream_graphql(query, variables = {}, extra_params: {}, headers: {})
55
+ post_graphql_json(graphql_operation(query, variables, extra_params), { 'Accept' => 'multipart/mixed' }.merge(headers))
56
+ unless response.content_type.to_s.split(';').first == Lighthouse::GraphQL::Defer::MULTIPART
57
+ raise NotStreamed, "Expected a streamed response, got a regular one (#{response.content_type})."
58
+ end
59
+
60
+ Lighthouse::GraphQL::Incremental::Multipart.parse(response.body)
61
+ end
62
+
63
+ # The endpoint's path.
64
+ def graphql_endpoint = '/graphql'
65
+
66
+ private
67
+
68
+ def graphql_operation(query, variables, extra_params)
69
+ operation = { query: query }
70
+ operation[:variables] = variables unless variables.empty?
71
+ operation.merge(extra_params)
72
+ end
73
+
74
+ def post_graphql_json(data, headers)
75
+ post graphql_endpoint, params: data.to_json, headers: { 'Content-Type' => 'application/json' }.merge(headers)
76
+ end
77
+
78
+ def introspect_by_name(path, name)
79
+ introspect.dig('data', '__schema', path)&.find { |entry| entry['name'] == name }
80
+ end
81
+ end
@@ -35,8 +35,41 @@ module Lighthouse
35
35
  include Operations
36
36
 
37
37
  # The action: dispatches StartRequest, runs the operation (or a batch),
38
- # sets Cache-Control, renders JSON, dispatches EndRequest.
38
+ # sets Cache-Control, renders JSON (or streams an operation that defers, when the
39
+ # schema uses Defer), dispatches EndRequest.
39
40
  def execute: () -> void
40
41
  end
42
+
43
+ # Requests to the app's endpoint from its tests (PHP Lighthouse's MakesGraphQLRequests),
44
+ # in Rails' integration session. Each answers the response's parsed body.
45
+ module Testing : _IntegrationSession
46
+ class NotStreamed < StandardError
47
+ end
48
+
49
+ def graphql: (String query, ?Hash[String | Symbol, untyped] variables, ?extra_params: Hash[String | Symbol, untyped],
50
+ ?headers: Hash[String, String]) -> untyped
51
+ def post_graphql: (Hash[String | Symbol, untyped] | Array[Hash[String | Symbol, untyped]] data, ?headers: Hash[String, String]) -> untyped
52
+ def multipart_graphql: (Hash[String | Symbol, untyped] operations, Hash[String, Array[String]] map, Hash[String | Symbol, untyped] files,
53
+ ?headers: Hash[String, String]) -> untyped
54
+ def introspect: () -> untyped
55
+ def introspect_type: (String name) -> Hash[String, untyped]?
56
+ def introspect_directive: (String name) -> Hash[String, untyped]?
57
+ # The payloads of a streamed response; NotStreamed when it came whole.
58
+ def stream_graphql: (String query, ?Hash[String | Symbol, untyped] variables, ?extra_params: Hash[String | Symbol, untyped],
59
+ ?headers: Hash[String, String]) -> Array[Hash[String, json]]
60
+ def graphql_endpoint: () -> String
61
+ end
62
+
63
+ # Rails' integration session (ActionDispatch::Integration::Runner), as Testing uses it.
64
+ interface _IntegrationSession
65
+ def post: (String path, ?params: untyped, ?headers: Hash[String, String]) -> untyped
66
+ def response: () -> _TestResponse
67
+ end
68
+
69
+ interface _TestResponse
70
+ def parsed_body: () -> untyped
71
+ def body: () -> String
72
+ def content_type: () -> String?
73
+ end
41
74
  end
42
75
  end
@@ -17,9 +17,20 @@ module Lighthouse
17
17
  end
18
18
 
19
19
  # Its instances, built with (field_def, type_def, directive_node, opts),
20
- # install the field's resolver in `define_resolver(target_type)`.
20
+ # install the field's resolver in `define_resolver(target_type)`. Its class
21
+ # says whether it applies a @search on its field (by default, it does not).
21
22
  module FieldResolver
22
23
  include Directive
24
+
25
+ # The class methods a resolver gets with the contract, and overrides to opt in.
26
+ module SearchDefaults
27
+ def applies_search?: () -> bool
28
+ def takes_search_results?: (_NamedType type, _FieldDefinition field_def, _DirectiveNode? directive, Symbol? root_kind) -> bool
29
+ end
30
+
31
+ # What Search::FieldCheck asks of a resolver class, with or without the contract.
32
+ def self.applies_search?: (Class klass) -> bool
33
+ def self.takes_search_results?: (Class klass, _NamedType type, _FieldDefinition field_def, _DirectiveNode? directive, Symbol? root_kind) -> bool
23
34
  end
24
35
 
25
36
  # Its instances, built with (arg_node, directive_node), answer
@@ -47,6 +58,16 @@ module Lighthouse
47
58
  module FieldBuilder
48
59
  include Directive
49
60
  end
61
+
62
+ # An argument directive that also narrows a full-text search: its instances,
63
+ # built with (arg_node, directive_node), answer `handle_search_builder(query, value)`
64
+ # with the Search::Query. @eq, @trashed and @builder on an argument do.
65
+ module SearchBuilder
66
+ include Directive
67
+
68
+ # Narrow the search by the client's value, writing to the query (`where`, `trashed`, `options`).
69
+ def handle_search_builder: (Search::Query query, untyped value) -> Search::Query
70
+ end
50
71
  end
51
72
 
52
73
  class DirectiveRegistry
@@ -146,12 +167,18 @@ module Lighthouse
146
167
 
147
168
  def initialize: (_FieldDefinition field_def, _NamedType type_def, _DirectiveNode? directive_node, ?Hash[Symbol, untyped] opts) -> void
148
169
 
170
+ # Asked when the schema is built, of the field's resolving directive's class (Search::FieldCheck):
171
+ # does it run the field's argument filters, a relational search among them?
172
+ def self.applies_search?: () -> bool
173
+ # Does it take the records a search engine outside the database answers with, on this field?
174
+ def self.takes_search_results?: (_NamedType type, _FieldDefinition field_def, _DirectiveNode? directive, Symbol? root_kind) -> bool
175
+
149
176
  # Install the field's resolver on `target_type_class` (a graphql-ruby type class).
150
177
  def define_resolver: (Class target_type_class) -> void
151
178
 
152
179
  # `ctx`: the query's context, which @builder on an argument receives.
153
- def apply_where_filters: (relation relation, _ArgumentSet? args, ?context? ctx) -> relation
154
- def apply_arg_builders: (relation relation, arguments args_h, ?context? ctx) -> relation
180
+ # `search`: nil, a relation only; :model, a Search::Result for the model's own relation; :given, one for a relation the app's code gave.
181
+ def apply_where_filters: (relation relation, _ArgumentSet? args, ?context? ctx, ?search: (:model | :given)?) -> (relation | Search::Result)
155
182
  def apply_field_builders: (relation relation, ?arguments args_h, ?context? ctx) -> relation
156
183
  def constantize_model: (String? name) -> Class?
157
184
  def apply_scopes: (relation relation) -> relation
@@ -170,9 +197,13 @@ module Lighthouse
170
197
  class BuilderApplier
171
198
  DEFINITION: String
172
199
 
173
- def self.apply: (relation relation, _NamedNode? field_def_ast_node, arguments args, context? ctx, BaseDirectiveResolver? resolver_instance) -> relation
174
- def self.apply_directive: (relation relation, _DirectiveNode directive_node, arguments args, context? ctx, BaseDirectiveResolver? resolver_instance) -> relation
200
+ # A builder that raises, or cannot be found, goes on to the caller, which fails the field.
201
+ def self.apply: (relation relation, _NamedNode? field_def_ast_node, arguments args, context? ctx) -> relation
202
+ def self.apply_directive: (relation relation, _DirectiveNode directive_node, arguments args, context? ctx) -> relation
175
203
  def self.extract_directive_arg: (_DirectiveNode directive_node, String name) -> literal
204
+ # The field's own query directives `apply` applies (@builder, @whereAuth, field builders), in SDL order.
205
+ def self.query_directives: (_NamedNode? field_def_ast_node) -> Array[_DirectiveNode]
206
+ def self.any?: (_NamedNode? field_def_ast_node) -> bool
176
207
  end
177
208
  end
178
209
 
@@ -193,6 +224,16 @@ module Lighthouse
193
224
  # (whatever its type allows, so untyped).
194
225
  def handle_builder: (relation relation, untyped value) -> relation
195
226
 
227
+ # Does the directive, as the SDL writes it, change the field's query? A
228
+ # Searchkick search takes one that does not (@limit without `builder: true`).
229
+ def self.changes_query?: (_DirectiveNode? directive_node) -> bool
230
+
231
+ # Does the client's value, once sent, narrow the query? (@search: only a string.)
232
+ def self.filters?: (untyped value) -> bool
233
+
234
+ # Does the directive run the field's search (@search)?
235
+ def self.searches?: () -> bool
236
+
196
237
  private
197
238
 
198
239
  # The directive's `key:`, else the argument's name in snake_case.
@@ -41,6 +41,13 @@ module Lighthouse
41
41
  # ActiveSupport::Notifications subscriber.
42
42
  def self.listening?: (Class event_class) -> bool
43
43
 
44
+ # The query of the operation `query` runs: a GraphQL::Query::Partial's is the
45
+ # query it runs part of.
46
+ def self.operation_query: (_Query query) -> _Query
47
+
48
+ # GraphQL::Query::Partial, where graphql-ruby has it (2.5.6 on).
49
+ PARTIAL: Class?
50
+
44
51
  # The ActiveSupport::Notifications name an event class is instrumented as.
45
52
  def self.notification_name: (Class event_class) -> String
46
53
 
@@ -96,6 +96,16 @@ module Lighthouse
96
96
  # protocol error as a ready-to-render { "errors" => [...] } Hash.
97
97
  def self?.execute: (schema schema, query: String?, ?extensions: extensions?, ?variables: Hash[String, untyped]?,
98
98
  ?operation_name: String?, ?context: Hash[Symbol, untyped], **untyped options) -> _Result
99
+ # `execute` for a response that may be streamed (Defer): yields the started
100
+ # Incremental::Run and answers what the block does, or a protocol error as a
101
+ # ready-to-render Hash. The operation ends once the run is done, or the block.
102
+ # Without a block, it answers the Run, which the caller ends (Run#finish).
103
+ def self?.incremental: [T] (schema schema, query: String?, ?extensions: extensions?, ?format: Incremental::format,
104
+ ?variables: Hash[String, untyped]?, ?operation_name: String?, ?context: Hash[Symbol, untyped],
105
+ **untyped options) { (Incremental::Run run) -> T } -> (T | Hash[String, json])
106
+ | (schema schema, query: String?, ?extensions: extensions?, ?format: Incremental::format,
107
+ ?variables: Hash[String, untyped]?, ?operation_name: String?, ?context: Hash[Symbol, untyped],
108
+ **untyped options) -> (Incremental::Run | Hash[String, json])
99
109
  # A batch: `schema.multiplex` with the query each operation (a Hash of
100
110
  # query, extensions, variables, operation_name, context) names. One result
101
111
  # per operation, in order; a protocol error is a ready-to-render Hash.
@@ -179,6 +189,113 @@ module Lighthouse
179
189
  end
180
190
  end
181
191
 
192
+ # @defer (experimental; the specification it follows is a draft): a graphql-ruby
193
+ # plugin, `use Lighthouse::GraphQL::Defer` in the schema class. Lighthouse::GraphQL::Controller
194
+ # then streams the response of an operation that defers, unless the client's Accept header
195
+ # leaves `multipart/mixed` out.
196
+ module Defer
197
+ MULTIPART: String
198
+ LEGACY: String
199
+ LEGACY_TYPE: String
200
+ FORMAT: String
201
+ GRAPHQL: String
202
+
203
+ # graphql-ruby's plugin hook.
204
+ def self?.use: (schema schema, **untyped options) -> void
205
+ # Does the schema use the plugin? `use` extends the schema class with Used.
206
+ def self?.enabled?: (schema schema) -> bool
207
+ module Used
208
+ end
209
+ # The Content-Type of a streamed response to a client that sends `accept`, or nil when it
210
+ # does not take one; it names Apollo's older format (`deferSpec=20220824`) when the client did.
211
+ def self?.stream_type: (String? accept) -> String?
212
+ # Is the Content-Type (stream_type's) Apollo's older format?
213
+ def self?.legacy?: (String? content_type) -> bool
214
+ # Each media range of the header.
215
+ def self?.ranges: (String? accept) -> Array[MediaRange]
216
+
217
+ # A media range of an Accept header.
218
+ class MediaRange
219
+ attr_reader type: String
220
+ attr_reader params: Array[String]
221
+ attr_reader q: Float
222
+ attr_reader index: Integer
223
+ def rank: () -> [Float, Integer]
224
+ def covers?: (String name) -> bool
225
+ def specificity: () -> Integer
226
+ def legacy?: () -> bool
227
+ end
228
+ end
229
+
230
+ module Incremental
231
+ # The payloads' format: the specification draft's, or Apollo's older one (Legacy).
232
+ type format = :draft | :legacy
233
+
234
+ # One operation, run in as many passes as @defer asks for.
235
+ class Run
236
+ # `options` are `schema.execute`'s: variables:, operation_name:, context:.
237
+ # A nil query string (a request without one) is answered as graphql-ruby answers it.
238
+ def initialize: (schema schema, String? query_string, ?format: format, **untyped options) -> void
239
+ # Runs the first pass; returns self. The block gets what ends the operation (see finish).
240
+ def start: () ?{ (_Result result) -> void } -> Run
241
+ # Calls start's block, once: with the first pass's result when nothing was deferred, else the response so far.
242
+ def finish: () -> void
243
+ # The first pass's result.
244
+ def result: () -> _Result
245
+ # Are fragments pending?
246
+ def deferred?: () -> bool
247
+ # The initial payload, then one per round of deferred fragments, until `hasNext` is false.
248
+ def each_payload: () { (Hash[String, json]) -> void } -> void
249
+ # The first payload, as the client is sent it (each_payload yields it first).
250
+ def first_payload: () -> Hash[String, json]
251
+ # The first payload could not be sent: the operation ends as one that failed.
252
+ def refuse!: () -> void
253
+ # The whole response: the data and the errors of every round the client was sent ({} if none).
254
+ def response: () -> Hash[String, json]
255
+ end
256
+
257
+ # Converts the draft's payloads to Apollo's older format (`deferSpec=20220824`).
258
+ class Legacy
259
+ def initialize: (Hash[String, untyped] pendings) -> void
260
+ def convert: (Hash[String, json] payload) -> Hash[String, json]
261
+ end
262
+
263
+ # The parts of a `multipart/mixed` response (graphql-over-http's IncrementalDelivery).
264
+ class Multipart
265
+ CONTENT_TYPE: String
266
+ PART_HEADERS: String
267
+ CLOSING: String
268
+
269
+ def self.headers: (?String content_type) -> Hash[String, String]
270
+ # The JSON of each part of a multipart/mixed body.
271
+ def self.parse: (String? body) -> Array[Hash[String, json]]
272
+ # The part of a payload, encoded as render json: does (the payload holds the app's values:
273
+ # a Time, an object's as_json; their errors are raised here).
274
+ def part: (Hash[String, untyped] payload) -> String
275
+ # A part (or the closing boundary) was written.
276
+ def written: (String part) -> void
277
+ def started?: () -> bool
278
+ # The closing boundary, once a part was written.
279
+ def closing: () -> String?
280
+ # The response as EndRequest carries it: its body the parts written.
281
+ def ended: (untyped response) -> Response
282
+ def initialize: (?keep: bool) -> void
283
+
284
+ class Response
285
+ def initialize: (untyped response, Array[String] parts) -> void
286
+ def body: () -> String
287
+ end
288
+ end
289
+
290
+ # The Rack body of a streamed response: writes each part as its round runs, then ends the
291
+ # operation and the request (`finish`, once).
292
+ class Body
293
+ def initialize: (Run run, Multipart multipart, String first, on_error: ^(StandardError) -> void, on_end: ^() -> void) -> void
294
+ def each: () { (String part) -> void } -> void
295
+ def finish: () -> void
296
+ end
297
+ end
298
+
182
299
  # The opt-in cache of the manipulated schema document, in tmp/cache.
183
300
  module SchemaCache
184
301
  PREFIX: String
@@ -0,0 +1,153 @@
1
+ # Full-text search for @search: the query the directives write to, the result an
2
+ # engine outside the database answers with, and the adapters of the two gems.
3
+ # The adapter protocol (_SearchAdapter) is experimental. See docs/filtering-and-ordering.md.
4
+ module Lighthouse
5
+ module Search
6
+ # The adapter in use: Config.search, else the detecting Search::Auto.
7
+ def self.adapter: () -> (_SearchAdapter | _SearchAdapterChooser)
8
+
9
+ # The adapter that searches the model (within the scope or index `index` names), or nil.
10
+ def self.adapter_for: (Class model, ?String? index) -> _SearchAdapter?
11
+
12
+ # The scope a model may define for what a search of it may return: `search_results`.
13
+ RESULTS_SCOPE: Symbol
14
+
15
+ # Does the model have a `search_results` scope?
16
+ def self.results_scope?: (Class model) -> bool
17
+
18
+ # The relation through the model's `search_results` scope, if it has one.
19
+ def self.results: (_ModelRelation relation) -> _ModelRelation
20
+
21
+ # Does the field have an argument or input field with @search? Walked once per field.
22
+ def self.searching?: (_FieldDefinition field_def) -> bool
23
+
24
+ # The models the field searches together (a union's or an interface's), kept when the schema is built; nil for one model.
25
+ def self.together: (_FieldDefinition field_def) -> Array[Class]?
26
+ def self.together!: (_FieldDefinition field_def, Array[Class] models) -> Array[Class]
27
+ # The adapter that searches the models together, or nil.
28
+ def self.adapter_together: (Array[Class] models) -> _TogetherSearchAdapter?
29
+
30
+ # What a search holds: the model, the term and what narrows it.
31
+ class Query
32
+ # nil for models searched together.
33
+ attr_reader model: Class?
34
+ # The models searched together, or nil for a search of one.
35
+ attr_reader models: Array[Class]?
36
+ attr_reader term: String
37
+ attr_reader index: String?
38
+ # [column, value] pairs, from @eq, all of which hold.
39
+ attr_reader wheres: Array[[String, untyped]]
40
+ # Adapter-specific options, from @builder on an argument.
41
+ attr_reader options: Hash[Symbol | String, untyped]
42
+ # :with, :only or :without, from @trashed; nil: not given.
43
+ attr_accessor trashed: (:with | :only | :without)?
44
+
45
+ def initialize: (Class? model, String term, ?String? index, ?models: Array[Class]?) -> void
46
+ def where: (String | Symbol column, untyped value) -> self
47
+ # The model's name, or the names of the models searched together.
48
+ def name: () -> String
49
+ # The same search of one model.
50
+ def for: (Class model) -> Query
51
+ end
52
+
53
+ # A search an engine answers: the page it is asked for and its total.
54
+ class Result
55
+ MAX_WINDOW: Integer
56
+
57
+ attr_reader query: Query
58
+
59
+ # The fiber-local key of the search @canQuery checked, while the field it checks resolves.
60
+ CHECKED: Symbol
61
+
62
+ # The block, in which the search of the same field is `result`, the one @canQuery checked.
63
+ def self.serving: [T] (Result? result) { () -> T } -> T
64
+ # The search @canQuery checked in this resolution, when it is this one; else nil.
65
+ def self.checked: (_EngineSearchAdapter adapter, Query query, String? field) -> Result?
66
+
67
+ # `field`: "Type.field", whose search it is.
68
+ def initialize: (_EngineSearchAdapter adapter, Query query, ?context: untyped, ?field: String?) -> void
69
+ def same_search?: (_EngineSearchAdapter adapter, Query query, String? field) -> bool
70
+ def window: (Integer offset, Integer limit) -> Array[_Record]
71
+ def count: () -> Integer
72
+ READ_LIMIT: Integer
73
+
74
+ def records: (?first: Integer?, ?offset: Integer?) -> Array[_Record]
75
+ # @find's record (more than one match: a GraphQL::ExecutionError), and @first's: the best match that loads.
76
+ def only_record: () -> _Record?
77
+ def first_record: () -> _Record?
78
+ # Every record a page can reach, for @canQuery, in a request of its own: READ_LIMIT at most, else a GraphQL::ExecutionError.
79
+ def every_record: () -> Array[_Record]
80
+ # Did the last `records` answer fewer than asked while more match? How many can a page reach?
81
+ def truncated?: () -> bool
82
+ def reachable: () -> Integer
83
+ # How many of the matches the engine pages through: the adapter's `result_window(query)`, else MAX_WINDOW; nil when the adapter cannot tell.
84
+ def result_window: () -> Integer?
85
+ end
86
+
87
+ # Searchkick (Elasticsearch / OpenSearch), outside the database.
88
+ class Searchkick
89
+ include _EngineSearchAdapter
90
+ include _TogetherSearchAdapter
91
+
92
+ DEFAULT_TRASHED_COLUMN: String
93
+ DEEP_PAGING_WINDOW: Integer
94
+
95
+ # @trashed filters on the column Config.soft_deletes tells (Support::SoftDeletes.column).
96
+ # `index`: what the engine tells of an index, read and kept.
97
+ def initialize: (?index: Searchkick::Index) -> void
98
+
99
+ # Why the model cannot be searched as it is (a narrowing default scope or search_results, without search_where), or nil.
100
+ def model_error: (Class model) -> String?
101
+
102
+ # The index's max_result_window, read from the engine; else the model's options', else 10,000.
103
+ def result_window: (Query query) -> Integer
104
+
105
+ # What an @builder may ask of Searchkick's search, and which conditions the database applies alike.
106
+ module Options
107
+ # The options of Searchkick's search an @builder may set, and the keys of its body_options.
108
+ BUILDER_OPTIONS: Array[Symbol]
109
+ BODY_OPTIONS: Array[Symbol]
110
+ # The values the database compares a column with as the engine does.
111
+ SQL_SCALARS: Array[Module]
112
+ end
113
+
114
+ # An index's mapping and max_result_window, read from the engine once per INDEX_READ_TTL seconds (a failed read FAILED_READ_TTL).
115
+ class Index
116
+ INDEX_READ_TTL: Integer
117
+ FAILED_READ_TTL: Integer
118
+
119
+ # `clock`: seconds, monotonic.
120
+ def initialize: (?clock: ^() -> Numeric) -> void
121
+ def fields: (Class model, String? name) -> Array[String]?
122
+ def result_window: (Class model, String? name) -> Integer?
123
+ # Why the last read of the index's `:mapping` or `:window` failed, while that is kept.
124
+ def failure: (:mapping | :window kind, Class model, String? name) -> StandardError?
125
+ end
126
+ end
127
+
128
+ # pg_search (PostgreSQL full-text search), in the database.
129
+ class PgSearch
130
+ include _RelationalSearchAdapter
131
+ include _EngineSearchAdapter
132
+ include _TogetherSearchAdapter
133
+
134
+ DEFAULT_SCOPE: Symbol
135
+
136
+ # Models searched together, through multisearch's documents (page), which have no result window.
137
+ def result_window: (Query query) -> nil
138
+
139
+ # Does `index` name one of the model's pg_search scopes?
140
+ def named?: (Class model, String? index) -> bool
141
+ end
142
+
143
+ # Picks Searchkick, then pg_search, per model.
144
+ class Auto
145
+ include _SearchAdapterChooser
146
+
147
+ def initialize: (?Array[_SearchAdapter]? adapters) -> void
148
+ def searchable?: (Class model, ?String? index) -> bool
149
+ # The first adapter that searches every one of the models together, or nil.
150
+ def adapter_together: (Array[Class] models) -> _TogetherSearchAdapter?
151
+ end
152
+ end
153
+ end
data/sig/lighthouse.rbs CHANGED
@@ -111,6 +111,12 @@ module Lighthouse
111
111
 
112
112
  type relation = _Relation
113
113
 
114
+ # An ActiveRecord::Relation, which knows its model (a model class does not answer `klass`).
115
+ interface _ModelRelation
116
+ include _Relation
117
+ def klass: () -> Class
118
+ end
119
+
114
120
  # An Arel attribute or SQL literal, which predicates build on.
115
121
  interface _ArelNode
116
122
  def eq: (untyped other) -> _ArelNode
@@ -128,6 +134,7 @@ module Lighthouse
128
134
  interface _Request
129
135
  def path: () -> String
130
136
  def headers: () -> untyped
137
+ def env: () -> Hash[String, untyped]
131
138
  end
132
139
 
133
140
  # What has response headers: an ActionDispatch::Response.
@@ -230,7 +237,9 @@ module Lighthouse
230
237
  # Config.soft_deletes: what "trashed" means for @softDeletes, @trashed,
231
238
  # @restore, @forceDelete and @withoutGlobalScopes. The filters take a model's
232
239
  # relation and answer the constrained one; `restore` and `force_delete` act
233
- # on a record and answer whether they succeeded.
240
+ # on a record and answer whether they succeeded. It may also answer
241
+ # `column(model)` and `kept_value(model)`: the column that marks trashed records
242
+ # and its value for the others, which a Searchkick search filters on.
234
243
  interface _SoftDeletes
235
244
  def soft_deletes?: (Class model) -> boolish
236
245
  def only_trashed: (relation relation) -> relation
@@ -240,6 +249,45 @@ module Lighthouse
240
249
  def force_delete: (_Record record) -> boolish
241
250
  end
242
251
 
252
+ # Config.search: what searches a model (see Lighthouse::Search). The protocol is
253
+ # experimental. `searchable?` says whether the model can be searched, within
254
+ # the pg_search scope or the index `index` names. A relational adapter
255
+ # (pg_search) narrows the field's relation, and every other directive applies
256
+ # on top; the others answer a page of records and the total, and take only
257
+ # the directives that include Contracts::SearchBuilder.
258
+ interface _SearchAdapter
259
+ def searchable?: (Class model, ?String? index) -> boolish
260
+ def relational?: () -> boolish
261
+ end
262
+
263
+ interface _RelationalSearchAdapter
264
+ include _SearchAdapter
265
+ def scope: (relation relation, Search::Query query) -> relation
266
+ end
267
+
268
+ # `page` answers one entry per hit, nil for a hit it could not load, and the total: every match, counted.
269
+ # It may answer `model_error(model)`: why a model cannot be searched as it is, which
270
+ # Search::FieldCheck makes a schema error.
271
+ # It may also answer `result_window(query)`: how many matches it pages through
272
+ # (Search::Result::MAX_WINDOW when it does not), or nil when it cannot tell.
273
+ interface _EngineSearchAdapter
274
+ include _SearchAdapter
275
+ def page: (Search::Query query, offset: Integer, limit: Integer) -> [Array[_Record?], Integer]
276
+ end
277
+
278
+ # Search::Auto: picks the adapter per model.
279
+ interface _SearchAdapterChooser
280
+ def adapter_for: (Class model, ?String? index) -> _SearchAdapter?
281
+ end
282
+
283
+ # An adapter that searches models together (a union's or an interface's): its `page` (as
284
+ # _EngineSearchAdapter's) answers a Search::Query with `models`, and `together_error(model)`
285
+ # why one cannot be searched with others as it is (a schema error).
286
+ interface _TogetherSearchAdapter
287
+ def searchable_together?: (Class model) -> boolish
288
+ def together_error: (Class model) -> String?
289
+ end
290
+
243
291
  # What DirectiveRegistry#register_manipulator takes: it transforms the SDL
244
292
  # before the schema is built.
245
293
  interface _SdlManipulator
@@ -279,6 +327,14 @@ module Lighthouse
279
327
  def self.schema_log: () -> bool
280
328
  def self.schema_log=: (bool? enabled) -> bool?
281
329
 
330
+ # @defer's limits (Defer), PHP Lighthouse's defer.max_nested_fields and
331
+ # defer.max_execution_ms: rounds of nesting, milliseconds; 0 (the default) is no limit.
332
+ def self.defer_max_nested_fields: () -> Integer
333
+ # Any value is taken, and read as a count (Support::Count): an Integer of 0 or more, or a String of digits.
334
+ def self.defer_max_nested_fields=: (Object? rounds) -> Object?
335
+ def self.defer_max_execution_ms: () -> Integer
336
+ def self.defer_max_execution_ms=: (Object? milliseconds) -> Object?
337
+
282
338
  # { queries:, mutations:, subscriptions:, builders:, validators:, events: } => [namespace, ...].
283
339
  # Assigning a partial hash overrides only the kinds it names.
284
340
  def self.namespaces: () -> Hash[Symbol, Array[String]]
@@ -344,6 +400,10 @@ module Lighthouse
344
400
  def self.soft_deletes: () -> _SoftDeletes?
345
401
  def self.soft_deletes=: (_SoftDeletes? adapter) -> _SoftDeletes?
346
402
 
403
+ # What searches a model for @search; nil: detected per model (Search::Auto).
404
+ def self.search: () -> (_SearchAdapter | _SearchAdapterChooser)?
405
+ def self.search=: ((_SearchAdapter | _SearchAdapterChooser)? adapter) -> (_SearchAdapter | _SearchAdapterChooser)?
406
+
347
407
  def self.feature_checker: () -> _FeatureChecker
348
408
  def self.feature_checker=: (_FeatureChecker? checker) -> _FeatureChecker?
349
409
  def self.feature_actor: () -> _UserReader
@@ -351,7 +411,19 @@ module Lighthouse
351
411
  end
352
412
 
353
413
  module Support
414
+ # A count a setting holds: an Integer of 0 or more, or a String of digits read as its number.
415
+ module Count
416
+ # Raises ArgumentError for a value that is not one.
417
+ def self?.read: (Symbol name, Object? value) -> Integer?
418
+ end
419
+
354
420
  module SoftDeletes
421
+ # :only, :with or :without, for a Trashed enum value; a client error for any other.
422
+ def self.trashed: (untyped value) -> (:only | :with | :without)
423
+ # The column that marks the model's trashed records, as the adapter tells it, and its value for the others.
424
+ def self.column: (Class model) -> String?
425
+ def self.kept_value: (Class model) -> untyped
426
+
355
427
  # A nullable timestamp column marking trashed records, with no gem:
356
428
  # `Config.soft_deletes = Support::SoftDeletes::Column.new(:archived_at)`.
357
429
  class Column
@@ -360,6 +432,10 @@ module Lighthouse
360
432
  DEFAULT_COLUMN: String
361
433
 
362
434
  def initialize: (?String | Symbol column) -> void
435
+
436
+ # The column that marks trashed records, and its value for the others, for a search engine to filter on.
437
+ def column: (Class model) -> String
438
+ def kept_value: (Class model) -> nil
363
439
  end
364
440
  end
365
441
  end