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/tracing/prometheus_trace.rb | lib/graphql/tracing/prometheus_trace.rb | # frozen_string_literal: true
require "graphql/tracing/monitor_trace"
module GraphQL
module Tracing
# A tracer for reporting GraphQL-Ruby times to Prometheus.
#
# The PrometheusExporter server must be run with a custom type collector that extends `GraphQL::Tracing::PrometheusTracing::GraphQLCollector`.
#
# @example Adding this trace to your schema
# require 'prometheus_exporter/client'
#
# class MySchema < GraphQL::Schema
# trace_with GraphQL::Tracing::PrometheusTrace
# end
#
# @example Running a custom type collector
# # lib/graphql_collector.rb
# if defined?(PrometheusExporter::Server)
# require 'graphql/tracing'
#
# class GraphQLCollector < GraphQL::Tracing::PrometheusTrace::GraphQLCollector
# end
# end
#
# # Then run:
# # bundle exec prometheus_exporter -a lib/graphql_collector.rb
PrometheusTrace = MonitorTrace.create_module("prometheus")
module PrometheusTrace
if defined?(PrometheusExporter::Server)
autoload :GraphQLCollector, "graphql/tracing/prometheus_trace/graphql_collector"
end
def initialize(client: PrometheusExporter::Client.default, keys_whitelist: [:execute_field], collector_type: "graphql", **rest)
@prometheus_client = client
@prometheus_keys_whitelist = keys_whitelist.map(&:to_sym) # handle previous string keys
@prometheus_collector_type = collector_type
setup_prometheus_monitor(**rest)
super
end
attr_reader :prometheus_collector_type, :prometheus_client, :prometheus_keys_whitelist
class PrometheusMonitor < MonitorTrace::Monitor
def instrument(keyword, object)
if active?(keyword)
start = gettime
result = yield
duration = gettime - start
send_json(duration, keyword, object)
result
else
yield
end
end
def active?(keyword)
@trace.prometheus_keys_whitelist.include?(keyword)
end
def gettime
::Process.clock_gettime(::Process::CLOCK_MONOTONIC)
end
def send_json(duration, keyword, object)
event_name = name_for(keyword, object)
@trace.prometheus_client.send_json(
type: @trace.prometheus_collector_type,
duration: duration,
platform_key: event_name,
key: keyword
)
end
include MonitorTrace::Monitor::GraphQLPrefixNames
class Event < MonitorTrace::Monitor::Event
def start
@start_time = @monitor.gettime
end
def finish
if @monitor.active?(keyword)
duration = @monitor.gettime - @start_time
@monitor.send_json(duration, keyword, object)
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/tracing/statsd_tracing.rb | lib/graphql/tracing/statsd_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
class StatsdTracing < PlatformTracing
self.platform_keys = {
'lex' => "graphql.lex",
'parse' => "graphql.parse",
'validate' => "graphql.validate",
'analyze_query' => "graphql.analyze_query",
'analyze_multiplex' => "graphql.analyze_multiplex",
'execute_multiplex' => "graphql.execute_multiplex",
'execute_query' => "graphql.execute_query",
'execute_query_lazy' => "graphql.execute_query_lazy",
}
# @param statsd [Object] A statsd client
def initialize(statsd:, **rest)
@statsd = statsd
super(**rest)
end
def platform_trace(platform_key, key, data)
@statsd.time(platform_key) do
yield
end
end
def platform_field_key(type, field)
"graphql.#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"graphql.authorized.#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"graphql.resolve_type.#{type.graphql_name}"
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/tracing/statsd_trace.rb | lib/graphql/tracing/statsd_trace.rb | # frozen_string_literal: true
require "graphql/tracing/monitor_trace"
module GraphQL
module Tracing
# A tracer for reporting GraphQL-Ruby times to Statsd.
# Passing any Statsd client that implements `.time(name) { ... }`
# and `.timing(name, ms)` will work.
#
# @example Installing this tracer
# # eg:
# # $statsd = Statsd.new 'localhost', 9125
# class MySchema < GraphQL::Schema
# use GraphQL::Tracing::StatsdTrace, statsd: $statsd
# end
StatsdTrace = MonitorTrace.create_module("statsd")
module StatsdTrace
class StatsdMonitor < MonitorTrace::Monitor
def initialize(statsd:, **_rest)
@statsd = statsd
super
end
attr_reader :statsd
def instrument(keyword, object)
@statsd.time(name_for(keyword, object)) do
yield
end
end
include MonitorTrace::Monitor::GraphQLPrefixNames
class Event < MonitorTrace::Monitor::Event
def start
@start_time = Process.clock_gettime(Process::CLOCK_MONOTONIC)
end
def finish
elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - @start_time
@monitor.statsd.timing(@monitor.name_for(keyword, object), elapsed)
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/tracing/monitor_trace.rb | lib/graphql/tracing/monitor_trace.rb | # frozen_string_literal: true
module GraphQL
module Tracing
# This module is the basis for Ruby-level integration with third-party monitoring platforms.
# Platform-specific traces include this module and implement an adapter.
#
# @see ActiveSupportNotificationsTrace Integration via ActiveSupport::Notifications, an alternative approach.
module MonitorTrace
class Monitor
def initialize(trace:, set_transaction_name:, **_rest)
@trace = trace
@set_transaction_name = set_transaction_name
@platform_field_key_cache = Hash.new { |h, k| h[k] = platform_field_key(k) }.compare_by_identity
@platform_authorized_key_cache = Hash.new { |h, k| h[k] = platform_authorized_key(k) }.compare_by_identity
@platform_resolve_type_key_cache = Hash.new { |h, k| h[k] = platform_resolve_type_key(k) }.compare_by_identity
@platform_source_class_key_cache = Hash.new { |h, source_cls| h[source_cls] = platform_source_class_key(source_cls) }.compare_by_identity
end
def instrument(keyword, object, &block)
raise "Implement #{self.class}#instrument to measure the block"
end
def start_event(keyword, object)
ev = self.class::Event.new(self, keyword, object)
ev.start
ev
end
# Get the transaction name based on the operation type and name if possible, or fall back to a user provided
# one. Useful for anonymous queries.
def transaction_name(query)
selected_op = query.selected_operation
txn_name = if selected_op
op_type = selected_op.operation_type
op_name = selected_op.name || fallback_transaction_name(query.context) || "anonymous"
"#{op_type}.#{op_name}"
else
"query.anonymous"
end
"GraphQL/#{txn_name}"
end
def fallback_transaction_name(context)
context[:tracing_fallback_transaction_name]
end
def name_for(keyword, object)
case keyword
when :execute_field
@platform_field_key_cache[object]
when :authorized
@platform_authorized_key_cache[object]
when :resolve_type
@platform_resolve_type_key_cache[object]
when :dataloader_source
@platform_source_class_key_cache[object.class]
when :parse then self.class::PARSE_NAME
when :lex then self.class::LEX_NAME
when :execute then self.class::EXECUTE_NAME
when :analyze then self.class::ANALYZE_NAME
when :validate then self.class::VALIDATE_NAME
else
raise "No name for #{keyword.inspect}"
end
end
class Event
def initialize(monitor, keyword, object)
@monitor = monitor
@keyword = keyword
@object = object
end
attr_reader :keyword, :object
def start
raise "Implement #{self.class}#start to begin a new event (#{inspect})"
end
def finish
raise "Implement #{self.class}#finish to end this event (#{inspect})"
end
end
module GraphQLSuffixNames
PARSE_NAME = "parse.graphql"
LEX_NAME = "lex.graphql"
VALIDATE_NAME = "validate.graphql"
EXECUTE_NAME = "execute.graphql"
ANALYZE_NAME = "analyze.graphql"
def platform_field_key(field)
"#{field.path}.graphql"
end
def platform_authorized_key(type)
"#{type.graphql_name}.authorized.graphql"
end
def platform_resolve_type_key(type)
"#{type.graphql_name}.resolve_type.graphql"
end
def platform_source_class_key(source_class)
"#{source_class.name.gsub("::", "_")}.fetch.graphql"
end
end
module GraphQLPrefixNames
PARSE_NAME = "graphql.parse"
LEX_NAME = "graphql.lex"
VALIDATE_NAME = "graphql.validate"
EXECUTE_NAME = "graphql.execute"
ANALYZE_NAME = "graphql.analyze"
def platform_field_key(field)
"graphql.#{field.path}"
end
def platform_authorized_key(type)
"graphql.authorized.#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"graphql.resolve_type.#{type.graphql_name}"
end
def platform_source_class_key(source_class)
"graphql.fetch.#{source_class.name.gsub("::", "_")}"
end
end
end
def self.create_module(monitor_name)
if !monitor_name.match?(/[a-z]+/)
raise ArgumentError, "monitor name must be [a-z]+, not: #{monitor_name.inspect}"
end
trace_module = Module.new
code = MODULE_TEMPLATE % {
monitor: monitor_name,
monitor_class: monitor_name.capitalize + "Monitor",
}
trace_module.module_eval(code, __FILE__, __LINE__ + 5) # rubocop:disable Development/NoEvalCop This is build-time with a validated string
trace_module
end
MODULE_TEMPLATE = <<~RUBY
# @param set_transaction_name [Boolean] If `true`, use the GraphQL operation name as the request name on the monitoring platform
# @param trace_scalars [Boolean] If `true`, leaf fields will be traced too (Scalars _and_ Enums)
# @param trace_authorized [Boolean] If `false`, skip tracing `authorized?` calls
# @param trace_resolve_type [Boolean] If `false`, skip tracing `resolve_type?` calls
def initialize(...)
setup_%{monitor}_monitor(...)
super
end
def setup_%{monitor}_monitor(trace_scalars: false, trace_authorized: true, trace_resolve_type: true, set_transaction_name: false, **kwargs)
@trace_scalars = trace_scalars
@trace_authorized = trace_authorized
@trace_resolve_type = trace_resolve_type
@set_transaction_name = set_transaction_name
@%{monitor} = %{monitor_class}.new(trace: self, set_transaction_name: @set_transaction_name, **kwargs)
end
def parse(query_string:)
@%{monitor}.instrument(:parse, query_string) do
super
end
end
def lex(query_string:)
@%{monitor}.instrument(:lex, query_string) do
super
end
end
def validate(query:, validate:)
@%{monitor}.instrument(:validate, query) do
super
end
end
def begin_analyze_multiplex(multiplex, analyzers)
begin_%{monitor}_event(:analyze, nil)
super
end
def end_analyze_multiplex(multiplex, analyzers)
finish_%{monitor}_event
super
end
def execute_multiplex(multiplex:)
@%{monitor}.instrument(:execute, multiplex) do
super
end
end
def begin_execute_field(field, object, arguments, query)
return_type = field.type.unwrap
trace_field = if return_type.kind.scalar? || return_type.kind.enum?
(field.trace.nil? && @trace_scalars) || field.trace
else
true
end
if trace_field
begin_%{monitor}_event(:execute_field, field)
end
super
end
def end_execute_field(field, object, arguments, query, result)
finish_%{monitor}_event
super
end
def dataloader_fiber_yield(source)
Fiber[PREVIOUS_EV_KEY] = finish_%{monitor}_event
super
end
def dataloader_fiber_resume(source)
prev_ev = Fiber[PREVIOUS_EV_KEY]
if prev_ev
begin_%{monitor}_event(prev_ev.keyword, prev_ev.object)
end
super
end
def begin_authorized(type, object, context)
@trace_authorized && begin_%{monitor}_event(:authorized, type)
super
end
def end_authorized(type, object, context, result)
finish_%{monitor}_event
super
end
def begin_resolve_type(type, value, context)
@trace_resolve_type && begin_%{monitor}_event(:resolve_type, type)
super
end
def end_resolve_type(type, value, context, resolved_type)
finish_%{monitor}_event
super
end
def begin_dataloader_source(source)
begin_%{monitor}_event(:dataloader_source, source)
super
end
def end_dataloader_source(source)
finish_%{monitor}_event
super
end
CURRENT_EV_KEY = :__graphql_%{monitor}_trace_event
PREVIOUS_EV_KEY = :__graphql_%{monitor}_trace_previous_event
private
def begin_%{monitor}_event(keyword, object)
Fiber[CURRENT_EV_KEY] = @%{monitor}.start_event(keyword, object)
end
def finish_%{monitor}_event
if ev = Fiber[CURRENT_EV_KEY]
ev.finish
# Use `false` to prevent grabbing an event from a parent fiber
Fiber[CURRENT_EV_KEY] = false
ev
end
end
RUBY
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/tracing/scout_tracing.rb | lib/graphql/tracing/scout_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
class ScoutTracing < PlatformTracing
INSTRUMENT_OPTS = { scope: true }
self.platform_keys = {
"lex" => "lex.graphql",
"parse" => "parse.graphql",
"validate" => "validate.graphql",
"analyze_query" => "analyze.graphql",
"analyze_multiplex" => "analyze.graphql",
"execute_multiplex" => "execute.graphql",
"execute_query" => "execute.graphql",
"execute_query_lazy" => "execute.graphql",
}
# @param set_transaction_name [Boolean] If true, the GraphQL operation name will be used as the transaction name.
# This is not advised if you run more than one query per HTTP request, for example, with `graphql-client` or multiplexing.
# It can also be specified per-query with `context[:set_scout_transaction_name]`.
def initialize(options = {})
self.class.include ScoutApm::Tracer
@set_transaction_name = options.fetch(:set_transaction_name, false)
super(options)
end
def platform_trace(platform_key, key, data)
if key == "execute_query"
set_this_txn_name = data[:query].context[:set_scout_transaction_name]
if set_this_txn_name == true || (set_this_txn_name.nil? && @set_transaction_name)
ScoutApm::Transaction.rename(transaction_name(data[:query]))
end
end
self.class.instrument("GraphQL", platform_key, INSTRUMENT_OPTS) do
yield
end
end
def platform_field_key(type, field)
"#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"#{type.graphql_name}.authorized"
end
def platform_resolve_type_key(type)
"#{type.graphql_name}.resolve_type"
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/tracing/appsignal_tracing.rb | lib/graphql/tracing/appsignal_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
class AppsignalTracing < PlatformTracing
self.platform_keys = {
"lex" => "lex.graphql",
"parse" => "parse.graphql",
"validate" => "validate.graphql",
"analyze_query" => "analyze.graphql",
"analyze_multiplex" => "analyze.graphql",
"execute_multiplex" => "execute.graphql",
"execute_query" => "execute.graphql",
"execute_query_lazy" => "execute.graphql",
}
# @param set_action_name [Boolean] If true, the GraphQL operation name will be used as the transaction name.
# This is not advised if you run more than one query per HTTP request, for example, with `graphql-client` or multiplexing.
# It can also be specified per-query with `context[:set_appsignal_action_name]`.
def initialize(options = {})
@set_action_name = options.fetch(:set_action_name, false)
super
end
def platform_trace(platform_key, key, data)
if key == "execute_query"
set_this_txn_name = data[:query].context[:set_appsignal_action_name]
if set_this_txn_name == true || (set_this_txn_name.nil? && @set_action_name)
Appsignal::Transaction.current.set_action(transaction_name(data[:query]))
end
end
Appsignal.instrument(platform_key) do
yield
end
end
def platform_field_key(type, field)
"#{type.graphql_name}.#{field.graphql_name}.graphql"
end
def platform_authorized_key(type)
"#{type.graphql_name}.authorized.graphql"
end
def platform_resolve_type_key(type)
"#{type.graphql_name}.resolve_type.graphql"
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/tracing/data_dog_tracing.rb | lib/graphql/tracing/data_dog_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
class DataDogTracing < PlatformTracing
self.platform_keys = {
'lex' => 'lex.graphql',
'parse' => 'parse.graphql',
'validate' => 'validate.graphql',
'analyze_query' => 'analyze.graphql',
'analyze_multiplex' => 'analyze.graphql',
'execute_multiplex' => 'execute.graphql',
'execute_query' => 'execute.graphql',
'execute_query_lazy' => 'execute.graphql',
}
def platform_trace(platform_key, key, data)
tracer.trace(platform_key, service: options[:service], type: 'custom') do |span|
span.set_tag('component', 'graphql')
span.set_tag('operation', key)
if key == 'execute_multiplex'
operations = data[:multiplex].queries.map(&:selected_operation_name).join(', ')
resource = if operations.empty?
first_query = data[:multiplex].queries.first
fallback_transaction_name(first_query && first_query.context)
else
operations
end
span.resource = resource if resource
# [Deprecated] will be removed in the future
span.set_metric('_dd1.sr.eausr', analytics_sample_rate) if analytics_enabled?
end
if key == 'execute_query'
span.set_tag(:selected_operation_name, data[:query].selected_operation_name)
span.set_tag(:selected_operation_type, data[:query].selected_operation.operation_type)
span.set_tag(:query_string, data[:query].query_string)
end
prepare_span(key, data, span)
yield
end
end
# Implement this method in a subclass to apply custom tags to datadog spans
# @param key [String] The event being traced
# @param data [Hash] The runtime data for this event (@see GraphQL::Tracing for keys for each event)
# @param span [Datadog::Tracing::SpanOperation] The datadog span for this event
def prepare_span(key, data, span)
end
def tracer
default_tracer = defined?(Datadog::Tracing) ? Datadog::Tracing : Datadog.tracer
# [Deprecated] options[:tracer] will be removed in the future
options.fetch(:tracer, default_tracer)
end
def analytics_enabled?
# [Deprecated] options[:analytics_enabled] will be removed in the future
options.fetch(:analytics_enabled, false)
end
def analytics_sample_rate
# [Deprecated] options[:analytics_sample_rate] will be removed in the future
options.fetch(:analytics_sample_rate, 1.0)
end
def platform_field_key(type, field)
"#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"#{type.graphql_name}.authorized"
end
def platform_resolve_type_key(type)
"#{type.graphql_name}.resolve_type"
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/tracing/new_relic_trace.rb | lib/graphql/tracing/new_relic_trace.rb | # frozen_string_literal: true
require "graphql/tracing/monitor_trace"
module GraphQL
module Tracing
# A tracer for reporting GraphQL-Ruby time to New Relic
#
# @example Installing the tracer
# class MySchema < GraphQL::Schema
# trace_with GraphQL::Tracing::NewRelicTrace
#
# # Optional, use the operation name to set the new relic transaction name:
# # trace_with GraphQL::Tracing::NewRelicTrace, set_transaction_name: true
# end
#
# @example Installing without trace events for `authorized?` or `resolve_type` calls
# trace_with GraphQL::Tracing::NewRelicTrace, trace_authorized: false, trace_resolve_type: false
NewRelicTrace = MonitorTrace.create_module("newrelic")
module NewRelicTrace
class NewrelicMonitor < MonitorTrace::Monitor
PARSE_NAME = "GraphQL/parse"
LEX_NAME = "GraphQL/lex"
VALIDATE_NAME = "GraphQL/validate"
EXECUTE_NAME = "GraphQL/execute"
ANALYZE_NAME = "GraphQL/analyze"
def instrument(keyword, payload, &block)
if keyword == :execute
query = payload.queries.first
set_this_txn_name = query.context[:set_new_relic_transaction_name]
if set_this_txn_name || (set_this_txn_name.nil? && @set_transaction_name)
NewRelic::Agent.set_transaction_name(transaction_name(query))
end
end
::NewRelic::Agent::MethodTracerHelpers.trace_execution_scoped(name_for(keyword, payload), &block)
end
def platform_source_class_key(source_class)
"GraphQL/Source/#{source_class.name}"
end
def platform_field_key(field)
"GraphQL/#{field.owner.graphql_name}/#{field.graphql_name}"
end
def platform_authorized_key(type)
"GraphQL/Authorized/#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"GraphQL/ResolveType/#{type.graphql_name}"
end
class Event < MonitorTrace::Monitor::Event
def start
name = @monitor.name_for(keyword, object)
@nr_ev = NewRelic::Agent::Tracer.start_transaction_or_segment(partial_name: name, category: :web)
end
def finish
@nr_ev.finish
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/tracing/detailed_trace.rb | lib/graphql/tracing/detailed_trace.rb | # frozen_string_literal: true
require "graphql/tracing/detailed_trace/memory_backend"
require "graphql/tracing/detailed_trace/redis_backend"
module GraphQL
module Tracing
# `DetailedTrace` can make detailed profiles for a subset of production traffic.
#
# When `MySchema.detailed_trace?(query)` returns `true`, a profiler-specific `trace_mode: ...` will be used for the query,
# overriding the one in `context[:trace_mode]`.
#
# By default, the detailed tracer calls `.inspect` on application objects returned from fields. You can customize
# this behavior by extending {DetailedTrace} and overriding {#inspect_object}. You can opt out of debug annotations
# entirely with `use ..., debug: false` or for a single query with `context: { detailed_trace_debug: false }`.
#
# __Redis__: The sampler stores its results in a provided Redis database. Depending on your needs,
# You can configure this database to retain all data (persistent) or to expire data according to your rules.
# If you need to save traces indefinitely, you can download them from Perfetto after opening them there.
#
# @example Adding the sampler to your schema
# class MySchema < GraphQL::Schema
# # Add the sampler:
# use GraphQL::Tracing::DetailedTrace, redis: Redis.new(...), limit: 100
#
# # And implement this hook to tell it when to take a sample:
# def self.detailed_trace?(query)
# # Could use `query.context`, `query.selected_operation_name`, `query.query_string` here
# # Could call out to Flipper, etc
# rand <= 0.000_1 # one in ten thousand
# end
# end
#
# @see Graphql::Dashboard GraphQL::Dashboard for viewing stored results
#
# @example Customizing debug output in traces
# class CustomDetailedTrace < GraphQL::Tracing::DetailedTrace
# def inspect_object(object)
# if object.is_a?(SomeThing)
# # handle it specially ...
# else
# super
# end
# end
# end
#
# @example disabling debug annotations completely
# use DetailedTrace, debug: false, ...
#
# @example disabling debug annotations for one query
# MySchema.execute(query_str, context: { detailed_trace_debug: false })
#
class DetailedTrace
# @param redis [Redis] If provided, profiles will be stored in Redis for later review
# @param limit [Integer] A maximum number of profiles to store
# @param debug [Boolean] if `false`, it won't create `debug` annotations in Perfetto traces (reduces overhead)
def self.use(schema, trace_mode: :profile_sample, memory: false, debug: debug?, redis: nil, limit: nil)
storage = if redis
RedisBackend.new(redis: redis, limit: limit)
elsif memory
MemoryBackend.new(limit: limit)
else
raise ArgumentError, "Pass `redis: ...` to store traces in Redis for later review"
end
detailed_trace = self.new(storage: storage, trace_mode: trace_mode, debug: debug)
schema.detailed_trace = detailed_trace
schema.trace_with(PerfettoTrace, mode: trace_mode, save_profile: true)
end
def initialize(storage:, trace_mode:, debug:)
@storage = storage
@trace_mode = trace_mode
@debug = debug
end
# @return [Symbol] The trace mode to use when {Schema.detailed_trace?} returns `true`
attr_reader :trace_mode
# @return [String] ID of saved trace
def save_trace(operation_name, duration_ms, begin_ms, trace_data)
@storage.save_trace(operation_name, duration_ms, begin_ms, trace_data)
end
# @return [Boolean]
def debug?
@debug
end
# @param last [Integer]
# @param before [Integer] Timestamp in milliseconds since epoch
# @return [Enumerable<StoredTrace>]
def traces(last: nil, before: nil)
@storage.traces(last: last, before: before)
end
# @return [StoredTrace, nil]
def find_trace(id)
@storage.find_trace(id)
end
# @return [void]
def delete_trace(id)
@storage.delete_trace(id)
end
# @return [void]
def delete_all_traces
@storage.delete_all_traces
end
def inspect_object(object)
self.class.inspect_object(object)
end
def self.inspect_object(object)
if defined?(ActiveRecord::Relation) && object.is_a?(ActiveRecord::Relation)
"#{object.class}, .to_sql=#{object.to_sql.inspect}"
else
object.inspect
end
end
# Default debug setting
# @return [true]
def self.debug?
true
end
class StoredTrace
def initialize(id:, operation_name:, duration_ms:, begin_ms:, trace_data:)
@id = id
@operation_name = operation_name
@duration_ms = duration_ms
@begin_ms = begin_ms
@trace_data = trace_data
end
attr_reader :id, :operation_name, :duration_ms, :begin_ms, :trace_data
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/tracing/call_legacy_tracers.rb | lib/graphql/tracing/call_legacy_tracers.rb | # frozen_string_literal: true
module GraphQL
module Tracing
# This trace class calls legacy-style tracer with payload hashes.
# New-style `trace_with` modules significantly reduce the overhead of tracing,
# but that advantage is lost when legacy-style tracers are also used (since the payload hashes are still constructed).
module CallLegacyTracers
def lex(query_string:)
(@multiplex || @query).trace("lex", { query_string: query_string }) { super }
end
def parse(query_string:)
(@multiplex || @query).trace("parse", { query_string: query_string }) { super }
end
def validate(query:, validate:)
query.trace("validate", { validate: validate, query: query }) { super }
end
def analyze_multiplex(multiplex:)
multiplex.trace("analyze_multiplex", { multiplex: multiplex }) { super }
end
def analyze_query(query:)
query.trace("analyze_query", { query: query }) { super }
end
def execute_multiplex(multiplex:)
multiplex.trace("execute_multiplex", { multiplex: multiplex }) { super }
end
def execute_query(query:)
query.trace("execute_query", { query: query }) { super }
end
def execute_query_lazy(query:, multiplex:)
multiplex.trace("execute_query_lazy", { multiplex: multiplex, query: query }) { super }
end
def execute_field(field:, query:, ast_node:, arguments:, object:)
query.trace("execute_field", { field: field, query: query, ast_node: ast_node, arguments: arguments, object: object, owner: field.owner, path: query.context[:current_path] }) { super }
end
def execute_field_lazy(field:, query:, ast_node:, arguments:, object:)
query.trace("execute_field_lazy", { field: field, query: query, ast_node: ast_node, arguments: arguments, object: object, owner: field.owner, path: query.context[:current_path] }) { super }
end
def authorized(query:, type:, object:)
query.trace("authorized", { context: query.context, type: type, object: object, path: query.context[:current_path] }) { super }
end
def authorized_lazy(query:, type:, object:)
query.trace("authorized_lazy", { context: query.context, type: type, object: object, path: query.context[:current_path] }) { super }
end
def resolve_type(query:, type:, object:)
query.trace("resolve_type", { context: query.context, type: type, object: object, path: query.context[:current_path] }) { super }
end
def resolve_type_lazy(query:, type:, object:)
query.trace("resolve_type_lazy", { context: query.context, type: type, object: object, path: query.context[:current_path] }) { super }
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/tracing/prometheus_tracing.rb | lib/graphql/tracing/prometheus_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
class PrometheusTracing < PlatformTracing
DEFAULT_WHITELIST = ['execute_field', 'execute_field_lazy'].freeze
DEFAULT_COLLECTOR_TYPE = 'graphql'.freeze
self.platform_keys = {
'lex' => "graphql.lex",
'parse' => "graphql.parse",
'validate' => "graphql.validate",
'analyze_query' => "graphql.analyze",
'analyze_multiplex' => "graphql.analyze",
'execute_multiplex' => "graphql.execute",
'execute_query' => "graphql.execute",
'execute_query_lazy' => "graphql.execute",
'execute_field' => "graphql.execute",
'execute_field_lazy' => "graphql.execute"
}
def initialize(opts = {})
@client = opts[:client] || PrometheusExporter::Client.default
@keys_whitelist = opts[:keys_whitelist] || DEFAULT_WHITELIST
@collector_type = opts[:collector_type] || DEFAULT_COLLECTOR_TYPE
super opts
end
def platform_trace(platform_key, key, _data, &block)
return yield unless @keys_whitelist.include?(key)
instrument_execution(platform_key, key, &block)
end
def platform_field_key(type, field)
"#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"#{type.graphql_name}.authorized"
end
def platform_resolve_type_key(type)
"#{type.graphql_name}.resolve_type"
end
private
def instrument_execution(platform_key, key, &block)
start = ::Process.clock_gettime ::Process::CLOCK_MONOTONIC
result = block.call
duration = ::Process.clock_gettime(::Process::CLOCK_MONOTONIC) - start
observe platform_key, key, duration
result
end
def observe(platform_key, key, duration)
@client.send_json(
type: @collector_type,
duration: duration,
platform_key: platform_key,
key: key
)
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/tracing/appoptics_trace.rb | lib/graphql/tracing/appoptics_trace.rb | # frozen_string_literal: true
require "graphql/tracing/platform_trace"
module GraphQL
module Tracing
# This class uses the AppopticsAPM SDK from the appoptics_apm gem to create
# traces for GraphQL.
#
# There are 4 configurations available. They can be set in the
# appoptics_apm config file or in code. Please see:
# {https://docs.appoptics.com/kb/apm_tracing/ruby/configure}
#
# AppOpticsAPM::Config[:graphql][:enabled] = true|false
# AppOpticsAPM::Config[:graphql][:transaction_name] = true|false
# AppOpticsAPM::Config[:graphql][:sanitize_query] = true|false
# AppOpticsAPM::Config[:graphql][:remove_comments] = true|false
module AppOpticsTrace
# These GraphQL events will show up as 'graphql.prep' spans
PREP_KEYS = ['lex', 'parse', 'validate', 'analyze_query', 'analyze_multiplex'].freeze
# These GraphQL events will show up as 'graphql.execute' spans
EXEC_KEYS = ['execute_multiplex', 'execute_query', 'execute_query_lazy'].freeze
# During auto-instrumentation this version of AppOpticsTracing is compared
# with the version provided in the appoptics_apm gem, so that the newer
# version of the class can be used
def self.version
Gem::Version.new('1.0.0')
end
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
[
'lex',
'parse',
'validate',
'analyze_query',
'analyze_multiplex',
'execute_multiplex',
'execute_query',
'execute_query_lazy',
].each do |trace_method|
module_eval <<-RUBY, __FILE__, __LINE__
def #{trace_method}(**data)
return super if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = span_name("#{trace_method}")
kvs = metadata(data, layer)
kvs[:Key] = "#{trace_method}" if (PREP_KEYS + EXEC_KEYS).include?("#{trace_method}")
transaction_name(kvs[:InboundQuery]) if kvs[:InboundQuery] && layer == 'graphql.execute'
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
super
end
end
RUBY
end
# rubocop:enable Development/NoEvalCop
def execute_field(query:, field:, ast_node:, arguments:, object:)
return_type = field.type.unwrap
trace_field = if return_type.kind.scalar? || return_type.kind.enum?
(field.trace.nil? && @trace_scalars) || field.trace
else
true
end
platform_key = if trace_field
@platform_key_cache[AppOpticsTrace].platform_field_key_cache[field]
else
nil
end
if platform_key && trace_field
return super if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = platform_key
kvs = metadata({query: query, field: field, ast_node: ast_node, arguments: arguments, object: object}, layer)
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
super
end
else
super
end
end
def execute_field_lazy(query:, field:, ast_node:, arguments:, object:) # rubocop:disable Development/TraceCallsSuperCop
execute_field(query: query, field: field, ast_node: ast_node, arguments: arguments, object: object)
end
def authorized(**data)
return super if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = @platform_key_cache[AppOpticsTrace].platform_authorized_key_cache[data[:type]]
kvs = metadata(data, layer)
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
super
end
end
def authorized_lazy(**data)
return super if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = @platform_key_cache[AppOpticsTrace].platform_authorized_key_cache[data[:type]]
kvs = metadata(data, layer)
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
super
end
end
def resolve_type(**data)
return super if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = @platform_key_cache[AppOpticsTrace].platform_resolve_type_key_cache[data[:type]]
kvs = metadata(data, layer)
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
super
end
end
def resolve_type_lazy(**data)
return super if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = @platform_key_cache[AppOpticsTrace].platform_resolve_type_key_cache[data[:type]]
kvs = metadata(data, layer)
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
super
end
end
include PlatformTrace
def platform_field_key(field)
"graphql.#{field.owner.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"graphql.authorized.#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"graphql.resolve_type.#{type.graphql_name}"
end
private
def gql_config
::AppOpticsAPM::Config[:graphql] ||= {}
end
def transaction_name(query)
return if gql_config[:transaction_name] == false ||
::AppOpticsAPM::SDK.get_transaction_name
split_query = query.strip.split(/\W+/, 3)
split_query[0] = 'query' if split_query[0].empty?
name = "graphql.#{split_query[0..1].join('.')}"
::AppOpticsAPM::SDK.set_transaction_name(name)
end
def multiplex_transaction_name(names)
return if gql_config[:transaction_name] == false ||
::AppOpticsAPM::SDK.get_transaction_name
name = "graphql.multiplex.#{names.join('.')}"
name = "#{name[0..251]}..." if name.length > 254
::AppOpticsAPM::SDK.set_transaction_name(name)
end
def span_name(key)
return 'graphql.prep' if PREP_KEYS.include?(key)
return 'graphql.execute' if EXEC_KEYS.include?(key)
key[/^graphql\./] ? key : "graphql.#{key}"
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def metadata(data, layer)
data.keys.map do |key|
case key
when :context
graphql_context(data[key], layer)
when :query
graphql_query(data[key])
when :query_string
graphql_query_string(data[key])
when :multiplex
graphql_multiplex(data[key])
when :path
[key, data[key].join(".")]
else
[key, data[key]]
end
end.tap { _1.flatten!(2) }.each_slice(2).to_h.merge(Spec: 'graphql')
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def graphql_context(context, layer)
context.errors && context.errors.each do |err|
AppOpticsAPM::API.log_exception(layer, err)
end
[[:Path, context.path.join('.')]]
end
def graphql_query(query)
return [] unless query
query_string = query.query_string
query_string = remove_comments(query_string) if gql_config[:remove_comments] != false
query_string = sanitize(query_string) if gql_config[:sanitize_query] != false
[[:InboundQuery, query_string],
[:Operation, query.selected_operation_name]]
end
def graphql_query_string(query_string)
query_string = remove_comments(query_string) if gql_config[:remove_comments] != false
query_string = sanitize(query_string) if gql_config[:sanitize_query] != false
[:InboundQuery, query_string]
end
def graphql_multiplex(data)
names = data.queries.map(&:operations).map!(&:keys).tap(&:flatten!).tap(&:compact!)
multiplex_transaction_name(names) if names.size > 1
[:Operations, names.join(', ')]
end
def sanitize(query)
return unless query
# remove arguments
query.gsub(/"[^"]*"/, '"?"') # strings
.gsub(/-?[0-9]*\.?[0-9]+e?[0-9]*/, '?') # ints + floats
.gsub(/\[[^\]]*\]/, '[?]') # arrays
end
def remove_comments(query)
return unless query
query.gsub(/#[^\n\r]*/, '')
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/tracing/notifications_trace.rb | lib/graphql/tracing/notifications_trace.rb | # frozen_string_literal: true
module GraphQL
module Tracing
# This implementation forwards events to a notification handler
# (i.e. ActiveSupport::Notifications or Dry::Monitor::Notifications) with a `graphql` suffix.
#
# @see ActiveSupportNotificationsTrace ActiveSupport::Notifications integration
module NotificationsTrace
# @api private
class Adapter
def instrument(keyword, payload, &block)
raise "Implement #{self.class}#instrument to measure the block"
end
def start_event(keyword, payload)
ev = self.class::Event.new(keyword, payload)
ev.start
ev
end
class Event
def initialize(name, payload)
@name = name
@payload = payload
end
attr_reader :name, :payload
def start
raise "Implement #{self.class}#start to begin a new event (#{inspect})"
end
def finish
raise "Implement #{self.class}#finish to end this event (#{inspect})"
end
end
end
# @api private
class DryMonitorAdapter < Adapter
def instrument(...)
Dry::Monitor.instrument(...)
end
class Event < Adapter::Event
def start
Dry::Monitor.start(@name, @payload)
end
def finish
Dry::Monitor.stop(@name, @payload)
end
end
end
# @api private
class ActiveSupportNotificationsAdapter < Adapter
def instrument(...)
ActiveSupport::Notifications.instrument(...)
end
class Event < Adapter::Event
def start
@asn_event = ActiveSupport::Notifications.instrumenter.new_event(@name, @payload)
@asn_event.start!
end
def finish
@asn_event.finish!
ActiveSupport::Notifications.publish_event(@asn_event)
end
end
end
# @param engine [Class] The notifications engine to use, eg `Dry::Monitor` or `ActiveSupport::Notifications`
def initialize(engine:, **rest)
adapter = if defined?(Dry::Monitor) && engine == Dry::Monitor
DryMonitoringAdapter
elsif defined?(ActiveSupport::Notifications) && engine == ActiveSupport::Notifications
ActiveSupportNotificationsAdapter
else
engine
end
@notifications = adapter.new
super
end
def parse(**payload)
@notifications.instrument("parse.graphql", payload) do
super
end
end
def lex(**payload)
@notifications.instrument("lex.graphql", payload) do
super
end
end
def validate(**payload)
@notifications.instrument("validate.graphql", payload) do
super
end
end
def begin_analyze_multiplex(multiplex, analyzers)
begin_notifications_event("analyze.graphql", {multiplex: multiplex, analyzers: analyzers})
super
end
def end_analyze_multiplex(_multiplex, _analyzers)
finish_notifications_event
super
end
def execute_multiplex(**payload)
@notifications.instrument("execute.graphql", payload) do
super
end
end
def begin_execute_field(field, object, arguments, query)
begin_notifications_event("execute_field.graphql", {field: field, object: object, arguments: arguments, query: query})
super
end
def end_execute_field(_field, _object, _arguments, _query, _result)
finish_notifications_event
super
end
def dataloader_fiber_yield(source)
Fiber[PREVIOUS_EV_KEY] = finish_notifications_event
super
end
def dataloader_fiber_resume(source)
prev_ev = Fiber[PREVIOUS_EV_KEY]
if prev_ev
begin_notifications_event(prev_ev.name, prev_ev.payload)
end
super
end
def begin_authorized(type, object, context)
begin_notifications_event("authorized.graphql", {type: type, object: object, context: context})
super
end
def end_authorized(type, object, context, result)
finish_notifications_event
super
end
def begin_resolve_type(type, object, context)
begin_notifications_event("resolve_type.graphql", {type: type, object: object, context: context})
super
end
def end_resolve_type(type, object, context, resolved_type)
finish_notifications_event
super
end
def begin_dataloader_source(source)
begin_notifications_event("dataloader_source.graphql", { source: source })
super
end
def end_dataloader_source(source)
finish_notifications_event
super
end
CURRENT_EV_KEY = :__notifications_graphql_trace_event
PREVIOUS_EV_KEY = :__notifications_graphql_trace_previous_event
private
def begin_notifications_event(name, payload)
Fiber[CURRENT_EV_KEY] = @notifications.start_event(name, payload)
end
def finish_notifications_event
if ev = Fiber[CURRENT_EV_KEY]
ev.finish
# Use `false` to prevent grabbing an event from a parent fiber
Fiber[CURRENT_EV_KEY] = false
ev
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/tracing/data_dog_trace.rb | lib/graphql/tracing/data_dog_trace.rb | # frozen_string_literal: true
require "graphql/tracing/monitor_trace"
module GraphQL
module Tracing
# A tracer for reporting to DataDog
# @example Adding this tracer to your schema
# class MySchema < GraphQL::Schema
# trace_with GraphQL::Tracing::DataDogTrace
# end
# @example Skipping `resolve_type` and `authorized` events
# trace_with GraphQL::Tracing::DataDogTrace, trace_authorized: false, trace_resolve_type: false
DataDogTrace = MonitorTrace.create_module("datadog")
module DataDogTrace
class DatadogMonitor < MonitorTrace::Monitor
def initialize(set_transaction_name:, service: nil, tracer: nil, **_rest)
super
if tracer.nil?
tracer = defined?(Datadog::Tracing) ? Datadog::Tracing : Datadog.tracer
end
@tracer = tracer
@service_name = service
@has_prepare_span = @trace.respond_to?(:prepare_span)
end
attr_reader :tracer, :service_name
def instrument(keyword, object)
trace_key = name_for(keyword, object)
@tracer.trace(trace_key, service: @service_name, type: 'custom') do |span|
span.set_tag('component', 'graphql')
op_name = keyword.respond_to?(:name) ? keyword.name : keyword.to_s
span.set_tag('operation', op_name)
if keyword == :execute
operations = object.queries.map(&:selected_operation_name).join(', ')
first_query = object.queries.first
resource = if operations.empty?
fallback_transaction_name(first_query && first_query.context)
else
operations
end
span.resource = resource if resource
span.set_tag("selected_operation_name", first_query.selected_operation_name)
span.set_tag("selected_operation_type", first_query.selected_operation&.operation_type)
span.set_tag("query_string", first_query.query_string)
end
if @has_prepare_span
@trace.prepare_span(keyword, object, span)
end
yield
end
end
include MonitorTrace::Monitor::GraphQLSuffixNames
class Event < MonitorTrace::Monitor::Event
def start
name = @monitor.name_for(keyword, object)
@dd_span = @monitor.tracer.trace(name, service: @monitor.service_name, type: 'custom')
end
def finish
@dd_span.finish
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/tracing/appsignal_trace.rb | lib/graphql/tracing/appsignal_trace.rb | # frozen_string_literal: true
require "graphql/tracing/monitor_trace"
module GraphQL
module Tracing
# Instrumentation for reporting GraphQL-Ruby times to Appsignal.
#
# @example Installing the tracer
# class MySchema < GraphQL::Schema
# trace_with GraphQL::Tracing::AppsignalTrace
# end
AppsignalTrace = MonitorTrace.create_module("appsignal")
module AppsignalTrace
# @param set_action_name [Boolean] If true, the GraphQL operation name will be used as the transaction name.
# This is not advised if you run more than one query per HTTP request, for example, with `graphql-client` or multiplexing.
# It can also be specified per-query with `context[:set_appsignal_action_name]`.
def initialize(set_action_name: false, **rest)
rest[:set_transaction_name] ||= set_action_name
setup_appsignal_monitor(**rest)
super
end
class AppsignalMonitor < MonitorTrace::Monitor
def instrument(keyword, object)
if keyword == :execute
query = object.queries.first
set_this_txn_name = query.context[:set_appsignal_action_name]
if set_this_txn_name == true || (set_this_txn_name.nil? && @set_transaction_name)
Appsignal::Transaction.current.set_action(transaction_name(query))
end
end
Appsignal.instrument(name_for(keyword, object)) do
yield
end
end
include MonitorTrace::Monitor::GraphQLSuffixNames
class Event < GraphQL::Tracing::MonitorTrace::Monitor::Event
def start
Appsignal::Transaction.current.start_event
end
def finish
Appsignal::Transaction.current.finish_event(
@monitor.name_for(@keyword, @object),
"",
""
)
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/tracing/platform_tracing.rb | lib/graphql/tracing/platform_tracing.rb | # frozen_string_literal: true
module GraphQL
module Tracing
# Each platform provides:
# - `.platform_keys`
# - `#platform_trace`
# - `#platform_field_key(type, field)`
# @api private
class PlatformTracing
class << self
attr_accessor :platform_keys
def inherited(child_class)
child_class.platform_keys = self.platform_keys
end
end
def initialize(options = {})
@options = options
@platform_keys = self.class.platform_keys
@trace_scalars = options.fetch(:trace_scalars, false)
end
def trace(key, data)
case key
when "lex", "parse", "validate", "analyze_query", "analyze_multiplex", "execute_query", "execute_query_lazy", "execute_multiplex"
platform_key = @platform_keys.fetch(key)
platform_trace(platform_key, key, data) do
yield
end
when "execute_field", "execute_field_lazy"
field = data[:field]
return_type = field.type.unwrap
trace_field = if return_type.kind.scalar? || return_type.kind.enum?
(field.trace.nil? && @trace_scalars) || field.trace
else
true
end
platform_key = if trace_field
context = data.fetch(:query).context
cached_platform_key(context, field, :field) { platform_field_key(field.owner, field) }
else
nil
end
if platform_key && trace_field
platform_trace(platform_key, key, data) do
yield
end
else
yield
end
when "authorized", "authorized_lazy"
type = data.fetch(:type)
context = data.fetch(:context)
platform_key = cached_platform_key(context, type, :authorized) { platform_authorized_key(type) }
platform_trace(platform_key, key, data) do
yield
end
when "resolve_type", "resolve_type_lazy"
type = data.fetch(:type)
context = data.fetch(:context)
platform_key = cached_platform_key(context, type, :resolve_type) { platform_resolve_type_key(type) }
platform_trace(platform_key, key, data) do
yield
end
else
# it's a custom key
yield
end
end
def self.use(schema_defn, options = {})
if options[:legacy_tracing]
tracer = self.new(**options)
schema_defn.tracer(tracer)
else
tracing_name = self.name.split("::").last
trace_name = tracing_name.sub("Tracing", "Trace")
if GraphQL::Tracing.const_defined?(trace_name, false)
trace_module = GraphQL::Tracing.const_get(trace_name)
warn("`use(#{self.name})` is deprecated, use the equivalent `trace_with(#{trace_module.name})` instead. More info: https://graphql-ruby.org/queries/tracing.html")
schema_defn.trace_with(trace_module, **options)
else
warn("`use(#{self.name})` and `Tracing::PlatformTracing` are deprecated. Use a `trace_with(...)` module instead. More info: https://graphql-ruby.org/queries/tracing.html. Please open an issue on the GraphQL-Ruby repo if you want to discuss further!")
tracer = self.new(**options)
schema_defn.tracer(tracer, silence_deprecation_warning: true)
end
end
end
private
# Get the transaction name based on the operation type and name if possible, or fall back to a user provided
# one. Useful for anonymous queries.
def transaction_name(query)
selected_op = query.selected_operation
txn_name = if selected_op
op_type = selected_op.operation_type
op_name = selected_op.name || fallback_transaction_name(query.context) || "anonymous"
"#{op_type}.#{op_name}"
else
"query.anonymous"
end
"GraphQL/#{txn_name}"
end
def fallback_transaction_name(context)
context[:tracing_fallback_transaction_name]
end
attr_reader :options
# Different kind of schema objects have different kinds of keys:
#
# - Object types: `.authorized`
# - Union/Interface types: `.resolve_type`
# - Fields: execution
#
# So, they can all share one cache.
#
# If the key isn't present, the given block is called and the result is cached for `key`.
#
# @param ctx [GraphQL::Query::Context]
# @param key [Class, GraphQL::Field] A part of the schema
# @param trace_phase [Symbol] The stage of execution being traced (used by OpenTelementry tracing)
# @return [String]
def cached_platform_key(ctx, key, trace_phase)
cache = ctx.namespace(self.class)[:platform_key_cache] ||= {}
cache.fetch(key) { cache[key] = yield }
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/tracing/legacy_hooks_trace.rb | lib/graphql/tracing/legacy_hooks_trace.rb | # frozen_string_literal: true
module GraphQL
module Tracing
module LegacyHooksTrace
def execute_multiplex(multiplex:)
multiplex_instrumenters = multiplex.schema.instrumenters[:multiplex]
query_instrumenters = multiplex.schema.instrumenters[:query]
# First, run multiplex instrumentation, then query instrumentation for each query
RunHooks.call_hooks(multiplex_instrumenters, multiplex, :before_multiplex, :after_multiplex) do
RunHooks.each_query_call_hooks(query_instrumenters, multiplex.queries) do
super
end
end
end
module RunHooks
module_function
# Call the before_ hooks of each query,
# Then yield if no errors.
# `call_hooks` takes care of appropriate cleanup.
def each_query_call_hooks(instrumenters, queries, i = 0)
if i >= queries.length
yield
else
query = queries[i]
call_hooks(instrumenters, query, :before_query, :after_query) {
each_query_call_hooks(instrumenters, queries, i + 1) {
yield
}
}
end
end
# Call each before hook, and if they all succeed, yield.
# If they don't all succeed, call after_ for each one that succeeded.
def call_hooks(instrumenters, object, before_hook_name, after_hook_name)
begin
successful = []
instrumenters.each do |instrumenter|
instrumenter.public_send(before_hook_name, object)
successful << instrumenter
end
# if any before hooks raise an exception, quit calling before hooks,
# but call the after hooks on anything that succeeded but also
# raise the exception that came from the before hook.
rescue GraphQL::ExecutionError => err
object.context.errors << err
rescue => e
raise call_after_hooks(successful, object, after_hook_name, e)
end
begin
yield # Call the user code
ensure
ex = call_after_hooks(successful, object, after_hook_name, nil)
raise ex if ex
end
end
def call_after_hooks(instrumenters, object, after_hook_name, ex)
instrumenters.reverse_each do |instrumenter|
begin
instrumenter.public_send(after_hook_name, object)
rescue => e
ex = e
end
end
ex
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/tracing/platform_trace.rb | lib/graphql/tracing/platform_trace.rb | # frozen_string_literal: true
module GraphQL
module Tracing
module PlatformTrace
def initialize(trace_scalars: false, **_options)
@trace_scalars = trace_scalars
@platform_key_cache = Hash.new { |h, mod| h[mod] = mod::KeyCache.new }
super
end
module BaseKeyCache
def initialize
@platform_field_key_cache = Hash.new { |h, k| h[k] = platform_field_key(k) }
@platform_authorized_key_cache = Hash.new { |h, k| h[k] = platform_authorized_key(k) }
@platform_resolve_type_key_cache = Hash.new { |h, k| h[k] = platform_resolve_type_key(k) }
end
attr_reader :platform_field_key_cache, :platform_authorized_key_cache, :platform_resolve_type_key_cache
end
def platform_execute_field_lazy(*args, &block)
platform_execute_field(*args, &block)
end
def platform_authorized_lazy(key, &block)
platform_authorized(key, &block)
end
def platform_resolve_type_lazy(key, &block)
platform_resolve_type(key, &block)
end
def self.included(child_class)
key_methods_class = Class.new {
include(child_class)
include(BaseKeyCache)
}
child_class.const_set(:KeyCache, key_methods_class)
# rubocop:disable Development/NoEvalCop This eval takes static inputs at load-time
[:execute_field, :execute_field_lazy].each do |field_trace_method|
if !child_class.method_defined?(field_trace_method)
child_class.module_eval <<-RUBY, __FILE__, __LINE__
def #{field_trace_method}(query:, field:, ast_node:, arguments:, object:)
return_type = field.type.unwrap
trace_field = if return_type.kind.scalar? || return_type.kind.enum?
(field.trace.nil? && @trace_scalars) || field.trace
else
true
end
platform_key = if trace_field
@platform_key_cache[#{child_class}].platform_field_key_cache[field]
else
nil
end
if platform_key && trace_field
platform_#{field_trace_method}(platform_key) do
super
end
else
super
end
end
RUBY
end
end
[:authorized, :authorized_lazy].each do |auth_trace_method|
if !child_class.method_defined?(auth_trace_method)
child_class.module_eval <<-RUBY, __FILE__, __LINE__
def #{auth_trace_method}(type:, query:, object:)
platform_key = @platform_key_cache[#{child_class}].platform_authorized_key_cache[type]
platform_#{auth_trace_method}(platform_key) do
super
end
end
RUBY
end
end
[:resolve_type, :resolve_type_lazy].each do |rt_trace_method|
if !child_class.method_defined?(rt_trace_method)
child_class.module_eval <<-RUBY, __FILE__, __LINE__
def #{rt_trace_method}(query:, type:, object:)
platform_key = @platform_key_cache[#{child_class}].platform_resolve_type_key_cache[type]
platform_#{rt_trace_method}(platform_key) do
super
end
end
RUBY
end
# rubocop:enable Development/NoEvalCop
end
end
private
# Get the transaction name based on the operation type and name if possible, or fall back to a user provided
# one. Useful for anonymous queries.
def transaction_name(query)
selected_op = query.selected_operation
txn_name = if selected_op
op_type = selected_op.operation_type
op_name = selected_op.name || fallback_transaction_name(query.context) || "anonymous"
"#{op_type}.#{op_name}"
else
"query.anonymous"
end
"GraphQL/#{txn_name}"
end
def fallback_transaction_name(context)
context[:tracing_fallback_transaction_name]
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/tracing/new_relic_tracing.rb | lib/graphql/tracing/new_relic_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
class NewRelicTracing < PlatformTracing
self.platform_keys = {
"lex" => "GraphQL/lex",
"parse" => "GraphQL/parse",
"validate" => "GraphQL/validate",
"analyze_query" => "GraphQL/analyze",
"analyze_multiplex" => "GraphQL/analyze",
"execute_multiplex" => "GraphQL/execute",
"execute_query" => "GraphQL/execute",
"execute_query_lazy" => "GraphQL/execute",
}
# @param set_transaction_name [Boolean] If true, the GraphQL operation name will be used as the transaction name.
# This is not advised if you run more than one query per HTTP request, for example, with `graphql-client` or multiplexing.
# It can also be specified per-query with `context[:set_new_relic_transaction_name]`.
def initialize(options = {})
@set_transaction_name = options.fetch(:set_transaction_name, false)
super
end
def platform_trace(platform_key, key, data)
if key == "execute_query"
set_this_txn_name = data[:query].context[:set_new_relic_transaction_name]
if set_this_txn_name == true || (set_this_txn_name.nil? && @set_transaction_name)
NewRelic::Agent.set_transaction_name(transaction_name(data[:query]))
end
end
NewRelic::Agent::MethodTracerHelpers.trace_execution_scoped(platform_key) do
yield
end
end
def platform_field_key(type, field)
"GraphQL/#{type.graphql_name}/#{field.graphql_name}"
end
def platform_authorized_key(type)
"GraphQL/Authorize/#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"GraphQL/ResolveType/#{type.graphql_name}"
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/tracing/trace.rb | lib/graphql/tracing/trace.rb | # frozen_string_literal: true
require "graphql/tracing"
module GraphQL
module Tracing
# This is the base class for a `trace` instance whose methods are called during query execution.
# "Trace modes" are subclasses of this with custom tracing modules mixed in.
#
# A trace module may implement any of the methods on `Trace`, being sure to call `super`
# to continue any tracing hooks and call the actual runtime behavior.
#
class Trace
# @param multiplex [GraphQL::Execution::Multiplex, nil]
# @param query [GraphQL::Query, nil]
def initialize(multiplex: nil, query: nil, **_options)
@multiplex = multiplex
@query = query
end
# The Ruby parser doesn't call this method (`graphql/c_parser` does.)
def lex(query_string:)
yield
end
# @param query_string [String]
# @return [void]
def parse(query_string:)
yield
end
def validate(query:, validate:)
yield
end
def begin_validate(query, validate)
end
def end_validate(query, validate, errors)
end
# @param multiplex [GraphQL::Execution::Multiplex]
# @param analyzers [Array<Class>]
# @return [void]
def begin_analyze_multiplex(multiplex, analyzers); end
# @param multiplex [GraphQL::Execution::Multiplex]
# @param analyzers [Array<Class>]
# @return [void]
def end_analyze_multiplex(multiplex, analyzers); end
# @param multiplex [GraphQL::Execution::Multiplex]
# @return [void]
def analyze_multiplex(multiplex:)
yield
end
def analyze_query(query:)
yield
end
# This wraps an entire `.execute` call.
# @param multiplex [GraphQL::Execution::Multiplex]
# @return [void]
def execute_multiplex(multiplex:)
yield
end
def execute_query(query:)
yield
end
def execute_query_lazy(query:, multiplex:)
yield
end
# GraphQL is about to resolve this field
# @param field [GraphQL::Schema::Field]
# @param object [GraphQL::Schema::Object]
# @param arguments [Hash]
# @param query [GraphQL::Query]
def begin_execute_field(field, object, arguments, query); end
# GraphQL just finished resolving this field
# @param field [GraphQL::Schema::Field]
# @param object [GraphQL::Schema::Object]
# @param arguments [Hash]
# @param query [GraphQL::Query]
# @param result [Object]
def end_execute_field(field, object, arguments, query, result); end
def execute_field(field:, query:, ast_node:, arguments:, object:)
yield
end
def execute_field_lazy(field:, query:, ast_node:, arguments:, object:)
yield
end
def authorized(query:, type:, object:)
yield
end
# A call to `.authorized?` is starting
# @param type [Class<GraphQL::Schema::Object>]
# @param object [Object]
# @param context [GraphQL::Query::Context]
# @return [void]
def begin_authorized(type, object, context)
end
# A call to `.authorized?` just finished
# @param type [Class<GraphQL::Schema::Object>]
# @param object [Object]
# @param context [GraphQL::Query::Context]
# @param authorized_result [Boolean]
# @return [void]
def end_authorized(type, object, context, authorized_result)
end
def authorized_lazy(query:, type:, object:)
yield
end
def resolve_type(query:, type:, object:)
yield
end
def resolve_type_lazy(query:, type:, object:)
yield
end
# A call to `.resolve_type` is starting
# @param type [Class<GraphQL::Schema::Union>, Module<GraphQL::Schema::Interface>]
# @param value [Object]
# @param context [GraphQL::Query::Context]
# @return [void]
def begin_resolve_type(type, value, context)
end
# A call to `.resolve_type` just ended
# @param type [Class<GraphQL::Schema::Union>, Module<GraphQL::Schema::Interface>]
# @param value [Object]
# @param context [GraphQL::Query::Context]
# @param resolved_type [Class<GraphQL::Schema::Object>]
# @return [void]
def end_resolve_type(type, value, context, resolved_type)
end
# A dataloader run is starting
# @param dataloader [GraphQL::Dataloader]
# @return [void]
def begin_dataloader(dataloader); end
# A dataloader run has ended
# @param dataloder [GraphQL::Dataloader]
# @return [void]
def end_dataloader(dataloader); end
# A source with pending keys is about to fetch
# @param source [GraphQL::Dataloader::Source]
# @return [void]
def begin_dataloader_source(source); end
# A fetch call has just ended
# @param source [GraphQL::Dataloader::Source]
# @return [void]
def end_dataloader_source(source); end
# Called when Dataloader spins up a new fiber for GraphQL execution
# @param jobs [Array<#call>] Execution steps to run
# @return [void]
def dataloader_spawn_execution_fiber(jobs); end
# Called when Dataloader spins up a new fiber for fetching data
# @param pending_sources [GraphQL::Dataloader::Source] Instances with pending keys
# @return [void]
def dataloader_spawn_source_fiber(pending_sources); end
# Called when an execution or source fiber terminates
# @return [void]
def dataloader_fiber_exit; end
# Called when a Dataloader fiber is paused to wait for data
# @param source [GraphQL::Dataloader::Source] The Source whose `load` call initiated this `yield`
# @return [void]
def dataloader_fiber_yield(source); end
# Called when a Dataloader fiber is resumed because data has been loaded
# @param source [GraphQL::Dataloader::Source] The Source whose `load` call previously caused this Fiber to wait
# @return [void]
def dataloader_fiber_resume(source); 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/tracing/appoptics_tracing.rb | lib/graphql/tracing/appoptics_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
# This class uses the AppopticsAPM SDK from the appoptics_apm gem to create
# traces for GraphQL.
#
# There are 4 configurations available. They can be set in the
# appoptics_apm config file or in code. Please see:
# {https://docs.appoptics.com/kb/apm_tracing/ruby/configure}
#
# AppOpticsAPM::Config[:graphql][:enabled] = true|false
# AppOpticsAPM::Config[:graphql][:transaction_name] = true|false
# AppOpticsAPM::Config[:graphql][:sanitize_query] = true|false
# AppOpticsAPM::Config[:graphql][:remove_comments] = true|false
class AppOpticsTracing < GraphQL::Tracing::PlatformTracing
# These GraphQL events will show up as 'graphql.prep' spans
PREP_KEYS = ['lex', 'parse', 'validate', 'analyze_query', 'analyze_multiplex'].freeze
# These GraphQL events will show up as 'graphql.execute' spans
EXEC_KEYS = ['execute_multiplex', 'execute_query', 'execute_query_lazy'].freeze
def initialize(...)
warn "GraphQL::Tracing::AppOptics tracing is deprecated; update to SolarWindsAPM instead, which uses OpenTelemetry."
super
end
# During auto-instrumentation this version of AppOpticsTracing is compared
# with the version provided in the appoptics_apm gem, so that the newer
# version of the class can be used
def self.version
Gem::Version.new('1.0.0')
end
self.platform_keys = {
'lex' => 'lex',
'parse' => 'parse',
'validate' => 'validate',
'analyze_query' => 'analyze_query',
'analyze_multiplex' => 'analyze_multiplex',
'execute_multiplex' => 'execute_multiplex',
'execute_query' => 'execute_query',
'execute_query_lazy' => 'execute_query_lazy'
}
def platform_trace(platform_key, _key, data)
return yield if !defined?(AppOpticsAPM) || gql_config[:enabled] == false
layer = span_name(platform_key)
kvs = metadata(data, layer)
kvs[:Key] = platform_key if (PREP_KEYS + EXEC_KEYS).include?(platform_key)
transaction_name(kvs[:InboundQuery]) if kvs[:InboundQuery] && layer == 'graphql.execute'
::AppOpticsAPM::SDK.trace(layer, kvs) do
kvs.clear # we don't have to send them twice
yield
end
end
def platform_field_key(type, field)
"graphql.#{type.graphql_name}.#{field.graphql_name}"
end
def platform_authorized_key(type)
"graphql.authorized.#{type.graphql_name}"
end
def platform_resolve_type_key(type)
"graphql.resolve_type.#{type.graphql_name}"
end
private
def gql_config
::AppOpticsAPM::Config[:graphql] ||= {}
end
def transaction_name(query)
return if gql_config[:transaction_name] == false ||
::AppOpticsAPM::SDK.get_transaction_name
split_query = query.strip.split(/\W+/, 3)
split_query[0] = 'query' if split_query[0].empty?
name = "graphql.#{split_query[0..1].join('.')}"
::AppOpticsAPM::SDK.set_transaction_name(name)
end
def multiplex_transaction_name(names)
return if gql_config[:transaction_name] == false ||
::AppOpticsAPM::SDK.get_transaction_name
name = "graphql.multiplex.#{names.join('.')}"
name = "#{name[0..251]}..." if name.length > 254
::AppOpticsAPM::SDK.set_transaction_name(name)
end
def span_name(key)
return 'graphql.prep' if PREP_KEYS.include?(key)
return 'graphql.execute' if EXEC_KEYS.include?(key)
key[/^graphql\./] ? key : "graphql.#{key}"
end
# rubocop:disable Metrics/AbcSize, Metrics/MethodLength
def metadata(data, layer)
data.keys.map do |key|
case key
when :context
graphql_context(data[key], layer)
when :query
graphql_query(data[key])
when :query_string
graphql_query_string(data[key])
when :multiplex
graphql_multiplex(data[key])
when :path
[key, data[key].join(".")]
else
[key, data[key]]
end
end.tap { _1.flatten!(2) }.each_slice(2).to_h.merge(Spec: 'graphql')
end
# rubocop:enable Metrics/AbcSize, Metrics/MethodLength
def graphql_context(context, layer)
context.errors && context.errors.each do |err|
AppOpticsAPM::API.log_exception(layer, err)
end
[[:Path, context.path.join('.')]]
end
def graphql_query(query)
return [] unless query
query_string = query.query_string
query_string = remove_comments(query_string) if gql_config[:remove_comments] != false
query_string = sanitize(query_string) if gql_config[:sanitize_query] != false
[[:InboundQuery, query_string],
[:Operation, query.selected_operation_name]]
end
def graphql_query_string(query_string)
query_string = remove_comments(query_string) if gql_config[:remove_comments] != false
query_string = sanitize(query_string) if gql_config[:sanitize_query] != false
[:InboundQuery, query_string]
end
def graphql_multiplex(data)
names = data.queries.map(&:operations).map!(&:keys).tap(&:flatten!).tap(&:compact!)
multiplex_transaction_name(names) if names.size > 1
[:Operations, names.join(', ')]
end
def sanitize(query)
return unless query
# remove arguments
query.gsub(/"[^"]*"/, '"?"') # strings
.gsub(/-?[0-9]*\.?[0-9]+e?[0-9]*/, '?') # ints + floats
.gsub(/\[[^\]]*\]/, '[?]') # arrays
end
def remove_comments(query)
return unless query
query.gsub(/#[^\n\r]*/, '')
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/tracing/perfetto_trace.rb | lib/graphql/tracing/perfetto_trace.rb | # frozen_string_literal: true
module GraphQL
module Tracing
# This produces a trace file for inspecting in the [Perfetto Trace Viewer](https://ui.perfetto.dev).
#
# To get the file, call {#write} on the trace.
#
# Use "trace modes" to configure this to run on command or on a sample of traffic.
#
# @example Writing trace output
#
# result = MySchema.execute(...)
# result.query.trace.write(file: "tmp/trace.dump")
#
# @example Running this instrumenter when `trace: true` is present in the request
#
# class MySchema < GraphQL::Schema
# # Only run this tracer when `context[:trace_mode]` is `:trace`
# trace_with GraphQL::Tracing::Perfetto, mode: :trace
# end
#
# # In graphql_controller.rb:
#
# context[:trace_mode] = params[:trace] ? :trace : nil
# result = MySchema.execute(query_str, context: context, variables: variables, ...)
# if context[:trace_mode] == :trace
# result.trace.write(file: ...)
# end
#
module PerfettoTrace
# TODOs:
# - Make debug annotations visible on both parts when dataloader is involved
PROTOBUF_AVAILABLE = begin
require "google/protobuf"
true
rescue LoadError
false
end
if PROTOBUF_AVAILABLE
require "graphql/tracing/perfetto_trace/trace_pb"
end
def self.included(_trace_class)
if !PROTOBUF_AVAILABLE
raise "#{self} can't be used because the `google-protobuf` gem wasn't available. Add it to your project, then try again."
end
end
DATALOADER_CATEGORY_IIDS = [5]
FIELD_EXECUTE_CATEGORY_IIDS = [6]
ACTIVE_SUPPORT_NOTIFICATIONS_CATEGORY_IIDS = [7]
AUTHORIZED_CATEGORY_IIDS = [8]
RESOLVE_TYPE_CATEGORY_IIDS = [9]
DA_OBJECT_IID = 10
DA_RESULT_IID = 11
DA_ARGUMENTS_IID = 12
DA_FETCH_KEYS_IID = 13
DA_STR_VAL_NIL_IID = 14
REVERSE_DEBUG_NAME_LOOKUP = {
DA_OBJECT_IID => "object",
DA_RESULT_IID => "result",
DA_ARGUMENTS_IID => "arguments",
DA_FETCH_KEYS_IID => "fetch keys",
}
DEBUG_INSPECT_CATEGORY_IIDS = [15]
DA_DEBUG_INSPECT_CLASS_IID = 16
DEBUG_INSPECT_EVENT_NAME_IID = 17
DA_DEBUG_INSPECT_FOR_IID = 18
# @param active_support_notifications_pattern [String, RegExp, false] A filter for `ActiveSupport::Notifications`, if it's present. Or `false` to skip subscribing.
def initialize(active_support_notifications_pattern: nil, save_profile: false, **_rest)
super
@active_support_notifications_pattern = active_support_notifications_pattern
@save_profile = save_profile
query = if @multiplex
@multiplex.queries.first
else
@query # could still be nil in some initializations
end
@detailed_trace = query&.schema&.detailed_trace || DetailedTrace
@create_debug_annotations = if (ctx = query&.context).nil? || (ctx_debug = ctx[:detailed_trace_debug]).nil?
@detailed_trace.debug?
else
ctx_debug
end
Fiber[:graphql_flow_stack] = nil
@sequence_id = object_id
@pid = Process.pid
@flow_ids = Hash.new { |h, source_inst| h[source_inst] = [] }.compare_by_identity
@new_interned_event_names = {}
@interned_event_name_iids = Hash.new { |h, k|
new_id = 100 + h.size
@new_interned_event_names[k] = new_id
h[k] = new_id
}
@source_name_iids = Hash.new do |h, source_class|
h[source_class] = @interned_event_name_iids[source_class.name]
end.compare_by_identity
@auth_name_iids = Hash.new do |h, graphql_type|
h[graphql_type] = @interned_event_name_iids["Authorize: #{graphql_type.graphql_name}"]
end.compare_by_identity
@resolve_type_name_iids = Hash.new do |h, graphql_type|
h[graphql_type] = @interned_event_name_iids["Resolve Type: #{graphql_type.graphql_name}"]
end.compare_by_identity
@new_interned_da_names = {}
@interned_da_name_ids = Hash.new { |h, k|
next_id = 100 + h.size
@new_interned_da_names[k] = next_id
h[k] = next_id
}
@new_interned_da_string_values = {}
@interned_da_string_values = Hash.new do |h, k|
new_id = 100 + h.size
@new_interned_da_string_values[k] = new_id
h[k] = new_id
end
@class_name_iids = Hash.new do |h, k|
h[k] = @interned_da_string_values[k.name]
end.compare_by_identity
@starting_objects = GC.stat(:total_allocated_objects)
@objects_counter_id = :objects_counter.object_id
@fibers_counter_id = :fibers_counter.object_id
@fields_counter_id = :fields_counter.object_id
@counts_objects = [@objects_counter_id]
@counts_objects_and_fields = [@objects_counter_id, @fields_counter_id]
@counts_fibers = [@fibers_counter_id]
@counts_fibers_and_objects = [@fibers_counter_id, @objects_counter_id]
@begin_validate = nil
@begin_time = nil
@packets = []
@packets << TracePacket.new(
track_descriptor: TrackDescriptor.new(
uuid: tid,
name: "Main Thread",
child_ordering: TrackDescriptor::ChildTracksOrdering::CHRONOLOGICAL,
),
first_packet_on_sequence: true,
previous_packet_dropped: true,
trusted_packet_sequence_id: @sequence_id,
sequence_flags: 3,
)
@packets << TracePacket.new(
interned_data: InternedData.new(
event_categories: [
EventCategory.new(name: "Dataloader", iid: DATALOADER_CATEGORY_IIDS.first),
EventCategory.new(name: "Field Execution", iid: FIELD_EXECUTE_CATEGORY_IIDS.first),
EventCategory.new(name: "ActiveSupport::Notifications", iid: ACTIVE_SUPPORT_NOTIFICATIONS_CATEGORY_IIDS.first),
EventCategory.new(name: "Authorized", iid: AUTHORIZED_CATEGORY_IIDS.first),
EventCategory.new(name: "Resolve Type", iid: RESOLVE_TYPE_CATEGORY_IIDS.first),
EventCategory.new(name: "Debug Inspect", iid: DEBUG_INSPECT_CATEGORY_IIDS.first),
],
debug_annotation_names: [
*REVERSE_DEBUG_NAME_LOOKUP.map { |(iid, name)| DebugAnnotationName.new(name: name, iid: iid) },
DebugAnnotationName.new(name: "inspect instance of", iid: DA_DEBUG_INSPECT_CLASS_IID),
DebugAnnotationName.new(name: "inspecting for", iid: DA_DEBUG_INSPECT_FOR_IID)
],
debug_annotation_string_values: [
InternedString.new(str: "(nil)", iid: DA_STR_VAL_NIL_IID),
],
event_names: [
EventName.new(name: "#{(@detailed_trace.is_a?(Class) ? @detailed_trace : @detailed_trace.class).name}#inspect_object", iid: DEBUG_INSPECT_EVENT_NAME_IID)
],
),
trusted_packet_sequence_id: @sequence_id,
sequence_flags: 2,
)
@main_fiber_id = fid
@packets << track_descriptor_packet(tid, fid, "Main Fiber")
@packets << track_descriptor_packet(tid, @objects_counter_id, "Allocated Objects", counter: {})
@packets << trace_packet(
type: TrackEvent::Type::TYPE_COUNTER,
track_uuid: @objects_counter_id,
counter_value: count_allocations,
)
@packets << track_descriptor_packet(tid, @fibers_counter_id, "Active Fibers", counter: {})
@fibers_count = 0
@packets << trace_packet(
type: TrackEvent::Type::TYPE_COUNTER,
track_uuid: @fibers_counter_id,
counter_value: count_fibers(0),
)
@packets << track_descriptor_packet(tid, @fields_counter_id, "Resolved Fields", counter: {})
@fields_count = -1
@packets << trace_packet(
type: TrackEvent::Type::TYPE_COUNTER,
track_uuid: @fields_counter_id,
counter_value: count_fields,
)
end
def execute_multiplex(multiplex:)
if defined?(ActiveSupport::Notifications) && @active_support_notifications_pattern != false
subscribe_to_active_support_notifications(@active_support_notifications_pattern)
end
@operation_name = multiplex.queries.map { |q| q.selected_operation_name || "anonymous" }.join(",")
@begin_time = Time.now
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
name: "Multiplex"
) { [ payload_to_debug("query_string", multiplex.queries.map(&:sanitized_query_string).join("\n\n")) ] }
result = super
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
)
result
ensure
unsubscribe_from_active_support_notifications
if @save_profile
begin_ts = (@begin_time.to_f * 1000).round
end_ts = (Time.now.to_f * 1000).round
duration_ms = end_ts - begin_ts
multiplex.schema.detailed_trace.save_trace(@operation_name, duration_ms, begin_ts, Trace.encode(Trace.new(packet: @packets)))
end
end
def begin_execute_field(field, object, arguments, query)
packet = trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
name: query.context.current_path.join("."),
category_iids: FIELD_EXECUTE_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
@packets << packet
fiber_flow_stack << packet
super
end
def end_execute_field(field, object, arguments, query, app_result)
end_ts = ts
start_field = fiber_flow_stack.pop
if @create_debug_annotations
start_field.track_event = dup_with(start_field.track_event,{
debug_annotations: [
payload_to_debug(nil, object.object, iid: DA_OBJECT_IID, intern_value: true),
payload_to_debug(nil, arguments, iid: DA_ARGUMENTS_IID),
payload_to_debug(nil, app_result, iid: DA_RESULT_IID, intern_value: true)
]
})
end
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects_and_fields,
extra_counter_values: [count_allocations, count_fields],
)
super
end
def begin_analyze_multiplex(m, analyzers)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
name: "Analysis") {
[
payload_to_debug("analyzers_count", analyzers.size),
payload_to_debug("analyzers", analyzers),
]
}
super
end
def end_analyze_multiplex(m, analyzers)
end_ts = ts
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
super
end
def parse(query_string:)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
name: "Parse"
)
result = super
end_ts = ts
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
result
end
def begin_validate(query, validate)
@begin_validate = trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
name: "Validate") {
[payload_to_debug("validate?", validate)]
}
@packets << @begin_validate
super
end
def end_validate(query, validate, validation_errors)
end_ts = ts
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
if @create_debug_annotations
new_bv_track_event = dup_with(
@begin_validate.track_event, {
debug_annotations: [
@begin_validate.track_event.debug_annotations.first,
payload_to_debug("valid?", validation_errors.empty?)
]
}
)
@begin_validate.track_event = new_bv_track_event
end
super
end
def dataloader_spawn_execution_fiber(jobs)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_INSTANT,
track_uuid: fid,
name: "Create Execution Fiber",
category_iids: DATALOADER_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_fibers_and_objects,
extra_counter_values: [count_fibers(1), count_allocations]
)
@packets << track_descriptor_packet(@did, fid, "Exec Fiber ##{fid}")
super
end
def dataloader_spawn_source_fiber(pending_sources)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_INSTANT,
track_uuid: fid,
name: "Create Source Fiber",
category_iids: DATALOADER_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_fibers_and_objects,
extra_counter_values: [count_fibers(1), count_allocations]
)
@packets << track_descriptor_packet(@did, fid, "Source Fiber ##{fid}")
super
end
def dataloader_fiber_yield(source)
ls = fiber_flow_stack.last
if (flow_id = ls.track_event.flow_ids.first)
# got it
else
flow_id = ls.track_event.name.object_id
ls.track_event = dup_with(ls.track_event, {flow_ids: [flow_id] }, delete_counters: true)
end
@flow_ids[source] << flow_id
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_INSTANT,
track_uuid: fid,
name: "Fiber Yield",
category_iids: DATALOADER_CATEGORY_IIDS,
)
super
end
def dataloader_fiber_resume(source)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_INSTANT,
track_uuid: fid,
name: "Fiber Resume",
category_iids: DATALOADER_CATEGORY_IIDS,
)
ls = fiber_flow_stack.pop
@packets << packet = TracePacket.new(
timestamp: ts,
track_event: dup_with(ls.track_event, { type: TrackEvent::Type::TYPE_SLICE_BEGIN }),
trusted_packet_sequence_id: @sequence_id,
)
fiber_flow_stack << packet
super
end
def dataloader_fiber_exit
@packets << trace_packet(
type: TrackEvent::Type::TYPE_INSTANT,
track_uuid: fid,
name: "Fiber Exit",
category_iids: DATALOADER_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_fibers,
extra_counter_values: [count_fibers(-1)],
)
super
end
def begin_dataloader(dl)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_COUNTER,
track_uuid: @fibers_counter_id,
counter_value: count_fibers(1),
)
@did = fid
@packets << track_descriptor_packet(@main_fiber_id, @did, "Dataloader Fiber ##{@did}")
super
end
def end_dataloader(dl)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_COUNTER,
track_uuid: @fibers_counter_id,
counter_value: count_fibers(-1),
)
super
end
def begin_dataloader_source(source)
fds = @flow_ids[source]
fds_copy = fds.dup
fds.clear
packet = trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
name_iid: @source_name_iids[source.class],
category_iids: DATALOADER_CATEGORY_IIDS,
flow_ids: fds_copy,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations]) {
[
payload_to_debug(nil, source.pending.values, iid: DA_FETCH_KEYS_IID, intern_value: true),
*(source.instance_variables - [:@pending, :@fetching, :@results, :@dataloader]).map { |iv|
payload_to_debug(iv.to_s, source.instance_variable_get(iv), intern_value: true)
}
]
}
@packets << packet
fiber_flow_stack << packet
super
end
def end_dataloader_source(source)
end_ts = ts
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
fiber_flow_stack.pop
super
end
def begin_authorized(type, obj, ctx)
packet = trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
category_iids: AUTHORIZED_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
name_iid: @auth_name_iids[type],
)
@packets << packet
fiber_flow_stack << packet
super
end
def end_authorized(type, obj, ctx, is_authorized)
end_ts = ts
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
beg_auth = fiber_flow_stack.pop
if @create_debug_annotations
beg_auth.track_event = dup_with(beg_auth.track_event, { debug_annotations: [payload_to_debug("authorized?", is_authorized)] })
end
super
end
def begin_resolve_type(type, value, context)
packet = trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
category_iids: RESOLVE_TYPE_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
name_iid: @resolve_type_name_iids[type],
)
@packets << packet
fiber_flow_stack << packet
super
end
def end_resolve_type(type, value, context, resolved_type)
end_ts = ts
@packets << trace_packet(
timestamp: end_ts,
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
)
rt_begin = fiber_flow_stack.pop
if @create_debug_annotations
rt_begin.track_event = dup_with(rt_begin.track_event, { debug_annotations: [payload_to_debug("resolved_type", resolved_type, intern_value: true)] })
end
super
end
# Dump protobuf output in the specified file.
# @param file [String] path to a file in a directory that already exists
# @param debug_json [Boolean] True to print JSON instead of binary
# @return [nil, String, Hash] If `file` was given, `nil`. If `file` was `nil`, a Hash if `debug_json: true`, else binary data.
def write(file:, debug_json: false)
trace = Trace.new(
packet: @packets,
)
data = if debug_json
small_json = Trace.encode_json(trace)
JSON.pretty_generate(JSON.parse(small_json))
else
Trace.encode(trace)
end
if file
File.write(file, data, mode: 'wb')
nil
else
data
end
end
private
def ts
Process.clock_gettime(Process::CLOCK_MONOTONIC, :nanosecond)
end
def tid
Thread.current.object_id
end
def fid
Fiber.current.object_id
end
def debug_annotation(iid, value_key, value)
if iid
DebugAnnotation.new(name_iid: iid, value_key => value)
else
DebugAnnotation.new(value_key => value)
end
end
def payload_to_debug(k, v, iid: nil, intern_value: false)
if iid.nil?
iid = @interned_da_name_ids[k]
end
case v
when String
if intern_value
v = @interned_da_string_values[v]
debug_annotation(iid, :string_value_iid, v)
else
debug_annotation(iid, :string_value, v)
end
when Float
debug_annotation(iid, :double_value, v)
when Integer
debug_annotation(iid, :int_value, v)
when true, false
debug_annotation(iid, :bool_value, v)
when nil
if iid
DebugAnnotation.new(name_iid: iid, string_value_iid: DA_STR_VAL_NIL_IID)
else
DebugAnnotation.new(name: k, string_value_iid: DA_STR_VAL_NIL_IID)
end
when Module
if intern_value
val_iid = @class_name_iids[v]
debug_annotation(iid, :string_value_iid, val_iid)
else
debug_annotation(iid, :string_value, v.name)
end
when Symbol
debug_annotation(iid, :string_value, v.inspect)
when Array
debug_annotation(iid, :array_values, v.each_with_index.map { |v2, idx| payload_to_debug((k ? "#{k}.#{idx}" : String(idx)), v2, intern_value: intern_value) }.compact)
when Hash
debug_annotation(iid, :dict_entries, v.map { |k2, v2| payload_to_debug(k2, v2, intern_value: intern_value) }.compact)
else
class_name_iid = @interned_da_string_values[v.class.name]
da = [
debug_annotation(DA_DEBUG_INSPECT_CLASS_IID, :string_value_iid, class_name_iid),
]
if k
k_str_value_iid = @interned_da_string_values[k]
da << debug_annotation(DA_DEBUG_INSPECT_FOR_IID, :string_value_iid, k_str_value_iid)
elsif iid
k = REVERSE_DEBUG_NAME_LOOKUP[iid] || @interned_da_name_ids.key(iid)
if k.nil?
da << debug_annotation(DA_DEBUG_INSPECT_FOR_IID, :string_value_iid, DA_STR_VAL_NIL_IID)
else
k_str_value_iid = @interned_da_string_values[k]
da << debug_annotation(DA_DEBUG_INSPECT_FOR_IID, :string_value_iid, k_str_value_iid)
end
end
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
name_iid: DEBUG_INSPECT_EVENT_NAME_IID,
category_iids: DEBUG_INSPECT_CATEGORY_IIDS,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations],
debug_annotations: da,
)
debug_str = @detailed_trace.inspect_object(v)
@packets << trace_packet(
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
)
if intern_value
str_iid = @interned_da_string_values[debug_str]
debug_annotation(iid, :string_value_iid, str_iid)
else
debug_annotation(iid, :string_value, debug_str)
end
end
end
def count_allocations
GC.stat(:total_allocated_objects) - @starting_objects
end
def count_fibers(diff)
@fibers_count += diff
end
def count_fields
@fields_count += 1
end
def dup_with(message, attrs, delete_counters: false)
new_attrs = message.to_h
if delete_counters
new_attrs.delete(:extra_counter_track_uuids)
new_attrs.delete(:extra_counter_values)
end
new_attrs.merge!(attrs)
message.class.new(**new_attrs)
end
def fiber_flow_stack
Fiber[:graphql_flow_stack] ||= []
end
def trace_packet(timestamp: ts, **event_attrs)
if @create_debug_annotations && block_given?
event_attrs[:debug_annotations] = yield
end
track_event = TrackEvent.new(event_attrs)
TracePacket.new(
timestamp: timestamp,
track_event: track_event,
trusted_packet_sequence_id: @sequence_id,
sequence_flags: 2,
interned_data: new_interned_data
)
end
def new_interned_data
if !@new_interned_da_names.empty?
da_names = @new_interned_da_names.map { |(name, iid)| DebugAnnotationName.new(iid: iid, name: name) }
@new_interned_da_names.clear
end
if !@new_interned_event_names.empty?
ev_names = @new_interned_event_names.map { |(name, iid)| EventName.new(iid: iid, name: name) }
@new_interned_event_names.clear
end
if !@new_interned_da_string_values.empty?
str_vals = @new_interned_da_string_values.map { |name, iid| InternedString.new(iid: iid, str: name.b) }
@new_interned_da_string_values.clear
end
if ev_names || da_names || str_vals
InternedData.new(
event_names: ev_names,
debug_annotation_names: da_names,
debug_annotation_string_values: str_vals,
)
else
nil
end
end
def track_descriptor_packet(parent_uuid, uuid, name, counter: nil)
td = if counter
TrackDescriptor.new(
parent_uuid: parent_uuid,
uuid: uuid,
name: name,
counter: counter
)
else
TrackDescriptor.new(
parent_uuid: parent_uuid,
uuid: uuid,
name: name,
child_ordering: TrackDescriptor::ChildTracksOrdering::CHRONOLOGICAL,
)
end
TracePacket.new(
track_descriptor: td,
trusted_packet_sequence_id: @sequence_id,
sequence_flags: 2,
)
end
def unsubscribe_from_active_support_notifications
if defined?(@as_subscriber)
ActiveSupport::Notifications.unsubscribe(@as_subscriber)
end
end
def subscribe_to_active_support_notifications(pattern)
@as_subscriber = ActiveSupport::Notifications.monotonic_subscribe(pattern) do |name, start, finish, id, payload|
metadata = @create_debug_annotations ? payload.map { |k, v| payload_to_debug(String(k), v, intern_value: true) } : nil
metadata&.compact!
te = if metadata.nil? || metadata.empty?
TrackEvent.new(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
category_iids: ACTIVE_SUPPORT_NOTIFICATIONS_CATEGORY_IIDS,
name: name,
)
else
TrackEvent.new(
type: TrackEvent::Type::TYPE_SLICE_BEGIN,
track_uuid: fid,
name: name,
category_iids: ACTIVE_SUPPORT_NOTIFICATIONS_CATEGORY_IIDS,
debug_annotations: metadata,
)
end
@packets << TracePacket.new(
timestamp: (start * 1_000_000_000).to_i,
track_event: te,
trusted_packet_sequence_id: @sequence_id,
sequence_flags: 2,
interned_data: new_interned_data
)
@packets << TracePacket.new(
timestamp: (finish * 1_000_000_000).to_i,
track_event: TrackEvent.new(
type: TrackEvent::Type::TYPE_SLICE_END,
track_uuid: fid,
name: name,
extra_counter_track_uuids: @counts_objects,
extra_counter_values: [count_allocations]
),
trusted_packet_sequence_id: @sequence_id,
sequence_flags: 2,
)
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/tracing/null_trace.rb | lib/graphql/tracing/null_trace.rb | # frozen_string_literal: true
require "graphql/tracing/trace"
module GraphQL
module Tracing
NullTrace = Trace.new.freeze
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/tracing/notifications_tracing.rb | lib/graphql/tracing/notifications_tracing.rb | # frozen_string_literal: true
require "graphql/tracing/platform_tracing"
module GraphQL
module Tracing
# This implementation forwards events to a notification handler (i.e.
# ActiveSupport::Notifications or Dry::Monitor::Notifications)
# with a `graphql` suffix.
#
# @see KEYS for event names
class NotificationsTracing
# A cache of frequently-used keys to avoid needless string allocations
KEYS = {
"lex" => "lex.graphql",
"parse" => "parse.graphql",
"validate" => "validate.graphql",
"analyze_multiplex" => "analyze_multiplex.graphql",
"analyze_query" => "analyze_query.graphql",
"execute_query" => "execute_query.graphql",
"execute_query_lazy" => "execute_query_lazy.graphql",
"execute_field" => "execute_field.graphql",
"execute_field_lazy" => "execute_field_lazy.graphql",
"authorized" => "authorized.graphql",
"authorized_lazy" => "authorized_lazy.graphql",
"resolve_type" => "resolve_type.graphql",
"resolve_type_lazy" => "resolve_type.graphql",
}
MAX_KEYS_SIZE = 100
# Initialize a new NotificationsTracing instance
#
# @param [Object] notifications_engine The notifications engine to use
def initialize(notifications_engine)
@notifications_engine = notifications_engine
end
# Sends a GraphQL tracing event to the notification handler
#
# @example
# . notifications_engine = Dry::Monitor::Notifications.new(:graphql)
# . tracer = GraphQL::Tracing::NotificationsTracing.new(notifications_engine)
# . tracer.trace("lex") { ... }
#
# @param [string] key The key for the event
# @param [Hash] metadata The metadata for the event
# @yield The block to execute for the event
def trace(key, metadata, &blk)
prefixed_key = KEYS[key] || "#{key}.graphql"
# Cache the new keys while making sure not to induce a memory leak
if KEYS.size < MAX_KEYS_SIZE
KEYS[key] ||= prefixed_key
end
@notifications_engine.instrument(prefixed_key, metadata, &blk)
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/tracing/prometheus_trace/graphql_collector.rb | lib/graphql/tracing/prometheus_trace/graphql_collector.rb | # frozen_string_literal: true
require "graphql/tracing"
module GraphQL
module Tracing
module PrometheusTrace
class GraphQLCollector < ::PrometheusExporter::Server::TypeCollector
def initialize
@graphql_gauge = PrometheusExporter::Metric::Base.default_aggregation.new(
'graphql_duration_seconds',
'Time spent in GraphQL operations, in seconds'
)
end
def type
'graphql'
end
def collect(object)
default_labels = { key: object['key'], platform_key: object['platform_key'] }
custom = object['custom_labels']
labels = custom.nil? ? default_labels : default_labels.merge(custom)
@graphql_gauge.observe object['duration'], labels
end
def metrics
[@graphql_gauge]
end
end
end
# Backwards-compat:
PrometheusTracing::GraphQLCollector = PrometheusTrace::GraphQLCollector
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/tracing/detailed_trace/redis_backend.rb | lib/graphql/tracing/detailed_trace/redis_backend.rb | # frozen_string_literal: true
module GraphQL
module Tracing
class DetailedTrace
class RedisBackend
KEY_PREFIX = "gql:trace:"
def initialize(redis:, limit: nil)
@redis = redis
@key = KEY_PREFIX + "traces"
@remrangebyrank_limit = limit ? -limit - 1 : nil
end
def traces(last:, before:)
before = case before
when Numeric
"(#{before}"
when nil
"+inf"
end
str_pairs = @redis.zrange(@key, before, 0, byscore: true, rev: true, limit: [0, last || 100], withscores: true)
str_pairs.map do |(str_data, score)|
entry_to_trace(score, str_data)
end
end
def delete_trace(id)
@redis.zremrangebyscore(@key, id, id)
nil
end
def delete_all_traces
@redis.del(@key)
end
def find_trace(id)
str_data = @redis.zrange(@key, id, id, byscore: true).first
if str_data.nil?
nil
else
entry_to_trace(id, str_data)
end
end
def save_trace(operation_name, duration_ms, begin_ms, trace_data)
id = begin_ms
data = JSON.dump({ "o" => operation_name, "d" => duration_ms, "b" => begin_ms, "t" => Base64.encode64(trace_data) })
@redis.pipelined do |pipeline|
pipeline.zadd(@key, id, data)
if @remrangebyrank_limit
pipeline.zremrangebyrank(@key, 0, @remrangebyrank_limit)
end
end
id
end
private
def entry_to_trace(id, json_str)
data = JSON.parse(json_str)
StoredTrace.new(
id: id,
operation_name: data["o"],
duration_ms: data["d"].to_f,
begin_ms: data["b"].to_i,
trace_data: Base64.decode64(data["t"]),
)
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/tracing/detailed_trace/memory_backend.rb | lib/graphql/tracing/detailed_trace/memory_backend.rb | # frozen_string_literal: true
module GraphQL
module Tracing
class DetailedTrace
# An in-memory trace storage backend. Suitable for testing and development only.
# It won't work for multi-process deployments and everything is erased when the app is restarted.
class MemoryBackend
def initialize(limit: nil)
@limit = limit
@traces = {}
@next_id = 0
end
def traces(last:, before:)
page = []
@traces.values.reverse_each do |trace|
if page.size == last
break
elsif before.nil? || trace.begin_ms < before
page << trace
end
end
page
end
def find_trace(id)
@traces[id]
end
def delete_trace(id)
@traces.delete(id.to_i)
nil
end
def delete_all_traces
@traces.clear
nil
end
def save_trace(operation_name, duration, begin_ms, trace_data)
id = @next_id
@next_id += 1
@traces[id] = DetailedTrace::StoredTrace.new(
id: id,
operation_name: operation_name,
duration_ms: duration,
begin_ms: begin_ms,
trace_data: trace_data
)
if @limit && @traces.size > @limit
del_keys = @traces.keys[0...-@limit]
del_keys.each { |k| @traces.delete(k) }
end
id
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/tracing/perfetto_trace/trace_pb.rb | lib/graphql/tracing/perfetto_trace/trace_pb.rb | # frozen_string_literal: true
# Generated by the protocol buffer compiler. DO NOT EDIT!
# source: trace.proto
require 'google/protobuf'
descriptor_data = "\n\x0btrace.proto\x12\x15perfetto_trace.protos\";\n\x05Trace\x12\x32\n\x06packet\x18\x01 \x03(\x0b\x32\".perfetto_trace.protos.TracePacket\"\x8a\x03\n\x0bTracePacket\x12\x11\n\ttimestamp\x18\x08 \x01(\x04\x12\x38\n\x0btrack_event\x18\x0b \x01(\x0b\x32!.perfetto_trace.protos.TrackEventH\x00\x12\x42\n\x10track_descriptor\x18< \x01(\x0b\x32&.perfetto_trace.protos.TrackDescriptorH\x00\x12$\n\x1atrusted_packet_sequence_id\x18\n \x01(\rH\x01\x12:\n\rinterned_data\x18\x0c \x01(\x0b\x32#.perfetto_trace.protos.InternedData\x12 \n\x18\x66irst_packet_on_sequence\x18W \x01(\x08\x12\x1f\n\x17previous_packet_dropped\x18* \x01(\x08\x12\x16\n\x0esequence_flags\x18\r \x01(\rB\x06\n\x04\x64\x61taB%\n#optional_trusted_packet_sequence_id\"\xf2\x04\n\nTrackEvent\x12\x15\n\rcategory_iids\x18\x03 \x03(\x04\x12\x12\n\ncategories\x18\x16 \x03(\t\x12\x12\n\x08name_iid\x18\n \x01(\x04H\x00\x12\x0e\n\x04name\x18\x17 \x01(\tH\x00\x12\x34\n\x04type\x18\t \x01(\x0e\x32&.perfetto_trace.protos.TrackEvent.Type\x12\x12\n\ntrack_uuid\x18\x0b \x01(\x04\x12\x17\n\rcounter_value\x18\x1e \x01(\x03H\x01\x12\x1e\n\x14\x64ouble_counter_value\x18, \x01(\x01H\x01\x12!\n\x19\x65xtra_counter_track_uuids\x18\x1f \x03(\x04\x12\x1c\n\x14\x65xtra_counter_values\x18\x0c \x03(\x03\x12(\n extra_double_counter_track_uuids\x18- \x03(\x04\x12#\n\x1b\x65xtra_double_counter_values\x18. \x03(\x01\x12\x10\n\x08\x66low_ids\x18/ \x03(\x06\x12\x1c\n\x14terminating_flow_ids\x18\x30 \x03(\x06\x12\x41\n\x11\x64\x65\x62ug_annotations\x18\x04 \x03(\x0b\x32&.perfetto_trace.protos.DebugAnnotation\"j\n\x04Type\x12\x14\n\x10TYPE_UNSPECIFIED\x10\x00\x12\x14\n\x10TYPE_SLICE_BEGIN\x10\x01\x12\x12\n\x0eTYPE_SLICE_END\x10\x02\x12\x10\n\x0cTYPE_INSTANT\x10\x03\x12\x10\n\x0cTYPE_COUNTER\x10\x04\x42\x0c\n\nname_fieldB\x15\n\x13\x63ounter_value_field\"\xd5\x02\n\x0f\x44\x65\x62ugAnnotation\x12\x12\n\x08name_iid\x18\x01 \x01(\x04H\x00\x12\x0e\n\x04name\x18\n \x01(\tH\x00\x12\x14\n\nbool_value\x18\x02 \x01(\x08H\x01\x12\x14\n\nuint_value\x18\x03 \x01(\x04H\x01\x12\x13\n\tint_value\x18\x04 \x01(\x03H\x01\x12\x16\n\x0c\x64ouble_value\x18\x05 \x01(\x01H\x01\x12\x16\n\x0cstring_value\x18\x06 \x01(\tH\x01\x12\x1a\n\x10string_value_iid\x18\x11 \x01(\x04H\x01\x12<\n\x0c\x64ict_entries\x18\x0b \x03(\x0b\x32&.perfetto_trace.protos.DebugAnnotation\x12<\n\x0c\x61rray_values\x18\x0c \x03(\x0b\x32&.perfetto_trace.protos.DebugAnnotationB\x0c\n\nname_fieldB\x07\n\x05value\"\xe1\x02\n\x0fTrackDescriptor\x12\x0c\n\x04uuid\x18\x01 \x01(\x04\x12\x13\n\x0bparent_uuid\x18\x05 \x01(\x04\x12\x0e\n\x04name\x18\x02 \x01(\tH\x00\x12\x39\n\x07\x63ounter\x18\x08 \x01(\x0b\x32(.perfetto_trace.protos.CounterDescriptor\x12R\n\x0e\x63hild_ordering\x18\x0b \x01(\x0e\x32:.perfetto_trace.protos.TrackDescriptor.ChildTracksOrdering\x12\x1a\n\x12sibling_order_rank\x18\x0c \x01(\x05\"V\n\x13\x43hildTracksOrdering\x12\x0b\n\x07UNKNOWN\x10\x00\x12\x11\n\rLEXICOGRAPHIC\x10\x01\x12\x11\n\rCHRONOLOGICAL\x10\x02\x12\x0c\n\x08\x45XPLICIT\x10\x03\x42\x18\n\x16static_or_dynamic_name\"\xb9\x03\n\x11\x43ounterDescriptor\x12I\n\x04type\x18\x01 \x01(\x0e\x32;.perfetto_trace.protos.CounterDescriptor.BuiltinCounterType\x12\x12\n\ncategories\x18\x02 \x03(\t\x12;\n\x04unit\x18\x03 \x01(\x0e\x32-.perfetto_trace.protos.CounterDescriptor.Unit\x12\x11\n\tunit_name\x18\x06 \x01(\t\x12\x17\n\x0funit_multiplier\x18\x04 \x01(\x03\x12\x16\n\x0eis_incremental\x18\x05 \x01(\x08\"o\n\x12\x42uiltinCounterType\x12\x17\n\x13\x43OUNTER_UNSPECIFIED\x10\x00\x12\x1a\n\x16\x43OUNTER_THREAD_TIME_NS\x10\x01\x12$\n COUNTER_THREAD_INSTRUCTION_COUNT\x10\x02\"S\n\x04Unit\x12\x14\n\x10UNIT_UNSPECIFIED\x10\x00\x12\x10\n\x0cUNIT_TIME_NS\x10\x01\x12\x0e\n\nUNIT_COUNT\x10\x02\x12\x13\n\x0fUNIT_SIZE_BYTES\x10\x03\"\xa0\x02\n\x0cInternedData\x12>\n\x10\x65vent_categories\x18\x01 \x03(\x0b\x32$.perfetto_trace.protos.EventCategory\x12\x35\n\x0b\x65vent_names\x18\x02 \x03(\x0b\x32 .perfetto_trace.protos.EventName\x12J\n\x16\x64\x65\x62ug_annotation_names\x18\x03 \x03(\x0b\x32*.perfetto_trace.protos.DebugAnnotationName\x12M\n\x1e\x64\x65\x62ug_annotation_string_values\x18\x1d \x03(\x0b\x32%.perfetto_trace.protos.InternedString\"*\n\x0eInternedString\x12\x0b\n\x03iid\x18\x01 \x01(\x04\x12\x0b\n\x03str\x18\x02 \x01(\x0c\"*\n\rEventCategory\x12\x0b\n\x03iid\x18\x01 \x01(\x04\x12\x0c\n\x04name\x18\x02 \x01(\t\"&\n\tEventName\x12\x0b\n\x03iid\x18\x01 \x01(\x04\x12\x0c\n\x04name\x18\x02 \x01(\t\"0\n\x13\x44\x65\x62ugAnnotationName\x12\x0b\n\x03iid\x18\x01 \x01(\x04\x12\x0c\n\x04name\x18\x02 \x01(\tB\"\xea\x02\x1fGraphQL::Tracing::PerfettoTrace"
pool = Google::Protobuf::DescriptorPool.generated_pool
pool.add_serialized_file(descriptor_data)
module GraphQL
module Tracing
module PerfettoTrace
Trace = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.Trace").msgclass
TracePacket = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.TracePacket").msgclass
TrackEvent = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.TrackEvent").msgclass
TrackEvent::Type = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.TrackEvent.Type").enummodule
DebugAnnotation = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.DebugAnnotation").msgclass
TrackDescriptor = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.TrackDescriptor").msgclass
TrackDescriptor::ChildTracksOrdering = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.TrackDescriptor.ChildTracksOrdering").enummodule
CounterDescriptor = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.CounterDescriptor").msgclass
CounterDescriptor::BuiltinCounterType = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.CounterDescriptor.BuiltinCounterType").enummodule
CounterDescriptor::Unit = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.CounterDescriptor.Unit").enummodule
InternedData = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.InternedData").msgclass
InternedString = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.InternedString").msgclass
EventCategory = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.EventCategory").msgclass
EventName = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.EventName").msgclass
DebugAnnotationName = ::Google::Protobuf::DescriptorPool.generated_pool.lookup("perfetto_trace.protos.DebugAnnotationName").msgclass
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/static_validation/base_visitor.rb | lib/graphql/static_validation/base_visitor.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class BaseVisitor < GraphQL::Language::StaticVisitor
def initialize(document, context)
@path = []
@object_types = []
@directives = []
@field_definitions = []
@argument_definitions = []
@directive_definitions = []
@context = context
@types = context.query.types
@schema = context.schema
super(document)
end
attr_reader :context
# @return [Array<GraphQL::ObjectType>] Types whose scope we've entered
attr_reader :object_types
# @return [Array<String>] The nesting of the current position in the AST
def path
@path.dup
end
# Build a class to visit the AST and perform validation,
# or use a pre-built class if rules is `ALL_RULES` or empty.
# @param rules [Array<Module, Class>]
# @return [Class] A class for validating `rules` during visitation
def self.including_rules(rules)
if rules.empty?
# It's not doing _anything?!?_
BaseVisitor
elsif rules == ALL_RULES
InterpreterVisitor
else
visitor_class = Class.new(self) do
include(GraphQL::StaticValidation::DefinitionDependencies)
end
rules.reverse_each do |r|
# If it's a class, it gets attached later.
if !r.is_a?(Class)
visitor_class.include(r)
end
end
visitor_class.include(ContextMethods)
visitor_class
end
end
module ContextMethods
def on_operation_definition(node, parent)
object_type = @schema.root_type_for_operation(node.operation_type)
push_type(object_type)
@path.push("#{node.operation_type}#{node.name ? " #{node.name}" : ""}")
super
@object_types.pop
@path.pop
end
def on_fragment_definition(node, parent)
on_fragment_with_type(node) do
@path.push("fragment #{node.name}")
super
end
end
def on_inline_fragment(node, parent)
on_fragment_with_type(node) do
@path.push("...#{node.type ? " on #{node.type.to_query_string}" : ""}")
super
end
end
def on_field(node, parent)
parent_type = @object_types.last
field_definition = @types.field(parent_type, node.name)
@field_definitions.push(field_definition)
if !field_definition.nil?
next_object_type = field_definition.type.unwrap
push_type(next_object_type)
else
push_type(nil)
end
@path.push(node.alias || node.name)
super
@field_definitions.pop
@object_types.pop
@path.pop
end
def on_directive(node, parent)
directive_defn = @context.schema_directives[node.name]
@directive_definitions.push(directive_defn)
super
@directive_definitions.pop
end
def on_argument(node, parent)
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)
super
@argument_definitions.pop
@path.pop
end
def on_fragment_spread(node, parent)
@path.push("... #{node.name}")
super
@path.pop
end
def on_input_object(node, parent)
arg_defn = @argument_definitions.last
if arg_defn && arg_defn.type.list?
@path.push(parent.children.index(node))
super
@path.pop
else
super
end
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::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
# Don't get the _last_ one because that's the current one.
# Get the second-to-last one, which is the parent of the current one.
@argument_definitions[-2]
end
private
def on_fragment_with_type(node)
object_type = if node.type
@types.type(node.type.name)
else
@object_types.last
end
push_type(object_type)
yield(node)
@object_types.pop
@path.pop
end
def push_type(t)
@object_types.push(t)
end
end
private
def add_error(error, path: nil)
if @context.too_many_errors?
throw :too_many_validation_errors
end
error.path ||= (path || @path.dup)
context.errors << error
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/static_validation/literal_validator.rb | lib/graphql/static_validation/literal_validator.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# Test whether `ast_value` is a valid input for `type`
class LiteralValidator
def initialize(context:)
@context = context
@types = context.types
@invalid_response = GraphQL::Query::InputValidationResult.new(valid: false, problems: [])
@valid_response = GraphQL::Query::InputValidationResult.new(valid: true, problems: [])
end
def validate(ast_value, type)
catch(:invalid) do
recursively_validate(ast_value, type)
end
end
private
def replace_nulls_in(ast_value)
case ast_value
when Array
ast_value.map { |v| replace_nulls_in(v) }
when GraphQL::Language::Nodes::InputObject
ast_value.to_h
when GraphQL::Language::Nodes::NullValue
nil
else
ast_value
end
end
def recursively_validate(ast_value, type)
if type.nil?
# this means we're an undefined argument, see #present_input_field_values_are_valid
maybe_raise_if_invalid(ast_value) do
@invalid_response
end
elsif ast_value.is_a?(GraphQL::Language::Nodes::NullValue)
maybe_raise_if_invalid(ast_value) do
type.kind.non_null? ? @invalid_response : @valid_response
end
elsif type.kind.non_null?
maybe_raise_if_invalid(ast_value) do
ast_value.nil? ?
@invalid_response :
recursively_validate(ast_value, type.of_type)
end
elsif type.kind.list?
item_type = type.of_type
results = ensure_array(ast_value).map { |val| recursively_validate(val, item_type) }
merge_results(results)
elsif ast_value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
@valid_response
elsif type.kind.scalar? && constant_scalar?(ast_value)
maybe_raise_if_invalid(ast_value) do
ruby_value = replace_nulls_in(ast_value)
type.validate_input(ruby_value, @context)
end
elsif type.kind.enum?
maybe_raise_if_invalid(ast_value) do
if ast_value.is_a?(GraphQL::Language::Nodes::Enum)
type.validate_input(ast_value.name, @context)
else
# if our ast_value isn't an Enum it's going to be invalid so return false
@invalid_response
end
end
elsif type.kind.input_object? && ast_value.is_a?(GraphQL::Language::Nodes::InputObject)
maybe_raise_if_invalid(ast_value) do
merge_results([
required_input_fields_are_present(type, ast_value),
present_input_field_values_are_valid(type, ast_value)
])
end
else
maybe_raise_if_invalid(ast_value) do
@invalid_response
end
end
end
# When `error_bubbling` is false, we want to bail on the first failure that we find.
# Use `throw` to escape the current call stack, returning the invalid response.
def maybe_raise_if_invalid(ast_value)
ret = yield
if !@context.schema.error_bubbling && !ret.valid?
throw(:invalid, ret)
else
ret
end
end
# The GraphQL grammar supports variables embedded within scalars but graphql.js
# doesn't support it so we won't either for simplicity
def constant_scalar?(ast_value)
if ast_value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
false
elsif ast_value.is_a?(Array)
ast_value.all? { |element| constant_scalar?(element) }
elsif ast_value.is_a?(GraphQL::Language::Nodes::InputObject)
ast_value.arguments.all? { |arg| constant_scalar?(arg.value) }
else
true
end
end
def required_input_fields_are_present(type, ast_node)
# TODO - would be nice to use these to create an error message so the caller knows
# that required fields are missing
required_field_names = @types.arguments(type)
.select { |argument| argument.type.kind.non_null? && !argument.default_value? }
.map!(&:name)
present_field_names = ast_node.arguments.map(&:name)
missing_required_field_names = required_field_names - present_field_names
if @context.schema.error_bubbling
missing_required_field_names.empty? ? @valid_response : @invalid_response
else
results = missing_required_field_names.map do |name|
arg_type = @types.argument(type, name).type
recursively_validate(GraphQL::Language::Nodes::NullValue.new(name: name), arg_type)
end
if type.one_of? && ast_node.arguments.size != 1
results << Query::InputValidationResult.from_problem("`#{type.graphql_name}` is a OneOf type, so only one argument may be given (instead of #{ast_node.arguments.size})")
end
merge_results(results)
end
end
def present_input_field_values_are_valid(type, ast_node)
results = ast_node.arguments.map do |value|
field = @types.argument(type, value.name)
# we want to call validate on an argument even if it's an invalid one
# so that our raise exception is on it instead of the entire InputObject
field_type = field && field.type
recursively_validate(value.value, field_type)
end
merge_results(results)
end
def ensure_array(value)
value.is_a?(Array) ? value : [value]
end
def merge_results(results_list)
merged_result = Query::InputValidationResult.new
results_list.each do |inner_result|
merged_result.merge_result!([], inner_result)
end
merged_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/static_validation/validation_context.rb | lib/graphql/static_validation/validation_context.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# The validation context gets passed to each validator.
#
# It exposes a {GraphQL::Language::Visitor} where validators may add hooks. ({Language::Visitor#visit} is called in {Validator#validate})
#
# It provides access to the schema & fragments which validators may read from.
#
# It holds a list of errors which each validator may add to.
class ValidationContext
extend Forwardable
attr_reader :query, :errors, :visitor,
:on_dependency_resolve_handlers,
:max_errors, :types, :schema
def_delegators :@query, :document, :fragments, :operations
def initialize(query, visitor_class, max_errors)
@query = query
@types = query.types # TODO update migrated callers to use this accessor
@schema = query.schema
@literal_validator = LiteralValidator.new(context: query.context)
@errors = []
@max_errors = max_errors || Float::INFINITY
@on_dependency_resolve_handlers = []
@visitor = visitor_class.new(document, self)
end
# TODO stop using def_delegators because of Array allocations
def_delegators :@visitor,
:path, :type_definition, :field_definition, :argument_definition,
:parent_type_definition, :directive_definition, :object_types, :dependencies
def on_dependency_resolve(&handler)
@on_dependency_resolve_handlers << handler
end
def validate_literal(ast_value, type)
@literal_validator.validate(ast_value, type)
end
def too_many_errors?
@errors.length >= @max_errors
end
def schema_directives
@schema_directives ||= schema.directives
end
def did_you_mean_suggestion(name, options)
if did_you_mean = schema.did_you_mean
suggestions = did_you_mean::SpellChecker.new(dictionary: options).correct(name)
case suggestions.size
when 0
""
when 1
" (Did you mean `#{suggestions.first}`?)"
else
last_sugg = suggestions.pop
" (Did you mean #{suggestions.map {|s| "`#{s}`"}.join(", ")} or `#{last_sugg}`?)"
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/static_validation/definition_dependencies.rb | lib/graphql/static_validation/definition_dependencies.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# Track fragment dependencies for operations
# and expose the fragment definitions which
# are used by a given operation
module DefinitionDependencies
attr_reader :dependencies
def initialize(*)
super
@defdep_node_paths = {}
# { name => [node, ...] } pairs for fragments (although duplicate-named fragments are _invalid_, they are _possible_)
@defdep_fragment_definitions = Hash.new{ |h, k| h[k] = [] }
# This tracks dependencies from fragment to Node where it was used
# { fragment_definition_name => [dependent_node, dependent_node]}
@defdep_dependent_definitions = Hash.new { |h, k| h[k] = Set.new }
# First-level usages of spreads within definitions
# (When a key has an empty list as its value,
# we can resolve that key's dependents)
# { definition_node => [node, node ...] }
@defdep_immediate_dependencies = Hash.new { |h, k| h[k] = Set.new }
# When we encounter a spread,
# this node is the one who depends on it
@defdep_current_parent = nil
end
def on_document(node, parent)
node.definitions.each do |definition|
if definition.is_a? GraphQL::Language::Nodes::FragmentDefinition
@defdep_fragment_definitions[definition.name] << definition
end
end
super
@dependencies = dependency_map { |defn, spreads, frag|
context.on_dependency_resolve_handlers.each { |h| h.call(defn, spreads, frag) }
}
end
def on_operation_definition(node, prev_node)
@defdep_node_paths[node.name] = NodeWithPath.new(node, context.path)
@defdep_current_parent = node
super
@defdep_current_parent = nil
end
def on_fragment_definition(node, parent)
@defdep_node_paths[node] = NodeWithPath.new(node, context.path)
@defdep_current_parent = node
super
@defdep_current_parent = nil
end
def on_fragment_spread(node, parent)
@defdep_node_paths[node] = NodeWithPath.new(node, context.path)
# Track both sides of the dependency
@defdep_dependent_definitions[node.name] << @defdep_current_parent
@defdep_immediate_dependencies[@defdep_current_parent] << node
super
end
# A map of operation definitions to an array of that operation's dependencies
# @return [DependencyMap]
def dependency_map(&block)
@dependency_map ||= resolve_dependencies(&block)
end
# Map definition AST nodes to the definition AST nodes they depend on.
# Expose circular dependencies.
class DependencyMap
# @return [Array<GraphQL::Language::Nodes::FragmentDefinition>]
attr_reader :cyclical_definitions
# @return [Hash<Node, Array<GraphQL::Language::Nodes::FragmentSpread>>]
attr_reader :unmet_dependencies
# @return [Array<GraphQL::Language::Nodes::FragmentDefinition>]
attr_reader :unused_dependencies
def initialize
@dependencies = Hash.new { |h, k| h[k] = [] }
@cyclical_definitions = []
@unmet_dependencies = Hash.new { |h, k| h[k] = [] }
@unused_dependencies = []
end
# @return [Array<GraphQL::Language::Nodes::AbstractNode>] dependencies for `definition_node`
def [](definition_node)
@dependencies[definition_node]
end
end
class NodeWithPath
extend Forwardable
attr_reader :node, :path
def initialize(node, path)
@node = node
@path = path
end
def_delegators :@node, :name, :eql?, :hash
end
private
# Return a hash of { node => [node, node ... ]} pairs
# Keys are top-level definitions
# Values are arrays of flattened dependencies
def resolve_dependencies
dependency_map = DependencyMap.new
# Don't allow the loop to run more times
# than the number of fragments in the document
max_loops = 0
@defdep_fragment_definitions.each_value do |v|
max_loops += v.size
end
loops = 0
# Instead of tracking independent fragments _as you visit_,
# determine them at the end. This way, we can treat fragments with the
# same name as if they were the same name. If _any_ of the fragments
# with that name has a dependency, we record it.
independent_fragment_nodes = @defdep_fragment_definitions.values.flatten - @defdep_immediate_dependencies.keys
visited_fragment_names = Set.new
while fragment_node = independent_fragment_nodes.pop
if visited_fragment_names.add?(fragment_node.name)
# this is a new fragment name
else
# this is a duplicate fragment name
next
end
loops += 1
if loops > max_loops
raise("Resolution loops exceeded the number of definitions; infinite loop detected. (Max: #{max_loops}, Current: #{loops})")
end
# Since it's independent, let's remove it from here.
# That way, we can use the remainder to identify cycles
@defdep_immediate_dependencies.delete(fragment_node)
fragment_usages = @defdep_dependent_definitions[fragment_node.name]
if fragment_usages.empty?
# If we didn't record any usages during the visit,
# then this fragment is unused.
dependency_map.unused_dependencies << @defdep_node_paths[fragment_node]
else
fragment_usages.each do |definition_node|
# Register the dependency AND second-order dependencies
dependency_map[definition_node] << fragment_node
dependency_map[definition_node].concat(dependency_map[fragment_node])
# Since we've registered it, remove it from our to-do list
deps = @defdep_immediate_dependencies[definition_node]
# Can't find a way to _just_ delete from `deps` and return the deleted entries
removed, remaining = deps.partition { |spread| spread.name == fragment_node.name }
@defdep_immediate_dependencies[definition_node] = remaining
if block_given?
yield(definition_node, removed, fragment_node)
end
if remaining.empty? &&
definition_node.is_a?(GraphQL::Language::Nodes::FragmentDefinition) &&
definition_node.name != fragment_node.name
# If all of this definition's dependencies have
# been resolved, we can now resolve its
# own dependents.
#
# But, it's possible to have a duplicate-named fragment here.
# Skip it in that case
independent_fragment_nodes << definition_node
end
end
end
end
# If any dependencies were _unmet_
# (eg, spreads with no corresponding definition)
# then they're still in there
@defdep_immediate_dependencies.each do |defn_node, deps|
deps.each do |spread|
if !@defdep_fragment_definitions.key?(spread.name)
dependency_map.unmet_dependencies[@defdep_node_paths[defn_node]] << @defdep_node_paths[spread]
deps.delete(spread)
end
end
if deps.empty?
@defdep_immediate_dependencies.delete(defn_node)
end
end
# Anything left in @immediate_dependencies is cyclical
cyclical_nodes = @defdep_immediate_dependencies.keys.map { |n| @defdep_node_paths[n] }
# @immediate_dependencies also includes operation names, but we don't care about
# those. They became nil when we looked them up on `@fragment_definitions`, so remove them.
cyclical_nodes.compact!
dependency_map.cyclical_definitions.concat(cyclical_nodes)
dependency_map
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/static_validation/validator.rb | lib/graphql/static_validation/validator.rb | # frozen_string_literal: true
require "timeout"
module GraphQL
module StaticValidation
# Initialized with a {GraphQL::Schema}, then it can validate {GraphQL::Language::Nodes::Documents}s based on that schema.
#
# By default, it's used by {GraphQL::Query}
#
# @example Validate a query
# validator = GraphQL::StaticValidation::Validator.new(schema: MySchema)
# query = GraphQL::Query.new(MySchema, query_string)
# errors = validator.validate(query)[:errors]
#
class Validator
# @param schema [GraphQL::Schema]
# @param rules [Array<#validate(context)>] a list of rules to use when validating
def initialize(schema:, rules: GraphQL::StaticValidation::ALL_RULES)
@schema = schema
@rules = rules
end
# Validate `query` against the schema. Returns an array of message hashes.
# @param query [GraphQL::Query]
# @param validate [Boolean]
# @param timeout [Float] Number of seconds to wait before aborting validation. Any positive number may be used, including Floats to specify fractional seconds.
# @param max_errors [Integer] Maximum number of errors before aborting validation. Any positive number will limit the number of errors. Defaults to nil for no limit.
# @return [Array<Hash>]
def validate(query, validate: true, timeout: nil, max_errors: nil)
errors = nil
query.current_trace.begin_validate(query, validate)
query.current_trace.validate(validate: validate, query: query) do
begin_t = Time.now
errors = if validate == false
[]
else
rules_to_use = validate ? @rules : []
visitor_class = BaseVisitor.including_rules(rules_to_use)
context = GraphQL::StaticValidation::ValidationContext.new(query, visitor_class, max_errors)
begin
# CAUTION: Usage of the timeout module makes the assumption that validation rules are stateless Ruby code that requires no cleanup if process was interrupted. This means no blocking IO calls, native gems, locks, or `rescue` clauses that must be reached.
# A timeout value of 0 or nil will execute the block without any timeout.
Timeout::timeout(timeout) do
catch(:too_many_validation_errors) do
context.visitor.visit
end
end
rescue Timeout::Error
handle_timeout(query, context)
end
context.errors
end
{
remaining_timeout: timeout ? (timeout - (Time.now - begin_t)) : nil,
errors: errors,
}
end
rescue GraphQL::ExecutionError => e
errors = [e]
{
remaining_timeout: nil,
errors: errors,
}
ensure
query.current_trace.end_validate(query, validate, errors)
end
# Invoked when static validation times out.
# @param query [GraphQL::Query]
# @param context [GraphQL::StaticValidation::ValidationContext]
def handle_timeout(query, context)
context.errors << GraphQL::StaticValidation::ValidationTimeoutError.new(
"Timeout on validation of query"
)
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/static_validation/interpreter_visitor.rb | lib/graphql/static_validation/interpreter_visitor.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class InterpreterVisitor < BaseVisitor
include(GraphQL::StaticValidation::DefinitionDependencies)
StaticValidation::ALL_RULES.reverse_each do |r|
include(r)
end
include(ContextMethods)
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/static_validation/validation_timeout_error.rb | lib/graphql/static_validation/validation_timeout_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class ValidationTimeoutError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code
}
super.merge({
"extensions" => extensions
})
end
def code
"validationTimeout"
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/static_validation/all_rules.rb | lib/graphql/static_validation/all_rules.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# Default rules for {GraphQL::StaticValidation::Validator}
#
# Order is important here. Some validators skip later hooks.
# which stops the visit on that node. That way it doesn't try to find fields on types that
# don't exist, etc.
ALL_RULES = [
GraphQL::StaticValidation::NoDefinitionsArePresent,
GraphQL::StaticValidation::DirectivesAreDefined,
GraphQL::StaticValidation::DirectivesAreInValidLocations,
GraphQL::StaticValidation::UniqueDirectivesPerLocation,
GraphQL::StaticValidation::OperationNamesAreValid,
GraphQL::StaticValidation::FragmentNamesAreUnique,
GraphQL::StaticValidation::FragmentsAreFinite,
GraphQL::StaticValidation::FragmentsAreNamed,
GraphQL::StaticValidation::FragmentsAreUsed,
GraphQL::StaticValidation::FragmentTypesExist,
GraphQL::StaticValidation::FragmentsAreOnCompositeTypes,
GraphQL::StaticValidation::FragmentSpreadsArePossible,
GraphQL::StaticValidation::FieldsAreDefinedOnType,
GraphQL::StaticValidation::FieldsWillMerge,
GraphQL::StaticValidation::FieldsHaveAppropriateSelections,
GraphQL::StaticValidation::ArgumentsAreDefined,
GraphQL::StaticValidation::ArgumentLiteralsAreCompatible,
GraphQL::StaticValidation::RequiredArgumentsArePresent,
GraphQL::StaticValidation::RequiredInputObjectAttributesArePresent,
GraphQL::StaticValidation::ArgumentNamesAreUnique,
GraphQL::StaticValidation::VariableNamesAreUnique,
GraphQL::StaticValidation::VariablesAreInputTypes,
GraphQL::StaticValidation::VariableDefaultValuesAreCorrectlyTyped,
GraphQL::StaticValidation::VariablesAreUsedAndDefined,
GraphQL::StaticValidation::VariableUsagesAreAllowed,
GraphQL::StaticValidation::MutationRootExists,
GraphQL::StaticValidation::QueryRootExists,
GraphQL::StaticValidation::SubscriptionRootExistsAndSingleSubscriptionSelection,
GraphQL::StaticValidation::InputObjectNamesAreUnique,
GraphQL::StaticValidation::OneOfInputObjectsAreValid,
].freeze
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/static_validation/error.rb | lib/graphql/static_validation/error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# Generates GraphQL-compliant validation message.
class Error
# Convenience for validators
module ErrorHelper
# Error `error_message` is located at `node`
def error(error_message, nodes, context: nil, path: nil, extensions: {})
path ||= context.path
nodes = Array(nodes)
GraphQL::StaticValidation::Error.new(error_message, nodes: nodes, path: path)
end
end
attr_reader :message
attr_accessor :path
def initialize(message, path: nil, nodes: [])
@message = message
@nodes = Array(nodes)
@path = path
end
# A hash representation of this Message
def to_h
{
"message" => message,
"locations" => locations
}.tap { |h| h["path"] = path unless path.nil? }
end
attr_reader :nodes
private
def locations
nodes.map do |node|
h = {"line" => node.line, "column" => node.col}
h["filename"] = node.filename if node.filename
h
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/static_validation/rules/variable_names_are_unique.rb | lib/graphql/static_validation/rules/variable_names_are_unique.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module VariableNamesAreUnique
def on_operation_definition(node, parent)
var_defns = node.variables
if !var_defns.empty?
vars_by_name = Hash.new { |h, k| h[k] = [] }
var_defns.each { |v| vars_by_name[v.name] << v }
vars_by_name.each do |name, defns|
if defns.size > 1
add_error(GraphQL::StaticValidation::VariableNamesAreUniqueError.new(
"There can only be one variable named \"#{name}\"",
nodes: defns,
name: name
))
end
end
end
super
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/static_validation/rules/variables_are_used_and_defined_error.rb | lib/graphql/static_validation/rules/variables_are_used_and_defined_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class VariablesAreUsedAndDefinedError < StaticValidation::Error
attr_reader :variable_name
attr_reader :violation
VIOLATIONS = {
:VARIABLE_NOT_USED => "variableNotUsed",
:VARIABLE_NOT_DEFINED => "variableNotDefined",
}
def initialize(message, path: nil, nodes: [], name:, error_type:)
super(message, path: path, nodes: nodes)
@variable_name = name
raise("Unexpected error type: #{error_type}") if !VIOLATIONS.values.include?(error_type)
@violation = error_type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"variableName" => variable_name
}
super.merge({
"extensions" => extensions
})
end
def code
@violation
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/static_validation/rules/argument_literals_are_compatible.rb | lib/graphql/static_validation/rules/argument_literals_are_compatible.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module ArgumentLiteralsAreCompatible
def on_argument(node, parent)
# Check the child arguments first;
# don't add a new error if one of them reports an error
super
# Don't validate variables here
if node.value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
return
end
if @context.schema.error_bubbling || context.errors.none? { |err| err.path.take(@path.size) == @path }
parent_defn = parent_definition(parent)
if parent_defn && (arg_defn = @types.argument(parent_defn, node.name))
validation_result = context.validate_literal(node.value, arg_defn.type)
if !validation_result.valid?
kind_of_node = node_type(parent)
error_arg_name = parent_name(parent, parent_defn)
string_value = if node.value == Float::INFINITY
""
else
" (#{GraphQL::Language::Printer.new.print(node.value)})"
end
problems = validation_result.problems
first_problem = problems && problems.first
if first_problem
message = first_problem["message"]
# This is some legacy stuff from when `CoercionError` was raised thru the stack
if message
coerce_extensions = first_problem["extensions"] || {
"code" => "argumentLiteralsIncompatible"
}
end
end
error_options = {
nodes: parent,
type: kind_of_node,
argument_name: node.name,
argument: arg_defn,
value: node.value
}
if coerce_extensions
error_options[:coerce_extensions] = coerce_extensions
end
message ||= "Argument '#{node.name}' on #{kind_of_node} '#{error_arg_name}' has an invalid value#{string_value}. Expected type '#{arg_defn.type.to_type_signature}'."
error = GraphQL::StaticValidation::ArgumentLiteralsAreCompatibleError.new(
message,
**error_options
)
add_error(error)
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/static_validation/rules/arguments_are_defined_error.rb | lib/graphql/static_validation/rules/arguments_are_defined_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class ArgumentsAreDefinedError < StaticValidation::Error
attr_reader :name
attr_reader :type_name
attr_reader :argument_name
attr_reader :parent
def initialize(message, path: nil, nodes: [], name:, type:, argument_name:, parent:)
super(message, path: path, nodes: nodes)
@name = name
@type_name = type
@argument_name = argument_name
@parent = parent
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"name" => name,
"typeName" => type_name,
"argumentName" => argument_name
}
super.merge({
"extensions" => extensions
})
end
def code
"argumentNotAccepted"
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/static_validation/rules/fragment_spreads_are_possible.rb | lib/graphql/static_validation/rules/fragment_spreads_are_possible.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentSpreadsArePossible
def initialize(*)
super
@spreads_to_validate = []
end
def on_inline_fragment(node, parent)
fragment_parent = context.object_types[-2]
fragment_child = context.object_types.last
if fragment_child
validate_fragment_in_scope(fragment_parent, fragment_child, node, context, context.path)
end
super
end
def on_fragment_spread(node, parent)
fragment_parent = context.object_types.last
@spreads_to_validate << FragmentSpread.new(node: node, parent_type: fragment_parent, path: context.path)
super
end
def on_document(node, parent)
super
@spreads_to_validate.each do |frag_spread|
frag_node = context.fragments[frag_spread.node.name]
if frag_node
fragment_child_name = frag_node.type.name
fragment_child = @types.type(fragment_child_name)
# Might be non-existent type name
if fragment_child
validate_fragment_in_scope(frag_spread.parent_type, fragment_child, frag_spread.node, context, frag_spread.path)
end
end
end
end
private
def validate_fragment_in_scope(parent_type, child_type, node, context, path)
if !child_type.kind.fields?
# It's not a valid fragment type, this error was handled someplace else
return
end
parent_types = @types.possible_types(parent_type.unwrap)
child_types = @types.possible_types(child_type.unwrap)
if child_types.none? { |c| parent_types.include?(c) }
name = node.respond_to?(:name) ? " #{node.name}" : ""
add_error(GraphQL::StaticValidation::FragmentSpreadsArePossibleError.new(
"Fragment#{name} on #{child_type.graphql_name} can't be spread inside #{parent_type.graphql_name}",
nodes: node,
path: path,
fragment_name: name.empty? ? "unknown" : name,
type: child_type.graphql_name,
parent: parent_type.graphql_name
))
end
end
class FragmentSpread
attr_reader :node, :parent_type, :path
def initialize(node:, parent_type:, path:)
@node = node
@parent_type = parent_type
@path = 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/static_validation/rules/fields_have_appropriate_selections.rb | lib/graphql/static_validation/rules/fields_have_appropriate_selections.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# Scalars _can't_ have selections
# Objects _must_ have selections
module FieldsHaveAppropriateSelections
include GraphQL::StaticValidation::Error::ErrorHelper
def on_field(node, parent)
field_defn = field_definition
if validate_field_selections(node, field_defn.type.unwrap)
super
end
end
def on_operation_definition(node, _parent)
if validate_field_selections(node, type_definition)
super
end
end
private
def validate_field_selections(ast_node, resolved_type)
msg = if resolved_type.nil?
nil
elsif resolved_type.kind.leaf?
if !ast_node.selections.empty?
selection_strs = ast_node.selections.map do |n|
case n
when GraphQL::Language::Nodes::InlineFragment
"\"... on #{n.type.name} { ... }\""
when GraphQL::Language::Nodes::Field
"\"#{n.name}\""
when GraphQL::Language::Nodes::FragmentSpread
"\"#{n.name}\""
else
raise "Invariant: unexpected selection node: #{n}"
end
end
"Selections can't be made on #{resolved_type.kind.name.sub("_", " ").downcase}s (%{node_name} returns #{resolved_type.graphql_name} but has selections [#{selection_strs.join(", ")}])"
else
nil
end
elsif ast_node.selections.empty?
return_validation_error = true
legacy_invalid_empty_selection_result = nil
if !resolved_type.kind.fields?
case @schema.allow_legacy_invalid_empty_selections_on_union
when true
legacy_invalid_empty_selection_result = @schema.legacy_invalid_empty_selections_on_union_with_type(@context.query, resolved_type)
case legacy_invalid_empty_selection_result
when :return_validation_error
# keep `return_validation_error = true`
when String
return_validation_error = false
# the string is returned below
when nil
# No error:
return_validation_error = false
legacy_invalid_empty_selection_result = nil
else
raise GraphQL::InvariantError, "Unexpected return value from legacy_invalid_empty_selections_on_union_with_type, must be `:return_validation_error`, String, or nil (got: #{legacy_invalid_empty_selection_result.inspect})"
end
when false
# pass -- error below
else
return_validation_error = false
@context.query.logger.warn("Unions require selections but #{ast_node.alias || ast_node.name} (#{resolved_type.graphql_name}) doesn't have any. This will fail with a validation error on a future GraphQL-Ruby version. More info: https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#allow_legacy_invalid_empty_selections_on_union-class_method")
end
end
if return_validation_error
"Field must have selections (%{node_name} returns #{resolved_type.graphql_name} but has no selections. Did you mean '#{ast_node.name} { ... }'?)"
else
legacy_invalid_empty_selection_result
end
else
nil
end
if msg
node_name = case ast_node
when GraphQL::Language::Nodes::Field
"field '#{ast_node.name}'"
when GraphQL::Language::Nodes::OperationDefinition
if ast_node.name.nil?
"anonymous query"
else
"#{ast_node.operation_type} '#{ast_node.name}'"
end
else
raise("Unexpected node #{ast_node}")
end
extensions = {
"rule": "StaticValidation::FieldsHaveAppropriateSelections",
"name": node_name.to_s
}
unless resolved_type.nil?
extensions["type"] = resolved_type.to_type_signature
end
add_error(GraphQL::StaticValidation::FieldsHaveAppropriateSelectionsError.new(
msg % { node_name: node_name },
nodes: ast_node,
node_name: node_name.to_s,
type: resolved_type.nil? ? nil : resolved_type.graphql_name,
))
false
else
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/static_validation/rules/operation_names_are_valid_error.rb | lib/graphql/static_validation/rules/operation_names_are_valid_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class OperationNamesAreValidError < StaticValidation::Error
attr_reader :operation_name
def initialize(message, path: nil, nodes: [], name: nil)
super(message, path: path, nodes: nodes)
@operation_name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code
}.tap { |h| h["operationName"] = operation_name unless operation_name.nil? }
super.merge({
"extensions" => extensions
})
end
def code
"uniquelyNamedOperations"
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/static_validation/rules/argument_names_are_unique_error.rb | lib/graphql/static_validation/rules/argument_names_are_unique_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class ArgumentNamesAreUniqueError < StaticValidation::Error
attr_reader :name
def initialize(message, path: nil, nodes: [], name:)
super(message, path: path, nodes: nodes)
@name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"name" => name
}
super.merge({
"extensions" => extensions
})
end
def code
"argumentNotUnique"
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/static_validation/rules/fields_are_defined_on_type_error.rb | lib/graphql/static_validation/rules/fields_are_defined_on_type_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FieldsAreDefinedOnTypeError < StaticValidation::Error
attr_reader :type_name
attr_reader :field_name
def initialize(message, path: nil, nodes: [], type:, field:)
super(message, path: path, nodes: nodes)
@type_name = type
@field_name = field
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"typeName" => type_name,
"fieldName" => field_name
}
super.merge({
"extensions" => extensions
})
end
def code
"undefinedField"
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/static_validation/rules/one_of_input_objects_are_valid.rb | lib/graphql/static_validation/rules/one_of_input_objects_are_valid.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module OneOfInputObjectsAreValid
def on_input_object(node, parent)
return super unless parent.is_a?(GraphQL::Language::Nodes::Argument)
parent_type = get_parent_type(context, parent)
return super unless parent_type && parent_type.kind.input_object? && parent_type.one_of?
validate_one_of_input_object(node, context, parent_type)
super
end
private
def validate_one_of_input_object(ast_node, context, parent_type)
present_fields = ast_node.arguments.map(&:name)
input_object_type = parent_type.to_type_signature
if present_fields.count != 1
add_error(
OneOfInputObjectsAreValidError.new(
"OneOf Input Object '#{input_object_type}' must specify exactly one key.",
path: context.path,
nodes: ast_node,
input_object_type: input_object_type
)
)
return
end
field = present_fields.first
value = ast_node.arguments.first.value
if value.is_a?(GraphQL::Language::Nodes::NullValue)
add_error(
OneOfInputObjectsAreValidError.new(
"Argument '#{input_object_type}.#{field}' must be non-null.",
path: [*context.path, field],
nodes: ast_node.arguments.first,
input_object_type: input_object_type
)
)
return
end
if value.is_a?(GraphQL::Language::Nodes::VariableIdentifier)
variable_name = value.name
variable_type = @declared_variables[variable_name].type
unless variable_type.is_a?(GraphQL::Language::Nodes::NonNullType)
add_error(
OneOfInputObjectsAreValidError.new(
"Variable '#{variable_name}' must be non-nullable to be used for OneOf Input Object '#{input_object_type}'.",
path: [*context.path, field],
nodes: ast_node,
input_object_type: input_object_type
)
)
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/static_validation/rules/variable_default_values_are_correctly_typed_error.rb | lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class VariableDefaultValuesAreCorrectlyTypedError < StaticValidation::Error
attr_reader :variable_name
attr_reader :type_name
attr_reader :violation
VIOLATIONS = {
:INVALID_TYPE => "defaultValueInvalidType",
:INVALID_ON_NON_NULL => "defaultValueInvalidOnNonNullVariable",
}
def initialize(message, path: nil, nodes: [], name:, type: nil, error_type:)
super(message, path: path, nodes: nodes)
@variable_name = name
@type_name = type
raise("Unexpected error type: #{error_type}") if !VIOLATIONS.values.include?(error_type)
@violation = error_type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"variableName" => variable_name
}.tap { |h| h["typeName"] = type_name unless type_name.nil? }
super.merge({
"extensions" => extensions
})
end
def code
@violation
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/static_validation/rules/required_arguments_are_present.rb | lib/graphql/static_validation/rules/required_arguments_are_present.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module RequiredArgumentsArePresent
def on_field(node, _parent)
assert_required_args(node, field_definition)
super
end
def on_directive(node, _parent)
directive_defn = context.schema_directives[node.name]
assert_required_args(node, directive_defn)
super
end
private
def assert_required_args(ast_node, defn)
args = @context.query.types.arguments(defn)
return if args.empty?
present_argument_names = ast_node.arguments.map(&:name)
required_argument_names = context.query.types.arguments(defn)
.select { |a| a.type.kind.non_null? && !a.default_value? && context.query.types.argument(defn, a.name) }
.map!(&:name)
missing_names = required_argument_names - present_argument_names
if !missing_names.empty?
add_error(GraphQL::StaticValidation::RequiredArgumentsArePresentError.new(
"#{ast_node.class.name.split("::").last} '#{ast_node.name}' is missing required arguments: #{missing_names.join(", ")}",
nodes: ast_node,
class_name: ast_node.class.name.split("::").last,
name: ast_node.name,
arguments: "#{missing_names.join(", ")}"
))
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/static_validation/rules/fragment_types_exist.rb | lib/graphql/static_validation/rules/fragment_types_exist.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentTypesExist
def on_fragment_definition(node, _parent)
if validate_type_exists(node)
super
end
end
def on_inline_fragment(node, _parent)
if validate_type_exists(node)
super
end
end
private
def validate_type_exists(fragment_node)
if !fragment_node.type
true
else
type_name = fragment_node.type.name
type = @types.type(type_name)
if type.nil?
@all_possible_fragment_type_names ||= begin
names = []
context.types.all_types.each do |type|
if type.kind.fields?
names << type.graphql_name
end
end
names
end
add_error(GraphQL::StaticValidation::FragmentTypesExistError.new(
"No such type #{type_name}, so it can't be a fragment condition#{context.did_you_mean_suggestion(type_name, @all_possible_fragment_type_names)}",
nodes: fragment_node,
type: type_name
))
false
else
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/static_validation/rules/directives_are_in_valid_locations.rb | lib/graphql/static_validation/rules/directives_are_in_valid_locations.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module DirectivesAreInValidLocations
include GraphQL::Language
def on_directive(node, parent)
validate_location(node, parent, context.schema_directives)
super
end
private
LOCATION_MESSAGE_NAMES = {
GraphQL::Schema::Directive::QUERY => "queries",
GraphQL::Schema::Directive::MUTATION => "mutations",
GraphQL::Schema::Directive::SUBSCRIPTION => "subscriptions",
GraphQL::Schema::Directive::FIELD => "fields",
GraphQL::Schema::Directive::FRAGMENT_DEFINITION => "fragment definitions",
GraphQL::Schema::Directive::FRAGMENT_SPREAD => "fragment spreads",
GraphQL::Schema::Directive::INLINE_FRAGMENT => "inline fragments",
GraphQL::Schema::Directive::VARIABLE_DEFINITION => "variable definitions",
}
SIMPLE_LOCATIONS = {
Nodes::Field => GraphQL::Schema::Directive::FIELD,
Nodes::InlineFragment => GraphQL::Schema::Directive::INLINE_FRAGMENT,
Nodes::FragmentSpread => GraphQL::Schema::Directive::FRAGMENT_SPREAD,
Nodes::FragmentDefinition => GraphQL::Schema::Directive::FRAGMENT_DEFINITION,
Nodes::VariableDefinition => GraphQL::Schema::Directive::VARIABLE_DEFINITION,
}
SIMPLE_LOCATION_NODES = SIMPLE_LOCATIONS.keys
def validate_location(ast_directive, ast_parent, directives)
directive_defn = directives[ast_directive.name]
case ast_parent
when Nodes::OperationDefinition
required_location = GraphQL::Schema::Directive.const_get(ast_parent.operation_type.upcase)
assert_includes_location(directive_defn, ast_directive, required_location)
when *SIMPLE_LOCATION_NODES
required_location = SIMPLE_LOCATIONS[ast_parent.class]
assert_includes_location(directive_defn, ast_directive, required_location)
else
add_error(GraphQL::StaticValidation::DirectivesAreInValidLocationsError.new(
"Directives can't be applied to #{ast_parent.class.name}s",
nodes: ast_directive,
target: ast_parent.class.name
))
end
end
def assert_includes_location(directive_defn, directive_ast, required_location)
if !directive_defn.locations.include?(required_location)
location_name = LOCATION_MESSAGE_NAMES[required_location]
allowed_location_names = directive_defn.locations.map { |loc| LOCATION_MESSAGE_NAMES[loc] }
add_error(GraphQL::StaticValidation::DirectivesAreInValidLocationsError.new(
"'@#{directive_defn.graphql_name}' can't be applied to #{location_name} (allowed: #{allowed_location_names.join(", ")})",
nodes: directive_ast,
target: location_name,
name: directive_defn.graphql_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/static_validation/rules/fragment_spreads_are_possible_error.rb | lib/graphql/static_validation/rules/fragment_spreads_are_possible_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentSpreadsArePossibleError < StaticValidation::Error
attr_reader :type_name
attr_reader :fragment_name
attr_reader :parent_name
def initialize(message, path: nil, nodes: [], type:, fragment_name:, parent:)
super(message, path: path, nodes: nodes)
@type_name = type
@fragment_name = fragment_name
@parent_name = parent
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"typeName" => type_name,
"fragmentName" => fragment_name,
"parentName" => parent_name
}
super.merge({
"extensions" => extensions
})
end
def code
"cannotSpreadFragment"
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/static_validation/rules/argument_names_are_unique.rb | lib/graphql/static_validation/rules/argument_names_are_unique.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module ArgumentNamesAreUnique
include GraphQL::StaticValidation::Error::ErrorHelper
def on_field(node, parent)
validate_arguments(node)
super
end
def on_directive(node, parent)
validate_arguments(node)
super
end
def validate_arguments(node)
argument_defns = node.arguments
if !argument_defns.empty?
args_by_name = Hash.new { |h, k| h[k] = [] }
argument_defns.each { |a| args_by_name[a.name] << a }
args_by_name.each do |name, defns|
if defns.size > 1
add_error(GraphQL::StaticValidation::ArgumentNamesAreUniqueError.new("There can be only one argument named \"#{name}\"", nodes: defns, name: name))
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/static_validation/rules/fragments_are_on_composite_types.rb | lib/graphql/static_validation/rules/fragments_are_on_composite_types.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentsAreOnCompositeTypes
def on_fragment_definition(node, parent)
validate_type_is_composite(node) && super
end
def on_inline_fragment(node, parent)
validate_type_is_composite(node) && super
end
private
def validate_type_is_composite(node)
node_type = node.type
if node_type.nil?
# Inline fragment on the same type
true
else
type_name = node_type.to_query_string
type_def = @types.type(type_name)
if type_def.nil? || !type_def.kind.composite?
add_error(GraphQL::StaticValidation::FragmentsAreOnCompositeTypesError.new(
"Invalid fragment on type #{type_name} (must be Union, Interface or Object)",
nodes: node,
type: type_name
))
false
else
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/static_validation/rules/argument_literals_are_compatible_error.rb | lib/graphql/static_validation/rules/argument_literals_are_compatible_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class ArgumentLiteralsAreCompatibleError < StaticValidation::Error
attr_reader :type_name
attr_reader :argument_name
attr_reader :argument
attr_reader :value
def initialize(message, path: nil, nodes: [], type:, argument_name: nil, extensions: nil, coerce_extensions: nil, argument: nil, value: nil)
super(message, path: path, nodes: nodes)
@type_name = type
@argument_name = argument_name
@extensions = extensions
@coerce_extensions = coerce_extensions
@argument = argument
@value = value
end
# A hash representation of this Message
def to_h
if @coerce_extensions
extensions = @coerce_extensions
# This is for legacy compat -- but this key is supposed to be a GraphQL type name :confounded:
extensions["typeName"] = "CoercionError"
else
extensions = {
"code" => code,
"typeName" => type_name
}
if argument_name
extensions["argumentName"] = argument_name
end
end
extensions.merge!(@extensions) unless @extensions.nil?
super.merge({
"extensions" => extensions
})
end
def code
"argumentLiteralsIncompatible"
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/static_validation/rules/fragments_are_finite.rb | lib/graphql/static_validation/rules/fragments_are_finite.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentsAreFinite
def on_document(_n, _p)
super
dependency_map = context.dependencies
dependency_map.cyclical_definitions.each do |defn|
if defn.node.is_a?(GraphQL::Language::Nodes::FragmentDefinition)
add_error(GraphQL::StaticValidation::FragmentsAreFiniteError.new(
"Fragment #{defn.name} contains an infinite loop",
nodes: defn.node,
path: defn.path,
name: defn.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/static_validation/rules/arguments_are_defined.rb | lib/graphql/static_validation/rules/arguments_are_defined.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module ArgumentsAreDefined
def on_argument(node, parent)
parent_defn = parent_definition(parent)
if parent_defn && @types.argument(parent_defn, node.name)
super
elsif parent_defn
kind_of_node = node_type(parent)
error_arg_name = parent_name(parent, parent_defn)
arg_names = context.types.arguments(parent_defn).map(&:graphql_name)
add_error(GraphQL::StaticValidation::ArgumentsAreDefinedError.new(
"#{kind_of_node} '#{error_arg_name}' doesn't accept argument '#{node.name}'#{context.did_you_mean_suggestion(node.name, arg_names)}",
nodes: node,
name: error_arg_name,
type: kind_of_node,
argument_name: node.name,
parent: parent_defn
))
else
# Some other weird error
super
end
end
private
# TODO smell: these methods are added to all visitors, since they're included in a module.
def parent_name(parent, type_defn)
case parent
when GraphQL::Language::Nodes::Field
parent.alias || parent.name
when GraphQL::Language::Nodes::InputObject
type_defn.graphql_name
when GraphQL::Language::Nodes::Argument, GraphQL::Language::Nodes::Directive
parent.name
else
raise "Invariant: Unexpected parent #{parent.inspect} (#{parent.class})"
end
end
def node_type(parent)
parent.class.name.split("::").last
end
def parent_definition(parent)
case parent
when GraphQL::Language::Nodes::InputObject
arg_defn = context.argument_definition
if arg_defn.nil?
nil
else
arg_ret_type = arg_defn.type.unwrap
if arg_ret_type.kind.input_object?
arg_ret_type
else
nil
end
end
when GraphQL::Language::Nodes::Directive
context.schema_directives[parent.name]
when GraphQL::Language::Nodes::Field
context.field_definition
else
raise "Unexpected argument parent: #{parent.class} (##{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/static_validation/rules/fields_will_merge_error.rb | lib/graphql/static_validation/rules/fields_will_merge_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FieldsWillMergeError < StaticValidation::Error
attr_reader :field_name
attr_reader :kind
def initialize(kind:, field_name:)
super(nil)
@field_name = field_name
@kind = kind
@conflicts = []
end
def message
@message || "Field '#{field_name}' has #{kind == :argument ? 'an' : 'a'} #{kind} conflict: #{conflicts}?"
end
attr_writer :message
def path
[]
end
def conflicts
@conflicts.join(' or ')
end
def add_conflict(node, conflict_str)
# Can't use `.include?` here because AST nodes implement `#==`
# based on string value, not including location. But sometimes,
# identical nodes conflict because of their differing return types.
if nodes.any? { |n| n == node && n.line == node.line && n.col == node.col }
# already have an error for this node
return
end
@nodes << node
@conflicts << conflict_str
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"fieldName" => field_name,
"conflicts" => conflicts
}
super.merge({
"extensions" => extensions
})
end
def code
"fieldConflict"
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/static_validation/rules/variable_default_values_are_correctly_typed.rb | lib/graphql/static_validation/rules/variable_default_values_are_correctly_typed.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module VariableDefaultValuesAreCorrectlyTyped
def on_variable_definition(node, parent)
if !node.default_value.nil?
value = node.default_value
type = context.schema.type_from_ast(node.type, context: context)
if type.nil?
# This is handled by another validator
else
validation_result = context.validate_literal(value, type)
if !validation_result.valid?
problems = validation_result.problems
first_problem = problems && problems.first
if first_problem
error_message = first_problem["explanation"]
end
error_message ||= "Default value for $#{node.name} doesn't match type #{type.to_type_signature}"
add_error(GraphQL::StaticValidation::VariableDefaultValuesAreCorrectlyTypedError.new(
error_message,
nodes: node,
name: node.name,
type: type.to_type_signature,
error_type: VariableDefaultValuesAreCorrectlyTypedError::VIOLATIONS[:INVALID_TYPE],
))
end
end
end
super
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/static_validation/rules/one_of_input_objects_are_valid_error.rb | lib/graphql/static_validation/rules/one_of_input_objects_are_valid_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class OneOfInputObjectsAreValidError < StaticValidation::Error
attr_reader :input_object_type
def initialize(message, path:, nodes:, input_object_type:)
super(message, path: path, nodes: nodes)
@input_object_type = input_object_type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"inputObjectType" => input_object_type
}
super.merge({
"extensions" => extensions
})
end
def code
"invalidOneOfInputObject"
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/static_validation/rules/variables_are_used_and_defined.rb | lib/graphql/static_validation/rules/variables_are_used_and_defined.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
# The problem is
# - Variable $usage must be determined at the OperationDefinition level
# - You can't tell how fragments use variables until you visit FragmentDefinitions (which may be at the end of the document)
#
# So, this validator includes some crazy logic to follow fragment spreads recursively, while avoiding infinite loops.
#
# `graphql-js` solves this problem by:
# - re-visiting the AST for each validator
# - allowing validators to say `followSpreads: true`
#
module VariablesAreUsedAndDefined
class VariableUsage
attr_accessor :ast_node, :used_by, :declared_by, :path
def used?
!!@used_by
end
def declared?
!!@declared_by
end
end
def initialize(*)
super
@variable_usages_for_context = Hash.new {|hash, key| hash[key] = Hash.new {|h, k| h[k] = VariableUsage.new } }
@spreads_for_context = Hash.new {|hash, key| hash[key] = [] }
@variable_context_stack = []
end
def on_operation_definition(node, parent)
# initialize the hash of vars for this context:
@variable_usages_for_context[node]
@variable_context_stack.push(node)
# mark variables as defined:
var_hash = @variable_usages_for_context[node]
node.variables.each { |var|
var_usage = var_hash[var.name]
var_usage.declared_by = node
var_usage.path = context.path
}
super
@variable_context_stack.pop
end
def on_fragment_definition(node, parent)
# initialize the hash of vars for this context:
@variable_usages_for_context[node]
@variable_context_stack.push(node)
super
@variable_context_stack.pop
end
# For FragmentSpreads:
# - find the context on the stack
# - mark the context as containing this spread
def on_fragment_spread(node, parent)
variable_context = @variable_context_stack.last
@spreads_for_context[variable_context] << node.name
super
end
# For VariableIdentifiers:
# - mark the variable as used
# - assign its AST node
def on_variable_identifier(node, parent)
usage_context = @variable_context_stack.last
declared_variables = @variable_usages_for_context[usage_context]
usage = declared_variables[node.name]
usage.used_by = usage_context
usage.ast_node = node
usage.path = context.path
super
end
def on_document(node, parent)
super
fragment_definitions = @variable_usages_for_context.select { |key, value| key.is_a?(GraphQL::Language::Nodes::FragmentDefinition) }
operation_definitions = @variable_usages_for_context.select { |key, value| key.is_a?(GraphQL::Language::Nodes::OperationDefinition) }
operation_definitions.each do |node, node_variables|
follow_spreads(node, node_variables, @spreads_for_context, fragment_definitions, [])
create_errors(node_variables)
end
end
private
# Follow spreads in `node`, looking them up from `spreads_for_context` and finding their match in `fragment_definitions`.
# Use those fragments to update {VariableUsage}s in `parent_variables`.
# Avoid infinite loops by skipping anything in `visited_fragments`.
def follow_spreads(node, parent_variables, spreads_for_context, fragment_definitions, visited_fragments)
spreads = spreads_for_context[node] - visited_fragments
spreads.each do |spread_name|
def_node = nil
variables = nil
# Implement `.find` by hand to avoid Ruby's internal allocations
fragment_definitions.each do |frag_def_node, vars|
if frag_def_node.name == spread_name
def_node = frag_def_node
variables = vars
break
end
end
next if !def_node
visited_fragments << spread_name
variables.each do |name, child_usage|
parent_usage = parent_variables[name]
if child_usage.used?
parent_usage.ast_node = child_usage.ast_node
parent_usage.used_by = child_usage.used_by
parent_usage.path = child_usage.path
end
end
follow_spreads(def_node, parent_variables, spreads_for_context, fragment_definitions, visited_fragments)
end
end
# Determine all the error messages,
# Then push messages into the validation context
def create_errors(node_variables)
# Declared but not used:
node_variables
.select { |name, usage| usage.declared? && !usage.used? }
.each { |var_name, usage|
declared_by_error_name = usage.declared_by.name || "anonymous #{usage.declared_by.operation_type}"
add_error(GraphQL::StaticValidation::VariablesAreUsedAndDefinedError.new(
"Variable $#{var_name} is declared by #{declared_by_error_name} but not used",
nodes: usage.declared_by,
path: usage.path,
name: var_name,
error_type: VariablesAreUsedAndDefinedError::VIOLATIONS[:VARIABLE_NOT_USED]
))
}
# Used but not declared:
node_variables
.select { |name, usage| usage.used? && !usage.declared? }
.each { |var_name, usage|
used_by_error_name = usage.used_by.name || "anonymous #{usage.used_by.operation_type}"
add_error(GraphQL::StaticValidation::VariablesAreUsedAndDefinedError.new(
"Variable $#{var_name} is used by #{used_by_error_name} but not declared",
nodes: usage.ast_node,
path: usage.path,
name: var_name,
error_type: VariablesAreUsedAndDefinedError::VIOLATIONS[:VARIABLE_NOT_DEFINED]
))
}
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/static_validation/rules/directives_are_in_valid_locations_error.rb | lib/graphql/static_validation/rules/directives_are_in_valid_locations_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class DirectivesAreInValidLocationsError < StaticValidation::Error
attr_reader :target_name
attr_reader :name
def initialize(message, path: nil, nodes: [], target:, name: nil)
super(message, path: path, nodes: nodes)
@target_name = target
@name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"targetName" => target_name
}.tap { |h| h["name"] = name unless name.nil? }
super.merge({
"extensions" => extensions
})
end
def code
"directiveCannotBeApplied"
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/static_validation/rules/fragment_names_are_unique_error.rb | lib/graphql/static_validation/rules/fragment_names_are_unique_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentNamesAreUniqueError < StaticValidation::Error
attr_reader :fragment_name
def initialize(message, path: nil, nodes: [], name:)
super(message, path: path, nodes: nodes)
@fragment_name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"fragmentName" => fragment_name
}
super.merge({
"extensions" => extensions
})
end
def code
"fragmentNotUnique"
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/static_validation/rules/unique_directives_per_location.rb | lib/graphql/static_validation/rules/unique_directives_per_location.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module UniqueDirectivesPerLocation
DIRECTIVE_NODE_HOOKS = [
:on_fragment_definition,
:on_fragment_spread,
:on_inline_fragment,
:on_operation_definition,
:on_scalar_type_definition,
:on_object_type_definition,
:on_input_value_definition,
:on_field_definition,
:on_interface_type_definition,
:on_union_type_definition,
:on_enum_type_definition,
:on_enum_value_definition,
:on_input_object_type_definition,
:on_field,
]
VALIDATE_DIRECTIVE_LOCATION_ON_NODE = <<~RUBY
def %{method_name}(node, parent)
if !node.directives.empty?
validate_directive_location(node)
end
super(node, parent)
end
RUBY
DIRECTIVE_NODE_HOOKS.each do |method_name|
# Can't use `define_method {...}` here because the proc can't be isolated for use in non-main Ractors
module_eval(VALIDATE_DIRECTIVE_LOCATION_ON_NODE % { method_name: method_name }) # rubocop:disable Development/NoEvalCop
end
private
def validate_directive_location(node)
used_directives = {}
node.directives.each do |ast_directive|
directive_name = ast_directive.name
if (first_node = used_directives[directive_name])
@directives_are_unique_errors_by_first_node ||= {}
err = @directives_are_unique_errors_by_first_node[first_node] ||= begin
error = GraphQL::StaticValidation::UniqueDirectivesPerLocationError.new(
"The directive \"#{directive_name}\" can only be used once at this location.",
nodes: [used_directives[directive_name]],
directive: directive_name,
)
add_error(error)
error
end
err.nodes << ast_directive
elsif !((dir_defn = context.schema_directives[directive_name]) && dir_defn.repeatable?)
used_directives[directive_name] = ast_directive
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/static_validation/rules/fragments_are_named_error.rb | lib/graphql/static_validation/rules/fragments_are_named_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentsAreNamedError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
}
super.merge({
"extensions" => extensions
})
end
def code
"anonymousFragment"
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/static_validation/rules/subscription_root_exists_and_single_subscription_selection.rb | lib/graphql/static_validation/rules/subscription_root_exists_and_single_subscription_selection.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module SubscriptionRootExistsAndSingleSubscriptionSelection
def on_operation_definition(node, parent)
if node.operation_type == "subscription"
if context.types.subscription_root.nil?
add_error(GraphQL::StaticValidation::SubscriptionRootExistsError.new(
'Schema is not configured for subscriptions',
nodes: node
))
elsif node.selections.size != 1
add_error(GraphQL::StaticValidation::NotSingleSubscriptionError.new(
'A subscription operation may only have one selection',
nodes: node,
))
else
super
end
else
super
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/static_validation/rules/directives_are_defined_error.rb | lib/graphql/static_validation/rules/directives_are_defined_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class DirectivesAreDefinedError < StaticValidation::Error
attr_reader :directive_name
def initialize(message, path: nil, nodes: [], directive:)
super(message, path: path, nodes: nodes)
@directive_name = directive
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"directiveName" => directive_name
}
super.merge({
"extensions" => extensions
})
end
def code
"undefinedDirective"
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/static_validation/rules/query_root_exists_error.rb | lib/graphql/static_validation/rules/query_root_exists_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class QueryRootExistsError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
}
super.merge({
"extensions" => extensions
})
end
def code
"missingQueryConfiguration"
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/static_validation/rules/input_object_names_are_unique_error.rb | lib/graphql/static_validation/rules/input_object_names_are_unique_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class InputObjectNamesAreUniqueError < StaticValidation::Error
attr_reader :name
def initialize(message, path: nil, nodes: [], name:)
super(message, path: path, nodes: nodes)
@name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"name" => name
}
super.merge({
"extensions" => extensions
})
end
def code
"inputFieldNotUnique"
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/static_validation/rules/variable_usages_are_allowed.rb | lib/graphql/static_validation/rules/variable_usages_are_allowed.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module VariableUsagesAreAllowed
def initialize(*)
super
# holds { name => ast_node } pairs
@declared_variables = {}
end
def on_operation_definition(node, parent)
@declared_variables = node.variables.each_with_object({}) { |var, memo| memo[var.name] = var }
super
end
def on_argument(node, parent)
node_values = if node.value.is_a?(Array)
node.value
else
[node.value]
end
node_values = node_values.select { |value| value.is_a? GraphQL::Language::Nodes::VariableIdentifier }
if !node_values.empty?
argument_owner = case parent
when GraphQL::Language::Nodes::Field
context.field_definition
when GraphQL::Language::Nodes::Directive
context.directive_definition
when GraphQL::Language::Nodes::InputObject
arg_type = context.argument_definition.type.unwrap
if arg_type.kind.input_object?
arg_type
else
# This is some kind of error
nil
end
else
raise("Unexpected argument parent: #{parent}")
end
node_values.each do |node_value|
var_defn_ast = @declared_variables[node_value.name]
# Might be undefined :(
# VariablesAreUsedAndDefined can't finalize its search until the end of the document.
var_defn_ast && argument_owner && validate_usage(argument_owner, node, var_defn_ast)
end
end
super
end
private
def validate_usage(argument_owner, arg_node, ast_var)
var_type = context.schema.type_from_ast(ast_var.type, context: context)
if var_type.nil?
return
end
if !ast_var.default_value.nil?
unless var_type.kind.non_null?
# If the value is required, but the argument is not,
# and yet there's a non-nil default, then we impliclty
# make the argument also a required type.
var_type = var_type.to_non_null_type
end
end
arg_defn = @types.argument(argument_owner, arg_node.name)
arg_defn_type = arg_defn.type
# If the argument is non-null, but it was given a default value,
# then treat it as nullable in practice, see https://github.com/rmosolgo/graphql-ruby/issues/3793
if arg_defn_type.non_null? && arg_defn.default_value?
arg_defn_type = arg_defn_type.of_type
end
var_inner_type = var_type.unwrap
arg_inner_type = arg_defn_type.unwrap
var_type = wrap_var_type_with_depth_of_arg(var_type, arg_node)
if var_inner_type != arg_inner_type
create_error("Type mismatch", var_type, ast_var, arg_defn, arg_node)
elsif list_dimension(var_type) != list_dimension(arg_defn_type)
create_error("List dimension mismatch", var_type, ast_var, arg_defn, arg_node)
elsif !non_null_levels_match(arg_defn_type, var_type)
create_error("Nullability mismatch", var_type, ast_var, arg_defn, arg_node)
end
end
def create_error(error_message, var_type, ast_var, arg_defn, arg_node)
add_error(GraphQL::StaticValidation::VariableUsagesAreAllowedError.new(
"#{error_message} on variable $#{ast_var.name} and argument #{arg_node.name} (#{var_type.to_type_signature} / #{arg_defn.type.to_type_signature})",
nodes: arg_node,
name: ast_var.name,
type: var_type.to_type_signature,
argument: arg_node.name,
error: error_message
))
end
def wrap_var_type_with_depth_of_arg(var_type, arg_node)
arg_node_value = arg_node.value
return var_type unless arg_node_value.is_a?(Array)
new_var_type = var_type
depth_of_array(arg_node_value).times do
# Since the array _is_ present, treat it like a non-null type
# (It satisfies a non-null requirement AND a nullable requirement)
new_var_type = new_var_type.to_list_type.to_non_null_type
end
new_var_type
end
# @return [Integer] Returns the max depth of `array`, or `0` if it isn't an array at all
def depth_of_array(array)
case array
when Array
max_child_depth = 0
array.each do |item|
item_depth = depth_of_array(item)
if item_depth > max_child_depth
max_child_depth = item_depth
end
end
1 + max_child_depth
else
0
end
end
def list_dimension(type)
if type.kind.list?
1 + list_dimension(type.of_type)
elsif type.kind.non_null?
list_dimension(type.of_type)
else
0
end
end
def non_null_levels_match(arg_type, var_type)
if arg_type.kind.non_null? && !var_type.kind.non_null?
false
elsif arg_type.kind.wraps? && var_type.kind.wraps?
# If var_type is a non-null wrapper for a type, and arg_type is nullable, peel off the wrapper
# That way, a var_type of `[DairyAnimal]!` works with an arg_type of `[DairyAnimal]`
if var_type.kind.non_null? && !arg_type.kind.non_null?
var_type = var_type.of_type
end
non_null_levels_match(arg_type.of_type, var_type.of_type)
else
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/static_validation/rules/variables_are_input_types.rb | lib/graphql/static_validation/rules/variables_are_input_types.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module VariablesAreInputTypes
def on_variable_definition(node, parent)
type_name = get_type_name(node.type)
type = context.query.types.type(type_name)
if type.nil?
@all_possible_input_type_names ||= begin
names = []
context.types.all_types.each { |(t)|
if t.kind.input?
names << t.graphql_name
end
}
names
end
add_error(GraphQL::StaticValidation::VariablesAreInputTypesError.new(
"#{type_name} isn't a defined input type (on $#{node.name})#{context.did_you_mean_suggestion(type_name, @all_possible_input_type_names)}",
nodes: node,
name: node.name,
type: type_name
))
elsif !type.kind.input?
add_error(GraphQL::StaticValidation::VariablesAreInputTypesError.new(
"#{type.graphql_name} isn't a valid input type (on $#{node.name})",
nodes: node,
name: node.name,
type: type_name
))
end
super
end
private
def get_type_name(ast_type)
if ast_type.respond_to?(:of_type)
get_type_name(ast_type.of_type)
else
ast_type.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/static_validation/rules/fragments_are_used.rb | lib/graphql/static_validation/rules/fragments_are_used.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentsAreUsed
def on_document(node, parent)
super
dependency_map = context.dependencies
dependency_map.unmet_dependencies.each do |op_defn, spreads|
spreads.each do |fragment_spread|
add_error(GraphQL::StaticValidation::FragmentsAreUsedError.new(
"Fragment #{fragment_spread.name} was used, but not defined",
nodes: fragment_spread.node,
path: fragment_spread.path,
fragment: fragment_spread.name
))
end
end
dependency_map.unused_dependencies.each do |fragment|
if fragment && !fragment.name.nil?
add_error(GraphQL::StaticValidation::FragmentsAreUsedError.new(
"Fragment #{fragment.name} was defined, but not used",
nodes: fragment.node,
path: fragment.path,
fragment: fragment.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/static_validation/rules/required_input_object_attributes_are_present.rb | lib/graphql/static_validation/rules/required_input_object_attributes_are_present.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module RequiredInputObjectAttributesArePresent
def on_input_object(node, parent)
if parent.is_a? GraphQL::Language::Nodes::Argument
validate_input_object(node, context, parent)
end
super
end
private
def get_parent_type(context, parent)
# If argument_definition is defined we're at nested object
# and need to refer to the containing input object type rather
# than the field_definition.
# h/t @rmosolgo
arg_defn = context.argument_definition
# Double checking that arg_defn is an input object as nested
# scalars, namely JSON, can make it to this branch
defn = if arg_defn && arg_defn.type.unwrap.kind.input_object?
arg_defn.type.unwrap
else
context.directive_definition || context.field_definition
end
parent_type = context.types.argument(defn, parent_name(parent, defn))
parent_type ? parent_type.type.unwrap : nil
end
def validate_input_object(ast_node, context, parent)
parent_type = get_parent_type(context, parent)
return unless parent_type && parent_type.kind.input_object?
required_fields = context.types.arguments(parent_type)
.select{ |arg| arg.type.kind.non_null? && !arg.default_value? }
.map!(&:graphql_name)
present_fields = ast_node.arguments.map(&:name)
missing_fields = required_fields - present_fields
missing_fields.each do |missing_field|
path = [*context.path, missing_field]
missing_field_type = context.types.argument(parent_type, missing_field).type
add_error(RequiredInputObjectAttributesArePresentError.new(
"Argument '#{missing_field}' on InputObject '#{parent_type.to_type_signature}' is required. Expected type #{missing_field_type.to_type_signature}",
argument_name: missing_field,
argument_type: missing_field_type.to_type_signature,
input_object_type: parent_type.to_type_signature,
path: path,
nodes: ast_node,
))
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/static_validation/rules/fragment_types_exist_error.rb | lib/graphql/static_validation/rules/fragment_types_exist_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentTypesExistError < StaticValidation::Error
attr_reader :type_name
def initialize(message, path: nil, nodes: [], type:)
super(message, path: path, nodes: nodes)
@type_name = type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"typeName" => type_name
}
super.merge({
"extensions" => extensions
})
end
def code
"undefinedType"
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/static_validation/rules/directives_are_defined.rb | lib/graphql/static_validation/rules/directives_are_defined.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module DirectivesAreDefined
def initialize(*)
super
end
def on_directive(node, parent)
if !@types.directive_exists?(node.name)
@directives_are_defined_errors_by_name ||= {}
error = @directives_are_defined_errors_by_name[node.name] ||= begin
@directive_names ||= @types.directives.map(&:graphql_name)
err = GraphQL::StaticValidation::DirectivesAreDefinedError.new(
"Directive @#{node.name} is not defined#{context.did_you_mean_suggestion(node.name, @directive_names)}",
nodes: [],
directive: node.name
)
add_error(err)
err
end
error.nodes << node
else
super
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/static_validation/rules/not_single_subscription_error.rb | lib/graphql/static_validation/rules/not_single_subscription_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class NotSingleSubscriptionError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
}
super.merge({
"extensions" => extensions
})
end
def code
"notSingleSubscription"
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/static_validation/rules/fields_have_appropriate_selections_error.rb | lib/graphql/static_validation/rules/fields_have_appropriate_selections_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FieldsHaveAppropriateSelectionsError < StaticValidation::Error
attr_reader :type_name
attr_reader :node_name
def initialize(message, path: nil, nodes: [], node_name:, type: nil)
super(message, path: path, nodes: nodes)
@node_name = node_name
@type_name = type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"nodeName" => node_name
}.tap { |h| h["typeName"] = type_name unless type_name.nil? }
super.merge({
"extensions" => extensions
})
end
def code
"selectionMismatch"
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/static_validation/rules/operation_names_are_valid.rb | lib/graphql/static_validation/rules/operation_names_are_valid.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module OperationNamesAreValid
def initialize(*)
super
@operation_names = Hash.new { |h, k| h[k] = [] }
end
def on_operation_definition(node, parent)
@operation_names[node.name] << node
super
end
def on_document(node, parent)
super
op_count = @operation_names.values.inject(0) { |m, v| m + v.size }
@operation_names.each do |name, nodes|
if name.nil? && op_count > 1
add_error(GraphQL::StaticValidation::OperationNamesAreValidError.new(
%|Operation name is required when multiple operations are present|,
nodes: nodes
))
elsif nodes.length > 1
add_error(GraphQL::StaticValidation::OperationNamesAreValidError.new(
%|Operation name "#{name}" must be unique|,
nodes: nodes,
name: 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/static_validation/rules/mutation_root_exists_error.rb | lib/graphql/static_validation/rules/mutation_root_exists_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class MutationRootExistsError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
}
super.merge({
"extensions" => extensions
})
end
def code
"missingMutationConfiguration"
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/static_validation/rules/fragments_are_finite_error.rb | lib/graphql/static_validation/rules/fragments_are_finite_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentsAreFiniteError < StaticValidation::Error
attr_reader :fragment_name
def initialize(message, path: nil, nodes: [], name:)
super(message, path: path, nodes: nodes)
@fragment_name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"fragmentName" => fragment_name
}
super.merge({
"extensions" => extensions
})
end
def code
"infiniteLoop"
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/static_validation/rules/required_input_object_attributes_are_present_error.rb | lib/graphql/static_validation/rules/required_input_object_attributes_are_present_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class RequiredInputObjectAttributesArePresentError < StaticValidation::Error
attr_reader :argument_type
attr_reader :argument_name
attr_reader :input_object_type
def initialize(message, path:, nodes:, argument_type:, argument_name:, input_object_type:)
super(message, path: path, nodes: nodes)
@argument_type = argument_type
@argument_name = argument_name
@input_object_type = input_object_type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"argumentName" => argument_name,
"argumentType" => argument_type,
"inputObjectType" => input_object_type,
}
super.merge({
"extensions" => extensions
})
end
def code
"missingRequiredInputObjectAttribute"
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/static_validation/rules/required_arguments_are_present_error.rb | lib/graphql/static_validation/rules/required_arguments_are_present_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class RequiredArgumentsArePresentError < StaticValidation::Error
attr_reader :class_name
attr_reader :name
attr_reader :arguments
def initialize(message, path: nil, nodes: [], class_name:, name:, arguments:)
super(message, path: path, nodes: nodes)
@class_name = class_name
@name = name
@arguments = arguments
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"className" => class_name,
"name" => name,
"arguments" => arguments
}
super.merge({
"extensions" => extensions
})
end
def code
"missingRequiredArguments"
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/static_validation/rules/fragments_are_named.rb | lib/graphql/static_validation/rules/fragments_are_named.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentsAreNamed
def on_fragment_definition(node, _parent)
if node.name.nil?
add_error(GraphQL::StaticValidation::FragmentsAreNamedError.new(
"Fragment definition has no name",
nodes: node
))
end
super
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/static_validation/rules/variable_usages_are_allowed_error.rb | lib/graphql/static_validation/rules/variable_usages_are_allowed_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class VariableUsagesAreAllowedError < StaticValidation::Error
attr_reader :type_name
attr_reader :variable_name
attr_reader :argument_name
attr_reader :error_message
def initialize(message, path: nil, nodes: [], type:, name:, argument:, error:)
super(message, path: path, nodes: nodes)
@type_name = type
@variable_name = name
@argument_name = argument
@error_message = error
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"variableName" => variable_name,
"typeName" => type_name,
"argumentName" => argument_name,
"errorMessage" => error_message
}
super.merge({
"extensions" => extensions
})
end
def code
"variableMismatch"
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/static_validation/rules/no_definitions_are_present.rb | lib/graphql/static_validation/rules/no_definitions_are_present.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module NoDefinitionsArePresent
include GraphQL::StaticValidation::Error::ErrorHelper
def initialize(*)
super
@schema_definition_nodes = []
end
def on_invalid_node(node, parent)
@schema_definition_nodes << node
nil
end
alias :on_directive_definition :on_invalid_node
alias :on_schema_definition :on_invalid_node
alias :on_scalar_type_definition :on_invalid_node
alias :on_object_type_definition :on_invalid_node
alias :on_input_object_type_definition :on_invalid_node
alias :on_interface_type_definition :on_invalid_node
alias :on_union_type_definition :on_invalid_node
alias :on_enum_type_definition :on_invalid_node
alias :on_schema_extension :on_invalid_node
alias :on_scalar_type_extension :on_invalid_node
alias :on_object_type_extension :on_invalid_node
alias :on_input_object_type_extension :on_invalid_node
alias :on_interface_type_extension :on_invalid_node
alias :on_union_type_extension :on_invalid_node
alias :on_enum_type_extension :on_invalid_node
def on_document(node, parent)
super
if !@schema_definition_nodes.empty?
add_error(GraphQL::StaticValidation::NoDefinitionsArePresentError.new(%|Query cannot contain schema definitions|, nodes: @schema_definition_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/static_validation/rules/fields_are_defined_on_type.rb | lib/graphql/static_validation/rules/fields_are_defined_on_type.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FieldsAreDefinedOnType
def on_field(node, parent)
parent_type = @object_types[-2]
field = context.query.types.field(parent_type, node.name)
if field.nil?
if parent_type.kind.union?
add_error(GraphQL::StaticValidation::FieldsHaveAppropriateSelectionsError.new(
"Selections can't be made directly on unions (see selections on #{parent_type.graphql_name})",
nodes: parent,
node_name: parent_type.graphql_name
))
else
possible_fields = possible_fields(context, parent_type)
suggestion = context.did_you_mean_suggestion(node.name, possible_fields)
message = "Field '#{node.name}' doesn't exist on type '#{parent_type.graphql_name}'#{suggestion}"
add_error(GraphQL::StaticValidation::FieldsAreDefinedOnTypeError.new(
message,
nodes: node,
field: node.name,
type: parent_type.graphql_name
))
end
else
super
end
end
private
def possible_fields(context, parent_type)
return EmptyObjects::EMPTY_ARRAY if parent_type.kind.leaf?
context.types.fields(parent_type).map(&:graphql_name)
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/static_validation/rules/fragments_are_on_composite_types_error.rb | lib/graphql/static_validation/rules/fragments_are_on_composite_types_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentsAreOnCompositeTypesError < StaticValidation::Error
attr_reader :type_name
attr_reader :argument_name
def initialize(message, path: nil, nodes: [], type:)
super(message, path: path, nodes: nodes)
@type_name = type
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"typeName" => type_name
}
super.merge({
"extensions" => extensions
})
end
def code
"fragmentOnNonCompositeType"
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/static_validation/rules/query_root_exists.rb | lib/graphql/static_validation/rules/query_root_exists.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module QueryRootExists
def on_operation_definition(node, _parent)
if (node.operation_type == 'query' || node.operation_type.nil?) && context.query.types.query_root.nil?
add_error(GraphQL::StaticValidation::QueryRootExistsError.new(
'Schema is not configured for queries',
nodes: node
))
else
super
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/static_validation/rules/fields_will_merge.rb | lib/graphql/static_validation/rules/fields_will_merge.rb | # frozen_string_literal: true
# frozen_string_literal: true
module GraphQL
module StaticValidation
module FieldsWillMerge
# Validates that a selection set is valid if all fields (including spreading any
# fragments) either correspond to distinct response names or can be merged
# without ambiguity.
#
# Original Algorithm: https://github.com/graphql/graphql-js/blob/master/src/validation/rules/OverlappingFieldsCanBeMerged.js
NO_ARGS = GraphQL::EmptyObjects::EMPTY_HASH
Field = Struct.new(:node, :definition, :owner_type, :parents)
FragmentSpread = Struct.new(:name, :parents)
def initialize(*)
super
@visited_fragments = {}
@compared_fragments = {}
@conflict_count = 0
end
def on_operation_definition(node, _parent)
setting_errors { conflicts_within_selection_set(node, type_definition) }
super
end
def on_field(node, _parent)
setting_errors { conflicts_within_selection_set(node, type_definition) }
super
end
private
def conflicts
@conflicts ||= Hash.new do |h, error_type|
h[error_type] = Hash.new do |h2, field_name|
h2[field_name] = GraphQL::StaticValidation::FieldsWillMergeError.new(kind: error_type, field_name: field_name)
end
end
end
def setting_errors
@conflicts = nil
yield
# don't initialize these if they weren't initialized in the block:
@conflicts&.each_value { |error_type| error_type.each_value { |error| add_error(error) } }
end
def conflicts_within_selection_set(node, parent_type)
return if parent_type.nil?
fields, fragment_spreads = fields_and_fragments_from_selection(node, owner_type: parent_type, parents: nil)
# (A) Find find all conflicts "within" the fields of this selection set.
find_conflicts_within(fields)
fragment_spreads.each_with_index do |fragment_spread, i|
are_mutually_exclusive = mutually_exclusive?(
fragment_spread.parents,
[parent_type]
)
# (B) Then find conflicts between these fields and those represented by
# each spread fragment name found.
find_conflicts_between_fields_and_fragment(
fragment_spread,
fields,
mutually_exclusive: are_mutually_exclusive,
)
# (C) Then compare this fragment with all other fragments found in this
# selection set to collect conflicts between fragments spread together.
# This compares each item in the list of fragment names to every other
# item in that same list (except for itself).
fragment_spreads[i + 1..-1].each do |fragment_spread2|
are_mutually_exclusive = mutually_exclusive?(
fragment_spread.parents,
fragment_spread2.parents
)
find_conflicts_between_fragments(
fragment_spread,
fragment_spread2,
mutually_exclusive: are_mutually_exclusive,
)
end
end
end
def find_conflicts_between_fragments(fragment_spread1, fragment_spread2, mutually_exclusive:)
fragment_name1 = fragment_spread1.name
fragment_name2 = fragment_spread2.name
return if fragment_name1 == fragment_name2
cache_key = compared_fragments_key(
fragment_name1,
fragment_name2,
mutually_exclusive,
)
if @compared_fragments.key?(cache_key)
return
else
@compared_fragments[cache_key] = true
end
fragment1 = context.fragments[fragment_name1]
fragment2 = context.fragments[fragment_name2]
return if fragment1.nil? || fragment2.nil?
fragment_type1 = context.query.types.type(fragment1.type.name)
fragment_type2 = context.query.types.type(fragment2.type.name)
return if fragment_type1.nil? || fragment_type2.nil?
fragment_fields1, fragment_spreads1 = fields_and_fragments_from_selection(
fragment1,
owner_type: fragment_type1,
parents: [*fragment_spread1.parents, fragment_type1]
)
fragment_fields2, fragment_spreads2 = fields_and_fragments_from_selection(
fragment2,
owner_type: fragment_type1,
parents: [*fragment_spread2.parents, fragment_type2]
)
# (F) First, find all conflicts between these two collections of fields
# (not including any nested fragments).
find_conflicts_between(
fragment_fields1,
fragment_fields2,
mutually_exclusive: mutually_exclusive,
)
# (G) Then collect conflicts between the first fragment and any nested
# fragments spread in the second fragment.
fragment_spreads2.each do |fragment_spread|
find_conflicts_between_fragments(
fragment_spread1,
fragment_spread,
mutually_exclusive: mutually_exclusive,
)
end
# (G) Then collect conflicts between the first fragment and any nested
# fragments spread in the second fragment.
fragment_spreads1.each do |fragment_spread|
find_conflicts_between_fragments(
fragment_spread2,
fragment_spread,
mutually_exclusive: mutually_exclusive,
)
end
end
def find_conflicts_between_fields_and_fragment(fragment_spread, fields, mutually_exclusive:)
fragment_name = fragment_spread.name
return if @visited_fragments.key?(fragment_name)
@visited_fragments[fragment_name] = true
fragment = context.fragments[fragment_name]
return if fragment.nil?
fragment_type = @types.type(fragment.type.name)
return if fragment_type.nil?
fragment_fields, fragment_spreads = fields_and_fragments_from_selection(fragment, owner_type: fragment_type, parents: [*fragment_spread.parents, fragment_type])
# (D) First find any conflicts between the provided collection of fields
# and the collection of fields represented by the given fragment.
find_conflicts_between(
fields,
fragment_fields,
mutually_exclusive: mutually_exclusive,
)
# (E) Then collect any conflicts between the provided collection of fields
# and any fragment names found in the given fragment.
fragment_spreads.each do |fragment_spread|
find_conflicts_between_fields_and_fragment(
fragment_spread,
fields,
mutually_exclusive: mutually_exclusive,
)
end
end
def find_conflicts_within(response_keys)
response_keys.each do |key, fields|
next if fields.size < 2
# find conflicts within nodes
i = 0
while i < fields.size
j = i + 1
while j < fields.size
find_conflict(key, fields[i], fields[j])
j += 1
end
i += 1
end
end
end
def find_conflict(response_key, field1, field2, mutually_exclusive: false)
return if @conflict_count >= context.max_errors
return if field1.definition.nil? || field2.definition.nil?
node1 = field1.node
node2 = field2.node
are_mutually_exclusive = mutually_exclusive ||
mutually_exclusive?(field1.parents, field2.parents)
if !are_mutually_exclusive
if node1.name != node2.name
conflict = conflicts[:field][response_key]
conflict.add_conflict(node1, node1.name)
conflict.add_conflict(node2, node2.name)
@conflict_count += 1
end
if !same_arguments?(node1, node2)
conflict = conflicts[:argument][response_key]
conflict.add_conflict(node1, GraphQL::Language.serialize(serialize_field_args(node1)))
conflict.add_conflict(node2, GraphQL::Language.serialize(serialize_field_args(node2)))
@conflict_count += 1
end
end
if !conflicts[:field].key?(response_key) &&
(t1 = field1.definition&.type) &&
(t2 = field2.definition&.type) &&
return_types_conflict?(t1, t2)
return_error = nil
message_override = nil
case @schema.allow_legacy_invalid_return_type_conflicts
when false
return_error = true
when true
legacy_handling = @schema.legacy_invalid_return_type_conflicts(@context.query, t1, t2, node1, node2)
case legacy_handling
when nil
return_error = false
when :return_validation_error
return_error = true
when String
return_error = true
message_override = legacy_handling
else
raise GraphQL::Error, "#{@schema}.legacy_invalid_scalar_conflicts returned unexpected value: #{legacy_handling.inspect}. Expected `nil`, String, or `:return_validation_error`."
end
else
return_error = false
@context.query.logger.warn <<~WARN
GraphQL-Ruby encountered mismatched types in this query: `#{t1.to_type_signature}` (at #{node1.line}:#{node1.col}) vs. `#{t2.to_type_signature}` (at #{node2.line}:#{node2.col}).
This will return an error in future GraphQL-Ruby versions, as per the GraphQL specification
Learn about migrating here: https://graphql-ruby.org/api-doc/#{GraphQL::VERSION}/GraphQL/Schema.html#allow_legacy_invalid_return_type_conflicts-class_method
WARN
end
if return_error
conflict = conflicts[:return_type][response_key]
if message_override
conflict.message = message_override
end
conflict.add_conflict(node1, "`#{t1.to_type_signature}`")
conflict.add_conflict(node2, "`#{t2.to_type_signature}`")
@conflict_count += 1
end
end
find_conflicts_between_sub_selection_sets(
field1,
field2,
mutually_exclusive: are_mutually_exclusive,
)
end
def return_types_conflict?(type1, type2)
if type1.list?
if type2.list?
return_types_conflict?(type1.of_type, type2.of_type)
else
true
end
elsif type2.list?
true
elsif type1.non_null?
if type2.non_null?
return_types_conflict?(type1.of_type, type2.of_type)
else
true
end
elsif type2.non_null?
true
elsif type1.kind.leaf? && type2.kind.leaf?
type1 != type2
else
# One or more of these are composite types,
# their selections will be validated later on.
false
end
end
def find_conflicts_between_sub_selection_sets(field1, field2, mutually_exclusive:)
return if field1.definition.nil? ||
field2.definition.nil? ||
(field1.node.selections.empty? && field2.node.selections.empty?)
return_type1 = field1.definition.type.unwrap
return_type2 = field2.definition.type.unwrap
parents1 = [return_type1]
parents2 = [return_type2]
fields, fragment_spreads = fields_and_fragments_from_selection(
field1.node,
owner_type: return_type1,
parents: parents1
)
fields2, fragment_spreads2 = fields_and_fragments_from_selection(
field2.node,
owner_type: return_type2,
parents: parents2
)
# (H) First, collect all conflicts between these two collections of field.
find_conflicts_between(fields, fields2, mutually_exclusive: mutually_exclusive)
# (I) Then collect conflicts between the first collection of fields and
# those referenced by each fragment name associated with the second.
fragment_spreads2.each do |fragment_spread|
find_conflicts_between_fields_and_fragment(
fragment_spread,
fields,
mutually_exclusive: mutually_exclusive,
)
end
# (I) Then collect conflicts between the second collection of fields and
# those referenced by each fragment name associated with the first.
fragment_spreads.each do |fragment_spread|
find_conflicts_between_fields_and_fragment(
fragment_spread,
fields2,
mutually_exclusive: mutually_exclusive,
)
end
# (J) Also collect conflicts between any fragment names by the first and
# fragment names by the second. This compares each item in the first set of
# names to each item in the second set of names.
fragment_spreads.each do |frag1|
fragment_spreads2.each do |frag2|
find_conflicts_between_fragments(
frag1,
frag2,
mutually_exclusive: mutually_exclusive
)
end
end
end
def find_conflicts_between(response_keys, response_keys2, mutually_exclusive:)
response_keys.each do |key, fields|
fields2 = response_keys2[key]
if fields2
fields.each do |field|
fields2.each do |field2|
find_conflict(
key,
field,
field2,
mutually_exclusive: mutually_exclusive,
)
end
end
end
end
end
NO_SELECTIONS = [GraphQL::EmptyObjects::EMPTY_HASH, GraphQL::EmptyObjects::EMPTY_ARRAY].freeze
def fields_and_fragments_from_selection(node, owner_type:, parents:)
if node.selections.empty?
NO_SELECTIONS
else
parents ||= []
fields, fragment_spreads = find_fields_and_fragments(node.selections, owner_type: owner_type, parents: parents, fields: [], fragment_spreads: [])
response_keys = fields.group_by { |f| f.node.alias || f.node.name }
[response_keys, fragment_spreads]
end
end
def find_fields_and_fragments(selections, owner_type:, parents:, fields:, fragment_spreads:)
selections.each do |node|
case node
when GraphQL::Language::Nodes::Field
definition = @types.field(owner_type, node.name)
fields << Field.new(node, definition, owner_type, parents)
when GraphQL::Language::Nodes::InlineFragment
fragment_type = node.type ? @types.type(node.type.name) : owner_type
find_fields_and_fragments(node.selections, parents: [*parents, fragment_type], owner_type: fragment_type, fields: fields, fragment_spreads: fragment_spreads) if fragment_type
when GraphQL::Language::Nodes::FragmentSpread
fragment_spreads << FragmentSpread.new(node.name, parents)
end
end
[fields, fragment_spreads]
end
def same_arguments?(field1, field2)
# Check for incompatible / non-identical arguments on this node:
arguments1 = field1.arguments
arguments2 = field2.arguments
return false if arguments1.length != arguments2.length
arguments1.all? do |argument1|
argument2 = arguments2.find { |argument| argument.name == argument1.name }
return false if argument2.nil?
serialize_arg(argument1.value) == serialize_arg(argument2.value)
end
end
def serialize_arg(arg_value)
case arg_value
when GraphQL::Language::Nodes::AbstractNode
arg_value.to_query_string
when Array
"[#{arg_value.map { |a| serialize_arg(a) }.join(", ")}]"
else
GraphQL::Language.serialize(arg_value)
end
end
def serialize_field_args(field)
serialized_args = {}
field.arguments.each do |argument|
serialized_args[argument.name] = serialize_arg(argument.value)
end
serialized_args
end
def compared_fragments_key(frag1, frag2, exclusive)
# Cache key to not compare two fragments more than once.
# The key includes both fragment names sorted (this way we
# avoid computing "A vs B" and "B vs A"). It also includes
# "exclusive" since the result may change depending on the parent_type
"#{[frag1, frag2].sort.join('-')}-#{exclusive}"
end
# Given two list of parents, find out if they are mutually exclusive
# In this context, `parents` represents the "self scope" of the field,
# what types may be found at this point in the query.
def mutually_exclusive?(parents1, parents2)
if parents1.empty? || parents2.empty?
false
elsif parents1.length == parents2.length
parents1.length.times.any? do |i|
type1 = parents1[i - 1]
type2 = parents2[i - 1]
if type1 == type2
# If the types we're comparing are the same type,
# then they aren't mutually exclusive
false
else
# Check if these two scopes have _any_ types in common.
possible_right_types = context.types.possible_types(type1)
possible_left_types = context.types.possible_types(type2)
(possible_right_types & possible_left_types).empty?
end
end
else
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/static_validation/rules/variable_names_are_unique_error.rb | lib/graphql/static_validation/rules/variable_names_are_unique_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class VariableNamesAreUniqueError < StaticValidation::Error
attr_reader :variable_name
def initialize(message, path: nil, nodes: [], name:)
super(message, path: path, nodes: nodes)
@variable_name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"variableName" => variable_name
}
super.merge({
"extensions" => extensions
})
end
def code
"variableNotUnique"
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/static_validation/rules/mutation_root_exists.rb | lib/graphql/static_validation/rules/mutation_root_exists.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module MutationRootExists
def on_operation_definition(node, _parent)
if node.operation_type == 'mutation' && context.query.types.mutation_root.nil?
add_error(GraphQL::StaticValidation::MutationRootExistsError.new(
'Schema is not configured for mutations',
nodes: node
))
else
super
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/static_validation/rules/input_object_names_are_unique.rb | lib/graphql/static_validation/rules/input_object_names_are_unique.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module InputObjectNamesAreUnique
def on_input_object(node, parent)
validate_input_fields(node)
super
end
private
def validate_input_fields(node)
input_field_defns = node.arguments
input_fields_by_name = Hash.new { |h, k| h[k] = [] }
input_field_defns.each { |a| input_fields_by_name[a.name] << a }
input_fields_by_name.each do |name, defns|
if defns.size > 1
error = GraphQL::StaticValidation::InputObjectNamesAreUniqueError.new(
"There can be only one input field named \"#{name}\"",
nodes: defns,
name: name
)
add_error(error)
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/static_validation/rules/no_definitions_are_present_error.rb | lib/graphql/static_validation/rules/no_definitions_are_present_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class NoDefinitionsArePresentError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
}
super.merge({
"extensions" => extensions
})
end
def code
"queryContainsSchemaDefinitions"
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/static_validation/rules/subscription_root_exists_error.rb | lib/graphql/static_validation/rules/subscription_root_exists_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class SubscriptionRootExistsError < StaticValidation::Error
def initialize(message, path: nil, nodes: [])
super(message, path: path, nodes: nodes)
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
}
super.merge({
"extensions" => extensions
})
end
def code
"missingSubscriptionConfiguration"
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/static_validation/rules/fragment_names_are_unique.rb | lib/graphql/static_validation/rules/fragment_names_are_unique.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
module FragmentNamesAreUnique
def initialize(*)
super
@fragments_by_name = Hash.new { |h, k| h[k] = [] }
end
def on_fragment_definition(node, parent)
@fragments_by_name[node.name] << node
super
end
def on_document(_n, _p)
super
@fragments_by_name.each do |name, fragments|
if fragments.length > 1
add_error(GraphQL::StaticValidation::FragmentNamesAreUniqueError.new(
%|Fragment name "#{name}" must be unique|,
nodes: fragments,
name: 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/static_validation/rules/unique_directives_per_location_error.rb | lib/graphql/static_validation/rules/unique_directives_per_location_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class UniqueDirectivesPerLocationError < StaticValidation::Error
attr_reader :directive_name
def initialize(message, path: nil, nodes: [], directive:)
super(message, path: path, nodes: nodes)
@directive_name = directive
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"directiveName" => directive_name
}
super.merge({
"extensions" => extensions
})
end
def code
"directiveNotUniqueForLocation"
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/static_validation/rules/fragments_are_used_error.rb | lib/graphql/static_validation/rules/fragments_are_used_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class FragmentsAreUsedError < StaticValidation::Error
attr_reader :fragment_name
def initialize(message, path: nil, nodes: [], fragment:)
super(message, path: path, nodes: nodes)
@fragment_name = fragment
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"fragmentName" => fragment_name
}
super.merge({
"extensions" => extensions
})
end
def code
"useAndDefineFragment"
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/static_validation/rules/variables_are_input_types_error.rb | lib/graphql/static_validation/rules/variables_are_input_types_error.rb | # frozen_string_literal: true
module GraphQL
module StaticValidation
class VariablesAreInputTypesError < StaticValidation::Error
attr_reader :type_name
attr_reader :variable_name
def initialize(message, path: nil, nodes: [], type:, name:)
super(message, path: path, nodes: nodes)
@type_name = type
@variable_name = name
end
# A hash representation of this Message
def to_h
extensions = {
"code" => code,
"typeName" => type_name,
"variableName" => variable_name
}
super.merge({
"extensions" => extensions
})
end
def code
"variableRequiresValidType"
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/errors.rb | lib/graphql/execution/errors.rb | # frozen_string_literal: true
module GraphQL
module Execution
class Errors
# Register this handler, updating the
# internal handler index to maintain least-to-most specific.
#
# @param error_class [Class<Exception>]
# @param error_handlers [Hash]
# @param error_handler [Proc]
# @return [void]
def self.register_rescue_from(error_class, error_handlers, error_handler)
subclasses_handlers = {}
this_level_subclasses = []
# During this traversal, do two things:
# - Identify any already-registered subclasses of this error class
# and gather them up to be inserted _under_ this class
# - Find the point in the index where this handler should be inserted
# (That is, _under_ any superclasses, or at top-level, if there are no superclasses registered)
while (error_handlers) do
this_level_subclasses.clear
# First, identify already-loaded handlers that belong
# _under_ this one. (That is, they're handlers
# for subclasses of `error_class`.)
error_handlers.each do |err_class, handler|
if err_class < error_class
subclasses_handlers[err_class] = handler
this_level_subclasses << err_class
end
end
# Any handlers that we'll be moving, delete them from this point in the index
this_level_subclasses.each do |err_class|
error_handlers.delete(err_class)
end
# See if any keys in this hash are superclasses of this new class:
next_index_point = error_handlers.find { |err_class, handler| error_class < err_class }
if next_index_point
error_handlers = next_index_point[1][:subclass_handlers]
else
# this new handler doesn't belong to any sub-handlers,
# so insert it in the current set of `handlers`
break
end
end
# Having found the point at which to insert this handler,
# register it and merge any subclass handlers back in at this point.
this_class_handlers = error_handlers[error_class]
this_class_handlers[:handler] = error_handler
this_class_handlers[:subclass_handlers].merge!(subclasses_handlers)
nil
end
# @return [Proc, nil] The handler for `error_class`, if one was registered on this schema or inherited
def self.find_handler_for(schema, error_class)
handlers = schema.error_handlers[:subclass_handlers]
handler = nil
while (handlers) do
_err_class, next_handler = handlers.find { |err_class, handler| error_class <= err_class }
if next_handler
handlers = next_handler[:subclass_handlers]
handler = next_handler
else
# Don't reassign `handler` --
# let the previous assignment carry over outside this block.
break
end
end
# check for a handler from a parent class:
if schema.superclass.respond_to?(:error_handlers)
parent_handler = find_handler_for(schema.superclass, error_class)
end
# If the inherited handler is more specific than the one defined here,
# use it.
# If it's a tie (or there is no parent handler), use the one defined here.
# If there's an inherited one, but not one defined here, use the inherited one.
# Otherwise, there's no handler for this error, return `nil`.
if parent_handler && handler && parent_handler[:class] < handler[:class]
parent_handler
elsif handler
handler
elsif parent_handler
parent_handler
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/execution/lookahead.rb | lib/graphql/execution/lookahead.rb | # frozen_string_literal: true
module GraphQL
module Execution
# Lookahead creates a uniform interface to inspect the forthcoming selections.
#
# It assumes that the AST it's working with is valid. (So, it's safe to use
# during execution, but if you're using it directly, be sure to validate first.)
#
# A field may get access to its lookahead by adding `extras: [:lookahead]`
# to its configuration.
#
# @example looking ahead in a field
# field :articles, [Types::Article], null: false,
# extras: [:lookahead]
#
# # For example, imagine a faster database call
# # may be issued when only some fields are requested.
# #
# # Imagine that _full_ fetch must be made to satisfy `fullContent`,
# # we can look ahead to see if we need that field. If we do,
# # we make the expensive database call instead of the cheap one.
# def articles(lookahead:)
# if lookahead.selects?(:full_content)
# fetch_full_articles(object)
# else
# fetch_preview_articles(object)
# end
# end
class Lookahead
# @param query [GraphQL::Query]
# @param ast_nodes [Array<GraphQL::Language::Nodes::Field>, Array<GraphQL::Language::Nodes::OperationDefinition>]
# @param field [GraphQL::Schema::Field] if `ast_nodes` are fields, this is the field definition matching those nodes
# @param root_type [Class] if `ast_nodes` are operation definition, this is the root type for that operation
def initialize(query:, ast_nodes:, field: nil, root_type: nil, owner_type: nil)
@ast_nodes = ast_nodes.freeze
@field = field
@root_type = root_type
@query = query
@selected_type = @field ? @field.type.unwrap : root_type
@owner_type = owner_type
end
# @return [Array<GraphQL::Language::Nodes::Field>]
attr_reader :ast_nodes
# @return [GraphQL::Schema::Field]
attr_reader :field
# @return [GraphQL::Schema::Object, GraphQL::Schema::Union, GraphQL::Schema::Interface]
attr_reader :owner_type
# @return [Hash<Symbol, Object>]
def arguments
if defined?(@arguments)
@arguments
else
@arguments = if @field
@query.after_lazy(@query.arguments_for(@ast_nodes.first, @field)) do |args|
case args
when Execution::Interpreter::Arguments
args.keyword_arguments
when GraphQL::ExecutionError
EmptyObjects::EMPTY_HASH
else
args
end
end
else
nil
end
end
end
# True if this node has a selection on `field_name`.
# If `field_name` is a String, it is treated as a GraphQL-style (camelized)
# field name and used verbatim. If `field_name` is a Symbol, it is
# treated as a Ruby-style (underscored) name and camelized before comparing.
#
# If `arguments:` is provided, each provided key/value will be matched
# against the arguments in the next selection. This method will return false
# if any of the given `arguments:` are not present and matching in the next selection.
# (But, the next selection may contain _more_ than the given arguments.)
# @param field_name [String, Symbol]
# @param arguments [Hash] Arguments which must match in the selection
# @return [Boolean]
def selects?(field_name, selected_type: @selected_type, arguments: nil)
selection(field_name, selected_type: selected_type, arguments: arguments).selected?
end
# True if this node has a selection with alias matching `alias_name`.
# If `alias_name` is a String, it is treated as a GraphQL-style (camelized)
# field name and used verbatim. If `alias_name` is a Symbol, it is
# treated as a Ruby-style (underscored) name and camelized before comparing.
#
# If `arguments:` is provided, each provided key/value will be matched
# against the arguments in the next selection. This method will return false
# if any of the given `arguments:` are not present and matching in the next selection.
# (But, the next selection may contain _more_ than the given arguments.)
# @param alias_name [String, Symbol]
# @param arguments [Hash] Arguments which must match in the selection
# @return [Boolean]
def selects_alias?(alias_name, arguments: nil)
alias_selection(alias_name, arguments: arguments).selected?
end
# @return [Boolean] True if this lookahead represents a field that was requested
def selected?
true
end
# Like {#selects?}, but can be used for chaining.
# It returns a null object (check with {#selected?})
# @param field_name [String, Symbol]
# @return [GraphQL::Execution::Lookahead]
def selection(field_name, selected_type: @selected_type, arguments: nil)
next_field_defn = case field_name
when String
@query.types.field(selected_type, field_name)
when Symbol
# Try to avoid the `.to_s` below, if possible
all_fields = if selected_type.kind.fields?
@query.types.fields(selected_type)
else
# Handle unions by checking possible
@query.types
.possible_types(selected_type)
.map { |t| @query.types.fields(t) }
.tap(&:flatten!)
end
if (match_by_orig_name = all_fields.find { |f| f.original_name == field_name })
match_by_orig_name
else
# Symbol#name is only present on 3.0+
sym_s = field_name.respond_to?(:name) ? field_name.name : field_name.to_s
guessed_name = Schema::Member::BuildType.camelize(sym_s)
@query.types.field(selected_type, guessed_name)
end
end
lookahead_for_selection(next_field_defn, selected_type, arguments)
end
# Like {#selection}, but for aliases.
# It returns a null object (check with {#selected?})
# @return [GraphQL::Execution::Lookahead]
def alias_selection(alias_name, selected_type: @selected_type, arguments: nil)
alias_cache_key = [alias_name, arguments]
return alias_selections[key] if alias_selections.key?(alias_name)
alias_node = lookup_alias_node(ast_nodes, alias_name)
return NULL_LOOKAHEAD unless alias_node
next_field_defn = @query.types.field(selected_type, alias_node.name)
alias_arguments = @query.arguments_for(alias_node, next_field_defn)
if alias_arguments.is_a?(::GraphQL::Execution::Interpreter::Arguments)
alias_arguments = alias_arguments.keyword_arguments
end
return NULL_LOOKAHEAD if arguments && arguments != alias_arguments
alias_selections[alias_cache_key] = lookahead_for_selection(next_field_defn, selected_type, alias_arguments, alias_name)
end
# Like {#selection}, but for all nodes.
# It returns a list of Lookaheads for all Selections
#
# If `arguments:` is provided, each provided key/value will be matched
# against the arguments in each selection. This method will filter the selections
# if any of the given `arguments:` do not match the given selection.
#
# @example getting the name of a selection
# def articles(lookahead:)
# next_lookaheads = lookahead.selections # => [#<GraphQL::Execution::Lookahead ...>, ...]
# next_lookaheads.map(&:name) #=> [:full_content, :title]
# end
#
# @param arguments [Hash] Arguments which must match in the selection
# @return [Array<GraphQL::Execution::Lookahead>]
def selections(arguments: nil)
subselections_by_type = {}
subselections_on_type = subselections_by_type[@selected_type] = {}
@ast_nodes.each do |node|
find_selections(subselections_by_type, subselections_on_type, @selected_type, node.selections, arguments)
end
subselections = []
subselections_by_type.each do |type, ast_nodes_by_response_key|
ast_nodes_by_response_key.each do |response_key, ast_nodes|
field_defn = @query.types.field(type, ast_nodes.first.name)
lookahead = Lookahead.new(query: @query, ast_nodes: ast_nodes, field: field_defn, owner_type: type)
subselections.push(lookahead)
end
end
subselections
end
# The method name of the field.
# It returns the method_sym of the Lookahead's field.
#
# @example getting the name of a selection
# def articles(lookahead:)
# article.selection(:full_content).name # => :full_content
# # ...
# end
#
# @return [Symbol]
def name
@field && @field.original_name
end
def inspect
"#<GraphQL::Execution::Lookahead #{@field ? "@field=#{@field.path.inspect}": "@root_type=#{@root_type}"} @ast_nodes.size=#{@ast_nodes.size}>"
end
# This is returned for {Lookahead#selection} when a non-existent field is passed
class NullLookahead < Lookahead
# No inputs required here.
def initialize
end
def selected?
false
end
def selects?(*)
false
end
def selection(*)
NULL_LOOKAHEAD
end
def selections(*)
[]
end
def inspect
"#<GraphQL::Execution::Lookahead::NullLookahead>"
end
end
# A singleton, so that misses don't come with overhead.
NULL_LOOKAHEAD = NullLookahead.new
private
def skipped_by_directive?(ast_selection)
ast_selection.directives.each do |directive|
dir_defn = @query.schema.directives.fetch(directive.name)
directive_class = dir_defn
if directive_class
dir_args = @query.arguments_for(directive, dir_defn)
return true unless directive_class.static_include?(dir_args, @query.context)
end
end
false
end
def find_selections(subselections_by_type, selections_on_type, selected_type, ast_selections, arguments)
ast_selections.each do |ast_selection|
next if skipped_by_directive?(ast_selection)
case ast_selection
when GraphQL::Language::Nodes::Field
response_key = ast_selection.alias || ast_selection.name
if selections_on_type.key?(response_key)
selections_on_type[response_key] << ast_selection
elsif arguments.nil? || arguments.empty?
selections_on_type[response_key] = [ast_selection]
else
field_defn = @query.types.field(selected_type, ast_selection.name)
if arguments_match?(arguments, field_defn, ast_selection)
selections_on_type[response_key] = [ast_selection]
end
end
when GraphQL::Language::Nodes::InlineFragment
on_type = selected_type
subselections_on_type = selections_on_type
if (t = ast_selection.type)
# Assuming this is valid, that `t` will be found.
on_type = @query.types.type(t.name)
subselections_on_type = subselections_by_type[on_type] ||= {}
end
find_selections(subselections_by_type, subselections_on_type, on_type, ast_selection.selections, arguments)
when GraphQL::Language::Nodes::FragmentSpread
frag_defn = lookup_fragment(ast_selection)
# Again, assuming a valid AST
on_type = @query.types.type(frag_defn.type.name)
subselections_on_type = subselections_by_type[on_type] ||= {}
find_selections(subselections_by_type, subselections_on_type, on_type, frag_defn.selections, arguments)
else
raise "Invariant: Unexpected selection type: #{ast_selection.class}"
end
end
end
# If a selection on `node` matches `field_name` (which is backed by `field_defn`)
# and matches the `arguments:` constraints, then add that node to `matches`
def find_selected_nodes(node, field_name, field_defn, arguments:, matches:, alias_name: NOT_CONFIGURED)
return if skipped_by_directive?(node)
case node
when GraphQL::Language::Nodes::Field
if node.name == field_name && (NOT_CONFIGURED.equal?(alias_name) || node.alias == alias_name)
if arguments.nil? || arguments.empty?
# No constraint applied
matches << node
elsif arguments_match?(arguments, field_defn, node)
matches << node
end
end
when GraphQL::Language::Nodes::InlineFragment
node.selections.each { |s| find_selected_nodes(s, field_name, field_defn, arguments: arguments, matches: matches, alias_name: alias_name) }
when GraphQL::Language::Nodes::FragmentSpread
frag_defn = lookup_fragment(node)
frag_defn.selections.each { |s| find_selected_nodes(s, field_name, field_defn, arguments: arguments, matches: matches, alias_name: alias_name) }
else
raise "Unexpected selection comparison on #{node.class.name} (#{node})"
end
end
def arguments_match?(arguments, field_defn, field_node)
query_kwargs = @query.arguments_for(field_node, field_defn)
arguments.all? do |arg_name, arg_value|
arg_name_sym = if arg_name.is_a?(String)
Schema::Member::BuildType.underscore(arg_name).to_sym
else
arg_name
end
# Make sure the constraint is present with a matching value
query_kwargs.key?(arg_name_sym) && query_kwargs[arg_name_sym] == arg_value
end
end
def lookahead_for_selection(field_defn, selected_type, arguments, alias_name = NOT_CONFIGURED)
return NULL_LOOKAHEAD unless field_defn
next_nodes = []
field_name = field_defn.name
@ast_nodes.each do |ast_node|
ast_node.selections.each do |selection|
find_selected_nodes(selection, field_name, field_defn, arguments: arguments, matches: next_nodes, alias_name: alias_name)
end
end
return NULL_LOOKAHEAD if next_nodes.empty?
Lookahead.new(query: @query, ast_nodes: next_nodes, field: field_defn, owner_type: selected_type)
end
def alias_selections
return @alias_selections if defined?(@alias_selections)
@alias_selections ||= {}
end
def lookup_alias_node(nodes, name)
return if nodes.empty?
nodes.flat_map(&:children)
.flat_map { |child| unwrap_fragments(child) }
.find { |child| child.is_a?(GraphQL::Language::Nodes::Field) && child.alias == name }
end
def unwrap_fragments(node)
case node
when GraphQL::Language::Nodes::InlineFragment
node.children
when GraphQL::Language::Nodes::FragmentSpread
lookup_fragment(node).children
else
[node]
end
end
def lookup_fragment(ast_selection)
@query.fragments[ast_selection.name] || raise("Invariant: Can't look ahead to nonexistent fragment #{ast_selection.name} (found: #{@query.fragments.keys})")
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.