lighthouse-graphql 0.8.2 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +152 -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 +102 -0
  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/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 +30 -1
  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 +99 -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 +27 -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 +34 -0
  68. data/lib/lighthouse/resolve_info.rb +7 -1
  69. data/lib/lighthouse/search/auto.rb +21 -0
  70. data/lib/lighthouse/search/enhancer.rb +127 -0
  71. data/lib/lighthouse/search/field_check.rb +171 -0
  72. data/lib/lighthouse/search/pg_search.rb +76 -0
  73. data/lib/lighthouse/search/query.rb +35 -0
  74. data/lib/lighthouse/search/result.rb +181 -0
  75. data/lib/lighthouse/search/searchkick.rb +292 -0
  76. data/lib/lighthouse/search/searchkick_index.rb +54 -0
  77. data/lib/lighthouse/search/searchkick_options.rb +74 -0
  78. data/lib/lighthouse/search.rb +78 -0
  79. data/lib/lighthouse/support/argument_walk.rb +81 -0
  80. data/lib/lighthouse/support/count.rb +16 -0
  81. data/lib/lighthouse/support/failures.rb +28 -0
  82. data/lib/lighthouse/support/memo.rb +72 -0
  83. data/lib/lighthouse/support/model_resolver.rb +24 -0
  84. data/lib/lighthouse/support/relations.rb +31 -0
  85. data/lib/lighthouse/support/soft_deletes.rb +42 -8
  86. data/lib/lighthouse/testing.rb +81 -0
  87. data/sig/lighthouse/controller.rbs +34 -1
  88. data/sig/lighthouse/directives.rbs +46 -5
  89. data/sig/lighthouse/events.rbs +7 -0
  90. data/sig/lighthouse/graphql.rbs +117 -0
  91. data/sig/lighthouse/search.rbs +132 -0
  92. data/sig/lighthouse.rbs +69 -1
  93. metadata +38 -1
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ # @stream, as the specification draft has it (graphql-spec PR #1110): on a list
4
+ # field, it asks for the first `initialCount` items at once and the rest after
5
+ # the response.
6
+ #
7
+ # StreamTrace, the trace module Defer.use adds to the schema, does the work: a
8
+ # field resolver returns the whole list, and StreamTrace cuts it where the
9
+ # directive says. graphql-ruby calls `resolve` around the resolution of a field
10
+ # that carries the directive, and of no other: it hands the directive's arguments
11
+ # to that field's `execute_field` through the fiber-local MARK, which StreamTrace
12
+ # takes before the field's resolver runs.
13
+ class Lighthouse::GraphQL::Incremental::StreamDirective < GraphQL::Schema::Directive
14
+ MARK = :lighthouse_stream
15
+
16
+ graphql_name 'stream'
17
+ description 'Deliver the items of a list after the first `initialCount` in a later part when the response is ' \
18
+ 'streamed (multipart/mixed, to a client that prefers it to JSON); the whole list otherwise (experimental).'
19
+ locations ::GraphQL::Schema::Directive::FIELD
20
+
21
+ argument :if, ::GraphQL::Types::Boolean, required: true, default_value: true,
22
+ description: 'Stream the list only when true.'
23
+ argument :label, ::GraphQL::Types::String, required: false,
24
+ description: 'Names the stream in the streamed response. Unique in the document, and not a variable.'
25
+ argument :initial_count, ::GraphQL::Types::Int, required: true, default_value: 0,
26
+ description: 'How many items come with the first response.'
27
+
28
+ class << self
29
+ def resolve(_object, arguments, context)
30
+ return yield if arguments[:if] == false
31
+
32
+ previous = Thread.current[MARK]
33
+ Thread.current[MARK] = [context[:current_field], arguments]
34
+ begin
35
+ yield
36
+ ensure
37
+ Thread.current[MARK] = previous
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,93 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The graphql-ruby trace module of incremental delivery: Defer.use adds it to the
4
+ # schema that uses the plugin (to it and its subclasses, in every trace mode, and
5
+ # to no other schema built on the same types), so it sees every field of that
6
+ # schema, whenever defined, and changes no field. It does two things.
7
+ #
8
+ # - @stream: StreamDirective, which graphql-ruby runs around a field that carries
9
+ # @stream, and only then, leaves the directive's arguments in its fiber-local
10
+ # MARK; the field's `execute_field`, which runs inside it, takes them before the
11
+ # resolver runs. Once the resolver has answered (or its lazy value is synced, the
12
+ # arguments kept by the field's AST node meanwhile), a negative initialCount is a
13
+ # field error (the draft's CompleteValue), streamed or not; with an
14
+ # Incremental::State in the context, the list keeps its first `initialCount`
15
+ # items, and the rest are kept in the State to follow (Run).
16
+ # - While a streamed response runs (Run puts its State in the fiber-local RUNNING),
17
+ # it hands the State the objects its deferred fragments will need: those of the
18
+ # object fields a fragment adds selections to, which the rest of the query
19
+ # resolved (Plan, State#keep); and it answers the field a stream's Partial runs
20
+ # again with the items left to stream, its resolver not run (State#answer).
21
+ #
22
+ # A field of any other request costs two fiber-local reads.
23
+ module Lighthouse::GraphQL::Incremental::StreamTrace
24
+ MARK = Lighthouse::GraphQL::Incremental::StreamDirective::MARK
25
+ RUNNING = :lighthouse_incremental_state
26
+ NEGATIVE = 'The initialCount of @stream must not be negative.'
27
+
28
+ # Where a field resolved: what `done` needs of it.
29
+ Site = Struct.new(:field, :query, :object, :ast_node)
30
+
31
+ def execute_field(field:, query:, object:, ast_node:, **options)
32
+ stream = Lighthouse::GraphQL::Incremental::StreamTrace.take(field)
33
+ state = Thread.current[RUNNING]
34
+ return super unless stream || state
35
+
36
+ result = Lighthouse::GraphQL::Incremental::StreamTrace.answer(state, query, ast_node) { super }
37
+ site = Site.new(field, query, object, ast_node)
38
+ return Lighthouse::GraphQL::Incremental::StreamTrace.done(result, stream, site) unless query.schema.lazy?(result)
39
+
40
+ ((@lighthouse_streams ||= {}.compare_by_identity)[object] ||= {}.compare_by_identity)[ast_node] = stream if stream
41
+ result
42
+ end
43
+
44
+ def execute_field_lazy(field:, query:, object:, ast_node:, **options)
45
+ result = super
46
+ stream = @lighthouse_streams&.[](object)&.delete(ast_node)
47
+ return result unless stream || Thread.current[RUNNING]
48
+
49
+ Lighthouse::GraphQL::Incremental::StreamTrace.done(result, stream, Site.new(field, query, object, ast_node))
50
+ end
51
+
52
+ # The items that stand in for the field of `ast_node` in a stream's Partial (State#answer), or
53
+ # what the block (the resolver) answers.
54
+ def self.answer(state, query, ast_node)
55
+ items = state ? state.answer(query, ast_node) : Lighthouse::GraphQL::Incremental::State::MISSING
56
+ items.equal?(Lighthouse::GraphQL::Incremental::State::MISSING) ? yield : items
57
+ end
58
+
59
+ # The arguments of the @stream StreamDirective marked `field` with, taken.
60
+ def self.take(field)
61
+ mark = Thread.current[MARK]
62
+ return nil unless mark && mark.first.equal?(field)
63
+
64
+ Thread.current[MARK] = nil
65
+ mark.last
66
+ end
67
+
68
+ # The value the field answers, cut where its @stream says; the State keeps it if it needs it.
69
+ def self.done(value, stream, site)
70
+ value = cut(value, stream, site) if stream
71
+ Thread.current[RUNNING]&.keep(site.query, site.ast_node, value)
72
+ value
73
+ end
74
+
75
+ # A list's first `initialCount` items, with the rest kept in the State; the list as it is when
76
+ # there is no rest to stream, or no State.
77
+ def self.cut(value, arguments, site)
78
+ return value unless list?(value)
79
+ return ::GraphQL::ExecutionError.new(NEGATIVE) if arguments[:initial_count].negative?
80
+
81
+ state = site.query.context[Lighthouse::GraphQL::Incremental::State::CONTEXT_KEY] or return value
82
+ initial = arguments[:initial_count]
83
+ items = value.to_a
84
+ return items if items.size <= initial
85
+
86
+ state.stream(site.object, arguments, items.drop(initial), site.query.context, site.field) ? items.first(initial) : items
87
+ end
88
+
89
+ # A list the resolver answered; nil (a nullable list's null) answers to `to_a` too, and stays null.
90
+ def self.list?(value)
91
+ !value.nil? && value.respond_to?(:to_a) && !value.is_a?(Hash)
92
+ end
93
+ end
@@ -0,0 +1,68 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The response's data so far, as the client puts it together (Run): the first
4
+ # payload's data, then each later entry's merged in at its path.
5
+ #
6
+ # Nothing is copied whole, and no payload changes: the tree holds the first
7
+ # payload's data and the entries' as they are, and each Hash or list later data
8
+ # goes in is copied (shallowly) the first time it does, with the ones above it.
9
+ class Lighthouse::GraphQL::Incremental::Tree
10
+ attr_reader :data
11
+
12
+ # What `path` leads to in `data` (Hashes and lists), or nil where it leads nowhere.
13
+ def self.at(data, path)
14
+ path.reduce(data) { |value, key| (value.is_a?(Array) && key.is_a?(Integer)) || value.is_a?(Hash) ? value[key] : nil }
15
+ end
16
+
17
+ def initialize(data)
18
+ @data = data
19
+ @own = {}.compare_by_identity
20
+ end
21
+
22
+ def at(path) = self.class.at(@data, path)
23
+
24
+ # The data as it is now, which later merges leave as it is (they copy what they change).
25
+ def snapshot
26
+ @own.clear
27
+ @data
28
+ end
29
+
30
+ def present?(path) = !at(path).nil?
31
+
32
+ # A fragment's data, at the path of its object.
33
+ def merge(path, data)
34
+ target = own_path(path) or return
35
+ merge_into(target, data)
36
+ end
37
+
38
+ # A stream's items, after the list's.
39
+ def append(path, items)
40
+ own_path(path)&.concat(items)
41
+ end
42
+
43
+ private
44
+
45
+ # The containers along `path`, the tree's own (copied where they were not yet); the last.
46
+ def own_path(path)
47
+ return nil unless @data.is_a?(Hash)
48
+
49
+ container = @data = own(@data)
50
+ path.each do |key|
51
+ child = self.class.at(container, [key])
52
+ return nil unless child.is_a?(Hash) || child.is_a?(Array)
53
+
54
+ container = container[key] = own(child)
55
+ end
56
+ container
57
+ end
58
+
59
+ def merge_into(target, data)
60
+ return unless target.is_a?(Hash)
61
+
62
+ data.each { |key, value| target[key].is_a?(Hash) && value.is_a?(Hash) ? merge_into(target[key] = own(target[key]), value) : target[key] = value }
63
+ end
64
+
65
+ def own(container)
66
+ @own.key?(container) ? container : container.dup.tap { |copy| @own[copy] = true }
67
+ end
68
+ end
@@ -9,12 +9,14 @@ module Lighthouse
9
9
  module Events; end
10
10
  module Generators; end
11
11
  module OrderBy; end
12
+ module Search; end
12
13
  module Support; end
13
14
  module WhereConditions; end
14
15
 
15
16
  module GraphQL
16
17
  module DataloaderSources; end
17
18
  module DirectiveResolvers; end
19
+ module Incremental; end
18
20
 
19
21
  module Directives
20
22
  module Arguments; end
@@ -41,8 +41,8 @@ module Lighthouse::GraphQL::NestedMutations::BelongsToOperations
41
41
  # model name, or an enum value such as TASK for Task.
42
42
  def morph_model(type)
43
43
  [type, type.to_s.downcase.camelize].uniq.each do |name|
44
- model = Lighthouse::Support::ModelResolver.constantize(name)
45
- return model if model.is_a?(Class) && model < ::ActiveRecord::Base
44
+ model = Lighthouse::Support::ModelResolver.model_class(name)
45
+ return model if model
46
46
  end
47
47
 
48
48
  raise ::GraphQL::ExecutionError, "Unknown type #{type} to connect."
@@ -59,7 +59,8 @@ module Lighthouse::GraphQL::Operations
59
59
 
60
60
  # Dispatch StartRequest, run the block, dispatch EndRequest with the
61
61
  # response. Only the outermost call dispatches, and stops the block where a
62
- # @throttle `with:` method performed the response.
62
+ # @throttle `with:` method performed the response. A streamed response
63
+ # dispatches EndRequest itself, once it is out (`lighthouse_streaming?`).
63
64
  def lighthouse_request
64
65
  return yield if @lighthouse_request_started
65
66
 
@@ -70,10 +71,13 @@ module Lighthouse::GraphQL::Operations
70
71
  rescue Lighthouse::GraphQL::Controller::Performed
71
72
  nil
72
73
  end
73
- Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(response))
74
+ Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(response)) unless lighthouse_streaming?
74
75
  result
75
76
  end
76
77
 
78
+ # Does the response go on after the action, ending the request itself (the controller's streamed one)?
79
+ def lighthouse_streaming? = false
80
+
77
81
  # The context of the operation: what @guard and the @can* directives read.
78
82
  def graphql_context
79
83
  respond_to?(:current_user, true) ? { current_user: current_user } : {}
@@ -37,6 +37,28 @@ module Lighthouse::GraphQL::Pagination
37
37
  # Where a page's rows and total come from.
38
38
  module List; end
39
39
 
40
+ # A window of records that may hold fewer records than positions: a search
41
+ # whose hits did not all load (Search::Result). Each record keeps its position
42
+ # in the whole list, and `covered` tells how many positions the window spans,
43
+ # so pages and cursors follow positions: the next page starts after a dropped
44
+ # hit, never before it, and no record shows twice. A plain array's records
45
+ # hold the positions from the window's offset on.
46
+ class Window < Array
47
+ attr_reader :positions, :covered
48
+
49
+ def initialize(records, positions, covered)
50
+ super(records)
51
+ @positions = positions
52
+ @covered = covered
53
+ end
54
+ end
55
+
56
+ # The positions of a window's records, from `offset`.
57
+ def positions(rows, offset) = rows.is_a?(Window) ? rows.positions : (offset...(offset + rows.size)).to_a
58
+
59
+ # How many positions a window spans.
60
+ def covered(rows) = rows.is_a?(Window) ? rows.covered : rows.size
61
+
40
62
  class RelationList
41
63
  include List
42
64
 
@@ -86,12 +108,16 @@ module Lighthouse::GraphQL::Pagination
86
108
  Paginator.new(list, per_page, page)
87
109
  end
88
110
 
89
- # Fetches one extra row to tell whether there is a next page, instead of counting.
111
+ # Fetches one extra position to tell whether there is a next page, instead of counting.
90
112
  def simple(list, per_page, page)
91
- rows = list.window((page - 1) * per_page, per_page + 1)
92
- items = rows.first(per_page)
113
+ offset = (page - 1) * per_page
114
+ rows = list.window(offset, per_page + 1)
115
+ all_positions = positions(rows, offset)
116
+ kept = rows.each_index.select { |index| all_positions[index] < offset + per_page }
117
+ items = kept.map { |index| rows[index] }
93
118
  {
94
- 'paginatorInfo' => item_range(items, page, per_page).merge('hasMorePages' => rows.size > per_page),
119
+ 'paginatorInfo' => item_range(items, page, per_page, kept.map { |index| all_positions[index] })
120
+ .merge('hasMorePages' => covered(rows) > per_page),
95
121
  'data' => items
96
122
  }
97
123
  end
@@ -127,6 +153,13 @@ module Lighthouse::GraphQL::Pagination
127
153
  def total
128
154
  @total ||= @list.count
129
155
  end
156
+
157
+ # How many records a page can reach: the total, but a search's only within
158
+ # its engine's result window (Search::Result#reachable). Pages are counted
159
+ # from it, so no page is announced that would then be refused.
160
+ def reachable
161
+ @reachable ||= @list.respond_to?(:reachable) ? @list.reachable : total
162
+ end
130
163
  end
131
164
 
132
165
  class Paginator < LazyPage
@@ -142,8 +175,9 @@ module Lighthouse::GraphQL::Pagination
142
175
 
143
176
  def info
144
177
  @info ||= begin
145
- last_page = @per_page.zero? ? 0 : [(total.to_f / @per_page).ceil, 1].max
146
- Lighthouse::GraphQL::Pagination.item_range(@items, @page, @per_page)
178
+ last_page = @per_page.zero? ? 0 : [(reachable.to_f / @per_page).ceil, 1].max
179
+ positions = Lighthouse::GraphQL::Pagination.positions(@items, (@page - 1) * @per_page)
180
+ Lighthouse::GraphQL::Pagination.item_range(@items, @page, @per_page, positions)
147
181
  .merge('hasMorePages' => @page < last_page, 'lastPage' => last_page, 'total' => total)
148
182
  end
149
183
  end
@@ -156,25 +190,35 @@ module Lighthouse::GraphQL::Pagination
156
190
  @offset = offset
157
191
  end
158
192
 
193
+ # A cursor is a record's position in the whole list, 1-based.
159
194
  def edges
160
- @items.each_with_index.map { |node, i| { 'cursor' => Lighthouse::GraphQL::Pagination.encode_cursor(@offset + i + 1), 'node' => node } }
195
+ cursors.zip(@items).map { |cursor, node| { 'cursor' => cursor, 'node' => node } }
161
196
  end
162
197
 
163
198
  def pageInfo = info # rubocop:disable Naming/MethodName -- the GraphQL field's name, which the default resolver reads
164
199
 
200
+ # The start and end cursors are the first and last edge's, as Relay's. A page
201
+ # whose hits all failed to load has no edge, but its end cursor is past the
202
+ # positions it spans, so the client walks on to the next page.
165
203
  def info
204
+ covered = Lighthouse::GraphQL::Pagination.covered(@items)
205
+ past = Lighthouse::GraphQL::Pagination.encode_cursor(@offset + covered) unless covered.zero?
166
206
  @info ||= {
167
- 'hasNextPage' => @offset + @items.size < total,
207
+ 'hasNextPage' => @offset + covered < reachable,
168
208
  'hasPreviousPage' => @offset.positive?,
169
- 'startCursor' => @items.empty? ? nil : Lighthouse::GraphQL::Pagination.encode_cursor(@offset + 1),
170
- 'endCursor' => @items.empty? ? nil : Lighthouse::GraphQL::Pagination.encode_cursor(@offset + @items.size),
209
+ 'startCursor' => cursors.first,
210
+ 'endCursor' => cursors.last || past,
171
211
  'total' => total,
172
212
  'count' => @items.size,
173
213
  'currentPage' => @first.zero? ? 1 : (@offset / @first) + 1,
174
- 'lastPage' => @first.zero? ? 0 : [(total.to_f / @first).ceil, 1].max
214
+ 'lastPage' => @first.zero? ? 0 : [(reachable.to_f / @first).ceil, 1].max
175
215
  }
176
216
  end
177
217
 
218
+ def cursors
219
+ @cursors ||= Lighthouse::GraphQL::Pagination.positions(@items, @offset).map { |position| Lighthouse::GraphQL::Pagination.encode_cursor(position + 1) }
220
+ end
221
+
178
222
  def marshal_dump
179
223
  [info, @items, @offset]
180
224
  end
@@ -185,13 +229,15 @@ module Lighthouse::GraphQL::Pagination
185
229
  end
186
230
  end
187
231
 
188
- def item_range(items, page, per_page)
189
- first_item = items.empty? ? nil : ((page - 1) * per_page) + 1
232
+ # firstItem and lastItem are the 1-based positions of the page's first and
233
+ # last record (`positions`, 0-based, of a Window whose hits did not all load).
234
+ def item_range(items, page, per_page, positions = nil)
235
+ positions ||= (0...items.size).map { |index| ((page - 1) * per_page) + index }
190
236
  {
191
237
  'count' => items.size,
192
238
  'currentPage' => page,
193
- 'firstItem' => first_item,
194
- 'lastItem' => first_item && (first_item + items.size - 1),
239
+ 'firstItem' => positions.first&.+(1),
240
+ 'lastItem' => positions.last&.+(1),
195
241
  'perPage' => per_page
196
242
  }
197
243
  end
@@ -54,19 +54,64 @@ module Lighthouse::GraphQL::PersistedQueries
54
54
  # `schema.execute` with the query the request names; a protocol error
55
55
  # comes back as a ready-to-render { "errors" => [...] } Hash. Dispatches
56
56
  # StartOperationOrOperations before and EndOperationOrOperations after.
57
+ # A protocol error raised as the query runs (a resolver asking `resolve`, say) is answered so too.
57
58
  def execute(schema, query:, extensions: nil, **options)
58
- operation = { query: query, variables: options[:variables], operation_name: options[:operation_name], extensions: extensions }
59
- Lighthouse::Events.dispatch(Lighthouse::Events::StartOperationOrOperations.new(operation))
60
- result =
59
+ operation(query, extensions, options) do |text, ended|
60
+ protocol { schema.execute(text, **options) }.tap { |result| ended.call(result) }
61
+ end
62
+ end
63
+
64
+ # `execute` for a response that may be streamed (Defer): yields the
65
+ # Incremental::Run of the query, started (its first pass has run), and answers
66
+ # what the block answers; or answers the ready-to-render Hash of a protocol
67
+ # error, without yielding. Dispatches the same events as `execute`: for a run
68
+ # that defers nothing, EndOperationOrOperations with its result at once; for one
69
+ # that defers, with the whole response (Incremental::Run#response, the data and
70
+ # errors of every round) once its last round has run, or, if the block streams
71
+ # none, once the block is done. Without a block, it answers the Run, which the caller ends
72
+ # (Run#finish) once its response is out (Lighthouse::GraphQL::Controller, whose streamed body
73
+ # outlives the action). `format`: the payloads' (Run).
74
+ #
75
+ # A protocol error raised as the first pass runs is answered as on the JSON path, nothing being
76
+ # sent yet; one raised in a later round fails the stream, as any error of a round does.
77
+ def incremental(schema, query:, extensions: nil, format: :draft, **options)
78
+ operation(query, extensions, options) do |text, ended|
79
+ run = protocol { Lighthouse::GraphQL::Incremental::Run.new(schema, text, format: format, **options).start(&ended) }
80
+ next run.tap { |error| ended.call(error) } if run.is_a?(Hash)
81
+ next run unless block_given?
82
+
61
83
  begin
62
- schema.execute(resolve(query, extensions), **options)
63
- rescue Error => e
64
- e.to_h
84
+ yield run
85
+ ensure
86
+ run.finish
65
87
  end
66
- Lighthouse::Events.dispatch(Lighthouse::Events::EndOperationOrOperations.new(result))
67
- result
88
+ end
68
89
  end
69
90
 
91
+ # What the block answers, or the Hash of the protocol Error it raises.
92
+ def protocol
93
+ yield
94
+ rescue Error => e
95
+ e.to_h
96
+ end
97
+
98
+ # What `execute` and `incremental` share: the block runs the query the request names
99
+ # (`text`) after StartOperationOrOperations, and calls `ended`, once, with what
100
+ # EndOperationOrOperations carries, once it is done. A protocol error (the request's query
101
+ # does not resolve) comes back as its Hash, and ends the operation, the block not run. An
102
+ # error raised elsewhere (a listener, the block) goes through as it is.
103
+ def operation(query, extensions, options)
104
+ operation = { query: query, variables: options[:variables], operation_name: options[:operation_name], extensions: extensions }
105
+ Lighthouse::Events.dispatch(Lighthouse::Events::StartOperationOrOperations.new(operation))
106
+ ended = ->(result) { Lighthouse::Events.dispatch(Lighthouse::Events::EndOperationOrOperations.new(result)) }
107
+ text = protocol { resolve(query, extensions) }
108
+ return text.tap { |error| ended.call(error) } if text.is_a?(Hash)
109
+
110
+ yield text, ended
111
+ end
112
+
113
+ private_class_method :protocol, :operation
114
+
70
115
  # A batch (a JSON array in the request) through `schema.multiplex`; see Batch.
71
116
  def multiplex(schema, operations, **options)
72
117
  Lighthouse::GraphQL::PersistedQueries::Batch.run(schema, operations, **options)
@@ -23,7 +23,12 @@ require_relative 'namespaces'
23
23
  graphql_ruby_patches
24
24
  reference_resolver
25
25
  support/naming
26
+ support/count
26
27
  support/directive_args
28
+ support/argument_walk
29
+ support/relations
30
+ support/failures
31
+ support/memo
27
32
  support/model_resolver
28
33
  support/authorization
29
34
  support/arguments
@@ -39,6 +44,7 @@ require_relative 'namespaces'
39
44
  contracts/arg_manipulator
40
45
  contracts/arg_builder
41
46
  contracts/field_builder
47
+ contracts/search_builder
42
48
  schema_stitcher
43
49
  document_ast
44
50
  generated_resolvers
@@ -60,8 +66,25 @@ require_relative 'namespaces'
60
66
  persisted_queries
61
67
  persisted_queries/batch
62
68
  persisted_queries/manifest
69
+ incremental/gone
70
+ incremental/state
71
+ incremental/defer_directive
72
+ incremental/stream_directive
73
+ incremental/stream_trace
74
+ incremental/document
75
+ incremental/rules
76
+ incremental/tree
77
+ incremental/delivery
78
+ incremental/plan
79
+ incremental/serializer
80
+ incremental/legacy
81
+ incremental/multipart
82
+ incremental/body
83
+ incremental/run
84
+ defer
63
85
  operations
64
86
  controller
87
+ testing
65
88
  schema_factory
66
89
  schema_implementation
67
90
  resolver_dispatch
@@ -83,6 +106,16 @@ require_relative 'namespaces'
83
106
  node_registry
84
107
  scalar_coercion
85
108
  pagination
109
+ search
110
+ search/query
111
+ search/result
112
+ search/searchkick
113
+ search/searchkick_index
114
+ search/searchkick_options
115
+ search/pg_search
116
+ search/auto
117
+ search/enhancer
118
+ search/field_check
86
119
  relation_batch
87
120
  relation_counts
88
121
  nested_mutations
@@ -142,6 +175,7 @@ require_relative 'namespaces'
142
175
  directives/arguments/where_conditions
143
176
  directives/arguments/where_has_conditions
144
177
  directives/arguments/soft_deletes
178
+ directives/arguments/search
145
179
  directives/definitions
146
180
  directives/registry
147
181
  dataloader_sources/association_loader
@@ -55,11 +55,17 @@ class Lighthouse::GraphQL::ResolveInfo
55
55
  # client used (@eq, @where, @in, @like, @orderBy, @whereConditions, @trashed,
56
56
  # ...), then the field's @builder, @whereAuth and @orderBy(column:), as
57
57
  # @all / @paginate apply them and as PHP Lighthouse's enhanceBuilder does.
58
+ #
59
+ # When the client searches (@search) through an engine outside the database
60
+ # (Searchkick), the answer is a Lighthouse::Search::Result instead, as PHP
61
+ # Lighthouse's is Scout's builder: `records(first:, offset:)`, `count`. The
62
+ # engine searches the model's whole index, so `relation` must be the model's
63
+ # (`Post.all`), with no `scopes`.
58
64
  def enhance_builder(relation, scopes: [])
59
65
  resolver = Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver.new(field, parent_type, nil)
60
66
  args = arguments.respond_to?(:to_h) ? arguments.to_h : {}
61
67
  relation = Array(scopes).reduce(relation) { |acc, scope| acc.public_send(scope) }
62
- resolver.apply_where_filters(relation, args, context)
68
+ resolver.apply_where_filters(relation, args, context, search: :given)
63
69
  end
64
70
 
65
71
  # `resolve_info`, for the classes that resolve a field.
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The default adapter: asks each engine, in order (Searchkick, then pg_search),
4
+ # whether the model uses it. A `within:` that names something of one engine's on
5
+ # the model (a pg_search scope; `named?(model, index)`) picks that engine, even
6
+ # for a model that uses both: Searchkick takes any `within:` as an index name.
7
+ # `Config.search` replaces it with one adapter.
8
+ class Lighthouse::Search::Auto
9
+ def initialize(adapters = nil)
10
+ @adapters = adapters || [Lighthouse::Search::Searchkick.new, Lighthouse::Search::PgSearch.new]
11
+ end
12
+
13
+ # The adapter that searches `model` (within the scope or index `index` names), or nil.
14
+ def adapter_for(model, index = nil)
15
+ searching = @adapters.select { |adapter| adapter.searchable?(model, index) }
16
+ named = index && searching.find { |adapter| adapter.respond_to?(:named?) && adapter.named?(model, index) }
17
+ named || searching.first
18
+ end
19
+
20
+ def searchable?(model, index = nil) = !adapter_for(model, index).nil?
21
+ end