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 CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 16b866dbbae1192cb051baae53de5a7938f9bb16c1f176a5112d8b1893cef78c
4
- data.tar.gz: b0a9ed4c1fdfe4e6d22b7ebb5d07ff192ea661dbaaf7751cc726854edbbdb4b7
3
+ metadata.gz: 815f08a034aad69b3a9c39116785fbc983379a3ded8488dff9771bca2518f982
4
+ data.tar.gz: b5e62380f814db7355ab6853ca7a750161d33b9c6159d60234a23a9ed2fff7cd
5
5
  SHA512:
6
- metadata.gz: 485c2dcd6ade1ff9f1c62be69544114784c18ebedf2e25609791d9113eccdf97ef6b41824fb7b6bf6d0fffa86a95d14aac6f43eab91c21109bf3ec592ffb8192
7
- data.tar.gz: 14a7e8b8718f655c53e9c7594099ba9060b9b34c60eb23a08a258c36856fa459c4da5aaa38ec99c74f32248cc365131a06176928ace9aa46cfbf65cc0e8458ec
6
+ metadata.gz: c85e2db9e25f226a26407e3a3b40798ce0c67201651dac17a04729d07884b511528cf47741ce799811b97e871a527bd3db99a80d6bf809aff456467cf76d18c7
7
+ data.tar.gz: 4cb67b7e7cba66786d169b250e8a2d07e334f494164d172e5c7c71ef4406d87a2345960592694b4bc77d177b088b5620c22709423d0beb696c15204e5f2c052e
data/CHANGELOG.md CHANGED
@@ -6,6 +6,68 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.10.0] - 2026-11-26
10
+
11
+ ### Added
12
+
13
+ - **Federation without `apollo-federation`, ported from PHP Lighthouse.** A schema that `@link`s the
14
+ Federation 2 spec (`extend schema @link(url: "https://specs.apollo.dev/federation/v2.9", import: [...])`)
15
+ is a subgraph; `federation: true` makes one without the link a Federation 1 subgraph. The spec's
16
+ directives it uses are declared for it under the names the link gives them (imports, `as:` renames, the
17
+ `federation__` prefix), and it gets `_Any`, `_Service`, `Query._service` and, with an entity, `_Entity`
18
+ and `Query._entities`.
19
+ - **The subgraph SDL keeps every federation directive** (`_service { sdl }`, `federation_sdl`, `FORMAT=federation`):
20
+ its own `extend schema @link(...)` and `@composeDirective`, and the directives applied to types, fields,
21
+ arguments, enum values and input fields; without Lighthouse's directives or the spec's types, fields and
22
+ definitions.
23
+ - **`_entities` finds a type's entities in one query per key**, by the first `@key` each representation has
24
+ (compound keys, a nested key through its association, a `@globalId` key decoded), on the type's model; or
25
+ through the type class's `resolve_references(representations, context)` / `resolve_reference`; or answers
26
+ the representation itself. The values sent for `@external` fields are set on the records, for `@requires`.
27
+ - **Entity interfaces and `@interfaceObject`**: an interface with `@key` is resolved through its types'
28
+ models, each record answered as its own type.
29
+ - **The types `@paginate` generates are `@shareable`** in a Federation 2 subgraph, since every subgraph that
30
+ paginates generates the same ones.
31
+ - **Federated subscriptions**: `use Lighthouse::GraphQL::Federation::CallbackSubscriptions` delivers the
32
+ Subscription fields to Apollo Router through its HTTP callback protocol (check, next, complete,
33
+ heartbeats), fanned out across processes through Action Cable's pubsub; `Lighthouse::GraphQL::Controller`
34
+ reads the router's `extensions.subscription`.
35
+ - **Subscriptions over Server-Sent Events**: `Lighthouse::GraphQL::Controller` answers a request whose
36
+ `Accept` names `text/event-stream` in graphql-sse's distinct connections mode (what GraphQL Yoga, Hive
37
+ Gateway and `@graphql-tools/executor-http` speak): a `next` event per result and update, keep-alive
38
+ comments, `complete` at the end. The stream is the operation's Action Cable channel, so
39
+ `ActionCableSubscriptions` serves WebSocket and SSE subscribers with one trigger
40
+ (`Lighthouse::GraphQL::EventStream`). docs/subscriptions.md compares the two transports, with a client
41
+ for each.
42
+ - **`examples/graphql-federations`**: the example blog as two subgraphs (two Rails apps) behind Apollo Router,
43
+ with an end-to-end suite that composes the supergraph with rover and drives every federation directive and
44
+ Lighthouse feature through the router; and behind GraphQL Yoga (`gateway/`, `@graphql-tools/federation`
45
+ with `@interfaceObject` added), which subscribes to the blog over Server-Sent Events.
46
+
47
+ ### Changed
48
+
49
+ - **`example/` is `examples/graphql/`**, beside the new federated example.
50
+ - **An object literal given to a scalar directive argument builds** (graphql-ruby read it as an input
51
+ object): the link's `import: [{ name: "@key", as: "@id" }]`.
52
+ - **`Federation::CallbackSubscriptions` is a `GraphQL::Subscriptions::ActionCableSubscriptions`**: besides
53
+ Apollo Router's callbacks it keeps the subscriptions that come over SSE or an Action Cable channel, which
54
+ it refused, and its triggers go through `ActionCableSubscriptions`' broadcast (its `serializer:` and
55
+ `namespace:` options apply). `CallbackSubscriptions::BROADCASTING_PREFIX` is gone: the topics are
56
+ `ActionCableSubscriptions`' own.
57
+
58
+ ### Removed
59
+
60
+ - **The `apollo-federation` integration.** Its SDL linked Federation 2.3 whatever the schema said, printed
61
+ `@key` twice, left out the directives of fields, arguments and enum values, printed Lighthouse's own
62
+ directives, and could not resolve an entity interface; included in the schema class, it silently took the
63
+ subgraph over from Lighthouse's. Its mixins are now refused by name: a base type (or its field, argument or
64
+ enum value class) including `ApolloFederation::Object`, `Interface`, `Union`, `Enum`, `EnumValue`,
65
+ `Scalar`, `InputObject`, `Field` or `Argument`, or a schema class including `ApolloFederation::Schema`, is
66
+ a `Lighthouse::DefinitionError` naming the class and the SDL directive that replaces what the mixin
67
+ declared. docs/federation.md has the table.
68
+ - **`Lighthouse::ReferenceResolver`.** Define `self.resolve_reference(representation, context)` (or
69
+ `resolve_references`) on the type class instead; looking a record up by id is what `_entities` does by itself.
70
+
9
71
  ## [0.9.1] - 2026-10-30
10
72
 
11
73
  ### Added
@@ -1031,7 +1093,8 @@ had been running inside a private monorepo as a path gem before being extracted.
1031
1093
  - Config-driven extension seams: `Lighthouse.configure`, `resolver_namespaces`,
1032
1094
  `on_error`, and `DirectiveRegistry.register` for app-defined directives.
1033
1095
 
1034
- [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.9.1...HEAD
1096
+ [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.10.0...HEAD
1097
+ [0.10.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.9.1...v0.10.0
1035
1098
  [0.9.1]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.9.0...v0.9.1
1036
1099
  [0.9.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.8.2...v0.9.0
1037
1100
  [0.8.2]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.8.1...v0.8.2
data/README.md CHANGED
@@ -43,7 +43,8 @@ the single source of truth. [Motivation](docs/motivation.md) explains the idea i
43
43
 
44
44
  The same directives reach the rest of an API, too:
45
45
  - real-time updates: `Subscription` fields on graphql-ruby's subscriptions, triggered
46
- by a mutation's `@broadcast`;
46
+ by a mutation's `@broadcast`, over WebSocket (Action Cable) and Server-Sent Events
47
+ at once ([choosing a transport](docs/subscriptions.md#choosing-a-transport));
47
48
  - soft deletes (`@softDeletes`, `@restore`, `@forceDelete`) and feature flags (`@feature`);
48
49
  - request lifecycle [events](docs/events.md);
49
50
  - a controller concern that serves the schema in a few lines.
@@ -67,8 +68,7 @@ Add the gem to your `Gemfile`:
67
68
  gem 'lighthouse-graphql'
68
69
  ```
69
70
 
70
- It depends on `graphql ~> 2.5` and `activesupport`. For federation you also need
71
- `apollo-federation` in your app (it is an optional, app-provided dependency).
71
+ It depends on `graphql ~> 2.5` and `activesupport`. Federation needs nothing more.
72
72
  On graphql 2.5, keep the `json` gem below 3: graphql 2.5 calls `JSON.generate`
73
73
  with an option json 3 removed (graphql 2.6 no longer does).
74
74
 
@@ -166,13 +166,19 @@ Prefer to wire it by hand? These are the steps the generator performs.
166
166
  See **[docs/getting-started.md](docs/getting-started.md)** for the full setup,
167
167
  including base types and configuration.
168
168
 
169
- ### Example app
169
+ ### Example apps
170
170
 
171
- [`example/`](example) is a small blog API built with Lighthouse on Rails 8.1. It shows
171
+ [`examples/graphql/`](examples/graphql) is a small blog API built with Lighthouse on Rails 8.1. It shows
172
172
  the schema, the generated `Resolvers::`/`Mutations::`/`Subscriptions::`/`Builders::`/`Validators::` classes
173
173
  under graphql-ruby's base classes,
174
174
  Pundit policies and the opt-in performance features working together, and its specs
175
- are the library's end-to-end suite. See [example/README.md](example/README.md).
175
+ are the library's end-to-end suite. See [examples/graphql/README.md](examples/graphql/README.md).
176
+
177
+ [`examples/graphql-federations/`](examples/graphql-federations) is the same blog split into two Apollo
178
+ Federation subgraphs, `accounts` and `blog` (two Rails apps), behind Apollo Router: entities across them,
179
+ an entity interface and `@interfaceObject`, `@requires`/`@provides`/`@override`/`@context`, subscriptions
180
+ through the router's HTTP callbacks, uploads, persisted queries and `@defer`, all driven through the router
181
+ by its suite. See [examples/graphql-federations/README.md](examples/graphql-federations/README.md).
176
182
 
177
183
  ---
178
184
 
@@ -194,9 +200,9 @@ or as Markdown in [`docs/`](docs):
194
200
  | [Authentication & authorization](docs/authorization.md) | `@guard`, `@canFind` / `@canModel` / `@canQuery` / `@canResolved` / `@canRoot` (Pundit by default) |
195
201
  | [Performance at scale](docs/performance.md) | Opt-in schema cache, SDL reloading in development, persisted queries (APQ) and trusted-document allowlists |
196
202
  | [Events](docs/events.md) | Request, schema-build and execution events, `@event`, the controller concern |
197
- | [Subscriptions](docs/subscriptions.md) | `Subscription` fields, `@subscription`, `@broadcast`, filtering and queued broadcasts |
203
+ | [Subscriptions](docs/subscriptions.md) | `Subscription` fields, `@subscription`, `@broadcast`, filtering and queued broadcasts, over WebSocket or Server-Sent Events |
198
204
  | [Caching](docs/caching.md) | `@cache`, `@cacheKey`, `@clearCache` (Rails.cache), `@cacheControl` (HTTP) |
199
- | [Apollo Federation](docs/federation.md) | `@key`, `resolve_reference`, the `ReferenceResolver` registry |
205
+ | [Apollo Federation](docs/federation.md) | Subgraphs: `@key` entities, entity interfaces, the subgraph SDL, subscriptions through Apollo Router |
200
206
  | [Custom directives](docs/custom-directives.md) | The contracts, the registry, writing your own directive |
201
207
  | [Configuration](docs/configuration.md) | `Lighthouse.configure`, namespaces, error handling |
202
208
  | [Best practices](docs/best-practices.md) | Conventions worth adopting |
@@ -329,14 +329,8 @@ returned by the directive class's `type_definitions` (`{ name => sdl }`). They
329
329
  are injected only alongside a directive that uses them, and only if the schema
330
330
  doesn't define them itself.
331
331
 
332
- ## Federation reference resolvers
332
+ ## Federation entities
333
333
 
334
- Custom federation entity resolvers are registered with
335
- `Lighthouse::ReferenceResolver` (see [federation.md](federation.md)), typically in
336
- `config/initializers/federation.rb` so they re-register on code reload:
337
-
338
- ```ruby
339
- Rails.application.config.to_prepare do
340
- Lighthouse::ReferenceResolver.register('User') { |ref, _ctx| User.find_by(id: ref['id']) }
341
- end
342
- ```
334
+ A subgraph needs no configuration: `extend schema @link(...)` to the Federation
335
+ spec makes the schema one. The gateway's entities are found by the type's model,
336
+ or by its type class's `resolve_reference` (see [federation.md](federation.md#entities)).
data/docs/federation.md CHANGED
@@ -1,109 +1,284 @@
1
1
  # Apollo Federation
2
2
 
3
- Lighthouse lets a Rails service act as an [Apollo Federation](https://www.apollographql.com/docs/federation/)
4
- **subgraph**: it understands the federation directives in your SDL and wires up
5
- entity resolution so a gateway can compose your types with other subgraphs.
3
+ Lighthouse lets a Rails app be an [Apollo Federation](https://www.apollographql.com/docs/federation/)
4
+ **subgraph**: a gateway, such as [Apollo Router](https://www.apollographql.com/docs/graphos/routing),
5
+ composes its schema with other subgraphs' into one supergraph, and asks each
6
+ subgraph for its part of every query. As in PHP Lighthouse, it takes no Ruby:
7
+ the SDL says it.
6
8
 
7
- This relies on the [`apollo-federation`](https://github.com/Gusto/apollo-federation-ruby)
8
- gem, which you include in your app's base types and schema.
9
+ The repository's [`examples/graphql-federations`](https://github.com/Vaz-Innovation/lighthouse-graphql/tree/main/examples/graphql-federations)
10
+ is two subgraphs (two Rails apps) behind Apollo Router and behind GraphQL Yoga,
11
+ with an end-to-end suite that drives every feature on this page through the
12
+ router, and the graph through Yoga, which subscribes over Server-Sent Events.
9
13
 
10
- ## Setup
14
+ ## A subgraph
11
15
 
12
- Include the federation mixins in the base types you pass to Lighthouse, and make
13
- your schema a federation schema:
16
+ Link the Federation 2 spec, importing the directives you use, and mark your
17
+ entities with `@key`:
18
+
19
+ ```graphql
20
+ extend schema
21
+ @link(url: "https://specs.apollo.dev/federation/v2.9", import: ["@key", "@shareable", "@external", "@requires"])
22
+
23
+ type Query {
24
+ user(id: ID! @eq): User @find
25
+ }
26
+
27
+ type User @key(fields: "id") {
28
+ id: ID!
29
+ name: String!
30
+ }
31
+ ```
32
+
33
+ That is all. While the schema is built, Lighthouse:
34
+
35
+ - declares the spec's directives the SDL uses (you don't write `directive @key ...`),
36
+ under the names the link gives them: an imported one keeps its name, or the
37
+ one `import: [{ name: "@key", as: "@id" }]` gives it; any other is prefixed,
38
+ `@federation__shareable` (or with the link's `as:`);
39
+ - adds what the spec asks of a subgraph: `scalar _Any`, `type _Service { sdl: String! }`,
40
+ `Query._service` and, when an object type has `@key`, `union _Entity` of them
41
+ and `Query._entities(representations: [_Any!]!): [_Entity]!`;
42
+ - makes the types `@paginate` generates (`PaginatorInfo`, `PageInfo`, `UserPaginator`,
43
+ `UserConnection`, ...) `@shareable`: every subgraph that paginates generates the
44
+ same ones, which composition would otherwise refuse.
45
+
46
+ A schema without the link is a Federation 1 subgraph when you ask for one with
47
+ `get_schema(options: { federation: true })`: its directives keep their names,
48
+ and nothing is `@shareable` (Federation 1 has no such directive).
49
+
50
+ Nothing changes in the app's schema class: no mixin, no plugin.
14
51
 
15
52
  ```ruby
16
- # app/graphql/types/base_object.rb
17
- class Types::BaseObject < GraphQL::Schema::Object
18
- include ApolloFederation::Object
19
-
20
- # Default entity resolution: look the record up by id on the model that shares
21
- # the type's GraphQL name. Lighthouse falls back to this when no custom
22
- # resolver is registered (see below).
23
- def self.resolve_reference(reference, _context)
24
- model = graphql_name.safe_constantize
25
- return nil unless model&.respond_to?(:find_by)
26
-
27
- model.find_by(id: reference[:id] || reference['id'])
28
- end
53
+ class AppSchema < Lighthouse::GraphQL::RbLightHouse.get_schema(options: { base_types: { ... } })
54
+ use GraphQL::Dataloader
29
55
  end
56
+ ```
30
57
 
31
- BaseAppSchema = Lighthouse::GraphQL::RbLightHouse.get_schema(
32
- schema_path: Rails.root.join('graphql/schema.graphql').to_s,
33
- options: { federation: true, base_types: { object: Types::BaseObject, resolver: Resolvers::BaseResolver } }
34
- )
58
+ ## The subgraph SDL
35
59
 
36
- class AppSchema < BaseAppSchema
37
- include ApolloFederation::Schema
38
- federation(version: '2.3')
39
- query(superclass.query)
40
- end
60
+ `Query._service { sdl }` answers the subgraph's SDL, which the gateway (or
61
+ `rover supergraph compose`) composes. It is the schema clients see, printed as
62
+ PHP Lighthouse's FederationPrinter prints it:
63
+
64
+ - with its `extend schema @link(...)` (and `@composeDirective`, and the links of
65
+ your own directives);
66
+ - with every directive it applies, on every kind of member: types, fields,
67
+ arguments, enum values, input fields, scalars, unions (`@tag` and
68
+ `@inaccessible` go anywhere);
69
+ - without Lighthouse's own directives (`@all`, `@paginate`, `@guard`, ...), which
70
+ are the server's;
71
+ - without what the spec adds (`_Any`, `_Entity`, `_Service`, `_entities`,
72
+ `_service`, and `Query` when it has no other field) or declares (the spec's
73
+ directive definitions): the gateway knows them from the link. A directive of
74
+ your own keeps its definition.
75
+
76
+ Print it with the rake task, or read it from the schema:
77
+
78
+ ```shell
79
+ FORMAT=federation bin/rails lighthouse:print_schema > accounts.graphql
41
80
  ```
42
81
 
43
- ## Declaring entities
82
+ ```ruby
83
+ AppSchema.federation_sdl
84
+ ```
85
+
86
+ ## Entities
87
+
88
+ The gateway asks a subgraph for the entities it has a part of with
89
+ `_entities(representations:)`: a list of `{ "__typename": "User", "id": "1" }`.
90
+ Lighthouse groups them by type, and resolves each group once, by, in order:
91
+
92
+ 1. **The type class's `resolve_references` or `resolve_reference`.** The class of
93
+ the type (`Types::UserType`, including `Lighthouse::GraphQL::Type`; see
94
+ [types.md](types.md)), as graphql-ruby's federation does it:
44
95
 
45
- Mark a type as a federation entity with `@key`. Lighthouse recognizes the
46
- federation directives during the resolution phase and applies them:
96
+ ```ruby
97
+ class Types::UserType < Types::BaseObject
98
+ # The group at once: an Array, in the representations' order.
99
+ def self.resolve_references(representations, context)
100
+ users = User.where(external_id: representations.pluck(:id)).index_by(&:external_id)
101
+ representations.map { |representation| users[representation[:id]] }
102
+ end
103
+
104
+ # Or one at a time.
105
+ def self.resolve_reference(representation, context) = User.find_by(external_id: representation[:id])
106
+ end
107
+ ```
108
+
109
+ A representation reads with string or symbol keys alike.
110
+
111
+ 2. **The type's model**: its `@model(class:)`, else the model of its name. It is
112
+ queried by the first `@key` whose fields the representation has, as PHP
113
+ Lighthouse does, but in one query for the whole group:
114
+ `User.where(id: [...])`, or `where(...).or(where(...))` for a compound key.
115
+ - A key field reads the column of its name in snake_case, or its `@rename(attribute:)`.
116
+ - A key field with `@globalId` is decoded first.
117
+ - A nested selection (`@key(fields: "author { id }")`) joins the association
118
+ of that name.
119
+ - The values the gateway sends for the type's `@external` fields (those a
120
+ `@requires` asks for) are set on each record (never saved), so the field
121
+ that requires them reads them as attributes: `@requires(fields: "name")` on
122
+ `signature` and a `User#signature` that reads `name`.
123
+
124
+ 3. **The representation itself**, for a type with no class method and no model:
125
+ its fields read the representation's values (`id`, and whatever `@requires`
126
+ brought), or are resolved by its type class's methods.
127
+
128
+ An entity a subgraph does not have is `null`, as the spec allows. A representation
129
+ that has none of the type's keys, or names a type the subgraph does not have, is
130
+ an error.
131
+
132
+ ### Entity interfaces and `@interfaceObject`
133
+
134
+ An interface may be an entity too (Federation 2.3):
47
135
 
48
136
  ```graphql
49
- type User @key(fields: "id") {
50
- id: ID!
51
- name: String
52
- }
137
+ # The subgraph that owns the interface: every implementation is an entity with its key.
138
+ interface Authored @key(fields: "id") { id: ID! author: User! }
139
+ type Post implements Authored @key(fields: "id") { ... }
140
+ type Comment implements Authored @key(fields: "id") { ... }
141
+ ```
53
142
 
54
- type Order @key(fields: "id") @shareable {
143
+ ```graphql
144
+ # Another subgraph adds fields to every Authored, knowing none of its types.
145
+ type Authored @key(fields: "id") @interfaceObject {
55
146
  id: ID!
147
+ likesCount: Int!
56
148
  }
57
149
  ```
58
150
 
59
- Supported object-level directives: `@key`, `@extends`, `@shareable`,
60
- `@inaccessible`. Field-level `@external` is recognized for federation composition.
61
-
62
- ## Entity resolution (`resolve_reference`)
151
+ The router asks the owning subgraph for `{ "__typename": "Authored", "id": ... }`
152
+ when it needs the concrete type: Lighthouse resolves the interface with its type
153
+ class's `resolve_reference(s)`, else looks the representation up in the model of
154
+ each type that implements it, in turn, and answers each record as the type it
155
+ resolves to (see [types.md](types.md)). The key must tell the implementations
156
+ apart: UUIDs, unique across the tables, do. In the subgraph that declares the
157
+ `@interfaceObject`, `Authored` is an object type like any other, usually with no
158
+ model: its fields are resolved from the representation by its type class.
63
159
 
64
- When the gateway asks your subgraph to resolve an entity (via `_entities`),
65
- Lighthouse routes to a `resolve_reference` it installs on each `@key` type. The
66
- order of precedence is:
160
+ ## The federation directives
67
161
 
68
- 1. **A custom resolver** registered with `Lighthouse::ReferenceResolver` for that
69
- type, if any.
70
- 2. **The base type's `resolve_reference`** otherwise (e.g. the default
71
- model-lookup-by-id shown above).
162
+ Lighthouse passes every directive of the spec through to the gateway; what it
163
+ does itself:
72
164
 
73
- This means direct-model entities resolve with **zero extra code** — the default
74
- lookup handles them — while you register custom resolvers only for the entities
75
- that need bespoke loading.
165
+ | Directive | Lighthouse |
166
+ | --- | --- |
167
+ | `@key` | Makes the type an entity: in `_Entity`, resolved by `_entities` (above). Repeatable; `resolvable: false` keys are kept, for the gateway. |
168
+ | `@external` | Its values in a representation are set on the record. |
169
+ | `@requires`, `@provides` | Passed through; the field resolves as any other. |
170
+ | `@shareable` | Passed through. Added to the types `@paginate` generates. |
171
+ | `@interfaceObject` | The type is an entity of its own in this subgraph. |
172
+ | `@override`, `@inaccessible`, `@tag`, `@extends` | Passed through. |
173
+ | `@composeDirective` | Passed through, with your directive's definition and link. |
174
+ | `@authenticated`, `@requiresScopes`, `@policy` | Passed through, for the router to enforce (`@policy` through its coprocessor or Rhai script); Lighthouse's own `@guard` and `@can*` still run in the subgraph. |
175
+ | `@context`, `@fromContext` | Passed through: the router fills the argument; the type that has the field must have a resolvable `@key`. |
176
+ | `@cost`, `@listSize` | Passed through, for the router's demand control. |
76
177
 
77
- ### Custom reference resolvers
178
+ ## Subscriptions
78
179
 
79
- For entities that aren't a straightforward `find_by(id:)` — for example, ones
80
- backed by a join or an external identifier — register a resolver. The single best
81
- place is an initializer:
180
+ Apollo Router delivers a subgraph's subscriptions to its clients (over WebSocket
181
+ or multipart HTTP) and asks the subgraph for them through its
182
+ [HTTP callback protocol](https://www.apollographql.com/docs/graphos/routing/operations/subscriptions/callback-protocol).
183
+ Lighthouse speaks it as a graphql-ruby subscription backend:
82
184
 
83
185
  ```ruby
84
- # config/initializers/federation.rb
85
- Rails.application.config.to_prepare do
86
- Lighthouse::ReferenceResolver.register('JudgmentCreditor') do |reference, _context|
87
- id = reference['id'] || reference[:id]
88
- OpenStruct.new(id: id, contacts: Contact.joins(:links).where(links: { external_id: id }))
89
- end
186
+ class AppSchema < Lighthouse::GraphQL::RbLightHouse.get_schema(options: { base_types: { ... } })
187
+ use Lighthouse::GraphQL::Federation::CallbackSubscriptions
90
188
  end
91
189
  ```
92
190
 
93
- `register(typename) { |reference, context| ... }` returns the object that
94
- represents the entity; its fields then resolve normally.
191
+ ```yaml
192
+ # router.yaml
193
+ subscription:
194
+ enabled: true
195
+ mode:
196
+ callback:
197
+ public_url: http://router.internal:4000/callback
198
+ listen: 0.0.0.0:4000
199
+ path: /callback
200
+ subgraphs: [blog]
201
+ ```
202
+
203
+ The subscription fields, their classes and `@broadcast` are what
204
+ [subscriptions.md](subscriptions.md) describes; only the transport changes. The
205
+ router sends the subscription to the subgraph's endpoint with
206
+ `extensions.subscription` (its callback URL, an id, a verifier and the heartbeat
207
+ interval), which `Lighthouse::GraphQL::Controller` reads:
208
+
209
+ 1. the subscription runs as any other (the class's `authorized?` / `authorize?`;
210
+ an error goes back to the router, and to the client);
211
+ 2. the backend sends the router a `check`, and keeps the subscription once the
212
+ router answers it; the request answers `{ "data": null }`;
213
+ 3. every update `@broadcast` (or `trigger`) causes runs the subscriber's
214
+ operation again, in its context (`filter?` and `update` decide who gets it),
215
+ and goes to the router as a `next` message; the router resolves the other
216
+ subgraphs' fields of it;
217
+ 4. a `check` is sent every heartbeat interval; a subscription the router answers
218
+ 404 for (its client left) is dropped; one that ends here (`unsubscribe`) is
219
+ sent `complete`.
220
+
221
+ A subscription lives in the process that received it, as ActionCable's do. A
222
+ trigger from another process (a job, another Puma worker) reaches it through
223
+ Action Cable's pubsub when the app has Action Cable (its `cable.yml` adapter:
224
+ solid_cable, redis, postgresql); otherwise only the triggering process's
225
+ subscriptions are updated. If a process restarts, its subscriptions' heartbeats
226
+ stop, the router ends them, and their clients subscribe again.
227
+
228
+ `use ..., client:` takes another HTTP client (`post(url, body) -> status`), and
229
+ `tick:` how often, in seconds, due heartbeats are sent (1).
230
+
231
+ The backend is graphql-ruby's `ActionCableSubscriptions` as well: a
232
+ subscription without a callback, over
233
+ [Server-Sent Events](subscriptions.md#over-server-sent-events) or an Action
234
+ Cable channel, is kept as that backend keeps it, and one trigger reaches the
235
+ router's subscriptions, the SSE streams and the sockets alike. A gateway that
236
+ asks its subgraphs for subscriptions over SSE (GraphQL Yoga, Hive Gateway, any
237
+ on `@graphql-tools/executor-http`) needs nothing else; `examples/graphql-federations`
238
+ runs its suite through Apollo Router and through GraphQL Yoga, whose clients
239
+ subscribe over SSE too. A subscription
240
+ that came through none of them (no callback, no channel) is refused.
241
+
242
+ ## Apollo Router and GraphOS
243
+
244
+ The router runs most of this unlicensed. Some of its features need a router
245
+ connected to GraphOS (`APOLLO_KEY` and `APOLLO_GRAPH_REF`; a free plan's graph
246
+ will do), and it refuses to start without one when its config or supergraph uses
247
+ them: subscriptions, batching (`batching:`), and the `@authenticated` and
248
+ `@requiresScopes` directives, among others (router 2.19 runs file uploads,
249
+ `@policy`, `@cost` and `@context` unlicensed). The example's suite starts the
250
+ router with them only when those variables are set.
251
+
252
+ ## Migrating from `apollo-federation`
95
253
 
96
- ## The federation subgraph SDL
254
+ A graphql-ruby app federates code-first with the [`apollo-federation`](https://github.com/Gusto/apollo-federation-ruby)
255
+ gem: a mixin in each base class, and the federation directives declared in Ruby.
256
+ Lighthouse federates from the SDL, so they move there, and the mixins go. Lighthouse
257
+ refuses them (a `Lighthouse::DefinitionError` naming each class): the type mixins
258
+ would be silently ignored, and `ApolloFederation::Schema` would replace the
259
+ subgraph's SDL and `_entities` with the gem's, which link Federation 2.3 whatever
260
+ the SDL says and cannot resolve an entity interface.
97
261
 
98
- A federation subgraph publishes its capabilities via the `_service { sdl }` field
99
- (and `federation_sdl`), which a gateway uses to compose the supergraph. With the
100
- setup above this is produced for you, including the `@link` to the federation spec
101
- and the `@key`/`@shareable`/… directives on your types.
262
+ | apollo-federation | Lighthouse |
263
+ | --- | --- |
264
+ | `include ApolloFederation::Schema`, `federation(version: '2.x')`, `query(superclass.query)` | `extend schema @link(url: "https://specs.apollo.dev/federation/v2.x", import: [...])` in the SDL |
265
+ | `include ApolloFederation::Object`; `key fields: :id` (`camelize:`, `resolvable: false`) | `type User @key(fields: "id")` (`resolvable: false` as written) |
266
+ | `extend_type`, `shareable`, `inaccessible`, `interface_object`, `tag name:` | `@extends`, `@shareable`, `@inaccessible`, `@interfaceObject`, `@tag(name:)` on the type |
267
+ | `include ApolloFederation::Field`; `external: true`, `requires: { fields: ... }`, `provides: { fields: ... }` | `@external`, `@requires(fields: "...")`, `@provides(fields: "...")` on the field |
268
+ | `shareable: true`, `inaccessible: true`, `override: { from: "x" }`, `tags: [{ name: "x" }]` | `@shareable`, `@inaccessible`, `@override(from: "x")`, `@tag(name: "x")` on the field |
269
+ | `include ApolloFederation::Interface`; `key fields:` | `interface Media @key(fields: "id")`, an entity interface (above) |
270
+ | `include ApolloFederation::Union`, `Enum`, `Scalar`, `InputObject`; `tag`, `inaccessible` | `@tag(name:)`, `@inaccessible` on the union, enum, scalar or input |
271
+ | `include ApolloFederation::EnumValue`, `Argument`; `tags:`, `inaccessible:` | `@tag(name:)`, `@inaccessible` on the enum value or argument |
272
+ | `def self.resolve_reference(reference, context)` on the type | The same, on its type class (`Types::UserType`); or nothing, when its model is found by its keys |
273
+ | `def self.resolve_references(references, context)` | The same |
274
+ | `use ApolloFederation::Tracing` | Unchanged: a plugin, not a mixin |
102
275
 
103
- ## Gateways
276
+ Two things work differently:
104
277
 
105
- Apollo Gateways that use `IntrospectAndCompose` poll subgraphs and recompose
106
- automatically when your subgraph SDL changes — no manual step needed when you
107
- deploy schema changes. Gateways that consume a static, pre-composed supergraph
108
- file need that file recomposed (e.g. via `rover supergraph compose`) after you
109
- change the subgraph.
278
+ - **Field names in the SDL are camelCase already**: `@key(fields: "authorId")`, where
279
+ `key fields: :author_id` was camelized for you. A representation reaches
280
+ `resolve_reference` with the gateway's camelCase keys, read with strings or
281
+ symbols alike (`representation[:authorId]`); `underscore_reference_keys` has no
282
+ counterpart.
283
+ - **`Lighthouse::ReferenceResolver` is gone too**: move each registered block into
284
+ its type class's `resolve_reference`.
@@ -22,9 +22,8 @@ bundle install
22
22
 
23
23
  You can also list `gem 'graphql'` yourself, to pin its version. On graphql 2.5, keep
24
24
  the `json` gem below 3: graphql 2.5 calls `JSON.generate` with an option json 3
25
- removed (graphql 2.6 no longer does). If you want federation, add `apollo-federation`
26
- to your app — it is intentionally **not** a hard dependency of Lighthouse so
27
- non-federated apps stay lean.
25
+ removed (graphql 2.6 no longer does). An Apollo Federation subgraph needs nothing
26
+ more: see [federation.md](federation.md).
28
27
 
29
28
  **graphql-ruby's install** (optional). This writes the schema class, the base
30
29
  classes (`Types::BaseObject`, ...), the root types and the controller. Choose its
@@ -142,7 +141,6 @@ module Types
142
141
  edge_type_class(Types::BaseEdge)
143
142
  connection_type_class(Types::BaseConnection)
144
143
  field_class Types::BaseField
145
- # include ApolloFederation::Object # if you use federation
146
144
  end
147
145
  end
148
146
  ```