lighthouse-graphql 0.7.3 → 0.8.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 (37) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +90 -1
  3. data/docs/authorization.md +33 -1
  4. data/docs/configuration.md +38 -0
  5. data/docs/directives.md +44 -0
  6. data/docs/getting-started.md +63 -10
  7. data/docs/performance.md +9 -0
  8. data/docs/relay.md +6 -2
  9. data/docs/uploads.md +28 -2
  10. data/lib/lighthouse/config.rb +18 -2
  11. data/lib/lighthouse/controller.rb +6 -67
  12. data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +7 -1
  13. data/lib/lighthouse/directive_resolvers/attachment_resolver.rb +139 -0
  14. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +29 -5
  15. data/lib/lighthouse/directives/registry.rb +1 -1
  16. data/lib/lighthouse/directives/soft_deletes_directive.rb +23 -6
  17. data/lib/lighthouse/field_resolver_stack.rb +32 -0
  18. data/lib/lighthouse/global_id.rb +16 -5
  19. data/lib/lighthouse/graphql/version.rb +1 -1
  20. data/lib/lighthouse/operations.rb +111 -0
  21. data/lib/lighthouse/pagination.rb +21 -1
  22. data/lib/lighthouse/persisted_queries/manifest.rb +40 -0
  23. data/lib/lighthouse/persisted_queries.rb +9 -27
  24. data/lib/lighthouse/railtie.rb +8 -1
  25. data/lib/lighthouse/rb_lighthouse.rb +6 -0
  26. data/lib/lighthouse/relation_batch.rb +1 -1
  27. data/lib/lighthouse/schema_generator.rb +2 -0
  28. data/lib/lighthouse/schema_printer.rb +100 -0
  29. data/lib/lighthouse/schema_report.rb +161 -0
  30. data/lib/lighthouse/server_directives.rb +63 -0
  31. data/lib/lighthouse/tasks/lighthouse.rake +25 -6
  32. data/lib/lighthouse/upload.rb +2 -1
  33. data/lib/lighthouse/upload_store.rb +53 -2
  34. data/sig/lighthouse/controller.rbs +19 -8
  35. data/sig/lighthouse/directives.rbs +27 -0
  36. data/sig/lighthouse.rbs +11 -2
  37. metadata +7 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: cf8e8162adf7eff6d40299e3e8ecc947b8958f032323d97b78596578030f3bfa
4
- data.tar.gz: 3b4fcda74e4e0b4eeed1baf5853fb72a753cd7ff401a25a25cf234efabdb581f
3
+ metadata.gz: f307869fd0902be910da0c9edad56620a3339962ccb77e388b7b11aad1565fde
4
+ data.tar.gz: 3e9164c49b69dcf6626b6985266fd33a65c90a76cf065e44efe7cee5bc250b0f
5
5
  SHA512:
6
- metadata.gz: 06c2d9e4a484d3bd54556ef758bccb41759f28f8ac39aaf2b857f5107a364f74b4a701e3cc426ec8a72ad12b5aa96a4406c139bd273542dc746725db71489e59
7
- data.tar.gz: d9eddb09ca7fc8acacbaeca60fa646d9a655a9a96a83a3be25aeeba418cd902cd64b9a2f9b0dd4c1108a258208a4a300b759837c8dca1300d8a39af1e74ae249
6
+ metadata.gz: ac2430336cfdc489d2d032d038ad3227d45cfd92101f66c4eff3c5a83b1325058d1e65fd16430fecf2a0b358849427e9be31a1b3ba2b309c787873cf20bf41bc
7
+ data.tar.gz: 8c9c10c5650b02845daa40cc74ad76909e8ea7622221d19d204a2b77fd3cec08b9686339c8b2606e067a06f4ba56a4d13111b42b155e0d8d0e5c5ed4831d6558
data/CHANGELOG.md CHANGED
@@ -6,6 +6,94 @@ project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.8.0] - 2026-10-29
10
+
11
+ ### Added
12
+
13
+ - **`config.schema_log` reports the schema on boot and on every reload in development**: a
14
+ pretty-printed `✓` with the build time, the number of types and root fields, what the reload
15
+ added and removed (`+ User.nickname − Post.legacyTitle`) and the files written, or a `✗`
16
+ with the error the next request would raise, plus the persisted operations the schema no
17
+ longer accepts. On by default in a development server (not rake tasks or the console),
18
+ through the Rails logger, and on the terminal from boot.
19
+ - **`@attachment` answers the URL of an ActiveStorage attachment**, or the URLs of a
20
+ `has_many_attached`: the read side of `@upload`. Every parent's attachments and blobs load
21
+ at once (two queries for any number of parents), the name defaults to the field's without
22
+ `Url`/`Urls` (`avatarUrl` reads `avatar`), and `url:` picks Rails' `REDIRECT` (default),
23
+ `PROXY`, or the service's `DIRECT` URL signed for `expiresIn`; `variant:` names a variant.
24
+ - **`@canModel` on an argument or input field: who may use it.** It checks its ability against
25
+ the model only when the client gives that argument a value, at any depth (in each input of
26
+ a list too), with the field's `@can*` directives and their `action:`.
27
+ `@softDeletes(ability: "view_trashed")` puts it on the `trashed` argument it adds, so
28
+ listing trashed records can be for admins only.
29
+ - **`lighthouse_execute` runs an operation from any controller action (#3)**, with the context the
30
+ GraphQL endpoint gives it (`graphql_context`, and the IP and controller `@throttle` counts
31
+ with), to render a page with its data loaded. It comes from the new
32
+ `Lighthouse::GraphQL::Operations` concern, which any controller can include (with
33
+ `lighthouse_schema`), and which `Lighthouse::GraphQL::Controller` includes. It returns the
34
+ result, or `nil` when a `@throttle` answered the request with a 429.
35
+ - `config.persisted_queries_manifest` takes a Hash of operations, or a callable answering a
36
+ Hash or a path (called per persisted query), besides a JSON file: a frontend build can keep
37
+ its trusted documents where it writes them. A Hash is checked once, until its content changes.
38
+ - **`config.schema_output` keeps the client schema in a file, in development**, for a codegen
39
+ to read, as NestJS's `autoSchemaFile`: rewritten on boot and on every reload, only when it
40
+ changed (atomically, so a watcher never reads half of it). A path (`.json` for the
41
+ introspection result), or `{ path:, schema: }`. `bin/rails lighthouse:schema_output:verify`
42
+ fails in CI when the committed file is out of date.
43
+ - `lighthouse:print_schema` takes PHP Lighthouse's options: `FORMAT=json` (the introspection
44
+ result), `FORMAT=federation` (a subgraph's SDL), and `WRITE=1` / `WRITE=path` to write a
45
+ file (schema_output's, else `lighthouse-schema.graphql`). graphql-ruby already prints in
46
+ alphabetical order, so there is no `--sort`. With no `SCHEMA=`, it and the other tasks
47
+ (`validate_schema`, `persisted_queries:verify`) take `<App>Schema`, the name graphql-ruby's
48
+ install gives, before trying `AppSchema`.
49
+
50
+ ### Changed
51
+
52
+ - **Clients no longer see Lighthouse's directives.** Introspection listed every directive
53
+ Lighthouse injects to build the schema (`@all`, `@canFind`, `@inject`, `@hash`, ... 96 in
54
+ the example app), with the types only they use (`CanAction`, `FeatureState`), and
55
+ `to_definition` / `lighthouse:print_schema` printed their definitions and every use
56
+ (`author: User! @belongsTo`). As in PHP Lighthouse, whose schema holds only the standard
57
+ directives and those the SDL declares, they are now taken out of the built schema: a client
58
+ sees `@skip`, `@include`, `@deprecated`, `@oneOf`, `@specifiedBy` and the SDL's own, and an
59
+ operation using `@all` is invalid. Lighthouse reads its directives from the SDL, so nothing
60
+ else changes.
61
+
62
+ ### Fixed
63
+
64
+ - **`@upload` purges what it stored when the field fails.** It stores a file before the
65
+ field resolves, and a model's validations run after: a `@create` the model refused left
66
+ its blobs in the bucket (#1). The blobs `@upload` stored for a field that raises, returns
67
+ an error or adds one to the context are now purged before the response (one the storage
68
+ service fails to delete is left to `purge_later`). The uploads guide now
69
+ recommends passing the file to the attachment attribute, which ActiveStorage uploads
70
+ only after commit.
71
+ - **Paginated queries end their order with the primary key.** Pages are cut by position, so
72
+ rows the field's order tied (`@orderBy(column: "created_at")`) could come back in another
73
+ order on the next page's query, and show on two pages or none; the same in the per-parent
74
+ row numbers of a batched relation. `@paginate` (every `type:`) and the paginated relation
75
+ directives now append the primary key unless the order names it already. PHP Lighthouse
76
+ leaves the order as it is.
77
+ - **`@globalId(decode:)` no longer loads the record to read its id (#2).** On a schema with
78
+ graphql-ruby's `object_from_id` (Rails' GlobalID, as its install writes it), decoding went
79
+ through `object_from_id`: a SELECT before `@find`'s own, under the model's default scope,
80
+ so a soft-deleted record's id did not decode for `@restore` / `@forceDelete` with an
81
+ `object_from_id` that kept the scope. A Rails GlobalID now decodes without the database,
82
+ as PHP Lighthouse's `decodeID` does; only an id of another format goes through
83
+ `object_from_id`.
84
+ - A directive the SDL uses that is neither built in, Lighthouse's nor declared fails the build
85
+ with ``No directive found for `@can` on Query.a.``, as PHP Lighthouse names it. On a root type
86
+ it failed with a `NoMethodError` from inside graphql-ruby.
87
+
88
+ - **An optional `Upload` takes an explicit `null`.** The scalar refused it ("Could not get
89
+ uploaded file ... Instead got: nil"), so a client had to leave the argument out. `null`
90
+ now reaches the resolver as `nil`, and `@upload` stores nothing for it.
91
+ - **`@canFind` fails when nothing is at its `find:` path, instead of passing unchecked.** A
92
+ misspelt path (`find: "inputt.id"`), or an optional argument the client left out, found
93
+ no ids, so no model was checked and the field resolved. It now fails with `Got no key to
94
+ find a model at the expected input path: …`, as PHP Lighthouse does (through `action:`,
95
+ like the other failures). A `*` over an empty list still checks no model.
96
+
9
97
  ## [0.7.3] - 2026-10-29
10
98
 
11
99
  ### Changed
@@ -736,7 +824,8 @@ had been running inside a private monorepo as a path gem before being extracted.
736
824
  - Config-driven extension seams: `Lighthouse.configure`, `resolver_namespaces`,
737
825
  `on_error`, and `DirectiveRegistry.register` for app-defined directives.
738
826
 
739
- [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.3...HEAD
827
+ [Unreleased]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.8.0...HEAD
828
+ [0.8.0]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.3...v0.8.0
740
829
  [0.7.3]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.2...v0.7.3
741
830
  [0.7.2]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.1...v0.7.2
742
831
  [0.7.1]: https://github.com/Vaz-Innovation/lighthouse-graphql/compare/v0.7.0...v0.7.1
@@ -107,7 +107,10 @@ Plus, per directive:
107
107
  - `@canFind(find: String!, model: String, findOrFail: Boolean = true, scopes: [String!])`.
108
108
  `find` is the argument holding the primary key or keys, and may be a dot path
109
109
  (`"input.id"`). A key that matches no record fails with
110
- `Couldn't find Post with 'id'=…`, unless `findOrFail: false`. `scopes` are model
110
+ `Couldn't find Post with 'id'=…`, unless `findOrFail: false`. Nothing at the path (a
111
+ misspelt one, or an optional argument the client left out) fails with
112
+ `Got no key to find a model at the expected input path: …`, as in PHP Lighthouse;
113
+ a `*` over an empty list (`"inputs.*.id"`) checks no model. `scopes` are model
111
114
  scopes applied to the lookup.
112
115
  - `@canModel(model: String)`.
113
116
  - `@canQuery(model: String, scopes: [String!])`. `scopes` narrow the records
@@ -131,6 +134,35 @@ post(id: ID!): Post @canFind(ability: "show", find: "id", action: EXCEPTION_NOT_
131
134
  `action` applies to the directive's own checks only. Errors from the resolver
132
135
  itself are untouched.
133
136
 
137
+ ### Who may use an argument
138
+
139
+ Some arguments are for some users only: `trashed` for admins, a filter on drafts
140
+ for editors. `@canModel` on an argument, or on an input field at any depth, checks
141
+ its ability against the model only when the client gives that argument a value, and
142
+ denies the whole field otherwise, as `@canModel` on the field does (`action:` too):
143
+
144
+ ```graphql
145
+ type Query {
146
+ posts(filter: PostFilter): [Post!]! @all
147
+ tasks(trashed: Trashed @trashed @canModel(ability: "view_trashed")): [Task!]! @all
148
+ }
149
+
150
+ input PostFilter {
151
+ title: String @like
152
+ status: PostStatus @eq @canModel(ability: "filter_by_status", model: "Post")
153
+ }
154
+ ```
155
+
156
+ ```ruby
157
+ class TaskPolicy < ApplicationPolicy
158
+ def view_trashed? = user&.admin?
159
+ end
160
+ ```
161
+
162
+ It runs with the field's `@can*` directives, before the field resolves. The model is
163
+ the directive's `model:`, else the field's, as for `@canModel` on a field.
164
+ `@softDeletes(ability:)` writes it on the `trashed` argument for you.
165
+
134
166
  ## Ordering
135
167
 
136
168
  The order you write directives in does not matter. They run as:
@@ -38,6 +38,44 @@ content is unchanged is left alone. `nil` (the default) turns it on in
38
38
  development when the app has a `graphql.config.yml`, which `lighthouse:install`
39
39
  writes. Set `true` or `false` to decide yourself.
40
40
 
41
+ ### `schema_log`
42
+
43
+ Log what development learns of the schema on boot and on every reload: it built (in
44
+ how long, how big, what the reload added and removed, the files it wrote), or why it
45
+ did not, and the persisted operations it no longer accepts:
46
+
47
+ ```text
48
+ [Lighthouse] ✓ AppSchema built in 61 ms: 47 types, 16 queries, 9 mutations, 3 subscriptions
49
+ [Lighthouse] + User.nickname − Post.legacyTitle
50
+ [Lighthouse] wrote schema.graphql
51
+
52
+ [Lighthouse] ✗ The schema does not build: Lighthouse::DefinitionError
53
+ [Lighthouse] No directive found for `@can` on User.nickname.
54
+ [Lighthouse] The next GraphQL request raises it: save a fix to reload.
55
+ ```
56
+
57
+ The schema is checked as `bin/rails lighthouse:validate_schema` checks it (the
58
+ `ValidateSchema` event, then every type), through the Rails logger, in colour when
59
+ `config.colorize_logging` is on. `nil` (the default) logs in a development server,
60
+ not in rake tasks or the console; `true` or `false` decide.
61
+
62
+ ### `schema_output`
63
+
64
+ A file development keeps the schema clients see in, for a codegen to read, as
65
+ NestJS's `autoSchemaFile`: rewritten on boot and on every reload, and only when it
66
+ changed, so a watcher runs only then ([`schema_log`](#schema-log) says when it did). A path under the app's root, whose extension
67
+ picks the format (`.json` for the introspection result, else SDL), or a Hash naming
68
+ the schema class too (`<App>Schema`, graphql-ruby's install's name, by default):
69
+
70
+ ```ruby
71
+ config.schema_output = 'schema.graphql'
72
+ config.schema_output = { path: 'app/javascript/graphql/schema.json', schema: 'Admin::Schema' }
73
+ ```
74
+
75
+ Commit the file and check it in CI with `bin/rails lighthouse:schema_output:verify`,
76
+ which fails when it is out of date; `bin/rails lighthouse:print_schema WRITE=1`
77
+ rewrites it. See [printing the schema](getting-started.md#the-schema-clients-see).
78
+
41
79
  ### `namespaces`
42
80
 
43
81
  Where each kind of class a schema names is looked up, by kind — they have
data/docs/directives.md CHANGED
@@ -89,6 +89,11 @@ type Query {
89
89
  - **The total** is only counted when the client selects `paginatorInfo` or
90
90
  `pageInfo`.
91
91
  - **Cursors** are base64 of the item's position.
92
+ - **The order** ends with the primary key: a page is cut by position, so rows the
93
+ field's order ties (`@orderBy(column: "created_at")` on posts created in the same
94
+ second), or a query with no order, would otherwise come back in another order on
95
+ the next page, and a row would show on two pages or none. An order that names
96
+ the key already, or a grouped query, is left as it is. PHP Lighthouse does not add it.
92
97
 
93
98
  ### `@count`
94
99
 
@@ -247,6 +252,35 @@ keywords (`def summary(words:)`), otherwise positionally, in the order the SDL
247
252
  declares them, as PHP Lighthouse passes them (`def summary(words)`). The SDL's
248
253
  defaults apply, and a method taking no parameters is called without them.
249
254
 
255
+ ### `@attachment`
256
+
257
+ The URL of an ActiveStorage attachment of the parent, or the URLs of a
258
+ `has_many_attached`: the read side of [`@upload`](uploads.md). Lighthouse's own, as
259
+ Laravel has no ActiveStorage.
260
+
261
+ ```graphql
262
+ type User {
263
+ avatarUrl: String @attachment # has_one_attached :avatar
264
+ avatarThumbUrl: String @attachment(name: "avatar", variant: "thumb")
265
+ photoUrls: [String!]! @attachment(url: PROXY) # has_many_attached :photos
266
+ }
267
+ ```
268
+
269
+ - **`name`** defaults to the field's name without its `Url` / `Urls` suffix:
270
+ `avatarUrl` reads `avatar`, `photoUrls` reads `photos`. A missing attachment is
271
+ `null`, a model without one of that name an error.
272
+ - **Every parent's attachments and blobs load at once**, two queries for any
273
+ number of users (`avatar_attachment: :blob`, what `User.with_attached_avatar`
274
+ loads), through the Dataloader when the schema uses it.
275
+ - **`url`**: `REDIRECT` (default) is Rails' redirect to the storage service,
276
+ `PROXY` streams the file through the app, and `DIRECT` is the service's own URL,
277
+ signed for `expiresIn` seconds on a private one (`ActiveStorage.service_urls_expire_in`
278
+ by default). The URL is absolute with the request's host, else a path.
279
+ - **`variant`** names a variant of the attachment
280
+ (`has_one_attached :avatar { |attachable| attachable.variant :thumb, resize_to_limit: [100, 100] }`).
281
+ A file that is not an image has none: `null`. A `REDIRECT` or `PROXY` variant is
282
+ processed when its URL is first followed; `DIRECT` processes it while resolving.
283
+
250
284
  ## Relay
251
285
 
252
286
  ### `@globalId` and `@node`
@@ -767,6 +801,16 @@ enum Trashed {
767
801
  }
768
802
  ```
769
803
 
804
+ Anyone may pass `trashed` unless you say who: `@softDeletes(ability: "view_trashed")`
805
+ puts [`@canModel`](authorization.md#who-may-use-an-argument) on the argument it adds,
806
+ so a client that passes `trashed` (any value) needs the ability on the model's policy.
807
+ Leaving `trashed` out lists the records as usual. PHP Lighthouse has no `ability:`.
808
+
809
+ ```graphql
810
+ tasks: [Task!]! @all @softDeletes(ability: "view_trashed")
811
+ # tasks(trashed: Trashed @trashed @canModel(ability: "view_trashed")): [Task!]! @all
812
+ ```
813
+
770
814
  ### `@trashed`
771
815
 
772
816
  The argument builder `@softDeletes` adds; use it by hand to name the argument
@@ -267,13 +267,48 @@ Route to it (`post '/graphql', to: 'graphql#execute'`, plus a `get` for
267
267
  - renders the JSON; in development an error renders as JSON with its backtrace.
268
268
 
269
269
  The hooks `graphql_context`, `graphql_schema` and `graphql_variables(param)` are
270
- private methods you can override. A controller with an action of its own wraps it
271
- in `lighthouse_request { ... }` to keep the request events:
270
+ private methods you can override.
271
+
272
+ ### Running an operation from another action
273
+
274
+ To render a page with its data already loaded, run the operation from the action
275
+ with `lighthouse_execute`, from `Lighthouse::GraphQL::Operations` (which
276
+ `Lighthouse::GraphQL::Controller` includes). It runs the operation as the endpoint
277
+ does, with the endpoint's context: `graphql_context`, and the client's IP and the
278
+ controller `@throttle` counts with. It returns the result, or `nil` when a
279
+ `@throttle` answered the request with a 429:
280
+
281
+ ```ruby
282
+ class PagesController < ApplicationController
283
+ include Lighthouse::GraphQL::Operations
284
+
285
+ lighthouse_schema AppSchema
286
+
287
+ def search
288
+ @results = lighthouse_execute('query Search($term: String!) { searchPosts(term: $term) { title } }',
289
+ variables: { term: params[:term] })
290
+ return if performed? # @throttle answered 429
291
+ end
292
+
293
+ private
294
+
295
+ def graphql_context = { current_user: current_user }
296
+ end
297
+ ```
298
+
299
+ `extensions:` runs a persisted query by its hash, and `context:` adds to the
300
+ context. The operation events (`StartOperationOrOperations`, `StartExecution`, ...)
301
+ fire as for a client's request. The request events (`StartRequest`, `EndRequest`)
302
+ are the GraphQL endpoint's, one per GraphQL request, as PHP Lighthouse's controller
303
+ dispatches them. `EndRequest` carries the response, which does not exist yet while
304
+ the action is still loading its data, so wrap the whole action in
305
+ `lighthouse_request { ... }` to dispatch them around it, with the page's response:
272
306
 
273
307
  ```ruby
274
308
  def search
275
309
  lighthouse_request do
276
- render json: Lighthouse::GraphQL::PersistedQueries.execute(AppSchema, query: params[:q], context: graphql_context)
310
+ results = lighthouse_execute(SEARCH, variables: { term: params[:term] })
311
+ render inertia: 'Search', props: { results: results } unless performed?
277
312
  end
278
313
  end
279
314
  ```
@@ -348,18 +383,36 @@ VS Code. The files are derived from your schema, so the generator adds them to
348
383
  registering a directive. The IDE reads every `.graphql` file the glob matches, as
349
384
  one schema: it does not follow `#import`.
350
385
 
351
- To see the schema clients get, with every type Lighthouse generated and the
352
- fields rewritten (`users { data { … } }`), print it. The task writes the SDL to
353
- stdout and nothing else, so redirect it to keep it:
386
+ > The IDE reads fields as you wrote them: `users: [User!]! @paginate` still looks
387
+ > like a list to it, although clients query `users { data { … } }`. Field
388
+ > rewrites are not something an extra file can express.
389
+
390
+ ### The schema clients see
391
+
392
+ Print it, as PHP Lighthouse's `lighthouse:print-schema` does: every type Lighthouse
393
+ generated, the fields rewritten (`users { data { … } }`), and none of Lighthouse's
394
+ directives, which instruct the server and are not part of the schema clients get
395
+ (nor of introspection). The task writes the SDL to stdout and nothing else:
354
396
 
355
397
  ```shell
356
- bin/rails lighthouse:print_schema # AppSchema
398
+ bin/rails lighthouse:print_schema # <App>Schema, else AppSchema
357
399
  SCHEMA=Admin::Schema bin/rails lighthouse:print_schema > generated.graphql
400
+ FORMAT=json bin/rails lighthouse:print_schema # the introspection result
401
+ FORMAT=federation bin/rails lighthouse:print_schema # a subgraph's SDL, with @key, ...
402
+ bin/rails lighthouse:print_schema WRITE=1 # config.schema_output, else lighthouse-schema.graphql
403
+ bin/rails lighthouse:print_schema WRITE=schema.graphql # that file
358
404
  ```
359
405
 
360
- > The IDE reads fields as you wrote them: `users: [User!]! @paginate` still looks
361
- > like a list to it, although clients query `users { data { … } }`. Field
362
- > rewrites are not something an extra file can express.
406
+ graphql-ruby prints types, fields, arguments and enum values in alphabetical order,
407
+ so the output is stable (PHP Lighthouse's `--sort`). `WRITE` leaves an unchanged
408
+ file alone. For a codegen, let development keep the file up to date with
409
+ [`schema_output`](configuration.md#schema-output), and check it in CI with
410
+ `bin/rails lighthouse:schema_output:verify`.
411
+
412
+ The schema is the one of the environment it is printed in: a field with
413
+ `@show(env: ["development"])` is in development's and not in production's. Print
414
+ the file a production client relies on with `RAILS_ENV=production` when the schema
415
+ uses `@show` or `@hide`.
363
416
 
364
417
  ## Casing: camelCase ↔ snake_case
365
418
 
data/docs/performance.md CHANGED
@@ -117,6 +117,15 @@ config.persisted_queries_only = Rails.env.production?
117
117
  - The manifest's operations are served from memory, so a cache eviction can
118
118
  never drop them. The file is reloaded when it changes, and an id that is not
119
119
  the SHA-256 of its body is rejected.
120
+ - The manifest can also be a Hash of operations, or a callable answering a Hash
121
+ or a path, called for every persisted query: to read what a frontend build
122
+ (Vite, graphql-codegen's persisted documents) writes somewhere of its own. A Hash
123
+ is checked once, until its content changes; keep the callable cheap (memoize the
124
+ parsed file), as it runs per request.
125
+
126
+ ```ruby
127
+ config.persisted_queries_manifest = -> { ViteManifest.persisted_documents } # a Hash, memoized
128
+ ```
120
129
  - With `persisted_queries_only`, nothing else runs, and arbitrary queries get
121
130
  `Only persisted queries are allowed.` (`PERSISTED_QUERY_NOT_IN_LIST`).
122
131
 
data/docs/relay.md CHANGED
@@ -156,8 +156,12 @@ directives then work on them. The schema has one kind of global id and one `Node
156
156
  - `@globalId` on a field that resolves an object's own id encodes it with
157
157
  `id_from_object`: `Tag.id` answers `tag.to_gid_param`, as graphql-ruby's `Node.id`
158
158
  does. Any other value is encoded as before.
159
- - `@globalId` on an argument decodes with `object_from_id`, which loads the object.
160
- `ID` gives its id, and `ARRAY` / `TYPE` its class name (`["Tag", 1]`, `"Tag"`).
159
+ - `@globalId` on an argument decodes a Rails GlobalID without reading the database,
160
+ as PHP Lighthouse decodes its ids: `ID` gives its id, and `ARRAY` / `TYPE` its
161
+ model's name (`["Tag", "1"]`, `"Tag"`). So `tag(id: ID! @globalId(decode: ID) @eq):
162
+ Tag @find` runs the one query of `@find`, and a soft-deleted record's id decodes for
163
+ `@restore`. An id of another format (an `id_from_object` of your own) is decoded
164
+ with `object_from_id`, which loads the object.
161
165
  - `node:` is the SDL's `Node` interface: `interface Node`, which `@node` adds, and
162
166
  `implements Node` refer to `Types::NodeType`. A `@node` type implements it.
163
167
  - `Query.node` and `nodes` find objects with `object_from_id`, through the
data/docs/uploads.md CHANGED
@@ -20,10 +20,16 @@ type Mutation {
20
20
 
21
21
  Lighthouse reads its values itself (`Lighthouse::GraphQL::Upload`): the resolver gets
22
22
  the uploaded file, an `ActionDispatch::Http::UploadedFile`. A value that is not a file
23
- makes the argument invalid. `Upload` is for arguments only, never a field's result.
23
+ makes the argument invalid. An optional `Upload` (`avatar: Upload`) also takes `null`,
24
+ which the resolver gets as `nil`; leaving the argument out is not the same as sending
25
+ `null`. `Upload` is for arguments only, never a field's result.
24
26
 
25
27
  An ActiveStorage attachment takes the file as it is: with `has_one_attached :avatar`
26
- on `User`, the mutation above attaches it.
28
+ on `User`, the mutation above attaches it. This is the way to attach a file to a model:
29
+ ActiveStorage uploads it once the record is saved and the transaction committed, so a
30
+ mutation the model's validations refuse uploads nothing. Reach for `@upload` when the
31
+ argument needs the stored blob itself (its signed id), or a `path:` or service of its
32
+ own.
27
33
 
28
34
  ## `@upload`
29
35
 
@@ -51,6 +57,15 @@ The signed id is what an attachment attribute attaches (`user.avatar = signed_id
51
57
  `ActiveStorage::Blob.find_signed` finds; the blob keeps the file's name and content
52
58
  type. Lists of files are stored one by one, and `null` stays `null`.
53
59
 
60
+ `@upload` stores the file before the field resolves (after `@guard`, the `@can*`
61
+ directives and `@validator`), and the model validates it after. When the field fails,
62
+ because the model refuses it, or the resolver raises or reports an error, the blobs
63
+ `@upload` stored for it are purged before the response (a blob the service fails to
64
+ delete is left to ActiveStorage's purge job), so no blob and no file is left behind. A blob
65
+ that is stored but never attached (the field succeeds and does not attach it) stays,
66
+ as ActiveStorage's own direct uploads do: purge those with a periodic job over
67
+ `ActiveStorage::Blob.unattached`.
68
+
54
69
  ActiveStorage makes a whole service public (`public: true` in `config/storage.yml`)
55
70
  or private, never one file. So `public:` must agree with the service's, and the schema
56
71
  never says a file is private that anyone can read: `@upload(public: true)` on a private
@@ -76,6 +91,17 @@ updateAvatar(avatar: Upload! @upload(disk: "avatars", path: "users", public: tru
76
91
  `@upload` runs once `@guard`, the `@can*` family and `@validator` have let the call
77
92
  through, so a refused call stores nothing.
78
93
 
94
+ ## Serving the files: `@attachment`
95
+
96
+ [`@attachment`](directives.md#attachment) answers the URL of an attachment, loading
97
+ every parent's at once:
98
+
99
+ ```graphql
100
+ type User {
101
+ avatarUrl: String @attachment
102
+ }
103
+ ```
104
+
79
105
  ## The request
80
106
 
81
107
  ```shell
@@ -32,13 +32,28 @@ module Lighthouse
32
32
  soft_deletes
33
33
  queue_broadcasts broadcast_queue
34
34
  global_id
35
+ schema_output schema_log
35
36
  ].freeze
36
37
 
37
38
  class << self
38
39
  attr_writer :schema_path, :ide_helper, :resolver_namespaces, :on_error, :authenticated_user, :policy_user, :authorizer,
39
40
  :transactional_mutations, :schema_cache, :watch_sdl, :persisted_queries, :persisted_queries_store, :persisted_queries_only,
40
41
  :queue_broadcasts,
41
- :convert_empty_strings_to_null, :feature_checker, :feature_actor, :global_id
42
+ :convert_empty_strings_to_null, :feature_checker, :feature_actor, :global_id, :schema_log
43
+
44
+ # A file development keeps the client schema in (SchemaPrinter): a path
45
+ # (under Rails.root; `.json` for the introspection result), or
46
+ # { path:, schema: 'AppSchema' }. nil (the default): none.
47
+ attr_accessor :schema_output
48
+
49
+ # Log the schema's build on boot and on every reload (SchemaReport): it
50
+ # built (in how long, what changed, the files written) or why not. nil
51
+ # (the default): in a development server, not in rake tasks or the console.
52
+ def schema_log
53
+ return @schema_log unless @schema_log.nil?
54
+
55
+ defined?(::Rails::Server) ? ::Rails.env.development? : false
56
+ end
42
57
 
43
58
  # The schema's entrypoint, as PHP Lighthouse's `schema_path`: the one file
44
59
  # the schema is read from, importing the others (`#import user.graphql`,
@@ -100,7 +115,8 @@ module Lighthouse
100
115
  # persisted_queries accept Apollo's Automatic Persisted Queries (PersistedQueries)
101
116
  # persisted_queries_store where APQ keeps queries; default Rails.cache
102
117
  # persisted_queries_ttl how long they live there (seconds; nil: until evicted)
103
- # persisted_queries_manifest a manifest of trusted operations, served by hash
118
+ # persisted_queries_manifest a manifest of trusted operations, served by hash: a JSON file,
119
+ # a Hash, or a callable answering either
104
120
  # persisted_queries_only reject any operation not in the manifest
105
121
  attr_accessor :schema_cache_path, :persisted_queries_ttl, :persisted_queries_manifest
106
122
 
@@ -31,9 +31,11 @@ require 'json'
31
31
  #
32
32
  # Hooks, private so they are not actions: `graphql_context` (default:
33
33
  # `{ current_user: current_user }` when the controller has a current_user, else
34
- # `{}`), `graphql_schema` and `graphql_variables(param)`. A controller with an
35
- # action of its own wraps it in `lighthouse_request { ... }` to get the request
36
- # events; a nested call dispatches them once.
34
+ # `{}`), `graphql_schema` and `graphql_variables(param)`, from
35
+ # Lighthouse::GraphQL::Operations, which also gives the controller's own actions
36
+ # `lighthouse_execute`. An action of its own wraps itself in
37
+ # `lighthouse_request { ... }` to get the request events; a nested call
38
+ # dispatches them once.
37
39
  module Lighthouse::GraphQL::Controller
38
40
  extend ActiveSupport::Concern
39
41
 
@@ -42,18 +44,7 @@ module Lighthouse::GraphQL::Controller
42
44
  # schema's rescue_from) catches it on its way out of the operation.
43
45
  class Performed < Exception; end # rubocop:disable Lint/InheritException
44
46
 
45
- included do
46
- class_attribute :lighthouse_schema_source, instance_writer: false
47
- end
48
-
49
- class_methods do
50
- # The schema `execute` runs: a schema class, its name (a String, constantized
51
- # per request so code reloading works) or a block (evaluated in the
52
- # controller, per request).
53
- def lighthouse_schema(schema = nil, &block)
54
- self.lighthouse_schema_source = schema || block
55
- end
56
- end
47
+ include Lighthouse::GraphQL::Operations
57
48
 
58
49
  def execute
59
50
  lighthouse_request do
@@ -74,58 +65,6 @@ module Lighthouse::GraphQL::Controller
74
65
 
75
66
  private
76
67
 
77
- # Dispatch StartRequest, run the block, dispatch EndRequest with the
78
- # response. Only the outermost call dispatches, and stops the block where a
79
- # @throttle `with:` method performed the response.
80
- def lighthouse_request
81
- return yield if @lighthouse_request_started
82
-
83
- @lighthouse_request_started = true
84
- Lighthouse::Events.dispatch(Lighthouse::Events::StartRequest.new(request))
85
- result = begin
86
- yield
87
- rescue Performed
88
- nil
89
- end
90
- Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(response))
91
- result
92
- end
93
-
94
- # The context of the operation: what @guard and the @can* directives read.
95
- def graphql_context
96
- respond_to?(:current_user, true) ? { current_user: current_user } : {}
97
- end
98
-
99
- # graphql_context, with what @throttle reads unless it sets its own: the
100
- # client's IP (rate_limit's default by:) and the controller, whose cache_store,
101
- # controller_path and methods rate_limit uses.
102
- def lighthouse_context
103
- { remote_ip: request.remote_ip, lighthouse_controller: self }.merge(graphql_context)
104
- end
105
-
106
- def graphql_schema
107
- source = lighthouse_schema_source
108
- case source
109
- when nil then raise Lighthouse::DefinitionError, "#{self.class}: name the schema with `lighthouse_schema AppSchema`"
110
- when String, Symbol then source.to_s.constantize
111
- when Proc then instance_exec(&source)
112
- else source
113
- end
114
- end
115
-
116
- # Variables arrive as a JSON string (GET or form posts) or as parameters.
117
- def graphql_variables(param)
118
- case param
119
- when String then param.present? ? JSON.parse(param) || {} : {}
120
- when Hash then param
121
- when nil then {}
122
- else
123
- raise ArgumentError, "Unexpected parameter: #{param}" unless param.respond_to?(:to_unsafe_h)
124
-
125
- param.to_unsafe_h
126
- end
127
- end
128
-
129
68
  # A multipart request's operation(s), a batch (a JSON array body), or the parameters.
130
69
  def lighthouse_operations
131
70
  Lighthouse::GraphQL::MultipartRequest.operations(params) || params[:_json] || params
@@ -112,8 +112,14 @@ class Lighthouse::GraphQL::DirectiveResolvers::ArgumentTransformsResolver < Ligh
112
112
  trim_all = phase == :rewrite && self.class.trims_all?(@field_def)
113
113
  inner = capture_inner(target_type_class)
114
114
 
115
- install(target_type_class, lambda do |obj, args, ctx|
115
+ resolve = lambda do |obj, args, ctx|
116
116
  inner.call(obj, args.is_a?(Hash) ? me.transform_hash(argument_defs, args, ctx, trim_all) : args, ctx)
117
+ end
118
+ return install(target_type_class, resolve) if phase == :rewrite
119
+
120
+ # A field that fails leaves no file @upload stored for it behind.
121
+ install(target_type_class, lambda do |obj, args, ctx|
122
+ Lighthouse::GraphQL::UploadStore.purge_on_failure(ctx) { resolve.call(obj, args, ctx) }
117
123
  end)
118
124
  end
119
125