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
@@ -65,7 +65,7 @@ class Lighthouse::GraphQL::RelationBatch
65
65
 
66
66
  # { owner key => its records in rows offset+1..offset+limit }
67
67
  def pages(owners, offset, limit)
68
- relation = relation(owners)
68
+ relation = Lighthouse::GraphQL::Pagination.stable_order(relation(owners))
69
69
  ranked = relation.unscope(:order).select(*selection(relation), "#{row_number(relation)} AS #{ROW}", "#{partition} AS #{OWNER}")
70
70
  rows = relation.klass.unscoped.from(ranked, relation.klass.table_name)
71
71
  .where("#{ROW} > ? AND #{ROW} <= ?", offset, offset + limit)
@@ -44,11 +44,13 @@ module Lighthouse::GraphQL::SchemaGenerator
44
44
  # The manipulated document — from the schema cache when it is enabled
45
45
  # and fresh (see SchemaCache), else built now.
46
46
  document = build_document(sdl_string)
47
+ Lighthouse::GraphQL::ServerDirectives.check_defined!(document)
47
48
  impl = default_implementation
48
49
  # base_types' resolver / mutation / subscription are Lighthouse's, not graphql-ruby's.
49
50
  bases = Lighthouse::GraphQL::ResolverBases.extract!(opts)
50
51
  schema = Lighthouse::GraphQL::RootTypes.build(document, bases[:roots]) { from_document(document, impl, opts) }
51
52
 
53
+ Lighthouse::GraphQL::ServerDirectives.hide!(schema)
52
54
  delegate_to_federation_sdl(schema)
53
55
  Lighthouse::GraphQL::GeneratedResolvers.install_dispatcher(schema)
54
56
  attach_schema(impl, schema)
@@ -0,0 +1,100 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ # The schema as clients see it (Lighthouse's directives are not in it, see
6
+ # ServerDirectives), printed as PHP Lighthouse's `lighthouse:print-schema`
7
+ # prints it: SDL, the introspection result as JSON (`json`), or a subgraph's
8
+ # SDL with its federation directives (`federation`). The SDL comes from
9
+ # graphql-ruby's printer (to_definition answers a federated schema with its
10
+ # subgraph SDL), which orders types, fields, arguments and values
11
+ # alphabetically: what PHP Lighthouse's `--sort` asks webonyx for.
12
+ #
13
+ # Config.schema_output keeps a file of it in development, as NestJS's
14
+ # autoSchemaFile does: rewritten on boot and on every reload (SchemaReport),
15
+ # only when it changed, so a codegen watching it runs only then.
16
+ #
17
+ # Lighthouse.configure { |config| config.schema_output = 'schema.graphql' }
18
+ # Lighthouse.configure { |config| config.schema_output = { path: 'schema.json', schema: 'Admin::Schema' } }
19
+ module Lighthouse::GraphQL::SchemaPrinter
20
+ FORMATS = %w[sdl json federation].freeze
21
+
22
+ # PHP Lighthouse's file names, for `lighthouse:print_schema WRITE=1` with no schema_output.
23
+ FILENAMES = {
24
+ 'sdl' => 'lighthouse-schema.graphql',
25
+ 'json' => 'lighthouse-schema.json',
26
+ 'federation' => 'lighthouse-schema-federation.graphql'
27
+ }.freeze
28
+
29
+ module_function
30
+
31
+ def print(schema, format: 'sdl')
32
+ format = format.to_s
33
+ raise ArgumentError, "Unknown schema format #{format.inspect}, expected #{FORMATS.join(', ')}." unless FORMATS.include?(format)
34
+
35
+ case format
36
+ when 'sdl' then ::GraphQL::Schema::Printer.print_schema(schema)
37
+ when 'json' then "#{JSON.pretty_generate(schema.as_json.fetch('data'))}\n"
38
+ else federation(schema)
39
+ end
40
+ end
41
+
42
+ def federation(schema)
43
+ raise ArgumentError, 'The federation format needs a federated schema (federation: true).' unless schema.respond_to?(:federation_sdl)
44
+
45
+ "#{schema.federation_sdl.chomp}\n"
46
+ end
47
+
48
+ # The app's schema class: `name`, else schema_output's `schema:`, else
49
+ # graphql-ruby's install's name (`<App>Schema`), else AppSchema.
50
+ def app_schema(name = nil)
51
+ candidates = [name, output&.fetch(:schema, nil), default_schema_name, 'AppSchema'].compact.uniq
52
+ candidates.each do |candidate|
53
+ schema = candidate.to_s.safe_constantize
54
+ return schema if schema
55
+ end
56
+ raise Lighthouse::DefinitionError, "No schema class #{candidates.join(' or ')}: name it with SCHEMA=, or schema_output's schema:."
57
+ end
58
+
59
+ def default_schema_name
60
+ return unless defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application
61
+
62
+ "#{::Rails.application.class.module_parent_name}Schema"
63
+ end
64
+
65
+ # Config.schema_output as { path:, schema:, format: }, the path
66
+ # absolute (under Rails.root) and the format from its extension; nil when unset.
67
+ def output
68
+ setting = Lighthouse::Config.schema_output
69
+ return if setting.nil?
70
+
71
+ options = setting.is_a?(Hash) ? setting.symbolize_keys : { path: setting }
72
+ path = Pathname(options.fetch(:path))
73
+ path = ::Rails.root.join(path) if path.relative? && defined?(::Rails) && ::Rails.root
74
+ { path: path, schema: options[:schema], format: path.extname == '.json' ? 'json' : 'sdl' }
75
+ end
76
+
77
+ # The schema as schema_output asks for it.
78
+ def output_content(setting = output)
79
+ print(app_schema(setting[:schema]), format: setting[:format])
80
+ end
81
+
82
+ # Writes `content` at `path` unless it holds it already, through a
83
+ # temporary file renamed over it, so a watcher never reads half a schema.
84
+ # True when it wrote.
85
+ def write(path, content)
86
+ path = Pathname(path)
87
+ return false if path.file? && path.read == content
88
+
89
+ path.dirname.mkpath
90
+ temporary = path.dirname.join(".#{path.basename}.#{Process.pid}.tmp")
91
+ temporary.write(content)
92
+ File.rename(temporary, path)
93
+ true
94
+ end
95
+
96
+ # Is the file at schema_output missing or out of date?
97
+ def stale?(setting = output)
98
+ !(setting[:path].file? && setting[:path].read == output_content(setting))
99
+ end
100
+ end
@@ -0,0 +1,161 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'set'
4
+
5
+ # What development learns of the schema on boot and on every reload. The
6
+ # schema is built and checked as `lighthouse:validate_schema` checks it
7
+ # (ValidateSchema, then every type), config.schema_output's file is rewritten
8
+ # when it changed, the persisted query manifest's operations are checked
9
+ # against it, and the outcome is logged:
10
+ #
11
+ # [Lighthouse] ✓ AppSchema built in 84 ms: 42 types, 18 queries, 9 mutations
12
+ # [Lighthouse] + Query.search + Post.excerpt − Post.legacyTitle
13
+ # [Lighthouse] wrote schema.graphql
14
+ #
15
+ # [Lighthouse] ✗ The schema does not build: Lighthouse::DefinitionError
16
+ # [Lighthouse] No directive found for `@can` on Query.a.
17
+ # [Lighthouse] The next GraphQL request raises it: save a fix to reload.
18
+ #
19
+ # Config.schema_log: nil (the default) logs in a development server (not in
20
+ # rake tasks or the console); true or false decide. schema_output is kept up
21
+ # to date in development either way.
22
+ module Lighthouse::GraphQL::SchemaReport
23
+ # The most added, removed or invalid entries a line lists.
24
+ LIST_LIMIT = 8
25
+
26
+ module_function
27
+
28
+ # The report's [level, text] lines, logged when Config.schema_log is on;
29
+ # nil when there is nothing to do.
30
+ def refresh(logger: default_logger)
31
+ log = Lighthouse::Config.schema_log
32
+ output = Lighthouse::GraphQL::SchemaPrinter.output if development?
33
+ return unless log || output
34
+
35
+ lines = report(output)
36
+ log ? write_log(logger, lines) : warn_errors(lines)
37
+ lines
38
+ end
39
+
40
+ def write_log(logger, lines)
41
+ echo = console_not_attached?(logger)
42
+ lines.each do |level, text|
43
+ logger&.public_send(level, "[Lighthouse] #{text}")
44
+ $stdout.puts("[Lighthouse] #{text}") if echo
45
+ end
46
+ end
47
+
48
+ # `rails server` copies the log to the terminal once the app is loaded, so
49
+ # the boot's report, logged while it loads, would reach only the log file.
50
+ def console_not_attached?(logger)
51
+ defined?(::Rails::Server) && logger && !::ActiveSupport::Logger.logger_outputs_to?(logger, $stdout, $stderr)
52
+ end
53
+
54
+ # schema_output without the log: a schema that does not build only warns, as before.
55
+ def warn_errors(lines)
56
+ lines.each { |level, text| warn("Lighthouse: #{text.strip}") if level == :error }
57
+ end
58
+
59
+ def report(output)
60
+ started = Process.clock_gettime(Process::CLOCK_MONOTONIC)
61
+ schema = Lighthouse::GraphQL::SchemaPrinter.app_schema(output&.fetch(:schema, nil))
62
+ Lighthouse::Events.dispatch(Lighthouse::Events::ValidateSchema.new(schema))
63
+ printed = Lighthouse::GraphQL::SchemaPrinter.print(schema) # builds every type, as validate_schema does
64
+ elapsed = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - started) * 1000).round
65
+
66
+ types = fingerprint(printed)
67
+ [[:info, "#{paint('✓', :green)} #{schema.name || 'The schema'} built in #{elapsed} ms: #{summary(schema, types)}"],
68
+ *changes(schema, types), *written(schema, output, printed), *stale_operations(schema)]
69
+ rescue StandardError => e
70
+ [[:error, "#{paint('✗', :red)} The schema does not build: #{e.class}"],
71
+ *e.message.lines.map { |line| [:error, " #{line.chomp}"] },
72
+ [:error, ' The next GraphQL request raises it: save a fix to reload.']]
73
+ end
74
+
75
+ # "42 types, 18 queries, 9 mutations"
76
+ def summary(schema, types)
77
+ roots = { 'queries' => schema.query, 'mutations' => schema.mutation, 'subscriptions' => schema.subscription }
78
+ counts = roots.filter_map { |label, root| "#{root.fields.size} #{label}" if root }
79
+ ["#{types.size} types", *counts].join(', ')
80
+ end
81
+
82
+ # What the reload added and removed: types, and the fields of the types kept.
83
+ def changes(schema, current)
84
+ previous = (@fingerprints ||= {})[schema.name]
85
+ @fingerprints[schema.name] = current
86
+ return [] unless previous
87
+ return [[:info, ' unchanged']] if previous == current
88
+
89
+ added = diff(current, previous).map { |name| "#{paint('+', :green)} #{name}" }
90
+ removed = diff(previous, current).map { |name| "#{paint('−', :red)} #{name}" }
91
+ [[:info, " #{limited(added + removed).join(' ')}"]]
92
+ end
93
+
94
+ # { "Type" => Set of its field names } for the types clients see: those of
95
+ # the printed schema, so none only Lighthouse's directives use.
96
+ def fingerprint(printed)
97
+ ::GraphQL.parse(printed).definitions.each_with_object({}) do |definition, types|
98
+ next unless definition.respond_to?(:name) && !definition.is_a?(::GraphQL::Language::Nodes::DirectiveDefinition)
99
+
100
+ types[definition.name] = (definition.respond_to?(:fields) ? definition.fields.map(&:name) : []).to_set
101
+ end
102
+ end
103
+
104
+ # Types in `from` but not `other`, then fields of the types in both.
105
+ def diff(from, other)
106
+ (from.keys - other.keys) + (from.keys & other.keys).flat_map { |type| (from[type] - other[type]).map { |field| "#{type}.#{field}" } }
107
+ end
108
+
109
+ def written(schema, output, printed)
110
+ return [] unless output
111
+
112
+ content = output[:format] == 'sdl' ? printed : Lighthouse::GraphQL::SchemaPrinter.print(schema, format: output[:format])
113
+ return [] unless Lighthouse::GraphQL::SchemaPrinter.write(output[:path], content)
114
+
115
+ [[:info, " wrote #{relative(output[:path])}"]]
116
+ end
117
+
118
+ # Manifest operations the schema no longer accepts, which shipped clients still send.
119
+ def stale_operations(schema)
120
+ return [] unless Lighthouse::Config.persisted_queries_manifest
121
+
122
+ invalid = invalid_operations(schema)
123
+ return [] if invalid.empty?
124
+
125
+ [[:warn, "#{paint('!', :yellow)} Persisted operations the schema no longer accepts: #{invalid.size}"],
126
+ *limited(invalid).map { |line| [:warn, " #{line}"] }]
127
+ rescue StandardError => e
128
+ [[:warn, "#{paint('!', :yellow)} The persisted query manifest can not be read: #{e.message}"]]
129
+ end
130
+
131
+ def invalid_operations(schema)
132
+ Lighthouse::GraphQL::PersistedQueries.manifest.filter_map do |hash, body|
133
+ errors = schema.validate(body)
134
+ "#{hash[0, 12]}…: #{errors.first.message}" if errors.any?
135
+ end
136
+ end
137
+
138
+ def limited(items)
139
+ items.size > LIST_LIMIT ? [*items.first(LIST_LIMIT), "and #{items.size - LIST_LIMIT} more"] : items
140
+ end
141
+
142
+ def relative(path)
143
+ root = ::Rails.root.to_s if defined?(::Rails) && ::Rails.respond_to?(:root) && ::Rails.root
144
+ root ? path.to_s.delete_prefix("#{root}/") : path.to_s
145
+ end
146
+
147
+ COLORS = { green: 32, red: 31, yellow: 33 }.freeze
148
+
149
+ # ANSI colours, as Rails' own log lines have, when the app colorizes logging.
150
+ def paint(text, color)
151
+ colorize? ? "\e[1;#{COLORS.fetch(color)}m#{text}\e[0m" : text
152
+ end
153
+
154
+ def colorize?
155
+ defined?(::Rails) && ::Rails.respond_to?(:application) && ::Rails.application&.config&.colorize_logging
156
+ end
157
+
158
+ def development? = defined?(::Rails) && ::Rails.respond_to?(:env) && ::Rails.env.development?
159
+
160
+ def default_logger = (::Rails.logger if defined?(::Rails) && ::Rails.respond_to?(:logger))
161
+ end
@@ -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
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.3
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