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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +152 -1
- data/docs/authorization.md +5 -1
- data/docs/configuration.md +71 -3
- data/docs/custom-directives.md +22 -0
- data/docs/defer.md +352 -0
- data/docs/directives.md +102 -0
- data/docs/events.md +30 -1
- data/docs/filtering-and-ordering.md +488 -0
- data/docs/getting-started.md +1 -1
- data/docs/performance.md +9 -0
- data/docs/resolvers.md +14 -2
- data/docs/testing.md +99 -0
- data/lib/lighthouse/complexity.rb +4 -2
- data/lib/lighthouse/config.rb +28 -11
- data/lib/lighthouse/contracts/field_resolver.rb +32 -0
- data/lib/lighthouse/contracts/search_builder.rb +16 -0
- data/lib/lighthouse/controller.rb +94 -18
- data/lib/lighthouse/defer.rb +114 -0
- data/lib/lighthouse/directive_resolvers/aggregate_resolver.rb +1 -0
- data/lib/lighthouse/directive_resolvers/all_resolver.rb +30 -1
- data/lib/lighthouse/directive_resolvers/argument_binding.rb +1 -3
- data/lib/lighthouse/directive_resolvers/association_resolvers.rb +1 -0
- data/lib/lighthouse/directive_resolvers/base.rb +99 -49
- data/lib/lighthouse/directive_resolvers/builder_applier.rb +24 -18
- data/lib/lighthouse/directive_resolvers/can_resolvers.rb +28 -2
- data/lib/lighthouse/directive_resolvers/count_resolver.rb +1 -0
- data/lib/lighthouse/directive_resolvers/field_resolver.rb +4 -0
- data/lib/lighthouse/directive_resolvers/find_resolver.rb +31 -16
- data/lib/lighthouse/directive_resolvers/first_resolver.rb +6 -3
- data/lib/lighthouse/directive_resolvers/global_id_types.rb +1 -2
- data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +2 -0
- data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +27 -4
- data/lib/lighthouse/directive_resolvers/throttle_resolver.rb +17 -6
- data/lib/lighthouse/directives/arguments/base.rb +14 -0
- data/lib/lighthouse/directives/arguments/filters.rb +6 -0
- data/lib/lighthouse/directives/arguments/more_filters.rb +3 -0
- data/lib/lighthouse/directives/arguments/search.rb +34 -0
- data/lib/lighthouse/directives/arguments/soft_deletes.rb +11 -0
- data/lib/lighthouse/directives/model_directive.rb +1 -1
- data/lib/lighthouse/directives/registry.rb +1 -1
- data/lib/lighthouse/events/execution_trace.rb +6 -1
- data/lib/lighthouse/events/lifecycle.rb +2 -1
- data/lib/lighthouse/events.rb +9 -0
- data/lib/lighthouse/field_resolver_stack.rb +22 -21
- data/lib/lighthouse/graphql/version.rb +1 -1
- data/lib/lighthouse/incremental/body.rb +76 -0
- data/lib/lighthouse/incremental/defer_directive.rb +34 -0
- data/lib/lighthouse/incremental/delivery.rb +94 -0
- data/lib/lighthouse/incremental/document.rb +242 -0
- data/lib/lighthouse/incremental/gone.rb +6 -0
- data/lib/lighthouse/incremental/legacy.rb +75 -0
- data/lib/lighthouse/incremental/multipart.rb +76 -0
- data/lib/lighthouse/incremental/plan.rb +249 -0
- data/lib/lighthouse/incremental/rules.rb +116 -0
- data/lib/lighthouse/incremental/run.rb +302 -0
- data/lib/lighthouse/incremental/serializer.rb +37 -0
- data/lib/lighthouse/incremental/state.rb +204 -0
- data/lib/lighthouse/incremental/stream_directive.rb +41 -0
- data/lib/lighthouse/incremental/stream_trace.rb +93 -0
- data/lib/lighthouse/incremental/tree.rb +68 -0
- data/lib/lighthouse/namespaces.rb +2 -0
- data/lib/lighthouse/nested_mutations/belongs_to_operations.rb +2 -2
- data/lib/lighthouse/operations.rb +6 -2
- data/lib/lighthouse/pagination.rb +61 -15
- data/lib/lighthouse/persisted_queries.rb +53 -8
- data/lib/lighthouse/rb_lighthouse.rb +34 -0
- data/lib/lighthouse/resolve_info.rb +7 -1
- data/lib/lighthouse/search/auto.rb +21 -0
- data/lib/lighthouse/search/enhancer.rb +127 -0
- data/lib/lighthouse/search/field_check.rb +171 -0
- data/lib/lighthouse/search/pg_search.rb +76 -0
- data/lib/lighthouse/search/query.rb +35 -0
- data/lib/lighthouse/search/result.rb +181 -0
- data/lib/lighthouse/search/searchkick.rb +292 -0
- data/lib/lighthouse/search/searchkick_index.rb +54 -0
- data/lib/lighthouse/search/searchkick_options.rb +74 -0
- data/lib/lighthouse/search.rb +78 -0
- data/lib/lighthouse/support/argument_walk.rb +81 -0
- data/lib/lighthouse/support/count.rb +16 -0
- data/lib/lighthouse/support/failures.rb +28 -0
- data/lib/lighthouse/support/memo.rb +72 -0
- data/lib/lighthouse/support/model_resolver.rb +24 -0
- data/lib/lighthouse/support/relations.rb +31 -0
- data/lib/lighthouse/support/soft_deletes.rb +42 -8
- data/lib/lighthouse/testing.rb +81 -0
- data/sig/lighthouse/controller.rbs +34 -1
- data/sig/lighthouse/directives.rbs +46 -5
- data/sig/lighthouse/events.rbs +7 -0
- data/sig/lighthouse/graphql.rbs +117 -0
- data/sig/lighthouse/search.rbs +132 -0
- data/sig/lighthouse.rbs +69 -1
- metadata +38 -1
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Searchkick (Elasticsearch / OpenSearch), outside the database: the filters the
|
|
4
|
+
# client sends are translated into Searchkick's `where:`, and what comes back are
|
|
5
|
+
# Active Record records in relevance order, so nested fields and the Dataloader
|
|
6
|
+
# work on them as usual. One request returns a page and the total, which is
|
|
7
|
+
# exact: Elasticsearch and OpenSearch 7+ stop counting at 10,000 unless asked
|
|
8
|
+
# (`track_total_hits`), so Lighthouse always asks, and an app's `body_options:`
|
|
9
|
+
# may not ask otherwise: totals, pages and @canQuery's check of every hit rely on it.
|
|
10
|
+
#
|
|
11
|
+
# The records load through the database with the filters the engine applied
|
|
12
|
+
# that it can apply too (@trashed's, and @eq's on a column of the model), so an
|
|
13
|
+
# index that lags the database may leave a record out, never answer one that no
|
|
14
|
+
# longer matches.
|
|
15
|
+
#
|
|
16
|
+
# `within:` names the index (`index_name:`), the model's own by default.
|
|
17
|
+
#
|
|
18
|
+
# Searchkick indexes what the model's `search_data` says. For @trashed the
|
|
19
|
+
# model must index its soft-delete column, the one Support::SoftDeletes filters
|
|
20
|
+
# the database on (paranoia's, discard's, Config.soft_deletes', else `deleted_at`),
|
|
21
|
+
# the one source of it: ONLY keeps the records with a value in it
|
|
22
|
+
# (other than paranoia's sentinel), WITHOUT the ones without, and WITH both, if
|
|
23
|
+
# the index holds trashed records at all.
|
|
24
|
+
# Searchkick loads what it finds through the model, whose default scope may hide
|
|
25
|
+
# trashed records (paranoia's): with ONLY and WITH they load past it.
|
|
26
|
+
#
|
|
27
|
+
# The records load through the app's own `scope_results:` (from @builder) first,
|
|
28
|
+
# then Lighthouse's: the model's default scope (with `unscope: true` too), its
|
|
29
|
+
# `search_results` scope, if it has one (Lighthouse::Search), and the filters
|
|
30
|
+
# above. An @builder sets only the options that rank or shape the hits
|
|
31
|
+
# (Searchkick::Options), never what loads, pages or counts them.
|
|
32
|
+
#
|
|
33
|
+
# The gem is not a dependency of Lighthouse: the adapter is used when the
|
|
34
|
+
# model calls `searchkick`.
|
|
35
|
+
class Lighthouse::Search::Searchkick
|
|
36
|
+
DEFAULT_TRASHED_COLUMN = 'deleted_at'
|
|
37
|
+
|
|
38
|
+
# The result window of a model with `searchkick deep_paging: true`, as Searchkick sets it.
|
|
39
|
+
DEEP_PAGING_WINDOW = 1_000_000_000
|
|
40
|
+
|
|
41
|
+
# `index`: what the engine tells of an index (Searchkick::Index), read and kept.
|
|
42
|
+
def initialize(index: Lighthouse::Search::Searchkick::Index.new)
|
|
43
|
+
@per_model = Lighthouse::Support::Memo.new
|
|
44
|
+
@index = index
|
|
45
|
+
end
|
|
46
|
+
|
|
47
|
+
def searchable?(model, _index = nil)
|
|
48
|
+
!!(defined?(::Searchkick) && model.respond_to?(:searchkick_index))
|
|
49
|
+
end
|
|
50
|
+
|
|
51
|
+
def relational? = false
|
|
52
|
+
|
|
53
|
+
# [one entry per hit at `offset`, `limit` of them, in relevance order: the
|
|
54
|
+
# record, or nil for a hit that did not load; the total that match].
|
|
55
|
+
def page(query, offset:, limit:)
|
|
56
|
+
response = query.model.searchkick_search(query.term, **search_options(query), offset: offset, limit: limit)
|
|
57
|
+
exact_total!(query, response)
|
|
58
|
+
[entries(response), response.total_count]
|
|
59
|
+
rescue StandardError => e
|
|
60
|
+
raise unless past_window?(e)
|
|
61
|
+
|
|
62
|
+
# The index's window is smaller than the model's options say: set on the server.
|
|
63
|
+
raise ::GraphQL::ExecutionError, "The search reads no further than the index.max_result_window of #{query.model.name}. Narrow the search instead."
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# How many of the matches the index the search reads pages through
|
|
67
|
+
# (Search::Result): its index.max_result_window, read from the engine
|
|
68
|
+
# (Searchkick::Index). When the settings cannot be read, the model's own index
|
|
69
|
+
# takes the window its options set (`max_result_window:`, in `searchkick` or
|
|
70
|
+
# its index `settings:`, whatever their keys; a billion with `deep_paging:
|
|
71
|
+
# true`), and any index the engines' default, 10,000.
|
|
72
|
+
def result_window(query)
|
|
73
|
+
@index.result_window(query.model, index_name(query)) ||
|
|
74
|
+
(own_index?(query) && options_window(query.model)) || Lighthouse::Search::Result::MAX_WINDOW
|
|
75
|
+
end
|
|
76
|
+
|
|
77
|
+
# Why the model cannot be searched as it is, or nil: a default scope (a
|
|
78
|
+
# tenant's, a soft delete's; any, as declared, since what one selects may
|
|
79
|
+
# depend on the request), a search_results scope, or the type condition of an
|
|
80
|
+
# STI subclass that searches its parent's index without Searchkick's
|
|
81
|
+
# `inheritance: true` (which filters the engine by type), needs `search_where`,
|
|
82
|
+
# the engine's `where:` for the same records (`{}` when they narrow nothing).
|
|
83
|
+
# Without it the engine would count, and page through, records that do not
|
|
84
|
+
# load: its totals would include other tenants' matches.
|
|
85
|
+
# Search::FieldCheck asks when the schema is built; a search asks too.
|
|
86
|
+
def model_error(model)
|
|
87
|
+
return nil if model.respond_to?(:search_where)
|
|
88
|
+
|
|
89
|
+
narrowing = narrowing(model)
|
|
90
|
+
return nil unless narrowing
|
|
91
|
+
|
|
92
|
+
"#{narrowing} narrows what a search loads, which the engine does not apply: its totals and pages would count records that " \
|
|
93
|
+
"do not load. Define #{model.name}.search_where, the engine's `where:` for the same records (`{ tenant_id: Current.tenant_id }`), " \
|
|
94
|
+
'or `{}` when the index holds no other'
|
|
95
|
+
end
|
|
96
|
+
|
|
97
|
+
private
|
|
98
|
+
|
|
99
|
+
# What narrows the records a search of the model loads, which the engine does not apply; nil when nothing does.
|
|
100
|
+
def narrowing(model)
|
|
101
|
+
return "#{model.name}'s default scope" if Lighthouse::Support::Relations.default_scope?(model)
|
|
102
|
+
return "#{model.name}.search_results" if Lighthouse::Search.results_scope?(model)
|
|
103
|
+
|
|
104
|
+
"#{model.name}'s STI type, in #{model.base_class.name}'s index without `inheritance: true`," if untyped_subclass?(model)
|
|
105
|
+
end
|
|
106
|
+
|
|
107
|
+
# An STI subclass (its relation has a type condition) whose index Searchkick
|
|
108
|
+
# does not filter by type (`searchkick inheritance: true`).
|
|
109
|
+
def untyped_subclass?(model)
|
|
110
|
+
model.respond_to?(:finder_needs_type_condition?) && model.finder_needs_type_condition? &&
|
|
111
|
+
!searchkick_option(model, :inheritance)
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
def searchkick_option(model, name) = ::ActiveSupport::HashWithIndifferentAccess.new(model.searchkick_options)[name]
|
|
115
|
+
|
|
116
|
+
# The response's records in their hits' places, nil where one did not load. A
|
|
117
|
+
# record is placed by its hit's index and id, as hits of two indices (Searchkick's
|
|
118
|
+
# `models:`, an `index_name:` list) may share an id.
|
|
119
|
+
def entries(response)
|
|
120
|
+
return response.to_a unless response.respond_to?(:with_hit) && response.respond_to?(:hits)
|
|
121
|
+
|
|
122
|
+
loaded = response.with_hit.to_h { |record, hit| [hit_key(hit), record] }
|
|
123
|
+
response.hits.map { |hit| loaded[hit_key(hit)] }
|
|
124
|
+
end
|
|
125
|
+
|
|
126
|
+
def hit_key(hit) = [hit['_index'], hit['_id'].to_s]
|
|
127
|
+
|
|
128
|
+
# The total must be every match: a total the engine stopped counting at
|
|
129
|
+
# (`"relation": "gte"`) would let a page, or @canQuery's check, miss records.
|
|
130
|
+
def exact_total!(query, response)
|
|
131
|
+
raw = response.response if response.respond_to?(:response)
|
|
132
|
+
total = raw.to_h.dig('hits', 'total') if raw.respond_to?(:to_h)
|
|
133
|
+
return unless total.is_a?(Hash) && total['relation'] && total['relation'] != 'eq'
|
|
134
|
+
|
|
135
|
+
raise Lighthouse::DefinitionError,
|
|
136
|
+
"@search on #{query.model.name}: the engine counted #{total['relation']} #{total['value']} matches, not every one, " \
|
|
137
|
+
'which totals, pages and @canQuery need (track_total_hits)'
|
|
138
|
+
end
|
|
139
|
+
|
|
140
|
+
# Does the search read the model's own index, whose settings the model tells?
|
|
141
|
+
def own_index?(query) = query.index.nil? || query.index == query.model.searchkick_index&.name
|
|
142
|
+
|
|
143
|
+
def index_name(query) = query.index || query.model.searchkick_index&.name
|
|
144
|
+
|
|
145
|
+
# The window the model's options set, or nil.
|
|
146
|
+
def options_window(model)
|
|
147
|
+
options = ::ActiveSupport::HashWithIndifferentAccess.new(model.searchkick_options)
|
|
148
|
+
settings = options[:settings] || {}
|
|
149
|
+
options[:max_result_window] || settings.dig(:index, :max_result_window) || settings[:'index.max_result_window'] ||
|
|
150
|
+
(DEEP_PAGING_WINDOW if options[:deep_paging])
|
|
151
|
+
end
|
|
152
|
+
|
|
153
|
+
def past_window?(error)
|
|
154
|
+
defined?(::Searchkick::InvalidQueryError) && error.is_a?(::Searchkick::InvalidQueryError) && error.message.include?('max_result_window')
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def search_options(query)
|
|
158
|
+
options = Lighthouse::Search::Searchkick::Options.builder!(query)
|
|
159
|
+
wheres = query.wheres.map { |column, value| { column => value } }
|
|
160
|
+
options[:where] = all_of(options[:where], engine_where(query), *wheres, trashed_filter(query))
|
|
161
|
+
options[:index_name] = query.index if query.index
|
|
162
|
+
options[:load] = true
|
|
163
|
+
options[:body_options] = Lighthouse::Search::Searchkick::Options.counting(options)
|
|
164
|
+
loading = results_scope(query, options[:scope_results])
|
|
165
|
+
options[:scope_results] = loading if loading
|
|
166
|
+
options
|
|
167
|
+
end
|
|
168
|
+
|
|
169
|
+
# What Searchkick loads the records it found through (`scope_results:`): the
|
|
170
|
+
# app's own first, then what Lighthouse narrows them to, last, so nothing
|
|
171
|
+
# widens it: the model's default scope when the model loads `unscope: true`
|
|
172
|
+
# (Searchkick loads through `unscoped`), the filters the engine applied that the
|
|
173
|
+
# database can apply too (@trashed's, the @eq ones on a column of the model,
|
|
174
|
+
# with a plain value), so a record the index holds as it was no longer matches,
|
|
175
|
+
# and the model's `search_results` scope; nil for the model alone.
|
|
176
|
+
def results_scope(query, own)
|
|
177
|
+
wheres = Lighthouse::Search::Searchkick::Options.database_wheres(query)
|
|
178
|
+
return own unless own || narrows_load?(query, wheres)
|
|
179
|
+
|
|
180
|
+
->(records) { load_through(own ? own.call(records) : records.all, query, wheres) }
|
|
181
|
+
end
|
|
182
|
+
|
|
183
|
+
def load_through(records, query, wheres)
|
|
184
|
+
records = records.merge(query.model.all) if searchkick_option(query.model, :unscope)
|
|
185
|
+
records = Lighthouse::Support::SoftDeletes.filter(records, query.trashed.to_s) if query.trashed
|
|
186
|
+
records = wheres.reduce(records) { |narrowed, (column, value)| narrowed.where(column => value) }
|
|
187
|
+
Lighthouse::Search.results(records)
|
|
188
|
+
end
|
|
189
|
+
|
|
190
|
+
def narrows_load?(query, wheres)
|
|
191
|
+
searchkick_option(query.model, :unscope) || query.trashed || wheres.any? || Lighthouse::Search.results_scope?(query.model)
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
# The model's search_where, the engine's `where:` for what its default scope and
|
|
195
|
+
# search_results keep, which must leave the soft-delete column to Lighthouse
|
|
196
|
+
# (trashed_filter): a condition on it in search_where could not yield to @trashed.
|
|
197
|
+
def engine_where(query)
|
|
198
|
+
model = query.model
|
|
199
|
+
where = (model.search_where if model.respond_to?(:search_where)).to_h
|
|
200
|
+
column = Lighthouse::Support::SoftDeletes.supported?(model) && trashed_column(model).first.to_s
|
|
201
|
+
return where unless column && names?(where, column)
|
|
202
|
+
|
|
203
|
+
raise Lighthouse::DefinitionError,
|
|
204
|
+
"#{model.name}.search_where names #{column}, the column @trashed and Lighthouse filter trashed records on: leave it out"
|
|
205
|
+
end
|
|
206
|
+
|
|
207
|
+
# Does the engine condition name `column`, at any depth (`_and`, `_or`, `_not`)?
|
|
208
|
+
def names?(condition, column)
|
|
209
|
+
case condition
|
|
210
|
+
when Hash then condition.any? { |key, value| key.to_s == column || names?(value, column) }
|
|
211
|
+
when Array then condition.any? { |each| names?(each, column) }
|
|
212
|
+
else false
|
|
213
|
+
end
|
|
214
|
+
end
|
|
215
|
+
|
|
216
|
+
# The conditions as one Searchkick `where:`, all of which hold: the app's
|
|
217
|
+
# (@builder), the @eq ones, @trashed's. Their keys are read alike, symbols or
|
|
218
|
+
# strings; conditions on different keys merge, and ones on a key more than one
|
|
219
|
+
# names are ANDed (Searchkick's `_and`), never overwritten.
|
|
220
|
+
def all_of(*conditions)
|
|
221
|
+
conditions = conditions.compact.map { |condition| condition.to_h.transform_keys(&:to_sym) }.reject(&:empty?)
|
|
222
|
+
keys = conditions.flat_map(&:keys)
|
|
223
|
+
keys.uniq.size == keys.size ? conditions.reduce({}, :merge) : { _and: conditions }
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
# @trashed's condition; without one, the records that are not trashed when the
|
|
227
|
+
# model's default scope hides the others (paranoia's), as they would not load.
|
|
228
|
+
# That one needs the index to hold the column only when it can be told: on an
|
|
229
|
+
# index without it, `WITHOUT` matches every hit, and the load still leaves the
|
|
230
|
+
# trashed records out.
|
|
231
|
+
def trashed_filter(query)
|
|
232
|
+
trashed = query.trashed || (:without if hides_trashed?(query.model))
|
|
233
|
+
return {} if trashed.nil? || trashed == :with # no filter: the index need not hold the column
|
|
234
|
+
|
|
235
|
+
column, kept = trashed_column(query.model)
|
|
236
|
+
require_indexed!(query, column, told: query.trashed.nil?)
|
|
237
|
+
trashed == :only ? { column.to_sym => { not: kept } } : { column.to_sym => kept }
|
|
238
|
+
end
|
|
239
|
+
|
|
240
|
+
# Does the model's default scope leave its trashed records out?
|
|
241
|
+
def hides_trashed?(model)
|
|
242
|
+
Lighthouse::Support::SoftDeletes.supported?(model) &&
|
|
243
|
+
!Lighthouse::Support::Relations.same_records?(model.all, Lighthouse::Support::SoftDeletes.with_trashed(model.all))
|
|
244
|
+
end
|
|
245
|
+
|
|
246
|
+
# [the indexed column that marks trashed records, its value for the others]:
|
|
247
|
+
# the soft-delete adapter's (paranoia's, with its sentinel; discard's;
|
|
248
|
+
# Config.soft_deletes'), which the database filters and the records load
|
|
249
|
+
# through too; deleted_at when an app's adapter does not tell.
|
|
250
|
+
def trashed_column(model)
|
|
251
|
+
[Lighthouse::Support::SoftDeletes.column(model) || DEFAULT_TRASHED_COLUMN, Lighthouse::Support::SoftDeletes.kept_value(model)]
|
|
252
|
+
end
|
|
253
|
+
|
|
254
|
+
# The index must hold the column, or the filter would match nothing (or everything).
|
|
255
|
+
# The model's search_data tells for its own index, the engine's mapping for any
|
|
256
|
+
# other `within:` names (or when search_data cannot run on a blank record). It
|
|
257
|
+
# fails closed: when the columns cannot be told, the search is refused too,
|
|
258
|
+
# naming why the mapping could not be read; unless `told` (Lighthouse's own
|
|
259
|
+
# filter, which holds either way) lets it go on.
|
|
260
|
+
def require_indexed!(query, column, told: false)
|
|
261
|
+
model = query.model
|
|
262
|
+
indexed = (indexed_columns(model) if own_index?(query)) || @index.fields(model, index_name(query))
|
|
263
|
+
return if indexed.nil? && told
|
|
264
|
+
|
|
265
|
+
unless indexed
|
|
266
|
+
raise ::GraphQL::ExecutionError,
|
|
267
|
+
"@trashed cannot tell whether #{index_label(query)} holds #{column}, which it filters the search on: " \
|
|
268
|
+
"#{model.name}#search_data does not run on a blank record, and the index's mapping cannot be read#{mapping_failure(query)}."
|
|
269
|
+
end
|
|
270
|
+
return if indexed.include?(column.to_s)
|
|
271
|
+
|
|
272
|
+
raise ::GraphQL::ExecutionError, "#{index_label(query)} does not hold #{column}, which @trashed filters the search on: add it to search_data."
|
|
273
|
+
end
|
|
274
|
+
|
|
275
|
+
def index_label(query) = own_index?(query) ? "#{query.model.name}'s index" : "the index #{query.index}"
|
|
276
|
+
|
|
277
|
+
# Why the engine did not answer the index's mapping, and the privilege reading it needs.
|
|
278
|
+
def mapping_failure(query)
|
|
279
|
+
error = @index.failure(:mapping, query.model, index_name(query))
|
|
280
|
+
" (#{error.class}: #{error.message}; reading it needs the view_index_metadata privilege on the index)" if error
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
# What `search_data` holds, or nil when it cannot run on a blank record, read
|
|
284
|
+
# once per model class.
|
|
285
|
+
def indexed_columns(model)
|
|
286
|
+
@per_model.get([:indexed_columns, model.name], model) do
|
|
287
|
+
model.new.search_data.keys.map(&:to_s)
|
|
288
|
+
rescue StandardError
|
|
289
|
+
nil
|
|
290
|
+
end
|
|
291
|
+
end
|
|
292
|
+
end
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# What the engine tells of an index that Search::Searchkick needs: the fields
|
|
4
|
+
# its mapping holds (@trashed's column) and its index.max_result_window. Each is
|
|
5
|
+
# read from the engine once per INDEX_READ_TTL seconds per model class and
|
|
6
|
+
# index, since a reindex changes them, by one thread at a time (Support::Memo):
|
|
7
|
+
# however many requests ask, the engine is asked once in that time. A read that
|
|
8
|
+
# fails is reported to Config.on_error and kept FAILED_READ_TTL seconds, its
|
|
9
|
+
# error at hand (`failure`) for the errors that need it. Reading them needs the
|
|
10
|
+
# `view_index_metadata` privilege on the index (`monitor` for OpenSearch's
|
|
11
|
+
# settings).
|
|
12
|
+
class Lighthouse::Search::Searchkick::Index
|
|
13
|
+
INDEX_READ_TTL = 60
|
|
14
|
+
FAILED_READ_TTL = 5
|
|
15
|
+
|
|
16
|
+
# `clock`: seconds, monotonic.
|
|
17
|
+
def initialize(clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
|
|
18
|
+
@reads = Lighthouse::Support::Memo.new(ttl: INDEX_READ_TTL, failed_ttl: FAILED_READ_TTL, clock: clock,
|
|
19
|
+
on_failure: ->(error) { Lighthouse::Config.handle_error(error, nil) })
|
|
20
|
+
end
|
|
21
|
+
|
|
22
|
+
# The fields the index `name` holds, or nil when its mapping cannot be read (no
|
|
23
|
+
# index yet, no privilege). A field every document leaves null has no mapping yet.
|
|
24
|
+
def fields(model, name)
|
|
25
|
+
@reads.get([:mapping, model.name, name], model) do
|
|
26
|
+
next nil unless client
|
|
27
|
+
|
|
28
|
+
client.indices.get_mapping(index: name).to_h.values.flat_map { |mapping| mapping.dig('mappings', 'properties')&.keys || [] }
|
|
29
|
+
end
|
|
30
|
+
end
|
|
31
|
+
|
|
32
|
+
# The index's max_result_window: the smallest of an alias's indices, the engines'
|
|
33
|
+
# default (Search::Result::MAX_WINDOW) for one that sets none; nil when its
|
|
34
|
+
# settings cannot be read.
|
|
35
|
+
def result_window(model, name)
|
|
36
|
+
@reads.get([:window, model.name, name], model) do
|
|
37
|
+
next nil unless client
|
|
38
|
+
|
|
39
|
+
windows = client.indices.get_settings(index: name).to_h.values.map do |index|
|
|
40
|
+
index.dig('settings', 'index', 'max_result_window')
|
|
41
|
+
end
|
|
42
|
+
windows.map { |window| window ? Integer(window) : Lighthouse::Search::Result::MAX_WINDOW }.min
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# Why the last read of the index's `:mapping` or `:window` failed, while that is
|
|
47
|
+
# kept; nil when it did not.
|
|
48
|
+
def failure(kind, model, name) = @reads.failure([kind, model.name, name], model)
|
|
49
|
+
|
|
50
|
+
private
|
|
51
|
+
|
|
52
|
+
# Searchkick's client; nil for a Searchkick that has none to ask (the suite's).
|
|
53
|
+
def client = (::Searchkick.client if ::Searchkick.respond_to?(:client))
|
|
54
|
+
end
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# What an @builder may ask of Searchkick's search (`query.options`), and which
|
|
4
|
+
# of the engine's conditions the database applies alike (Search::Searchkick).
|
|
5
|
+
module Lighthouse::Search::Searchkick::Options
|
|
6
|
+
module_function
|
|
7
|
+
|
|
8
|
+
# The options of Searchkick's `search` an @builder on an argument may set
|
|
9
|
+
# (`query.options`): what ranks, highlights or aggregates the hits, never what
|
|
10
|
+
# loads them, pages them or counts them (`load:`, `index_name:`, `models:`,
|
|
11
|
+
# `unscope:`, `page:`, `body:`, ...), which Lighthouse sets. `where:` and
|
|
12
|
+
# `scope_results:` compose with Lighthouse's own.
|
|
13
|
+
BUILDER_OPTIONS = %i[
|
|
14
|
+
fields match operator where order boost_by boost_where boost_by_distance boost_by_recency indices_boost
|
|
15
|
+
misspellings highlight aggs smart_aggs emoji exclude conversions conversions_term explain debug
|
|
16
|
+
includes model_includes scope_results body_options timeout
|
|
17
|
+
].freeze
|
|
18
|
+
|
|
19
|
+
# The keys of `body_options:` an @builder may set: none that replaces the query,
|
|
20
|
+
# its paging or its count (`query`, `size`, `from`, `track_total_hits`, `terminate_after`, ...).
|
|
21
|
+
BODY_OPTIONS = %i[min_score explain profile timeout].freeze
|
|
22
|
+
|
|
23
|
+
# The values the database compares a column with as the engine does: a
|
|
24
|
+
# scalar, a list of them, a Range of them (BETWEEN). Not an engine operator
|
|
25
|
+
# (`{ gt: 3 }`) nor a Regexp, which are the index's alone.
|
|
26
|
+
SQL_SCALARS = [String, Symbol, Numeric, TrueClass, FalseClass, NilClass, Date, Time].freeze
|
|
27
|
+
|
|
28
|
+
# The options an @builder set (query.options), which must be BUILDER_OPTIONS,
|
|
29
|
+
# their keys read alike, symbols or strings.
|
|
30
|
+
def builder!(query)
|
|
31
|
+
options = query.options.to_h.transform_keys(&:to_sym)
|
|
32
|
+
refused = options.keys - BUILDER_OPTIONS
|
|
33
|
+
return options if refused.empty?
|
|
34
|
+
|
|
35
|
+
raise Lighthouse::DefinitionError,
|
|
36
|
+
"@search: an @builder may not set #{refused.map { |key| "`#{key}:`" }.join(', ')} of Searchkick's search, which decide " \
|
|
37
|
+
"what loads, how it pages or what it counts, and which Lighthouse sets; it may set #{BUILDER_OPTIONS.join(', ')}"
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
# The app's body_options (BODY_OPTIONS), and track_total_hits: true, which they may not set.
|
|
41
|
+
def counting(options)
|
|
42
|
+
body = (options[:body_options] || {}).to_h.transform_keys(&:to_sym)
|
|
43
|
+
if body.key?(:track_total_hits)
|
|
44
|
+
raise Lighthouse::DefinitionError,
|
|
45
|
+
'@search: Lighthouse asks the engine to count every match (track_total_hits: true), which totals, pages and ' \
|
|
46
|
+
"@canQuery's check of every hit rely on: body_options cannot set track_total_hits"
|
|
47
|
+
end
|
|
48
|
+
refused = body.keys - BODY_OPTIONS
|
|
49
|
+
unless refused.empty?
|
|
50
|
+
raise Lighthouse::DefinitionError,
|
|
51
|
+
"@search: body_options may not set #{refused.join(', ')}, which would replace the search's query, paging or count; " \
|
|
52
|
+
"it may set #{BODY_OPTIONS.join(', ')}"
|
|
53
|
+
end
|
|
54
|
+
body.merge(track_total_hits: true)
|
|
55
|
+
end
|
|
56
|
+
|
|
57
|
+
# The engine conditions the database applies alike: a column of the model, and a
|
|
58
|
+
# value the database compares as the engine does (SQL_SCALARS: a scalar, a list
|
|
59
|
+
# or a Range of them).
|
|
60
|
+
def database_wheres(query)
|
|
61
|
+
columns = query.model.column_names
|
|
62
|
+
query.wheres.select { |column, value| columns.include?(column) && sql_value?(value) }
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
def sql_value?(value)
|
|
66
|
+
case value
|
|
67
|
+
when Array then value.all? { |each| scalar?(each) }
|
|
68
|
+
when Range then scalar?(value.begin) && scalar?(value.end)
|
|
69
|
+
else scalar?(value)
|
|
70
|
+
end
|
|
71
|
+
end
|
|
72
|
+
|
|
73
|
+
def scalar?(value) = SQL_SCALARS.any? { |kind| value.is_a?(kind) }
|
|
74
|
+
end
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# Full-text search behind one seam, for @search. Laravel Scout is the abstraction
|
|
4
|
+
# PHP Lighthouse has; Ruby has two gems, so an adapter stands between the
|
|
5
|
+
# directives and the engine. It answers:
|
|
6
|
+
#
|
|
7
|
+
# searchable?(model, index = nil) can this model be searched (within the scope or index `index` names)?
|
|
8
|
+
# relational? is the search a scope on the model's relation (pg_search)?
|
|
9
|
+
# scope(relation, query) relational: the relation narrowed to the matches, ranked
|
|
10
|
+
# page(query, offset:, limit:) otherwise: [records, total] of the engine's response
|
|
11
|
+
#
|
|
12
|
+
# `query` is a Search::Query. A relational adapter lets every other directive of
|
|
13
|
+
# the field apply on top of the scope; the others (Searchkick) answer on their own
|
|
14
|
+
# and take only the directives that include Contracts::SearchBuilder. The
|
|
15
|
+
# protocol is experimental until both adapters have shipped.
|
|
16
|
+
#
|
|
17
|
+
# The adapter is detected per model (Search::Auto): Searchkick, then pg_search.
|
|
18
|
+
# `Config.search` replaces the detection with one adapter, or the app's own.
|
|
19
|
+
#
|
|
20
|
+
# A model's `search_results` scope, when it has one, is what a search of it may
|
|
21
|
+
# return, checked in the database: pg_search applies it to the search, Searchkick
|
|
22
|
+
# loads the records it finds through it (`scope_results:`), so a record an index
|
|
23
|
+
# not yet updated still holds is not returned.
|
|
24
|
+
module Lighthouse::Search
|
|
25
|
+
RESULTS_SCOPE = :search_results
|
|
26
|
+
|
|
27
|
+
module_function
|
|
28
|
+
|
|
29
|
+
# The adapter in use: Config.search, else the detecting one.
|
|
30
|
+
def adapter
|
|
31
|
+
Lighthouse::Config.search || (@default ||= Lighthouse::Search::Auto.new)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# The adapter that searches `model`, or nil.
|
|
35
|
+
def adapter_for(model, index = nil)
|
|
36
|
+
adapter = self.adapter
|
|
37
|
+
return adapter.adapter_for(model, index) if adapter.respond_to?(:adapter_for)
|
|
38
|
+
|
|
39
|
+
adapter if adapter.searchable?(model, index)
|
|
40
|
+
end
|
|
41
|
+
|
|
42
|
+
# Does the model have a `search_results` scope?
|
|
43
|
+
def results_scope?(model) = model.respond_to?(RESULTS_SCOPE)
|
|
44
|
+
|
|
45
|
+
# The relation through the model's `search_results` scope, if it has one.
|
|
46
|
+
def results(relation)
|
|
47
|
+
results_scope?(relation.klass) ? relation.public_send(RESULTS_SCOPE) : relation
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
# [path, @search directive node] for every argument and input field of the
|
|
51
|
+
# field carrying @search, at any depth (Support::ArgumentWalk). Walked once per
|
|
52
|
+
# field (Support::Memo.on), the first time it is asked (Search::FieldCheck,
|
|
53
|
+
# when the schema is built).
|
|
54
|
+
def directives(field_def)
|
|
55
|
+
Lighthouse::Support::Memo.on(field_def, :searches) do
|
|
56
|
+
walk = Lighthouse::Support::ArgumentWalk
|
|
57
|
+
walk.field_definitions(field_def).flat_map do |path, argument|
|
|
58
|
+
walk.directives(argument).select { |d| d.name == 'search' }.map { |dnode| [path, dnode] }
|
|
59
|
+
end.freeze
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
# The field's own query constraints an engine outside the database cannot apply
|
|
64
|
+
# ("`scopes:`" of its resolving directive `directive`, "@builder", "@whereAuth",
|
|
65
|
+
# "@orderBy"): Search::FieldCheck refuses them when the schema is built, and
|
|
66
|
+
# BaseDirectiveResolver as a search runs, for a field whose model the build
|
|
67
|
+
# could not tell. Worked out once per field and directive.
|
|
68
|
+
def dropped_constraints(field_def, directive)
|
|
69
|
+
Lighthouse::Support::Memo.on(field_def, :dropped_constraints) { {}.compare_by_identity }[directive] ||= begin
|
|
70
|
+
scopes = Lighthouse::Support::DirectiveArgs.literal(directive, 'scopes') if directive
|
|
71
|
+
queries = Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.query_directives(field_def.ast_node)
|
|
72
|
+
((scopes.present? ? ['`scopes:`'] : []) + queries.map { |query| "@#{query.name}" }).freeze
|
|
73
|
+
end
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
# Does the field have an argument or input field with @search?
|
|
77
|
+
def searching?(field_def) = directives(field_def).any?
|
|
78
|
+
end
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# The one walk through a field's arguments and the fields of the input types they
|
|
4
|
+
# take, so what is found when the schema is built (Search::FieldCheck, the
|
|
5
|
+
# @canModel on arguments) and when a query runs (BaseDirectiveResolver's argument
|
|
6
|
+
# builders) is the same: graphql-ruby's argument definitions, in SDL order, and the
|
|
7
|
+
# directives the SDL puts on each.
|
|
8
|
+
module Lighthouse::Support::ArgumentWalk
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# The directives the SDL puts on an argument or input field.
|
|
12
|
+
def directives(argument) = argument.ast_node&.directives || []
|
|
13
|
+
|
|
14
|
+
# The fields of the input type an argument takes, by name; none for another type.
|
|
15
|
+
def input_fields(argument)
|
|
16
|
+
type = argument.type.unwrap
|
|
17
|
+
type.kind.input_object? ? type.arguments : {}
|
|
18
|
+
end
|
|
19
|
+
|
|
20
|
+
# Does the argument take a list (of input objects, say)?
|
|
21
|
+
def list?(argument)
|
|
22
|
+
(argument.type.non_null? ? argument.type.of_type : argument.type).list?
|
|
23
|
+
end
|
|
24
|
+
|
|
25
|
+
# Support::ArgumentWalk.definitions of a field's arguments, walked once per
|
|
26
|
+
# field when the schema is built (for its searches and its @canModel), and kept
|
|
27
|
+
# on the field: a schema built again on reload starts afresh.
|
|
28
|
+
def field_definitions(field_def)
|
|
29
|
+
return field_def.instance_variable_get(:@lighthouse_argument_walk) if field_def.instance_variable_defined?(:@lighthouse_argument_walk)
|
|
30
|
+
|
|
31
|
+
field_def.instance_variable_set(:@lighthouse_argument_walk, definitions(field_def.arguments).freeze)
|
|
32
|
+
end
|
|
33
|
+
|
|
34
|
+
# [dot path ("filter.trashed", "inputs.*.status"), argument] for every argument
|
|
35
|
+
# and input field, at any depth, each before the fields of its input type; `*`
|
|
36
|
+
# steps into each of a list. An input type is not walked twice on one path.
|
|
37
|
+
def definitions(arguments, prefix = nil, seen = Set.new)
|
|
38
|
+
arguments.each_value.flat_map do |argument|
|
|
39
|
+
path = [prefix, argument.graphql_name].compact.join('.')
|
|
40
|
+
type_name = argument.type.unwrap.graphql_name
|
|
41
|
+
nested = seen.include?(type_name) ? {} : input_fields(argument)
|
|
42
|
+
[[path, argument], *definitions(nested, list?(argument) ? "#{path}.*" : path, seen | [type_name])]
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
|
|
46
|
+
# [path, argument] for every argument and input field that holds a value when
|
|
47
|
+
# the client sends none for it, as graphql-ruby fills defaults in: an omitted
|
|
48
|
+
# argument's default value; within an input object, the value its default
|
|
49
|
+
# literal gives a field, else the field's own default. An input object holds
|
|
50
|
+
# values when a default gives it, or when the client must send it (non-null,
|
|
51
|
+
# no default): its fields' defaults apply then. A field's default under a
|
|
52
|
+
# parent the client may leave out applies only when the client sends the parent.
|
|
53
|
+
# `literal`: what a default gives this level (by GraphQL name); nil at the top.
|
|
54
|
+
def implicit(arguments, literal = nil, prefix = nil, seen = Set.new)
|
|
55
|
+
arguments.each_value.flat_map do |argument|
|
|
56
|
+
name = argument.graphql_name
|
|
57
|
+
path = [prefix, name].compact.join('.')
|
|
58
|
+
value = literal&.key?(name) ? literal[name] : (argument.default_value if argument.default_value?)
|
|
59
|
+
[*([[path, argument]] unless value.nil?), *implicit_fields(argument, value, path, seen)]
|
|
60
|
+
end
|
|
61
|
+
end
|
|
62
|
+
|
|
63
|
+
def implicit_fields(argument, value, path, seen)
|
|
64
|
+
type_name = argument.type.unwrap.graphql_name
|
|
65
|
+
fields = input_fields(argument)
|
|
66
|
+
return [] if fields.empty? || seen.include?(type_name)
|
|
67
|
+
|
|
68
|
+
prefix = list?(argument) ? "#{path}.*" : path
|
|
69
|
+
implicit_objects(argument, value).flat_map { |object| implicit(fields, object, prefix, seen | [type_name]) }
|
|
70
|
+
end
|
|
71
|
+
private_class_method :implicit_fields
|
|
72
|
+
|
|
73
|
+
# The input objects an argument holds without the client: those its value
|
|
74
|
+
# gives, else an empty one the client must send (non-null, no default).
|
|
75
|
+
def implicit_objects(argument, value)
|
|
76
|
+
return argument.type.non_null? ? [{}] : [] if value.nil?
|
|
77
|
+
|
|
78
|
+
(value.is_a?(Array) ? value : [value]).grep(Hash)
|
|
79
|
+
end
|
|
80
|
+
private_class_method :implicit_objects
|
|
81
|
+
end
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# A count a setting holds (Config.defer_max_nested_fields, defer_max_execution_ms): an Integer
|
|
4
|
+
# of 0 or more, or a String of digits (as ENV holds one) read as its number; anything else
|
|
5
|
+
# raises ArgumentError as the setting is assigned, not as a request runs.
|
|
6
|
+
module Lighthouse::Support::Count
|
|
7
|
+
module_function
|
|
8
|
+
|
|
9
|
+
# `value` as the setting `name` holds it; nil (the setting's default) as it is.
|
|
10
|
+
def read(name, value)
|
|
11
|
+
value = Integer(value.strip, 10) if value.is_a?(String) && value.strip.match?(/\A\d+\z/)
|
|
12
|
+
return value if value.nil? || (value.is_a?(Integer) && !value.negative?)
|
|
13
|
+
|
|
14
|
+
raise ArgumentError, "Lighthouse::Config.#{name} must be an Integer of 0 or more, got #{value.inspect}."
|
|
15
|
+
end
|
|
16
|
+
end
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# How the work a field's directives do fails: its filters
|
|
4
|
+
# (BaseDirectiveResolver#apply_where_filters) and the engine requests a search
|
|
5
|
+
# makes (Search::Result), which may run later, as a page resolves. The same
|
|
6
|
+
# way wherever it runs, never answering the rows a failing part would have
|
|
7
|
+
# left out.
|
|
8
|
+
module Lighthouse::Support::Failures
|
|
9
|
+
module_function
|
|
10
|
+
|
|
11
|
+
# The block, failing the field when it raises. A client's error is raised as it
|
|
12
|
+
# is. A schema error found only as the query runs (a field whose model the build
|
|
13
|
+
# could not tell) is reported (Config.on_error) and the client reads it. Any
|
|
14
|
+
# other (a builder's, an engine's) is reported and raised as it is, so that the
|
|
15
|
+
# schema's rescue_from maps it, as any resolver's error; unmapped, it is
|
|
16
|
+
# graphql-ruby's.
|
|
17
|
+
def strictly(context)
|
|
18
|
+
yield
|
|
19
|
+
rescue ::GraphQL::ExecutionError
|
|
20
|
+
raise
|
|
21
|
+
rescue Lighthouse::DefinitionError => e
|
|
22
|
+
Lighthouse::Config.handle_error(e, context)
|
|
23
|
+
raise ::GraphQL::ExecutionError, e.message.end_with?('.') ? e.message : "#{e.message}."
|
|
24
|
+
rescue StandardError => e
|
|
25
|
+
Lighthouse::Config.handle_error(e, context)
|
|
26
|
+
raise
|
|
27
|
+
end
|
|
28
|
+
end
|