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/spec/dummy/config/puma.rb
spec/dummy/config/puma.rb
# frozen_string_literal: true # Puma can serve each request in a thread from an internal thread pool. # The `threads` method setting takes two numbers: a minimum and maximum. # Any libraries that use thread pools should be configured to match # the maximum value specified for Puma. Default is set to 5 threads for minimum # and maximum; this matches the default thread size of Active Record. # threads_count = ENV.fetch("RAILS_MAX_THREADS") { 5 } threads threads_count, threads_count # Specifies the `port` that Puma will listen on to receive requests; default is 3000. # port ENV.fetch("PORT") { 3000 } # Specifies the `environment` that Puma will run in. # environment ENV.fetch("RAILS_ENV") { "development" } # Specifies the number of `workers` to boot in clustered mode. # Workers are forked webserver processes. If using threads and workers together # the concurrency of the application would be max `threads` * `workers`. # Workers do not work on JRuby or Windows (both of which do not support # processes). # # workers ENV.fetch("WEB_CONCURRENCY") { 2 } # Use the `preload_app!` method when specifying a `workers` number. # This directive tells Puma to first boot the application and load code # before forking the application. This takes advantage of Copy On Write # process behavior so workers use less memory. If you use this option # you need to make sure to reconnect any threads in the `on_worker_boot` # block. # # preload_app! # If you are preloading your application and using Active Record, it's # recommended that you close any connections to the database before workers # are forked to prevent connection leakage. # # before_fork do # ActiveRecord::Base.connection_pool.disconnect! if defined?(ActiveRecord) # end # The code in the `on_worker_boot` will be called if you are using # clustered mode by specifying a number of `workers`. After each worker # process is booted, this block will be run. If you are using the `preload_app!` # option, you will want to use this block to reconnect to any threads # or connections that may have been created at application boot, as Ruby # cannot share connections between processes. # # on_worker_boot do # ActiveRecord::Base.establish_connection if defined?(ActiveRecord) # end # # Allow puma to be restarted by `rails restart` command. plugin :tmp_restart
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/routes.rb
spec/dummy/config/routes.rb
# frozen_string_literal: true Rails.application.routes.draw do root to: "pages#show" mount GraphQL::Dashboard, at: "/dash", schema: "DummySchema" end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/boot.rb
spec/dummy/config/boot.rb
# frozen_string_literal: true ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) require 'bundler/setup' # Set up gems listed in the Gemfile. require 'bootsnap/setup'
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/filter_parameter_logging.rb
spec/dummy/config/initializers/filter_parameter_logging.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Configure sensitive parameters which will be filtered from the log file. Rails.application.config.filter_parameters += [:password]
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/application_controller_renderer.rb
spec/dummy/config/initializers/application_controller_renderer.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # ActiveSupport::Reloader.to_prepare do # ApplicationController.renderer.defaults.merge!( # http_host: 'example.org', # https: false # ) # end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/wrap_parameters.rb
spec/dummy/config/initializers/wrap_parameters.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # This file contains settings for ActionController::ParamsWrapper which # is enabled by default. # Enable parameter wrapping for JSON. You can disable this by setting :format to an empty array. ActiveSupport.on_load(:action_controller) do wrap_parameters format: [:json] end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/inflections.rb
spec/dummy/config/initializers/inflections.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new inflection rules using the following format. Inflections # are locale specific, and you may define rules for as many different # locales as you wish. All of these examples are active by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.plural /^(ox)$/i, '\1en' # inflect.singular /^(ox)en/i, '\1' # inflect.irregular 'person', 'people' # inflect.uncountable %w( fish sheep ) # end # These inflection rules are supported but not enabled by default: # ActiveSupport::Inflector.inflections(:en) do |inflect| # inflect.acronym 'RESTful' # end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/graphql_dashboard.rb
spec/dummy/config/initializers/graphql_dashboard.rb
# frozen_string_literal: true ActiveSupport.on_load(:graphql_dashboard_application_controller) do def self.hook_was_called? true end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/cookies_serializer.rb
spec/dummy/config/initializers/cookies_serializer.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Specify a serializer for the signed and encrypted cookie jars. # Valid options are :json, :marshal, and :hybrid. Rails.application.config.action_dispatch.cookies_serializer = :json
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/backtrace_silencers.rb
spec/dummy/config/initializers/backtrace_silencers.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # You can add backtrace silencers for libraries that you're using but don't wish to see in your backtraces. # Rails.backtrace_cleaner.add_silencer { |line| line =~ /my_noisy_library/ } # You can also remove all the silencers if you're trying to debug a problem that might stem from framework code. # Rails.backtrace_cleaner.remove_silencers!
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/initializers/mime_types.rb
spec/dummy/config/initializers/mime_types.rb
# frozen_string_literal: true # Be sure to restart your server when you modify this file. # Add new mime types for use in respond_to blocks: # Mime::Type.register "text/richtext", :rtf
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/environments/test.rb
spec/dummy/config/environments/test.rb
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # The test environment is used exclusively to run your application's # test suite. You never need to work with it otherwise. Remember that # your test database is "scratch space" for the test suite and is wiped # and recreated between test runs. Don't rely on the data there! config.cache_classes = true # Do not eager load code on boot. This avoids loading your whole application # just for the purpose of running a single test. If you are using a tool that # preloads Rails for running tests, you may have to set it to true. config.eager_load = false # Configure public file server for tests with Cache-Control for performance. config.public_file_server.enabled = true config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{1.hour.seconds.to_i}" } # Show full error reports and disable caching. config.consider_all_requests_local = true config.action_controller.perform_caching = false # Raise exceptions instead of rendering exception templates. config.action_dispatch.show_exceptions = false # Disable request forgery protection in test environment. config.action_controller.allow_forgery_protection = false # Print deprecation notices to the stderr. config.active_support.deprecation = :stderr # Raises error for missing translations # config.action_view.raise_on_missing_translations = true end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/environments/development.rb
spec/dummy/config/environments/development.rb
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # In the development environment your application's code is reloaded on # every request. This slows down response time but is perfect for development # since you don't have to restart the web server when you make code changes. config.cache_classes = false # Do not eager load code on boot. config.eager_load = false # Show full error reports. config.consider_all_requests_local = true # Enable/disable caching. By default caching is disabled. if Rails.root.join('tmp/caching-dev.txt').exist? config.action_controller.perform_caching = true config.cache_store = :memory_store config.public_file_server.headers = { 'Cache-Control' => "public, max-age=#{2.days.seconds.to_i}" } else config.action_controller.perform_caching = false config.cache_store = :null_store end # Print deprecation notices to the Rails logger. config.active_support.deprecation = :log # Raises error for missing translations # config.action_view.raise_on_missing_translations = true # Use an evented file watcher to asynchronously detect changes in source code, # routes, locales, etc. This feature depends on the listen gem. config.file_watcher = ActiveSupport::EventedFileUpdateChecker end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/spec/dummy/config/environments/production.rb
spec/dummy/config/environments/production.rb
# frozen_string_literal: true Rails.application.configure do # Settings specified here will take precedence over those in config/application.rb. # Code is not reloaded between requests. config.cache_classes = true # Eager load code on boot. This eager loads most of Rails and # your application in memory, allowing both threaded web servers # and those relying on copy on write to perform better. # Rake tasks automatically ignore this option for performance. config.eager_load = true # Full error reports are disabled and caching is turned on. config.consider_all_requests_local = false config.action_controller.perform_caching = true # Attempt to read encrypted secrets from `config/secrets.yml.enc`. # Requires an encryption key in `ENV["RAILS_MASTER_KEY"]` or # `config/secrets.yml.key`. config.read_encrypted_secrets = true # Disable serving static files from the `/public` folder by default since # Apache or NGINX already handles this. config.public_file_server.enabled = ENV['RAILS_SERVE_STATIC_FILES'].present? # Enable serving of images, stylesheets, and JavaScripts from an asset server. # config.action_controller.asset_host = 'http://assets.example.com' # Specifies the header that your server uses for sending files. # config.action_dispatch.x_sendfile_header = 'X-Sendfile' # for Apache # config.action_dispatch.x_sendfile_header = 'X-Accel-Redirect' # for NGINX # Mount Action Cable outside main process or domain # config.action_cable.mount_path = nil # config.action_cable.url = 'wss://example.com/cable' # config.action_cable.allowed_request_origins = [ 'http://example.com', /http:\/\/example.*/ ] # Force all access to the app over SSL, use Strict-Transport-Security, and use secure cookies. # config.force_ssl = true # Use the lowest log level to ensure availability of diagnostic information # when problems arise. config.log_level = :debug # Prepend all log lines with the following tags. config.log_tags = [ :request_id ] # Use a different cache store in production. # config.cache_store = :mem_cache_store # Use a real queuing backend for Active Job (and separate queues per environment) # config.active_job.queue_adapter = :resque # config.active_job.queue_name_prefix = "dummy_#{Rails.env}" # Enable locale fallbacks for I18n (makes lookups for any locale fall back to # the I18n.default_locale when a translation cannot be found). config.i18n.fallbacks = true # Send deprecation notices to registered listeners. config.active_support.deprecation = :notify # Use default logging formatter so that PID and timestamp are not suppressed. config.log_formatter = ::Logger::Formatter.new # Use a different logger for distributed setups. # require 'syslog/logger' # config.logger = ActiveSupport::TaggedLogging.new(Syslog::Logger.new 'app-name') if ENV["RAILS_LOG_TO_STDOUT"].present? logger = ActiveSupport::Logger.new(STDOUT) logger.formatter = config.log_formatter config.logger = ActiveSupport::TaggedLogging.new(logger) end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/cop/development/none_without_block_cop.rb
cop/development/none_without_block_cop.rb
# frozen_string_literal: true require 'rubocop' module Cop module Development # A custom Rubocop rule to catch uses of `.none?` without a block. # # @see https://github.com/rmosolgo/graphql-ruby/pull/2090 class NoneWithoutBlockCop < RuboCop::Cop::Base MSG = <<-MD Instead of `.none?` or `.any?` without a block: - Use `.empty?` to check for an empty collection (faster) - Add a block to explicitly check for `false` (more clear) Run `-a` to replace this with `%{bang}.empty?`. MD def on_block(node) # Since this method was called with a block, it can't be # a case of `.none?` without a block ignore_node(node.send_node) end def on_send(node) if !ignored_node?(node) && (node.method_name == :none? || node.method_name == :any?) && node.arguments.size == 0 add_offense(node, message: MSG % { bang: node.method_name == :none? ? "" : "!.." } ) end end def autocorrect(node) lambda do |corrector| if node.method_name == :none? corrector.replace(node.location.selector, "empty?") else # Backtrack to any chained method calls so we can insert `!` before them full_exp = node while node.parent.send_type? full_exp = node.parent end new_source = "!" + full_exp.source_range.source.sub("any?", "empty?") corrector.replace(full_exp, new_source) 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/cop/development/trace_methods_cop.rb
cop/development/trace_methods_cop.rb
# frozen_string_literal: true require 'rubocop' module Cop module Development class TraceMethodsCop < RuboCop::Cop::Base extend RuboCop::Cop::AutoCorrector TRACE_HOOKS = [ :analyze_multiplex, :analyze_query, :authorized, :authorized_lazy, :begin_analyze_multiplex, :begin_authorized, :begin_dataloader, :begin_dataloader_source, :begin_execute_field, :begin_resolve_type, :begin_validate, :dataloader_fiber_exit, :dataloader_fiber_resume, :dataloader_fiber_yield, :dataloader_spawn_execution_fiber, :dataloader_spawn_source_fiber, :end_analyze_multiplex, :end_authorized, :end_dataloader, :end_dataloader_source, :end_execute_field, :end_resolve_type, :end_validate, :execute_field, :execute_field_lazy, :execute_multiplex, :execute_query, :execute_query_lazy, :lex, :parse, :resolve_type, :resolve_type_lazy, :validate, ] MSG = "Trace methods should call `super` to pass control to other traces" def on_def(node) if TRACE_HOOKS.include?(node.method_name) && !node.each_descendant(:super, :zsuper).any? add_offense(node) do |corrector| if node.body offset = node.loc.column + 2 corrector.insert_after(node.body.loc.expression, "\n#{' ' * offset}super") end end end end def on_module(node) if node.defined_module_name.to_s.end_with?("Trace") all_defs = [] node.body.each_child_node do |body_node| if body_node.def_type? all_defs << body_node.method_name end end missing_defs = TRACE_HOOKS - all_defs redundant_defs = [ # Not really necessary for making a good trace: :lex, :analyze_query, :execute_query, :execute_query_lazy, # Only useful for isolated event tracking: :begin_dataloader, :end_dataloader, :dataloader_fiber_exit, :dataloader_spawn_execution_fiber, :dataloader_spawn_source_fiber ] missing_defs.each do |missing_def| if all_defs.include?(:"begin_#{missing_def}") && all_defs.include?(:"end_#{missing_def}") redundant_defs << missing_def redundant_defs << :"#{missing_def}_lazy" end missing_name = missing_def.to_s if missing_name.start_with?("begin") && all_defs.include?(:"#{missing_name.sub("begin_", "")}") redundant_defs << missing_def elsif missing_name.start_with?("end") && all_defs.include?(:"#{missing_name.sub("end_", "")}") redundant_defs << missing_def end end missing_defs -= redundant_defs if missing_defs.any? add_offense(node, message: "Missing some trace hook methods:\n\n- #{missing_defs.join("\n- ")}") 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/cop/development/no_eval_cop.rb
cop/development/no_eval_cop.rb
# frozen_string_literal: true require 'rubocop' module Cop module Development class NoEvalCop < RuboCop::Cop::Base MSG_TEMPLATE = "Don't use `%{eval_method_name}` which accepts strings and may result evaluating unexpected code. Use `%{exec_method_name}` instead, and pass a block." def on_send(node) case node.method_name when :module_eval, :class_eval, :instance_eval message = MSG_TEMPLATE % { eval_method_name: node.method_name, exec_method_name: node.method_name.to_s.sub("eval", "exec").to_sym } add_offense node, message: message end end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/cop/development/context_is_passed_cop.rb
cop/development/context_is_passed_cop.rb
# frozen_string_literal: true require 'rubocop' module Cop module Development class ContextIsPassedCop < RuboCop::Cop::Base MSG = <<-MSG This method also accepts `context` as an argument. Pass it so that the returned value will reflect the current query, or use another method that isn't context-dependent. MSG # These are already context-aware or else not query-related def_node_matcher :likely_query_specific_receiver?, " { (send _ {:ast_node :query :context :warden :ctx :query_ctx :query_context}) (lvar {:ast_node :query :context :warden :ctx :query_ctx :query_context}) (ivar {:@query :@context :@warden}) (send _ {:introspection_system}) } " def_node_matcher :method_doesnt_receive_second_context_argument?, <<-MATCHER (send _ {:get_field :get_argument :get_type} _) MATCHER def_node_matcher :method_doesnt_receive_first_context_argument?, <<-MATCHER (send _ {:fields :arguments :types :enum_values}) MATCHER def_node_matcher :is_enum_values_call_without_arguments?, " (send (send _ {:enum :enum_type (ivar {:@enum :@enum_type})}) {:values}) " def on_send(node) if ( method_doesnt_receive_second_context_argument?(node) || method_doesnt_receive_first_context_argument?(node) || is_enum_values_call_without_arguments?(node) ) && !likely_query_specific_receiver?(node.to_a[0]) add_offense(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/cop/development/no_focus_cop.rb
cop/development/no_focus_cop.rb
# frozen_string_literal: true require 'rubocop' module Cop module Development # Make sure no tests are focused, from https://github.com/rubocop-hq/rubocop/issues/3773#issuecomment-420662102 class NoFocusCop < RuboCop::Cop::Base MSG = 'Remove `focus` from tests.' def_node_matcher :focused?, <<-MATCHER (send nil? :focus) MATCHER def on_send(node) return unless focused?(node) add_offense node 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.rb
lib/graphql.rb
# frozen_string_literal: true require "delegate" require "json" require "set" require "singleton" require "forwardable" require "fiber/storage" if RUBY_VERSION < "3.2.0" require "graphql/autoload" module GraphQL extend Autoload # Load all `autoload`-configured classes, and also eager-load dependents who have autoloads of their own. def self.eager_load! super Query.eager_load! Types.eager_load! Schema.eager_load! end class Error < StandardError end # This error is raised when GraphQL-Ruby encounters a situation # that it *thought* would never happen. Please report this bug! class InvariantError < Error def initialize(message) message += " This is probably a bug in GraphQL-Ruby, please report this error on GitHub: https://github.com/rmosolgo/graphql-ruby/issues/new?template=bug_report.md" super(message) end end class RequiredImplementationMissingError < Error end class << self def default_parser @default_parser ||= GraphQL::Language::Parser end attr_writer :default_parser end # Turn a query string or schema definition into an AST # @param graphql_string [String] a GraphQL query string or schema definition # @return [GraphQL::Language::Nodes::Document] def self.parse(graphql_string, trace: GraphQL::Tracing::NullTrace, filename: nil, max_tokens: nil) default_parser.parse(graphql_string, trace: trace, filename: filename, max_tokens: max_tokens) end # Read the contents of `filename` and parse them as GraphQL # @param filename [String] Path to a `.graphql` file containing IDL or query # @return [GraphQL::Language::Nodes::Document] def self.parse_file(filename) content = File.read(filename) default_parser.parse(content, filename: filename) end # @return [Array<Array>] def self.scan(graphql_string) default_parser.scan(graphql_string) end def self.parse_with_racc(string, filename: nil, trace: GraphQL::Tracing::NullTrace) warn "`GraphQL.parse_with_racc` is deprecated; GraphQL-Ruby no longer uses racc for parsing. Call `GraphQL.parse` or `GraphQL::Language::Parser.parse` instead." GraphQL::Language::Parser.parse(string, filename: filename, trace: trace) end def self.scan_with_ruby(graphql_string) GraphQL::Language::Lexer.tokenize(graphql_string) end NOT_CONFIGURED = Object.new.freeze private_constant :NOT_CONFIGURED module EmptyObjects EMPTY_HASH = {}.freeze EMPTY_ARRAY = [].freeze end class << self # If true, the parser should raise when an integer or float is followed immediately by an identifier (instead of a space or punctuation) attr_accessor :reject_numbers_followed_by_names end self.reject_numbers_followed_by_names = false autoload :ExecutionError, "graphql/execution_error" autoload :RuntimeTypeError, "graphql/runtime_type_error" autoload :UnresolvedTypeError, "graphql/unresolved_type_error" autoload :InvalidNullError, "graphql/invalid_null_error" autoload :AnalysisError, "graphql/analysis_error" autoload :CoercionError, "graphql/coercion_error" autoload :InvalidNameError, "graphql/invalid_name_error" autoload :IntegerDecodingError, "graphql/integer_decoding_error" autoload :IntegerEncodingError, "graphql/integer_encoding_error" autoload :StringEncodingError, "graphql/string_encoding_error" autoload :DateEncodingError, "graphql/date_encoding_error" autoload :DurationEncodingError, "graphql/duration_encoding_error" autoload :TypeKinds, "graphql/type_kinds" autoload :NameValidator, "graphql/name_validator" autoload :Language, "graphql/language" autoload :Analysis, "graphql/analysis" autoload :Tracing, "graphql/tracing" autoload :Dig, "graphql/dig" autoload :Execution, "graphql/execution" autoload :Pagination, "graphql/pagination" autoload :Schema, "graphql/schema" autoload :Query, "graphql/query" autoload :Dataloader, "graphql/dataloader" autoload :Types, "graphql/types" autoload :StaticValidation, "graphql/static_validation" autoload :Execution, "graphql/execution" autoload :Introspection, "graphql/introspection" autoload :Relay, "graphql/relay" autoload :Subscriptions, "graphql/subscriptions" autoload :ParseError, "graphql/parse_error" autoload :Backtrace, "graphql/backtrace" autoload :UnauthorizedError, "graphql/unauthorized_error" autoload :UnauthorizedEnumValueError, "graphql/unauthorized_enum_value_error" autoload :UnauthorizedFieldError, "graphql/unauthorized_field_error" autoload :LoadApplicationObjectFailedError, "graphql/load_application_object_failed_error" autoload :Testing, "graphql/testing" autoload :Current, "graphql/current" if defined?(::Rails::Engine) autoload :Dashboard, 'graphql/dashboard' end end require "graphql/version" require "graphql/railtie" if defined? Rails::Railtie
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution_error.rb
lib/graphql/execution_error.rb
# frozen_string_literal: true module GraphQL # If a field's resolve function returns a {ExecutionError}, # the error will be inserted into the response's `"errors"` key # and the field will resolve to `nil`. class ExecutionError < GraphQL::Error # @return [GraphQL::Language::Nodes::Field] the field where the error occurred attr_accessor :ast_node # @return [String] an array describing the JSON-path into the execution # response which corresponds to this error. attr_accessor :path # @return [Hash] Optional data for error objects # @deprecated Use `extensions` instead of `options`. The GraphQL spec # recommends that any custom entries in an error be under the # `extensions` key. attr_accessor :options # @return [Hash] Optional custom data for error objects which will be added # under the `extensions` key. attr_accessor :extensions def initialize(message, ast_node: nil, options: nil, extensions: nil) @ast_node = ast_node @options = options @extensions = extensions super(message) end # @return [Hash] An entry for the response's "errors" key def to_h hash = { "message" => message, } if ast_node hash["locations"] = [ { "line" => ast_node.line, "column" => ast_node.col, } ] end if path hash["path"] = path end if options hash.merge!(options) end if extensions hash["extensions"] = extensions.each_with_object({}) { |(key, value), ext| ext[key.to_s] = value } end hash 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/rubocop.rb
lib/graphql/rubocop.rb
# frozen_string_literal: true require "graphql/rubocop/graphql/default_null_true" require "graphql/rubocop/graphql/default_required_true" require "graphql/rubocop/graphql/field_type_in_block" require "graphql/rubocop/graphql/root_types_in_block"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/current.rb
lib/graphql/current.rb
# frozen_string_literal: true module GraphQL # This module exposes Fiber-level runtime information. # # It won't work across unrelated fibers, although it will work in child Fibers. # # @example Setting Up ActiveRecord::QueryLogs # # config.active_record.query_log_tags = [ # :namespaced_controller, # :action, # :job, # # ... # { # # GraphQL runtime info: # current_graphql_operation: -> { GraphQL::Current.operation_name }, # current_graphql_field: -> { GraphQL::Current.field&.path }, # current_dataloader_source: -> { GraphQL::Current.dataloader_source_class }, # # ... # }, # ] # module Current # @return [String, nil] Comma-joined operation names for the currently-running {Execution::Multiplex}. `nil` if all operations are anonymous. def self.operation_name if (m = Fiber[:__graphql_current_multiplex]) m.context[:__graphql_current_operation_name] ||= begin names = m.queries.map { |q| q.selected_operation_name } if names.all?(&:nil?) nil else names.join(",") end end else nil end end # @see GraphQL::Field#path for a string identifying this field # @return [GraphQL::Field, nil] The currently-running field, if there is one. def self.field Fiber[:__graphql_runtime_info]&.values&.first&.current_field end # @return [Class, nil] The currently-running {Dataloader::Source} class, if there is one. def self.dataloader_source_class Fiber[:__graphql_current_dataloader_source]&.class end # @return [GraphQL::Dataloader::Source, nil] The currently-running source, if there is one def self.dataloader_source Fiber[:__graphql_current_dataloader_source] end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/language.rb
lib/graphql/language.rb
# frozen_string_literal: true require "graphql/language/block_string" require "graphql/language/comment" require "graphql/language/printer" require "graphql/language/sanitized_printer" require "graphql/language/document_from_schema_definition" require "graphql/language/generation" require "graphql/language/lexer" require "graphql/language/nodes" require "graphql/language/cache" require "graphql/language/parser" require "graphql/language/static_visitor" require "graphql/language/visitor" require "graphql/language/definition_slice" require "strscan" module GraphQL module Language # @api private def self.serialize(value) if value.is_a?(Hash) serialized_hash = value.map do |k, v| "#{k}:#{serialize v}" end.join(",") "{#{serialized_hash}}" elsif value.is_a?(Array) serialized_array = value.map do |v| serialize v end.join(",") "[#{serialized_array}]" else JSON.generate(value, quirks_mode: true) end rescue JSON::GeneratorError if Float::INFINITY == value "Infinity" else raise end end # Returns a new string if any single-quoted newlines were escaped. # Otherwise, returns `query_str` unchanged. # @return [String] def self.escape_single_quoted_newlines(query_str) scanner = StringScanner.new(query_str) inside_single_quoted_string = false new_query_str = nil while !scanner.eos? if scanner.skip(/(?:\\"|[^"\n\r]|""")+/m) new_query_str && (new_query_str << scanner.matched) elsif scanner.skip('"') new_query_str && (new_query_str << '"') inside_single_quoted_string = !inside_single_quoted_string elsif scanner.skip("\n") if inside_single_quoted_string new_query_str ||= query_str[0, scanner.pos - 1] new_query_str << '\\n' else new_query_str && (new_query_str << "\n") end elsif scanner.skip("\r") if inside_single_quoted_string new_query_str ||= query_str[0, scanner.pos - 1] new_query_str << '\\r' else new_query_str && (new_query_str << "\r") end elsif scanner.eos? break else raise ArgumentError, "Unmatchable string scanner segment: #{scanner.rest.inspect}" end end new_query_str || query_str end INVALID_NUMBER_FOLLOWED_BY_NAME_REGEXP = %r{ ( ((?<num>#{Lexer::INT_REGEXP}(#{Lexer::FLOAT_EXP_REGEXP})?)(?<name>#{Lexer::IDENTIFIER_REGEXP})#{Lexer::IGNORE_REGEXP}:) | ((?<num>#{Lexer::INT_REGEXP}#{Lexer::FLOAT_DECIMAL_REGEXP}#{Lexer::FLOAT_EXP_REGEXP})(?<name>#{Lexer::IDENTIFIER_REGEXP})#{Lexer::IGNORE_REGEXP}:) | ((?<num>#{Lexer::INT_REGEXP}#{Lexer::FLOAT_DECIMAL_REGEXP})(?<name>#{Lexer::IDENTIFIER_REGEXP})#{Lexer::IGNORE_REGEXP}:) )}x def self.add_space_between_numbers_and_names(query_str) if query_str.match?(INVALID_NUMBER_FOLLOWED_BY_NAME_REGEXP) query_str.gsub(INVALID_NUMBER_FOLLOWED_BY_NAME_REGEXP, "\\k<num> \\k<name>:") else query_str 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/unauthorized_enum_value_error.rb
lib/graphql/unauthorized_enum_value_error.rb
# frozen_string_literal: true module GraphQL class UnauthorizedEnumValueError < GraphQL::UnauthorizedError # @return [GraphQL::Schema::EnumValue] The value whose `#authorized?` check returned false attr_accessor :enum_value def initialize(type:, context:, enum_value:) @enum_value = enum_value message ||= "#{enum_value.path} failed authorization" super(message, object: enum_value.value, type: type, context: context) 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/duration_encoding_error.rb
lib/graphql/duration_encoding_error.rb
# frozen_string_literal: true module GraphQL # This error is raised when `Types::ISO8601Duration` is asked to return a value # that cannot be parsed as an ISO8601-formatted duration by ActiveSupport::Duration. # # @see GraphQL::Types::ISO8601Duration which raises this error class DurationEncodingError < GraphQL::RuntimeTypeError # The value which couldn't be encoded attr_reader :duration_value def initialize(value) @duration_value = value super("Duration cannot be parsed: #{value}. \nDuration must be an ISO8601-formatted duration.") 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/parse_error.rb
lib/graphql/parse_error.rb
# frozen_string_literal: true module GraphQL class ParseError < GraphQL::Error attr_reader :line, :col, :query def initialize(message, line, col, query, filename: nil) if filename message += " (#{filename})" end super(message) @line = line @col = col @query = query end def to_h locations = line ? [{ "line" => line, "column" => col }] : [] { "message" => message, "locations" => locations, } 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/version.rb
lib/graphql/version.rb
# frozen_string_literal: true module GraphQL VERSION = "2.5.16" end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/autoload.rb
lib/graphql/autoload.rb
# frozen_string_literal: true module GraphQL # @see GraphQL::Railtie for automatic Rails integration module Autoload # Register a constant named `const_name` to be loaded from `path`. # This is like `Kernel#autoload` but it tracks the constants so they can be eager-loaded with {#eager_load!} # @param const_name [Symbol] # @param path [String] # @return [void] def autoload(const_name, path) @_eagerloaded_constants ||= [] @_eagerloaded_constants << const_name super const_name, path end # Call this to load this constant's `autoload` dependents and continue calling recursively # @return [void] def eager_load! @_eager_loading = true if @_eagerloaded_constants @_eagerloaded_constants.each { |const_name| const_get(const_name) } @_eagerloaded_constants = nil end nil ensure @_eager_loading = false end private # @return [Boolean] `true` if GraphQL-Ruby is currently eager-loading its constants def eager_loading? @_eager_loading ||= false end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/analysis.rb
lib/graphql/analysis.rb
# frozen_string_literal: true require "graphql/analysis/visitor" require "graphql/analysis/analyzer" require "graphql/analysis/field_usage" require "graphql/analysis/query_complexity" require "graphql/analysis/max_query_complexity" require "graphql/analysis/query_depth" require "graphql/analysis/max_query_depth" module GraphQL module Analysis AST = self class TimeoutError < AnalysisError def initialize(...) super("Timeout on validation of query") end end module_function # Analyze a multiplex, and all queries within. # Multiplex analyzers are ran for all queries, keeping state. # Query analyzers are ran per query, without carrying state between queries. # # @param multiplex [GraphQL::Execution::Multiplex] # @param analyzers [Array<GraphQL::Analysis::Analyzer>] # @return [Array<Any>] Results from multiplex analyzers def analyze_multiplex(multiplex, analyzers) multiplex_analyzers = analyzers.map { |analyzer| analyzer.new(multiplex) } multiplex.current_trace.analyze_multiplex(multiplex: multiplex) do query_results = multiplex.queries.map do |query| if query.valid? analyze_query( query, query.analyzers, multiplex_analyzers: multiplex_analyzers ) else [] end end multiplex_results = multiplex_analyzers.map(&:result) multiplex_errors = analysis_errors(multiplex_results) multiplex.queries.each_with_index do |query, idx| query.analysis_errors = multiplex_errors + analysis_errors(query_results[idx]) end multiplex_results end end # @param query [GraphQL::Query] # @param analyzers [Array<GraphQL::Analysis::Analyzer>] # @return [Array<Any>] Results from those analyzers def analyze_query(query, analyzers, multiplex_analyzers: []) query.current_trace.analyze_query(query: query) do query_analyzers = analyzers .map { |analyzer| analyzer.new(query) } .tap { _1.select!(&:analyze?) } analyzers_to_run = query_analyzers + multiplex_analyzers if !analyzers_to_run.empty? analyzers_to_run.select!(&:visit?) if !analyzers_to_run.empty? visitor = GraphQL::Analysis::Visitor.new( query: query, analyzers: analyzers_to_run, timeout: query.validate_timeout_remaining, ) visitor.visit if !visitor.rescued_errors.empty? return visitor.rescued_errors end end query_analyzers.map(&:result) else [] end end rescue TimeoutError => err [err] rescue GraphQL::UnauthorizedError, GraphQL::ExecutionError # This error was raised during analysis and will be returned the client before execution [] end def analysis_errors(results) results.flatten.tap { _1.select! { |r| r.is_a?(GraphQL::AnalysisError) } } end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dashboard.rb
lib/graphql/dashboard.rb
# frozen_string_literal: true require 'rails/engine' module Graphql # `GraphQL::Dashboard` is a `Rails::Engine`-based dashboard for viewing metadata about your GraphQL schema. # # Pass the class name of your schema when mounting it. # @see GraphQL::Tracing::DetailedTrace DetailedTrace for viewing production traces in the Dashboard # # @example Mounting the Dashboard in your app # mount GraphQL::Dashboard, at: "graphql_dashboard", schema: "MySchema" # # @example Authenticating the Dashboard with HTTP Basic Auth # # config/initializers/graphql_dashboard.rb # GraphQL::Dashboard.middleware.use(Rack::Auth::Basic) do |username, password| # # Compare the provided username/password to an application setting: # ActiveSupport::SecurityUtils.secure_compare(Rails.application.credentials.graphql_dashboard_username, username) && # ActiveSupport::SecurityUtils.secure_compare(Rails.application.credentials.graphql_dashboard_username, password) # end # # @example Custom Rails authentication # # config/initializers/graphql_dashboard.rb # ActiveSupport.on_load(:graphql_dashboard_application_controller) do # # context here is GraphQL::Dashboard::ApplicationController # # before_action do # raise ActionController::RoutingError.new('Not Found') unless current_user&.admin? # end # # def current_user # # load current user # end # end # class Dashboard < Rails::Engine engine_name "graphql_dashboard" isolate_namespace(Graphql::Dashboard) routes.draw do root "landings#show" resources :statics, only: :show, constraints: { id: /[0-9A-Za-z\-.]+/ } namespace :detailed_traces do resources :traces, only: [:index, :show, :destroy] do collection do delete :delete_all, to: "traces#delete_all", as: :delete_all end end end namespace :limiters do resources :limiters, only: [:show, :update], param: :name end namespace :operation_store do resources :clients, param: :name do resources :operations, param: :digest, only: [:index] do collection do get :archived, to: "operations#index", archived_status: :archived, as: :archived post :archive, to: "operations#update", modification: :archive, as: :archive post :unarchive, to: "operations#update", modification: :unarchive, as: :unarchive end end end resources :operations, param: :digest, only: [:index, :show] do collection do get :archived, to: "operations#index", archived_status: :archived, as: :archived post :archive, to: "operations#update", modification: :archive, as: :archive post :unarchive, to: "operations#update", modification: :unarchive, as: :unarchive end end resources :index_entries, only: [:index, :show], param: :name, constraints: { name: /[A-Za-z0-9_.]+/} end namespace :subscriptions do resources :topics, only: [:index, :show], param: :name, constraints: { name: /.*/ } resources :subscriptions, only: [:show], constraints: { id: /[a-zA-Z0-9\-]+/ } post "/subscriptions/clear_all", to: "subscriptions#clear_all", as: :clear_all end end class ApplicationController < ActionController::Base protect_from_forgery with: :exception prepend_view_path(File.join(__FILE__, "../dashboard/views")) content_security_policy do |policy| policy.default_src(:self) if policy.default_src(*policy.default_src).blank? policy.connect_src(:self) if policy.connect_src(*policy.connect_src).blank? policy.base_uri(:none) if policy.base_uri(*policy.base_uri).blank? policy.font_src(:self) if policy.font_src(*policy.font_src).blank? policy.img_src(:self, :data) if policy.img_src(*policy.img_src).blank? policy.object_src(:none) if policy.object_src(*policy.object_src).blank? policy.script_src(:self) if policy.script_src(*policy.script_src).blank? policy.style_src(:self) if policy.style_src(*policy.style_src).blank? policy.form_action(:self) if policy.form_action(*policy.form_action).blank? policy.frame_ancestors(:none) if policy.frame_ancestors(*policy.frame_ancestors).blank? end def schema_class @schema_class ||= begin schema_param = request.query_parameters["schema"] || params[:schema] case schema_param when Class schema_param when String schema_param.constantize else raise "Missing `params[:schema]`, please provide a class or string to `mount GraphQL::Dashboard, schema: ...`" end end end helper_method :schema_class end class LandingsController < ApplicationController def show end end class StaticsController < ApplicationController skip_after_action :verify_same_origin_request # Use an explicit list of files to avoid any chance of reading other files from disk STATICS = {} [ "icon.png", "header-icon.png", "charts.min.css", "dashboard.css", "dashboard.js", "bootstrap-5.3.3.min.css", "bootstrap-5.3.3.min.js", ].each do |static_file| STATICS[static_file] = File.expand_path("../dashboard/statics/#{static_file}", __FILE__) end def show expires_in 1.year, public: true if (filepath = STATICS[params[:id]]) render file: filepath else head :not_found end end end end end require 'graphql/dashboard/detailed_traces' require 'graphql/dashboard/limiters' require 'graphql/dashboard/operation_store' require 'graphql/dashboard/subscriptions' # Rails expects the engine to be called `Graphql::Dashboard`, # but `GraphQL::Dashboard` is consistent with this gem's naming. # So define both constants to refer to the same class. GraphQL::Dashboard = Graphql::Dashboard ActiveSupport.run_load_hooks(:graphql_dashboard_application_controller, GraphQL::Dashboard::ApplicationController)
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/unauthorized_error.rb
lib/graphql/unauthorized_error.rb
# frozen_string_literal: true module GraphQL # When an `authorized?` hook returns false, this error is used to communicate the failure. # It's passed to {Schema.unauthorized_object}. # # Alternatively, custom code in `authorized?` may raise this error. It will be routed the same way. class UnauthorizedError < GraphQL::Error # @return [Object] the application object that failed the authorization check attr_reader :object # @return [Class] the GraphQL object type whose `.authorized?` method was called (and returned false) attr_reader :type # @return [GraphQL::Query::Context] the context for the current query attr_accessor :context def initialize(message = nil, object: nil, type: nil, context: nil) if message.nil? && object.nil? && type.nil? raise ArgumentError, "#{self.class.name} requires either a message or keywords" end @object = object @type = type @context = context message ||= "An instance of #{object.class} failed #{type.graphql_name}'s authorization check" super(message) 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/relay.rb
lib/graphql/relay.rb
# frozen_string_literal: true require 'graphql/relay/range_add'
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/string_encoding_error.rb
lib/graphql/string_encoding_error.rb
# frozen_string_literal: true module GraphQL class StringEncodingError < GraphQL::RuntimeTypeError attr_reader :string, :field, :path def initialize(str, context:) @string = str @field = context[:current_field] @path = context[:current_path] message = "String #{str.inspect} was encoded as #{str.encoding}".dup if @path message << " @ #{@path.join(".")}" end if @field message << " (#{@field.path})" end message << ". GraphQL requires an encoding compatible with UTF-8." super(message) 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/load_application_object_failed_error.rb
lib/graphql/load_application_object_failed_error.rb
# frozen_string_literal: true module GraphQL # Raised when a argument is configured with `loads:` and the client provides an `ID`, # but no object is loaded for that ID. # # @see GraphQL::Schema::Member::HasArguments::ArgumentObjectLoader#load_application_object_failed, A hook which you can override in resolvers, mutations and input objects. class LoadApplicationObjectFailedError < GraphQL::ExecutionError # @return [GraphQL::Schema::Argument] the argument definition for the argument that was looked up attr_reader :argument # @return [String] The ID provided by the client attr_reader :id # @return [Object] The value found with this ID attr_reader :object # @return [GraphQL::Query::Context] attr_reader :context def initialize(argument:, id:, object:, context:) @id = id @argument = argument @object = object @context = context super("No object found for `#{argument.graphql_name}: #{id.inspect}`") 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/query.rb
lib/graphql/query.rb
# frozen_string_literal: true module GraphQL # A combination of query string and {Schema} instance which can be reduced to a {#result}. class Query extend Autoload include Tracing::Traceable extend Forwardable autoload :Context, "graphql/query/context" autoload :Fingerprint, "graphql/query/fingerprint" autoload :NullContext, "graphql/query/null_context" autoload :Partial, "graphql/query/partial" autoload :Result, "graphql/query/result" autoload :Variables, "graphql/query/variables" autoload :InputValidationResult, "graphql/query/input_validation_result" autoload :VariableValidationError, "graphql/query/variable_validation_error" autoload :ValidationPipeline, "graphql/query/validation_pipeline" # Code shared with {Partial} module Runnable def after_lazy(value, &block) if !defined?(@runtime_instance) @runtime_instance = context.namespace(:interpreter_runtime)[:runtime] end if @runtime_instance @runtime_instance.minimal_after_lazy(value, &block) else @schema.after_lazy(value, &block) end end # Node-level cache for calculating arguments. Used during execution and query analysis. # @param ast_node [GraphQL::Language::Nodes::AbstractNode] # @param definition [GraphQL::Schema::Field] # @param parent_object [GraphQL::Schema::Object] # @return [Hash{Symbol => Object}] def arguments_for(ast_node, definition, parent_object: nil) arguments_cache.fetch(ast_node, definition, parent_object) end def arguments_cache @arguments_cache ||= Execution::Interpreter::ArgumentsCache.new(self) end # @api private def handle_or_reraise(err) @schema.handle_or_reraise(context, err) end end include Runnable class OperationNameMissingError < GraphQL::ExecutionError def initialize(name) msg = if name.nil? %|An operation name is required| else %|No operation named "#{name}"| end super(msg) end end attr_reader :schema, :context, :provided_variables # The value for root types attr_accessor :root_value # @return [nil, String] The operation name provided by client or the one inferred from the document. Used to determine which operation to run. attr_accessor :operation_name # @return [Boolean] if false, static validation is skipped (execution behavior for invalid queries is undefined) attr_reader :validate # @param new_validate [Boolean] if false, static validation is skipped. This can't be reasssigned after validation. def validate=(new_validate) if defined?(@validation_pipeline) && @validation_pipeline && @validation_pipeline.has_validated? raise ArgumentError, "Can't reassign Query#validate= after validation has run, remove this assignment." else @validate = new_validate end end # @return [GraphQL::StaticValidation::Validator] if present, the query will validate with these rules. attr_reader :static_validator # @param new_validator [GraphQL::StaticValidation::Validator] if present, the query will validate with these rules. This can't be reasssigned after validation. def static_validator=(new_validator) if defined?(@validation_pipeline) && @validation_pipeline && @validation_pipeline.has_validated? raise ArgumentError, "Can't reassign Query#static_validator= after validation has run, remove this assignment." elsif !new_validator.is_a?(GraphQL::StaticValidation::Validator) raise ArgumentError, "Expected a `GraphQL::StaticValidation::Validator` instance." else @static_validator = new_validator end end attr_writer :query_string # @return [GraphQL::Language::Nodes::Document] def document # It's ok if this hasn't been assigned yet if @query_string || @document with_prepared_ast { @document } else nil end end def inspect "query ..." end # @return [String, nil] The name of the operation to run (may be inferred) def selected_operation_name return nil unless selected_operation selected_operation.name end # @return [String, nil] the triggered event, if this query is a subscription update attr_reader :subscription_topic attr_reader :tracers # Prepare query `query_string` on `schema` # @param schema [GraphQL::Schema] # @param query_string [String] # @param context [#[]] an arbitrary hash of values which you can access in {GraphQL::Field#resolve} # @param variables [Hash] values for `$variables` in the query # @param operation_name [String] if the query string contains many operations, this is the one which should be executed # @param root_value [Object] the object used to resolve fields on the root type # @param max_depth [Numeric] the maximum number of nested selections allowed for this query (falls back to schema-level value) # @param max_complexity [Numeric] the maximum field complexity for this query (falls back to schema-level value) # @param visibility_profile [Symbol] Another way to assign `context[:visibility_profile]` def initialize(schema, query_string = nil, query: nil, document: nil, context: nil, variables: nil, multiplex: nil, validate: true, static_validator: nil, visibility_profile: nil, subscription_topic: nil, operation_name: nil, root_value: nil, max_depth: schema.max_depth, max_complexity: schema.max_complexity, warden: nil, use_visibility_profile: nil) # Even if `variables: nil` is passed, use an empty hash for simpler logic variables ||= {} @multiplex = multiplex @schema = schema @context = schema.context_class.new(query: self, values: context) if visibility_profile @context[:visibility_profile] ||= visibility_profile end if use_visibility_profile.nil? use_visibility_profile = warden ? false : schema.use_visibility_profile? end if use_visibility_profile @visibility_profile = @schema.visibility.profile_for(@context) @warden = Schema::Warden::NullWarden.new(context: @context, schema: @schema) else @visibility_profile = nil @warden = warden end @subscription_topic = subscription_topic @root_value = root_value @fragments = nil @operations = nil @validate = validate self.static_validator = static_validator if static_validator context_tracers = (context ? context.fetch(:tracers, []) : []) @tracers = schema.tracers + context_tracers if !context_tracers.empty? && !(schema.trace_class <= GraphQL::Tracing::CallLegacyTracers) raise ArgumentError, "context[:tracers] are not supported without `trace_with(GraphQL::Tracing::CallLegacyTracers)` in the schema configuration, please add it." end @analysis_errors = [] if variables.is_a?(String) raise ArgumentError, "Query variables should be a Hash, not a String. Try JSON.parse to prepare variables." else @provided_variables = variables || {} end @query_string = query_string || query @document = document if @query_string && @document raise ArgumentError, "Query should only be provided a query string or a document, not both." end if @query_string && !@query_string.is_a?(String) raise ArgumentError, "Query string argument should be a String, got #{@query_string.class.name} instead." end # A two-layer cache of type resolution: # { abstract_type => { value => resolved_type } } @resolved_types_cache = Hash.new do |h1, k1| h1[k1] = Hash.new do |h2, k2| h2[k2] = @schema.resolve_type(k1, k2, @context) end end # Trying to execute a document # with no operations returns an empty hash @ast_variables = [] @mutation = false @operation_name = operation_name @prepared_ast = false @validation_pipeline = nil @max_depth = max_depth @max_complexity = max_complexity @result_values = nil @executed = false @logger = schema.logger_for(context) end # If a document was provided to `GraphQL::Schema#execute` instead of the raw query string, we will need to get it from the document def query_string @query_string ||= (document ? document.to_query_string : nil) end # @return [Symbol, nil] attr_reader :visibility_profile attr_accessor :multiplex # @return [GraphQL::Tracing::Trace] def current_trace @current_trace ||= context[:trace] || (multiplex ? multiplex.current_trace : schema.new_trace(multiplex: multiplex, query: self)) end def subscription_update? @subscription_topic && subscription? end # A lookahead for the root selections of this query # @return [GraphQL::Execution::Lookahead] def lookahead @lookahead ||= begin if selected_operation.nil? GraphQL::Execution::Lookahead::NULL_LOOKAHEAD else GraphQL::Execution::Lookahead.new(query: self, root_type: root_type, ast_nodes: [selected_operation]) end end end # @api private def result_values=(result_hash) if @executed raise "Invariant: Can't reassign result" else @executed = true @result_values = result_hash end end # @api private attr_reader :result_values def fragments with_prepared_ast { @fragments } end def operations with_prepared_ast { @operations } end # Run subtree partials of this query and return their results. # Each partial is identified with a `path:` and `object:` # where the path references a field in the AST and the object will be treated # as the return value from that field. Subfields of the field named by `path` # will be executed with `object` as the starting point # @param partials_hashes [Array<Hash{Symbol => Object}>] Hashes with `path:` and `object:` keys # @return [Array<GraphQL::Query::Result>] def run_partials(partials_hashes) partials = partials_hashes.map { |partial_options| Partial.new(query: self, **partial_options) } Execution::Interpreter.run_all(@schema, partials, context: @context) end # Get the result for this query, executing it once # @return [GraphQL::Query::Result] A Hash-like GraphQL response, with `"data"` and/or `"errors"` keys def result if !@executed Execution::Interpreter.run_all(@schema, [self], context: @context) end @result ||= Query::Result.new(query: self, values: @result_values) end def executed? @executed end def static_errors validation_errors + analysis_errors + context.errors end # This is the operation to run for this query. # If more than one operation is present, it must be named at runtime. # @return [GraphQL::Language::Nodes::OperationDefinition, nil] def selected_operation with_prepared_ast { @selected_operation } end # Determine the values for variables of this query, using default values # if a value isn't provided at runtime. # # If some variable is invalid, errors are added to {#validation_errors}. # # @return [GraphQL::Query::Variables] Variables to apply to this query def variables @variables ||= begin with_prepared_ast { GraphQL::Query::Variables.new( @context, @ast_variables, @provided_variables, ) } end end # A version of the given query string, with: # - Variables inlined to the query # - Strings replaced with `<REDACTED>` # @return [String, nil] Returns nil if the query is invalid. def sanitized_query_string(inline_variables: true) with_prepared_ast { schema.sanitized_printer.new(self, inline_variables: inline_variables).sanitized_query_string } end # This contains a few components: # # - The selected operation name (or `anonymous`) # - The fingerprint of the query string # - The number of given variables (for readability) # - The fingerprint of the given variables # # This fingerprint can be used to track runs of the same operation-variables combination over time. # # @see operation_fingerprint # @see variables_fingerprint # @return [String] An opaque hash identifying this operation-variables combination def fingerprint @fingerprint ||= "#{operation_fingerprint}/#{variables_fingerprint}" end # @return [String] An opaque hash for identifying this query's given query string and selected operation def operation_fingerprint @operation_fingerprint ||= "#{selected_operation_name || "anonymous"}/#{Fingerprint.generate(query_string || "")}" end # @return [String] An opaque hash for identifying this query's given a variable values (not including defaults) def variables_fingerprint @variables_fingerprint ||= "#{provided_variables.size}/#{Fingerprint.generate(provided_variables.to_json)}" end def validation_pipeline with_prepared_ast { @validation_pipeline } end def_delegators :validation_pipeline, :validation_errors, :analyzers, :ast_analyzers, :max_depth, :max_complexity, :validate_timeout_remaining attr_accessor :analysis_errors def valid? validation_pipeline.valid? && analysis_errors.empty? end def warden with_prepared_ast { @warden } end def get_type(type_name) types.type(type_name) # rubocop:disable Development/ContextIsPassedCop end def get_field(owner, field_name) types.field(owner, field_name) # rubocop:disable Development/ContextIsPassedCop end def possible_types(type) types.possible_types(type) # rubocop:disable Development/ContextIsPassedCop end def root_type_for_operation(op_type) case op_type when "query", nil types.query_root # rubocop:disable Development/ContextIsPassedCop when "mutation" types.mutation_root # rubocop:disable Development/ContextIsPassedCop when "subscription" types.subscription_root # rubocop:disable Development/ContextIsPassedCop else raise ArgumentError, "unexpected root type name: #{op_type.inspect}; expected nil, 'query', 'mutation', or 'subscription'" end end def root_type root_type_for_operation(selected_operation.operation_type) end def types @visibility_profile || warden.visibility_profile end # @param abstract_type [GraphQL::UnionType, GraphQL::InterfaceType] # @param value [Object] Any runtime value # @return [GraphQL::ObjectType, nil] The runtime type of `value` from {Schema#resolve_type} # @see {#possible_types} to apply filtering from `only` / `except` def resolve_type(abstract_type, value = NOT_CONFIGURED) if value.is_a?(Symbol) && value == NOT_CONFIGURED # Old method signature value = abstract_type abstract_type = nil end if value.is_a?(GraphQL::Schema::Object) value = value.object end @resolved_types_cache[abstract_type][value] end def mutation? with_prepared_ast { @mutation } end def query? with_prepared_ast { @query } end def subscription? with_prepared_ast { @subscription } end attr_reader :logger private def find_operation(operations, operation_name) if operation_name.nil? && operations.length == 1 operations.values.first elsif !operations.key?(operation_name) nil else operations.fetch(operation_name) end end def prepare_ast @prepared_ast = true @warden ||= @schema.warden_class.new(schema: @schema, context: @context) parse_error = nil @document ||= begin if query_string GraphQL.parse(query_string, trace: self.current_trace, max_tokens: @schema.max_query_string_tokens) end rescue GraphQL::ParseError => err parse_error = err @schema.parse_error(err, @context) nil end @fragments = {} @operations = {} if @document @document.definitions.each do |part| case part when GraphQL::Language::Nodes::FragmentDefinition @fragments[part.name] = part when GraphQL::Language::Nodes::OperationDefinition @operations[part.name] = part end end elsif parse_error # This will be handled later else parse_error = GraphQL::ExecutionError.new("No query string was present") @context.add_error(parse_error) end # Trying to execute a document # with no operations returns an empty hash @ast_variables = [] @mutation = false @subscription = false operation_name_error = nil if !@operations.empty? @selected_operation = find_operation(@operations, @operation_name) if @selected_operation.nil? operation_name_error = GraphQL::Query::OperationNameMissingError.new(@operation_name) else if @operation_name.nil? @operation_name = @selected_operation.name end @ast_variables = @selected_operation.variables @mutation = @selected_operation.operation_type == "mutation" @query = @selected_operation.operation_type == "query" @subscription = @selected_operation.operation_type == "subscription" end end @validation_pipeline = GraphQL::Query::ValidationPipeline.new( query: self, parse_error: parse_error, operation_name_error: operation_name_error, max_depth: @max_depth, max_complexity: @max_complexity ) end # Since the query string is processed at the last possible moment, # any internal values which depend on it should be accessed within this wrapper. def with_prepared_ast if !@prepared_ast prepare_ast end yield end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/pagination.rb
lib/graphql/pagination.rb
# frozen_string_literal: true require "graphql/pagination/array_connection" require "graphql/pagination/active_record_relation_connection" require "graphql/pagination/connections" require "graphql/pagination/mongoid_relation_connection" require "graphql/pagination/sequel_dataset_connection"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/invalid_name_error.rb
lib/graphql/invalid_name_error.rb
# frozen_string_literal: true module GraphQL class InvalidNameError < GraphQL::Error attr_reader :name, :valid_regex def initialize(name, valid_regex) @name = name @valid_regex = valid_regex super("Names must match #{@valid_regex.inspect} but '#{@name}' does not") end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/backtrace.rb
lib/graphql/backtrace.rb
# frozen_string_literal: true require "graphql/backtrace/table" require "graphql/backtrace/traced_error" module GraphQL # Wrap unhandled errors with {TracedError}. # # {TracedError} provides a GraphQL backtrace with arguments and return values. # The underlying error is available as {TracedError#cause}. # # @example toggling backtrace annotation # class MySchema < GraphQL::Schema # if Rails.env.development? || Rails.env.test? # use GraphQL::Backtrace # end # end # class Backtrace include Enumerable extend Forwardable def_delegators :to_a, :each, :[] def self.use(schema_defn) schema_defn.using_backtrace = true end def initialize(context, value: nil) @table = Table.new(context, value: value) end def inspect @table.to_table end alias :to_s :inspect def to_a @table.to_backtrace 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/unresolved_type_error.rb
lib/graphql/unresolved_type_error.rb
# frozen_string_literal: true module GraphQL # Error raised when the value provided for a field # can't be resolved to one of the possible types for the field. class UnresolvedTypeError < GraphQL::RuntimeTypeError # @return [Object] The runtime value which couldn't be successfully resolved with `resolve_type` attr_reader :value # @return [GraphQL::Field] The field whose value couldn't be resolved (`field.type` is type which couldn't be resolved) attr_reader :field # @return [GraphQL::BaseType] The owner of `field` attr_reader :parent_type # @return [Object] The return of {Schema#resolve_type} for `value` attr_reader :resolved_type # @return [Array<GraphQL::BaseType>] The allowed options for resolving `value` to `field.type` attr_reader :possible_types def initialize(value, field, parent_type, resolved_type, possible_types) @value = value @field = field @parent_type = parent_type @resolved_type = resolved_type @possible_types = possible_types message = "The value from \"#{field.graphql_name}\" on \"#{parent_type.graphql_name}\" could not be resolved to \"#{field.type.to_type_signature}\". " \ "(Received: `#{resolved_type.inspect}`, Expected: [#{possible_types.map(&:graphql_name).join(", ")}]) " \ "Make sure you have defined a `resolve_type` proc on your schema and that value `#{value.inspect}` " \ "gets resolved to a valid type. You may need to add your type to `orphan_types` if it implements an " \ "interface but isn't a return type of any other field." super(message) 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.rb
lib/graphql/static_validation.rb
# frozen_string_literal: true require "graphql/static_validation/error" require "graphql/static_validation/definition_dependencies" require "graphql/static_validation/validator" require "graphql/static_validation/validation_context" require "graphql/static_validation/validation_timeout_error" require "graphql/static_validation/literal_validator" require "graphql/static_validation/base_visitor" rules_glob = File.expand_path("../static_validation/rules/*.rb", __FILE__) Dir.glob(rules_glob).each do |file| require(file) end require "graphql/static_validation/all_rules" require "graphql/static_validation/interpreter_visitor"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/type_kinds.rb
lib/graphql/type_kinds.rb
# frozen_string_literal: true module GraphQL # Type kinds are the basic categories which a type may belong to (`Object`, `Scalar`, `Union`...) module TypeKinds # These objects are singletons, eg `GraphQL::TypeKinds::UNION`, `GraphQL::TypeKinds::SCALAR`. class TypeKind attr_reader :name, :description def initialize(name, abstract: false, leaf: false, fields: false, wraps: false, input: false, description: nil) @name = name @abstract = abstract @fields = fields @wraps = wraps @input = input @leaf = leaf @composite = fields? || abstract? @description = description freeze end # Does this TypeKind have multiple possible implementers? # @deprecated Use `abstract?` instead of `resolves?`. def resolves?; @abstract; end # Is this TypeKind abstract? def abstract?; @abstract; end # Does this TypeKind have queryable fields? def fields?; @fields; end # Does this TypeKind modify another type? def wraps?; @wraps; end # Is this TypeKind a valid query input? def input?; @input; end def to_s; @name; end # Is this TypeKind a primitive value? def leaf?; @leaf; end # Is this TypeKind composed of many values? def composite?; @composite; end def scalar? self == TypeKinds::SCALAR end def object? self == TypeKinds::OBJECT end def interface? self == TypeKinds::INTERFACE end def union? self == TypeKinds::UNION end def enum? self == TypeKinds::ENUM end def input_object? self == TypeKinds::INPUT_OBJECT end def list? self == TypeKinds::LIST end def non_null? self == TypeKinds::NON_NULL end end TYPE_KINDS = [ SCALAR = TypeKind.new("SCALAR", input: true, leaf: true, description: 'Indicates this type is a scalar.'), OBJECT = TypeKind.new("OBJECT", fields: true, description: 'Indicates this type is an object. `fields` and `interfaces` are valid fields.'), INTERFACE = TypeKind.new("INTERFACE", abstract: true, fields: true, description: 'Indicates this type is an interface. `fields` and `possibleTypes` are valid fields.'), UNION = TypeKind.new("UNION", abstract: true, description: 'Indicates this type is a union. `possibleTypes` is a valid field.'), ENUM = TypeKind.new("ENUM", input: true, leaf: true, description: 'Indicates this type is an enum. `enumValues` is a valid field.'), INPUT_OBJECT = TypeKind.new("INPUT_OBJECT", input: true, description: 'Indicates this type is an input object. `inputFields` is a valid field.'), LIST = TypeKind.new("LIST", wraps: true, description: 'Indicates this type is a list. `ofType` is a valid field.'), NON_NULL = TypeKind.new("NON_NULL", wraps: true, description: 'Indicates this type is a non-null. `ofType` is a valid field.'), ] 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/railtie.rb
lib/graphql/railtie.rb
# frozen_string_literal: true module GraphQL # Support {GraphQL::Parser::Cache} and {GraphQL.eager_load!} # # @example Enable the parser cache with default directory # # config.graphql.parser_cache = true # class Railtie < Rails::Railtie config.graphql = ActiveSupport::OrderedOptions.new config.graphql.parser_cache = false config.eager_load_namespaces << GraphQL initializer("graphql.cache") do |app| if config.graphql.parser_cache Language::Parser.cache ||= Language::Cache.new( app.root.join("tmp/cache/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/rake_task.rb
lib/graphql/rake_task.rb
# frozen_string_literal: true require "fileutils" require "rake" require "graphql/rake_task/validate" module GraphQL # A rake task for dumping a schema as IDL or JSON. # # By default, schemas are looked up by name as constants using `schema_name:`. # You can provide a `load_schema` function to return your schema another way. # # Use `load_context:` and `visible?` to dump schemas under certain visibility constraints. # # @example Dump a Schema to .graphql + .json files # require "graphql/rake_task" # GraphQL::RakeTask.new(schema_name: "MySchema") # # # $ rake graphql:schema:dump # # Schema IDL dumped to ./schema.graphql # # Schema JSON dumped to ./schema.json # # @example Invoking the task from Ruby # require "rake" # Rake::Task["graphql:schema:dump"].invoke # # @example Providing arguments to build the introspection query # require "graphql/rake_task" # GraphQL::RakeTask.new(schema_name: "MySchema", include_is_one_of: true) class RakeTask include Rake::DSL DEFAULT_OPTIONS = { namespace: "graphql", dependencies: nil, schema_name: nil, load_schema: ->(task) { Object.const_get(task.schema_name) }, load_context: ->(task) { {} }, directory: ".", idl_outfile: "schema.graphql", json_outfile: "schema.json", include_deprecated_args: true, include_schema_description: false, include_is_repeatable: false, include_specified_by_url: false, include_is_one_of: false } # @return [String] Namespace for generated tasks attr_writer :namespace def rake_namespace @namespace end # @return [Array<String>] attr_accessor :dependencies # @return [String] By default, used to find the schema as a constant. # @see {#load_schema} for loading a schema another way attr_accessor :schema_name # @return [<#call(task)>] A proc for loading the target GraphQL schema attr_accessor :load_schema # @return [<#call(task)>] A callable for loading the query context attr_accessor :load_context # @return [String] target for IDL task attr_accessor :idl_outfile # @return [String] target for JSON task attr_accessor :json_outfile # @return [String] directory for IDL & JSON files attr_accessor :directory # @return [Boolean] Options for additional fields in the introspection query JSON response # @see GraphQL::Schema.as_json attr_accessor :include_deprecated_args, :include_schema_description, :include_is_repeatable, :include_specified_by_url, :include_is_one_of # Set the parameters of this task by passing keyword arguments # or assigning attributes inside the block def initialize(options = {}) all_options = DEFAULT_OPTIONS.merge(options) all_options.each do |k, v| self.public_send("#{k}=", v) end if block_given? yield(self) end define_task end private # Use the provided `method_name` to generate a string from the specified schema # then write it to `file`. def write_outfile(method_name, file) schema = @load_schema.call(self) context = @load_context.call(self) result = case method_name when :to_json schema.to_json( include_is_one_of: include_is_one_of, include_deprecated_args: include_deprecated_args, include_is_repeatable: include_is_repeatable, include_specified_by_url: include_specified_by_url, include_schema_description: include_schema_description, context: context ) when :to_definition schema.to_definition(context: context) else raise ArgumentError, "Unexpected schema dump method: #{method_name.inspect}" end dir = File.dirname(file) FileUtils.mkdir_p(dir) if !result.end_with?("\n") result += "\n" end File.write(file, result) end def idl_path File.join(@directory, @idl_outfile) end def json_path File.join(@directory, @json_outfile) end def load_rails_environment_if_defined if Rake::Task.task_defined?('environment') Rake::Task['environment'].invoke end end # Use the Rake DSL to add tasks def define_task namespace(@namespace) do namespace("schema") do desc("Dump the schema to IDL in #{idl_path}") task :idl => @dependencies do load_rails_environment_if_defined write_outfile(:to_definition, idl_path) puts "Schema IDL dumped into #{idl_path}" end desc("Dump the schema to JSON in #{json_path}") task :json => @dependencies do load_rails_environment_if_defined write_outfile(:to_json, json_path) puts "Schema JSON dumped into #{json_path}" end desc("Dump the schema to JSON and IDL") task :dump => [:idl, :json] 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/integer_encoding_error.rb
lib/graphql/integer_encoding_error.rb
# frozen_string_literal: true module GraphQL # This error is raised when `Types::Int` is asked to return a value outside of 32-bit integer range. # # For values outside that range, consider: # # - `ID` for database primary keys or other identifiers # - `GraphQL::Types::BigInt` for really big integer values # # @see GraphQL::Types::Int which raises this error class IntegerEncodingError < GraphQL::RuntimeTypeError # The value which couldn't be encoded attr_reader :integer_value # @return [GraphQL::Schema::Field] The field that returned a too-big integer attr_reader :field # @return [Array<String, Integer>] Where the field appeared in the GraphQL response attr_reader :path def initialize(value, context:) @integer_value = value @field = context[:current_field] @path = context[:current_path] message = "Integer out of bounds: #{value}".dup if @path message << " @ #{@path.join(".")}" end if @field message << " (#{@field.path})" end message << ". Consider using ID or GraphQL::Types::BigInt instead." super(message) 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/date_encoding_error.rb
lib/graphql/date_encoding_error.rb
# frozen_string_literal: true module GraphQL # This error is raised when `Types::ISO8601Date` is asked to return a value # that cannot be parsed to a Ruby Date. # # @see GraphQL::Types::ISO8601Date which raises this error class DateEncodingError < GraphQL::RuntimeTypeError # The value which couldn't be encoded attr_reader :date_value def initialize(value) @date_value = value super("Date cannot be parsed: #{value}. \nDate must be able to be parsed as a Ruby Date object.") 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/integer_decoding_error.rb
lib/graphql/integer_decoding_error.rb
# frozen_string_literal: true module GraphQL # This error is raised when `Types::Int` is given an input value outside of 32-bit integer range. # # For really big integer values, consider `GraphQL::Types::BigInt` # # @see GraphQL::Types::Int which raises this error class IntegerDecodingError < GraphQL::RuntimeTypeError # The value which couldn't be decoded attr_reader :integer_value def initialize(value) @integer_value = value super("Integer out of bounds: #{value}. \nConsider using GraphQL::Types::BigInt instead.") 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/invalid_null_error.rb
lib/graphql/invalid_null_error.rb
# frozen_string_literal: true module GraphQL # Raised automatically when a field's resolve function returns `nil` # for a non-null field. class InvalidNullError < GraphQL::Error # @return [GraphQL::BaseType] The owner of {#field} attr_reader :parent_type # @return [GraphQL::Field] The field which failed to return a value attr_reader :field # @return [GraphQL::Language::Nodes::Field] the field where the error occurred attr_reader :ast_node # @return [Boolean] indicates an array result caused the error attr_reader :is_from_array def initialize(parent_type, field, ast_node, is_from_array: false) @parent_type = parent_type @field = field @ast_node = ast_node @is_from_array = is_from_array # For List elements, identify the non-null error is for an # element and the required element type so it's not ambiguous # whether it was caused by a null instead of the list or a # null element. if @is_from_array super("Cannot return null for non-nullable element of type '#{@field.type.of_type.of_type.to_type_signature}' for #{@parent_type.graphql_name}.#{@field.graphql_name}") else super("Cannot return null for non-nullable field #{@parent_type.graphql_name}.#{@field.graphql_name}") end end class << self attr_accessor :parent_class def subclass_for(parent_class) subclass = Class.new(self) subclass.parent_class = parent_class subclass end def inspect if (name.nil? || parent_class&.name.nil?) && parent_class.respond_to?(:mutation) && (mutation = parent_class.mutation) "#{mutation.inspect}::#{parent_class.graphql_name}::InvalidNullError" 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/introspection.rb
lib/graphql/introspection.rb
# frozen_string_literal: true module GraphQL module Introspection def self.query(include_deprecated_args: false, include_schema_description: false, include_is_repeatable: false, include_specified_by_url: false, include_is_one_of: false) # The introspection query to end all introspection queries, copied from # https://github.com/graphql/graphql-js/blob/master/src/utilities/introspectionQuery.js <<-QUERY.gsub(/\n{2,}/, "\n") query IntrospectionQuery { __schema { #{include_schema_description ? "description" : ""} queryType { name } mutationType { name } subscriptionType { name } types { ...FullType } directives { name description locations #{include_is_repeatable ? "isRepeatable" : ""} args#{include_deprecated_args ? '(includeDeprecated: true)' : ''} { ...InputValue } } } } fragment FullType on __Type { kind name description #{include_specified_by_url ? "specifiedByURL" : ""} #{include_is_one_of ? "isOneOf" : ""} fields(includeDeprecated: true) { name description args#{include_deprecated_args ? '(includeDeprecated: true)' : ''} { ...InputValue } type { ...TypeRef } isDeprecated deprecationReason } inputFields#{include_deprecated_args ? '(includeDeprecated: true)' : ''} { ...InputValue } interfaces { ...TypeRef } enumValues(includeDeprecated: true) { name description isDeprecated deprecationReason } possibleTypes { ...TypeRef } } fragment InputValue on __InputValue { name description type { ...TypeRef } defaultValue #{include_deprecated_args ? 'isDeprecated' : ''} #{include_deprecated_args ? 'deprecationReason' : ''} } fragment TypeRef on __Type { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name ofType { kind name } } } } } } } } QUERY end end end require "graphql/introspection/base_object" require "graphql/introspection/input_value_type" require "graphql/introspection/enum_value_type" require "graphql/introspection/type_kind_enum" require "graphql/introspection/type_type" require "graphql/introspection/field_type" require "graphql/introspection/directive_location_enum" require "graphql/introspection/directive_type" require "graphql/introspection/schema_type" require "graphql/introspection/introspection_query" require "graphql/introspection/dynamic_fields" require "graphql/introspection/entry_points"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/types.rb
lib/graphql/types.rb
# frozen_string_literal: true module GraphQL module Types extend Autoload autoload :Boolean, "graphql/types/boolean" autoload :BigInt, "graphql/types/big_int" autoload :Float, "graphql/types/float" autoload :ID, "graphql/types/id" autoload :Int, "graphql/types/int" autoload :JSON, "graphql/types/json" autoload :String, "graphql/types/string" autoload :ISO8601Date, "graphql/types/iso_8601_date" autoload :ISO8601DateTime, "graphql/types/iso_8601_date_time" autoload :ISO8601Duration, "graphql/types/iso_8601_duration" autoload :Relay, "graphql/types/relay" 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/dataloader.rb
lib/graphql/dataloader.rb
# frozen_string_literal: true require "graphql/dataloader/null_dataloader" require "graphql/dataloader/request" require "graphql/dataloader/request_all" require "graphql/dataloader/source" require "graphql/dataloader/active_record_association_source" require "graphql/dataloader/active_record_source" module GraphQL # This plugin supports Fiber-based concurrency, along with {GraphQL::Dataloader::Source}. # # @example Installing Dataloader # # class MySchema < GraphQL::Schema # use GraphQL::Dataloader # end # # @example Waiting for batch-loaded data in a GraphQL field # # field :team, Types::Team, null: true # # def team # dataloader.with(Sources::Record, Team).load(object.team_id) # end # class Dataloader class << self attr_accessor :default_nonblocking, :default_fiber_limit end def self.use(schema, nonblocking: nil, fiber_limit: nil) dataloader_class = if nonblocking warn("`nonblocking: true` is deprecated from `GraphQL::Dataloader`, please use `GraphQL::Dataloader::AsyncDataloader` instead. Docs: https://graphql-ruby.org/dataloader/async_dataloader.") Class.new(self) { self.default_nonblocking = true } else self end if fiber_limit dataloader_class = Class.new(dataloader_class) dataloader_class.default_fiber_limit = fiber_limit end schema.dataloader_class = dataloader_class end # Call the block with a Dataloader instance, # then run all enqueued jobs and return the result of the block. def self.with_dataloading(&block) dataloader = self.new result = nil dataloader.append_job { result = block.call(dataloader) } dataloader.run result end def initialize(nonblocking: self.class.default_nonblocking, fiber_limit: self.class.default_fiber_limit) @source_cache = Hash.new { |h, k| h[k] = {} } @pending_jobs = [] if !nonblocking.nil? @nonblocking = nonblocking end @fiber_limit = fiber_limit @lazies_at_depth = Hash.new { |h, k| h[k] = [] } end # @return [Integer, nil] attr_reader :fiber_limit def nonblocking? @nonblocking end # This is called before the fiber is spawned, from the parent context (i.e. from # the thread or fiber that it is scheduled from). # # @return [Hash<Symbol, Object>] Current fiber-local variables def get_fiber_variables fiber_vars = {} Thread.current.keys.each do |fiber_var_key| fiber_vars[fiber_var_key] = Thread.current[fiber_var_key] end fiber_vars end # Set up the fiber variables in a new fiber. # # This is called within the fiber, right after it is spawned. # # @param vars [Hash<Symbol, Object>] Fiber-local variables from {get_fiber_variables} # @return [void] def set_fiber_variables(vars) vars.each { |k, v| Thread.current[k] = v } nil end # This method is called when Dataloader is finished using a fiber. # Use it to perform any cleanup, such as releasing database connections (if required manually) def cleanup_fiber end # Get a Source instance from this dataloader, for calling `.load(...)` or `.request(...)` on. # # @param source_class [Class<GraphQL::Dataloader::Source] # @param batch_parameters [Array<Object>] # @return [GraphQL::Dataloader::Source] An instance of {source_class}, initialized with `self, *batch_parameters`, # and cached for the lifetime of this {Multiplex}. if RUBY_VERSION < "3" || RUBY_ENGINE != "ruby" # truffle-ruby wasn't doing well with the implementation below def with(source_class, *batch_args) batch_key = source_class.batch_key_for(*batch_args) @source_cache[source_class][batch_key] ||= begin source = source_class.new(*batch_args) source.setup(self) source end end else def with(source_class, *batch_args, **batch_kwargs) batch_key = source_class.batch_key_for(*batch_args, **batch_kwargs) @source_cache[source_class][batch_key] ||= begin source = source_class.new(*batch_args, **batch_kwargs) source.setup(self) source end end end # Tell the dataloader that this fiber is waiting for data. # # Dataloader will resume the fiber after the requested data has been loaded (by another Fiber). # # @return [void] def yield(source = Fiber[:__graphql_current_dataloader_source]) trace = Fiber[:__graphql_current_multiplex]&.current_trace trace&.dataloader_fiber_yield(source) Fiber.yield trace&.dataloader_fiber_resume(source) nil end # @api private Nothing to see here def append_job(callable = nil, &job) # Given a block, queue it up to be worked through when `#run` is called. # (If the dataloader is already running, then a Fiber will pick this up later.) @pending_jobs.push(callable || job) nil end # Clear any already-loaded objects from {Source} caches # @return [void] def clear_cache @source_cache.each do |_source_class, batched_sources| batched_sources.each_value(&:clear_cache) end nil end # Use a self-contained queue for the work in the block. def run_isolated prev_queue = @pending_jobs prev_pending_keys = {} prev_lazies_at_depth = @lazies_at_depth @lazies_at_depth = @lazies_at_depth.dup.clear # Clear pending loads but keep already-cached records # in case they are useful to the given block. @source_cache.each do |source_class, batched_sources| batched_sources.each do |batch_args, batched_source_instance| if batched_source_instance.pending? prev_pending_keys[batched_source_instance] = batched_source_instance.pending.dup batched_source_instance.pending.clear end end end @pending_jobs = [] res = nil # Make sure the block is inside a Fiber, so it can `Fiber.yield` append_job { res = yield } run res ensure @pending_jobs = prev_queue @lazies_at_depth = prev_lazies_at_depth prev_pending_keys.each do |source_instance, pending| pending.each do |key, value| if !source_instance.results.key?(key) source_instance.pending[key] = value end end end end # @param trace_query_lazy [nil, Execution::Multiplex] def run(trace_query_lazy: nil) trace = Fiber[:__graphql_current_multiplex]&.current_trace jobs_fiber_limit, total_fiber_limit = calculate_fiber_limit job_fibers = [] next_job_fibers = [] source_fibers = [] next_source_fibers = [] first_pass = true manager = spawn_fiber do trace&.begin_dataloader(self) while first_pass || !job_fibers.empty? first_pass = false run_pending_steps(trace, job_fibers, next_job_fibers, jobs_fiber_limit, source_fibers, next_source_fibers, total_fiber_limit) if !@lazies_at_depth.empty? with_trace_query_lazy(trace_query_lazy) do run_next_pending_lazies(job_fibers, trace) run_pending_steps(trace, job_fibers, next_job_fibers, jobs_fiber_limit, source_fibers, next_source_fibers, total_fiber_limit) end end end trace&.end_dataloader(self) end run_fiber(manager) if manager.alive? raise "Invariant: Manager fiber didn't terminate properly." end if !job_fibers.empty? raise "Invariant: job fibers should have exited but #{job_fibers.size} remained" end if !source_fibers.empty? raise "Invariant: source fibers should have exited but #{source_fibers.size} remained" end rescue UncaughtThrowError => e throw e.tag, e.value end def run_fiber(f) f.resume end # @api private def lazy_at_depth(depth, lazy) @lazies_at_depth[depth] << lazy end def spawn_fiber fiber_vars = get_fiber_variables Fiber.new(blocking: !@nonblocking) { set_fiber_variables(fiber_vars) yield cleanup_fiber } end # Pre-warm the Dataloader cache with ActiveRecord objects which were loaded elsewhere. # These will be used by {Dataloader::ActiveRecordSource}, {Dataloader::ActiveRecordAssociationSource} and their helper # methods, `dataload_record` and `dataload_association`. # @param records [Array<ActiveRecord::Base>] Already-loaded records to warm the cache with # @param index_by [Symbol] The attribute to use as the cache key. (Should match `find_by:` when using {ActiveRecordSource}) # @return [void] def merge_records(records, index_by: :id) records_by_class = Hash.new { |h, k| h[k] = {} } records.each do |r| records_by_class[r.class][r.public_send(index_by)] = r end records_by_class.each do |r_class, records| with(ActiveRecordSource, r_class).merge(records) end end private def run_next_pending_lazies(job_fibers, trace) smallest_depth = nil @lazies_at_depth.each_key do |depth_key| smallest_depth ||= depth_key if depth_key < smallest_depth smallest_depth = depth_key end end if smallest_depth lazies = @lazies_at_depth.delete(smallest_depth) if !lazies.empty? lazies.each_with_index do |l, idx| append_job { l.value } end job_fibers.unshift(spawn_job_fiber(trace)) end end end def run_pending_steps(trace, job_fibers, next_job_fibers, jobs_fiber_limit, source_fibers, next_source_fibers, total_fiber_limit) while (f = (job_fibers.shift || (((next_job_fibers.size + job_fibers.size) < jobs_fiber_limit) && spawn_job_fiber(trace)))) if f.alive? finished = run_fiber(f) if !finished next_job_fibers << f end end end join_queues(job_fibers, next_job_fibers) while (!source_fibers.empty? || @source_cache.each_value.any? { |group_sources| group_sources.each_value.any?(&:pending?) }) while (f = source_fibers.shift || (((job_fibers.size + source_fibers.size + next_source_fibers.size + next_job_fibers.size) < total_fiber_limit) && spawn_source_fiber(trace))) if f.alive? finished = run_fiber(f) if !finished next_source_fibers << f end end end join_queues(source_fibers, next_source_fibers) end end def with_trace_query_lazy(multiplex_or_nil, &block) if (multiplex = multiplex_or_nil) query = multiplex.queries.length == 1 ? multiplex.queries[0] : nil multiplex.current_trace.execute_query_lazy(query: query, multiplex: multiplex, &block) else yield end end def calculate_fiber_limit total_fiber_limit = @fiber_limit || Float::INFINITY if total_fiber_limit < 4 raise ArgumentError, "Dataloader fiber limit is too low (#{total_fiber_limit}), it must be at least 4" end total_fiber_limit -= 1 # deduct one fiber for `manager` # Deduct at least one fiber for sources jobs_fiber_limit = total_fiber_limit - 2 return jobs_fiber_limit, total_fiber_limit end def join_queues(prev_queue, new_queue) @nonblocking && Fiber.scheduler.run prev_queue.concat(new_queue) new_queue.clear end def spawn_job_fiber(trace) if !@pending_jobs.empty? spawn_fiber do trace&.dataloader_spawn_execution_fiber(@pending_jobs) while job = @pending_jobs.shift job.call end trace&.dataloader_fiber_exit end end end def spawn_source_fiber(trace) pending_sources = nil @source_cache.each_value do |source_by_batch_params| source_by_batch_params.each_value do |source| if source.pending? pending_sources ||= [] pending_sources << source end end end if pending_sources spawn_fiber do trace&.dataloader_spawn_source_fiber(pending_sources) pending_sources.each do |source| Fiber[:__graphql_current_dataloader_source] = source trace&.begin_dataloader_source(source) source.run_pending_keys trace&.end_dataloader_source(source) end trace&.dataloader_fiber_exit end end end end end require "graphql/dataloader/async_dataloader"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/execution.rb
lib/graphql/execution.rb
# frozen_string_literal: true require "graphql/execution/directive_checks" require "graphql/execution/interpreter" require "graphql/execution/lazy" require "graphql/execution/lookahead" require "graphql/execution/multiplex" require "graphql/execution/errors" module GraphQL module Execution # @api private class Skip < GraphQL::Error; end # Just a singleton for implementing {Query::Context#skip} # @api private SKIP = Skip.new 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/name_validator.rb
lib/graphql/name_validator.rb
# frozen_string_literal: true module GraphQL class NameValidator VALID_NAME_REGEX = /^[_a-zA-Z][_a-zA-Z0-9]*$/ def self.validate!(name) name = name.is_a?(String) ? name : name.to_s raise GraphQL::InvalidNameError.new(name, VALID_NAME_REGEX) unless name.match?(VALID_NAME_REGEX) 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/runtime_type_error.rb
lib/graphql/runtime_type_error.rb
# frozen_string_literal: true module GraphQL class RuntimeTypeError < GraphQL::Error 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/subscriptions.rb
lib/graphql/subscriptions.rb
# frozen_string_literal: true require "securerandom" require "graphql/subscriptions/broadcast_analyzer" require "graphql/subscriptions/event" require "graphql/subscriptions/serialize" require "graphql/subscriptions/action_cable_subscriptions" require "graphql/subscriptions/default_subscription_resolve_extension" module GraphQL class Subscriptions # Raised when either: # - the triggered `event_name` doesn't match a field in the schema; or # - one or more arguments don't match the field arguments class InvalidTriggerError < GraphQL::Error end # Raised when either: # - An initial subscription didn't have a value for `context[subscription_scope]` # - Or, an update didn't pass `.trigger(..., scope:)` # When raised, the initial subscription or update fails completely. class SubscriptionScopeMissingError < GraphQL::Error end # @see {Subscriptions#initialize} for options, concrete implementations may add options. def self.use(defn, options = {}) schema = defn.is_a?(Class) ? defn : defn.target if schema.subscriptions(inherited: false) raise ArgumentError, "Can't reinstall subscriptions. #{schema} is using #{schema.subscriptions}, can't also add #{self}" end options[:schema] = schema schema.subscriptions = self.new(**options) schema.add_subscription_extension_if_necessary nil end # @param schema [Class] the GraphQL schema this manager belongs to # @param validate_update [Boolean] If false, then validation is skipped when executing updates def initialize(schema:, validate_update: true, broadcast: false, default_broadcastable: false, **rest) if broadcast schema.query_analyzer(Subscriptions::BroadcastAnalyzer) end @default_broadcastable = default_broadcastable @schema = schema @validate_update = validate_update end # @return [Boolean] Used when fields don't have `broadcastable:` explicitly set attr_reader :default_broadcastable # Fetch subscriptions matching this field + arguments pair # And pass them off to the queue. # @param event_name [String] # @param args [Hash<String, Symbol => Object] # @param object [Object] # @param scope [Symbol, String] # @param context [Hash] # @return [void] def trigger(event_name, args, object, scope: nil, context: {}) # Make something as context-like as possible, even though there isn't a current query: dummy_query = @schema.query_class.new(@schema, "{ __typename }", validate: false, context: context) context = dummy_query.context event_name = event_name.to_s # Try with the verbatim input first: field = dummy_query.types.field(@schema.subscription, event_name) # rubocop:disable Development/ContextIsPassedCop if field.nil? # And if it wasn't found, normalize it: normalized_event_name = normalize_name(event_name) field = dummy_query.types.field(@schema.subscription, normalized_event_name) # rubocop:disable Development/ContextIsPassedCop if field.nil? raise InvalidTriggerError, "No subscription matching trigger: #{event_name} (looked for #{@schema.subscription.graphql_name}.#{normalized_event_name})" end else # Since we found a field, the original input was already normalized normalized_event_name = event_name end # Normalize symbol-keyed args to strings, try camelizing them # Should this accept a real context somehow? normalized_args = normalize_arguments(normalized_event_name, field, args, GraphQL::Query::NullContext.instance) event = Subscriptions::Event.new( name: normalized_event_name, arguments: normalized_args, field: field, scope: scope, context: context, ) execute_all(event, object) end # `event` was triggered on `object`, and `subscription_id` was subscribed, # so it should be updated. # # Load `subscription_id`'s GraphQL data, re-evaluate the query and return the result. # # @param subscription_id [String] # @param event [GraphQL::Subscriptions::Event] The event which was triggered # @param object [Object] The value for the subscription field # @return [GraphQL::Query::Result] def execute_update(subscription_id, event, object) # Lookup the saved data for this subscription query_data = read_subscription(subscription_id) if query_data.nil? delete_subscription(subscription_id) return nil end # Fetch the required keys from the saved data query_string = query_data.fetch(:query_string) variables = query_data.fetch(:variables) context = query_data.fetch(:context) operation_name = query_data.fetch(:operation_name) execute_options = { query: query_string, context: context, subscription_topic: event.topic, operation_name: operation_name, variables: variables, root_value: object, } # merge event's and query's context together context.merge!(event.context) unless event.context.nil? || context.nil? execute_options[:validate] = validate_update?(**execute_options) result = @schema.execute(**execute_options) subscriptions_context = result.context.namespace(:subscriptions) if subscriptions_context[:no_update] result = nil end if subscriptions_context[:unsubscribed] && !subscriptions_context[:final_update] # `unsubscribe` was called, clean up on our side # The transport should also send `{more: false}` to client delete_subscription(subscription_id) result = nil end result end # Define this method to customize whether to validate # this subscription when executing an update. # # @return [Boolean] defaults to `true`, or false if `validate: false` is provided. def validate_update?(query:, context:, root_value:, subscription_topic:, operation_name:, variables:) @validate_update end # Run the update query for this subscription and deliver it # @see {#execute_update} # @see {#deliver} # @return [void] def execute(subscription_id, event, object) res = execute_update(subscription_id, event, object) if !res.nil? deliver(subscription_id, res) if res.context.namespace(:subscriptions)[:unsubscribed] # `unsubscribe` was called, clean up on our side # The transport should also send `{more: false}` to client delete_subscription(subscription_id) end end end # Event `event` occurred on `object`, # Update all subscribers. # @param event [Subscriptions::Event] # @param object [Object] # @return [void] def execute_all(event, object) raise GraphQL::RequiredImplementationMissingError end # The system wants to send an update to this subscription. # Read its data and return it. # @param subscription_id [String] # @return [Hash] Containing required keys def read_subscription(subscription_id) raise GraphQL::RequiredImplementationMissingError end # A subscription query was re-evaluated, returning `result`. # The result should be send to `subscription_id`. # @param subscription_id [String] # @param result [Hash] # @return [void] def deliver(subscription_id, result) raise GraphQL::RequiredImplementationMissingError end # `query` was executed and found subscriptions to `events`. # Update the database to reflect this new state. # @param query [GraphQL::Query] # @param events [Array<GraphQL::Subscriptions::Event>] # @return [void] def write_subscription(query, events) raise GraphQL::RequiredImplementationMissingError end # A subscription was terminated server-side. # Clean up the database. # @param subscription_id [String] # @return void. def delete_subscription(subscription_id) raise GraphQL::RequiredImplementationMissingError end # @return [String] A new unique identifier for a subscription def build_id SecureRandom.uuid end # Convert a user-provided event name or argument # to the equivalent in GraphQL. # # By default, it converts the identifier to camelcase. # Override this in a subclass to change the transformation. # # @param event_or_arg_name [String, Symbol] # @return [String] def normalize_name(event_or_arg_name) Schema::Member::BuildType.camelize(event_or_arg_name.to_s) end # @return [Boolean] if true, then a query like this one would be broadcasted def broadcastable?(query_str, **query_options) query = @schema.query_class.new(@schema, query_str, **query_options) if !query.valid? raise "Invalid query: #{query.validation_errors.map(&:to_h).inspect}" end GraphQL::Analysis.analyze_query(query, @schema.query_analyzers) query.context.namespace(:subscriptions)[:subscription_broadcastable] end private # Recursively normalize `args` as belonging to `arg_owner`: # - convert symbols to strings, # - if needed, camelize the string (using {#normalize_name}) # @param arg_owner [GraphQL::Field, GraphQL::BaseType] # @param args [Hash, Array, Any] some GraphQL input value to coerce as `arg_owner` # @return [Any] normalized arguments value def normalize_arguments(event_name, arg_owner, args, context) case arg_owner when GraphQL::Schema::Field, Class return args if args.nil? if arg_owner.is_a?(Class) && !arg_owner.kind.input_object? # it's a type, but not an input object return args end normalized_args = {} missing_arg_names = [] args.each do |k, v| arg_name = k.to_s arg_defn = arg_owner.get_argument(arg_name, context) if arg_defn normalized_arg_name = arg_name else normalized_arg_name = normalize_name(arg_name) arg_defn = arg_owner.get_argument(normalized_arg_name, context) end if arg_defn if arg_defn.loads normalized_arg_name = arg_defn.keyword.to_s end normalized = normalize_arguments(event_name, arg_defn.type, v, context) normalized_args[normalized_arg_name] = normalized else # Couldn't find a matching argument definition missing_arg_names << arg_name end end # Backfill default values so that trigger arguments # match query arguments. arg_owner.arguments(context).each do |_name, arg_defn| if arg_defn.default_value? && !normalized_args.key?(arg_defn.name) default_value = arg_defn.default_value # We don't have an underlying "object" here, so it can't call methods. # This is broken. normalized_args[arg_defn.name] = arg_defn.prepare_value(nil, default_value, context: context) end end if !missing_arg_names.empty? arg_owner_name = if arg_owner.is_a?(GraphQL::Schema::Field) arg_owner.path elsif arg_owner.is_a?(Class) arg_owner.graphql_name else arg_owner.to_s end raise InvalidTriggerError, "Can't trigger Subscription.#{event_name}, received undefined arguments: #{missing_arg_names.join(", ")}. (Should match arguments of #{arg_owner_name}.)" end normalized_args when GraphQL::Schema::List args&.map { |a| normalize_arguments(event_name, arg_owner.of_type, a, context) } when GraphQL::Schema::NonNull normalize_arguments(event_name, arg_owner.of_type, args, context) else args 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/unauthorized_field_error.rb
lib/graphql/unauthorized_field_error.rb
# frozen_string_literal: true module GraphQL class UnauthorizedFieldError < GraphQL::UnauthorizedError # @return [Field] the field that failed the authorization check attr_accessor :field def initialize(message = nil, object: nil, type: nil, context: nil, field: nil) if message.nil? && [field, type].any?(&:nil?) raise ArgumentError, "#{self.class.name} requires either a message or keywords" end @field = field message ||= begin if object "An instance of #{object.class} failed #{type.name}'s authorization check on field #{field.name}" else "Failed #{type.name}'s authorization check on field #{field.name}" end end super(message, object: object, type: type, context: context) 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/coercion_error.rb
lib/graphql/coercion_error.rb
# frozen_string_literal: true module GraphQL class CoercionError < GraphQL::ExecutionError end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/schema.rb
lib/graphql/schema.rb
# frozen_string_literal: true require "logger" require "graphql/schema/addition" require "graphql/schema/always_visible" require "graphql/schema/base_64_encoder" require "graphql/schema/find_inherited_value" require "graphql/schema/finder" require "graphql/schema/introspection_system" require "graphql/schema/late_bound_type" require "graphql/schema/ractor_shareable" require "graphql/schema/timeout" require "graphql/schema/type_expression" require "graphql/schema/unique_within_type" require "graphql/schema/warden" require "graphql/schema/build_from_definition" require "graphql/schema/validator" require "graphql/schema/member" require "graphql/schema/wrapper" require "graphql/schema/list" require "graphql/schema/non_null" require "graphql/schema/argument" require "graphql/schema/enum_value" require "graphql/schema/enum" require "graphql/schema/field_extension" require "graphql/schema/field" require "graphql/schema/input_object" require "graphql/schema/interface" require "graphql/schema/scalar" require "graphql/schema/object" require "graphql/schema/union" require "graphql/schema/directive" require "graphql/schema/directive/deprecated" require "graphql/schema/directive/include" require "graphql/schema/directive/one_of" require "graphql/schema/directive/skip" require "graphql/schema/directive/feature" require "graphql/schema/directive/flagged" require "graphql/schema/directive/transform" require "graphql/schema/directive/specified_by" require "graphql/schema/type_membership" require "graphql/schema/resolver" require "graphql/schema/mutation" require "graphql/schema/has_single_input_argument" require "graphql/schema/relay_classic_mutation" require "graphql/schema/subscription" require "graphql/schema/visibility" module GraphQL # A GraphQL schema which may be queried with {GraphQL::Query}. # # The {Schema} contains: # # - types for exposing your application # - query analyzers for assessing incoming queries (including max depth & max complexity restrictions) # - execution strategies for running incoming queries # # Schemas start with root types, {Schema#query}, {Schema#mutation} and {Schema#subscription}. # The schema will traverse the tree of fields & types, using those as starting points. # Any undiscoverable types may be provided with the `types` configuration. # # Schemas can restrict large incoming queries with `max_depth` and `max_complexity` configurations. # (These configurations can be overridden by specific calls to {Schema.execute}) # # @example defining a schema # class MySchema < GraphQL::Schema # query QueryType # # If types are only connected by way of interfaces, they must be added here # orphan_types ImageType, AudioType # end # class Schema extend GraphQL::Schema::Member::HasAstNode extend GraphQL::Schema::FindInheritedValue extend Autoload autoload :BUILT_IN_TYPES, "graphql/schema/built_in_types" class DuplicateNamesError < GraphQL::Error attr_reader :duplicated_name def initialize(duplicated_name:, duplicated_definition_1:, duplicated_definition_2:) @duplicated_name = duplicated_name super( "Found two visible definitions for `#{duplicated_name}`: #{duplicated_definition_1}, #{duplicated_definition_2}" ) end end class UnresolvedLateBoundTypeError < GraphQL::Error attr_reader :type def initialize(type:) @type = type super("Late bound type was never found: #{type.inspect}") end end # Error that is raised when [#Schema#from_definition] is passed an invalid schema definition string. class InvalidDocumentError < Error; end; class << self # Create schema with the result of an introspection query. # @param introspection_result [Hash] A response from {GraphQL::Introspection::INTROSPECTION_QUERY} # @return [Class<GraphQL::Schema>] the schema described by `input` def from_introspection(introspection_result) GraphQL::Schema::Loader.load(introspection_result) end # Create schema from an IDL schema or file containing an IDL definition. # @param definition_or_path [String] A schema definition string, or a path to a file containing the definition # @param default_resolve [<#call(type, field, obj, args, ctx)>] A callable for handling field resolution # @param parser [Object] An object for handling definition string parsing (must respond to `parse`) # @param using [Hash] Plugins to attach to the created schema with `use(key, value)` # @return [Class] the schema described by `document` def from_definition(definition_or_path, default_resolve: nil, parser: GraphQL.default_parser, using: {}, base_types: {}) # If the file ends in `.graphql` or `.graphqls`, treat it like a filepath if definition_or_path.end_with?(".graphql") || definition_or_path.end_with?(".graphqls") GraphQL::Schema::BuildFromDefinition.from_definition_path( self, definition_or_path, default_resolve: default_resolve, parser: parser, using: using, base_types: base_types, ) else GraphQL::Schema::BuildFromDefinition.from_definition( self, definition_or_path, default_resolve: default_resolve, parser: parser, using: using, base_types: base_types, ) end end def deprecated_graphql_definition graphql_definition(silence_deprecation_warning: true) end # @return [GraphQL::Subscriptions] def subscriptions(inherited: true) defined?(@subscriptions) ? @subscriptions : (inherited ? find_inherited_value(:subscriptions, nil) : nil) end def subscriptions=(new_implementation) @subscriptions = new_implementation end # @param new_mode [Symbol] If configured, this will be used when `context: { trace_mode: ... }` isn't set. def default_trace_mode(new_mode = NOT_CONFIGURED) if !NOT_CONFIGURED.equal?(new_mode) @default_trace_mode = new_mode elsif defined?(@default_trace_mode) && !@default_trace_mode.nil? # This `nil?` check seems necessary because of # Ractors silently initializing @default_trace_mode somehow @default_trace_mode elsif superclass.respond_to?(:default_trace_mode) superclass.default_trace_mode else :default end end def trace_class(new_class = nil) if new_class # If any modules were already added for `:default`, # re-apply them here mods = trace_modules_for(:default) mods.each { |mod| new_class.include(mod) } new_class.include(DefaultTraceClass) trace_mode(:default, new_class) end trace_class_for(:default, build: true) end # @return [Class] Return the trace class to use for this mode, looking one up on the superclass if this Schema doesn't have one defined. def trace_class_for(mode, build: false) if (trace_class = own_trace_modes[mode]) trace_class elsif superclass.respond_to?(:trace_class_for) && (trace_class = superclass.trace_class_for(mode, build: false)) trace_class elsif build own_trace_modes[mode] = build_trace_mode(mode) else nil end end # Configure `trace_class` to be used whenever `context: { trace_mode: mode_name }` is requested. # {default_trace_mode} is used when no `trace_mode: ...` is requested. # # When a `trace_class` is added this way, it will _not_ receive other modules added with `trace_with(...)` # unless `trace_mode` is explicitly given. (This class will not receive any default trace modules.) # # Subclasses of the schema will use `trace_class` as a base class for this mode and those # subclass also will _not_ receive default tracing modules. # # @param mode_name [Symbol] # @param trace_class [Class] subclass of GraphQL::Tracing::Trace # @return void def trace_mode(mode_name, trace_class) own_trace_modes[mode_name] = trace_class nil end def own_trace_modes @own_trace_modes ||= {} end def build_trace_mode(mode) case mode when :default # Use the superclass's default mode if it has one, or else start an inheritance chain at the built-in base class. base_class = (superclass.respond_to?(:trace_class_for) && superclass.trace_class_for(mode, build: true)) || GraphQL::Tracing::Trace const_set(:DefaultTrace, Class.new(base_class) do include DefaultTraceClass end) else # First, see if the superclass has a custom-defined class for this. # Then, if it doesn't, use this class's default trace base_class = (superclass.respond_to?(:trace_class_for) && superclass.trace_class_for(mode)) || trace_class_for(:default, build: true) # Prepare the default trace class if it hasn't been initialized yet base_class ||= (own_trace_modes[:default] = build_trace_mode(:default)) mods = trace_modules_for(mode) if base_class < DefaultTraceClass mods = trace_modules_for(:default) + mods end # Copy the existing default options into this mode's options default_options = trace_options_for(:default) add_trace_options_for(mode, default_options) Class.new(base_class) do !mods.empty? && include(*mods) end end end def own_trace_modules @own_trace_modules ||= Hash.new { |h, k| h[k] = [] } end # @return [Array<Module>] Modules added for tracing in `trace_mode`, including inherited ones def trace_modules_for(trace_mode) modules = own_trace_modules[trace_mode] if superclass.respond_to?(:trace_modules_for) modules += superclass.trace_modules_for(trace_mode) end modules end # Returns the JSON response of {Introspection::INTROSPECTION_QUERY}. # @see #as_json Return a Hash representation of the schema # @return [String] def to_json(**args) JSON.pretty_generate(as_json(**args)) end # Return the Hash response of {Introspection::INTROSPECTION_QUERY}. # @param context [Hash] # @param include_deprecated_args [Boolean] If true, deprecated arguments will be included in the JSON response # @param include_schema_description [Boolean] If true, the schema's description will be queried and included in the response # @param include_is_repeatable [Boolean] If true, `isRepeatable: true|false` will be included with the schema's directives # @param include_specified_by_url [Boolean] If true, scalar types' `specifiedByUrl:` will be included in the response # @param include_is_one_of [Boolean] If true, `isOneOf: true|false` will be included with input objects # @return [Hash] GraphQL result def as_json(context: {}, include_deprecated_args: true, include_schema_description: false, include_is_repeatable: false, include_specified_by_url: false, include_is_one_of: false) introspection_query = Introspection.query( include_deprecated_args: include_deprecated_args, include_schema_description: include_schema_description, include_is_repeatable: include_is_repeatable, include_is_one_of: include_is_one_of, include_specified_by_url: include_specified_by_url, ) execute(introspection_query, context: context).to_h end # Return the GraphQL IDL for the schema # @param context [Hash] # @return [String] def to_definition(context: {}) GraphQL::Schema::Printer.print_schema(self, context: context) end # Return the GraphQL::Language::Document IDL AST for the schema # @return [GraphQL::Language::Document] def to_document GraphQL::Language::DocumentFromSchemaDefinition.new(self).document end # @return [String, nil] def description(new_description = nil) if new_description @description = new_description elsif defined?(@description) @description else find_inherited_value(:description, nil) end end def find(path) if !@finder @find_cache = {} @finder ||= GraphQL::Schema::Finder.new(self) end @find_cache[path] ||= @finder.find(path) end def static_validator GraphQL::StaticValidation::Validator.new(schema: self) end # Add `plugin` to this schema # @param plugin [#use] A Schema plugin # @return void def use(plugin, **kwargs) if !kwargs.empty? plugin.use(self, **kwargs) else plugin.use(self) end own_plugins << [plugin, kwargs] end def plugins find_inherited_value(:plugins, EMPTY_ARRAY) + own_plugins end # Build a map of `{ name => type }` and return it # @return [Hash<String => Class>] A dictionary of type classes by their GraphQL name # @see get_type Which is more efficient for finding _one type_ by name, because it doesn't merge hashes. def types(context = GraphQL::Query::NullContext.instance) if use_visibility_profile? types = Visibility::Profile.from_context(context, self) return types.all_types_h end all_types = non_introspection_types.merge(introspection_system.types) visible_types = {} all_types.each do |k, v| visible_types[k] =if v.is_a?(Array) visible_t = nil v.each do |t| if t.visible?(context) if visible_t.nil? visible_t = t else raise DuplicateNamesError.new( duplicated_name: k, duplicated_definition_1: visible_t.inspect, duplicated_definition_2: t.inspect ) end end end visible_t else v end end visible_types end # @param type_name [String] # @param context [GraphQL::Query::Context] Used for filtering definitions at query-time # @param use_visibility_profile Private, for migration to {Schema::Visibility} # @return [Module, nil] A type, or nil if there's no type called `type_name` def get_type(type_name, context = GraphQL::Query::NullContext.instance, use_visibility_profile = use_visibility_profile?) if use_visibility_profile profile = Visibility::Profile.from_context(context, self) return profile.type(type_name) end local_entry = own_types[type_name] type_defn = case local_entry when nil nil when Array if context.respond_to?(:types) && context.types.is_a?(GraphQL::Schema::Visibility::Profile) local_entry else visible_t = nil warden = Warden.from_context(context) local_entry.each do |t| if warden.visible_type?(t, context) if visible_t.nil? visible_t = t else raise DuplicateNamesError.new( duplicated_name: type_name, duplicated_definition_1: visible_t.inspect, duplicated_definition_2: t.inspect ) end end end visible_t end when Module local_entry else raise "Invariant: unexpected own_types[#{type_name.inspect}]: #{local_entry.inspect}" end type_defn || introspection_system.types[type_name] || # todo context-specific introspection? (superclass.respond_to?(:get_type) ? superclass.get_type(type_name, context, use_visibility_profile) : nil) end # @return [Boolean] Does this schema have _any_ definition for a type named `type_name`, regardless of visibility? def has_defined_type?(type_name) own_types.key?(type_name) || introspection_system.types.key?(type_name) || (superclass.respond_to?(:has_defined_type?) ? superclass.has_defined_type?(type_name) : false) end # @api private attr_writer :connections # @return [GraphQL::Pagination::Connections] if installed def connections if defined?(@connections) @connections else inherited_connections = find_inherited_value(:connections, nil) # This schema is part of an inheritance chain which is using new connections, # make a new instance, so we don't pollute the upstream one. if inherited_connections @connections = Pagination::Connections.new(schema: self) else nil end end end # Get or set the root `query { ... }` object for this schema. # # @example Using `Types::Query` as the entry-point # query { Types::Query } # # @param new_query_object [Class<GraphQL::Schema::Object>] The root type to use for queries # @param lazy_load_block If a block is given, then it will be called when GraphQL-Ruby needs the root query type. # @return [Class<GraphQL::Schema::Object>, nil] The configured query root type, if there is one. def query(new_query_object = nil, &lazy_load_block) if new_query_object || block_given? if @query_object dup_defn = new_query_object || yield raise GraphQL::Error, "Second definition of `query(...)` (#{dup_defn.inspect}) is invalid, already configured with #{@query_object.inspect}" elsif use_visibility_profile? if block_given? if visibility.preload? @query_object = lazy_load_block.call self.visibility.query_configured(@query_object) else @query_object = lazy_load_block end else @query_object = new_query_object self.visibility.query_configured(@query_object) end else @query_object = new_query_object || lazy_load_block.call add_type_and_traverse(@query_object, root: true) end nil elsif @query_object.is_a?(Proc) @query_object = @query_object.call self.visibility&.query_configured(@query_object) @query_object else @query_object || find_inherited_value(:query) end end # Get or set the root `mutation { ... }` object for this schema. # # @example Using `Types::Mutation` as the entry-point # mutation { Types::Mutation } # # @param new_mutation_object [Class<GraphQL::Schema::Object>] The root type to use for mutations # @param lazy_load_block If a block is given, then it will be called when GraphQL-Ruby needs the root mutation type. # @return [Class<GraphQL::Schema::Object>, nil] The configured mutation root type, if there is one. def mutation(new_mutation_object = nil, &lazy_load_block) if new_mutation_object || block_given? if @mutation_object dup_defn = new_mutation_object || yield raise GraphQL::Error, "Second definition of `mutation(...)` (#{dup_defn.inspect}) is invalid, already configured with #{@mutation_object.inspect}" elsif use_visibility_profile? if block_given? if visibility.preload? @mutation_object = lazy_load_block.call self.visibility.mutation_configured(@mutation_object) else @mutation_object = lazy_load_block end else @mutation_object = new_mutation_object self.visibility.mutation_configured(@mutation_object) end else @mutation_object = new_mutation_object || lazy_load_block.call add_type_and_traverse(@mutation_object, root: true) end nil elsif @mutation_object.is_a?(Proc) @mutation_object = @mutation_object.call self.visibility&.mutation_configured(@mutation_object) @mutation_object else @mutation_object || find_inherited_value(:mutation) end end # Get or set the root `subscription { ... }` object for this schema. # # @example Using `Types::Subscription` as the entry-point # subscription { Types::Subscription } # # @param new_subscription_object [Class<GraphQL::Schema::Object>] The root type to use for subscriptions # @param lazy_load_block If a block is given, then it will be called when GraphQL-Ruby needs the root subscription type. # @return [Class<GraphQL::Schema::Object>, nil] The configured subscription root type, if there is one. def subscription(new_subscription_object = nil, &lazy_load_block) if new_subscription_object || block_given? if @subscription_object dup_defn = new_subscription_object || yield raise GraphQL::Error, "Second definition of `subscription(...)` (#{dup_defn.inspect}) is invalid, already configured with #{@subscription_object.inspect}" elsif use_visibility_profile? if block_given? if visibility.preload? @subscription_object = lazy_load_block.call visibility.subscription_configured(@subscription_object) else @subscription_object = lazy_load_block end else @subscription_object = new_subscription_object self.visibility.subscription_configured(@subscription_object) end add_subscription_extension_if_necessary else @subscription_object = new_subscription_object || lazy_load_block.call add_subscription_extension_if_necessary add_type_and_traverse(@subscription_object, root: true) end nil elsif @subscription_object.is_a?(Proc) @subscription_object = @subscription_object.call add_subscription_extension_if_necessary self.visibility.subscription_configured(@subscription_object) @subscription_object else @subscription_object || find_inherited_value(:subscription) end end # @api private def root_type_for_operation(operation) case operation when "query" query when "mutation" mutation when "subscription" subscription else raise ArgumentError, "unknown operation type: #{operation}" end end # @return [Array<Class>] The root types (query, mutation, subscription) defined for this schema def root_types if use_visibility_profile? [query, mutation, subscription].compact else @root_types end end # @api private def warden_class if defined?(@warden_class) @warden_class elsif superclass.respond_to?(:warden_class) superclass.warden_class else GraphQL::Schema::Warden end end # @api private attr_writer :warden_class # @api private def visibility_profile_class if defined?(@visibility_profile_class) @visibility_profile_class elsif superclass.respond_to?(:visibility_profile_class) superclass.visibility_profile_class else GraphQL::Schema::Visibility::Profile end end # @api private attr_writer :visibility_profile_class, :use_visibility_profile # @api private attr_accessor :visibility # @api private def use_visibility_profile? if defined?(@use_visibility_profile) @use_visibility_profile elsif superclass.respond_to?(:use_visibility_profile?) superclass.use_visibility_profile? else false end end # @param type [Module] The type definition whose possible types you want to see # @param context [GraphQL::Query::Context] used for filtering visible possible types at runtime # @param use_visibility_profile Private, for migration to {Schema::Visibility} # @return [Hash<String, Module>] All possible types, if no `type` is given. # @return [Array<Module>] Possible types for `type`, if it's given. def possible_types(type = nil, context = GraphQL::Query::NullContext.instance, use_visibility_profile = use_visibility_profile?) if use_visibility_profile if type return Visibility::Profile.from_context(context, self).possible_types(type) else raise "Schema.possible_types is not implemented for `use_visibility_profile?`" end end if type # TODO duck-typing `.possible_types` would probably be nicer here if type.kind.union? type.possible_types(context: context) else stored_possible_types = own_possible_types[type] visible_possible_types = if stored_possible_types && type.kind.interface? stored_possible_types.select do |possible_type| possible_type.interfaces(context).include?(type) end else stored_possible_types end visible_possible_types || introspection_system.possible_types[type] || ( superclass.respond_to?(:possible_types) ? superclass.possible_types(type, context, use_visibility_profile) : EMPTY_ARRAY ) end else find_inherited_value(:possible_types, EMPTY_HASH) .merge(own_possible_types) .merge(introspection_system.possible_types) end end def union_memberships(type = nil) if type own_um = own_union_memberships.fetch(type.graphql_name, EMPTY_ARRAY) inherited_um = find_inherited_value(:union_memberships, EMPTY_HASH).fetch(type.graphql_name, EMPTY_ARRAY) own_um + inherited_um else joined_um = own_union_memberships.dup find_inherited_value(:union_memberhips, EMPTY_HASH).each do |k, v| um = joined_um[k] ||= [] um.concat(v) end joined_um end end # @api private # @see GraphQL::Dataloader def dataloader_class @dataloader_class || GraphQL::Dataloader::NullDataloader end attr_writer :dataloader_class def references_to(to_type = nil, from: nil) if to_type if from refs = own_references_to[to_type] ||= [] refs << from else get_references_to(to_type) || EMPTY_ARRAY end else # `@own_references_to` can be quite large for big schemas, # and generally speaking, we won't inherit any values. # So optimize the most common case -- don't create a duplicate Hash. inherited_value = find_inherited_value(:references_to, EMPTY_HASH) if !inherited_value.empty? inherited_value.merge(own_references_to) else own_references_to end end end def type_from_ast(ast_node, context: self.query_class.new(self, "{ __typename }").context) GraphQL::Schema::TypeExpression.build_type(context.query.types, ast_node) end def get_field(type_or_name, field_name, context = GraphQL::Query::NullContext.instance, use_visibility_profile = use_visibility_profile?) if use_visibility_profile profile = Visibility::Profile.from_context(context, self) parent_type = case type_or_name when String profile.type(type_or_name) when Module type_or_name when LateBoundType profile.type(type_or_name.name) else raise GraphQL::InvariantError, "Unexpected field owner for #{field_name.inspect}: #{type_or_name.inspect} (#{type_or_name.class})" end return profile.field(parent_type, field_name) end parent_type = case type_or_name when LateBoundType get_type(type_or_name.name, context) when String get_type(type_or_name, context) when Module type_or_name else raise GraphQL::InvariantError, "Unexpected field owner for #{field_name.inspect}: #{type_or_name.inspect} (#{type_or_name.class})" end if parent_type.kind.fields? && (field = parent_type.get_field(field_name, context)) field elsif parent_type == query && (entry_point_field = introspection_system.entry_point(name: field_name)) entry_point_field elsif (dynamic_field = introspection_system.dynamic_field(name: field_name)) dynamic_field else nil end end def get_fields(type, context = GraphQL::Query::NullContext.instance) type.fields(context) end # Pass a custom introspection module here to use it for this schema. # @param new_introspection_namespace [Module] If given, use this module for custom introspection on the schema # @return [Module, nil] The configured namespace, if there is one def introspection(new_introspection_namespace = nil) if new_introspection_namespace @introspection = new_introspection_namespace # reset this cached value: @introspection_system = nil introspection_system @introspection else @introspection || find_inherited_value(:introspection) end end # @return [Schema::IntrospectionSystem] Based on {introspection} def introspection_system if !@introspection_system @introspection_system = Schema::IntrospectionSystem.new(self) @introspection_system.resolve_late_bindings self.visibility&.introspection_system_configured(@introspection_system) end @introspection_system end def cursor_encoder(new_encoder = nil) if new_encoder @cursor_encoder = new_encoder end @cursor_encoder || find_inherited_value(:cursor_encoder, Base64Encoder) end def default_max_page_size(new_default_max_page_size = nil) if new_default_max_page_size @default_max_page_size = new_default_max_page_size else @default_max_page_size || find_inherited_value(:default_max_page_size) end end # A limit on the number of tokens to accept on incoming query strings. # Use this to prevent parsing maliciously-large query strings. # @return [nil, Integer] def max_query_string_tokens(new_max_tokens = NOT_CONFIGURED) if NOT_CONFIGURED.equal?(new_max_tokens) defined?(@max_query_string_tokens) ? @max_query_string_tokens : find_inherited_value(:max_query_string_tokens) else @max_query_string_tokens = new_max_tokens end end def default_page_size(new_default_page_size = nil) if new_default_page_size @default_page_size = new_default_page_size else @default_page_size || find_inherited_value(:default_page_size) end end def query_execution_strategy(new_query_execution_strategy = nil, deprecation_warning: true) if deprecation_warning warn "GraphQL::Schema.query_execution_strategy is deprecated without replacement. Use `GraphQL::Query.new` directly to create and execute a custom query instead." warn " #{caller(1, 1).first}" end if new_query_execution_strategy @query_execution_strategy = new_query_execution_strategy else @query_execution_strategy || (superclass.respond_to?(:query_execution_strategy) ? superclass.query_execution_strategy(deprecation_warning: false) : self.default_execution_strategy) end end def mutation_execution_strategy(new_mutation_execution_strategy = nil, deprecation_warning: true) if deprecation_warning
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
true
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/dig.rb
lib/graphql/dig.rb
# frozen_string_literal: true module GraphQL module Dig # implemented using the old activesupport #dig instead of the ruby built-in # so we can use some of the magic in Schema::InputObject and Interpreter::Arguments # to handle stringified/symbolized keys. # # @param own_key [String, Symbol] A key to retrieve # @param rest_keys [Array<[String, Symbol>] Retrieves the value object corresponding to the each key objects repeatedly # @return [Object] def dig(own_key, *rest_keys) val = self[own_key] if val.nil? || rest_keys.empty? val else val.dig(*rest_keys) 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.rb
lib/graphql/tracing.rb
# frozen_string_literal: true module GraphQL module Tracing autoload :Trace, "graphql/tracing/trace" autoload :CallLegacyTracers, "graphql/tracing/call_legacy_tracers" autoload :LegacyTrace, "graphql/tracing/legacy_trace" autoload :LegacyHooksTrace, "graphql/tracing/legacy_hooks_trace" autoload :NullTrace, "graphql/tracing/null_trace" autoload :ActiveSupportNotificationsTracing, "graphql/tracing/active_support_notifications_tracing" autoload :PlatformTracing, "graphql/tracing/platform_tracing" autoload :AppOpticsTracing, "graphql/tracing/appoptics_tracing" autoload :AppsignalTracing, "graphql/tracing/appsignal_tracing" autoload :DataDogTracing, "graphql/tracing/data_dog_tracing" autoload :NewRelicTracing, "graphql/tracing/new_relic_tracing" autoload :NotificationsTracing, "graphql/tracing/notifications_tracing" autoload :ScoutTracing, "graphql/tracing/scout_tracing" autoload :StatsdTracing, "graphql/tracing/statsd_tracing" autoload :PrometheusTracing, "graphql/tracing/prometheus_tracing" autoload :ActiveSupportNotificationsTrace, "graphql/tracing/active_support_notifications_trace" autoload :PlatformTrace, "graphql/tracing/platform_trace" autoload :AppOpticsTrace, "graphql/tracing/appoptics_trace" autoload :AppsignalTrace, "graphql/tracing/appsignal_trace" autoload :DataDogTrace, "graphql/tracing/data_dog_trace" autoload :MonitorTrace, "graphql/tracing/monitor_trace" autoload :NewRelicTrace, "graphql/tracing/new_relic_trace" autoload :NotificationsTrace, "graphql/tracing/notifications_trace" autoload :SentryTrace, "graphql/tracing/sentry_trace" autoload :ScoutTrace, "graphql/tracing/scout_trace" autoload :StatsdTrace, "graphql/tracing/statsd_trace" autoload :PrometheusTrace, "graphql/tracing/prometheus_trace" autoload :PerfettoTrace, "graphql/tracing/perfetto_trace" autoload :DetailedTrace, "graphql/tracing/detailed_trace" # Objects may include traceable to gain a `.trace(...)` method. # The object must have a `@tracers` ivar of type `Array<<#trace(k, d, &b)>>`. # @api private module Traceable # @param key [String] The name of the event in GraphQL internals # @param metadata [Hash] Event-related metadata (can be anything) # @return [Object] Must return the value of the block def trace(key, metadata, &block) return yield if @tracers.empty? call_tracers(0, key, metadata, &block) end private # If there's a tracer at `idx`, call it and then increment `idx`. # Otherwise, yield. # # @param idx [Integer] Which tracer to call # @param key [String] The current event name # @param metadata [Object] The current event object # @return Whatever the block returns def call_tracers(idx, key, metadata, &block) if idx == @tracers.length yield else @tracers[idx].trace(key, metadata) { call_tracers(idx + 1, key, metadata, &block) } end end end module NullTracer module_function def trace(k, v) 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/analysis_error.rb
lib/graphql/analysis_error.rb
# frozen_string_literal: true module GraphQL class AnalysisError < GraphQL::ExecutionError end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/testing.rb
lib/graphql/testing.rb
# frozen_string_literal: true require "graphql/testing/helpers" require "graphql/testing/mock_action_cable"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/rubocop/graphql/root_types_in_block.rb
lib/graphql/rubocop/graphql/root_types_in_block.rb
# frozen_string_literal: true require_relative "./base_cop" module GraphQL module Rubocop module GraphQL # Identify (and auto-correct) any root types in your schema file. # # @example # # bad, immediately causes Rails to load `app/graphql/types/query.rb` # query Types::Query # # # good, defers loading until the file is needed # query { Types::Query } # class RootTypesInBlock < BaseCop MSG = "type configuration can be moved to a block to defer loading the type's file" def_node_matcher :root_type_config_without_block, <<-Pattern ( send nil? {:query :mutation :subscription} const ) Pattern def on_send(node) root_type_config_without_block(node) do add_offense(node) do |corrector| new_node_source = node.source_range.source new_node_source.sub!(/(query|mutation|subscription)/, '\1 {') new_node_source << " }" corrector.replace(node, new_node_source) 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/rubocop/graphql/field_type_in_block.rb
lib/graphql/rubocop/graphql/field_type_in_block.rb
# frozen_string_literal: true require_relative "./base_cop" module GraphQL module Rubocop module GraphQL # Identify (and auto-correct) any field whose type configuration isn't given # in the configuration block. # # @example # # bad, immediately causes Rails to load `app/graphql/types/thing.rb` # field :thing, Types::Thing # # # good, defers loading until the file is needed # field :thing do # type(Types::Thing) # end # class FieldTypeInBlock < BaseCop MSG = "type configuration can be moved to a block to defer loading the type's file" BUILT_IN_SCALAR_NAMES = ["Float", "Int", "Integer", "String", "ID", "Boolean"] def_node_matcher :field_config_with_inline_type, <<-Pattern ( send {nil? _} :field sym ${const array} ... ) Pattern def_node_matcher :field_config_with_inline_type_and_block, <<-Pattern ( block (send {nil? _} :field sym ${const array} ...) ... (args) _ ) Pattern def on_block(node) ignore_node(node) field_config_with_inline_type_and_block(node) do |type_const| type_const_str = get_type_argument_str(node, type_const) if ignore_inline_type_str?(type_const_str) # Do nothing ... else add_offense(type_const) do |corrector| cleaned_node_source = delete_type_argument(node, type_const) field_indent = determine_field_indent(node) cleaned_node_source.sub!(/(\{|do)/, "\\1\n#{field_indent} type #{type_const_str}") corrector.replace(node, cleaned_node_source) end end end end def on_send(node) return if part_of_ignored_node?(node) field_config_with_inline_type(node) do |type_const| type_const_str = get_type_argument_str(node, type_const) if ignore_inline_type_str?(type_const_str) # Do nothing -- not loading from another file else add_offense(type_const) do |corrector| cleaned_node_source = delete_type_argument(node, type_const) field_indent = determine_field_indent(node) cleaned_node_source += " do\n#{field_indent} type #{type_const_str}\n#{field_indent}end" corrector.replace(node, cleaned_node_source) end end end end private def ignore_inline_type_str?(type_str) if BUILT_IN_SCALAR_NAMES.include?(type_str) true elsif (inner_type_str = type_str.sub(/\[([A-Za-z]+)(, null: (true|false))?\]/, '\1')) && BUILT_IN_SCALAR_NAMES.include?(inner_type_str) true else false end end def get_type_argument_str(send_node, type_const) first_pos = type_const.location.expression.begin_pos end_pos = type_const.location.expression.end_pos node_source = send_node.source_range.source node_first_pos = send_node.location.expression.begin_pos relative_first_pos = first_pos - node_first_pos end_removal_pos = end_pos - node_first_pos node_source[relative_first_pos...end_removal_pos] end def delete_type_argument(send_node, type_const) first_pos = type_const.location.expression.begin_pos end_pos = type_const.location.expression.end_pos node_source = send_node.source_range.source node_first_pos = send_node.location.expression.begin_pos relative_first_pos = first_pos - node_first_pos end_removal_pos = end_pos - node_first_pos begin_removal_pos = relative_first_pos while node_source[begin_removal_pos] != "," begin_removal_pos -= 1 if begin_removal_pos < 1 raise "Invariant: somehow backtracked to beginning of node looking for a comma (node source: #{node_source.inspect})" end end node_source[0...begin_removal_pos] + node_source[end_removal_pos..-1] end def determine_field_indent(send_node) type_defn_node = send_node while (type_defn_node && !(type_defn_node.class_definition? || type_defn_node.module_definition?)) type_defn_node = type_defn_node.parent end if type_defn_node.nil? raise "Invariant: Something went wrong in GraphQL-Ruby, couldn't find surrounding class definition for field (#{send_node}).\n\nPlease report this error on GitHub." end type_defn_source = type_defn_node.source indent_test_idx = send_node.location.expression.begin_pos - type_defn_node.source_range.begin_pos - 1 field_indent = "".dup while type_defn_source[indent_test_idx] == " " field_indent << " " indent_test_idx -= 1 if indent_test_idx == 0 raise "Invariant: somehow backtracted to beginning of class when looking for field indent (source: #{node_source.inspect})" end end field_indent 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/rubocop/graphql/base_cop.rb
lib/graphql/rubocop/graphql/base_cop.rb
# frozen_string_literal: true require "rubocop" module GraphQL module Rubocop module GraphQL class BaseCop < RuboCop::Cop::Base extend RuboCop::Cop::AutoCorrector # Return the source of `send_node`, but without the keyword argument represented by `pair_node` def source_without_keyword_argument(send_node, pair_node) # work back to the preceding comma first_pos = pair_node.location.expression.begin_pos end_pos = pair_node.location.expression.end_pos node_source = send_node.source_range.source node_first_pos = send_node.location.expression.begin_pos relative_first_pos = first_pos - node_first_pos relative_last_pos = end_pos - node_first_pos begin_removal_pos = relative_first_pos while node_source[begin_removal_pos] != "," begin_removal_pos -= 1 if begin_removal_pos < 1 raise "Invariant: somehow backtracked to beginning of node looking for a comma (node source: #{node_source.inspect})" end end end_removal_pos = relative_last_pos cleaned_node_source = node_source[0...begin_removal_pos] + node_source[end_removal_pos..-1] cleaned_node_source 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/rubocop/graphql/default_required_true.rb
lib/graphql/rubocop/graphql/default_required_true.rb
# frozen_string_literal: true require_relative "./base_cop" module GraphQL module Rubocop module GraphQL # Identify (and auto-correct) any argument configuration which duplicates # the default `required: true` property. # # `required: true` is default because required arguments can always be converted # to optional arguments (`required: false`) without a breaking change. (The opposite change, from `required: false` # to `required: true`, change.) # # @example # # Both of these define `id: ID!` in GraphQL: # # # bad # argument :id, ID, required: true # # # good # argument :id, ID # class DefaultRequiredTrue < BaseCop MSG = "`required: true` is the default and can be removed." def_node_matcher :argument_config_with_required_true?, <<-Pattern ( send {nil? _} :argument ... (hash <$(pair (sym :required) (true)) ...>) ) Pattern def on_send(node) argument_config_with_required_true?(node) do |required_config| add_offense(required_config) do |corrector| cleaned_node_source = source_without_keyword_argument(node, required_config) corrector.replace(node, cleaned_node_source) 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/rubocop/graphql/default_null_true.rb
lib/graphql/rubocop/graphql/default_null_true.rb
# frozen_string_literal: true require_relative "base_cop" module GraphQL module Rubocop module GraphQL # Identify (and auto-correct) any field configuration which duplicates # the default `null: true` property. # # `null: true` is default because nullable fields can always be converted # to non-null fields (`null: false`) without a breaking change. (The opposite change, from `null: false` # to `null: true`, change.) # # @example # # Both of these define `name: String` in GraphQL: # # # bad # field :name, String, null: true # # # good # field :name, String # class DefaultNullTrue < BaseCop MSG = "`null: true` is the default and can be removed." def_node_matcher :field_config_with_null_true?, <<-Pattern ( send nil? :field ... (hash $(pair (sym :null) (true)) ...) ) Pattern def on_send(node) field_config_with_null_true?(node) do |null_config| add_offense(null_config) do |corrector| cleaned_node_source = source_without_keyword_argument(node, null_config) corrector.replace(node.source_range, cleaned_node_source) 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/query/input_validation_result.rb
lib/graphql/query/input_validation_result.rb
# frozen_string_literal: true module GraphQL class Query class InputValidationResult attr_accessor :problems def self.from_problem(explanation, path = nil, extensions: nil, message: nil) result = self.new result.add_problem(explanation, path, extensions: extensions, message: message) result end def initialize(valid: true, problems: nil) @valid = valid @problems = problems end def valid? @valid end def add_problem(explanation, path = nil, extensions: nil, message: nil) @problems ||= [] @valid = false problem = { "path" => path || [], "explanation" => explanation } if extensions problem["extensions"] = extensions end if message problem["message"] = message end @problems.push(problem) end def merge_result!(path, inner_result) return if inner_result.nil? || inner_result.valid? if inner_result.problems inner_result.problems.each do |p| item_path = [path, *p["path"]] add_problem(p["explanation"], item_path, message: p["message"], extensions: p["extensions"]) end end # It could have been explicitly set on inner_result (if it had no problems) @valid = false end VALID = self.new VALID.freeze 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/query/variable_validation_error.rb
lib/graphql/query/variable_validation_error.rb
# frozen_string_literal: true module GraphQL class Query class VariableValidationError < GraphQL::ExecutionError attr_accessor :value, :validation_result def initialize(variable_ast, type, value, validation_result, msg: nil) @value = value @validation_result = validation_result msg ||= "Variable $#{variable_ast.name} of type #{type.to_type_signature} was provided invalid value" if !problem_fields.empty? msg += " for #{problem_fields.join(", ")}" end super(msg) self.ast_node = variable_ast end def to_h # It is possible there are other extension items in this error, so handle # a one level deep merge explicitly. However beyond that only show the # latest value and problems. super.merge({ "extensions" => { "value" => value, "problems" => validation_result.problems }}) do |key, oldValue, newValue| if oldValue.respond_to?(:merge) oldValue.merge(newValue) else newValue end end end private def problem_fields @problem_fields ||= @validation_result .problems .reject { |problem| problem["path"].empty? } .map { |problem| "#{problem['path'].join('.')} (#{problem['explanation']})" } 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/query/validation_pipeline.rb
lib/graphql/query/validation_pipeline.rb
# frozen_string_literal: true module GraphQL class Query # Contain the validation pipeline and expose the results. # # 0. Checks in {Query#initialize}: # - Rescue a ParseError, halt if there is one # - Check for selected operation, halt if not found # 1. Validate the AST, halt if errors # 2. Validate the variables, halt if errors # 3. Run query analyzers, halt if errors # # {#valid?} is false if any of the above checks halted the pipeline. # # @api private class ValidationPipeline attr_reader :max_depth, :max_complexity, :validate_timeout_remaining def initialize(query:, parse_error:, operation_name_error:, max_depth:, max_complexity:) @validation_errors = [] @parse_error = parse_error @operation_name_error = operation_name_error @query = query @schema = query.schema @max_depth = max_depth @max_complexity = max_complexity @has_validated = false end # @return [Boolean] does this query have errors that should prevent it from running? def valid? ensure_has_validated @valid end # @return [Array<GraphQL::StaticValidation::Error, GraphQL::Query::VariableValidationError>] Static validation errors for the query string def validation_errors ensure_has_validated @validation_errors end def analyzers ensure_has_validated @query_analyzers end def has_validated? @has_validated == true end private # If the pipeline wasn't run yet, run it. # If it was already run, do nothing. def ensure_has_validated return if @has_validated @has_validated = true if @parse_error # This is kind of crazy: we push the parse error into `ctx` # in `def self.parse_error` by default so that users can _opt out_ by redefining that hook. # That means we can't _re-add_ the error here (otherwise we'd either # add it twice _or_ override the user's choice to not add it). # So we just have to know that it was invalid and go from there. @valid = false return elsif @operation_name_error @validation_errors << @operation_name_error else validator = @query.static_validator || @schema.static_validator validation_result = validator.validate(@query, validate: @query.validate, timeout: @schema.validate_timeout, max_errors: @schema.validate_max_errors) @validation_errors.concat(validation_result[:errors]) @validate_timeout_remaining = validation_result[:remaining_timeout] if @validation_errors.empty? @validation_errors.concat(@query.variables.errors) end if @validation_errors.empty? @query_analyzers = build_analyzers( @schema, @max_depth, @max_complexity ) end end @valid = @validation_errors.empty? rescue SystemStackError => err @valid = false @schema.query_stack_error(@query, err) end # If there are max_* values, add them, # otherwise reuse the schema's list of analyzers. def build_analyzers(schema, max_depth, max_complexity) qa = schema.query_analyzers.dup if max_depth || max_complexity # Depending on the analysis engine, we must use different analyzers # remove this once everything has switched over to AST analyzers if max_depth qa << GraphQL::Analysis::MaxQueryDepth end if max_complexity qa << GraphQL::Analysis::MaxQueryComplexity end qa else qa 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/query/variables.rb
lib/graphql/query/variables.rb
# frozen_string_literal: true module GraphQL class Query # Read-only access to query variables, applying default values if needed. class Variables extend Forwardable # @return [Array<GraphQL::Query::VariableValidationError>] Any errors encountered when parsing the provided variables and literal values attr_reader :errors attr_reader :context def initialize(ctx, ast_variables, provided_variables) schema = ctx.schema @context = ctx @provided_variables = deep_stringify(provided_variables) @errors = [] @storage = ast_variables.each_with_object({}) do |ast_variable, memo| if schema.validate_max_errors && schema.validate_max_errors <= @errors.count add_max_errors_reached_message break end # Find the right value for this variable: # - First, use the value provided at runtime # - Then, fall back to the default value from the query string # If it's still nil, raise an error if it's required. variable_type = schema.type_from_ast(ast_variable.type, context: ctx) if variable_type.nil? || !variable_type.unwrap.kind.input? # Pass -- it will get handled by a validator else variable_name = ast_variable.name default_value = ast_variable.default_value provided_value = @provided_variables[variable_name] value_was_provided = @provided_variables.key?(variable_name) max_errors = schema.validate_max_errors - @errors.count if schema.validate_max_errors begin validation_result = variable_type.validate_input(provided_value, ctx, max_errors: max_errors) if validation_result.valid? if value_was_provided # Add the variable if a value was provided memo[variable_name] = provided_value elsif default_value != nil memo[variable_name] = if default_value.is_a?(Language::Nodes::NullValue) nil else default_value end end end rescue GraphQL::ExecutionError => ex # TODO: This should really include the path to the problematic node in the variable value # like InputValidationResults generated by validate_non_null_input but unfortunately we don't # have this information available in the coerce_input call chain. Note this path is the path # that appears under errors.extensions.problems.path and NOT the result path under errors.path. validation_result = GraphQL::Query::InputValidationResult.from_problem(ex.message) end if !validation_result.valid? @errors << GraphQL::Query::VariableValidationError.new(ast_variable, variable_type, provided_value, validation_result) end end end end def_delegators :@storage, :length, :key?, :[], :fetch, :to_h private def deep_stringify(val) case val when Array val.map { |v| deep_stringify(v) } when Hash new_val = {} val.each do |k, v| new_val[k.to_s] = deep_stringify(v) end new_val else val end end def add_max_errors_reached_message message = "Too many errors processing variables, max validation error limit reached. Execution aborted" validation_result = GraphQL::Query::InputValidationResult.from_problem(message) errors << GraphQL::Query::VariableValidationError.new(nil, nil, nil, validation_result, msg: message) end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/query/result.rb
lib/graphql/query/result.rb
# frozen_string_literal: true module GraphQL class Query # A result from {Schema#execute}. # It provides the requested data and # access to the {Query} and {Query::Context}. class Result extend Forwardable def initialize(query:, values:) @query = query @to_h = values end # @return [GraphQL::Query] The query that was executed attr_reader :query # @return [Hash] The resulting hash of "data" and/or "errors" attr_reader :to_h def_delegators :@query, :context, :mutation?, :query?, :subscription? def_delegators :@to_h, :[], :keys, :values, :to_json, :as_json # Delegate any hash-like method to the underlying hash. def method_missing(method_name, *args, &block) if @to_h.respond_to?(method_name) @to_h.public_send(method_name, *args, &block) else super end end def respond_to_missing?(method_name, include_private = false) @to_h.respond_to?(method_name) || super end def inspect "#<GraphQL::Query::Result @query=... @to_h=#{@to_h}>" end # A result is equal to another object when: # # - The other object is a Hash whose value matches `result.to_h` # - The other object is a Result whose value matches `result.to_h` # # (The query is ignored for comparing result equality.) # # @return [Boolean] def ==(other) case other when Hash @to_h == other when Query::Result @to_h == other.to_h 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/query/fingerprint.rb
lib/graphql/query/fingerprint.rb
# frozen_string_literal: true require 'digest/sha2' module GraphQL class Query # @api private # @see Query#query_fingerprint # @see Query#variables_fingerprint # @see Query#fingerprint module Fingerprint # Make an obfuscated hash of the given string (either a query string or variables JSON) # @param string [String] # @return [String] A normalized, opaque hash def self.generate(input_str) # Implemented to be: # - Short (and uniform) length # - Stable # - Irreversibly Opaque (don't want to leak variable values) # - URL-friendly bytes = Digest::SHA256.digest(input_str) Base64.urlsafe_encode64(bytes) 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/query/null_context.rb
lib/graphql/query/null_context.rb
# frozen_string_literal: true require "graphql/query/context" module GraphQL class Query # This object can be `ctx` in places where there is no query class NullContext < Context include Singleton class NullQuery def after_lazy(value) yield(value) end end class NullSchema < GraphQL::Schema end extend Forwardable attr_reader :schema, :query, :warden, :dataloader def_delegators GraphQL::EmptyObjects::EMPTY_HASH, :[], :fetch, :dig, :key?, :to_h def initialize @query = NullQuery.new @dataloader = GraphQL::Dataloader::NullDataloader.new @schema = NullSchema @warden = Schema::Warden::NullWarden.new(context: self, schema: @schema) @types = @warden.visibility_profile freeze end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/query/context.rb
lib/graphql/query/context.rb
# frozen_string_literal: true module GraphQL class Query # Expose some query-specific info to field resolve functions. # It delegates `[]` to the hash that's passed to `GraphQL::Query#initialize`. class Context class ExecutionErrors def initialize(ctx) @context = ctx end def add(err_or_msg) err = case err_or_msg when String GraphQL::ExecutionError.new(err_or_msg) when GraphQL::ExecutionError err_or_msg else raise ArgumentError, "expected String or GraphQL::ExecutionError, not #{err_or_msg.class} (#{err_or_msg.inspect})" end # This will assign ast_node and path @context.add_error(err) end alias :>> :add alias :push :add end extend Forwardable # @return [Array<GraphQL::ExecutionError>] errors returned during execution attr_reader :errors # @return [GraphQL::Query] The query whose context this is attr_reader :query # @return [GraphQL::Schema] attr_reader :schema # Make a new context which delegates key lookup to `values` # @param query [GraphQL::Query] the query who owns this context # @param values [Hash] A hash of arbitrary values which will be accessible at query-time def initialize(query:, schema: query.schema, values:) @query = query @schema = schema @provided_values = values || {} # Namespaced storage, where user-provided values are in `nil` namespace: @storage = Hash.new { |h, k| h[k] = {} } @storage[nil] = @provided_values @errors = [] @scoped_context = ScopedContext.new(self) end # Modify this hash to return extensions to client. # @return [Hash] A hash that will be added verbatim to the result hash, as `"extensions" => { ... }` def response_extensions namespace(:__query_result_extensions__) end def dataloader @dataloader ||= self[:dataloader] || (query.multiplex ? query.multiplex.dataloader : schema.dataloader_class.new) end # @api private attr_writer :interpreter # @api private attr_writer :value # @api private attr_reader :scoped_context def []=(key, value) @provided_values[key] = value end def_delegators :@query, :trace def types @types ||= @query.types end attr_writer :types RUNTIME_METADATA_KEYS = Set.new([:current_object, :current_arguments, :current_field, :current_path]).freeze # @!method []=(key, value) # Reassign `key` to the hash passed to {Schema#execute} as `context:` # Lookup `key` from the hash passed to {Schema#execute} as `context:` def [](key) if @scoped_context.key?(key) @scoped_context[key] elsif @provided_values.key?(key) @provided_values[key] elsif RUNTIME_METADATA_KEYS.include?(key) if key == :current_path current_path else (current_runtime_state = Fiber[:__graphql_runtime_info]) && (query_runtime_state = current_runtime_state[@query]) && (query_runtime_state.public_send(key)) end else # not found nil end end # Return this value to tell the runtime # to exclude this field from the response altogether def skip GraphQL::Execution::SKIP end # Add error at query-level. # @param error [GraphQL::ExecutionError] an execution error # @return [void] def add_error(error) if !error.is_a?(ExecutionError) raise TypeError, "expected error to be a ExecutionError, but was #{error.class}" end errors << error nil end # @example Print the GraphQL backtrace during field resolution # puts ctx.backtrace # # @return [GraphQL::Backtrace] The backtrace for this point in query execution def backtrace GraphQL::Backtrace.new(self) end def execution_errors @execution_errors ||= ExecutionErrors.new(self) end def current_path current_runtime_state = Fiber[:__graphql_runtime_info] query_runtime_state = current_runtime_state && current_runtime_state[@query] path = query_runtime_state && (result = query_runtime_state.current_result) && (result.path) if path && (rn = query_runtime_state.current_result_name) path = path.dup path.push(rn) end path end def delete(key) if @scoped_context.key?(key) @scoped_context.delete(key) else @provided_values.delete(key) end end UNSPECIFIED_FETCH_DEFAULT = Object.new def fetch(key, default = UNSPECIFIED_FETCH_DEFAULT) if RUNTIME_METADATA_KEYS.include?(key) (runtime = Fiber[:__graphql_runtime_info]) && (query_runtime_state = runtime[@query]) && (query_runtime_state.public_send(key)) elsif @scoped_context.key?(key) scoped_context[key] elsif @provided_values.key?(key) @provided_values[key] elsif default != UNSPECIFIED_FETCH_DEFAULT default elsif block_given? yield(self, key) else raise KeyError.new(key: key) end end def dig(key, *other_keys) if RUNTIME_METADATA_KEYS.include?(key) (current_runtime_state = Fiber[:__graphql_runtime_info]) && (query_runtime_state = current_runtime_state[@query]) && (obj = query_runtime_state.public_send(key)) && if other_keys.empty? obj else obj.dig(*other_keys) end elsif @scoped_context.key?(key) @scoped_context.dig(key, *other_keys) else @provided_values.dig(key, *other_keys) end end def to_h if (current_scoped_context = @scoped_context.merged_context) @provided_values.merge(current_scoped_context) else @provided_values end end alias :to_hash :to_h def key?(key) @scoped_context.key?(key) || @provided_values.key?(key) end # @return [GraphQL::Schema::Warden] def warden @warden ||= (@query && @query.warden) end # @api private attr_writer :warden # Get an isolated hash for `ns`. Doesn't affect user-provided storage. # @param ns [Object] a usage-specific namespace identifier # @return [Hash] namespaced storage def namespace(ns) if ns == :interpreter self else @storage[ns] end end # @return [Boolean] true if this namespace was accessed before def namespace?(ns) @storage.key?(ns) end def logger @query && @query.logger end def inspect "#<#{self.class} ...>" end def scoped_merge!(hash) @scoped_context.merge!(hash) end def scoped_set!(key, value) scoped_merge!(key => value) nil end # Use this when you need to do a scoped set _inside_ a lazy-loaded (or batch-loaded) # block of code. # # @example using scoped context inside a promise # scoped_ctx = context.scoped # SomeBatchLoader.load(...).then do |thing| # # use a scoped_ctx which was created _before_ dataloading: # scoped_ctx.set!(:thing, thing) # end # @return [Context::Scoped] def scoped Scoped.new(@scoped_context, current_path) end class Scoped def initialize(scoped_context, path) @path = path @scoped_context = scoped_context end def merge!(hash) @scoped_context.merge!(hash, at: @path) end def set!(key, value) @scoped_context.merge!({ key => value }, at: @path) nil end end end end end require "graphql/query/context/scoped_context"
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/query/partial.rb
lib/graphql/query/partial.rb
# frozen_string_literal: true module GraphQL class Query # This class is _like_ a {GraphQL::Query}, except it can run on an arbitrary path within a query string. # # It depends on a "parent" {Query}. # # During execution, it calls query-related tracing hooks but passes itself as `query:`. # # The {Partial} will use your {Schema.resolve_type} hook to find the right GraphQL type to use for # `object` in some cases. # # @see Query#run_partials Run via {Query#run_partials} class Partial include Query::Runnable # @param path [Array<String, Integer>] A path in `query.query_string` to start executing from # @param object [Object] A starting object for execution # @param query [GraphQL::Query] A full query instance that this partial is based on. Caches are shared. # @param context [Hash] Extra context values to merge into `query.context`, if provided # @param fragment_node [GraphQL::Language::Nodes::InlineFragment, GraphQL::Language::Nodes::FragmentDefinition] def initialize(path: nil, object:, query:, context: nil, fragment_node: nil, type: nil) @path = path @object = object @query = query @schema = query.schema context_vals = @query.context.to_h if context context_vals = context_vals.merge(context) end @context = GraphQL::Query::Context.new(query: self, schema: @query.schema, values: context_vals) @multiplex = nil @result_values = nil @result = nil if fragment_node @ast_nodes = [fragment_node] @root_type = type || raise(ArgumentError, "Pass `type:` when using `node:`") # This is only used when `@leaf` @field_definition = nil elsif path.nil? raise ArgumentError, "`path:` is required if `node:` is not given; add `path:`" else set_type_info_from_path end @leaf = @root_type.unwrap.kind.leaf? end def leaf? @leaf end attr_reader :context, :query, :ast_nodes, :root_type, :object, :field_definition, :path, :schema attr_accessor :multiplex, :result_values class Result < GraphQL::Query::Result def path @query.path end # @return [GraphQL::Query::Partial] def partial @query end end def result @result ||= Result.new(query: self, values: result_values) end def current_trace @query.current_trace end def types @query.types end def resolve_type(...) @query.resolve_type(...) end def variables @query.variables end def fragments @query.fragments end def valid? @query.valid? end def analyzers EmptyObjects::EMPTY_ARRAY end def analysis_errors=(_ignored) # pass end def subscription? @query.subscription? end def selected_operation ast_nodes.first end def static_errors @query.static_errors end def selected_operation_name @query.selected_operation_name end private def set_type_info_from_path selections = [@query.selected_operation] type = @query.root_type parent_type = nil field_defn = nil @path.each do |name_in_doc| if name_in_doc.is_a?(Integer) if type.list? type = type.unwrap next else raise ArgumentError, "Received path with index `#{name_in_doc}`, but type wasn't a list. Type: #{type.to_type_signature}, path: #{@path}" end end next_selections = [] selections.each do |selection| selections_to_check = [] selections_to_check.concat(selection.selections) while (sel = selections_to_check.shift) case sel when GraphQL::Language::Nodes::InlineFragment selections_to_check.concat(sel.selections) when GraphQL::Language::Nodes::FragmentSpread fragment = @query.fragments[sel.name] selections_to_check.concat(fragment.selections) when GraphQL::Language::Nodes::Field if sel.alias == name_in_doc || sel.name == name_in_doc next_selections << sel end else raise "Unexpected selection in partial path: #{sel.class}, #{sel.inspect}" end end end if next_selections.empty? raise ArgumentError, "Path `#{@path.inspect}` is not present in this query. `#{name_in_doc.inspect}` was not found. Try a different path or rewrite the query to include it." end field_name = next_selections.first.name field_defn = @schema.get_field(type, field_name, @query.context) || raise("Invariant: no field called #{field_name} on #{type.graphql_name}") parent_type = type type = field_defn.type if type.non_null? type = type.of_type end selections = next_selections end @ast_nodes = selections @root_type = type @field_definition = field_defn 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/query/context/scoped_context.rb
lib/graphql/query/context/scoped_context.rb
# frozen_string_literal: true module GraphQL class Query class Context class ScopedContext def initialize(query_context) @query_context = query_context @scoped_contexts = nil @all_keys = nil end def merged_context if @scoped_contexts.nil? GraphQL::EmptyObjects::EMPTY_HASH else merged_ctx = {} each_present_path_ctx do |path_ctx| merged_ctx = path_ctx.merge(merged_ctx) end merged_ctx end end def merge!(hash, at: current_path) @all_keys ||= Set.new @all_keys.merge(hash.keys) ctx = @scoped_contexts ||= {} at.each do |path_part| ctx = ctx[path_part] ||= { parent: ctx } end this_scoped_ctx = ctx[:scoped_context] ||= {} this_scoped_ctx.merge!(hash) end def key?(key) if @all_keys && @all_keys.include?(key) each_present_path_ctx do |path_ctx| if path_ctx.key?(key) return true end end end false end def [](key) each_present_path_ctx do |path_ctx| if path_ctx.key?(key) return path_ctx[key] end end nil end def current_path @query_context.current_path || GraphQL::EmptyObjects::EMPTY_ARRAY end def dig(key, *other_keys) each_present_path_ctx do |path_ctx| if path_ctx.key?(key) found_value = path_ctx[key] if !other_keys.empty? return found_value.dig(*other_keys) else return found_value end end end nil end private # Start at the current location, # but look up the tree for previously-assigned scoped values def each_present_path_ctx ctx = @scoped_contexts if ctx.nil? # no-op else current_path.each do |path_part| if ctx.key?(path_part) ctx = ctx[path_part] else break end end while ctx if (scoped_ctx = ctx[:scoped_context]) yield(scoped_ctx) end ctx = ctx[:parent] 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/subscriptions/event.rb
lib/graphql/subscriptions/event.rb
# frozen_string_literal: true module GraphQL class Subscriptions # This thing can be: # - Subscribed to by `subscription { ... }` # - Triggered by `MySchema.subscriber.trigger(name, arguments, obj)` # class Event # @return [String] Corresponds to the Subscription root field name attr_reader :name # @return [GraphQL::Execution::Interpreter::Arguments] attr_reader :arguments # @return [GraphQL::Query::Context] attr_reader :context # @return [String] An opaque string which identifies this event, derived from `name` and `arguments` attr_reader :topic def initialize(name:, arguments:, field: nil, context: nil, scope: nil) @name = name @arguments = self.class.arguments_without_field_extras(arguments: arguments, field: field) @context = context field ||= context.field scope_key = field.subscription_scope scope_val = scope || (context && scope_key && context[scope_key]) if scope_key && (subscription = field.resolver) && (subscription.respond_to?(:subscription_scope_optional?)) && !subscription.subscription_scope_optional? && scope_val.nil? raise Subscriptions::SubscriptionScopeMissingError, "#{field.path} (#{subscription}) requires a `scope:` value to trigger updates (Set `subscription_scope ..., optional: true` to disable this requirement)" end @topic = self.class.serialize(name, arguments, field, scope: scope_val, context: context) end # @return [String] an identifier for this unit of subscription def self.serialize(_name, arguments, field, scope:, context: GraphQL::Query::NullContext.instance) subscription = field.resolver || GraphQL::Schema::Subscription arguments = arguments_without_field_extras(field: field, arguments: arguments) normalized_args = stringify_args(field, arguments.to_h, context) subscription.topic_for(arguments: normalized_args, field: field, scope: scope) end # @return [String] a logical identifier for this event. (Stable when the query is broadcastable.) def fingerprint @fingerprint ||= begin # When this query has been flagged as broadcastable, # use a generalized, stable fingerprint so that # duplicate subscriptions can be evaluated and distributed in bulk. # (`@topic` includes field, args, and subscription scope already.) if @context.namespace(:subscriptions)[:subscription_broadcastable] "#{@topic}/#{@context.query.fingerprint}" else # not broadcastable, build a unique ID for this event @context.schema.subscriptions.build_id end end end class << self def arguments_without_field_extras(arguments:, field:) if !field.extras.empty? arguments = arguments.dup field.extras.each do |extra_key| arguments.delete(extra_key) end end arguments end private # This method does not support cyclic references in the Hash, # nor does it support Hashes whose keys are not sortable # with respect to their peers ( cases where a <=> b might throw an error ) def deep_sort_hash_keys(hash_to_sort) raise ArgumentError.new("Argument must be a Hash") unless hash_to_sort.is_a?(Hash) hash_to_sort.keys.sort.map do |k| if hash_to_sort[k].is_a?(Hash) [k, deep_sort_hash_keys(hash_to_sort[k])] elsif hash_to_sort[k].is_a?(Array) [k, deep_sort_array_hashes(hash_to_sort[k])] else [k, hash_to_sort[k]] end end.to_h end def deep_sort_array_hashes(array_to_inspect) raise ArgumentError.new("Argument must be an Array") unless array_to_inspect.is_a?(Array) array_to_inspect.map do |v| if v.is_a?(Hash) deep_sort_hash_keys(v) elsif v.is_a?(Array) deep_sort_array_hashes(v) else v end end end def stringify_args(arg_owner, args, context) arg_owner = arg_owner.respond_to?(:unwrap) ? arg_owner.unwrap : arg_owner # remove list and non-null wrappers case args when Hash next_args = {} args.each do |k, v| arg_name = k.to_s camelized_arg_name = GraphQL::Schema::Member::BuildType.camelize(arg_name) arg_defn = get_arg_definition(arg_owner, camelized_arg_name, context) arg_defn ||= get_arg_definition(arg_owner, arg_name, context) normalized_arg_name = arg_defn.graphql_name arg_base_type = arg_defn.type.unwrap # In the case where the value being emitted is seen as a "JSON" # type, treat the value as one atomic unit of serialization is_json_definition = arg_base_type && arg_base_type <= GraphQL::Types::JSON if is_json_definition sorted_value = if v.is_a?(Hash) deep_sort_hash_keys(v) elsif v.is_a?(Array) deep_sort_array_hashes(v) else v end next_args[normalized_arg_name] = sorted_value.respond_to?(:to_json) ? sorted_value.to_json : sorted_value else next_args[normalized_arg_name] = stringify_args(arg_base_type, v, context) end end # Make sure they're deeply sorted next_args.sort.to_h when Array args.map { |a| stringify_args(arg_owner, a, context) } when GraphQL::Schema::InputObject stringify_args(arg_owner, args.to_h, context) else if arg_owner.is_a?(Class) && arg_owner < GraphQL::Schema::Enum # `prepare:` may have made the value something other than # a defined value of this enum -- use _that_ in this case. arg_owner.coerce_isolated_input(args) || args else args end end end def get_arg_definition(arg_owner, arg_name, context) context.types.argument(arg_owner, arg_name) || context.types.arguments(arg_owner).find { |v| v.keyword.to_s == arg_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/subscriptions/broadcast_analyzer.rb
lib/graphql/subscriptions/broadcast_analyzer.rb
# frozen_string_literal: true module GraphQL class Subscriptions # Detect whether the current operation: # - Is a subscription operation # - Is completely broadcastable # # Assign the result to `context.namespace(:subscriptions)[:subscription_broadcastable]` # @api private # @see Subscriptions#broadcastable? for a public API class BroadcastAnalyzer < GraphQL::Analysis::Analyzer def initialize(subject) super @default_broadcastable = subject.schema.subscriptions.default_broadcastable # Maybe this will get set to false while analyzing @subscription_broadcastable = true end # Only analyze subscription operations def analyze? @query.subscription? end def on_enter_field(node, parent, visitor) if (@subscription_broadcastable == false) || visitor.skipping? return end current_field = visitor.field_definition current_type = visitor.parent_type_definition apply_broadcastable(current_type, current_field) if current_type.kind.interface? pt = @query.possible_types(current_type) pt.each do |object_type| ot_field = @query.get_field(object_type, current_field.graphql_name) # Inherited fields would be exactly the same object; # only check fields that are overrides of the inherited one if ot_field && ot_field != current_field apply_broadcastable(object_type, ot_field) end end end end # Assign the result to context. # (This method is allowed to return an error, but we don't need to) # @return [void] def result query.context.namespace(:subscriptions)[:subscription_broadcastable] = @subscription_broadcastable nil end private # Modify `@subscription_broadcastable` based on `field_defn`'s configuration (and/or the default value) def apply_broadcastable(owner_type, field_defn) current_field_broadcastable = field_defn.introspection? || field_defn.broadcastable? if current_field_broadcastable.nil? && owner_type.respond_to?(:default_broadcastable?) current_field_broadcastable = owner_type.default_broadcastable? end case current_field_broadcastable when nil query.logger.debug { "`broadcastable: nil` for field: #{field_defn.path}" } # If the value wasn't set, mix in the default value: # - If the default is false and the current value is true, make it false # - If the default is true and the current value is true, it stays true # - If the default is false and the current value is false, keep it false # - If the default is true and the current value is false, keep it false @subscription_broadcastable = @subscription_broadcastable && @default_broadcastable when false query.logger.debug { "`broadcastable: false` for field: #{field_defn.path}" } # One non-broadcastable field is enough to make the whole subscription non-broadcastable @subscription_broadcastable = false when true # Leave `@broadcastable_query` true if it's already true, # but don't _set_ it to true if it was set to false by something else. # Actually, just leave it! else raise ArgumentError, "Unexpected `.broadcastable?` value for #{field_defn.path}: #{current_field_broadcastable}" 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/subscriptions/serialize.rb
lib/graphql/subscriptions/serialize.rb
# frozen_string_literal: true require "set" module GraphQL class Subscriptions # Serialization helpers for passing subscription data around. # @api private module Serialize GLOBALID_KEY = "__gid__" SYMBOL_KEY = "__sym__" SYMBOL_KEYS_KEY = "__sym_keys__" TIMESTAMP_KEY = "__timestamp__" TIMESTAMP_FORMAT = "%Y-%m-%d %H:%M:%S.%N%z" # eg '2020-01-01 23:59:59.123456789+05:00' OPEN_STRUCT_KEY = "__ostruct__" module_function # @param str [String] A serialized object from {.dump} # @return [Object] An object equivalent to the one passed to {.dump} def load(str) parsed_obj = JSON.parse(str) load_value(parsed_obj) end # @param obj [Object] Some subscription-related data to dump # @return [String] The stringified object def dump(obj) JSON.generate(dump_value(obj), quirks_mode: true) end # This is for turning objects into subscription scopes. # It's a one-way transformation, can't reload this :'( # @param obj [Object] # @return [String] def dump_recursive(obj) case when obj.is_a?(Array) obj.map { |i| dump_recursive(i) }.join(':') when obj.is_a?(Hash) obj.map { |k, v| "#{dump_recursive(k)}:#{dump_recursive(v)}" }.join(":") when obj.is_a?(GraphQL::Schema::InputObject) dump_recursive(obj.to_h) when obj.respond_to?(:to_gid_param) obj.to_gid_param when obj.respond_to?(:to_param) obj.to_param else obj.to_s end end class << self private # @param value [Object] A parsed JSON object # @return [Object] An object that load Global::Identification recursive def load_value(value) if value.is_a?(Array) is_gids = (v1 = value[0]).is_a?(Hash) && v1.size == 1 && v1[GLOBALID_KEY] if is_gids # Assume it's an array of global IDs ids = value.map { |v| v[GLOBALID_KEY] } GlobalID::Locator.locate_many(ids) else value.map { |item| load_value(item) } end elsif value.is_a?(Hash) if value.size == 1 case value.keys.first # there's only 1 key when GLOBALID_KEY GlobalID::Locator.locate(value[GLOBALID_KEY]) when SYMBOL_KEY value[SYMBOL_KEY].to_sym when TIMESTAMP_KEY timestamp_class_name, *timestamp_args = value[TIMESTAMP_KEY] timestamp_class = Object.const_get(timestamp_class_name) if defined?(ActiveSupport::TimeWithZone) && timestamp_class <= ActiveSupport::TimeWithZone zone_name, timestamp_s = timestamp_args zone = ActiveSupport::TimeZone[zone_name] raise "Zone #{zone_name} not found, unable to deserialize" unless zone zone.strptime(timestamp_s, TIMESTAMP_FORMAT) else timestamp_s = timestamp_args.first timestamp_class.strptime(timestamp_s, TIMESTAMP_FORMAT) end when OPEN_STRUCT_KEY ostruct_values = load_value(value[OPEN_STRUCT_KEY]) OpenStruct.new(ostruct_values) else key = value.keys.first { key => load_value(value[key]) } end else loaded_h = {} sym_keys = value.fetch(SYMBOL_KEYS_KEY, []) value.each do |k, v| if k == SYMBOL_KEYS_KEY next end if sym_keys.include?(k) k = k.to_sym end loaded_h[k] = load_value(v) end loaded_h end else value end end # @param obj [Object] Some subscription-related data to dump # @return [Object] The object that converted Global::Identification def dump_value(obj) if obj.is_a?(Array) obj.map{|item| dump_value(item)} elsif obj.is_a?(Hash) symbol_keys = nil dumped_h = {} obj.each do |k, v| dumped_h[k.to_s] = dump_value(v) if k.is_a?(Symbol) symbol_keys ||= Set.new symbol_keys << k.to_s end end if symbol_keys dumped_h[SYMBOL_KEYS_KEY] = symbol_keys.to_a end dumped_h elsif obj.is_a?(Symbol) { SYMBOL_KEY => obj.to_s } elsif obj.respond_to?(:to_gid_param) {GLOBALID_KEY => obj.to_gid_param} elsif defined?(ActiveSupport::TimeWithZone) && obj.is_a?(ActiveSupport::TimeWithZone) && obj.class.name != Time.name # This handles a case where Rails prior to 7 would # make the class ActiveSupport::TimeWithZone return "Time" for # its name. In Rails 7, it will now return "ActiveSupport::TimeWithZone", # which happens to be incompatible with expectations we have # with what a Time class supports ( notably, strptime in `load_value` ). # # This now passes along the name of the zone, such that a future deserialization # of this string will use the correct time zone from the ActiveSupport TimeZone # list to produce the time. # { TIMESTAMP_KEY => [obj.class.name, obj.time_zone.name, obj.strftime(TIMESTAMP_FORMAT)] } elsif obj.is_a?(Date) || obj.is_a?(Time) # DateTime extends Date; for TimeWithZone, call `.utc` first. { TIMESTAMP_KEY => [obj.class.name, obj.strftime(TIMESTAMP_FORMAT)] } elsif defined?(OpenStruct) && obj.is_a?(OpenStruct) { OPEN_STRUCT_KEY => dump_value(obj.to_h) } elsif defined?(ActiveRecord::Relation) && obj.is_a?(ActiveRecord::Relation) dump_value(obj.to_a) else obj end end end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/subscriptions/action_cable_subscriptions.rb
lib/graphql/subscriptions/action_cable_subscriptions.rb
# frozen_string_literal: true module GraphQL class Subscriptions # A subscriptions implementation that sends data # as ActionCable broadcastings. # # Some things to keep in mind: # # - No queueing system; ActiveJob should be added # - Take care to reload context when re-delivering the subscription. (see {Query#subscription_update?}) # - Avoid the async ActionCable adapter and use the redis or PostgreSQL adapters instead. Otherwise calling #trigger won't work from background jobs or the Rails console. # # @example Adding ActionCableSubscriptions to your schema # class MySchema < GraphQL::Schema # # ... # use GraphQL::Subscriptions::ActionCableSubscriptions # end # # @example Implementing a channel for GraphQL Subscriptions # class GraphqlChannel < ApplicationCable::Channel # def subscribed # @subscription_ids = [] # end # # def execute(data) # query = data["query"] # variables = ensure_hash(data["variables"]) # operation_name = data["operationName"] # context = { # # Re-implement whatever context methods you need # # in this channel or ApplicationCable::Channel # # current_user: current_user, # # Make sure the channel is in the context # channel: self, # } # # result = MySchema.execute( # query, # context: context, # variables: variables, # operation_name: operation_name # ) # # payload = { # result: result.to_h, # more: result.subscription?, # } # # # Track the subscription here so we can remove it # # on unsubscribe. # if result.context[:subscription_id] # @subscription_ids << result.context[:subscription_id] # end # # transmit(payload) # end # # def unsubscribed # @subscription_ids.each { |sid| # MySchema.subscriptions.delete_subscription(sid) # } # end # # private # # def ensure_hash(ambiguous_param) # case ambiguous_param # when String # if ambiguous_param.present? # ensure_hash(JSON.parse(ambiguous_param)) # else # {} # end # when Hash, ActionController::Parameters # ambiguous_param # when nil # {} # else # raise ArgumentError, "Unexpected parameter: #{ambiguous_param}" # end # end # end # # @see GraphQL::Testing::MockActionCable for test helpers class ActionCableSubscriptions < GraphQL::Subscriptions SUBSCRIPTION_PREFIX = "graphql-subscription:" EVENT_PREFIX = "graphql-event:" # @param serializer [<#dump(obj), #load(string)] Used for serializing messages before handing them to `.broadcast(msg)` # @param namespace [string] Used to namespace events and subscriptions (default: '') def initialize(serializer: Serialize, namespace: '', action_cable: ActionCable, action_cable_coder: ActiveSupport::JSON, **rest) # A per-process map of subscriptions to deliver. # This is provided by Rails, so let's use it @subscriptions = Concurrent::Map.new @events = Concurrent::Map.new do |h, k| h.compute_if_absent(k) do Concurrent::Map.new do |h2, k2| h2.compute_if_absent(k2) { Concurrent::Array.new } end end end @action_cable = action_cable @action_cable_coder = action_cable_coder @serializer = serializer @serialize_with_context = case @serializer.method(:load).arity when 1 false when 2 true else raise ArgumentError, "#{@serializer} must respond to `.load` accepting one or two arguments" end @transmit_ns = namespace super end # An event was triggered; Push the data over ActionCable. # Subscribers will re-evaluate locally. def execute_all(event, object) stream = stream_event_name(event) message = @serializer.dump(object) @action_cable.server.broadcast(stream, message) end # This subscription was re-evaluated. # Send it to the specific stream where this client was waiting. def deliver(subscription_id, result) has_more = !result.context.namespace(:subscriptions)[:final_update] payload = { result: result.to_h, more: has_more } @action_cable.server.broadcast(stream_subscription_name(subscription_id), payload) end # A query was run where these events were subscribed to. # Store them in memory in _this_ ActionCable frontend. # It will receive notifications when events come in # and re-evaluate the query locally. def write_subscription(query, events) unless (channel = query.context[:channel]) raise GraphQL::Error, "This GraphQL Subscription client does not support the transport protocol expected"\ "by the backend Subscription Server implementation (graphql-ruby ActionCableSubscriptions in this case)."\ "Some official client implementation including Apollo (https://graphql-ruby.org/javascript_client/apollo_subscriptions.html), "\ "Relay Modern (https://graphql-ruby.org/javascript_client/relay_subscriptions.html#actioncable)."\ "GraphiQL via `graphiql-rails` may not work out of box (#1051)." end subscription_id = query.context[:subscription_id] ||= build_id stream = stream_subscription_name(subscription_id) channel.stream_from(stream) @subscriptions[subscription_id] = query events.each do |event| # Setup a new listener to run all events with this topic in this process setup_stream(channel, event) # Add this event to the list of events to be updated @events[event.topic][event.fingerprint] << event end end # Every subscribing channel is listening here, but only one of them takes any action. # This is so we can reuse payloads when possible, and make one payload to send to # all subscribers. # # But the problem is, any channel could close at any time, so each channel has to # be ready to take over the primary position. # # To make sure there's always one-and-only-one channel building payloads, # let the listener belonging to the first event on the list be # the one to build and publish payloads. # def setup_stream(channel, initial_event) topic = initial_event.topic event_stream = stream_event_name(initial_event) channel.stream_from(event_stream, coder: @action_cable_coder) do |message| events_by_fingerprint = @events[topic] object = nil events_by_fingerprint.each do |_fingerprint, events| if !events.empty? && events.first == initial_event # The fingerprint has told us that this response should be shared by all subscribers, # so just run it once, then deliver the result to every subscriber first_event = events.first first_subscription_id = first_event.context.fetch(:subscription_id) object ||= load_action_cable_message(message, first_event.context) result = execute_update(first_subscription_id, first_event, object) if !result.nil? # Having calculated the result _once_, send the same payload to all subscribers events.each do |event| subscription_id = event.context.fetch(:subscription_id) deliver(subscription_id, result) end end end end nil end end # This is called to turn an ActionCable-broadcasted string (JSON) # into a query-ready application object. # @param message [String] n ActionCable-broadcasted string (JSON) # @param context [GraphQL::Query::Context] the context of the first event for a given subscription fingerprint def load_action_cable_message(message, context) if @serialize_with_context @serializer.load(message, context) else @serializer.load(message) end end # Return the query from "storage" (in memory) def read_subscription(subscription_id) query = @subscriptions[subscription_id] if query.nil? # This can happen when a subscription is triggered from an unsubscribed channel, # see https://github.com/rmosolgo/graphql-ruby/issues/2478. # (This `nil` is handled by `#execute_update`) nil else { query_string: query.query_string, variables: query.provided_variables, context: query.context.to_h, operation_name: query.operation_name, } end end # The channel was closed, forget about it. def delete_subscription(subscription_id) query = @subscriptions.delete(subscription_id) # In case this came from the server, tell the client to unsubscribe: @action_cable.server.broadcast(stream_subscription_name(subscription_id), { more: false }) # This can be `nil` when `.trigger` happens inside an unsubscribed ActionCable channel, # see https://github.com/rmosolgo/graphql-ruby/issues/2478 if query events = query.context.namespace(:subscriptions)[:events] events.each do |event| ev_by_fingerprint = @events[event.topic] ev_for_fingerprint = ev_by_fingerprint[event.fingerprint] ev_for_fingerprint.delete(event) if ev_for_fingerprint.empty? ev_by_fingerprint.delete(event.fingerprint) end end end end private def stream_subscription_name(subscription_id) [SUBSCRIPTION_PREFIX, @transmit_ns, subscription_id].join end def stream_event_name(event) [EVENT_PREFIX, @transmit_ns, event.topic].join 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/subscriptions/default_subscription_resolve_extension.rb
lib/graphql/subscriptions/default_subscription_resolve_extension.rb
# frozen_string_literal: true module GraphQL class Subscriptions class DefaultSubscriptionResolveExtension < GraphQL::Schema::FieldExtension def resolve(context:, object:, arguments:) has_override_implementation = @field.resolver || object.respond_to?(@field.resolver_method) if !has_override_implementation if context.query.subscription_update? object.object else context.skip end else yield(object, arguments) end end def after_resolve(value:, context:, object:, arguments:, **rest) if value.is_a?(GraphQL::ExecutionError) value elsif @field.resolver&.method_defined?(:subscription_written?) && (subscription_namespace = context.namespace(:subscriptions)) && (subscriptions_by_path = subscription_namespace[:subscriptions]) (subscription_instance = subscriptions_by_path[context.current_path]) # If it was already written, don't append this event to be written later if !subscription_instance.subscription_written? events = context.namespace(:subscriptions)[:events] events << subscription_instance.event end value elsif (events = context.namespace(:subscriptions)[:events]) # This is the first execution, so gather an Event # for the backend to register: event = Subscriptions::Event.new( name: field.name, arguments: arguments, context: context, field: field, ) events << event value elsif context.query.subscription_topic == Subscriptions::Event.serialize( field.name, arguments, field, scope: (field.subscription_scope ? context[field.subscription_scope] : nil), ) # This is a subscription update. The resolver returned `skip` if it should be skipped, # or else it returned an object to resolve the update. value else # This is a subscription update, but this event wasn't triggered. context.skip 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/introspection/field_type.rb
lib/graphql/introspection/field_type.rb
# frozen_string_literal: true module GraphQL module Introspection class FieldType < Introspection::BaseObject graphql_name "__Field" description "Object and Interface types are described by a list of Fields, each of which has "\ "a name, potentially a list of arguments, and a return type." field :name, String, null: false field :description, String field :args, [GraphQL::Schema::LateBoundType.new("__InputValue")], null: false, scope: false do argument :include_deprecated, Boolean, required: false, default_value: false end field :type, GraphQL::Schema::LateBoundType.new("__Type"), null: false field :is_deprecated, Boolean, null: false field :deprecation_reason, String def is_deprecated !!@object.deprecation_reason end def args(include_deprecated:) args = @context.types.arguments(@object) args = args.reject(&:deprecation_reason) unless include_deprecated args 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/introspection/directive_location_enum.rb
lib/graphql/introspection/directive_location_enum.rb
# frozen_string_literal: true module GraphQL module Introspection class DirectiveLocationEnum < GraphQL::Schema::Enum graphql_name "__DirectiveLocation" description "A Directive can be adjacent to many parts of the GraphQL language, "\ "a __DirectiveLocation describes one such possible adjacencies." GraphQL::Schema::Directive::LOCATIONS.each do |location| value(location.to_s, GraphQL::Schema::Directive::LOCATION_DESCRIPTIONS[location], value: location, value_method: false) end introspection true end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/introspection/directive_type.rb
lib/graphql/introspection/directive_type.rb
# frozen_string_literal: true module GraphQL module Introspection class DirectiveType < Introspection::BaseObject graphql_name "__Directive" description "A Directive provides a way to describe alternate runtime execution and type validation behavior in a GraphQL document."\ "\n\n"\ "In some cases, you need to provide options to alter GraphQL's execution behavior "\ "in ways field arguments will not suffice, such as conditionally including or "\ "skipping a field. Directives provide this by describing additional information "\ "to the executor." field :name, String, null: false, method: :graphql_name field :description, String field :locations, [GraphQL::Schema::LateBoundType.new("__DirectiveLocation")], null: false, scope: false field :args, [GraphQL::Schema::LateBoundType.new("__InputValue")], null: false, scope: false do argument :include_deprecated, Boolean, required: false, default_value: false end field :on_operation, Boolean, null: false, deprecation_reason: "Use `locations`.", method: :on_operation? field :on_fragment, Boolean, null: false, deprecation_reason: "Use `locations`.", method: :on_fragment? field :on_field, Boolean, null: false, deprecation_reason: "Use `locations`.", method: :on_field? field :is_repeatable, Boolean, method: :repeatable? def args(include_deprecated:) args = @context.types.arguments(@object) args = args.reject(&:deprecation_reason) unless include_deprecated args 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/introspection/enum_value_type.rb
lib/graphql/introspection/enum_value_type.rb
# frozen_string_literal: true module GraphQL module Introspection class EnumValueType < Introspection::BaseObject graphql_name "__EnumValue" description "One possible value for a given Enum. Enum values are unique values, not a "\ "placeholder for a string or numeric value. However an Enum value is returned in "\ "a JSON response as a string." field :name, String, null: false field :description, String field :is_deprecated, Boolean, null: false field :deprecation_reason, String def name object.graphql_name end def is_deprecated !!@object.deprecation_reason 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/introspection/input_value_type.rb
lib/graphql/introspection/input_value_type.rb
# frozen_string_literal: true module GraphQL module Introspection class InputValueType < Introspection::BaseObject graphql_name "__InputValue" description "Arguments provided to Fields or Directives and the input fields of an "\ "InputObject are represented as Input Values which describe their type and "\ "optionally a default value." field :name, String, null: false field :description, String field :type, GraphQL::Schema::LateBoundType.new("__Type"), null: false field :default_value, String, "A GraphQL-formatted string representing the default value for this input value." field :is_deprecated, Boolean, null: false field :deprecation_reason, String def is_deprecated !!@object.deprecation_reason end def default_value if @object.default_value? value = @object.default_value if value.nil? 'null' else if (@object.type.kind.list? || (@object.type.kind.non_null? && @object.type.of_type.kind.list?)) && !value.respond_to?(:map) # This is a bit odd -- we expect the default value to be an application-style value, so we use coerce result below. # But coerce_result doesn't wrap single-item lists, which are valid inputs to list types. # So, apply that wrapper here if needed. value = [value] end coerced_default_value = @object.type.coerce_result(value, @context) serialize_default_value(coerced_default_value, @object.type) end else nil end end private # Recursively serialize, taking care not to add quotes to enum values def serialize_default_value(value, type) if value.nil? 'null' elsif type.kind.list? inner_type = type.of_type "[" + value.map { |v| serialize_default_value(v, inner_type) }.join(", ") + "]" elsif type.kind.non_null? serialize_default_value(value, type.of_type) elsif type.kind.enum? value elsif type.kind.input_object? "{" + value.map do |k, v| arg_defn = type.get_argument(k, context) "#{k}: #{serialize_default_value(v, arg_defn.type)}" end.join(", ") + "}" else GraphQL::Language.serialize(value) end end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/introspection/base_object.rb
lib/graphql/introspection/base_object.rb
# frozen_string_literal: true module GraphQL module Introspection class BaseObject < GraphQL::Schema::Object introspection(true) def self.field(*args, **kwargs, &block) kwargs[:introspection] = true super(*args, **kwargs, &block) 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/introspection/dynamic_fields.rb
lib/graphql/introspection/dynamic_fields.rb
# frozen_string_literal: true module GraphQL module Introspection class DynamicFields < Introspection::BaseObject field :__typename, String, "The name of this type", null: false, dynamic_introspection: true def __typename object.class.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/introspection/introspection_query.rb
lib/graphql/introspection/introspection_query.rb
# frozen_string_literal: true # This query is used by graphql-client so don't add the includeDeprecated # argument for inputFields since the server may not support it. Two stage # introspection queries will be required to handle this in clients. GraphQL::Introspection::INTROSPECTION_QUERY = GraphQL::Introspection.query
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/introspection/type_type.rb
lib/graphql/introspection/type_type.rb
# frozen_string_literal: true module GraphQL module Introspection class TypeType < Introspection::BaseObject graphql_name "__Type" description "The fundamental unit of any GraphQL Schema is the type. There are many kinds of types in "\ "GraphQL as represented by the `__TypeKind` enum.\n\n"\ "Depending on the kind of a type, certain fields describe information about that type. "\ "Scalar types provide no information beyond a name and description, while "\ "Enum types provide their values. Object and Interface types provide the fields "\ "they describe. Abstract types, Union and Interface, provide the Object types "\ "possible at runtime. List and NonNull types compose other types." field :kind, GraphQL::Schema::LateBoundType.new("__TypeKind"), null: false field :name, String, method: :graphql_name field :description, String field :fields, [GraphQL::Schema::LateBoundType.new("__Field")], scope: false do argument :include_deprecated, Boolean, required: false, default_value: false end field :interfaces, [GraphQL::Schema::LateBoundType.new("__Type")], scope: false field :possible_types, [GraphQL::Schema::LateBoundType.new("__Type")], scope: false field :enum_values, [GraphQL::Schema::LateBoundType.new("__EnumValue")], scope: false do argument :include_deprecated, Boolean, required: false, default_value: false end field :input_fields, [GraphQL::Schema::LateBoundType.new("__InputValue")], scope: false do argument :include_deprecated, Boolean, required: false, default_value: false end field :of_type, GraphQL::Schema::LateBoundType.new("__Type") field :specifiedByURL, String, resolver_method: :specified_by_url field :is_one_of, Boolean, null: false def is_one_of object.kind.input_object? && object.directives.any? { |d| d.graphql_name == "oneOf" } end def specified_by_url if object.kind.scalar? object.specified_by_url else nil end end def kind @object.kind.name end def enum_values(include_deprecated:) if !@object.kind.enum? nil else enum_values = @context.types.enum_values(@object) if !include_deprecated enum_values = enum_values.select {|f| !f.deprecation_reason } end enum_values end end def interfaces if @object.kind.object? || @object.kind.interface? @context.types.interfaces(@object).sort_by(&:graphql_name) else nil end end def input_fields(include_deprecated:) if @object.kind.input_object? args = @context.types.arguments(@object) args = args.reject(&:deprecation_reason) unless include_deprecated args else nil end end def possible_types if @object.kind.abstract? @context.types.possible_types(@object).sort_by(&:graphql_name) else nil end end def fields(include_deprecated:) if !@object.kind.fields? nil else fields = @context.types.fields(@object) if !include_deprecated fields = fields.select {|f| !f.deprecation_reason } end fields.sort_by(&:name) end end def of_type @object.kind.wraps? ? @object.of_type : nil end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/introspection/schema_type.rb
lib/graphql/introspection/schema_type.rb
# frozen_string_literal: true module GraphQL module Introspection class SchemaType < Introspection::BaseObject graphql_name "__Schema" description "A GraphQL Schema defines the capabilities of a GraphQL server. It exposes all "\ "available types and directives on the server, as well as the entry points for "\ "query, mutation, and subscription operations." field :types, [GraphQL::Schema::LateBoundType.new("__Type")], "A list of all types supported by this server.", null: false, scope: false field :query_type, GraphQL::Schema::LateBoundType.new("__Type"), "The type that query operations will be rooted at.", null: false field :mutation_type, GraphQL::Schema::LateBoundType.new("__Type"), "If this server supports mutation, the type that mutation operations will be rooted at." field :subscription_type, GraphQL::Schema::LateBoundType.new("__Type"), "If this server support subscription, the type that subscription operations will be rooted at." field :directives, [GraphQL::Schema::LateBoundType.new("__Directive")], "A list of all directives supported by this server.", null: false, scope: false field :description, String, resolver_method: :schema_description def schema_description context.schema.description end def types query_types = context.types.all_types types = query_types + context.schema.extra_types types.sort_by!(&:graphql_name) types end def query_type @context.types.query_root end def mutation_type @context.types.mutation_root end def subscription_type @context.types.subscription_root end def directives @context.types.directives.sort_by(&: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/introspection/type_kind_enum.rb
lib/graphql/introspection/type_kind_enum.rb
# frozen_string_literal: true module GraphQL module Introspection class TypeKindEnum < GraphQL::Schema::Enum graphql_name "__TypeKind" description "An enum describing what kind of type a given `__Type` is." GraphQL::TypeKinds::TYPE_KINDS.each do |type_kind| value(type_kind.name, type_kind.description) end introspection true end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false
rmosolgo/graphql-ruby
https://github.com/rmosolgo/graphql-ruby/blob/fa2ba4e489f8475b194f7c6985e0b25681a442c2/lib/graphql/introspection/entry_points.rb
lib/graphql/introspection/entry_points.rb
# frozen_string_literal: true module GraphQL module Introspection class EntryPoints < Introspection::BaseObject field :__schema, GraphQL::Schema::LateBoundType.new("__Schema"), "This GraphQL schema", null: false, dynamic_introspection: true field :__type, GraphQL::Schema::LateBoundType.new("__Type"), "A type in the GraphQL system", dynamic_introspection: true do argument :name, String end def __schema # Apply wrapping manually since this field isn't wrapped by instrumentation schema = context.schema schema_type = schema.introspection_system.types["__Schema"] schema_type.wrap(schema, context) end def __type(name:) if context.types.reachable_type?(name) && (type = context.types.type(name)) type elsif (type = context.schema.extra_types.find { |t| t.graphql_name == name }) type 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/relay/range_add.rb
lib/graphql/relay/range_add.rb
# frozen_string_literal: true module GraphQL module Relay # This provides some isolation from `GraphQL::Relay` internals. # # Given a list of items and a new item, it will provide a connection and an edge. # # The connection doesn't receive outside arguments, so the list of items # should be ordered and paginated before providing it here. # # @example Adding a comment to list of comments # post = Post.find(args[:post_id]) # comments = post.comments # new_comment = comments.build(body: args[:body]) # new_comment.save! # # range_add = GraphQL::Relay::RangeAdd.new( # parent: post, # collection: comments, # item: new_comment, # context: context, # ) # # response = { # post: post, # comments_connection: range_add.connection, # new_comment_edge: range_add.edge, # } class RangeAdd attr_reader :edge, :connection, :parent # @param collection [Object] The list of items to wrap in a connection # @param item [Object] The newly-added item (will be wrapped in `edge_class`) # @param context [GraphQL::Query::Context] The surrounding `ctx`, will be passed to the connection # @param parent [Object] The owner of `collection`, will be passed to the connection if provided # @param edge_class [Class] The class to wrap `item` with (defaults to the connection's edge class) def initialize(collection:, item:, context:, parent: nil, edge_class: nil) conn_class = context.schema.connections.wrapper_for(collection) # The rest will be added by ConnectionExtension @connection = conn_class.new(collection, parent: parent, context: context, edge_class: edge_class) # Check if this connection supports it, to support old versions of GraphQL-Pro @edge = if @connection.respond_to?(:range_add_edge) @connection.range_add_edge(item) else @connection.edge_class.new(item, @connection) end @parent = parent 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_trace.rb
lib/graphql/tracing/legacy_trace.rb
# frozen_string_literal: true require "graphql/tracing/trace" require "graphql/tracing/call_legacy_tracers" module GraphQL module Tracing class LegacyTrace < Trace include CallLegacyTracers 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_trace.rb
lib/graphql/tracing/scout_trace.rb
# frozen_string_literal: true require "graphql/tracing/monitor_trace" module GraphQL module Tracing # A tracer for sending GraphQL-Ruby times to Scout # # @example Adding this tracer to your schema # class MySchema < GraphQL::Schema # trace_with GraphQL::Tracing::ScoutTrace # end ScoutTrace = MonitorTrace.create_module("scout") module ScoutTrace class ScoutMonitor < MonitorTrace::Monitor def instrument(keyword, object) if keyword == :execute query = object.queries.first set_this_txn_name = 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(query)) end end ScoutApm::Tracer.instrument("GraphQL", name_for(keyword, object), INSTRUMENT_OPTS) do yield end end INSTRUMENT_OPTS = { scope: true } include MonitorTrace::Monitor::GraphQLSuffixNames class Event < MonitorTrace::Monitor::Event def start layer = ScoutApm::Layer.new("GraphQL", @monitor.name_for(keyword, object)) layer.subscopable! @scout_req = ScoutApm::RequestManager.lookup @scout_req.start_layer(layer) end def finish @scout_req.stop_layer 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/active_support_notifications_trace.rb
lib/graphql/tracing/active_support_notifications_trace.rb
# frozen_string_literal: true require "graphql/tracing/notifications_trace" module GraphQL module Tracing # This implementation forwards events to ActiveSupport::Notifications with a `graphql` suffix. # # @example Sending execution events to ActiveSupport::Notifications # class MySchema < GraphQL::Schema # trace_with(GraphQL::Tracing::ActiveSupportNotificationsTrace) # end # # @example Subscribing to GraphQL events with ActiveSupport::Notifications # ActiveSupport::Notifications.subscribe(/graphql/) do |event| # pp event.name # pp event.payload # end # module ActiveSupportNotificationsTrace include NotificationsTrace def initialize(engine: ActiveSupport::Notifications, **rest) 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/sentry_trace.rb
lib/graphql/tracing/sentry_trace.rb
# frozen_string_literal: true require "graphql/tracing/monitor_trace" module GraphQL module Tracing # A tracer for reporting GraphQL-Ruby times to Sentry. # # @example Installing the tracer # class MySchema < GraphQL::Schema # trace_with GraphQL::Tracing::SentryTrace # end # @see MonitorTrace Configuration Options in the parent module SentryTrace = MonitorTrace.create_module("sentry") module SentryTrace class SentryMonitor < MonitorTrace::Monitor def instrument(keyword, object) return yield unless Sentry.initialized? platform_key = name_for(keyword, object) Sentry.with_child_span(op: platform_key, start_timestamp: Sentry.utc_now.to_f) do |span| result = yield return result unless span span.finish if keyword == :execute queries = object.queries operation_names = queries.map{|q| operation_name(q) } span.set_description(operation_names.join(", ")) if queries.size == 1 query = queries.first set_this_txn_name = query.context[:set_sentry_transaction_name] if set_this_txn_name == true || (set_this_txn_name.nil? && @set_transaction_name) Sentry.configure_scope do |scope| scope.set_transaction_name(transaction_name(query)) end end span.set_data('graphql.document', query.query_string) if query.selected_operation_name span.set_data('graphql.operation.name', query.selected_operation_name) end if query.selected_operation span.set_data('graphql.operation.type', query.selected_operation.operation_type) end end end result end end include MonitorTrace::Monitor::GraphQLPrefixNames private def operation_name(query) selected_op = query.selected_operation if selected_op [selected_op.operation_type, selected_op.name].compact.join(' ') else 'GraphQL Operation' end end class Event < MonitorTrace::Monitor::Event def start if Sentry.initialized? && (@span = Sentry.get_current_scope.get_span) span_name = @monitor.name_for(@keyword, @object) @span.start_child(op: span_name) end end def finish @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/active_support_notifications_tracing.rb
lib/graphql/tracing/active_support_notifications_tracing.rb
# frozen_string_literal: true require "graphql/tracing/notifications_tracing" module GraphQL module Tracing # This implementation forwards events to ActiveSupport::Notifications # with a `graphql` suffix. # # @see KEYS for event names module ActiveSupportNotificationsTracing # A cache of frequently-used keys to avoid needless string allocations KEYS = NotificationsTracing::KEYS NOTIFICATIONS_ENGINE = NotificationsTracing.new(ActiveSupport::Notifications) if defined?(ActiveSupport::Notifications) def self.trace(key, metadata, &blk) NOTIFICATIONS_ENGINE.trace(key, metadata, &blk) end end end end
ruby
MIT
fa2ba4e489f8475b194f7c6985e0b25681a442c2
2026-01-04T15:43:02.089024Z
false