lighthouse-graphql 0.9.1 → 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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +64 -1
- data/README.md +14 -8
- data/docs/configuration.md +4 -10
- data/docs/federation.md +250 -75
- data/docs/getting-started.md +2 -4
- data/docs/subscriptions.md +142 -2
- data/lib/generators/lighthouse/install/templates/initializer.rb.tt +2 -4
- data/lib/lighthouse/controller.rb +35 -8
- data/lib/lighthouse/directives/pagination_manipulator.rb +7 -1
- data/lib/lighthouse/event_stream.rb +188 -0
- data/lib/lighthouse/federation/any.rb +19 -0
- data/lib/lighthouse/federation/apollo_federation_check.rb +89 -0
- data/lib/lighthouse/federation/callback_subscriptions.rb +261 -0
- data/lib/lighthouse/federation/definitions.rb +83 -0
- data/lib/lighthouse/federation/entities.rb +265 -0
- data/lib/lighthouse/federation/link.rb +89 -0
- data/lib/lighthouse/federation/printer.rb +44 -0
- data/lib/lighthouse/federation.rb +145 -0
- data/lib/lighthouse/graphql/version.rb +1 -1
- data/lib/lighthouse/graphql_ruby_patches.rb +7 -1
- data/lib/lighthouse/namespaces.rb +1 -0
- data/lib/lighthouse/rb_lighthouse.rb +9 -2
- data/lib/lighthouse/scalar_coercion.rb +3 -2
- data/lib/lighthouse/schema_generator.rb +12 -17
- data/lib/lighthouse/schema_printer.rb +3 -1
- data/lib/lighthouse/type_resolution.rb +5 -4
- data/sig/lighthouse/federation.rbs +51 -0
- data/sig/lighthouse/graphql.rbs +29 -0
- data/sig/lighthouse.rbs +6 -0
- metadata +11 -3
- data/lib/lighthouse/federation_directives.rb +0 -53
- data/lib/lighthouse/reference_resolver.rb +0 -22
data/docs/subscriptions.md
CHANGED
|
@@ -36,6 +36,11 @@ end
|
|
|
36
36
|
|
|
37
37
|
## Enabling a backend
|
|
38
38
|
|
|
39
|
+
A subgraph behind Apollo Router delivers its subscriptions through the router
|
|
40
|
+
instead, with `Lighthouse::GraphQL::Federation::CallbackSubscriptions`: see
|
|
41
|
+
[federation.md](federation.md#subscriptions). Everything below about the
|
|
42
|
+
subscription fields, their classes and `@broadcast` holds for it too.
|
|
43
|
+
|
|
39
44
|
graphql-ruby delivers subscriptions through a *backend* that stores who subscribed
|
|
40
45
|
and sends the updates: ActionCable (bundled), or a gem such as Pusher or Ably.
|
|
41
46
|
Lighthouse needs none of its own; give the schema one with `use`, in the schema
|
|
@@ -91,6 +96,141 @@ GlobalID. A Rails app that loads ActiveJob has that; one that picks its railties
|
|
|
91
96
|
(an API-only `config/application.rb`) needs `require 'global_id/railtie'`, or the
|
|
92
97
|
subscribers would receive the model's `inspect` string.
|
|
93
98
|
|
|
99
|
+
## Over Server-Sent Events
|
|
100
|
+
|
|
101
|
+
The same backend serves subscriptions over
|
|
102
|
+
[Server-Sent Events](https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events),
|
|
103
|
+
with nothing more to set up: `Lighthouse::GraphQL::Controller` answers a request
|
|
104
|
+
whose `Accept` names `text/event-stream` (a GET or a POST to the endpoint) in
|
|
105
|
+
[graphql-sse](https://github.com/enisdenjo/graphql-sse/blob/master/PROTOCOL.md)'s
|
|
106
|
+
*distinct connections* mode, which `graphql-sse`'s client, GraphQL Yoga, Hive
|
|
107
|
+
Gateway and `@graphql-tools/executor-http` speak:
|
|
108
|
+
|
|
109
|
+
```text
|
|
110
|
+
GET /graphql?query=subscription+%7B+postCreated+%7B+title+%7D+%7D
|
|
111
|
+
Accept: text/event-stream
|
|
112
|
+
|
|
113
|
+
event: next
|
|
114
|
+
data: {"data":{"postCreated":{"title":"Hello"}}}
|
|
115
|
+
|
|
116
|
+
:
|
|
117
|
+
|
|
118
|
+
event: next
|
|
119
|
+
data: {"data":{"postCreated":{"title":"Again"}}}
|
|
120
|
+
|
|
121
|
+
event: complete
|
|
122
|
+
data:
|
|
123
|
+
```
|
|
124
|
+
|
|
125
|
+
Each update is a `next` event; a `:` comment is written every 12 seconds while
|
|
126
|
+
none comes, which keeps proxies from closing the connection and finds out a
|
|
127
|
+
client that left; `complete` ends the stream when the subscription ends on the
|
|
128
|
+
server (`unsubscribe`, `delete_subscription`). A client that goes away ends it
|
|
129
|
+
too, and its subscription is deleted. A query or a mutation sent this way is one
|
|
130
|
+
`next` and `complete`.
|
|
131
|
+
|
|
132
|
+
The response stands for an Action Cable channel (`channel` in the operation's
|
|
133
|
+
context, as `GraphqlChannel` gives a socket's), so `ActionCableSubscriptions`
|
|
134
|
+
keeps an SSE subscription as it keeps a WebSocket one, and one trigger reaches
|
|
135
|
+
both through Action Cable's pubsub. Action Cable's server speaks WebSocket only:
|
|
136
|
+
it is its pubsub, the `cable.yml` adapter, that SSE rides on, so the app needs
|
|
137
|
+
Action Cable loaded and configured, but no socket open. The rules above hold:
|
|
138
|
+
a shared adapter for triggers from other processes, GlobalID for the roots.
|
|
139
|
+
|
|
140
|
+
Each open stream holds the server thread that answers it (as
|
|
141
|
+
`ActionController::Live` does): size Puma's threads (or run a server that
|
|
142
|
+
streams without one, such as Falcon) for the subscribers you expect. An update
|
|
143
|
+
runs on a thread of its own, inside the app's executor, as Action Cable runs a
|
|
144
|
+
channel's, with its own database connection and query cache.
|
|
145
|
+
|
|
146
|
+
## Choosing a transport
|
|
147
|
+
|
|
148
|
+
There is no switch between them: with `ActionCableSubscriptions` as the backend,
|
|
149
|
+
WebSocket and Server-Sent Events are both on, and each client picks one per
|
|
150
|
+
operation. A `@broadcast` reaches the subscribers of both; the server never needs
|
|
151
|
+
to know which one a subscriber came through.
|
|
152
|
+
|
|
153
|
+
| | WebSocket (Action Cable) | Server-Sent Events |
|
|
154
|
+
| --- | --- | --- |
|
|
155
|
+
| The client connects to | `/cable`, and calls the `GraphqlChannel`'s `execute` | the GraphQL endpoint, with `Accept: text/event-stream` |
|
|
156
|
+
| The server needs | Action Cable mounted, `ApplicationCable::Connection` and the [channel above](#enabling-a-backend) | nothing more than the backend and `cable.yml` (Action Cable loaded, no socket served) |
|
|
157
|
+
| Who the user is | the channel's context (`current_user` from `identified_by`) | the endpoint's `graphql_context`, as for its queries (`Authorization`, the session cookie) |
|
|
158
|
+
| One connection carries | every operation of the client, both ways | one subscription, server to client |
|
|
159
|
+
| Holds on the server | a socket, in Action Cable's own worker pool | a server thread per open stream ([above](#over-server-sent-events)) |
|
|
160
|
+
| Gets through | proxies and load balancers that upgrade connections | anything that passes HTTP; multiplexed over HTTP/2 |
|
|
161
|
+
| Spoken by | `@rails/actioncable` with `graphql-ruby-client` (Apollo, Relay, urql) | `graphql-sse`, GraphQL Yoga and Hive Gateway, `@graphql-tools/executor-http`, `EventSource` |
|
|
162
|
+
|
|
163
|
+
Server-Sent Events are the simpler of the two to run: plain HTTP, the endpoint's
|
|
164
|
+
authentication, and what gateways speak to their subgraphs (a subgraph behind
|
|
165
|
+
GraphQL Yoga needs nothing else; see [federation.md](federation.md#subscriptions)).
|
|
166
|
+
WebSocket shares one connection between all of a client's operations, and costs
|
|
167
|
+
the server no thread per subscription: prefer it for many subscriptions per
|
|
168
|
+
client, or many clients on a threaded server such as Puma.
|
|
169
|
+
|
|
170
|
+
### A client over Server-Sent Events
|
|
171
|
+
|
|
172
|
+
[`graphql-sse`](https://github.com/enisdenjo/graphql-sse)'s client, in its
|
|
173
|
+
default *distinct connections* mode (`singleConnection: false`), which is the one
|
|
174
|
+
Lighthouse speaks: each subscription is a POST that accepts `text/event-stream`.
|
|
175
|
+
|
|
176
|
+
```js
|
|
177
|
+
import { createClient } from 'graphql-sse';
|
|
178
|
+
|
|
179
|
+
const client = createClient({
|
|
180
|
+
url: '/graphql',
|
|
181
|
+
headers: () => ({ Authorization: `Bearer ${token}` }),
|
|
182
|
+
});
|
|
183
|
+
|
|
184
|
+
const unsubscribe = client.subscribe(
|
|
185
|
+
{ query: 'subscription { postCreated { title } }' },
|
|
186
|
+
{ next: (result) => console.log(result.data), error: console.error, complete: () => {} },
|
|
187
|
+
);
|
|
188
|
+
// unsubscribe() closes the stream, and the server deletes the subscription.
|
|
189
|
+
```
|
|
190
|
+
|
|
191
|
+
Without a library, the browser's `EventSource` sends a GET with the operation in
|
|
192
|
+
the query string (it cannot set headers, so it authenticates with the session cookie):
|
|
193
|
+
|
|
194
|
+
```js
|
|
195
|
+
const query = encodeURIComponent('subscription { postCreated { title } }');
|
|
196
|
+
const source = new EventSource(`/graphql?query=${query}`, { withCredentials: true });
|
|
197
|
+
|
|
198
|
+
source.addEventListener('next', (event) => console.log(JSON.parse(event.data)));
|
|
199
|
+
source.addEventListener('complete', () => source.close());
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
### A client over WebSocket
|
|
203
|
+
|
|
204
|
+
[`graphql-ruby-client`](https://graphql-ruby.org/javascript_client/apollo_subscriptions)'s
|
|
205
|
+
link sends subscriptions to the `GraphqlChannel`, and the rest over HTTP, in
|
|
206
|
+
Apollo Client (`createActionCableHandler` does the same for Relay):
|
|
207
|
+
|
|
208
|
+
```js
|
|
209
|
+
import { ApolloClient, ApolloLink, HttpLink, InMemoryCache } from '@apollo/client';
|
|
210
|
+
import { getMainDefinition } from '@apollo/client/utilities';
|
|
211
|
+
import { createConsumer } from '@rails/actioncable';
|
|
212
|
+
import ActionCableLink from 'graphql-ruby-client/subscriptions/ActionCableLink';
|
|
213
|
+
|
|
214
|
+
const cable = createConsumer(`/cable?token=${token}`); // a browser WebSocket cannot set headers
|
|
215
|
+
const subscription = ({ query }) => {
|
|
216
|
+
const definition = getMainDefinition(query);
|
|
217
|
+
return definition.kind === 'OperationDefinition' && definition.operation === 'subscription';
|
|
218
|
+
};
|
|
219
|
+
|
|
220
|
+
const client = new ApolloClient({
|
|
221
|
+
link: ApolloLink.split(subscription, new ActionCableLink({ cable }), new HttpLink({ uri: '/graphql' })),
|
|
222
|
+
cache: new InMemoryCache(),
|
|
223
|
+
});
|
|
224
|
+
```
|
|
225
|
+
|
|
226
|
+
The token in the URL is read by `ApplicationCable::Connection`, which identifies
|
|
227
|
+
the socket (`identified_by :current_user`), and the channel passes it on in the
|
|
228
|
+
context; the example app's [`connection.rb`](https://github.com/Vaz-Innovation/lighthouse-graphql/blob/main/examples/graphql/app/channels/application_cable/connection.rb)
|
|
229
|
+
does that.
|
|
230
|
+
|
|
231
|
+
A client can use both, for instance WebSocket in the browser and SSE from a
|
|
232
|
+
server or a gateway: they are the same subscriptions.
|
|
233
|
+
|
|
94
234
|
## Defining subscription fields
|
|
95
235
|
|
|
96
236
|
A field of the `Subscription` type needs nothing but its SDL, and then
|
|
@@ -446,8 +586,8 @@ the repository's own specs do, in `spec/support/in_memory_subscriptions.rb`.
|
|
|
446
586
|
graphql-ruby also ships `GraphQL::Testing::MockActionCable` for the real
|
|
447
587
|
ActionCable backend.
|
|
448
588
|
|
|
449
|
-
The repository's `
|
|
589
|
+
The repository's `examples/graphql/` app is a complete setup: subscription classes under
|
|
450
590
|
`Subscriptions::BaseSubscription`,
|
|
451
591
|
`GraphqlChannel`, `ApplicationCable::Connection` with token authentication, and
|
|
452
592
|
specs that drive a mutation through `POST /graphql` and watch the update arrive on
|
|
453
|
-
an ActionCable subscriber (`
|
|
593
|
+
an ActionCable subscriber (`examples/graphql/spec/subscriptions/delivery_spec.rb`).
|
|
@@ -89,12 +89,10 @@ Lighthouse.configure do |config|
|
|
|
89
89
|
# config.feature_checker = ->(name, actor, _ctx) { Flipper.enabled?(name.to_sym, actor) }
|
|
90
90
|
end
|
|
91
91
|
|
|
92
|
-
# Register app-defined directives
|
|
93
|
-
#
|
|
94
|
-
# is built. See docs/custom-directives.md and docs/federation.md.
|
|
92
|
+
# Register app-defined directives inside to_prepare, so they reference
|
|
93
|
+
# reloadable constants and run before the schema is built. See docs/custom-directives.md.
|
|
95
94
|
# Rails.application.config.to_prepare do
|
|
96
95
|
# Lighthouse::DirectiveRegistry.register(Directives::Upcase)
|
|
97
|
-
# Lighthouse::ReferenceResolver.register('User') { |ref, _ctx| User.find_by(id: ref['id']) }
|
|
98
96
|
# end
|
|
99
97
|
|
|
100
98
|
# Listen to Lighthouse's request, schema-build and execution events. A listener
|
|
@@ -90,21 +90,28 @@ module Lighthouse::GraphQL::Controller
|
|
|
90
90
|
end
|
|
91
91
|
|
|
92
92
|
# What PersistedQueries runs an operation with: its query, extensions, variables and
|
|
93
|
-
# name, in the request's context.
|
|
93
|
+
# name, in the request's context. A subscription Apollo Router asks a subgraph
|
|
94
|
+
# for carries its callback in the extensions (Federation::CallbackSubscriptions).
|
|
94
95
|
def lighthouse_arguments(operation)
|
|
95
96
|
operation = operation.with_indifferent_access if operation.is_a?(Hash)
|
|
97
|
+
context = lighthouse_context.merge(Lighthouse::GraphQL::Federation::CallbackSubscriptions.context_for(operation[:extensions]))
|
|
96
98
|
{ query: operation[:query], extensions: operation[:extensions], variables: graphql_variables(operation[:variables]),
|
|
97
|
-
operation_name: operation[:operationName], context:
|
|
99
|
+
operation_name: operation[:operationName], context: context }
|
|
98
100
|
end
|
|
99
101
|
|
|
100
|
-
# One operation:
|
|
101
|
-
# once, for
|
|
102
|
+
# One operation: over Server-Sent Events when the client asks for them, else answered whole,
|
|
103
|
+
# or streamed (Defer) when it defers. The schema is resolved once, for all.
|
|
102
104
|
def lighthouse_respond(operation)
|
|
103
105
|
schema = graphql_schema
|
|
106
|
+
return lighthouse_event_stream(operation, schema) if !request.head? && Lighthouse::GraphQL::EventStream.accepted?(request.headers['Accept'])
|
|
107
|
+
|
|
104
108
|
stream_type = lighthouse_stream_type(schema)
|
|
105
109
|
return lighthouse_incremental(operation, schema, stream_type) if stream_type
|
|
106
110
|
|
|
107
111
|
result = lighthouse_operation(operation, schema)
|
|
112
|
+
callback = Lighthouse::GraphQL::Federation::CallbackSubscriptions.response(result)
|
|
113
|
+
return render json: callback.first, status: callback.last if callback
|
|
114
|
+
|
|
108
115
|
Lighthouse::GraphQL::CacheControl.apply(response, result)
|
|
109
116
|
render json: result
|
|
110
117
|
end
|
|
@@ -139,11 +146,31 @@ module Lighthouse::GraphQL::Controller
|
|
|
139
146
|
def lighthouse_stream(run, stream_type)
|
|
140
147
|
multipart = Lighthouse::GraphQL::Incremental::Multipart.new(keep: Lighthouse::Events.listening?(Lighthouse::Events::EndRequest))
|
|
141
148
|
first = lighthouse_first_part(run, multipart)
|
|
142
|
-
Lighthouse::GraphQL::Incremental::Multipart.headers(stream_type).each { |name, value| response.headers[name] = value }
|
|
143
149
|
ended = -> { Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(multipart.ended(response))) }
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
150
|
+
body = Lighthouse::GraphQL::Incremental::Body.new(run, multipart, first, on_error: method(:lighthouse_report), on_end: ended)
|
|
151
|
+
lighthouse_body(body, Lighthouse::GraphQL::Incremental::Multipart.headers(stream_type))
|
|
152
|
+
end
|
|
153
|
+
|
|
154
|
+
# An operation over Server-Sent Events (EventStream), for a client whose Accept asks for
|
|
155
|
+
# `text/event-stream`: its result as a `next` event and, a subscription, each update as
|
|
156
|
+
# another, until it ends. The stream is the operation's Action Cable channel (`channel` in
|
|
157
|
+
# its context, as GraphqlChannel gives a socket's), so the schema's ActionCableSubscriptions
|
|
158
|
+
# (or Federation::CallbackSubscriptions) delivers to it as to a WebSocket. It ends the request
|
|
159
|
+
# once it is done.
|
|
160
|
+
def lighthouse_event_stream(operation, schema)
|
|
161
|
+
ended = -> { Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(response)) }
|
|
162
|
+
stream = Lighthouse::GraphQL::EventStream.new(schema, on_error: method(:lighthouse_report), on_end: ended)
|
|
163
|
+
arguments = lighthouse_arguments(operation)
|
|
164
|
+
stream.start(Lighthouse::GraphQL::PersistedQueries.execute(schema, **arguments, context: arguments[:context].merge(channel: stream)))
|
|
165
|
+
lighthouse_body(stream, Lighthouse::GraphQL::EventStream.headers)
|
|
166
|
+
end
|
|
167
|
+
|
|
168
|
+
# A body the server writes after the action, as it comes; finished once the response is.
|
|
169
|
+
def lighthouse_body(body, headers)
|
|
170
|
+
headers.each { |name, value| response.headers[name] = value }
|
|
171
|
+
@lighthouse_body = body
|
|
172
|
+
request.env['rack.response_finished']&.push(->(*) { body.finish })
|
|
173
|
+
self.response_body = body
|
|
147
174
|
end
|
|
148
175
|
|
|
149
176
|
def lighthouse_first_part(run, multipart)
|
|
@@ -46,9 +46,15 @@ class Lighthouse::GraphQL::Directives::PaginationManipulator
|
|
|
46
46
|
# pageInfo, edges, node) take their parent's maxAge, as in PHP Lighthouse:
|
|
47
47
|
# they are not entities of their own, so they must not turn a cacheable
|
|
48
48
|
# page into `no-cache`.
|
|
49
|
+
#
|
|
50
|
+
# In a Federation 2 subgraph the generated types are @shareable: every
|
|
51
|
+
# subgraph that paginates generates the same PaginatorInfo, PageInfo, ...,
|
|
52
|
+
# which the gateway may then resolve from any of them.
|
|
49
53
|
def initialize(document, cache_control: false)
|
|
50
54
|
@document = document
|
|
51
55
|
@inherit = cache_control ? ' @cacheControl(inheritMaxAge: true)' : ''
|
|
56
|
+
link = Lighthouse::GraphQL::Federation::Link.from_document(document)
|
|
57
|
+
@shareable = link&.v2? ? " @#{link.directive('shareable')}" : ''
|
|
52
58
|
@defined = document.definitions.filter_map { |d| d.name if d.respond_to?(:name) && !d.class.name.end_with?('Extension') }
|
|
53
59
|
@generated = {}
|
|
54
60
|
end
|
|
@@ -108,7 +114,7 @@ class Lighthouse::GraphQL::Directives::PaginationManipulator
|
|
|
108
114
|
end
|
|
109
115
|
|
|
110
116
|
def generate(name, sdl)
|
|
111
|
-
@generated[name] ||= sdl.strip
|
|
117
|
+
@generated[name] ||= sdl.strip.sub(/^type #{name}\b/, "type #{name}#{@shareable}")
|
|
112
118
|
end
|
|
113
119
|
|
|
114
120
|
def paginator_type(item, suffix, info)
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'active_support/json'
|
|
4
|
+
require 'time'
|
|
5
|
+
|
|
6
|
+
# GraphQL over Server-Sent Events: the response of a request whose Accept names
|
|
7
|
+
# `text/event-stream`, in graphql-sse's distinct connections mode
|
|
8
|
+
# (https://github.com/enisdenjo/graphql-sse/blob/master/PROTOCOL.md), which
|
|
9
|
+
# GraphQL Yoga, Hive Gateway and @graphql-tools/executor-http speak. Each result
|
|
10
|
+
# is a `next` event, and a `complete` event ends the stream:
|
|
11
|
+
#
|
|
12
|
+
# event: next
|
|
13
|
+
# data: {"data":{"postCreated":{"title":"Hello"}}}
|
|
14
|
+
#
|
|
15
|
+
# event: complete
|
|
16
|
+
# data:
|
|
17
|
+
#
|
|
18
|
+
# A query or a mutation is one `next` and the `complete`. A subscription stays
|
|
19
|
+
# open: the stream stands for an Action Cable channel (`stream_from`, all that
|
|
20
|
+
# graphql-ruby's ActionCableSubscriptions asks of one), so the schema's one
|
|
21
|
+
# backend serves its subscriptions over WebSocket (a channel) and SSE alike, and
|
|
22
|
+
# a trigger reaches both through Action Cable's pubsub (cable.yml's adapter).
|
|
23
|
+
# Each update is a `next`; the subscription ending on the server
|
|
24
|
+
# (`unsubscribe`) is the `complete`; the client going away ends it here.
|
|
25
|
+
#
|
|
26
|
+
# Lighthouse::GraphQL::Controller answers with it, as Rails streams a template
|
|
27
|
+
# (`self.response_body =`): the server iterates `each` in the request's thread,
|
|
28
|
+
# which the stream keeps for as long as it is open (as ActionController::Live
|
|
29
|
+
# does), waiting for its updates and writing a comment every `keep_alive`
|
|
30
|
+
# seconds, which is how a client gone is found out. Each update runs in a
|
|
31
|
+
# thread of its own, inside the Rails app's executor, as Action Cable runs a
|
|
32
|
+
# channel's: its own connections, query cache and reloading.
|
|
33
|
+
class Lighthouse::GraphQL::EventStream
|
|
34
|
+
Gone = Lighthouse::GraphQL::Incremental::Gone
|
|
35
|
+
|
|
36
|
+
CONTENT_TYPE = 'text/event-stream'
|
|
37
|
+
KEEP_ALIVE = ":\n\n"
|
|
38
|
+
COMPLETE = "event: complete\ndata:\n\n"
|
|
39
|
+
|
|
40
|
+
# The subscription the stream delivers, once `start` saw it kept.
|
|
41
|
+
attr_reader :subscription_id
|
|
42
|
+
|
|
43
|
+
# Does an Accept header take an event stream?
|
|
44
|
+
def self.accepted?(accept)
|
|
45
|
+
accept.to_s.split(',').any? { |type| type.split(';').first.to_s.strip.casecmp?(CONTENT_TYPE) }
|
|
46
|
+
end
|
|
47
|
+
|
|
48
|
+
# The headers of the response: as a multipart one's, uncached and unbuffered.
|
|
49
|
+
def self.headers
|
|
50
|
+
Lighthouse::GraphQL::Incremental::Multipart.headers("#{CONTENT_TYPE}; charset=utf-8").merge('Connection' => 'keep-alive')
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# An event of the stream: `next` with a result, as its JSON.
|
|
54
|
+
def self.event(result) = "event: next\ndata: #{ActiveSupport::JSON.encode(result)}\n\n"
|
|
55
|
+
|
|
56
|
+
# The events of a stream's body, as a client reads them: each `next`'s result.
|
|
57
|
+
def self.parse(body)
|
|
58
|
+
body.to_s.split("\n\n").filter_map do |event|
|
|
59
|
+
lines = event.lines.map(&:chomp)
|
|
60
|
+
next unless lines.include?('event: next')
|
|
61
|
+
|
|
62
|
+
JSON.parse(lines.grep(/\Adata:/).map { |line| line.delete_prefix('data:').strip }.join("\n"))
|
|
63
|
+
end
|
|
64
|
+
end
|
|
65
|
+
|
|
66
|
+
# `pubsub`: what subscriptions listen to (Action Cable's, by default, when
|
|
67
|
+
# one is asked for). `on_error` is told of an error that ended the stream on
|
|
68
|
+
# its way, `on_end` that it ended.
|
|
69
|
+
def initialize(schema, pubsub: nil, keep_alive: 12, on_error: nil, on_end: nil)
|
|
70
|
+
@schema = schema
|
|
71
|
+
@pubsub = pubsub
|
|
72
|
+
@executor = ::Rails.application&.executor if defined?(::Rails) && ::Rails.respond_to?(:application)
|
|
73
|
+
@keep_alive = keep_alive
|
|
74
|
+
@on_error = on_error
|
|
75
|
+
@on_end = on_end
|
|
76
|
+
@listeners = []
|
|
77
|
+
@items = []
|
|
78
|
+
@lock = Mutex.new
|
|
79
|
+
@arrived = ConditionVariable.new
|
|
80
|
+
end
|
|
81
|
+
|
|
82
|
+
# The operation's result: the stream's first event, if any, and whether it goes on.
|
|
83
|
+
def start(result)
|
|
84
|
+
hash = result.to_h
|
|
85
|
+
@subscription_id = result.context[:subscription_id] if result.respond_to?(:context)
|
|
86
|
+
@open = result.respond_to?(:subscription?) && result.subscription? && !@subscription_id.nil? && !hash.key?('errors')
|
|
87
|
+
# A subscription's own request answers no data, unless its `subscribe` returned some.
|
|
88
|
+
@first = @open && hash['data'].blank? ? nil : self.class.event(hash)
|
|
89
|
+
self
|
|
90
|
+
end
|
|
91
|
+
|
|
92
|
+
# What graphql-ruby's ActionCableSubscriptions calls on a channel: listen to a
|
|
93
|
+
# broadcasting, with the block (its message decoded by `coder`, when given)
|
|
94
|
+
# or, without one, to send each message (JSON, then) to the client.
|
|
95
|
+
def stream_from(broadcasting, callback = nil, coder: nil, &block)
|
|
96
|
+
handler = block || callback
|
|
97
|
+
coder ||= ActiveSupport::JSON unless handler
|
|
98
|
+
listener = ->(message) { push([handler, coder ? coder.decode(message) : message]) }
|
|
99
|
+
@lock.synchronize { @listeners << [broadcasting, listener] }
|
|
100
|
+
pubsub.subscribe(broadcasting, listener)
|
|
101
|
+
end
|
|
102
|
+
|
|
103
|
+
# The body: the first event, then each update as it comes, until the
|
|
104
|
+
# subscription ends or the client goes away.
|
|
105
|
+
def each(&write)
|
|
106
|
+
emit(write, @first) if @first
|
|
107
|
+
until @done || !@open
|
|
108
|
+
item = pop
|
|
109
|
+
item ? handle(item, write) : emit(write, KEEP_ALIVE)
|
|
110
|
+
end
|
|
111
|
+
emit(write, COMPLETE)
|
|
112
|
+
rescue Gone
|
|
113
|
+
nil
|
|
114
|
+
rescue StandardError => e
|
|
115
|
+
@on_error&.call(e)
|
|
116
|
+
ensure
|
|
117
|
+
finish
|
|
118
|
+
end
|
|
119
|
+
|
|
120
|
+
# Stops listening, forgets the subscription and ends the request, once.
|
|
121
|
+
def finish
|
|
122
|
+
return if @finished
|
|
123
|
+
|
|
124
|
+
@finished = true
|
|
125
|
+
@done = true
|
|
126
|
+
listeners = @lock.synchronize { @listeners.dup.tap { @listeners.clear } }
|
|
127
|
+
listeners.each { |broadcasting, listener| pubsub.unsubscribe(broadcasting, listener) }
|
|
128
|
+
@schema.subscriptions&.delete_subscription(@subscription_id) if @subscription_id
|
|
129
|
+
ensure
|
|
130
|
+
@lock.synchronize { @arrived.broadcast }
|
|
131
|
+
@on_end&.call
|
|
132
|
+
end
|
|
133
|
+
|
|
134
|
+
def open? = @open && !@done
|
|
135
|
+
|
|
136
|
+
private
|
|
137
|
+
|
|
138
|
+
# A message to the client (no handler): its result is a `next`, its end the
|
|
139
|
+
# `complete`. A broadcasting's (a handler) runs the update, which comes back as
|
|
140
|
+
# a message to the client.
|
|
141
|
+
def handle((handler, message), write)
|
|
142
|
+
return update(handler, message) if handler
|
|
143
|
+
return @done = true unless message.is_a?(Hash)
|
|
144
|
+
|
|
145
|
+
emit(write, self.class.event(message['result'])) if message['result']
|
|
146
|
+
@done = true if message['more'] == false
|
|
147
|
+
end
|
|
148
|
+
|
|
149
|
+
# Writes to the client: an error the server raises is the client gone.
|
|
150
|
+
def emit(write, text)
|
|
151
|
+
write.call(text)
|
|
152
|
+
rescue StandardError
|
|
153
|
+
raise Gone
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def update(handler, message)
|
|
157
|
+
run = -> { handler.call(message) }
|
|
158
|
+
@executor ? Thread.new { @executor.wrap(&run) }.join : run.call
|
|
159
|
+
rescue StandardError => e
|
|
160
|
+
@on_error&.call(e)
|
|
161
|
+
end
|
|
162
|
+
|
|
163
|
+
def push(item)
|
|
164
|
+
@lock.synchronize do
|
|
165
|
+
@items << item
|
|
166
|
+
@arrived.signal
|
|
167
|
+
end
|
|
168
|
+
end
|
|
169
|
+
|
|
170
|
+
# The next item, or nil when none came for `keep_alive` seconds.
|
|
171
|
+
def pop
|
|
172
|
+
@lock.synchronize do
|
|
173
|
+
@arrived.wait(@lock, @keep_alive) if @items.empty? && !@done
|
|
174
|
+
@items.shift
|
|
175
|
+
end
|
|
176
|
+
end
|
|
177
|
+
|
|
178
|
+
def pubsub
|
|
179
|
+
@pubsub ||= begin
|
|
180
|
+
unless defined?(::ActionCable) && ::ActionCable.respond_to?(:server)
|
|
181
|
+
raise Lighthouse::DefinitionError,
|
|
182
|
+
'A subscription over Server-Sent Events goes through Action Cable: add it to the app (cable.yml names its pubsub adapter).'
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
::ActionCable.server.pubsub
|
|
186
|
+
end
|
|
187
|
+
end
|
|
188
|
+
end
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
require 'active_support/hash_with_indifferent_access'
|
|
4
|
+
|
|
5
|
+
# The spec's `scalar _Any`: an entity representation the gateway sends to
|
|
6
|
+
# `Query._entities`, `{ "__typename": "User", "id": "1" }`. Read as a Hash
|
|
7
|
+
# whose keys are strings or symbols alike, as the resolvers that receive it
|
|
8
|
+
# (Entities) read it.
|
|
9
|
+
class Lighthouse::GraphQL::Federation::Any < GraphQL::Schema::Scalar
|
|
10
|
+
graphql_name '_Any'
|
|
11
|
+
|
|
12
|
+
def self.coerce_input(value, _context)
|
|
13
|
+
raise ::GraphQL::CoercionError, 'An entity representation is an object with a __typename.' unless value.is_a?(Hash)
|
|
14
|
+
|
|
15
|
+
ActiveSupport::HashWithIndifferentAccess.new(value)
|
|
16
|
+
end
|
|
17
|
+
|
|
18
|
+
def self.coerce_result(value, _context) = value
|
|
19
|
+
end
|
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
# An app coming from graphql-ruby's code-first federation follows the
|
|
4
|
+
# apollo-federation gem's setup: a mixin in each base class
|
|
5
|
+
# (ApolloFederation::Object, Interface, Union, Enum, EnumValue, Scalar,
|
|
6
|
+
# InputObject, Field, Argument) and ApolloFederation::Schema in the schema.
|
|
7
|
+
# Lighthouse is the subgraph itself, from the SDL: those mixins would not
|
|
8
|
+
# federate anything here. The type mixins' declarations (`key fields: :id`,
|
|
9
|
+
# `field :name, external: true`) are never read, and the schema mixin replaces
|
|
10
|
+
# the subgraph's SDL and `_entities` with the gem's, which link Federation 2.3
|
|
11
|
+
# whatever the SDL says. So each is refused, by name, with what to write instead
|
|
12
|
+
# (docs/federation.md#migrating-from-apollo-federation): the base types when the
|
|
13
|
+
# schema is built, the schema mixin as the app's schema class includes it.
|
|
14
|
+
# The gem need not be loaded; its tracing plugin (`use ApolloFederation::Tracing`) is no mixin.
|
|
15
|
+
module Lighthouse::GraphQL::Federation::ApolloFederationCheck
|
|
16
|
+
# The gem's mixins, and what each declared that the SDL says now.
|
|
17
|
+
TYPE_MIXINS = {
|
|
18
|
+
'Object' => '`key fields:`, `extend_type`, `shareable`, `interface_object` → @key, @extends, @shareable, @interfaceObject on the SDL type',
|
|
19
|
+
'Interface' => '`key fields:` → @key on the SDL interface',
|
|
20
|
+
'Union' => '`tag`, `inaccessible` → @tag, @inaccessible on the SDL union',
|
|
21
|
+
'Enum' => '`tag`, `inaccessible` → @tag, @inaccessible on the SDL enum',
|
|
22
|
+
'EnumValue' => '`tags:`, `inaccessible:` → @tag, @inaccessible on the SDL enum value',
|
|
23
|
+
'Scalar' => '`tag`, `inaccessible` → @tag, @inaccessible on the SDL scalar',
|
|
24
|
+
'InputObject' => '`tag`, `inaccessible` → @tag, @inaccessible on the SDL input',
|
|
25
|
+
'Field' => '`external:`, `requires:`, `provides:`, `shareable:`, `override:`, `tags:` → @external, @requires, ... on the SDL field',
|
|
26
|
+
'Argument' => '`tags:`, `inaccessible:` → @tag, @inaccessible on the SDL argument'
|
|
27
|
+
}.freeze
|
|
28
|
+
|
|
29
|
+
GUIDE = 'Lighthouse makes the schema a subgraph from its SDL: `extend schema @link(url: "https://specs.apollo.dev/federation/v2.9", ' \
|
|
30
|
+
'import: ["@key", ...])` and the directives on its types. See docs/federation.md#migrating-from-apollo-federation.'
|
|
31
|
+
|
|
32
|
+
# Refuses `include ApolloFederation::Schema` in a schema class built on Lighthouse's.
|
|
33
|
+
module SchemaGuard
|
|
34
|
+
def include(*modules)
|
|
35
|
+
Lighthouse::GraphQL::Federation::ApolloFederationCheck.refuse_schema_mixin!(self, modules)
|
|
36
|
+
super
|
|
37
|
+
end
|
|
38
|
+
end
|
|
39
|
+
|
|
40
|
+
module_function
|
|
41
|
+
|
|
42
|
+
# The base types (and the field, argument and enum value classes they use)
|
|
43
|
+
# must not include the gem's mixins.
|
|
44
|
+
def check_types!(base_types)
|
|
45
|
+
found = base_classes(base_types).flat_map do |klass|
|
|
46
|
+
TYPE_MIXINS.filter_map { |name, moved| "#{klass} includes ApolloFederation::#{name} (#{moved})" if includes?(klass, name) }
|
|
47
|
+
end.uniq
|
|
48
|
+
return if found.empty?
|
|
49
|
+
|
|
50
|
+
raise Lighthouse::DefinitionError, "#{found.join('; ')}. Remove the apollo-federation mixins: #{GUIDE}"
|
|
51
|
+
end
|
|
52
|
+
|
|
53
|
+
# Guards `schema`, and the app's schema classes inheriting from it.
|
|
54
|
+
def guard!(schema)
|
|
55
|
+
schema.singleton_class.prepend(SchemaGuard) unless schema.singleton_class.include?(SchemaGuard)
|
|
56
|
+
end
|
|
57
|
+
|
|
58
|
+
def refuse_schema_mixin!(schema, modules)
|
|
59
|
+
mixin = mixin('Schema')
|
|
60
|
+
return unless mixin && modules.include?(mixin)
|
|
61
|
+
|
|
62
|
+
raise Lighthouse::DefinitionError,
|
|
63
|
+
"#{schema.name || schema} includes ApolloFederation::Schema, whose subgraph SDL and _entities would replace " \
|
|
64
|
+
"Lighthouse's (linking Federation 2.3 whatever the SDL says). Remove it, with `federation(version:)` and " \
|
|
65
|
+
"`query(superclass.query)`: #{GUIDE}"
|
|
66
|
+
end
|
|
67
|
+
|
|
68
|
+
# Every class a base type names, with the classes of its fields, arguments and enum values.
|
|
69
|
+
def base_classes(base_types)
|
|
70
|
+
base_types.values.grep(Module).flat_map do |klass|
|
|
71
|
+
field_class = klass.respond_to?(:field_class) ? klass.field_class : nil
|
|
72
|
+
argument_classes = [klass, field_class].filter_map { |owner| owner.argument_class if owner.respond_to?(:argument_class) }
|
|
73
|
+
enum_value_class = klass.respond_to?(:enum_value_class) ? klass.enum_value_class : nil
|
|
74
|
+
[klass, field_class, *argument_classes, enum_value_class]
|
|
75
|
+
end.compact.uniq
|
|
76
|
+
end
|
|
77
|
+
|
|
78
|
+
def includes?(klass, name)
|
|
79
|
+
mod = mixin(name)
|
|
80
|
+
!mod.nil? && klass.include?(mod)
|
|
81
|
+
end
|
|
82
|
+
|
|
83
|
+
# The gem's mixin of that name, when the gem is loaded.
|
|
84
|
+
def mixin(name)
|
|
85
|
+
return unless defined?(::ApolloFederation) && ::ApolloFederation.const_defined?(name, false)
|
|
86
|
+
|
|
87
|
+
::ApolloFederation.const_get(name, false)
|
|
88
|
+
end
|
|
89
|
+
end
|