lighthouse-graphql 0.8.1 → 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.
Files changed (97) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +166 -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 -1
  8. data/docs/events.md +30 -1
  9. data/docs/filtering-and-ordering.md +488 -0
  10. data/docs/getting-started.md +1 -1
  11. data/docs/performance.md +9 -0
  12. data/docs/relay.md +27 -0
  13. data/docs/resolvers.md +14 -2
  14. data/docs/testing.md +99 -0
  15. data/lib/lighthouse/complexity.rb +4 -2
  16. data/lib/lighthouse/config.rb +28 -11
  17. data/lib/lighthouse/contracts/field_resolver.rb +32 -0
  18. data/lib/lighthouse/contracts/search_builder.rb +16 -0
  19. data/lib/lighthouse/controller.rb +94 -18
  20. data/lib/lighthouse/defer.rb +114 -0
  21. data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +1 -0
  22. data/lib/lighthouse/directive_resolvers/all_resolver.rb +30 -1
  23. data/lib/lighthouse/directive_resolvers/argument_binding.rb +1 -3
  24. data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +14 -4
  25. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +1 -0
  26. data/lib/lighthouse/directive_resolvers/base.rb +99 -49
  27. data/lib/lighthouse/directive_resolvers/builder_applier.rb +24 -18
  28. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +28 -2
  29. data/lib/lighthouse/directive_resolvers/count_resolver.rb +1 -0
  30. data/lib/lighthouse/directive_resolvers/field_resolver.rb +4 -0
  31. data/lib/lighthouse/directive_resolvers/find_resolver.rb +31 -16
  32. data/lib/lighthouse/directive_resolvers/first_resolver.rb +6 -3
  33. data/lib/lighthouse/directive_resolvers/global_id_resolver.rb +6 -0
  34. data/lib/lighthouse/directive_resolvers/global_id_types.rb +83 -0
  35. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +2 -0
  36. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +27 -4
  37. data/lib/lighthouse/directive_resolvers/throttle_resolver.rb +17 -6
  38. data/lib/lighthouse/directives/arguments/base.rb +14 -0
  39. data/lib/lighthouse/directives/arguments/filters.rb +6 -0
  40. data/lib/lighthouse/directives/arguments/more_filters.rb +3 -0
  41. data/lib/lighthouse/directives/arguments/search.rb +34 -0
  42. data/lib/lighthouse/directives/arguments/soft_deletes.rb +11 -0
  43. data/lib/lighthouse/directives/model_directive.rb +1 -1
  44. data/lib/lighthouse/directives/registry.rb +1 -1
  45. data/lib/lighthouse/events/execution_trace.rb +6 -1
  46. data/lib/lighthouse/events/lifecycle.rb +2 -1
  47. data/lib/lighthouse/events.rb +9 -0
  48. data/lib/lighthouse/field_resolver_stack.rb +22 -21
  49. data/lib/lighthouse/global_id.rb +28 -0
  50. data/lib/lighthouse/graphql/version.rb +1 -1
  51. data/lib/lighthouse/incremental/body.rb +76 -0
  52. data/lib/lighthouse/incremental/defer_directive.rb +34 -0
  53. data/lib/lighthouse/incremental/delivery.rb +94 -0
  54. data/lib/lighthouse/incremental/document.rb +242 -0
  55. data/lib/lighthouse/incremental/gone.rb +6 -0
  56. data/lib/lighthouse/incremental/legacy.rb +75 -0
  57. data/lib/lighthouse/incremental/multipart.rb +76 -0
  58. data/lib/lighthouse/incremental/plan.rb +249 -0
  59. data/lib/lighthouse/incremental/rules.rb +116 -0
  60. data/lib/lighthouse/incremental/run.rb +302 -0
  61. data/lib/lighthouse/incremental/serializer.rb +37 -0
  62. data/lib/lighthouse/incremental/state.rb +204 -0
  63. data/lib/lighthouse/incremental/stream_directive.rb +41 -0
  64. data/lib/lighthouse/incremental/stream_trace.rb +93 -0
  65. data/lib/lighthouse/incremental/tree.rb +68 -0
  66. data/lib/lighthouse/namespaces.rb +2 -0
  67. data/lib/lighthouse/nested_mutations/belongs_to_operations.rb +2 -2
  68. data/lib/lighthouse/operations.rb +6 -2
  69. data/lib/lighthouse/pagination.rb +61 -15
  70. data/lib/lighthouse/persisted_queries.rb +53 -8
  71. data/lib/lighthouse/rb_lighthouse.rb +35 -0
  72. data/lib/lighthouse/resolve_info.rb +7 -1
  73. data/lib/lighthouse/search/auto.rb +21 -0
  74. data/lib/lighthouse/search/enhancer.rb +127 -0
  75. data/lib/lighthouse/search/field_check.rb +171 -0
  76. data/lib/lighthouse/search/pg_search.rb +76 -0
  77. data/lib/lighthouse/search/query.rb +35 -0
  78. data/lib/lighthouse/search/result.rb +181 -0
  79. data/lib/lighthouse/search/searchkick.rb +292 -0
  80. data/lib/lighthouse/search/searchkick_index.rb +54 -0
  81. data/lib/lighthouse/search/searchkick_options.rb +74 -0
  82. data/lib/lighthouse/search.rb +78 -0
  83. data/lib/lighthouse/support/argument_walk.rb +81 -0
  84. data/lib/lighthouse/support/count.rb +16 -0
  85. data/lib/lighthouse/support/failures.rb +28 -0
  86. data/lib/lighthouse/support/memo.rb +72 -0
  87. data/lib/lighthouse/support/model_resolver.rb +24 -0
  88. data/lib/lighthouse/support/relations.rb +31 -0
  89. data/lib/lighthouse/support/soft_deletes.rb +42 -8
  90. data/lib/lighthouse/testing.rb +81 -0
  91. data/sig/lighthouse/controller.rbs +34 -1
  92. data/sig/lighthouse/directives.rbs +46 -5
  93. data/sig/lighthouse/events.rbs +7 -0
  94. data/sig/lighthouse/graphql.rbs +117 -0
  95. data/sig/lighthouse/search.rbs +132 -0
  96. data/sig/lighthouse.rbs +69 -1
  97. metadata +39 -1
data/docs/defer.md ADDED
@@ -0,0 +1,352 @@
1
+ # Deferred fields: @defer and @stream
2
+
3
+ **Experimental: not enabled by default, not guaranteed to be stable.**
4
+
5
+ Deferring fields lets a client get the data it needs to render the most important content as
6
+ fast as possible, and the rest in the background, in later parts of the same response.
7
+ Lighthouse supports `@defer` (and `@stream`) through a plugin of the schema, as PHP Lighthouse
8
+ does through a service provider, but as the
9
+ [specification draft](https://github.com/graphql/graphql-spec/pull/1110) (RFC stage 2) has them:
10
+ `@defer` goes on a fragment, not on a field.
11
+
12
+ ```graphql
13
+ query Feed {
14
+ posts(first: 10) {
15
+ data {
16
+ title
17
+ ... @defer(label: "details") { author { name } comments { data { body } } }
18
+ }
19
+ }
20
+ }
21
+ ```
22
+
23
+ The draft can still change, and the plugin, the settings and the payloads may change with it
24
+ before it reaches stage 3.
25
+
26
+ ## Setup
27
+
28
+ Use the plugin in the schema class, as PHP Lighthouse registers its `DeferServiceProvider`:
29
+
30
+ ```ruby
31
+ # app/graphql/app_schema.rb
32
+ class AppSchema < Lighthouse::GraphQL::RbLightHouse.get_schema(options: { ... })
33
+ use GraphQL::Dataloader
34
+ use Lighthouse::GraphQL::Defer # adds @defer and @stream
35
+ end
36
+ ```
37
+
38
+ That is all. The `GraphqlController` that `rails generate lighthouse:install` writes includes
39
+ `Lighthouse::GraphQL::Controller`, which streams the response of an operation that defers, from
40
+ the same action and the same routes, `POST` and `GET` alike: no controller nor route of its own.
41
+
42
+ Without the plugin the schema has no `@defer`, as the specification asks of a server that does
43
+ not implement it. The plugin needs graphql-ruby 2.5.23 or newer (`use` raises otherwise).
44
+
45
+ ## When the response streams
46
+
47
+ As in PHP Lighthouse, the response is streamed when the operation defers something: a fragment
48
+ or a list is pending once the first pass has run. One that defers nothing (no `@defer`, or one
49
+ with `if: false`) is answered as JSON, as without the plugin.
50
+
51
+ Lighthouse streams to any client, as PHP Lighthouse does, but one whose `Accept` header leaves
52
+ `multipart/mixed` out: no media range covers it (`application/json` alone), or the most specific
53
+ one that does is at `q=0` (`multipart/mixed;q=0`). That client gets the whole response at once, the
54
+ deferred fragments in it, as the specification allows. A client that sends no `Accept` header, or
55
+ `*/*`, is streamed to.
56
+
57
+ The format is the specification draft's (below), or Apollo's older one when the client's
58
+ preferred `multipart/mixed` range names it (`multipart/mixed;deferSpec=20220824`):
59
+
60
+ | The client sends | It gets |
61
+ | --- | --- |
62
+ | no `Accept`, `*/*`, `multipart/mixed` (GraphiQL: `application/json, multipart/mixed`) | the draft's format, `multipart/mixed; boundary="-"` |
63
+ | `multipart/mixed;incrementalSpec=v0.2` | the draft's format, `multipart/mixed; boundary="-"; incrementalSpec=v0.2` |
64
+ | `multipart/mixed;deferSpec=20220824` (Apollo Client 3) | Apollo's older format, `multipart/mixed; boundary="-"; deferSpec=20220824` |
65
+ | `application/json`, `application/graphql-response+json` only | the whole response, as JSON |
66
+
67
+ `Lighthouse::GraphQL::Defer.stream_type(accept)` answers the Content-Type a header gets, or nil.
68
+
69
+ Some requests are always answered whole: a batch (a JSON array of operations), which answers one
70
+ JSON array, and a `HEAD` request, which has no body. A multipart upload's operation streams as
71
+ any other.
72
+
73
+ ## Configuration
74
+
75
+ Two settings keep a deferred response from running too long, PHP Lighthouse's
76
+ `defer.max_nested_fields` and `defer.max_execution_ms`, with their meaning. `0`, the default, is
77
+ no limit.
78
+
79
+ ```ruby
80
+ Lighthouse.configure do |config|
81
+ config.defer_max_nested_fields = 3 # rounds of nested deferred fragments
82
+ config.defer_max_execution_ms = 2_000 # since the first pass started
83
+ end
84
+ ```
85
+
86
+ A response goes in rounds: the first payload, then one payload for each round, which resolves
87
+ every fragment pending and announces the fragments those hold. Past `defer_max_nested_fields`
88
+ rounds, or once `defer_max_execution_ms` milliseconds have gone, the round that runs is the last:
89
+ it resolves the fragments it holds where they stand, without deferring them. See
90
+ [configuration.md](configuration.md#defer_max_nested_fields-and-defer_max_execution_ms).
91
+
92
+ ## Writing @defer
93
+
94
+ `@defer` goes on an inline fragment or a fragment spread (`...Details @defer`), with `if` (defer
95
+ only when true; a variable is fine) and `label` (names the fragment in the response):
96
+
97
+ ```graphql
98
+ directive @defer(if: Boolean! = true, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT
99
+ ```
100
+
101
+ To defer one field, as PHP Lighthouse's `field @defer { ... }` does, put it in a fragment of its
102
+ own: `... @defer { field { ... } }`. Fragments nest: one inside a deferred fragment arrives a round
103
+ after it.
104
+
105
+ The rules, from the draft and PHP Lighthouse. They hold for every query of the schema, streamed or
106
+ not (a graphql-ruby analyzer checks them before anything runs, and a query that breaks one is
107
+ answered the errors, without data):
108
+
109
+ - `@defer` is not allowed on a root mutation field, whose fields must run one after the other:
110
+ "The @defer directive cannot be used on a root mutation field.", whether the fragment is inline or
111
+ named. A fragment deeper in a mutation's response defers as in a query.
112
+ - In a subscription, `@defer` must be disabled: `if: false`, or a variable that is false for the
113
+ request (one that is true is refused, as the draft forbids incremental delivery there).
114
+ - `label` is a string, not a variable, and no two `@defer` or `@stream` of the document share one
115
+ (in any of its operations and fragments).
116
+ - `@skip` and `@include` on the fragment answer first: a fragment they leave out is neither
117
+ deferred nor resolved.
118
+ - A fragment with `if` not false is always deferred, and completes. A field it selects that the
119
+ rest of the query also asks for at the same path (itself, or through an inline or a named
120
+ fragment) comes in the first payload as usual, resolved once, and is not sent again: in
121
+ `{ ...UserWithParent ... @defer { parent { name } } }`, where `UserWithParent` also selects
122
+ `parent { name }`, the fragment is pending, then completes with no data of its own. A fragment
123
+ that adds selections to such a field (`... @defer { parent { email } }`) gets them, without
124
+ `parent` resolving again, at the `subPath` of `parent`. Two fragments of a round that select
125
+ one field send it once, as the draft's grouped field sets do (below).
126
+ - A fragment on a type the object does not have runs nowhere, and one on a union with no type
127
+ condition runs where it stands, as the specification has it.
128
+
129
+ ## What the client gets
130
+
131
+ The first part is the response without the deferred fragments, and a `pending` entry for each
132
+ one, with a string `id`, the `path` of the object it will run on and its `label`. A fragment under
133
+ a list is pending once for each item. Then a part for each round: the `incremental` data of each
134
+ fragment, under its `id`, and the ids that are `completed`, with the `pending` entries of the
135
+ fragments that round found; the last part has `hasNext: false`.
136
+
137
+ ```json
138
+ { "data": { "posts": { "data": [{ "title": "Hello" }] } },
139
+ "pending": [{ "id": "0", "path": ["posts", "data", 0], "label": "details" }], "hasNext": true }
140
+ { "incremental": [{ "id": "0", "data": { "author": { "name": "Ana" }, "comments": { "data": [] } } }],
141
+ "completed": [{ "id": "0" }], "hasNext": false }
142
+ ```
143
+
144
+ An entry carries what was not sent yet, and is one grouped field set of the draft: the fields that
145
+ the same fragments of a round select at a path. Of `... @defer(label: "a") { name loud } ...
146
+ @defer(label: "b") { loud id }`, `name` is a's, `id` is b's, and `loud` is sent once, for both,
147
+ under the first one's `id`; below an object field two fragments select differently, the fields are
148
+ grouped the same way, the object field coming first in an entry of its own. What a fragment adds to
149
+ an object field already sent comes in an entry of its own, at the field's `subPath` from the
150
+ fragment's path:
151
+
152
+ ```json
153
+ { "data": { "user": { "parent": { "name": "Ana" } } },
154
+ "pending": [{ "id": "0", "path": ["user"] }], "hasNext": true }
155
+ { "incremental": [{ "id": "0", "data": { "name": "Bo" } },
156
+ { "id": "0", "subPath": ["parent"], "data": { "email": "ana@example.com" } }],
157
+ "completed": [{ "id": "0" }], "hasNext": false }
158
+ ```
159
+
160
+ The errors of a deferred field come with it, on its `incremental` entry, with the path the field
161
+ has in the response. A fragment's delivery is all or nothing: when a non-null field fails beyond
162
+ any part of it (its object, or an object it adds to at a `subPath`), it sends no data at all, and
163
+ its `id` is `completed` with the `errors`; the fragments it holds are not announced. A field it
164
+ shares with another fragment fails that one too, as the draft has it, but a field of its own does
165
+ not: the other fragment sends its fields all the same. A field a fragment that failed had resolved
166
+ resolves again for a later fragment that selects it (its value was never sent). The `extensions` that `BuildExtensionsResponse` and
167
+ `ManipulateResult` listeners add while a fragment runs are on its `incremental` entry too; an entry
168
+ that would carry nothing else (no data, no errors) is not sent, and its extensions go on the
169
+ part's own `extensions`, as those of a fragment that sends no data.
170
+
171
+ ### Apollo's older format
172
+
173
+ A client that names `deferSpec=20220824` gets the payloads in the format graphql-js 17.0.0-alpha.2
174
+ answered, which Apollo Client 3 and Apollo Client 4's `Defer20220824Handler` read. The fragments,
175
+ their rounds and their data are the same; only the payloads are written another way:
176
+
177
+ - The first payload has no `pending`.
178
+ - An `incremental` entry has a `path` instead of an `id`: the path of the fragment's object, and
179
+ the `subPath` after it, with the fragment's `label`. A stream's `items` come at the path of the
180
+ list and the index of the first item (`["users", 1]` after `initialCount: 1`).
181
+ - There is no `completed`. A fragment that failed sends `data: null` with its `errors` (a stream,
182
+ `items: null`); one that completes with nothing of its own to send (the response already holds
183
+ it) sends `data: {}` at its path, so that the client hears of each fragment.
184
+
185
+ ```json
186
+ { "data": { "posts": { "data": [{ "title": "Hello" }] } }, "hasNext": true }
187
+ { "incremental": [{ "data": { "author": { "name": "Ana" }, "comments": { "data": [] } },
188
+ "path": ["posts", "data", 0], "label": "details" }], "hasNext": false }
189
+ ```
190
+
191
+ ## Streaming lists (experimental)
192
+
193
+ `@stream` on a list field answers its first `initialCount` items (default 0) at once, and the
194
+ others in a later part. PHP Lighthouse has no `@stream`.
195
+
196
+ ```graphql
197
+ directive @stream(if: Boolean! = true, label: String, initialCount: Int! = 0) on FIELD
198
+
199
+ query { posts(first: 50) { data @stream(initialCount: 5, label: "rest") { title } } }
200
+ ```
201
+
202
+ ```json
203
+ { "data": { "posts": { "data": [ ... 5 items ... ] } },
204
+ "pending": [{ "id": "0", "path": ["posts", "data"], "label": "rest" }], "hasNext": true }
205
+ { "incremental": [{ "id": "0", "items": [ ... 45 items ... ] }], "completed": [{ "id": "0" }], "hasNext": false }
206
+ ```
207
+
208
+ The field's resolver runs once and returns the whole list; `@stream` cuts it where `initialCount`
209
+ says, and the items that follow run in the next round, all together so the Dataloader batches
210
+ across them: as graphql-ruby completes the list, on the field's object (under a type condition on
211
+ an interface or a union too), the field answered with those items and its resolver not run. A list of scalars streams too, and so does a paginated field's
212
+ `data`. A list that resolves to `null` is `null`, and so is a `null` item where the list's items
213
+ may be; where they may not, a `null` item (or one a non-null field's error nulls) fails the
214
+ stream, which completes with the error, the items already sent staying. An item may carry `@defer`: its fragment is
215
+ announced with the items, at the index the item has in the list, and arrives after them. The rest
216
+ of a list is one batch: the specification allows a server to cut it as it pleases. The later items
217
+ run what every declaration of the field selects (`users @stream { id } ... on Query { users { name }
218
+ }`), and nothing of another field of the same name. Where that depends on more than the field's
219
+ object (a declaration under a type condition above it, or in another deferred fragment, or the
220
+ streamed field itself in a named fragment spread both inside a deferred fragment and outside), the
221
+ list is answered whole.
222
+
223
+ `@stream` needs a list field (a validation error otherwise), follows the rules of `@defer` for
224
+ `label`, mutations ("The @stream directive cannot be used on a root mutation field.") and
225
+ subscriptions, and a negative `initialCount` is a field error: the field is `null`, with the error at
226
+ its path. The plugin adds a graphql-ruby trace module to the schema that uses it (and no other
227
+ schema built on the same types), which cuts the lists of every field of that schema, whenever the
228
+ field was defined, and changes no field; a field that is not streamed costs it a method call and
229
+ two fiber-local reads (the @stream mark, then whether a streamed response runs), and a lazy one a
230
+ fiber-local read more when its value syncs.
231
+
232
+ ## Clients
233
+
234
+ - **GraphiQL** (`GraphiQL.createFetcher`, as the example app's `/graphiql`) reads the draft's
235
+ format: a query with `@defer` shows the deferred fields as they arrive.
236
+ - **Apollo Client 4** reads either, with the handler of its format: `GraphQL17Alpha9Handler` (the
237
+ draft's) or `Defer20220824Handler` (the older one), as its `incrementalHandler`.
238
+ - **Apollo Client 3** sends `multipart/mixed;deferSpec=20220824` and gets the older format.
239
+ - **graphql-js 17** and **Relay** read the draft's format.
240
+
241
+ A client that cannot read `multipart/mixed` should leave it out of its `Accept` header
242
+ (`application/json`), and gets the whole response.
243
+
244
+ ## Transport
245
+
246
+ The response is the body Rails streams from the action, as it streams a template
247
+ (`self.response_body =`, the parts of a `multipart/mixed` body, graphql-over-http's incremental
248
+ delivery): the server writes each part as its round has run, in the request's thread, inside its
249
+ executor (the database connection, `ActiveSupport::CurrentAttributes` and the query cache are the
250
+ request's, as for any action). No thread of its own, as `ActionController::Live` would start. A
251
+ part's JSON is encoded as `render json:` encodes any response.
252
+
253
+ Streaming needs a server that writes the body as it goes (Puma; not a single-threaded buffering
254
+ one), sending it chunked, and proxies that do not buffer: the response sends `X-Accel-Buffering: no`
255
+ for nginx, `Cache-Control: no-store`, so no cache keeps it, and a `Last-Modified` so `Rack::ETag`
256
+ lets it through. Do not put `Rack::Deflater` in front of it. `@cacheControl` does not apply to a
257
+ streamed response.
258
+
259
+ The first part is encoded in the action, so that an error there (a value of the app's that does
260
+ not encode) is answered as on the JSON path, through the controller's `rescue_from`, nothing being
261
+ sent. Once the action returns, the response is on its way and can no longer be refused: a
262
+ `@throttle` past its limit in a later round is the field's error ("Rate limit for Query.x exceeded.
263
+ Try again later."), and its `with:` method is not called. A round that fails, or a part that cannot
264
+ be encoded, ends the stream all the same, with a last part that completes, with an error, every id
265
+ the client was sent and has not seen completed, and the closing boundary. The error goes to
266
+ `Rails.error` (`handled: true`, `severity: :error`) and the log, and not to the controller's
267
+ `rescue_from` handlers, which could not render on a response already on its way. An error
268
+ writing the closing boundary is reported after it. A client that goes away (the server cannot
269
+ write a part) ends the stream quietly: nothing more is written or reported.
270
+
271
+ ## How it runs
272
+
273
+ - **The client's document, as it came.** It is never rewritten: validation, analysis, listeners
274
+ (`StartExecution#query`), `query.query_string`, the operation's fingerprint and tracing see the
275
+ document the client sent, streamed or not. graphql-ruby hands `@defer` its arguments, not its node;
276
+ Lighthouse knows the node by the arguments graphql-ruby caches for it.
277
+ - **Every field resolves once.** The first pass leaves the deferred fragments out; each round
278
+ then runs the pending fragments on the objects the passes before it loaded
279
+ (`GraphQL::Query::Partial`), never by running their parents again, and leaves out what the
280
+ response already holds. `@throttle`, `@guard`, `@cache`, events and the rest of a field's
281
+ directives run in the pass that resolves the field; a mutation does not run twice. To reach an
282
+ object field the response already holds, the plugin's trace module keeps, while a streamed
283
+ response runs, the objects its fragments will need, in whatever trace mode the app picks. An app
284
+ that gives a trace class of its own, leaving out the schema's trace modules, gets every response
285
+ whole.
286
+ - **No N+1.** The fragments of a round run together, in one multiplex, so the Dataloader batches
287
+ across them: a deferred fragment under a list of 50 costs the queries it costs without `@defer`.
288
+ When two fragments select different fields of an object field neither was sent, that field
289
+ resolves first and the fields below it in a second multiplex of the same round (a pass), each
290
+ batched in turn.
291
+ - **The schema's `execute`.** The first pass is the schema's `execute`, as on the JSON path: an
292
+ app's own `AppSchema.execute` (instrumentation, a tenant in the context, a default context) runs
293
+ for a streamed request too, and the query is the schema's `query_class`. An `execute` that runs
294
+ the query without the context it was given, or answers no `GraphQL::Query::Result`, gets the
295
+ response whole. The rounds are not operations, and do not go through `execute`: they run their
296
+ `GraphQL::Query::Partial`s through `schema.multiplex` (which an override of `multiplex` sees),
297
+ with the first pass's context. To act on every part of a streamed response, use a graphql-ruby
298
+ trace module (`trace_with`) or Lighthouse's execution events, which see the rounds too.
299
+ Partials run on graphql-ruby's standard execution engine; its new one (2.6's
300
+ `GraphQL::Execution::Next`) is not supported.
301
+ - **Validation and complexity cover the whole document**, before the first pass: the deferred
302
+ fragments count for `max_complexity` and `max_depth`, as they would without `@defer`.
303
+ - **Events.** `StartExecution` and `EndExecution` fire for the first pass, and again for each unit a
304
+ round runs (the fragments of one path on its object, or a stream's items), with the client's
305
+ document; `EndOperationOrOperations` after the closing boundary, and `EndRequest` last, once the
306
+ response is out ([events.md](events.md)).
307
+
308
+ ## Testing
309
+
310
+ `Lighthouse::GraphQL::Testing#stream_graphql`, PHP Lighthouse's `streamGraphQL`, posts a query
311
+ that defers and answers its payloads, in order ([testing.md](testing.md)):
312
+
313
+ ```ruby
314
+ it 'defers the details' do
315
+ initial, later = stream_graphql('{ posts(first: 1) { data { title ... @defer { author { name } } } } }')
316
+
317
+ expect(initial['pending'].size).to eq(1)
318
+ expect(later['completed']).to eq([{ 'id' => '0' }])
319
+ end
320
+ ```
321
+
322
+ ## Differences from PHP Lighthouse
323
+
324
+ - **Fragments, not fields.** PHP Lighthouse's `@defer` goes on a field (`directive @defer(if:
325
+ Boolean = true) on FIELD`); the draft's, and this one, on a fragment, with a `label`. A query
326
+ written for PHP Lighthouse puts each deferred field in a fragment: `parent @defer { name }`
327
+ becomes `... @defer { parent { name } }`.
328
+ - **The draft's format, or Apollo's, not the 2018 one.** PHP Lighthouse answers `null` for a
329
+ deferred field first, then chunks keyed by path (`{ "user.parent": { "data": ... } }`) and no
330
+ `hasNext`. This leaves the field out of the first payload, and answers `pending`, `incremental`,
331
+ `completed` and `hasNext`, or Apollo's `deferSpec=20220824` format to a client that names it,
332
+ which today's clients read.
333
+ - **A client can say it does not stream.** PHP Lighthouse streams whatever the client accepts; this
334
+ answers the whole response to a client whose `Accept` header leaves `multipart/mixed` out.
335
+ - **One pass per round, not the query again.** PHP Lighthouse runs the whole operation again for
336
+ each round, and answers what it already has from the previous result; this runs only the deferred
337
+ fragments, on the objects already loaded. A field resolves once, and a mutation runs once.
338
+ - **`@stream` is added.** PHP Lighthouse has none.
339
+ - **A field asked for outside the fragment too is sent once, and the fragment still completes.**
340
+ PHP Lighthouse (as Apollo) does not defer a field one of whose declarations is not deferred: the
341
+ field, with everything any declaration selects of it, comes in the first payload. As the draft
342
+ has it, the fragment here is deferred all the same: the field comes in the first payload with
343
+ what the rest of the query selects of it, the fragment sends what it adds, and completes.
344
+ - **Non-null fields can be deferred.** PHP Lighthouse refuses `@defer` on a Non-Null field ("The
345
+ @defer directive cannot be used on a Non-Nullable field.") because it answers `null` for it first;
346
+ the draft's format leaves the field out instead, so nothing needs refusing.
347
+ - **The rules hold for every query.** PHP Lighthouse checks them as a deferred field resolves; here
348
+ they are checked before anything runs, for every request, streamed or not.
349
+ - **The time limit counts milliseconds from the first pass.** `defer_max_execution_ms` starts when
350
+ the first pass does; PHP Lighthouse's deadline is set when its `Defer` is built, as
351
+ `microtime(true) + max_execution_ms * 1000`, a time in seconds plus the setting times a thousand
352
+ (2000 reads as two million seconds).
data/docs/directives.md CHANGED
@@ -286,7 +286,10 @@ type User {
286
286
  ### `@globalId` and `@node`
287
287
 
288
288
  `@globalId` encodes a field's value as a Relay global id (base64 of `Type:id`), and
289
- decodes an argument or input field (`decode: ARRAY | TYPE | ID`). `@node` on a type
289
+ decodes an argument or input field (`decode: ARRAY | TYPE | ID`). A decoded id must be
290
+ of the type it is for: `type:` names it, and with `decode: ID` an argument filtering
291
+ the field's model by its key is checked against that model, so another type's id
292
+ fails the field ([relay.md](relay.md#the-type-of-a-decoded-id)). `@node` on a type
290
293
  makes it implement `Node` and adds `Query.node(id:)`, which finds the type's model
291
294
  record, or calls `@node(resolver:)`. See [relay.md](relay.md).
292
295
 
@@ -352,6 +355,30 @@ type Mutation {
352
355
  }
353
356
  ```
354
357
 
358
+ ### `@defer`
359
+
360
+ Experimental. On a fragment: its fields arrive in a later part of the response, which
361
+ `Lighthouse::GraphQL::Controller` streams as `multipart/mixed`, as PHP Lighthouse does, to any
362
+ client but one whose `Accept` header leaves it out (in the specification draft's format, or
363
+ Apollo's older `deferSpec=20220824` one when the client names it). Otherwise they come with the
364
+ rest of the response. Not in the SDL: the schema's `use
365
+ Lighthouse::GraphQL::Defer` adds it, and clients write it in their queries, as the
366
+ [specification draft](https://github.com/graphql/graphql-spec/pull/1110) has it
367
+ (`directive @defer(if: Boolean! = true, label: String) on FRAGMENT_SPREAD | INLINE_FRAGMENT`).
368
+ PHP Lighthouse's `@defer` goes on a field instead: `parent @defer { name }` is written
369
+ `... @defer { parent { name } }` here. Not on a root mutation field; limits:
370
+ [`defer_max_nested_fields` and `defer_max_execution_ms`](configuration.md#defer_max_nested_fields-and-defer_max_execution_ms).
371
+ Guide: [defer.md](defer.md).
372
+
373
+ ### `@stream`
374
+
375
+ Experimental. On a list field: its first `initialCount` items (default 0) come with the response,
376
+ the others in a later part, when the response is streamed as for `@defer`; otherwise the list
377
+ comes whole. Also added by `use
378
+ Lighthouse::GraphQL::Defer`, and written by clients as the specification draft has it
379
+ (`directive @stream(if: Boolean! = true, label: String, initialCount: Int! = 0) on FIELD`).
380
+ Guide: [defer.md](defer.md#streaming-lists-experimental).
381
+
355
382
  ### `@hide` and `@show`
356
383
 
357
384
  Leave a field out of the schema by environment (`Rails.env`): `@hide(env:)` removes
@@ -557,6 +584,7 @@ Full guide: [filtering-and-ordering.md](filtering-and-ordering.md).
557
584
  | `@whereBetween` / `@whereNotBetween` | `column BETWEEN` / `NOT BETWEEN` the input's two fields, in order |
558
585
  | `@whereJsonContains` | a JSON column contains the value (every value of a list); `key: "meta->tags"` points into it |
559
586
  | `@scope(name:)` | calls the model scope with the value (`name:` defaults to the argument's) |
587
+ | [`@search(within:)`](#search) | runs the field's query through a full-text engine (Searchkick, pg_search) |
560
588
  | `@orderBy` | sort by the client's clauses (columns, relations' aggregates); on a field, a fixed order |
561
589
 
562
590
  ```graphql
@@ -610,6 +638,83 @@ parents it would cut them all together, as PHP Lighthouse warns. PHP Lighthouse
610
638
  also allows `@limit` on the field itself, where it only marks the field the argument
611
639
  limits; it is accepted there and changes nothing.
612
640
 
641
+ ### `@search`
642
+
643
+ Perform a full-text search by the given input value, as PHP Lighthouse's `@search`
644
+ does through Laravel Scout. On a `String` argument or input field:
645
+
646
+ ```graphql
647
+ type Query {
648
+ posts(search: String @search, authorId: ID @eq(key: "author_id")): [Post!]! @paginate
649
+ }
650
+ ```
651
+
652
+ When the client sends a string (`""` too), the field's query runs through the engine
653
+ instead of the database. `null` or an omitted argument falls back to the database
654
+ query, so `posts(first: 10)` still lists. (`@convertEmptyStringsToNull` turns `""` into
655
+ `null`, so it does not search.)
656
+
657
+ ```graphql
658
+ directive @search(
659
+ "Specify a custom index to use for search."
660
+ within: String
661
+ ) on ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION
662
+ ```
663
+
664
+ `within:` names the Searchkick index (`index_name:`), or the `pg_search_scope` to
665
+ search with (`search` by default); on a model that uses both gems, naming one of its
666
+ pg_search scopes searches with pg_search. It must be a string, or the schema fails to build.
667
+
668
+ Ruby has no Laravel Scout, so two gems back it, **neither a dependency of Lighthouse**: add
669
+ the one your models use to your Gemfile. The engine is detected per model
670
+ ([`Config.search`](configuration.md#search) replaces the detection):
671
+
672
+ | Model | Engine | Runs |
673
+ | --- | --- | --- |
674
+ | calls `searchkick` | [Searchkick](https://github.com/ankane/searchkick) | in Elasticsearch / OpenSearch, outside the database |
675
+ | includes `PgSearch::Model` | [pg_search](https://github.com/Casecommons/pg_search) | in PostgreSQL, as a scope on the relation |
676
+
677
+ The two behave differently, and so do the directives next to `@search`; the
678
+ [full guide](filtering-and-ordering.md#full-text-search) has the details, and how to set
679
+ each engine up.
680
+
681
+ - **pg_search** narrows the relation, ranked first, and **everything else applies on
682
+ top of it**: `scopes:`, `@builder`, `@whereAuth`, every argument filter, `@orderBy`,
683
+ pagination, nested fields, batched as usual, and mass mutations (`@delete`, ...), where a
684
+ `@search` argument counts as a filter only when the search runs. The primary key ends the
685
+ order, after the orders that break the rank's ties.
686
+ - **Searchkick** answers with the records the engine found, in relevance order. Only `@eq`,
687
+ `@trashed` and `@builder` on an argument narrow it (as Scout's `@eq` / `@trashed` /
688
+ `@builder`); they work at any depth of input objects. It serves `@all`, `@paginate` of the
689
+ model's whole table, `@first` (the best match), `@find` (the one match; more is an error), and a resolver of your own (`resolve_info.enhance_builder` answers a
690
+ `Lighthouse::Search::Result`, for the model's own relation only), with an exact total, within the index's result window (read
691
+ from the engine, 10,000 matches by default; a page past it is an error the client reads). `@all` reads what
692
+ the client asks for (`first`, an argument's `@limit`, else every match), 10,000 records at most at once,
693
+ with an error next to them when that answers fewer than asked. The records load through the
694
+ filters the database can apply too (`@trashed`'s, `@eq` on a column), so a stale index never
695
+ answers one that no longer matches.
696
+
697
+ A model's `search_results` scope, when it has one, is what a search of it may return:
698
+ Searchkick loads the records it finds through it, so a record the index still holds after it
699
+ should have left is not returned. A search counts only what it can load: a Searchkick model
700
+ with a default scope (any, as declared) or `search_results` defines `search_where`, the
701
+ engine's `where:` for the same records, leaving out the soft-delete column Lighthouse filters on
702
+ itself, or the schema does not build; pages follow the
703
+ engine's positions, so a hit that does not load is never shown twice nor skips another. `@canQuery` on the field checks every record the search
704
+ finds, as PHP Lighthouse does (with Searchkick, 10,000 at most: more is an error), and the hits it
705
+ checked serve the field's page, in that resolution only.
706
+
707
+ Two `@search` arguments sent together, and (Searchkick) an argument whose directive an
708
+ engine cannot apply (`@neq`, `@orderBy`, `@whereConditions`, ...), are errors.
709
+ Schema errors, at build, where PHP Lighthouse fails when a query runs: a `within:` that is
710
+ not a string, a model that is not searchable, a `@search` nothing applies (graphql-ruby's
711
+ default reader, `@create`, ...), which PHP Lighthouse ignores, and, with Searchkick, a field with `scopes:`,
712
+ `@builder`, `@whereAuth` or `@orderBy(column:)`, or an `@canQuery` with `scopes:`, which PHP
713
+ Lighthouse **drops silently** when it searches (a search that skipped `@whereAuth` would
714
+ return records the user must not see), and a value graphql-ruby fills in without the client
715
+ (an argument's default, the fields of a default object) whose directive the engine cannot
716
+ apply, which would fail every search.
717
+
613
718
  ### `@orderBy`
614
719
 
615
720
  ```graphql
data/docs/events.md CHANGED
@@ -73,6 +73,15 @@ def search
73
73
  end
74
74
  ```
75
75
 
76
+ For a response streamed with [`@defer`](defer.md),
77
+ the events end in this order: the last part and the closing boundary are written,
78
+ `EndOperationOrOperations` fires, then `EndRequest`, once the response is out (after the action
79
+ returned: the server writes the response's body as it goes), however the stream ended (an error,
80
+ or a client that left, even at the first part). `EndRequest`'s `response` is the response, but for
81
+ its `body`: the parts written, as the client was sent them (the response's own body is the
82
+ client's, which the server reads as it goes, and reading it would take parts from the client). The
83
+ parts are kept for it only while something listens to `EndRequest`.
84
+
76
85
  Without the concern, dispatch them yourself:
77
86
  `Lighthouse::Events.dispatch(Lighthouse::Events::StartRequest.new(request))`, and
78
87
  `EndRequest.new(response)` after rendering.
@@ -95,6 +104,25 @@ it builds, so they fire however the query was started: the controller,
95
104
  With no listener, and no `ActiveSupport::Notifications` subscriber, they cost
96
105
  one lookup per request.
97
106
 
107
+ For a response streamed with [`@defer`](defer.md),
108
+ `EndOperationOrOperations` comes after the closing boundary, and `result_or_results` is the whole
109
+ response as the client puts it together: a Hash of the data of every part, and the errors of every
110
+ part (the first one's first). When the client goes away before the last part, it comes then, with
111
+ what the client was sent (no error says so: the client left, the server did not fail): an empty
112
+ Hash, `{}`, when it left before the first part. When the first part fails (a value of the app's
113
+ that does not encode), nothing was sent and the error is the server's: `{ "errors" => [{
114
+ "message" => "Internal server error" }] }`. A query that
115
+ defers nothing gets its result at once, as without `@defer`.
116
+
117
+ The fragments deferred with [`@defer`](defer.md) run after the
118
+ first response, in rounds, a payload each. A round runs its units (the fields the same fragments
119
+ select at one path, on its object, or a stream's items) in one multiplex, and, when two fragments
120
+ select different fields of an object field that resolves in it, the fields below that field in
121
+ another multiplex after it (a pass), so a round is one multiplex or more. The execution events fire
122
+ again for each unit of each pass, as a multiplex fires them for each of its queries, with the
123
+ operation's `query` (the client's document, never rewritten), `variables` and `operation_name`, and
124
+ the result of that unit.
125
+
98
126
  `StartExecution#query` is the parsed `GraphQL::Language::Nodes::Document`, and
99
127
  `operation_name` the one the client gave. Both events carry the `GraphQL::Query` as
100
128
  `graphql_query`, and `EndExecution` its `operation_name` (the operation that ran,
@@ -123,7 +151,8 @@ end
123
151
 
124
152
  `query_complexity` is the query's complexity score, the number graphql-ruby
125
153
  checks against `max_complexity` (see [security.md](security.md#reading-the-score)).
126
- It is `nil` for a query that failed validation.
154
+ It is `nil` for a query that failed validation, and for the later parts of a response streamed
155
+ with `@defer`: the operation's score comes once, with the first part.
127
156
 
128
157
  **`ManipulateResult`**: change `event.result` (the Hash with `data`, `errors` and
129
158
  `extensions`) in place, or assign a new Hash to `event.result=`: