repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/directive_checks.rb | lib/graphql/execution/directive_checks.rb | # frozen_string_literal: true
module GraphQL
module Execution
# Boolean checks for how an AST node's directives should
# influence its execution
# @api private
module DirectiveChecks
SKIP = "skip"
INCLUDE = "include"
module_function
# @return [Boolean] Should this node be included in the query?
def include?(directive_ast_nodes, query)
directive_ast_nodes.each do |directive_ast_node|
name = directive_ast_node.name
directive_defn = query.schema.directives[name]
case name
when SKIP
args = query.arguments_for(directive_ast_node, directive_defn)
if args[:if] == true
return false
end
when INCLUDE
args = query.arguments_for(directive_ast_node, directive_defn)
if args[:if] == false
return false
end
else
# Undefined directive, or one we don't care about
end
end
true
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/lazy.rb | lib/graphql/execution/lazy.rb | # frozen_string_literal: true
require "graphql/execution/lazy/lazy_method_map"
module GraphQL
module Execution
# This wraps a value which is available, but not yet calculated, like a promise or future.
#
# Calling `#value` will trigger calculation & return the "lazy" value.
#
# This is an itty-bitty promise-like object, with key differences:
# - It has only two states, not-resolved and resolved
# - It has no error-catching functionality
# @api private
class Lazy
attr_reader :field
# Create a {Lazy} which will get its inner value by calling the block
# @param field [GraphQL::Schema::Field]
# @param get_value_func [Proc] a block to get the inner value (later)
def initialize(field: nil, &get_value_func)
@get_value_func = get_value_func
@resolved = false
@field = field
end
# @return [Object] The wrapped value, calling the lazy block if necessary
def value
if !@resolved
@resolved = true
v = @get_value_func.call
if v.is_a?(Lazy)
v = v.value
end
@value = v
end
# `SKIP` was made into a subclass of `GraphQL::Error` to improve runtime performance
# (fewer clauses in a hot `case` block), but now it requires special handling here.
# I think it's still worth it for the performance win, but if the number of special
# cases grows, then maybe it's worth rethinking somehow.
if @value.is_a?(StandardError) && @value != GraphQL::Execution::SKIP
raise @value
else
@value
end
end
# @return [Lazy] A {Lazy} whose value depends on another {Lazy}, plus any transformations in `block`
def then
self.class.new {
yield(value)
}
end
# @param lazies [Array<Object>] Maybe-lazy objects
# @return [Lazy] A lazy which will sync all of `lazies`
def self.all(lazies)
self.new {
lazies.map { |l| l.is_a?(Lazy) ? l.value : l }
}
end
# This can be used for fields which _had no_ lazy results
# @api private
NullResult = Lazy.new(){}
NullResult.value
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/multiplex.rb | lib/graphql/execution/multiplex.rb | # frozen_string_literal: true
module GraphQL
module Execution
# Execute multiple queries under the same multiplex "umbrella".
# They can share a batching context and reduce redundant database hits.
#
# The flow is:
#
# - Multiplex instrumentation setup
# - Query instrumentation setup
# - Analyze the multiplex + each query
# - Begin each query
# - Resolve lazy values, breadth-first across all queries
# - Finish each query (eg, get errors)
# - Query instrumentation teardown
# - Multiplex instrumentation teardown
#
# If one query raises an application error, all queries will be in undefined states.
#
# Validation errors and {GraphQL::ExecutionError}s are handled in isolation:
# one of these errors in one query will not affect the other queries.
#
# @see {Schema#multiplex} for public API
# @api private
class Multiplex
include Tracing::Traceable
attr_reader :context, :queries, :schema, :max_complexity, :dataloader, :current_trace
def initialize(schema:, queries:, context:, max_complexity:)
@schema = schema
@queries = queries
@queries.each { |q| q.multiplex = self }
@context = context
@dataloader = @context[:dataloader] ||= @schema.dataloader_class.new
@tracers = schema.tracers + (context[:tracers] || [])
@max_complexity = max_complexity
@current_trace = context[:trace] ||= schema.new_trace(multiplex: self)
@logger = nil
end
def logger
@logger ||= @schema.logger_for(context)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter.rb | lib/graphql/execution/interpreter.rb | # frozen_string_literal: true
require "fiber"
require "graphql/execution/interpreter/argument_value"
require "graphql/execution/interpreter/arguments"
require "graphql/execution/interpreter/arguments_cache"
require "graphql/execution/interpreter/execution_errors"
require "graphql/execution/interpreter/runtime"
require "graphql/execution/interpreter/resolve"
require "graphql/execution/interpreter/handles_raw_value"
module GraphQL
module Execution
class Interpreter
class << self
# Used internally to signal that the query shouldn't be executed
# @api private
NO_OPERATION = GraphQL::EmptyObjects::EMPTY_HASH
# @param schema [GraphQL::Schema]
# @param queries [Array<GraphQL::Query, Hash>]
# @param context [Hash]
# @param max_complexity [Integer, nil]
# @return [Array<GraphQL::Query::Result>] One result per query
def run_all(schema, query_options, context: {}, max_complexity: schema.max_complexity)
queries = query_options.map do |opts|
query = case opts
when Hash
schema.query_class.new(schema, nil, **opts)
when GraphQL::Query, GraphQL::Query::Partial
opts
else
raise "Expected Hash or GraphQL::Query, not #{opts.class} (#{opts.inspect})"
end
query
end
return GraphQL::EmptyObjects::EMPTY_ARRAY if queries.empty?
multiplex = Execution::Multiplex.new(schema: schema, queries: queries, context: context, max_complexity: max_complexity)
trace = multiplex.current_trace
Fiber[:__graphql_current_multiplex] = multiplex
trace.execute_multiplex(multiplex: multiplex) do
schema = multiplex.schema
queries = multiplex.queries
multiplex_analyzers = schema.multiplex_analyzers
if multiplex.max_complexity
multiplex_analyzers += [GraphQL::Analysis::MaxQueryComplexity]
end
trace.begin_analyze_multiplex(multiplex, multiplex_analyzers)
schema.analysis_engine.analyze_multiplex(multiplex, multiplex_analyzers)
trace.end_analyze_multiplex(multiplex, multiplex_analyzers)
begin
# Since this is basically the batching context,
# share it for a whole multiplex
multiplex.context[:interpreter_instance] ||= multiplex.schema.query_execution_strategy(deprecation_warning: false).new
# Do as much eager evaluation of the query as possible
results = []
queries.each_with_index do |query, idx|
if query.subscription? && !query.subscription_update?
subs_namespace = query.context.namespace(:subscriptions)
subs_namespace[:events] = []
subs_namespace[:subscriptions] = {}
end
multiplex.dataloader.append_job {
operation = query.selected_operation
result = if operation.nil? || !query.valid? || !query.context.errors.empty?
NO_OPERATION
else
begin
# Although queries in a multiplex _share_ an Interpreter instance,
# they also have another item of state, which is private to that query
# in particular, assign it here:
runtime = Runtime.new(query: query)
query.context.namespace(:interpreter_runtime)[:runtime] = runtime
query.current_trace.execute_query(query: query) do
runtime.run_eager
end
rescue GraphQL::ExecutionError => err
query.context.errors << err
end
end
results[idx] = result
}
end
multiplex.dataloader.run(trace_query_lazy: multiplex)
# Then, find all errors and assign the result to the query object
results.each_with_index do |data_result, idx|
query = queries[idx]
if (events = query.context.namespace(:subscriptions)[:events]) && !events.empty?
schema.subscriptions.write_subscription(query, events)
end
# Assign the result so that it can be accessed in instrumentation
query.result_values = if data_result.equal?(NO_OPERATION)
if !query.valid? || !query.context.errors.empty?
# A bit weird, but `Query#static_errors` _includes_ `query.context.errors`
{ "errors" => query.static_errors.map(&:to_h) }
else
data_result
end
else
result = {}
if !query.context.errors.empty?
error_result = query.context.errors.map(&:to_h)
result["errors"] = error_result
end
result["data"] = query.context.namespace(:interpreter_runtime)[:runtime].final_result
result
end
if query.context.namespace?(:__query_result_extensions__)
query.result_values["extensions"] = query.context.namespace(:__query_result_extensions__)
end
# Get the Query::Result, not the Hash
results[idx] = query.result
end
results
rescue Exception
# TODO rescue at a higher level so it will catch errors in analysis, too
# Assign values here so that the query's `@executed` becomes true
queries.map { |q| q.result_values ||= {} }
raise
ensure
Fiber[:__graphql_current_multiplex] = nil
queries.map { |query|
runtime = query.context.namespace(:interpreter_runtime)[:runtime]
if runtime
runtime.delete_all_interpreter_context
end
}
end
end
end
end
class ListResultFailedError < GraphQL::Error
def initialize(value:, path:, field:)
message = "Failed to build a GraphQL list result for field `#{field.path}` at path `#{path.join(".")}`.\n".dup
message << "Expected `#{value.inspect}` (#{value.class}) to implement `.each` to satisfy the GraphQL return type `#{field.type.to_type_signature}`.\n"
if field.connection?
message << "\nThis field was treated as a Relay-style connection; add `connection: false` to the `field(...)` to disable this behavior."
end
super(message)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/lazy/lazy_method_map.rb | lib/graphql/execution/lazy/lazy_method_map.rb | # frozen_string_literal: true
require 'thread'
begin
require 'concurrent'
rescue LoadError
# no problem, we'll fallback to our own map
end
module GraphQL
module Execution
class Lazy
# {GraphQL::Schema} uses this to match returned values to lazy resolution methods.
# Methods may be registered for classes, they apply to its subclasses also.
# The result of this lookup is cached for future resolutions.
# Instances of this class are thread-safe.
# @api private
# @see {Schema#lazy?} looks up values from this map
class LazyMethodMap
def initialize(use_concurrent: defined?(Concurrent::Map))
@storage = use_concurrent ? Concurrent::Map.new : ConcurrentishMap.new
end
def initialize_copy(other)
@storage = other.storage.dup
end
# @param lazy_class [Class] A class which represents a lazy value (subclasses may also be used)
# @param lazy_value_method [Symbol] The method to call on this class to get its value
def set(lazy_class, lazy_value_method)
@storage[lazy_class] = lazy_value_method
end
# @param value [Object] an object which may have a `lazy_value_method` registered for its class or superclasses
# @return [Symbol, nil] The `lazy_value_method` for this object, or nil
def get(value)
@storage.compute_if_absent(value.class) { find_superclass_method(value.class) }
end
def each
@storage.each_pair { |k, v| yield(k, v) }
end
protected
attr_reader :storage
private
def find_superclass_method(value_class)
@storage.each_pair { |lazy_class, lazy_value_method|
return lazy_value_method if value_class < lazy_class
}
nil
end
# Mock the Concurrent::Map API
class ConcurrentishMap
extend Forwardable
# Technically this should be under the mutex too,
# but I know it's only used when the lock is already acquired.
def_delegators :@storage, :each_pair, :size
def initialize
@semaphore = Mutex.new
# Access to this hash must always be managed by the mutex
# since it may be modified at runtime
@storage = {}
end
def []=(key, value)
@semaphore.synchronize {
@storage[key] = value
}
end
def compute_if_absent(key)
@semaphore.synchronize {
@storage.fetch(key) { @storage[key] = yield }
}
end
def initialize_copy(other)
@semaphore = Mutex.new
@storage = other.copy_storage
end
protected
def copy_storage
@semaphore.synchronize {
@storage.dup
}
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/arguments_cache.rb | lib/graphql/execution/interpreter/arguments_cache.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
class ArgumentsCache
def initialize(query)
@query = query
@dataloader = query.context.dataloader
@storage = Hash.new do |h, argument_owner|
h[argument_owner] = if argument_owner.arguments_statically_coercible?
shared_values_cache = {}
Hash.new do |h2, ignored_parent_object|
h2[ignored_parent_object] = shared_values_cache
end.compare_by_identity
else
Hash.new do |h2, parent_object|
h2[parent_object] = {}.compare_by_identity
end.compare_by_identity
end
end.compare_by_identity
end
def fetch(ast_node, argument_owner, parent_object)
# This runs eagerly if no block is given
@storage[argument_owner][parent_object][ast_node] ||= begin
args_hash = self.class.prepare_args_hash(@query, ast_node)
kwarg_arguments = argument_owner.coerce_arguments(parent_object, args_hash, @query.context)
@query.after_lazy(kwarg_arguments) do |resolved_args|
@storage[argument_owner][parent_object][ast_node] = resolved_args
end
end
end
# @yield [Interpreter::Arguments, Lazy<Interpreter::Arguments>] The finally-loaded arguments
def dataload_for(ast_node, argument_owner, parent_object, &block)
# First, normalize all AST or Ruby values to a plain Ruby hash
arg_storage = @storage[argument_owner][parent_object]
if (args = arg_storage[ast_node])
yield(args)
else
args_hash = self.class.prepare_args_hash(@query, ast_node)
argument_owner.coerce_arguments(parent_object, args_hash, @query.context) do |resolved_args|
arg_storage[ast_node] = resolved_args
yield(resolved_args)
end
end
nil
end
private
NO_ARGUMENTS = GraphQL::EmptyObjects::EMPTY_HASH
NO_VALUE_GIVEN = NOT_CONFIGURED
def self.prepare_args_hash(query, ast_arg_or_hash_or_value)
case ast_arg_or_hash_or_value
when Hash
if ast_arg_or_hash_or_value.empty?
return NO_ARGUMENTS
end
args_hash = {}
ast_arg_or_hash_or_value.each do |k, v|
args_hash[k] = prepare_args_hash(query, v)
end
args_hash
when Array
ast_arg_or_hash_or_value.map { |v| prepare_args_hash(query, v) }
when GraphQL::Language::Nodes::Field, GraphQL::Language::Nodes::InputObject, GraphQL::Language::Nodes::Directive
if ast_arg_or_hash_or_value.arguments.empty? # rubocop:disable Development/ContextIsPassedCop -- AST-related
return NO_ARGUMENTS
end
args_hash = {}
ast_arg_or_hash_or_value.arguments.each do |arg| # rubocop:disable Development/ContextIsPassedCop -- AST-related
v = prepare_args_hash(query, arg.value)
if v != NO_VALUE_GIVEN
args_hash[arg.name] = v
end
end
args_hash
when GraphQL::Language::Nodes::VariableIdentifier
if query.variables.key?(ast_arg_or_hash_or_value.name)
variable_value = query.variables[ast_arg_or_hash_or_value.name]
prepare_args_hash(query, variable_value)
else
NO_VALUE_GIVEN
end
when GraphQL::Language::Nodes::Enum
ast_arg_or_hash_or_value.name
when GraphQL::Language::Nodes::NullValue
nil
else
ast_arg_or_hash_or_value
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/resolve.rb | lib/graphql/execution/interpreter/resolve.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
module Resolve
# Continue field results in `results` until there's nothing else to continue.
# @return [void]
# @deprecated Call `dataloader.run` instead
def self.resolve_all(results, dataloader)
warn "#{self}.#{__method__} is deprecated; Use `dataloader.run` instead.#{caller(1, 5).map { |l| "\n #{l}"}.join}"
dataloader.append_job { resolve(results, dataloader) }
nil
end
# @deprecated Call `dataloader.run` instead
def self.resolve_each_depth(lazies_at_depth, dataloader)
warn "#{self}.#{__method__} is deprecated; Use `dataloader.run` instead.#{caller(1, 5).map { |l| "\n #{l}"}.join}"
smallest_depth = nil
lazies_at_depth.each_key do |depth_key|
smallest_depth ||= depth_key
if depth_key < smallest_depth
smallest_depth = depth_key
end
end
if smallest_depth
lazies = lazies_at_depth.delete(smallest_depth)
if !lazies.empty?
lazies.each do |l|
dataloader.append_job { l.value }
end
# Run lazies _and_ dataloader, see if more are enqueued
dataloader.run
resolve_each_depth(lazies_at_depth, dataloader)
end
end
nil
end
# @deprecated Call `dataloader.run` instead
def self.resolve(results, dataloader)
warn "#{self}.#{__method__} is deprecated; Use `dataloader.run` instead.#{caller(1, 5).map { |l| "\n #{l}"}.join}"
# There might be pending jobs here that _will_ write lazies
# into the result hash. We should run them out, so we
# can be sure that all lazies will be present in the result hashes.
# A better implementation would somehow interleave (or unify)
# these approaches.
dataloader.run
next_results = []
while !results.empty?
result_value = results.shift
if result_value.is_a?(Runtime::GraphQLResultHash) || result_value.is_a?(Hash)
results.concat(result_value.values)
next
elsif result_value.is_a?(Runtime::GraphQLResultArray)
results.concat(result_value.values)
next
elsif result_value.is_a?(Array)
results.concat(result_value)
next
elsif result_value.is_a?(Lazy)
loaded_value = result_value.value
if loaded_value.is_a?(Lazy)
# Since this field returned another lazy,
# add it to the same queue
results << loaded_value
elsif loaded_value.is_a?(Runtime::GraphQLResultHash) || loaded_value.is_a?(Runtime::GraphQLResultArray) ||
loaded_value.is_a?(Hash) || loaded_value.is_a?(Array)
# Add these values in wholesale --
# they might be modified by later work in the dataloader.
next_results << loaded_value
end
end
end
if !next_results.empty?
# Any pending data loader jobs may populate the
# resutl arrays or result hashes accumulated in
# `next_results``. Run those **to completion**
# before continuing to resolve `next_results`.
# (Just `.append_job` doesn't work if any pending
# jobs require multiple passes.)
dataloader.run
dataloader.append_job { resolve(next_results, dataloader) }
end
nil
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/arguments.rb | lib/graphql/execution/interpreter/arguments.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
# A wrapper for argument hashes in GraphQL queries.
#
# This object is immutable so that the runtime code can be sure that
# modifications don't leak from one use to another
#
# @see GraphQL::Query#arguments_for to get access to these objects.
class Arguments
extend Forwardable
include GraphQL::Dig
# The Ruby-style arguments hash, ready for a resolver.
# This hash is the one used at runtime.
#
# @return [Hash<Symbol, Object>]
attr_reader :keyword_arguments
# @param argument_values [nil, Hash{Symbol => ArgumentValue}]
# @param keyword_arguments [nil, Hash{Symbol => Object}]
def initialize(keyword_arguments: nil, argument_values:)
@empty = argument_values.nil? || argument_values.empty?
# This is only present when `extras` have been merged in:
if keyword_arguments
# This is a little crazy. We expect the `:argument_details` extra to _include extras_,
# but the object isn't created until _after_ extras are put together.
# So, we have to use a special flag here to say, "at the last minute, add yourself to the keyword args."
#
# Otherwise:
# - We can't access the final Arguments instance _while_ we're preparing extras
# - After we _can_ access it, it's frozen, so we can't add anything.
#
# So, this flag gives us a chance to sneak it in before freezing, _and_ while we have access
# to the new Arguments instance itself.
if keyword_arguments[:argument_details] == :__arguments_add_self
keyword_arguments[:argument_details] = self
end
@keyword_arguments = keyword_arguments.freeze
elsif !@empty
@keyword_arguments = {}
argument_values.each do |name, arg_val|
@keyword_arguments[name] = arg_val.value
end
@keyword_arguments.freeze
else
@keyword_arguments = NO_ARGS
end
@argument_values = argument_values ? argument_values.freeze : NO_ARGS
freeze
end
# @return [Hash{Symbol => ArgumentValue}]
attr_reader :argument_values
def empty?
@empty
end
def_delegators :keyword_arguments, :key?, :[], :fetch, :keys, :each, :values, :size, :to_h
def_delegators :argument_values, :each_value
def inspect
"#<#{self.class} @keyword_arguments=#{keyword_arguments.inspect}>"
end
# Create a new arguments instance which includes these extras.
#
# This is called by the runtime to implement field `extras: [...]`
#
# @param extra_args [Hash<Symbol => Object>]
# @return [Interpreter::Arguments]
# @api private
def merge_extras(extra_args)
self.class.new(
argument_values: argument_values,
keyword_arguments: keyword_arguments.merge(extra_args)
)
end
NO_ARGS = GraphQL::EmptyObjects::EMPTY_HASH
EMPTY = self.new(argument_values: nil, keyword_arguments: NO_ARGS).freeze
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/argument_value.rb | lib/graphql/execution/interpreter/argument_value.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
# A container for metadata regarding arguments present in a GraphQL query.
# @see Interpreter::Arguments#argument_values for a hash of these objects.
class ArgumentValue
def initialize(definition:, value:, original_value:, default_used:)
@definition = definition
@value = value
@original_value = original_value
@default_used = default_used
end
# @return [Object] The Ruby-ready value for this Argument
attr_reader :value
# @return [Object] The value of this argument _before_ `prepare` is applied.
attr_reader :original_value
# @return [GraphQL::Schema::Argument] The definition instance for this argument
attr_reader :definition
# @return [Boolean] `true` if the schema-defined `default_value:` was applied in this case. (No client-provided value was present.)
def default_used?
@default_used
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/handles_raw_value.rb | lib/graphql/execution/interpreter/handles_raw_value.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
# Wrapper for raw values
class RawValue
def initialize(obj = nil)
@object = obj
end
def resolve
@object
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/runtime.rb | lib/graphql/execution/interpreter/runtime.rb | # frozen_string_literal: true
require "graphql/execution/interpreter/runtime/graphql_result"
module GraphQL
module Execution
class Interpreter
# I think it would be even better if we could somehow make
# `continue_field` not recursive. "Trampolining" it somehow.
#
# @api private
class Runtime
class CurrentState
def initialize
@current_field = nil
@current_arguments = nil
@current_result_name = nil
@current_result = nil
@was_authorized_by_scope_items = nil
end
def current_object
@current_result.graphql_application_value
end
attr_accessor :current_result, :current_result_name,
:current_arguments, :current_field, :was_authorized_by_scope_items
end
# @return [GraphQL::Query]
attr_reader :query
# @return [Class<GraphQL::Schema>]
attr_reader :schema
# @return [GraphQL::Query::Context]
attr_reader :context
def initialize(query:)
@query = query
@current_trace = query.current_trace
@dataloader = query.multiplex.dataloader
@schema = query.schema
@context = query.context
@response = nil
# Identify runtime directives by checking which of this schema's directives have overridden `def self.resolve`
@runtime_directive_names = []
noop_resolve_owner = GraphQL::Schema::Directive.singleton_class
@schema_directives = schema.directives
@schema_directives.each do |name, dir_defn|
if dir_defn.method(:resolve).owner != noop_resolve_owner
@runtime_directive_names << name
end
end
# { Class => Boolean }
@lazy_cache = {}.compare_by_identity
end
def final_result
@response.respond_to?(:graphql_result_data) ? @response.graphql_result_data : @response
end
def inspect
"#<#{self.class.name} response=#{@response.inspect}>"
end
# @return [void]
def run_eager
root_type = query.root_type
case query
when GraphQL::Query
ast_node = query.selected_operation
selections = ast_node.selections
object = query.root_value
is_eager = ast_node.operation_type == "mutation"
base_path = nil
when GraphQL::Query::Partial
ast_node = query.ast_nodes.first
selections = query.ast_nodes.map(&:selections).inject(&:+)
object = query.object
is_eager = false
base_path = query.path
else
raise ArgumentError, "Unexpected Runnable, can't execute: #{query.class} (#{query.inspect})"
end
object = schema.sync_lazy(object) # TODO test query partial with lazy root object
runtime_state = get_current_runtime_state
case root_type.kind.name
when "OBJECT"
object_proxy = root_type.wrap(object, context)
object_proxy = schema.sync_lazy(object_proxy)
if object_proxy.nil?
@response = nil
else
@response = GraphQLResultHash.new(nil, root_type, object_proxy, nil, false, selections, is_eager, ast_node, nil, nil)
@response.base_path = base_path
runtime_state.current_result = @response
call_method_on_directives(:resolve, object, ast_node.directives) do
each_gathered_selections(@response) do |selections, is_selection_array, ordered_result_keys|
@response.ordered_result_keys ||= ordered_result_keys
if is_selection_array
selection_response = GraphQLResultHash.new(nil, root_type, object_proxy, nil, false, selections, is_eager, ast_node, nil, nil)
selection_response.ordered_result_keys = ordered_result_keys
final_response = @response
else
selection_response = @response
final_response = nil
end
@dataloader.append_job {
evaluate_selections(
selections,
selection_response,
final_response,
nil,
)
}
end
end
end
when "LIST"
inner_type = root_type.unwrap
case inner_type.kind.name
when "SCALAR", "ENUM"
result_name = ast_node.alias || ast_node.name
field_defn = query.field_definition
owner_type = field_defn.owner
selection_result = GraphQLResultHash.new(nil, owner_type, nil, nil, false, EmptyObjects::EMPTY_ARRAY, false, ast_node, nil, nil)
selection_result.base_path = base_path
selection_result.ordered_result_keys = [result_name]
runtime_state = get_current_runtime_state
runtime_state.current_result = selection_result
runtime_state.current_result_name = result_name
continue_value = continue_value(object, field_defn, false, ast_node, result_name, selection_result)
if HALT != continue_value
continue_field(continue_value, owner_type, field_defn, root_type, ast_node, nil, false, nil, nil, result_name, selection_result, false, runtime_state) # rubocop:disable Metrics/ParameterLists
end
@response = selection_result[result_name]
else
@response = GraphQLResultArray.new(nil, root_type, nil, nil, false, selections, false, ast_node, nil, nil)
@response.base_path = base_path
idx = nil
object.each do |inner_value|
idx ||= 0
this_idx = idx
idx += 1
@dataloader.append_job do
runtime_state.current_result_name = this_idx
runtime_state.current_result = @response
continue_field(
inner_value, root_type, nil, inner_type, nil, @response.graphql_selections, false, object_proxy,
nil, this_idx, @response, false, runtime_state
)
end
end
end
when "SCALAR", "ENUM"
result_name = ast_node.alias || ast_node.name
field_defn = query.field_definition
owner_type = field_defn.owner
selection_result = GraphQLResultHash.new(nil, owner_type, nil, nil, false, EmptyObjects::EMPTY_ARRAY, false, ast_node, nil, nil)
selection_result.ordered_result_keys = [result_name]
selection_result.base_path = base_path
runtime_state = get_current_runtime_state
runtime_state.current_result = selection_result
runtime_state.current_result_name = result_name
continue_value = continue_value(object, field_defn, false, ast_node, result_name, selection_result)
if HALT != continue_value
continue_field(continue_value, owner_type, field_defn, query.root_type, ast_node, nil, false, nil, nil, result_name, selection_result, false, runtime_state) # rubocop:disable Metrics/ParameterLists
end
@response = selection_result[result_name]
when "UNION", "INTERFACE"
resolved_type, _resolved_obj = resolve_type(root_type, object)
resolved_type = schema.sync_lazy(resolved_type)
object_proxy = resolved_type.wrap(object, context)
object_proxy = schema.sync_lazy(object_proxy)
@response = GraphQLResultHash.new(nil, resolved_type, object_proxy, nil, false, selections, false, query.ast_nodes.first, nil, nil)
@response.base_path = base_path
each_gathered_selections(@response) do |selections, is_selection_array, ordered_result_keys|
@response.ordered_result_keys ||= ordered_result_keys
if is_selection_array == true
raise "This isn't supported yet"
end
@dataloader.append_job {
evaluate_selections(
selections,
@response,
nil,
runtime_state,
)
}
end
else
raise "Invariant: unsupported type kind for partial execution: #{root_type.kind.inspect} (#{root_type})"
end
nil
end
def each_gathered_selections(response_hash)
ordered_result_keys = []
gathered_selections = gather_selections(response_hash.graphql_application_value, response_hash.graphql_result_type, response_hash.graphql_selections, nil, {}, ordered_result_keys)
ordered_result_keys.uniq!
if gathered_selections.is_a?(Array)
gathered_selections.each do |item|
yield(item, true, ordered_result_keys)
end
else
yield(gathered_selections, false, ordered_result_keys)
end
end
def gather_selections(owner_object, owner_type, selections, selections_to_run, selections_by_name, ordered_result_keys)
selections.each do |node|
# Skip gathering this if the directive says so
if !directives_include?(node, owner_object, owner_type)
next
end
if node.is_a?(GraphQL::Language::Nodes::Field)
response_key = node.alias || node.name
ordered_result_keys << response_key
selections = selections_by_name[response_key]
# if there was already a selection of this field,
# use an array to hold all selections,
# otherwise, use the single node to represent the selection
if selections
# This field was already selected at least once,
# add this node to the list of selections
s = Array(selections)
s << node
selections_by_name[response_key] = s
else
# No selection was found for this field yet
selections_by_name[response_key] = node
end
else
# This is an InlineFragment or a FragmentSpread
if !@runtime_directive_names.empty? && node.directives.any? { |d| @runtime_directive_names.include?(d.name) }
next_selections = {}
next_selections[:graphql_directives] = node.directives
if selections_to_run
selections_to_run << next_selections
else
selections_to_run = []
selections_to_run << selections_by_name
selections_to_run << next_selections
end
else
next_selections = selections_by_name
end
case node
when GraphQL::Language::Nodes::InlineFragment
if node.type
type_defn = query.types.type(node.type.name)
if query.types.possible_types(type_defn).include?(owner_type)
result = gather_selections(owner_object, owner_type, node.selections, selections_to_run, next_selections, ordered_result_keys)
if !result.equal?(next_selections)
selections_to_run = result
end
end
else
# it's an untyped fragment, definitely continue
result = gather_selections(owner_object, owner_type, node.selections, selections_to_run, next_selections, ordered_result_keys)
if !result.equal?(next_selections)
selections_to_run = result
end
end
when GraphQL::Language::Nodes::FragmentSpread
fragment_def = query.fragments[node.name]
type_defn = query.types.type(fragment_def.type.name)
if query.types.possible_types(type_defn).include?(owner_type)
result = gather_selections(owner_object, owner_type, fragment_def.selections, selections_to_run, next_selections, ordered_result_keys)
if !result.equal?(next_selections)
selections_to_run = result
end
end
else
raise "Invariant: unexpected selection class: #{node.class}"
end
end
end
selections_to_run || selections_by_name
end
NO_ARGS = GraphQL::EmptyObjects::EMPTY_HASH
# @return [void]
def evaluate_selections(gathered_selections, selections_result, target_result, runtime_state) # rubocop:disable Metrics/ParameterLists
runtime_state ||= get_current_runtime_state
runtime_state.current_result_name = nil
runtime_state.current_result = selections_result
# This is a less-frequent case; use a fast check since it's often not there.
if (directives = gathered_selections[:graphql_directives])
gathered_selections.delete(:graphql_directives)
end
call_method_on_directives(:resolve, selections_result.graphql_application_value, directives) do
gathered_selections.each do |result_name, field_ast_nodes_or_ast_node|
# Field resolution may pause the fiber,
# so it wouldn't get to the `Resolve` call that happens below.
# So instead trigger a run from this outer context.
if selections_result.graphql_is_eager
@dataloader.clear_cache
@dataloader.run_isolated {
evaluate_selection(
result_name, field_ast_nodes_or_ast_node, selections_result
)
@dataloader.clear_cache
}
else
@dataloader.append_job {
evaluate_selection(
result_name, field_ast_nodes_or_ast_node, selections_result
)
}
end
end
if target_result
selections_result.merge_into(target_result)
end
selections_result
end
end
# @return [void]
def evaluate_selection(result_name, field_ast_nodes_or_ast_node, selections_result) # rubocop:disable Metrics/ParameterLists
return if selections_result.graphql_dead
# As a performance optimization, the hash key will be a `Node` if
# there's only one selection of the field. But if there are multiple
# selections of the field, it will be an Array of nodes
if field_ast_nodes_or_ast_node.is_a?(Array)
field_ast_nodes = field_ast_nodes_or_ast_node
ast_node = field_ast_nodes.first
else
field_ast_nodes = nil
ast_node = field_ast_nodes_or_ast_node
end
field_name = ast_node.name
owner_type = selections_result.graphql_result_type
field_defn = query.types.field(owner_type, field_name)
# Set this before calling `run_with_directives`, so that the directive can have the latest path
runtime_state = get_current_runtime_state
runtime_state.current_field = field_defn
runtime_state.current_result = selections_result
runtime_state.current_result_name = result_name
owner_object = selections_result.graphql_application_value
if field_defn.dynamic_introspection
owner_object = field_defn.owner.wrap(owner_object, context)
end
if !field_defn.any_arguments?
resolved_arguments = GraphQL::Execution::Interpreter::Arguments::EMPTY
if field_defn.extras.size == 0
evaluate_selection_with_resolved_keyword_args(
NO_ARGS, resolved_arguments, field_defn, ast_node, field_ast_nodes, owner_object, result_name, selections_result, runtime_state
)
else
evaluate_selection_with_args(resolved_arguments, field_defn, ast_node, field_ast_nodes, owner_object, result_name, selections_result, runtime_state)
end
else
@query.arguments_cache.dataload_for(ast_node, field_defn, owner_object) do |resolved_arguments|
runtime_state = get_current_runtime_state # This might be in a different fiber
runtime_state.current_field = field_defn
runtime_state.current_arguments = resolved_arguments
runtime_state.current_result_name = result_name
runtime_state.current_result = selections_result
evaluate_selection_with_args(resolved_arguments, field_defn, ast_node, field_ast_nodes, owner_object, result_name, selections_result, runtime_state)
end
end
end
def evaluate_selection_with_args(arguments, field_defn, ast_node, field_ast_nodes, object, result_name, selection_result, runtime_state) # rubocop:disable Metrics/ParameterLists
after_lazy(arguments, field: field_defn, ast_node: ast_node, owner_object: object, arguments: arguments, result_name: result_name, result: selection_result, runtime_state: runtime_state) do |resolved_arguments, runtime_state|
if resolved_arguments.is_a?(GraphQL::ExecutionError) || resolved_arguments.is_a?(GraphQL::UnauthorizedError)
next if selection_result.collect_result(result_name, resolved_arguments)
return_type_non_null = field_defn.type.non_null?
continue_value(resolved_arguments, field_defn, return_type_non_null, ast_node, result_name, selection_result)
next
end
kwarg_arguments = if field_defn.extras.empty?
if resolved_arguments.empty?
# We can avoid allocating the `{ Symbol => Object }` hash in this case
NO_ARGS
else
resolved_arguments.keyword_arguments
end
else
# Bundle up the extras, then make a new arguments instance
# that includes the extras, too.
extra_args = {}
field_defn.extras.each do |extra|
case extra
when :ast_node
extra_args[:ast_node] = ast_node
when :execution_errors
extra_args[:execution_errors] = ExecutionErrors.new(context, ast_node, current_path)
when :path
extra_args[:path] = current_path
when :lookahead
if !field_ast_nodes
field_ast_nodes = [ast_node]
end
extra_args[:lookahead] = Execution::Lookahead.new(
query: query,
ast_nodes: field_ast_nodes,
field: field_defn,
)
when :argument_details
# Use this flag to tell Interpreter::Arguments to add itself
# to the keyword args hash _before_ freezing everything.
extra_args[:argument_details] = :__arguments_add_self
when :parent
parent_result = selection_result.graphql_parent
extra_args[:parent] = parent_result&.graphql_application_value&.object
else
extra_args[extra] = field_defn.fetch_extra(extra, context)
end
end
if !extra_args.empty?
resolved_arguments = resolved_arguments.merge_extras(extra_args)
end
resolved_arguments.keyword_arguments
end
evaluate_selection_with_resolved_keyword_args(kwarg_arguments, resolved_arguments, field_defn, ast_node, field_ast_nodes, object, result_name, selection_result, runtime_state)
end
end
def evaluate_selection_with_resolved_keyword_args(kwarg_arguments, resolved_arguments, field_defn, ast_node, field_ast_nodes, object, result_name, selection_result, runtime_state) # rubocop:disable Metrics/ParameterLists
runtime_state.current_field = field_defn
runtime_state.current_arguments = resolved_arguments
runtime_state.current_result_name = result_name
runtime_state.current_result = selection_result
# Optimize for the case that field is selected only once
if field_ast_nodes.nil? || field_ast_nodes.size == 1
next_selections = ast_node.selections
directives = ast_node.directives
else
next_selections = []
directives = []
field_ast_nodes.each { |f|
next_selections.concat(f.selections)
directives.concat(f.directives)
}
end
call_method_on_directives(:resolve, object, directives) do
if !directives.empty?
# This might be executed in a different context; reset this info
runtime_state = get_current_runtime_state
runtime_state.current_field = field_defn
runtime_state.current_arguments = resolved_arguments
runtime_state.current_result_name = result_name
runtime_state.current_result = selection_result
end
# Actually call the field resolver and capture the result
app_result = begin
@current_trace.begin_execute_field(field_defn, object, kwarg_arguments, query)
@current_trace.execute_field(field: field_defn, ast_node: ast_node, query: query, object: object, arguments: kwarg_arguments) do
field_defn.resolve(object, kwarg_arguments, context)
end
rescue GraphQL::ExecutionError => err
err
rescue StandardError => err
begin
query.handle_or_reraise(err)
rescue GraphQL::ExecutionError => ex_err
ex_err
end
end
@current_trace.end_execute_field(field_defn, object, kwarg_arguments, query, app_result)
after_lazy(app_result, field: field_defn, ast_node: ast_node, owner_object: object, arguments: resolved_arguments, result_name: result_name, result: selection_result, runtime_state: runtime_state) do |inner_result, runtime_state|
next if selection_result.collect_result(result_name, inner_result)
owner_type = selection_result.graphql_result_type
return_type = field_defn.type
continue_value = continue_value(inner_result, field_defn, return_type.non_null?, ast_node, result_name, selection_result)
if HALT != continue_value
was_scoped = runtime_state.was_authorized_by_scope_items
runtime_state.was_authorized_by_scope_items = nil
continue_field(continue_value, owner_type, field_defn, return_type, ast_node, next_selections, false, object, resolved_arguments, result_name, selection_result, was_scoped, runtime_state)
else
nil
end
end
end
# If this field is a root mutation field, immediately resolve
# all of its child fields before moving on to the next root mutation field.
# (Subselections of this mutation will still be resolved level-by-level.)
if selection_result.graphql_is_eager
@dataloader.run
end
end
def set_result(selection_result, result_name, value, is_child_result, is_non_null)
if !selection_result.graphql_dead
if value.nil? && is_non_null
# This is an invalid nil that should be propagated
# One caller of this method passes a block,
# namely when application code returns a `nil` to GraphQL and it doesn't belong there.
# The other possibility for reaching here is when a field returns an ExecutionError, so we write
# `nil` to the response, not knowing whether it's an invalid `nil` or not.
# (And in that case, we don't have to call the schema's handler, since it's not a bug in the application.)
# TODO the code is trying to tell me something.
yield if block_given?
parent = selection_result.graphql_parent
if parent.nil? # This is a top-level result hash
@response = nil
else
name_in_parent = selection_result.graphql_result_name
is_non_null_in_parent = selection_result.graphql_is_non_null_in_parent
set_result(parent, name_in_parent, nil, false, is_non_null_in_parent)
set_graphql_dead(selection_result)
end
elsif is_child_result
selection_result.set_child_result(result_name, value)
else
selection_result.set_leaf(result_name, value)
end
end
end
# Mark this node and any already-registered children as dead,
# so that it accepts no more writes.
def set_graphql_dead(selection_result)
case selection_result
when GraphQLResultArray
selection_result.graphql_dead = true
selection_result.values.each { |v| set_graphql_dead(v) }
when GraphQLResultHash
selection_result.graphql_dead = true
selection_result.each { |k, v| set_graphql_dead(v) }
else
# It's a scalar, no way to mark it dead.
end
end
def current_path
st = get_current_runtime_state
result = st.current_result
path = result && result.path
if path && (rn = st.current_result_name)
path = path.dup
path.push(rn)
end
path
end
HALT = Object.new.freeze
def continue_value(value, field, is_non_null, ast_node, result_name, selection_result) # rubocop:disable Metrics/ParameterLists
case value
when nil
if is_non_null
set_result(selection_result, result_name, nil, false, is_non_null) do
# When this comes from a list item, use the parent object:
is_from_array = selection_result.is_a?(GraphQLResultArray)
parent_type = is_from_array ? selection_result.graphql_parent.graphql_result_type : selection_result.graphql_result_type
# This block is called if `result_name` is not dead. (Maybe a previous invalid nil caused it be marked dead.)
err = parent_type::InvalidNullError.new(parent_type, field, ast_node, is_from_array: is_from_array)
schema.type_error(err, context)
end
else
set_result(selection_result, result_name, nil, false, is_non_null)
end
HALT
when GraphQL::Error
# Handle these cases inside a single `when`
# to avoid the overhead of checking three different classes
# every time.
if value.is_a?(GraphQL::ExecutionError)
if selection_result.nil? || !selection_result.graphql_dead
value.path ||= current_path
value.ast_node ||= ast_node
context.errors << value
if selection_result
set_result(selection_result, result_name, nil, false, is_non_null)
end
end
HALT
elsif value.is_a?(GraphQL::UnauthorizedFieldError)
value.field ||= field
# this hook might raise & crash, or it might return
# a replacement value
next_value = begin
schema.unauthorized_field(value)
rescue GraphQL::ExecutionError => err
err
end
continue_value(next_value, field, is_non_null, ast_node, result_name, selection_result)
elsif value.is_a?(GraphQL::UnauthorizedError)
# this hook might raise & crash, or it might return
# a replacement value
next_value = begin
schema.unauthorized_object(value)
rescue GraphQL::ExecutionError => err
err
end
continue_value(next_value, field, is_non_null, ast_node, result_name, selection_result)
elsif GraphQL::Execution::SKIP == value
# It's possible a lazy was already written here
case selection_result
when GraphQLResultHash
selection_result.delete(result_name)
when GraphQLResultArray
selection_result.graphql_skip_at(result_name)
when nil
# this can happen with directives
else
raise "Invariant: unexpected result class #{selection_result.class} (#{selection_result.inspect})"
end
HALT
else
# What could this actually _be_? Anyhow,
# preserve the default behavior of doing nothing with it.
value
end
when Array
# It's an array full of execution errors; add them all.
if !value.empty? && value.all?(GraphQL::ExecutionError)
list_type_at_all = (field && (field.type.list?))
if selection_result.nil? || !selection_result.graphql_dead
value.each_with_index do |error, index|
error.ast_node ||= ast_node
error.path ||= current_path + (list_type_at_all ? [index] : [])
context.errors << error
end
if selection_result
if list_type_at_all
result_without_errors = value.map { |v| v.is_a?(GraphQL::ExecutionError) ? nil : v }
set_result(selection_result, result_name, result_without_errors, false, is_non_null)
else
set_result(selection_result, result_name, nil, false, is_non_null)
end
end
end
HALT
else
value
end
when GraphQL::Execution::Interpreter::RawValue
# Write raw value directly to the response without resolving nested objects
set_result(selection_result, result_name, value.resolve, false, is_non_null)
HALT
else
value
end
end
# The resolver for `field` returned `value`. Continue to execute the query,
# treating `value` as `type` (probably the return type of the field).
#
# Use `next_selections` to resolve object fields, if there are any.
#
# Location information from `path` and `ast_node`.
#
# @return [Lazy, Array, Hash, Object] Lazy, Array, and Hash are all traversed to resolve lazy values later
def continue_field(value, owner_type, field, current_type, ast_node, next_selections, is_non_null, owner_object, arguments, result_name, selection_result, was_scoped, runtime_state) # rubocop:disable Metrics/ParameterLists
if current_type.non_null?
current_type = current_type.of_type
is_non_null = true
end
case current_type.kind.name
when "SCALAR", "ENUM"
r = begin
current_type.coerce_result(value, context)
rescue GraphQL::ExecutionError => ex_err
return continue_value(ex_err, field, is_non_null, ast_node, result_name, selection_result)
rescue StandardError => err
begin
query.handle_or_reraise(err)
rescue GraphQL::ExecutionError => ex_err
return continue_value(ex_err, field, is_non_null, ast_node, result_name, selection_result)
end
end
set_result(selection_result, result_name, r, false, is_non_null)
r
when "UNION", "INTERFACE"
resolved_type_or_lazy = begin
resolve_type(current_type, value)
rescue GraphQL::ExecutionError, GraphQL::UnauthorizedError => ex_err
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | true |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/execution_errors.rb | lib/graphql/execution/interpreter/execution_errors.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
class ExecutionErrors
def initialize(ctx, ast_node, path)
@context = ctx
@ast_node = ast_node
@path = path
end
def add(err_or_msg)
err = case err_or_msg
when String
GraphQL::ExecutionError.new(err_or_msg)
when GraphQL::ExecutionError
err_or_msg
else
raise ArgumentError, "expected String or GraphQL::ExecutionError, not #{err_or_msg.class} (#{err_or_msg.inspect})"
end
err.ast_node ||= @ast_node
err.path ||= @path
@context.add_error(err)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution/interpreter/runtime/graphql_result.rb | lib/graphql/execution/interpreter/runtime/graphql_result.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Interpreter
class Runtime
module GraphQLResult
def initialize(result_name, result_type, application_value, parent_result, is_non_null_in_parent, selections, is_eager, ast_node, graphql_arguments, graphql_field) # rubocop:disable Metrics/ParameterLists
@ast_node = ast_node
@graphql_arguments = graphql_arguments
@graphql_field = graphql_field
@graphql_parent = parent_result
@graphql_application_value = application_value
@graphql_result_type = result_type
if parent_result && parent_result.graphql_dead
@graphql_dead = true
end
@graphql_result_name = result_name
@graphql_is_non_null_in_parent = is_non_null_in_parent
# Jump through some hoops to avoid creating this duplicate storage if at all possible.
@graphql_metadata = nil
@graphql_selections = selections
@graphql_is_eager = is_eager
@base_path = nil
end
# TODO test full path in Partial
attr_writer :base_path
def path
@path ||= build_path([])
end
def build_path(path_array)
graphql_result_name && path_array.unshift(graphql_result_name)
if @graphql_parent
@graphql_parent.build_path(path_array)
elsif @base_path
@base_path + path_array
else
path_array
end
end
def depth
@depth ||= if @graphql_parent
@graphql_parent.depth + 1
else
1
end
end
attr_accessor :graphql_dead
attr_reader :graphql_parent, :graphql_result_name, :graphql_is_non_null_in_parent,
:graphql_application_value, :graphql_result_type, :graphql_selections, :graphql_is_eager, :ast_node, :graphql_arguments, :graphql_field
# @return [Hash] Plain-Ruby result data (`@graphql_metadata` contains Result wrapper objects)
attr_accessor :graphql_result_data
end
class GraphQLResultHash
def initialize(_result_name, _result_type, _application_value, _parent_result, _is_non_null_in_parent, _selections, _is_eager, _ast_node, _graphql_arguments, graphql_field) # rubocop:disable Metrics/ParameterLists
super
@graphql_result_data = {}
@ordered_result_keys = nil
end
attr_accessor :ordered_result_keys
include GraphQLResult
attr_accessor :graphql_merged_into
def set_leaf(key, value)
# This is a hack.
# Basically, this object is merged into the root-level result at some point.
# But the problem is, some lazies are created whose closures retain reference to _this_
# object. When those lazies are resolved, they cause an update to this object.
#
# In order to return a proper top-level result, we have to update that top-level result object.
# In order to return a proper partial result (eg, for a directive), we have to update this object, too.
# Yowza.
if (t = @graphql_merged_into)
t.set_leaf(key, value)
end
before_size = @graphql_result_data.size
@graphql_result_data[key] = value
after_size = @graphql_result_data.size
if after_size > before_size && @ordered_result_keys[before_size] != key
fix_result_order
end
# keep this up-to-date if it's been initialized
@graphql_metadata && @graphql_metadata[key] = value
value
end
def set_child_result(key, value)
if (t = @graphql_merged_into)
t.set_child_result(key, value)
end
before_size = @graphql_result_data.size
@graphql_result_data[key] = value.graphql_result_data
after_size = @graphql_result_data.size
if after_size > before_size && @ordered_result_keys[before_size] != key
fix_result_order
end
# If we encounter some part of this response that requires metadata tracking,
# then create the metadata hash if necessary. It will be kept up-to-date after this.
(@graphql_metadata ||= @graphql_result_data.dup)[key] = value
value
end
def delete(key)
@graphql_metadata && @graphql_metadata.delete(key)
@graphql_result_data.delete(key)
end
def each
(@graphql_metadata || @graphql_result_data).each { |k, v| yield(k, v) }
end
def values
(@graphql_metadata || @graphql_result_data).values
end
def key?(k)
@graphql_result_data.key?(k)
end
def [](k)
(@graphql_metadata || @graphql_result_data)[k]
end
def merge_into(into_result)
self.each do |key, value|
case value
when GraphQLResultHash
next_into = into_result[key]
if next_into
value.merge_into(next_into)
else
into_result.set_child_result(key, value)
end
when GraphQLResultArray
# There's no special handling of arrays because currently, there's no way to split the execution
# of a list over several concurrent flows.
into_result.set_child_result(key, value)
else
# We have to assume that, since this passed the `fields_will_merge` selection,
# that the old and new values are the same.
into_result.set_leaf(key, value)
end
end
@graphql_merged_into = into_result
end
def fix_result_order
@ordered_result_keys.each do |k|
if @graphql_result_data.key?(k)
@graphql_result_data[k] = @graphql_result_data.delete(k)
end
end
end
# hook for breadth-first implementations to signal when collecting results.
def collect_result(result_name, result_value)
false
end
end
class GraphQLResultArray
include GraphQLResult
def initialize(_result_name, _result_type, _application_value, _parent_result, _is_non_null_in_parent, _selections, _is_eager, _ast_node, _graphql_arguments, graphql_field) # rubocop:disable Metrics/ParameterLists
super
@graphql_result_data = []
end
def graphql_skip_at(index)
# Mark this index as dead. It's tricky because some indices may already be storing
# `Lazy`s. So the runtime is still holding indexes _before_ skipping,
# this object has to coordinate incoming writes to account for any already-skipped indices.
@skip_indices ||= []
@skip_indices << index
offset_by = @skip_indices.count { |skipped_idx| skipped_idx < index}
delete_at_index = index - offset_by
@graphql_metadata && @graphql_metadata.delete_at(delete_at_index)
@graphql_result_data.delete_at(delete_at_index)
end
def set_leaf(idx, value)
if @skip_indices
offset_by = @skip_indices.count { |skipped_idx| skipped_idx < idx }
idx -= offset_by
end
@graphql_result_data[idx] = value
@graphql_metadata && @graphql_metadata[idx] = value
value
end
def set_child_result(idx, value)
if @skip_indices
offset_by = @skip_indices.count { |skipped_idx| skipped_idx < idx }
idx -= offset_by
end
@graphql_result_data[idx] = value.graphql_result_data
# If we encounter some part of this response that requires metadata tracking,
# then create the metadata hash if necessary. It will be kept up-to-date after this.
(@graphql_metadata ||= @graphql_result_data.dup)[idx] = value
value
end
def values
(@graphql_metadata || @graphql_result_data)
end
def [](idx)
(@graphql_metadata || @graphql_result_data)[idx]
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/query_depth.rb | lib/graphql/analysis/query_depth.rb | # frozen_string_literal: true
module GraphQL
module Analysis
# A query reducer for measuring the depth of a given query.
#
# See https://graphql-ruby.org/queries/ast_analysis.html for more examples.
#
# @example Logging the depth of a query
# class LogQueryDepth < GraphQL::Analysis::QueryDepth
# def result
# log("GraphQL query depth: #{@max_depth}")
# end
# end
#
# # In your Schema file:
#
# class MySchema < GraphQL::Schema
# query_analyzer LogQueryDepth
# end
#
# # When you run the query, the depth will get logged:
#
# Schema.execute(query_str)
# # GraphQL query depth: 8
#
class QueryDepth < Analyzer
def initialize(query)
@max_depth = 0
@current_depth = 0
@count_introspection_fields = query.schema.count_introspection_fields
super
end
def on_enter_field(node, parent, visitor)
return if visitor.skipping? ||
visitor.visiting_fragment_definition? ||
(@count_introspection_fields == false && visitor.field_definition.introspection?)
@current_depth += 1
end
def on_leave_field(node, parent, visitor)
return if visitor.skipping? ||
visitor.visiting_fragment_definition? ||
(@count_introspection_fields == false && visitor.field_definition.introspection?)
if @max_depth < @current_depth
@max_depth = @current_depth
end
@current_depth -= 1
end
def result
@max_depth
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/query_complexity.rb | lib/graphql/analysis/query_complexity.rb | # frozen_string_literal: true
module GraphQL
module Analysis
# Calculate the complexity of a query, using {Field#complexity} values.
class QueryComplexity < Analyzer
# State for the query complexity calculation:
# - `complexities_on_type` holds complexity scores for each type
def initialize(query)
super
@skip_introspection_fields = !query.schema.max_complexity_count_introspection_fields
@complexities_on_type_by_query = {}
end
# Override this method to use the complexity result
def result
case subject.schema.complexity_cost_calculation_mode_for(subject.context)
when :future
max_possible_complexity
when :legacy
max_possible_complexity(mode: :legacy)
when :compare
future_complexity = max_possible_complexity
legacy_complexity = max_possible_complexity(mode: :legacy)
if future_complexity != legacy_complexity
subject.schema.legacy_complexity_cost_calculation_mismatch(subject, future_complexity, legacy_complexity)
else
future_complexity
end
when nil
subject.logger.warn <<~GRAPHQL
GraphQL-Ruby's complexity cost system is getting some "breaking fixes" in a future version. See the migration notes at https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#complexity_cost_calculation_mode_for-class_method
To opt into the future behavior, configure your schema (#{subject.schema.name ? subject.schema.name : subject.schema.ancestors}) with:
complexity_cost_calculation_mode(:future) # or `:legacy`, `:compare`
GRAPHQL
max_possible_complexity(mode: :legacy)
else
raise ArgumentError, "Expected `:future`, `:legacy`, `:compare`, or `nil` from `#{query.schema}.complexity_cost_calculation_mode_for` but got: #{query.schema.complexity_cost_calculation_mode.inspect}"
end
end
# ScopedTypeComplexity models a tree of GraphQL types mapped to inner selections, ie:
# Hash<GraphQL::BaseType, Hash<String, ScopedTypeComplexity>>
class ScopedTypeComplexity < Hash
# A proc for defaulting empty namespace requests as a new scope hash.
DEFAULT_PROC = ->(h, k) { h[k] = {} }
attr_reader :field_definition, :response_path, :query
# @param parent_type [Class] The owner of `field_definition`
# @param field_definition [GraphQL::Field, GraphQL::Schema::Field] Used for getting the `.complexity` configuration
# @param query [GraphQL::Query] Used for `query.possible_types`
# @param response_path [Array<String>] The path to the response key for the field
# @return [Hash<GraphQL::BaseType, Hash<String, ScopedTypeComplexity>>]
def initialize(parent_type, field_definition, query, response_path)
super(&DEFAULT_PROC)
@parent_type = parent_type
@field_definition = field_definition
@query = query
@response_path = response_path
@nodes = []
end
# @return [Array<GraphQL::Language::Nodes::Field>]
attr_reader :nodes
def own_complexity(child_complexity)
@field_definition.calculate_complexity(query: @query, nodes: @nodes, child_complexity: child_complexity)
end
def composite?
!empty?
end
end
def on_enter_field(node, parent, visitor)
# We don't want to visit fragment definitions,
# we'll visit them when we hit the spreads instead
return if visitor.visiting_fragment_definition?
return if visitor.skipping?
return if @skip_introspection_fields && visitor.field_definition.introspection?
parent_type = visitor.parent_type_definition
field_key = node.alias || node.name
# Find or create a complexity scope stack for this query.
scopes_stack = @complexities_on_type_by_query[visitor.query] ||= [ScopedTypeComplexity.new(nil, nil, query, visitor.response_path)]
# Find or create the complexity costing node for this field.
scope = scopes_stack.last[parent_type][field_key] ||= ScopedTypeComplexity.new(parent_type, visitor.field_definition, visitor.query, visitor.response_path)
scope.nodes.push(node)
scopes_stack.push(scope)
end
def on_leave_field(node, parent, visitor)
# We don't want to visit fragment definitions,
# we'll visit them when we hit the spreads instead
return if visitor.visiting_fragment_definition?
return if visitor.skipping?
return if @skip_introspection_fields && visitor.field_definition.introspection?
scopes_stack = @complexities_on_type_by_query[visitor.query]
scopes_stack.pop
end
private
# @return [Integer]
def max_possible_complexity(mode: :future)
@complexities_on_type_by_query.reduce(0) do |total, (query, scopes_stack)|
total + merged_max_complexity_for_scopes(query, [scopes_stack.first], mode)
end
end
# @param query [GraphQL::Query] Used for `query.possible_types`
# @param scopes [Array<ScopedTypeComplexity>] Array of scoped type complexities
# @param mode [:future, :legacy]
# @return [Integer]
def merged_max_complexity_for_scopes(query, scopes, mode)
# Aggregate a set of all possible scope types encountered (scope keys).
# Use a hash, but ignore the values; it's just a fast way to work with the keys.
possible_scope_types = scopes.each_with_object({}) do |scope, memo|
memo.merge!(scope)
end
# Expand abstract scope types into their concrete implementations;
# overlapping abstracts coalesce through their intersecting types.
possible_scope_types.keys.each do |possible_scope_type|
next unless possible_scope_type.kind.abstract?
query.types.possible_types(possible_scope_type).each do |impl_type|
possible_scope_types[impl_type] ||= true
end
possible_scope_types.delete(possible_scope_type)
end
# Aggregate the lexical selections that may apply to each possible type,
# and then return the maximum cost among possible typed selections.
possible_scope_types.each_key.reduce(0) do |max, possible_scope_type|
# Collect inner selections from all scopes that intersect with this possible type.
all_inner_selections = scopes.each_with_object([]) do |scope, memo|
scope.each do |scope_type, inner_selections|
memo << inner_selections if types_intersect?(query, scope_type, possible_scope_type)
end
end
# Find the maximum complexity for the scope type among possible lexical branches.
complexity = case mode
when :legacy
legacy_merged_max_complexity(query, all_inner_selections)
when :future
merged_max_complexity(query, all_inner_selections)
else
raise ArgumentError, "Expected :legacy or :future, not: #{mode.inspect}"
end
complexity > max ? complexity : max
end
end
def types_intersect?(query, a, b)
return true if a == b
a_types = query.types.possible_types(a)
query.types.possible_types(b).any? { |t| a_types.include?(t) }
end
# A hook which is called whenever a field's max complexity is calculated.
# Override this method to capture individual field complexity details.
#
# @param scoped_type_complexity [ScopedTypeComplexity]
# @param max_complexity [Numeric] Field's maximum complexity including child complexity
# @param child_complexity [Numeric, nil] Field's child complexity
def field_complexity(scoped_type_complexity, max_complexity:, child_complexity: nil)
end
# @param inner_selections [Array<Hash<String, ScopedTypeComplexity>>] Field selections for a scope
# @return [Integer] Total complexity value for all these selections in the parent scope
def merged_max_complexity(query, inner_selections)
# Aggregate a set of all unique field selection keys across all scopes.
# Use a hash, but ignore the values; it's just a fast way to work with the keys.
unique_field_keys = inner_selections.each_with_object({}) do |inner_selection, memo|
memo.merge!(inner_selection)
end
# Add up the total cost for each unique field name's coalesced selections
unique_field_keys.each_key.reduce(0) do |total, field_key|
# Collect all child scopes for this field key;
# all keys come with at least one scope.
child_scopes = inner_selections.filter_map { _1[field_key] }
# Compute maximum possible cost of child selections;
# composites merge their maximums, while leaf scopes are always zero.
# FieldsWillMerge validation assures all scopes are uniformly composite or leaf.
maximum_children_cost = if child_scopes.any?(&:composite?)
merged_max_complexity_for_scopes(query, child_scopes, :future)
else
0
end
# Identify the maximum cost and scope among possibilities
maximum_cost = 0
maximum_scope = child_scopes.reduce(child_scopes.last) do |max_scope, possible_scope|
scope_cost = possible_scope.own_complexity(maximum_children_cost)
if scope_cost > maximum_cost
maximum_cost = scope_cost
possible_scope
else
max_scope
end
end
field_complexity(
maximum_scope,
max_complexity: maximum_cost,
child_complexity: maximum_children_cost,
)
total + maximum_cost
end
end
def legacy_merged_max_complexity(query, inner_selections)
# Aggregate a set of all unique field selection keys across all scopes.
# Use a hash, but ignore the values; it's just a fast way to work with the keys.
unique_field_keys = inner_selections.each_with_object({}) do |inner_selection, memo|
memo.merge!(inner_selection)
end
# Add up the total cost for each unique field name's coalesced selections
unique_field_keys.each_key.reduce(0) do |total, field_key|
composite_scopes = nil
field_cost = 0
# Collect composite selection scopes for further aggregation,
# leaf selections report their costs directly.
inner_selections.each do |inner_selection|
child_scope = inner_selection[field_key]
next unless child_scope
# Empty child scopes are leaf nodes with zero child complexity.
if child_scope.empty?
field_cost = child_scope.own_complexity(0)
field_complexity(child_scope, max_complexity: field_cost, child_complexity: nil)
else
composite_scopes ||= []
composite_scopes << child_scope
end
end
if composite_scopes
child_complexity = merged_max_complexity_for_scopes(query, composite_scopes, :legacy)
# This is the last composite scope visited; assume it's representative (for backwards compatibility).
# Note: it would be more correct to score each composite scope and use the maximum possibility.
field_cost = composite_scopes.last.own_complexity(child_complexity)
field_complexity(composite_scopes.last, max_complexity: field_cost, child_complexity: child_complexity)
end
total + field_cost
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/field_usage.rb | lib/graphql/analysis/field_usage.rb | # frozen_string_literal: true
module GraphQL
module Analysis
class FieldUsage < Analyzer
def initialize(query)
super
@used_fields = Set.new
@used_deprecated_fields = Set.new
@used_deprecated_arguments = Set.new
@used_deprecated_enum_values = Set.new
end
def on_leave_field(node, parent, visitor)
field_defn = visitor.field_definition
field = "#{visitor.parent_type_definition.graphql_name}.#{field_defn.graphql_name}"
@used_fields << field
@used_deprecated_fields << field if field_defn.deprecation_reason
arguments = visitor.query.arguments_for(node, field_defn)
# If there was an error when preparing this argument object,
# then this might be an error or something:
if arguments.respond_to?(:argument_values)
extract_deprecated_arguments(arguments.argument_values)
end
end
def result
{
used_fields: @used_fields.to_a,
used_deprecated_fields: @used_deprecated_fields.to_a,
used_deprecated_arguments: @used_deprecated_arguments.to_a,
used_deprecated_enum_values: @used_deprecated_enum_values.to_a,
}
end
private
def extract_deprecated_arguments(argument_values)
argument_values.each_pair do |_argument_name, argument|
if argument.definition.deprecation_reason
@used_deprecated_arguments << argument.definition.path
end
arg_val = argument.value
next if arg_val.nil?
argument_type = argument.definition.type
if argument_type.non_null?
argument_type = argument_type.of_type
end
if argument_type.kind.input_object?
extract_deprecated_arguments(argument.original_value.arguments.argument_values) # rubocop:disable Development/ContextIsPassedCop -- runtime args instance
elsif argument_type.kind.enum?
extract_deprecated_enum_value(argument_type, arg_val)
elsif argument_type.list?
inner_type = argument_type.unwrap
case inner_type.kind
when TypeKinds::INPUT_OBJECT
argument.original_value.each do |value|
extract_deprecated_arguments(value.arguments.argument_values) # rubocop:disable Development/ContextIsPassedCop -- runtime args instance
end
when TypeKinds::ENUM
arg_val.each do |value|
extract_deprecated_enum_value(inner_type, value)
end
else
# Not a kind of input that we track
end
end
end
end
def extract_deprecated_enum_value(enum_type, value)
enum_value = @query.types.enum_values(enum_type).find { |ev| ev.value == value }
if enum_value&.deprecation_reason
@used_deprecated_enum_values << enum_value.path
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/max_query_depth.rb | lib/graphql/analysis/max_query_depth.rb | # frozen_string_literal: true
module GraphQL
module Analysis
class MaxQueryDepth < QueryDepth
def result
configured_max_depth = if query
query.max_depth
else
multiplex.schema.max_depth
end
if configured_max_depth && @max_depth > configured_max_depth
GraphQL::AnalysisError.new("Query has depth of #{@max_depth}, which exceeds max depth of #{configured_max_depth}")
else
nil
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/max_query_complexity.rb | lib/graphql/analysis/max_query_complexity.rb | # frozen_string_literal: true
module GraphQL
module Analysis
# Used under the hood to implement complexity validation,
# see {Schema#max_complexity} and {Query#max_complexity}
class MaxQueryComplexity < QueryComplexity
def result
return if subject.max_complexity.nil?
total_complexity = max_possible_complexity
if total_complexity > subject.max_complexity
GraphQL::AnalysisError.new("Query has complexity of #{total_complexity}, which exceeds max complexity of #{subject.max_complexity}")
else
nil
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/analyzer.rb | lib/graphql/analysis/analyzer.rb | # frozen_string_literal: true
module GraphQL
module Analysis
# Query analyzer for query ASTs. Query analyzers respond to visitor style methods
# but are prefixed by `enter` and `leave`.
#
# When an analyzer is initialized with a Multiplex, you can always get the current query from
# `visitor.query` in the visit methods.
#
# @param [GraphQL::Query, GraphQL::Execution::Multiplex] The query or multiplex to analyze
class Analyzer
def initialize(subject)
@subject = subject
if subject.is_a?(GraphQL::Query)
@query = subject
@multiplex = nil
else
@multiplex = subject
@query = nil
end
end
# Analyzer hook to decide at analysis time whether a query should
# be analyzed or not.
# @return [Boolean] If the query should be analyzed or not
def analyze?
true
end
# Analyzer hook to decide at analysis time whether analysis
# requires a visitor pass; can be disabled for precomputed results.
# @return [Boolean] If analysis requires visitation or not
def visit?
true
end
# The result for this analyzer. Returning {GraphQL::AnalysisError} results
# in a query error.
# @return [Any] The analyzer result
def result
raise GraphQL::RequiredImplementationMissingError
end
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
class << self
private
def build_visitor_hooks(member_name)
class_eval(<<-EOS, __FILE__, __LINE__ + 1)
def on_enter_#{member_name}(node, parent, visitor)
end
def on_leave_#{member_name}(node, parent, visitor)
end
EOS
end
end
build_visitor_hooks :argument
build_visitor_hooks :directive
build_visitor_hooks :document
build_visitor_hooks :enum
build_visitor_hooks :field
build_visitor_hooks :fragment_spread
build_visitor_hooks :inline_fragment
build_visitor_hooks :input_object
build_visitor_hooks :list_type
build_visitor_hooks :non_null_type
build_visitor_hooks :null_value
build_visitor_hooks :operation_definition
build_visitor_hooks :type_name
build_visitor_hooks :variable_definition
build_visitor_hooks :variable_identifier
build_visitor_hooks :abstract_node
# rubocop:enable Development/NoEvalCop
protected
# @return [GraphQL::Query, GraphQL::Execution::Multiplex] Whatever this analyzer is analyzing
attr_reader :subject
# @return [GraphQL::Query, nil] `nil` if this analyzer is visiting a multiplex
# (When this is `nil`, use `visitor.query` inside visit methods to get the current query)
attr_reader :query
# @return [GraphQL::Execution::Multiplex, nil] `nil` if this analyzer is visiting a query
attr_reader :multiplex
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis/visitor.rb | lib/graphql/analysis/visitor.rb | # frozen_string_literal: true
module GraphQL
module Analysis
# Depth first traversal through a query AST, calling AST analyzers
# along the way.
#
# The visitor is a special case of GraphQL::Language::StaticVisitor, visiting
# only the selected operation, providing helpers for common use cases such
# as skipped fields and visiting fragment spreads.
#
# @see {GraphQL::Analysis::Analyzer} AST Analyzers for queries
class Visitor < GraphQL::Language::StaticVisitor
def initialize(query:, analyzers:, timeout:)
@analyzers = analyzers
@path = []
@object_types = []
@directives = []
@field_definitions = []
@argument_definitions = []
@directive_definitions = []
@rescued_errors = []
@query = query
@schema = query.schema
@types = query.types
@response_path = []
@skip_stack = [false]
@timeout_time = if timeout
Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) + timeout
else
Float::INFINITY
end
super(query.selected_operation)
end
# @return [GraphQL::Query] the query being visited
attr_reader :query
# @return [Array<GraphQL::ObjectType>] Types whose scope we've entered
attr_reader :object_types
# @return [Array<GraphQL::AnalysisError]
attr_reader :rescued_errors
def visit
return unless @document
super
end
# Visit Helpers
# @return [GraphQL::Execution::Interpreter::Arguments] Arguments for this node, merging default values, literal values and query variables
# @see {GraphQL::Query#arguments_for}
def arguments_for(ast_node, field_definition)
@query.arguments_for(ast_node, field_definition)
end
# @return [Boolean] If the visitor is currently inside a fragment definition
def visiting_fragment_definition?
@in_fragment_def
end
# @return [Boolean] If the current node should be skipped because of a skip or include directive
def skipping?
@skipping
end
# @return [Array<String>] The path to the response key for the current field
def response_path
@response_path.dup
end
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
# Visitor Hooks
[
:operation_definition, :fragment_definition,
:inline_fragment, :field, :directive, :argument, :fragment_spread
].each do |node_type|
module_eval <<-RUBY, __FILE__, __LINE__
def call_on_enter_#{node_type}(node, parent)
@analyzers.each do |a|
a.on_enter_#{node_type}(node, parent, self)
rescue AnalysisError => err
@rescued_errors << err
end
end
def call_on_leave_#{node_type}(node, parent)
@analyzers.each do |a|
a.on_leave_#{node_type}(node, parent, self)
rescue AnalysisError => err
@rescued_errors << err
end
end
RUBY
end
# rubocop:enable Development/NoEvalCop
def on_operation_definition(node, parent)
check_timeout
object_type = @schema.root_type_for_operation(node.operation_type)
@object_types.push(object_type)
@path.push("#{node.operation_type}#{node.name ? " #{node.name}" : ""}")
call_on_enter_operation_definition(node, parent)
super
call_on_leave_operation_definition(node, parent)
@object_types.pop
@path.pop
end
def on_inline_fragment(node, parent)
check_timeout
object_type = if node.type
@types.type(node.type.name)
else
@object_types.last
end
@object_types.push(object_type)
@path.push("...#{node.type ? " on #{node.type.name}" : ""}")
@skipping = @skip_stack.last || skip?(node)
@skip_stack << @skipping
call_on_enter_inline_fragment(node, parent)
super
@skipping = @skip_stack.pop
call_on_leave_inline_fragment(node, parent)
@object_types.pop
@path.pop
end
def on_field(node, parent)
check_timeout
@response_path.push(node.alias || node.name)
parent_type = @object_types.last
# This could be nil if the previous field wasn't found:
field_definition = parent_type && @types.field(parent_type, node.name)
@field_definitions.push(field_definition)
if !field_definition.nil?
next_object_type = field_definition.type.unwrap
@object_types.push(next_object_type)
else
@object_types.push(nil)
end
@path.push(node.alias || node.name)
@skipping = @skip_stack.last || skip?(node)
@skip_stack << @skipping
call_on_enter_field(node, parent)
super
@skipping = @skip_stack.pop
call_on_leave_field(node, parent)
@response_path.pop
@field_definitions.pop
@object_types.pop
@path.pop
end
def on_directive(node, parent)
check_timeout
directive_defn = @schema.directives[node.name]
@directive_definitions.push(directive_defn)
call_on_enter_directive(node, parent)
super
call_on_leave_directive(node, parent)
@directive_definitions.pop
end
def on_argument(node, parent)
check_timeout
argument_defn = if (arg = @argument_definitions.last)
arg_type = arg.type.unwrap
if arg_type.kind.input_object?
@types.argument(arg_type, node.name)
else
nil
end
elsif (directive_defn = @directive_definitions.last)
@types.argument(directive_defn, node.name)
elsif (field_defn = @field_definitions.last)
@types.argument(field_defn, node.name)
else
nil
end
@argument_definitions.push(argument_defn)
@path.push(node.name)
call_on_enter_argument(node, parent)
super
call_on_leave_argument(node, parent)
@argument_definitions.pop
@path.pop
end
def on_fragment_spread(node, parent)
check_timeout
@path.push("... #{node.name}")
@skipping = @skip_stack.last || skip?(node)
@skip_stack << @skipping
call_on_enter_fragment_spread(node, parent)
enter_fragment_spread_inline(node)
super
@skipping = @skip_stack.pop
leave_fragment_spread_inline(node)
call_on_leave_fragment_spread(node, parent)
@path.pop
end
# @return [GraphQL::BaseType] The current object type
def type_definition
@object_types.last
end
# @return [GraphQL::BaseType] The type which the current type came from
def parent_type_definition
@object_types[-2]
end
# @return [GraphQL::Field, nil] The most-recently-entered GraphQL::Field, if currently inside one
def field_definition
@field_definitions.last
end
# @return [GraphQL::Field, nil] The GraphQL field which returned the object that the current field belongs to
def previous_field_definition
@field_definitions[-2]
end
# @return [GraphQL::Directive, nil] The most-recently-entered GraphQL::Directive, if currently inside one
def directive_definition
@directive_definitions.last
end
# @return [GraphQL::Argument, nil] The most-recently-entered GraphQL::Argument, if currently inside one
def argument_definition
@argument_definitions.last
end
# @return [GraphQL::Argument, nil] The previous GraphQL argument
def previous_argument_definition
@argument_definitions[-2]
end
private
# Visit a fragment spread inline instead of visiting the definition
# by itself.
def enter_fragment_spread_inline(fragment_spread)
fragment_def = query.fragments[fragment_spread.name]
object_type = if fragment_def.type
@types.type(fragment_def.type.name)
else
object_types.last
end
object_types << object_type
on_fragment_definition_children(fragment_def)
end
# Visit a fragment spread inline instead of visiting the definition
# by itself.
def leave_fragment_spread_inline(_fragment_spread)
object_types.pop
end
def skip?(ast_node)
dir = ast_node.directives
!dir.empty? && !GraphQL::Execution::DirectiveChecks.include?(dir, query)
end
def check_timeout
if Process.clock_gettime(Process::CLOCK_MONOTONIC, :float_second) > @timeout_time
raise GraphQL::Analysis::TimeoutError
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/iso_8601_date.rb | lib/graphql/types/iso_8601_date.rb | # frozen_string_literal: true
module GraphQL
module Types
# This scalar takes `Date`s and transmits them as strings,
# using ISO 8601 format.
#
# Use it for fields or arguments as follows:
#
# field :published_at, GraphQL::Types::ISO8601Date, null: false
#
# argument :deliver_at, GraphQL::Types::ISO8601Date, null: false
#
# Alternatively, use this built-in scalar as inspiration for your
# own Date type.
class ISO8601Date < GraphQL::Schema::Scalar
description "An ISO 8601-encoded date"
specified_by_url "https://tools.ietf.org/html/rfc3339"
# @param value [Date,Time,DateTime,String]
# @return [String]
def self.coerce_result(value, _ctx)
Date.parse(value.to_s).iso8601
end
# @param str_value [String, Date, DateTime, Time]
# @return [Date, nil]
def self.coerce_input(value, ctx)
if value.is_a?(::Date)
value
elsif value.is_a?(::DateTime)
value.to_date
elsif value.is_a?(::Time)
value.to_date
elsif value.nil?
nil
else
Date.iso8601(value)
end
rescue ArgumentError, TypeError
err = GraphQL::DateEncodingError.new(value)
ctx.schema.type_error(err, ctx)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/iso_8601_date_time.rb | lib/graphql/types/iso_8601_date_time.rb | # frozen_string_literal: true
require 'time'
module GraphQL
module Types
# This scalar takes `Time`s and transmits them as strings,
# using ISO 8601 format.
#
# Use it for fields or arguments as follows:
#
# field :created_at, GraphQL::Types::ISO8601DateTime, null: false
#
# argument :deliver_at, GraphQL::Types::ISO8601DateTime, null: false
#
# Alternatively, use this built-in scalar as inspiration for your
# own DateTime type.
class ISO8601DateTime < GraphQL::Schema::Scalar
description "An ISO 8601-encoded datetime"
specified_by_url "https://tools.ietf.org/html/rfc3339"
# It's not compatible with Rails' default,
# i.e. ActiveSupport::JSON::Encoder.time_precision (3 by default)
DEFAULT_TIME_PRECISION = 0
# @return [Integer]
def self.time_precision
@time_precision || DEFAULT_TIME_PRECISION
end
# @param [Integer] value
def self.time_precision=(value)
@time_precision = value
end
# @param value [Time,Date,DateTime,String]
# @return [String]
def self.coerce_result(value, _ctx)
case value
when Date
return value.to_time.iso8601(time_precision)
when ::String
return Time.parse(value).iso8601(time_precision)
else
# Time, DateTime or compatible is given:
return value.iso8601(time_precision)
end
rescue StandardError => error
raise GraphQL::Error, "An incompatible object (#{value.class}) was given to #{self}. Make sure that only Times, Dates, DateTimes, and well-formatted Strings are used with this type. (#{error.message})"
end
# @param str_value [String]
# @return [Time]
def self.coerce_input(str_value, _ctx)
Time.iso8601(str_value)
rescue ArgumentError, TypeError
begin
dt = Date.iso8601(str_value).to_time
# For compatibility, continue accepting dates given without times
# But without this, it would zero out given any time part of `str_value` (hours and/or minutes)
if dt.iso8601.start_with?(str_value)
dt
elsif str_value.length == 8 && str_value.match?(/\A\d{8}\Z/)
# Allow dates that are missing the "-". eg. "20220404"
dt
else
nil
end
rescue ArgumentError, TypeError
# Invalid input
nil
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/int.rb | lib/graphql/types/int.rb | # frozen_string_literal: true
module GraphQL
module Types
# @see {Types::BigInt} for handling integers outside 32-bit range.
class Int < GraphQL::Schema::Scalar
description "Represents non-fractional signed whole numeric values. Int can represent values between -(2^31) and 2^31 - 1."
MIN = -(2**31)
MAX = (2**31) - 1
def self.coerce_input(value, ctx)
return if !value.is_a?(Integer)
if value >= MIN && value <= MAX
value
else
err = GraphQL::IntegerDecodingError.new(value)
ctx.schema.type_error(err, ctx)
end
end
def self.coerce_result(value, ctx)
value = value.to_i
if value >= MIN && value <= MAX
value
else
err = GraphQL::IntegerEncodingError.new(value, context: ctx)
ctx.schema.type_error(err, ctx)
end
end
default_scalar true
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/id.rb | lib/graphql/types/id.rb | # frozen_string_literal: true
module GraphQL
module Types
class ID < GraphQL::Schema::Scalar
graphql_name "ID"
description "Represents a unique identifier that is Base64 obfuscated. It is often used to refetch an object or as key for a cache. The ID type appears in a JSON response as a String; however, it is not intended to be human-readable. When expected as an input type, any string (such as `\"VXNlci0xMA==\"`) or integer (such as `4`) input value will be accepted as an ID."
default_scalar true
def self.coerce_result(value, _ctx)
value.is_a?(::String) ? value : value.to_s
end
def self.coerce_input(value, _ctx)
case value
when ::String
value
when Integer
value.to_s
else
nil
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay.rb | lib/graphql/types/relay.rb | # frozen_string_literal: true
# behavior modules:
require "graphql/types/relay/connection_behaviors"
require "graphql/types/relay/edge_behaviors"
require "graphql/types/relay/node_behaviors"
require "graphql/types/relay/page_info_behaviors"
require "graphql/types/relay/has_node_field"
require "graphql/types/relay/has_nodes_field"
# concrete classes based on the gem defaults:
require "graphql/types/relay/page_info"
require "graphql/types/relay/base_connection"
require "graphql/types/relay/base_edge"
require "graphql/types/relay/node"
module GraphQL
module Types
# This module contains some types and fields that could support Relay conventions in GraphQL.
#
# You can use these classes out of the box if you want, but if you want to use your _own_
# GraphQL extensions along with the features in this code, you could also
# open up the source files and copy the relevant methods and configuration into
# your own classes.
#
# For example, the provided object types extend {Types::Relay::BaseObject},
# but you might want to:
#
# 1. Migrate the extensions from {Types::Relay::BaseObject} into _your app's_ base object
# 2. Copy {Relay::BaseConnection}, {Relay::BaseEdge}, etc into _your app_, and
# change them to extend _your_ base object.
#
# Similarly, `BaseField`'s extensions could be migrated to your app
# and `Node` could be implemented to mix in your base interface module.
module Relay
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/float.rb | lib/graphql/types/float.rb | # frozen_string_literal: true
module GraphQL
module Types
class Float < GraphQL::Schema::Scalar
description "Represents signed double-precision fractional values as specified by [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point)."
def self.coerce_input(value, _ctx)
value.is_a?(Numeric) ? value.to_f : nil
end
def self.coerce_result(value, _ctx)
value.to_f
end
default_scalar true
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/boolean.rb | lib/graphql/types/boolean.rb | # frozen_string_literal: true
module GraphQL
module Types
class Boolean < GraphQL::Schema::Scalar
description "Represents `true` or `false` values."
def self.coerce_input(value, _ctx)
(value == true || value == false) ? value : nil
end
def self.coerce_result(value, _ctx)
!!value
end
default_scalar true
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/json.rb | lib/graphql/types/json.rb | # frozen_string_literal: true
module GraphQL
module Types
# An untyped JSON scalar that maps to Ruby hashes, arrays, strings, integers, floats, booleans and nils.
# This should be used judiciously because it subverts the GraphQL type system.
#
# Use it for fields or arguments as follows:
#
# field :template_parameters, GraphQL::Types::JSON, null: false
#
# argument :template_parameters, GraphQL::Types::JSON, null: false
#
class JSON < GraphQL::Schema::Scalar
description "Represents untyped JSON"
def self.coerce_input(value, _context)
value
end
def self.coerce_result(value, _context)
value
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/iso_8601_duration.rb | lib/graphql/types/iso_8601_duration.rb | # frozen_string_literal: true
module GraphQL
module Types
# This scalar takes `Duration`s and transmits them as strings,
# using ISO 8601 format. ActiveSupport >= 5.0 must be loaded to use
# this scalar.
#
# Use it for fields or arguments as follows:
#
# field :age, GraphQL::Types::ISO8601Duration, null: false
#
# argument :interval, GraphQL::Types::ISO8601Duration, null: false
#
# Alternatively, use this built-in scalar as inspiration for your
# own Duration type.
class ISO8601Duration < GraphQL::Schema::Scalar
description "An ISO 8601-encoded duration"
# @return [Integer, nil]
def self.seconds_precision
# ActiveSupport::Duration precision defaults to whatever input was given
@seconds_precision
end
# @param [Integer, nil] value
def self.seconds_precision=(value)
@seconds_precision = value
end
# @param value [ActiveSupport::Duration, String]
# @return [String]
# @raise [GraphQL::Error] if ActiveSupport::Duration is not defined or if an incompatible object is passed
def self.coerce_result(value, _ctx)
unless defined?(ActiveSupport::Duration)
raise GraphQL::Error, "ActiveSupport >= 5.0 must be loaded to use the built-in ISO8601Duration type."
end
begin
case value
when ActiveSupport::Duration
value.iso8601(precision: seconds_precision)
when ::String
ActiveSupport::Duration.parse(value).iso8601(precision: seconds_precision)
else
# Try calling as ActiveSupport::Duration compatible as a fallback
value.iso8601(precision: seconds_precision)
end
rescue StandardError => error
raise GraphQL::Error, "An incompatible object (#{value.class}) was given to #{self}. Make sure that only ActiveSupport::Durations and well-formatted Strings are used with this type. (#{error.message})"
end
end
# @param value [String, ActiveSupport::Duration]
# @return [ActiveSupport::Duration, nil]
# @raise [GraphQL::Error] if ActiveSupport::Duration is not defined
# @raise [GraphQL::DurationEncodingError] if duration cannot be parsed
def self.coerce_input(value, ctx)
unless defined?(ActiveSupport::Duration)
raise GraphQL::Error, "ActiveSupport >= 5.0 must be loaded to use the built-in ISO8601Duration type."
end
begin
if value.is_a?(ActiveSupport::Duration)
value
elsif value.nil?
nil
else
ActiveSupport::Duration.parse(value)
end
rescue ArgumentError, TypeError
err = GraphQL::DurationEncodingError.new(value)
ctx.schema.type_error(err, ctx)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/string.rb | lib/graphql/types/string.rb | # frozen_string_literal: true
module GraphQL
module Types
class String < GraphQL::Schema::Scalar
description "Represents textual data as UTF-8 character sequences. This type is most often used by GraphQL to represent free-form human-readable text."
def self.coerce_result(value, ctx)
str = value.to_s
if str.encoding == Encoding::UTF_8 || str.ascii_only?
str
elsif str.frozen?
str.encode(Encoding::UTF_8)
else
str.encode!(Encoding::UTF_8)
end
rescue EncodingError
err = GraphQL::StringEncodingError.new(str, context: ctx)
ctx.schema.type_error(err, ctx)
end
def self.coerce_input(value, _ctx)
value.is_a?(::String) ? value : nil
end
default_scalar true
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/big_int.rb | lib/graphql/types/big_int.rb | # frozen_string_literal: true
module GraphQL
module Types
class BigInt < GraphQL::Schema::Scalar
description "Represents non-fractional signed whole numeric values. Since the value may exceed the size of a 32-bit integer, it's encoded as a string."
def self.coerce_input(value, _ctx)
value && parse_int(value)
rescue ArgumentError
nil
end
def self.coerce_result(value, _ctx)
value.to_i.to_s
end
def self.parse_int(value)
value.is_a?(Numeric) ? value : Integer(value, 10)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/connection_behaviors.rb | lib/graphql/types/relay/connection_behaviors.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
module ConnectionBehaviors
extend Forwardable
def_delegators :@object, :cursor_from_node, :parent
def self.included(child_class)
child_class.extend(ClassMethods)
child_class.has_nodes_field(true)
child_class.node_nullable(true)
child_class.edges_nullable(true)
child_class.edge_nullable(true)
child_class.module_exec {
self.edge_type = nil
self.node_type = nil
self.edge_class = nil
}
child_class.default_broadcastable(nil)
add_page_info_field(child_class)
end
module ClassMethods
def inherited(child_class)
super
child_class.has_nodes_field(has_nodes_field)
child_class.node_nullable(node_nullable)
child_class.edges_nullable(edges_nullable)
child_class.edge_nullable(edge_nullable)
child_class.edge_type = nil
child_class.node_type = nil
child_class.edge_class = nil
child_class.default_broadcastable(default_broadcastable?)
end
def default_relay?
true
end
def default_broadcastable?
@default_broadcastable
end
def default_broadcastable(new_value)
@default_broadcastable = new_value
end
# @return [Class]
attr_reader :node_type
# @return [Class]
attr_reader :edge_class
# Configure this connection to return `edges` and `nodes` based on `edge_type_class`.
#
# This method will use the inputs to create:
# - `edges` field
# - `nodes` field
# - description
#
# It's called when you subclass this base connection, trying to use the
# class name to set defaults. You can call it again in the class definition
# to override the default (or provide a value, if the default lookup failed).
# @param field_options [Hash] Any extra keyword arguments to pass to the `field :edges, ...` and `field :nodes, ...` configurations
def edge_type(edge_type_class, edge_class: GraphQL::Pagination::Connection::Edge, node_type: edge_type_class.node_type, nodes_field: self.has_nodes_field, node_nullable: self.node_nullable, edges_nullable: self.edges_nullable, edge_nullable: self.edge_nullable, field_options: nil)
# Set this connection's graphql name
node_type_name = node_type.graphql_name
@node_type = node_type
@edge_type = edge_type_class
@edge_class = edge_class
base_field_options = {
name: :edges,
type: [edge_type_class, null: edge_nullable],
null: edges_nullable,
description: "A list of edges.",
scope: false, # Assume that the connection was already scoped.
connection: false,
}
if field_options
base_field_options.merge!(field_options)
end
field(**base_field_options)
define_nodes_field(node_nullable, field_options: field_options) if nodes_field
description("The connection type for #{node_type_name}.")
end
# Filter this list according to the way its node type would scope them
def scope_items(items, context)
node_type.scope_items(items, context)
end
# The connection will skip auth on its nodes if the node_type is configured for that
def reauthorize_scoped_objects(new_value = nil)
if new_value.nil?
if @reauthorize_scoped_objects != nil
@reauthorize_scoped_objects
else
node_type.reauthorize_scoped_objects
end
else
@reauthorize_scoped_objects = new_value
end
end
# Add the shortcut `nodes` field to this connection and its subclasses
def nodes_field(node_nullable: self.node_nullable, field_options: nil)
define_nodes_field(node_nullable, field_options: field_options)
end
def authorized?(obj, ctx)
true # Let nodes be filtered out
end
def visible?(ctx)
# if this is an abstract base class, there may be no `node_type`
node_type ? node_type.visible?(ctx) : super
end
# Set the default `node_nullable` for this class and its child classes. (Defaults to `true`.)
# Use `node_nullable(false)` in your base class to make non-null `node` and `nodes` fields.
def node_nullable(new_value = nil)
if new_value.nil?
defined?(@node_nullable) ? @node_nullable : superclass.node_nullable
else
@node_nullable = new_value
end
end
# Set the default `edges_nullable` for this class and its child classes. (Defaults to `true`.)
# Use `edges_nullable(false)` in your base class to make non-null `edges` fields.
def edges_nullable(new_value = nil)
if new_value.nil?
defined?(@edges_nullable) ? @edges_nullable : superclass.edges_nullable
else
@edges_nullable = new_value
end
end
# Set the default `edge_nullable` for this class and its child classes. (Defaults to `true`.)
# Use `edge_nullable(false)` in your base class to make non-null `edge` fields.
def edge_nullable(new_value = nil)
if new_value.nil?
defined?(@edge_nullable) ? @edge_nullable : superclass.edge_nullable
else
@edge_nullable = new_value
end
end
# Set the default `nodes_field` for this class and its child classes. (Defaults to `true`.)
# Use `nodes_field(false)` in your base class to prevent adding of a nodes field.
def has_nodes_field(new_value = nil)
if new_value.nil?
defined?(@nodes_field) ? @nodes_field : superclass.has_nodes_field
else
@nodes_field = new_value
end
end
protected
attr_writer :edge_type, :node_type, :edge_class
private
def define_nodes_field(nullable, field_options: nil)
base_field_options = {
name: :nodes,
type: [@node_type, null: nullable],
null: nullable,
description: "A list of nodes.",
connection: false,
# Assume that the connection was scoped before this step:
scope: false,
}
if field_options
base_field_options.merge!(field_options)
end
field(**base_field_options)
end
end
class << self
def add_page_info_field(obj_type)
obj_type.field :page_info, GraphQL::Types::Relay::PageInfo, null: false, description: "Information to aid in pagination."
end
end
def edges
# Assume that whatever authorization needed to happen
# already happened at the connection level.
current_runtime_state = Fiber[:__graphql_runtime_info]
query_runtime_state = current_runtime_state[context.query]
query_runtime_state.was_authorized_by_scope_items = @object.was_authorized_by_scope_items?
@object.edges
end
def nodes
# Assume that whatever authorization needed to happen
# already happened at the connection level.
current_runtime_state = Fiber[:__graphql_runtime_info]
query_runtime_state = current_runtime_state[context.query]
query_runtime_state.was_authorized_by_scope_items = @object.was_authorized_by_scope_items?
@object.nodes
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/has_node_field.rb | lib/graphql/types/relay/has_node_field.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
# Include this module to your root Query type to get a Relay-compliant `node(id: ID!): Node` field that uses the schema's `object_from_id` hook.
module HasNodeField
def self.included(child_class)
child_class.field(**field_options, &field_block)
end
class << self
def field_options
{
name: "node",
type: GraphQL::Types::Relay::Node,
null: true,
description: "Fetches an object given its ID.",
relay_node_field: true,
}
end
def field_block
Proc.new {
argument :id, "ID!",
description: "ID of the object."
def resolve(obj, args, ctx)
ctx.schema.object_from_id(args[:id], ctx)
end
def resolve_field(obj, args, ctx)
resolve(obj, args, ctx)
end
}
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/base_edge.rb | lib/graphql/types/relay/base_edge.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
# A class-based definition for Relay edges.
#
# Use this as a parent class in your app, or use it as inspiration for your
# own base `Edge` class.
#
# For example, you may want to extend your own `BaseObject` instead of the
# built-in `GraphQL::Schema::Object`.
#
# @example Making a UserEdge type
# # Make a base class for your app
# class Types::BaseEdge < GraphQL::Types::Relay::BaseEdge
# end
#
# # Then extend your own base class
# class Types::UserEdge < Types::BaseEdge
# node_type(Types::User)
# end
#
# @see {Relay::BaseConnection} for connection types
class BaseEdge < GraphQL::Schema::Object
include Types::Relay::EdgeBehaviors
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/page_info.rb | lib/graphql/types/relay/page_info.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
# The return type of a connection's `pageInfo` field
class PageInfo < GraphQL::Schema::Object
include PageInfoBehaviors
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/edge_behaviors.rb | lib/graphql/types/relay/edge_behaviors.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
module EdgeBehaviors
def self.included(child_class)
child_class.description("An edge in a connection.")
child_class.field(:cursor, String, null: false, description: "A cursor for use in pagination.")
child_class.extend(ClassMethods)
child_class.class_exec { self.node_type = nil }
child_class.node_nullable(true)
child_class.default_broadcastable(nil)
end
def node
current_runtime_state = Fiber[:__graphql_runtime_info]
query_runtime_state = current_runtime_state[context.query]
query_runtime_state.was_authorized_by_scope_items = @object.was_authorized_by_scope_items?
@object.node
end
module ClassMethods
def inherited(child_class)
super
child_class.node_type = nil
child_class.node_nullable = nil
child_class.default_broadcastable(default_broadcastable?)
end
def default_relay?
true
end
def default_broadcastable?
@default_broadcastable
end
def default_broadcastable(new_value)
@default_broadcastable = new_value
end
# Get or set the Object type that this edge wraps.
#
# @param node_type [Class] A `Schema::Object` subclass
# @param null [Boolean]
# @param field_options [Hash] Any extra arguments to pass to the `field :node` configuration
def node_type(node_type = nil, null: self.node_nullable, field_options: nil)
if node_type
@node_type = node_type
# Add a default `node` field
base_field_options = {
name: :node,
type: node_type,
null: null,
description: "The item at the end of the edge.",
connection: false,
}
if field_options
base_field_options.merge!(field_options)
end
field(**base_field_options)
end
@node_type
end
def authorized?(obj, ctx)
true
end
def visible?(ctx)
node_type.visible?(ctx)
end
# Set the default `node_nullable` for this class and its child classes. (Defaults to `true`.)
# Use `node_nullable(false)` in your base class to make non-null `node` field.
def node_nullable(new_value = nil)
if new_value.nil?
@node_nullable != nil ? @node_nullable : superclass.node_nullable
else
@node_nullable = new_value
end
end
protected
attr_writer :node_type, :node_nullable
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/node.rb | lib/graphql/types/relay/node.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
# This can be used for Relay's `Node` interface,
# or you can take it as inspiration for your own implementation
# of the `Node` interface.
module Node
include GraphQL::Schema::Interface
include Types::Relay::NodeBehaviors
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/node_behaviors.rb | lib/graphql/types/relay/node_behaviors.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
module NodeBehaviors
def self.included(child_module)
child_module.extend(ClassMethods)
child_module.description("An object with an ID.")
child_module.field(:id, ID, null: false, description: "ID of the object.", resolver_method: :default_global_id)
end
def default_global_id
context.schema.id_from_object(object, self.class, context)
end
module ClassMethods
def default_relay?
true
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/base_connection.rb | lib/graphql/types/relay/base_connection.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
# Use this to implement Relay connections, or take it as inspiration
# for Relay classes in your own app.
#
# You may wish to copy this code into your own base class,
# so you can extend your own `BaseObject` instead of `GraphQL::Schema::Object`.
#
# @example Implementation a connection and edge
# class BaseObject < GraphQL::Schema::Object; end
#
# # Given some object in your app ...
# class Types::Post < BaseObject
# end
#
# # Make a couple of base classes:
# class Types::BaseEdge < GraphQL::Types::Relay::BaseEdge; end
# class Types::BaseConnection < GraphQL::Types::Relay::BaseConnection; end
#
# # Then extend them for the object in your app
# class Types::PostEdge < Types::BaseEdge
# node_type Types::Post
# end
#
# class Types::PostConnection < Types::BaseConnection
# edge_type Types::PostEdge,
# edges_nullable: true,
# edge_nullable: true,
# node_nullable: true,
# nodes_field: true
#
# # Alternatively, you can call the class methods followed by your edge type
# # edges_nullable true
# # edge_nullable true
# # node_nullable true
# # has_nodes_field true
# # edge_type Types::PostEdge
# end
#
# @see Relay::BaseEdge for edge types
class BaseConnection < Schema::Object
include ConnectionBehaviors
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/has_nodes_field.rb | lib/graphql/types/relay/has_nodes_field.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
# Include this module to your root Query type to get a Relay-style `nodes(id: ID!): [Node]` field that uses the schema's `object_from_id` hook.
module HasNodesField
def self.included(child_class)
child_class.field(**field_options, &field_block)
end
class << self
def field_options
{
name: "nodes",
type: [GraphQL::Types::Relay::Node, null: true],
null: false,
description: "Fetches a list of objects given a list of IDs.",
relay_nodes_field: true,
}
end
def field_block
Proc.new {
argument :ids, "[ID!]!",
description: "IDs of the objects."
def resolve(obj, args, ctx)
args[:ids].map { |id| ctx.schema.object_from_id(id, ctx) }
end
def resolve_field(obj, args, ctx)
resolve(obj, args, ctx)
end
}
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types/relay/page_info_behaviors.rb | lib/graphql/types/relay/page_info_behaviors.rb | # frozen_string_literal: true
module GraphQL
module Types
module Relay
module PageInfoBehaviors
def self.included(child_class)
child_class.extend ClassMethods
child_class.description "Information about pagination in a connection."
child_class.field :has_next_page, Boolean, null: false,
description: "When paginating forwards, are there more items?"
child_class.field :has_previous_page, Boolean, null: false,
description: "When paginating backwards, are there more items?"
child_class.field :start_cursor, String, null: true,
description: "When paginating backwards, the cursor to continue."
child_class.field :end_cursor, String, null: true,
description: "When paginating forwards, the cursor to continue."
end
end
module ClassMethods
def default_relay?
true
end
def default_broadcastable?
true
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dashboard/limiters.rb | lib/graphql/dashboard/limiters.rb | # frozen_string_literal: true
require_relative "./installable"
module Graphql
class Dashboard < Rails::Engine
module Limiters
class LimitersController < Dashboard::ApplicationController
include Installable
FALLBACK_CSP_NONCE_GENERATOR = ->(_req) { SecureRandom.hex(32) }
def show
name = params[:name]
@title = case name
when "runtime"
"Runtime Limiter"
when "active_operations"
"Active Operation Limiter"
when "mutations"
"Mutation Limiter"
else
raise ArgumentError, "Unknown limiter name: #{name}"
end
limiter = limiter_for(name)
if limiter.nil?
@install_path = "http://graphql-ruby.org/limiters/#{name}"
else
@chart_mode = params[:chart] || "day"
@current_soft = limiter.soft_limit_enabled?
@histogram = limiter.dashboard_histogram(@chart_mode)
# These configs may have already been defined by the application; provide overrides here if not.
request.content_security_policy_nonce_generator ||= FALLBACK_CSP_NONCE_GENERATOR
nonce_dirs = request.content_security_policy_nonce_directives || []
if !nonce_dirs.include?("style-src")
nonce_dirs += ["style-src"]
request.content_security_policy_nonce_directives = nonce_dirs
end
@csp_nonce = request.content_security_policy_nonce
end
end
def update
name = params[:name]
limiter = limiter_for(name)
if limiter
limiter.toggle_soft_limit
flash[:success] = if limiter.soft_limit_enabled?
"Enabled soft limiting -- over-limit traffic will be logged but not rejected."
else
"Disabled soft limiting -- over-limit traffic will be rejected."
end
else
flash[:warning] = "No limiter configured for #{name.inspect}"
end
redirect_to graphql_dashboard.limiters_limiter_path(name, chart: params[:chart])
end
private
def limiter_for(name)
case name
when "runtime"
schema_class.enterprise_runtime_limiter
when "active_operations"
schema_class.enterprise_active_operation_limiter
when "mutations"
schema_class.enterprise_mutation_limiter
else
raise ArgumentError, "Unknown limiter: #{name}"
end
end
def feature_installed?
defined?(GraphQL::Enterprise::Limiter) &&
(
schema_class.enterprise_active_operation_limiter ||
schema_class.enterprise_runtime_limiter ||
(schema_class.respond_to?(:enterprise_mutation_limiter) && schema_class.enterprise_mutation_limiter)
)
end
INSTALLABLE_COMPONENT_HEADER_HTML = "Rate limiters aren't installed on this schema yet."
INSTALLABLE_COMPONENT_MESSAGE_HTML = <<-HTML.html_safe
Check out the docs to get started with GraphQL-Enterprise's
<a href="https://graphql-ruby.org/limiters/runtime.html">runtime limiter</a> or
<a href="https://graphql-ruby.org/limiters/active_operations.html">active operation limiter</a>.
HTML
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dashboard/installable.rb | lib/graphql/dashboard/installable.rb | # frozen_string_literal: true
module Graphql
class Dashboard < Rails::Engine
module Installable
def self.included(child_module)
child_module.before_action(:check_installed)
end
def feature_installed?
raise "Implement #{self.class}#feature_installed? to check whether this should render `not_installed` or not."
end
def check_installed
if !feature_installed?
@component_header_html = self.class::INSTALLABLE_COMPONENT_HEADER_HTML
@component_message_html = self.class::INSTALLABLE_COMPONENT_MESSAGE_HTML
render "graphql/dashboard/not_installed"
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dashboard/operation_store.rb | lib/graphql/dashboard/operation_store.rb | # frozen_string_literal: true
require_relative "./installable"
module Graphql
class Dashboard < Rails::Engine
module OperationStore
class BaseController < Dashboard::ApplicationController
include Installable
private
def feature_installed?
schema_class.respond_to?(:operation_store) && schema_class.operation_store.is_a?(GraphQL::Pro::OperationStore)
end
INSTALLABLE_COMPONENT_HEADER_HTML = "<code>OperationStore</code> isn't installed for this schema yet.".html_safe
INSTALLABLE_COMPONENT_MESSAGE_HTML = <<-HTML.html_safe
Learn more about improving performance and security with stored operations
in the <a href="https://graphql-ruby.org/operation_store/overview.html"><code>OperationStore</code> docs</a>.
HTML
end
class ClientsController < BaseController
def index
@order_by = params[:order_by] || "name"
@order_dir = params[:order_dir].presence || "asc"
clients_page = schema_class.operation_store.all_clients(
page: params[:page]&.to_i || 1,
per_page: params[:per_page]&.to_i || 25,
order_by: @order_by,
order_dir: @order_dir,
)
@clients_page = clients_page
end
def new
@client = init_client(secret: SecureRandom.hex(32))
end
def create
client_params = params.require(:client).permit(:name, :secret)
schema_class.operation_store.upsert_client(client_params[:name], client_params[:secret])
flash[:success] = "Created #{client_params[:name].inspect}"
redirect_to graphql_dashboard.operation_store_clients_path
end
def edit
@client = schema_class.operation_store.get_client(params[:name])
end
def update
client_name = params[:name]
client_secret = params.require(:client).permit(:secret)[:secret]
schema_class.operation_store.upsert_client(client_name, client_secret)
flash[:success] = "Updated #{client_name.inspect}"
redirect_to graphql_dashboard.operation_store_clients_path
end
def destroy
client_name = params[:name]
schema_class.operation_store.delete_client(client_name)
flash[:success] = "Deleted #{client_name.inspect}"
redirect_to graphql_dashboard.operation_store_clients_path
end
private
def init_client(name: nil, secret: nil)
GraphQL::Pro::OperationStore::ClientRecord.new(
name: name,
secret: secret,
created_at: nil,
operations_count: 0,
archived_operations_count: 0,
last_synced_at: nil,
last_used_at: nil,
)
end
end
class OperationsController < BaseController
def index
@client_operations = client_name = params[:client_name]
per_page = params[:per_page]&.to_i || 25
page = params[:page]&.to_i || 1
@is_archived = params[:archived_status] == :archived
order_by = params[:order_by] || "name"
order_dir = params[:order_dir]&.to_sym || :asc
if @client_operations
@operations_page = schema_class.operation_store.get_client_operations_by_client(
client_name,
page: page,
per_page: per_page,
is_archived: @is_archived,
order_by: order_by,
order_dir: order_dir,
)
opposite_archive_mode_count = schema_class.operation_store.get_client_operations_by_client(
client_name,
page: 1,
per_page: 1,
is_archived: !@is_archived,
order_by: order_by,
order_dir: order_dir,
).total_count
else
@operations_page = schema_class.operation_store.all_operations(
page: page,
per_page: per_page,
is_archived: @is_archived,
order_by: order_by,
order_dir: order_dir,
)
opposite_archive_mode_count = schema_class.operation_store.all_operations(
page: 1,
per_page: 1,
is_archived: !@is_archived,
order_by: order_by,
order_dir: order_dir,
).total_count
end
if @is_archived
@archived_operations_count = @operations_page.total_count
@unarchived_operations_count = opposite_archive_mode_count
else
@archived_operations_count = opposite_archive_mode_count
@unarchived_operations_count = @operations_page.total_count
end
end
def show
digest = params[:digest]
@operation = schema_class.operation_store.get_operation_by_digest(digest)
if @operation
# Parse & re-format the query
document = GraphQL.parse(@operation.body)
@graphql_source = document.to_query_string
@client_operations = schema_class.operation_store.get_client_operations_by_digest(digest)
@entries = schema_class.operation_store.get_index_entries_by_digest(digest)
end
end
def update
is_archived = case params[:modification]
when :archive
true
when :unarchive
false
else
raise ArgumentError, "Unexpected modification: #{params[:modification].inspect}"
end
if (client_name = params[:client_name])
operation_aliases = params[:operation_aliases]
schema_class.operation_store.archive_client_operations(
client_name: client_name,
operation_aliases: operation_aliases,
is_archived: is_archived
)
flash[:success] = "#{is_archived ? "Archived" : "Activated"} #{operation_aliases.size} #{"operation".pluralize(operation_aliases.size)}"
else
digests = params[:digests]
schema_class.operation_store.archive_operations(
digests: digests,
is_archived: is_archived
)
flash[:success] = "#{is_archived ? "Archived" : "Activated"} #{digests.size} #{"operation".pluralize(digests.size)}"
end
head :no_content
end
end
class IndexEntriesController < BaseController
def index
@search_term = if request.params["q"] && request.params["q"].length > 0
request.params["q"]
else
nil
end
@index_entries_page = schema_class.operation_store.all_index_entries(
search_term: @search_term,
page: params[:page]&.to_i || 1,
per_page: params[:per_page]&.to_i || 25,
)
end
def show
name = params[:name]
@entry = schema_class.operation_store.index.get_entry(name)
@chain = schema_class.operation_store.index.index_entry_chain(name)
@operations = schema_class.operation_store.get_operations_by_index_entry(name)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dashboard/detailed_traces.rb | lib/graphql/dashboard/detailed_traces.rb | # frozen_string_literal: true
require_relative "./installable"
module Graphql
class Dashboard < Rails::Engine
module DetailedTraces
class TracesController < Graphql::Dashboard::ApplicationController
include Installable
def index
@last = params[:last]&.to_i || 50
@before = params[:before]&.to_i
@traces = schema_class.detailed_trace.traces(last: @last, before: @before)
end
def show
trace = schema_class.detailed_trace.find_trace(params[:id].to_i)
send_data(trace.trace_data)
end
def destroy
schema_class.detailed_trace.delete_trace(params[:id])
flash[:success] = "Trace deleted."
head :no_content
end
def delete_all
schema_class.detailed_trace.delete_all_traces
flash[:success] = "Deleted all traces."
head :no_content
end
private
def feature_installed?
!!schema_class.detailed_trace
end
INSTALLABLE_COMPONENT_HEADER_HTML = "Detailed traces aren't installed yet."
INSTALLABLE_COMPONENT_MESSAGE_HTML = <<~HTML.html_safe
GraphQL-Ruby can instrument production traffic and save tracing artifacts here for later review.
<br>
Read more in <a href="https://graphql-ruby.org/queries/tracing#detailed-traces">the detailed tracing docs</a>.
HTML
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dashboard/subscriptions.rb | lib/graphql/dashboard/subscriptions.rb | # frozen_string_literal: true
module Graphql
class Dashboard < Rails::Engine
module Subscriptions
class BaseController < Graphql::Dashboard::ApplicationController
include Installable
def feature_installed?
schema_class.subscriptions.is_a?(GraphQL::Pro::Subscriptions)
end
INSTALLABLE_COMPONENT_HEADER_HTML = "GraphQL-Pro Subscriptions aren't installed on this schema yet.".html_safe
INSTALLABLE_COMPONENT_MESSAGE_HTML = <<-HTML.html_safe
Deliver live updates over
<a href="https://graphql-ruby.org/subscriptions/pusher_implementation.html">Pusher</a> or
<a href="https://graphql-ruby.org/subscriptions/ably_implementation.html"> Ably</a>
with GraphQL-Pro's subscription integrations.
HTML
end
class TopicsController < BaseController
def show
topic_name = params[:name]
all_subscription_ids = []
schema_class.subscriptions.each_subscription_id(topic_name) do |sid|
all_subscription_ids << sid
end
page = params[:page]&.to_i || 1
limit = params[:per_page]&.to_i || 20
offset = limit * (page - 1)
subscription_ids = all_subscription_ids[offset, limit]
subs = schema_class.subscriptions.read_subscriptions(subscription_ids)
show_broadcast_subscribers_count = schema_class.subscriptions.show_broadcast_subscribers_count?
subs.each do |sub|
sub[:is_broadcast] = is_broadcast = schema_class.subscriptions.broadcast_subscription_id?(sub[:id])
if is_broadcast && show_broadcast_subscribers_count
sub[:subscribers_count] = sub_count =schema_class.subscriptions.count_broadcast_subscribed(sub[:id])
sub[:still_subscribed] = sub_count > 0
else
sub[:still_subscribed] = schema_class.subscriptions.still_subscribed?(sub[:id])
sub[:subscribers_count] = nil
end
end
@topic_last_triggered_at = schema_class.subscriptions.topic_last_triggered_at(topic_name)
@subscriptions = subs
@subscriptions_count = all_subscription_ids.size
@show_broadcast_subscribers_count = show_broadcast_subscribers_count
@has_next_page = all_subscription_ids.size > offset + limit ? page + 1 : false
end
def index
page = params[:page]&.to_i || 1
per_page = params[:per_page]&.to_i || 20
offset = per_page * (page - 1)
limit = per_page
topics, all_topics_count, has_next_page = schema_class.subscriptions.topics(offset: offset, limit: limit)
@topics = topics
@all_topics_count = all_topics_count
@has_next_page = has_next_page
@page = page
end
end
class SubscriptionsController < BaseController
def show
subscription_id = params[:id]
subscriptions = schema_class.subscriptions
query_data = subscriptions.read_subscription(subscription_id)
is_broadcast = subscriptions.broadcast_subscription_id?(subscription_id)
if is_broadcast && subscriptions.show_broadcast_subscribers_count?
subscribers_count = subscriptions.count_broadcast_subscribed(subscription_id)
is_still_subscribed = subscribers_count > 0
else
subscribers_count = nil
is_still_subscribed = subscriptions.still_subscribed?(subscription_id)
end
@query_data = query_data
@still_subscribed = is_still_subscribed
@is_broadcast = is_broadcast
@subscribers_count = subscribers_count
end
def clear_all
schema_class.subscriptions.clear
flash[:success] = "All subscription data cleared."
head :no_content
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/mongoid_relation_connection.rb | lib/graphql/pagination/mongoid_relation_connection.rb | # frozen_string_literal: true
require "graphql/pagination/relation_connection"
module GraphQL
module Pagination
class MongoidRelationConnection < Pagination::RelationConnection
def relation_offset(relation)
relation.options.skip
end
def relation_limit(relation)
relation.options.limit
end
def relation_count(relation)
relation.all.count(relation.options.slice(:limit, :skip))
end
def null_relation(relation)
relation.without_options.none
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/sequel_dataset_connection.rb | lib/graphql/pagination/sequel_dataset_connection.rb | # frozen_string_literal: true
require "graphql/pagination/relation_connection"
module GraphQL
module Pagination
# Customizes `RelationConnection` to work with `Sequel::Dataset`s.
class SequelDatasetConnection < Pagination::RelationConnection
private
def relation_offset(relation)
relation.opts[:offset]
end
def relation_limit(relation)
relation.opts[:limit]
end
def relation_count(relation)
# Remove order to make it faster
relation.order(nil).count
end
def null_relation(relation)
relation.where(false)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/array_connection.rb | lib/graphql/pagination/array_connection.rb | # frozen_string_literal: true
require "graphql/pagination/connection"
module GraphQL
module Pagination
class ArrayConnection < Pagination::Connection
def nodes
load_nodes
@nodes
end
def has_previous_page
load_nodes
@has_previous_page
end
def has_next_page
load_nodes
@has_next_page
end
def cursor_for(item)
idx = items.find_index(item) + 1
encode(idx.to_s)
end
private
def index_from_cursor(cursor)
decode(cursor).to_i
end
# Populate all the pagination info _once_,
# It doesn't do anything on subsequent calls.
def load_nodes
@nodes ||= begin
sliced_nodes = if before && after
end_idx = index_from_cursor(before) - 2
end_idx < 0 ? [] : items[index_from_cursor(after)..end_idx] || []
elsif before
end_idx = index_from_cursor(before) - 2
end_idx < 0 ? [] : items[0..end_idx] || []
elsif after
items[index_from_cursor(after)..-1] || []
else
items
end
@has_previous_page = if last
# There are items preceding the ones in this result
sliced_nodes.count > last
elsif after
# We've paginated into the Array a bit, there are some behind us
index_from_cursor(after) > 0
else
false
end
@has_next_page = if before
# The original array is longer than the `before` index
index_from_cursor(before) < items.length + 1
elsif first
# There are more items after these items
sliced_nodes.count > first
else
false
end
limited_nodes = sliced_nodes
limited_nodes = limited_nodes.first(first) if first
limited_nodes = limited_nodes.last(last) if last
limited_nodes
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/relation_connection.rb | lib/graphql/pagination/relation_connection.rb | # frozen_string_literal: true
require "graphql/pagination/connection"
module GraphQL
module Pagination
# A generic class for working with database query objects.
class RelationConnection < Pagination::Connection
def nodes
load_nodes
@nodes
end
def has_previous_page
if @has_previous_page.nil?
@has_previous_page = if after_offset && after_offset > 0
true
elsif last
# See whether there are any nodes _before_ the current offset.
# If there _is no_ current offset, then there can't be any nodes before it.
# Assume that if the offset is positive, there are nodes before the offset.
limited_nodes
!(@paged_nodes_offset.nil? || @paged_nodes_offset == 0)
else
false
end
end
@has_previous_page
end
def has_next_page
if @has_next_page.nil?
@has_next_page = if before_offset && before_offset > 0
true
elsif first
if @nodes && @nodes.count < first
false
else
relation_larger_than(sliced_nodes, @sliced_nodes_offset, first)
end
else
false
end
end
@has_next_page
end
def cursor_for(item)
load_nodes
# index in nodes + existing offset + 1 (because it's offset, not index)
offset = nodes.index(item) + 1 + (@paged_nodes_offset || 0) - (relation_offset(items) || 0)
encode(offset.to_s)
end
private
# @param relation [Object] A database query object
# @param _initial_offset [Integer] The number of items already excluded from the relation
# @param size [Integer] The value against which we check the relation size
# @return [Boolean] True if the number of items in this relation is larger than `size`
def relation_larger_than(relation, _initial_offset, size)
relation_count(set_limit(relation, size + 1)) == size + 1
end
# @param relation [Object] A database query object
# @return [Integer, nil] The offset value, or nil if there isn't one
def relation_offset(relation)
raise "#{self.class}#relation_offset(relation) must return the offset value for a #{relation.class} (#{relation.inspect})"
end
# @param relation [Object] A database query object
# @return [Integer, nil] The limit value, or nil if there isn't one
def relation_limit(relation)
raise "#{self.class}#relation_limit(relation) must return the limit value for a #{relation.class} (#{relation.inspect})"
end
# @param relation [Object] A database query object
# @return [Integer, nil] The number of items in this relation (hopefully determined without loading all records into memory!)
def relation_count(relation)
raise "#{self.class}#relation_count(relation) must return the count of records for a #{relation.class} (#{relation.inspect})"
end
# @param relation [Object] A database query object
# @return [Object] A modified query object which will return no records
def null_relation(relation)
raise "#{self.class}#null_relation(relation) must return an empty relation for a #{relation.class} (#{relation.inspect})"
end
# @return [Integer]
def offset_from_cursor(cursor)
decode(cursor).to_i
end
# Abstract this operation so we can always ignore inputs less than zero.
# (Sequel doesn't like it, understandably.)
def set_offset(relation, offset_value)
if offset_value >= 0
relation.offset(offset_value)
else
relation.offset(0)
end
end
# Abstract this operation so we can always ignore inputs less than zero.
# (Sequel doesn't like it, understandably.)
def set_limit(relation, limit_value)
if limit_value > 0
relation.limit(limit_value)
elsif limit_value == 0
null_relation(relation)
else
relation
end
end
def calculate_sliced_nodes_parameters
if defined?(@sliced_nodes_limit)
return
else
next_offset = relation_offset(items) || 0
relation_limit = relation_limit(items)
if after_offset
next_offset += after_offset
end
if before_offset && after_offset
if after_offset < before_offset
# Get the number of items between the two cursors
space_between = before_offset - after_offset - 1
relation_limit = space_between
else
# The cursors overextend one another to an empty set
@sliced_nodes_null_relation = true
end
elsif before_offset
# Use limit to cut off the tail of the relation
relation_limit = before_offset - 1
end
@sliced_nodes_limit = relation_limit
@sliced_nodes_offset = next_offset
end
end
# Apply `before` and `after` to the underlying `items`,
# returning a new relation.
def sliced_nodes
@sliced_nodes ||= begin
calculate_sliced_nodes_parameters
paginated_nodes = items
if @sliced_nodes_null_relation
paginated_nodes = null_relation(paginated_nodes)
else
if @sliced_nodes_limit
paginated_nodes = set_limit(paginated_nodes, @sliced_nodes_limit)
end
if @sliced_nodes_offset
paginated_nodes = set_offset(paginated_nodes, @sliced_nodes_offset)
end
end
paginated_nodes
end
end
# @return [Integer, nil]
def before_offset
@before_offset ||= before && offset_from_cursor(before)
end
# @return [Integer, nil]
def after_offset
@after_offset ||= after && offset_from_cursor(after)
end
# Apply `first` and `last` to `sliced_nodes`,
# returning a new relation
def limited_nodes
@limited_nodes ||= begin
calculate_sliced_nodes_parameters
if @sliced_nodes_null_relation
# it's an empty set
return sliced_nodes
end
relation_limit = @sliced_nodes_limit
relation_offset = @sliced_nodes_offset
if first && (relation_limit.nil? || relation_limit > first)
# `first` would create a stricter limit that the one already applied, so add it
relation_limit = first
end
if last
if relation_limit
if last <= relation_limit
# `last` is a smaller slice than the current limit, so apply it
relation_offset += (relation_limit - last)
relation_limit = last
end
else
# No limit, so get the last items
sliced_nodes_count = relation_count(sliced_nodes)
relation_offset += (sliced_nodes_count - [last, sliced_nodes_count].min)
relation_limit = last
end
end
@paged_nodes_offset = relation_offset
paginated_nodes = items
paginated_nodes = set_offset(paginated_nodes, relation_offset)
if relation_limit
paginated_nodes = set_limit(paginated_nodes, relation_limit)
end
paginated_nodes
end
end
# Load nodes after applying first/last/before/after,
# returns an array of nodes
def load_nodes
# Return an array so we can consistently use `.index(node)` on it
@nodes ||= limited_nodes.to_a
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/connection.rb | lib/graphql/pagination/connection.rb | # frozen_string_literal: true
module GraphQL
module Pagination
# A Connection wraps a list of items and provides cursor-based pagination over it.
#
# Connections were introduced by Facebook's `Relay` front-end framework, but
# proved to be generally useful for GraphQL APIs. When in doubt, use connections
# to serve lists (like Arrays, ActiveRecord::Relations) via GraphQL.
#
# Unlike the previous connection implementation, these default to bidirectional pagination.
#
# Pagination arguments and context may be provided at initialization or assigned later (see {Schema::Field::ConnectionExtension}).
class Connection
class PaginationImplementationMissingError < GraphQL::Error
end
# @return [Object] A list object, from the application. This is the unpaginated value passed into the connection.
attr_reader :items
# @return [GraphQL::Query::Context]
attr_reader :context
def context=(new_ctx)
@context = new_ctx
if @was_authorized_by_scope_items.nil?
@was_authorized_by_scope_items = detect_was_authorized_by_scope_items
end
@context
end
# @return [Object] the object this collection belongs to
attr_accessor :parent
# Raw access to client-provided values. (`max_page_size` not applied to first or last.)
attr_accessor :before_value, :after_value, :first_value, :last_value
# @return [String, nil] the client-provided cursor. `""` is treated as `nil`.
def before
if defined?(@before)
@before
else
@before = @before_value == "" ? nil : @before_value
end
end
# @return [String, nil] the client-provided cursor. `""` is treated as `nil`.
def after
if defined?(@after)
@after
else
@after = @after_value == "" ? nil : @after_value
end
end
# @return [Hash<Symbol => Object>] The field arguments from the field that returned this connection
attr_accessor :arguments
# @param items [Object] some unpaginated collection item, like an `Array` or `ActiveRecord::Relation`
# @param context [Query::Context]
# @param parent [Object] The object this collection belongs to
# @param first [Integer, nil] The limit parameter from the client, if it provided one
# @param after [String, nil] A cursor for pagination, if the client provided one
# @param last [Integer, nil] Limit parameter from the client, if provided
# @param before [String, nil] A cursor for pagination, if the client provided one.
# @param arguments [Hash] The arguments to the field that returned the collection wrapped by this connection
# @param max_page_size [Integer, nil] A configured value to cap the result size. Applied as `first` if neither first or last are given and no `default_page_size` is set.
# @param default_page_size [Integer, nil] A configured value to determine the result size when neither first or last are given.
def initialize(items, parent: nil, field: nil, context: nil, first: nil, after: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, last: nil, before: nil, edge_class: nil, arguments: nil)
@items = items
@parent = parent
@context = context
@field = field
@first_value = first
@after_value = after
@last_value = last
@before_value = before
@arguments = arguments
@edge_class = edge_class || self.class::Edge
# This is only true if the object was _initialized_ with an override
# or if one is assigned later.
@has_max_page_size_override = max_page_size != NOT_CONFIGURED
@max_page_size = if max_page_size == NOT_CONFIGURED
nil
else
max_page_size
end
@has_default_page_size_override = default_page_size != NOT_CONFIGURED
@default_page_size = if default_page_size == NOT_CONFIGURED
nil
else
default_page_size
end
@was_authorized_by_scope_items = detect_was_authorized_by_scope_items
end
def was_authorized_by_scope_items?
@was_authorized_by_scope_items
end
def max_page_size=(new_value)
@has_max_page_size_override = true
@max_page_size = new_value
end
def max_page_size
if @has_max_page_size_override
@max_page_size
else
context.schema.default_max_page_size
end
end
def has_max_page_size_override?
@has_max_page_size_override
end
def default_page_size=(new_value)
@has_default_page_size_override = true
@default_page_size = new_value
end
def default_page_size
if @has_default_page_size_override
@default_page_size
else
context.schema.default_page_size
end
end
def has_default_page_size_override?
@has_default_page_size_override
end
attr_writer :first
# @return [Integer, nil]
# A clamped `first` value.
# (The underlying instance variable doesn't have limits on it.)
# If neither `first` nor `last` is given, but `default_page_size` is
# present, default_page_size is used for first. If `default_page_size`
# is greater than `max_page_size``, it'll be clamped down to
# `max_page_size`. If `default_page_size` is nil, use `max_page_size`.
def first
@first ||= begin
capped = limit_pagination_argument(@first_value, max_page_size)
if capped.nil? && last.nil?
capped = limit_pagination_argument(default_page_size, max_page_size) || max_page_size
end
capped
end
end
# This is called by `Relay::RangeAdd` -- it can be overridden
# when `item` needs some modifications based on this connection's state.
#
# @param item [Object] An item newly added to `items`
# @return [Edge]
def range_add_edge(item)
edge_class.new(item, self)
end
attr_writer :last
# @return [Integer, nil] A clamped `last` value. (The underlying instance variable doesn't have limits on it)
def last
@last ||= limit_pagination_argument(@last_value, max_page_size)
end
# @return [Array<Edge>] {nodes}, but wrapped with Edge instances
def edges
@edges ||= nodes.map { |n| @edge_class.new(n, self) }
end
# @return [Class] A wrapper class for edges of this connection
attr_accessor :edge_class
# @return [GraphQL::Schema::Field] The field this connection was returned by
attr_accessor :field
# @return [Array<Object>] A slice of {items}, constrained by {@first_value}/{@after_value}/{@last_value}/{@before_value}
def nodes
raise PaginationImplementationMissingError, "Implement #{self.class}#nodes to paginate `@items`"
end
# A dynamic alias for compatibility with {Relay::BaseConnection}.
# @deprecated use {#nodes} instead
def edge_nodes
nodes
end
# The connection object itself implements `PageInfo` fields
def page_info
self
end
# @return [Boolean] True if there are more items after this page
def has_next_page
raise PaginationImplementationMissingError, "Implement #{self.class}#has_next_page to return the next-page check"
end
# @return [Boolean] True if there were items before these items
def has_previous_page
raise PaginationImplementationMissingError, "Implement #{self.class}#has_previous_page to return the previous-page check"
end
# @return [String] The cursor of the first item in {nodes}
def start_cursor
nodes.first && cursor_for(nodes.first)
end
# @return [String] The cursor of the last item in {nodes}
def end_cursor
nodes.last && cursor_for(nodes.last)
end
# Return a cursor for this item.
# @param item [Object] one of the passed in {items}, taken from {nodes}
# @return [String]
def cursor_for(item)
raise PaginationImplementationMissingError, "Implement #{self.class}#cursor_for(item) to return the cursor for #{item.inspect}"
end
private
def detect_was_authorized_by_scope_items
if @context &&
(current_runtime_state = Fiber[:__graphql_runtime_info]) &&
(query_runtime_state = current_runtime_state[@context.query])
query_runtime_state.was_authorized_by_scope_items
else
nil
end
end
# @param argument [nil, Integer] `first` or `last`, as provided by the client
# @param max_page_size [nil, Integer]
# @return [nil, Integer] `nil` if the input was `nil`, otherwise a value between `0` and `max_page_size`
def limit_pagination_argument(argument, max_page_size)
if argument
if argument < 0
argument = 0
elsif max_page_size && argument > max_page_size
argument = max_page_size
end
end
argument
end
def decode(cursor)
context.schema.cursor_encoder.decode(cursor, nonce: true)
end
def encode(cursor)
context.schema.cursor_encoder.encode(cursor, nonce: true)
end
# A wrapper around paginated items. It includes a {cursor} for pagination
# and could be extended with custom relationship-level data.
class Edge
attr_reader :node
def initialize(node, connection)
@connection = connection
@node = node
end
def parent
@connection.parent
end
def cursor
@cursor ||= @connection.cursor_for(@node)
end
def was_authorized_by_scope_items?
@connection.was_authorized_by_scope_items?
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/connections.rb | lib/graphql/pagination/connections.rb | # frozen_string_literal: true
module GraphQL
module Pagination
# A schema-level connection wrapper manager.
#
# Attach as a plugin.
#
# @example Adding a custom wrapper
# class MySchema < GraphQL::Schema
# connections.add(MyApp::SearchResults, MyApp::SearchResultsConnection)
# end
#
# @example Removing default connection support for arrays (they can still be manually wrapped)
# class MySchema < GraphQL::Schema
# connections.delete(Array)
# end
#
# @see {Schema.connections}
class Connections
class ImplementationMissingError < GraphQL::Error
end
def initialize(schema:)
@schema = schema
@wrappers = {}
add_default
end
def add(nodes_class, implementation)
@wrappers[nodes_class] = implementation
end
def delete(nodes_class)
@wrappers.delete(nodes_class)
end
def all_wrappers
all_wrappers = {}
@schema.ancestors.reverse_each do |schema_class|
if schema_class.respond_to?(:connections) && (c = schema_class.connections)
all_wrappers.merge!(c.wrappers)
end
end
all_wrappers
end
def wrapper_for(items, wrappers: all_wrappers)
impl = nil
items.class.ancestors.each { |cls|
impl = wrappers[cls]
break if impl
}
impl
end
# Used by the runtime to wrap values in connection wrappers.
# @api Private
def wrap(field, parent, items, arguments, context)
return items if GraphQL::Execution::Interpreter::RawValue === items
wrappers = context ? context.namespace(:connections)[:all_wrappers] : all_wrappers
impl = wrapper_for(items, wrappers: wrappers)
if impl
impl.new(
items,
context: context,
parent: parent,
field: field,
max_page_size: field.has_max_page_size? ? field.max_page_size : context.schema.default_max_page_size,
default_page_size: field.has_default_page_size? ? field.default_page_size : context.schema.default_page_size,
first: arguments[:first],
after: arguments[:after],
last: arguments[:last],
before: arguments[:before],
arguments: arguments,
edge_class: edge_class_for_field(field),
)
else
raise ImplementationMissingError, "Couldn't find a connection wrapper for #{items.class} during #{field.path} (#{items.inspect})"
end
end
# use an override if there is one
# @api private
def edge_class_for_field(field)
conn_type = field.type.unwrap
conn_type_edge_type = conn_type.respond_to?(:edge_class) && conn_type.edge_class
if conn_type_edge_type && conn_type_edge_type != Pagination::Connection::Edge
conn_type_edge_type
else
nil
end
end
protected
attr_reader :wrappers
private
def add_default
add(Array, Pagination::ArrayConnection)
if defined?(ActiveRecord::Relation)
add(ActiveRecord::Relation, Pagination::ActiveRecordRelationConnection)
end
if defined?(Sequel::Dataset)
add(Sequel::Dataset, Pagination::SequelDatasetConnection)
end
if defined?(Mongoid::Criteria)
add(Mongoid::Criteria, Pagination::MongoidRelationConnection)
end
# Mongoid 5 and 6
if defined?(Mongoid::Relations::Targets::Enumerable)
add(Mongoid::Relations::Targets::Enumerable, Pagination::MongoidRelationConnection)
end
# Mongoid 7
if defined?(Mongoid::Association::Referenced::HasMany::Targets::Enumerable)
add(Mongoid::Association::Referenced::HasMany::Targets::Enumerable, Pagination::MongoidRelationConnection)
end
# Mongoid 7.3+
if defined?(Mongoid::Association::Referenced::HasMany::Enumerable)
add(Mongoid::Association::Referenced::HasMany::Enumerable, Pagination::MongoidRelationConnection)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination/active_record_relation_connection.rb | lib/graphql/pagination/active_record_relation_connection.rb | # frozen_string_literal: true
require "graphql/pagination/relation_connection"
module GraphQL
module Pagination
# Customizes `RelationConnection` to work with `ActiveRecord::Relation`s.
class ActiveRecordRelationConnection < Pagination::RelationConnection
private
def relation_count(relation)
int_or_hash = if already_loaded?(relation)
relation.size
elsif relation.respond_to?(:unscope)
relation.unscope(:order).count(:all)
else
# Rails 3
relation.count
end
if int_or_hash.is_a?(Integer)
int_or_hash
else
# Grouped relations return count-by-group hashes
int_or_hash.length
end
end
def relation_limit(relation)
if relation.is_a?(Array)
nil
else
relation.limit_value
end
end
def relation_offset(relation)
if relation.is_a?(Array)
nil
else
relation.offset_value
end
end
def null_relation(relation)
if relation.respond_to?(:none)
relation.none
else
# Rails 3
relation.where("1=2")
end
end
def set_limit(nodes, limit)
if already_loaded?(nodes)
nodes.take(limit)
else
super
end
end
def set_offset(nodes, offset)
if already_loaded?(nodes)
# If the client sent a bogus cursor beyond the size of the relation,
# it might get `nil` from `#[...]`, so return an empty array in that case
nodes[offset..-1] || []
else
super
end
end
private
def already_loaded?(relation)
relation.is_a?(Array) || relation.loaded?
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/testing/helpers.rb | lib/graphql/testing/helpers.rb | # frozen_string_literal: true
module GraphQL
module Testing
module Helpers
# @param schema_class [Class<GraphQL::Schema>]
# @return [Module] A helpers module which always uses the given schema
def self.for(schema_class)
SchemaHelpers.for(schema_class)
end
class Error < GraphQL::Error
end
class TypeNotVisibleError < Error
def initialize(type_name:)
message = "`#{type_name}` should be `visible?` this field resolution and `context`, but it was not"
super(message)
end
end
class FieldNotVisibleError < Error
def initialize(type_name:, field_name:)
message = "`#{type_name}.#{field_name}` should be `visible?` for this resolution, but it was not"
super(message)
end
end
class TypeNotDefinedError < Error
def initialize(type_name:)
message = "No type named `#{type_name}` is defined; choose another type name or define this type."
super(message)
end
end
class FieldNotDefinedError < Error
def initialize(type_name:, field_name:)
message = "`#{type_name}` has no field named `#{field_name}`; pick another name or define this field."
super(message)
end
end
def run_graphql_field(schema, field_path, object, arguments: {}, context: {}, ast_node: nil, lookahead: nil, visibility_profile: nil)
type_name, *field_names = field_path.split(".")
dummy_query = GraphQL::Query.new(schema, "{ __typename }", context: context, visibility_profile: visibility_profile)
query_context = dummy_query.context
dataloader = query_context.dataloader
object_type = dummy_query.types.type(type_name) # rubocop:disable Development/ContextIsPassedCop
if object_type
graphql_result = object
field_names.each do |field_name|
inner_object = graphql_result
dataloader.run_isolated {
graphql_result = object_type.wrap(inner_object, query_context)
}
if graphql_result.nil?
return nil
end
visible_field = dummy_query.types.field(object_type, field_name) # rubocop:disable Development/ContextIsPassedCop
if visible_field
dataloader.run_isolated {
query_context[:current_field] = visible_field
field_args = visible_field.coerce_arguments(graphql_result, arguments, query_context)
field_args = schema.sync_lazy(field_args)
if !visible_field.extras.empty?
extra_args = {}
visible_field.extras.each do |extra|
extra_args[extra] = case extra
when :ast_node
ast_node ||= GraphQL::Language::Nodes::Field.new(name: visible_field.graphql_name)
when :lookahead
lookahead ||= begin
ast_node ||= GraphQL::Language::Nodes::Field.new(name: visible_field.graphql_name)
Execution::Lookahead.new(
query: dummy_query,
ast_nodes: [ast_node],
field: visible_field,
)
end
else
raise ArgumentError, "This extra isn't supported in `run_graphql_field` yet: `#{extra.inspect}`. Open an issue on GitHub to request it: https://github.com/rmosolgo/graphql-ruby/issues/new"
end
end
field_args = field_args.merge_extras(extra_args)
end
graphql_result = visible_field.resolve(graphql_result, field_args.keyword_arguments, query_context)
graphql_result = schema.sync_lazy(graphql_result)
}
object_type = visible_field.type.unwrap
elsif object_type.all_field_definitions.any? { |f| f.graphql_name == field_name }
raise FieldNotVisibleError.new(field_name: field_name, type_name: type_name)
else
raise FieldNotDefinedError.new(type_name: type_name, field_name: field_name)
end
end
graphql_result
else
unfiltered_type = schema.use_visibility_profile? ? schema.visibility.get_type(type_name) : schema.get_type(type_name) # rubocop:disable Development/ContextIsPassedCop
if unfiltered_type
raise TypeNotVisibleError.new(type_name: type_name)
else
raise TypeNotDefinedError.new(type_name: type_name)
end
end
end
def with_resolution_context(schema, type:, object:, context:{}, visibility_profile: nil)
resolution_context = ResolutionAssertionContext.new(
self,
schema: schema,
type_name: type,
object: object,
context: context,
visibility_profile: visibility_profile,
)
yield(resolution_context)
end
class ResolutionAssertionContext
def initialize(test, type_name:, object:, schema:, context:, visibility_profile:)
@test = test
@type_name = type_name
@object = object
@schema = schema
@context = context
@visibility_profile = visibility_profile
end
attr_reader :visibility_profile
def run_graphql_field(field_name, arguments: {})
if @schema
@test.run_graphql_field(@schema, "#{@type_name}.#{field_name}", @object, arguments: arguments, context: @context, visibility_profile: @visibility_profile)
else
@test.run_graphql_field("#{@type_name}.#{field_name}", @object, arguments: arguments, context: @context, visibility_profile: @visibility_profile)
end
end
end
module SchemaHelpers
include Helpers
def run_graphql_field(field_path, object, arguments: {}, context: {}, visibility_profile: nil)
super(@@schema_class_for_helpers, field_path, object, arguments: arguments, context: context, visibility_profile: visibility_profile)
end
def with_resolution_context(*args, **kwargs, &block)
# schema will be added later
super(nil, *args, **kwargs, &block)
end
def self.for(schema_class)
Module.new do
include SchemaHelpers
@@schema_class_for_helpers = schema_class
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/testing/mock_action_cable.rb | lib/graphql/testing/mock_action_cable.rb | # frozen_string_literal: true
module GraphQL
module Testing
# A stub implementation of ActionCable.
# Any methods to support the mock backend have `mock` in the name.
#
# @example Configuring your schema to use MockActionCable in the test environment
# class MySchema < GraphQL::Schema
# # Use MockActionCable in test:
# use GraphQL::Subscriptions::ActionCableSubscriptions,
# action_cable: Rails.env.test? ? GraphQL::Testing::MockActionCable : ActionCable
# end
#
# @example Clearing old data before each test
# setup do
# GraphQL::Testing::MockActionCable.clear_mocks
# end
#
# @example Using MockActionCable in a test case
# # Create a channel to use in the test, pass it to GraphQL
# mock_channel = GraphQL::Testing::MockActionCable.get_mock_channel
# ActionCableTestSchema.execute("subscription { newsFlash { text } }", context: { channel: mock_channel })
#
# # Trigger a subscription update
# ActionCableTestSchema.subscriptions.trigger(:news_flash, {}, {text: "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"})
#
# # Check messages on the channel
# expected_msg = {
# result: {
# "data" => {
# "newsFlash" => {
# "text" => "After yesterday's rain, someone stopped on Rio Road to help a box turtle across five lanes of traffic"
# }
# }
# },
# more: true,
# }
# assert_equal [expected_msg], mock_channel.mock_broadcasted_messages
#
class MockActionCable
class MockChannel
def initialize
@mock_broadcasted_messages = []
end
# @return [Array<Hash>] Payloads "sent" to this channel by GraphQL-Ruby
attr_reader :mock_broadcasted_messages
# Called by ActionCableSubscriptions. Implements a Rails API.
def stream_from(stream_name, coder: nil, &block)
# Rails uses `coder`, we don't
block ||= ->(msg) { @mock_broadcasted_messages << msg }
MockActionCable.mock_stream_for(stream_name).add_mock_channel(self, block)
end
end
# Used by mock code
# @api private
class MockStream
def initialize
@mock_channels = {}
end
def add_mock_channel(channel, handler)
@mock_channels[channel] = handler
end
def mock_broadcast(message)
@mock_channels.each do |channel, handler|
handler && handler.call(message)
end
end
end
class << self
# Call this before each test run to make sure that MockActionCable's data is empty
def clear_mocks
@mock_streams = {}
end
# Implements Rails API
def server
self
end
# Implements Rails API
def broadcast(stream_name, message)
stream = @mock_streams[stream_name]
stream && stream.mock_broadcast(message)
end
# Used by mock code
def mock_stream_for(stream_name)
@mock_streams[stream_name] ||= MockStream.new
end
# Use this as `context[:channel]` to simulate an ActionCable channel
#
# @return [GraphQL::Testing::MockActionCable::MockChannel]
def get_mock_channel
MockChannel.new
end
# @return [Array<String>] Streams that currently have subscribers
def mock_stream_names
@mock_streams.keys
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/rake_task/validate.rb | lib/graphql/rake_task/validate.rb | # frozen_string_literal: true
module GraphQL
class RakeTask
extend Rake::DSL
desc "Get the checksum of a graphql-pro version and compare it to published versions on GitHub and graphql-ruby.org"
task "graphql:pro:validate", [:gem_version] do |t, args|
version = args[:gem_version]
if version.nil?
raise ArgumentError, "A specific version is required, eg `rake graphql:pro:validate[1.12.0]`"
end
check = "\e[32m✓\e[0m"
ex = "\e[31m✘\e[0m"
puts "Validating graphql-pro v#{version}"
puts " - Checking for graphql-pro credentials..."
creds = `bundle config gems.graphql.pro --parseable`[/[a-z0-9]{11}:[a-z0-9]{11}/]
if creds.nil?
puts " #{ex} failed, please set with `bundle config gems.graphql.pro $MY_CREDENTIALS`"
exit(1)
else
puts " #{check} found"
end
puts " - Fetching the gem..."
fetch_result = `gem fetch graphql-pro -v #{version} --source https://#{creds}@gems.graphql.pro`
if fetch_result.empty?
puts " #{ex} failed to fetch v#{version}"
exit(1)
else
puts " #{check} fetched"
end
puts " - Validating digest..."
require "digest/sha2"
gem_digest = Digest::SHA512.new.hexdigest(File.read("graphql-pro-#{version}.gem"))
require "net/http"
github_uri = URI("https://raw.githubusercontent.com/rmosolgo/graphql-ruby/master/guides/pro/checksums/graphql-pro-#{version}.txt")
# Remove final newline from .txt file
github_digest = Net::HTTP.get(github_uri).chomp
docs_uri = URI("https://graphql-ruby.org/pro/checksums/graphql-pro-#{version}.txt")
docs_digest = Net::HTTP.get(docs_uri).chomp
if docs_digest == gem_digest && github_digest == gem_digest
puts " #{check} validated from GitHub"
puts " #{check} validated from graphql-ruby.org"
else
puts " #{ex} SHA mismatch:"
puts " Downloaded: #{gem_digest}"
puts " GitHub: #{github_digest}"
puts " graphql-ruby.org: #{docs_digest}"
puts ""
puts " This download of graphql-pro is invalid, please open an issue:"
puts " https://github.com/rmosolgo/graphql-ruby/issues/new?title=graphql-pro%20digest%20mismatch%20(#{version})"
exit(1)
end
puts "\e[32m✔\e[0m graphql-pro #{version} validated successfully!"
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/backtrace/table.rb | lib/graphql/backtrace/table.rb | # frozen_string_literal: true
module GraphQL
class Backtrace
# A class for turning a context into a human-readable table or array
class Table
MIN_COL_WIDTH = 4
MAX_COL_WIDTH = 100
HEADERS = [
"Loc",
"Field",
"Object",
"Arguments",
"Result",
]
def initialize(context, value:)
@context = context
@override_value = value
end
# @return [String] A table layout of backtrace with metadata
def to_table
@to_table ||= render_table(rows)
end
# @return [Array<String>] An array of position + field name entries
def to_backtrace
@to_backtrace ||= begin
backtrace = rows.map { |r| "#{r[0]}: #{r[1]}" }
# skip the header entry
backtrace.shift
backtrace
end
end
private
def rows
@rows ||= begin
query = @context.query
query_ctx = @context
runtime_inst = query_ctx.namespace(:interpreter_runtime)[:runtime]
result = runtime_inst.instance_variable_get(:@response)
rows = []
result_path = []
last_part = nil
path = @context.current_path
path.each do |path_part|
value = value_at(runtime_inst, result_path)
if result_path.empty?
name = query.selected_operation.operation_type || "query"
if (n = query.selected_operation_name)
name += " #{n}"
end
args = query.variables
else
name = result.graphql_field.path
args = result.graphql_arguments
end
object = result.graphql_parent ? result.graphql_parent.graphql_application_value : result.graphql_application_value
object = object.object.inspect
rows << [
result.ast_node.position.join(":"),
name,
"#{object}",
args.to_h.inspect,
inspect_result(value),
]
result_path << path_part
if path_part == path.last
last_part = path_part
else
result = result[path_part]
end
end
object = result.graphql_application_value.object.inspect
ast_node = nil
result.graphql_selections.each do |s|
found_ast_node = find_ast_node(s, last_part)
if found_ast_node
ast_node = found_ast_node
break
end
end
if ast_node
field_defn = query.get_field(result.graphql_result_type, ast_node.name)
args = query.arguments_for(ast_node, field_defn).to_h
field_path = field_defn.path
if ast_node.alias
field_path += " as #{ast_node.alias}"
end
rows << [
ast_node.position.join(":"),
field_path,
"#{object}",
args.inspect,
inspect_result(@override_value)
]
end
rows << HEADERS
rows.reverse!
rows
end
end
def find_ast_node(node, last_part)
return nil unless node
return node if node.respond_to?(:alias) && node.respond_to?(:name) && (node.alias == last_part || node.name == last_part)
return nil unless node.respond_to?(:selections)
return nil if node.selections.nil? || node.selections.empty?
node.selections.each do |child|
child_ast_node = find_ast_node(child, last_part)
return child_ast_node if child_ast_node
end
nil
end
# @return [String]
def render_table(rows)
max = Array.new(HEADERS.length, MIN_COL_WIDTH)
rows.each do |row|
row.each_with_index do |col, idx|
col_len = col.length
max_len = max[idx]
if col_len > max_len
if col_len > MAX_COL_WIDTH
max[idx] = MAX_COL_WIDTH
else
max[idx] = col_len
end
end
end
end
table = "".dup
last_col_idx = max.length - 1
rows.each do |row|
table << row.map.each_with_index do |col, idx|
max_len = max[idx]
if idx < last_col_idx
col = col.ljust(max_len)
end
if col.length > max_len
col = col[0, max_len - 3] + "..."
end
col
end.join(" | ")
table << "\n"
end
table
end
def value_at(runtime, path)
response = runtime.final_result
path.each do |key|
response && (response = response[key])
end
response
end
def inspect_result(obj)
case obj
when Hash
"{" +
obj.map do |key, val|
"#{key}: #{inspect_truncated(val)}"
end.join(", ") +
"}"
when Array
"[" +
obj.map { |v| inspect_truncated(v) }.join(", ") +
"]"
else
inspect_truncated(obj)
end
end
def inspect_truncated(obj)
case obj
when Hash
"{...}"
when Array
"[...]"
when GraphQL::Execution::Lazy
"(unresolved)"
else
"#{obj.inspect}"
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/backtrace/traced_error.rb | lib/graphql/backtrace/traced_error.rb | # frozen_string_literal: true
module GraphQL
class Backtrace
# When {Backtrace} is enabled, raised errors are wrapped with {TracedError}.
class TracedError < GraphQL::Error
# @return [Array<String>] Printable backtrace of GraphQL error context
attr_reader :graphql_backtrace
# @return [GraphQL::Query::Context] The context at the field where the error was raised
attr_reader :context
MESSAGE_TEMPLATE = <<-MESSAGE
Unhandled error during GraphQL execution:
%{cause_message}
%{cause_backtrace}
%{cause_backtrace_more}
Use #cause to access the original exception (including #cause.backtrace).
GraphQL Backtrace:
%{graphql_table}
MESSAGE
# This many lines of the original Ruby backtrace
# are included in the message
CAUSE_BACKTRACE_PREVIEW_LENGTH = 10
def initialize(err, current_ctx)
@context = current_ctx
backtrace = Backtrace.new(current_ctx, value: err)
@graphql_backtrace = backtrace.to_a
cause_backtrace_preview = err.backtrace.first(CAUSE_BACKTRACE_PREVIEW_LENGTH).join("\n ")
cause_backtrace_remainder_length = err.backtrace.length - CAUSE_BACKTRACE_PREVIEW_LENGTH
cause_backtrace_more = if cause_backtrace_remainder_length < 0
""
elsif cause_backtrace_remainder_length == 1
"... and 1 more line\n"
else
"... and #{cause_backtrace_remainder_length} more lines\n"
end
message = MESSAGE_TEMPLATE % {
cause_message: err.message,
cause_backtrace: cause_backtrace_preview,
cause_backtrace_more: cause_backtrace_more,
graphql_table: backtrace.inspect,
}
super(message)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/definition_slice.rb | lib/graphql/language/definition_slice.rb | # frozen_string_literal: true
module GraphQL
module Language
module DefinitionSlice
extend self
def slice(document, name)
definitions = {}
document.definitions.each { |d| definitions[d.name] = d }
names = Set.new
DependencyVisitor.find_definition_dependencies(definitions, name, names)
definitions = document.definitions.select { |d| names.include?(d.name) }
Nodes::Document.new(definitions: definitions)
end
private
class DependencyVisitor < GraphQL::Language::StaticVisitor
def initialize(doc, definitions, names)
@names = names
@definitions = definitions
super(doc)
end
def on_fragment_spread(node, parent)
if fragment = @definitions[node.name]
self.class.find_definition_dependencies(@definitions, fragment.name, @names)
end
super
end
def self.find_definition_dependencies(definitions, name, names)
names.add(name)
visitor = self.new(definitions[name], definitions, names)
visitor.visit
nil
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/static_visitor.rb | lib/graphql/language/static_visitor.rb | # frozen_string_literal: true
module GraphQL
module Language
# Like `GraphQL::Language::Visitor` except it doesn't support
# making changes to the document -- only visiting it as-is.
class StaticVisitor
def initialize(document)
@document = document
end
# Visit `document` and all children
# @return [void]
def visit
# `@document` may be any kind of node:
visit_method = @document.visit_method
result = public_send(visit_method, @document, nil)
@result = if result.is_a?(Array)
result.first
else
# The node wasn't modified
@document
end
end
def on_document_children(document_node)
document_node.children.each do |child_node|
visit_method = child_node.visit_method
public_send(visit_method, child_node, document_node)
end
end
def on_field_children(new_node)
new_node.arguments.each do |arg_node| # rubocop:disable Development/ContextIsPassedCop
on_argument(arg_node, new_node)
end
visit_directives(new_node)
visit_selections(new_node)
end
def visit_directives(new_node)
new_node.directives.each do |dir_node|
on_directive(dir_node, new_node)
end
end
def visit_selections(new_node)
new_node.selections.each do |selection|
case selection
when GraphQL::Language::Nodes::Field
on_field(selection, new_node)
when GraphQL::Language::Nodes::InlineFragment
on_inline_fragment(selection, new_node)
when GraphQL::Language::Nodes::FragmentSpread
on_fragment_spread(selection, new_node)
else
raise ArgumentError, "Invariant: unexpected field selection #{selection.class} (#{selection.inspect})"
end
end
end
def on_fragment_definition_children(new_node)
visit_directives(new_node)
visit_selections(new_node)
end
alias :on_inline_fragment_children :on_fragment_definition_children
def on_operation_definition_children(new_node)
new_node.variables.each do |arg_node|
on_variable_definition(arg_node, new_node)
end
visit_directives(new_node)
visit_selections(new_node)
end
def on_argument_children(new_node)
new_node.children.each do |value_node|
case value_node
when Language::Nodes::VariableIdentifier
on_variable_identifier(value_node, new_node)
when Language::Nodes::InputObject
on_input_object(value_node, new_node)
when Language::Nodes::Enum
on_enum(value_node, new_node)
when Language::Nodes::NullValue
on_null_value(value_node, new_node)
else
raise ArgumentError, "Invariant: unexpected argument value node #{value_node.class} (#{value_node.inspect})"
end
end
end
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
# We don't use `alias` here because it breaks `super`
def self.make_visit_methods(ast_node_class)
node_method = ast_node_class.visit_method
children_of_type = ast_node_class.children_of_type
child_visit_method = :"#{node_method}_children"
class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
# The default implementation for visiting an AST node.
# It doesn't _do_ anything, but it continues to visiting the node's children.
# To customize this hook, override one of its make_visit_methods (or the base method?)
# in your subclasses.
#
# @param node [GraphQL::Language::Nodes::AbstractNode] the node being visited
# @param parent [GraphQL::Language::Nodes::AbstractNode, nil] the previously-visited node, or `nil` if this is the root node.
# @return [void]
def #{node_method}(node, parent)
#{
if method_defined?(child_visit_method)
"#{child_visit_method}(node)"
elsif children_of_type
children_of_type.map do |child_accessor, child_class|
"node.#{child_accessor}.each do |child_node|
#{child_class.visit_method}(child_node, node)
end"
end.join("\n")
else
""
end
}
end
RUBY
end
[
Language::Nodes::Argument,
Language::Nodes::Directive,
Language::Nodes::DirectiveDefinition,
Language::Nodes::DirectiveLocation,
Language::Nodes::Document,
Language::Nodes::Enum,
Language::Nodes::EnumTypeDefinition,
Language::Nodes::EnumTypeExtension,
Language::Nodes::EnumValueDefinition,
Language::Nodes::Field,
Language::Nodes::FieldDefinition,
Language::Nodes::FragmentDefinition,
Language::Nodes::FragmentSpread,
Language::Nodes::InlineFragment,
Language::Nodes::InputObject,
Language::Nodes::InputObjectTypeDefinition,
Language::Nodes::InputObjectTypeExtension,
Language::Nodes::InputValueDefinition,
Language::Nodes::InterfaceTypeDefinition,
Language::Nodes::InterfaceTypeExtension,
Language::Nodes::ListType,
Language::Nodes::NonNullType,
Language::Nodes::NullValue,
Language::Nodes::ObjectTypeDefinition,
Language::Nodes::ObjectTypeExtension,
Language::Nodes::OperationDefinition,
Language::Nodes::ScalarTypeDefinition,
Language::Nodes::ScalarTypeExtension,
Language::Nodes::SchemaDefinition,
Language::Nodes::SchemaExtension,
Language::Nodes::TypeName,
Language::Nodes::UnionTypeDefinition,
Language::Nodes::UnionTypeExtension,
Language::Nodes::VariableDefinition,
Language::Nodes::VariableIdentifier,
].each do |ast_node_class|
make_visit_methods(ast_node_class)
end
# rubocop:disable Development/NoEvalCop
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/nodes.rb | lib/graphql/language/nodes.rb | # frozen_string_literal: true
module GraphQL
module Language
module Nodes
NONE = GraphQL::EmptyObjects::EMPTY_ARRAY
# {AbstractNode} is the base class for all nodes in a GraphQL AST.
#
# It provides some APIs for working with ASTs:
# - `children` returns all AST nodes attached to this one. Used for tree traversal.
# - `scalars` returns all scalar (Ruby) values attached to this one. Used for comparing nodes.
# - `to_query_string` turns an AST node into a GraphQL string
class AbstractNode
module DefinitionNode
# This AST node's {#line} returns the first line, which may be the description.
# @return [Integer] The first line of the definition (not the description)
attr_reader :definition_line
def initialize(definition_line: nil, **_rest)
@definition_line = definition_line
super(**_rest)
end
def marshal_dump
super << @definition_line
end
def marshal_load(values)
@definition_line = values.pop
super
end
end
attr_reader :filename
def line
@line ||= @source&.line_at(@pos)
end
def col
@col ||= @source&.column_at(@pos)
end
def definition_line
@definition_line ||= (@source && @definition_pos) ? @source.line_at(@definition_pos) : nil
end
# Value equality
# @return [Boolean] True if `self` is equivalent to `other`
def ==(other)
return true if equal?(other)
other.kind_of?(self.class) &&
other.scalars == self.scalars &&
other.children == self.children
end
NO_CHILDREN = GraphQL::EmptyObjects::EMPTY_ARRAY
# @return [Array<GraphQL::Language::Nodes::AbstractNode>] all nodes in the tree below this one
def children
NO_CHILDREN
end
# @return [Array<Integer, Float, String, Boolean, Array>] Scalar values attached to this node
def scalars
NO_CHILDREN
end
# This might be unnecessary, but its easiest to add it here.
def initialize_copy(other)
@children = nil
@scalars = nil
@query_string = nil
end
def children_method_name
self.class.children_method_name
end
def position
[line, col]
end
def to_query_string(printer: GraphQL::Language::Printer.new)
if printer.is_a?(GraphQL::Language::Printer)
if frozen?
@query_string || printer.print(self)
else
@query_string ||= printer.print(self)
end
else
printer.print(self)
end
end
# This creates a copy of `self`, with `new_options` applied.
# @param new_options [Hash]
# @return [AbstractNode] a shallow copy of `self`
def merge(new_options)
dup.merge!(new_options)
end
# Copy `self`, but modify the copy so that `previous_child` is replaced by `new_child`
def replace_child(previous_child, new_child)
# Figure out which list `previous_child` may be found in
method_name = previous_child.children_method_name
# Get the value from this (original) node
prev_children = public_send(method_name)
if prev_children.is_a?(Array)
# Copy that list, and replace `previous_child` with `new_child`
# in the list.
new_children = prev_children.dup
prev_idx = new_children.index(previous_child)
new_children[prev_idx] = new_child
else
# Use the new value for the given attribute
new_children = new_child
end
# Copy this node, but with the new child value
copy_of_self = merge(method_name => new_children)
# Return the copy:
copy_of_self
end
# TODO DRY with `replace_child`
def delete_child(previous_child)
# Figure out which list `previous_child` may be found in
method_name = previous_child.children_method_name
# Copy that list, and delete previous_child
new_children = public_send(method_name).dup
new_children.delete(previous_child)
# Copy this node, but with the new list of children:
copy_of_self = merge(method_name => new_children)
# Return the copy:
copy_of_self
end
protected
def merge!(new_options)
new_options.each do |key, value|
instance_variable_set(:"@#{key}", value)
end
self
end
class << self
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
# Add a default `#visit_method` and `#children_method_name` using the class name
def inherited(child_class)
super
name_underscored = child_class.name
.split("::").last
.gsub(/([a-z])([A-Z])/,'\1_\2') # insert underscores
.downcase # remove caps
child_class.module_eval <<-RUBY, __FILE__, __LINE__
def visit_method
:on_#{name_underscored}
end
class << self
attr_accessor :children_method_name
def visit_method
:on_#{name_underscored}
end
end
self.children_method_name = :#{name_underscored}s
RUBY
end
def children_of_type
@children_methods
end
private
# Name accessors which return lists of nodes,
# along with the kind of node they return, if possible.
# - Add a reader for these children
# - Add a persistent update method to add a child
# - Generate a `#children` method
def children_methods(children_of_type)
if defined?(@children_methods)
raise "Can't re-call .children_methods for #{self} (already have: #{@children_methods})"
else
@children_methods = children_of_type
end
if children_of_type == false
@children_methods = {}
# skip
else
children_of_type.each do |method_name, node_type|
module_eval <<-RUBY, __FILE__, __LINE__
# A reader for these children
attr_reader :#{method_name}
RUBY
if node_type
# Only generate a method if we know what kind of node to make
module_eval <<-RUBY, __FILE__, __LINE__
# Singular method: create a node with these options
# and return a new `self` which includes that node in this list.
def merge_#{method_name.to_s.sub(/s$/, "")}(**node_opts)
merge(#{method_name}: #{method_name} + [#{node_type.name}.new(**node_opts)])
end
RUBY
end
end
if children_of_type.size == 1
module_eval <<-RUBY, __FILE__, __LINE__
alias :children #{children_of_type.keys.first}
RUBY
else
module_eval <<-RUBY, __FILE__, __LINE__
def children
@children ||= begin
if #{children_of_type.keys.map { |k| "@#{k}.any?" }.join(" || ")}
new_children = []
#{children_of_type.keys.map { |k| "new_children.concat(@#{k})" }.join("; ")}
new_children.freeze
new_children
else
NO_CHILDREN
end
end
end
RUBY
end
end
if defined?(@scalar_methods)
if !@initialize_was_generated
@initialize_was_generated = true
generate_initialize
else
# This method was defined manually
end
else
raise "Can't generate_initialize because scalar_methods wasn't called; call it before children_methods"
end
end
# These methods return a plain Ruby value, not another node
# - Add reader methods
# - Add a `#scalars` method
def scalar_methods(*method_names)
if defined?(@scalar_methods)
raise "Can't re-call .scalar_methods for #{self} (already have: #{@scalar_methods})"
else
@scalar_methods = method_names
end
if method_names == [false]
@scalar_methods = []
# skip it
else
module_eval <<-RUBY, __FILE__, __LINE__
# add readers for each scalar
attr_reader #{method_names.map { |m| ":#{m}"}.join(", ")}
def scalars
@scalars ||= [#{method_names.map { |k| "@#{k}" }.join(", ")}].freeze
end
RUBY
end
end
DEFAULT_INITIALIZE_OPTIONS = [
"line: nil",
"col: nil",
"pos: nil",
"filename: nil",
"source: nil"
]
IGNORED_MARSHALLING_KEYWORDS = [:comment]
def generate_initialize
return if method_defined?(:marshal_load, false) # checking for `:initialize` doesn't work right
scalar_method_names = @scalar_methods
# TODO: These probably should be scalar methods, but `types` returns an array
[:types, :description, :comment].each do |extra_method|
if method_defined?(extra_method)
scalar_method_names += [extra_method]
end
end
children_method_names = @children_methods.keys
all_method_names = scalar_method_names + children_method_names
if all_method_names.include?(:alias)
# Rather than complicating this special case,
# let it be overridden (in field)
return
else
arguments = scalar_method_names.map { |m| "#{m}: nil"} +
children_method_names.map { |m| "#{m}: NO_CHILDREN" } +
DEFAULT_INITIALIZE_OPTIONS
assignments = scalar_method_names.map { |m| "@#{m} = #{m}"} +
children_method_names.map { |m| "@#{m} = #{m}.freeze" }
if name.end_with?("Definition") && name != "FragmentDefinition"
arguments << "definition_pos: nil"
assignments << "@definition_pos = definition_pos"
end
keywords = scalar_method_names.map { |m| "#{m}: #{m}"} +
children_method_names.map { |m| "#{m}: #{m}" }
ignored_keywords = IGNORED_MARSHALLING_KEYWORDS.map do |keyword|
"#{keyword.to_s}: nil"
end
marshalling_method_names = all_method_names - IGNORED_MARSHALLING_KEYWORDS
module_eval <<-RUBY, __FILE__, __LINE__
def initialize(#{arguments.join(", ")})
@line = line
@col = col
@pos = pos
@filename = filename
@source = source
#{assignments.join("\n")}
end
def self.from_a(filename, line, col, #{marshalling_method_names.join(", ")}, #{ignored_keywords.join(", ")})
self.new(filename: filename, line: line, col: col, #{keywords.join(", ")})
end
def marshal_dump
[
line, col, # use methods here to force them to be calculated
@filename,
#{marshalling_method_names.map { |n| "@#{n}," }.join}
]
end
def marshal_load(values)
@line, @col, @filename #{marshalling_method_names.map { |n| ", @#{n}"}.join} = values
end
RUBY
end
end
# rubocop:enable Development/NoEvalCop
end
end
# Base class for non-null type names and list type names
class WrapperType < AbstractNode
scalar_methods :of_type
children_methods(false)
end
# Base class for nodes whose only value is a name (no child nodes or other scalars)
class NameOnlyNode < AbstractNode
scalar_methods :name
children_methods(false)
end
# A key-value pair for a field's inputs
class Argument < AbstractNode
scalar_methods :name, :value
children_methods(false)
# @!attribute name
# @return [String] the key for this argument
# @!attribute value
# @return [String, Float, Integer, Boolean, Array, InputObject, VariableIdentifier] The value passed for this key
def children
@children ||= Array(value).flatten.tap { _1.select! { |v| v.is_a?(AbstractNode) } }
end
end
class Directive < AbstractNode
scalar_methods :name
children_methods(arguments: GraphQL::Language::Nodes::Argument)
end
class DirectiveLocation < NameOnlyNode
end
class DirectiveDefinition < AbstractNode
attr_reader :description
scalar_methods :name, :repeatable
children_methods(
arguments: Nodes::Argument,
locations: Nodes::DirectiveLocation,
)
self.children_method_name = :definitions
end
# An enum value. The string is available as {#name}.
class Enum < NameOnlyNode
end
# A null value literal.
class NullValue < NameOnlyNode
end
# A single selection in a GraphQL query.
class Field < AbstractNode
def initialize(name: nil, arguments: NONE, directives: NONE, selections: NONE, field_alias: nil, line: nil, col: nil, pos: nil, filename: nil, source: nil)
@name = name
@arguments = arguments || NONE
@directives = directives || NONE
@selections = selections || NONE
# oops, alias is a keyword:
@alias = field_alias
@line = line
@col = col
@pos = pos
@filename = filename
@source = source
end
def self.from_a(filename, line, col, field_alias, name, arguments, directives, selections) # rubocop:disable Metrics/ParameterLists
self.new(filename: filename, line: line, col: col, field_alias: field_alias, name: name, arguments: arguments, directives: directives, selections: selections)
end
def marshal_dump
[line, col, @filename, @name, @arguments, @directives, @selections, @alias]
end
def marshal_load(values)
@line, @col, @filename, @name, @arguments, @directives, @selections, @alias = values
end
scalar_methods :name, :alias
children_methods({
arguments: GraphQL::Language::Nodes::Argument,
selections: GraphQL::Language::Nodes::Field,
directives: GraphQL::Language::Nodes::Directive,
})
# Override this because default is `:fields`
self.children_method_name = :selections
end
# A reusable fragment, defined at document-level.
class FragmentDefinition < AbstractNode
def initialize(name: nil, type: nil, directives: NONE, selections: NONE, filename: nil, pos: nil, source: nil, line: nil, col: nil)
@name = name
@type = type
@directives = directives
@selections = selections
@filename = filename
@pos = pos
@source = source
@line = line
@col = col
end
def self.from_a(filename, line, col, name, type, directives, selections)
self.new(filename: filename, line: line, col: col, name: name, type: type, directives: directives, selections: selections)
end
def marshal_dump
[line, col, @filename, @name, @type, @directives, @selections]
end
def marshal_load(values)
@line, @col, @filename, @name, @type, @directives, @selections = values
end
scalar_methods :name, :type
children_methods({
selections: GraphQL::Language::Nodes::Field,
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
# Application of a named fragment in a selection
class FragmentSpread < AbstractNode
scalar_methods :name
children_methods(directives: GraphQL::Language::Nodes::Directive)
self.children_method_name = :selections
# @!attribute name
# @return [String] The identifier of the fragment to apply, corresponds with {FragmentDefinition#name}
end
# An unnamed fragment, defined directly in the query with `... { }`
class InlineFragment < AbstractNode
scalar_methods :type
children_methods({
directives: GraphQL::Language::Nodes::Directive,
selections: GraphQL::Language::Nodes::Field,
})
self.children_method_name = :selections
# @!attribute type
# @return [String, nil] Name of the type this fragment applies to, or `nil` if this fragment applies to any type
end
# A collection of key-value inputs which may be a field argument
class InputObject < AbstractNode
scalar_methods(false)
children_methods(arguments: GraphQL::Language::Nodes::Argument)
# @!attribute arguments
# @return [Array<Nodes::Argument>] A list of key-value pairs inside this input object
# @return [Hash<String, Any>] Recursively turn this input object into a Ruby Hash
def to_h(options={})
arguments.inject({}) do |memo, pair|
v = pair.value
memo[pair.name] = serialize_value_for_hash v
memo
end
end
self.children_method_name = :value
private
def serialize_value_for_hash(value)
case value
when InputObject
value.to_h
when Array
value.map do |v|
serialize_value_for_hash v
end
when Enum
value.name
when NullValue
nil
else
value
end
end
end
# A list type definition, denoted with `[...]` (used for variable type definitions)
class ListType < WrapperType
end
# A non-null type definition, denoted with `...!` (used for variable type definitions)
class NonNullType < WrapperType
end
# An operation-level query variable
class VariableDefinition < AbstractNode
scalar_methods :name, :type, :default_value
children_methods(directives: Directive)
# @!attribute default_value
# @return [String, Integer, Float, Boolean, Array, NullValue] A Ruby value to use if no other value is provided
# @!attribute type
# @return [TypeName, NonNullType, ListType] The expected type of this value
# @!attribute name
# @return [String] The identifier for this variable, _without_ `$`
self.children_method_name = :variables
end
# A query, mutation or subscription.
# May be anonymous or named.
# May be explicitly typed (eg `mutation { ... }`) or implicitly a query (eg `{ ... }`).
class OperationDefinition < AbstractNode
scalar_methods :operation_type, :name
children_methods({
variables: GraphQL::Language::Nodes::VariableDefinition,
directives: GraphQL::Language::Nodes::Directive,
selections: GraphQL::Language::Nodes::Field,
})
# @!attribute variables
# @return [Array<VariableDefinition>] Variable $definitions for this operation
# @!attribute selections
# @return [Array<Field>] Root-level fields on this operation
# @!attribute operation_type
# @return [String, nil] The root type for this operation, or `nil` for implicit `"query"`
# @!attribute name
# @return [String, nil] The name for this operation, or `nil` if unnamed
self.children_method_name = :definitions
end
# This is the AST root for normal queries
#
# @example Deriving a document by parsing a string
# document = GraphQL.parse(query_string)
#
# @example Creating a string from a document
# document.to_query_string
# # { ... }
#
# @example Creating a custom string from a document
# class VariableScrubber < GraphQL::Language::Printer
# def print_argument(arg)
# print_string("#{arg.name}: <HIDDEN>")
# end
# end
#
# document.to_query_string(printer: VariableScrubber.new)
#
class Document < AbstractNode
scalar_methods false
children_methods(definitions: nil)
# @!attribute definitions
# @return [Array<OperationDefinition, FragmentDefinition>] top-level GraphQL units: operations or fragments
def slice_definition(name)
GraphQL::Language::DefinitionSlice.slice(self, name)
end
end
# A type name, used for variable definitions
class TypeName < NameOnlyNode
end
# Usage of a variable in a query. Name does _not_ include `$`.
class VariableIdentifier < NameOnlyNode
self.children_method_name = :value
end
class SchemaDefinition < AbstractNode
scalar_methods :query, :mutation, :subscription
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
class SchemaExtension < AbstractNode
scalar_methods :query, :mutation, :subscription
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
class ScalarTypeDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
class ScalarTypeExtension < AbstractNode
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
class InputValueDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name, :type, :default_value
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :fields
end
class FieldDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name, :type
children_methods({
arguments: GraphQL::Language::Nodes::InputValueDefinition,
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :fields
# this is so that `children_method_name` of `InputValueDefinition` works properly
# with `#replace_child`
alias :fields :arguments
def merge(new_options)
if (f = new_options.delete(:fields))
new_options[:arguments] = f
end
super
end
end
class ObjectTypeDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name, :interfaces
children_methods({
directives: GraphQL::Language::Nodes::Directive,
fields: GraphQL::Language::Nodes::FieldDefinition,
})
self.children_method_name = :definitions
end
class ObjectTypeExtension < AbstractNode
scalar_methods :name, :interfaces
children_methods({
directives: GraphQL::Language::Nodes::Directive,
fields: GraphQL::Language::Nodes::FieldDefinition,
})
self.children_method_name = :definitions
end
class InterfaceTypeDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name
children_methods({
interfaces: GraphQL::Language::Nodes::TypeName,
directives: GraphQL::Language::Nodes::Directive,
fields: GraphQL::Language::Nodes::FieldDefinition,
})
self.children_method_name = :definitions
end
class InterfaceTypeExtension < AbstractNode
scalar_methods :name
children_methods({
interfaces: GraphQL::Language::Nodes::TypeName,
directives: GraphQL::Language::Nodes::Directive,
fields: GraphQL::Language::Nodes::FieldDefinition,
})
self.children_method_name = :definitions
end
class UnionTypeDefinition < AbstractNode
attr_reader :description, :comment, :types
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
class UnionTypeExtension < AbstractNode
attr_reader :types
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :definitions
end
class EnumValueDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
})
self.children_method_name = :values
end
class EnumTypeDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
values: GraphQL::Language::Nodes::EnumValueDefinition,
})
self.children_method_name = :definitions
end
class EnumTypeExtension < AbstractNode
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
values: GraphQL::Language::Nodes::EnumValueDefinition,
})
self.children_method_name = :definitions
end
class InputObjectTypeDefinition < AbstractNode
attr_reader :description, :comment
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
fields: GraphQL::Language::Nodes::InputValueDefinition,
})
self.children_method_name = :definitions
end
class InputObjectTypeExtension < AbstractNode
scalar_methods :name
children_methods({
directives: GraphQL::Language::Nodes::Directive,
fields: GraphQL::Language::Nodes::InputValueDefinition,
})
self.children_method_name = :definitions
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/block_string.rb | lib/graphql/language/block_string.rb | # frozen_string_literal: true
module GraphQL
module Language
module BlockString
# Remove leading and trailing whitespace from a block string.
# See "Block Strings" in https://github.com/facebook/graphql/blob/master/spec/Section%202%20--%20Language.md
def self.trim_whitespace(str)
# Early return for the most common cases:
if str == ""
return "".dup
elsif !(has_newline = str.include?("\n")) && !(str.start_with?(" "))
return str
end
lines = has_newline ? str.split("\n") : [str]
common_indent = nil
# find the common whitespace
lines.each_with_index do |line, idx|
if idx == 0
next
end
line_length = line.size
line_indent = if line.match?(/\A [^ ]/)
2
elsif line.match?(/\A [^ ]/)
4
elsif line.match?(/\A[^ ]/)
0
else
line[/\A */].size
end
if line_indent < line_length && (common_indent.nil? || line_indent < common_indent)
common_indent = line_indent
end
end
# Remove the common whitespace
if common_indent && common_indent > 0
lines.each_with_index do |line, idx|
if idx == 0
next
else
line.slice!(0, common_indent)
end
end
end
# Remove leading & trailing blank lines
while lines.size > 0 && contains_only_whitespace?(lines.first)
lines.shift
end
while lines.size > 0 && contains_only_whitespace?(lines.last)
lines.pop
end
# Rebuild the string
lines.size > 1 ? lines.join("\n") : (lines.first || "".dup)
end
def self.print(str, indent: '')
line_length = 120 - indent.length
block_str = "".dup
triple_quotes = "\"\"\"\n"
block_str << indent
block_str << triple_quotes
if str.include?("\n")
str.split("\n") do |line|
if line == ''
block_str << "\n"
else
break_line(line, line_length) do |subline|
block_str << indent
block_str << subline
block_str << "\n"
end
end
end
else
break_line(str, line_length) do |subline|
block_str << indent
block_str << subline
block_str << "\n"
end
end
block_str << indent
block_str << triple_quotes
end
private
def self.break_line(line, length)
return yield(line) if line.length < length + 5
parts = line.split(Regexp.new("((?: |^).{15,#{length - 40}}(?= |$))"))
return yield(line) if parts.length < 4
yield(parts.slice!(0, 3).join)
parts.each_with_index do |part, i|
next if i % 2 == 1
yield "#{part[1..-1]}#{parts[i + 1]}"
end
nil
end
def self.contains_only_whitespace?(line)
line.match?(/^\s*$/)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/parser.rb | lib/graphql/language/parser.rb | # frozen_string_literal: true
require "strscan"
require "graphql/language/nodes"
require "graphql/tracing/null_trace"
module GraphQL
module Language
class Parser
include GraphQL::Language::Nodes
include EmptyObjects
class << self
attr_accessor :cache
def parse(graphql_str, filename: nil, trace: Tracing::NullTrace, max_tokens: nil)
self.new(graphql_str, filename: filename, trace: trace, max_tokens: max_tokens).parse
end
def parse_file(filename, trace: Tracing::NullTrace)
if cache
cache.fetch(filename) do
parse(File.read(filename), filename: filename, trace: trace)
end
else
parse(File.read(filename), filename: filename, trace: trace)
end
end
end
def initialize(graphql_str, filename: nil, trace: Tracing::NullTrace, max_tokens: nil)
if graphql_str.nil?
raise GraphQL::ParseError.new("No query string was present", nil, nil, nil)
end
@lexer = Lexer.new(graphql_str, filename: filename, max_tokens: max_tokens)
@graphql_str = graphql_str
@filename = filename
@trace = trace
@dedup_identifiers = false
@lines_at = nil
end
def parse
@document ||= begin
@trace.parse(query_string: @graphql_str) do
document
end
rescue SystemStackError
raise GraphQL::ParseError.new("This query is too large to execute.", nil, nil, @query_str, filename: @filename)
end
end
def tokens_count
parse
@lexer.tokens_count
end
def line_at(pos)
line = lines_at.bsearch_index { |l| l >= pos }
if line.nil?
@lines_at.size + 1
else
line + 1
end
end
def column_at(pos)
next_line_idx = lines_at.bsearch_index { |l| l >= pos } || 0
if next_line_idx > 0
line_pos = @lines_at[next_line_idx - 1]
pos - line_pos
else
pos + 1
end
end
private
# @return [Array<Integer>] Positions of each line break in the original string
def lines_at
@lines_at ||= begin
la = []
idx = 0
while idx
idx = @graphql_str.index("\n", idx)
if idx
la << idx
idx += 1
end
end
la
end
end
attr_reader :token_name
def advance_token
@token_name = @lexer.advance
end
def pos
@lexer.pos
end
def document
any_tokens = advance_token
defns = []
if any_tokens
defns << definition
else
# Only ignored characters is not a valid document
raise GraphQL::ParseError.new("Unexpected end of document", nil, nil, @graphql_str)
end
while !@lexer.finished?
defns << definition
end
Document.new(pos: 0, definitions: defns, filename: @filename, source: self)
end
def definition
case token_name
when :FRAGMENT
loc = pos
expect_token :FRAGMENT
f_name = if !at?(:ON)
parse_name
end
expect_token :ON
f_type = parse_type_name
directives = parse_directives
selections = selection_set
Nodes::FragmentDefinition.new(
pos: loc,
name: f_name,
type: f_type,
directives: directives,
selections: selections,
filename: @filename,
source: self
)
when :QUERY, :MUTATION, :SUBSCRIPTION, :LCURLY
op_loc = pos
op_type = case token_name
when :LCURLY
"query"
else
parse_operation_type
end
op_name = case token_name
when :LPAREN, :LCURLY, :DIR_SIGN
nil
else
parse_name
end
variable_definitions = if at?(:LPAREN)
expect_token(:LPAREN)
defs = []
while !at?(:RPAREN)
loc = pos
expect_token(:VAR_SIGN)
var_name = parse_name
expect_token(:COLON)
var_type = self.type || raise_parse_error("Missing type definition for variable: $#{var_name}")
default_value = if at?(:EQUALS)
advance_token
value
end
directives = parse_directives
defs << Nodes::VariableDefinition.new(
pos: loc,
name: var_name,
type: var_type,
default_value: default_value,
directives: directives,
filename: @filename,
source: self
)
end
expect_token(:RPAREN)
defs
else
EmptyObjects::EMPTY_ARRAY
end
directives = parse_directives
OperationDefinition.new(
pos: op_loc,
operation_type: op_type,
name: op_name,
variables: variable_definitions,
directives: directives,
selections: selection_set,
filename: @filename,
source: self
)
when :EXTEND
loc = pos
advance_token
case token_name
when :SCALAR
advance_token
name = parse_name
directives = parse_directives
ScalarTypeExtension.new(pos: loc, name: name, directives: directives, filename: @filename, source: self)
when :TYPE
advance_token
name = parse_name
implements_interfaces = parse_implements
directives = parse_directives
field_defns = at?(:LCURLY) ? parse_field_definitions : EMPTY_ARRAY
ObjectTypeExtension.new(pos: loc, name: name, interfaces: implements_interfaces, directives: directives, fields: field_defns, filename: @filename, source: self)
when :INTERFACE
advance_token
name = parse_name
directives = parse_directives
interfaces = parse_implements
fields_definition = at?(:LCURLY) ? parse_field_definitions : EMPTY_ARRAY
InterfaceTypeExtension.new(pos: loc, name: name, directives: directives, fields: fields_definition, interfaces: interfaces, filename: @filename, source: self)
when :UNION
advance_token
name = parse_name
directives = parse_directives
union_member_types = parse_union_members
UnionTypeExtension.new(pos: loc, name: name, directives: directives, types: union_member_types, filename: @filename, source: self)
when :ENUM
advance_token
name = parse_name
directives = parse_directives
enum_values_definition = parse_enum_value_definitions
Nodes::EnumTypeExtension.new(pos: loc, name: name, directives: directives, values: enum_values_definition, filename: @filename, source: self)
when :INPUT
advance_token
name = parse_name
directives = parse_directives
input_fields_definition = parse_input_object_field_definitions
InputObjectTypeExtension.new(pos: loc, name: name, directives: directives, fields: input_fields_definition, filename: @filename, source: self)
when :SCHEMA
advance_token
directives = parse_directives
query = mutation = subscription = nil
if at?(:LCURLY)
advance_token
while !at?(:RCURLY)
if at?(:QUERY)
advance_token
expect_token(:COLON)
query = parse_name
elsif at?(:MUTATION)
advance_token
expect_token(:COLON)
mutation = parse_name
elsif at?(:SUBSCRIPTION)
advance_token
expect_token(:COLON)
subscription = parse_name
else
expect_one_of([:QUERY, :MUTATION, :SUBSCRIPTION])
end
end
expect_token :RCURLY
end
SchemaExtension.new(
subscription: subscription,
mutation: mutation,
query: query,
directives: directives,
pos: loc,
filename: @filename,
source: self,
)
else
expect_one_of([:SCHEMA, :SCALAR, :TYPE, :ENUM, :INPUT, :UNION, :INTERFACE])
end
else
loc = pos
desc = at?(:STRING) ? string_value : nil
defn_loc = pos
case token_name
when :SCHEMA
advance_token
directives = parse_directives
query = mutation = subscription = nil
expect_token :LCURLY
while !at?(:RCURLY)
if at?(:QUERY)
advance_token
expect_token(:COLON)
query = parse_name
elsif at?(:MUTATION)
advance_token
expect_token(:COLON)
mutation = parse_name
elsif at?(:SUBSCRIPTION)
advance_token
expect_token(:COLON)
subscription = parse_name
else
expect_one_of([:QUERY, :MUTATION, :SUBSCRIPTION])
end
end
expect_token :RCURLY
SchemaDefinition.new(pos: loc, definition_pos: defn_loc, query: query, mutation: mutation, subscription: subscription, directives: directives, filename: @filename, source: self)
when :DIRECTIVE
advance_token
expect_token :DIR_SIGN
name = parse_name
arguments_definition = parse_argument_definitions
repeatable = if at?(:REPEATABLE)
advance_token
true
else
false
end
expect_token :ON
directive_locations = [DirectiveLocation.new(pos: pos, name: parse_name, filename: @filename, source: self)]
while at?(:PIPE)
advance_token
directive_locations << DirectiveLocation.new(pos: pos, name: parse_name, filename: @filename, source: self)
end
DirectiveDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, arguments: arguments_definition, locations: directive_locations, repeatable: repeatable, filename: @filename, source: self)
when :TYPE
advance_token
name = parse_name
implements_interfaces = parse_implements
directives = parse_directives
field_defns = at?(:LCURLY) ? parse_field_definitions : EMPTY_ARRAY
ObjectTypeDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, interfaces: implements_interfaces, directives: directives, fields: field_defns, filename: @filename, source: self)
when :INTERFACE
advance_token
name = parse_name
interfaces = parse_implements
directives = parse_directives
fields_definition = parse_field_definitions
InterfaceTypeDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, directives: directives, fields: fields_definition, interfaces: interfaces, filename: @filename, source: self)
when :UNION
advance_token
name = parse_name
directives = parse_directives
union_member_types = parse_union_members
UnionTypeDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, directives: directives, types: union_member_types, filename: @filename, source: self)
when :SCALAR
advance_token
name = parse_name
directives = parse_directives
ScalarTypeDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, directives: directives, filename: @filename, source: self)
when :ENUM
advance_token
name = parse_name
directives = parse_directives
enum_values_definition = parse_enum_value_definitions
Nodes::EnumTypeDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, directives: directives, values: enum_values_definition, filename: @filename, source: self)
when :INPUT
advance_token
name = parse_name
directives = parse_directives
input_fields_definition = parse_input_object_field_definitions
InputObjectTypeDefinition.new(pos: loc, definition_pos: defn_loc, description: desc, name: name, directives: directives, fields: input_fields_definition, filename: @filename, source: self)
else
expect_one_of([:SCHEMA, :SCALAR, :TYPE, :ENUM, :INPUT, :UNION, :INTERFACE])
end
end
end
def parse_input_object_field_definitions
if at?(:LCURLY)
expect_token :LCURLY
list = []
while !at?(:RCURLY)
list << parse_input_value_definition
end
expect_token :RCURLY
list
else
EMPTY_ARRAY
end
end
def parse_enum_value_definitions
if at?(:LCURLY)
expect_token :LCURLY
list = []
while !at?(:RCURLY)
v_loc = pos
description = if at?(:STRING); string_value; end
defn_loc = pos
# Any identifier, but not true, false, or null
enum_value = if at?(:TRUE) || at?(:FALSE) || at?(:NULL)
expect_token(:IDENTIFIER)
else
parse_name
end
v_directives = parse_directives
list << EnumValueDefinition.new(pos: v_loc, definition_pos: defn_loc, description: description, name: enum_value, directives: v_directives, filename: @filename, source: self)
end
expect_token :RCURLY
list
else
EMPTY_ARRAY
end
end
def parse_union_members
if at?(:EQUALS)
expect_token :EQUALS
if at?(:PIPE)
advance_token
end
list = [parse_type_name]
while at?(:PIPE)
advance_token
list << parse_type_name
end
list
else
EMPTY_ARRAY
end
end
def parse_implements
if at?(:IMPLEMENTS)
advance_token
list = []
while true
advance_token if at?(:AMP)
break unless at?(:IDENTIFIER)
list << parse_type_name
end
list
else
EMPTY_ARRAY
end
end
def parse_field_definitions
expect_token :LCURLY
list = []
while !at?(:RCURLY)
loc = pos
description = if at?(:STRING); string_value; end
defn_loc = pos
name = parse_name
arguments_definition = parse_argument_definitions
expect_token :COLON
type = self.type
directives = parse_directives
list << FieldDefinition.new(pos: loc, definition_pos: defn_loc, description: description, name: name, arguments: arguments_definition, type: type, directives: directives, filename: @filename, source: self)
end
expect_token :RCURLY
list
end
def parse_argument_definitions
if at?(:LPAREN)
advance_token
list = []
while !at?(:RPAREN)
list << parse_input_value_definition
end
expect_token :RPAREN
list
else
EMPTY_ARRAY
end
end
def parse_input_value_definition
loc = pos
description = if at?(:STRING); string_value; end
defn_loc = pos
name = parse_name
expect_token :COLON
type = self.type
default_value = if at?(:EQUALS)
advance_token
value
else
nil
end
directives = parse_directives
InputValueDefinition.new(pos: loc, definition_pos: defn_loc, description: description, name: name, type: type, default_value: default_value, directives: directives, filename: @filename, source: self)
end
def type
parsed_type = case token_name
when :IDENTIFIER
parse_type_name
when :LBRACKET
list_type
else
nil
end
if at?(:BANG) && parsed_type
parsed_type = Nodes::NonNullType.new(pos: pos, of_type: parsed_type, source: self)
expect_token(:BANG)
end
parsed_type
end
def list_type
loc = pos
expect_token(:LBRACKET)
inner_type = self.type
parsed_list_type = if inner_type
Nodes::ListType.new(pos: loc, of_type: inner_type, source: self)
else
nil
end
expect_token(:RBRACKET)
parsed_list_type
end
def parse_operation_type
val = if at?(:QUERY)
"query"
elsif at?(:MUTATION)
"mutation"
elsif at?(:SUBSCRIPTION)
"subscription"
else
expect_one_of([:QUERY, :MUTATION, :SUBSCRIPTION])
end
advance_token
val
end
def selection_set
expect_token(:LCURLY)
selections = []
while @token_name != :RCURLY
selections << if at?(:ELLIPSIS)
loc = pos
advance_token
case token_name
when :ON, :DIR_SIGN, :LCURLY
if_type = if at?(:ON)
advance_token
parse_type_name
else
nil
end
directives = parse_directives
Nodes::InlineFragment.new(pos: loc, type: if_type, directives: directives, selections: selection_set, filename: @filename, source: self)
else
name = parse_name_without_on
directives = parse_directives
# Can this ever happen?
# expect_token(:IDENTIFIER) if at?(:ON)
FragmentSpread.new(pos: loc, name: name, directives: directives, filename: @filename, source: self)
end
else
loc = pos
name = parse_name
field_alias = nil
if at?(:COLON)
advance_token
field_alias = name
name = parse_name
end
arguments = at?(:LPAREN) ? parse_arguments : nil
directives = at?(:DIR_SIGN) ? parse_directives : nil
selection_set = at?(:LCURLY) ? self.selection_set : nil
Nodes::Field.new(pos: loc, field_alias: field_alias, name: name, arguments: arguments, directives: directives, selections: selection_set, filename: @filename, source: self)
end
end
expect_token(:RCURLY)
selections
end
def parse_name
case token_name
when :IDENTIFIER
expect_token_value(:IDENTIFIER)
when :SCHEMA
advance_token
"schema"
when :SCALAR
advance_token
"scalar"
when :IMPLEMENTS
advance_token
"implements"
when :INTERFACE
advance_token
"interface"
when :UNION
advance_token
"union"
when :ENUM
advance_token
"enum"
when :INPUT
advance_token
"input"
when :DIRECTIVE
advance_token
"directive"
when :TYPE
advance_token
"type"
when :QUERY
advance_token
"query"
when :MUTATION
advance_token
"mutation"
when :SUBSCRIPTION
advance_token
"subscription"
when :TRUE
advance_token
"true"
when :FALSE
advance_token
"false"
when :FRAGMENT
advance_token
"fragment"
when :REPEATABLE
advance_token
"repeatable"
when :NULL
advance_token
"null"
when :ON
advance_token
"on"
when :EXTEND
advance_token
"extend"
else
expect_token(:NAME)
end
end
def parse_name_without_on
if at?(:ON)
expect_token(:IDENTIFIER)
else
parse_name
end
end
def parse_type_name
TypeName.new(pos: pos, name: parse_name, filename: @filename, source: self)
end
def parse_directives
if at?(:DIR_SIGN)
dirs = []
while at?(:DIR_SIGN)
loc = pos
advance_token
name = parse_name
arguments = parse_arguments
dirs << Nodes::Directive.new(pos: loc, name: name, arguments: arguments, filename: @filename, source: self)
end
dirs
else
EMPTY_ARRAY
end
end
def parse_arguments
if at?(:LPAREN)
advance_token
args = []
while !at?(:RPAREN)
loc = pos
name = parse_name
expect_token(:COLON)
args << Nodes::Argument.new(pos: loc, name: name, value: value, filename: @filename, source: self)
end
if args.empty?
expect_token(:ARGUMENT_NAME) # At least one argument is required
end
expect_token(:RPAREN)
args
else
EMPTY_ARRAY
end
end
def string_value
token_value = @lexer.string_value
expect_token :STRING
token_value
end
def value
case token_name
when :INT
expect_token_value(:INT).to_i
when :FLOAT
expect_token_value(:FLOAT).to_f
when :STRING
string_value
when :TRUE
advance_token
true
when :FALSE
advance_token
false
when :NULL
advance_token
NullValue.new(pos: pos, name: "null", filename: @filename, source: self)
when :IDENTIFIER
Nodes::Enum.new(pos: pos, name: expect_token_value(:IDENTIFIER), filename: @filename, source: self)
when :LBRACKET
advance_token
list = []
while !at?(:RBRACKET)
list << value
end
expect_token(:RBRACKET)
list
when :LCURLY
start = pos
advance_token
args = []
while !at?(:RCURLY)
loc = pos
n = parse_name
expect_token(:COLON)
args << Argument.new(pos: loc, name: n, value: value, filename: @filename, source: self)
end
expect_token(:RCURLY)
InputObject.new(pos: start, arguments: args, filename: @filename, source: self)
when :VAR_SIGN
loc = pos
advance_token
VariableIdentifier.new(pos: loc, name: parse_name, filename: @filename, source: self)
when :SCHEMA
advance_token
Nodes::Enum.new(pos: pos, name: "schema", filename: @filename, source: self)
when :SCALAR
advance_token
Nodes::Enum.new(pos: pos, name: "scalar", filename: @filename, source: self)
when :IMPLEMENTS
advance_token
Nodes::Enum.new(pos: pos, name: "implements", filename: @filename, source: self)
when :INTERFACE
advance_token
Nodes::Enum.new(pos: pos, name: "interface", filename: @filename, source: self)
when :UNION
advance_token
Nodes::Enum.new(pos: pos, name: "union", filename: @filename, source: self)
when :ENUM
advance_token
Nodes::Enum.new(pos: pos, name: "enum", filename: @filename, source: self)
when :INPUT
advance_token
Nodes::Enum.new(pos: pos, name: "input", filename: @filename, source: self)
when :DIRECTIVE
advance_token
Nodes::Enum.new(pos: pos, name: "directive", filename: @filename, source: self)
when :TYPE
advance_token
Nodes::Enum.new(pos: pos, name: "type", filename: @filename, source: self)
when :QUERY
advance_token
Nodes::Enum.new(pos: pos, name: "query", filename: @filename, source: self)
when :MUTATION
advance_token
Nodes::Enum.new(pos: pos, name: "mutation", filename: @filename, source: self)
when :SUBSCRIPTION
advance_token
Nodes::Enum.new(pos: pos, name: "subscription", filename: @filename, source: self)
when :FRAGMENT
advance_token
Nodes::Enum.new(pos: pos, name: "fragment", filename: @filename, source: self)
when :REPEATABLE
advance_token
Nodes::Enum.new(pos: pos, name: "repeatable", filename: @filename, source: self)
when :ON
advance_token
Nodes::Enum.new(pos: pos, name: "on", filename: @filename, source: self)
when :EXTEND
advance_token
Nodes::Enum.new(pos: pos, name: "extend", filename: @filename, source: self)
else
expect_token(:VALUE)
end
end
def at?(expected_token_name)
@token_name == expected_token_name
end
def expect_token(expected_token_name)
unless @token_name == expected_token_name
raise_parse_error("Expected #{expected_token_name}, actual: #{token_name || "(none)"} (#{debug_token_value.inspect})")
end
advance_token
end
def expect_one_of(token_names)
raise_parse_error("Expected one of #{token_names.join(", ")}, actual: #{token_name || "NOTHING"} (#{debug_token_value.inspect})")
end
def raise_parse_error(message)
message += " at [#{@lexer.line_number}, #{@lexer.column_number}]"
raise GraphQL::ParseError.new(
message,
@lexer.line_number,
@lexer.column_number,
@graphql_str,
filename: @filename,
)
end
# Only use when we care about the expected token's value
def expect_token_value(tok)
token_value = @lexer.token_value
if @dedup_identifiers
token_value = -token_value
end
expect_token(tok)
token_value
end
# token_value works for when the scanner matched something
# which is usually fine and it's good for it to be fast at that.
def debug_token_value
@lexer.debug_token_value(token_name)
end
class SchemaParser < Parser
def initialize(*args, **kwargs)
super
@dedup_identifiers = true
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/sanitized_printer.rb | lib/graphql/language/sanitized_printer.rb | # frozen_string_literal: true
module GraphQL
module Language
# A custom printer used to print sanitized queries. It inlines provided variables
# within the query for facilitate logging and analysis of queries.
#
# The printer returns `nil` if the query is invalid.
#
# Since the GraphQL Ruby AST for a GraphQL query doesnt contain any reference
# on the type of fields or arguments, we have to track the current object, field
# and input type while printing the query.
#
# @example Printing a scrubbed string
# printer = QueryPrinter.new(query)
# puts printer.sanitized_query_string
#
# @see {Query#sanitized_query_string}
class SanitizedPrinter < GraphQL::Language::Printer
REDACTED = "\"<REDACTED>\""
def initialize(query, inline_variables: true)
@query = query
@current_type = nil
@current_field = nil
@current_input_type = nil
@inline_variables = inline_variables
end
# @return [String, nil] A scrubbed query string, if the query was valid.
def sanitized_query_string
if query.valid?
print(query.document)
else
nil
end
end
def print_node(node, indent: "")
case node
when FalseClass, Float, Integer, String, TrueClass
if @current_argument && redact_argument_value?(@current_argument, node)
print_string(redacted_argument_value(@current_argument))
else
super
end
when Array
old_input_type = @current_input_type
if @current_input_type && @current_input_type.list?
@current_input_type = @current_input_type.of_type
@current_input_type = @current_input_type.of_type if @current_input_type.non_null?
end
super
@current_input_type = old_input_type
else
super
end
end
# Indicates whether or not to redact non-null values for the given argument. Defaults to redacting all strings
# arguments but this can be customized by subclasses.
def redact_argument_value?(argument, value)
# Default to redacting any strings or custom scalars encoded as strings
type = argument.type.unwrap
value.is_a?(String) && type.kind.scalar? && (type.graphql_name == "String" || !type.default_scalar?)
end
# Returns the value to use for redacted versions of the given argument. Defaults to the
# string "<REDACTED>".
def redacted_argument_value(argument)
REDACTED
end
def print_argument(argument)
# We won't have type information if we're recursing into a custom scalar
return super if @current_input_type && @current_input_type.kind.scalar?
arg_owner = @current_input_type || @current_directive || @current_field
old_current_argument = @current_argument
@current_argument = arg_owner.get_argument(argument.name, @query.context)
old_input_type = @current_input_type
@current_input_type = @current_argument.type.non_null? ? @current_argument.type.of_type : @current_argument.type
argument_value = if coerce_argument_value_to_list?(@current_input_type, argument.value)
[argument.value]
else
argument.value
end
print_string("#{argument.name}: ")
print_node(argument_value)
@current_input_type = old_input_type
@current_argument = old_current_argument
end
def coerce_argument_value_to_list?(type, value)
type.list? &&
!value.is_a?(Array) &&
!value.nil? &&
!value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
end
def print_variable_identifier(variable_id)
if @inline_variables
variable_value = query.variables[variable_id.name]
print_node(value_to_ast(variable_value, @current_input_type))
else
super
end
end
def print_field(field, indent: "")
@current_field = query.types.field(@current_type, field.name)
old_type = @current_type
@current_type = @current_field.type.unwrap
super
@current_type = old_type
end
def print_inline_fragment(inline_fragment, indent: "")
old_type = @current_type
if inline_fragment.type
@current_type = query.get_type(inline_fragment.type.name)
end
super
@current_type = old_type
end
def print_fragment_definition(fragment_def, indent: "")
old_type = @current_type
@current_type = query.get_type(fragment_def.type.name)
super
@current_type = old_type
end
def print_directive(directive)
@current_directive = query.schema.directives[directive.name]
super
@current_directive = nil
end
# Print the operation definition but do not include the variable
# definitions since we will inline them within the query
def print_operation_definition(operation_definition, indent: "")
old_type = @current_type
@current_type = query.schema.public_send(operation_definition.operation_type)
if @inline_variables
print_string("#{indent}#{operation_definition.operation_type}")
print_string(" #{operation_definition.name}") if operation_definition.name
print_directives(operation_definition.directives)
print_selections(operation_definition.selections, indent: indent)
else
super
end
@current_type = old_type
end
private
def value_to_ast(value, type)
type = type.of_type if type.non_null?
if value.nil?
return GraphQL::Language::Nodes::NullValue.new(name: "null")
end
case type.kind.name
when "INPUT_OBJECT"
value = if value.respond_to?(:to_unsafe_h)
# for ActionController::Parameters
value.to_unsafe_h
else
value.to_h
end
arguments = value.map do |key, val|
sub_type = type.get_argument(key.to_s, @query.context).type
GraphQL::Language::Nodes::Argument.new(
name: key.to_s,
value: value_to_ast(val, sub_type)
)
end
GraphQL::Language::Nodes::InputObject.new(
arguments: arguments
)
when "LIST"
if value.is_a?(Array)
value.map { |v| value_to_ast(v, type.of_type) }
else
[value].map { |v| value_to_ast(v, type.of_type) }
end
when "ENUM"
if value.is_a?(GraphQL::Language::Nodes::Enum)
# if it was a default value, it's already wrapped
value
else
GraphQL::Language::Nodes::Enum.new(name: value)
end
else
value
end
end
attr_reader :query
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/document_from_schema_definition.rb | lib/graphql/language/document_from_schema_definition.rb | # frozen_string_literal: true
module GraphQL
module Language
# @api private
#
# {GraphQL::Language::DocumentFromSchemaDefinition} is used to convert a {GraphQL::Schema} object
# To a {GraphQL::Language::Document} AST node.
#
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
# @param include_introspection_types [Boolean] Whether or not to include introspection types in the AST
# @param include_built_in_scalars [Boolean] Whether or not to include built in scalars in the AST
# @param include_built_in_directives [Boolean] Whether or not to include built in directives in the AST
class DocumentFromSchemaDefinition
def initialize(
schema, context: nil, include_introspection_types: false,
include_built_in_directives: false, include_built_in_scalars: false, always_include_schema: false
)
@schema = schema
@context = context
@always_include_schema = always_include_schema
@include_introspection_types = include_introspection_types
@include_built_in_scalars = include_built_in_scalars
@include_built_in_directives = include_built_in_directives
@include_one_of = false
dummy_query = @schema.query_class.new(@schema, "{ __typename }", validate: false, context: context)
@types = dummy_query.types # rubocop:disable Development/ContextIsPassedCop
end
def document
GraphQL::Language::Nodes::Document.new(
definitions: build_definition_nodes
)
end
def build_schema_node
if !schema_respects_root_name_conventions?(@schema)
GraphQL::Language::Nodes::SchemaDefinition.new(
query: @types.query_root&.graphql_name,
mutation: @types.mutation_root&.graphql_name,
subscription: @types.subscription_root&.graphql_name,
directives: definition_directives(@schema, :schema_directives)
)
else
# A plain `schema ...` _must_ include root type definitions.
# If the only difference is directives, then you have to use `extend schema`
GraphQL::Language::Nodes::SchemaExtension.new(directives: definition_directives(@schema, :schema_directives))
end
end
def build_object_type_node(object_type)
ints = @types.interfaces(object_type)
if !ints.empty?
ints = ints.sort_by(&:graphql_name)
ints.map! { |iface| build_type_name_node(iface) }
end
GraphQL::Language::Nodes::ObjectTypeDefinition.new(
name: object_type.graphql_name,
comment: object_type.comment,
interfaces: ints,
fields: build_field_nodes(@types.fields(object_type)),
description: object_type.description,
directives: directives(object_type),
)
end
def build_field_node(field)
GraphQL::Language::Nodes::FieldDefinition.new(
name: field.graphql_name,
comment: field.comment,
arguments: build_argument_nodes(@types.arguments(field)),
type: build_type_name_node(field.type),
description: field.description,
directives: directives(field),
)
end
def build_union_type_node(union_type)
GraphQL::Language::Nodes::UnionTypeDefinition.new(
name: union_type.graphql_name,
comment: union_type.comment,
description: union_type.description,
types: @types.possible_types(union_type).sort_by(&:graphql_name).map { |type| build_type_name_node(type) },
directives: directives(union_type),
)
end
def build_interface_type_node(interface_type)
GraphQL::Language::Nodes::InterfaceTypeDefinition.new(
name: interface_type.graphql_name,
comment: interface_type.comment,
interfaces: @types.interfaces(interface_type).sort_by(&:graphql_name).map { |type| build_type_name_node(type) },
description: interface_type.description,
fields: build_field_nodes(@types.fields(interface_type)),
directives: directives(interface_type),
)
end
def build_enum_type_node(enum_type)
GraphQL::Language::Nodes::EnumTypeDefinition.new(
name: enum_type.graphql_name,
comment: enum_type.comment,
values: @types.enum_values(enum_type).sort_by(&:graphql_name).map do |enum_value|
build_enum_value_node(enum_value)
end,
description: enum_type.description,
directives: directives(enum_type),
)
end
def build_enum_value_node(enum_value)
GraphQL::Language::Nodes::EnumValueDefinition.new(
name: enum_value.graphql_name,
comment: enum_value.comment,
description: enum_value.description,
directives: directives(enum_value),
)
end
def build_scalar_type_node(scalar_type)
GraphQL::Language::Nodes::ScalarTypeDefinition.new(
name: scalar_type.graphql_name,
comment: scalar_type.comment,
description: scalar_type.description,
directives: directives(scalar_type),
)
end
def build_argument_node(argument)
if argument.default_value?
default_value = build_default_value(argument.default_value, argument.type)
else
default_value = nil
end
argument_node = GraphQL::Language::Nodes::InputValueDefinition.new(
name: argument.graphql_name,
comment: argument.comment,
description: argument.description,
type: build_type_name_node(argument.type),
default_value: default_value,
directives: directives(argument),
)
argument_node
end
def build_input_object_node(input_object)
GraphQL::Language::Nodes::InputObjectTypeDefinition.new(
name: input_object.graphql_name,
comment: input_object.comment,
fields: build_argument_nodes(@types.arguments(input_object)),
description: input_object.description,
directives: directives(input_object),
)
end
def build_directive_node(directive)
GraphQL::Language::Nodes::DirectiveDefinition.new(
name: directive.graphql_name,
repeatable: directive.repeatable?,
arguments: build_argument_nodes(@types.arguments(directive)),
locations: build_directive_location_nodes(directive.locations),
description: directive.description,
)
end
def build_directive_location_nodes(locations)
locations.sort.map { |location| build_directive_location_node(location) }
end
def build_directive_location_node(location)
GraphQL::Language::Nodes::DirectiveLocation.new(
name: location.to_s
)
end
def build_type_name_node(type)
case type.kind.name
when "LIST"
GraphQL::Language::Nodes::ListType.new(
of_type: build_type_name_node(type.of_type)
)
when "NON_NULL"
GraphQL::Language::Nodes::NonNullType.new(
of_type: build_type_name_node(type.of_type)
)
else
@cached_type_name_nodes ||= {}
@cached_type_name_nodes[type.graphql_name] ||= GraphQL::Language::Nodes::TypeName.new(name: type.graphql_name)
end
end
def build_default_value(default_value, type)
if default_value.nil?
return GraphQL::Language::Nodes::NullValue.new(name: "null")
end
case type.kind.name
when "SCALAR"
type.coerce_isolated_result(default_value)
when "ENUM"
GraphQL::Language::Nodes::Enum.new(name: type.coerce_isolated_result(default_value))
when "INPUT_OBJECT"
GraphQL::Language::Nodes::InputObject.new(
arguments: default_value.to_h.map do |arg_name, arg_value|
args = @types.arguments(type)
arg = args.find { |a| a.keyword.to_s == arg_name.to_s }
if arg.nil?
raise ArgumentError, "No argument definition on #{type.graphql_name} for argument: #{arg_name.inspect} (expected one of: #{args.map(&:keyword)})"
end
GraphQL::Language::Nodes::Argument.new(
name: arg.graphql_name.to_s,
value: build_default_value(arg_value, arg.type)
)
end
)
when "NON_NULL"
build_default_value(default_value, type.of_type)
when "LIST"
default_value.to_a.map { |v| build_default_value(v, type.of_type) }
else
raise GraphQL::RequiredImplementationMissingError, "Unexpected default value type #{type.inspect}"
end
end
def build_type_definition_node(type)
case type.kind.name
when "OBJECT"
build_object_type_node(type)
when "UNION"
build_union_type_node(type)
when "INTERFACE"
build_interface_type_node(type)
when "SCALAR"
build_scalar_type_node(type)
when "ENUM"
build_enum_type_node(type)
when "INPUT_OBJECT"
build_input_object_node(type)
else
raise TypeError
end
end
def build_argument_nodes(arguments)
if !arguments.empty?
nodes = arguments.map { |arg| build_argument_node(arg) }
nodes.sort_by!(&:name)
nodes
else
arguments
end
end
def build_directive_nodes(directives)
directives
.map { |directive| build_directive_node(directive) }
.sort_by(&:name)
end
def build_definition_nodes
dirs_to_build = @types.directives
if !include_built_in_directives
dirs_to_build = dirs_to_build.reject { |directive| directive.default_directive? }
end
definitions = build_directive_nodes(dirs_to_build)
all_types = @types.all_types
type_nodes = build_type_definition_nodes(all_types)
if !(ex_t = schema.extra_types).empty?
dummy_query = Class.new(GraphQL::Schema::Object) do
graphql_name "DummyQuery"
(all_types + ex_t).each_with_index do |type, idx|
if !type.kind.input_object? && !type.introspection?
field "f#{idx}", type
end
end
end
extra_types_schema = Class.new(GraphQL::Schema) do
query(dummy_query)
end
extra_types_types = GraphQL::Query.new(extra_types_schema, "{ __typename }", context: @context).types # rubocop:disable Development/ContextIsPassedCop
# Temporarily replace `@types` with something from this example schema.
# It'd be much nicer to pass this in, but that would be a big refactor :S
prev_types = @types
@types = extra_types_types
type_nodes += build_type_definition_nodes(ex_t)
@types = prev_types
end
type_nodes.sort_by!(&:name)
if @include_one_of
# This may have been set to true when iterating over all types
definitions.concat(build_directive_nodes([GraphQL::Schema::Directive::OneOf]))
end
definitions.concat(type_nodes)
if include_schema_node?
definitions.unshift(build_schema_node)
end
definitions
end
def build_type_definition_nodes(types)
if !include_introspection_types
types = types.reject { |type| type.introspection? }
end
if !include_built_in_scalars
types = types.reject { |type| type.kind.scalar? && type.default_scalar? }
end
types.map { |type| build_type_definition_node(type) }
end
def build_field_nodes(fields)
f_nodes = fields.map { |field| build_field_node(field) }
f_nodes.sort_by!(&:name)
f_nodes
end
private
def include_schema_node?
always_include_schema ||
!schema_respects_root_name_conventions?(schema) ||
!schema.schema_directives.empty?
end
def schema_respects_root_name_conventions?(schema)
(schema.query.nil? || schema.query.graphql_name == 'Query') &&
(schema.mutation.nil? || schema.mutation.graphql_name == 'Mutation') &&
(schema.subscription.nil? || schema.subscription.graphql_name == 'Subscription')
end
def directives(member)
definition_directives(member, :directives)
end
def definition_directives(member, directives_method)
if !member.respond_to?(directives_method) || member.directives.empty?
EmptyObjects::EMPTY_ARRAY
else
visible_directives = member.public_send(directives_method).select { |dir| @types.directive_exists?(dir.graphql_name) }
visible_directives.map! do |dir|
args = []
dir.arguments.argument_values.each_value do |arg_value| # rubocop:disable Development/ContextIsPassedCop -- directive instance method
arg_defn = arg_value.definition
if arg_defn.default_value? && arg_value.value == arg_defn.default_value
next
else
value_node = build_default_value(arg_value.value, arg_value.definition.type)
args << GraphQL::Language::Nodes::Argument.new(
name: arg_value.definition.name,
value: value_node,
)
end
end
# If this schema uses this built-in directive definition,
# include it in the print-out since it's not part of the spec yet.
@include_one_of ||= dir.class == GraphQL::Schema::Directive::OneOf
GraphQL::Language::Nodes::Directive.new(
name: dir.class.graphql_name,
arguments: args
)
end
visible_directives
end
end
attr_reader :schema, :always_include_schema,
:include_introspection_types, :include_built_in_directives, :include_built_in_scalars
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/comment.rb | lib/graphql/language/comment.rb | # frozen_string_literal: true
module GraphQL
module Language
module Comment
def self.print(str, indent: '')
lines = str.split("\n").map do |line|
comment_str = "".dup
comment_str << indent
comment_str << "# "
comment_str << line
comment_str.rstrip
end
lines.join("\n") + "\n"
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/lexer.rb | lib/graphql/language/lexer.rb | # frozen_string_literal: true
module GraphQL
module Language
class Lexer
def initialize(graphql_str, filename: nil, max_tokens: nil)
if !(graphql_str.encoding == Encoding::UTF_8 || graphql_str.ascii_only?)
graphql_str = graphql_str.dup.force_encoding(Encoding::UTF_8)
end
@string = graphql_str
@filename = filename
@scanner = StringScanner.new(graphql_str)
@pos = nil
@max_tokens = max_tokens || Float::INFINITY
@tokens_count = 0
@finished = false
end
def finished?
@finished
end
def freeze
@scanner = nil
super
end
attr_reader :pos, :tokens_count
def advance
@scanner.skip(IGNORE_REGEXP)
if @scanner.eos?
@finished = true
return false
end
@tokens_count += 1
if @tokens_count > @max_tokens
raise_parse_error("This query is too large to execute.")
end
@pos = @scanner.pos
next_byte = @string.getbyte(@pos)
next_byte_is_for = FIRST_BYTES[next_byte]
case next_byte_is_for
when ByteFor::PUNCTUATION
@scanner.pos += 1
PUNCTUATION_NAME_FOR_BYTE[next_byte]
when ByteFor::NAME
if len = @scanner.skip(KEYWORD_REGEXP)
case len
when 2
:ON
when 12
:SUBSCRIPTION
else
pos = @pos
# Use bytes 2 and 3 as a unique identifier for this keyword
bytes = (@string.getbyte(pos + 2) << 8) | @string.getbyte(pos + 1)
KEYWORD_BY_TWO_BYTES[_hash(bytes)]
end
else
@scanner.skip(IDENTIFIER_REGEXP)
:IDENTIFIER
end
when ByteFor::IDENTIFIER
@scanner.skip(IDENTIFIER_REGEXP)
:IDENTIFIER
when ByteFor::NUMBER
if len = @scanner.skip(NUMERIC_REGEXP)
if GraphQL.reject_numbers_followed_by_names
new_pos = @scanner.pos
peek_byte = @string.getbyte(new_pos)
next_first_byte = FIRST_BYTES[peek_byte]
if next_first_byte == ByteFor::NAME || next_first_byte == ByteFor::IDENTIFIER
number_part = token_value
name_part = @scanner.scan(IDENTIFIER_REGEXP)
raise_parse_error("Name after number is not allowed (in `#{number_part}#{name_part}`)")
end
end
# Check for a matched decimal:
@scanner[1] ? :FLOAT : :INT
else
# Attempt to find the part after the `-`
value = @scanner.scan(/-\s?[a-z0-9]*/i)
invalid_byte_for_number_error_message = "Expected type 'number', but it was malformed#{value.nil? ? "" : ": #{value.inspect}"}."
raise_parse_error(invalid_byte_for_number_error_message)
end
when ByteFor::ELLIPSIS
if @string.getbyte(@pos + 1) != 46 || @string.getbyte(@pos + 2) != 46
raise_parse_error("Expected `...`, actual: #{@string[@pos..@pos + 2].inspect}")
end
@scanner.pos += 3
:ELLIPSIS
when ByteFor::STRING
if @scanner.skip(BLOCK_STRING_REGEXP) || @scanner.skip(QUOTED_STRING_REGEXP)
:STRING
else
raise_parse_error("Expected string or block string, but it was malformed")
end
else
@scanner.pos += 1
:UNKNOWN_CHAR
end
rescue ArgumentError => err
if err.message == "invalid byte sequence in UTF-8"
raise_parse_error("Parse error on bad Unicode escape sequence", nil, nil)
end
end
def token_value
@string.byteslice(@scanner.pos - @scanner.matched_size, @scanner.matched_size)
rescue StandardError => err
raise GraphQL::Error, "(token_value failed: #{err.class}: #{err.message})"
end
def debug_token_value(token_name)
if token_name && Lexer::Punctuation.const_defined?(token_name)
Lexer::Punctuation.const_get(token_name)
elsif token_name == :ELLIPSIS
"..."
elsif token_name == :STRING
string_value
elsif @scanner.matched_size.nil?
@scanner.peek(1)
else
token_value
end
end
ESCAPES = /\\["\\\/bfnrt]/
ESCAPES_REPLACE = {
'\\"' => '"',
"\\\\" => "\\",
"\\/" => '/',
"\\b" => "\b",
"\\f" => "\f",
"\\n" => "\n",
"\\r" => "\r",
"\\t" => "\t",
}
UTF_8 = /\\u(?:([\dAa-f]{4})|\{([\da-f]{4,})\})(?:\\u([\dAa-f]{4}))?/i
VALID_STRING = /\A(?:[^\\]|#{ESCAPES}|#{UTF_8})*\z/o
ESCAPED = /(?:#{ESCAPES}|#{UTF_8})/o
def string_value
str = token_value
is_block = str.start_with?('"""')
if is_block
str.gsub!(/\A"""|"""\z/, '')
return Language::BlockString.trim_whitespace(str)
else
str.gsub!(/\A"|"\z/, '')
if !str.valid_encoding? || !str.match?(VALID_STRING)
raise_parse_error("Bad unicode escape in #{str.inspect}")
else
Lexer.replace_escaped_characters_in_place(str)
if !str.valid_encoding?
raise_parse_error("Bad unicode escape in #{str.inspect}")
else
str
end
end
end
end
def line_number
@scanner.string[0..@pos].count("\n") + 1
end
def column_number
@scanner.string[0..@pos].split("\n").last.length
end
def raise_parse_error(message, line = line_number, col = column_number)
raise GraphQL::ParseError.new(message, line, col, @string, filename: @filename)
end
IGNORE_REGEXP = %r{
(?:
[, \c\r\n\t]+ |
\#.*$
)*
}x
IDENTIFIER_REGEXP = /[_A-Za-z][_0-9A-Za-z]*/
INT_REGEXP = /-?(?:[0]|[1-9][0-9]*)/
FLOAT_DECIMAL_REGEXP = /[.][0-9]+/
FLOAT_EXP_REGEXP = /[eE][+-]?[0-9]+/
# TODO: FLOAT_EXP_REGEXP should not be allowed to follow INT_REGEXP, integers are not allowed to have exponent parts.
NUMERIC_REGEXP = /#{INT_REGEXP}(#{FLOAT_DECIMAL_REGEXP}#{FLOAT_EXP_REGEXP}|#{FLOAT_DECIMAL_REGEXP}|#{FLOAT_EXP_REGEXP})?/
KEYWORDS = [
"on",
"fragment",
"true",
"false",
"null",
"query",
"mutation",
"subscription",
"schema",
"scalar",
"type",
"extend",
"implements",
"interface",
"union",
"enum",
"input",
"directive",
"repeatable"
].freeze
KEYWORD_REGEXP = /#{Regexp.union(KEYWORDS.sort)}\b/
KEYWORD_BY_TWO_BYTES = [
:INTERFACE,
:MUTATION,
:EXTEND,
:FALSE,
:ENUM,
:TRUE,
:NULL,
nil,
nil,
nil,
nil,
nil,
nil,
nil,
:QUERY,
nil,
nil,
:REPEATABLE,
:IMPLEMENTS,
:INPUT,
:TYPE,
:SCHEMA,
nil,
nil,
nil,
:DIRECTIVE,
:UNION,
nil,
nil,
:SCALAR,
nil,
:FRAGMENT
].freeze
# This produces a unique integer for bytes 2 and 3 of each keyword string
# See https://tenderlovemaking.com/2023/09/02/fast-tokenizers-with-stringscanner.html
def _hash key
(key * 18592990) >> 27 & 0x1f
end
module Punctuation
LCURLY = '{'
RCURLY = '}'
LPAREN = '('
RPAREN = ')'
LBRACKET = '['
RBRACKET = ']'
COLON = ':'
VAR_SIGN = '$'
DIR_SIGN = '@'
EQUALS = '='
BANG = '!'
PIPE = '|'
AMP = '&'
end
# A sparse array mapping the bytes for each punctuation
# to a symbol name for that punctuation
PUNCTUATION_NAME_FOR_BYTE = Punctuation.constants.each_with_object([]) { |name, arr|
punct = Punctuation.const_get(name)
arr[punct.ord] = name
}.freeze
QUOTE = '"'
UNICODE_DIGIT = /[0-9A-Za-z]/
FOUR_DIGIT_UNICODE = /#{UNICODE_DIGIT}{4}/
N_DIGIT_UNICODE = %r{#{Punctuation::LCURLY}#{UNICODE_DIGIT}{4,}#{Punctuation::RCURLY}}x
UNICODE_ESCAPE = %r{\\u(?:#{FOUR_DIGIT_UNICODE}|#{N_DIGIT_UNICODE})}
STRING_ESCAPE = %r{[\\][\\/bfnrt]}
BLOCK_QUOTE = '"""'
ESCAPED_QUOTE = /\\"/;
STRING_CHAR = /#{ESCAPED_QUOTE}|[^"\\\n\r]|#{UNICODE_ESCAPE}|#{STRING_ESCAPE}/
QUOTED_STRING_REGEXP = %r{#{QUOTE} (?:#{STRING_CHAR})* #{QUOTE}}x
BLOCK_STRING_REGEXP = %r{
#{BLOCK_QUOTE}
(?: [^"\\] | # Any characters that aren't a quote or slash
(?<!") ["]{1,2} (?!") | # Any quotes that don't have quotes next to them
\\"{0,3}(?!") | # A slash followed by <= 3 quotes that aren't followed by a quote
\\ | # A slash
"{1,2}(?!") # 1 or 2 " followed by something that isn't a quote
)*
(?:"")?
#{BLOCK_QUOTE}
}xm
# Use this array to check, for a given byte that will start a token,
# what kind of token might it start?
FIRST_BYTES = Array.new(255)
module ByteFor
NUMBER = 0 # int or float
NAME = 1 # identifier or keyword
STRING = 2
ELLIPSIS = 3
IDENTIFIER = 4 # identifier, *not* a keyword
PUNCTUATION = 5
end
(0..9).each { |i| FIRST_BYTES[i.to_s.ord] = ByteFor::NUMBER }
FIRST_BYTES["-".ord] = ByteFor::NUMBER
# Some of these may be overwritten below, if keywords start with the same character
("A".."Z").each { |char| FIRST_BYTES[char.ord] = ByteFor::IDENTIFIER }
("a".."z").each { |char| FIRST_BYTES[char.ord] = ByteFor::IDENTIFIER }
FIRST_BYTES['_'.ord] = ByteFor::IDENTIFIER
FIRST_BYTES['.'.ord] = ByteFor::ELLIPSIS
FIRST_BYTES['"'.ord] = ByteFor::STRING
KEYWORDS.each { |kw| FIRST_BYTES[kw.getbyte(0)] = ByteFor::NAME }
Punctuation.constants.each do |punct_name|
punct = Punctuation.const_get(punct_name)
FIRST_BYTES[punct.ord] = ByteFor::PUNCTUATION
end
FIRST_BYTES.freeze
# Replace any escaped unicode or whitespace with the _actual_ characters
# To avoid allocating more strings, this modifies the string passed into it
def self.replace_escaped_characters_in_place(raw_string)
raw_string.gsub!(ESCAPED) do |matched_str|
if (point_str_1 = $1 || $2)
codepoint_1 = point_str_1.to_i(16)
if (codepoint_2 = $3)
codepoint_2 = codepoint_2.to_i(16)
if (codepoint_1 >= 0xD800 && codepoint_1 <= 0xDBFF) && # leading surrogate
(codepoint_2 >= 0xDC00 && codepoint_2 <= 0xDFFF) # trailing surrogate
# A surrogate pair
combined = ((codepoint_1 - 0xD800) * 0x400) + (codepoint_2 - 0xDC00) + 0x10000
[combined].pack('U'.freeze)
else
# Two separate code points
[codepoint_1].pack('U'.freeze) + [codepoint_2].pack('U'.freeze)
end
else
[codepoint_1].pack('U'.freeze)
end
else
ESCAPES_REPLACE[matched_str]
end
end
nil
end
# This is not used during parsing because the parser
# doesn't actually need tokens.
def self.tokenize(string)
lexer = GraphQL::Language::Lexer.new(string)
tokens = []
while (token_name = lexer.advance)
new_token = [
token_name,
lexer.line_number,
lexer.column_number,
lexer.debug_token_value(token_name),
]
tokens << new_token
end
tokens
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/printer.rb | lib/graphql/language/printer.rb | # frozen_string_literal: true
module GraphQL
module Language
class Printer
OMISSION = "... (truncated)"
class TruncatableBuffer
class TruncateSizeReached < StandardError; end
DEFAULT_INIT_CAPACITY = 500
def initialize(truncate_size: nil)
@out = String.new(capacity: truncate_size || DEFAULT_INIT_CAPACITY)
@truncate_size = truncate_size
end
def append(other)
if @truncate_size && (@out.size + other.size) > @truncate_size
@out << other.slice(0, @truncate_size - @out.size)
raise(TruncateSizeReached, "Truncate size reached")
else
@out << other
end
end
def to_string
@out
end
end
# Turn an arbitrary AST node back into a string.
#
# @example Turning a document into a query string
# document = GraphQL.parse(query_string)
# GraphQL::Language::Printer.new.print(document)
# # => "{ ... }"
#
#
# @example Building a custom printer
#
# class MyPrinter < GraphQL::Language::Printer
# def print_argument(arg)
# print_string("#{arg.name}: <HIDDEN>")
# end
# end
#
# MyPrinter.new.print(document)
# # => "mutation { pay(creditCard: <HIDDEN>) { success } }"
#
# @param node [Nodes::AbstractNode]
# @param indent [String] Whitespace to add to the printed node
# @param truncate_size [Integer, nil] The size to truncate to.
# @return [String] Valid GraphQL for `node`
def print(node, indent: "", truncate_size: nil)
truncate_size = truncate_size ? [truncate_size - OMISSION.size, 0].max : nil
@out = TruncatableBuffer.new(truncate_size: truncate_size)
print_node(node, indent: indent)
@out.to_string
rescue TruncatableBuffer::TruncateSizeReached
@out.to_string << OMISSION
end
protected
def print_string(str)
@out.append(str)
end
def print_document(document)
document.definitions.each_with_index do |d, i|
print_node(d)
print_string("\n\n") if i < document.definitions.size - 1
end
end
def print_argument(argument)
print_string(argument.name)
print_string(": ")
print_node(argument.value)
end
def print_input_object(input_object)
print_string("{")
input_object.arguments.each_with_index do |a, i|
print_argument(a)
print_string(", ") if i < input_object.arguments.size - 1
end
print_string("}")
end
def print_directive(directive)
print_string("@")
print_string(directive.name)
if !directive.arguments.empty?
print_string("(")
directive.arguments.each_with_index do |a, i|
print_argument(a)
print_string(", ") if i < directive.arguments.size - 1
end
print_string(")")
end
end
def print_enum(enum)
print_string(enum.name)
end
def print_null_value
print_string("null")
end
def print_field(field, indent: "")
print_string(indent)
if field.alias
print_string(field.alias)
print_string(": ")
end
print_string(field.name)
if !field.arguments.empty?
print_string("(")
field.arguments.each_with_index do |a, i|
print_argument(a)
print_string(", ") if i < field.arguments.size - 1
end
print_string(")")
end
print_directives(field.directives)
print_selections(field.selections, indent: indent)
end
def print_fragment_definition(fragment_def, indent: "")
print_string(indent)
print_string("fragment")
if fragment_def.name
print_string(" ")
print_string(fragment_def.name)
end
if fragment_def.type
print_string(" on ")
print_node(fragment_def.type)
end
print_directives(fragment_def.directives)
print_selections(fragment_def.selections, indent: indent)
end
def print_fragment_spread(fragment_spread, indent: "")
print_string(indent)
print_string("...")
print_string(fragment_spread.name)
print_directives(fragment_spread.directives)
end
def print_inline_fragment(inline_fragment, indent: "")
print_string(indent)
print_string("...")
if inline_fragment.type
print_string(" on ")
print_node(inline_fragment.type)
end
print_directives(inline_fragment.directives)
print_selections(inline_fragment.selections, indent: indent)
end
def print_list_type(list_type)
print_string("[")
print_node(list_type.of_type)
print_string("]")
end
def print_non_null_type(non_null_type)
print_node(non_null_type.of_type)
print_string("!")
end
def print_operation_definition(operation_definition, indent: "")
print_string(indent)
print_string(operation_definition.operation_type)
if operation_definition.name
print_string(" ")
print_string(operation_definition.name)
end
if !operation_definition.variables.empty?
print_string("(")
operation_definition.variables.each_with_index do |v, i|
print_variable_definition(v)
print_string(", ") if i < operation_definition.variables.size - 1
end
print_string(")")
end
print_directives(operation_definition.directives)
print_selections(operation_definition.selections, indent: indent)
end
def print_type_name(type_name)
print_string(type_name.name)
end
def print_variable_definition(variable_definition)
print_string("$")
print_string(variable_definition.name)
print_string(": ")
print_node(variable_definition.type)
unless variable_definition.default_value.nil?
print_string(" = ")
print_node(variable_definition.default_value)
end
variable_definition.directives.each do |dir|
print_string(" ")
print_directive(dir)
end
end
def print_variable_identifier(variable_identifier)
print_string("$")
print_string(variable_identifier.name)
end
def print_schema_definition(schema, extension: false)
has_conventional_names = (schema.query.nil? || schema.query == 'Query') &&
(schema.mutation.nil? || schema.mutation == 'Mutation') &&
(schema.subscription.nil? || schema.subscription == 'Subscription')
if has_conventional_names && schema.directives.empty?
return
end
extension ? print_string("extend schema") : print_string("schema")
if !schema.directives.empty?
schema.directives.each do |dir|
print_string("\n ")
print_node(dir)
end
if !has_conventional_names
print_string("\n")
end
end
if !has_conventional_names
if schema.directives.empty?
print_string(" ")
end
print_string("{\n")
print_string(" query: #{schema.query}\n") if schema.query
print_string(" mutation: #{schema.mutation}\n") if schema.mutation
print_string(" subscription: #{schema.subscription}\n") if schema.subscription
print_string("}")
end
end
def print_scalar_type_definition(scalar_type, extension: false)
extension ? print_string("extend ") : print_description_and_comment(scalar_type)
print_string("scalar ")
print_string(scalar_type.name)
print_directives(scalar_type.directives)
end
def print_object_type_definition(object_type, extension: false)
extension ? print_string("extend ") : print_description_and_comment(object_type)
print_string("type ")
print_string(object_type.name)
print_implements(object_type) unless object_type.interfaces.empty?
print_directives(object_type.directives)
print_field_definitions(object_type.fields)
end
def print_implements(type)
print_string(" implements ")
i = 0
type.interfaces.each do |int|
if i > 0
print_string(" & ")
end
print_string(int.name)
i += 1
end
end
def print_input_value_definition(input_value)
print_string(input_value.name)
print_string(": ")
print_node(input_value.type)
unless input_value.default_value.nil?
print_string(" = ")
print_node(input_value.default_value)
end
print_directives(input_value.directives)
end
def print_arguments(arguments, indent: "")
if arguments.all? { |arg| !arg.description && !arg.comment }
print_string("(")
arguments.each_with_index do |arg, i|
print_input_value_definition(arg)
print_string(", ") if i < arguments.size - 1
end
print_string(")")
return
end
print_string("(\n")
arguments.each_with_index do |arg, i|
print_comment(arg, indent: " " + indent, first_in_block: i == 0)
print_description(arg, indent: " " + indent, first_in_block: i == 0)
print_string(" ")
print_string(indent)
print_input_value_definition(arg)
print_string("\n") if i < arguments.size - 1
end
print_string("\n")
print_string(indent)
print_string(")")
end
def print_field_definition(field)
print_string(field.name)
unless field.arguments.empty?
print_arguments(field.arguments, indent: " ")
end
print_string(": ")
print_node(field.type)
print_directives(field.directives)
end
def print_interface_type_definition(interface_type, extension: false)
extension ? print_string("extend ") : print_description_and_comment(interface_type)
print_string("interface ")
print_string(interface_type.name)
print_implements(interface_type) if !interface_type.interfaces.empty?
print_directives(interface_type.directives)
print_field_definitions(interface_type.fields)
end
def print_union_type_definition(union_type, extension: false)
extension ? print_string("extend ") : print_description_and_comment(union_type)
print_string("union ")
print_string(union_type.name)
print_directives(union_type.directives)
if !union_type.types.empty?
print_string(" = ")
i = 0
union_type.types.each do |t|
if i > 0
print_string(" | ")
end
print_string(t.name)
i += 1
end
end
end
def print_enum_type_definition(enum_type, extension: false)
extension ? print_string("extend ") : print_description_and_comment(enum_type)
print_string("enum ")
print_string(enum_type.name)
print_directives(enum_type.directives)
if !enum_type.values.empty?
print_string(" {\n")
enum_type.values.each.with_index do |value, i|
print_description(value, indent: " ", first_in_block: i == 0)
print_comment(value, indent: " ", first_in_block: i == 0)
print_enum_value_definition(value)
end
print_string("}")
end
end
def print_enum_value_definition(enum_value)
print_string(" ")
print_string(enum_value.name)
print_directives(enum_value.directives)
print_string("\n")
end
def print_input_object_type_definition(input_object_type, extension: false)
extension ? print_string("extend ") : print_description_and_comment(input_object_type)
print_string("input ")
print_string(input_object_type.name)
print_directives(input_object_type.directives)
if !input_object_type.fields.empty?
print_string(" {\n")
input_object_type.fields.each.with_index do |field, i|
print_description(field, indent: " ", first_in_block: i == 0)
print_comment(field, indent: " ", first_in_block: i == 0)
print_string(" ")
print_input_value_definition(field)
print_string("\n")
end
print_string("}")
end
end
def print_directive_definition(directive)
print_description(directive)
print_string("directive @")
print_string(directive.name)
if !directive.arguments.empty?
print_arguments(directive.arguments)
end
if directive.repeatable
print_string(" repeatable")
end
print_string(" on ")
i = 0
directive.locations.each do |loc|
if i > 0
print_string(" | ")
end
print_string(loc.name)
i += 1
end
end
def print_description(node, indent: "", first_in_block: true)
return unless node.description
print_string("\n") if indent != "" && !first_in_block
print_string(GraphQL::Language::BlockString.print(node.description, indent: indent))
end
def print_comment(node, indent: "", first_in_block: true)
return unless node.comment
print_string("\n") if indent != "" && !first_in_block
print_string(GraphQL::Language::Comment.print(node.comment, indent: indent))
end
def print_description_and_comment(node)
print_description(node)
print_comment(node)
end
def print_field_definitions(fields)
return if fields.empty?
print_string(" {\n")
i = 0
fields.each do |field|
print_description(field, indent: " ", first_in_block: i == 0)
print_comment(field, indent: " ", first_in_block: i == 0)
print_string(" ")
print_field_definition(field)
print_string("\n")
i += 1
end
print_string("}")
end
def print_directives(directives)
return if directives.empty?
directives.each do |d|
print_string(" ")
print_directive(d)
end
end
def print_selections(selections, indent: "")
return if selections.empty?
print_string(" {\n")
selections.each do |selection|
print_node(selection, indent: indent + " ")
print_string("\n")
end
print_string(indent)
print_string("}")
end
def print_node(node, indent: "")
case node
when Nodes::Document
print_document(node)
when Nodes::Argument
print_argument(node)
when Nodes::Directive
print_directive(node)
when Nodes::Enum
print_enum(node)
when Nodes::NullValue
print_null_value
when Nodes::Field
print_field(node, indent: indent)
when Nodes::FragmentDefinition
print_fragment_definition(node, indent: indent)
when Nodes::FragmentSpread
print_fragment_spread(node, indent: indent)
when Nodes::InlineFragment
print_inline_fragment(node, indent: indent)
when Nodes::InputObject
print_input_object(node)
when Nodes::ListType
print_list_type(node)
when Nodes::NonNullType
print_non_null_type(node)
when Nodes::OperationDefinition
print_operation_definition(node, indent: indent)
when Nodes::TypeName
print_type_name(node)
when Nodes::VariableDefinition
print_variable_definition(node)
when Nodes::VariableIdentifier
print_variable_identifier(node)
when Nodes::SchemaDefinition
print_schema_definition(node)
when Nodes::SchemaExtension
print_schema_definition(node, extension: true)
when Nodes::ScalarTypeDefinition
print_scalar_type_definition(node)
when Nodes::ScalarTypeExtension
print_scalar_type_definition(node, extension: true)
when Nodes::ObjectTypeDefinition
print_object_type_definition(node)
when Nodes::ObjectTypeExtension
print_object_type_definition(node, extension: true)
when Nodes::InputValueDefinition
print_input_value_definition(node)
when Nodes::FieldDefinition
print_field_definition(node)
when Nodes::InterfaceTypeDefinition
print_interface_type_definition(node)
when Nodes::InterfaceTypeExtension
print_interface_type_definition(node, extension: true)
when Nodes::UnionTypeDefinition
print_union_type_definition(node)
when Nodes::UnionTypeExtension
print_union_type_definition(node, extension: true)
when Nodes::EnumTypeDefinition
print_enum_type_definition(node)
when Nodes::EnumTypeExtension
print_enum_type_definition(node, extension: true)
when Nodes::EnumValueDefinition
print_enum_value_definition(node)
when Nodes::InputObjectTypeDefinition
print_input_object_type_definition(node)
when Nodes::InputObjectTypeExtension
print_input_object_type_definition(node, extension: true)
when Nodes::DirectiveDefinition
print_directive_definition(node)
when FalseClass, Float, Integer, NilClass, String, TrueClass, Symbol
print_string(GraphQL::Language.serialize(node))
when Array
print_string("[")
node.each_with_index do |v, i|
print_node(v)
print_string(", ") if i < node.length - 1
end
print_string("]")
when Hash
print_string("{")
node.each_with_index do |(k, v), i|
print_string(k)
print_string(": ")
print_node(v)
print_string(", ") if i < node.length - 1
end
print_string("}")
else
print_string(GraphQL::Language.serialize(node.to_s))
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/visitor.rb | lib/graphql/language/visitor.rb | # frozen_string_literal: true
module GraphQL
module Language
# Depth-first traversal through the tree, calling hooks at each stop.
#
# @example Create a visitor counting certain field names
# class NameCounter < GraphQL::Language::Visitor
# def initialize(document, field_name)
# super(document)
# @field_name = field_name
# @count = 0
# end
#
# attr_reader :count
#
# def on_field(node, parent)
# # if this field matches our search, increment the counter
# if node.name == @field_name
# @count += 1
# end
# # Continue visiting subfields:
# super
# end
# end
#
# # Initialize a visitor
# visitor = NameCounter.new(document, "name")
# # Run it
# visitor.visit
# # Check the result
# visitor.count
# # => 3
#
# @see GraphQL::Language::StaticVisitor for a faster visitor that doesn't support modifying the document
class Visitor
class DeleteNode; end
# When this is returned from a visitor method,
# Then the `node` passed into the method is removed from `parent`'s children.
DELETE_NODE = DeleteNode.new
def initialize(document)
@document = document
@result = nil
end
# @return [GraphQL::Language::Nodes::Document] The document with any modifications applied
attr_reader :result
# Visit `document` and all children
# @return [void]
def visit
# `@document` may be any kind of node:
visit_method = :"#{@document.visit_method}_with_modifications"
result = public_send(visit_method, @document, nil)
@result = if result.is_a?(Array)
result.first
else
# The node wasn't modified
@document
end
end
def on_document_children(document_node)
new_node = document_node
document_node.children.each do |child_node|
visit_method = :"#{child_node.visit_method}_with_modifications"
new_child_and_node = public_send(visit_method, child_node, new_node)
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end
new_node
end
def on_field_children(new_node)
new_node.arguments.each do |arg_node| # rubocop:disable Development/ContextIsPassedCop
new_child_and_node = on_argument_with_modifications(arg_node, new_node)
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end
new_node = visit_directives(new_node)
new_node = visit_selections(new_node)
new_node
end
def visit_directives(new_node)
new_node.directives.each do |dir_node|
new_child_and_node = on_directive_with_modifications(dir_node, new_node)
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end
new_node
end
def visit_selections(new_node)
new_node.selections.each do |selection|
new_child_and_node = case selection
when GraphQL::Language::Nodes::Field
on_field_with_modifications(selection, new_node)
when GraphQL::Language::Nodes::InlineFragment
on_inline_fragment_with_modifications(selection, new_node)
when GraphQL::Language::Nodes::FragmentSpread
on_fragment_spread_with_modifications(selection, new_node)
else
raise ArgumentError, "Invariant: unexpected field selection #{selection.class} (#{selection.inspect})"
end
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end
new_node
end
def on_fragment_definition_children(new_node)
new_node = visit_directives(new_node)
new_node = visit_selections(new_node)
new_node
end
alias :on_inline_fragment_children :on_fragment_definition_children
def on_operation_definition_children(new_node)
new_node.variables.each do |arg_node|
new_child_and_node = on_variable_definition_with_modifications(arg_node, new_node)
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end
new_node = visit_directives(new_node)
new_node = visit_selections(new_node)
new_node
end
def on_argument_children(new_node)
new_node.children.each do |value_node|
new_child_and_node = case value_node
when Language::Nodes::VariableIdentifier
on_variable_identifier_with_modifications(value_node, new_node)
when Language::Nodes::InputObject
on_input_object_with_modifications(value_node, new_node)
when Language::Nodes::Enum
on_enum_with_modifications(value_node, new_node)
when Language::Nodes::NullValue
on_null_value_with_modifications(value_node, new_node)
else
raise ArgumentError, "Invariant: unexpected argument value node #{value_node.class} (#{value_node.inspect})"
end
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end
new_node
end
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
# We don't use `alias` here because it breaks `super`
def self.make_visit_methods(ast_node_class)
node_method = ast_node_class.visit_method
children_of_type = ast_node_class.children_of_type
child_visit_method = :"#{node_method}_children"
class_eval(<<-RUBY, __FILE__, __LINE__ + 1)
# The default implementation for visiting an AST node.
# It doesn't _do_ anything, but it continues to visiting the node's children.
# To customize this hook, override one of its make_visit_methods (or the base method?)
# in your subclasses.
#
# @param node [GraphQL::Language::Nodes::AbstractNode] the node being visited
# @param parent [GraphQL::Language::Nodes::AbstractNode, nil] the previously-visited node, or `nil` if this is the root node.
# @return [Array, nil] If there were modifications, it returns an array of new nodes, otherwise, it returns `nil`.
def #{node_method}(node, parent)
if node.equal?(DELETE_NODE)
# This might be passed to `super(DELETE_NODE, ...)`
# by a user hook, don't want to keep visiting in that case.
[node, parent]
else
new_node = node
#{
if method_defined?(child_visit_method)
"new_node = #{child_visit_method}(new_node)"
elsif children_of_type
children_of_type.map do |child_accessor, child_class|
"node.#{child_accessor}.each do |child_node|
new_child_and_node = #{child_class.visit_method}_with_modifications(child_node, new_node)
# Reassign `node` in case the child hook makes a modification
if new_child_and_node.is_a?(Array)
new_node = new_child_and_node[1]
end
end"
end.join("\n")
else
""
end
}
if new_node.equal?(node)
[node, parent]
else
[new_node, parent]
end
end
end
def #{node_method}_with_modifications(node, parent)
new_node_and_new_parent = #{node_method}(node, parent)
apply_modifications(node, parent, new_node_and_new_parent)
end
RUBY
end
[
Language::Nodes::Argument,
Language::Nodes::Directive,
Language::Nodes::DirectiveDefinition,
Language::Nodes::DirectiveLocation,
Language::Nodes::Document,
Language::Nodes::Enum,
Language::Nodes::EnumTypeDefinition,
Language::Nodes::EnumTypeExtension,
Language::Nodes::EnumValueDefinition,
Language::Nodes::Field,
Language::Nodes::FieldDefinition,
Language::Nodes::FragmentDefinition,
Language::Nodes::FragmentSpread,
Language::Nodes::InlineFragment,
Language::Nodes::InputObject,
Language::Nodes::InputObjectTypeDefinition,
Language::Nodes::InputObjectTypeExtension,
Language::Nodes::InputValueDefinition,
Language::Nodes::InterfaceTypeDefinition,
Language::Nodes::InterfaceTypeExtension,
Language::Nodes::ListType,
Language::Nodes::NonNullType,
Language::Nodes::NullValue,
Language::Nodes::ObjectTypeDefinition,
Language::Nodes::ObjectTypeExtension,
Language::Nodes::OperationDefinition,
Language::Nodes::ScalarTypeDefinition,
Language::Nodes::ScalarTypeExtension,
Language::Nodes::SchemaDefinition,
Language::Nodes::SchemaExtension,
Language::Nodes::TypeName,
Language::Nodes::UnionTypeDefinition,
Language::Nodes::UnionTypeExtension,
Language::Nodes::VariableDefinition,
Language::Nodes::VariableIdentifier,
].each do |ast_node_class|
make_visit_methods(ast_node_class)
end
# rubocop:enable Development/NoEvalCop
private
def apply_modifications(node, parent, new_node_and_new_parent)
if new_node_and_new_parent.is_a?(Array)
new_node = new_node_and_new_parent[0]
new_parent = new_node_and_new_parent[1]
if new_node.is_a?(Nodes::AbstractNode) && !node.equal?(new_node)
# The user-provided hook returned a new node.
new_parent = new_parent && new_parent.replace_child(node, new_node)
return new_node, new_parent
elsif new_node.equal?(DELETE_NODE)
# The user-provided hook requested to remove this node
new_parent = new_parent && new_parent.delete_child(node)
return nil, new_parent
elsif new_node_and_new_parent.none? { |n| n == nil || n.class < Nodes::AbstractNode }
# The user-provided hook returned an array of who-knows-what
# return nil here to signify that no changes should be made
nil
else
new_node_and_new_parent
end
else
# The user-provided hook didn't make any modifications.
# In fact, the hook might have returned who-knows-what, so
# ignore the return value and use the original values.
new_node_and_new_parent
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/generation.rb | lib/graphql/language/generation.rb | # frozen_string_literal: true
module GraphQL
module Language
# Exposes {.generate}, which turns AST nodes back into query strings.
module Generation
extend self
# Turn an AST node back into a string.
#
# @example Turning a document into a query
# document = GraphQL.parse(query_string)
# GraphQL::Language::Generation.generate(document)
# # => "{ ... }"
#
# @param node [GraphQL::Language::Nodes::AbstractNode] an AST node to recursively stringify
# @param indent [String] Whitespace to add to each printed node
# @param printer [GraphQL::Language::Printer] An optional custom printer for printing AST nodes. Defaults to GraphQL::Language::Printer
# @return [String] Valid GraphQL for `node`
def generate(node, indent: "", printer: GraphQL::Language::Printer.new)
printer.print(node, indent: indent)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language/cache.rb | lib/graphql/language/cache.rb | # frozen_string_literal: true
require 'graphql/version'
require 'digest/sha2'
module GraphQL
module Language
# This cache is used by {GraphQL::Language::Parser.parse_file} when it's enabled.
#
# With Rails, parser caching may enabled by setting `config.graphql.parser_cache = true` in your Rails application.
#
# The cache may be manually built by assigning `GraphQL::Language::Parser.cache = GraphQL::Language::Cache.new("some_dir")`.
# This will create a directory (`tmp/cache/graphql` by default) that stores a cache of parsed files.
#
# Much like [bootsnap](https://github.com/Shopify/bootsnap), the parser cache needs to be cleaned up manually.
# You will need to clear the cache directory for each new deployment of your application.
# Also note that the parser cache will grow as your schema is loaded, so the cache directory must be writable.
#
# @see GraphQL::Railtie for simple Rails integration
class Cache
def initialize(path)
@path = path
end
DIGEST = Digest::SHA256.new << GraphQL::VERSION
def fetch(filename)
hash = DIGEST.dup << filename
begin
hash << File.mtime(filename).to_i.to_s
rescue SystemCallError
return yield
end
cache_path = @path.join(hash.to_s)
if cache_path.exist?
Marshal.load(cache_path.read)
else
payload = yield
tmp_path = "#{cache_path}.#{rand}"
@path.mkpath
File.binwrite(tmp_path, Marshal.dump(payload))
File.rename(tmp_path, cache_path.to_s)
payload
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/warden.rb | lib/graphql/schema/warden.rb | # frozen_string_literal: true
require 'set'
module GraphQL
class Schema
# Restrict access to a {GraphQL::Schema} with a user-defined `visible?` implementations.
#
# When validating and executing a query, all access to schema members
# should go through a warden. If you access the schema directly,
# you may show a client something that it shouldn't be allowed to see.
#
# @api private
class Warden
def self.from_context(context)
context.warden || PassThruWarden
rescue NoMethodError
# this might be a hash which won't respond to #warden
PassThruWarden
end
def self.types_from_context(context)
context.types || PassThruWarden
rescue NoMethodError
# this might be a hash which won't respond to #warden
PassThruWarden
end
def self.use(schema)
# no-op
end
# @param visibility_method [Symbol] a Warden method to call for this entry
# @param entry [Object, Array<Object>] One or more definitions for a given name in a GraphQL Schema
# @param context [GraphQL::Query::Context]
# @param warden [Warden]
# @return [Object] `entry` or one of `entry`'s items if exactly one of them is visible for this context
# @return [nil] If neither `entry` nor any of `entry`'s items are visible for this context
def self.visible_entry?(visibility_method, entry, context, warden = Warden.from_context(context))
if entry.is_a?(Array)
visible_item = nil
entry.each do |item|
if warden.public_send(visibility_method, item, context)
if visible_item.nil?
visible_item = item
else
raise DuplicateNamesError.new(
duplicated_name: item.path, duplicated_definition_1: visible_item.inspect, duplicated_definition_2: item.inspect
)
end
end
end
visible_item
elsif warden.public_send(visibility_method, entry, context)
entry
else
nil
end
end
# This is used when a caller provides a Hash for context.
# We want to call the schema's hooks, but we don't have a full-blown warden.
# The `context` arguments to these methods exist purely to simplify the code that
# calls methods on this object, so it will have everything it needs.
class PassThruWarden
class << self
def visible_field?(field, ctx); field.visible?(ctx); end
def visible_argument?(arg, ctx); arg.visible?(ctx); end
def visible_type?(type, ctx); type.visible?(ctx); end
def visible_enum_value?(ev, ctx); ev.visible?(ctx); end
def visible_type_membership?(tm, ctx); tm.visible?(ctx); end
def interface_type_memberships(obj_t, ctx); obj_t.interface_type_memberships; end
def arguments(owner, ctx); owner.arguments(ctx); end
def loadable?(type, ctx); type.visible?(ctx); end
def loadable_possible_types(type, ctx); type.possible_types(ctx); end
def visibility_profile
@visibility_profile ||= Warden::VisibilityProfile.new(self)
end
end
end
class NullWarden
def initialize(_filter = nil, context:, schema:)
@schema = schema
@visibility_profile = Warden::VisibilityProfile.new(self)
end
# No-op, but for compatibility:
attr_writer :skip_warning
attr_reader :visibility_profile
def visible_field?(field_defn, _ctx = nil, owner = nil); true; end
def visible_argument?(arg_defn, _ctx = nil); true; end
def visible_type?(type_defn, _ctx = nil); true; end
def visible_enum_value?(enum_value, _ctx = nil); enum_value.visible?(Query::NullContext.instance); end
def visible_type_membership?(type_membership, _ctx = nil); true; end
def interface_type_memberships(obj_type, _ctx = nil); obj_type.interface_type_memberships; end
def get_type(type_name); @schema.get_type(type_name, Query::NullContext.instance, false); end # rubocop:disable Development/ContextIsPassedCop
def arguments(argument_owner, ctx = nil); argument_owner.all_argument_definitions; end
def enum_values(enum_defn); enum_defn.enum_values(Query::NullContext.instance); end # rubocop:disable Development/ContextIsPassedCop
def get_argument(parent_type, argument_name); parent_type.get_argument(argument_name); end # rubocop:disable Development/ContextIsPassedCop
def types; @schema.types; end # rubocop:disable Development/ContextIsPassedCop
def root_type_for_operation(op_name); @schema.root_type_for_operation(op_name); end
def directives; @schema.directives.values; end
def fields(type_defn); type_defn.all_field_definitions; end # rubocop:disable Development/ContextIsPassedCop
def get_field(parent_type, field_name); @schema.get_field(parent_type, field_name); end
def reachable_type?(type_name); true; end
def loadable?(type, _ctx); true; end
def loadable_possible_types(abstract_type, _ctx); union_type.possible_types; end
def reachable_types; @schema.types.values; end # rubocop:disable Development/ContextIsPassedCop
def possible_types(type_defn); @schema.possible_types(type_defn, Query::NullContext.instance, false); end
def interfaces(obj_type); obj_type.interfaces; end
end
def visibility_profile
@visibility_profile ||= VisibilityProfile.new(self)
end
class VisibilityProfile
def initialize(warden)
@warden = warden
end
def directives
@warden.directives
end
def directive_exists?(dir_name)
@warden.directives.any? { |d| d.graphql_name == dir_name }
end
def type(name)
@warden.get_type(name)
end
def field(owner, field_name)
@warden.get_field(owner, field_name)
end
def argument(owner, arg_name)
@warden.get_argument(owner, arg_name)
end
def query_root
@warden.root_type_for_operation("query")
end
def mutation_root
@warden.root_type_for_operation("mutation")
end
def subscription_root
@warden.root_type_for_operation("subscription")
end
def arguments(owner)
@warden.arguments(owner)
end
def fields(owner)
@warden.fields(owner)
end
def possible_types(type)
@warden.possible_types(type)
end
def enum_values(enum_type)
@warden.enum_values(enum_type)
end
def all_types
@warden.reachable_types
end
def interfaces(obj_type)
@warden.interfaces(obj_type)
end
def loadable?(t, ctx) # TODO remove ctx here?
@warden.loadable?(t, ctx)
end
def loadable_possible_types(t, ctx)
@warden.loadable_possible_types(t, ctx)
end
def reachable_type?(type_name)
!!@warden.reachable_type?(type_name)
end
def visible_enum_value?(enum_value, ctx = nil)
@warden.visible_enum_value?(enum_value, ctx)
end
end
# @param context [GraphQL::Query::Context]
# @param schema [GraphQL::Schema]
def initialize(context:, schema:)
@schema = schema
# Cache these to avoid repeated hits to the inheritance chain when one isn't present
@query = @schema.query
@mutation = @schema.mutation
@subscription = @schema.subscription
@context = context
@visibility_cache = read_through { |m| check_visible(schema, m) }
# Initialize all ivars to improve object shape consistency:
@types = @visible_types = @reachable_types = @visible_parent_fields =
@visible_possible_types = @visible_fields = @visible_arguments = @visible_enum_arrays =
@visible_enum_values = @visible_interfaces = @type_visibility = @type_memberships =
@visible_and_reachable_type = @unions = @unfiltered_interfaces =
@reachable_type_set = @visibility_profile = @loadable_possible_types =
nil
@skip_warning = schema.plugins.any? { |(plugin, _opts)| plugin == GraphQL::Schema::Warden }
end
attr_writer :skip_warning
# @return [Hash<String, GraphQL::BaseType>] Visible types in the schema
def types
@types ||= begin
vis_types = {}
@schema.types(@context).each do |n, t|
if visible_and_reachable_type?(t)
vis_types[n] = t
end
end
vis_types
end
end
# @return [Boolean] True if this type is used for `loads:` but not in the schema otherwise and not _explicitly_ hidden.
def loadable?(type, _ctx)
visible_type?(type) &&
!referenced?(type) &&
(type.respond_to?(:interfaces) ? interfaces(type).all? { |i| loadable?(i, _ctx) } : true)
end
# This abstract type was determined to be used for `loads` only.
# All its possible types are valid possibilities here -- no filtering.
def loadable_possible_types(abstract_type, _ctx)
@loadable_possible_types ||= read_through do |t|
if t.is_a?(Class) # union
t.possible_types
else
@schema.possible_types(abstract_type)
end
end
@loadable_possible_types[abstract_type]
end
# @return [GraphQL::BaseType, nil] The type named `type_name`, if it exists (else `nil`)
def get_type(type_name)
@visible_types ||= read_through do |name|
type_defn = @schema.get_type(name, @context, false)
if type_defn && visible_and_reachable_type?(type_defn)
type_defn
else
nil
end
end
@visible_types[type_name]
end
# @return [Array<GraphQL::BaseType>] Visible and reachable types in the schema
def reachable_types
@reachable_types ||= reachable_type_set.to_a
end
# @return Boolean True if the type is visible and reachable in the schema
def reachable_type?(type_name)
type = get_type(type_name) # rubocop:disable Development/ContextIsPassedCop -- `self` is query-aware
type && reachable_type_set.include?(type)
end
# @return [GraphQL::Field, nil] The field named `field_name` on `parent_type`, if it exists
def get_field(parent_type, field_name)
@visible_parent_fields ||= read_through do |type|
read_through do |f_name|
field_defn = @schema.get_field(type, f_name, @context)
if field_defn && visible_field?(field_defn, nil, type)
field_defn
else
nil
end
end
end
@visible_parent_fields[parent_type][field_name]
end
# @return [GraphQL::Argument, nil] The argument named `argument_name` on `parent_type`, if it exists and is visible
def get_argument(parent_type, argument_name)
argument = parent_type.get_argument(argument_name, @context)
return argument if argument && visible_argument?(argument, @context)
end
# @return [Array<GraphQL::BaseType>] The types which may be member of `type_defn`
def possible_types(type_defn)
@visible_possible_types ||= read_through { |type_defn|
pt = @schema.possible_types(type_defn, @context, false)
pt.select { |t| visible_and_reachable_type?(t) }
}
@visible_possible_types[type_defn]
end
# @param type_defn [GraphQL::ObjectType, GraphQL::InterfaceType]
# @return [Array<GraphQL::Field>] Fields on `type_defn`
def fields(type_defn)
@visible_fields ||= read_through { |t| @schema.get_fields(t, @context).values }
@visible_fields[type_defn]
end
# @param argument_owner [GraphQL::Field, GraphQL::InputObjectType]
# @return [Array<GraphQL::Argument>] Visible arguments on `argument_owner`
def arguments(argument_owner, ctx = nil)
@visible_arguments ||= read_through { |o|
args = o.arguments(@context)
if !args.empty?
args = args.values
args.select! { |a| visible_argument?(a, @context) }
args
else
EmptyObjects::EMPTY_ARRAY
end
}
@visible_arguments[argument_owner]
end
# @return [Array<GraphQL::EnumType::EnumValue>] Visible members of `enum_defn`
def enum_values(enum_defn)
@visible_enum_arrays ||= read_through { |e|
values = e.enum_values(@context)
if values.size == 0
raise GraphQL::Schema::Enum::MissingValuesError.new(e)
end
values
}
@visible_enum_arrays[enum_defn]
end
def visible_enum_value?(enum_value, _ctx = nil)
@visible_enum_values ||= read_through { |ev| visible?(ev) }
@visible_enum_values[enum_value]
end
# @return [Array<GraphQL::InterfaceType>] Visible interfaces implemented by `obj_type`
def interfaces(obj_type)
@visible_interfaces ||= read_through { |t|
ints = t.interfaces(@context)
if !ints.empty?
ints.select! { |i| visible_type?(i) }
end
ints
}
@visible_interfaces[obj_type]
end
def directives
@schema.directives.each_value.select { |d| visible?(d) }
end
def root_type_for_operation(op_name)
root_type = @schema.root_type_for_operation(op_name)
if root_type && visible?(root_type)
root_type
else
nil
end
end
# @param owner [Class, Module] If provided, confirm that field has the given owner.
def visible_field?(field_defn, _ctx = nil, owner = field_defn.owner)
# This field is visible in its own right
visible?(field_defn) &&
# This field's return type is visible
visible_and_reachable_type?(field_defn.type.unwrap) &&
# This field is either defined on this object type,
# or the interface it's inherited from is also visible
((field_defn.respond_to?(:owner) && field_defn.owner == owner) || field_on_visible_interface?(field_defn, owner))
end
def visible_argument?(arg_defn, _ctx = nil)
visible?(arg_defn) && visible_and_reachable_type?(arg_defn.type.unwrap)
end
def visible_type?(type_defn, _ctx = nil)
@type_visibility ||= read_through { |type_defn| visible?(type_defn) }
@type_visibility[type_defn]
end
def visible_type_membership?(type_membership, _ctx = nil)
visible?(type_membership)
end
def interface_type_memberships(obj_type, _ctx = nil)
@type_memberships ||= read_through do |obj_t|
obj_t.interface_type_memberships
end
@type_memberships[obj_type]
end
private
def visible_and_reachable_type?(type_defn)
@visible_and_reachable_type ||= read_through do |type_defn|
next false unless visible_type?(type_defn)
next true if root_type?(type_defn) || type_defn.introspection?
if type_defn.kind.union?
!possible_types(type_defn).empty? && (referenced?(type_defn) || orphan_type?(type_defn))
elsif type_defn.kind.interface?
if !possible_types(type_defn).empty?
true
else
if @context.respond_to?(:logger) && (logger = @context.logger)
logger.debug { "Interface `#{type_defn.graphql_name}` hidden because it has no visible implementers" }
end
false
end
else
if referenced?(type_defn)
true
elsif type_defn.kind.object?
# Show this object if it belongs to ...
interfaces(type_defn).any? { |t| referenced?(t) } || # an interface which is referenced in the schema
union_memberships(type_defn).any? { |t| referenced?(t) || orphan_type?(t) } # or a union which is referenced or added via orphan_types
else
false
end
end
end
@visible_and_reachable_type[type_defn]
end
def union_memberships(obj_type)
@unions ||= read_through { |obj_type| @schema.union_memberships(obj_type).select { |u| visible?(u) } }
@unions[obj_type]
end
# We need this to tell whether a field was inherited by an interface
# even when that interface is hidden from `#interfaces`
def unfiltered_interfaces(type_defn)
@unfiltered_interfaces ||= read_through(&:interfaces)
@unfiltered_interfaces[type_defn]
end
# If this field was inherited from an interface, and the field on that interface is _hidden_,
# then treat this inherited field as hidden.
# (If it _wasn't_ inherited, then don't hide it for this reason.)
def field_on_visible_interface?(field_defn, type_defn)
if type_defn.kind.object?
any_interface_has_field = false
any_interface_has_visible_field = false
ints = unfiltered_interfaces(type_defn)
ints.each do |interface_type|
if (iface_field_defn = interface_type.get_field(field_defn.graphql_name, @context))
any_interface_has_field = true
if interfaces(type_defn).include?(interface_type) && visible_field?(iface_field_defn, nil, interface_type)
any_interface_has_visible_field = true
end
end
end
if any_interface_has_field
any_interface_has_visible_field
else
# it's the object's own field
true
end
else
true
end
end
def root_type?(type_defn)
@query == type_defn ||
@mutation == type_defn ||
@subscription == type_defn
end
def referenced?(type_defn)
members = @schema.references_to(type_defn)
members.any? { |m| visible?(m) }
end
def orphan_type?(type_defn)
@schema.orphan_types.include?(type_defn)
end
def visible?(member)
@visibility_cache[member]
end
def read_through
Hash.new { |h, k| h[k] = yield(k) }.compare_by_identity
end
def check_visible(schema, member)
if schema.visible?(member, @context)
true
elsif @skip_warning
false
else
member_s = member.respond_to?(:path) ? member.path : member.inspect
member_type = case member
when Module
if member.respond_to?(:kind)
member.kind.name.downcase
else
""
end
when GraphQL::Schema::Field
"field"
when GraphQL::Schema::EnumValue
"enum value"
when GraphQL::Schema::Argument
"argument"
else
""
end
schema_s = schema.name ? "#{schema.name}'s" : ""
schema_name = schema.name ? "#{schema.name}" : "your schema"
warn(ADD_WARDEN_WARNING % { schema_s: schema_s, schema_name: schema_name, member: member_s, member_type: member_type })
@skip_warning = true # only warn once per query
# If there's no schema name, add the backtrace for additional context:
if schema_s == ""
puts caller.map { |l| " #{l}"}
end
false
end
end
ADD_WARDEN_WARNING = <<~WARNING
DEPRECATION: %{schema_s} "%{member}" %{member_type} returned `false` for `.visible?` but `GraphQL::Schema::Visibility` isn't configured yet.
Address this warning by adding:
use GraphQL::Schema::Visibility
to the definition for %{schema_name}. (Future GraphQL-Ruby versions won't check `.visible?` methods by default.)
Alternatively, for legacy behavior, add:
use GraphQL::Schema::Warden # legacy visibility behavior
For more information see: https://graphql-ruby.org/authorization/visibility.html
WARNING
def reachable_type_set
return @reachable_type_set if @reachable_type_set
@reachable_type_set = Set.new
rt_hash = {}
unvisited_types = []
['query', 'mutation', 'subscription'].each do |op_name|
root_type = root_type_for_operation(op_name)
unvisited_types << root_type if root_type
end
unvisited_types.concat(@schema.introspection_system.types.values)
directives.each do |dir_class|
arguments(dir_class).each do |arg_defn|
arg_t = arg_defn.type.unwrap
if get_type(arg_t.graphql_name) # rubocop:disable Development/ContextIsPassedCop -- `self` is query-aware
unvisited_types << arg_t
end
end
end
@schema.orphan_types.each do |orphan_type|
if get_type(orphan_type.graphql_name) == orphan_type # rubocop:disable Development/ContextIsPassedCop -- `self` is query-aware
unvisited_types << orphan_type
end
end
included_interface_possible_types_set = Set.new
until unvisited_types.empty?
type = unvisited_types.pop
visit_type(type, unvisited_types, @reachable_type_set, rt_hash, included_interface_possible_types_set, include_interface_possible_types: false)
end
@reachable_type_set
end
def visit_type(type, unvisited_types, visited_type_set, type_by_name_hash, included_interface_possible_types_set, include_interface_possible_types:)
if visited_type_set.add?(type) || (include_interface_possible_types && type.kind.interface? && included_interface_possible_types_set.add?(type))
type_by_name = type_by_name_hash[type.graphql_name] ||= type
if type_by_name != type
name_1, name_2 = [type.inspect, type_by_name.inspect].sort
raise DuplicateNamesError.new(
duplicated_name: type.graphql_name, duplicated_definition_1: name_1, duplicated_definition_2: name_2
)
end
if type.kind.input_object?
# recurse into visible arguments
arguments(type).each do |argument|
argument_type = argument.type.unwrap
unvisited_types << argument_type
end
elsif type.kind.union?
# recurse into visible possible types
possible_types(type).each do |possible_type|
unvisited_types << possible_type
end
elsif type.kind.fields?
if type.kind.object?
# recurse into visible implemented interfaces
interfaces(type).each do |interface|
unvisited_types << interface
end
elsif include_interface_possible_types
possible_types(type).each do |pt|
unvisited_types << pt
end
end
# Don't visit interface possible types -- it's not enough to justify visibility
# recurse into visible fields
fields(type).each do |field|
field_type = field.type.unwrap
# In this case, if it's an interface, we want to include
visit_type(field_type, unvisited_types, visited_type_set, type_by_name_hash, included_interface_possible_types_set, include_interface_possible_types: true)
# recurse into visible arguments
arguments(field).each do |argument|
argument_type = argument.type.unwrap
unvisited_types << argument_type
end
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/unique_within_type.rb | lib/graphql/schema/unique_within_type.rb | # frozen_string_literal: true
require "base64"
module GraphQL
class Schema
module UniqueWithinType
class << self
attr_accessor :default_id_separator
end
self.default_id_separator = "-"
module_function
# @param type_name [String]
# @param object_value [Any]
# @return [String] a unique, opaque ID generated as a function of the two inputs
def encode(type_name, object_value, separator: self.default_id_separator)
object_value_str = object_value.to_s
if type_name.include?(separator)
raise "encode(#{type_name}, #{object_value_str}) contains reserved characters `#{separator}` in the type name"
end
Base64.strict_encode64([type_name, object_value_str].join(separator))
end
# @param node_id [String] A unique ID generated by {.encode}
# @return [Array<(String, String)>] The type name & value passed to {.encode}
def decode(node_id, separator: self.default_id_separator)
GraphQL::Schema::Base64Encoder.decode(node_id).split(separator, 2)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/subscription.rb | lib/graphql/schema/subscription.rb | # frozen_string_literal: true
module GraphQL
class Schema
# This class can be extended to create fields on your subscription root.
#
# It provides hooks for the different parts of the subscription lifecycle:
#
# - `#authorized?`: called before initial subscription and subsequent updates
# - `#subscribe`: called for the initial subscription
# - `#update`: called for subsequent update
#
# Also, `#unsubscribe` terminates the subscription.
class Subscription < GraphQL::Schema::Resolver
extend GraphQL::Schema::Resolver::HasPayloadType
extend GraphQL::Schema::Member::HasFields
NO_UPDATE = :no_update
# The generated payload type is required; If there's no payload,
# propagate null.
null false
# @api private
def initialize(object:, context:, field:)
super
# Figure out whether this is an update or an initial subscription
@mode = context.query.subscription_update? ? :update : :subscribe
@subscription_written = false
@original_arguments = nil
if (subs_ns = context.namespace(:subscriptions)) &&
(sub_insts = subs_ns[:subscriptions])
sub_insts[context.current_path] = self
end
end
# @api private
def resolve_with_support(**args)
@original_arguments = args # before `loads:` have been run
result = nil
unsubscribed = true
unsubscribed_result = catch :graphql_subscription_unsubscribed do
result = super
unsubscribed = false
end
if unsubscribed
if unsubscribed_result
context.namespace(:subscriptions)[:final_update] = true
unsubscribed_result
else
context.skip
end
else
result
end
end
# Implement the {Resolve} API.
# You can implement this if you want code to run for _both_ the initial subscription
# and for later updates. Or, implement {#subscribe} and {#update}
def resolve(**args)
# Dispatch based on `@mode`, which will raise a `NoMethodError` if we ever
# have an unexpected `@mode`
public_send("resolve_#{@mode}", **args)
end
# Wrap the user-defined `#subscribe` hook
# @api private
def resolve_subscribe(**args)
ret_val = !args.empty? ? subscribe(**args) : subscribe
if ret_val == :no_response
context.skip
else
ret_val
end
end
# The default implementation returns nothing on subscribe.
# Override it to return an object or
# `:no_response` to (explicitly) return nothing.
def subscribe(args = {})
:no_response
end
# Wrap the user-provided `#update` hook
# @api private
def resolve_update(**args)
ret_val = !args.empty? ? update(**args) : update
if ret_val == NO_UPDATE
context.namespace(:subscriptions)[:no_update] = true
context.skip
else
ret_val
end
end
# The default implementation returns the root object.
# Override it to return {NO_UPDATE} if you want to
# skip updates sometimes. Or override it to return a different object.
def update(args = {})
object
end
# If an argument is flagged with `loads:` and no object is found for it,
# remove this subscription (assuming that the object was deleted in the meantime,
# or that it became inaccessible).
def load_application_object_failed(err)
if @mode == :update
unsubscribe
end
super
end
# Call this to halt execution and remove this subscription from the system
# @param update_value [Object] if present, deliver this update before unsubscribing
# @return [void]
def unsubscribe(update_value = nil)
context.namespace(:subscriptions)[:unsubscribed] = true
throw :graphql_subscription_unsubscribed, update_value
end
# Call this method to provide a new subscription_scope; OR
# call it without an argument to get the subscription_scope
# @param new_scope [Symbol]
# @param optional [Boolean] If true, then don't require `scope:` to be provided to updates to this subscription.
# @return [Symbol]
def self.subscription_scope(new_scope = NOT_CONFIGURED, optional: false)
if new_scope != NOT_CONFIGURED
@subscription_scope = new_scope
@subscription_scope_optional = optional
elsif defined?(@subscription_scope)
@subscription_scope
else
find_inherited_value(:subscription_scope)
end
end
def self.subscription_scope_optional?
if defined?(@subscription_scope_optional)
@subscription_scope_optional
else
find_inherited_value(:subscription_scope_optional, false)
end
end
# This is called during initial subscription to get a "name" for this subscription.
# Later, when `.trigger` is called, this will be called again to build another "name".
# Any subscribers with matching topic will begin the update flow.
#
# The default implementation creates a string using the field name, subscription scope, and argument keys and values.
# In that implementation, only `.trigger` calls with _exact matches_ result in updates to subscribers.
#
# To implement a filtered stream-type subscription flow, override this method to return a string with field name and subscription scope.
# Then, implement {#update} to compare its arguments to the current `object` and return {NO_UPDATE} when an
# update should be filtered out.
#
# @see {#update} for how to skip updates when an event comes with a matching topic.
# @param arguments [Hash<String => Object>] The arguments for this topic, in GraphQL-style (camelized strings)
# @param field [GraphQL::Schema::Field]
# @param scope [Object, nil] A value corresponding to `.trigger(... scope:)` (for updates) or the `subscription_scope` found in `context` (for initial subscriptions).
# @return [String] An identifier corresponding to a stream of updates
def self.topic_for(arguments:, field:, scope:)
Subscriptions::Serialize.dump_recursive([scope, field.graphql_name, arguments])
end
# Calls through to `schema.subscriptions` to register this subscription with the backend.
# This is automatically called by GraphQL-Ruby after a query finishes successfully,
# but if you need to commit the subscription during `#subscribe`, you can call it there.
# (This method also sets a flag showing that this subscription was already written.)
#
# If you call this method yourself, you may also need to {#unsubscribe}
# or call `subscriptions.delete_subscription` to clean up the database if the query crashes with an error
# later in execution.
# @return [void]
def write_subscription
if subscription_written?
raise GraphQL::Error, "`write_subscription` was called but `#{self.class}#subscription_written?` is already true. Remove a call to `write subscription`."
else
@subscription_written = true
context.schema.subscriptions.write_subscription(context.query, [event])
end
nil
end
# @return [Boolean] `true` if {#write_subscription} was called already
def subscription_written?
@subscription_written
end
# @return [Subscriptions::Event] This object is used as a representation of this subscription for the backend
def event
@event ||= Subscriptions::Event.new(
name: field.name,
arguments: @original_arguments,
context: context,
field: field,
)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/mutation.rb | lib/graphql/schema/mutation.rb | # frozen_string_literal: true
module GraphQL
class Schema
# This base class accepts configuration for a mutation root field,
# then it can be hooked up to your mutation root object type.
#
# If you want to customize how this class generates types, in your base class,
# override the various `generate_*` methods.
#
# @see {GraphQL::Schema::RelayClassicMutation} for an extension of this class with some conventions built-in.
#
# @example Creating a comment
# # Define the mutation:
# class Mutations::CreateComment < GraphQL::Schema::Mutation
# argument :body, String, required: true
# argument :post_id, ID, required: true
#
# field :comment, Types::Comment, null: true
# field :errors, [String], null: false
#
# def resolve(body:, post_id:)
# post = Post.find(post_id)
# comment = post.comments.build(body: body, author: context[:current_user])
# if comment.save
# # Successful creation, return the created object with no errors
# {
# comment: comment,
# errors: [],
# }
# else
# # Failed save, return the errors to the client
# {
# comment: nil,
# errors: comment.errors.full_messages
# }
# end
# end
# end
#
# # Hook it up to your mutation:
# class Types::Mutation < GraphQL::Schema::Object
# field :create_comment, mutation: Mutations::CreateComment
# end
#
# # Call it from GraphQL:
# result = MySchema.execute <<-GRAPHQL
# mutation {
# createComment(postId: "1", body: "Nice Post!") {
# errors
# comment {
# body
# author {
# login
# }
# }
# }
# }
# GRAPHQL
#
class Mutation < GraphQL::Schema::Resolver
extend GraphQL::Schema::Member::HasFields
extend GraphQL::Schema::Resolver::HasPayloadType
# @api private
def call_resolve(_args_hash)
# Clear any cached values from `loads` or authorization:
dataloader.clear_cache
super
end
class << self
def visible?(context)
true
end
private
def conflict_field_name_warning(field_defn)
"#{self.graphql_name}'s `field :#{field_defn.name}` conflicts with a built-in method, use `hash_key:` or `method:` to pick a different resolve behavior for this field (for example, `hash_key: :#{field_defn.resolver_method}_value`, and modify the return hash). Or use `method_conflict_warning: false` to suppress this warning."
end
# Override this to attach self as `mutation`
def generate_payload_type
payload_class = super
payload_class.mutation(self)
payload_class
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/member.rb | lib/graphql/schema/member.rb | # frozen_string_literal: true
require 'graphql/schema/member/base_dsl_methods'
require 'graphql/schema/member/graphql_type_names'
require 'graphql/schema/member/has_ast_node'
require 'graphql/schema/member/has_dataloader'
require 'graphql/schema/member/has_directives'
require 'graphql/schema/member/has_deprecation_reason'
require 'graphql/schema/member/has_interfaces'
require 'graphql/schema/member/has_path'
require 'graphql/schema/member/has_unresolved_type_error'
require 'graphql/schema/member/has_validators'
require 'graphql/schema/member/relay_shortcuts'
require 'graphql/schema/member/scoped'
require 'graphql/schema/member/type_system_helpers'
require 'graphql/schema/member/validates_input'
module GraphQL
class Schema
# The base class for things that make up the schema,
# eg objects, enums, scalars.
#
# @api private
class Member
include GraphQLTypeNames
extend BaseDSLMethods
extend BaseDSLMethods::ConfigurationExtension
introspection(false)
extend TypeSystemHelpers
extend Scoped
extend RelayShortcuts
extend HasPath
extend HasAstNode
extend HasDirectives
end
end
end
require 'graphql/schema/member/has_arguments'
require 'graphql/schema/member/has_fields'
require 'graphql/schema/member/build_type'
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/non_null.rb | lib/graphql/schema/non_null.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Represents a non null type in the schema.
# Wraps a {Schema::Member} when it is required.
# @see {Schema::Member::TypeSystemHelpers#to_non_null_type}
class NonNull < GraphQL::Schema::Wrapper
include Schema::Member::ValidatesInput
# @return [GraphQL::TypeKinds::NON_NULL]
def kind
GraphQL::TypeKinds::NON_NULL
end
# @return [true]
def non_null?
true
end
# @return [Boolean] True if this type wraps a list type
def list?
@of_type.list?
end
def to_type_signature
"#{@of_type.to_type_signature}!"
end
def inspect
"#<#{self.class.name} @of_type=#{@of_type.inspect}>"
end
def validate_input(value, ctx, max_errors: nil)
if value.nil?
result = GraphQL::Query::InputValidationResult.new
result.add_problem("Expected value to not be null")
result
else
of_type.validate_input(value, ctx, max_errors: max_errors)
end
end
# This is for introspection, where it's expected the name will be `null`
def graphql_name
nil
end
def coerce_input(value, ctx)
# `.validate_input` above is used for variables, but this method is used for arguments
if value.nil?
raise GraphQL::ExecutionError, "`null` is not a valid input for `#{to_type_signature}`, please provide a value for this argument."
end
of_type.coerce_input(value, ctx)
end
def coerce_result(value, ctx)
of_type.coerce_result(value, ctx)
end
# This is for implementing introspection
def description
nil
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/timeout.rb | lib/graphql/schema/timeout.rb | # frozen_string_literal: true
module GraphQL
class Schema
# This plugin will stop resolving new fields after `max_seconds` have elapsed.
# After the time has passed, any remaining fields will be `nil`, with errors added
# to the `errors` key. Any already-resolved fields will be in the `data` key, so
# you'll get a partial response.
#
# You can subclass `GraphQL::Schema::Timeout` and override `max_seconds` and/or `handle_timeout`
# to provide custom logic when a timeout error occurs.
#
# Note that this will stop a query _in between_ field resolutions, but
# it doesn't interrupt long-running `resolve` functions. Be sure to use
# timeout options for external connections. For more info, see
# www.mikeperham.com/2015/05/08/timeout-rubys-most-dangerous-api/
#
# @example Stop resolving fields after 2 seconds
# class MySchema < GraphQL::Schema
# use GraphQL::Schema::Timeout, max_seconds: 2
# end
#
# @example Notifying Bugsnag and logging a timeout
# class MyTimeout < GraphQL::Schema::Timeout
# def handle_timeout(error, query)
# Rails.logger.warn("GraphQL Timeout: #{error.message}: #{query.query_string}")
# Bugsnag.notify(error, {query_string: query.query_string})
# end
# end
#
# class MySchema < GraphQL::Schema
# use MyTimeout, max_seconds: 2
# end
#
class Timeout
def self.use(schema, max_seconds: nil)
timeout = self.new(max_seconds: max_seconds)
schema.trace_with(self::Trace, timeout: timeout)
end
def initialize(max_seconds:)
@max_seconds = max_seconds
end
module Trace
# @param max_seconds [Numeric] how many seconds the query should be allowed to resolve new fields
def initialize(timeout:, **rest)
@timeout = timeout
super
end
def execute_multiplex(multiplex:)
multiplex.queries.each do |query|
timeout_duration_s = @timeout.max_seconds(query)
timeout_state = if timeout_duration_s == false
# if the method returns `false`, don't apply a timeout
false
else
now = Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond)
timeout_at = now + (timeout_duration_s * 1000)
{
timeout_at: timeout_at,
timed_out: false
}
end
query.context.namespace(@timeout)[:state] = timeout_state
end
super
end
def execute_field(query:, field:, **_rest)
timeout_state = query.context.namespace(@timeout).fetch(:state)
# If the `:state` is `false`, then `max_seconds(query)` opted out of timeout for this query.
if timeout_state == false
super
elsif Process.clock_gettime(Process::CLOCK_MONOTONIC, :millisecond) > timeout_state.fetch(:timeout_at)
error = GraphQL::Schema::Timeout::TimeoutError.new(field)
# Only invoke the timeout callback for the first timeout
if !timeout_state[:timed_out]
timeout_state[:timed_out] = true
@timeout.handle_timeout(error, query)
timeout_state = query.context.namespace(@timeout).fetch(:state)
end
# `handle_timeout` may have set this to be `false`
if timeout_state != false
error
else
super
end
else
super
end
end
end
# Called at the start of each query.
# The default implementation returns the `max_seconds:` value from installing this plugin.
#
# @param query [GraphQL::Query] The query that's about to run
# @return [Numeric, false] The number of seconds after which to interrupt query execution and call {#handle_error}, or `false` to bypass the timeout.
def max_seconds(query)
@max_seconds
end
# Invoked when a query times out.
# @param error [GraphQL::Schema::Timeout::TimeoutError]
# @param query [GraphQL::Error]
def handle_timeout(error, query)
# override to do something interesting
end
# Call this method (eg, from {#handle_timeout}) to disable timeout tracking
# for the given query.
# @param query [GraphQL::Query]
# @return [void]
def disable_timeout(query)
query.context.namespace(self)[:state] = false
nil
end
# This error is raised when a query exceeds `max_seconds`.
# Since it's a child of {GraphQL::ExecutionError},
# its message will be added to the response's `errors` key.
#
# To raise an error that will stop query resolution, use a custom block
# to take this error and raise a new one which _doesn't_ descend from {GraphQL::ExecutionError},
# such as `RuntimeError`.
class TimeoutError < GraphQL::ExecutionError
def initialize(field)
super("Timeout on #{field.path}")
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/find_inherited_value.rb | lib/graphql/schema/find_inherited_value.rb | # frozen_string_literal: true
module GraphQL
class Schema
module FindInheritedValue
def self.extended(child_cls)
child_cls.singleton_class.include(GraphQL::EmptyObjects)
end
def self.included(child_cls)
child_cls.include(GraphQL::EmptyObjects)
end
private
def find_inherited_value(method_name, default_value = nil)
if self.is_a?(Class)
superclass.respond_to?(method_name, true) ? superclass.send(method_name) : default_value
else
ancestors_except_self = ancestors
ancestors_except_self.delete(self)
ancestors_except_self.each do |ancestor|
if ancestor.respond_to?(method_name, true)
return ancestor.send(method_name)
end
end
default_value
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/interface.rb | lib/graphql/schema/interface.rb | # frozen_string_literal: true
module GraphQL
class Schema
module Interface
include GraphQL::Schema::Member::GraphQLTypeNames
module DefinitionMethods
include GraphQL::Schema::Member::BaseDSLMethods
# ConfigurationExtension's responsibilities are in `def included` below
include GraphQL::Schema::Member::TypeSystemHelpers
include GraphQL::Schema::Member::HasFields
include GraphQL::Schema::Member::HasPath
include GraphQL::Schema::Member::RelayShortcuts
include GraphQL::Schema::Member::Scoped
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasUnresolvedTypeError
include GraphQL::Schema::Member::HasDataloader
include GraphQL::Schema::Member::HasDirectives
include GraphQL::Schema::Member::HasInterfaces
# Methods defined in this block will be:
# - Added as class methods to this interface
# - Added as class methods to all child interfaces
def definition_methods(&block)
# Use an instance variable to tell whether it's been included previously or not;
# You can't use constant detection because constants are brought into scope
# by `include`, which has already happened at this point.
if !defined?(@_definition_methods)
defn_methods_module = Module.new
@_definition_methods = defn_methods_module
const_set(:DefinitionMethods, defn_methods_module)
extend(self::DefinitionMethods)
end
self::DefinitionMethods.module_exec(&block)
end
# @see {Schema::Warden} hides interfaces without visible implementations
def visible?(context)
true
end
def type_membership_class(membership_class = nil)
if membership_class
@type_membership_class = membership_class
else
@type_membership_class || find_inherited_value(:type_membership_class, GraphQL::Schema::TypeMembership)
end
end
# Here's the tricky part. Make sure behavior keeps making its way down the inheritance chain.
def included(child_class)
if !child_class.is_a?(Class)
# In this case, it's been included into another interface.
# This is how interface inheritance is implemented
# We need this before we can call `own_interfaces`
child_class.extend(Schema::Interface::DefinitionMethods)
child_class.type_membership_class(self.type_membership_class)
child_class.ancestors.reverse_each do |ancestor|
if ancestor.const_defined?(:DefinitionMethods) && ancestor != child_class
child_class.extend(ancestor::DefinitionMethods)
end
end
child_class.introspection(introspection)
child_class.description(description)
child_class.comment(nil)
# If interfaces are mixed into each other, only define this class once
if !child_class.const_defined?(:UnresolvedTypeError, false)
add_unresolved_type_error(child_class)
end
elsif child_class < GraphQL::Schema::Object
# This is being included into an object type, make sure it's using `implements(...)`
backtrace_line = caller_locations(0, 10).find do |location|
location.base_label == "implements" &&
location.path.end_with?("schema/member/has_interfaces.rb")
end
if !backtrace_line
raise "Attach interfaces using `implements(#{self})`, not `include(#{self})`"
end
end
super
end
# Register other Interface or Object types as implementers of this Interface.
#
# When those Interfaces or Objects aren't used as the return values of fields,
# they may have to be registered using this method so that GraphQL-Ruby can find them.
# @param types [Class, Module]
# @return [Array<Module, Class>] Implementers of this interface, if they're registered
def orphan_types(*types)
if !types.empty?
@orphan_types ||= []
@orphan_types.concat(types)
else
if defined?(@orphan_types)
all_orphan_types = @orphan_types.dup
if defined?(super)
all_orphan_types += super
all_orphan_types.uniq!
end
all_orphan_types
elsif defined?(super)
super
else
EmptyObjects::EMPTY_ARRAY
end
end
end
def kind
GraphQL::TypeKinds::INTERFACE
end
end
extend DefinitionMethods
def unwrap
self
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/introspection_system.rb | lib/graphql/schema/introspection_system.rb | # frozen_string_literal: true
module GraphQL
class Schema
class IntrospectionSystem
attr_reader :types, :possible_types
def initialize(schema)
@schema = schema
@class_based = !!@schema.is_a?(Class)
@built_in_namespace = GraphQL::Introspection
@custom_namespace = if @class_based
schema.introspection || @built_in_namespace
else
schema.introspection_namespace || @built_in_namespace
end
type_defns = [
load_constant(:SchemaType),
load_constant(:TypeType),
load_constant(:FieldType),
load_constant(:DirectiveType),
load_constant(:EnumValueType),
load_constant(:InputValueType),
load_constant(:TypeKindEnum),
load_constant(:DirectiveLocationEnum)
]
@types = {}
@possible_types = {}.compare_by_identity
type_defns.each do |t|
@types[t.graphql_name] = t
@possible_types[t] = [t]
end
@entry_point_fields =
if schema.disable_introspection_entry_points?
{}
else
entry_point_fields = get_fields_from_class(class_sym: :EntryPoints)
entry_point_fields.delete('__schema') if schema.disable_schema_introspection_entry_point?
entry_point_fields.delete('__type') if schema.disable_type_introspection_entry_point?
entry_point_fields
end
@entry_point_fields.each { |k, v| v.dynamic_introspection = true }
@dynamic_fields = get_fields_from_class(class_sym: :DynamicFields)
@dynamic_fields.each { |k, v| v.dynamic_introspection = true }
end
def entry_points
@entry_point_fields.values
end
def entry_point(name:)
@entry_point_fields[name]
end
def dynamic_fields
@dynamic_fields.values
end
def dynamic_field(name:)
@dynamic_fields[name]
end
# The introspection system is prepared with a bunch of LateBoundTypes.
# Replace those with the objects that they refer to, since LateBoundTypes
# aren't handled at runtime.
#
# @api private
# @return void
def resolve_late_bindings
@types.each do |name, t|
if t.kind.fields?
t.all_field_definitions.each do |field_defn|
field_defn.type = resolve_late_binding(field_defn.type)
end
end
end
@entry_point_fields.each do |name, f|
f.type = resolve_late_binding(f.type)
end
@dynamic_fields.each do |name, f|
f.type = resolve_late_binding(f.type)
end
nil
end
private
def resolve_late_binding(late_bound_type)
case late_bound_type
when GraphQL::Schema::LateBoundType
type_name = late_bound_type.name
@types[type_name] || @schema.get_type(type_name)
when GraphQL::Schema::List
resolve_late_binding(late_bound_type.of_type).to_list_type
when GraphQL::Schema::NonNull
resolve_late_binding(late_bound_type.of_type).to_non_null_type
when Module
# It's a normal type -- no change required
late_bound_type
else
raise "Invariant: unexpected type: #{late_bound_type} (#{late_bound_type.class})"
end
end
def load_constant(class_name)
const = @custom_namespace.const_get(class_name)
dup_type_class(const)
rescue NameError
# Dup the built-in so that the cached fields aren't shared
dup_type_class(@built_in_namespace.const_get(class_name))
end
def get_fields_from_class(class_sym:)
object_type_defn = load_constant(class_sym)
object_type_defn.fields
end
# This is probably not 100% robust -- but it has to be good enough to avoid modifying the built-in introspection types
def dup_type_class(type_class)
type_name = type_class.graphql_name
Class.new(type_class) do
# This won't be inherited like other things will
graphql_name(type_name)
if type_class.kind.fields?
type_class.fields.each do |_name, field_defn|
dup_field = field_defn.dup
dup_field.owner = self
add_field(dup_field)
end
end
end
end
class PerFieldProxyResolve
def initialize(object_class:, inner_resolve:)
@object_class = object_class
@inner_resolve = inner_resolve
end
def call(obj, args, ctx)
query_ctx = ctx.query.context
# Remove the QueryType wrapper
if obj.is_a?(GraphQL::Schema::Object)
obj = obj.object
end
wrapped_object = @object_class.wrap(obj, query_ctx)
@inner_resolve.call(wrapped_object, args, ctx)
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/field.rb | lib/graphql/schema/field.rb | # frozen_string_literal: true
require "graphql/schema/field/connection_extension"
require "graphql/schema/field/scope_extension"
module GraphQL
class Schema
class Field
include GraphQL::Schema::Member::HasArguments
include GraphQL::Schema::Member::HasArguments::FieldConfigured
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasPath
include GraphQL::Schema::Member::HasValidators
extend GraphQL::Schema::FindInheritedValue
include GraphQL::EmptyObjects
include GraphQL::Schema::Member::HasDirectives
include GraphQL::Schema::Member::HasDeprecationReason
class FieldImplementationFailed < GraphQL::Error; end
# @return [String] the GraphQL name for this field, camelized unless `camelize: false` is provided
attr_reader :name
alias :graphql_name :name
attr_writer :description
# @return [Symbol] Method or hash key on the underlying object to look up
attr_reader :method_sym
# @return [String] Method or hash key on the underlying object to look up
attr_reader :method_str
attr_reader :hash_key
attr_reader :dig_keys
# @return [Symbol] The method on the type to look up
def resolver_method
if @resolver_class
@resolver_class.resolver_method
else
@resolver_method
end
end
# @return [String, nil]
def deprecation_reason
super || @resolver_class&.deprecation_reason
end
def directives
if @resolver_class && !(r_dirs = @resolver_class.directives).empty?
if !(own_dirs = super).empty?
new_dirs = own_dirs.dup
r_dirs.each do |r_dir|
if r_dir.class.repeatable? ||
( (r_dir_name = r_dir.graphql_name) &&
(!new_dirs.any? { |d| d.graphql_name == r_dir_name })
)
new_dirs << r_dir
end
end
new_dirs
else
r_dirs
end
else
super
end
end
# @return [Class] The thing this field was defined on (type, mutation, resolver)
attr_accessor :owner
# @return [Class] The GraphQL type this field belongs to. (For fields defined on mutations, it's the payload type)
def owner_type
@owner_type ||= if owner.nil?
raise GraphQL::InvariantError, "Field #{original_name.inspect} (graphql name: #{graphql_name.inspect}) has no owner, but all fields should have an owner. How did this happen?!"
elsif owner < GraphQL::Schema::Mutation
owner.payload_type
else
owner
end
end
# @return [Symbol] the original name of the field, passed in by the user
attr_reader :original_name
# @return [Class, nil] The {Schema::Resolver} this field was derived from, if there is one
def resolver
@resolver_class
end
# @return [Boolean] Is this field a predefined introspection field?
def introspection?
@introspection
end
def inspect
"#<#{self.class} #{path}#{!all_argument_definitions.empty? ? "(...)" : ""}: #{type.to_type_signature}>"
end
alias :mutation :resolver
# @return [Boolean] Apply tracing to this field? (Default: skip scalars, this is the override value)
attr_reader :trace
# @return [String, nil]
def subscription_scope
@subscription_scope || (@resolver_class.respond_to?(:subscription_scope) ? @resolver_class.subscription_scope : nil)
end
attr_writer :subscription_scope
# Create a field instance from a list of arguments, keyword arguments, and a block.
#
# This method implements prioritization between the `resolver` or `mutation` defaults
# and the local overrides via other keywords.
#
# It also normalizes positional arguments into keywords for {Schema::Field#initialize}.
# @param resolver [Class] A {GraphQL::Schema::Resolver} class to use for field configuration
# @param mutation [Class] A {GraphQL::Schema::Mutation} class to use for field configuration
# @param subscription [Class] A {GraphQL::Schema::Subscription} class to use for field configuration
# @return [GraphQL::Schema:Field] an instance of `self`
# @see {.initialize} for other options
def self.from_options(name = nil, type = nil, desc = nil, comment: nil, resolver: nil, mutation: nil, subscription: nil,**kwargs, &block)
if (resolver_class = resolver || mutation || subscription)
# Add a reference to that parent class
kwargs[:resolver_class] = resolver_class
end
if name
kwargs[:name] = name
end
if comment
kwargs[:comment] = comment
end
if !type.nil?
if desc
if kwargs[:description]
raise ArgumentError, "Provide description as a positional argument or `description:` keyword, but not both (#{desc.inspect}, #{kwargs[:description].inspect})"
end
kwargs[:description] = desc
kwargs[:type] = type
elsif (resolver || mutation) && type.is_a?(String)
# The return type should be copied from the resolver, and the second positional argument is the description
kwargs[:description] = type
else
kwargs[:type] = type
end
if type.is_a?(Class) && type < GraphQL::Schema::Mutation
raise ArgumentError, "Use `field #{name.inspect}, mutation: Mutation, ...` to provide a mutation to this field instead"
end
end
new(**kwargs, &block)
end
# Can be set with `connection: true|false` or inferred from a type name ending in `*Connection`
# @return [Boolean] if true, this field will be wrapped with Relay connection behavior
def connection?
if @connection.nil?
# Provide default based on type name
return_type_name = if @return_type_expr
Member::BuildType.to_type_name(@return_type_expr)
elsif @resolver_class && @resolver_class.type
Member::BuildType.to_type_name(@resolver_class.type)
elsif type
# As a last ditch, try to force loading the return type:
type.unwrap.name
end
if return_type_name
@connection = return_type_name.end_with?("Connection") && return_type_name != "Connection"
else
# TODO set this when type is set by method
false # not loaded yet?
end
else
@connection
end
end
# @return [Boolean] if true, the return type's `.scope_items` method will be applied to this field's return value
def scoped?
if !@scope.nil?
# The default was overridden
@scope
elsif @return_type_expr
# Detect a list return type, but don't call `type` since that may eager-load an otherwise lazy-loaded type
@return_type_expr.is_a?(Array) ||
(@return_type_expr.is_a?(String) && @return_type_expr.include?("[")) ||
connection?
elsif @resolver_class
resolver_type = @resolver_class.type_expr
resolver_type.is_a?(Array) ||
(resolver_type.is_a?(String) && resolver_type.include?("[")) ||
connection?
else
false
end
end
# This extension is applied to fields when {#connection?} is true.
#
# You can override it in your base field definition.
# @return [Class] A {FieldExtension} subclass for implementing pagination behavior.
# @example Configuring a custom extension
# class Types::BaseField < GraphQL::Schema::Field
# connection_extension(MyCustomExtension)
# end
def self.connection_extension(new_extension_class = nil)
if new_extension_class
@connection_extension = new_extension_class
else
@connection_extension ||= find_inherited_value(:connection_extension, ConnectionExtension)
end
end
# @return Boolean
attr_reader :relay_node_field
# @return Boolean
attr_reader :relay_nodes_field
# @return [Boolean] Should we warn if this field's name conflicts with a built-in method?
def method_conflict_warning?
@method_conflict_warning
end
# @param name [Symbol] The underscore-cased version of this field name (will be camelized for the GraphQL API)
# @param type [Class, GraphQL::BaseType, Array] The return type of this field
# @param owner [Class] The type that this field belongs to
# @param null [Boolean] (defaults to `true`) `true` if this field may return `null`, `false` if it is never `null`
# @param description [String] Field description
# @param comment [String] Field comment
# @param deprecation_reason [String] If present, the field is marked "deprecated" with this message
# @param method [Symbol] The method to call on the underlying object to resolve this field (defaults to `name`)
# @param hash_key [String, Symbol] The hash key to lookup on the underlying object (if its a Hash) to resolve this field (defaults to `name` or `name.to_s`)
# @param dig [Array<String, Symbol>] The nested hash keys to lookup on the underlying hash to resolve this field using dig
# @param resolver_method [Symbol] The method on the type to call to resolve this field (defaults to `name`)
# @param connection [Boolean] `true` if this field should get automagic connection behavior; default is to infer by `*Connection` in the return type name
# @param connection_extension [Class] The extension to add, to implement connections. If `nil`, no extension is added.
# @param max_page_size [Integer, nil] For connections, the maximum number of items to return from this field, or `nil` to allow unlimited results.
# @param default_page_size [Integer, nil] For connections, the default number of items to return from this field, or `nil` to return unlimited results.
# @param introspection [Boolean] If true, this field will be marked as `#introspection?` and the name may begin with `__`
# @param resolver_class [Class] (Private) A {Schema::Resolver} which this field was derived from. Use `resolver:` to create a field with a resolver.
# @param arguments [{String=>GraphQL::Schema::Argument, Hash}] Arguments for this field (may be added in the block, also)
# @param camelize [Boolean] If true, the field name will be camelized when building the schema
# @param complexity [Numeric] When provided, set the complexity for this field
# @param scope [Boolean] If true, the return type's `.scope_items` method will be called on the return value
# @param subscription_scope [Symbol, String] A key in `context` which will be used to scope subscription payloads
# @param extensions [Array<Class, Hash<Class => Object>>] Named extensions to apply to this field (see also {#extension})
# @param directives [Hash{Class => Hash}] Directives to apply to this field
# @param trace [Boolean] If true, a {GraphQL::Tracing} tracer will measure this scalar field
# @param broadcastable [Boolean] Whether or not this field can be distributed in subscription broadcasts
# @param ast_node [Language::Nodes::FieldDefinition, nil] If this schema was parsed from definition, this AST node defined the field
# @param method_conflict_warning [Boolean] If false, skip the warning if this field's method conflicts with a built-in method
# @param validates [Array<Hash>] Configurations for validating this field
# @param fallback_value [Object] A fallback value if the method is not defined
def initialize(type: nil, name: nil, owner: nil, null: nil, description: NOT_CONFIGURED, comment: NOT_CONFIGURED, deprecation_reason: nil, method: nil, hash_key: nil, dig: nil, resolver_method: nil, connection: nil, max_page_size: NOT_CONFIGURED, default_page_size: NOT_CONFIGURED, scope: nil, introspection: false, camelize: true, trace: nil, complexity: nil, ast_node: nil, extras: EMPTY_ARRAY, extensions: EMPTY_ARRAY, connection_extension: self.class.connection_extension, resolver_class: nil, subscription_scope: nil, relay_node_field: false, relay_nodes_field: false, method_conflict_warning: true, broadcastable: NOT_CONFIGURED, arguments: EMPTY_HASH, directives: EMPTY_HASH, validates: EMPTY_ARRAY, fallback_value: NOT_CONFIGURED, dynamic_introspection: false, &definition_block)
if name.nil?
raise ArgumentError, "missing first `name` argument or keyword `name:`"
end
if !(resolver_class)
if type.nil? && !block_given?
raise ArgumentError, "missing second `type` argument, keyword `type:`, or a block containing `type(...)`"
end
end
@original_name = name
name_s = -name.to_s
@underscored_name = -Member::BuildType.underscore(name_s)
@name = -(camelize ? Member::BuildType.camelize(name_s) : name_s)
NameValidator.validate!(@name)
@description = description
@comment = comment
@type = @owner_type = @own_validators = @own_directives = @own_arguments = @arguments_statically_coercible = nil # these will be prepared later if necessary
self.deprecation_reason = deprecation_reason
if method && hash_key && dig
raise ArgumentError, "Provide `method:`, `hash_key:` _or_ `dig:`, not multiple. (called with: `method: #{method.inspect}, hash_key: #{hash_key.inspect}, dig: #{dig.inspect}`)"
end
if resolver_method
if method
raise ArgumentError, "Provide `method:` _or_ `resolver_method:`, not both. (called with: `method: #{method.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
if hash_key || dig
raise ArgumentError, "Provide `hash_key:`, `dig:`, _or_ `resolver_method:`, not multiple. (called with: `hash_key: #{hash_key.inspect}, dig: #{dig.inspect}, resolver_method: #{resolver_method.inspect}`)"
end
end
method_name = method || hash_key || name_s
@dig_keys = dig
if hash_key
@hash_key = hash_key
@hash_key_str = hash_key.to_s
else
@hash_key = NOT_CONFIGURED
@hash_key_str = NOT_CONFIGURED
end
@method_str = -method_name.to_s
@method_sym = method_name.to_sym
@resolver_method = (resolver_method || name_s).to_sym
@complexity = complexity
@dynamic_introspection = dynamic_introspection
@return_type_expr = type
@return_type_null = if !null.nil?
null
elsif resolver_class
nil
else
true
end
@connection = connection
@max_page_size = max_page_size
@default_page_size = default_page_size
@introspection = introspection
@extras = extras
@broadcastable = broadcastable
@resolver_class = resolver_class
@scope = scope
@trace = trace
@relay_node_field = relay_node_field
@relay_nodes_field = relay_nodes_field
@ast_node = ast_node
@method_conflict_warning = method_conflict_warning
@fallback_value = fallback_value
@definition_block = definition_block
arguments.each do |name, arg|
case arg
when Hash
argument(name: name, **arg)
when GraphQL::Schema::Argument
add_argument(arg)
when Array
arg.each { |a| add_argument(a) }
else
raise ArgumentError, "Unexpected argument config (#{arg.class}): #{arg.inspect}"
end
end
@owner = owner
@subscription_scope = subscription_scope
@extensions = EMPTY_ARRAY
@call_after_define = false
set_pagination_extensions(connection_extension: connection_extension)
# Do this last so we have as much context as possible when initializing them:
if !extensions.empty?
self.extensions(extensions)
end
if resolver_class && !resolver_class.extensions.empty?
self.extensions(resolver_class.extensions)
end
if !directives.empty?
directives.each do |(dir_class, options)|
self.directive(dir_class, **options)
end
end
if !validates.empty?
self.validates(validates)
end
if @definition_block.nil?
self.extensions.each(&:after_define_apply)
@call_after_define = true
end
end
# Calls the definition block, if one was given.
# This is deferred so that references to the return type
# can be lazily evaluated, reducing Rails boot time.
# @return [self]
# @api private
def ensure_loaded
if @definition_block
if @definition_block.arity == 1
@definition_block.call(self)
else
instance_exec(self, &@definition_block)
end
self.extensions.each(&:after_define_apply)
@call_after_define = true
@definition_block = nil
end
self
end
attr_accessor :dynamic_introspection
# If true, subscription updates with this field can be shared between viewers
# @return [Boolean, nil]
# @see GraphQL::Subscriptions::BroadcastAnalyzer
def broadcastable?
if !NOT_CONFIGURED.equal?(@broadcastable)
@broadcastable
elsif @resolver_class
@resolver_class.broadcastable?
else
nil
end
end
# @param text [String]
# @return [String]
def description(text = nil)
if text
@description = text
elsif !NOT_CONFIGURED.equal?(@description)
@description
elsif @resolver_class
@resolver_class.description
else
nil
end
end
# @param text [String]
# @return [String, nil]
def comment(text = nil)
if text
@comment = text
elsif !NOT_CONFIGURED.equal?(@comment)
@comment
elsif @resolver_class
@resolver_class.comment
else
nil
end
end
# Read extension instances from this field,
# or add new classes/options to be initialized on this field.
# Extensions are executed in the order they are added.
#
# @example adding an extension
# extensions([MyExtensionClass])
#
# @example adding multiple extensions
# extensions([MyExtensionClass, AnotherExtensionClass])
#
# @example adding an extension with options
# extensions([MyExtensionClass, { AnotherExtensionClass => { filter: true } }])
#
# @param extensions [Array<Class, Hash<Class => Hash>>] Add extensions to this field. For hash elements, only the first key/value is used.
# @return [Array<GraphQL::Schema::FieldExtension>] extensions to apply to this field
def extensions(new_extensions = nil)
if new_extensions
new_extensions.each do |extension_config|
if extension_config.is_a?(Hash)
extension_class, options = *extension_config.to_a[0]
self.extension(extension_class, **options)
else
self.extension(extension_config)
end
end
end
@extensions
end
# Add `extension` to this field, initialized with `options` if provided.
#
# @example adding an extension
# extension(MyExtensionClass)
#
# @example adding an extension with options
# extension(MyExtensionClass, filter: true)
#
# @param extension_class [Class] subclass of {Schema::FieldExtension}
# @param options [Hash] if provided, given as `options:` when initializing `extension`.
# @return [void]
def extension(extension_class, **options)
extension_inst = extension_class.new(field: self, options: options)
if @extensions.frozen?
@extensions = @extensions.dup
end
if @call_after_define
extension_inst.after_define_apply
end
@extensions << extension_inst
nil
end
# Read extras (as symbols) from this field,
# or add new extras to be opted into by this field's resolver.
#
# @param new_extras [Array<Symbol>] Add extras to this field
# @return [Array<Symbol>]
def extras(new_extras = nil)
if new_extras.nil?
# Read the value
field_extras = @extras
if @resolver_class && !@resolver_class.extras.empty?
field_extras + @resolver_class.extras
else
field_extras
end
else
if @extras.frozen?
@extras = @extras.dup
end
# Append to the set of extras on this field
@extras.concat(new_extras)
end
end
def calculate_complexity(query:, nodes:, child_complexity:)
if respond_to?(:complexity_for)
lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
complexity_for(child_complexity: child_complexity, query: query, lookahead: lookahead)
elsif connection?
arguments = query.arguments_for(nodes.first, self)
max_possible_page_size = nil
if arguments.respond_to?(:[]) # It might have been an error
if arguments[:first]
max_possible_page_size = arguments[:first]
end
if arguments[:last] && (max_possible_page_size.nil? || arguments[:last] > max_possible_page_size)
max_possible_page_size = arguments[:last]
end
elsif arguments.is_a?(GraphQL::ExecutionError) || arguments.is_a?(GraphQL::UnauthorizedError)
raise arguments
end
if max_possible_page_size.nil?
max_possible_page_size = default_page_size || query.schema.default_page_size || max_page_size || query.schema.default_max_page_size
end
if max_possible_page_size.nil?
raise GraphQL::Error, "Can't calculate complexity for #{path}, no `first:`, `last:`, `default_page_size`, `max_page_size` or `default_max_page_size`"
else
metadata_complexity = 0
lookahead = GraphQL::Execution::Lookahead.new(query: query, field: self, ast_nodes: nodes, owner_type: owner)
lookahead.selections.each do |next_lookahead|
# this includes `pageInfo`, `nodes` and `edges` and any custom fields
# TODO this doesn't support procs yet -- unlikely to need it.
metadata_complexity += next_lookahead.field.complexity
if next_lookahead.name != :nodes && next_lookahead.name != :edges
# subfields, eg, for pageInfo -- assumes no subselections
metadata_complexity += next_lookahead.selections.size
end
end
# Possible bug: selections on `edges` and `nodes` are _both_ multiplied here. Should they be?
items_complexity = child_complexity - metadata_complexity
subfields_complexity = (max_possible_page_size * items_complexity) + metadata_complexity
# Apply this field's own complexity
apply_own_complexity_to(subfields_complexity, query, nodes)
end
else
apply_own_complexity_to(child_complexity, query, nodes)
end
end
def complexity(new_complexity = nil)
case new_complexity
when Proc
if new_complexity.parameters.size != 3
fail(
"A complexity proc should always accept 3 parameters: ctx, args, child_complexity. "\
"E.g.: complexity ->(ctx, args, child_complexity) { child_complexity * args[:limit] }"
)
else
@complexity = new_complexity
end
when Numeric
@complexity = new_complexity
when nil
if @resolver_class
@complexity || @resolver_class.complexity || 1
else
@complexity || 1
end
else
raise("Invalid complexity: #{new_complexity.inspect} on #{@name}")
end
end
# @return [Boolean] True if this field's {#max_page_size} should override the schema default.
def has_max_page_size?
!NOT_CONFIGURED.equal?(@max_page_size) || (@resolver_class && @resolver_class.has_max_page_size?)
end
# @return [Integer, nil] Applied to connections if {#has_max_page_size?}
def max_page_size
if !NOT_CONFIGURED.equal?(@max_page_size)
@max_page_size
elsif @resolver_class && @resolver_class.has_max_page_size?
@resolver_class.max_page_size
else
nil
end
end
# @return [Boolean] True if this field's {#default_page_size} should override the schema default.
def has_default_page_size?
!NOT_CONFIGURED.equal?(@default_page_size) || (@resolver_class && @resolver_class.has_default_page_size?)
end
# @return [Integer, nil] Applied to connections if {#has_default_page_size?}
def default_page_size
if !NOT_CONFIGURED.equal?(@default_page_size)
@default_page_size
elsif @resolver_class && @resolver_class.has_default_page_size?
@resolver_class.default_page_size
else
nil
end
end
def freeze
type
owner_type
arguments_statically_coercible?
connection?
super
end
class MissingReturnTypeError < GraphQL::Error; end
attr_writer :type
# Get or set the return type of this field.
#
# It may return nil if no type was configured or if the given definition block wasn't called yet.
# @param new_type [Module, GraphQL::Schema::NonNull, GraphQL::Schema::List] A GraphQL return type
# @return [Module, GraphQL::Schema::NonNull, GraphQL::Schema::List, nil] the configured type for this field
def type(new_type = NOT_CONFIGURED)
if NOT_CONFIGURED.equal?(new_type)
if @resolver_class
return_type = @return_type_expr || @resolver_class.type_expr
if return_type.nil?
raise MissingReturnTypeError, "Can't determine the return type for #{self.path} (it has `resolver: #{@resolver_class}`, perhaps that class is missing a `type ...` declaration, or perhaps its type causes a cyclical loading issue)"
end
nullable = @return_type_null.nil? ? @resolver_class.null : @return_type_null
Member::BuildType.parse_type(return_type, null: nullable)
elsif !@return_type_expr.nil?
@type ||= Member::BuildType.parse_type(@return_type_expr, null: @return_type_null)
end
else
@return_type_expr = new_type
# If `type` is set in the definition block, then the `connection_extension: ...` given as a keyword won't be used, hmm...
# Also, arguments added by `connection_extension` will clobber anything previously defined,
# so `type(...)` should go first.
set_pagination_extensions(connection_extension: self.class.connection_extension)
end
rescue GraphQL::Schema::InvalidDocumentError, MissingReturnTypeError => err
# Let this propagate up
raise err
rescue StandardError => err
raise MissingReturnTypeError, "Failed to build return type for #{@owner.graphql_name}.#{name} from #{@return_type_expr.inspect}: (#{err.class}) #{err.message}", err.backtrace
end
def visible?(context)
if @resolver_class
@resolver_class.visible?(context)
else
true
end
end
def authorized?(object, args, context)
if @resolver_class
# The resolver _instance_ will check itself during `resolve()`
@resolver_class.authorized?(object, context)
else
if args.size > 0
if (arg_values = context[:current_arguments])
# ^^ that's provided by the interpreter at runtime, and includes info about whether the default value was used or not.
using_arg_values = true
arg_values = arg_values.argument_values
else
arg_values = args
using_arg_values = false
end
args = context.types.arguments(self)
args.each do |arg|
arg_key = arg.keyword
if arg_values.key?(arg_key)
arg_value = arg_values[arg_key]
if using_arg_values
if arg_value.default_used?
# pass -- no auth required for default used
next
else
application_arg_value = arg_value.value
if application_arg_value.is_a?(GraphQL::Execution::Interpreter::Arguments)
application_arg_value.keyword_arguments
end
end
else
application_arg_value = arg_value
end
if !arg.authorized?(object, application_arg_value, context)
return false
end
end
end
end
true
end
end
# This method is called by the interpreter for each field.
# You can extend it in your base field classes.
# @param object [GraphQL::Schema::Object] An instance of some type class, wrapping an application object
# @param args [Hash] A symbol-keyed hash of Ruby keyword arguments. (Empty if no args)
# @param ctx [GraphQL::Query::Context]
def resolve(object, args, query_ctx)
# Unwrap the GraphQL object to get the application object.
application_object = object.object
method_receiver = nil
method_to_call = nil
method_args = nil
@own_validators && Schema::Validator.validate!(validators, application_object, query_ctx, args)
query_ctx.query.after_lazy(self.authorized?(application_object, args, query_ctx)) do |is_authorized|
if is_authorized
with_extensions(object, args, query_ctx) do |obj, ruby_kwargs|
method_args = ruby_kwargs
if @resolver_class
if obj.is_a?(GraphQL::Schema::Object)
obj = obj.object
end
obj = @resolver_class.new(object: obj, context: query_ctx, field: self)
end
inner_object = obj.object
if !NOT_CONFIGURED.equal?(@hash_key)
hash_value = if inner_object.is_a?(Hash)
inner_object.key?(@hash_key) ? inner_object[@hash_key] : inner_object[@hash_key_str]
elsif inner_object.respond_to?(:[])
inner_object[@hash_key]
else
nil
end
if hash_value == false
hash_value
else
hash_value || (@fallback_value != NOT_CONFIGURED ? @fallback_value : nil)
end
elsif obj.respond_to?(resolver_method)
method_to_call = resolver_method
method_receiver = obj
# Call the method with kwargs, if there are any
if !ruby_kwargs.empty?
obj.public_send(resolver_method, **ruby_kwargs)
else
obj.public_send(resolver_method)
end
elsif inner_object.is_a?(Hash)
if @dig_keys
inner_object.dig(*@dig_keys)
elsif inner_object.key?(@method_sym)
inner_object[@method_sym]
elsif inner_object.key?(@method_str) || !inner_object.default_proc.nil?
inner_object[@method_str]
elsif @fallback_value != NOT_CONFIGURED
@fallback_value
else
nil
end
elsif inner_object.respond_to?(@method_sym)
method_to_call = @method_sym
method_receiver = obj.object
if !ruby_kwargs.empty?
inner_object.public_send(@method_sym, **ruby_kwargs)
else
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | true |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/visibility.rb | lib/graphql/schema/visibility.rb | # frozen_string_literal: true
require "graphql/schema/visibility/profile"
require "graphql/schema/visibility/migration"
require "graphql/schema/visibility/visit"
module GraphQL
class Schema
# Use this plugin to make some parts of your schema hidden from some viewers.
#
class Visibility
# @param schema [Class<GraphQL::Schema>]
# @param profiles [Hash<Symbol => Hash>] A hash of `name => context` pairs for preloading visibility profiles
# @param preload [Boolean] if `true`, load the default schema profile and all named profiles immediately (defaults to `true` for `Rails.env.production?` and `Rails.env.staging?`)
# @param migration_errors [Boolean] if `true`, raise an error when `Visibility` and `Warden` return different results
def self.use(schema, dynamic: false, profiles: EmptyObjects::EMPTY_HASH, preload: (defined?(Rails.env) ? (Rails.env.production? || Rails.env.staging?) : nil), migration_errors: false)
profiles&.each { |name, ctx|
ctx[:visibility_profile] = name
ctx.freeze
}
schema.visibility = self.new(schema, dynamic: dynamic, preload: preload, profiles: profiles, migration_errors: migration_errors)
end
def initialize(schema, dynamic:, preload:, profiles:, migration_errors:)
@schema = schema
schema.use_visibility_profile = true
schema.visibility_profile_class = if migration_errors
Visibility::Migration
else
Visibility::Profile
end
@preload = preload
@profiles = profiles
@cached_profiles = {}
@dynamic = dynamic
@migration_errors = migration_errors
# Top-level type caches:
@visit = nil
@interface_type_memberships = nil
@directives = nil
@types = nil
@all_references = nil
@loaded_all = false
if preload
self.preload
end
end
def freeze
load_all
@visit = true
@interface_type_memberships.default_proc = nil
@all_references.default_proc = nil
super
end
def all_directives
load_all
@directives
end
def all_interface_type_memberships
load_all
@interface_type_memberships
end
def all_references
load_all
@all_references
end
def get_type(type_name)
load_all
@types[type_name]
end
attr_accessor :types
def preload?
@preload
end
def preload
# Traverse the schema now (and in the *_configured hooks below)
# To make sure things are loaded during boot
@preloaded_types = Set.new
types_to_visit = [
@schema.query,
@schema.mutation,
@schema.subscription,
*@schema.introspection_system.types.values,
*@schema.introspection_system.entry_points.map { |ep| ep.type.unwrap },
*@schema.orphan_types,
]
# Root types may have been nil:
types_to_visit.compact!
ensure_all_loaded(types_to_visit)
@profiles.each do |profile_name, example_ctx|
prof = profile_for(example_ctx)
prof.preload
end
end
# @api private
def query_configured(query_type)
if @preload
ensure_all_loaded([query_type])
end
end
# @api private
def mutation_configured(mutation_type)
if @preload
ensure_all_loaded([mutation_type])
end
end
# @api private
def subscription_configured(subscription_type)
if @preload
ensure_all_loaded([subscription_type])
end
end
# @api private
def orphan_types_configured(orphan_types)
if @preload
ensure_all_loaded(orphan_types)
end
end
# @api private
def introspection_system_configured(introspection_system)
if @preload
introspection_types = [
*@schema.introspection_system.types.values,
*@schema.introspection_system.entry_points.map { |ep| ep.type.unwrap },
]
ensure_all_loaded(introspection_types)
end
end
# Make another Visibility for `schema` based on this one
# @return [Visibility]
# @api private
def dup_for(other_schema)
self.class.new(
other_schema,
dynamic: @dynamic,
preload: @preload,
profiles: @profiles,
migration_errors: @migration_errors
)
end
def migration_errors?
@migration_errors
end
attr_reader :cached_profiles
def profile_for(context)
if !@profiles.empty?
visibility_profile = context[:visibility_profile]
if @profiles.include?(visibility_profile)
profile_ctx = @profiles[visibility_profile]
@cached_profiles[visibility_profile] ||= @schema.visibility_profile_class.new(name: visibility_profile, context: profile_ctx, schema: @schema, visibility: self)
elsif @dynamic
if context.is_a?(Query::NullContext)
top_level_profile
else
@schema.visibility_profile_class.new(context: context, schema: @schema, visibility: self)
end
elsif !context.key?(:visibility_profile)
raise ArgumentError, "#{@schema} expects a visibility profile, but `visibility_profile:` wasn't passed. Provide a `visibility_profile:` value or add `dynamic: true` to your visibility configuration."
else
raise ArgumentError, "`#{visibility_profile.inspect}` isn't allowed for `visibility_profile:` (must be one of #{@profiles.keys.map(&:inspect).join(", ")}). Or, add `#{visibility_profile.inspect}` to the list of profiles in the schema definition."
end
elsif context.is_a?(Query::NullContext)
top_level_profile
else
@schema.visibility_profile_class.new(context: context, schema: @schema, visibility: self)
end
end
attr_reader :top_level
# @api private
attr_reader :unfiltered_interface_type_memberships
def top_level_profile(refresh: false)
if refresh
@top_level_profile = nil
end
@top_level_profile ||= @schema.visibility_profile_class.new(context: Query::NullContext.instance, schema: @schema, visibility: self)
end
private
def ensure_all_loaded(types_to_visit)
while (type = types_to_visit.shift)
if type.kind.fields? && @preloaded_types.add?(type)
type.all_field_definitions.each do |field_defn|
field_defn.ensure_loaded
types_to_visit << field_defn.type.unwrap
end
end
end
top_level_profile(refresh: true)
nil
end
def load_all(types: nil)
if @visit.nil?
# Set up the visit system
@interface_type_memberships = Hash.new { |h, interface_type|
h[interface_type] = Hash.new { |h2, obj_type|
h2[obj_type] = []
}.compare_by_identity
}.compare_by_identity
@directives = []
@types = {} # String => Module
@all_references = Hash.new { |h, member| h[member] = Set.new.compare_by_identity }.compare_by_identity
@unions_for_references = Set.new
@visit = Visibility::Visit.new(@schema) do |member|
if member.is_a?(Module)
type_name = member.graphql_name
if (prev_t = @types[type_name])
if prev_t.is_a?(Array)
prev_t << member
else
@types[type_name] = [member, prev_t]
end
else
@types[member.graphql_name] = member
end
member.directives.each { |dir| @all_references[dir.class] << member }
if member < GraphQL::Schema::Directive
@directives << member
elsif member.respond_to?(:interface_type_memberships)
member.interface_type_memberships.each do |itm|
@all_references[itm.abstract_type] << member
# `itm.object_type` may not actually be `member` if this implementation
# is inherited from a superclass
@interface_type_memberships[itm.abstract_type][member] << itm
end
elsif member < GraphQL::Schema::Union
@unions_for_references << member
end
elsif member.is_a?(GraphQL::Schema::Argument)
member.validate_default_value
@all_references[member.type.unwrap] << member
if !(dirs = member.directives).empty?
dir_owner = member.owner
if dir_owner.respond_to?(:owner)
dir_owner = dir_owner.owner
end
dirs.each { |dir| @all_references[dir.class] << dir_owner }
end
elsif member.is_a?(GraphQL::Schema::Field)
@all_references[member.type.unwrap] << member
if !(dirs = member.directives).empty?
dir_owner = member.owner
dirs.each { |dir| @all_references[dir.class] << dir_owner }
end
elsif member.is_a?(GraphQL::Schema::EnumValue)
if !(dirs = member.directives).empty?
dir_owner = member.owner
dirs.each { |dir| @all_references[dir.class] << dir_owner }
end
end
true
end
@schema.root_types.each { |t| @all_references[t] << true }
@schema.introspection_system.types.each_value { |t| @all_references[t] << true }
@schema.directives.each_value { |dir_class| @all_references[dir_class] << true }
@visit.visit_each(types: []) # visit default directives
end
if types
@visit.visit_each(types: types, directives: [])
elsif @loaded_all == false
@loaded_all = true
@visit.visit_each
else
# already loaded all
return
end
# TODO: somehow don't iterate over all these,
# only the ones that may have been modified
@interface_type_memberships.each do |int_type, obj_type_memberships|
referrers = @all_references[int_type].select { |r| r.is_a?(GraphQL::Schema::Field) }
if !referrers.empty?
obj_type_memberships.each_key do |impl_type|
@all_references[impl_type] |= referrers
end
end
end
@unions_for_references.each do |union_type|
refs = @all_references[union_type]
union_type.all_possible_types.each do |object_type|
@all_references[object_type] |= refs # Add new items
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/built_in_types.rb | lib/graphql/schema/built_in_types.rb | # frozen_string_literal: true
module GraphQL
class Schema
BUILT_IN_TYPES = {
"Int" => GraphQL::Types::Int,
"String" => GraphQL::Types::String,
"Float" => GraphQL::Types::Float,
"Boolean" => GraphQL::Types::Boolean,
"ID" => GraphQL::Types::ID,
}
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/loader.rb | lib/graphql/schema/loader.rb | # frozen_string_literal: true
module GraphQL
class Schema
# You can use the result of {GraphQL::Introspection::INTROSPECTION_QUERY}
# to make a schema. This schema is missing some important details like
# `resolve` functions, but it does include the full type system,
# so you can use it to validate queries.
#
# @see GraphQL::Schema.from_introspection for a public API
module Loader
extend self
# Create schema with the result of an introspection query.
# @param introspection_result [Hash] A response from {GraphQL::Introspection::INTROSPECTION_QUERY}
# @return [Class] the schema described by `input`
def load(introspection_result)
schema = introspection_result.fetch("data").fetch("__schema")
types = {}
type_resolver = ->(type) { resolve_type(types, type) }
schema.fetch("types").each do |type|
next if type.fetch("name").start_with?("__")
type_object = define_type(type, type_resolver)
types[type["name"]] = type_object
end
directives = []
schema.fetch("directives", []).each do |directive|
next if GraphQL::Schema.default_directives.include?(directive.fetch("name"))
directives << define_directive(directive, type_resolver)
end
Class.new(GraphQL::Schema) do
add_type_and_traverse(types.values, root: false)
orphan_types(types.values.select { |t| t.kind.object? })
directives(directives)
description(schema["description"])
def self.resolve_type(*)
raise(GraphQL::RequiredImplementationMissingError, "This schema was loaded from string, so it can't resolve types for objects")
end
[:query, :mutation, :subscription].each do |root|
type = schema["#{root}Type"]
if type
type_defn = types.fetch(type.fetch("name"))
self.public_send(root, type_defn)
end
end
end
end
NullScalarCoerce = ->(val, _ctx) { val }
class << self
private
def resolve_type(types, type)
case kind = type.fetch("kind")
when "ENUM", "INTERFACE", "INPUT_OBJECT", "OBJECT", "SCALAR", "UNION"
type_name = type.fetch("name")
type = types[type_name] || Schema::BUILT_IN_TYPES[type_name]
if type.nil?
GraphQL::Schema::LateBoundType.new(type_name)
else
type
end
when "LIST"
Schema::List.new(resolve_type(types, type.fetch("ofType")))
when "NON_NULL"
Schema::NonNull.new(resolve_type(types, type.fetch("ofType")))
else
fail GraphQL::RequiredImplementationMissingError, "#{kind} not implemented"
end
end
def extract_default_value(default_value_str, input_value_ast)
case input_value_ast
when String, Integer, Float, TrueClass, FalseClass
input_value_ast
when GraphQL::Language::Nodes::Enum
input_value_ast.name
when GraphQL::Language::Nodes::NullValue
nil
when GraphQL::Language::Nodes::InputObject
input_value_ast.to_h
when Array
input_value_ast.map { |element| extract_default_value(default_value_str, element) }
else
raise(
"Encountered unexpected type when loading default value. "\
"input_value_ast.class is #{input_value_ast.class} "\
"default_value is #{default_value_str}"
)
end
end
def define_type(type, type_resolver)
loader = self
case type.fetch("kind")
when "ENUM"
Class.new(GraphQL::Schema::Enum) do
graphql_name(type["name"])
description(type["description"])
type["enumValues"].each do |enum_value|
value(
enum_value["name"],
description: enum_value["description"],
deprecation_reason: enum_value["deprecationReason"],
)
end
end
when "INTERFACE"
Module.new do
include GraphQL::Schema::Interface
graphql_name(type["name"])
description(type["description"])
loader.build_fields(self, type["fields"] || [], type_resolver)
end
when "INPUT_OBJECT"
Class.new(GraphQL::Schema::InputObject) do
graphql_name(type["name"])
description(type["description"])
loader.build_arguments(self, type["inputFields"], type_resolver)
end
when "OBJECT"
Class.new(GraphQL::Schema::Object) do
graphql_name(type["name"])
description(type["description"])
if type["interfaces"]
type["interfaces"].each do |interface_type|
implements(type_resolver.call(interface_type))
end
end
loader.build_fields(self, type["fields"], type_resolver)
end
when "SCALAR"
type_name = type.fetch("name")
if (builtin = GraphQL::Schema::BUILT_IN_TYPES[type_name])
builtin
else
Class.new(GraphQL::Schema::Scalar) do
graphql_name(type["name"])
description(type["description"])
specified_by_url(type["specifiedByURL"])
end
end
when "UNION"
Class.new(GraphQL::Schema::Union) do
graphql_name(type["name"])
description(type["description"])
possible_types(*(type["possibleTypes"].map { |pt| type_resolver.call(pt) }))
end
else
fail GraphQL::RequiredImplementationMissingError, "#{type["kind"]} not implemented"
end
end
def define_directive(directive, type_resolver)
loader = self
Class.new(GraphQL::Schema::Directive) do
graphql_name(directive["name"])
description(directive["description"])
locations(*directive["locations"].map(&:to_sym))
repeatable(directive["isRepeatable"])
loader.build_arguments(self, directive["args"], type_resolver)
end
end
public
def build_fields(type_defn, fields, type_resolver)
loader = self
fields.each do |field_hash|
unwrapped_field_hash = field_hash
while (of_type = unwrapped_field_hash["ofType"])
unwrapped_field_hash = of_type
end
type_defn.field(
field_hash["name"],
type: type_resolver.call(field_hash["type"]),
description: field_hash["description"],
deprecation_reason: field_hash["deprecationReason"],
null: true,
camelize: false,
connection_extension: nil,
) do
if !field_hash["args"].empty?
loader.build_arguments(self, field_hash["args"], type_resolver)
end
end
end
end
def build_arguments(arg_owner, args, type_resolver)
args.each do |arg|
kwargs = {
type: type_resolver.call(arg["type"]),
description: arg["description"],
deprecation_reason: arg["deprecationReason"],
required: false,
camelize: false,
}
if arg["defaultValue"]
default_value_str = arg["defaultValue"]
dummy_query_str = "query getStuff($var: InputObj = #{default_value_str}) { __typename }"
# Returns a `GraphQL::Language::Nodes::Document`:
dummy_query_ast = GraphQL.parse(dummy_query_str)
# Reach into the AST for the default value:
input_value_ast = dummy_query_ast.definitions.first.variables.first.default_value
kwargs[:default_value] = extract_default_value(default_value_str, input_value_ast)
end
arg_owner.argument(arg["name"], **kwargs)
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/ractor_shareable.rb | lib/graphql/schema/ractor_shareable.rb | # frozen_string_literal: true
module GraphQL
class Schema
module RactorShareable
def self.extended(schema_class)
schema_class.extend(SchemaExtension)
schema_class.freeze_schema
end
module SchemaExtension
def freeze_error_handlers(handlers)
handlers[:subclass_handlers].default_proc = nil
handlers[:subclass_handlers].each do |_class, subclass_handlers|
freeze_error_handlers(subclass_handlers)
end
Ractor.make_shareable(handlers)
end
def freeze_schema
# warm some ivars:
default_analysis_engine
default_execution_strategy
GraphQL.default_parser
default_logger
freeze_error_handlers(error_handlers)
# TODO: this freezes errors of parent classes which could cause trouble
parent_class = superclass
while parent_class.respond_to?(:error_handlers)
freeze_error_handlers(parent_class.error_handlers)
parent_class = parent_class.superclass
end
own_tracers.freeze
@frozen_tracers = tracers.freeze
own_trace_modes.each do |m|
trace_options_for(m)
build_trace_mode(m)
end
build_trace_mode(:default)
Ractor.make_shareable(@trace_options_for_mode)
Ractor.make_shareable(own_trace_modes)
Ractor.make_shareable(own_multiplex_analyzers)
@frozen_multiplex_analyzers = Ractor.make_shareable(multiplex_analyzers)
Ractor.make_shareable(own_query_analyzers)
@frozen_query_analyzers = Ractor.make_shareable(query_analyzers)
Ractor.make_shareable(own_plugins)
own_plugins.each do |(plugin, options)|
Ractor.make_shareable(plugin)
Ractor.make_shareable(options)
end
@frozen_plugins = Ractor.make_shareable(plugins)
Ractor.make_shareable(own_references_to)
@frozen_directives = Ractor.make_shareable(directives)
Ractor.make_shareable(visibility)
Ractor.make_shareable(introspection_system)
extend(FrozenMethods)
Ractor.make_shareable(self)
superclass.respond_to?(:freeze_schema) && superclass.freeze_schema
end
module FrozenMethods
def tracers; @frozen_tracers; end
def multiplex_analyzers; @frozen_multiplex_analyzers; end
def query_analyzers; @frozen_query_analyzers; end
def plugins; @frozen_plugins; end
def directives; @frozen_directives; end
# This actually accumulates info during execution...
# How to support it?
def lazy?(_obj); false; end
def sync_lazy(obj); obj; end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/finder.rb | lib/graphql/schema/finder.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Find schema members using string paths
#
# @example Finding object types
# MySchema.find("SomeObjectType")
#
# @example Finding fields
# MySchema.find("SomeObjectType.myField")
#
# @example Finding arguments
# MySchema.find("SomeObjectType.myField.anArgument")
#
# @example Finding directives
# MySchema.find("@include")
#
class Finder
class MemberNotFoundError < ArgumentError; end
def initialize(schema)
@schema = schema
end
def find(path)
path = path.split(".")
type_or_directive = path.shift
if type_or_directive.start_with?("@")
directive = schema.directives[type_or_directive[1..-1]]
if directive.nil?
raise MemberNotFoundError, "Could not find directive `#{type_or_directive}` in schema."
end
return directive if path.empty?
find_in_directive(directive, path: path)
else
type = schema.get_type(type_or_directive) # rubocop:disable Development/ContextIsPassedCop -- build-time
if type.nil?
raise MemberNotFoundError, "Could not find type `#{type_or_directive}` in schema."
end
return type if path.empty?
find_in_type(type, path: path)
end
end
private
attr_reader :schema
def find_in_directive(directive, path:)
argument_name = path.shift
argument = directive.get_argument(argument_name) # rubocop:disable Development/ContextIsPassedCop -- build-time
if argument.nil?
raise MemberNotFoundError, "Could not find argument `#{argument_name}` on directive #{directive}."
end
argument
end
def find_in_type(type, path:)
case type.kind.name
when "OBJECT"
find_in_fields_type(type, kind: "object", path: path)
when "INTERFACE"
find_in_fields_type(type, kind: "interface", path: path)
when "INPUT_OBJECT"
find_in_input_object(type, path: path)
when "UNION"
# Error out if path that was provided is too long
# i.e UnionType.PossibleType.aField
# Use PossibleType.aField instead.
if invalid = path.first
raise MemberNotFoundError, "Cannot select union possible type `#{invalid}`. Select the type directly instead."
end
when "ENUM"
find_in_enum_type(type, path: path)
else
raise "Unexpected find_in_type: #{type.inspect} (#{path})"
end
end
def find_in_fields_type(type, kind:, path:)
field_name = path.shift
field = schema.get_field(type, field_name)
if field.nil?
raise MemberNotFoundError, "Could not find field `#{field_name}` on #{kind} type `#{type.graphql_name}`."
end
return field if path.empty?
find_in_field(field, path: path)
end
def find_in_field(field, path:)
argument_name = path.shift
argument = field.get_argument(argument_name) # rubocop:disable Development/ContextIsPassedCop -- build-time
if argument.nil?
raise MemberNotFoundError, "Could not find argument `#{argument_name}` on field `#{field.name}`."
end
# Error out if path that was provided is too long
# i.e Type.field.argument.somethingBad
if invalid = path.first
raise MemberNotFoundError, "Cannot select member `#{invalid}` on a field."
end
argument
end
def find_in_input_object(input_object, path:)
field_name = path.shift
input_field = input_object.get_argument(field_name) # rubocop:disable Development/ContextIsPassedCop -- build-time
if input_field.nil?
raise MemberNotFoundError, "Could not find input field `#{field_name}` on input object type `#{input_object.graphql_name}`."
end
# Error out if path that was provided is too long
# i.e InputType.inputField.bad
if invalid = path.first
raise MemberNotFoundError, "Cannot select member `#{invalid}` on an input field."
end
input_field
end
def find_in_enum_type(enum_type, path:)
value_name = path.shift
enum_value = enum_type.enum_values.find { |v| v.graphql_name == value_name } # rubocop:disable Development/ContextIsPassedCop -- build-time, not runtime
if enum_value.nil?
raise MemberNotFoundError, "Could not find enum value `#{value_name}` on enum type `#{enum_type.graphql_name}`."
end
# Error out if path that was provided is too long
# i.e Enum.VALUE.wat
if invalid = path.first
raise MemberNotFoundError, "Cannot select member `#{invalid}` on an enum value."
end
enum_value
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/build_from_definition.rb | lib/graphql/schema/build_from_definition.rb | # frozen_string_literal: true
require "graphql/schema/build_from_definition/resolve_map"
module GraphQL
class Schema
module BuildFromDefinition
class << self
# @see {Schema.from_definition}
def from_definition(schema_superclass, definition_string, parser: GraphQL.default_parser, **kwargs)
if defined?(parser::SchemaParser)
parser = parser::SchemaParser
end
from_document(schema_superclass, parser.parse(definition_string), **kwargs)
end
def from_definition_path(schema_superclass, definition_path, parser: GraphQL.default_parser, **kwargs)
if defined?(parser::SchemaParser)
parser = parser::SchemaParser
end
from_document(schema_superclass, parser.parse_file(definition_path), **kwargs)
end
def from_document(schema_superclass, document, default_resolve:, using: {}, base_types: {}, relay: false)
Builder.build(schema_superclass, document, default_resolve: default_resolve || {}, relay: relay, using: using, base_types: base_types)
end
end
# @api private
module Builder
include GraphQL::EmptyObjects
extend self
def build(schema_superclass, document, default_resolve:, using: {}, base_types: {}, relay:)
raise InvalidDocumentError.new('Must provide a document ast.') if !document || !document.is_a?(GraphQL::Language::Nodes::Document)
base_types = {
object: GraphQL::Schema::Object,
interface: GraphQL::Schema::Interface,
union: GraphQL::Schema::Union,
scalar: GraphQL::Schema::Scalar,
enum: GraphQL::Schema::Enum,
input_object: GraphQL::Schema::InputObject,
}.merge!(base_types)
if default_resolve.is_a?(Hash)
default_resolve = ResolveMap.new(default_resolve)
end
schema_defns = document.definitions.select { |d| d.is_a?(GraphQL::Language::Nodes::SchemaDefinition) }
if schema_defns.size > 1
raise InvalidDocumentError.new('Must provide only one schema definition.')
end
schema_definition = schema_defns.first
types = {}
directives = schema_superclass.directives.dup
type_resolver = build_resolve_type(types, directives, ->(type_name) { types[type_name] ||= Schema::LateBoundType.new(type_name)})
# Make a different type resolver because we need to coerce directive arguments
# _while_ building the schema.
# It will dig for a type if it encounters a custom type. This could be a problem if there are cycles.
directive_type_resolver = nil
directive_type_resolver = build_resolve_type(types, directives, ->(type_name) {
types[type_name] ||= begin
defn = document.definitions.find { |d| d.respond_to?(:name) && d.name == type_name }
if defn
build_definition_from_node(defn, directive_type_resolver, default_resolve, base_types)
elsif (built_in_defn = GraphQL::Schema::BUILT_IN_TYPES[type_name])
built_in_defn
else
raise "No definition for #{type_name.inspect} found in schema document or built-in types. Add a definition for it or remove it."
end
end
})
directives.merge!(GraphQL::Schema.default_directives)
document.definitions.each do |definition|
if definition.is_a?(GraphQL::Language::Nodes::DirectiveDefinition)
directives[definition.name] = build_directive(definition, directive_type_resolver)
end
end
# In case any directives referenced built-in types for their arguments:
replace_late_bound_types_with_built_in(types)
schema_extensions = nil
document.definitions.each do |definition|
case definition
when GraphQL::Language::Nodes::SchemaDefinition, GraphQL::Language::Nodes::DirectiveDefinition
nil # already handled
when GraphQL::Language::Nodes::SchemaExtension,
GraphQL::Language::Nodes::ScalarTypeExtension,
GraphQL::Language::Nodes::ObjectTypeExtension,
GraphQL::Language::Nodes::InterfaceTypeExtension,
GraphQL::Language::Nodes::UnionTypeExtension,
GraphQL::Language::Nodes::EnumTypeExtension,
GraphQL::Language::Nodes::InputObjectTypeExtension
schema_extensions ||= []
schema_extensions << definition
else
# It's possible that this was already loaded by the directives
prev_type = types[definition.name]
if prev_type.nil? || prev_type.is_a?(Schema::LateBoundType)
types[definition.name] = build_definition_from_node(definition, type_resolver, default_resolve, base_types)
end
end
end
replace_late_bound_types_with_built_in(types)
if schema_definition
if schema_definition.query
raise InvalidDocumentError.new("Specified query type \"#{schema_definition.query}\" not found in document.") unless types[schema_definition.query]
query_root_type = types[schema_definition.query]
end
if schema_definition.mutation
raise InvalidDocumentError.new("Specified mutation type \"#{schema_definition.mutation}\" not found in document.") unless types[schema_definition.mutation]
mutation_root_type = types[schema_definition.mutation]
end
if schema_definition.subscription
raise InvalidDocumentError.new("Specified subscription type \"#{schema_definition.subscription}\" not found in document.") unless types[schema_definition.subscription]
subscription_root_type = types[schema_definition.subscription]
end
if schema_definition.query.nil? &&
schema_definition.mutation.nil? &&
schema_definition.subscription.nil?
# This schema may have been given with directives only,
# check for defaults:
query_root_type = types['Query']
mutation_root_type = types['Mutation']
subscription_root_type = types['Subscription']
end
else
query_root_type = types['Query']
mutation_root_type = types['Mutation']
subscription_root_type = types['Subscription']
end
raise InvalidDocumentError.new('Must provide schema definition with query type or a type named Query.') unless query_root_type
schema_extensions&.each do |ext|
next if ext.is_a?(GraphQL::Language::Nodes::SchemaExtension)
built_type = types[ext.name]
case ext
when GraphQL::Language::Nodes::ScalarTypeExtension
build_directives(built_type, ext, type_resolver)
when GraphQL::Language::Nodes::ObjectTypeExtension
build_directives(built_type, ext, type_resolver)
build_fields(built_type, ext.fields, type_resolver, default_resolve: true)
build_interfaces(built_type, ext.interfaces, type_resolver)
when GraphQL::Language::Nodes::InterfaceTypeExtension
build_directives(built_type, ext, type_resolver)
build_fields(built_type, ext.fields, type_resolver, default_resolve: nil)
build_interfaces(built_type, ext.interfaces, type_resolver)
when GraphQL::Language::Nodes::UnionTypeExtension
build_directives(built_type, ext, type_resolver)
built_type.possible_types(*ext.types.map { |type_name| type_resolver.call(type_name) })
when GraphQL::Language::Nodes::EnumTypeExtension
build_directives(built_type, ext, type_resolver)
build_values(built_type, ext.values, type_resolver)
when GraphQL::Language::Nodes::InputObjectTypeExtension
build_directives(built_type, ext, type_resolver)
build_arguments(built_type, ext.fields, type_resolver)
end
end
builder = self
found_types = types.values
object_types = found_types.select { |t| t.respond_to?(:kind) && t.kind.object? }
schema_class = Class.new(schema_superclass) do
begin
# Add these first so that there's some chance of resolving late-bound types
add_type_and_traverse(found_types, root: false)
orphan_types(object_types)
query query_root_type
mutation mutation_root_type
subscription subscription_root_type
rescue Schema::UnresolvedLateBoundTypeError => err
type_name = err.type.name
err_backtrace = err.backtrace
raise InvalidDocumentError, "Type \"#{type_name}\" not found in document.", err_backtrace
end
object_types.each do |t|
t.interfaces.each do |int_t|
if int_t.is_a?(LateBoundType)
int_t = types[int_t.graphql_name]
t.implements(int_t)
end
int_t.orphan_types(t)
end
end
if default_resolve.respond_to?(:resolve_type)
def self.resolve_type(*args)
self.definition_default_resolve.resolve_type(*args)
end
else
def self.resolve_type(*args)
NullResolveType.call(*args)
end
end
directives directives.values
if schema_definition
ast_node(schema_definition)
builder.build_directives(self, schema_definition, type_resolver)
end
using.each do |plugin, options|
if options
use(plugin, **options)
else
use(plugin)
end
end
# Empty `orphan_types` -- this will make unreachable types ... unreachable.
own_orphan_types.clear
class << self
attr_accessor :definition_default_resolve
end
self.definition_default_resolve = default_resolve
def definition_default_resolve
self.class.definition_default_resolve
end
def self.inherited(child_class)
child_class.definition_default_resolve = self.definition_default_resolve
super
end
end
schema_extensions&.each do |ext|
if ext.is_a?(GraphQL::Language::Nodes::SchemaExtension)
build_directives(schema_class, ext, type_resolver)
end
end
schema_class
end
NullResolveType = ->(type, obj, ctx) {
raise(GraphQL::RequiredImplementationMissingError, "Generated Schema cannot use Interface or Union types for execution. Implement resolve_type on your resolver.")
}
def build_definition_from_node(definition, type_resolver, default_resolve, base_types)
case definition
when GraphQL::Language::Nodes::EnumTypeDefinition
build_enum_type(definition, type_resolver, base_types[:enum])
when GraphQL::Language::Nodes::ObjectTypeDefinition
build_object_type(definition, type_resolver, base_types[:object])
when GraphQL::Language::Nodes::InterfaceTypeDefinition
build_interface_type(definition, type_resolver, base_types[:interface])
when GraphQL::Language::Nodes::UnionTypeDefinition
build_union_type(definition, type_resolver, base_types[:union])
when GraphQL::Language::Nodes::ScalarTypeDefinition
build_scalar_type(definition, type_resolver, base_types[:scalar], default_resolve: default_resolve)
when GraphQL::Language::Nodes::InputObjectTypeDefinition
build_input_object_type(definition, type_resolver, base_types[:input_object])
when GraphQL::Language::Nodes::DirectiveDefinition
build_directive(definition, type_resolver)
end
end
# Modify `types`, replacing any late-bound references to built-in types
# with their actual definitions.
#
# (Schema definitions are allowed to reference those built-ins without redefining them.)
# @return void
def replace_late_bound_types_with_built_in(types)
GraphQL::Schema::BUILT_IN_TYPES.each do |scalar_name, built_in_scalar|
existing_type = types[scalar_name]
if existing_type.is_a?(GraphQL::Schema::LateBoundType)
types[scalar_name] = built_in_scalar
end
end
end
def build_directives(definition, ast_node, type_resolver)
dirs = prepare_directives(ast_node, type_resolver)
dirs.each do |(dir_class, options)|
if definition.respond_to?(:schema_directive)
# it's a schema
definition.schema_directive(dir_class, **options)
else
definition.directive(dir_class, **options)
end
end
end
def prepare_directives(ast_node, type_resolver)
dirs = []
ast_node.directives.each do |dir_node|
if dir_node.name == "deprecated"
# This is handled using `deprecation_reason`
next
else
dir_class = type_resolver.call(dir_node.name)
if dir_class.nil?
raise ArgumentError, "No definition for @#{dir_node.name} #{ast_node.respond_to?(:name) ? "on #{ast_node.name} " : ""}at #{ast_node.line}:#{ast_node.col}"
end
options = args_to_kwargs(dir_class, dir_node)
dirs << [dir_class, options]
end
end
dirs
end
def args_to_kwargs(arg_owner, node)
if node.respond_to?(:arguments)
kwargs = {}
node.arguments.each do |arg_node|
arg_defn = arg_owner.get_argument(arg_node.name)
kwargs[arg_defn.keyword] = args_to_kwargs(arg_defn.type.unwrap, arg_node.value)
end
kwargs
elsif node.is_a?(Array)
node.map { |n| args_to_kwargs(arg_owner, n) }
elsif node.is_a?(Language::Nodes::Enum)
node.name
else
# scalar
node
end
end
def build_enum_type(enum_type_definition, type_resolver, base_type)
builder = self
Class.new(base_type) do
graphql_name(enum_type_definition.name)
builder.build_directives(self, enum_type_definition, type_resolver)
description(enum_type_definition.description)
ast_node(enum_type_definition)
builder.build_values(self, enum_type_definition.values, type_resolver)
end
end
def build_values(type_class, enum_value_definitions, type_resolver)
enum_value_definitions.each do |enum_value_definition|
type_class.value(enum_value_definition.name,
value: enum_value_definition.name,
deprecation_reason: build_deprecation_reason(enum_value_definition.directives),
description: enum_value_definition.description,
directives: prepare_directives(enum_value_definition, type_resolver),
ast_node: enum_value_definition,
)
end
end
def build_deprecation_reason(directives)
deprecated_directive = directives.find{ |d| d.name == 'deprecated' }
return unless deprecated_directive
reason = deprecated_directive.arguments.find{ |a| a.name == 'reason' }
return GraphQL::Schema::Directive::DEFAULT_DEPRECATION_REASON unless reason
reason.value
end
def build_scalar_type(scalar_type_definition, type_resolver, base_type, default_resolve:)
builder = self
Class.new(base_type) do
graphql_name(scalar_type_definition.name)
description(scalar_type_definition.description)
ast_node(scalar_type_definition)
builder.build_directives(self, scalar_type_definition, type_resolver)
if default_resolve.respond_to?(:coerce_input)
# Put these method definitions in another method to avoid retaining `type_resolve`
# from this method's bindiing
builder.build_scalar_type_coerce_method(self, :coerce_input, default_resolve)
builder.build_scalar_type_coerce_method(self, :coerce_result, default_resolve)
end
end
end
def build_scalar_type_coerce_method(scalar_class, method_name, default_definition_resolve)
scalar_class.define_singleton_method(method_name) do |val, ctx|
default_definition_resolve.public_send(method_name, self, val, ctx)
end
end
def build_union_type(union_type_definition, type_resolver, base_type)
builder = self
Class.new(base_type) do
graphql_name(union_type_definition.name)
description(union_type_definition.description)
possible_types(*union_type_definition.types.map { |type_name| type_resolver.call(type_name) })
ast_node(union_type_definition)
builder.build_directives(self, union_type_definition, type_resolver)
end
end
def build_object_type(object_type_definition, type_resolver, base_type)
builder = self
Class.new(base_type) do
graphql_name(object_type_definition.name)
description(object_type_definition.description)
ast_node(object_type_definition)
builder.build_directives(self, object_type_definition, type_resolver)
builder.build_interfaces(self, object_type_definition.interfaces, type_resolver)
builder.build_fields(self, object_type_definition.fields, type_resolver, default_resolve: true)
end
end
def build_interfaces(type_class, interface_names, type_resolver)
interface_names.each do |interface_name|
type_class.implements(type_resolver.call(interface_name))
end
end
def build_input_object_type(input_object_type_definition, type_resolver, base_type)
builder = self
Class.new(base_type) do
graphql_name(input_object_type_definition.name)
description(input_object_type_definition.description)
ast_node(input_object_type_definition)
builder.build_directives(self, input_object_type_definition, type_resolver)
builder.build_arguments(self, input_object_type_definition.fields, type_resolver)
end
end
def build_default_value(default_value)
case default_value
when GraphQL::Language::Nodes::Enum
default_value.name
when GraphQL::Language::Nodes::NullValue
nil
when GraphQL::Language::Nodes::InputObject
default_value.to_h
when Array
default_value.map { |v| build_default_value(v) }
else
default_value
end
end
def build_arguments(type_class, arguments, type_resolver)
builder = self
arguments.each do |argument_defn|
default_value_kwargs = if !argument_defn.default_value.nil?
{ default_value: builder.build_default_value(argument_defn.default_value) }
else
EMPTY_HASH
end
type_class.argument(
argument_defn.name,
type: type_resolver.call(argument_defn.type),
required: false,
description: argument_defn.description,
deprecation_reason: builder.build_deprecation_reason(argument_defn.directives),
ast_node: argument_defn,
camelize: false,
directives: prepare_directives(argument_defn, type_resolver),
**default_value_kwargs
)
end
end
def build_directive(directive_definition, type_resolver)
builder = self
Class.new(GraphQL::Schema::Directive) do
graphql_name(directive_definition.name)
description(directive_definition.description)
repeatable(directive_definition.repeatable)
locations(*directive_definition.locations.map { |location| location.name.to_sym })
ast_node(directive_definition)
builder.build_arguments(self, directive_definition.arguments, type_resolver)
end
end
def build_interface_type(interface_type_definition, type_resolver, base_type)
builder = self
Module.new do
include base_type
graphql_name(interface_type_definition.name)
description(interface_type_definition.description)
builder.build_interfaces(self, interface_type_definition.interfaces, type_resolver)
ast_node(interface_type_definition)
builder.build_directives(self, interface_type_definition, type_resolver)
builder.build_fields(self, interface_type_definition.fields, type_resolver, default_resolve: nil)
end
end
def build_fields(owner, field_definitions, type_resolver, default_resolve:)
builder = self
field_definitions.each do |field_definition|
resolve_method_name = -"resolve_field_#{field_definition.name}"
schema_field_defn = owner.field(
field_definition.name,
description: field_definition.description,
type: type_resolver.call(field_definition.type),
null: true,
connection_extension: nil,
deprecation_reason: build_deprecation_reason(field_definition.directives),
ast_node: field_definition,
method_conflict_warning: false,
camelize: false,
directives: prepare_directives(field_definition, type_resolver),
resolver_method: resolve_method_name,
)
builder.build_arguments(schema_field_defn, field_definition.arguments, type_resolver)
# Don't do this for interfaces
if default_resolve
define_field_resolve_method(owner, resolve_method_name, field_definition.name)
end
end
end
def define_field_resolve_method(owner, method_name, field_name)
owner.define_method(method_name) { |**args|
field_instance = context.types.field(owner, field_name)
context.schema.definition_default_resolve.call(self.class, field_instance, object, args, context)
}
end
def build_resolve_type(lookup_hash, directives, missing_type_handler)
resolve_type_proc = nil
resolve_type_proc = ->(ast_node) {
case ast_node
when GraphQL::Language::Nodes::TypeName
type_name = ast_node.name
if lookup_hash.key?(type_name)
lookup_hash[type_name]
else
missing_type_handler.call(type_name)
end
when GraphQL::Language::Nodes::NonNullType
resolve_type_proc.call(ast_node.of_type).to_non_null_type
when GraphQL::Language::Nodes::ListType
resolve_type_proc.call(ast_node.of_type).to_list_type
when String
directives[ast_node] ||= missing_type_handler.call(ast_node)
else
raise "Unexpected ast_node: #{ast_node.inspect}"
end
}
resolve_type_proc
end
end
private_constant :Builder
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/resolver.rb | lib/graphql/schema/resolver.rb | # frozen_string_literal: true
require "graphql/schema/resolver/has_payload_type"
module GraphQL
class Schema
# A class-based container for field configuration and resolution logic. It supports:
#
# - Arguments, via `.argument(...)` helper, which will be applied to the field.
# - Return type, via `.type(..., null: ...)`, which will be applied to the field.
# - Description, via `.description(...)`, which will be applied to the field
# - Comment, via `.comment(...)`, which will be applied to the field
# - Resolution, via `#resolve(**args)` method, which will be called to resolve the field.
# - `#object` and `#context` accessors for use during `#resolve`.
#
# Resolvers can be attached with the `resolver:` option in a `field(...)` call.
#
# A resolver's configuration may be overridden with other keywords in the `field(...)` call.
#
# @see {GraphQL::Schema::Mutation} for a concrete subclass of `Resolver`.
# @see {GraphQL::Function} `Resolver` is a replacement for `GraphQL::Function`
class Resolver
include Schema::Member::GraphQLTypeNames
# Really we only need description & comment from here, but:
extend Schema::Member::BaseDSLMethods
extend GraphQL::Schema::Member::HasArguments
extend GraphQL::Schema::Member::HasValidators
include Schema::Member::HasPath
extend Schema::Member::HasPath
extend Schema::Member::HasDirectives
include Schema::Member::HasDataloader
extend Schema::Member::HasDeprecationReason
# @param object [Object] The application object that this field is being resolved on
# @param context [GraphQL::Query::Context]
# @param field [GraphQL::Schema::Field]
def initialize(object:, context:, field:)
@object = object
@context = context
@field = field
# Since this hash is constantly rebuilt, cache it for this call
@arguments_by_keyword = {}
context.types.arguments(self.class).each do |arg|
@arguments_by_keyword[arg.keyword] = arg
end
@prepared_arguments = nil
end
# @return [Object] The application object this field is being resolved on
attr_reader :object
# @return [GraphQL::Query::Context]
attr_reader :context
# @return [GraphQL::Schema::Field]
attr_reader :field
def arguments
@prepared_arguments || raise("Arguments have not been prepared yet, still waiting for #load_arguments to resolve. (Call `.arguments` later in the code.)")
end
# This method is _actually_ called by the runtime,
# it does some preparation and then eventually calls
# the user-defined `#resolve` method.
# @api private
def resolve_with_support(**args)
# First call the ready? hook which may raise
raw_ready_val = if !args.empty?
ready?(**args)
else
ready?
end
context.query.after_lazy(raw_ready_val) do |ready_val|
if ready_val.is_a?(Array)
is_ready, ready_early_return = ready_val
if is_ready != false
raise "Unexpected result from #ready? (expected `true`, `false` or `[false, {...}]`): [#{is_ready.inspect}, #{ready_early_return.inspect}]"
else
ready_early_return
end
elsif ready_val
# Then call each prepare hook, which may return a different value
# for that argument, or may return a lazy object
load_arguments_val = load_arguments(args)
context.query.after_lazy(load_arguments_val) do |loaded_args|
@prepared_arguments = loaded_args
Schema::Validator.validate!(self.class.validators, object, context, loaded_args, as: @field)
# Then call `authorized?`, which may raise or may return a lazy object
raw_authorized_val = if !loaded_args.empty?
authorized?(**loaded_args)
else
authorized?
end
context.query.after_lazy(raw_authorized_val) do |authorized_val|
# If the `authorized?` returned two values, `false, early_return`,
# then use the early return value instead of continuing
if authorized_val.is_a?(Array)
authorized_result, early_return = authorized_val
if authorized_result == false
early_return
else
raise "Unexpected result from #authorized? (expected `true`, `false` or `[false, {...}]`): [#{authorized_result.inspect}, #{early_return.inspect}]"
end
elsif authorized_val
# Finally, all the hooks have passed, so resolve it
call_resolve(loaded_args)
else
raise GraphQL::UnauthorizedFieldError.new(context: context, object: object, type: field.owner, field: field)
end
end
end
end
end
end
# @api private {GraphQL::Schema::Mutation} uses this to clear the dataloader cache
def call_resolve(args_hash)
if !args_hash.empty?
public_send(self.class.resolve_method, **args_hash)
else
public_send(self.class.resolve_method)
end
end
# Do the work. Everything happens here.
# @return [Object] An object corresponding to the return type
def resolve(**args)
raise GraphQL::RequiredImplementationMissingError, "#{self.class.name}#resolve should execute the field's logic"
end
# Called before arguments are prepared.
# Implement this hook to make checks before doing any work.
#
# If it returns a lazy object (like a promise), it will be synced by GraphQL
# (but the resulting value won't be used).
#
# @param args [Hash] The input arguments, if there are any
# @raise [GraphQL::ExecutionError] To add an error to the response
# @raise [GraphQL::UnauthorizedError] To signal an authorization failure
# @return [Boolean, early_return_data] If `false`, execution will stop (and `early_return_data` will be returned instead, if present.)
def ready?(**args)
true
end
# Called after arguments are loaded, but before resolving.
#
# Override it to check everything before calling the mutation.
# @param inputs [Hash] The input arguments
# @raise [GraphQL::ExecutionError] To add an error to the response
# @raise [GraphQL::UnauthorizedError] To signal an authorization failure
# @return [Boolean, early_return_data] If `false`, execution will stop (and `early_return_data` will be returned instead, if present.)
def authorized?(**inputs)
arg_owner = @field # || self.class
args = context.types.arguments(arg_owner)
authorize_arguments(args, inputs)
end
# Called when an object loaded by `loads:` fails the `.authorized?` check for its resolved GraphQL object type.
#
# By default, the error is re-raised and passed along to {{Schema.unauthorized_object}}.
#
# Any value returned here will be used _instead of_ of the loaded object.
# @param err [GraphQL::UnauthorizedError]
def unauthorized_object(err)
raise err
end
private
def authorize_arguments(args, inputs)
args.each do |argument|
arg_keyword = argument.keyword
if inputs.key?(arg_keyword) && !(arg_value = inputs[arg_keyword]).nil? && (arg_value != argument.default_value)
auth_result = argument.authorized?(self, arg_value, context)
if auth_result.is_a?(Array)
# only return this second value if the application returned a second value
arg_auth, err = auth_result
if !arg_auth
return arg_auth, err
end
elsif auth_result == false
return auth_result
end
end
end
true
end
def load_arguments(args)
prepared_args = {}
prepare_lazies = []
args.each do |key, value|
arg_defn = @arguments_by_keyword[key]
if arg_defn
prepped_value = prepared_args[key] = arg_defn.load_and_authorize_value(self, value, context)
if context.schema.lazy?(prepped_value)
prepare_lazies << context.query.after_lazy(prepped_value) do |finished_prepped_value|
prepared_args[key] = finished_prepped_value
end
end
else
# these are `extras:`
prepared_args[key] = value
end
end
# Avoid returning a lazy if none are needed
if !prepare_lazies.empty?
GraphQL::Execution::Lazy.all(prepare_lazies).then { prepared_args }
else
prepared_args
end
end
def get_argument(name, context = GraphQL::Query::NullContext.instance)
self.class.get_argument(name, context)
end
class << self
def field_arguments(context = GraphQL::Query::NullContext.instance)
arguments(context)
end
def any_field_arguments?
any_arguments?
end
def get_field_argument(name, context = GraphQL::Query::NullContext.instance)
get_argument(name, context)
end
def all_field_argument_definitions
all_argument_definitions
end
# Default `:resolve` set below.
# @return [Symbol] The method to call on instances of this object to resolve the field
def resolve_method(new_method = nil)
if new_method
@resolve_method = new_method
end
@resolve_method || (superclass.respond_to?(:resolve_method) ? superclass.resolve_method : :resolve)
end
# Additional info injected into {#resolve}
# @see {GraphQL::Schema::Field#extras}
def extras(new_extras = nil)
if new_extras
@own_extras = new_extras
end
own_extras = @own_extras || []
own_extras + (superclass.respond_to?(:extras) ? superclass.extras : [])
end
# If `true` (default), then the return type for this resolver will be nullable.
# If `false`, then the return type is non-null.
#
# @see #type which sets the return type of this field and accepts a `null:` option
# @param allow_null [Boolean] Whether or not the response can be null
def null(allow_null = nil)
if !allow_null.nil?
@null = allow_null
end
@null.nil? ? (superclass.respond_to?(:null) ? superclass.null : true) : @null
end
def resolver_method(new_method_name = nil)
if new_method_name
@resolver_method = new_method_name
else
@resolver_method || :resolve_with_support
end
end
# Call this method to get the return type of the field,
# or use it as a configuration method to assign a return type
# instead of generating one.
# TODO unify with {#null}
# @param new_type [Class, Array<Class>, nil] If a type definition class is provided, it will be used as the return type of the field
# @param null [true, false] Whether or not the field may return `nil`
# @return [Class] The type which this field returns.
def type(new_type = nil, null: nil)
if new_type
if null.nil?
raise ArgumentError, "required argument `null:` is missing"
end
@type_expr = new_type
@null = null
else
if type_expr
GraphQL::Schema::Member::BuildType.parse_type(type_expr, null: self.null)
elsif superclass.respond_to?(:type)
superclass.type
else
nil
end
end
end
# Specifies the complexity of the field. Defaults to `1`
# @return [Integer, Proc]
def complexity(new_complexity = nil)
if new_complexity
@complexity = new_complexity
end
@complexity || (superclass.respond_to?(:complexity) ? superclass.complexity : 1)
end
def broadcastable(new_broadcastable)
@broadcastable = new_broadcastable
end
# @return [Boolean, nil]
def broadcastable?
if defined?(@broadcastable)
@broadcastable
else
(superclass.respond_to?(:broadcastable?) ? superclass.broadcastable? : nil)
end
end
# Get or set the `max_page_size:` which will be configured for fields using this resolver
# (`nil` means "unlimited max page size".)
# @param max_page_size [Integer, nil] Set a new value
# @return [Integer, nil] The `max_page_size` assigned to fields that use this resolver
def max_page_size(new_max_page_size = NOT_CONFIGURED)
if new_max_page_size != NOT_CONFIGURED
@max_page_size = new_max_page_size
elsif defined?(@max_page_size)
@max_page_size
elsif superclass.respond_to?(:max_page_size)
superclass.max_page_size
else
nil
end
end
# @return [Boolean] `true` if this resolver or a superclass has an assigned `max_page_size`
def has_max_page_size?
(!!defined?(@max_page_size)) || (superclass.respond_to?(:has_max_page_size?) && superclass.has_max_page_size?)
end
# Get or set the `default_page_size:` which will be configured for fields using this resolver
# (`nil` means "unlimited default page size".)
# @param default_page_size [Integer, nil] Set a new value
# @return [Integer, nil] The `default_page_size` assigned to fields that use this resolver
def default_page_size(new_default_page_size = NOT_CONFIGURED)
if new_default_page_size != NOT_CONFIGURED
@default_page_size = new_default_page_size
elsif defined?(@default_page_size)
@default_page_size
elsif superclass.respond_to?(:default_page_size)
superclass.default_page_size
else
nil
end
end
# @return [Boolean] `true` if this resolver or a superclass has an assigned `default_page_size`
def has_default_page_size?
(!!defined?(@default_page_size)) || (superclass.respond_to?(:has_default_page_size?) && superclass.has_default_page_size?)
end
# A non-normalized type configuration, without `null` applied
def type_expr
@type_expr || (superclass.respond_to?(:type_expr) ? superclass.type_expr : nil)
end
# Add an argument to this field's signature, but
# also add some preparation hook methods which will be used for this argument
# @see {GraphQL::Schema::Argument#initialize} for the signature
def argument(*args, **kwargs, &block)
# Use `from_resolver: true` to short-circuit the InputObject's own `loads:` implementation
# so that we can support `#load_{x}` methods below.
super(*args, from_resolver: true, **kwargs)
end
# Registers new extension
# @param extension [Class] Extension class
# @param options [Hash] Optional extension options
def extension(extension, **options)
@own_extensions ||= []
@own_extensions << {extension => options}
end
# @api private
def extensions
own_exts = @own_extensions
# Jump through some hoops to avoid creating arrays when we don't actually need them
if superclass.respond_to?(:extensions)
s_exts = superclass.extensions
if own_exts
if !s_exts.empty?
own_exts + s_exts
else
own_exts
end
else
s_exts
end
else
own_exts || EMPTY_ARRAY
end
end
def inherited(child_class)
child_class.description(description)
super
end
private
attr_reader :own_extensions
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/validator.rb | lib/graphql/schema/validator.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Validator
# The thing being validated
# @return [GraphQL::Schema::Argument, GraphQL::Schema::Field, GraphQL::Schema::Resolver, Class<GraphQL::Schema::InputObject>]
attr_reader :validated
# @param validated [GraphQL::Schema::Argument, GraphQL::Schema::Field, GraphQL::Schema::Resolver, Class<GraphQL::Schema::InputObject>] The argument or argument owner this validator is attached to
# @param allow_blank [Boolean] if `true`, then objects that respond to `.blank?` and return true for `.blank?` will skip this validation
# @param allow_null [Boolean] if `true`, then incoming `null`s will skip this validation
def initialize(validated:, allow_blank: false, allow_null: false)
@validated = validated
@allow_blank = allow_blank
@allow_null = allow_null
end
# @param object [Object] The application object that this argument's field is being resolved for
# @param context [GraphQL::Query::Context]
# @param value [Object] The client-provided value for this argument (after parsing and coercing by the input type)
# @return [nil, Array<String>, String] Error message or messages to add
def validate(object, context, value)
raise GraphQL::RequiredImplementationMissingError, "Validator classes should implement #validate"
end
# This is like `String#%`, but it supports the case that only some of `string`'s
# values are present in `substitutions`
def partial_format(string, substitutions)
substitutions.each do |key, value|
sub_v = value.is_a?(String) ? value : value.to_s
string = string.gsub("%{#{key}}", sub_v)
end
string
end
# @return [Boolean] `true` if `value` is `nil` and this validator has `allow_null: true` or if value is `.blank?` and this validator has `allow_blank: true`
def permitted_empty_value?(value)
(value.nil? && @allow_null) ||
(@allow_blank && value.respond_to?(:blank?) && value.blank?)
end
# @param schema_member [GraphQL::Schema::Field, GraphQL::Schema::Argument, Class<GraphQL::Schema::InputObject>]
# @param validates_hash [Hash{Symbol => Hash}, Hash{Class => Hash} nil] A configuration passed as `validates:`
# @return [Array<Validator>]
def self.from_config(schema_member, validates_hash)
if validates_hash.nil? || validates_hash.empty?
EMPTY_ARRAY
else
validates_hash = validates_hash.dup
default_options = {}
if validates_hash[:allow_null]
default_options[:allow_null] = validates_hash.delete(:allow_null)
end
if validates_hash[:allow_blank]
default_options[:allow_blank] = validates_hash.delete(:allow_blank)
end
# allow_nil or allow_blank are the _only_ validations:
if validates_hash.empty?
validates_hash = default_options
end
validates_hash.map do |validator_name, options|
validator_class = case validator_name
when Class
validator_name
else
all_validators[validator_name] || raise(ArgumentError, "unknown validation: #{validator_name.inspect}")
end
if options.is_a?(Hash)
validator_class.new(validated: schema_member, **(default_options.merge(options)))
else
validator_class.new(options, validated: schema_member, **default_options)
end
end
end
end
# Add `validator_class` to be initialized when `validates:` is given `name`.
# (It's initialized with whatever options are given by the key `name`).
# @param name [Symbol]
# @param validator_class [Class]
# @return [void]
def self.install(name, validator_class)
all_validators[name] = validator_class
nil
end
# Remove whatever validator class is {.install}ed at `name`, if there is one
# @param name [Symbol]
# @return [void]
def self.uninstall(name)
all_validators.delete(name)
nil
end
class << self
attr_accessor :all_validators
end
self.all_validators = {}
include GraphQL::EmptyObjects
class ValidationFailedError < GraphQL::ExecutionError
attr_reader :errors
def initialize(errors:)
@errors = errors
super(errors.join(", "))
end
end
# @param validators [Array<Validator>]
# @param object [Object]
# @param context [Query::Context]
# @param value [Object]
# @return [void]
# @raises [ValidationFailedError]
def self.validate!(validators, object, context, value, as: nil)
# Assuming the default case is no errors, reduce allocations in that case.
# This will be replaced with a mutable array if we actually get any errors.
all_errors = EMPTY_ARRAY
validators.each do |validator|
validated = as || validator.validated
errors = validator.validate(object, context, value)
if errors &&
(errors.is_a?(Array) && errors != EMPTY_ARRAY) ||
(errors.is_a?(String))
if all_errors.frozen? # It's empty
all_errors = []
end
interpolation_vars = { validated: validated.graphql_name, value: value.inspect }
if errors.is_a?(String)
all_errors << (errors % interpolation_vars)
else
errors = errors.map { |e| e % interpolation_vars }
all_errors.concat(errors)
end
end
end
if !all_errors.empty?
raise ValidationFailedError.new(errors: all_errors)
end
nil
end
end
end
end
require "graphql/schema/validator/length_validator"
GraphQL::Schema::Validator.install(:length, GraphQL::Schema::Validator::LengthValidator)
require "graphql/schema/validator/numericality_validator"
GraphQL::Schema::Validator.install(:numericality, GraphQL::Schema::Validator::NumericalityValidator)
require "graphql/schema/validator/format_validator"
GraphQL::Schema::Validator.install(:format, GraphQL::Schema::Validator::FormatValidator)
require "graphql/schema/validator/inclusion_validator"
GraphQL::Schema::Validator.install(:inclusion, GraphQL::Schema::Validator::InclusionValidator)
require "graphql/schema/validator/exclusion_validator"
GraphQL::Schema::Validator.install(:exclusion, GraphQL::Schema::Validator::ExclusionValidator)
require "graphql/schema/validator/required_validator"
GraphQL::Schema::Validator.install(:required, GraphQL::Schema::Validator::RequiredValidator)
require "graphql/schema/validator/allow_null_validator"
GraphQL::Schema::Validator.install(:allow_null, GraphQL::Schema::Validator::AllowNullValidator)
require "graphql/schema/validator/allow_blank_validator"
GraphQL::Schema::Validator.install(:allow_blank, GraphQL::Schema::Validator::AllowBlankValidator)
require "graphql/schema/validator/all_validator"
GraphQL::Schema::Validator.install(:all, GraphQL::Schema::Validator::AllValidator)
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/object.rb | lib/graphql/schema/object.rb | # frozen_string_literal: true
require "graphql/query/null_context"
module GraphQL
class Schema
class Object < GraphQL::Schema::Member
extend GraphQL::Schema::Member::HasFields
extend GraphQL::Schema::Member::HasInterfaces
include Member::HasDataloader
# Raised when an Object doesn't have any field defined and hasn't explicitly opted out of this requirement
class FieldsAreRequiredError < GraphQL::Error
def initialize(object_type)
message = "Object types must have fields, but #{object_type.graphql_name} doesn't have any. Define a field for this type, remove it from your schema, or add `has_no_fields(true)` to its definition."
super(message)
end
end
# @return [Object] the application object this type is wrapping
attr_reader :object
# @return [GraphQL::Query::Context] the context instance for this query
attr_reader :context
# @return [GraphQL::Dataloader]
def dataloader
context.dataloader
end
# Call this in a field method to return a value that should be returned to the client
# without any further handling by GraphQL.
def raw_value(obj)
GraphQL::Execution::Interpreter::RawValue.new(obj)
end
class << self
# This is protected so that we can be sure callers use the public method, {.authorized_new}
# @see authorized_new to make instances
protected :new
def wrap_scoped(object, context)
scoped_new(object, context)
end
# This is called by the runtime to return an object to call methods on.
def wrap(object, context)
authorized_new(object, context)
end
# Make a new instance of this type _if_ the auth check passes,
# otherwise, raise an error.
#
# Probably only the framework should call this method.
#
# This might return a {GraphQL::Execution::Lazy} if the user-provided `.authorized?`
# hook returns some lazy value (like a Promise).
#
# The reason that the auth check is in this wrapper method instead of {.new} is because
# of how it might return a Promise. It would be weird if `.new` returned a promise;
# It would be a headache to try to maintain Promise-y state inside a {Schema::Object}
# instance. So, hopefully this wrapper method will do the job.
#
# @param object [Object] The thing wrapped by this object
# @param context [GraphQL::Query::Context]
# @return [GraphQL::Schema::Object, GraphQL::Execution::Lazy]
# @raise [GraphQL::UnauthorizedError] if the user-provided hook returns `false`
def authorized_new(object, context)
context.query.current_trace.begin_authorized(self, object, context)
begin
maybe_lazy_auth_val = context.query.current_trace.authorized(query: context.query, type: self, object: object) do
begin
authorized?(object, context)
rescue GraphQL::UnauthorizedError => err
context.schema.unauthorized_object(err)
rescue StandardError => err
context.query.handle_or_reraise(err)
end
end
ensure
context.query.current_trace.end_authorized(self, object, context, maybe_lazy_auth_val)
end
auth_val = if context.schema.lazy?(maybe_lazy_auth_val)
GraphQL::Execution::Lazy.new do
context.query.current_trace.begin_authorized(self, object, context)
context.query.current_trace.authorized_lazy(query: context.query, type: self, object: object) do
res = context.schema.sync_lazy(maybe_lazy_auth_val)
context.query.current_trace.end_authorized(self, object, context, res)
res
end
end
else
maybe_lazy_auth_val
end
context.query.after_lazy(auth_val) do |is_authorized|
if is_authorized
self.new(object, context)
else
# It failed the authorization check, so go to the schema's authorized object hook
err = GraphQL::UnauthorizedError.new(object: object, type: self, context: context)
# If a new value was returned, wrap that instead of the original value
begin
new_obj = context.schema.unauthorized_object(err)
if new_obj
self.new(new_obj, context)
else
nil
end
end
end
end
end
def scoped_new(object, context)
self.new(object, context)
end
end
def initialize(object, context)
@object = object
@context = context
end
class << self
# Set up a type-specific invalid null error to use when this object's non-null fields wrongly return `nil`.
# It should help with debugging and bug tracker integrations.
def const_missing(name)
if name == :InvalidNullError
custom_err_class = GraphQL::InvalidNullError.subclass_for(self)
const_set(:InvalidNullError, custom_err_class)
custom_err_class
else
super
end
end
def kind
GraphQL::TypeKinds::OBJECT
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/union.rb | lib/graphql/schema/union.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Union < GraphQL::Schema::Member
extend GraphQL::Schema::Member::HasUnresolvedTypeError
class << self
def inherited(child_class)
add_unresolved_type_error(child_class)
super
end
def possible_types(*types, context: GraphQL::Query::NullContext.instance, **options)
if !types.empty?
types.each do |t|
assert_valid_union_member(t)
type_memberships << type_membership_class.new(self, t, **options)
end
else
visible_types = []
warden = Warden.from_context(context)
type_memberships.each do |type_membership|
if warden.visible_type_membership?(type_membership, context)
visible_types << type_membership.object_type
end
end
visible_types
end
end
def all_possible_types
type_memberships.map(&:object_type)
end
def type_membership_class(membership_class = nil)
if membership_class
@type_membership_class = membership_class
else
@type_membership_class || find_inherited_value(:type_membership_class, GraphQL::Schema::TypeMembership)
end
end
def kind
GraphQL::TypeKinds::UNION
end
def type_memberships
@type_memberships ||= []
end
# Update a type membership whose `.object_type` is a string or late-bound type
# so that the type membership's `.object_type` is the given `object_type`.
# (This is used for updating the union after the schema as lazily loaded the union member.)
# @api private
def assign_type_membership_object_type(object_type)
assert_valid_union_member(object_type)
type_memberships.each { |tm|
possible_type = tm.object_type
if possible_type.is_a?(String) && (possible_type == object_type.name)
# This is a match of Ruby class names, not graphql names,
# since strings are used to refer to constants.
tm.object_type = object_type
elsif possible_type.is_a?(LateBoundType) && possible_type.graphql_name == object_type.graphql_name
tm.object_type = object_type
end
}
nil
end
private
def assert_valid_union_member(type_defn)
case type_defn
when Class
if !type_defn.kind.object?
raise ArgumentError, "Union possible_types can only be object types (not #{type_defn.kind.name}, #{type_defn.inspect})"
end
when Module
# it's an interface type, defined as a module
raise ArgumentError, "Union possible_types can only be object types (not interface types), remove #{type_defn.graphql_name} (#{type_defn.inspect})"
when String, GraphQL::Schema::LateBoundType
# Ok - assume it will get checked later
else
raise ArgumentError, "Union possible_types can only be class-based GraphQL types (not #{type_defn.inspect} (#{type_defn.class.name}))."
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/addition.rb | lib/graphql/schema/addition.rb | # frozen_string_literal: true
module GraphQL
class Schema
class Addition
attr_reader :directives, :possible_types, :types, :union_memberships, :references, :arguments_with_default_values
def initialize(schema:, own_types:, new_types:)
@schema = schema
@own_types = own_types
@directives = Set.new
@possible_types = {}
@types = {}
@union_memberships = {}
@references = Hash.new { |h, k| h[k] = Set.new }
@arguments_with_default_values = []
add_type_and_traverse(new_types)
end
private
def references_to(thing, from:)
@references[thing].add(from)
end
def get_type(name)
local_type = @types[name]
# This isn't really sophisticated, but
# I think it's good enough to support the current usage of LateBoundTypes
if local_type.is_a?(Array)
local_type = local_type.first
end
local_type || @schema.get_type(name)
end
# Lookup using `own_types` here because it's ok to override
# inherited types by name
def get_local_type(name)
@types[name] || @own_types[name]
end
def add_directives_from(owner)
if !(dir_instances = owner.directives).empty?
dirs = dir_instances.map(&:class)
@directives.merge(dirs)
add_type_and_traverse(dirs)
end
end
def add_type_and_traverse(new_types)
late_types = []
path = []
new_types.each do |t|
path.push(t.graphql_name)
add_type(t, owner: nil, late_types: late_types, path: path)
path.pop
end
missed_late_types = 0
while (late_type_vals = late_types.shift)
type_owner, lt = late_type_vals
if lt.is_a?(String)
type = Member::BuildType.constantize(lt)
# Reset the counter, since we might succeed next go-round
missed_late_types = 0
update_type_owner(type_owner, type)
add_type(type, owner: type_owner, late_types: late_types, path: [type.graphql_name])
elsif lt.is_a?(LateBoundType)
if (type = get_type(lt.name))
# Reset the counter, since we might succeed next go-round
missed_late_types = 0
update_type_owner(type_owner, type)
add_type(type, owner: type_owner, late_types: late_types, path: [type.graphql_name])
else
missed_late_types += 1
# Add it back to the list, maybe we'll be able to resolve it later.
late_types << [type_owner, lt]
if missed_late_types == late_types.size
# We've looked at all of them and haven't resolved one.
raise UnresolvedLateBoundTypeError.new(type: lt)
else
# Try the next one
end
end
else
raise ArgumentError, "Unexpected late type: #{lt.inspect}"
end
end
nil
end
def update_type_owner(owner, type)
case owner
when Module
if owner.kind.union?
# It's a union with possible_types
# Replace the item by class name
owner.assign_type_membership_object_type(type)
@possible_types[owner] = owner.possible_types
elsif type.kind.interface? && (owner.kind.object? || owner.kind.interface?)
new_interfaces = []
owner.interfaces.each do |int_t|
if int_t.is_a?(String) && int_t == type.graphql_name
new_interfaces << type
elsif int_t.is_a?(LateBoundType) && int_t.graphql_name == type.graphql_name
new_interfaces << type
else
# Don't re-add proper interface definitions,
# they were probably already added, maybe with options.
end
end
owner.implements(*new_interfaces)
new_interfaces.each do |int|
pt = @possible_types[int] ||= []
if !pt.include?(owner) && owner.is_a?(Class)
pt << owner
end
int.interfaces.each do |indirect_int|
if indirect_int.is_a?(LateBoundType) && (indirect_int_type = get_type(indirect_int.graphql_name))
update_type_owner(owner, indirect_int_type)
end
end
end
end
when nil
# It's a root type
@types[type.graphql_name] = type
when GraphQL::Schema::Field, GraphQL::Schema::Argument
orig_type = owner.type
unwrapped_t = type
# Apply list/non-null wrapper as needed
if orig_type.respond_to?(:of_type)
transforms = []
while (orig_type.respond_to?(:of_type))
if orig_type.kind.non_null?
transforms << :to_non_null_type
elsif orig_type.kind.list?
transforms << :to_list_type
else
raise "Invariant: :of_type isn't non-null or list"
end
orig_type = orig_type.of_type
end
transforms.reverse_each { |t| type = type.public_send(t) }
end
owner.type = type
references_to(unwrapped_t, from: owner)
else
raise "Unexpected update: #{owner.inspect} #{type.inspect}"
end
end
def add_type(type, owner:, late_types:, path:)
if type.is_a?(String) || type.is_a?(GraphQL::Schema::LateBoundType)
late_types << [owner, type]
return
end
if owner.is_a?(Class) && owner < GraphQL::Schema::Union
um = @union_memberships[type.graphql_name] ||= []
um << owner
end
if (prev_type = get_local_type(type.graphql_name)) && (prev_type == type || (prev_type.is_a?(Array) && prev_type.include?(type)))
# No need to re-visit
elsif type.is_a?(Class) && type < GraphQL::Schema::Directive
@directives << type
type.all_argument_definitions.each do |arg|
arg_type = arg.type.unwrap
if !arg_type.is_a?(GraphQL::Schema::LateBoundType)
references_to(arg_type, from: arg)
end
path.push(arg.graphql_name)
add_type(arg_type, owner: arg, late_types: late_types, path: path)
path.pop
if arg.default_value?
@arguments_with_default_values << arg
end
end
else
prev_type = @types[type.graphql_name]
if prev_type.nil?
@types[type.graphql_name] = type
elsif prev_type.is_a?(Array)
prev_type << type
else
@types[type.graphql_name] = [prev_type, type]
end
add_directives_from(type)
if type.kind.fields?
type.all_field_definitions.each do |field|
field.ensure_loaded
name = field.graphql_name
field_type = field.type.unwrap
if !field_type.is_a?(GraphQL::Schema::LateBoundType)
references_to(field_type, from: field)
end
path.push(name)
add_type(field_type, owner: field, late_types: late_types, path: path)
add_directives_from(field)
field.all_argument_definitions.each do |arg|
add_directives_from(arg)
arg_type = arg.type.unwrap
if !arg_type.is_a?(GraphQL::Schema::LateBoundType)
references_to(arg_type, from: arg)
end
path.push(arg.graphql_name)
add_type(arg_type, owner: arg, late_types: late_types, path: path)
path.pop
if arg.default_value?
@arguments_with_default_values << arg
end
end
path.pop
end
end
if type.kind.input_object?
type.all_argument_definitions.each do |arg|
add_directives_from(arg)
arg_type = arg.type.unwrap
if !arg_type.is_a?(GraphQL::Schema::LateBoundType)
references_to(arg_type, from: arg)
end
path.push(arg.graphql_name)
add_type(arg_type, owner: arg, late_types: late_types, path: path)
path.pop
if arg.default_value?
@arguments_with_default_values << arg
end
end
end
if type.kind.union?
@possible_types[type] = type.all_possible_types
path.push("possible_types")
type.all_possible_types.each do |t|
add_type(t, owner: type, late_types: late_types, path: path)
end
path.pop
end
if type.kind.interface?
path.push("orphan_types")
type.orphan_types.each do |t|
add_type(t, owner: type, late_types: late_types, path: path)
end
path.pop
end
if type.kind.object?
possible_types_for_this_name = @possible_types[type] ||= []
possible_types_for_this_name << type
end
if type.kind.object? || type.kind.interface?
path.push("implements")
type.interface_type_memberships.each do |interface_type_membership|
case interface_type_membership
when Schema::TypeMembership
interface_type = interface_type_membership.abstract_type
# We can get these now; we'll have to get late-bound types later
if interface_type.is_a?(Module) && type.is_a?(Class)
implementers = @possible_types[interface_type] ||= []
if !implementers.include?(type)
implementers << type
end
end
when String, Schema::LateBoundType
interface_type = interface_type_membership
else
raise ArgumentError, "Invariant: unexpected type membership for #{type.graphql_name}: #{interface_type_membership.class} (#{interface_type_membership.inspect})"
end
add_type(interface_type, owner: type, late_types: late_types, path: path)
end
path.pop
end
if type.kind.enum?
type.all_enum_value_definitions.each do |value_definition|
add_directives_from(value_definition)
end
end
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/type_membership.rb | lib/graphql/schema/type_membership.rb | # frozen_string_literal: true
module GraphQL
class Schema
# This class joins an object type to an abstract type (interface or union) of which
# it is a member.
class TypeMembership
# @return [Class<GraphQL::Schema::Object>]
attr_accessor :object_type
# @return [Class<GraphQL::Schema::Union>, Module<GraphQL::Schema::Interface>]
attr_reader :abstract_type
# @return [Hash]
attr_reader :options
# Called when an object is hooked up to an abstract type, such as {Schema::Union.possible_types}
# or {Schema::Object.implements} (for interfaces).
#
# @param abstract_type [Class<GraphQL::Schema::Union>, Module<GraphQL::Schema::Interface>]
# @param object_type [Class<GraphQL::Schema::Object>]
# @param options [Hash] Any options passed to `.possible_types` or `.implements`
def initialize(abstract_type, object_type, **options)
@abstract_type = abstract_type
@object_type = object_type
@options = options
end
# @return [Boolean] if false, {#object_type} will be treated as _not_ a member of {#abstract_type}
def visible?(ctx)
warden = Warden.from_context(ctx)
(@object_type.respond_to?(:visible?) ? warden.visible_type?(@object_type, ctx) : true) &&
(@abstract_type.respond_to?(:visible?) ? warden.visible_type?(@abstract_type, ctx) : true)
end
def graphql_name
"#{@object_type.graphql_name}.#{@abstract_type.kind.interface? ? "implements" : "belongsTo" }.#{@abstract_type.graphql_name}"
end
def path
graphql_name
end
def inspect
"#<#{self.class} #{@object_type.inspect} => #{@abstract_type.inspect}>"
end
alias :type_class :itself
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/enum.rb | lib/graphql/schema/enum.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Extend this class to define GraphQL enums in your schema.
#
# By default, GraphQL enum values are translated into Ruby strings.
# You can provide a custom value with the `value:` keyword.
#
# @example
# # equivalent to
# # enum PizzaTopping {
# # MUSHROOMS
# # ONIONS
# # PEPPERS
# # }
# class PizzaTopping < GraphQL::Schema::Enum
# value :MUSHROOMS
# value :ONIONS
# value :PEPPERS
# end
class Enum < GraphQL::Schema::Member
extend GraphQL::Schema::Member::ValidatesInput
# This is raised when either:
#
# - A resolver returns a value which doesn't match any of the enum's configured values;
# - Or, the resolver returns a value which matches a value, but that value's `authorized?` check returns false.
#
# In either case, the field should be modified so that the invalid value isn't returned.
#
# {GraphQL::Schema::Enum} subclasses get their own subclass of this error, so that bug trackers can better show where they came from.
class UnresolvedValueError < GraphQL::Error
def initialize(value:, enum:, context:, authorized:)
fix_message = if authorized == false
", but this value was unauthorized. Update the field or resolver to return a different value in this case (or return `nil`)."
else
", but this isn't a valid value for `#{enum.graphql_name}`. Update the field or resolver to return one of `#{enum.graphql_name}`'s values instead."
end
message = if (cp = context[:current_path]) && (cf = context[:current_field])
"`#{cf.path}` returned `#{value.inspect}` at `#{cp.join(".")}`#{fix_message}"
else
"`#{value.inspect}` was returned for `#{enum.graphql_name}`#{fix_message}"
end
super(message)
end
end
# Raised when a {GraphQL::Schema::Enum} is defined to have no values.
# This can also happen when all values return false for `.visible?`.
class MissingValuesError < GraphQL::Error
def initialize(enum_type)
@enum_type = enum_type
super("Enum types require at least one value, but #{enum_type.graphql_name} didn't provide any for this query. Make sure at least one value is defined and visible for this query.")
end
end
class << self
# Define a value for this enum
# @option kwargs [String, Symbol] :graphql_name the GraphQL value for this, usually `SCREAMING_CASE`
# @option kwargs [String] :description, the GraphQL description for this value, present in documentation
# @option kwargs [String] :comment, the GraphQL comment for this value, present in documentation
# @option kwargs [::Object] :value the translated Ruby value for this object (defaults to `graphql_name`)
# @option kwargs [::Object] :value_method, the method name to fetch `graphql_name` (defaults to `graphql_name.downcase`)
# @option kwargs [String] :deprecation_reason if this object is deprecated, include a message here
# @param value_method [Symbol, false] A method to generate for this value, or `false` to skip generation
# @return [void]
# @see {Schema::EnumValue} which handles these inputs by default
def value(*args, value_method: nil, **kwargs, &block)
kwargs[:owner] = self
value = enum_value_class.new(*args, **kwargs, &block)
if value_method || (value_methods && value_method != false)
generate_value_method(value, value_method)
end
key = value.graphql_name
prev_value = own_values[key]
case prev_value
when nil
own_values[key] = value
when GraphQL::Schema::EnumValue
own_values[key] = [prev_value, value]
when Array
prev_value << value
else
raise "Invariant: Unexpected enum value for #{key.inspect}: #{prev_value.inspect}"
end
value
end
# @return [Array<GraphQL::Schema::EnumValue>] Possible values of this enum
def enum_values(context = GraphQL::Query::NullContext.instance)
inherited_values = superclass.respond_to?(:enum_values) ? superclass.enum_values(context) : nil
visible_values = []
types = Warden.types_from_context(context)
own_values.each do |key, values_entry|
visible_value = nil
if values_entry.is_a?(Array)
values_entry.each do |v|
if types.visible_enum_value?(v, context)
if visible_value.nil?
visible_value = v
visible_values << v
else
raise DuplicateNamesError.new(
duplicated_name: v.path, duplicated_definition_1: visible_value.inspect, duplicated_definition_2: v.inspect
)
end
end
end
elsif types.visible_enum_value?(values_entry, context)
visible_values << values_entry
end
end
if inherited_values
# Local values take precedence over inherited ones
inherited_values.each do |i_val|
if !visible_values.any? { |v| v.graphql_name == i_val.graphql_name }
visible_values << i_val
end
end
end
visible_values
end
# @return [Array<Schema::EnumValue>] An unfiltered list of all definitions
def all_enum_value_definitions
all_defns = if superclass.respond_to?(:all_enum_value_definitions)
superclass.all_enum_value_definitions
else
[]
end
@own_values && @own_values.each do |_key, value|
if value.is_a?(Array)
all_defns.concat(value)
else
all_defns << value
end
end
all_defns
end
# @return [Hash<String => GraphQL::Schema::EnumValue>] Possible values of this enum, keyed by name.
def values(context = GraphQL::Query::NullContext.instance)
enum_values(context).each_with_object({}) { |val, obj| obj[val.graphql_name] = val }
end
# @return [Class] for handling `value(...)` inputs and building `GraphQL::Enum::EnumValue`s out of them
def enum_value_class(new_enum_value_class = nil)
if new_enum_value_class
@enum_value_class = new_enum_value_class
elsif defined?(@enum_value_class) && @enum_value_class
@enum_value_class
else
superclass <= GraphQL::Schema::Enum ? superclass.enum_value_class : nil
end
end
def value_methods(new_value = NOT_CONFIGURED)
if NOT_CONFIGURED.equal?(new_value)
if @value_methods != nil
@value_methods
else
find_inherited_value(:value_methods, false)
end
else
@value_methods = new_value
end
end
def kind
GraphQL::TypeKinds::ENUM
end
def validate_non_null_input(value_name, ctx, max_errors: nil)
allowed_values = ctx.types.enum_values(self)
matching_value = allowed_values.find { |v| v.graphql_name == value_name }
if matching_value.nil?
GraphQL::Query::InputValidationResult.from_problem("Expected #{GraphQL::Language.serialize(value_name)} to be one of: #{allowed_values.map(&:graphql_name).join(', ')}")
else
nil
end
# rescue MissingValuesError
# nil
end
# Called by the runtime when a field returns a value to give back to the client.
# This method checks that the incoming {value} matches one of the enum's defined values.
# @param value [Object] Any value matching the values for this enum.
# @param ctx [GraphQL::Query::Context]
# @raise [GraphQL::Schema::Enum::UnresolvedValueError] if {value} doesn't match a configured value or if the matching value isn't authorized.
# @return [String] The GraphQL-ready string for {value}
def coerce_result(value, ctx)
types = ctx.types
all_values = types ? types.enum_values(self) : values.each_value
enum_value = all_values.find { |val| val.value == value }
if enum_value && (was_authed = enum_value.authorized?(ctx))
enum_value.graphql_name
else
raise self::UnresolvedValueError.new(enum: self, value: value, context: ctx, authorized: was_authed)
end
end
# Called by the runtime with incoming string representations from a query.
# It will match the string to a configured by name or by Ruby value.
# @param value_name [String, Object] A string from a GraphQL query, or a Ruby value matching a `value(..., value: ...)` configuration
# @param ctx [GraphQL::Query::Context]
# @raise [GraphQL::UnauthorizedEnumValueError] if an {EnumValue} matches but returns false for `.authorized?`. Goes to {Schema.unauthorized_object}.
# @return [Object] The Ruby value for the matched {GraphQL::Schema::EnumValue}
def coerce_input(value_name, ctx)
all_values = ctx.types ? ctx.types.enum_values(self) : values.each_value
# This tries matching by incoming GraphQL string, then checks Ruby-defined values
if v = (all_values.find { |val| val.graphql_name == value_name } || all_values.find { |val| val.value == value_name })
if v.authorized?(ctx)
v.value
else
raise GraphQL::UnauthorizedEnumValueError.new(type: self, enum_value: v, context: ctx)
end
else
nil
end
end
def inherited(child_class)
if child_class.name
# Don't assign a custom error class to anonymous classes
# because they would end up with names like `#<Class0x1234>::UnresolvedValueError` which messes up bug trackers
child_class.const_set(:UnresolvedValueError, Class.new(Schema::Enum::UnresolvedValueError))
end
child_class.class_exec { @value_methods = nil }
super
end
private
def own_values
@own_values ||= {}
end
def generate_value_method(value, configured_value_method)
return if configured_value_method == false
value_method_name = configured_value_method || value.graphql_name.downcase
if respond_to?(value_method_name.to_sym)
warn "Failed to define value method for :#{value_method_name}, because " \
"#{value.owner.name || value.owner.graphql_name} already responds to that method. Use `value_method:` to override the method name " \
"or `value_method: false` to disable Enum value method generation."
return
end
define_singleton_method(value_method_name) { value.graphql_name }
end
end
enum_value_class(GraphQL::Schema::EnumValue)
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/directive.rb | lib/graphql/schema/directive.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Subclasses of this can influence how {GraphQL::Execution::Interpreter} runs queries.
#
# - {.include?}: if it returns `false`, the field or fragment will be skipped altogether, as if it were absent
# - {.resolve}: Wraps field resolution (so it should call `yield` to continue)
class Directive < GraphQL::Schema::Member
extend GraphQL::Schema::Member::HasArguments
extend GraphQL::Schema::Member::HasArguments::HasDirectiveArguments
extend GraphQL::Schema::Member::HasValidators
class << self
# Directives aren't types, they don't have kinds.
undef_method :kind
def path
"@#{super}"
end
# Return a name based on the class name,
# but downcase the first letter.
def default_graphql_name
@default_graphql_name ||= begin
camelized_name = super.dup
camelized_name[0] = camelized_name[0].downcase
-camelized_name
end
end
def locations(*new_locations)
if !new_locations.empty?
new_locations.each do |new_loc|
if !LOCATIONS.include?(new_loc.to_sym)
raise ArgumentError, "#{self} (#{self.graphql_name}) has an invalid directive location: `locations #{new_loc}` "
end
end
@locations = new_locations
else
@locations ||= (superclass.respond_to?(:locations) ? superclass.locations : [])
end
end
def default_directive(new_default_directive = nil)
if new_default_directive != nil
@default_directive = new_default_directive
elsif @default_directive.nil?
@default_directive = (superclass.respond_to?(:default_directive) ? superclass.default_directive : false)
else
!!@default_directive
end
end
def default_directive?
default_directive
end
# If false, this part of the query won't be evaluated
def include?(_object, arguments, context)
static_include?(arguments, context)
end
# Determines whether {Execution::Lookahead} considers the field to be selected
def static_include?(_arguments, _context)
true
end
# Continuing is passed as a block; `yield` to continue
def resolve(object, arguments, context)
yield
end
# Continuing is passed as a block, yield to continue.
def resolve_each(object, arguments, context)
yield
end
def validate!(arguments, context)
Schema::Validator.validate!(validators, self, context, arguments)
end
def on_field?
locations.include?(FIELD)
end
def on_fragment?
locations.include?(FRAGMENT_SPREAD) && locations.include?(INLINE_FRAGMENT)
end
def on_operation?
locations.include?(QUERY) && locations.include?(MUTATION) && locations.include?(SUBSCRIPTION)
end
def repeatable?
!!@repeatable
end
def repeatable(new_value)
@repeatable = new_value
end
private
def inherited(subclass)
super
subclass.class_exec do
@default_graphql_name ||= nil
end
end
end
# @return [GraphQL::Schema::Field, GraphQL::Schema::Argument, Class, Module]
attr_reader :owner
# @return [GraphQL::Interpreter::Arguments]
attr_reader :arguments
class InvalidArgumentError < GraphQL::Error
end
def initialize(owner, **arguments)
@owner = owner
assert_valid_owner
# It's be nice if we had the real context here, but we don't. What we _would_ get is:
# - error handling
# - lazy resolution
# Probably, those won't be needed here, since these are configuration arguments,
# not runtime arguments.
context = Query::NullContext.instance
self.class.all_argument_definitions.each do |arg_defn|
keyword = arg_defn.keyword
arg_type = arg_defn.type
if arguments.key?(keyword)
value = arguments[keyword]
# This is a Ruby-land value; convert it to graphql for validation
graphql_value = begin
coerce_value = value
if arg_type.list? && (!coerce_value.nil?) && (!coerce_value.is_a?(Array))
# When validating inputs, GraphQL accepts a single item
# and implicitly converts it to a one-item list.
# However, we're using result coercion here to go from Ruby value
# to GraphQL value, so it doesn't have that feature.
# Keep the GraphQL-type behavior but implement it manually:
wrap_type = arg_type
while wrap_type.list?
if wrap_type.non_null?
wrap_type = wrap_type.of_type
end
wrap_type = wrap_type.of_type
coerce_value = [coerce_value]
end
end
arg_type.coerce_isolated_result(coerce_value)
rescue GraphQL::Schema::Enum::UnresolvedValueError
# Let validation handle this
value
end
else
value = graphql_value = nil
end
result = arg_type.validate_input(graphql_value, context)
if !result.valid?
raise InvalidArgumentError, "@#{graphql_name}.#{arg_defn.graphql_name} on #{owner.path} is invalid (#{value.inspect}): #{result.problems.first["explanation"]}"
end
end
self.class.validate!(arguments, context)
@arguments = self.class.coerce_arguments(nil, arguments, context)
if @arguments.is_a?(GraphQL::ExecutionError)
raise @arguments
end
end
def graphql_name
self.class.graphql_name
end
LOCATIONS = [
QUERY = :QUERY,
MUTATION = :MUTATION,
SUBSCRIPTION = :SUBSCRIPTION,
FIELD = :FIELD,
FRAGMENT_DEFINITION = :FRAGMENT_DEFINITION,
FRAGMENT_SPREAD = :FRAGMENT_SPREAD,
INLINE_FRAGMENT = :INLINE_FRAGMENT,
SCHEMA = :SCHEMA,
SCALAR = :SCALAR,
OBJECT = :OBJECT,
FIELD_DEFINITION = :FIELD_DEFINITION,
ARGUMENT_DEFINITION = :ARGUMENT_DEFINITION,
INTERFACE = :INTERFACE,
UNION = :UNION,
ENUM = :ENUM,
ENUM_VALUE = :ENUM_VALUE,
INPUT_OBJECT = :INPUT_OBJECT,
INPUT_FIELD_DEFINITION = :INPUT_FIELD_DEFINITION,
VARIABLE_DEFINITION = :VARIABLE_DEFINITION,
]
DEFAULT_DEPRECATION_REASON = 'No longer supported'
LOCATION_DESCRIPTIONS = {
QUERY: 'Location adjacent to a query operation.',
MUTATION: 'Location adjacent to a mutation operation.',
SUBSCRIPTION: 'Location adjacent to a subscription operation.',
FIELD: 'Location adjacent to a field.',
FRAGMENT_DEFINITION: 'Location adjacent to a fragment definition.',
FRAGMENT_SPREAD: 'Location adjacent to a fragment spread.',
INLINE_FRAGMENT: 'Location adjacent to an inline fragment.',
SCHEMA: 'Location adjacent to a schema definition.',
SCALAR: 'Location adjacent to a scalar definition.',
OBJECT: 'Location adjacent to an object type definition.',
FIELD_DEFINITION: 'Location adjacent to a field definition.',
ARGUMENT_DEFINITION: 'Location adjacent to an argument definition.',
INTERFACE: 'Location adjacent to an interface definition.',
UNION: 'Location adjacent to a union definition.',
ENUM: 'Location adjacent to an enum definition.',
ENUM_VALUE: 'Location adjacent to an enum value definition.',
INPUT_OBJECT: 'Location adjacent to an input object type definition.',
INPUT_FIELD_DEFINITION: 'Location adjacent to an input object field definition.',
VARIABLE_DEFINITION: 'Location adjacent to a variable definition.',
}
private
def assert_valid_owner
case @owner
when Class
if @owner < GraphQL::Schema::Object
assert_has_location(OBJECT)
elsif @owner < GraphQL::Schema::Union
assert_has_location(UNION)
elsif @owner < GraphQL::Schema::Enum
assert_has_location(ENUM)
elsif @owner < GraphQL::Schema::InputObject
assert_has_location(INPUT_OBJECT)
elsif @owner < GraphQL::Schema::Scalar
assert_has_location(SCALAR)
elsif @owner < GraphQL::Schema
assert_has_location(SCHEMA)
elsif @owner < GraphQL::Schema::Resolver
assert_has_location(FIELD_DEFINITION)
else
raise "Unexpected directive owner class: #{@owner}"
end
when Module
assert_has_location(INTERFACE)
when GraphQL::Schema::Argument
if @owner.owner.is_a?(GraphQL::Schema::Field)
assert_has_location(ARGUMENT_DEFINITION)
else
assert_has_location(INPUT_FIELD_DEFINITION)
end
when GraphQL::Schema::Field
assert_has_location(FIELD_DEFINITION)
when GraphQL::Schema::EnumValue
assert_has_location(ENUM_VALUE)
else
raise "Unexpected directive owner: #{@owner.inspect}"
end
end
def assert_has_location(location)
if !self.class.locations.include?(location)
raise ArgumentError, <<-MD
Directive `@#{self.class.graphql_name}` can't be attached to #{@owner.graphql_name} because #{location} isn't included in its locations (#{self.class.locations.join(", ")}).
Use `locations(#{location})` to update this directive's definition, or remove it from #{@owner.graphql_name}.
MD
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/list.rb | lib/graphql/schema/list.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Represents a list type in the schema.
# Wraps a {Schema::Member} as a list type.
# @see Schema::Member::TypeSystemHelpers#to_list_type Create a list type from another GraphQL type
class List < GraphQL::Schema::Wrapper
include Schema::Member::ValidatesInput
# @return [GraphQL::TypeKinds::LIST]
def kind
GraphQL::TypeKinds::LIST
end
# @return [true]
def list?
true
end
def to_type_signature
"[#{@of_type.to_type_signature}]"
end
# This is for introspection, where it's expected the name will be `null`
def graphql_name
nil
end
# Also for implementing introspection
def description
nil
end
def coerce_result(value, ctx)
value.map { |i| i.nil? ? nil : of_type.coerce_result(i, ctx) }
end
def coerce_input(value, ctx)
if value.nil?
nil
else
coerced = ensure_array(value).map { |item| item.nil? ? item : of_type.coerce_input(item, ctx) }
ctx.schema.after_any_lazies(coerced, &:itself)
end
end
def validate_non_null_input(value, ctx, max_errors: nil)
result = GraphQL::Query::InputValidationResult.new
ensure_array(value).each_with_index do |item, index|
item_result = of_type.validate_input(item, ctx)
unless item_result.valid?
if max_errors
if max_errors == 0
add_max_errors_reached_message(result)
break
end
max_errors -= 1
end
result.merge_result!(index, item_result)
end
end
result.valid? ? nil : result
end
private
def ensure_array(value)
# `Array({ a: 1 })` makes `[[:a, 1]]`, so do it manually
if value.is_a?(Array)
value
else
[value]
end
end
def add_max_errors_reached_message(result)
message = "Too many errors processing list variable, max validation error limit reached. Execution aborted"
item_result = GraphQL::Query::InputValidationResult.from_problem(message)
result.merge_result!(nil, item_result)
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/field_extension.rb | lib/graphql/schema/field_extension.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Extend this class to make field-level customizations to resolve behavior.
#
# When a extension is added to a field with `extension(MyExtension)`, a `MyExtension` instance
# is created, and its hooks are applied whenever that field is called.
#
# The instance is frozen so that instance variables aren't modified during query execution,
# which could cause all kinds of issues due to race conditions.
class FieldExtension
# @return [GraphQL::Schema::Field]
attr_reader :field
# @return [Object]
attr_reader :options
# @return [Array<Symbol>, nil] `default_argument`s added, if any were added (otherwise, `nil`)
attr_reader :added_default_arguments
# Called when the extension is mounted with `extension(name, options)`.
# The instance will be frozen to avoid improper use of state during execution.
# @param field [GraphQL::Schema::Field] The field where this extension was mounted
# @param options [Object] The second argument to `extension`, or `{}` if nothing was passed.
def initialize(field:, options:)
@field = field
@options = options || {}
@added_default_arguments = nil
apply
end
class << self
# @return [Array(Array, Hash), nil] A list of default argument configs, or `nil` if there aren't any
def default_argument_configurations
args = superclass.respond_to?(:default_argument_configurations) ? superclass.default_argument_configurations : nil
if @own_default_argument_configurations
if args
args.concat(@own_default_argument_configurations)
else
args = @own_default_argument_configurations.dup
end
end
args
end
# @see Argument#initialize
# @see HasArguments#argument
def default_argument(*argument_args, **argument_kwargs)
configs = @own_default_argument_configurations ||= []
configs << [argument_args, argument_kwargs]
end
# If configured, these `extras` will be added to the field if they aren't already present,
# but removed by from `arguments` before the field's `resolve` is called.
# (The extras _will_ be present for other extensions, though.)
#
# @param new_extras [Array<Symbol>] If provided, assign extras used by this extension
# @return [Array<Symbol>] any extras assigned to this extension
def extras(new_extras = nil)
if new_extras
@own_extras = new_extras
end
inherited_extras = self.superclass.respond_to?(:extras) ? superclass.extras : nil
if @own_extras
if inherited_extras
inherited_extras + @own_extras
else
@own_extras
end
elsif inherited_extras
inherited_extras
else
GraphQL::EmptyObjects::EMPTY_ARRAY
end
end
end
# Called when this extension is attached to a field.
# The field definition may be extended during this method.
# @return [void]
def apply
end
# Called after the field's definition block has been executed.
# (Any arguments from the block are present on `field`)
# @return [void]
def after_define
end
# @api private
def after_define_apply
after_define
if (configs = self.class.default_argument_configurations)
existing_keywords = field.all_argument_definitions.map(&:keyword)
existing_keywords.uniq!
@added_default_arguments = []
configs.each do |config|
argument_args, argument_kwargs = config
arg_name = argument_args[0]
if !existing_keywords.include?(arg_name)
@added_default_arguments << arg_name
field.argument(*argument_args, **argument_kwargs)
end
end
end
if !(extras = self.class.extras).empty?
@added_extras = extras - field.extras
field.extras(@added_extras)
else
@added_extras = nil
end
freeze
end
# @api private
attr_reader :added_extras
# Called before resolving {#field}. It should either:
#
# - `yield` values to continue execution; OR
# - return something else to shortcut field execution.
#
# Whatever this method returns will be used for execution.
#
# @param object [Object] The object the field is being resolved on
# @param arguments [Hash] Ruby keyword arguments for resolving this field
# @param context [Query::Context] the context for this query
# @yieldparam object [Object] The object to continue resolving the field on
# @yieldparam arguments [Hash] The keyword arguments to continue resolving with
# @yieldparam memo [Object] Any extension-specific value which will be passed to {#after_resolve} later
# @return [Object] The return value for this field.
def resolve(object:, arguments:, context:)
yield(object, arguments, nil)
end
# Called after {#field} was resolved, and after any lazy values (like `Promise`s) were synced,
# but before the value was added to the GraphQL response.
#
# Whatever this hook returns will be used as the return value.
#
# @param object [Object] The object the field is being resolved on
# @param arguments [Hash] Ruby keyword arguments for resolving this field
# @param context [Query::Context] the context for this query
# @param value [Object] Whatever the field previously returned
# @param memo [Object] The third value yielded by {#resolve}, or `nil` if there wasn't one
# @return [Object] The return value for this field.
def after_resolve(object:, arguments:, context:, value:, memo:)
value
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/printer.rb | lib/graphql/schema/printer.rb | # frozen_string_literal: true
module GraphQL
class Schema
# Used to convert your {GraphQL::Schema} to a GraphQL schema string
#
# @example print your schema to standard output (via helper)
# puts GraphQL::Schema::Printer.print_schema(MySchema)
#
# @example print your schema to standard output
# puts GraphQL::Schema::Printer.new(MySchema).print_schema
#
# @example print a single type to standard output
# class Types::Query < GraphQL::Schema::Object
# description "The query root of this schema"
#
# field :post, Types::Post, null: true
# end
#
# class Types::Post < GraphQL::Schema::Object
# description "A blog post"
#
# field :id, ID, null: false
# field :title, String, null: false
# field :body, String, null: false
# end
#
# class MySchema < GraphQL::Schema
# query(Types::Query)
# end
#
# printer = GraphQL::Schema::Printer.new(MySchema)
# puts printer.print_type(Types::Post)
#
class Printer < GraphQL::Language::Printer
attr_reader :schema, :warden
# @param schema [GraphQL::Schema]
# @param context [Hash]
# @param introspection [Boolean] Should include the introspection types in the string?
def initialize(schema, context: nil, introspection: false)
@document_from_schema = GraphQL::Language::DocumentFromSchemaDefinition.new(
schema,
context: context,
include_introspection_types: introspection,
)
@document = @document_from_schema.document
@schema = schema
end
# Return the GraphQL schema string for the introspection type system
def self.print_introspection_schema
query_root = Class.new(GraphQL::Schema::Object) do
graphql_name "Root"
field :throwaway_field, String
def self.visible?(ctx)
false
end
end
schema = Class.new(GraphQL::Schema) {
use GraphQL::Schema::Visibility
query(query_root)
def self.visible?(member, _ctx)
member.graphql_name != "Root"
end
}
introspection_schema_ast = GraphQL::Language::DocumentFromSchemaDefinition.new(
schema,
include_introspection_types: true,
include_built_in_directives: true,
).document
introspection_schema_ast.to_query_string(printer: IntrospectionPrinter.new)
end
# Return a GraphQL schema string for the defined types in the schema
# @param schema [GraphQL::Schema]
# @param context [Hash]
# @param only [<#call(member, ctx)>]
# @param except [<#call(member, ctx)>]
def self.print_schema(schema, **args)
printer = new(schema, **args)
printer.print_schema
end
# Return a GraphQL schema string for the defined types in the schema
def print_schema
print(@document) + "\n"
end
def print_type(type)
node = @document_from_schema.build_type_definition_node(type)
print(node)
end
class IntrospectionPrinter < GraphQL::Language::Printer
def print_schema_definition(schema)
print_string("schema {\n query: Root\n}")
end
end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
rmosolgo/graphql-ruby | https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema/enum_value.rb | lib/graphql/schema/enum_value.rb | # frozen_string_literal: true
module GraphQL
class Schema
# A possible value for an {Enum}.
#
# You can extend this class to customize enum values in your schema.
#
# @example custom enum value class
# # define a custom class:
# class CustomEnumValue < GraphQL::Schema::EnumValue
# def initialize(*args)
# # arguments to `value(...)` in Enum classes are passed here
# super
# end
# end
#
# class BaseEnum < GraphQL::Schema::Enum
# # use it for these enums:
# enum_value_class CustomEnumValue
# end
class EnumValue < GraphQL::Schema::Member
include GraphQL::Schema::Member::HasPath
include GraphQL::Schema::Member::HasAstNode
include GraphQL::Schema::Member::HasDirectives
include GraphQL::Schema::Member::HasDeprecationReason
attr_reader :graphql_name
# @return [Class] The enum type that owns this value
attr_reader :owner
def initialize(graphql_name, desc = nil, owner:, ast_node: nil, directives: nil, description: nil, comment: nil, value: NOT_CONFIGURED, deprecation_reason: nil, &block)
@graphql_name = graphql_name.to_s
GraphQL::NameValidator.validate!(@graphql_name)
@description = desc || description
@comment = comment
@value = value == NOT_CONFIGURED ? @graphql_name : value
if deprecation_reason
self.deprecation_reason = deprecation_reason
end
@owner = owner
@ast_node = ast_node
if directives
directives.each do |dir_class, dir_options|
directive(dir_class, **dir_options)
end
end
if block_given?
instance_exec(self, &block)
end
end
def description(new_desc = nil)
if new_desc
@description = new_desc
end
@description
end
def comment(new_comment = nil)
if new_comment
@comment = new_comment
end
@comment
end
def value(new_val = nil)
unless new_val.nil?
@value = new_val
end
@value
end
def inspect
"#<#{self.class} #{path} @value=#{@value.inspect}#{description ? " @description=#{description.inspect}" : ""}#{deprecation_reason ? " @deprecation_reason=#{deprecation_reason.inspect}" : ""}>"
end
def visible?(_ctx); true; end
def authorized?(_ctx); true; end
end
end
end
| ruby | MIT | fa2ba4e489f8475b194f7c6985e0b25681a442c2 | 2026-01-04T15:43:02.089024Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.