graphql-stitching 1.7.0 → 1.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 63b137317e57972e09c9926447c53ab26ac99a146557258e94b62abff305d096
4
- data.tar.gz: e3a2217f5c04cc1a8a8412f15bb0ee5e6c4340869f945758735468c0903840f6
3
+ metadata.gz: 43ca2665bc1d0e0a87eead760ee4f7b1caddf324861b66414bc011958901eeff
4
+ data.tar.gz: 18a14928e703744d29b57665c51ecdb6a17b1d9d2b7bc58fe8727a37b55fbcd5
5
5
  SHA512:
6
- metadata.gz: 63ccfdcf28c02490946d2b7b9fef5dbe726cc47a214887010dc7dfa7f066d266bb7b2e5d899b13ad705060b8f7981904f47029a119c73c1aa582181d97ec6bec
7
- data.tar.gz: d72baafd4419199658afbdba8a70a109a84da1e48e712344f568a5d4f75f5d0b2da3f3549a50370e528357fd003d9f8cbae825a490b2b0eed86c84528471855f
6
+ metadata.gz: b5ee7817b699447b35c937eb3df872433f8c318310debab6fea1577513171260a39e900c64cf37b4bfcb6f4fde4b509b5216ddf95879dd53a9878a3924016b5d
7
+ data.tar.gz: 0ddda7a4df33d5b6946a3a6283a4388d507c18d7ff758db1b2f09179546d6be87b6e78390fa6f623442e0f6e79a91aac69b0922542c4134673175377c47cfc0f
data/README.md CHANGED
@@ -10,16 +10,28 @@ GraphQL stitching composes a single schema from multiple underlying GraphQL reso
10
10
  - Shared objects, fields, enums, and inputs across locations.
11
11
  - Combining local and remote schemas.
12
12
  - [Visibility controls](./docs/visibility.md) for hiding schema elements.
13
- - [File uploads](./docs/http_executable.md) via multipart forms.
13
+ - [File uploads](./docs/executables.md) via multipart forms.
14
14
  - Tested with all minor versions of `graphql-ruby`.
15
15
 
16
16
  **NOT Supported:**
17
17
  - Computed fields (ie: federation-style `@requires`).
18
18
  - Defer/stream.
19
19
 
20
- This Ruby implementation is designed as a generic library to join basic spec-compliant GraphQL schemas using their existing types and fields in a [DIY](https://dictionary.cambridge.org/us/dictionary/english/diy) capacity. The opportunity here is for a Ruby application to stitch its local schemas together or onto remote sources without requiring an additional proxy service running in another language. If your goal is a purely high-throughput federation gateway with managed schema deployments, consider more opinionated frameworks such as [Apollo Federation](https://www.apollographql.com/docs/federation/).
20
+ This Ruby implementation is designed as a generic library to join basic spec-compliant GraphQL schemas using their existing types and fields in a do-it-yourself capacity. The opportunity here is for a Ruby application to stitch its local schemas together or onto remote sources without requiring an additional proxy service running in another language. If your goal is a purely high-throughput federation gateway with managed schema deployments, consider more opinionated frameworks such as [Apollo Federation](https://www.apollographql.com/docs/federation/).
21
21
 
22
- ## Getting started
22
+ ## Documentation
23
+
24
+ 1. [Introduction](./docs/introduction.md)
25
+ 1. [Composing a supergraph](./docs/composing_a_supergraph.md)
26
+ 1. [Merged types](./docs/merged_types.md)
27
+ 1. [Executables & file uploads](./docs/executables.md)
28
+ 1. [Serving a supergraph](./docs/serving_a_supergraph.md)
29
+ 1. [Visibility controls](./docs/visibility.md)
30
+ 1. [Performance concerns](./docs/performance.md)
31
+ 1. [Error handling](./docs/error_handling.md)
32
+ 1. [Subscriptions](./docs/subscriptions.md)
33
+
34
+ ## Quick Start
23
35
 
24
36
  Add to your Gemfile:
25
37
 
@@ -33,461 +45,83 @@ Run `bundle install`, then require unless running an autoloading framework (Rail
33
45
  require "graphql/stitching"
34
46
  ```
35
47
 
36
- ## Usage
37
-
38
- The [`Client`](./docs/client.md) component builds a stitched graph wrapped in an executable workflow (with optional query plan caching hooks):
39
-
40
- ```ruby
41
- movies_schema = <<~GRAPHQL
42
- type Movie { id: ID! name: String! }
43
- type Query { movie(id: ID!): Movie }
44
- GRAPHQL
45
-
46
- showtimes_schema = <<~GRAPHQL
47
- type Showtime { id: ID! time: String! }
48
- type Query { showtime(id: ID!): Showtime }
49
- GRAPHQL
50
-
51
- client = GraphQL::Stitching::Client.new(locations: {
52
- movies: {
53
- schema: GraphQL::Schema.from_definition(movies_schema),
54
- executable: GraphQL::Stitching::HttpExecutable.new(url: "http://localhost:3000"),
55
- },
56
- showtimes: {
57
- schema: GraphQL::Schema.from_definition(showtimes_schema),
58
- executable: GraphQL::Stitching::HttpExecutable.new(url: "http://localhost:3001"),
59
- },
60
- my_local: {
61
- schema: MyLocal::GraphQL::Schema,
62
- },
63
- })
64
-
65
- result = client.execute(
66
- query: "query FetchFromAll($movieId:ID!, $showtimeId:ID!){
67
- movie(id:$movieId) { name }
68
- showtime(id:$showtimeId): { time }
69
- myLocalField
70
- }",
71
- variables: { "movieId" => "1", "showtimeId" => "2" },
72
- operation_name: "FetchFromAll"
73
- )
74
- ```
75
-
76
- Schemas provided in [location settings](./docs/composer.md#performing-composition) may be class-based schemas with local resolvers (locally-executable schemas), or schemas built from SDL strings (schema definition language parsed using `GraphQL::Schema.from_definition`) and mapped to remote locations via [executables](#executables).
77
-
78
- A Client bundles up the component parts of stitching, which are worth familiarizing with:
79
-
80
- - [Composer](./docs/composer.md) - merges and validates many schemas into one supergraph.
81
- - [Supergraph](./docs/supergraph.md) - manages the combined schema, location routing maps, and executable resources. Can be exported, cached, and rehydrated.
82
- - [Request](./docs/request.md) - manages the lifecycle of a stitched GraphQL request.
83
- - [HttpExecutable](./docs/http_executable.md) - proxies requests to remotes with multipart file upload support.
84
-
85
- ## Merged types
86
-
87
- `Object` and `Interface` types may exist with different fields in different graph locations, and will get merged together in the combined schema.
88
-
89
- ![Merging types](./docs/images/merging.png)
90
-
91
- To facilitate this, schemas should be designed around **merged type keys** that stitching can cross-reference and fetch across locations using **type resolver queries** (discussed below). For those in an Apollo ecosystem, there's also _limited_ support for merging types though [federation `_entities`](./docs/federation_entities.md).
92
-
93
- ### Merged type keys
94
-
95
- Foreign keys in a GraphQL schema frequently look like the `Product.imageId` field here:
96
-
97
- ```graphql
98
- # -- Products schema:
99
-
100
- type Product {
101
- id: ID!
102
- imageId: ID!
103
- }
104
-
105
- # -- Images schema:
106
-
107
- type Image {
108
- id: ID!
109
- url: String!
110
- }
111
- ```
112
-
113
- However, this design does not lend itself to merging types across locations. A simple schema refactor makes this foreign key more expressive as an entity type, and turns the key into an _object_ that will merge with analogous objects in other locations:
114
-
115
- ```graphql
116
- # -- Products schema:
117
-
118
- type Product {
119
- id: ID!
120
- image: Image!
121
- }
122
-
123
- type Image {
124
- id: ID!
125
- }
126
-
127
- # -- Images schema:
128
-
129
- type Image {
130
- id: ID!
131
- url: String!
132
- }
133
- ```
134
-
135
- ### Merged type resolver queries
136
-
137
- Each location that provides a unique variant of a type must provide at least one _resolver query_ for accessing it. Type resolvers are root queries identified by a `@stitch` directive:
48
+ A stitched schema is [_composed_](./docs/composing_a_supergraph.md) from many _subgraph_ schemas. These can be remote APIs expressed as Schema Definition Language (SDL), or local schemas built from Ruby classes. Subgraph type names that overlap become [_merged types_](./docs/merged_types.md), and require `@stitch` directives to identify where each variant of the type can be fetched and what key field links them:
138
49
 
50
+ _schemas/product_infos.graphql_
139
51
  ```graphql
140
52
  directive @stitch(key: String!, arguments: String) repeatable on FIELD_DEFINITION
141
- ```
142
-
143
- This directive tells stitching how to cross-reference and fetch types from across locations, for example:
144
53
 
145
- ```ruby
146
- products_schema = <<~GRAPHQL
147
- directive @stitch(key: String!, arguments: String) repeatable on FIELD_DEFINITION
148
-
149
- type Product {
150
- id: ID!
151
- name: String!
152
- }
153
-
154
- type Query {
155
- product(id: ID!): Product @stitch(key: "id")
156
- }
157
- GRAPHQL
158
-
159
- catalog_schema = <<~GRAPHQL
160
- directive @stitch(key: String!, arguments: String) repeatable on FIELD_DEFINITION
161
-
162
- type Product {
163
- id: ID!
164
- price: Float!
165
- }
166
-
167
- type Query {
168
- products(ids: [ID!]!): [Product]! @stitch(key: "id")
169
- }
170
- GRAPHQL
171
-
172
- client = GraphQL::Stitching::Client.new(locations: {
173
- products: {
174
- schema: GraphQL::Schema.from_definition(products_schema),
175
- executable: GraphQL::Stitching::HttpExecutable.new(url: "http://localhost:3001"),
176
- },
177
- catalog: {
178
- schema: GraphQL::Schema.from_definition(catalog_schema),
179
- executable: GraphQL::Stitching::HttpExecutable.new(url: "http://localhost:3002"),
180
- },
181
- })
182
- ```
183
-
184
- Focusing on the `@stitch` directive usage:
185
-
186
- ```graphql
187
54
  type Product {
188
55
  id: ID!
189
56
  name: String!
190
57
  }
191
- type Query {
192
- product(id: ID!): Product @stitch(key: "id")
193
- }
194
- ```
195
-
196
- * The `@stitch` directive marks a root query where the merged type may be accessed. The merged type identity is inferred from the field return. This identifier can also be provided as [static configuration](#sdl-based-schemas).
197
- * The `key: "id"` parameter indicates that an `{ id }` must be selected from prior locations so it can be submitted as an argument to this query. The query argument used to send the key is inferred when possible ([more on arguments](#argument-shapes) later).
198
-
199
- Merged types must have a resolver query in each of their possible locations. The one exception to this requirement are [outbound-only types](./docs/mechanics.md#outbound-only-merged-types) that contain no exclusive data, such as foreign keys:
200
-
201
- ```graphql
202
- type Product {
203
- id: ID!
204
- }
205
- ```
206
-
207
- The above type contains nothing but a key field that is available in other locations. Therefore, this variant will never require an inbound request to fetch it, and its resolver query may be omitted from this location.
208
-
209
- #### List queries
210
-
211
- It's okay ([even preferable](#batching) in most circumstances) to provide a list accessor as a resolver query. The only requirement is that both the field argument and return type must be lists, and the query results are expected to be a mapped set with `null` holding the position of missing results.
212
-
213
- ```graphql
214
- type Query {
215
- products(ids: [ID!]!): [Product]! @stitch(key: "id")
216
- }
217
-
218
- # input: ["1", "2", "3"]
219
- # result: [{ id: "1" }, null, { id: "3" }]
220
- ```
221
-
222
- See [error handling](./docs/mechanics.md#stitched-errors) tips for list queries.
223
-
224
- #### Abstract queries
225
-
226
- It's okay for resolver queries to be implemented through abstract types. An abstract query will provide access to all of its possible types by default, each of which must implement the key.
227
-
228
- ```graphql
229
- interface Node {
230
- id: ID!
231
- }
232
- type Product implements Node {
233
- id: ID!
234
- name: String!
235
- }
236
- type Query {
237
- nodes(ids: [ID!]!): [Node]! @stitch(key: "id")
238
- }
239
- ```
240
-
241
- To customize which types an abstract query provides and their respective keys, you may extend the `@stitch` directive with a `typeName` constraint. This can be repeated to select multiple types.
242
-
243
- ```graphql
244
- directive @stitch(key: String!, arguments: String, typeName: String) repeatable on FIELD_DEFINITION
245
-
246
- type Product { sku: ID! }
247
- type Order { id: ID! }
248
- type Customer { id: ID! } # << not stitched
249
- union Entity = Product | Order | Customer
250
-
251
- type Query {
252
- entity(key: ID!): Entity
253
- @stitch(key: "sku", typeName: "Product")
254
- @stitch(key: "id", typeName: "Order")
255
- }
256
- ```
257
-
258
- #### Argument shapes
259
-
260
- Stitching infers which argument to use for queries with a single argument, or when the key name matches its intended argument. For custom mappings, the `arguments` option may specify a template of GraphQL arguments that insert key selections:
261
-
262
- ```graphql
263
- type Product {
264
- id: ID!
265
- }
266
- type Query {
267
- product(byId: ID, bySku: ID): Product
268
- @stitch(key: "id", arguments: "byId: $.id")
269
- }
270
- ```
271
-
272
- Key insertions are prefixed by `$` and specify a dot-notation path to any selections made by the resolver key, or `__typename`. This syntax allows sending multiple arguments that intermix stitching keys with complex input shapes and other static values:
273
-
274
- ```graphql
275
- type Product {
276
- id: ID!
277
- }
278
- union Entity = Product
279
- input EntityKey {
280
- id: ID!
281
- type: String!
282
- }
283
- enum EntitySource {
284
- DATABASE
285
- CACHE
286
- }
287
-
288
- type Query {
289
- entities(keys: [EntityKey!]!, source: EntitySource = DATABASE): [Entity]!
290
- @stitch(key: "id", arguments: "keys: { id: $.id, type: $.__typename }, source: CACHE")
291
- }
292
- ```
293
-
294
- See [resolver arguments](./docs/type_resolver.md#arguments) for full documentation on shaping input.
295
-
296
- #### Composite type keys
297
-
298
- Resolver keys may make composite selections for multiple key fields and/or nested scopes, for example:
299
-
300
- ```graphql
301
- interface FieldOwner {
302
- id: ID!
303
- }
304
- type CustomField {
305
- owner: FieldOwner!
306
- key: String!
307
- value: String
308
- }
309
- input CustomFieldLookup {
310
- ownerId: ID!
311
- ownerType: String!
312
- key: String!
313
- }
314
-
315
- type Query {
316
- customFields(lookups: [CustomFieldLookup!]!): [CustomField]! @stitch(
317
- key: "owner { id __typename } key",
318
- arguments: "lookups: { ownerId: $.owner.id, ownerType: $.owner.__typename, key: $.key }"
319
- )
320
- }
321
- ```
322
-
323
- Note that composite key selections may _not_ be distributed across locations. The complete selection criteria must be available in each location that provides the key.
324
-
325
- #### Multiple type keys
326
-
327
- A type may exist in multiple locations across the graph using different keys, for example:
328
-
329
- ```graphql
330
- type Product { id:ID! } # storefronts location
331
- type Product { id:ID! sku:ID! } # products location
332
- type Product { sku:ID! } # catelog location
333
- ```
334
58
 
335
- In the above graph, the `storefronts` and `catelog` locations have different keys that join through an intermediary. This pattern is perfectly valid and resolvable as long as the intermediary provides resolver queries for each possible key:
336
-
337
- ```graphql
338
- type Product {
339
- id: ID!
340
- sku: ID!
341
- }
342
59
  type Query {
343
- productById(id: ID!): Product @stitch(key: "id")
344
- productBySku(sku: ID!): Product @stitch(key: "sku")
345
- }
346
- ```
347
-
348
- The `@stitch` directive is also repeatable, allowing a single query to associate with multiple keys:
349
-
350
- ```graphql
351
- type Product {
352
- id: ID!
353
- sku: ID!
354
- }
355
- type Query {
356
- product(id: ID, sku: ID): Product @stitch(key: "id") @stitch(key: "sku")
60
+ product(id: ID!): Product @stitch(key: "id")
357
61
  }
358
62
  ```
359
63
 
360
- #### Class-based schemas
361
-
362
- The `@stitch` directive can be added to class-based schemas with a directive definition provided by the library:
363
-
64
+ _product_prices_schema.rb_
364
65
  ```ruby
365
- class Query < GraphQL::Schema::Object
366
- field :product, Product, null: false do
367
- directive GraphQL::Stitching::Directives::Stitch, key: "id"
368
- argument :id, ID, required: true
369
- end
66
+ class Product < GraphQL::Schema::Object
67
+ field :id, ID, null: false
68
+ field :price, Float, null: false
370
69
  end
371
- ```
372
-
373
- The `@stitch` directive can be exported from a class-based schema to an SDL string by calling `schema.to_definition`.
374
70
 
375
- #### SDL-based schemas
376
-
377
- A clean schema may also have stitching directives applied via static configuration by passing a `stitch` array in [location settings](./docs/composer.md#performing-composition):
378
-
379
- ```ruby
380
- sdl_string = <<~GRAPHQL
381
- type Product {
382
- id: ID!
383
- sku: ID!
384
- }
385
- type Query {
386
- productById(id: ID!): Product
387
- productBySku(sku: ID!): Product
388
- }
389
- GRAPHQL
390
-
391
- supergraph = GraphQL::Stitching::Composer.new.perform({
392
- products: {
393
- schema: GraphQL::Schema.from_definition(sdl_string),
394
- executable: ->() { ... },
395
- stitch: [
396
- { field_name: "productById", key: "id" },
397
- { field_name: "productBySku", key: "sku", arguments: "mySku: $.sku" },
398
- ]
399
- },
400
- # ...
401
- })
402
- ```
403
-
404
- #### Custom directive names
405
-
406
- The library is configured to use a `@stitch` directive by default. You may customize this by setting a new name during initialization:
407
-
408
- ```ruby
409
- GraphQL::Stitching.stitch_directive = "resolver"
410
- ```
411
-
412
- ## Executables
413
-
414
- An executable resource performs location-specific GraphQL requests. Executables may be `GraphQL::Schema` classes, or any object that responds to `.call(request, source, variables)` and returns a raw GraphQL response:
71
+ class Query < GraphQL::Schema::Object
72
+ field :products, [Product, null: true], null: false do |f|
73
+ f.directive(GraphQL::Stitching::Directives::Stitch, key: "id")
74
+ f.argument(ids: [ID, null: false], required: true)
75
+ end
415
76
 
416
- ```ruby
417
- class MyExecutable
418
- def call(request, source, variables)
419
- # process a GraphQL request...
420
- return {
421
- "data" => { ... },
422
- "errors" => [ ... ],
423
- }
77
+ def products(ids:)
78
+ products_by_id = ProductModel.where(id: ids).index_by(&:id)
79
+ ids.map { |id| products_by_id[id] }
424
80
  end
425
81
  end
82
+
83
+ class ProductPricesSchema < GraphQL::Schema
84
+ directive(GraphQL::Stitching::Directives::Stitch)
85
+ query(Query)
86
+ end
426
87
  ```
427
88
 
428
- A [Supergraph](./docs/supergraph.md) is composed with executable resources provided for each location. Any location that omits the `executable` option will use the provided `schema` as its default executable:
89
+ These subgraph schemas are composed into a _supergraph_, or, a single combined schema that can be queried as one. Remote schemas are mapped to their resolver locations using [_executables_](./docs/executables.md):
429
90
 
430
91
  ```ruby
431
- supergraph = GraphQL::Stitching::Composer.new.perform({
432
- first: {
433
- schema: FirstSchema,
434
- # executable:^^^^^^ delegates to FirstSchema,
435
- },
436
- second: {
437
- schema: SecondSchema,
438
- executable: GraphQL::Stitching::HttpExecutable.new(url: "http://localhost:3001", headers: { ... }),
439
- },
440
- third: {
441
- schema: ThirdSchema,
442
- executable: MyExecutable.new,
92
+ client = GraphQL::Stitching::Client.new(locations: {
93
+ infos: {
94
+ schema: GraphQL::Schema.from_definition(File.read("schemas/product_infos.graphql")),
95
+ executable: GraphQL::Stitching::HttpExecutable.new(url: "http://localhost:3001"),
443
96
  },
444
- fourth: {
445
- schema: FourthSchema,
446
- executable: ->(req, query, vars) { ... },
97
+ prices: {
98
+ schema: ProductPricesSchema,
447
99
  },
448
100
  })
449
101
  ```
450
102
 
451
- The `GraphQL::Stitching::HttpExecutable` class is provided as a simple executable wrapper around `Net::HTTP.post` with [file upload](./docs/http_executable.md#graphql-file-uploads) support. You should build your own executables to leverage your existing libraries and to add instrumentation. Note that you must manually assign all executables to a `Supergraph` when rehydrating it from cache ([see docs](./docs/supergraph.md)).
452
-
453
- ## Batching
103
+ A stitching client then acts as a drop-in replacement for [serving GraphQL queries](./docs/serving_a_supergraph.md) using the combined schema. Internally, a query is broken down by location and sequenced into multiple requests, then all results are merged and shaped to match the original query.
454
104
 
455
- The stitching executor automatically batches subgraph requests so that only one request is made per location per generation of data. This is done using batched queries that combine all data access for a given a location. For example:
105
+ ```ruby
106
+ query = %|
107
+ query FetchProduct($id: ID!) {
108
+ product(id: $id) {
109
+ name # from infos schema
110
+ price # from prices schema
111
+ }
112
+ }
113
+ |
456
114
 
457
- ```graphql
458
- query MyOperation_2($_0_key:[ID!]!, $_1_0_key:ID!, $_1_1_key:ID!, $_1_2_key:ID!) {
459
- _0_result: widgets(ids: $_0_key) { ... } # << 3 Widget
460
- _1_0_result: sprocket(id: $_1_0_key) { ... } # << 1 Sprocket
461
- _1_1_result: sprocket(id: $_1_1_key) { ... } # << 1 Sprocket
462
- _1_2_result: sprocket(id: $_1_2_key) { ... } # << 1 Sprocket
463
- }
115
+ result = client.execute(
116
+ query: query,
117
+ variables: { "id" => "1" },
118
+ operation_name: "FetchProduct",
119
+ )
464
120
  ```
465
121
 
466
- Tips:
467
-
468
- * List queries (like the `widgets` selection above) are generally preferable as resolver queries because they keep the batched document consistent regardless of set size, and make for smaller documents that parse and validate faster.
469
- * Assure that root field resolvers across your subgraph implement batching to anticipate cases like the three `sprocket` selections above.
470
-
471
- Otherwise, there's no developer intervention necessary (or generally possible) to improve upon data access. Note that multiple generations of data may still force the executor to return to a previous location for more data.
472
-
473
- ## Concurrency
474
-
475
- The [Executor](./docs/executor.md) component builds atop the Ruby fiber-based implementation of `GraphQL::Dataloader`. Non-blocking concurrency requires setting a fiber scheduler via `Fiber.set_scheduler`, see [graphql-ruby docs](https://graphql-ruby.org/dataloader/nonblocking.html). You may also need to build your own remote clients using corresponding HTTP libraries.
476
-
477
- ## Additional topics
478
-
479
- - [Deploying a stitched schema](./docs/mechanics.md#deploying-a-stitched-schema)
480
- - [Schema composition merge patterns](./docs/composer.md#merge-patterns)
481
- - [Visibility controls](./docs/visibility.md)
482
- - [Subscriptions tutorial](./docs/subscriptions.md)
483
- - [Field selection routing](./docs/mechanics.md#field-selection-routing)
484
- - [Root selection routing](./docs/mechanics.md#root-selection-routing)
485
- - [Stitched errors](./docs/mechanics.md#stitched-errors)
486
- - [Null results](./docs/mechanics.md#null-results)
487
-
488
122
  ## Examples
489
123
 
490
- This repo includes working examples of stitched schemas running across small Rack servers. Clone the repo, `cd` into each example and try running it following its README instructions.
124
+ Clone this repo, then `cd` into each example and follow its README instructions.
491
125
 
492
126
  - [Merged types](./examples/merged_types)
493
127
  - [File uploads](./examples/file_uploads)