lighthouse-graphql 0.8.2 → 0.9.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- checksums.yaml +4 -4
- data/CHANGELOG.md +168 -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 +106 -0
- data/docs/events.md +30 -1
- data/docs/filtering-and-ordering.md +567 -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 +32 -3
- 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 +116 -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 +29 -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 +35 -0
- data/lib/lighthouse/resolve_info.rb +7 -1
- data/lib/lighthouse/schema_generator.rb +2 -0
- data/lib/lighthouse/search/auto.rb +26 -0
- data/lib/lighthouse/search/enhancer.rb +151 -0
- data/lib/lighthouse/search/field_check.rb +173 -0
- data/lib/lighthouse/search/pg_search.rb +146 -0
- data/lib/lighthouse/search/query.rb +54 -0
- data/lib/lighthouse/search/result.rb +181 -0
- data/lib/lighthouse/search/searchkick.rb +335 -0
- data/lib/lighthouse/search/searchkick_index.rb +54 -0
- data/lib/lighthouse/search/searchkick_options.rb +74 -0
- data/lib/lighthouse/search/together_check.rb +137 -0
- data/lib/lighthouse/search.rb +101 -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 +153 -0
- data/sig/lighthouse.rbs +77 -1
- metadata +39 -1
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# A search an engine outside the database answers: the page of records it found
|
|
4
|
+
# and its total, in relevance order. It is the list @paginate pages
|
|
5
|
+
# (Pagination::List), and @all reads whole. The engine is asked once per page,
|
|
6
|
+
# whose response holds the total too, so a page costs one request even when
|
|
7
|
+
# the client selects `paginatorInfo`. Each field's search is its own Result, and
|
|
8
|
+
# asks the engine itself: one is never shared between fields or requests, nor
|
|
9
|
+
# kept in the query's context. Within one resolution of a field, the search
|
|
10
|
+
# @canQuery checked serves the page (`Result.serving`), from the hits it read and
|
|
11
|
+
# checked: a record the index gains in between is never answered unchecked.
|
|
12
|
+
#
|
|
13
|
+
# The total is exact, every match counted (Search::Searchkick asks for it): pages,
|
|
14
|
+
# truncation and @canQuery's check of every hit rely on it.
|
|
15
|
+
#
|
|
16
|
+
# An engine pages no further than its result window (Elasticsearch's and
|
|
17
|
+
# OpenSearch's index.max_result_window): a window that runs past it is cut at
|
|
18
|
+
# its end, and one that starts past it is a client error. When the adapter does
|
|
19
|
+
# not know the window (`result_window` nil), the engine refuses on its own.
|
|
20
|
+
#
|
|
21
|
+
# The engine's requests fail as the field's filters do (Support::Failures),
|
|
22
|
+
# whenever they run: an engine's error is reported to Config.on_error.
|
|
23
|
+
class Lighthouse::Search::Result
|
|
24
|
+
include Lighthouse::GraphQL::Pagination::List
|
|
25
|
+
|
|
26
|
+
# The result window of an adapter that does not tell it (`result_window(query)`):
|
|
27
|
+
# Elasticsearch's and OpenSearch's default index.max_result_window.
|
|
28
|
+
MAX_WINDOW = 10_000
|
|
29
|
+
|
|
30
|
+
# The most records one read asks for, whatever the window (a billion with
|
|
31
|
+
# Searchkick's `deep_paging`): @all, and the records @canQuery checks.
|
|
32
|
+
READ_LIMIT = 10_000
|
|
33
|
+
|
|
34
|
+
# The fiber-local key of the search @canQuery checked, while the field it checks resolves.
|
|
35
|
+
CHECKED = :lighthouse_checked_search
|
|
36
|
+
|
|
37
|
+
# The block (one resolution of a field: CanQueryDirectiveResolver), in which a
|
|
38
|
+
# search of the same field (`checked`) is the `result` @canQuery read: the
|
|
39
|
+
# Enhancer answers it, whose hits serve the page. Fiber-local, so neither
|
|
40
|
+
# another field, resolving meanwhile in another fiber, nor another query sees it.
|
|
41
|
+
def self.serving(result)
|
|
42
|
+
previous = Thread.current[CHECKED]
|
|
43
|
+
Thread.current[CHECKED] = result
|
|
44
|
+
yield
|
|
45
|
+
ensure
|
|
46
|
+
Thread.current[CHECKED] = previous
|
|
47
|
+
end
|
|
48
|
+
|
|
49
|
+
# The search @canQuery checked in this resolution, when it is this one: the same
|
|
50
|
+
# field, adapter, model, term, index and conditions; else nil.
|
|
51
|
+
def self.checked(adapter, query, field)
|
|
52
|
+
checked = Thread.current[CHECKED]
|
|
53
|
+
checked if checked.is_a?(self) && checked.same_search?(adapter, query, field)
|
|
54
|
+
end
|
|
55
|
+
|
|
56
|
+
# `context`: the query's, to which the engine's errors are reported. `field`:
|
|
57
|
+
# "Type.field", whose search this is.
|
|
58
|
+
def initialize(adapter, query, context: nil, field: nil)
|
|
59
|
+
@adapter = adapter
|
|
60
|
+
@query = query
|
|
61
|
+
@context = context
|
|
62
|
+
@field = field
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
attr_reader :query
|
|
66
|
+
|
|
67
|
+
# The engine's name, for errors: Searchkick.
|
|
68
|
+
def adapter_name = @adapter.class.name.demodulize
|
|
69
|
+
|
|
70
|
+
# The records at `offset`, `limit` positions of them, within the result window:
|
|
71
|
+
# a Pagination::Window, whose records keep their engine positions. The adapter
|
|
72
|
+
# answers one entry per hit, nil for a hit that did not load (the model's
|
|
73
|
+
# scopes, a record gone from the database), so pages and cursors follow the
|
|
74
|
+
# engine's positions, and none shows a record twice.
|
|
75
|
+
def window(offset, limit)
|
|
76
|
+
return [] if limit.zero?
|
|
77
|
+
|
|
78
|
+
limit = within_window(offset, limit)
|
|
79
|
+
entries = @checked ? (@checked[offset, limit] || []) : request(offset, limit)
|
|
80
|
+
loaded = entries.each_index.reject { |index| entries[index].nil? }
|
|
81
|
+
Lighthouse::GraphQL::Pagination::Window.new(entries.compact, loaded.map { |index| offset + index }, entries.size)
|
|
82
|
+
end
|
|
83
|
+
|
|
84
|
+
# How many records match: the total the last page came with, else a request for no records.
|
|
85
|
+
def count
|
|
86
|
+
request(0, 0) unless @count
|
|
87
|
+
@count
|
|
88
|
+
end
|
|
89
|
+
|
|
90
|
+
# What @all returns: `first` records from `offset` (every one when nil), of
|
|
91
|
+
# which one read takes READ_LIMIT at most, within the result window.
|
|
92
|
+
# `truncated?` tells when that answered fewer than asked while more match.
|
|
93
|
+
def records(first: nil, offset: nil)
|
|
94
|
+
offset ||= 0
|
|
95
|
+
found = window(offset, [first || READ_LIMIT, READ_LIMIT].min)
|
|
96
|
+
read = Lighthouse::GraphQL::Pagination.covered(found)
|
|
97
|
+
@truncated = (first.nil? || read < first) && count > offset + read
|
|
98
|
+
found
|
|
99
|
+
end
|
|
100
|
+
|
|
101
|
+
# Did the last `records` answer fewer matches than asked for, while more match
|
|
102
|
+
# (READ_LIMIT, the result window)?
|
|
103
|
+
def truncated? = @truncated == true
|
|
104
|
+
|
|
105
|
+
# What @find returns: the one record the search finds, or nil. More than one
|
|
106
|
+
# match, as the engine counts them, is an error, as in PHP Lighthouse.
|
|
107
|
+
def only_record
|
|
108
|
+
found = window(0, 1)
|
|
109
|
+
raise ::GraphQL::ExecutionError, 'The query returned more than one result.' if count > 1
|
|
110
|
+
|
|
111
|
+
found.first
|
|
112
|
+
end
|
|
113
|
+
|
|
114
|
+
# What @first returns: the best match that loads, or nil. A best hit that does
|
|
115
|
+
# not load (the model's scopes, a record gone from the database) yields to the
|
|
116
|
+
# next one, read within the result window and READ_LIMIT.
|
|
117
|
+
def first_record
|
|
118
|
+
found = window(0, 1)
|
|
119
|
+
return found.first if found.any? || count <= 1
|
|
120
|
+
|
|
121
|
+
window(0, [reachable, READ_LIMIT].min).first
|
|
122
|
+
end
|
|
123
|
+
|
|
124
|
+
# How many matches a page can reach: the total, within the result window.
|
|
125
|
+
def reachable = result_window ? [count, result_window].min : count
|
|
126
|
+
|
|
127
|
+
# Every record the search finds that a page can reach, for @canQuery to check:
|
|
128
|
+
# one request, of READ_LIMIT records at most, whose hits then serve every page
|
|
129
|
+
# of this Result, and no other request. A search that finds more within the
|
|
130
|
+
# result window is a client error, as a page could reach a record not checked.
|
|
131
|
+
def every_record
|
|
132
|
+
found = window(0, READ_LIMIT)
|
|
133
|
+
unless reachable <= READ_LIMIT
|
|
134
|
+
raise ::GraphQL::ExecutionError,
|
|
135
|
+
"@canQuery checks every record the search finds, at most #{READ_LIMIT}, and this one finds #{reachable}. Narrow the search."
|
|
136
|
+
end
|
|
137
|
+
|
|
138
|
+
@checked ||= @last_entries
|
|
139
|
+
found
|
|
140
|
+
end
|
|
141
|
+
|
|
142
|
+
# Is it the search of `field` that `adapter` runs for `query`? Its options aside,
|
|
143
|
+
# which may hold an @builder's procs, made again for each search.
|
|
144
|
+
def same_search?(adapter, query, field)
|
|
145
|
+
@adapter.equal?(adapter) && @field == field && query.model.equal?(@query.model) && query.models == @query.models &&
|
|
146
|
+
[query.term, query.index, query.wheres, query.trashed] == [@query.term, @query.index, @query.wheres, @query.trashed]
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# How many of the matches the engine pages through; nil when the adapter cannot tell.
|
|
150
|
+
def result_window
|
|
151
|
+
return @result_window if defined?(@result_window)
|
|
152
|
+
|
|
153
|
+
@result_window = Lighthouse::Support::Failures.strictly(@context) do
|
|
154
|
+
@adapter.respond_to?(:result_window) ? @adapter.result_window(@query) : MAX_WINDOW
|
|
155
|
+
end
|
|
156
|
+
end
|
|
157
|
+
|
|
158
|
+
private
|
|
159
|
+
|
|
160
|
+
# The engine's entries at `offset`, `limit` of them; its total, which must be a count.
|
|
161
|
+
def request(offset, limit)
|
|
162
|
+
Lighthouse::Support::Failures.strictly(@context) do
|
|
163
|
+
entries, total = @adapter.page(@query, offset: offset, limit: limit)
|
|
164
|
+
unless total.is_a?(Integer)
|
|
165
|
+
raise Lighthouse::DefinitionError, "@search: #{adapter_name} answered #{total.inspect} for the total, not the count of every match"
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
@count = total
|
|
169
|
+
@last_entries = entries
|
|
170
|
+
end
|
|
171
|
+
end
|
|
172
|
+
|
|
173
|
+
def within_window(offset, limit)
|
|
174
|
+
return limit if result_window.nil?
|
|
175
|
+
return [limit, result_window - offset].min if offset < result_window
|
|
176
|
+
|
|
177
|
+
raise ::GraphQL::ExecutionError,
|
|
178
|
+
"The search reads no further than its first #{result_window} matches (the index.max_result_window of " \
|
|
179
|
+
"#{@query.name}), so offset #{offset} is past them. Narrow the search instead."
|
|
180
|
+
end
|
|
181
|
+
end
|
|
@@ -0,0 +1,335 @@
|
|
|
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 = search(query, offset, 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.name}. Narrow the search instead."
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# Models searched together: those it searches alone, and why one cannot be as it is (model_error).
|
|
67
|
+
def searchable_together?(model) = searchable?(model)
|
|
68
|
+
def together_error(model) = model_error(model)
|
|
69
|
+
|
|
70
|
+
# How many of the matches the index the search reads pages through
|
|
71
|
+
# (Search::Result): its index.max_result_window, read from the engine
|
|
72
|
+
# (Searchkick::Index). When the settings cannot be read, the model's own index
|
|
73
|
+
# takes the window its options set (`max_result_window:`, in `searchkick` or
|
|
74
|
+
# its index `settings:`, whatever their keys; a billion with `deep_paging:
|
|
75
|
+
# true`), and any index the engines' default, 10,000.
|
|
76
|
+
def result_window(query)
|
|
77
|
+
return query.models.map { |model| result_window(query.for(model)) }.min if query.models
|
|
78
|
+
|
|
79
|
+
@index.result_window(query.model, index_name(query)) ||
|
|
80
|
+
(own_index?(query) && options_window(query.model)) || Lighthouse::Search::Result::MAX_WINDOW
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# Why the model cannot be searched as it is, or nil: a default scope (a
|
|
84
|
+
# tenant's, a soft delete's; any, as declared, since what one selects may
|
|
85
|
+
# depend on the request), a search_results scope, or the type condition of an
|
|
86
|
+
# STI subclass that searches its parent's index without Searchkick's
|
|
87
|
+
# `inheritance: true` (which filters the engine by type), needs `search_where`,
|
|
88
|
+
# the engine's `where:` for the same records (`{}` when they narrow nothing).
|
|
89
|
+
# Without it the engine would count, and page through, records that do not
|
|
90
|
+
# load: its totals would include other tenants' matches.
|
|
91
|
+
# Search::FieldCheck asks when the schema is built; a search asks too.
|
|
92
|
+
def model_error(model)
|
|
93
|
+
return nil if model.respond_to?(:search_where)
|
|
94
|
+
|
|
95
|
+
narrowing = narrowing(model)
|
|
96
|
+
return nil unless narrowing
|
|
97
|
+
|
|
98
|
+
"#{narrowing} narrows what a search loads, which the engine does not apply: its totals and pages would count records that " \
|
|
99
|
+
"do not load. Define #{model.name}.search_where, the engine's `where:` for the same records (`{ tenant_id: Current.tenant_id }`), " \
|
|
100
|
+
'or `{}` when the index holds no other'
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
private
|
|
104
|
+
|
|
105
|
+
# What narrows the records a search of the model loads, which the engine does not apply; nil when nothing does.
|
|
106
|
+
def narrowing(model)
|
|
107
|
+
return "#{model.name}'s default scope" if Lighthouse::Support::Relations.default_scope?(model)
|
|
108
|
+
return "#{model.name}.search_results" if Lighthouse::Search.results_scope?(model)
|
|
109
|
+
|
|
110
|
+
"#{model.name}'s STI type, in #{model.base_class.name}'s index without `inheritance: true`," if untyped_subclass?(model)
|
|
111
|
+
end
|
|
112
|
+
|
|
113
|
+
# An STI subclass (its relation has a type condition) whose index Searchkick
|
|
114
|
+
# does not filter by type (`searchkick inheritance: true`).
|
|
115
|
+
def untyped_subclass?(model)
|
|
116
|
+
model.respond_to?(:finder_needs_type_condition?) && model.finder_needs_type_condition? &&
|
|
117
|
+
!searchkick_option(model, :inheritance)
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
def searchkick_option(model, name) = ::ActiveSupport::HashWithIndifferentAccess.new(model.searchkick_options)[name]
|
|
121
|
+
|
|
122
|
+
# The response's records in their hits' places, nil where one did not load. A
|
|
123
|
+
# record is placed by its hit's index and id, as hits of two indices (Searchkick's
|
|
124
|
+
# `models:`, an `index_name:` list) may share an id.
|
|
125
|
+
def entries(response)
|
|
126
|
+
return response.to_a unless response.respond_to?(:with_hit) && response.respond_to?(:hits)
|
|
127
|
+
|
|
128
|
+
loaded = response.with_hit.to_h { |record, hit| [hit_key(hit), record] }
|
|
129
|
+
response.hits.map { |hit| loaded[hit_key(hit)] }
|
|
130
|
+
end
|
|
131
|
+
|
|
132
|
+
def hit_key(hit) = [hit['_index'], hit['_id'].to_s]
|
|
133
|
+
|
|
134
|
+
# The total must be every match: a total the engine stopped counting at
|
|
135
|
+
# (`"relation": "gte"`) would let a page, or @canQuery's check, miss records.
|
|
136
|
+
def exact_total!(query, response)
|
|
137
|
+
raw = response.response if response.respond_to?(:response)
|
|
138
|
+
total = raw.to_h.dig('hits', 'total') if raw.respond_to?(:to_h)
|
|
139
|
+
return unless total.is_a?(Hash) && total['relation'] && total['relation'] != 'eq'
|
|
140
|
+
|
|
141
|
+
raise Lighthouse::DefinitionError,
|
|
142
|
+
"@search on #{query.name}: the engine counted #{total['relation']} #{total['value']} matches, not every one, " \
|
|
143
|
+
'which totals, pages and @canQuery need (track_total_hits)'
|
|
144
|
+
end
|
|
145
|
+
|
|
146
|
+
# Does the search read the model's own index, whose settings the model tells?
|
|
147
|
+
def own_index?(query) = query.index.nil? || query.index == query.model.searchkick_index&.name
|
|
148
|
+
|
|
149
|
+
def index_name(query) = query.index || query.model.searchkick_index&.name
|
|
150
|
+
|
|
151
|
+
# The window the model's options set, or nil.
|
|
152
|
+
def options_window(model)
|
|
153
|
+
options = ::ActiveSupport::HashWithIndifferentAccess.new(model.searchkick_options)
|
|
154
|
+
settings = options[:settings] || {}
|
|
155
|
+
options[:max_result_window] || settings.dig(:index, :max_result_window) || settings[:'index.max_result_window'] ||
|
|
156
|
+
(DEEP_PAGING_WINDOW if options[:deep_paging])
|
|
157
|
+
end
|
|
158
|
+
|
|
159
|
+
def past_window?(error)
|
|
160
|
+
defined?(::Searchkick::InvalidQueryError) && error.is_a?(::Searchkick::InvalidQueryError) && error.message.include?('max_result_window')
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
# The engine's response to the search, `limit` hits from `offset`: of the model, or of the
|
|
164
|
+
# models searched together, in one request over their indices.
|
|
165
|
+
def search(query, offset, limit)
|
|
166
|
+
return query.model.searchkick_search(query.term, **search_options(query), offset: offset, limit: limit) unless query.models
|
|
167
|
+
|
|
168
|
+
::Searchkick.search(query.term, models: query.models, **together_options(query), offset: offset, limit: limit)
|
|
169
|
+
end
|
|
170
|
+
|
|
171
|
+
def search_options(query)
|
|
172
|
+
options = Lighthouse::Search::Searchkick::Options.builder!(query)
|
|
173
|
+
wheres = query.wheres.map { |column, value| { column => value } }
|
|
174
|
+
options[:where] = all_of(options[:where], engine_where(query), *wheres, trashed_filter(query))
|
|
175
|
+
options[:index_name] = query.index if query.index
|
|
176
|
+
loaded(options, results_scope(query, options[:scope_results]))
|
|
177
|
+
end
|
|
178
|
+
|
|
179
|
+
# The options of a search of several models, in one request over their indices. What narrows
|
|
180
|
+
# each model holds in its own index only (`_index`, which the engines match against the
|
|
181
|
+
# alias Searchkick names): its search_where, and the records its default scope hides; what the
|
|
182
|
+
# client sends (@eq) holds in every index, matching nothing in one that does not hold the
|
|
183
|
+
# column. Each model's records load through its own narrowing (results_scope), which Searchkick
|
|
184
|
+
# calls with each model's relation.
|
|
185
|
+
def together_options(query)
|
|
186
|
+
options = Lighthouse::Search::Searchkick::Options.builder!(query)
|
|
187
|
+
wheres = query.wheres.map { |column, value| { column => value } }
|
|
188
|
+
each_own = query.models.map { |model| own_where(query.for(model)) }
|
|
189
|
+
options[:where] = all_of(options[:where], *wheres, { _or: each_own })
|
|
190
|
+
loads = query.models.index_with { |model| results_scope(query.for(model), options[:scope_results]) }.compact
|
|
191
|
+
loaded(options, loads.empty? ? nil : ->(records) { (loads[model_of(records)] || :itself.to_proc).call(records) })
|
|
192
|
+
end
|
|
193
|
+
|
|
194
|
+
# What Searchkick loads a model's hits through: the model itself, or a relation of it.
|
|
195
|
+
def model_of(records) = records.respond_to?(:klass) ? records.klass : records
|
|
196
|
+
|
|
197
|
+
# What one model's hits must hold in a search of several: being in its index, and what its own
|
|
198
|
+
# search would have the engine apply.
|
|
199
|
+
def own_where(query)
|
|
200
|
+
all_of({ _index: query.model.searchkick_index.name }, engine_where(query), trashed_filter(query))
|
|
201
|
+
end
|
|
202
|
+
|
|
203
|
+
# The options Lighthouse sets whatever the search: the records load, through `loading` (the
|
|
204
|
+
# `scope_results:` that narrows them) if any, and every match is counted.
|
|
205
|
+
def loaded(options, loading)
|
|
206
|
+
options[:load] = true
|
|
207
|
+
options[:body_options] = Lighthouse::Search::Searchkick::Options.counting(options)
|
|
208
|
+
options[:scope_results] = loading if loading
|
|
209
|
+
options
|
|
210
|
+
end
|
|
211
|
+
|
|
212
|
+
# What Searchkick loads the records it found through (`scope_results:`): the
|
|
213
|
+
# app's own first, then what Lighthouse narrows them to, last, so nothing
|
|
214
|
+
# widens it: the model's default scope when the model loads `unscope: true`
|
|
215
|
+
# (Searchkick loads through `unscoped`), the filters the engine applied that the
|
|
216
|
+
# database can apply too (@trashed's, the @eq ones on a column of the model,
|
|
217
|
+
# with a plain value), so a record the index holds as it was no longer matches,
|
|
218
|
+
# and the model's `search_results` scope; nil for the model alone.
|
|
219
|
+
def results_scope(query, own)
|
|
220
|
+
wheres = Lighthouse::Search::Searchkick::Options.database_wheres(query)
|
|
221
|
+
return own unless own || narrows_load?(query, wheres)
|
|
222
|
+
|
|
223
|
+
->(records) { load_through(own ? own.call(records) : records.all, query, wheres) }
|
|
224
|
+
end
|
|
225
|
+
|
|
226
|
+
def load_through(records, query, wheres)
|
|
227
|
+
records = records.merge(query.model.all) if searchkick_option(query.model, :unscope)
|
|
228
|
+
records = Lighthouse::Support::SoftDeletes.filter(records, query.trashed.to_s) if query.trashed
|
|
229
|
+
records = wheres.reduce(records) { |narrowed, (column, value)| narrowed.where(column => value) }
|
|
230
|
+
Lighthouse::Search.results(records)
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def narrows_load?(query, wheres)
|
|
234
|
+
searchkick_option(query.model, :unscope) || query.trashed || wheres.any? || Lighthouse::Search.results_scope?(query.model)
|
|
235
|
+
end
|
|
236
|
+
|
|
237
|
+
# The model's search_where, the engine's `where:` for what its default scope and
|
|
238
|
+
# search_results keep, which must leave the soft-delete column to Lighthouse
|
|
239
|
+
# (trashed_filter): a condition on it in search_where could not yield to @trashed.
|
|
240
|
+
def engine_where(query)
|
|
241
|
+
model = query.model
|
|
242
|
+
where = (model.search_where if model.respond_to?(:search_where)).to_h
|
|
243
|
+
column = Lighthouse::Support::SoftDeletes.supported?(model) && trashed_column(model).first.to_s
|
|
244
|
+
return where unless column && names?(where, column)
|
|
245
|
+
|
|
246
|
+
raise Lighthouse::DefinitionError,
|
|
247
|
+
"#{model.name}.search_where names #{column}, the column @trashed and Lighthouse filter trashed records on: leave it out"
|
|
248
|
+
end
|
|
249
|
+
|
|
250
|
+
# Does the engine condition name `column`, at any depth (`_and`, `_or`, `_not`)?
|
|
251
|
+
def names?(condition, column)
|
|
252
|
+
case condition
|
|
253
|
+
when Hash then condition.any? { |key, value| key.to_s == column || names?(value, column) }
|
|
254
|
+
when Array then condition.any? { |each| names?(each, column) }
|
|
255
|
+
else false
|
|
256
|
+
end
|
|
257
|
+
end
|
|
258
|
+
|
|
259
|
+
# The conditions as one Searchkick `where:`, all of which hold: the app's
|
|
260
|
+
# (@builder), the @eq ones, @trashed's. Their keys are read alike, symbols or
|
|
261
|
+
# strings; conditions on different keys merge, and ones on a key more than one
|
|
262
|
+
# names are ANDed (Searchkick's `_and`), never overwritten.
|
|
263
|
+
def all_of(*conditions)
|
|
264
|
+
conditions = conditions.compact.map { |condition| condition.to_h.transform_keys(&:to_sym) }.reject(&:empty?)
|
|
265
|
+
keys = conditions.flat_map(&:keys)
|
|
266
|
+
keys.uniq.size == keys.size ? conditions.reduce({}, :merge) : { _and: conditions }
|
|
267
|
+
end
|
|
268
|
+
|
|
269
|
+
# @trashed's condition; without one, the records that are not trashed when the
|
|
270
|
+
# model's default scope hides the others (paranoia's), as they would not load.
|
|
271
|
+
# That one needs the index to hold the column only when it can be told: on an
|
|
272
|
+
# index without it, `WITHOUT` matches every hit, and the load still leaves the
|
|
273
|
+
# trashed records out.
|
|
274
|
+
def trashed_filter(query)
|
|
275
|
+
trashed = query.trashed || (:without if hides_trashed?(query.model))
|
|
276
|
+
return {} if trashed.nil? || trashed == :with # no filter: the index need not hold the column
|
|
277
|
+
|
|
278
|
+
column, kept = trashed_column(query.model)
|
|
279
|
+
require_indexed!(query, column, told: query.trashed.nil?)
|
|
280
|
+
trashed == :only ? { column.to_sym => { not: kept } } : { column.to_sym => kept }
|
|
281
|
+
end
|
|
282
|
+
|
|
283
|
+
# Does the model's default scope leave its trashed records out?
|
|
284
|
+
def hides_trashed?(model)
|
|
285
|
+
Lighthouse::Support::SoftDeletes.supported?(model) &&
|
|
286
|
+
!Lighthouse::Support::Relations.same_records?(model.all, Lighthouse::Support::SoftDeletes.with_trashed(model.all))
|
|
287
|
+
end
|
|
288
|
+
|
|
289
|
+
# [the indexed column that marks trashed records, its value for the others]:
|
|
290
|
+
# the soft-delete adapter's (paranoia's, with its sentinel; discard's;
|
|
291
|
+
# Config.soft_deletes'), which the database filters and the records load
|
|
292
|
+
# through too; deleted_at when an app's adapter does not tell.
|
|
293
|
+
def trashed_column(model)
|
|
294
|
+
[Lighthouse::Support::SoftDeletes.column(model) || DEFAULT_TRASHED_COLUMN, Lighthouse::Support::SoftDeletes.kept_value(model)]
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
# The index must hold the column, or the filter would match nothing (or everything).
|
|
298
|
+
# The model's search_data tells for its own index, the engine's mapping for any
|
|
299
|
+
# other `within:` names (or when search_data cannot run on a blank record). It
|
|
300
|
+
# fails closed: when the columns cannot be told, the search is refused too,
|
|
301
|
+
# naming why the mapping could not be read; unless `told` (Lighthouse's own
|
|
302
|
+
# filter, which holds either way) lets it go on.
|
|
303
|
+
def require_indexed!(query, column, told: false)
|
|
304
|
+
model = query.model
|
|
305
|
+
indexed = (indexed_columns(model) if own_index?(query)) || @index.fields(model, index_name(query))
|
|
306
|
+
return if indexed.nil? && told
|
|
307
|
+
|
|
308
|
+
unless indexed
|
|
309
|
+
raise ::GraphQL::ExecutionError,
|
|
310
|
+
"@trashed cannot tell whether #{index_label(query)} holds #{column}, which it filters the search on: " \
|
|
311
|
+
"#{model.name}#search_data does not run on a blank record, and the index's mapping cannot be read#{mapping_failure(query)}."
|
|
312
|
+
end
|
|
313
|
+
return if indexed.include?(column.to_s)
|
|
314
|
+
|
|
315
|
+
raise ::GraphQL::ExecutionError, "#{index_label(query)} does not hold #{column}, which @trashed filters the search on: add it to search_data."
|
|
316
|
+
end
|
|
317
|
+
|
|
318
|
+
def index_label(query) = own_index?(query) ? "#{query.model.name}'s index" : "the index #{query.index}"
|
|
319
|
+
|
|
320
|
+
# Why the engine did not answer the index's mapping, and the privilege reading it needs.
|
|
321
|
+
def mapping_failure(query)
|
|
322
|
+
error = @index.failure(:mapping, query.model, index_name(query))
|
|
323
|
+
" (#{error.class}: #{error.message}; reading it needs the view_index_metadata privilege on the index)" if error
|
|
324
|
+
end
|
|
325
|
+
|
|
326
|
+
# What `search_data` holds, or nil when it cannot run on a blank record, read
|
|
327
|
+
# once per model class.
|
|
328
|
+
def indexed_columns(model)
|
|
329
|
+
@per_model.get([:indexed_columns, model.name], model) do
|
|
330
|
+
model.new.search_data.keys.map(&:to_s)
|
|
331
|
+
rescue StandardError
|
|
332
|
+
nil
|
|
333
|
+
end
|
|
334
|
+
end
|
|
335
|
+
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
|