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
@@ -243,6 +243,494 @@ type Query {
243
243
  An argument written with a type of its own, such as `orderBy: [MyClause!] @orderBy`,
244
244
  keeps that type. Its input needs a `column` and an `order`.
245
245
 
246
+ ## Full-text search
247
+
248
+ `@search` runs a field's query through a full-text engine when the client sends a
249
+ search term, as PHP Lighthouse's does through Laravel Scout (the directive is in
250
+ [directives.md](directives.md#search)). Ruby has no Scout: Lighthouse supports the two gems
251
+ Rails apps use, behind one adapter seam. Neither is a dependency of Lighthouse, so add the
252
+ one you use to your Gemfile.
253
+
254
+ ```graphql
255
+ type Query {
256
+ posts(
257
+ search: String @search
258
+ authorId: ID @eq(key: "author_id")
259
+ orderBy: _ @orderBy(columns: ["created_at"])
260
+ ): [Post!]! @paginate
261
+ }
262
+ ```
263
+
264
+ The search runs when the client sends a string for the argument (`""` too). `null` or
265
+ nothing leaves the query to the database.
266
+
267
+ | | [pg_search](https://github.com/Casecommons/pg_search) | [Searchkick](https://github.com/ankane/searchkick) |
268
+ | --- | --- | --- |
269
+ | Searches | PostgreSQL's full-text search, in the table | an Elasticsearch or OpenSearch index, a copy of the table |
270
+ | The search is | a scope on the field's relation | an engine request that answers records |
271
+ | Everything else Lighthouse applies | composes on it | `@eq`, `@trashed`, `@builder` on an argument, and the model's `search_where` |
272
+ | Fields | any that applies a search | `@all`, `@paginate` of the model's whole table, `@find`, `@first`, a resolver of your own |
273
+ | Up to date | always | once the index is (callbacks, jobs) |
274
+
275
+ Lighthouse is tested with Searchkick 6.2 on Elasticsearch 9.5 and on OpenSearch 2.19 and 3.9,
276
+ and with pg_search 2.3 and 2.4 on PostgreSQL 16 (the [example app](https://github.com/Vaz-Innovation/lighthouse-graphql/tree/main/example)'s suite).
277
+
278
+ ### Setting up pg_search
279
+
280
+ ```ruby
281
+ # Gemfile
282
+ gem 'pg_search'
283
+ ```
284
+
285
+ ```ruby
286
+ class Post < ApplicationRecord
287
+ include PgSearch::Model
288
+
289
+ pg_search_scope :search, against: { title: 'A', body: 'B' }, using: { tsearch: { prefix: true } }
290
+ pg_search_scope :search_title, against: :title
291
+ end
292
+ ```
293
+
294
+ `@search` calls the scope `search`, or the one `within:` names: `@search(within: "search_title")`.
295
+ There is nothing to index: the scope searches the table, so a search sees every change at once.
296
+ On a model that uses both gems, a `within:` that names one of its pg_search scopes searches with
297
+ pg_search; no `within:`, or any other, searches with Searchkick (where it names an index).
298
+
299
+ ### Setting up Searchkick
300
+
301
+ ```ruby
302
+ # Gemfile
303
+ gem 'searchkick'
304
+ gem 'elasticsearch' # Elasticsearch: the client's major version is the server's (9 for Elasticsearch 9, 8 for 8)
305
+ # or
306
+ gem 'opensearch-ruby' # OpenSearch 2 or 3
307
+ ```
308
+
309
+ Searchkick talks to `ELASTICSEARCH_URL` or `OPENSEARCH_URL` (`http://localhost:9200` by default).
310
+ With both clients loaded (say, Elasticsearch in production and OpenSearch elsewhere), Searchkick
311
+ refuses to guess: name the one in use in an initializer, and require only it:
312
+
313
+ ```ruby
314
+ # config/initializers/searchkick.rb, with both gems `require: false` in the Gemfile
315
+ if ENV['OPENSEARCH_URL']
316
+ require 'opensearch'
317
+ Searchkick.client_type = :opensearch
318
+ else
319
+ require 'elasticsearch'
320
+ Searchkick.client_type = :elasticsearch
321
+ end
322
+ ```
323
+
324
+ Then the model. The index is a copy of what `search_data` says, so it must hold the text to search
325
+ **and every column a filter of the field reads**: the `key:` of each `@eq`, the soft-delete
326
+ column for `@trashed`, and those `search_where` filters on. An `@eq` on a column the index does not
327
+ hold matches nothing.
328
+
329
+ ```ruby
330
+ class Comment < ApplicationRecord
331
+ belongs_to :post
332
+
333
+ searchkick callbacks: :async
334
+
335
+ # What the index holds: `body` to search, `post_id` for an `@eq(key: "post_id")` argument,
336
+ # and whether the post is published, for search_where.
337
+ def search_data = { body: body, post_id: post_id, published: post.published? }
338
+
339
+ # Which records are indexed at all: what must not be found must not be indexed.
340
+ def should_index? = post.published?
341
+
342
+ # What a reindex loads with each batch, for search_data and should_index?.
343
+ scope :search_import, -> { includes(:post) }
344
+
345
+ # What a search may return, checked in the database as the records it finds load.
346
+ scope :search_results, -> { where(post: Post.published) }
347
+
348
+ # The same, in the engine, so that totals and pages count only those.
349
+ def self.search_where = { published: true }
350
+ end
351
+ ```
352
+
353
+ ```graphql
354
+ type Query {
355
+ searchComments(search: String! @search, postId: ID @eq(key: "post_id")): [Comment!]! @paginate
356
+ }
357
+ ```
358
+
359
+ Run `Comment.reindex` once, to create the index and fill it, and again after you change
360
+ `search_data` or the index's settings. Searchkick's callbacks keep it up to date as records change:
361
+ in the same request by default, or in an Active Job with `callbacks: :async` (start a worker, such
362
+ as `bin/jobs` for Solid Queue). `should_index?` only decides on the record that changed: when another
363
+ record decides it (unpublishing a post hides its comments), reindex those too: the example app's
364
+ Post calls `comments.reindex(mode: :async)` in an `after_commit` when `published` changes.
365
+ `search_import` is Searchkick's: without it, a `should_index?` or `search_data` that reads an
366
+ association loads it once per record.
367
+
368
+ ### What Lighthouse does with pg_search
369
+
370
+ `@search` calls the scope on the field's relation. Because a pg_search scope is a relation,
371
+ **everything else Lighthouse does composes on it**: the field's `scopes:`, `@builder`, `@whereAuth`,
372
+ every argument filter, `@whereConditions`, `@orderBy`, nested fields and nested `@paginate`
373
+ (batched through one window query), `@count`, `@first`, `@find` and `@canQuery`.
374
+
375
+ A mass mutation (`@delete`, `@forceDelete`, `@restore`) can take a `@search` argument too: it acts on
376
+ the records the search finds. It still refuses to run without a filter (`Would modify all models, use
377
+ an argument to filter.`), and a `@search` argument counts as one only when the search runs, for a
378
+ string: `deletePosts(search: null)` deletes nothing, as in PHP Lighthouse. With Searchkick a mass
379
+ mutation is a schema error.
380
+
381
+ **Order.** A search is in order of relevance: pg_search's rank always sorts first. The orders the
382
+ relation already had break its ties, in the order they apply, as on a field without a search: the
383
+ model's default scope, the field's `scopes:`, the model's `search_results` scope; then the client's
384
+ `orderBy`, the field's `@orderBy(column:)`, and the primary key ends the order, once, unless an order
385
+ before already names it. A client that sorts by date gets the best matches first and, among equally
386
+ ranked ones, the newest; matches that rank and sort alike come back in the same order every time, on
387
+ every field. pg_search's own tie-break, the primary key, is dropped so that these orders decide (a node
388
+ of its own in pg_search 2.4, the end of the rank's SQL in 2.3); an `order_within_rank:` the scope names
389
+ is kept, right after the rank.
390
+
391
+ ### What Lighthouse does with Searchkick
392
+
393
+ Searchkick queries Elasticsearch or OpenSearch, which knows nothing of your database, so what narrows a
394
+ search is translated into the engine's filters. Lighthouse does it for the directives of PHP
395
+ Lighthouse's `ScoutBuilderDirective`:
396
+
397
+ | Directive | In the search |
398
+ | --- | --- |
399
+ | `@eq` | `where: { column => value }`, a filter on the indexed column |
400
+ | `@trashed` | a filter on the indexed soft-delete column: [below](#soft-deletes-in-a-search) |
401
+ | `@builder` on an argument | gets the `Lighthouse::Search::Query` instead of the relation (below) |
402
+
403
+ They work at any depth of input objects (`filter: CommentFilter` with `@eq` fields). The engine
404
+ answers with Active Record records, in relevance order, loaded in one query through the model (and
405
+ its default scope), so nested fields and the Dataloader work on them as usual.
406
+
407
+ ```ruby
408
+ # app/graphql/builders/title_fields.rb: `titleOnly: Boolean @builder(class: "TitleFields")`
409
+ class Builders::TitleFields
410
+ def self.call(target, value, _context)
411
+ return target unless value
412
+ return target.where(body: nil) unless target.is_a?(Lighthouse::Search::Query) # a relation
413
+
414
+ target.options[:fields] = ['title^10'] # passed to Searchkick's search
415
+ target
416
+ end
417
+ end
418
+ ```
419
+
420
+ A query holds `model`, `term`, `index`, `wheres` (the `[column, value]` pairs of `@eq`, in order),
421
+ `trashed` and `options`: the options of Searchkick's `search` that rank, highlight or aggregate the
422
+ hits, `Lighthouse::Search::Searchkick::Options::BUILDER_OPTIONS`: `fields:`, `match:`, `operator:`, `where:`,
423
+ `order:`, `boost_by:`, `boost_where:`, `boost_by_distance:`, `boost_by_recency:`, `indices_boost:`,
424
+ `misspellings:`, `highlight:`, `aggs:`, `smart_aggs:`, `emoji:`, `exclude:`, `conversions:`,
425
+ `conversions_term:`, `explain:`, `debug:`, `includes:`, `model_includes:`, `scope_results:`,
426
+ `body_options:` (`min_score`, `explain`, `profile`, `timeout`) and `timeout:`. Any other, one that
427
+ decides what loads, how it pages or what it counts (`load:`, `index_name:`, `models:`, `unscope:`,
428
+ `select:`, `page:`, `body:`, `body_options: { query: ... }`, `track_total_hits`, ...), is an error the
429
+ client reads, reported to `Config.on_error`: Lighthouse sets those. Lighthouse adds `where:`, with
430
+ yours, the model's `search_where`, every `@eq` and `@trashed` all holding: keys are read alike, symbols
431
+ or strings, and conditions on one column (yours and an `@eq`'s, or two `@eq` of a list of inputs) are
432
+ ANDed (`_and`), never overwritten. It adds `index_name:` (from `within:`), `load: true`, `track_total_hits:
433
+ true` to your `body_options:` and its own `scope_results:`, which runs after yours, so yours cannot widen
434
+ what loads.
435
+
436
+ **Which fields.** Whatever the engine, something must apply the search: a directive that runs the
437
+ field's argument filters (`@all`, `@paginate`, `@find`, `@first`, `@count`, `@aggregate`, a
438
+ relationship, a mass mutation), or your own code, which reads it through
439
+ [`resolve_info.enhance_builder`](#in-a-resolver-of-your-own): `@field`, the conventional class of a root
440
+ field, or a method of the type's class. A field nothing resolves but graphql-ruby's default reader,
441
+ which reads it off the parent (`type User { comments(search: String @search): [Comment!]! }`), or one
442
+ whose directive runs no filters (`@create`, `@method`, ...), would ignore the search: it is a schema
443
+ error, `nothing applies the search`. Each resolver class says what it does, through
444
+ `Contracts::FieldResolver`, which by default says it applies no search: a directive of your own opts in
445
+ with `def self.applies_search? = true` (it runs the field's filters, `apply_where_filters` or
446
+ `resolve_info.enhance_builder`), and `def self.takes_search_results?(type, field_def, directive,
447
+ root_kind) = true` when it also takes a Searchkick `Lighthouse::Search::Result`.
448
+
449
+ The engine answers with records, not a relation, so `@search` with Searchkick is for `@all`, `@paginate`
450
+ of the model's whole table (on a root field, with its own `model:`, or where the parent type's model has
451
+ no association of the field's name; a parent type that is no model is refused, as only a query's records
452
+ would tell what it pages, and a record that turns out to page an association answers a client error),
453
+ `@first`, `@find` and your own code. `@first` answers the best match that loads; `@find` the one match,
454
+ or null, and an error when the engine counts more than one, as PHP Lighthouse's `@find` on Scout's
455
+ `get()`. An `id` argument of `@find` without a filter directive selects by primary key in the
456
+ database, which the engine cannot: give it `@eq`, which the engine applies, or the field is a schema
457
+ error. Any other field (`@count`, `@aggregate`, a mass mutation, a nested relationship) is a schema
458
+ error at build, when Lighthouse can tell the field's model: PHP Lighthouse ignores the search on
459
+ `@count` and `@aggregate` (they drop the Scout builder `enhanceBuilder` returns, and count every
460
+ record) and fails on a mass mutation, which takes only a query builder. For the same
461
+ reason a field with `scopes:`, `@builder`, `@whereAuth` or `@orderBy(column:)`, or an `@canQuery` with
462
+ `scopes:`, is a schema error: **PHP Lighthouse drops those silently when it searches**, and a search that skipped `@whereAuth` would return
463
+ records the user must not see. Lighthouse fails when the schema is built instead. Put the constraint in
464
+ the index (`search_data` and an `@eq` argument), in the model's [`search_results`
465
+ scope](#keeping-private-records-out-of-a-search), or search with pg_search.
466
+
467
+ At run time, a client that sends an argument whose directive the engine cannot apply (`@neq`, `@in`,
468
+ `@like`, `@orderBy`, `@whereConditions`, ...) with a search, or two `@search` arguments, gets an error,
469
+ as in PHP Lighthouse. Such an argument with a **default value** would be sent on every search, as
470
+ graphql-ruby fills the default in (and PHP Lighthouse fails every search of the field): it is a schema
471
+ error. So is an input field that holds a value the client did not send, as graphql-ruby fills it in:
472
+ the value an argument's default object gives it, else its own default, inside a default object or an
473
+ input object the client must send (`filter: PostFilter!`). An input field's default under a parent the
474
+ client may leave out (`filter: PostFilter`) applies only when it sends the parent, and is not refused:
475
+ a search with that parent is then the run-time error above. A default for `@eq`, `@trashed` or
476
+ `@builder` is fine.
477
+
478
+ A directive that does not change the query is taken with a search: `@limit` cuts what the field
479
+ resolved (not `@limit(builder: true)`, a LIMIT on the query, which is refused); an argument directive
480
+ of your own says so with `def self.changes_query?(directive_node) = false`. (`@in`, `@notIn` and
481
+ `@whereKey` are refused with a search, as in PHP Lighthouse, where only `@eq`, `@trashed` and
482
+ `@builder` write to Scout's builder.)
483
+
484
+ **Order.** The engine's relevance; ties as the engine breaks them. `@orderBy` is refused with a search;
485
+ an `@builder` on an argument can set Searchkick's `order:`.
486
+
487
+ ### Pagination and totals
488
+
489
+ `@paginate` pages a search with all three types: `PAGINATOR`, `SIMPLE` and `CONNECTION`, whose cursors
490
+ are positions. With pg_search it pages the relation, as any other. With Searchkick each page is one
491
+ engine request (`offset:` and `limit:`), whose response holds the total too, so a page and
492
+ `paginatorInfo { total }` cost **one request**. Unlike Scout, `first: 0` can still count.
493
+
494
+ **Pages follow the engine's positions.** A hit may not load (the model's default scope or
495
+ `search_results` scope drops it, or its row is gone from the database): the page then holds fewer
496
+ records than `first`, but its positions are still the engine's. `firstItem` and `lastItem` are the
497
+ positions of its first and last record; `SIMPLE`'s `hasMorePages` says whether the engine has hits past
498
+ the page; and a `CONNECTION`'s cursors are the records' engine positions, its `startCursor` and
499
+ `endCursor` its first and last edge's, as Relay's (a page whose hits all failed to load has no edge, and
500
+ its `endCursor` is past them, so the client walks on). No record shows twice, and none is skipped.
501
+
502
+ **The total is exact.** Elasticsearch and OpenSearch stop counting matches at 10,000 unless asked
503
+ (`track_total_hits`), which made `total`, `lastPage` and `hasMorePages` wrong past it. Lighthouse asks
504
+ on every search, and nothing turns it off: totals, the pages within the result window and `@canQuery`'s
505
+ check of every hit (below) rely on every match being counted, and an estimate (`track_total_hits: false`,
506
+ or a number, which stops at it) would let a page serve a record no check saw. An `@builder` whose
507
+ `body_options` set `track_total_hits` is an error the client reads, reported to
508
+ [`Config.on_error`](configuration.md#on_error), as is a response whose total is not exact.
509
+
510
+ **Reads by `@all`.** `@all` reads what the client asks for: `first` records, as many as an argument's
511
+ `@limit` (without `builder: true`) lets the field answer, or every match. One request reads 10,000
512
+ records at most, and no further than the result window. When that answers fewer than asked while more
513
+ match, the field answers those records with an error next to them: `@all answered 10000 of the 12345
514
+ matches the search finds from offset 0: a search reads 10000 at most at once, and no further than its
515
+ first 10000 matches (the index.max_result_window). Use @paginate, or first and offset, to read the others.`
516
+
517
+ **The result window.** The engines page through the first 10,000 matches only (the index's
518
+ `index.max_result_window`). Lighthouse reads no further: a page that runs past it is cut at its end, and
519
+ a page that starts past it is an error the client reads:
520
+
521
+ > The search reads no further than its first 10000 matches (the index.max_result_window of Comment), so
522
+ > offset 10000 is past them. Narrow the search instead.
523
+
524
+ `total` stays the true number of matches; `lastPage`, `hasMorePages` and `hasNextPage` count only the
525
+ pages within the window, so no page is announced that would then be refused.
526
+
527
+ Lighthouse reads the window from the engine: the `index.max_result_window` of the index the search reads
528
+ (the model's, or the one `within:` names; the smallest of an alias's indices), 10,000 when it sets none.
529
+ It is read once a minute per index at most, as the mapping is (below). When the settings cannot be read,
530
+ it takes the window the model sets for its own index, `searchkick max_result_window: 50_000` (or `settings:
531
+ { index: { max_result_window: 50_000 } }`, with symbol or string keys, nested or as
532
+ `'index.max_result_window'`), a billion with `searchkick deep_paging: true`, else 10,000, for any index.
533
+ No request asks past it. If the engine still refuses a page as past its window (it changed within the
534
+ minute), the refusal becomes the same error, without the number: `The search reads no further than the
535
+ index.max_result_window of Comment. Narrow the search instead.` Raising the window lets clients page
536
+ deeper at the engine's expense; Searchkick [advises against it](https://github.com/ankane/searchkick#deep-paging).
537
+
538
+ ### Soft deletes in a search
539
+
540
+ With pg_search, `@trashed` and `@softDeletes` filter the relation, as without a search.
541
+
542
+ With Searchkick, `@trashed` filters on the soft-delete column the index holds, so `search_data` must hold
543
+ it (`deleted_at: deleted_at`), or `ONLY` and `WITHOUT` are an error (`WITH` filters nothing): `Comment's
544
+ index does not hold deleted_at, which @trashed filters the search on: add it to search_data.` Lighthouse
545
+ reads the columns from `search_data` on a blank record, for the model's own index; for another index
546
+ `within:` names, or when `search_data` raises (it reads an association), from that index's mapping on
547
+ the engine. Reading the mapping needs the `view_index_metadata` privilege on the index (the settings,
548
+ for the result window, too). It is read at most once a minute per model and index, by one thread while
549
+ the others wait for it (a reindex may add or remove a column); a read that fails is reported to
550
+ [`Config.on_error`](configuration.md#on_error) and tried again after five seconds, however many requests
551
+ ask. When neither can be read, `ONLY` and `WITHOUT` are refused, rather than filter on a column the index
552
+ may not hold, with the engine's reason: `@trashed cannot tell whether Comment's index holds deleted_at
553
+ ... (Elastic::Transport::Transport::Errors::Forbidden: ...; reading it needs the view_index_metadata
554
+ privilege on the index).` The filter Lighthouse adds on its own (below) goes on: it holds either way. (A column every document leaves null has no
555
+ mapping yet: let `search_data` run on a blank record.) The column is the one the database path filters on
556
+ ([`Config.soft_deletes`](configuration.md#soft-deletes)): paranoia's (`paranoia_column`, and its
557
+ `sentinel_value` in place of null for the records that are not trashed), discard's (`discard_column`),
558
+ a `Column.new(:archived_at)`'s, else `deleted_at`. An adapter of your own tells it with `column(model)`
559
+ and `kept_value(model)`. `Config.soft_deletes` is the one place to name it: the support check, the
560
+ engine's filter and the records' load all read it, as the database filters do.
561
+
562
+ | `trashed:` | In the engine | Loads the records |
563
+ | --- | --- | --- |
564
+ | `ONLY` | a value in the column, other than paranoia's sentinel | the trashed ones, past the default scope that hides them |
565
+ | `WITH` | no filter | past that default scope |
566
+ | `WITHOUT` | no value in the column, or the sentinel | the ones not trashed |
567
+ | omitted | as `WITHOUT` when the model's default scope hides trashed records, else no filter | through the model |
568
+
569
+ The soft-delete column is Lighthouse's to filter on: a model whose default scope hides trashed records
570
+ (paranoia's, discard's `kept` when the model adds it, or your own on the column) is filtered on it in
571
+ the engine as `WITHOUT` when the client does not say, so its index must hold the column too. Its
572
+ `search_where` ([below](#what-a-search-counts)) leaves the column out, `{}` when nothing else narrows: a
573
+ `search_where` that names it anywhere (in `_and`, `_or`, `_not` too) is an error the client reads at the
574
+ first search, reported to `Config.on_error`, as its condition could not give way to `@trashed`. Lighthouse
575
+ loads the records with `Support::SoftDeletes.filter`, the database's `@trashed`, through Searchkick's
576
+ `scope_results:`, as Scout loads them `withTrashed()`, so a record trashed or restored since the index
577
+ read it is not answered for the wrong `trashed:`. All of this needs trashed records in the index: a
578
+ model that leaves them out (`should_index?` returning false once trashed) finds none with `ONLY`.
579
+
580
+ ### What a search counts
581
+
582
+ **A search counts only what it can load**: its total, `lastPage` and pages are the engine's, and the
583
+ engine knows nothing of the database. What narrows the records a search loads must narrow the engine's
584
+ hits the same way, or a total would count what the client cannot see: with `default_scope {
585
+ where(tenant_id: Current.tenant_id) }`, one tenant's search would load its own records but count every
586
+ tenant's matches. So a Searchkick model with a default scope, a `search_results` scope (below), or an
587
+ STI subclass that searches its parent's index without `searchkick inheritance: true` (which filters the
588
+ engine by type), must define **`search_where`**. Any default scope counts, as declared: what one selects may depend on the
589
+ request (`where(tenant_id: Current.tenant_id) if Current.tenant_id` narrows nothing when the schema is
590
+ built, outside one), so Lighthouse does not judge it by what it selects. `search_where` is the engine's
591
+ `where:` for the same records, from what `search_data` indexes (`{}` for a default scope that only
592
+ orders, or only hides trashed records, which Lighthouse filters on itself: [above](#soft-deletes-in-a-search)).
593
+ Every search of the model ANDs it in. Without it the
594
+ model is a schema error (or, for a field whose model Lighthouse cannot tell, an error at the first
595
+ search):
596
+
597
+ ```ruby
598
+ class Post < ApplicationRecord
599
+ searchkick
600
+ default_scope { where(tenant_id: Current.tenant_id) }
601
+
602
+ def search_data = { title: title, tenant_id: tenant_id }
603
+ def self.search_where = { tenant_id: Current.tenant_id }
604
+ end
605
+ ```
606
+
607
+ `search_where` returns `{}` when the index holds no record the scopes would leave out (should_index?
608
+ keeps them out). The scopes still apply as the hits load, a guard for an index not yet updated: a
609
+ record the index holds after it should have left is never returned, and until the index is updated,
610
+ the total counts it. That holds for a model that loads `searchkick unscope: true` too, which Searchkick
611
+ loads through `unscoped`: Lighthouse merges the model's default scope back in. So do the filters the
612
+ engine applied that the database can apply too: `@trashed`'s, and each `@eq` (or `query.where`) on a
613
+ column of the model whose value the database compares as the engine does, a scalar, a list or a Range
614
+ of them; a record the index still holds as it was (its author changed since) is not answered for a
615
+ filter it no longer matches. A condition only the index holds (a field `search_data` computes, an
616
+ engine operator such as `{ gt: 3 }`, a Regexp) is the index's alone. That window, the time a reindex job takes, is the only one where a count includes
617
+ a record the client cannot load; filter on an indexed column in `search_where` to keep counts exact
618
+ even then, for what the index itself says.
619
+
620
+ ### Keeping private records out of a search
621
+
622
+ A search answers from the index, not the table. **What must not be found must not be indexed**:
623
+ `should_index?` decides it per record, and the index follows as callbacks or jobs run. Until they do,
624
+ or for good if a job fails, the index still holds a record that must no longer be found.
625
+
626
+ A model's `search_results` scope, when it has one, is what a search of it may return, checked in the
627
+ database. Lighthouse loads the records Searchkick finds through it (Searchkick's `scope_results:`), so
628
+ a record the index still holds is not returned; a page may come out short (its positions are still
629
+ the engine's), and Searchkick logs it as a record the database does not have ("Records in search index
630
+ do not exist in database"). With Searchkick it needs its engine counterpart, `search_where`
631
+ ([above](#what-a-search-counts)), so that totals count the same records. With pg_search the scope
632
+ narrows the search itself, totals included.
633
+
634
+ ```ruby
635
+ scope :search_results, -> { where(post: Post.published) }
636
+ def self.search_where = { published: true } # search_data indexes `published: post.published?`
637
+ ```
638
+
639
+ It is the model's, the same for every client: what depends on the user belongs in `@canQuery` or
640
+ `@canResolved`, or, with pg_search, in `@whereAuth`.
641
+
642
+ ### `@canQuery` on a searched field
643
+
644
+ `@canQuery` checks the policy against each record the field's query would return. When the client
645
+ searches, those are the records the search finds: **all of them, not only the page** the field
646
+ returns, as PHP Lighthouse checks the hits of the Scout builder. With Searchkick that is one engine
647
+ request, of 10,000 records at most, each loaded and checked, whose hits then serve the field's page:
648
+ what the index gains between the check and the page is never answered unchecked. They serve that one
649
+ resolution of the field only, handed from `@canQuery` to the field's resolver, never kept in the
650
+ query's context: each field, each place of it in the response, each query of a multiplex and each run
651
+ of a stored subscription context searches again. A search that finds more within the result window (a page cannot reach past it) is an error, `@canQuery
652
+ checks every record the search finds, at most 10000, and this one finds 12345. Narrow the search.`,
653
+ passed to the client or replaced as `action:` says, as any failed check. With pg_search, the scope's
654
+ records, all of them. Its `model:` must be searchable, and with Searchkick its `scopes:` are a schema
655
+ error (PHP Lighthouse drops them). `@canResolved` checks only the records the field returns, after it
656
+ resolves.
657
+
658
+ ### In a resolver of your own
659
+
660
+ `resolve_info.enhance_builder(Comment.all)` applies the field's search too (see
661
+ [resolvers.md](resolvers.md)). With pg_search it answers the relation, searched; with Searchkick, when
662
+ the client searched, a `Lighthouse::Search::Result`, as PHP Lighthouse answers Scout's builder:
663
+ `records(first:, offset:)` reads the records, `count` the total. The engine searches the model's whole
664
+ index, so the relation must select what the model's own does: `Comment.all`, `Comment` itself, or
665
+ either in another order. Any other (`Comment.where(...)`, `Comment.unscoped.where(...)`, a `with_deleted`,
666
+ a `rewhere`, a `merge`, joins, `none`) is refused with a `Lighthouse::DefinitionError`, since the engine
667
+ would drop its conditions and could return records it leaves out. The check compares every condition,
668
+ with its values, to the model's own, and refuses when in doubt: a model whose default scope reads the
669
+ clock (`where('published_at <= ?', Time.current)`) cannot be told from another, and is refused there.
670
+ `@all`, `@paginate` and `@canQuery`, which build the model's relation themselves, need no such check.
671
+
672
+ ```graphql
673
+ type Query {
674
+ found(search: String @search, postId: ID @eq(key: "post_id")): [Comment!]! @field(resolver: "Found")
675
+ }
676
+ ```
677
+
678
+ ```ruby
679
+ class Found
680
+ def self.call(_object, _args, _context, resolve_info)
681
+ found = resolve_info.enhance_builder(Comment.all)
682
+ found.is_a?(Lighthouse::Search::Result) ? found.records(first: 20) : found.limit(20)
683
+ end
684
+ end
685
+ ```
686
+
687
+ ### Choosing the engine
688
+
689
+ By default the engine is detected per model: Searchkick if it calls `searchkick`, else pg_search if it
690
+ includes `PgSearch::Model`. [`Config.search`](configuration.md#search) replaces that with one adapter
691
+ (`Lighthouse::Search::PgSearch.new`, `Lighthouse::Search::Searchkick.new`) or your own. An adapter
692
+ answers `searchable?(model, index)`, `relational?` and either `scope(relation, query)` (a relational one,
693
+ like pg_search) or `page(query, offset:, limit:)` returning `[entries, total]`, one entry per engine
694
+ hit (the record, or nil for one it could not load) and the total, every match counted (an Integer: anything
695
+ else is an error the client reads), and optionally `result_window(query)` (10,000 when it does not, nil when
696
+ it cannot tell), `named?(model, index)` (does `within:` name something of its own
697
+ on the model: picked first when it does) and `model_error(model)` (why a model cannot be searched as it
698
+ is: a schema error). This protocol is experimental.
699
+
700
+ ### Errors
701
+
702
+ | Case | PHP Lighthouse | Lighthouse |
703
+ | --- | --- | --- |
704
+ | Two `@search` arguments sent | `ScoutException` at run time | client error |
705
+ | An argument the engine cannot apply is sent | `ScoutException` at run time | same with Searchkick; none with pg_search |
706
+ | Model not searchable | `ScoutException` at run time | schema error at build, once the field's model is known |
707
+ | `within:` not a string | `DefinitionException` | schema error at build |
708
+ | Nested field (a relation) | `ScoutException` at run time | schema error with Searchkick; works with pg_search |
709
+ | `@find` when the search finds more than one record | "The query returned more than one result." | same, counted by the engine with Searchkick |
710
+ | `@find` with an `id` argument without a filter directive | not a case: PHP's `@find` selects by its arguments' directives only | schema error with Searchkick (give it `@eq`); works with pg_search |
711
+ | `@count`, `@aggregate` | the search ignored: every record counted | schema error with Searchkick; works with pg_search |
712
+ | A mass mutation (`@delete`, `@restore`, `@forceDelete`) | a type error at run time | schema error with Searchkick; works with pg_search |
713
+ | Field has `scopes:`, `@builder`, `@whereAuth`, `@orderBy(column:)` | dropped silently | schema error with Searchkick (a client error, reported, for a resolver of your own whose type is no model); applied with pg_search |
714
+ | `@canQuery` with `scopes:` | dropped silently | schema error with Searchkick; applied with pg_search |
715
+ | A default value for a directive the engine cannot apply | `ScoutException` on every search | schema error with Searchkick; applied with pg_search |
716
+ | A mass mutation's `@search` sent as `null` | not a filter: "Would modify all models" | same |
717
+ | `@trashed` `ONLY` / `WITHOUT` on an index that does not hold the column, or whose columns cannot be told | not a case: Scout indexes its own `__soft_deleted` (with `scout.soft_delete` on) | client error |
718
+ | A page past the result window | depends on the Scout driver | client error |
719
+ | `@canQuery` on more than 10,000 matches a page can reach | checks the hits Scout's `get()` returns | client error |
720
+ | `enhance_builder` given a narrowed relation | conditions dropped | client error, reported to `Config.on_error` |
721
+ | A `@search` nothing applies (the default reader, `@create`, ...) | ignored | schema error |
722
+ | A directive of your own on a searched field, which does not say it applies a search | (no such contract) | schema error |
723
+ | A Searchkick model with a default scope or `search_results`, without `search_where` | the engine counts what does not load | schema error |
724
+ | A nested `@paginate` whose record pages an association its type's model lacks | `ScoutException` at run time | client error |
725
+ | A filter raises (on any field) | the error | the error, reported to `Config.on_error`, for the schema's `rescue_from` |
726
+ | The engine raises, as the field resolves or as a page asks for it | the error | the same |
727
+ | A search the field's own directives would narrow, on a field whose model the build could not tell | directives dropped silently | client error, reported |
728
+ | `@all` answers fewer than asked while more match (10,000 at once, the result window) | Scout's `get()` answers its driver's default | those records, with an error next to them |
729
+ | `body_options` setting `track_total_hits`, or a total the engine did not count to the end | an estimate | client error, reported |
730
+ | A `search_where` naming the soft-delete column | (no such hook) | client error, reported |
731
+ | An `@builder` setting a Searchkick option that decides what loads, pages or counts (`load: false`, ...) | applied | client error, reported |
732
+ | An STI subclass searching its parent's index without `inheritance: true` nor `search_where` | counts the other types | schema error |
733
+
246
734
  ## Complex where conditions
247
735
 
248
736
  `@whereConditions` works as in PHP Lighthouse. The client builds the `WHERE`
@@ -331,7 +331,7 @@ Lighthouse.configure do |config|
331
331
  # e.g. @field(resolver: "Users::Profile") or @all(model: "User").
332
332
  config.resolver_namespaces = ['App::Graphql', 'Resolvers']
333
333
 
334
- # How swallowed directive errors are surfaced (raise in test, log otherwise).
334
+ # How directive errors are reported (raise in test, log otherwise).
335
335
  # config.on_error = ->(error, _ctx) { Sentry.capture_exception(error) }
336
336
  end
337
337
  ```
data/docs/performance.md CHANGED
@@ -12,6 +12,8 @@ by default**; enable the ones your app needs.
12
12
  | [`watch_sdl`](#reloading-the-sdl-in-development) | Reloads the app when a `.graphql` file changes | Developing; typically `Rails.env.development?` |
13
13
  | [`persisted_queries`](#persisted-queries) | Apollo's Automatic Persisted Queries, optionally an allowlist | Large queries, CDN caching of `GET`s, locking the API down to known operations |
14
14
 
15
+ [`@defer`](defer.md) (experimental) is a fourth, a plugin of the schema.
16
+
15
17
  ## Schema cache
16
18
 
17
19
  ```ruby
@@ -136,6 +138,13 @@ clients:
136
138
  bin/rails lighthouse:persisted_queries:verify SCHEMA=AppSchema
137
139
  ```
138
140
 
141
+ ## Deferring fields (experimental)
142
+
143
+ `@defer` and `@stream` send the fields a client can wait for after the rest of the response, in
144
+ later parts of it, so it renders the most important content first. They are a plugin of the
145
+ schema, `use Lighthouse::GraphQL::Defer`, as PHP Lighthouse's are a service provider: the guide is
146
+ [defer.md](defer.md).
147
+
139
148
  ## What is deliberately not cached
140
149
 
141
150
  - **Query ASTs and validation results.** PHP Lighthouse caches them because PHP
data/docs/relay.md CHANGED
@@ -47,6 +47,33 @@ type Mutation {
47
47
  Lists of ids decode item by item. A value that is not a global id makes the field
48
48
  fail with `"…" is not a valid global id.`
49
49
 
50
+ ### The type of a decoded id
51
+
52
+ Relay ids are unique across types, so a decoded id is checked to be of the type it is
53
+ for: another type's id makes the field fail with `"…" is not a valid global id for
54
+ User.`, where it would find the record that happens to have the same number (a
55
+ `Post`'s id finding user 1, or `@delete` removing it). PHP Lighthouse does not check.
56
+
57
+ - **Inferred** with `decode: ID`, when the argument filters the field's model by its
58
+ key: `@whereKey`, an `@eq` or `@in` on the primary key, or an argument named after
59
+ it (`id`). That is an argument of the field, or a field of an input one of its
60
+ arguments takes (`user(by: UserBy!)`), unless that argument is an association of
61
+ the model. The field's model is its `model:`, else its return type's.
62
+ - **Explicit** with `type:`, a GraphQL type or model name, for any other argument and
63
+ any `decode:`:
64
+
65
+ ```graphql
66
+ type Query {
67
+ user(id: ID! @globalId(decode: ID) @eq): User @find # a User's id, inferred
68
+ posts(authorId: ID! @globalId(decode: ID, type: "User") @eq(key: "author_id")): [Post!]! @all
69
+ }
70
+ ```
71
+
72
+ An id of a subclass (STI) passes, and so does the id of a type whose
73
+ [`@model`](directives.md#model) is the field's model. `authorId` above, without
74
+ `type:`, is not checked: it holds another model's id, as the inputs of nested
75
+ mutations do.
76
+
50
77
  ## Nodes
51
78
 
52
79
  `@node` registers a type for refetching:
data/docs/resolvers.md CHANGED
@@ -283,6 +283,14 @@ What PHP Lighthouse hands a resolver as `$resolveInfo`. A `Resolvers::` or
283
283
  what the field declares: its `@builder` classes, and the argument directives the
284
284
  client used (`@eq`, `@where`, `@in`, `@like`, `@orderBy`, `@whereConditions`, ...),
285
285
  then the field's own `@orderBy(column:)`, as `@all` and `@paginate` apply them. `scopes:` adds model scopes.
286
+ When the client searches ([`@search`](filtering-and-ordering.md#in-a-resolver-of-your-own)), it searches
287
+ too: with pg_search the answer is still a relation, with Searchkick a `Lighthouse::Search::Result`
288
+ (`records(first:, offset:)`, `count`), for which the relation must select what the model's own does
289
+ (`Post.all`, or `Post`): any other is refused, as the engine would drop its conditions.
290
+ A field your class resolves may search with Searchkick this way, whatever its type, unless it
291
+ has a `@builder`, `@whereAuth` or `@orderBy(column:)` of its own, which the engine cannot apply:
292
+ the schema refuses to build when it can tell the field's model, and each search of it is an
293
+ error the client reads when it cannot (a type that is no model), never answered without them.
286
294
 
287
295
  ```graphql
288
296
  type Query {
@@ -513,8 +521,12 @@ end
513
521
  `@builder` works with `@all`, `@paginate`, `@first`, `@count` and `@aggregate`.
514
522
  It is repeatable, and `method:` names a method other than `call`. Builder classes
515
523
  are looked up in the builders namespace only. Raising a `GraphQL::ExecutionError`
516
- from a builder (e.g. a tenancy check) always reaches the client; it never falls
517
- back to the unscoped relation.
524
+ from a builder (e.g. a tenancy check) always reaches the client. Any other error
525
+ fails the field too: it is reported to [`on_error`](configuration.md#on_error), then
526
+ raised as it is, as any resolver's error, so your schema's `rescue_from` maps it
527
+ (unmapped, it is graphql-ruby's error). A query never falls back to the relation
528
+ without the builder. A builder whose class or method cannot be found is a schema
529
+ error, which the client reads, reported too.
518
530
 
519
531
  The gem ships RBS signatures in `sig/`, so with Steep (or anything that reads
520
532
  `rbs collection`) a builder can be checked against `Lighthouse::_Builder`: