lighthouse-graphql 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (49) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +80 -1
  3. data/README.md +14 -8
  4. data/docs/configuration.md +4 -10
  5. data/docs/directives.md +4 -0
  6. data/docs/federation.md +250 -75
  7. data/docs/filtering-and-ordering.md +79 -0
  8. data/docs/getting-started.md +2 -4
  9. data/docs/subscriptions.md +142 -2
  10. data/lib/generators/lighthouse/install/templates/initializer.rb.tt +2 -4
  11. data/lib/lighthouse/controller.rb +35 -8
  12. data/lib/lighthouse/directive_resolvers/all_resolver.rb +2 -2
  13. data/lib/lighthouse/directive_resolvers/base.rb +17 -0
  14. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +2 -2
  15. data/lib/lighthouse/directive_resolvers/paginate_resolver.rb +2 -0
  16. data/lib/lighthouse/directives/pagination_manipulator.rb +7 -1
  17. data/lib/lighthouse/event_stream.rb +188 -0
  18. data/lib/lighthouse/federation/any.rb +19 -0
  19. data/lib/lighthouse/federation/apollo_federation_check.rb +89 -0
  20. data/lib/lighthouse/federation/callback_subscriptions.rb +261 -0
  21. data/lib/lighthouse/federation/definitions.rb +83 -0
  22. data/lib/lighthouse/federation/entities.rb +265 -0
  23. data/lib/lighthouse/federation/link.rb +89 -0
  24. data/lib/lighthouse/federation/printer.rb +44 -0
  25. data/lib/lighthouse/federation.rb +145 -0
  26. data/lib/lighthouse/graphql/version.rb +1 -1
  27. data/lib/lighthouse/graphql_ruby_patches.rb +7 -1
  28. data/lib/lighthouse/namespaces.rb +1 -0
  29. data/lib/lighthouse/rb_lighthouse.rb +10 -2
  30. data/lib/lighthouse/scalar_coercion.rb +3 -2
  31. data/lib/lighthouse/schema_generator.rb +14 -17
  32. data/lib/lighthouse/schema_printer.rb +3 -1
  33. data/lib/lighthouse/search/auto.rb +5 -0
  34. data/lib/lighthouse/search/enhancer.rb +25 -1
  35. data/lib/lighthouse/search/field_check.rb +3 -1
  36. data/lib/lighthouse/search/pg_search.rb +70 -0
  37. data/lib/lighthouse/search/query.rb +20 -1
  38. data/lib/lighthouse/search/result.rb +2 -2
  39. data/lib/lighthouse/search/searchkick.rb +47 -4
  40. data/lib/lighthouse/search/together_check.rb +137 -0
  41. data/lib/lighthouse/search.rb +23 -0
  42. data/lib/lighthouse/type_resolution.rb +5 -4
  43. data/sig/lighthouse/federation.rbs +51 -0
  44. data/sig/lighthouse/graphql.rbs +29 -0
  45. data/sig/lighthouse/search.rbs +23 -2
  46. data/sig/lighthouse.rbs +14 -0
  47. metadata +12 -3
  48. data/lib/lighthouse/federation_directives.rb +0 -53
  49. data/lib/lighthouse/reference_resolver.rb +0 -22
@@ -0,0 +1,261 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+ require 'net/http'
5
+ require 'concurrent'
6
+ require 'active_support/json'
7
+
8
+ # Federated subscriptions: a graphql-ruby subscription backend that delivers a
9
+ # subgraph's Subscription fields to Apollo Router through its HTTP callback
10
+ # protocol (https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/callback-protocol).
11
+ # Clients subscribe through the router (WebSocket or multipart HTTP); the
12
+ # router asks the subgraph with an ordinary POST that carries
13
+ # `extensions.subscription` (callbackUrl, subscriptionId, verifier,
14
+ # heartbeatIntervalMs), and the subgraph sends every update to callbackUrl.
15
+ #
16
+ # class AppSchema < Lighthouse::GraphQL::RbLightHouse.get_schema(...)
17
+ # use Lighthouse::GraphQL::Federation::CallbackSubscriptions
18
+ # end
19
+ #
20
+ # Lighthouse::GraphQL::Controller reads the extension. The subscription runs as
21
+ # any other: its class's `authorized?` / `authorize?`, then, the router having
22
+ # answered the protocol's `check`, it is kept, and the request answers
23
+ # `{ "data": null }`. `@broadcast` and `trigger` then reach it as they reach an
24
+ # ActionCable one: each update runs the subscriber's operation again, in its
25
+ # context, and goes to the router as a `next` message; one the router answers
26
+ # 404 (the client left) is dropped. Every subscription is sent the `check`
27
+ # heartbeat its router asks for, and a `complete` when it ends here
28
+ # (`unsubscribe`).
29
+ #
30
+ # It is graphql-ruby's ActionCableSubscriptions as well: a subscription without
31
+ # a callback, over Server-Sent Events (Lighthouse::GraphQL::EventStream, which
32
+ # GraphQL Yoga and Hive Gateway ask a subgraph for) or an Action Cable channel
33
+ # (WebSocket), is that backend's, and one trigger reaches all three.
34
+ #
35
+ # Subscriptions live in the process that received them, as ActionCable's do. A
36
+ # trigger from another process (a job, another Puma worker) reaches them
37
+ # through ActionCable's pubsub when the app has Action Cable (its cable.yml
38
+ # adapter: solid_cable, redis, postgresql), else only the triggering process'
39
+ # own callback subscriptions are updated. A restarted process loses its
40
+ # subscriptions: the router ends them when their heartbeats stop, and its
41
+ # clients subscribe again.
42
+ #
43
+ # Options: `client:` posts the messages (`post(url, body) -> status`, Net::HTTP
44
+ # by default), `tick:` how often, in seconds, due heartbeats are sent (1), and
45
+ # ActionCableSubscriptions' own.
46
+ class Lighthouse::GraphQL::Federation::CallbackSubscriptions < GraphQL::Subscriptions::ActionCableSubscriptions
47
+ # Where the controller puts the router's extension, in the operation's context.
48
+ CONTEXT_KEY = :lighthouse_subscription_callback
49
+
50
+ HEADERS = { 'Content-Type' => 'application/json', 'subscription-protocol' => 'callback/1.0' }.freeze
51
+
52
+ # The router's `extensions.subscription` for a subscription it asks for.
53
+ Callback = Struct.new(:url, :id, :verifier, :heartbeat_ms, keyword_init: true) do
54
+ # The extension of a request's `extensions`, or nil.
55
+ def self.from_extensions(extensions)
56
+ subscription = subscription_of(extensions)
57
+ return if subscription.nil? || subscription[:callbackUrl].blank? || subscription[:subscriptionId].blank?
58
+
59
+ new(url: subscription[:callbackUrl].to_s, id: subscription[:subscriptionId].to_s, verifier: subscription[:verifier].to_s,
60
+ heartbeat_ms: subscription[:heartbeatIntervalMs].to_i)
61
+ end
62
+
63
+ # `extensions.subscription`, from a JSON string, a Hash or parameters.
64
+ def self.subscription_of(extensions)
65
+ extensions = JSON.parse(extensions) if extensions.is_a?(String) && !extensions.empty?
66
+ extensions = extensions.to_unsafe_h if extensions.respond_to?(:to_unsafe_h)
67
+ subscription = extensions.is_a?(Hash) ? extensions.with_indifferent_access[:subscription] : nil
68
+ subscription.to_h.with_indifferent_access if subscription.respond_to?(:to_h)
69
+ end
70
+
71
+ def message(action, **rest)
72
+ { kind: 'subscription', action: action, id: id, verifier: verifier, **rest }
73
+ end
74
+ end
75
+
76
+ # Posts a message with Net::HTTP; answers the status.
77
+ class NetHttpClient
78
+ def initialize(open_timeout: 5, read_timeout: 10)
79
+ @open_timeout = open_timeout
80
+ @read_timeout = read_timeout
81
+ end
82
+
83
+ def post(url, body)
84
+ uri = URI(url)
85
+ Net::HTTP.start(uri.host, uri.port, use_ssl: uri.scheme == 'https', open_timeout: @open_timeout, read_timeout: @read_timeout) do |http|
86
+ http.post(uri.request_uri, body, HEADERS).code.to_i
87
+ end
88
+ end
89
+ end
90
+
91
+ # A kept subscription: its operation, its events and where its updates go.
92
+ Entry = Struct.new(:query, :events, :callback, :due_at, keyword_init: true)
93
+
94
+ # The context of an operation the router sent (`extensions` from its
95
+ # request): what the backend keeps it by. Empty for any other.
96
+ def self.context_for(extensions)
97
+ callback = Callback.from_extensions(extensions)
98
+ callback ? { CONTEXT_KEY => callback } : {}
99
+ end
100
+
101
+ # The body of the router's request once the subscription ran: `{ data: null }`,
102
+ # with the operation's errors (an unauthorized subscriber, an invalid
103
+ # operation); a 400 when the router refused the `check`. Nil for any other.
104
+ def self.response(result)
105
+ context = result.respond_to?(:context) ? result.context : nil
106
+ callback = context && context[CONTEXT_KEY]
107
+ return unless callback
108
+
109
+ errors = result.to_h['errors']
110
+ return [{ 'errors' => [{ 'message' => 'The router refused the subscription callback check.' }] }, 400] if context[:lighthouse_callback_refused]
111
+
112
+ [errors ? { 'data' => nil, 'errors' => errors } : { 'data' => nil }, 200]
113
+ end
114
+
115
+ # Action Cable, when the app has it (ActionCableSubscriptions' `action_cable:`).
116
+ def initialize(client: NetHttpClient.new, tick: 1, action_cable: (::ActionCable if defined?(::ActionCable)), **rest)
117
+ super(action_cable: action_cable, **rest)
118
+ @client = client
119
+ @tick = tick
120
+ @entries = Concurrent::Map.new
121
+ @topics = Concurrent::Map.new
122
+ @streams = Concurrent::Set.new
123
+ @lock = Mutex.new
124
+ end
125
+
126
+ # The router's subscription ran: `check` its callback, then keep it. One over
127
+ # SSE or a channel is ActionCableSubscriptions'; any other is refused.
128
+ def write_subscription(query, events)
129
+ callback = query.context[CONTEXT_KEY]
130
+ return super if callback.nil? && query.context[:channel]
131
+ return refuse(query) unless callback
132
+
133
+ if send_message(callback, :check) == 204
134
+ keep(query, events, callback)
135
+ else
136
+ query.context[:lighthouse_callback_refused] = true
137
+ end
138
+ end
139
+
140
+ # Updates every subscription to the event's topic: through ActionCable's
141
+ # pubsub, in every process, when it is there (ActionCableSubscriptions'
142
+ # broadcast, which this process' callback subscriptions listen to as well).
143
+ def execute_all(event, object)
144
+ pubsub ? super : execute_topic(event.topic, object)
145
+ end
146
+
147
+ def read_subscription(subscription_id)
148
+ entry = @entries[subscription_id]
149
+ return super unless entry
150
+
151
+ { query_string: entry.query.query_string, variables: entry.query.provided_variables, context: entry.query.context.to_h,
152
+ operation_name: entry.query.operation_name }
153
+ end
154
+
155
+ # A `next` message with the update; a subscription the router no longer has is dropped.
156
+ def deliver(subscription_id, result)
157
+ entry = @entries[subscription_id]
158
+ return super unless entry
159
+
160
+ status = send_message(entry.callback, :next, payload: result.to_h.slice('data', 'errors'))
161
+ drop(subscription_id) unless (200..299).cover?(status)
162
+ end
163
+
164
+ # Ended here (`unsubscribe`): the router is told it is `complete`.
165
+ def delete_subscription(subscription_id)
166
+ return super unless @entries.key?(subscription_id)
167
+
168
+ entry = drop(subscription_id)
169
+ send_message(entry.callback, :complete) if entry
170
+ end
171
+
172
+ # Sends the heartbeats that are due; the timer calls it every `tick` seconds.
173
+ def heartbeat!(now = monotonic)
174
+ @entries.each_pair do |id, entry|
175
+ next if entry.callback.heartbeat_ms <= 0 || entry.due_at > now
176
+
177
+ entry.due_at = next_heartbeat(entry.callback, now)
178
+ drop(id) unless send_message(entry.callback, :check) == 204
179
+ end
180
+ end
181
+
182
+ # The ids of the subscriptions this process keeps: the router's, then the others'.
183
+ def subscription_ids = @entries.keys + @subscriptions.keys
184
+
185
+ private
186
+
187
+ def refuse(query)
188
+ message = 'This subgraph delivers subscriptions through Apollo Router HTTP callbacks, Server-Sent Events ' \
189
+ '(Accept: text/event-stream) or Action Cable: subscribe through one of them.'
190
+ query.context.add_error(::GraphQL::ExecutionError.new(message))
191
+ end
192
+
193
+ def keep(query, events, callback)
194
+ query.context[:subscription_id] = callback.id
195
+ @entries[callback.id] = Entry.new(query: query, events: events, callback: callback, due_at: next_heartbeat(callback))
196
+ events.each do |event|
197
+ (@topics.compute_if_absent(event.topic) { Concurrent::Array.new }) << callback.id
198
+ stream(event)
199
+ end
200
+ start_heartbeats
201
+ end
202
+
203
+ def execute_topic(topic, object)
204
+ (@topics[topic] || []).dup.each do |id|
205
+ entry = @entries[id]
206
+ event = entry&.events&.find { |candidate| candidate.topic == topic }
207
+ execute(id, event, object) if event
208
+ end
209
+ end
210
+
211
+ # Forgets a subscription, without telling the router; answers its entry.
212
+ def drop(subscription_id)
213
+ entry = @entries.delete(subscription_id)
214
+ entry&.events&.each { |event| @topics[event.topic]&.delete(subscription_id) }
215
+ entry
216
+ end
217
+
218
+ # The router's status; 0 when it could not be reached.
219
+ def send_message(callback, action, **rest)
220
+ @client.post(callback.url, JSON.generate(callback.message(action.to_s, **rest)))
221
+ rescue StandardError => e
222
+ message = "Lighthouse: subscription callback #{action} to #{callback.url} failed: #{e.class}: #{e.message}"
223
+ ::Rails.logger&.warn(message) if defined?(::Rails.logger)
224
+ 0
225
+ end
226
+
227
+ # ActionCable's pubsub, when the app has Action Cable configured; nil otherwise.
228
+ def pubsub
229
+ return unless @action_cable.respond_to?(:server)
230
+
231
+ @action_cable.server.pubsub
232
+ rescue StandardError
233
+ nil
234
+ end
235
+
236
+ # Listens, once per process, to the broadcasting of a topic's events
237
+ # (ActionCableSubscriptions'), for the callback subscriptions to it.
238
+ def stream(event)
239
+ adapter = pubsub
240
+ return unless adapter && @streams.add?(event.topic)
241
+
242
+ adapter.subscribe(stream_event_name(event), lambda { |message|
243
+ execute_topic(event.topic, load_action_cable_message(ActiveSupport::JSON.decode(message), event.context))
244
+ })
245
+ end
246
+
247
+ def start_heartbeats
248
+ @lock.synchronize do
249
+ return if @timer
250
+
251
+ @timer = Concurrent::TimerTask.new(execution_interval: @tick) { heartbeat! }
252
+ @timer.execute
253
+ end
254
+ end
255
+
256
+ def next_heartbeat(callback, now = monotonic)
257
+ now + (callback.heartbeat_ms / 1000.0)
258
+ end
259
+
260
+ def monotonic = Process.clock_gettime(Process::CLOCK_MONOTONIC)
261
+ end
@@ -0,0 +1,83 @@
1
+ # frozen_string_literal: true
2
+
3
+ # The SDL of the Apollo Federation spec's directives and of the types they
4
+ # take, under the names the schema's Link gives them. The subgraph declares
5
+ # none of them: what it uses is injected while the schema is built, as
6
+ # Lighthouse's own directives are, and left out of the SDL the gateway
7
+ # composes (Federation::Printer), which knows them from the link.
8
+ module Lighthouse::GraphQL::Federation::Definitions
9
+ # Where @tag and @inaccessible may go.
10
+ EVERYWHERE = 'FIELD_DEFINITION | OBJECT | INTERFACE | UNION | ARGUMENT_DEFINITION | SCALAR | ENUM | ENUM_VALUE | ' \
11
+ 'INPUT_OBJECT | INPUT_FIELD_DEFINITION'
12
+
13
+ # Where the access-control directives (@authenticated, @requiresScopes, @policy) go.
14
+ ACCESS = 'FIELD_DEFINITION | OBJECT | INTERFACE | SCALAR | ENUM'
15
+
16
+ # By spec name: the definition, with %<name>s for the local name of each
17
+ # spec directive and type it mentions. Federation 1 knows the first five.
18
+ DIRECTIVES = {
19
+ 'key' => 'directive @%<key>s(fields: %<FieldSet>s!, resolvable: Boolean = true) repeatable on OBJECT | INTERFACE',
20
+ 'requires' => 'directive @%<requires>s(fields: %<FieldSet>s!) on FIELD_DEFINITION',
21
+ 'provides' => 'directive @%<provides>s(fields: %<FieldSet>s!) on FIELD_DEFINITION',
22
+ 'external' => 'directive @%<external>s on OBJECT | FIELD_DEFINITION',
23
+ 'extends' => 'directive @%<extends>s on OBJECT | INTERFACE',
24
+ 'tag' => "directive @%<tag>s(name: String!) repeatable on #{EVERYWHERE} | SCHEMA",
25
+ 'shareable' => 'directive @%<shareable>s repeatable on OBJECT | FIELD_DEFINITION',
26
+ 'inaccessible' => "directive @%<inaccessible>s on #{EVERYWHERE}",
27
+ 'override' => 'directive @%<override>s(from: String!, label: String) on FIELD_DEFINITION',
28
+ 'composeDirective' => 'directive @%<composeDirective>s(name: String!) repeatable on SCHEMA',
29
+ 'interfaceObject' => 'directive @%<interfaceObject>s on OBJECT',
30
+ 'authenticated' => "directive @%<authenticated>s on #{ACCESS}",
31
+ 'requiresScopes' => "directive @%<requiresScopes>s(scopes: [[%<Scope>s!]!]!) on #{ACCESS}",
32
+ 'policy' => "directive @%<policy>s(policies: [[%<Policy>s!]!]!) on #{ACCESS}",
33
+ 'context' => 'directive @%<context>s(name: String!) repeatable on INTERFACE | OBJECT | UNION',
34
+ 'fromContext' => 'directive @%<fromContext>s(field: %<ContextFieldValue>s) on ARGUMENT_DEFINITION',
35
+ 'cost' => 'directive @%<cost>s(weight: Int!) on ARGUMENT_DEFINITION | ENUM | FIELD_DEFINITION | INPUT_FIELD_DEFINITION | OBJECT | SCALAR',
36
+ 'listSize' => 'directive @%<listSize>s(assumedSize: Int, slicingArguments: [String!], sizedFields: [String!], ' \
37
+ 'requireOneSlicingArgument: Boolean = true) on FIELD_DEFINITION'
38
+ }.freeze
39
+
40
+ V1_DIRECTIVES = %w[key requires provides external extends].freeze
41
+
42
+ # The spec's scalars, by spec name.
43
+ TYPES = %w[FieldSet Scope Policy ContextFieldValue].freeze
44
+
45
+ # The link spec's own, which a Federation 2 schema uses to declare its links.
46
+ LINK = {
47
+ 'link' => 'directive @link(url: String!, as: String, import: [link__Import], for: link__Purpose) repeatable on SCHEMA'
48
+ }.freeze
49
+
50
+ LINK_TYPES = {
51
+ 'link__Import' => 'scalar link__Import',
52
+ 'link__Purpose' => <<~GRAPHQL.chomp
53
+ enum link__Purpose {
54
+ "`SECURITY` features provide metadata necessary to securely resolve fields."
55
+ SECURITY
56
+ "`EXECUTION` features provide metadata necessary for operation execution."
57
+ EXECUTION
58
+ }
59
+ GRAPHQL
60
+ }.freeze
61
+
62
+ module_function
63
+
64
+ # { local name => definition } of every spec directive the link knows.
65
+ def directives(link)
66
+ names = names(link)
67
+ spec = link.v2? ? DIRECTIVES : DIRECTIVES.slice(*V1_DIRECTIVES)
68
+ definitions = spec.to_h { |name, sdl| [link.directive(name), format(sdl, names)] }
69
+ link.v2? ? definitions.merge(LINK) : definitions
70
+ end
71
+
72
+ # { local name => definition } of the spec's scalars (and the link spec's types).
73
+ def types(link)
74
+ scalars = TYPES.to_h { |name| [link.type(name), "scalar #{link.type(name)}"] }
75
+ link.v2? ? scalars.merge(LINK_TYPES) : scalars.slice(link.type('FieldSet'))
76
+ end
77
+
78
+ # The local names of the spec's directives and types, as format's references.
79
+ def names(link)
80
+ directive_names = DIRECTIVES.keys.to_h { |name| [name.to_sym, link.directive(name)] }
81
+ directive_names.merge(TYPES.to_h { |name| [name.to_sym, link.type(name)] })
82
+ end
83
+ end
@@ -0,0 +1,265 @@
1
+ # frozen_string_literal: true
2
+
3
+ # `Query._entities(representations:)`: the entities the gateway asks a subgraph
4
+ # for, by their keys: `[{ "__typename": "User", "id": "1" }, ...]`. As PHP
5
+ # Lighthouse's Entities and EntityResolverProvider, the representations are
6
+ # grouped by __typename and each group is resolved once, in order, by:
7
+ #
8
+ # 1. The type class, Types::<Name>Type including Lighthouse::GraphQL::Type, as
9
+ # graphql-ruby's federation does it: `self.resolve_references(representations,
10
+ # context)` for the group at once (an Array, in their order), or
11
+ # `self.resolve_reference(representation, context)` for each.
12
+ # 2. The type's model (@model(class:), else the model of its name), queried by
13
+ # the first @key whose fields the representation has, as PHP Lighthouse does,
14
+ # but in one query for the whole group. A key field with @globalId is
15
+ # decoded; a nested selection (`@key(fields: "author { id }")`) joins the
16
+ # association. The values the gateway sends for the type's @external fields
17
+ # (those a @requires asks for) are set on each record.
18
+ # 3. The representation itself, for a type that has no model: its fields read
19
+ # the representation's values, or are resolved by its type class.
20
+ #
21
+ # An entity interface (`interface Media @key(fields: "id")`, Federation 2.3) is
22
+ # looked up in the models of the types that implement it, in turn, and each
23
+ # record answers as the object type it resolves to (TypeResolution).
24
+ #
25
+ # A representation nothing is found for is null, as the spec allows.
26
+ module Lighthouse::GraphQL::Federation::Entities
27
+ Nodes = ::GraphQL::Language::Nodes
28
+
29
+ # The context key of { entity => object type }, for _Entity's resolve_type.
30
+ TYPES = :lighthouse_federation_entity_types
31
+
32
+ module_function
33
+
34
+ def resolve(representations, context)
35
+ schema = context.schema
36
+ results = Array.new(representations.size)
37
+ representations.each_with_index.group_by { |representation, _| typename(representation) }.each do |typename, entries|
38
+ type = entity_type(schema, typename)
39
+ unique = entries.map(&:first).uniq
40
+ found = unique.zip(resolve_group(schema, type, unique, context)).to_h
41
+ entries.each { |representation, index| results[index] = remember(schema, type, found[representation], context) }
42
+ end
43
+ results
44
+ end
45
+
46
+ # The object type `_Entity` resolves `object` to, when `_entities` returned it.
47
+ def type_of(object, context)
48
+ map = context[TYPES]
49
+ map[object] if map
50
+ end
51
+
52
+ def typename(representation)
53
+ name = representation['__typename'] || representation[:__typename]
54
+ raise ::GraphQL::ExecutionError, 'Each representation must have a __typename.' if name.blank?
55
+
56
+ name.to_s
57
+ end
58
+
59
+ def entity_type(schema, typename)
60
+ type = schema.get_type(typename)
61
+ return type if type && (type.kind.object? || type.kind.interface?)
62
+
63
+ raise ::GraphQL::ExecutionError, "Unknown __typename `#{typename}`."
64
+ end
65
+
66
+ def resolve_group(schema, type, representations, context)
67
+ klass = Lighthouse::GraphQL::Type.class_for(type.graphql_name, type.kind.interface? ? :interface : :object)
68
+ return Array(klass.resolve_references(representations, context)) if klass.respond_to?(:resolve_references)
69
+ return representations.map { |representation| klass.resolve_reference(representation, context) } if klass.respond_to?(:resolve_reference)
70
+
71
+ return from_models(schema, type, representations, context) if type.kind.interface?
72
+
73
+ model = Lighthouse::GraphQL::Directives::ModelDirective.model_for(type)
74
+ return representations unless Lighthouse::Support::ModelResolver.model?(model)
75
+
76
+ Lookup.new(schema, type, context).find(model, representations)
77
+ end
78
+
79
+ # An entity interface: each implementing type's model, in turn, for the
80
+ # representations not found yet.
81
+ def from_models(schema, interface, representations, context)
82
+ found = {}
83
+ lookup = Lookup.new(schema, interface, context)
84
+ interface_models(schema, interface).each do |model|
85
+ missing = representations.reject { |representation| found[representation] }
86
+ next if missing.empty?
87
+
88
+ missing.zip(lookup.find(model, missing)).each { |representation, record| found[representation] = record if record }
89
+ end
90
+ representations.map { |representation| found[representation] }
91
+ end
92
+
93
+ # The models of the types implementing an entity interface, in their order.
94
+ def interface_models(schema, interface)
95
+ models = schema.possible_types(interface).map { |type| Lighthouse::GraphQL::Directives::ModelDirective.model_for(type) }
96
+ models = models.select { |model| Lighthouse::Support::ModelResolver.model?(model) }
97
+ return models if models.any?
98
+
99
+ raise ::GraphQL::ExecutionError,
100
+ "Lighthouse can not resolve the entity interface #{interface.graphql_name}: none of its types has a model. " \
101
+ "Define Types::#{interface.graphql_name}Type's resolve_reference(representation, context)."
102
+ end
103
+
104
+ # Keeps the object type of what was found, for the _Entity union.
105
+ def remember(schema, type, object, context)
106
+ return if object.nil?
107
+
108
+ concrete = type.kind.object? ? type : Lighthouse::GraphQL::TypeResolution.resolve(schema, type, object, context)
109
+ concrete, object = concrete if concrete.is_a?(Array)
110
+ (context[TYPES] ||= {}.compare_by_identity)[object] = concrete
111
+ object
112
+ end
113
+
114
+ # The records of a model for representations of `type`, by its keys.
115
+ class Lookup
116
+ def initialize(schema, type, context)
117
+ @schema = schema
118
+ @type = type
119
+ @context = context
120
+ @link = Lighthouse::GraphQL::Federation.schema_link(schema)
121
+ end
122
+
123
+ # The record for each representation, or nil, in their order.
124
+ def find(model, representations)
125
+ keyed = representations.map { |representation| [representation, key_for(representation)] }
126
+ found = {}
127
+ keyed.group_by(&:last).each do |selections, group|
128
+ found.merge!(find_by_key(model, selections, group.map(&:first)))
129
+ end
130
+ representations.map { |representation| hydrate(found[representation], representation) }
131
+ end
132
+
133
+ private
134
+
135
+ # The first @key whose fields the representation has, as PHP Lighthouse picks it.
136
+ def key_for(representation)
137
+ key = keys.find { |selections| satisfies?(selections, representation) }
138
+ return key if key
139
+
140
+ raise ::GraphQL::ExecutionError,
141
+ "Representation does not satisfy any set of uniquely identifying keys: #{representation.to_h.to_json}"
142
+ end
143
+
144
+ # Each @key(fields:) of the type, parsed: its field selections.
145
+ def keys
146
+ @keys ||= (@type.ast_node&.directives || []).select { |d| d.name == @link.directive('key') }.map do |directive|
147
+ fields = Lighthouse::Support::DirectiveArgs.literal(directive, 'fields').to_s
148
+ ::GraphQL::Language::Parser.parse("{ #{fields} }").definitions.first.selections
149
+ end
150
+ end
151
+
152
+ def satisfies?(selections, value)
153
+ selections.all? do |selection|
154
+ raise Lighthouse::DefinitionError, "@key on #{@type.graphql_name} may only select fields." unless selection.is_a?(Nodes::Field)
155
+
156
+ nested = value.is_a?(Hash) ? value[selection.name] : nil
157
+ next false if nested.nil?
158
+
159
+ selection.selections.empty? || satisfies?(selection.selections, nested)
160
+ end
161
+ end
162
+
163
+ # { representation => record } for representations sharing a key: one
164
+ # query for them all when the key's fields are flat, one each otherwise.
165
+ def find_by_key(model, selections, representations)
166
+ return representations.index_with { |representation| find_one(model, selections, representation) } if nested?(selections)
167
+
168
+ columns = selections.map { |selection| column(@type, selection.name) }
169
+ rows = representations.index_with { |representation| key_row(selections, representation) }
170
+ records = by_columns(rows.values.uniq.map { |row| model.where(columns.zip(row).to_h) }.reduce(:or), columns)
171
+ rows.transform_values { |row| records[row.map(&:to_s)] }
172
+ end
173
+
174
+ # The relation's records by the values of `columns`, as strings.
175
+ def by_columns(relation, columns)
176
+ relation.to_a.index_by { |record| columns.map { |column| record.public_send(column).to_s } }
177
+ end
178
+
179
+ # The representation's values of a flat key's fields, as the columns hold them.
180
+ def key_row(selections, representation)
181
+ selections.map { |selection| key_value(@type, selection, representation[selection.name]) }
182
+ end
183
+
184
+ def nested?(selections)
185
+ selections.any? { |selection| selection.selections.any? }
186
+ end
187
+
188
+ def find_one(model, selections, representation)
189
+ records = constrain(model.all, @type, selections, representation).limit(2).to_a
190
+ raise ::GraphQL::ExecutionError, 'The query returned more than one result.' if records.size > 1
191
+
192
+ records.first
193
+ end
194
+
195
+ # `relation` constrained to the key's values; a nested selection joins its association.
196
+ def constrain(relation, type, selections, values)
197
+ selections.reduce(relation) do |scope, selection|
198
+ attribute = column(type, selection.name)
199
+ value = values[selection.name]
200
+ next scope.where(attribute => key_value(type, selection, value)) if selection.selections.empty?
201
+
202
+ join(scope, type, selection, attribute, value)
203
+ end
204
+ end
205
+
206
+ # `scope` joined to the association a nested key selection names, constrained to its values.
207
+ def join(scope, type, selection, attribute, value)
208
+ association = scope.klass.reflect_on_association(attribute.to_sym)
209
+ unless association
210
+ raise Lighthouse::DefinitionError, "@key on #{type.graphql_name} selects #{selection.name}, which is no association of #{scope.klass}."
211
+ end
212
+
213
+ field_type = type.get_field(selection.name).type.unwrap
214
+ scope.joins(association.name).merge(constrain(association.klass.all, field_type, selection.selections, value))
215
+ end
216
+
217
+ # A key field's value as the column holds it: a @globalId field's decoded.
218
+ def key_value(type, selection, value)
219
+ field = type.get_field(selection.name)
220
+ return value unless field && directive?(field, 'globalId')
221
+
222
+ Lighthouse::GraphQL::GlobalId.decode!(value, @context).last
223
+ end
224
+
225
+ # The attribute a field of `type` reads: its @rename's, else its name in snake_case.
226
+ def column(type, name)
227
+ field = type.get_field(name)
228
+ rename = field&.ast_node&.directives&.find { |d| d.name == 'rename' }
229
+ (rename && Lighthouse::Support::DirectiveArgs.literal(rename, 'attribute')) || Lighthouse::Support::Naming.attribute(name)
230
+ end
231
+
232
+ def directive?(field, name)
233
+ (field.ast_node&.directives || []).any? { |d| d.name == name }
234
+ end
235
+
236
+ # The values the gateway sent for the type's @external fields (those a
237
+ # @requires needs), set on the record, as PHP Lighthouse sets them.
238
+ def hydrate(record, representation)
239
+ return record if record.nil? || !@type.kind.object?
240
+
241
+ external_fields.each do |field|
242
+ next unless representation.key?(field.graphql_name)
243
+
244
+ assign(record, column(@type, field.graphql_name), representation[field.graphql_name])
245
+ end
246
+ record
247
+ end
248
+
249
+ def external_fields
250
+ external = @link.directive('external')
251
+ type_external = (@type.ast_node&.directives || []).any? { |d| d.name == external }
252
+ @type.fields.values.select { |field| type_external || directive?(field, external) }
253
+ end
254
+
255
+ # A column is written (not saved); anything else answers from the record.
256
+ def assign(record, attribute, value)
257
+ if record.respond_to?(:has_attribute?) && record.has_attribute?(attribute)
258
+ record[attribute] = value
259
+ record.clear_attribute_change(attribute) if record.respond_to?(:clear_attribute_change)
260
+ else
261
+ record.define_singleton_method(attribute) { value }
262
+ end
263
+ end
264
+ end
265
+ end