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
@@ -0,0 +1,137 @@
1
+ # frozen_string_literal: true
2
+
3
+ # A field of a union or an interface (with @all or @paginate, and no `model:`) whose @search
4
+ # searches the models of its types together, in one search, checked when the schema is built
5
+ # (SchemaGenerator, before FieldCheck, which leaves the field to it), as FieldCheck checks a
6
+ # field of one model. It keeps the models for the field's resolvers (Search.together!).
7
+ #
8
+ # Each type is a model's (@model, or its name), one engine searches them all
9
+ # (`adapter_together`, `together_error`), the @search argument is a top-level, non-null one,
10
+ # with no `within:`, on a root field; and nothing a model would apply alone, but the engine
11
+ # across them cannot, is asked for: `scopes:`, @builder, @whereAuth, @orderBy(column:),
12
+ # @trashed, a default value the engine cannot apply, an @canQuery's `scopes:`.
13
+ class Lighthouse::Search::TogetherCheck < Lighthouse::Search::FieldCheck
14
+ # Every field of the schema's object types (`root_kinds`: SchemaGenerator#root_kinds).
15
+ def self.check_schema!(schema, root_kinds)
16
+ schema.types.each_value do |type|
17
+ next unless type.kind.object?
18
+
19
+ type.fields.each_value { |field_def| check!(schema, type, field_def, root_kinds[type.graphql_name]) if field_def.owner == type }
20
+ end
21
+ end
22
+
23
+ def self.check!(schema, type, field_def, root_kind)
24
+ return unless field_def.ast_node
25
+
26
+ new(schema, type, field_def, root_kind).check!
27
+ end
28
+
29
+ def initialize(schema, type, field_def, root_kind)
30
+ super(type, field_def, field_def.ast_node.directives || [], root_kind)
31
+ @schema = schema
32
+ end
33
+
34
+ def check!
35
+ searches = Lighthouse::Search.directives(@field_def)
36
+ together!(searches) if searches.any? && together?
37
+ end
38
+
39
+ private
40
+
41
+ # Does the field search the models of a union's or an interface's types together? One that a
42
+ # data directive resolves without a `model:` of its own.
43
+ def together?
44
+ !resolving_directive.nil? && returned&.kind&.abstract? &&
45
+ Lighthouse::Support::DirectiveArgs.literal(resolving_directive, 'model').nil?
46
+ end
47
+
48
+ # The type of what the field returns: of its items, for a paginated field (`PostPaginator`'s Post).
49
+ def returned
50
+ type = @field_def.type.unwrap
51
+ return type unless resolving_directive.name == 'paginate'
52
+
53
+ @schema.get_type(type.graphql_name.sub(Lighthouse::Support::ModelResolver::PAGINATION_SUFFIX, ''))
54
+ end
55
+
56
+ def together!(searches)
57
+ path = searches.first.first
58
+ searches.each { |each_path, directive| within_string!(each_path, directive) }
59
+ applied!(path)
60
+ together_field!(path, searches)
61
+ models = together_models(path)
62
+ adapter = together_adapter!(path, models)
63
+ together_constraints!(path, adapter)
64
+ can_queries.each { |can_query| together_can_query!(path, can_query) }
65
+ Lighthouse::Search.together!(@field_def, models)
66
+ end
67
+
68
+ # On a root field, with @all or @paginate, and one @search: a top-level, non-null argument
69
+ # (with no models to list, a field of several models answers a search, always), with no `within:`.
70
+ def together_field!(path, searches)
71
+ unless @root_kind && %w[all paginate].include?(resolving_directive.name)
72
+ fail!(path, "#{abstract_name} has several models, which only @all or @paginate on a root field search together " \
73
+ '(or give the directive the `model:` it searches)')
74
+ end
75
+ one_search!(path, searches)
76
+ return if Lighthouse::Support::DirectiveArgs.literal(searches.first.last, 'within').nil?
77
+
78
+ fail!(path, "`within:` names one model's index or scope, and #{abstract_name}'s models are searched together")
79
+ end
80
+
81
+ def one_search!(path, searches)
82
+ return if searches.size == 1 && @field_def.arguments[path]&.type&.non_null?
83
+
84
+ fail!(path, "a field that searches #{abstract_name}'s models together needs its search: one @search, on a non-null argument " \
85
+ '(`search: String!`), which there is no table to list without')
86
+ end
87
+
88
+ # The models of the union's or the interface's object types: each must be a model's.
89
+ def together_models(path)
90
+ types = @schema.possible_types(returned).sort_by(&:graphql_name)
91
+ types.map do |type|
92
+ Lighthouse::GraphQL::Directives::ModelDirective.model_for(type) ||
93
+ fail!(path, "#{abstract_name}'s type #{type.graphql_name} is no model's: give it @model(class:), or remove it")
94
+ end
95
+ end
96
+
97
+ def together_adapter!(path, models)
98
+ adapter = Lighthouse::Search.adapter_together(models) || no_engine!(path, models)
99
+ models.each do |model|
100
+ error = adapter.together_error(model)
101
+ fail!(path, error) if error
102
+ end
103
+ adapter
104
+ end
105
+
106
+ # What one model's search would apply, and a search of several cannot: the field's own query
107
+ # directives and `scopes:`, @trashed (each model has its own soft-delete column) and default
108
+ # values the engine cannot apply.
109
+ def together_constraints!(path, adapter)
110
+ name = adapter.class.name.demodulize
111
+ dropped = dropped_constraints
112
+ fail!(path, "#{name} cannot apply #{dropped.join(', ')} to models searched together; remove them") unless dropped.empty?
113
+ trashed = Lighthouse::Support::ArgumentWalk.field_definitions(@field_def).find do |_, argument|
114
+ Lighthouse::Support::ArgumentWalk.directives(argument).any? { |directive| directive.name == 'trashed' }
115
+ end
116
+ fail!(path, "@trashed on #{trashed.first} cannot filter models searched together, each with its own soft deletes") if trashed
117
+ defaulted_constraints.each do |constraint|
118
+ fail!(path, "#{name} cannot apply #{constraint}, whose default value would apply to every search; remove the default")
119
+ end
120
+ end
121
+
122
+ def no_engine!(path, models)
123
+ engines = models.map { |model| "#{model.name} (#{engine_name(model)})" }
124
+ fail!(path, "no engine searches #{abstract_name}'s models together: #{engines.join(', ')}. One engine searches them " \
125
+ 'all: Searchkick, or pg_search through its multisearch documents')
126
+ end
127
+
128
+ def engine_name(model) = Lighthouse::Search.adapter_for(model)&.class&.name&.demodulize || 'not searchable'
129
+
130
+ def together_can_query!(path, can_query)
131
+ return if Lighthouse::Support::DirectiveArgs.literal(can_query, 'scopes').blank?
132
+
133
+ fail!(path, 'the `scopes:` of @canQuery cannot narrow models searched together; remove them')
134
+ end
135
+
136
+ def abstract_name = returned.graphql_name
137
+ end
@@ -0,0 +1,101 @@
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
+ # searchable_together?(model) can it search the model with others (optional, with together_error)?
12
+ # together_error(model) why it cannot search the model with others as it is, or nil
13
+ #
14
+ # Models searched together (a field of a union or an interface: FieldCheck) are one search
15
+ # over all of them, a Query with `models`, which the adapter answers with `page`, whatever it
16
+ # is: Searchkick over their indices, pg_search through its multisearch documents.
17
+ #
18
+ # `query` is a Search::Query. A relational adapter lets every other directive of
19
+ # the field apply on top of the scope; the others (Searchkick) answer on their own
20
+ # and take only the directives that include Contracts::SearchBuilder. The
21
+ # protocol is experimental until both adapters have shipped.
22
+ #
23
+ # The adapter is detected per model (Search::Auto): Searchkick, then pg_search.
24
+ # `Config.search` replaces the detection with one adapter, or the app's own.
25
+ #
26
+ # A model's `search_results` scope, when it has one, is what a search of it may
27
+ # return, checked in the database: pg_search applies it to the search, Searchkick
28
+ # loads the records it finds through it (`scope_results:`), so a record an index
29
+ # not yet updated still holds is not returned.
30
+ module Lighthouse::Search
31
+ RESULTS_SCOPE = :search_results
32
+
33
+ module_function
34
+
35
+ # The adapter in use: Config.search, else the detecting one.
36
+ def adapter
37
+ Lighthouse::Config.search || (@default ||= Lighthouse::Search::Auto.new)
38
+ end
39
+
40
+ # The adapter that searches `model`, or nil.
41
+ def adapter_for(model, index = nil)
42
+ adapter = self.adapter
43
+ return adapter.adapter_for(model, index) if adapter.respond_to?(:adapter_for)
44
+
45
+ adapter if adapter.searchable?(model, index)
46
+ end
47
+
48
+ # Does the model have a `search_results` scope?
49
+ def results_scope?(model) = model.respond_to?(RESULTS_SCOPE)
50
+
51
+ # The relation through the model's `search_results` scope, if it has one.
52
+ def results(relation)
53
+ results_scope?(relation.klass) ? relation.public_send(RESULTS_SCOPE) : relation
54
+ end
55
+
56
+ # [path, @search directive node] for every argument and input field of the
57
+ # field carrying @search, at any depth (Support::ArgumentWalk). Walked once per
58
+ # field (Support::Memo.on), the first time it is asked (Search::FieldCheck,
59
+ # when the schema is built).
60
+ def directives(field_def)
61
+ Lighthouse::Support::Memo.on(field_def, :searches) do
62
+ walk = Lighthouse::Support::ArgumentWalk
63
+ walk.field_definitions(field_def).flat_map do |path, argument|
64
+ walk.directives(argument).select { |d| d.name == 'search' }.map { |dnode| [path, dnode] }
65
+ end.freeze
66
+ end
67
+ end
68
+
69
+ # The field's own query constraints an engine outside the database cannot apply
70
+ # ("`scopes:`" of its resolving directive `directive`, "@builder", "@whereAuth",
71
+ # "@orderBy"): Search::FieldCheck refuses them when the schema is built, and
72
+ # BaseDirectiveResolver as a search runs, for a field whose model the build
73
+ # could not tell. Worked out once per field and directive.
74
+ def dropped_constraints(field_def, directive)
75
+ Lighthouse::Support::Memo.on(field_def, :dropped_constraints) { {}.compare_by_identity }[directive] ||= begin
76
+ scopes = Lighthouse::Support::DirectiveArgs.literal(directive, 'scopes') if directive
77
+ queries = Lighthouse::GraphQL::DirectiveResolvers::BuilderApplier.query_directives(field_def.ast_node)
78
+ ((scopes.present? ? ['`scopes:`'] : []) + queries.map { |query| "@#{query.name}" }).freeze
79
+ end
80
+ end
81
+
82
+ # Does the field have an argument or input field with @search?
83
+ def searching?(field_def) = directives(field_def).any?
84
+
85
+ # The models the field searches together (Search::FieldCheck keeps them when the schema is
86
+ # built: the models of its union's or interface's types), or nil for a field of one model.
87
+ def together(field_def) = Lighthouse::Support::Memo.on(field_def, :searched_together) { nil }
88
+
89
+ def together!(field_def, models)
90
+ field_def.instance_variable_set(:@lighthouse_searched_together, models.freeze)
91
+ end
92
+
93
+ # The adapter that searches `models` together (`searchable_together?` each of them, and
94
+ # `together_error`), or nil when none does.
95
+ def adapter_together(models)
96
+ adapter = self.adapter
97
+ return adapter.adapter_together(models) if adapter.respond_to?(:adapter_together)
98
+
99
+ adapter if adapter.respond_to?(:together_error) && models.all? { |model| adapter.searchable_together?(model) }
100
+ end
101
+ 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
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ # What a block works out for a key, kept: the one cache of what Lighthouse
4
+ # reads of a model or an index (Search::Searchkick, Search::Searchkick::Index).
5
+ #
6
+ # - A value belongs to the class it was worked out for (`owner`): a class code
7
+ # reloading makes, under the same name, is worked out again.
8
+ # - With `ttl:`, a value is worked out again once it is that many seconds old;
9
+ # without, it is kept.
10
+ # - With `failed_ttl:`, a block that raises is kept as a failure that long
11
+ # (`get` answers nil, `failure` the error), and `on_failure` hears of it
12
+ # once; without, the error is raised.
13
+ # - One block at a time works out a key: other threads asking for it meanwhile
14
+ # wait and take its value, so the source is asked once however many ask.
15
+ class Lighthouse::Support::Memo
16
+ Entry = Struct.new(:owner, :value, :error, :expires)
17
+
18
+ # What the block works out for `object` (a field's definition), kept on it as
19
+ # `name`: worked out once, the first time it is asked (when the schema is
20
+ # built), and gone with the object, as a schema built again on reload is.
21
+ def self.on(object, name)
22
+ ivar = :"@lighthouse_#{name}"
23
+ return object.instance_variable_get(ivar) if object.instance_variable_defined?(ivar)
24
+
25
+ object.instance_variable_set(ivar, yield)
26
+ end
27
+
28
+ # `clock`: seconds, monotonic.
29
+ def initialize(ttl: nil, failed_ttl: nil, on_failure: nil, clock: -> { Process.clock_gettime(Process::CLOCK_MONOTONIC) })
30
+ @ttl = ttl
31
+ @failed_ttl = failed_ttl
32
+ @on_failure = on_failure
33
+ @clock = clock
34
+ @entries = {}
35
+ @locks = {}
36
+ @lock = Mutex.new
37
+ end
38
+
39
+ # The value for `key` and `owner`, worked out by the block when none is kept.
40
+ def get(key, owner = nil, &block)
41
+ entry = kept(key, owner)
42
+ return entry.value if entry
43
+
44
+ lock_for(key).synchronize do
45
+ entry = kept(key, owner) || (@entries[key] = work_out(owner, &block))
46
+ entry.value
47
+ end
48
+ end
49
+
50
+ # The error the last block for `key` raised, while its failure is kept; else nil.
51
+ def failure(key, owner = nil) = kept(key, owner)&.error
52
+
53
+ private
54
+
55
+ def kept(key, owner)
56
+ entry = @entries[key]
57
+ return nil unless entry && entry.owner.equal?(owner)
58
+
59
+ entry if entry.expires.nil? || @clock.call < entry.expires
60
+ end
61
+
62
+ def work_out(owner)
63
+ Entry.new(owner, yield, nil, @ttl && (@clock.call + @ttl))
64
+ rescue StandardError => e
65
+ raise unless @failed_ttl
66
+
67
+ @on_failure&.call(e)
68
+ Entry.new(owner, nil, e, @clock.call + @failed_ttl)
69
+ end
70
+
71
+ def lock_for(key) = @lock.synchronize { @locks[key] ||= Mutex.new }
72
+ end
@@ -13,6 +13,30 @@ module Lighthouse::Support::ModelResolver
13
13
 
14
14
  DEFAULT_NAMESPACES = ['App::Graphql'].freeze
15
15
 
16
+ # The suffix of a type Lighthouse generates for @paginate: PostPaginator, PostSimplePaginator, PostConnection.
17
+ PAGINATION_SUFFIX = /(SimplePaginator|Paginator|Connection)\z/
18
+
19
+ # The name of the model a directive on a field acts on: the directive's own
20
+ # `model:`, else the `model:` of another directive on the field
21
+ # (`@count(model: "Post") @canQuery`), else the field's return type without a
22
+ # generated Paginator/Connection suffix. `directive_node` nil: the field's.
23
+ def field_model_name(field_def, directive_node = nil)
24
+ Lighthouse::Support::DirectiveArgs.literal(directive_node, 'model') ||
25
+ (field_def.ast_node&.directives || []).filter_map { |d| Lighthouse::Support::DirectiveArgs.literal(d, 'model') }.first ||
26
+ field_def.type.unwrap.graphql_name.sub(PAGINATION_SUFFIX, '')
27
+ end
28
+
29
+ # Is `value` an Active Record model class (not ActiveRecord::Base itself)?
30
+ def model?(value)
31
+ !!(defined?(::ActiveRecord::Base) && value.is_a?(Class) && value < ::ActiveRecord::Base)
32
+ end
33
+
34
+ # The Active Record model a class, or a class name, names; nil for anything else.
35
+ def model_class(name_or_class)
36
+ model = name_or_class.is_a?(Class) ? name_or_class : constantize(name_or_class)
37
+ model if model?(model)
38
+ end
39
+
16
40
  def namespaces
17
41
  if defined?(Lighthouse::Config) &&
18
42
  Lighthouse::Config.respond_to?(:resolver_namespaces) &&
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ # What tells two relations of a model apart by the records they select, for
4
+ # the checks a search outside the database needs: is a relation the model's
5
+ # own (Search::Enhancer), has the model a default scope (Search::Searchkick)?
6
+ module Lighthouse::Support::Relations
7
+ module_function
8
+
9
+ # The parts of a relation that decide which records it selects. Order, select
10
+ # and preloading do not.
11
+ SELECTING = %i[where_clause having_clause from_clause joins_values left_outer_joins_values group_values limit_value offset_value].freeze
12
+
13
+ # Does `relation` select what `other` does? Each part equal, conditions and their
14
+ # values included; a null relation (`none`) selects nothing.
15
+ def same_records?(relation, other)
16
+ null?(relation) == null?(other) && SELECTING.all? { |part| relation.public_send(part) == other.public_send(part) }
17
+ end
18
+
19
+ # Has the model a default scope? Told from its declaration, never from what it
20
+ # selects now: a scope that reads the request (`where(tenant_id:
21
+ # Current.tenant_id) if Current.tenant_id`) narrows nothing outside one, and
22
+ # everything within. Any default scope counts, an order alone too.
23
+ def default_scope?(model) = model.respond_to?(:default_scopes) && model.default_scopes.any?
24
+
25
+ # `none`: a null relation (Rails 7.1+ answers null_relation?).
26
+ def null?(relation)
27
+ return relation.null_relation? if relation.respond_to?(:null_relation?)
28
+
29
+ !!(defined?(::ActiveRecord::NullRelation) && relation.is_a?(::ActiveRecord::NullRelation))
30
+ end
31
+ end
@@ -12,8 +12,11 @@
12
12
  # `Config.soft_deletes` replaces the detection with an adapter of the app's
13
13
  # own: any object answering `soft_deletes?(model)`, `only_trashed(relation)`,
14
14
  # `with_trashed(relation)`, `without_trashed(relation)`, `restore(record)` and
15
- # `force_delete(record)` (the last two answering whether they succeeded).
16
- # `Column.new(:archived_at)` is a ready-made one for another column name.
15
+ # `force_delete(record)` (the last two answering whether they succeeded), and
16
+ # optionally `column(model)` and `kept_value(model)`: the column that marks the
17
+ # trashed records and its value for the others, which a search engine filters on
18
+ # (Search::Searchkick). `Column.new(:archived_at)` is a ready-made one for another
19
+ # column name.
17
20
  module Lighthouse::Support::SoftDeletes
18
21
  module_function
19
22
 
@@ -49,16 +52,36 @@ module Lighthouse::Support::SoftDeletes
49
52
  adapter.without_trashed(relation)
50
53
  end
51
54
 
55
+ TRASHED = { 'ONLY' => :only, 'WITH' => :with, 'WITHOUT' => :without }.freeze
56
+
57
+ # :only, :with or :without, for a `Trashed` enum value (ONLY, WITH or WITHOUT).
58
+ def trashed(value)
59
+ TRASHED.fetch(value.to_s.upcase) do
60
+ raise ::GraphQL::ExecutionError, "Unknown trashed value #{value.inspect}, expected ONLY, WITH or WITHOUT."
61
+ end
62
+ end
63
+
52
64
  # The relation for a `Trashed` enum value: ONLY, WITH or WITHOUT.
53
- def filter(relation, trashed)
54
- case trashed.to_s.upcase
55
- when 'ONLY' then only_trashed(relation)
56
- when 'WITH' then with_trashed(relation)
57
- when 'WITHOUT' then without_trashed(relation)
58
- else raise ::GraphQL::ExecutionError, "Unknown trashed value #{trashed.inspect}, expected ONLY, WITH or WITHOUT."
65
+ def filter(relation, value)
66
+ case trashed(value)
67
+ when :only then only_trashed(relation)
68
+ when :with then with_trashed(relation)
69
+ else without_trashed(relation)
59
70
  end
60
71
  end
61
72
 
73
+ # The column that marks the model's trashed records, as the adapter tells it
74
+ # (`column(model)`), for a search engine to filter on; nil when it does not.
75
+ def column(model)
76
+ adapter.respond_to?(:column) ? adapter.column(model)&.to_s : nil
77
+ end
78
+
79
+ # What that column holds for the records that are not trashed: nil, or
80
+ # paranoia's sentinel value (`kept_value(model)`).
81
+ def kept_value(model)
82
+ adapter.respond_to?(:kept_value) ? adapter.kept_value(model) : nil
83
+ end
84
+
62
85
  def restore(record)
63
86
  require_support!(record.class)
64
87
  adapter.restore(record)
@@ -88,6 +111,9 @@ module Lighthouse::Support::SoftDeletes
88
111
  def restore(record) = record.restore
89
112
 
90
113
  def force_delete(record) = record.really_destroy!
114
+
115
+ def column(model) = model.paranoia_column
116
+ def kept_value(model) = model.paranoia_sentinel_value
91
117
  end
92
118
 
93
119
  # discard: `kept` / `discarded` scopes, `#undiscard`; `#destroy` really deletes.
@@ -105,6 +131,9 @@ module Lighthouse::Support::SoftDeletes
105
131
  def restore(record) = record.undiscard
106
132
 
107
133
  def force_delete(record) = record.destroy
134
+
135
+ def column(model) = model.discard_column
136
+ def kept_value(_model) = nil
108
137
  end
109
138
 
110
139
  # A nullable timestamp column (`deleted_at` by default) and no gem. It marks
@@ -133,6 +162,9 @@ module Lighthouse::Support::SoftDeletes
133
162
  end
134
163
 
135
164
  def force_delete(record) = record.destroy
165
+
166
+ def column(_model) = @column
167
+ def kept_value(_model) = nil
136
168
  end
137
169
 
138
170
  # The default adapter: asks each strategy, in order, whether the model uses it.
@@ -150,6 +182,8 @@ module Lighthouse::Support::SoftDeletes
150
182
  def without_trashed(relation) = strategy!(relation.klass).without_trashed(relation)
151
183
  def restore(record) = strategy!(record.class).restore(record)
152
184
  def force_delete(record) = strategy!(record.class).force_delete(record)
185
+ def column(model) = strategy(model)&.column(model)
186
+ def kept_value(model) = strategy(model)&.kept_value(model)
153
187
 
154
188
  private
155
189