code
stringlengths
26
124k
docstring
stringlengths
23
125k
func_name
stringlengths
1
98
language
stringclasses
1 value
repo
stringlengths
5
53
path
stringlengths
7
151
url
stringlengths
50
211
license
stringclasses
7 values
def insert_interceptor_after(after_class, interceptor_class, opts = {}) raise ServerAlreadyStartedError if @started @interceptors.insert_after(after_class, interceptor_class, opts) end
# Insert an interceptor after another in the currently registered order of execution @param [Class] after_class The interceptor that you want to add the new interceptor after @param [Class] interceptor_class The Interceptor to add to the registry @param [Hash] opts A hash of options for the interceptor
insert_interceptor_after
ruby
bigcommerce/gruf
lib/gruf/server.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/server.rb
MIT
def remove_interceptor(klass) raise ServerAlreadyStartedError if @started @interceptors.remove(klass) end
# Remove an interceptor from the server @param [Class] klass
remove_interceptor
ruby
bigcommerce/gruf
lib/gruf/server.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/server.rb
MIT
def clear_interceptors raise ServerAlreadyStartedError if @started @interceptors.clear end
# Clear the interceptor registry of interceptors
clear_interceptors
ruby
bigcommerce/gruf
lib/gruf/server.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/server.rb
MIT
def ssl_credentials return :this_port_is_insecure unless options.fetch(:use_ssl, Gruf.use_ssl) private_key = File.read(options.fetch(:ssl_key_file, Gruf.ssl_key_file)) cert_chain = File.read(options.fetch(:ssl_crt_file, Gruf.ssl_crt_file)) certs = [nil, [{ private_key: private_key, cert_chain: cert_chain }], false] GRPC::Core::ServerCredentials.new(*certs) end
# Load the SSL/TLS credentials for this server @return [GRPC::Core::ServerCredentials|Symbol] :nocov:
ssl_credentials
ruby
bigcommerce/gruf
lib/gruf/server.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/server.rb
MIT
def update_proc_title(state) Process.setproctitle("gruf #{Gruf::VERSION} -- #{state}") end
:nocov: # Updates proc name/title @param [Symbol] state :nocov:
update_proc_title
ruby
bigcommerce/gruf
lib/gruf/server.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/server.rb
MIT
def server_mutex(&block) @server_mutex ||= begin require 'monitor' Monitor.new end @server_mutex.synchronize(&block) end
:nocov: # Handle thread-safe access to the server
server_mutex
ruby
bigcommerce/gruf
lib/gruf/server.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/server.rb
MIT
def initialize(service:, options: {}, client_options: {}) @unsynchronized_methods = options.delete(:unsynchronized_methods) { [] } @expiry = options.delete(:internal_cache_expiry) { Gruf.synchronized_client_internal_cache_expiry } @locks = Concurrent::Map.new @results = Concurrent::Map.new super end
# Initialize the client and setup the stub @param [Module] service The namespace of the client Stub that is desired to load @param [Hash] options A hash of options for the client @option options [Array] :unsynchronized_methods A list of methods (as symbols) that should be excluded from synchronization @option options [Integer] :internal_cache_expiry The length of time to keep results around for other threads to fetch (in seconds) @param [Hash] client_options A hash of options to pass to the gRPC client stub
initialize
ruby
bigcommerce/gruf
lib/gruf/synchronized_client.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/synchronized_client.rb
MIT
def call(request_method, params = {}, metadata = {}, opts = {}, &block) # Allow for bypassing extra behavior for selected methods return super if unsynchronized_methods.include?(request_method.to_sym) # Generate a unique key based on the method and params key = "#{request_method}.#{params.hash}" # Create a lock for this call if we haven't seen it already, then acquire it lock = @locks.compute_if_absent(key) { Mutex.new } lock.synchronize do # Return value from results cache if it exists. This occurs for callers that were # waiting on the lock while the first caller was making the actual grpc call. response = @results.get(lock) if response Gruf.logger.debug "Returning cached result for #{key}:#{lock.inspect}" next response end # Make the grpc call and record response for other callers that are blocked # on the same lock response = super @results.put(lock, response) # Schedule a task to come in later and clean out result to prevent memory bloat Concurrent::ScheduledTask.new(@expiry, args: [@results, lock]) { |h, k| h.delete(k) }.execute # Remove the lock from the map. The next caller to come through with the # same params will create a new lock and start the process over again. # Anyone who was waiting on this call will be using a local reference # to the same lock as us, and will fetch the result from the cache. @locks.delete(key) # Return response response end end
# Call the client's method with given params. If another call is already active for the same endpoint and the same params, block until the active call is complete. When unblocked, callers will get a copy of the original result. @param [String|Symbol] request_method The method that is being requested on the service @param [Hash] params (Optional) A hash of parameters that will be inserted into the gRPC request message that is required for the given above call @param [Hash] metadata (Optional) A hash of metadata key/values that are transported with the client request @param [Hash] opts (Optional) A hash of options to send to the gRPC request_response method @return [Gruf::Response] The response from the server @raise [Gruf::Client::Error|GRPC::BadStatus] If an error occurs, an exception will be raised according to the error type that was returned
call
ruby
bigcommerce/gruf
lib/gruf/synchronized_client.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/synchronized_client.rb
MIT
def initialize(result, time) @result = result @time = time.to_f end
# Initialize the result object @param [Object] result The result of the block that was called @param [Float] time The time, in ms, of the block execution
initialize
ruby
bigcommerce/gruf
lib/gruf/timer.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/timer.rb
MIT
def success? !result.is_a?(GRPC::BadStatus) && !result.is_a?(StandardError) && !result.is_a?(GRPC::Core::CallError) end
# Was this result a successful result? @return [Boolean] Whether or not this result was a success
success?
ruby
bigcommerce/gruf
lib/gruf/timer.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/timer.rb
MIT
def initialize( args = ARGV, server: nil, services: nil, hook_executor: nil, logger: nil ) @args = args setup! # ensure we set some defaults from CLI here so we can allow configuration @services = services.is_a?(Array) ? services : [] @hook_executor = hook_executor || Gruf::Hooks::Executor.new(hooks: Gruf.hooks&.prepare) @server = server || Gruf::Server.new(Gruf.server_options) @logger = logger || Gruf.logger || ::Logger.new($stderr) end
# @param [Hash|ARGV] @param [::Gruf::Server|NilClass] server @param [Array<Class>|NilClass] services @param [Gruf::Hooks::Executor|NilClass] hook_executor @param [Logger|NilClass] logger
initialize
ruby
bigcommerce/gruf
lib/gruf/cli/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/cli/executor.rb
MIT
def setup! @options = parse_options Gruf.server_binding_url = @options[:host] if @options[:host] if @options.suppress_default_interceptors? Gruf.interceptors.remove(Gruf::Interceptors::ActiveRecord::ConnectionReset) Gruf.interceptors.remove(Gruf::Interceptors::Instrumentation::OutputMetadataTimer) end Gruf.backtrace_on_error = true if @options.backtrace_on_error? Gruf.health_check_enabled = true if @options.health_check? end
# Setup options for CLI execution and configure Gruf based on inputs
setup!
ruby
bigcommerce/gruf
lib/gruf/cli/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/cli/executor.rb
MIT
def parse_options ::Slop.parse(@args) do |o| o.null '-h', '--help', 'Display help message' do puts o exit(0) end o.string '--host', 'Specify the binding url for the gRPC service' o.string '--services', 'Optional. Run gruf with only the passed gRPC service classes (comma-separated)' o.bool '--health-check', 'Serve the default gRPC health check (defaults to false). ' o.bool '--suppress-default-interceptors', 'Do not use the default interceptors' o.bool '--backtrace-on-error', 'Push backtraces on exceptions to the error serializer' o.null '-v', '--version', 'print gruf version' do puts Gruf::VERSION exit(0) end end end
# Parse all CLI arguments into an options result @return [Slop::Result]
parse_options
ruby
bigcommerce/gruf
lib/gruf/cli/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/cli/executor.rb
MIT
def register_services! # wait to load controllers until last possible second to allow late configuration ::Gruf.autoloaders.load!(controllers_path: Gruf.controllers_path) services = determine_services(@services) services = bind_health_check!(services) if health_check_enabled? services.map! { |s| s.is_a?(Class) ? s : s.constantize } if services.any? services.each { |s| @server.add_service(s) } return end raise NoServicesBoundError rescue NoServicesBoundError @logger.fatal 'FATAL ERROR: No services bound to this gruf process; please bind a service to a Gruf ' \ 'controller to start the server successfully' exit(1) rescue NameError => e @logger.fatal 'FATAL ERROR: Could not start server; passed services to run are not loaded or valid ' \ "constants: #{e.message}" exit(1) rescue StandardError => e @logger.fatal "FATAL ERROR: Could not start server: #{e.message}" exit(1) end
# Register services; note that this happens after gruf is initialized, and right before the server is run. This will interpret the services to run in the following precedence: 1. initializer arguments to the executor 2. ARGV options (the --services option) 3. services set to the global gruf configuration (Gruf.services)
register_services!
ruby
bigcommerce/gruf
lib/gruf/cli/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/cli/executor.rb
MIT
def bind_health_check!(services) # do this here to trigger autoloading the controller in zeitwerk, since we don't explicitly load this # controller. This binds the service and makes sure the method handlers are setup. require 'gruf/controllers/health_controller' # if we're already bound to the services array (say someone explicitly passes the health check in, skip) return services if services.include?(::Grpc::Health::V1::Health::Service) # otherwise, manually add the grpc service services << ::Grpc::Health::V1::Health::Service services end
# Load the health check if enabled into the services array @param [Array<Class>] services @return [Array<Class>]
bind_health_check!
ruby
bigcommerce/gruf
lib/gruf/cli/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/cli/executor.rb
MIT
def determine_services(services = []) # first check initializer arguments return services if services.any? # next check CLI arguments services = @options[:services].to_s.split(',').map(&:strip).uniq # finally, if none, use global gruf autoloaded services services = ::Gruf.services || [] unless services.any? services end
# Determine how we load services (initializer -> ARGV -> Gruf.services) @return [Array<Class>]
determine_services
ruby
bigcommerce/gruf
lib/gruf/cli/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/cli/executor.rb
MIT
def initialize(error) @error = error super end
# Initialize the client error @param [Object] error The deserialized error
initialize
ruby
bigcommerce/gruf
lib/gruf/client/error.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/client/error.rb
MIT
def initialize( default_class: nil, deserializer_class: nil, metadata_key: nil ) @default_class = default_class || Gruf::Client::Errors::Internal @metadata_key = (metadata_key || Gruf.error_metadata_key).to_s @deserializer_class = deserializer_class || default_serializer end
# @param [Class] default_class @param [Class] deserializer_class @param [String|Symbol] metadata_key
initialize
ruby
bigcommerce/gruf
lib/gruf/client/error_factory.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/client/error_factory.rb
MIT
def from_exception(exception) # passthrough on Signals, we don't want to mess with these return exception if exception.is_a?(SignalException) exception_class = determine_class(exception) if exception.is_a?(GRPC::BadStatus) # if it's a GRPC::BadStatus code, let's check for any trailing error metadata and decode it exception_class.new(deserialize(exception)) else # otherwise, let's just capture the error and build the wrapper class exception_class.new(exception) end end
# Determine the proper error class to raise given the incoming exception. This will attempt to coalesce the exception object into the appropriate Gruf::Client::Errors subclass, or fallback to the default class if none is found (or it is a StandardError or higher-level error). It will leave alone Signals instead of attempting to coalesce them. @param [Exception] exception @return [Gruf::Client::Errors::Base|SignalException]
from_exception
ruby
bigcommerce/gruf
lib/gruf/client/error_factory.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/client/error_factory.rb
MIT
def deserialize(exception) if exception.respond_to?(:metadata) key = exception.metadata.key?(@metadata_key.to_s) ? @metadata_key.to_s : @metadata_key.to_sym return @deserializer_class.new(exception.metadata[key]).deserialize if exception.metadata.key?(key) end exception end
# Deserialize any trailing metadata error payload from the exception @param [Gruf::Client::Errors::Base] @return [String]
deserialize
ruby
bigcommerce/gruf
lib/gruf/client/error_factory.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/client/error_factory.rb
MIT
def determine_class(exception) error_class = Gruf::Client::Errors.const_get(exception.class.name.demodulize) # Ruby module inheritance will have StandardError, ScriptError, etc still get to this point # So we need to explicitly check for ancestry here return @default_class unless error_class.ancestors.include?(Gruf::Client::Errors::Base) error_class rescue NameError => _e @default_class end
# @param [Exception] exception @return [Gruf::Client::Errors::Base]
determine_class
ruby
bigcommerce/gruf
lib/gruf/client/error_factory.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/client/error_factory.rb
MIT
def initialize(path:, reloading: nil, tag: nil) super() @path = path @loader = ::Zeitwerk::Loader.new @loader.tag = tag || 'gruf-controllers' @setup = false @reloading_enabled = reloading || ::Gruf.development? setup! end
# @param [String] path @param [Boolean] reloading @param [String] tag
initialize
ruby
bigcommerce/gruf
lib/gruf/controllers/autoloader.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/autoloader.rb
MIT
def reload return unless @reloading_enabled reload_lock.with_write_lock do @loader.reload end end
# Reload all files managed by the autoloader, if reloading is enabled
reload
ruby
bigcommerce/gruf
lib/gruf/controllers/autoloader.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/autoloader.rb
MIT
def reload_lock @reload_lock ||= Concurrent::ReadWriteLock.new end
# Handle thread-safe access to the loader
reload_lock
ruby
bigcommerce/gruf
lib/gruf/controllers/autoloader.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/autoloader.rb
MIT
def initialize(method_key:, service:, rpc_desc:, active_call:, message:) @request = Request.new( method_key: method_key, service: service, rpc_desc: rpc_desc, active_call: active_call, message: message ) @error = Gruf::Error.new @interceptors = Gruf.interceptors.prepare(@request, @error) end
# Initialize the controller within the given request context @param [Symbol] method_key The gRPC method that this controller relates to @param [GRPC::GenericService] service The gRPC service stub for this controller @param [GRPC::RpcDesc] rpc_desc The RPC descriptor for this service method @param [GRPC::ActiveCall] active_call The gRPC ActiveCall object @param [Google::Protobuf::MessageExts] message The incoming protobuf request message
initialize
ruby
bigcommerce/gruf
lib/gruf/controllers/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/base.rb
MIT
def process_action(method_key, &block) send(method_key, &block) end
# Call a method on this controller. Override this in a subclass to modify the behavior around processing a method @param [Symbol] method_key The name of the gRPC service method being called as a Symbol @param [block] &block The passed block for executing the method
process_action
ruby
bigcommerce/gruf
lib/gruf/controllers/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/base.rb
MIT
def call(method_key, &block) Interceptors::Context.new(@interceptors).intercept! do process_action(method_key, &block) end rescue GRPC::BadStatus raise # passthrough, to be caught by Gruf::Interceptors::Timer rescue GRPC::Core::CallError, StandardError => e # CallError is not a StandardError set_debug_info(e.message, e.backtrace) if Gruf.backtrace_on_error error_message = Gruf.use_exception_message ? e.message : Gruf.internal_error_message fail!(:internal, :unknown, error_message) end
# Call a method on this controller @param [Symbol] method_key The name of the gRPC service method being called as a Symbol @param [block] &block The passed block for executing the method
call
ruby
bigcommerce/gruf
lib/gruf/controllers/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/base.rb
MIT
def initialize(rpc_desc) @rpc_desc = rpc_desc end
# Initialize a new request type object @param [GRPC::RpcDesc] rpc_desc The RPC descriptor for the request type
initialize
ruby
bigcommerce/gruf
lib/gruf/controllers/request.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/request.rb
MIT
def initialize(method_key:, service:, rpc_desc:, active_call:, message:) @method_key = method_key @service = service @active_call = active_call @message = message @rpc_desc = rpc_desc @type = Type.new(rpc_desc) @context = ::ActiveSupport::HashWithIndifferentAccess.new end
# Initialize an inbound controller request object @param [Symbol] method_key The method symbol of the RPC method being executed @param [Class] service The class of the service being executed against @param [GRPC::RpcDesc] rpc_desc The RPC descriptor of the call @param [GRPC::ActiveCall] active_call The restricted view of the call @param [Object|Google::Protobuf::MessageExts] message The protobuf message (or messages) of the request
initialize
ruby
bigcommerce/gruf
lib/gruf/controllers/request.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/request.rb
MIT
def service_key @service.name.to_s.underscore.tr('/', '.').gsub('.service', '') end
# Returns the service name as a translated name separated by periods. Strips the superfluous "Service" suffix from the name @return [String] The mapped service key
service_key
ruby
bigcommerce/gruf
lib/gruf/controllers/request.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/request.rb
MIT
def messages if client_streamer? # rubocop:disable Style/ExplicitBlockArgument @message.call { |msg| yield msg } # rubocop:enable Style/ExplicitBlockArgument elsif bidi_streamer? @message else [@message] end end
# Return all messages for this request, properly handling different request types @return [Enumerable<Object>] All messages for this request @return [Object] If a bidi streamed request, will return the message object
messages
ruby
bigcommerce/gruf
lib/gruf/controllers/request.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/request.rb
MIT
def bind!(service:, controller:) rpc_methods = service.rpc_descs.map { |rd| BoundDesc.new(rd) } rpc_methods.each { |name, desc| bind_method(service, controller, name, desc) } end
# Bind all methods on the service to the passed controller @param [Class<Gruf::Controllers::Base>] controller
bind!
ruby
bigcommerce/gruf
lib/gruf/controllers/service_binder.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/service_binder.rb
MIT
def bind_method(service_ref, controller, method_name, desc) method_key = method_name.to_s.underscore.to_sym controller_name = controller.name service_ref.class_eval do if desc.request_response? define_method(method_key) do |message, active_call| Gruf::Autoloaders.controllers.with_fresh_controller(controller_name) do |fresh_controller| c = fresh_controller.new( method_key: method_key, service: service_ref, message: message, active_call: active_call, rpc_desc: desc ) c.call(method_key) end end elsif desc.client_streamer? define_method(method_key) do |active_call| Gruf::Autoloaders.controllers.with_fresh_controller(controller_name) do |fresh_controller| c = fresh_controller.new( method_key: method_key, service: service_ref, message: proc { |&block| active_call.each_remote_read(&block) }, active_call: active_call, rpc_desc: desc ) c.call(method_key) end end elsif desc.server_streamer? define_method(method_key) do |message, active_call, &block| Gruf::Autoloaders.controllers.with_fresh_controller(controller_name) do |fresh_controller| c = fresh_controller.new( method_key: method_key, service: service_ref, message: message, active_call: active_call, rpc_desc: desc ) c.call(method_key, &block) end end else # bidi define_method(method_key) do |messages, active_call, &block| Gruf::Autoloaders.controllers.with_fresh_controller(controller_name) do |fresh_controller| c = fresh_controller.new( method_key: method_key, service: service_ref, message: messages, active_call: active_call, rpc_desc: desc ) c.call(method_key, &block) end end end end end
# Bind the grpc methods to the service, allowing for server interception and execution control @param [Gruf::Controllers::Base] controller @param [Symbol] method_name @param [BoundDesc] desc
bind_method
ruby
bigcommerce/gruf
lib/gruf/controllers/service_binder.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/controllers/service_binder.rb
MIT
def initialize(detail, stack_trace = []) @detail = detail @stack_trace = (stack_trace.is_a?(String) ? stack_trace.split("\n") : stack_trace) # Limit the size of the stack trace to reduce risk of overflowing metadata stack_trace_limit = Gruf.backtrace_limit.to_i stack_trace_limit = 10 if stack_trace_limit.negative? @stack_trace = @stack_trace[0..stack_trace_limit] if stack_trace_limit.positive? end
# @param [String] detail The detail message of the exception @param [Array<String>] stack_trace The stack trace generated by the exception as an array of strings
initialize
ruby
bigcommerce/gruf
lib/gruf/errors/debug_info.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/errors/debug_info.rb
MIT
def to_h { detail: detail, stack_trace: stack_trace } end
# Return this object marshalled into a hash @return [Hash] The debug info represented as a hash
to_h
ruby
bigcommerce/gruf
lib/gruf/errors/debug_info.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/errors/debug_info.rb
MIT
def initialize(field_name, error_code, message = '') @field_name = field_name @error_code = error_code @message = message end
# @param [Symbol] field_name The name of the field as a Symbol @param [Symbol] error_code The application error code for the field, e.g. :job_not_found @param [String] message (Optional) The error message for the field, e.g. "Job with ID 123 not found"
initialize
ruby
bigcommerce/gruf
lib/gruf/errors/field.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/errors/field.rb
MIT
def to_h { field_name: field_name, error_code: error_code, message: message } end
# Return the field error represented as a hash @return [Hash] The error represented as a hash
to_h
ruby
bigcommerce/gruf
lib/gruf/errors/field.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/errors/field.rb
MIT
def fail!(error_code, app_code = nil, message = '', metadata = {}) e = error e.code = error_code.to_sym e.app_code = app_code ? app_code.to_sym : e.code e.message = message.to_s e.metadata = metadata e.fail!(request.active_call) end
# Will issue a GRPC BadStatus exception, with a code based on the code passed. @param [Symbol] error_code The network error code that maps to gRPC status codes @param [Symbol] app_code The application-specific code for the error @param [String] message (Optional) A detail message about the error @param [Hash] metadata (Optional) Any metadata to inject into the trailing metadata for the response
fail!
ruby
bigcommerce/gruf
lib/gruf/errors/helpers.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/errors/helpers.rb
MIT
def call(name, arguments = {}) name = name.to_sym @hooks.each do |hook| next unless hook.respond_to?(name) hook.send(name, **arguments) end end
# Execute a hook point for each registered hook in the registry @param [Symbol] name @param [Hash] arguments
call
ruby
bigcommerce/gruf
lib/gruf/hooks/executor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/executor.rb
MIT
def use(hook_class, options = {}) hooks_mutex do @registry << { klass: hook_class, options: options } end end
# Add a hook to the registry @param [Class] hook_class The class of the hook to add @param [Hash] options A hash of options to pass into the hook during initialization
use
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def remove(hook_class) pos = @registry.find_index { |opts| opts.fetch(:klass, '') == hook_class } raise HookNotFoundError if pos.nil? @registry.delete_at(pos) end
# Remove a hook from the registry @param [Class] hook_class The hook class to remove @raise [HookNotFoundError] if the hook is not found
remove
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def insert_before(before_class, hook_class, options = {}) hooks_mutex do pos = @registry.find_index { |opts| opts.fetch(:klass, '') == before_class } raise HookNotFoundError if pos.nil? @registry.insert( pos, klass: hook_class, options: options ) end end
# Insert a hook before another specified hook @param [Class] before_class The hook to insert before @param [Class] hook_class The class of the hook to add @param [Hash] options A hash of options to pass into the hook during initialization @raise [HookNotFoundError] if the before hook is not found
insert_before
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def insert_after(after_class, hook_class, options = {}) hooks_mutex do pos = @registry.find_index { |opts| opts.fetch(:klass, '') == after_class } raise HookNotFoundError if pos.nil? @registry.insert( (pos + 1), klass: hook_class, options: options ) end end
# Insert a hook after another specified hook @param [Class] after_class The hook to insert after @param [Class] hook_class The class of the hook to add @param [Hash] options A hash of options to pass into the hook during initialization @raise [HookNotFoundError] if the after hook is not found
insert_after
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def list hooks_mutex do @registry.map { |h| h[:klass] } end end
# Return a list of the hook classes in the registry in their execution order @return [Array<Class>]
list
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def prepare is = [] hooks_mutex do @registry.each do |o| is << o[:klass].new(options: o[:options]) end end is end
# Lazily load and return all hooks for the given request @return [Array<Gruf::Hooks::Base>]
prepare
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def count hooks_mutex do @registry ||= [] @registry.count end end
# @return [Integer] The number of hooks currently loaded
count
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def hooks_mutex(&block) @hooks_mutex ||= begin require 'monitor' Monitor.new end @hooks_mutex.synchronize(&block) end
# Handle mutations to the hook registry in a thread-safe manner
hooks_mutex
ruby
bigcommerce/gruf
lib/gruf/hooks/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/hooks/registry.rb
MIT
def initialize(request, error, options = {}) @request = request @error = error @options = options || {} end
# @param [Gruf::Controllers::Request] request @param [Gruf::Error] error @param [Hash] options
initialize
ruby
bigcommerce/gruf
lib/gruf/interceptors/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/base.rb
MIT
def call(request_context:) logger.debug "Logging client interceptor for request: #{request_context.method}" yield end
# Handles interception of outbound calls. Implement this in your derivative interceptor implementation. @param [Gruf::Outbound::RequestContext] request_context The context of the outbound request @return [Object] This method must return the response from the yielded block
call
ruby
bigcommerce/gruf
lib/gruf/interceptors/client_interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/client_interceptor.rb
MIT
def request_response(request: nil, call: nil, method: nil, metadata: nil, &block) rc = Gruf::Outbound::RequestContext.new( type: :request_response, requests: [request], call: call, method: method, metadata: metadata ) call(request_context: rc, &block) end
# Call the interceptor from the request_response call @param [Object] request The request being sent @param [GRPC::ActiveCall] call The GRPC ActiveCall object @param [Method] method The method being called @param [Hash] metadata A hash of outgoing metadata @return [Object] The response message
request_response
ruby
bigcommerce/gruf
lib/gruf/interceptors/client_interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/client_interceptor.rb
MIT
def client_streamer(requests: nil, call: nil, method: nil, metadata: nil, &block) rc = Gruf::Outbound::RequestContext.new( type: :client_streamer, requests: requests, call: call, method: method, metadata: metadata ) call(request_context: rc, &block) end
# Call the interceptor from the client_streamer call @param [Enumerable] requests An enumerable of requests being sent @param [GRPC::ActiveCall] call The GRPC ActiveCall object @param [Method] method The method being called @param [Hash] metadata A hash of outgoing metadata @return [Object] The response message
client_streamer
ruby
bigcommerce/gruf
lib/gruf/interceptors/client_interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/client_interceptor.rb
MIT
def server_streamer(request: nil, call: nil, method: nil, metadata: nil, &block) rc = Gruf::Outbound::RequestContext.new( type: :server_streamer, requests: [request], call: call, method: method, metadata: metadata ) call(request_context: rc, &block) end
# Call the interceptor from the server_streamer call @param [Object] request The request being sent @param [GRPC::ActiveCall] call The GRPC ActiveCall object @param [Method] method The method being called @param [Hash] metadata A hash of outgoing metadata @return [Object] The response message
server_streamer
ruby
bigcommerce/gruf
lib/gruf/interceptors/client_interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/client_interceptor.rb
MIT
def bidi_streamer(requests: nil, call: nil, method: nil, metadata: nil, &block) rc = Gruf::Outbound::RequestContext.new( type: :bidi_streamer, requests: requests, call: call, method: method, metadata: metadata ) call(request_context: rc, &block) end
# Call the interceptor from the bidi_streamer call @param [Enumerable] requests An enumerable of requests being sent @param [GRPC::ActiveCall] call The GRPC ActiveCall object @param [Method] method The method being called @param [Hash] metadata A hash of outgoing metadata
bidi_streamer
ruby
bigcommerce/gruf
lib/gruf/interceptors/client_interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/client_interceptor.rb
MIT
def initialize(interceptors = nil) @interceptors = interceptors || [] end
# Initialize the interception context @param [Array<Gruf::Interceptors::ServerInterceptor>] interceptors
initialize
ruby
bigcommerce/gruf
lib/gruf/interceptors/context.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/context.rb
MIT
def intercept!(&block) return yield if @interceptors.none? i = @interceptors.shift return yield unless i logger.debug "Intercepting request with interceptor: #{i.class}" i.call do if @interceptors.any? intercept!(&block) else yield end end end
# Intercept the given request and run interceptors in a FIFO execution order
intercept!
ruby
bigcommerce/gruf
lib/gruf/interceptors/context.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/context.rb
MIT
def use(interceptor_class, options = {}) interceptors_mutex do @registry << { klass: interceptor_class, options: options } end end
# Add an interceptor to the registry @param [Class] interceptor_class The class of the interceptor to add @param [Hash] options A hash of options to pass into the interceptor during initialization
use
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def remove(interceptor_class) pos = @registry.find_index { |opts| opts.fetch(:klass, '') == interceptor_class } raise InterceptorNotFoundError if pos.nil? @registry.delete_at(pos) end
# Remove an interceptor from the registry @param [Class] interceptor_class The interceptor class to remove @raise [InterceptorNotFoundError] if the interceptor is not found
remove
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def insert_before(before_class, interceptor_class, options = {}) interceptors_mutex do pos = @registry.find_index { |opts| opts.fetch(:klass, '') == before_class } raise InterceptorNotFoundError if pos.nil? @registry.insert( pos, klass: interceptor_class, options: options ) end end
# Insert an interceptor before another specified interceptor @param [Class] before_class The interceptor to insert before @param [Class] interceptor_class The class of the interceptor to add @param [Hash] options A hash of options to pass into the interceptor during initialization @raise [InterceptorNotFoundError] if the before interceptor is not found
insert_before
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def insert_after(after_class, interceptor_class, options = {}) interceptors_mutex do pos = @registry.find_index { |opts| opts.fetch(:klass, '') == after_class } raise InterceptorNotFoundError if pos.nil? @registry.insert( (pos + 1), klass: interceptor_class, options: options ) end end
# Insert an interceptor after another specified interceptor @param [Class] after_class The interceptor to insert after @param [Class] interceptor_class The class of the interceptor to add @param [Hash] options A hash of options to pass into the interceptor during initialization @raise [InterceptorNotFoundError] if the after interceptor is not found
insert_after
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def list interceptors_mutex do @registry.map { |h| h[:klass] } end end
# Return a list of the interceptor classes in the registry in their execution order @return [Array<Class>]
list
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def prepare(request, error) is = [] interceptors_mutex do @registry.each do |o| is << o[:klass].new(request, error, o[:options]) end end is end
# Load and return all interceptors for the given request @param [Gruf::Controllers::Request] request @param [Gruf::Error] error @return [Array<Gruf::Interceptors::Base>]
prepare
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def count interceptors_mutex do @registry ||= [] @registry.count end end
# @return [Integer] The number of interceptors currently loaded
count
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def interceptors_mutex(&block) @interceptors_mutex ||= begin require 'monitor' Monitor.new end @interceptors_mutex.synchronize(&block) end
# Handle mutations to the interceptor registry in a thread-safe manner
interceptors_mutex
ruby
bigcommerce/gruf
lib/gruf/interceptors/registry.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/registry.rb
MIT
def initialize(message, elapsed, successful) @message = message @elapsed = elapsed.to_f @successful = successful ? true : false end
# @param [Object] message The protobuf message @param [Float] elapsed The elapsed time of the request @param [Boolean] successful If the request was successful
initialize
ruby
bigcommerce/gruf
lib/gruf/interceptors/timer.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/timer.rb
MIT
def call yield ensure target_classes.each { |klass| klass.connection_handler.clear_active_connections! } if enabled? end
# Reset any ActiveRecord connections after a gRPC service is called. Because of the way gRPC manages its connection pool, we need to ensure that this is done properly
call
ruby
bigcommerce/gruf
lib/gruf/interceptors/active_record/connection_reset.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/active_record/connection_reset.rb
MIT
def target_classes options[:target_classes] || [::ActiveRecord::Base] end
# @return [Array<Class>] The list of ActiveRecord classes to reset
target_classes
ruby
bigcommerce/gruf
lib/gruf/interceptors/active_record/connection_reset.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/active_record/connection_reset.rb
MIT
def bypass? options.fetch(:excluded_methods, []).include?(request.method_name) end
# @return [Boolean] If this method is in the excluded list, bypass
bypass?
ruby
bigcommerce/gruf
lib/gruf/interceptors/authentication/basic.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/authentication/basic.rb
MIT
def valid? server_credentials.any? do |cred| username = cred.fetch(:username, '').to_s password = cred.fetch(:password, '').to_s if username.empty? request_password == password else request_credentials == "#{username}:#{password}" end end end
# @return [Boolean] True if the basic authentication was valid
valid?
ruby
bigcommerce/gruf
lib/gruf/interceptors/authentication/basic.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/authentication/basic.rb
MIT
def server_credentials options.fetch(:credentials, []) end
# @return [Array<Hash>] An array of valid server credentials for this service
server_credentials
ruby
bigcommerce/gruf
lib/gruf/interceptors/authentication/basic.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/authentication/basic.rb
MIT
def request_credentials credentials = if request.active_call.respond_to?(:metadata) request.active_call.metadata['authorization'].to_s else '' end Base64.decode64(credentials.to_s.gsub('Basic ', '').strip) end
# @return [String] The decoded request credentials
request_credentials
ruby
bigcommerce/gruf
lib/gruf/interceptors/authentication/basic.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/authentication/basic.rb
MIT
def request_password @request_password ||= request_credentials.split(':').last end
# @return [String] The decoded request password
request_password
ruby
bigcommerce/gruf
lib/gruf/interceptors/authentication/basic.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/authentication/basic.rb
MIT
def call(&block) return unless active_call.respond_to?(:output_metadata) result = Gruf::Interceptors::Timer.time(&block) output_metadata.update(metadata_key => result.elapsed.to_s) raise result.message unless result.successful? result.message end
# Handle the instrumented response. Note: this will only instrument timings of _successful_ responses.
call
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/output_metadata_timer.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/output_metadata_timer.rb
MIT
def metadata_key options.fetch(:metadata_key, :timer).to_sym end
# @return [Symbol] The metadata key that the time result should be set to
metadata_key
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/output_metadata_timer.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/output_metadata_timer.rb
MIT
def call(&block) unless client Gruf.logger.error 'Statsd module loaded, but no client configured!' return yield end client.increment(route_key) result = Gruf::Interceptors::Timer.time(&block) client.increment("#{route_key}.#{postfix(result.successful?)}") client.timing(route_key, result.elapsed) raise result.message unless result.successful? result.message end
# Push data to StatsD, only doing so if a client is set
call
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/statsd.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/statsd.rb
MIT
def postfix(successful) successful ? 'success' : 'failure' end
# @param [Boolean] successful Whether or not the request was successful @return [String] The appropriate postfix for the key dependent on response status
postfix
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/statsd.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/statsd.rb
MIT
def key_prefix prefix = options.fetch(:prefix, '').to_s prefix.empty? ? '' : "#{prefix}." end
# @return [String] Return the sanitized key prefix for the statsd metric key
key_prefix
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/statsd.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/statsd.rb
MIT
def client @client ||= options.fetch(:client, nil) end
# @return [::Statsd] Return the given StatsD client
client
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/statsd.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/statsd.rb
MIT
def call(&block) return yield if options.fetch(:ignore_methods, [])&.include?(request.method_name) result = Gruf::Interceptors::Timer.time(&block) # Fetch log level options and merge with default... log_level_map = LOG_LEVEL_MAP.merge(options.fetch(:log_levels, {})) # A result is either successful, or, some level of feedback handled in the else block... if result.successful? type = log_level_map['GRPC::Ok'] || :debug status_name = 'GRPC::Ok' else type = log_level_map[result.message_class_name] || :error status_name = result.message_class_name end payload = {} if !request.client_streamer? && !request.bidi_streamer? payload[:params] = sanitize(request.message.to_h) if options.fetch(:log_parameters, false) payload[:message] = message(request, result) payload[:status] = status(result.message, result.successful?) else payload[:params] = {} payload[:message] = '' payload[:status] = GRPC::Core::StatusCodes::OK end payload[:service] = request.service_key payload[:method] = request.method_key payload[:action] = request.method_key payload[:grpc_status] = status_name payload[:duration] = result.elapsed_rounded payload[:thread_id] = Thread.current.object_id payload[:time] = Time.now.to_s payload[:host] = Socket.gethostname logger.send(type, formatter.format(payload, request: request, result: result)) raise result.message unless result.successful? result.message end
## Log the request, sending it to the appropriate formatter @return [String]
call
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def message(request, result) return "[GRPC::Ok] (#{request.method_name})" if result.successful? "[#{result.message_class_name}] (#{request.method_name}) #{result.message.message}" end
# Return an appropriate log message dependent on the status @param [Gruf::Controllers::Request] request @param [Gruf::Interceptors::Timer::Result] result @return [String] The appropriate message body
message
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def status(response, successful) successful ? GRPC::Core::StatusCodes::OK : response.code end
# Return the proper status code for the response @param [Object] response The response object @param [Boolean] successful If the response was successful @return [Boolean] The proper status code
status
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def formatter unless @formatter fmt = options.fetch(:formatter, :plain) @formatter = case fmt when Symbol prefix = 'Gruf::Interceptors::Instrumentation::RequestLogging::Formatters::' klass = "#{prefix}#{fmt.to_s.capitalize}" fmt = klass.constantize.new when Class fmt = fmt.new else fmt end raise InvalidFormatterError unless fmt.is_a?(Formatters::Base) end @formatter end
# Determine the appropriate formatter for the request logging @return [Gruf::Instrumentation::RequestLogging::Formatters::Base]
formatter
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def sanitize(params = {}) blocklists = (options.fetch(:blocklist, []) || []).map(&:to_s) redacted_string = options.fetch(:redacted_string, nil) || 'REDACTED' blocklists.each do |blocklist| parts = blocklist.split('.').map(&:to_sym) redact!(parts, 0, params, redacted_string) end params end
# Redact any blocklisted params and return an updated hash @param [Hash] params The hash of parameters to sanitize @return [Hash] The sanitized params in hash form
sanitize
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def redact!(parts = [], idx = 0, params = {}, redacted_string = 'REDACTED') return unless parts.is_a?(Array) && params.is_a?(Hash) return if idx >= parts.size || !params.key?(parts[idx]) if idx == parts.size - 1 if params[parts[idx]].is_a? Hash hash_deep_redact!(params[parts[idx]], redacted_string) else params[parts[idx]] = redacted_string end return end redact!(parts, idx + 1, params[parts[idx]], redacted_string) end
# Helper method to recursively redact based on the blocklist @param [Array] parts The blocklist. ex. 'data.schema' -> [:data, :schema] @param [Integer] idx The current index of the blocklist @param [Hash] params The hash of parameters to sanitize @param [String] redacted_string The custom redact string
redact!
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def hash_deep_redact!(hash, redacted_string) hash.each_key do |key| if hash[key].is_a? Hash hash_deep_redact!(hash[key], redacted_string) else hash[key] = redacted_string end end end
# Helper method to recursively redact the value of all hash keys @param [Hash] hash Part of the hash of parameters to sanitize @param [String] redacted_string The custom redact string
hash_deep_redact!
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/interceptor.rb
MIT
def format(_payload, request:, result:) raise NotImplementedError end
# Format the parameters into a loggable string. Must be implemented in every derivative class @param [Hash] _payload The incoming request payload @param [Gruf::Controllers::Request] request The current controller request @param [Gruf::Interceptors::Timer::Result] result The timed result of the response @return [String] The formatted string
format
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/formatters/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/formatters/base.rb
MIT
def format(payload, request:, result:) payload.merge(format: 'json').to_json end
# Format the request into a JSON-friendly payload @param [Hash] payload The incoming request payload @param [Gruf::Controllers::Request] request The current controller request @param [Gruf::Interceptors::Timer::Result] result The timed result of the response @return [String] The JSON representation of the payload
format
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/formatters/logstash.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/formatters/logstash.rb
MIT
def format(payload, request:, result:) time = payload.fetch(:duration, 0) grpc_status = payload.fetch(:grpc_status, 'GRPC::Ok') route_key = payload.fetch(:method, 'unknown') body = payload.fetch(:message, '') msg = "[#{grpc_status}] (#{route_key}) [#{time}ms] #{body}".strip msg += " Parameters: #{payload[:params].to_h}" if payload.key?(:params) msg.strip end
# Format the request by only outputting the message body and params (if set to log params) @param [Hash] payload The incoming request payload @param [Gruf::Controllers::Request] request The current controller request @param [Gruf::Interceptors::Timer::Result] result The timed result of the response @return [String] The formatted string
format
ruby
bigcommerce/gruf
lib/gruf/interceptors/instrumentation/request_logging/formatters/plain.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/interceptors/instrumentation/request_logging/formatters/plain.rb
MIT
def initialize(type:, requests:, call:, method:, metadata:) @type = type @requests = requests @call = call @method = method @metadata = metadata end
# Initialize the new request context @param [Symbol] type The type of request @param [Enumerable] requests An enumerable of requests being sent @param [GRPC::ActiveCall] call The GRPC ActiveCall object @param [Method] method The method being called @param [Hash] metadata A hash of outgoing metadata
initialize
ruby
bigcommerce/gruf
lib/gruf/outbound/request_context.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/outbound/request_context.rb
MIT
def route_key @method[1..].to_s.underscore.tr('/', '.') end
# Return the proper routing key for the request @return [String]
route_key
ruby
bigcommerce/gruf
lib/gruf/outbound/request_context.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/outbound/request_context.rb
MIT
def initialize(err) @error = err end
# @param [Gruf::Error|String] err The error to serialize
initialize
ruby
bigcommerce/gruf
lib/gruf/serializers/errors/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/serializers/errors/base.rb
MIT
def serialize raise NotImplementedError end
# Must be implemented in a derived class. This method should serialize the error into a transportable String that can be pushed into GRPC metadata across the wire. @return [String] The serialized error
serialize
ruby
bigcommerce/gruf
lib/gruf/serializers/errors/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/serializers/errors/base.rb
MIT
def deserialize raise NotImplementedError end
# Must be implemented in a derived class. This method should deserialize the error object that is transported over the gRPC trailing metadata payload. @return [Object|Hash] The deserialized error object
deserialize
ruby
bigcommerce/gruf
lib/gruf/serializers/errors/base.rb
https://github.com/bigcommerce/gruf/blob/master/lib/gruf/serializers/errors/base.rb
MIT
def build_operation(options = {}) double(:operation, { execute: true, metadata: {}, trailing_metadata: {}, deadline: Time.now.to_i + 600, cancelled?: false, execution_time: rand(1_000..10_000) }.merge(options)) end
# Build a gRPC operation stub for testing
build_operation
ruby
bigcommerce/gruf
spec/support/helpers.rb
https://github.com/bigcommerce/gruf/blob/master/spec/support/helpers.rb
MIT
def run_server(server) grpc_server = nil grpc_server = server.server t = Thread.new { grpc_server.run_till_terminated_or_interrupted(%w[INT TERM QUIT]) } grpc_server.wait_till_running timeout = ::ENV.fetch('GRUF_RSPEC_SERVER_TIMEOUT_SEC', 2) poll_period = ::ENV.fetch('GRPC_RSPEC_SERVER_POLL_PERIOD_SEC', 0.01).to_f begin yield ensure grpc_server.stop current_execution = 0.0 until grpc_server.stopped? break if timeout.to_f > current_execution sleep(poll_period) current_execution += poll_period end t.join t.kill end rescue StandardError, RuntimeError, Exception => e grpc_server&.stop t&.join t&.kill nil ensure grpc_server&.stop t&.join t&.kill nil end
# Runs a server @param [Gruf::Server] server
run_server
ruby
bigcommerce/gruf
spec/support/helpers.rb
https://github.com/bigcommerce/gruf/blob/master/spec/support/helpers.rb
MIT
def method_missing(method, *, &) h.public_send(method, *, &) rescue NoMethodError super end
To avoid having to address the view context explicitly we try to delegate to it
method_missing
ruby
hschne/rails-mini-profiler
app/presenters/rails_mini_profiler/base_presenter.rb
https://github.com/hschne/rails-mini-profiler/blob/master/app/presenters/rails_mini_profiler/base_presenter.rb
MIT
def configuration @configuration ||= Configuration.new end
Create a new configuration object @return [Configuration] a new configuration
configuration
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler.rb
MIT
def logger @logger ||= configuration.logger end
Access the current logger @return [Logger] the logger instance
logger
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler.rb
MIT
def authorize!(current_user) RailsMiniProfiler::User.current_user = current_user end
Authorize the current user for this request @param current_user [Object] the current user @see User#current_user
authorize!
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler.rb
MIT
def initialize(request_context, configuration: RailsMiniProfiler.configuration) @configuration = configuration @profiled_request = request_context.profiled_request @original_response = request_context.response end
@param request_context [RequestContext] The current request context @param configuration [Configuration] The current configuration
initialize
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT
def render return @original_response unless render_badge? modified_response = ResponseWrapper.new([], @original_response.status, @original_response.headers) modified_response.write(modified_body) modified_response.finish @original_response.close if @original_response.respond_to?(:close) modified_response end
Inject the badge into the response @return [ResponseWrapper] The modified response
render
ruby
hschne/rails-mini-profiler
lib/rails_mini_profiler/badge.rb
https://github.com/hschne/rails-mini-profiler/blob/master/lib/rails_mini_profiler/badge.rb
MIT