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.
- checksums.yaml +4 -4
- data/CHANGELOG.md +126 -1
- data/docs/authorization.md +33 -1
- data/docs/configuration.md +38 -0
- data/docs/directives.md +51 -4
- data/docs/filtering-and-ordering.md +52 -0
- data/docs/getting-started.md +63 -10
- data/docs/performance.md +9 -0
- data/docs/relay.md +6 -2
- data/docs/uploads.md +28 -2
- data/lib/lighthouse/ast_builder.rb +14 -5
- data/lib/lighthouse/config.rb +18 -2
- data/lib/lighthouse/controller.rb +6 -67
- data/lib/lighthouse/directive_resolvers/argument_transforms_resolver.rb +7 -1
- data/lib/lighthouse/directive_resolvers/association_resolvers.rb +5 -7
- data/lib/lighthouse/directive_resolvers/attachment_resolver.rb +139 -0
- data/lib/lighthouse/directive_resolvers/base.rb +26 -22
- data/lib/lighthouse/directive_resolvers/can_resolvers.rb +29 -5
- data/lib/lighthouse/directive_resolvers/model_mutation_resolver.rb +1 -8
- data/lib/lighthouse/directives/definitions.rb +2 -2
- data/lib/lighthouse/directives/registry.rb +1 -1
- data/lib/lighthouse/directives/soft_deletes_directive.rb +23 -6
- data/lib/lighthouse/document_ast.rb +6 -0
- data/lib/lighthouse/field_resolver_stack.rb +32 -0
- data/lib/lighthouse/global_id.rb +16 -5
- data/lib/lighthouse/graphql/version.rb +1 -1
- data/lib/lighthouse/operations.rb +111 -0
- data/lib/lighthouse/pagination.rb +21 -1
- data/lib/lighthouse/persisted_queries/manifest.rb +40 -0
- data/lib/lighthouse/persisted_queries.rb +9 -27
- data/lib/lighthouse/railtie.rb +8 -1
- data/lib/lighthouse/rb_lighthouse.rb +6 -0
- data/lib/lighthouse/relation_batch.rb +1 -1
- data/lib/lighthouse/schema_generator.rb +2 -0
- data/lib/lighthouse/schema_printer.rb +100 -0
- data/lib/lighthouse/schema_report.rb +161 -0
- data/lib/lighthouse/server_directives.rb +63 -0
- data/lib/lighthouse/tasks/lighthouse.rake +25 -6
- data/lib/lighthouse/upload.rb +2 -1
- data/lib/lighthouse/upload_store.rb +53 -2
- data/sig/lighthouse/controller.rbs +19 -8
- data/sig/lighthouse/directives.rbs +27 -0
- data/sig/lighthouse/graphql.rbs +3 -0
- data/sig/lighthouse.rbs +11 -2
- metadata +7 -1
data/lib/lighthouse/global_id.rb
CHANGED
|
@@ -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`,
|
|
15
|
-
#
|
|
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,
|
|
30
|
-
# object_from_id (schema_ids?)
|
|
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) ?
|
|
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)
|
|
@@ -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`
|
|
17
|
-
#
|
|
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
|
|
20
|
-
#
|
|
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
|
|
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
|
data/lib/lighthouse/railtie.rb
CHANGED
|
@@ -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
|
|
@@ -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
|