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
@@ -0,0 +1,139 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative 'base'
4
+
5
+ # @attachment — the URL of an ActiveStorage attachment of the parent: the read
6
+ # side of @upload, Lighthouse's (Laravel has no ActiveStorage).
7
+ #
8
+ # type User {
9
+ # avatarUrl: String @attachment # has_one_attached :avatar
10
+ # avatarThumbUrl: String @attachment(name: "avatar", variant: "thumb")
11
+ # photoUrls: [String!]! @attachment(url: PROXY) # has_many_attached :photos
12
+ # }
13
+ #
14
+ # Every parent's attachments and their blobs are loaded at once
15
+ # (`avatar_attachment: :blob`, what `User.with_attached_avatar` loads), through
16
+ # the Dataloader when the schema uses it. `name` defaults to the field's name
17
+ # without its Url / Urls suffix: avatarUrl reads `avatar`, photoUrls `photos`.
18
+ #
19
+ # `url` says how the URL serves the file: REDIRECT (Rails' redirect to the
20
+ # service, the default), PROXY (streamed through the app) or DIRECT (the
21
+ # service's own URL, signed for `expiresIn` on a private one). A REDIRECT or
22
+ # PROXY URL is absolute when the request's host is known (the controller in the
23
+ # context, else the routes' default_url_options), else a path. A variant is
24
+ # processed when its URL is first followed, except DIRECT, which processes it
25
+ # while resolving.
26
+ class Lighthouse::GraphQL::DirectiveResolvers::AttachmentDirectiveResolver < Lighthouse::GraphQL::DirectiveResolvers::BaseDirectiveResolver
27
+ TYPE_DEFINITIONS = {
28
+ 'AttachmentUrl' => <<~GRAPHQL.chomp
29
+ "How an @attachment URL serves the file."
30
+ enum AttachmentUrl {
31
+ "Rails' redirect to the storage service (rails_storage_redirect_url)."
32
+ REDIRECT
33
+ "Streamed through the app (rails_storage_proxy_url)."
34
+ PROXY
35
+ "The storage service's own URL, signed for expiresIn on a private service."
36
+ DIRECT
37
+ }
38
+ GRAPHQL
39
+ }.freeze
40
+
41
+ def self.directive_name = 'attachment'
42
+
43
+ def self.type_definitions = TYPE_DEFINITIONS
44
+
45
+ def self.definition
46
+ <<~GRAPHQL.chomp
47
+ """
48
+ The URL of an ActiveStorage attachment of the parent, or the URLs of a has_many_attached.
49
+ Every parent's attachments and blobs are loaded at once.
50
+ """
51
+ directive @attachment(
52
+ "The attachment's name. Defaults to the field's name without its Url / Urls suffix."
53
+ name: String
54
+ "A named variant of the attachment (`has_one_attached :avatar { |a| a.variant :thumb, ... }`)."
55
+ variant: String
56
+ "How the URL serves the file."
57
+ url: AttachmentUrl = REDIRECT
58
+ "How many seconds a DIRECT URL is valid. Defaults to ActiveStorage.service_urls_expire_in."
59
+ expiresIn: Int
60
+ ) on FIELD_DEFINITION
61
+ GRAPHQL
62
+ end
63
+
64
+ def define_resolver(target_type_class)
65
+ me = self
66
+ install(target_type_class, ->(obj, _args, ctx) { me.send(:resolve, obj, ctx) })
67
+ end
68
+
69
+ protected
70
+
71
+ def resolve(record, ctx)
72
+ return if record.nil?
73
+
74
+ reflection = reflection(record)
75
+ preload(record, reflection, ctx)
76
+ attached = record.public_send(attachment_name)
77
+ return attached.attachments.filter_map { |attachment| url(attachment, ctx) } if reflection.macro == :has_many_attached
78
+
79
+ url(attached.attachment, ctx) if attached.attached?
80
+ end
81
+
82
+ def attachment_name
83
+ @attachment_name ||= (directive_arg('name') || default_name).to_s
84
+ end
85
+
86
+ # avatarUrl -> avatar, photoUrls -> photos, avatar -> avatar.
87
+ def default_name
88
+ attribute = Lighthouse::Support::Naming.attribute(@field_def.name)
89
+ attribute.end_with?('_urls') ? attribute.delete_suffix('_urls').pluralize : attribute.delete_suffix('_url')
90
+ end
91
+
92
+ def reflection(record)
93
+ reflection = record.class.respond_to?(:reflect_on_attachment) && record.class.reflect_on_attachment(attachment_name)
94
+ return reflection if reflection
95
+
96
+ raise Lighthouse::DefinitionError,
97
+ "@attachment on #{@type_def.graphql_name}.#{@field_def.name}: #{record.class.name} has no attachment `#{attachment_name}`."
98
+ end
99
+
100
+ def preload(record, reflection, ctx)
101
+ dataloader = Lighthouse::Support::Batching.dataloader(ctx)
102
+ return unless dataloader
103
+
104
+ association = reflection.macro == :has_many_attached ? :"#{attachment_name}_attachments" : :"#{attachment_name}_attachment"
105
+ dataloader.with(Lighthouse::GraphQL::DataloaderSources::PreloadLoader, [{ association => :blob }], []).load(record)
106
+ end
107
+
108
+ def url(attachment, ctx)
109
+ variant = directive_arg('variant')
110
+ return if variant && !attachment.variable?
111
+
112
+ target = variant ? attachment.variant(variant.to_sym) : attachment
113
+ options = url_options(ctx)
114
+ case directive_arg('url')
115
+ when 'DIRECT' then direct_url(target, options)
116
+ when 'PROXY' then route(:rails_storage_proxy, target, options)
117
+ else route(:rails_storage_redirect, target, options)
118
+ end
119
+ end
120
+
121
+ def route(name, target, options)
122
+ helpers = ::Rails.application.routes.url_helpers
123
+ options[:host] ? helpers.public_send(:"#{name}_url", target, **options) : helpers.public_send(:"#{name}_path", target)
124
+ end
125
+
126
+ # The service signs the URL; the Disk service builds it from ActiveStorage::Current's host.
127
+ def direct_url(target, options)
128
+ target = target.processed if target.respond_to?(:processed)
129
+ expires_in = directive_arg('expiresIn')&.seconds || ::ActiveStorage.service_urls_expire_in
130
+ ::ActiveStorage::Current.set(url_options: options.slice(:host, :port, :protocol)) { target.url(expires_in: expires_in) }
131
+ end
132
+
133
+ # The request's, through the controller in the context, else the routes' defaults.
134
+ def url_options(ctx)
135
+ controller = ctx.respond_to?(:[]) ? ctx[:lighthouse_controller] : nil
136
+ options = controller.respond_to?(:url_options) ? controller.url_options : ::Rails.application.routes.default_url_options
137
+ options.to_h.symbolize_keys.slice(:host, :port, :protocol, :script_name)
138
+ end
139
+ end
@@ -49,14 +49,14 @@ module Lighthouse::GraphQL::DirectiveResolvers
49
49
  def self.type_definitions = TYPE_DEFINITIONS
50
50
 
51
51
  # The SDL of a @can* directive: `description`, the arguments they share, then the `extra` ones.
52
- def self.definition_with(description, extra = [])
52
+ def self.definition_with(description, extra = [], locations: 'FIELD_DEFINITION')
53
53
  <<~GRAPHQL.chomp
54
54
  """
55
55
  #{description}
56
56
  """
57
57
  directive @#{directive_name}(
58
58
  #{[*COMMON_ARGUMENTS, *extra].join("\n")}
59
- ) repeatable on FIELD_DEFINITION
59
+ ) repeatable on #{locations}
60
60
  GRAPHQL
61
61
  end
62
62
 
@@ -136,7 +136,7 @@ module Lighthouse::GraphQL::DirectiveResolvers
136
136
 
137
137
  def authorize_before(_obj, args, ctx)
138
138
  model = model_class
139
- ids = Lighthouse::Support::Arguments.dig(Lighthouse::Support::Arguments.plain(args), directive_arg('find')).flatten.uniq
139
+ ids = ids_to_find(Lighthouse::Support::Arguments.plain(args))
140
140
  records = scoped(model.where(model.primary_key => ids)).to_a
141
141
  if directive_arg('findOrFail') != false && records.size < ids.size
142
142
  missing = ids.map(&:to_s) - records.map { |r| r.public_send(model.primary_key).to_s }
@@ -145,21 +145,45 @@ module Lighthouse::GraphQL::DirectiveResolvers
145
145
 
146
146
  authorize_each!(ctx, records, args)
147
147
  end
148
+
149
+ # The ids at the `find:` path. Nothing there (a misspelt path, an argument
150
+ # the client left out) is an error, as in PHP Lighthouse, so the field never
151
+ # resolves with nothing checked. A `*` over an empty list finds no model to check.
152
+ def ids_to_find(args)
153
+ find = directive_arg('find').to_s
154
+ ids = Lighthouse::Support::Arguments.dig(args, find)
155
+ return ids.flatten.uniq unless ids.empty? && !empty_list_at?(args, find)
156
+
157
+ raise ::GraphQL::ExecutionError, "Got no key to find a model at the expected input path: #{find}."
158
+ end
159
+
160
+ def empty_list_at?(args, find)
161
+ return false unless find.include?('*')
162
+
163
+ lists = Lighthouse::Support::Arguments.dig(args, find.split('.*').first)
164
+ lists.any? && lists.all? { |list| list.respond_to?(:empty?) && list.empty? }
165
+ end
148
166
  end
149
167
 
150
168
  class CanModelDirectiveResolver < CanDirectiveResolver
151
169
  def self.directive_name = 'canModel'
152
170
 
153
171
  def self.definition
154
- definition_with(<<~TEXT.chomp, [MODEL_ARGUMENT])
172
+ definition_with(<<~TEXT.chomp, [MODEL_ARGUMENT], locations: 'FIELD_DEFINITION | ARGUMENT_DEFINITION | INPUT_FIELD_DEFINITION')
155
173
  Check a policy against the model class itself, before the field resolves,
156
- e.g. `create?` before a @create.
174
+ e.g. `create?` before a @create. On an argument or input field, only when
175
+ the client gives it a value: who may use it, e.g. `trashed`.
157
176
  TEXT
158
177
  end
159
178
 
160
179
  protected
161
180
 
181
+ # On an argument (FieldResolverStack passes its path as `argument:`), only
182
+ # when the client gave it a value.
162
183
  def authorize_before(_obj, args, ctx)
184
+ path = @opts[:argument]
185
+ return if path && Lighthouse::Support::Arguments.dig(Lighthouse::Support::Arguments.plain(args), path).empty?
186
+
163
187
  authorize!(ctx, model_class, args)
164
188
  end
165
189
  end
@@ -202,7 +202,7 @@ class Lighthouse::DirectiveRegistry
202
202
  CacheDirectiveResolver ClearCacheDirectiveResolver EventDirectiveResolver
203
203
  ValidatorDirectiveResolver ConvertEmptyStringsToNullDirectiveResolver
204
204
  SubscriptionDirectiveResolver BroadcastDirectiveResolver
205
- WithDirectiveResolver WithCountDirectiveResolver LazyLoadDirectiveResolver
205
+ WithDirectiveResolver WithCountDirectiveResolver LazyLoadDirectiveResolver AttachmentDirectiveResolver
206
206
  GlobalIdDirectiveResolver NamespacedDirectiveResolver ThrottleDirectiveResolver AsyncDirectiveResolver
207
207
  ].freeze
208
208
 
@@ -6,6 +6,12 @@
6
6
  #
7
7
  # tasks: [Task!]! @all @softDeletes -> tasks(trashed: Trashed @trashed): [Task!]! @all
8
8
  #
9
+ # `ability:` puts a @canModel on the argument, so only who the policy allows
10
+ # may use it (Lighthouse's, not PHP Lighthouse's):
11
+ #
12
+ # tasks: [Task!]! @all @softDeletes(ability: "view_trashed")
13
+ # -> tasks(trashed: Trashed @trashed @canModel(ability: "view_trashed")): [Task!]! @all
14
+ #
9
15
  # The `Trashed` enum is added once whenever a `@trashed` argument is in the
10
16
  # schema (generated here or written by hand), unless the app declares its own.
11
17
  class Lighthouse::GraphQL::Directives::SoftDeletesDirective
@@ -16,7 +22,10 @@ class Lighthouse::GraphQL::Directives::SoftDeletesDirective
16
22
  This manipulates the schema by adding the argument
17
23
  `trashed: Trashed @trashed` to the field.
18
24
  """
19
- directive @softDeletes on FIELD_DEFINITION
25
+ directive @softDeletes(
26
+ "The policy ability a user needs to pass `trashed` (a @canModel on it). Without it, anyone may."
27
+ ability: String
28
+ ) on FIELD_DEFINITION
20
29
  GRAPHQL
21
30
  }.freeze
22
31
 
@@ -98,19 +107,27 @@ class Lighthouse::GraphQL::Directives::SoftDeletesDirective
98
107
  end
99
108
 
100
109
  def soft_delete(field)
101
- if field.directives.any? { |directive| directive.name == 'softDeletes' }
110
+ directive = field.directives.find { |node| node.name == 'softDeletes' }
111
+ if directive
102
112
  @rewritten = true
103
- field = field.merge(arguments: with_trashed_argument(field.arguments),
104
- directives: field.directives.reject { |directive| directive.name == 'softDeletes' })
113
+ field = field.merge(arguments: with_trashed_argument(field.arguments, ability(directive)),
114
+ directives: field.directives.reject { |node| node.name == 'softDeletes' })
105
115
  end
106
116
  @trashed ||= field.arguments.any? { |argument| trashed?(argument) }
107
117
  field
108
118
  end
109
119
 
110
- def with_trashed_argument(arguments)
120
+ # The field's arguments with `trashed`, unless it has one of its own;
121
+ # behind @canModel(ability:) when `ability` is given.
122
+ def with_trashed_argument(arguments, ability)
111
123
  return arguments if arguments.any? { |argument| argument.name == 'trashed' }
112
124
 
113
- arguments + ::GraphQL::Language::Parser.parse(ARGUMENT).definitions.first.fields.first.arguments
125
+ sdl = ability ? ARGUMENT.sub('@trashed', "@trashed @canModel(ability: #{ability.to_json})") : ARGUMENT
126
+ arguments + ::GraphQL::Language::Parser.parse(sdl).definitions.first.fields.first.arguments
127
+ end
128
+
129
+ def ability(directive)
130
+ Lighthouse::Support::DirectiveArgs.literal(directive, 'ability')
114
131
  end
115
132
 
116
133
  def trashed?(node)
@@ -22,6 +22,7 @@ module Lighthouse::GraphQL::FieldResolverStack
22
22
  steps << own_step(type, field_def, root_kind, bases, type_class) unless resolving_directive?(directives)
23
23
  steps << validator_step(type, field_def, opts) if input_validation?(field_def, directives)
24
24
  steps.concat(argument_steps(type, field_def, directives, opts))
25
+ steps.concat(argument_authorization_steps(type, field_def, opts))
25
26
 
26
27
  steps.compact.each_with_index.sort_by { |(order, _), index| [order, index] }.each { |(_, step), _| step.call }
27
28
  end
@@ -110,6 +111,37 @@ module Lighthouse::GraphQL::FieldResolverStack
110
111
  steps
111
112
  end
112
113
 
114
+ # A @canModel on an argument or input field, at any depth: who may use it.
115
+ # Ordered with the field's @can* directives; it checks only when the client
116
+ # gave the argument a value (CanModelDirectiveResolver).
117
+ def argument_authorization_steps(type, field_def, opts)
118
+ resolver = Lighthouse::GraphQL::DirectiveResolvers::CanModelDirectiveResolver
119
+ order = Lighthouse::DirectiveRegistry.default.resolution_order(resolver.directive_name)
120
+ authorized_arguments(field_def.arguments).map do |path, dnode|
121
+ [order, -> { resolver.new(field_def, type, dnode, opts.merge(argument: path)).define_resolver(type) }]
122
+ end
123
+ end
124
+
125
+ # [dot path ("filter.trashed", "inputs.*.status"), @canModel node] for every
126
+ # argument and input field carrying @canModel; an input type is not walked
127
+ # twice on one path.
128
+ def authorized_arguments(arguments, prefix = nil, seen = Set.new)
129
+ arguments.each_value.flat_map do |argument|
130
+ path = [prefix, argument.graphql_name].compact.join('.')
131
+ own = (argument.ast_node&.directives || []).select { |d| d.name == 'canModel' }.map { |dnode| [path, dnode] }
132
+ own + authorized_input_fields(argument, path, seen)
133
+ end
134
+ end
135
+
136
+ # Those of the input type an argument takes; `*` steps into each of a list.
137
+ def authorized_input_fields(argument, path, seen)
138
+ type = argument.type.unwrap
139
+ return [] unless type.kind.input_object? && seen.exclude?(type.graphql_name)
140
+
141
+ list = (argument.type.non_null? ? argument.type.of_type : argument.type).list?
142
+ authorized_arguments(type.arguments, list ? "#{path}.*" : path, seen | [type.graphql_name])
143
+ end
144
+
113
145
  # Around whatever resolves the field, as @lazyLoad: the result is cut to the client's @limit.
114
146
  def limit_step(type, field_def, opts)
115
147
  [1, -> { Lighthouse::GraphQL::DirectiveResolvers::LimitResolver.new(field_def, type, nil, opts).define_resolver(type) }]
@@ -11,8 +11,10 @@ require 'base64'
11
11
  # A schema that implements graphql-ruby's Relay ids, `id_from_object` and
12
12
  # `object_from_id` (graphql-ruby's install writes them, on Rails' GlobalID),
13
13
  # has one kind of global id: @globalId encodes an object's own id with
14
- # `id_from_object`, and decodes with `object_from_id`, as graphql-ruby's
15
- # Query.node and Node's `id` do.
14
+ # `id_from_object`, as graphql-ruby's Node `id` does. It decodes one as PHP
15
+ # Lighthouse's GlobalId does, without reading the database: Rails' GlobalID
16
+ # names the model and the id. Only an id of another format is decoded
17
+ # through `object_from_id`, which loads the record.
16
18
  module Lighthouse::GraphQL::GlobalId
17
19
  module_function
18
20
 
@@ -26,11 +28,11 @@ module Lighthouse::GraphQL::GlobalId
26
28
  []
27
29
  end
28
30
 
29
- # [type, id] for a global id a client sent, through the schema's
30
- # object_from_id (schema_ids?) or Config.global_id; a
31
+ # [type, id] for a global id a client sent, from Rails' GlobalID or the
32
+ # schema's object_from_id (schema_ids?), else Config.global_id; a
31
33
  # GraphQL::ExecutionError when it is not one.
32
34
  def decode!(global_id, context = nil)
33
- type, id = schema_ids?(context&.schema) ? decode_object(global_id, context) : Lighthouse::Config.global_id.decode(global_id)
35
+ type, id = schema_ids?(context&.schema) ? decode_schema_id(global_id, context) : Lighthouse::Config.global_id.decode(global_id)
34
36
  return [type, id] if type.present? && !id.nil?
35
37
 
36
38
  raise ::GraphQL::ExecutionError, "#{global_id.inspect} is not a valid global id."
@@ -49,6 +51,15 @@ module Lighthouse::GraphQL::GlobalId
49
51
  schema.respond_to?(:object_from_id) && schema.method(:object_from_id).owner != ::GraphQL::Schema.singleton_class
50
52
  end
51
53
 
54
+ # A Rails GlobalID (`to_gid_param`, graphql-ruby's install's
55
+ # id_from_object) names its model and id, so the record needs no SELECT,
56
+ # and one a default scope hides (a soft-deleted record @restore looks for)
57
+ # decodes too. Any other id goes through object_from_id.
58
+ def decode_schema_id(global_id, context)
59
+ gid = defined?(::GlobalID) && global_id.is_a?(String) ? ::GlobalID.parse(global_id) : nil
60
+ gid ? [gid.model_name.demodulize, gid.model_id] : decode_object(global_id, context)
61
+ end
62
+
52
63
  # [type, id] of the object the schema's object_from_id finds.
53
64
  def decode_object(global_id, context)
54
65
  object = context.schema.object_from_id(global_id, context)
@@ -2,6 +2,6 @@
2
2
 
3
3
  module Lighthouse
4
4
  module GraphQL
5
- VERSION = '0.7.3'
5
+ VERSION = '0.8.0'
6
6
  end
7
7
  end
@@ -0,0 +1,111 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'active_support/concern'
4
+ require 'active_support/core_ext/class/attribute'
5
+ require 'json'
6
+
7
+ # Run a GraphQL operation from any controller action, with the context the
8
+ # endpoint gives it: to render a page with its data already loaded, say.
9
+ # Lighthouse::GraphQL::Controller includes it, and adds the `execute` action.
10
+ #
11
+ # class PagesController < ApplicationController
12
+ # include Lighthouse::GraphQL::Operations
13
+ #
14
+ # lighthouse_schema AppSchema
15
+ #
16
+ # def home
17
+ # @feed = lighthouse_execute('query Feed { posts(first: 10) { data { title } } }')
18
+ # return if performed? # a @throttle answered 429
19
+ # end
20
+ # end
21
+ #
22
+ # `lighthouse_execute` runs the operation as the endpoint does
23
+ # (PersistedQueries.execute: the operation events, persisted queries), with
24
+ # `lighthouse_context`: `graphql_context` and what @throttle reads. The request
25
+ # events (StartRequest, EndRequest) are the endpoint's, one per GraphQL
26
+ # request, as PHP Lighthouse's GraphQLController dispatches them: wrap an
27
+ # action in `lighthouse_request { ... }` to dispatch them around it.
28
+ module Lighthouse::GraphQL::Operations
29
+ extend ActiveSupport::Concern
30
+
31
+ included do
32
+ class_attribute :lighthouse_schema_source, instance_writer: false
33
+ end
34
+
35
+ class_methods do
36
+ # The schema the operations run on: a schema class, its name (a String,
37
+ # constantized per request so code reloading works) or a block (evaluated
38
+ # in the controller, per request).
39
+ def lighthouse_schema(schema = nil, &block)
40
+ self.lighthouse_schema_source = schema || block
41
+ end
42
+ end
43
+
44
+ private
45
+
46
+ # The result of `query` (a Hash, as the endpoint renders it), or nil when a
47
+ # @throttle `with:` method performed the response instead (`performed?`).
48
+ # `context` adds to lighthouse_context; `extensions` takes a persisted
49
+ # query's hash, as a client's request does (`query` nil).
50
+ def lighthouse_execute(query, variables: {}, operation_name: nil, extensions: nil, context: {})
51
+ Lighthouse::GraphQL::PersistedQueries.execute(
52
+ graphql_schema,
53
+ query: query, extensions: extensions, variables: graphql_variables(variables), operation_name: operation_name,
54
+ context: lighthouse_context.merge(context)
55
+ ).to_h
56
+ rescue Lighthouse::GraphQL::Controller::Performed
57
+ nil
58
+ end
59
+
60
+ # Dispatch StartRequest, run the block, dispatch EndRequest with the
61
+ # response. Only the outermost call dispatches, and stops the block where a
62
+ # @throttle `with:` method performed the response.
63
+ def lighthouse_request
64
+ return yield if @lighthouse_request_started
65
+
66
+ @lighthouse_request_started = true
67
+ Lighthouse::Events.dispatch(Lighthouse::Events::StartRequest.new(request))
68
+ result = begin
69
+ yield
70
+ rescue Lighthouse::GraphQL::Controller::Performed
71
+ nil
72
+ end
73
+ Lighthouse::Events.dispatch(Lighthouse::Events::EndRequest.new(response))
74
+ result
75
+ end
76
+
77
+ # The context of the operation: what @guard and the @can* directives read.
78
+ def graphql_context
79
+ respond_to?(:current_user, true) ? { current_user: current_user } : {}
80
+ end
81
+
82
+ # graphql_context, with what @throttle reads unless it sets its own: the
83
+ # client's IP (rate_limit's default by:) and the controller, whose cache_store,
84
+ # controller_path and methods rate_limit uses.
85
+ def lighthouse_context
86
+ { remote_ip: request.remote_ip, lighthouse_controller: self }.merge(graphql_context)
87
+ end
88
+
89
+ def graphql_schema
90
+ source = lighthouse_schema_source
91
+ case source
92
+ when nil then raise Lighthouse::DefinitionError, "#{self.class}: name the schema with `lighthouse_schema AppSchema`"
93
+ when String, Symbol then source.to_s.constantize
94
+ when Proc then instance_exec(&source)
95
+ else source
96
+ end
97
+ end
98
+
99
+ # Variables arrive as a JSON string (GET or form posts) or as parameters.
100
+ def graphql_variables(param)
101
+ case param
102
+ when String then param.present? ? JSON.parse(param) || {} : {}
103
+ when Hash then param
104
+ when nil then {}
105
+ else
106
+ raise ArgumentError, "Unexpected parameter: #{param}" unless param.respond_to?(:to_unsafe_h)
107
+
108
+ param.to_unsafe_h
109
+ end
110
+ end
111
+ end
@@ -200,7 +200,27 @@ module Lighthouse::GraphQL::Pagination
200
200
  return [] if limit.zero?
201
201
  return Array(relation)[offset, limit] || [] unless relation.respond_to?(:offset)
202
202
 
203
- relation.offset(offset).limit(limit).to_a
203
+ stable_order(relation).offset(offset).limit(limit).to_a
204
+ end
205
+
206
+ # The relation, its ORDER BY ending with the primary key. Pages are cut by
207
+ # position (an OFFSET, or a row number per parent), and rows the order ties
208
+ # (posts with the same created_at), or a relation with no order at all, may
209
+ # come back in another order on the next page's query: a row then shows on
210
+ # two pages, or on none. PHP Lighthouse leaves the order as it is. A grouped
211
+ # relation is left alone: its key may not be in the GROUP BY.
212
+ def stable_order(relation)
213
+ return relation unless relation.respond_to?(:klass) && relation.klass.primary_key && relation.group_values.empty?
214
+
215
+ table = relation.klass.arel_table
216
+ missing = Array(relation.klass.primary_key).reject { |key| ordered_by?(relation, table.name, key) }
217
+ missing.empty? ? relation : relation.order(*missing.map { |key| table[key].asc })
218
+ end
219
+
220
+ # Does the relation's ORDER BY name `table`.`key`, or `key` alone?
221
+ def ordered_by?(relation, table_name, key)
222
+ column = /(?:\A|[^\w."`\]])(?:["`\[]?#{Regexp.escape(table_name)}["`\]]?\.)?["`\[]?#{Regexp.escape(key)}["`\]]?(?:\s|,|\z)/i
223
+ relation.order_values.any? { |order| (order.respond_to?(:to_sql) ? order.to_sql : order.to_s).match?(column) }
204
224
  end
205
225
 
206
226
  def count(relation)
@@ -0,0 +1,40 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'json'
4
+
5
+ # Config.persisted_queries_manifest's operations by hash: from a JSON file
6
+ # (reloaded when it changes), a Hash, or a callable answering either. Each id
7
+ # is checked to be the SHA-256 of its body, once per file version or content.
8
+ module Lighthouse::GraphQL::PersistedQueries::Manifest
9
+ module_function
10
+
11
+ def operations
12
+ source = Lighthouse::Config.persisted_queries_manifest
13
+ source = source.call if source.respond_to?(:call)
14
+ return {} unless source
15
+ return cached(source) { load(source, 'persisted_queries_manifest') } if source.is_a?(Hash)
16
+
17
+ path = source.to_s
18
+ cached([path, File.mtime(path)]) { load(JSON.parse(File.read(path)), path) }
19
+ end
20
+
21
+ # The block's operations, checked once per `key`: a file's path and mtime, or a Hash's content.
22
+ def cached(key)
23
+ return @operations if @key == key
24
+
25
+ @operations = yield
26
+ @key = key.dup
27
+ @operations
28
+ end
29
+
30
+ def load(data, origin)
31
+ data = data.deep_stringify_keys
32
+ operations = data['operations'].is_a?(Array) ? data['operations'].to_h { |op| [op['id'], op['body']] } : data
33
+ operations.each do |hash, body|
34
+ next if Lighthouse::GraphQL::PersistedQueries.digest(body.to_s) == hash
35
+
36
+ raise Lighthouse::DefinitionError, "#{origin}: operation #{hash} is not the SHA-256 of its body."
37
+ end
38
+ operations
39
+ end
40
+ end
@@ -13,11 +13,14 @@ require 'json'
13
13
  # hash, which registers it. Requests shrink to a hash, and fit in a GET —
14
14
  # which CDNs can cache (see @cacheControl).
15
15
  #
16
- # Manifest: `Config.persisted_queries_manifest` points at a JSON file of
17
- # operations — Apollo's persisted query manifest
16
+ # Manifest: `Config.persisted_queries_manifest` names the operations your
17
+ # client build generated — Apollo's persisted query manifest
18
18
  # (`{ "operations": [{ "id": sha256, "body": query }] }`) or a plain
19
- # `{ sha256 => query }` object — generated by your client build. Its
20
- # operations are served from memory, never evicted. With
19
+ # `{ sha256 => query }` object (graphql-codegen's persisted documents): a
20
+ # JSON file, reloaded when it changes; a Hash of them; or a callable
21
+ # answering either, called for every persisted query (a Hash it answers
22
+ # again is not checked again). Its operations are served from memory, never
23
+ # evicted. With
21
24
  # `persisted_queries_only`, nothing else runs: an allowlist ("trusted
22
25
  # documents"), so arbitrary queries cannot reach the API.
23
26
  #
@@ -107,29 +110,8 @@ module Lighthouse::GraphQL::PersistedQueries
107
110
  manifest[hash] || (!only? && store.read(key(hash))) || raise(Error.new(*NOT_FOUND))
108
111
  end
109
112
 
110
- # The manifest's operations by hash, reloaded when the file changes.
111
- def manifest
112
- path = Lighthouse::Config.persisted_queries_manifest
113
- return {} unless path
114
-
115
- mtime = File.mtime(path.to_s)
116
- return @manifest if @manifest_source == [path.to_s, mtime]
117
-
118
- @manifest = load_manifest(path.to_s)
119
- @manifest_source = [path.to_s, mtime]
120
- @manifest
121
- end
122
-
123
- def load_manifest(path)
124
- data = JSON.parse(File.read(path))
125
- operations = data.is_a?(Hash) && data['operations'].is_a?(Array) ? data['operations'].to_h { |op| [op['id'], op['body']] } : data
126
- operations.each do |hash, body|
127
- next if digest(body.to_s) == hash
128
-
129
- raise Lighthouse::DefinitionError, "#{path}: operation #{hash} is not the SHA-256 of its body."
130
- end
131
- operations
132
- end
113
+ # The manifest's operations by hash (Manifest).
114
+ def manifest = Lighthouse::GraphQL::PersistedQueries::Manifest.operations
133
115
 
134
116
  def store
135
117
  Lighthouse::Config.persisted_queries_store
@@ -3,7 +3,9 @@
3
3
  # Hooks Lighthouse into a Rails host: exposes the `lighthouse:*` rake tasks,
4
4
  # with `config.watch_sdl` reloads the app when a .graphql file changes, and
5
5
  # with `config.ide_helper` (on in development when the app has a
6
- # graphql.config.yml) rewrites the IDE helper files on boot and every reload.
6
+ # graphql.config.yml) rewrites the IDE helper files on boot and every reload,
7
+ # and in development logs the schema's build (`config.schema_log`) and keeps
8
+ # `config.schema_output`'s file up to date (SchemaReport).
7
9
  # Generators (`rails g lighthouse:install`) are found through lib/generators.
8
10
  class Lighthouse::Railtie < Rails::Railtie
9
11
  rake_tasks do
@@ -20,6 +22,11 @@ class Lighthouse::Railtie < Rails::Railtie
20
22
  app.reloader.to_prepare { Lighthouse::IdeHelper.refresh(output_dir: app.root) }
21
23
  end
22
24
 
25
+ # Development's report on the schema (config.schema_log), and config.schema_output's file.
26
+ initializer 'lighthouse.schema_report', after: :load_config_initializers do |app|
27
+ app.reloader.to_prepare { Lighthouse::GraphQL::SchemaReport.refresh }
28
+ end
29
+
23
30
  # Rails' reloader then treats a .graphql edit like a Ruby one: the app's
24
31
  # constants — the schema among them — are reloaded on the next request.
25
32
  # Every .graphql under the entrypoint's folder is watched, imported or not.
@@ -52,10 +52,15 @@ require_relative 'namespaces'
52
52
  resolver_bases
53
53
  root_types
54
54
  ast_builder
55
+ server_directives
56
+ schema_printer
57
+ schema_report
55
58
  schema_generator
56
59
  schema_cache
57
60
  persisted_queries
58
61
  persisted_queries/batch
62
+ persisted_queries/manifest
63
+ operations
59
64
  controller
60
65
  schema_factory
61
66
  schema_implementation
@@ -118,6 +123,7 @@ require_relative 'namespaces'
118
123
  directive_resolvers/event_resolver
119
124
  directive_resolvers/convert_empty_strings_resolver
120
125
  directive_resolvers/with_resolver
126
+ directive_resolvers/attachment_resolver
121
127
  directive_resolvers/with_count_resolver
122
128
  directive_resolvers/lazy_load_resolver
123
129
  directive_resolvers/limit_resolver