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.
Files changed (95) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +168 -1
  3. data/docs/authorization.md +5 -1
  4. data/docs/configuration.md +71 -3
  5. data/docs/custom-directives.md +22 -0
  6. data/docs/defer.md +352 -0
  7. data/docs/directives.md +106 -0
  8. data/docs/events.md +30 -1
  9. data/docs/filtering-and-ordering.md +567 -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 +32 -3
  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 +116 -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 +29 -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 +35 -0
  68. data/lib/lighthouse/resolve_info.rb +7 -1
  69. data/lib/lighthouse/schema_generator.rb +2 -0
  70. data/lib/lighthouse/search/auto.rb +26 -0
  71. data/lib/lighthouse/search/enhancer.rb +151 -0
  72. data/lib/lighthouse/search/field_check.rb +173 -0
  73. data/lib/lighthouse/search/pg_search.rb +146 -0
  74. data/lib/lighthouse/search/query.rb +54 -0
  75. data/lib/lighthouse/search/result.rb +181 -0
  76. data/lib/lighthouse/search/searchkick.rb +335 -0
  77. data/lib/lighthouse/search/searchkick_index.rb +54 -0
  78. data/lib/lighthouse/search/searchkick_options.rb +74 -0
  79. data/lib/lighthouse/search/together_check.rb +137 -0
  80. data/lib/lighthouse/search.rb +101 -0
  81. data/lib/lighthouse/support/argument_walk.rb +81 -0
  82. data/lib/lighthouse/support/count.rb +16 -0
  83. data/lib/lighthouse/support/failures.rb +28 -0
  84. data/lib/lighthouse/support/memo.rb +72 -0
  85. data/lib/lighthouse/support/model_resolver.rb +24 -0
  86. data/lib/lighthouse/support/relations.rb +31 -0
  87. data/lib/lighthouse/support/soft_deletes.rb +42 -8
  88. data/lib/lighthouse/testing.rb +81 -0
  89. data/sig/lighthouse/controller.rbs +34 -1
  90. data/sig/lighthouse/directives.rbs +46 -5
  91. data/sig/lighthouse/events.rbs +7 -0
  92. data/sig/lighthouse/graphql.rbs +117 -0
  93. data/sig/lighthouse/search.rbs +153 -0
  94. data/sig/lighthouse.rbs +77 -1
  95. metadata +39 -1
@@ -19,6 +19,11 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
19
19
  "The name of the association on the parent model. Defaults to the field's name in snake_case."
20
20
  )
21
21
 
22
+ # Whether the resolver applies a @search on its field, as Contracts::FieldResolver
23
+ # describes: the base resolver does not; a subclass that runs the field's
24
+ # argument filters says so.
25
+ extend Lighthouse::Contracts::FieldResolver::SearchDefaults
26
+
22
27
  def initialize(field_def, type_def, directive_node, opts = {})
23
28
  @field_def = field_def
24
29
  @type_def = type_def
@@ -30,38 +35,29 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
30
35
  raise NotImplementedError
31
36
  end
32
37
 
33
- # `ctx`: the query's context, for @builder on an argument.
34
- def apply_where_filters(relation, args, ctx = nil)
35
- return relation unless relation.respond_to?(:where)
36
-
37
- args_h = args.respond_to?(:to_h) ? args.to_h : (args || {})
38
-
39
- apply_field_builders(apply_arg_builders(relation, args_h, ctx), args_h, ctx)
40
- rescue ::GraphQL::ExecutionError
41
- raise
42
- rescue StandardError => e
43
- Lighthouse::Config.handle_error(e)
44
- relation
45
- end
46
-
47
- # Compose argument-builder directives (@eq, @neq, @in, @notIn, @like,
48
- # @where, @orderBy, @whereConditions, @whereHasConditions) onto the relation, in SDL argument order, for each
49
- # field argument that carries one and that the client supplied a value
50
- # for — and for the fields of the input objects the client sent, at any depth.
51
- def apply_arg_builders(relation, args_h, ctx = nil)
38
+ # What a caller can take from a search outside the database (Searchkick), which
39
+ # answers with a Search::Result in place of a relation (`search:`):
40
+ #
41
+ # nil a relation only: such a search is a client error
42
+ # :model a Search::Result, for the model's own relation the caller built (`Model.all`, `scopes:`)
43
+ # :given a Search::Result, for a relation the app's code gave (enhance_builder), which the
44
+ # engine refuses unless it selects what the model's own does
45
+ SEARCHES = [nil, :model, :given].freeze
46
+
47
+ # The relation searched (@search), then narrowed by the field's argument
48
+ # directives and its own query directives (@builder, @whereAuth, @orderBy(column:)),
49
+ # as PHP Lighthouse's enhanceBuilder. `ctx`: the query's context, for @builder
50
+ # on an argument. `search`: SEARCHES.
51
+ #
52
+ # A filter that raises fails the field, never answering the rows it would have
53
+ # left out (Support::Failures). A relational search's order ends with the primary key,
54
+ # once every other order applies (apply_search).
55
+ def apply_where_filters(relation, args, ctx = nil, search: nil)
56
+ raise ArgumentError, "search: is nil, :model or :given, got #{search.inspect}" unless SEARCHES.include?(search)
52
57
  return relation unless relation.respond_to?(:where)
53
- return relation unless @field_def.ast_node
54
-
55
- arg_builders(args_h).each do |values, node, dnode, builder_class|
56
- relation = apply_arg_builder(relation, values, ctx, [[node.name], node, dnode, builder_class])
57
- end
58
58
 
59
- relation
60
- rescue ::GraphQL::ExecutionError
61
- raise
62
- rescue StandardError => e
63
- Lighthouse::Config.handle_error(e)
64
- relation
59
+ relation = relation.all if relation.is_a?(Class) # a model class, as `enhance_builder(Post)` gives it
60
+ Lighthouse::Support::Failures.strictly(ctx) { filter(relation, args_hash(args), ctx, search) }
65
61
  end
66
62
 
67
63
  def constantize_model(name)
@@ -97,27 +93,88 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
97
93
  # another directive on the field (`@count(model: "Post") @canQuery`), or
98
94
  # the field's return type without a generated Paginator/Connection suffix.
99
95
  def model_class
100
- name = directive_arg('model') || sibling_model_name || return_type_model_name
96
+ name = Lighthouse::Support::ModelResolver.field_model_name(@field_def, @directive_node)
101
97
  constantize_model(name) || raise(Lighthouse::DefinitionError,
102
98
  "@#{@directive_node&.name} on #{@type_def.graphql_name}.#{@field_def.name}: no model #{name}")
103
99
  end
104
100
 
105
101
  private
106
102
 
107
- def sibling_model_name
108
- (@field_def.ast_node&.directives || []).filter_map do |d|
109
- Lighthouse::Support::DirectiveArgs.literal(d, 'model')
110
- end.first
103
+ def args_hash(args) = args.respond_to?(:to_h) ? args.to_h : (args || {})
104
+
105
+ # The argument directives (@eq, @in, @where, @orderBy, @whereConditions, ...), in
106
+ # SDL order, for each argument the client sent, and the fields of the input
107
+ # objects it sent, at any depth; then the field's own query directives.
108
+ def filter(relation, args_h, ctx, search)
109
+ builders = @field_def.ast_node ? arg_builders(args_h) : []
110
+ searched = searching? ? apply_search(relation, builders, ctx, search) : relation
111
+ return unconstrained!(searched) if searched.is_a?(Lighthouse::Search::Result)
112
+
113
+ filtered = apply_field_builders(builders.reduce(searched) { |acc, built| apply_built(acc, built, ctx) }, args_h, ctx)
114
+ searched.equal?(relation) ? filtered : Lighthouse::GraphQL::Pagination.stable_order(filtered)
115
+ end
116
+
117
+ # An engine's Search::Result answers without the field's own query directives
118
+ # (@builder, @whereAuth, @orderBy(column:)) and its directive's `scopes:`, which
119
+ # only a relation takes. Search::FieldCheck refuses such a field when the schema
120
+ # is built; one whose model it could not tell is refused here, never answered
121
+ # without them.
122
+ def unconstrained!(result)
123
+ dropped = Lighthouse::Search.dropped_constraints(@field_def, @directive_node)
124
+ return result if dropped.empty?
125
+
126
+ raise Lighthouse::DefinitionError,
127
+ "@search on #{@type_def.graphql_name}.#{@field_def.name}: #{result.adapter_name} answers outside the database, so it cannot " \
128
+ "apply #{dropped.join(', ')} of the field; it does not search"
129
+ end
130
+
131
+ # One of arg_builders, on the relation.
132
+ def apply_built(relation, (values, node, dnode, builder_class), ctx)
133
+ apply_arg_builder(relation, values, ctx, [[node.name], node, dnode, builder_class])
134
+ end
135
+
136
+ # The relation searched, when the client sent a string for an argument with @search
137
+ # (Search::Enhancer), else the relation itself: its errors are the client's or
138
+ # the schema's, never swallowed. A relational search's order ends with the primary
139
+ # key once every other order applies (apply_where_filters), so the matches that
140
+ # rank, and sort, alike come back in one order, whatever the field resolves with.
141
+ # `builders`: the field's arg_builders, walked once for the search and the
142
+ # filters after it.
143
+ def apply_search(relation, builders, ctx, search)
144
+ arguments = builders.map do |values, node, dnode, builder_class|
145
+ path = [node.name]
146
+ Lighthouse::Search::Enhancer::Argument.new(node, dnode, builder_class, dig_arg(values, path), arg_present?(values, path))
147
+ end
148
+ field = "#{@type_def.graphql_name}.#{@field_def.name}"
149
+ Lighthouse::Search::Enhancer.new(arguments, relation, search: search, context: ctx, field: field).enhance
111
150
  end
112
151
 
113
- def return_type_model_name
114
- @field_def.type.unwrap.graphql_name.sub(/(SimplePaginator|Paginator|Connection)\z/, '')
152
+ public
153
+
154
+ # The models the field searches together (a union's or an interface's types': Search.together),
155
+ # or nil for a field of one model.
156
+ def searched_together = Lighthouse::Search.together(@field_def)
157
+
158
+ # The search of the models the field searches together, narrowed by the field's argument
159
+ # filters: a Search::Result. Its errors fail the field, as the filters' (Support::Failures).
160
+ def search_together(args, ctx)
161
+ Lighthouse::Support::Failures.strictly(ctx) do
162
+ builders = @field_def.ast_node ? arg_builders(args_hash(args)) : []
163
+ unconstrained!(apply_search(nil, builders, ctx, searched_together))
164
+ end
165
+ end
166
+
167
+ private
168
+
169
+ # Does the field have an argument or input field with @search? Known when the schema is built.
170
+ def searching?
171
+ @field_def.ast_node && Lighthouse::Search.searching?(@field_def)
115
172
  end
116
173
 
117
174
  # The field's own query directives (@builder, @whereAuth, @orderBy(column:)),
118
175
  # in SDL order, after the arguments', as PHP Lighthouse's enhanceBuilder applies them.
119
176
  def apply_field_builders(relation, args_h = {}, ctx = nil)
120
- Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.apply(relation, @field_def.ast_node, args_h, ctx, self)
177
+ Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.apply(relation, @field_def.ast_node, args_h, ctx)
121
178
  end
122
179
 
123
180
  # Every (argument, directive, builder class) on the field, in SDL order.
@@ -143,8 +200,14 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
143
200
 
144
201
  # Did the client send an argument or input field, at any depth, that
145
202
  # carries an argument-builder directive? As PHP Lighthouse's wouldEnhanceBuilder.
203
+ # Each directive's class says whether the client's value narrows
204
+ # (Arguments::Base.filters?): @search only for a string, which runs the search
205
+ # (PHP Lighthouse's ScoutEnhancer#wouldEnhanceBuilder).
146
206
  def filtering?(args_h)
147
- arg_builders(args_h).any? { |values, node, _dnode, _builder_class| arg_present?(values, [node.name]) }
207
+ arg_builders(args_h).any? do |values, node, _dnode, builder_class|
208
+ path = [node.name]
209
+ arg_present?(values, path) && (!builder_class.respond_to?(:filters?) || builder_class.filters?(dig_arg(values, path)))
210
+ end
148
211
  end
149
212
 
150
213
  # [values, node, directive, builder class] for every argument-builder
@@ -153,27 +216,31 @@ class Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
153
216
  # as PHP Lighthouse's applyArgBuilderDirectives goes through them. `values`
154
217
  # holds the node's value: the arguments, or the input object it is a field of.
155
218
  def arg_builders(args_h)
156
- builders_in(@field_def.ast_node.arguments || [], @field_def.arguments, args_h)
219
+ builders_in(@field_def.arguments, args_h)
157
220
  end
158
221
 
159
- def builders_in(nodes, arguments, values)
222
+ # The argument definitions and their directives are Support::ArgumentWalk's, as
223
+ # the schema's build sees them; the values guide the walk into input objects.
224
+ def builders_in(arguments, values)
160
225
  registry = Lighthouse::DirectiveRegistry.default
161
- nodes.flat_map do |node|
162
- own = (node.directives || []).filter_map do |dnode|
226
+ walk = Lighthouse::Support::ArgumentWalk
227
+ arguments.each_value.flat_map do |argument|
228
+ node = argument.ast_node
229
+ next [] unless node
230
+
231
+ own = walk.directives(argument).filter_map do |dnode|
163
232
  builder_class = dnode.name == 'builder' ? :builder : registry.arg_builder_class(dnode.name)
164
233
  [values, node, dnode, builder_class] if builder_class
165
234
  end
166
- own + nested_builders(arguments[node.name], dig_arg(values, [node.name]))
235
+ own + nested_builders(argument, dig_arg(values, [node.name]))
167
236
  end
168
237
  end
169
238
 
170
239
  def nested_builders(argument, value)
171
- return [] if argument.nil? || value.nil?
172
-
173
- type = argument.type.unwrap
174
- return [] unless type.kind.input_object?
240
+ fields = Lighthouse::Support::ArgumentWalk.input_fields(argument)
241
+ return [] if value.nil? || fields.empty?
175
242
 
176
- [value].flatten.compact.flat_map { |input| builders_in(type.arguments.values.filter_map(&:ast_node), type.arguments, input) }
243
+ [value].flatten.compact.flat_map { |input| builders_in(fields, input) }
177
244
  end
178
245
 
179
246
  # The client's value at `path` (an argument, then input fields), or nil.
@@ -52,25 +52,31 @@ class Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier
52
52
 
53
53
  DEFINITIONS = { 'builder' => DEFINITION, 'whereAuth' => WHERE_AUTH_DEFINITION }.freeze
54
54
 
55
- def self.apply(relation, field_def_ast_node, args, ctx, resolver_instance)
55
+ # A builder that raises goes on to the caller, which fails the field
56
+ # (BaseDirectiveResolver#apply_where_filters): never skipped.
57
+ def self.apply(relation, field_def_ast_node, args, ctx)
56
58
  return relation unless field_def_ast_node&.directives
57
59
 
58
60
  registry = Lighthouse::DirectiveRegistry.default
59
61
  field_def_ast_node.directives.reduce(relation) do |acc, directive_node|
60
62
  case directive_node.name
61
- when 'builder' then apply_directive(acc, directive_node, args, ctx, resolver_instance)
63
+ when 'builder' then apply_directive(acc, directive_node, args, ctx)
62
64
  when 'whereAuth' then where_auth(acc, directive_node, ctx)
63
65
  else field_builder(registry, acc, field_def_ast_node, directive_node)
64
66
  end
65
67
  end
66
68
  end
67
69
 
68
- # Does the field carry a query directive of its own?
69
- def self.any?(field_def_ast_node)
70
+ # The field's own query directives, which `apply` applies: @builder,
71
+ # @whereAuth and the registry's field builders, in SDL order.
72
+ def self.query_directives(field_def_ast_node)
70
73
  registry = Lighthouse::DirectiveRegistry.default
71
- (field_def_ast_node&.directives || []).any? { |d| DEFINITIONS.key?(d.name) || registry.field_builder_class(d.name) }
74
+ (field_def_ast_node&.directives || []).select { |d| DEFINITIONS.key?(d.name) || registry.field_builder_class(d.name) }
72
75
  end
73
76
 
77
+ # Does the field carry a query directive of its own?
78
+ def self.any?(field_def_ast_node) = query_directives(field_def_ast_node).any?
79
+
74
80
  def self.field_builder(registry, relation, field_def_ast_node, directive_node)
75
81
  builder_class = registry.field_builder_class(directive_node.name)
76
82
  builder_class ? builder_class.new(field_def_ast_node, directive_node).handle_field_builder(relation) : relation
@@ -92,7 +98,7 @@ class Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier
92
98
  relation.where(model.primary_key => owned.select(model.arel_table[model.primary_key]))
93
99
  end
94
100
 
95
- def self.apply_directive(relation, directive_node, args, ctx, _resolver_instance)
101
+ def self.apply_directive(relation, directive_node, args, ctx)
96
102
  value = directive_node.arguments&.any? { |a| a.name == 'value' } ? extract_directive_arg(directive_node, 'value') : args
97
103
  call_builder(relation, directive_node, value, ctx)
98
104
  end
@@ -102,24 +108,24 @@ class Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier
102
108
  call_builder(relation, directive_node, value, ctx)
103
109
  end
104
110
 
111
+ # The builder's relation. One that cannot be found, or raises, is never
112
+ # skipped: a builder that enforces tenancy would be bypassed, and the query
113
+ # answer every row. Its error goes on to the caller, which fails the field
114
+ # (BaseDirectiveResolver#apply_where_filters).
105
115
  def self.call_builder(relation, directive_node, value, ctx)
106
116
  builder_class, method_name = reference(directive_node)
107
- return relation unless builder_class
108
-
109
- receiver = builder_receiver(builder_class, method_name)
110
- return relation unless receiver
117
+ receiver = builder_class && builder_receiver(builder_class, method_name)
118
+ raise Lighthouse::DefinitionError, "@builder: no builder #{reference_name(directive_node)}." unless receiver
111
119
 
112
120
  receiver.public_send(method_name, relation, value, ctx) || relation
113
- rescue ::GraphQL::ExecutionError
114
- # Client-facing errors (e.g. authorization / scoping guards raised by a
115
- # builder) MUST propagate — never silently fall back to the unscoped
116
- # relation, or a builder that enforces tenancy could be bypassed.
117
- raise
118
- rescue StandardError => e
119
- Lighthouse::Config.handle_error(e)
120
- relation
121
121
  end
122
122
 
123
+ # What the directive names, for its errors.
124
+ def self.reference_name(directive_node)
125
+ [extract_directive_arg(directive_node, 'class'), extract_directive_arg(directive_node, 'method')].compact.join(' ').inspect
126
+ end
127
+ private_class_method :reference_name
128
+
123
129
  # [builder class, method name] from `class:` and `method:`, or from
124
130
  # `method: "Class@method"`. Builders are not resolvers: they live in their
125
131
  # own namespace (Config.namespaces[:builders], app/graphql/builders).
@@ -60,7 +60,14 @@ module Lighthouse::GraphQL::DirectiveResolvers
60
60
  GRAPHQL
61
61
  end
62
62
 
63
+ # Which @can* act on a model (model_class), told when the schema is built.
64
+ def self.model? = false
65
+
63
66
  def define_resolver(target_type_class)
67
+ # A field whose model cannot be told fails the build, not a query. On an
68
+ # argument, the model is looked for only when the client gives it a value:
69
+ # an input type may be shared with fields that have no model.
70
+ model_class if self.class.model? && !@opts[:argument] && !searched_together
64
71
  me = self
65
72
  inner = capture_inner(target_type_class)
66
73
  install(target_type_class, lambda do |obj, args, ctx|
@@ -115,6 +122,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
115
122
  end
116
123
 
117
124
  class CanFindDirectiveResolver < CanDirectiveResolver
125
+ def self.model? = true
118
126
  def self.directive_name = 'canFind'
119
127
 
120
128
  def self.definition
@@ -166,6 +174,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
166
174
  end
167
175
 
168
176
  class CanModelDirectiveResolver < CanDirectiveResolver
177
+ def self.model? = true
169
178
  def self.directive_name = 'canModel'
170
179
 
171
180
  def self.definition
@@ -189,6 +198,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
189
198
  end
190
199
 
191
200
  class CanQueryDirectiveResolver < CanDirectiveResolver
201
+ def self.model? = true
192
202
  def self.directive_name = 'canQuery'
193
203
 
194
204
  def self.definition
@@ -200,9 +210,25 @@ module Lighthouse::GraphQL::DirectiveResolvers
200
210
 
201
211
  protected
202
212
 
203
- # The records the field's argument filters (@eq, @where, ...) select.
213
+ # The field resolves with the search @canQuery checked serving its page
214
+ # (Search::Result.serving), in this resolution only: what the index gains
215
+ # between the check and the page is never answered unchecked.
216
+ def authorize_and_resolve(inner, obj, args, ctx)
217
+ checked = check { authorize_before(obj, args, ctx) }
218
+ Lighthouse::Search::Result.serving(checked) { inner.call(obj, args, ctx) }
219
+ end
220
+
221
+ # The records the field's argument filters (@eq, @where, ...) select. When the
222
+ # client searches (@search), the records the search finds: all of them, not
223
+ # only the page the field returns, as PHP Lighthouse checks what its Scout
224
+ # builder gets. An engine outside the database (Searchkick) answers 10,000 at
225
+ # most, and more that a page could reach is an error (Search::Result#every_record).
226
+ # Answers the Search::Result it checked, else nil.
204
227
  def authorize_before(_obj, args, ctx)
205
- authorize_each!(ctx, apply_where_filters(scoped(model_class.all), args, ctx).to_a, args)
228
+ found = searched_together ? search_together(args, ctx) : apply_where_filters(scoped(model_class.all), args, ctx, search: :model)
229
+ searched = found.is_a?(Lighthouse::Search::Result)
230
+ authorize_each!(ctx, searched ? found.every_record : found.to_a, args)
231
+ found if searched
206
232
  end
207
233
  end
208
234
 
@@ -9,6 +9,7 @@ require_relative 'builder_applier'
9
9
  # and where/argument filters before counting.
10
10
  class Lighthouse::GraphQL::DirectiveResolvers::CountDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
11
11
  def self.directive_name = 'count'
12
+ def self.applies_search? = true
12
13
 
13
14
  def self.definition
14
15
  <<~GRAPHQL.chomp
@@ -5,6 +5,10 @@ require_relative 'base'
5
5
  class Lighthouse::GraphQL::DirectiveResolvers::FieldDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
6
6
  def self.directive_name = 'field'
7
7
 
8
+ # The class it names reads the search through resolve_info.enhance_builder.
9
+ def self.applies_search? = true
10
+ def self.takes_search_results?(*) = true
11
+
8
12
  def self.definition
9
13
  <<~GRAPHQL.chomp
10
14
  """
@@ -12,6 +12,20 @@ require_relative 'base'
12
12
  # match is an error, as in PHP Lighthouse; none returns null.
13
13
  class Lighthouse::GraphQL::DirectiveResolvers::FindDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
14
14
  def self.directive_name = 'find'
15
+ def self.applies_search? = true
16
+
17
+ # It finds in the model's whole table, so it takes the records an engine answers
18
+ # with (Searchkick); not with an `id` argument that has no filter directive, which
19
+ # selects by primary key in the database only.
20
+ def self.takes_search_results?(_type, field_def, _directive, _root_kind) = !primary_key_argument?(field_def)
21
+
22
+ # Does the field have an `id` argument without a filter directive (@eq, @where, ...),
23
+ # which selects by primary key?
24
+ def self.primary_key_argument?(field_def)
25
+ argument = (field_def.ast_node&.arguments || []).find { |a| a.name == 'id' }
26
+ registry = Lighthouse::DirectiveRegistry.default
27
+ !argument.nil? && argument.directives.none? { |d| registry.arg_builder_class(d.name) }
28
+ end
15
29
 
16
30
  def self.definition
17
31
  <<~GRAPHQL.chomp
@@ -27,6 +41,8 @@ class Lighthouse::GraphQL::DirectiveResolvers::FindDirectiveResolver < Lighthous
27
41
  end
28
42
 
29
43
  def define_resolver(target_type_class)
44
+ # Only a field with no scopes and no query directive of its own (@builder, @whereAuth) can batch a lookup by `id`.
45
+ @batchable = !directive_arg('scopes') && Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.query_directives(@field_def.ast_node).empty?
30
46
  me = self
31
47
  install(target_type_class, lambda do |_obj, args, ctx|
32
48
  me.send(:find, Lighthouse::Support::Arguments.shallow(args), ctx)
@@ -40,28 +56,27 @@ class Lighthouse::GraphQL::DirectiveResolvers::FindDirectiveResolver < Lighthous
40
56
  dataloader = Lighthouse::Support::Batching.dataloader(ctx)
41
57
  return dataloader.with(Lighthouse::GraphQL::DataloaderSources::ModelLoader, model).load(args[:id]) if dataloader && batchable?(args)
42
58
 
43
- records = find_relation(model, args).limit(2).to_a
59
+ found = find_relation(model, args, ctx)
60
+ return found.only_record if found.is_a?(Lighthouse::Search::Result)
61
+
62
+ records = found.limit(2).to_a
44
63
  raise ::GraphQL::ExecutionError, 'The query returned more than one result.' if records.size > 1
45
64
 
46
65
  records.first
47
66
  end
48
67
 
49
- # Only a lookup by `id` alone, with no scopes to apply, can be batched.
50
- def batchable?(args)
51
- args.keys == [:id] && !directive_arg('scopes')
52
- end
68
+ # Only a lookup by `id` alone, with no scopes and no query directive of the
69
+ # field's own (@builder, @whereAuth) to apply, can be batched.
70
+ def batchable?(args) = @batchable && args.keys == [:id]
53
71
 
54
- def find_relation(model, args)
72
+ # The model's relation, filtered; or the search an engine answers (Search::Result).
73
+ # One narrowed by primary key is not the model's own, which an engine would search
74
+ # whole: Search::Enhancer refuses it (`search: :given`), as Search::FieldCheck does
75
+ # when the schema is built.
76
+ def find_relation(model, args, ctx)
55
77
  relation = apply_scopes(model.all)
56
- relation = relation.where(model.primary_key => args[:id]) if args.key?(:id) && !filtered?('id')
57
- apply_where_filters(relation, args)
58
- end
59
-
60
- # Does the argument carry a filter directive (@eq, @where, ...)? An `id`
61
- # without one still selects by primary key.
62
- def filtered?(name)
63
- argument = (@field_def.ast_node&.arguments || []).find { |a| a.name == name }
64
- registry = Lighthouse::DirectiveRegistry.default
65
- argument&.directives&.any? { |d| registry.arg_builder_class(d.name) }
78
+ by_key = args.key?(:id) && self.class.primary_key_argument?(@field_def)
79
+ relation = relation.where(model.primary_key => args[:id]) if by_key
80
+ apply_where_filters(relation, args, ctx, search: by_key ? :given : :model)
66
81
  end
67
82
  end
@@ -5,9 +5,12 @@ require_relative 'builder_applier'
5
5
 
6
6
  # @first(model: "Model") — return a single record (the first match). Like
7
7
  # @all but `.first`, honoring `scopes:`, @builder and where/argument filters so it can
8
- # be combined with @eq/@where to fetch one record by criteria.
8
+ # be combined with @eq/@where to fetch one record by criteria. With a search an
9
+ # engine answers (Searchkick), the best match.
9
10
  class Lighthouse::GraphQL::DirectiveResolvers::FirstDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
10
11
  def self.directive_name = 'first'
12
+ def self.applies_search? = true
13
+ def self.takes_search_results?(*) = true
11
14
 
12
15
  def self.definition
13
16
  <<~GRAPHQL.chomp
@@ -33,8 +36,8 @@ class Lighthouse::GraphQL::DirectiveResolvers::FirstDirectiveResolver < Lighthou
33
36
 
34
37
  args_h = arguments.respond_to?(:to_h) ? arguments.to_h : {}
35
38
  relation = resolver_instance.apply_scopes(model_class.all)
36
- relation = resolver_instance.apply_where_filters(relation, args_h, ctx)
37
- relation.first
39
+ relation = resolver_instance.apply_where_filters(relation, args_h, ctx, search: :model)
40
+ relation.is_a?(Lighthouse::Search::Result) ? relation.first_record : relation.first
38
41
  end
39
42
 
40
43
  target_type_class.define_singleton_method(method_name, &resolver)
@@ -48,8 +48,7 @@ class Lighthouse::GraphQL::DirectiveResolvers::GlobalIdTypes
48
48
 
49
49
  # The field's model, when it has one: a field returning a scalar has none.
50
50
  def field_model
51
- model = @resolver.send(:model_class)
52
- model if defined?(::ActiveRecord::Base) && model < ::ActiveRecord::Base
51
+ Lighthouse::Support::ModelResolver.model_class(@resolver.send(:model_class))
53
52
  rescue Lighthouse::DefinitionError
54
53
  nil
55
54
  end
@@ -248,6 +248,8 @@ module Lighthouse::GraphQL::DirectiveResolvers
248
248
  class ModifyModelsResolver < ModelMutationResolver
249
249
  WOULD_MODIFY_ALL = 'Would modify all models, use an argument to filter.'
250
250
 
251
+ def self.applies_search? = true
252
+
251
253
  protected
252
254
 
253
255
  # A record whose callbacks refuse the action is reported as an error next
@@ -17,6 +17,28 @@ require_relative 'builder_applier'
17
17
  class Lighthouse::GraphQL::DirectiveResolvers::PaginateDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
18
18
  def self.directive_name = 'paginate'
19
19
 
20
+ def self.applies_search? = true
21
+
22
+ # The model's whole table takes the records an engine answers with: on a root
23
+ # field, with `model:`, or where the parent type's model has no association of
24
+ # its name. What a parent whose type is no model pages is only known from a
25
+ # query's records (nested?), so it is not taken; nor, at run time, a parent
26
+ # record that has the association its type's model lacks (Search::Enhancer).
27
+ def self.takes_search_results?(type, field_def, directive, root_kind)
28
+ return true if root_kind || Lighthouse::Support::DirectiveArgs.literal(directive, 'model')
29
+
30
+ parent = Lighthouse::Support::ModelResolver.model_class(Lighthouse::GraphQL::Directives::ModelDirective.model_for(type))
31
+ !parent.nil? && !pages_association?(parent, Lighthouse::Support::Naming.attribute(field_def.name), directive)
32
+ end
33
+
34
+ # Does the field page `parent`'s association of its name, rather than the
35
+ # model's whole table? Not with `model:`, as PHP Lighthouse's.
36
+ def self.pages_association?(parent, name, directive)
37
+ return false if Lighthouse::Support::DirectiveArgs.literal(directive, 'model')
38
+
39
+ !!(parent.respond_to?(:reflect_on_association) && parent.reflect_on_association(name.to_sym))
40
+ end
41
+
20
42
  def self.definition
21
43
  <<~GRAPHQL.chomp
22
44
  """
@@ -71,8 +93,10 @@ class Lighthouse::GraphQL::DirectiveResolvers::PaginateDirectiveResolver < Light
71
93
  # the other parents' when the Dataloader can; otherwise, or with `model:`,
72
94
  # the model's whole table.
73
95
  def page_list(obj, args, ctx)
96
+ return search_together(args, ctx) if searched_together
97
+
74
98
  name = Lighthouse::Support::Naming.attribute(@field_def.name)
75
- return decorate_relation(model_class.all, args, ctx) unless nested?(obj, name)
99
+ return decorate_relation(model_class.all, args, ctx, search: :model) unless nested?(obj, name)
76
100
 
77
101
  dataloader = Lighthouse::Support::Batching.dataloader(ctx)
78
102
  batch = dataloader && Lighthouse::GraphQL::RelationBatch.for(obj, name, args, self, ctx)
@@ -82,14 +106,15 @@ class Lighthouse::GraphQL::DirectiveResolvers::PaginateDirectiveResolver < Light
82
106
  end
83
107
 
84
108
  def nested?(obj, name)
85
- !directive_arg('model') && obj.respond_to?(:association) && obj.class.reflect_on_association(name.to_sym)
109
+ obj.respond_to?(:association) && self.class.pages_association?(obj.class, name, @directive_node)
86
110
  end
87
111
 
88
112
  public
89
113
 
90
114
  # `scopes:`, the argument filters and @builder, on one relation or a RelationBatch.
91
- def decorate_relation(relation, args, ctx)
92
- apply_where_filters(apply_scopes(relation), args, ctx)
115
+ # `search`: what it takes from a search outside the database (apply_where_filters).
116
+ def decorate_relation(relation, args, ctx, search: nil)
117
+ apply_where_filters(apply_scopes(relation), args, ctx, search: search)
93
118
  end
94
119
 
95
120
  protected
@@ -17,6 +17,9 @@ require_relative 'base'
17
17
  # ActionController::TooManyRequests, which Rails answers with a 429
18
18
  # (`head :too_many_requests` on a Rails without it, 7.2). Without Action
19
19
  # Pack at all, the field fails: "Rate limit for Query.x exceeded. Try again later."
20
+ # So does it where the response is already on its way (a later part of a
21
+ # streamed @defer response, see Defer): it can no longer be a 429, nor
22
+ # anything `with:` would render, so `with:` is not called.
20
23
  # name: as rate_limit's: the field by default (Query.x). Fields, and the
21
24
  # controller's own `rate_limit`, of the same name count together.
22
25
  # prefix: as rate_limit's scope: the controller's path by default.
@@ -112,16 +115,24 @@ class Lighthouse::GraphQL::DirectiveResolvers::ThrottleDirectiveResolver < Light
112
115
  # Past the limit: instrumented as rate_limit's, around `with`, after which a
113
116
  # response `with` performed ends the request, as a before_action's would.
114
117
  def refuse(controller, limit, location, counted)
118
+ committed = committed?(controller)
115
119
  payload = { request: controller&.request, to: limit[:to], within: limit[:within], **counted }
116
- ActiveSupport::Notifications.instrument('rate_limit.action_controller', payload) { limited(controller, limit[:with], location) }
120
+ ActiveSupport::Notifications.instrument('rate_limit.action_controller', payload) { limited(controller, limit[:with], location, committed) }
117
121
  raise Lighthouse::GraphQL::Controller::Performed if controller&.performed?
118
122
  end
119
123
 
120
- # The controller's `with` method, else rate_limit's default `with`.
121
- def limited(controller, with, location)
122
- return call_with(controller, with, location) if with && controller
123
- raise ::ActionController::TooManyRequests if defined?(::ActionController::TooManyRequests)
124
- return controller.head(:too_many_requests) if controller
124
+ # Is the controller's response on its way (a later part of a streamed @defer response)? It
125
+ # can then be neither a 429 nor what `with:` renders.
126
+ def committed?(controller) = controller.respond_to?(:response) && controller.response.respond_to?(:committed?) && controller.response.committed?
127
+
128
+ # The controller's `with` method, else rate_limit's default `with`; a field error once the
129
+ # response is `committed`.
130
+ def limited(controller, with, location, committed)
131
+ unless committed
132
+ return call_with(controller, with, location) if with && controller
133
+ raise ::ActionController::TooManyRequests if defined?(::ActionController::TooManyRequests)
134
+ return controller.head(:too_many_requests) if controller
135
+ end
125
136
 
126
137
  raise ::GraphQL::ExecutionError, "Rate limit for #{location} exceeded. Try again later."
127
138
  end
@@ -25,6 +25,20 @@ class Lighthouse::GraphQL::Directives::Arguments::Base
25
25
  GRAPHQL
26
26
  end
27
27
 
28
+ # Does the directive, as the SDL writes it (`directive_node`), change the field's
29
+ # query? Most do; one that does not (@limit without `builder: true`, which cuts
30
+ # what the field resolved) leaves a search outside the database alone.
31
+ def self.changes_query?(_directive_node) = true
32
+
33
+ # Does the client's value, once sent, narrow the query? Any value does, null
34
+ # too, as PHP Lighthouse's wouldEnhanceBuilder counts what the client sent; a
35
+ # mass mutation (@delete, ...) refuses to run unless one argument does. @search
36
+ # narrows only for a string, which runs the search.
37
+ def self.filters?(_value) = true
38
+
39
+ # Does the directive run the field's search (@search)?
40
+ def self.searches? = false
41
+
28
42
  def initialize(arg_node, directive_node)
29
43
  @arg_node = arg_node
30
44
  @directive_node = directive_node