lighthouse-graphql 0.7.2 → 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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +126 -1
  3. data/docs/authorization.md +33 -1
  4. data/docs/configuration.md +38 -0
  5. data/docs/directives.md +51 -4
  6. data/docs/filtering-and-ordering.md +52 -0
  7. data/docs/getting-started.md +63 -10
  8. data/docs/performance.md +9 -0
  9. data/docs/relay.md +6 -2
  10. data/docs/uploads.md +28 -2
  11. data/lib/lighthouse/ast_builder.rb +14 -5
  12. data/lib/lighthouse/config.rb +18 -2
  13. data/lib/lighthouse/controller.rb +6 -67
  14. data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +7 -1
  15. data/lib/lighthouse/directive_resolvers/association_resolvers.rb +5 -7
  16. data/lib/lighthouse/directive_resolvers/attachment_resolver.rb +139 -0
  17. data/lib/lighthouse/directive_resolvers/base.rb +26 -22
  18. data/lib/lighthouse/directive_resolvers/can_resolvers.rb +29 -5
  19. data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +1 -8
  20. data/lib/lighthouse/directives/definitions.rb +2 -2
  21. data/lib/lighthouse/directives/registry.rb +1 -1
  22. data/lib/lighthouse/directives/soft_deletes_directive.rb +23 -6
  23. data/lib/lighthouse/document_ast.rb +6 -0
  24. data/lib/lighthouse/field_resolver_stack.rb +32 -0
  25. data/lib/lighthouse/global_id.rb +16 -5
  26. data/lib/lighthouse/graphql/version.rb +1 -1
  27. data/lib/lighthouse/operations.rb +111 -0
  28. data/lib/lighthouse/pagination.rb +21 -1
  29. data/lib/lighthouse/persisted_queries/manifest.rb +40 -0
  30. data/lib/lighthouse/persisted_queries.rb +9 -27
  31. data/lib/lighthouse/railtie.rb +8 -1
  32. data/lib/lighthouse/rb_lighthouse.rb +6 -0
  33. data/lib/lighthouse/relation_batch.rb +1 -1
  34. data/lib/lighthouse/schema_generator.rb +2 -0
  35. data/lib/lighthouse/schema_printer.rb +100 -0
  36. data/lib/lighthouse/schema_report.rb +161 -0
  37. data/lib/lighthouse/server_directives.rb +63 -0
  38. data/lib/lighthouse/tasks/lighthouse.rake +25 -6
  39. data/lib/lighthouse/upload.rb +2 -1
  40. data/lib/lighthouse/upload_store.rb +53 -2
  41. data/sig/lighthouse/controller.rbs +19 -8
  42. data/sig/lighthouse/directives.rbs +27 -0
  43. data/sig/lighthouse/graphql.rbs +3 -0
  44. data/sig/lighthouse.rbs +11 -2
  45. metadata +7 -1
@@ -0,0 +1,63 @@
1
+ # frozen_string_literal: true
2
+
3
+ # Lighthouse's directives instruct the server. PHP Lighthouse's executable
4
+ # schema holds only the standard directives and those the SDL declares: its
5
+ # own are found by name (DirectiveLocator), never added to the schema.
6
+ # Lighthouse injects their definitions for graphql-ruby to build the schema
7
+ # (SchemaGenerator.inject_directive_definitions), so it checks every directive
8
+ # the SDL uses has one, and then takes them out of the built schema.
9
+ module Lighthouse::GraphQL::ServerDirectives
10
+ Nodes = ::GraphQL::Language::Nodes
11
+
12
+ # Where a client may use a directive: in an operation, not the schema.
13
+ EXECUTABLE_LOCATIONS = %w[QUERY MUTATION SUBSCRIPTION FIELD FRAGMENT_DEFINITION FRAGMENT_SPREAD INLINE_FRAGMENT VARIABLE_DEFINITION].freeze
14
+
15
+ # The lists of a definition whose members may carry directives.
16
+ MEMBER_LISTS = %i[fields arguments values].freeze
17
+
18
+ module_function
19
+
20
+ # Every directive the document uses is built in, Lighthouse's or declared;
21
+ # else a DefinitionError naming it and where, as PHP Lighthouse's
22
+ # DirectiveLocator raises. graphql-ruby fails too, but on a root type with a
23
+ # NoMethodError from inside its builder.
24
+ def check_defined!(document)
25
+ defined = ::GraphQL::Schema.default_directives.keys.to_set
26
+ definitions = document.definitions.group_by { |node| node.is_a?(Nodes::DirectiveDefinition) }
27
+ (definitions[true] || []).each { |node| defined << node.name }
28
+
29
+ each_member(definitions[false] || []) do |node, owner|
30
+ unknown = node.directives.find { |directive| defined.exclude?(directive.name) }
31
+ raise Lighthouse::DefinitionError, "No directive found for `@#{unknown.name}` on #{owner}." if unknown
32
+ end
33
+ end
34
+
35
+ # Each definition, and each of its fields, arguments, values and input
36
+ # fields at any depth, with its path (`Query.posts.first`).
37
+ def each_member(definitions)
38
+ stack = definitions.map { |node| [node, node.try(:name) || 'schema'] }
39
+ while (entry = stack.pop)
40
+ node, owner = entry
41
+ yield node, owner
42
+ MEMBER_LISTS.each do |list|
43
+ node.public_send(list).each { |child| stack << [child, "#{owner}.#{child.name}"] } if node.respond_to?(list)
44
+ end
45
+ end
46
+ end
47
+
48
+ # Take Lighthouse's directives out of the built schema: clients see none
49
+ # of them, in introspection or the printed schema (definitions, uses, nor
50
+ # the types only they use), and an operation using one is invalid.
51
+ # Lighthouse reads them from the SDL's nodes, not the schema. One a client
52
+ # may use in an operation stays. Removed, not hidden: graphql-ruby only
53
+ # checks `visible?` in a schema using GraphQL::Schema::Visibility.
54
+ def hide!(schema, registry: Lighthouse::DirectiveRegistry.default)
55
+ return unless schema.respond_to?(:own_directives, true)
56
+
57
+ names = registry.directive_definitions.keys.to_set
58
+ own = schema.send(:own_directives)
59
+ own.delete_if do |name, directive|
60
+ names.include?(name) && !directive.locations.map(&:to_s).intersect?(EXECUTABLE_LOCATIONS)
61
+ end
62
+ end
63
+ end
@@ -7,12 +7,31 @@ namespace :lighthouse do
7
7
  Lighthouse::IdeHelper.write(output_dir: output_dir).each { |path| puts "Wrote #{path}" }
8
8
  end
9
9
 
10
- desc 'Print the final schema (SDL) to stdout, as clients see it (SCHEMA=AppSchema)'
10
+ desc 'Print the schema clients see (SCHEMA=AppSchema FORMAT=sdl|json|federation; WRITE=1 or WRITE=path writes a file)'
11
11
  task print_schema: :environment do
12
- schema = Object.const_get(ENV.fetch('SCHEMA', 'AppSchema'))
13
- puts schema.to_definition
12
+ printer = Lighthouse::GraphQL::SchemaPrinter
13
+ output = printer.output
14
+ schema = printer.app_schema(ENV.fetch('SCHEMA', nil))
15
+ format = ENV.fetch('FORMAT') { ENV['WRITE'] == '1' && output ? output[:format] : 'sdl' }
16
+ content = printer.print(schema, format: format)
17
+ if (write = ENV.fetch('WRITE', nil))
18
+ path = write == '1' ? (output&.fetch(:path) || Rails.root.join(printer::FILENAMES.fetch(format))) : Rails.root.join(write)
19
+ puts printer.write(path, content) ? "Wrote #{path}" : "#{path} is up to date"
20
+ else
21
+ puts content
22
+ end
14
23
  rescue StandardError => e
15
- abort("#{schema || 'Schema'} can not be printed: #{e.message}")
24
+ abort("#{schema || 'The schema'} can not be printed: #{e.message}")
25
+ end
26
+
27
+ namespace :schema_output do
28
+ desc 'Fail when the file config.schema_output names is missing or out of date (for CI)'
29
+ task verify: :environment do
30
+ printer = Lighthouse::GraphQL::SchemaPrinter
31
+ output = printer.output || abort('config.schema_output is not set.')
32
+ abort("#{output[:path]} is out of date: run bin/rails lighthouse:print_schema WRITE=1") if printer.stale?(output)
33
+ puts "#{output[:path]} is up to date."
34
+ end
16
35
  end
17
36
 
18
37
  desc 'Build the schema cache in tmp/cache (for config.schema_cache; e.g. during a Docker build)'
@@ -28,7 +47,7 @@ namespace :lighthouse do
28
47
 
29
48
  desc 'Build the schema, dispatch the ValidateSchema event and check graphql-ruby accepts it (SCHEMA=AppSchema)'
30
49
  task validate_schema: :environment do
31
- schema = Object.const_get(ENV.fetch('SCHEMA', 'AppSchema'))
50
+ schema = Lighthouse::GraphQL::SchemaPrinter.app_schema(ENV.fetch('SCHEMA', nil))
32
51
  Lighthouse::Events.dispatch(Lighthouse::Events::ValidateSchema.new(schema))
33
52
  schema.to_definition # builds every type: unresolvable references and duplicate names raise
34
53
  puts "#{schema} is valid."
@@ -39,7 +58,7 @@ namespace :lighthouse do
39
58
  namespace :persisted_queries do
40
59
  desc 'Validate every operation of the persisted query manifest against the schema (SCHEMA=AppSchema)'
41
60
  task verify: :environment do
42
- schema = Object.const_get(ENV.fetch('SCHEMA', 'AppSchema'))
61
+ schema = Lighthouse::GraphQL::SchemaPrinter.app_schema(ENV.fetch('SCHEMA', nil))
43
62
  failures = Lighthouse::GraphQL::PersistedQueries.manifest.filter_map do |hash, body|
44
63
  errors = schema.validate(body)
45
64
  "#{hash}: #{errors.map(&:message).join('; ')}" if errors.any?
@@ -10,8 +10,9 @@
10
10
  class Lighthouse::GraphQL::Upload < GraphQL::Schema::Scalar
11
11
  graphql_name 'Upload'
12
12
 
13
+ # An optional Upload the client sets to null stays null.
13
14
  def self.coerce_input(value, _context)
14
- return value if file?(value)
15
+ return value if value.nil? || file?(value)
15
16
 
16
17
  raise ::GraphQL::CoercionError,
17
18
  'Could not get uploaded file, be sure to conform to GraphQL multipart request specification: ' \
@@ -10,7 +10,16 @@
10
10
  # which a has_one_attached / has_many_attached attribute attaches (where Laravel
11
11
  # hands the stored path, for a model to keep). To store files elsewhere, declare
12
12
  # an ActiveStorage service for it, as a Laravel app declares a disk.
13
+ #
14
+ # A blob is stored before the field resolves (after @guard, @can* and
15
+ # @validator), and the model's own validations run after. When the field
16
+ # fails, the blobs it stored are purged, so a refused mutation leaves no blob
17
+ # and no file behind: see purge_on_failure.
13
18
  module Lighthouse::GraphQL::UploadStore
19
+ # The fiber-local list of the blobs stored for the field resolving: graphql-ruby's
20
+ # dataloader runs each field in a fiber of its own.
21
+ STORED = :lighthouse_uploads_stored
22
+
14
23
  module_function
15
24
 
16
25
  def call(file, argument:, disk: nil, path: nil, public: nil)
@@ -23,9 +32,51 @@ module Lighthouse::GraphQL::UploadStore
23
32
 
24
33
  service = service(argument, disk, public == true)
25
34
  file.rewind if file.respond_to?(:rewind) # a @validator, or another argument the multipart map sent it to, may have read it
26
- ::ActiveStorage::Blob.create_and_upload!(
35
+ blob = ::ActiveStorage::Blob.create_and_upload!(
27
36
  io: file, filename: filename(file), content_type: file.try(:content_type), key: key(path), service_name: service.name
28
- ).signed_id
37
+ )
38
+ Thread.current[STORED]&.push(blob)
39
+ blob.signed_id
40
+ end
41
+
42
+ # Runs the block, a field's resolution, and purges the blobs @upload stored
43
+ # meanwhile when it fails: it raises, returns a GraphQL::ExecutionError, or
44
+ # adds an error to the query's `context`. Nested in another, a success
45
+ # hands its blobs to the outer one.
46
+ def purge_on_failure(context)
47
+ outer = Thread.current[STORED]
48
+ blobs = Thread.current[STORED] = []
49
+ errors = error_count(context)
50
+ result = yield
51
+ failed?(result, context, errors) ? purge(blobs) : outer&.concat(blobs)
52
+ result
53
+ rescue StandardError
54
+ purge(blobs || [])
55
+ raise
56
+ ensure
57
+ Thread.current[STORED] = outer
58
+ end
59
+
60
+ # Not Array(result): a relation would be loaded.
61
+ def failed?(result, context, errors_before)
62
+ result.is_a?(::GraphQL::ExecutionError) || (result.is_a?(Array) && result.any?(::GraphQL::ExecutionError)) ||
63
+ error_count(context) > errors_before
64
+ end
65
+
66
+ def error_count(context)
67
+ context.respond_to?(:errors) ? context.errors.size : 0
68
+ end
69
+
70
+ # Now, not later: the blobs are attached to nothing, and the client is told
71
+ # the mutation failed, so none outlives the response. One the service fails
72
+ # to delete is left to ActiveStorage's job to retry.
73
+ def purge(blobs)
74
+ blobs.each do |blob|
75
+ blob.purge
76
+ rescue StandardError
77
+ blob.purge_later
78
+ end
79
+ blobs.clear
29
80
  end
30
81
 
31
82
  # The service `disk` names, or the default one, checked to be as public as asked.
@@ -1,30 +1,41 @@
1
- # The Rails controller concern that serves a schema. See docs/getting-started.md.
1
+ # The Rails controller concerns that run and serve a schema. See docs/getting-started.md.
2
2
  module Lighthouse
3
3
  module GraphQL
4
- module Controller
4
+ # Run an operation from any action, with the context the endpoint gives it.
5
+ module Operations
5
6
  module ClassMethods
6
- # The schema `execute` runs: a schema class, its name (constantized per
7
- # request) or a block (evaluated in the controller, per request).
7
+ # The schema the operations run on: a schema class, its name (constantized
8
+ # per request) or a block (evaluated in the controller, per request).
8
9
  def lighthouse_schema: (?(Class | String | Symbol)? schema) ?{ () -> untyped } -> untyped
9
10
  end
10
11
 
11
- # The action: dispatches StartRequest, runs the operation (or a batch),
12
- # sets Cache-Control, renders JSON, dispatches EndRequest.
13
- def execute: () -> untyped
14
-
15
12
  private
16
13
 
14
+ # The operation's result, or nil when a @throttle performed the response.
15
+ def lighthouse_execute: (String? query, ?variables: untyped, ?operation_name: String?, ?extensions: Hash[untyped, untyped]?, ?context: Hash[Symbol, untyped]) -> Hash[String, untyped]?
16
+
17
17
  # Dispatch StartRequest, yield, dispatch EndRequest; only the outermost call does.
18
18
  def lighthouse_request: [T] () { () -> T } -> T
19
19
 
20
20
  # The operation's context; { current_user: current_user } when the controller has one.
21
21
  def graphql_context: () -> Hash[Symbol, untyped]
22
22
 
23
+ # graphql_context, with what @throttle reads: remote_ip and the controller.
24
+ def lighthouse_context: () -> Hash[Symbol, untyped]
25
+
23
26
  # The schema class `lighthouse_schema` names.
24
27
  def graphql_schema: () -> untyped
25
28
 
26
29
  # The `variables` parameter as a Hash: from a JSON String, a Hash or parameters.
27
30
  def graphql_variables: (untyped param) -> Hash[String, untyped]
28
31
  end
32
+
33
+ module Controller
34
+ include Operations
35
+
36
+ # The action: dispatches StartRequest, runs the operation (or a batch),
37
+ # sets Cache-Control, renders JSON, dispatches EndRequest.
38
+ def execute: () -> untyped
39
+ end
29
40
  end
30
41
  end
@@ -88,6 +88,33 @@ module Lighthouse
88
88
  def manipulate_sdl: (String sdl) -> String
89
89
  end
90
90
 
91
+ module GraphQL
92
+ # The schema clients see, printed (`bin/rails lighthouse:print_schema`), and
93
+ # Config.schema_output's file, kept up to date in development.
94
+ module SchemaPrinter
95
+ FORMATS: Array[String]
96
+ FILENAMES: Hash[String, String]
97
+
98
+ def self?.print: (untyped schema, ?format: String | Symbol) -> String
99
+ def self?.app_schema: (?String? name) -> untyped
100
+ def self?.output: () -> Hash[Symbol, untyped]?
101
+ def self?.output_content: (?Hash[Symbol, untyped]? setting) -> String
102
+ # Writes unless the file holds `content` already; true when it wrote.
103
+ def self?.write: (path path, String content) -> bool
104
+ def self?.stale?: (?Hash[Symbol, untyped]? setting) -> bool
105
+ end
106
+
107
+ # Development's report on the schema, on boot and every reload: logged
108
+ # with Config.schema_log; schema_output's file rewritten.
109
+ module SchemaReport
110
+ LIST_LIMIT: Integer
111
+
112
+ # The report's [level, text] lines; nil when there is nothing to do.
113
+ def self?.refresh: (?logger: untyped) -> Array[[Symbol, String]]?
114
+ def self?.report: (Hash[Symbol, untyped]? output) -> Array[[Symbol, String]]
115
+ end
116
+ end
117
+
91
118
  # Writes the SDL an IDE needs next to the app's own: `bin/rails lighthouse:ide_helper`.
92
119
  module IdeHelper
93
120
  DIRECTIVES_FILE: String
@@ -51,6 +51,7 @@ module Lighthouse
51
51
  # Adds a type, or replaces the one of the same name.
52
52
  def put_type: (untyped definition) -> self
53
53
  def remove_type: (String name) -> self
54
+ def remove_directive: (String name) -> self
54
55
  # Adds the type parsed from the SDL (or the block's), unless one of the name exists.
55
56
  def define_type: (String name, ?String? sdl) ?{ () -> String } -> untyped
56
57
  def type?: (String name) -> bool
@@ -62,6 +63,8 @@ module Lighthouse
62
63
  # The manipulation phase: extensions merged, then the type, field and argument manipulators.
63
64
  module ASTBuilder
64
65
  ROOT_TYPES: Array[String]
66
+ # graphql-ruby's own directives, whose definitions the SDL may repeat.
67
+ BUILT_IN_DIRECTIVES: Array[String]
65
68
 
66
69
  def self?.build: (String sdl, ?registry: DirectiveRegistry) -> String
67
70
  end
data/sig/lighthouse.rbs CHANGED
@@ -101,6 +101,14 @@ module Lighthouse
101
101
  def self.ide_helper: () -> bool?
102
102
  def self.ide_helper=: (bool? enabled) -> bool?
103
103
 
104
+ # The file development keeps the client schema in: a path, or { path:, schema: }; nil: none.
105
+ def self.schema_output: () -> (path | Hash[Symbol, untyped])?
106
+ def self.schema_output=: ((path | Hash[Symbol, untyped])? output) -> (path | Hash[Symbol, untyped])?
107
+
108
+ # Log the schema's build on boot and every reload; nil: in a development server.
109
+ def self.schema_log: () -> bool
110
+ def self.schema_log=: (bool? enabled) -> bool?
111
+
104
112
  # { queries:, mutations:, subscriptions:, builders:, validators:, events: } => [namespace, ...].
105
113
  # Assigning a partial hash overrides only the kinds it names.
106
114
  def self.namespaces: () -> Hash[Symbol, Array[String]]
@@ -134,8 +142,9 @@ module Lighthouse
134
142
  def self.persisted_queries_store=: (untyped store) -> untyped
135
143
  def self.persisted_queries_ttl: () -> Numeric?
136
144
  def self.persisted_queries_ttl=: (Numeric? seconds) -> Numeric?
137
- def self.persisted_queries_manifest: () -> path?
138
- def self.persisted_queries_manifest=: (path? path) -> path?
145
+ # A JSON file, a Hash of operations, or a callable answering either.
146
+ def self.persisted_queries_manifest: () -> (path | Hash[untyped, untyped] | ^() -> (path | Hash[untyped, untyped])?)?
147
+ def self.persisted_queries_manifest=: ((path | Hash[untyped, untyped] | ^() -> (path | Hash[untyped, untyped])?)? manifest) -> untyped
139
148
  def self.persisted_queries_only: () -> bool
140
149
  def self.persisted_queries_only=: (bool? enabled) -> bool?
141
150
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lighthouse-graphql
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.7.2
4
+ version: 0.8.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Vaz Innovation
@@ -118,6 +118,7 @@ files:
118
118
  - lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb
119
119
  - lib/lighthouse/directive_resolvers/association_resolvers.rb
120
120
  - lib/lighthouse/directive_resolvers/async_resolver.rb
121
+ - lib/lighthouse/directive_resolvers/attachment_resolver.rb
121
122
  - lib/lighthouse/directive_resolvers/auth_resolver.rb
122
123
  - lib/lighthouse/directive_resolvers/base.rb
123
124
  - lib/lighthouse/directive_resolvers/broadcast_resolver.rb
@@ -190,10 +191,12 @@ files:
190
191
  - lib/lighthouse/nested_mutations/many_to_many_operations.rb
191
192
  - lib/lighthouse/nested_mutations/partitioner.rb
192
193
  - lib/lighthouse/node_registry.rb
194
+ - lib/lighthouse/operations.rb
193
195
  - lib/lighthouse/order_by/types.rb
194
196
  - lib/lighthouse/pagination.rb
195
197
  - lib/lighthouse/persisted_queries.rb
196
198
  - lib/lighthouse/persisted_queries/batch.rb
199
+ - lib/lighthouse/persisted_queries/manifest.rb
197
200
  - lib/lighthouse/railtie.rb
198
201
  - lib/lighthouse/rb_lighthouse.rb
199
202
  - lib/lighthouse/reference_resolver.rb
@@ -208,7 +211,10 @@ files:
208
211
  - lib/lighthouse/schema_factory.rb
209
212
  - lib/lighthouse/schema_generator.rb
210
213
  - lib/lighthouse/schema_implementation.rb
214
+ - lib/lighthouse/schema_printer.rb
215
+ - lib/lighthouse/schema_report.rb
211
216
  - lib/lighthouse/schema_stitcher.rb
217
+ - lib/lighthouse/server_directives.rb
212
218
  - lib/lighthouse/subscription.rb
213
219
  - lib/lighthouse/support/arguments.rb
214
220
  - lib/lighthouse/support/authorization.rb