repo
stringlengths
5
58
path
stringlengths
9
168
func_name
stringlengths
9
130
original_string
stringlengths
66
10.5k
language
stringclasses
1 value
code
stringlengths
66
10.5k
code_tokens
list
docstring
stringlengths
8
16k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
94
266
partition
stringclasses
1 value
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.long_poll
def long_poll(routing_keys, ack, &handler) raise ArgumentError, "Block missing" unless block_given? params = { :wait_time => @options[:listen_timeout] - 5, :timestamp => Time.now.to_f } params[:routing_keys] = routing_keys if routing_keys params[:ack] = ack if ack && ack.any? options = { :request_timeout => @connect_interval, :poll_timeout => @options[:listen_timeout] } event_uuids = [] events = make_request(:poll, "/listen", params, "listen", options) if events events.each do |event| event = SerializationHelper.symbolize_keys(event) Log.info("Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}") @stats["events"].update("#{event[:type]} #{event[:path]}") event_uuids << event[:uuid] handler.call(event) end end event_uuids if event_uuids.any? end
ruby
def long_poll(routing_keys, ack, &handler) raise ArgumentError, "Block missing" unless block_given? params = { :wait_time => @options[:listen_timeout] - 5, :timestamp => Time.now.to_f } params[:routing_keys] = routing_keys if routing_keys params[:ack] = ack if ack && ack.any? options = { :request_timeout => @connect_interval, :poll_timeout => @options[:listen_timeout] } event_uuids = [] events = make_request(:poll, "/listen", params, "listen", options) if events events.each do |event| event = SerializationHelper.symbolize_keys(event) Log.info("Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}") @stats["events"].update("#{event[:type]} #{event[:path]}") event_uuids << event[:uuid] handler.call(event) end end event_uuids if event_uuids.any? end
[ "def", "long_poll", "(", "routing_keys", ",", "ack", ",", "&", "handler", ")", "raise", "ArgumentError", ",", "\"Block missing\"", "unless", "block_given?", "params", "=", "{", ":wait_time", "=>", "@options", "[", ":listen_timeout", "]", "-", "5", ",", ":timestamp", "=>", "Time", ".", "now", ".", "to_f", "}", "params", "[", ":routing_keys", "]", "=", "routing_keys", "if", "routing_keys", "params", "[", ":ack", "]", "=", "ack", "if", "ack", "&&", "ack", ".", "any?", "options", "=", "{", ":request_timeout", "=>", "@connect_interval", ",", ":poll_timeout", "=>", "@options", "[", ":listen_timeout", "]", "}", "event_uuids", "=", "[", "]", "events", "=", "make_request", "(", ":poll", ",", "\"/listen\"", ",", "params", ",", "\"listen\"", ",", "options", ")", "if", "events", "events", ".", "each", "do", "|", "event", "|", "event", "=", "SerializationHelper", ".", "symbolize_keys", "(", "event", ")", "Log", ".", "info", "(", "\"Received EVENT <#{event[:uuid]}> #{event[:type]} #{event[:path]} from #{event[:from]}\"", ")", "@stats", "[", "\"events\"", "]", ".", "update", "(", "\"#{event[:type]} #{event[:path]}\"", ")", "event_uuids", "<<", "event", "[", ":uuid", "]", "handler", ".", "call", "(", "event", ")", "end", "end", "event_uuids", "if", "event_uuids", ".", "any?", "end" ]
Make long-polling request to receive one or more events Do not return until an event is received or the polling times out or fails @param [Array, NilClass] routing_keys as strings to assist router in delivering event to interested parties @param [Array, NilClass] ack UUIDs for events received on previous poll @yield [event] required block called for each event received @yieldparam [Object] event received @return [Array, NilClass] UUIDs of events received, or nil if none @raise [ArgumentError] block missing
[ "Make", "long", "-", "polling", "request", "to", "receive", "one", "or", "more", "events", "Do", "not", "return", "until", "an", "event", "is", "received", "or", "the", "polling", "times", "out", "or", "fails" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L584-L609
train
rightscale/right_agent
lib/right_agent/clients/router_client.rb
RightScale.RouterClient.process_long_poll
def process_long_poll(result) case result when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError # Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff @connect_interval = CONNECT_INTERVAL update_listen_state(:choose, backoff_reconnect_interval) result = nil when Exception ErrorTracker.track(self, result) update_listen_state(:choose, backoff_reconnect_interval) result = nil else @reconnect_interval = RECONNECT_INTERVAL @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks update_listen_state(:choose) end result end
ruby
def process_long_poll(result) case result when Exceptions::Unauthorized, Exceptions::ConnectivityFailure, Exceptions::RetryableError, Exceptions::InternalServerError # Reset connect_interval otherwise long-poll and WebSocket connect attempts will continue to backoff @connect_interval = CONNECT_INTERVAL update_listen_state(:choose, backoff_reconnect_interval) result = nil when Exception ErrorTracker.track(self, result) update_listen_state(:choose, backoff_reconnect_interval) result = nil else @reconnect_interval = RECONNECT_INTERVAL @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks update_listen_state(:choose) end result end
[ "def", "process_long_poll", "(", "result", ")", "case", "result", "when", "Exceptions", "::", "Unauthorized", ",", "Exceptions", "::", "ConnectivityFailure", ",", "Exceptions", "::", "RetryableError", ",", "Exceptions", "::", "InternalServerError", "@connect_interval", "=", "CONNECT_INTERVAL", "update_listen_state", "(", ":choose", ",", "backoff_reconnect_interval", ")", "result", "=", "nil", "when", "Exception", "ErrorTracker", ".", "track", "(", "self", ",", "result", ")", "update_listen_state", "(", ":choose", ",", "backoff_reconnect_interval", ")", "result", "=", "nil", "else", "@reconnect_interval", "=", "RECONNECT_INTERVAL", "@communicated_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "}", "if", "@communicated_callbacks", "update_listen_state", "(", ":choose", ")", "end", "result", "end" ]
Process result from long-polling attempt Not necessary to log failure since should already have been done by underlying HTTP client @param [Array, NilClass] result from long-polling attempt @return [Array, NilClass] result for long-polling attempt
[ "Process", "result", "from", "long", "-", "polling", "attempt", "Not", "necessary", "to", "log", "failure", "since", "should", "already", "have", "been", "done", "by", "underlying", "HTTP", "client" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/router_client.rb#L617-L634
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.init
def init(type, auth_client, options) raise ArgumentError, "Auth client does not support server type #{type.inspect}" unless auth_client.respond_to?(type.to_s + "_url") raise ArgumentError, ":api_version option missing" unless options[:api_version] @type = type @auth_client = auth_client @http_client = nil @status_callbacks = [] @options = options.dup @options[:server_name] ||= type.to_s @options[:open_timeout] ||= DEFAULT_OPEN_TIMEOUT @options[:request_timeout] ||= DEFAULT_REQUEST_TIMEOUT @options[:retry_timeout] ||= DEFAULT_RETRY_TIMEOUT @options[:retry_intervals] ||= DEFAULT_RETRY_INTERVALS @options[:reconnect_interval] ||= DEFAULT_RECONNECT_INTERVAL reset_stats @state = :pending create_http_client enable_use if check_health == :connected state == :connected end
ruby
def init(type, auth_client, options) raise ArgumentError, "Auth client does not support server type #{type.inspect}" unless auth_client.respond_to?(type.to_s + "_url") raise ArgumentError, ":api_version option missing" unless options[:api_version] @type = type @auth_client = auth_client @http_client = nil @status_callbacks = [] @options = options.dup @options[:server_name] ||= type.to_s @options[:open_timeout] ||= DEFAULT_OPEN_TIMEOUT @options[:request_timeout] ||= DEFAULT_REQUEST_TIMEOUT @options[:retry_timeout] ||= DEFAULT_RETRY_TIMEOUT @options[:retry_intervals] ||= DEFAULT_RETRY_INTERVALS @options[:reconnect_interval] ||= DEFAULT_RECONNECT_INTERVAL reset_stats @state = :pending create_http_client enable_use if check_health == :connected state == :connected end
[ "def", "init", "(", "type", ",", "auth_client", ",", "options", ")", "raise", "ArgumentError", ",", "\"Auth client does not support server type #{type.inspect}\"", "unless", "auth_client", ".", "respond_to?", "(", "type", ".", "to_s", "+", "\"_url\"", ")", "raise", "ArgumentError", ",", "\":api_version option missing\"", "unless", "options", "[", ":api_version", "]", "@type", "=", "type", "@auth_client", "=", "auth_client", "@http_client", "=", "nil", "@status_callbacks", "=", "[", "]", "@options", "=", "options", ".", "dup", "@options", "[", ":server_name", "]", "||=", "type", ".", "to_s", "@options", "[", ":open_timeout", "]", "||=", "DEFAULT_OPEN_TIMEOUT", "@options", "[", ":request_timeout", "]", "||=", "DEFAULT_REQUEST_TIMEOUT", "@options", "[", ":retry_timeout", "]", "||=", "DEFAULT_RETRY_TIMEOUT", "@options", "[", ":retry_intervals", "]", "||=", "DEFAULT_RETRY_INTERVALS", "@options", "[", ":reconnect_interval", "]", "||=", "DEFAULT_RECONNECT_INTERVAL", "reset_stats", "@state", "=", ":pending", "create_http_client", "enable_use", "if", "check_health", "==", ":connected", "state", "==", ":connected", "end" ]
Set configuration of this client and initialize HTTP access @param [Symbol] type of server for use in obtaining URL from auth_client, e.g., :router @param [AuthClient] auth_client providing authorization session for HTTP requests @option options [String] :server_name for use in reporting errors, e.g., RightNet @option options [String] :api_version of server for use in X-API-Version header @option options [Numeric] :open_timeout maximum wait for connection; defaults to DEFAULT_OPEN_TIMEOUT @option options [Numeric] :request_timeout maximum wait for response; defaults to DEFAULT_REQUEST_TIMEOUT @option options [Numeric] :retry_timeout maximum before stop retrying; defaults to DEFAULT_RETRY_TIMEOUT @option options [Array] :retry_intervals between successive retries; defaults to DEFAULT_RETRY_INTERVALS @option options [Boolean] :retry_enabled for requests that fail to connect or that return a retry result @option options [Numeric] :reconnect_interval for reconnect attempts after lose connectivity @option options [Boolean] :non_blocking i/o is to be used for HTTP requests by applying EM::HttpRequest and fibers instead of RestClient; requests remain synchronous @option options [Array] :filter_params symbols or strings for names of request parameters whose values are to be hidden when logging; also applied to contents of any parameters named :payload; can be augmented on individual requests @return [Boolean] whether currently connected @raise [ArgumentError] auth client does not support this client type @raise [ArgumentError] :api_version missing
[ "Set", "configuration", "of", "this", "client", "and", "initialize", "HTTP", "access" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L86-L105
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.create_http_client
def create_http_client close_http_client("reconnecting") url = @auth_client.send(@type.to_s + "_url") Log.info("Connecting to #{@options[:server_name]} via #{url.inspect}") options = {:server_name => @options[:server_name]} options[:api_version] = @options[:api_version] if @options[:api_version] options[:non_blocking] = @options[:non_blocking] if @options[:non_blocking] options[:filter_params] = @options[:filter_params] if @options[:filter_params] @http_client = RightScale::BalancedHttpClient.new(url, options) end
ruby
def create_http_client close_http_client("reconnecting") url = @auth_client.send(@type.to_s + "_url") Log.info("Connecting to #{@options[:server_name]} via #{url.inspect}") options = {:server_name => @options[:server_name]} options[:api_version] = @options[:api_version] if @options[:api_version] options[:non_blocking] = @options[:non_blocking] if @options[:non_blocking] options[:filter_params] = @options[:filter_params] if @options[:filter_params] @http_client = RightScale::BalancedHttpClient.new(url, options) end
[ "def", "create_http_client", "close_http_client", "(", "\"reconnecting\"", ")", "url", "=", "@auth_client", ".", "send", "(", "@type", ".", "to_s", "+", "\"_url\"", ")", "Log", ".", "info", "(", "\"Connecting to #{@options[:server_name]} via #{url.inspect}\"", ")", "options", "=", "{", ":server_name", "=>", "@options", "[", ":server_name", "]", "}", "options", "[", ":api_version", "]", "=", "@options", "[", ":api_version", "]", "if", "@options", "[", ":api_version", "]", "options", "[", ":non_blocking", "]", "=", "@options", "[", ":non_blocking", "]", "if", "@options", "[", ":non_blocking", "]", "options", "[", ":filter_params", "]", "=", "@options", "[", ":filter_params", "]", "if", "@options", "[", ":filter_params", "]", "@http_client", "=", "RightScale", "::", "BalancedHttpClient", ".", "new", "(", "url", ",", "options", ")", "end" ]
Create HTTP client If there is an existing client, close it first @return [TrueClass] always true @return [BalancedHttpClient] client
[ "Create", "HTTP", "client", "If", "there", "is", "an", "existing", "client", "close", "it", "first" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L227-L236
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.close_http_client
def close_http_client(reason) @http_client.close(reason) if @http_client true rescue StandardError => e ErrorTracker.log(self, "Failed closing connection", e) false end
ruby
def close_http_client(reason) @http_client.close(reason) if @http_client true rescue StandardError => e ErrorTracker.log(self, "Failed closing connection", e) false end
[ "def", "close_http_client", "(", "reason", ")", "@http_client", ".", "close", "(", "reason", ")", "if", "@http_client", "true", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed closing connection\"", ",", "e", ")", "false", "end" ]
Close HTTP client persistent connections @param [String] reason for closing @return [Boolean] false if failed, otherwise true
[ "Close", "HTTP", "client", "persistent", "connections" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L243-L249
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.check_health
def check_health begin @http_client.check_health self.state = :connected rescue BalancedHttpClient::NotResponding => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e.nested_exception) self.state = :disconnected rescue StandardError => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e, nil, :caller) self.state = :disconnected end end
ruby
def check_health begin @http_client.check_health self.state = :connected rescue BalancedHttpClient::NotResponding => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e.nested_exception) self.state = :disconnected rescue StandardError => e ErrorTracker.log(self, "Failed #{@options[:server_name]} health check", e, nil, :caller) self.state = :disconnected end end
[ "def", "check_health", "begin", "@http_client", ".", "check_health", "self", ".", "state", "=", ":connected", "rescue", "BalancedHttpClient", "::", "NotResponding", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed #{@options[:server_name]} health check\"", ",", "e", ".", "nested_exception", ")", "self", ".", "state", "=", ":disconnected", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed #{@options[:server_name]} health check\"", ",", "e", ",", "nil", ",", ":caller", ")", "self", ".", "state", "=", ":disconnected", "end", "end" ]
Check health of RightApi directly without applying RequestBalancer Do not check whether HTTP client exists @return [Symbol] RightApi client state
[ "Check", "health", "of", "RightApi", "directly", "without", "applying", "RequestBalancer", "Do", "not", "check", "whether", "HTTP", "client", "exists" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L263-L274
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.reconnect
def reconnect unless @reconnecting @reconnecting = true if EM.reactor_running? @stats["reconnects"].update("initiate") @reconnect_timer = EM_S::PeriodicTimer.new(rand(@options[:reconnect_interval])) do begin reconnect_once rescue Exception => e ErrorTracker.log(self, "Failed #{@options[:server_name]} reconnect", e, nil, :caller) @stats["reconnects"].update("failure") self.state = :disconnected end @reconnect_timer.interval = @options[:reconnect_interval] if @reconnect_timer end else reconnect_once end end true end
ruby
def reconnect unless @reconnecting @reconnecting = true if EM.reactor_running? @stats["reconnects"].update("initiate") @reconnect_timer = EM_S::PeriodicTimer.new(rand(@options[:reconnect_interval])) do begin reconnect_once rescue Exception => e ErrorTracker.log(self, "Failed #{@options[:server_name]} reconnect", e, nil, :caller) @stats["reconnects"].update("failure") self.state = :disconnected end @reconnect_timer.interval = @options[:reconnect_interval] if @reconnect_timer end else reconnect_once end end true end
[ "def", "reconnect", "unless", "@reconnecting", "@reconnecting", "=", "true", "if", "EM", ".", "reactor_running?", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"initiate\"", ")", "@reconnect_timer", "=", "EM_S", "::", "PeriodicTimer", ".", "new", "(", "rand", "(", "@options", "[", ":reconnect_interval", "]", ")", ")", "do", "begin", "reconnect_once", "rescue", "Exception", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed #{@options[:server_name]} reconnect\"", ",", "e", ",", "nil", ",", ":caller", ")", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"failure\"", ")", "self", ".", "state", "=", ":disconnected", "end", "@reconnect_timer", ".", "interval", "=", "@options", "[", ":reconnect_interval", "]", "if", "@reconnect_timer", "end", "else", "reconnect_once", "end", "end", "true", "end" ]
If EventMachine reactor is running, begin attempting to periodically reconnect with server by checking health. Randomize initial attempt to reduce server spiking. If EventMachine reactor is NOT running, attempt to reconnect once and raise any exception that is encountered. @return [TrueClass] always true
[ "If", "EventMachine", "reactor", "is", "running", "begin", "attempting", "to", "periodically", "reconnect", "with", "server", "by", "checking", "health", ".", "Randomize", "initial", "attempt", "to", "reduce", "server", "spiking", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L284-L306
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.make_request
def make_request(verb, path, params = {}, type = nil, options = {}) raise Exceptions::Terminating if state == :closed started_at = Time.now time_to_live = (options[:time_to_live] && options[:time_to_live] > 0) ? options[:time_to_live] : nil expires_at = started_at + [time_to_live || @options[:retry_timeout], @options[:retry_timeout]].min headers = time_to_live ? @auth_client.headers.merge("X-Expires-At" => started_at + time_to_live) : @auth_client.headers request_uuid = options[:request_uuid] || RightSupport::Data::UUID.generate attempts = 0 result = nil @stats["requests sent"].measure(type || path, request_uuid) do begin attempts += 1 http_options = { :open_timeout => @options[:open_timeout], :request_timeout => @options[:request_timeout], :request_uuid => request_uuid, :headers => headers } reconnect_once if (:disconnected == state) && !EM.reactor_running? raise Exceptions::ConnectivityFailure, "#{@type} client not connected" unless [:connected, :closing].include?(state) result = @http_client.send(verb, path, params, http_options.merge(options)) rescue StandardError => e request_uuid = handle_exception(e, type || path, request_uuid, expires_at, attempts) request_uuid ? retry : raise end end @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks result end
ruby
def make_request(verb, path, params = {}, type = nil, options = {}) raise Exceptions::Terminating if state == :closed started_at = Time.now time_to_live = (options[:time_to_live] && options[:time_to_live] > 0) ? options[:time_to_live] : nil expires_at = started_at + [time_to_live || @options[:retry_timeout], @options[:retry_timeout]].min headers = time_to_live ? @auth_client.headers.merge("X-Expires-At" => started_at + time_to_live) : @auth_client.headers request_uuid = options[:request_uuid] || RightSupport::Data::UUID.generate attempts = 0 result = nil @stats["requests sent"].measure(type || path, request_uuid) do begin attempts += 1 http_options = { :open_timeout => @options[:open_timeout], :request_timeout => @options[:request_timeout], :request_uuid => request_uuid, :headers => headers } reconnect_once if (:disconnected == state) && !EM.reactor_running? raise Exceptions::ConnectivityFailure, "#{@type} client not connected" unless [:connected, :closing].include?(state) result = @http_client.send(verb, path, params, http_options.merge(options)) rescue StandardError => e request_uuid = handle_exception(e, type || path, request_uuid, expires_at, attempts) request_uuid ? retry : raise end end @communicated_callbacks.each { |callback| callback.call } if @communicated_callbacks result end
[ "def", "make_request", "(", "verb", ",", "path", ",", "params", "=", "{", "}", ",", "type", "=", "nil", ",", "options", "=", "{", "}", ")", "raise", "Exceptions", "::", "Terminating", "if", "state", "==", ":closed", "started_at", "=", "Time", ".", "now", "time_to_live", "=", "(", "options", "[", ":time_to_live", "]", "&&", "options", "[", ":time_to_live", "]", ">", "0", ")", "?", "options", "[", ":time_to_live", "]", ":", "nil", "expires_at", "=", "started_at", "+", "[", "time_to_live", "||", "@options", "[", ":retry_timeout", "]", ",", "@options", "[", ":retry_timeout", "]", "]", ".", "min", "headers", "=", "time_to_live", "?", "@auth_client", ".", "headers", ".", "merge", "(", "\"X-Expires-At\"", "=>", "started_at", "+", "time_to_live", ")", ":", "@auth_client", ".", "headers", "request_uuid", "=", "options", "[", ":request_uuid", "]", "||", "RightSupport", "::", "Data", "::", "UUID", ".", "generate", "attempts", "=", "0", "result", "=", "nil", "@stats", "[", "\"requests sent\"", "]", ".", "measure", "(", "type", "||", "path", ",", "request_uuid", ")", "do", "begin", "attempts", "+=", "1", "http_options", "=", "{", ":open_timeout", "=>", "@options", "[", ":open_timeout", "]", ",", ":request_timeout", "=>", "@options", "[", ":request_timeout", "]", ",", ":request_uuid", "=>", "request_uuid", ",", ":headers", "=>", "headers", "}", "reconnect_once", "if", "(", ":disconnected", "==", "state", ")", "&&", "!", "EM", ".", "reactor_running?", "raise", "Exceptions", "::", "ConnectivityFailure", ",", "\"#{@type} client not connected\"", "unless", "[", ":connected", ",", ":closing", "]", ".", "include?", "(", "state", ")", "result", "=", "@http_client", ".", "send", "(", "verb", ",", "path", ",", "params", ",", "http_options", ".", "merge", "(", "options", ")", ")", "rescue", "StandardError", "=>", "e", "request_uuid", "=", "handle_exception", "(", "e", ",", "type", "||", "path", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "request_uuid", "?", "retry", ":", "raise", "end", "end", "@communicated_callbacks", ".", "each", "{", "|", "callback", "|", "callback", ".", "call", "}", "if", "@communicated_callbacks", "result", "end" ]
Make request via HTTP. Attempt to reconnect first if disconnected and EM reactor is not running. Rely on underlying HTTP client to log request and response. Retry request if response indicates to or if there are connectivity failures. There are also several timeouts involved: - Underlying BalancedHttpClient connection open timeout (:open_timeout) - Underlying BalancedHttpClient request timeout (:request_timeout) - Retry timeout for this method and its handlers (:retry_timeout) - Seconds before request expires and is to be ignored (:time_to_live) and if the target server is a RightNet router: - Router response timeout (ideally > :retry_timeout and < :request_timeout) - Router retry timeout (ideally = :retry_timeout) There are several possible levels of retry involved, starting with the outermost: - This method will retry if the targeted server is not responding or if it receives a retry response, but the total elapsed time is not allowed to exceed :request_timeout - RequestBalancer in BalancedHttpClient will retry using other endpoints if it gets an error that it considers retryable, and even if a front-end balancer is in use there will likely be at least two such endpoints for redundancy and if the target server is a RightNet router: - The router when sending a request via AMQP will retry if it receives no response, but not exceeding its configured :retry_timeout; if the router's timeouts for retry are consistent with the ones prescribed above, there will be no retry by the RequestBalancer after router retries @param [Symbol] verb for HTTP REST request @param [String] path in URI for desired resource @param [Hash] params for HTTP request @param [String] type of request for use in logging; defaults to path @param [String, NilClass] request_uuid uniquely identifying this request; defaults to randomly generated UUID @param [Numeric, NilClass] time_to_live seconds before request expires and is to be ignored; non-positive value or nil means never expire; defaults to nil @param [Hash] options augmenting or overriding default options for HTTP request @return [Object, NilClass] result of request with nil meaning no result @raise [Exceptions::Unauthorized] authorization failed @raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection to it, or it is out of service or too busy to respond @raise [Exceptions::RetryableError] request failed but if retried may succeed @raise [Exceptions::Terminating] closing client and terminating service @raise [Exceptions::InternalServerError] internal error in server being accessed
[ "Make", "request", "via", "HTTP", ".", "Attempt", "to", "reconnect", "first", "if", "disconnected", "and", "EM", "reactor", "is", "not", "running", ".", "Rely", "on", "underlying", "HTTP", "client", "to", "log", "request", "and", "response", ".", "Retry", "request", "if", "response", "indicates", "to", "or", "if", "there", "are", "connectivity", "failures", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L367-L394
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_exception
def handle_exception(exception, type, request_uuid, expires_at, attempts) result = request_uuid if exception.respond_to?(:http_code) case exception.http_code when 301, 302 # MovedPermanently, Found handle_redirect(exception, type, request_uuid) when 401 # Unauthorized raise Exceptions::Unauthorized.new(exception.http_body, exception) when 403 # Forbidden @auth_client.expired raise Exceptions::RetryableError.new("Authorization expired", exception) when 449 # RetryWith result = handle_retry_with(exception, type, request_uuid, expires_at, attempts) when 500 # InternalServerError raise Exceptions::InternalServerError.new(exception.http_body, @options[:server_name]) else @stats["request failures"].update("#{type} - #{exception.http_code}") result = nil end elsif exception.is_a?(BalancedHttpClient::NotResponding) handle_not_responding(exception, type, request_uuid, expires_at, attempts) else @stats["request failures"].update("#{type} - #{exception.class.name}") result = nil end result end
ruby
def handle_exception(exception, type, request_uuid, expires_at, attempts) result = request_uuid if exception.respond_to?(:http_code) case exception.http_code when 301, 302 # MovedPermanently, Found handle_redirect(exception, type, request_uuid) when 401 # Unauthorized raise Exceptions::Unauthorized.new(exception.http_body, exception) when 403 # Forbidden @auth_client.expired raise Exceptions::RetryableError.new("Authorization expired", exception) when 449 # RetryWith result = handle_retry_with(exception, type, request_uuid, expires_at, attempts) when 500 # InternalServerError raise Exceptions::InternalServerError.new(exception.http_body, @options[:server_name]) else @stats["request failures"].update("#{type} - #{exception.http_code}") result = nil end elsif exception.is_a?(BalancedHttpClient::NotResponding) handle_not_responding(exception, type, request_uuid, expires_at, attempts) else @stats["request failures"].update("#{type} - #{exception.class.name}") result = nil end result end
[ "def", "handle_exception", "(", "exception", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "result", "=", "request_uuid", "if", "exception", ".", "respond_to?", "(", ":http_code", ")", "case", "exception", ".", "http_code", "when", "301", ",", "302", "handle_redirect", "(", "exception", ",", "type", ",", "request_uuid", ")", "when", "401", "raise", "Exceptions", "::", "Unauthorized", ".", "new", "(", "exception", ".", "http_body", ",", "exception", ")", "when", "403", "@auth_client", ".", "expired", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "\"Authorization expired\"", ",", "exception", ")", "when", "449", "result", "=", "handle_retry_with", "(", "exception", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "when", "500", "raise", "Exceptions", "::", "InternalServerError", ".", "new", "(", "exception", ".", "http_body", ",", "@options", "[", ":server_name", "]", ")", "else", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - #{exception.http_code}\"", ")", "result", "=", "nil", "end", "elsif", "exception", ".", "is_a?", "(", "BalancedHttpClient", "::", "NotResponding", ")", "handle_not_responding", "(", "exception", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "else", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - #{exception.class.name}\"", ")", "result", "=", "nil", "end", "result", "end" ]
Examine exception to determine whether to setup retry, raise new exception, or re-raise @param [StandardError] exception raised @param [String] action from request type @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @param [Time] expires_at time for request @param [Integer] attempts to make request @return [String, NilClass] request UUID to be used on retry or nil if to raise instead @raise [Exceptions::Unauthorized] authorization failed @raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection to it, or it is out of service or too busy to respond @raise [Exceptions::RetryableError] request failed but if retried may succeed @raise [Exceptions::InternalServerError] internal error in server being accessed
[ "Examine", "exception", "to", "determine", "whether", "to", "setup", "retry", "raise", "new", "exception", "or", "re", "-", "raise" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L412-L438
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_redirect
def handle_redirect(redirect, type, request_uuid) Log.info("Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>") if redirect.respond_to?(:response) && (location = redirect.response.headers[:location]) && !location.empty? Log.info("Requesting auth client to handle redirect to #{location.inspect}") @stats["reconnects"].update("redirect") @auth_client.redirect(location) raise Exceptions::RetryableError.new(redirect.http_body, redirect) else raise Exceptions::InternalServerError.new("No redirect location provided", @options[:server_name]) end true end
ruby
def handle_redirect(redirect, type, request_uuid) Log.info("Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>") if redirect.respond_to?(:response) && (location = redirect.response.headers[:location]) && !location.empty? Log.info("Requesting auth client to handle redirect to #{location.inspect}") @stats["reconnects"].update("redirect") @auth_client.redirect(location) raise Exceptions::RetryableError.new(redirect.http_body, redirect) else raise Exceptions::InternalServerError.new("No redirect location provided", @options[:server_name]) end true end
[ "def", "handle_redirect", "(", "redirect", ",", "type", ",", "request_uuid", ")", "Log", ".", "info", "(", "\"Received REDIRECT #{redirect} for #{type} request <#{request_uuid}>\"", ")", "if", "redirect", ".", "respond_to?", "(", ":response", ")", "&&", "(", "location", "=", "redirect", ".", "response", ".", "headers", "[", ":location", "]", ")", "&&", "!", "location", ".", "empty?", "Log", ".", "info", "(", "\"Requesting auth client to handle redirect to #{location.inspect}\"", ")", "@stats", "[", "\"reconnects\"", "]", ".", "update", "(", "\"redirect\"", ")", "@auth_client", ".", "redirect", "(", "location", ")", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "redirect", ".", "http_body", ",", "redirect", ")", "else", "raise", "Exceptions", "::", "InternalServerError", ".", "new", "(", "\"No redirect location provided\"", ",", "@options", "[", ":server_name", "]", ")", "end", "true", "end" ]
Treat redirect response as indication that no longer accessing the correct shard Handle it by informing auth client so that it can re-authorize Do not retry, but tell client to with the expectation that re-auth will correct the situation @param [RestClient::MovedPermanently, RestClient::Found] redirect exception raised @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @return [TrueClass] never returns @raise [Exceptions::RetryableError] request redirected but if retried may succeed @raise [Exceptions::InternalServerError] no redirect location provided
[ "Treat", "redirect", "response", "as", "indication", "that", "no", "longer", "accessing", "the", "correct", "shard", "Handle", "it", "by", "informing", "auth", "client", "so", "that", "it", "can", "re", "-", "authorize", "Do", "not", "retry", "but", "tell", "client", "to", "with", "the", "expectation", "that", "re", "-", "auth", "will", "correct", "the", "situation" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L452-L463
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_retry_with
def handle_retry_with(retry_result, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts, 1)) when nil @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) when 0 @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to retryable error (#{retry_result.http_body})") wait(interval) end # Change request_uuid so that retried request not rejected as duplicate "#{request_uuid}:retry" end
ruby
def handle_retry_with(retry_result, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts, 1)) when nil @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) when 0 @stats["request failures"].update("#{type} - retry") raise Exceptions::RetryableError.new(retry_result.http_body, retry_result) else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to retryable error (#{retry_result.http_body})") wait(interval) end # Change request_uuid so that retried request not rejected as duplicate "#{request_uuid}:retry" end
[ "def", "handle_retry_with", "(", "retry_result", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "case", "(", "interval", "=", "retry_interval", "(", "expires_at", ",", "attempts", ",", "1", ")", ")", "when", "nil", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - retry\"", ")", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "retry_result", ".", "http_body", ",", "retry_result", ")", "when", "0", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - retry\"", ")", "raise", "Exceptions", "::", "RetryableError", ".", "new", "(", "retry_result", ".", "http_body", ",", "retry_result", ")", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Retrying #{type} request <#{request_uuid}> in #{interval} seconds \"", "+", "\"in response to retryable error (#{retry_result.http_body})\"", ")", "wait", "(", "interval", ")", "end", "\"#{request_uuid}:retry\"", "end" ]
Handle retry response by retrying it only once This indicates the request was received but a retryable error prevented it from being processed; the retry responsibility may be passed on If retrying, this function does not return until it is time to retry @param [RestClient::RetryWith] retry_result exception raised @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @param [Time] expires_at time for request @param [Integer] attempts to make request @return [String] request UUID to be used on retry @raise [Exceptions::RetryableError] request failed but if retried may succeed
[ "Handle", "retry", "response", "by", "retrying", "it", "only", "once", "This", "indicates", "the", "request", "was", "received", "but", "a", "retryable", "error", "prevented", "it", "from", "being", "processed", ";", "the", "retry", "responsibility", "may", "be", "passed", "on", "If", "retrying", "this", "function", "does", "not", "return", "until", "it", "is", "time", "to", "retry" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L479-L494
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.handle_not_responding
def handle_not_responding(not_responding, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts)) when nil @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message) when 0 @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message + " after #{attempts} attempts") else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to routing failure (#{BalancedHttpClient.exception_text(not_responding)})") wait(interval) end true end
ruby
def handle_not_responding(not_responding, type, request_uuid, expires_at, attempts) case (interval = retry_interval(expires_at, attempts)) when nil @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message) when 0 @stats["request failures"].update("#{type} - no result") self.state = :disconnected raise Exceptions::ConnectivityFailure.new(not_responding.message + " after #{attempts} attempts") else ErrorTracker.log(self, "Retrying #{type} request <#{request_uuid}> in #{interval} seconds " + "in response to routing failure (#{BalancedHttpClient.exception_text(not_responding)})") wait(interval) end true end
[ "def", "handle_not_responding", "(", "not_responding", ",", "type", ",", "request_uuid", ",", "expires_at", ",", "attempts", ")", "case", "(", "interval", "=", "retry_interval", "(", "expires_at", ",", "attempts", ")", ")", "when", "nil", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - no result\"", ")", "self", ".", "state", "=", ":disconnected", "raise", "Exceptions", "::", "ConnectivityFailure", ".", "new", "(", "not_responding", ".", "message", ")", "when", "0", "@stats", "[", "\"request failures\"", "]", ".", "update", "(", "\"#{type} - no result\"", ")", "self", ".", "state", "=", ":disconnected", "raise", "Exceptions", "::", "ConnectivityFailure", ".", "new", "(", "not_responding", ".", "message", "+", "\" after #{attempts} attempts\"", ")", "else", "ErrorTracker", ".", "log", "(", "self", ",", "\"Retrying #{type} request <#{request_uuid}> in #{interval} seconds \"", "+", "\"in response to routing failure (#{BalancedHttpClient.exception_text(not_responding)})\"", ")", "wait", "(", "interval", ")", "end", "true", "end" ]
Handle not responding response by determining whether okay to retry If request is being retried, this function does not return until it is time to retry @param [BalancedHttpClient::NotResponding] not_responding exception indicating targeted server is too busy or out of service @param [String] type of request for use in logging @param [String] request_uuid originally created for this request @param [Time] expires_at time for request @param [Integer] attempts to make request @return [TrueClass] always true @raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection to it, or it is out of service or too busy to respond
[ "Handle", "not", "responding", "response", "by", "determining", "whether", "okay", "to", "retry", "If", "request", "is", "being", "retried", "this", "function", "does", "not", "return", "until", "it", "is", "time", "to", "retry" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L510-L526
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.retry_interval
def retry_interval(expires_at, attempts, max_retries = nil) if @options[:retry_enabled] if max_retries.nil? || attempts <= max_retries interval = @options[:retry_intervals][attempts - 1] || @options[:retry_intervals][-1] ((Time.now + interval) < expires_at) ? interval : 0 else 0 end end end
ruby
def retry_interval(expires_at, attempts, max_retries = nil) if @options[:retry_enabled] if max_retries.nil? || attempts <= max_retries interval = @options[:retry_intervals][attempts - 1] || @options[:retry_intervals][-1] ((Time.now + interval) < expires_at) ? interval : 0 else 0 end end end
[ "def", "retry_interval", "(", "expires_at", ",", "attempts", ",", "max_retries", "=", "nil", ")", "if", "@options", "[", ":retry_enabled", "]", "if", "max_retries", ".", "nil?", "||", "attempts", "<=", "max_retries", "interval", "=", "@options", "[", ":retry_intervals", "]", "[", "attempts", "-", "1", "]", "||", "@options", "[", ":retry_intervals", "]", "[", "-", "1", "]", "(", "(", "Time", ".", "now", "+", "interval", ")", "<", "expires_at", ")", "?", "interval", ":", "0", "else", "0", "end", "end", "end" ]
Determine time interval before next retry @param [Time] expires_at time for request @param [Integer] attempts so far @param [Integer] max_retries @return [Integer, NilClass] retry interval with 0 meaning no try and nil meaning retry disabled
[ "Determine", "time", "interval", "before", "next", "retry" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L535-L544
train
rightscale/right_agent
lib/right_agent/clients/base_retry_client.rb
RightScale.BaseRetryClient.wait
def wait(interval) if @options[:non_blocking] fiber = Fiber.current EM.add_timer(interval) { fiber.resume } Fiber.yield else sleep(interval) end true end
ruby
def wait(interval) if @options[:non_blocking] fiber = Fiber.current EM.add_timer(interval) { fiber.resume } Fiber.yield else sleep(interval) end true end
[ "def", "wait", "(", "interval", ")", "if", "@options", "[", ":non_blocking", "]", "fiber", "=", "Fiber", ".", "current", "EM", ".", "add_timer", "(", "interval", ")", "{", "fiber", ".", "resume", "}", "Fiber", ".", "yield", "else", "sleep", "(", "interval", ")", "end", "true", "end" ]
Wait the specified interval in non-blocking fashion if possible @param [Numeric] interval to wait @return [TrueClass] always true
[ "Wait", "the", "specified", "interval", "in", "non", "-", "blocking", "fashion", "if", "possible" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/base_retry_client.rb#L551-L560
train
rightscale/right_agent
lib/right_agent/retryable_request.rb
RightScale.RetryableRequest.handle_response
def handle_response(r) return true if @done @raw_response = r res = result_from(r) if res.success? if @cancel_timer @cancel_timer.cancel @cancel_timer = nil end @done = true succeed(res.content) else reason = res.content if res.non_delivery? Log.info("Request non-delivery (#{reason}) for #{@operation}") elsif res.retry? reason = (reason && !reason.empty?) ? reason : "RightScale not ready" Log.info("Request #{@operation} failed (#{reason}) and should be retried") elsif res.cancel? reason = (reason && !reason.empty?) ? reason : "RightScale cannot execute request" Log.info("Request #{@operation} canceled (#{reason})") else Log.info("Request #{@operation} failed (#{reason})") end if (res.non_delivery? || res.retry? || @retry_on_error) && !res.cancel? Log.info("Retrying in #{@retry_delay} seconds...") if @retry_delay > 0 this_delay = @retry_delay if (@retries += 1) >= @retry_delay_count @retry_delay = [@retry_delay * RETRY_BACKOFF_FACTOR, @max_retry_delay].min @retry_delay_count = [@retry_delay_count / RETRY_BACKOFF_FACTOR, 1].max @retries = 0 end EM.add_timer(this_delay) { run } else EM.next_tick { run } end else cancel(res.content) end end true end
ruby
def handle_response(r) return true if @done @raw_response = r res = result_from(r) if res.success? if @cancel_timer @cancel_timer.cancel @cancel_timer = nil end @done = true succeed(res.content) else reason = res.content if res.non_delivery? Log.info("Request non-delivery (#{reason}) for #{@operation}") elsif res.retry? reason = (reason && !reason.empty?) ? reason : "RightScale not ready" Log.info("Request #{@operation} failed (#{reason}) and should be retried") elsif res.cancel? reason = (reason && !reason.empty?) ? reason : "RightScale cannot execute request" Log.info("Request #{@operation} canceled (#{reason})") else Log.info("Request #{@operation} failed (#{reason})") end if (res.non_delivery? || res.retry? || @retry_on_error) && !res.cancel? Log.info("Retrying in #{@retry_delay} seconds...") if @retry_delay > 0 this_delay = @retry_delay if (@retries += 1) >= @retry_delay_count @retry_delay = [@retry_delay * RETRY_BACKOFF_FACTOR, @max_retry_delay].min @retry_delay_count = [@retry_delay_count / RETRY_BACKOFF_FACTOR, 1].max @retries = 0 end EM.add_timer(this_delay) { run } else EM.next_tick { run } end else cancel(res.content) end end true end
[ "def", "handle_response", "(", "r", ")", "return", "true", "if", "@done", "@raw_response", "=", "r", "res", "=", "result_from", "(", "r", ")", "if", "res", ".", "success?", "if", "@cancel_timer", "@cancel_timer", ".", "cancel", "@cancel_timer", "=", "nil", "end", "@done", "=", "true", "succeed", "(", "res", ".", "content", ")", "else", "reason", "=", "res", ".", "content", "if", "res", ".", "non_delivery?", "Log", ".", "info", "(", "\"Request non-delivery (#{reason}) for #{@operation}\"", ")", "elsif", "res", ".", "retry?", "reason", "=", "(", "reason", "&&", "!", "reason", ".", "empty?", ")", "?", "reason", ":", "\"RightScale not ready\"", "Log", ".", "info", "(", "\"Request #{@operation} failed (#{reason}) and should be retried\"", ")", "elsif", "res", ".", "cancel?", "reason", "=", "(", "reason", "&&", "!", "reason", ".", "empty?", ")", "?", "reason", ":", "\"RightScale cannot execute request\"", "Log", ".", "info", "(", "\"Request #{@operation} canceled (#{reason})\"", ")", "else", "Log", ".", "info", "(", "\"Request #{@operation} failed (#{reason})\"", ")", "end", "if", "(", "res", ".", "non_delivery?", "||", "res", ".", "retry?", "||", "@retry_on_error", ")", "&&", "!", "res", ".", "cancel?", "Log", ".", "info", "(", "\"Retrying in #{@retry_delay} seconds...\"", ")", "if", "@retry_delay", ">", "0", "this_delay", "=", "@retry_delay", "if", "(", "@retries", "+=", "1", ")", ">=", "@retry_delay_count", "@retry_delay", "=", "[", "@retry_delay", "*", "RETRY_BACKOFF_FACTOR", ",", "@max_retry_delay", "]", ".", "min", "@retry_delay_count", "=", "[", "@retry_delay_count", "/", "RETRY_BACKOFF_FACTOR", ",", "1", "]", ".", "max", "@retries", "=", "0", "end", "EM", ".", "add_timer", "(", "this_delay", ")", "{", "run", "}", "else", "EM", ".", "next_tick", "{", "run", "}", "end", "else", "cancel", "(", "res", ".", "content", ")", "end", "end", "true", "end" ]
Process request response and retry if needed === Parameters r(Result):: Request result === Return true:: Always return true
[ "Process", "request", "response", "and", "retry", "if", "needed" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/retryable_request.rb#L151-L193
train
rightscale/right_agent
lib/right_agent/serialize/secure_serializer.rb
RightScale.SecureSerializer.dump
def dump(obj, encrypt = nil) must_encrypt = encrypt || @encrypt serialize_format = if obj.respond_to?(:send_version) && can_handle_msgpack_result?(obj.send_version) @serializer.format else :json end encode_format = serialize_format == :json ? :pem : :der msg = @serializer.dump(obj, serialize_format) if must_encrypt certs = @store.get_target(obj) if certs msg = EncryptedDocument.new(msg, certs).encrypted_data(encode_format) else target = obj.target_for_encryption if obj.respond_to?(:target_for_encryption) ErrorTracker.log(self, "No certs available for object #{obj.class} being sent to #{target.inspect}") if target end end sig = Signature.new(msg, @cert, @key).data(encode_format) @serializer.dump({'id' => @identity, 'data' => msg, 'signature' => sig, 'encrypted' => !certs.nil?}, serialize_format) end
ruby
def dump(obj, encrypt = nil) must_encrypt = encrypt || @encrypt serialize_format = if obj.respond_to?(:send_version) && can_handle_msgpack_result?(obj.send_version) @serializer.format else :json end encode_format = serialize_format == :json ? :pem : :der msg = @serializer.dump(obj, serialize_format) if must_encrypt certs = @store.get_target(obj) if certs msg = EncryptedDocument.new(msg, certs).encrypted_data(encode_format) else target = obj.target_for_encryption if obj.respond_to?(:target_for_encryption) ErrorTracker.log(self, "No certs available for object #{obj.class} being sent to #{target.inspect}") if target end end sig = Signature.new(msg, @cert, @key).data(encode_format) @serializer.dump({'id' => @identity, 'data' => msg, 'signature' => sig, 'encrypted' => !certs.nil?}, serialize_format) end
[ "def", "dump", "(", "obj", ",", "encrypt", "=", "nil", ")", "must_encrypt", "=", "encrypt", "||", "@encrypt", "serialize_format", "=", "if", "obj", ".", "respond_to?", "(", ":send_version", ")", "&&", "can_handle_msgpack_result?", "(", "obj", ".", "send_version", ")", "@serializer", ".", "format", "else", ":json", "end", "encode_format", "=", "serialize_format", "==", ":json", "?", ":pem", ":", ":der", "msg", "=", "@serializer", ".", "dump", "(", "obj", ",", "serialize_format", ")", "if", "must_encrypt", "certs", "=", "@store", ".", "get_target", "(", "obj", ")", "if", "certs", "msg", "=", "EncryptedDocument", ".", "new", "(", "msg", ",", "certs", ")", ".", "encrypted_data", "(", "encode_format", ")", "else", "target", "=", "obj", ".", "target_for_encryption", "if", "obj", ".", "respond_to?", "(", ":target_for_encryption", ")", "ErrorTracker", ".", "log", "(", "self", ",", "\"No certs available for object #{obj.class} being sent to #{target.inspect}\"", ")", "if", "target", "end", "end", "sig", "=", "Signature", ".", "new", "(", "msg", ",", "@cert", ",", "@key", ")", ".", "data", "(", "encode_format", ")", "@serializer", ".", "dump", "(", "{", "'id'", "=>", "@identity", ",", "'data'", "=>", "msg", ",", "'signature'", "=>", "sig", ",", "'encrypted'", "=>", "!", "certs", ".", "nil?", "}", ",", "serialize_format", ")", "end" ]
Initialize serializer, must be called prior to using it === Parameters serializer(Serializer):: Object serializer identity(String):: Serialized identity associated with serialized messages store(Object):: Credentials store exposing certificates used for encryption (:get_target), signature validation (:get_signer), and certificate(s)/key(s) used for decryption (:get_receiver) encrypt(Boolean):: true if data should be signed and encrypted, otherwise just signed, true by default Serialize, sign, and encrypt message Sign and encrypt using X.509 certificate === Parameters obj(Object):: Object to be serialized and encrypted encrypt(Boolean|nil):: true if object should be signed and encrypted, false if just signed, nil means use class setting === Return (String):: MessagePack serialized and optionally encrypted object
[ "Initialize", "serializer", "must", "be", "called", "prior", "to", "using", "it" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/serialize/secure_serializer.rb#L90-L110
train
rightscale/right_agent
lib/right_agent/serialize/secure_serializer.rb
RightScale.SecureSerializer.load
def load(msg, id = nil) msg = @serializer.load(msg) sig = Signature.from_data(msg['signature']) certs = @store.get_signer(msg['id']) raise MissingCertificate.new("Could not find a certificate for signer #{msg['id']}") unless certs certs = [ certs ] unless certs.respond_to?(:any?) raise InvalidSignature.new("Failed signature check for signer #{msg['id']}") unless certs.any? { |c| sig.match?(c) } data = msg['data'] if data && msg['encrypted'] cert, key = @store.get_receiver(id) raise MissingCertificate.new("Could not find a certificate for #{id.inspect}") unless cert raise MissingPrivateKey.new("Could not find a private key for #{id.inspect}") unless key data = EncryptedDocument.from_data(data).decrypted_data(key, cert) end @serializer.load(data) if data end
ruby
def load(msg, id = nil) msg = @serializer.load(msg) sig = Signature.from_data(msg['signature']) certs = @store.get_signer(msg['id']) raise MissingCertificate.new("Could not find a certificate for signer #{msg['id']}") unless certs certs = [ certs ] unless certs.respond_to?(:any?) raise InvalidSignature.new("Failed signature check for signer #{msg['id']}") unless certs.any? { |c| sig.match?(c) } data = msg['data'] if data && msg['encrypted'] cert, key = @store.get_receiver(id) raise MissingCertificate.new("Could not find a certificate for #{id.inspect}") unless cert raise MissingPrivateKey.new("Could not find a private key for #{id.inspect}") unless key data = EncryptedDocument.from_data(data).decrypted_data(key, cert) end @serializer.load(data) if data end
[ "def", "load", "(", "msg", ",", "id", "=", "nil", ")", "msg", "=", "@serializer", ".", "load", "(", "msg", ")", "sig", "=", "Signature", ".", "from_data", "(", "msg", "[", "'signature'", "]", ")", "certs", "=", "@store", ".", "get_signer", "(", "msg", "[", "'id'", "]", ")", "raise", "MissingCertificate", ".", "new", "(", "\"Could not find a certificate for signer #{msg['id']}\"", ")", "unless", "certs", "certs", "=", "[", "certs", "]", "unless", "certs", ".", "respond_to?", "(", ":any?", ")", "raise", "InvalidSignature", ".", "new", "(", "\"Failed signature check for signer #{msg['id']}\"", ")", "unless", "certs", ".", "any?", "{", "|", "c", "|", "sig", ".", "match?", "(", "c", ")", "}", "data", "=", "msg", "[", "'data'", "]", "if", "data", "&&", "msg", "[", "'encrypted'", "]", "cert", ",", "key", "=", "@store", ".", "get_receiver", "(", "id", ")", "raise", "MissingCertificate", ".", "new", "(", "\"Could not find a certificate for #{id.inspect}\"", ")", "unless", "cert", "raise", "MissingPrivateKey", ".", "new", "(", "\"Could not find a private key for #{id.inspect}\"", ")", "unless", "key", "data", "=", "EncryptedDocument", ".", "from_data", "(", "data", ")", ".", "decrypted_data", "(", "key", ",", "cert", ")", "end", "@serializer", ".", "load", "(", "data", ")", "if", "data", "end" ]
Decrypt, authorize signature, and unserialize message Use x.509 certificate store for decrypting and validating signature === Parameters msg(String):: Serialized and optionally encrypted object using MessagePack or JSON id(String|nil):: Optional identifier of source of data for use in determining who is the receiver === Return (Object):: Unserialized object === Raise MissingCertificate:: If could not find certificate for message signer or receiver MissingPrivateKey:: If could not find private key for message receiver InvalidSignature:: If message signature check failed for message
[ "Decrypt", "authorize", "signature", "and", "unserialize", "message", "Use", "x", ".", "509", "certificate", "store", "for", "decrypting", "and", "validating", "signature" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/serialize/secure_serializer.rb#L127-L144
train
rightscale/right_agent
lib/right_agent/core_payload_types/right_script_attachment.rb
RightScale.RightScriptAttachment.fill_out
def fill_out(session) session['scope'] = "attachments" if @digest session['resource'] = @digest else session['resource'] = to_hash session['url'] = @url session['etag'] = @etag end @token = session.to_s end
ruby
def fill_out(session) session['scope'] = "attachments" if @digest session['resource'] = @digest else session['resource'] = to_hash session['url'] = @url session['etag'] = @etag end @token = session.to_s end
[ "def", "fill_out", "(", "session", ")", "session", "[", "'scope'", "]", "=", "\"attachments\"", "if", "@digest", "session", "[", "'resource'", "]", "=", "@digest", "else", "session", "[", "'resource'", "]", "=", "to_hash", "session", "[", "'url'", "]", "=", "@url", "session", "[", "'etag'", "]", "=", "@etag", "end", "@token", "=", "session", ".", "to_s", "end" ]
Fill out the session cookie appropriately for this attachment.
[ "Fill", "out", "the", "session", "cookie", "appropriately", "for", "this", "attachment", "." ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/core_payload_types/right_script_attachment.rb#L68-L78
train
rightscale/right_agent
lib/right_agent/command/command_parser.rb
RightScale.CommandParser.parse_chunk
def parse_chunk(chunk) @buildup << chunk chunks = @buildup.split(CommandSerializer::SEPARATOR, -1) if (do_call = chunks.size > 1) commands = [] (0..chunks.size - 2).each do |i| begin commands << CommandSerializer.load(chunks[i]) rescue StandardError => e # log any exceptions caused by serializing individual chunks instead # of halting EM. each command is discrete so we need to keep trying # so long as there are more commands to process (although subsequent # commands may lack context if previous commands failed). Log.error("Failed parsing command chunk", e, :trace) end end commands.each do |cmd| EM.next_tick do begin @callback.call(cmd) rescue Exception => e # log any exceptions raised by callback instead of halting EM. Log.error("Failed executing parsed command", e, :trace) end end end @buildup = chunks.last end do_call rescue StandardError => e # log any other exceptions instead of halting EM. Log.error("Failed parsing command chunk", e, :trace) end
ruby
def parse_chunk(chunk) @buildup << chunk chunks = @buildup.split(CommandSerializer::SEPARATOR, -1) if (do_call = chunks.size > 1) commands = [] (0..chunks.size - 2).each do |i| begin commands << CommandSerializer.load(chunks[i]) rescue StandardError => e # log any exceptions caused by serializing individual chunks instead # of halting EM. each command is discrete so we need to keep trying # so long as there are more commands to process (although subsequent # commands may lack context if previous commands failed). Log.error("Failed parsing command chunk", e, :trace) end end commands.each do |cmd| EM.next_tick do begin @callback.call(cmd) rescue Exception => e # log any exceptions raised by callback instead of halting EM. Log.error("Failed executing parsed command", e, :trace) end end end @buildup = chunks.last end do_call rescue StandardError => e # log any other exceptions instead of halting EM. Log.error("Failed parsing command chunk", e, :trace) end
[ "def", "parse_chunk", "(", "chunk", ")", "@buildup", "<<", "chunk", "chunks", "=", "@buildup", ".", "split", "(", "CommandSerializer", "::", "SEPARATOR", ",", "-", "1", ")", "if", "(", "do_call", "=", "chunks", ".", "size", ">", "1", ")", "commands", "=", "[", "]", "(", "0", "..", "chunks", ".", "size", "-", "2", ")", ".", "each", "do", "|", "i", "|", "begin", "commands", "<<", "CommandSerializer", ".", "load", "(", "chunks", "[", "i", "]", ")", "rescue", "StandardError", "=>", "e", "Log", ".", "error", "(", "\"Failed parsing command chunk\"", ",", "e", ",", ":trace", ")", "end", "end", "commands", ".", "each", "do", "|", "cmd", "|", "EM", ".", "next_tick", "do", "begin", "@callback", ".", "call", "(", "cmd", ")", "rescue", "Exception", "=>", "e", "Log", ".", "error", "(", "\"Failed executing parsed command\"", ",", "e", ",", ":trace", ")", "end", "end", "end", "@buildup", "=", "chunks", ".", "last", "end", "do_call", "rescue", "StandardError", "=>", "e", "Log", ".", "error", "(", "\"Failed parsing command chunk\"", ",", "e", ",", ":trace", ")", "end" ]
Register callback block === Block Block that will get called back whenever a command is successfully parsed === Raise (ArgumentError): If block is missing Parse given input May cause multiple callbacks if multiple commands are successfully parsed Callback happens in next EM tick === Parameters chunk(String):: Chunck of serialized command(s) to be parsed === Return true:: If callback was called at least once false:: Otherwise
[ "Register", "callback", "block" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/command/command_parser.rb#L51-L83
train
rightscale/right_agent
spec/spec_helper.rb
RightScale.SpecHelper.issue_cert
def issue_cert test_dn = { 'C' => 'US', 'ST' => 'California', 'L' => 'Santa Barbara', 'O' => 'Agent', 'OU' => 'Certification Services', 'CN' => 'Agent test' } dn = DistinguishedName.new(test_dn) key = RsaKeyPair.new [ Certificate.new(key, dn, dn), key ] end
ruby
def issue_cert test_dn = { 'C' => 'US', 'ST' => 'California', 'L' => 'Santa Barbara', 'O' => 'Agent', 'OU' => 'Certification Services', 'CN' => 'Agent test' } dn = DistinguishedName.new(test_dn) key = RsaKeyPair.new [ Certificate.new(key, dn, dn), key ] end
[ "def", "issue_cert", "test_dn", "=", "{", "'C'", "=>", "'US'", ",", "'ST'", "=>", "'California'", ",", "'L'", "=>", "'Santa Barbara'", ",", "'O'", "=>", "'Agent'", ",", "'OU'", "=>", "'Certification Services'", ",", "'CN'", "=>", "'Agent test'", "}", "dn", "=", "DistinguishedName", ".", "new", "(", "test_dn", ")", "key", "=", "RsaKeyPair", ".", "new", "[", "Certificate", ".", "new", "(", "key", ",", "dn", ",", "dn", ")", ",", "key", "]", "end" ]
Create test certificate
[ "Create", "test", "certificate" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/spec/spec_helper.rb#L57-L67
train
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.dispatch
def dispatch(request) token = request.token actor, method, idempotent = route(request) received_at = @request_stats.update(method, (token if request.is_a?(Request))) if (dup = duplicate?(request, method, idempotent)) raise DuplicateRequest, dup end unless (result = expired?(request, method)) result = perform(request, actor, method, idempotent) end if request.is_a?(Request) duration = @request_stats.finish(received_at, token) Result.new(token, request.reply_to, result, @identity, request.from, request.tries, request.persistent, duration) end end
ruby
def dispatch(request) token = request.token actor, method, idempotent = route(request) received_at = @request_stats.update(method, (token if request.is_a?(Request))) if (dup = duplicate?(request, method, idempotent)) raise DuplicateRequest, dup end unless (result = expired?(request, method)) result = perform(request, actor, method, idempotent) end if request.is_a?(Request) duration = @request_stats.finish(received_at, token) Result.new(token, request.reply_to, result, @identity, request.from, request.tries, request.persistent, duration) end end
[ "def", "dispatch", "(", "request", ")", "token", "=", "request", ".", "token", "actor", ",", "method", ",", "idempotent", "=", "route", "(", "request", ")", "received_at", "=", "@request_stats", ".", "update", "(", "method", ",", "(", "token", "if", "request", ".", "is_a?", "(", "Request", ")", ")", ")", "if", "(", "dup", "=", "duplicate?", "(", "request", ",", "method", ",", "idempotent", ")", ")", "raise", "DuplicateRequest", ",", "dup", "end", "unless", "(", "result", "=", "expired?", "(", "request", ",", "method", ")", ")", "result", "=", "perform", "(", "request", ",", "actor", ",", "method", ",", "idempotent", ")", "end", "if", "request", ".", "is_a?", "(", "Request", ")", "duration", "=", "@request_stats", ".", "finish", "(", "received_at", ",", "token", ")", "Result", ".", "new", "(", "token", ",", "request", ".", "reply_to", ",", "result", ",", "@identity", ",", "request", ".", "from", ",", "request", ".", "tries", ",", "request", ".", "persistent", ",", "duration", ")", "end", "end" ]
Route request to appropriate actor for servicing Reject requests whose TTL has expired or that are duplicates of work already dispatched === Parameters request(Request|Push):: Packet containing request header(AMQP::Frame::Header|nil):: Request header containing ack control === Return (Result|nil):: Result of request, or nil if there is no result because request is a Push === Raise InvalidRequestType:: If the request cannot be routed to an actor DuplicateRequest:: If request rejected because it has already been processed
[ "Route", "request", "to", "appropriate", "actor", "for", "servicing", "Reject", "requests", "whose", "TTL", "has", "expired", "or", "that", "are", "duplicates", "of", "work", "already", "dispatched" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L86-L100
train
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.stats
def stats(reset = false) stats = { "dispatched cache" => (@dispatched_cache.stats if @dispatched_cache), "dispatch failures" => @dispatch_failure_stats.all, "rejects" => @reject_stats.all, "requests" => @request_stats.all } reset_stats if reset stats end
ruby
def stats(reset = false) stats = { "dispatched cache" => (@dispatched_cache.stats if @dispatched_cache), "dispatch failures" => @dispatch_failure_stats.all, "rejects" => @reject_stats.all, "requests" => @request_stats.all } reset_stats if reset stats end
[ "def", "stats", "(", "reset", "=", "false", ")", "stats", "=", "{", "\"dispatched cache\"", "=>", "(", "@dispatched_cache", ".", "stats", "if", "@dispatched_cache", ")", ",", "\"dispatch failures\"", "=>", "@dispatch_failure_stats", ".", "all", ",", "\"rejects\"", "=>", "@reject_stats", ".", "all", ",", "\"requests\"", "=>", "@request_stats", ".", "all", "}", "reset_stats", "if", "reset", "stats", "end" ]
Get dispatcher statistics === Parameters reset(Boolean):: Whether to reset the statistics after getting the current ones === Return stats(Hash):: Current statistics: "dispatched cache"(Hash|nil):: Number of dispatched requests cached and age of youngest and oldest, or nil if empty "dispatch failures"(Hash|nil):: Dispatch failure activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per failure type, or nil if none "rejects"(Hash|nil):: Request reject activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per reason ("duplicate (<method>)", "retry duplicate (<method>)", or "stale (<method>)"), or nil if none "requests"(Hash|nil):: Request activity stats with keys "total", "percent", "last", and "rate" with percentage breakdown per request type, or nil if none
[ "Get", "dispatcher", "statistics" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L118-L127
train
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.expired?
def expired?(request, method) if (expires_at = request.expires_at) && expires_at > 0 && (now = Time.now.to_i) >= expires_at @reject_stats.update("expired (#{method})") Log.info("REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago") # For agents that do not know about non-delivery, use error result if can_handle_non_delivery_result?(request.recv_version) OperationResult.non_delivery(OperationResult::TTL_EXPIRATION) else OperationResult.error("Could not deliver request (#{OperationResult::TTL_EXPIRATION})") end end end
ruby
def expired?(request, method) if (expires_at = request.expires_at) && expires_at > 0 && (now = Time.now.to_i) >= expires_at @reject_stats.update("expired (#{method})") Log.info("REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago") # For agents that do not know about non-delivery, use error result if can_handle_non_delivery_result?(request.recv_version) OperationResult.non_delivery(OperationResult::TTL_EXPIRATION) else OperationResult.error("Could not deliver request (#{OperationResult::TTL_EXPIRATION})") end end end
[ "def", "expired?", "(", "request", ",", "method", ")", "if", "(", "expires_at", "=", "request", ".", "expires_at", ")", "&&", "expires_at", ">", "0", "&&", "(", "now", "=", "Time", ".", "now", ".", "to_i", ")", ">=", "expires_at", "@reject_stats", ".", "update", "(", "\"expired (#{method})\"", ")", "Log", ".", "info", "(", "\"REJECT EXPIRED <#{request.token}> from #{request.from} TTL #{RightSupport::Stats.elapsed(now - expires_at)} ago\"", ")", "if", "can_handle_non_delivery_result?", "(", "request", ".", "recv_version", ")", "OperationResult", ".", "non_delivery", "(", "OperationResult", "::", "TTL_EXPIRATION", ")", "else", "OperationResult", ".", "error", "(", "\"Could not deliver request (#{OperationResult::TTL_EXPIRATION})\"", ")", "end", "end", "end" ]
Determine if request TTL has expired === Parameters request(Push|Request):: Request to be checked method(String):: Actor method requested to be performed === Return (OperationResult|nil):: Error result if expired, otherwise nil
[ "Determine", "if", "request", "TTL", "has", "expired" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L150-L161
train
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.duplicate?
def duplicate?(request, method, idempotent) if !idempotent && @dispatched_cache if (serviced_by = @dispatched_cache.serviced_by(request.token)) from_retry = "" else from_retry = "retry " request.tries.each { |t| break if (serviced_by = @dispatched_cache.serviced_by(t)) } end if serviced_by @reject_stats.update("#{from_retry}duplicate (#{method})") msg = "<#{request.token}> already serviced by #{serviced_by == @identity ? 'self' : serviced_by}" Log.info("REJECT #{from_retry.upcase}DUP #{msg}") msg end end end
ruby
def duplicate?(request, method, idempotent) if !idempotent && @dispatched_cache if (serviced_by = @dispatched_cache.serviced_by(request.token)) from_retry = "" else from_retry = "retry " request.tries.each { |t| break if (serviced_by = @dispatched_cache.serviced_by(t)) } end if serviced_by @reject_stats.update("#{from_retry}duplicate (#{method})") msg = "<#{request.token}> already serviced by #{serviced_by == @identity ? 'self' : serviced_by}" Log.info("REJECT #{from_retry.upcase}DUP #{msg}") msg end end end
[ "def", "duplicate?", "(", "request", ",", "method", ",", "idempotent", ")", "if", "!", "idempotent", "&&", "@dispatched_cache", "if", "(", "serviced_by", "=", "@dispatched_cache", ".", "serviced_by", "(", "request", ".", "token", ")", ")", "from_retry", "=", "\"\"", "else", "from_retry", "=", "\"retry \"", "request", ".", "tries", ".", "each", "{", "|", "t", "|", "break", "if", "(", "serviced_by", "=", "@dispatched_cache", ".", "serviced_by", "(", "t", ")", ")", "}", "end", "if", "serviced_by", "@reject_stats", ".", "update", "(", "\"#{from_retry}duplicate (#{method})\"", ")", "msg", "=", "\"<#{request.token}> already serviced by #{serviced_by == @identity ? 'self' : serviced_by}\"", "Log", ".", "info", "(", "\"REJECT #{from_retry.upcase}DUP #{msg}\"", ")", "msg", "end", "end", "end" ]
Determine whether this request is a duplicate === Parameters request(Request|Push):: Packet containing request method(String):: Actor method requested to be performed idempotent(Boolean):: Whether this method is idempotent === Return (String|nil):: Messaging describing who already serviced request if it is a duplicate, otherwise nil
[ "Determine", "whether", "this", "request", "is", "a", "duplicate" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L172-L187
train
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.route
def route(request) prefix, method = request.type.split('/')[1..-1] method ||= :index method = method.to_sym actor = @registry.actor_for(prefix) if actor.nil? || !actor.respond_to?(method) raise InvalidRequestType, "Unknown actor or method for dispatching request <#{request.token}> of type #{request.type}" end [actor, method, actor.class.idempotent?(method)] end
ruby
def route(request) prefix, method = request.type.split('/')[1..-1] method ||= :index method = method.to_sym actor = @registry.actor_for(prefix) if actor.nil? || !actor.respond_to?(method) raise InvalidRequestType, "Unknown actor or method for dispatching request <#{request.token}> of type #{request.type}" end [actor, method, actor.class.idempotent?(method)] end
[ "def", "route", "(", "request", ")", "prefix", ",", "method", "=", "request", ".", "type", ".", "split", "(", "'/'", ")", "[", "1", "..", "-", "1", "]", "method", "||=", ":index", "method", "=", "method", ".", "to_sym", "actor", "=", "@registry", ".", "actor_for", "(", "prefix", ")", "if", "actor", ".", "nil?", "||", "!", "actor", ".", "respond_to?", "(", "method", ")", "raise", "InvalidRequestType", ",", "\"Unknown actor or method for dispatching request <#{request.token}> of type #{request.type}\"", "end", "[", "actor", ",", "method", ",", "actor", ".", "class", ".", "idempotent?", "(", "method", ")", "]", "end" ]
Use request type to route request to actor and an associated method === Parameters request(Push|Request):: Packet containing request === Return (Array):: Actor name, method name, and whether method is idempotent === Raise InvalidRequestType:: If the request cannot be routed to an actor
[ "Use", "request", "type", "to", "route", "request", "to", "actor", "and", "an", "associated", "method" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L199-L208
train
rightscale/right_agent
lib/right_agent/dispatcher.rb
RightScale.Dispatcher.perform
def perform(request, actor, method, idempotent) @dispatched_cache.store(request.token) if @dispatched_cache && !idempotent if actor.method(method).arity.abs == 1 actor.send(method, request.payload) else actor.send(method, request.payload, request) end rescue StandardError => e ErrorTracker.log(self, "Failed dispatching #{request.trace}", e, request) @dispatch_failure_stats.update("#{request.type}->#{e.class.name}") OperationResult.error("Could not handle #{request.type} request", e) end
ruby
def perform(request, actor, method, idempotent) @dispatched_cache.store(request.token) if @dispatched_cache && !idempotent if actor.method(method).arity.abs == 1 actor.send(method, request.payload) else actor.send(method, request.payload, request) end rescue StandardError => e ErrorTracker.log(self, "Failed dispatching #{request.trace}", e, request) @dispatch_failure_stats.update("#{request.type}->#{e.class.name}") OperationResult.error("Could not handle #{request.type} request", e) end
[ "def", "perform", "(", "request", ",", "actor", ",", "method", ",", "idempotent", ")", "@dispatched_cache", ".", "store", "(", "request", ".", "token", ")", "if", "@dispatched_cache", "&&", "!", "idempotent", "if", "actor", ".", "method", "(", "method", ")", ".", "arity", ".", "abs", "==", "1", "actor", ".", "send", "(", "method", ",", "request", ".", "payload", ")", "else", "actor", ".", "send", "(", "method", ",", "request", ".", "payload", ",", "request", ")", "end", "rescue", "StandardError", "=>", "e", "ErrorTracker", ".", "log", "(", "self", ",", "\"Failed dispatching #{request.trace}\"", ",", "e", ",", "request", ")", "@dispatch_failure_stats", ".", "update", "(", "\"#{request.type}->#{e.class.name}\"", ")", "OperationResult", ".", "error", "(", "\"Could not handle #{request.type} request\"", ",", "e", ")", "end" ]
Perform requested action === Parameters request(Push|Request):: Packet containing request token(String):: Unique identity token for request method(String):: Actor method requested to be performed idempotent(Boolean):: Whether this method is idempotent === Return (OperationResult):: Result from performing a request
[ "Perform", "requested", "action" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/dispatcher.rb#L220-L231
train
rightscale/right_agent
lib/right_agent/security/certificate.rb
RightScale.Certificate.save
def save(file) File.open(file, "w") do |f| f.write(@raw_cert.to_pem) end true end
ruby
def save(file) File.open(file, "w") do |f| f.write(@raw_cert.to_pem) end true end
[ "def", "save", "(", "file", ")", "File", ".", "open", "(", "file", ",", "\"w\"", ")", "do", "|", "f", "|", "f", ".", "write", "(", "@raw_cert", ".", "to_pem", ")", "end", "true", "end" ]
Save certificate to file in PEM format === Parameters file(String):: File path name === Return true:: Always return true
[ "Save", "certificate", "to", "file", "in", "PEM", "format" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/security/certificate.rb#L84-L89
train
rightscale/right_agent
lib/right_agent/history.rb
RightScale.History.load
def load events = [] File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history) events end
ruby
def load events = [] File.open(@history, "r") { |f| events = f.readlines.map { |l| JSON.legacy_load(l) } } if File.readable?(@history) events end
[ "def", "load", "events", "=", "[", "]", "File", ".", "open", "(", "@history", ",", "\"r\"", ")", "{", "|", "f", "|", "events", "=", "f", ".", "readlines", ".", "map", "{", "|", "l", "|", "JSON", ".", "legacy_load", "(", "l", ")", "}", "}", "if", "File", ".", "readable?", "(", "@history", ")", "events", "end" ]
Load events from history file === Return events(Array):: List of historical events with each being a hash of :time(Integer):: Time in seconds in Unix-epoch when event occurred :pid(Integer):: Process id of agent recording the event :event(Object):: Event object in the form String or {String => Object}, where String is the event name and Object is any associated JSON-encodable data
[ "Load", "events", "from", "history", "file" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/history.rb#L63-L67
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.map_request
def map_request(type, payload, options) verb, path = API_MAP[type] raise ArgumentError, "Unsupported request type: #{type}" if path.nil? actor, action = type.split("/")[1..-1] path, params, request_options = parameterize(actor, action, payload, path) if action == "query_tags" map_query_tags(verb, params, action, options.merge(request_options)) else map_response(make_request(verb, path, params, action, options.merge(request_options)), path) end end
ruby
def map_request(type, payload, options) verb, path = API_MAP[type] raise ArgumentError, "Unsupported request type: #{type}" if path.nil? actor, action = type.split("/")[1..-1] path, params, request_options = parameterize(actor, action, payload, path) if action == "query_tags" map_query_tags(verb, params, action, options.merge(request_options)) else map_response(make_request(verb, path, params, action, options.merge(request_options)), path) end end
[ "def", "map_request", "(", "type", ",", "payload", ",", "options", ")", "verb", ",", "path", "=", "API_MAP", "[", "type", "]", "raise", "ArgumentError", ",", "\"Unsupported request type: #{type}\"", "if", "path", ".", "nil?", "actor", ",", "action", "=", "type", ".", "split", "(", "\"/\"", ")", "[", "1", "..", "-", "1", "]", "path", ",", "params", ",", "request_options", "=", "parameterize", "(", "actor", ",", "action", ",", "payload", ",", "path", ")", "if", "action", "==", "\"query_tags\"", "map_query_tags", "(", "verb", ",", "params", ",", "action", ",", "options", ".", "merge", "(", "request_options", ")", ")", "else", "map_response", "(", "make_request", "(", "verb", ",", "path", ",", "params", ",", "action", ",", "options", ".", "merge", "(", "request_options", ")", ")", ",", "path", ")", "end", "end" ]
Convert request to RightApi form and then make request via HTTP @param [String] type of request as path specifying actor and action @param [Hash, NilClass] payload for request @option options [String] :request_uuid uniquely identifying this request @option options [Numeric] :time_to_live seconds before request expires and is to be ignored @return [Object, NilClass] response from request @raise [Exceptions::Unauthorized] authorization failed @raise [Exceptions::ConnectivityFailure] cannot connect to server, lost connection to it, or it is too busy to respond @raise [Exceptions::RetryableError] request failed but if retried may succeed @raise [Exceptions::Terminating] closing client and terminating service @raise [Exceptions::InternalServerError] internal error in server being accessed
[ "Convert", "request", "to", "RightApi", "form", "and", "then", "make", "request", "via", "HTTP" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L192-L202
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.map_response
def map_response(response, path) case path when "/audit_entries" # Convert returned audit entry href to audit ID response.sub!(/^.*\/api\/audit_entries\//, "") if response.is_a?(String) when "/tags/by_resource", "/tags/by_tag" # Extract tags for each instance resource from response array with members of form # {"actions" => [], "links" => [{"rel" => "resource", "href" => <href>}, ...]}, "tags" => [{"name" => <tag>}, ...] tags = {} if response response.each do |hash| r = {} hash["links"].each { |l| r[l["href"]] = {"tags" => []} if l["href"] =~ /instances/ } hash["tags"].each { |t| r.each_key { |k| r[k]["tags"] << t["name"] } } if r.any? tags.merge!(r) end end response = tags end response end
ruby
def map_response(response, path) case path when "/audit_entries" # Convert returned audit entry href to audit ID response.sub!(/^.*\/api\/audit_entries\//, "") if response.is_a?(String) when "/tags/by_resource", "/tags/by_tag" # Extract tags for each instance resource from response array with members of form # {"actions" => [], "links" => [{"rel" => "resource", "href" => <href>}, ...]}, "tags" => [{"name" => <tag>}, ...] tags = {} if response response.each do |hash| r = {} hash["links"].each { |l| r[l["href"]] = {"tags" => []} if l["href"] =~ /instances/ } hash["tags"].each { |t| r.each_key { |k| r[k]["tags"] << t["name"] } } if r.any? tags.merge!(r) end end response = tags end response end
[ "def", "map_response", "(", "response", ",", "path", ")", "case", "path", "when", "\"/audit_entries\"", "response", ".", "sub!", "(", "/", "\\/", "\\/", "\\/", "/", ",", "\"\"", ")", "if", "response", ".", "is_a?", "(", "String", ")", "when", "\"/tags/by_resource\"", ",", "\"/tags/by_tag\"", "tags", "=", "{", "}", "if", "response", "response", ".", "each", "do", "|", "hash", "|", "r", "=", "{", "}", "hash", "[", "\"links\"", "]", ".", "each", "{", "|", "l", "|", "r", "[", "l", "[", "\"href\"", "]", "]", "=", "{", "\"tags\"", "=>", "[", "]", "}", "if", "l", "[", "\"href\"", "]", "=~", "/", "/", "}", "hash", "[", "\"tags\"", "]", ".", "each", "{", "|", "t", "|", "r", ".", "each_key", "{", "|", "k", "|", "r", "[", "k", "]", "[", "\"tags\"", "]", "<<", "t", "[", "\"name\"", "]", "}", "}", "if", "r", ".", "any?", "tags", ".", "merge!", "(", "r", ")", "end", "end", "response", "=", "tags", "end", "response", "end" ]
Convert response from request into required form where necessary @param [Object] response received @param [String] path in URI for desired resource @return [Object] converted response
[ "Convert", "response", "from", "request", "into", "required", "form", "where", "necessary" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L210-L230
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.map_query_tags
def map_query_tags(verb, params, action, options) response = {} hrefs = params[:resource_hrefs] || [] hrefs.concat(query_by_tag(verb, params[:tags], action, options)) if params[:tags] response = query_by_resource(verb, hrefs, action, options) if hrefs.any? response end
ruby
def map_query_tags(verb, params, action, options) response = {} hrefs = params[:resource_hrefs] || [] hrefs.concat(query_by_tag(verb, params[:tags], action, options)) if params[:tags] response = query_by_resource(verb, hrefs, action, options) if hrefs.any? response end
[ "def", "map_query_tags", "(", "verb", ",", "params", ",", "action", ",", "options", ")", "response", "=", "{", "}", "hrefs", "=", "params", "[", ":resource_hrefs", "]", "||", "[", "]", "hrefs", ".", "concat", "(", "query_by_tag", "(", "verb", ",", "params", "[", ":tags", "]", ",", "action", ",", "options", ")", ")", "if", "params", "[", ":tags", "]", "response", "=", "query_by_resource", "(", "verb", ",", "hrefs", ",", "action", ",", "options", ")", "if", "hrefs", ".", "any?", "response", "end" ]
Convert tag query request into one or more API requests and then convert responses Currently only retrieving "instances" resources @param [Symbol] verb for HTTP REST request @param [Hash] params for HTTP request @param [String] action from request type @param [Hash] options augmenting or overriding default options for HTTP request @return [Hash] tags retrieved with resource href as key and tags array as value
[ "Convert", "tag", "query", "request", "into", "one", "or", "more", "API", "requests", "and", "then", "convert", "responses", "Currently", "only", "retrieving", "instances", "resources" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L241-L247
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.query_by_tag
def query_by_tag(verb, tags, action, options) path = "/tags/by_tag" params = {:tags => tags, :match_all => false, :resource_type => "instances"} map_response(make_request(verb, path, params, action, options), path).keys end
ruby
def query_by_tag(verb, tags, action, options) path = "/tags/by_tag" params = {:tags => tags, :match_all => false, :resource_type => "instances"} map_response(make_request(verb, path, params, action, options), path).keys end
[ "def", "query_by_tag", "(", "verb", ",", "tags", ",", "action", ",", "options", ")", "path", "=", "\"/tags/by_tag\"", "params", "=", "{", ":tags", "=>", "tags", ",", ":match_all", "=>", "false", ",", ":resource_type", "=>", "\"instances\"", "}", "map_response", "(", "make_request", "(", "verb", ",", "path", ",", "params", ",", "action", ",", "options", ")", ",", "path", ")", ".", "keys", "end" ]
Query API for resources with specified tags @param [Symbol] verb for HTTP REST request @param [Array] tags that all resources retrieved must have @param [String] action from request type @param [Hash] options augmenting or overriding default options for HTTP request @return [Array] resource hrefs
[ "Query", "API", "for", "resources", "with", "specified", "tags" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L257-L261
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.query_by_resource
def query_by_resource(verb, hrefs, action, options) path = "/tags/by_resource" params = {:resource_hrefs => hrefs} map_response(make_request(verb, path, params, action, options), path) end
ruby
def query_by_resource(verb, hrefs, action, options) path = "/tags/by_resource" params = {:resource_hrefs => hrefs} map_response(make_request(verb, path, params, action, options), path) end
[ "def", "query_by_resource", "(", "verb", ",", "hrefs", ",", "action", ",", "options", ")", "path", "=", "\"/tags/by_resource\"", "params", "=", "{", ":resource_hrefs", "=>", "hrefs", "}", "map_response", "(", "make_request", "(", "verb", ",", "path", ",", "params", ",", "action", ",", "options", ")", ",", "path", ")", "end" ]
Query API for tags associated with a set of resources @param [Symbol] verb for HTTP REST request @param [Array] hrefs for resources whose tags are to be retrieved @param [String] action from request type @param [Hash] options augmenting or overriding default options for HTTP request @return [Hash] tags retrieved with resource href as key and tags array as value
[ "Query", "API", "for", "tags", "associated", "with", "a", "set", "of", "resources" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L271-L275
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.parameterize
def parameterize(actor, action, payload, path) options = {} params = {} if actor == "auditor" path = path.sub(/:id/, payload[:audit_id].to_s || "") params = parameterize_audit(action, payload) options = {:filter_params => AUDIT_FILTER_PARAMS} elsif actor == "router" && action =~ /_tags/ if action != "query_tags" params[:resource_hrefs] = [@self_href] else params[:resource_hrefs] = Array(payload[:hrefs]).flatten.compact if payload[:hrefs] end params[:tags] = Array(payload[:tags]).flatten.compact if payload[:tags] else # Can remove :agent_identity here since now carried in the authorization as the :agent payload.each { |k, v| params[k.to_sym] = v if k.to_sym != :agent_identity } if payload.is_a?(Hash) end [path, params, options] end
ruby
def parameterize(actor, action, payload, path) options = {} params = {} if actor == "auditor" path = path.sub(/:id/, payload[:audit_id].to_s || "") params = parameterize_audit(action, payload) options = {:filter_params => AUDIT_FILTER_PARAMS} elsif actor == "router" && action =~ /_tags/ if action != "query_tags" params[:resource_hrefs] = [@self_href] else params[:resource_hrefs] = Array(payload[:hrefs]).flatten.compact if payload[:hrefs] end params[:tags] = Array(payload[:tags]).flatten.compact if payload[:tags] else # Can remove :agent_identity here since now carried in the authorization as the :agent payload.each { |k, v| params[k.to_sym] = v if k.to_sym != :agent_identity } if payload.is_a?(Hash) end [path, params, options] end
[ "def", "parameterize", "(", "actor", ",", "action", ",", "payload", ",", "path", ")", "options", "=", "{", "}", "params", "=", "{", "}", "if", "actor", "==", "\"auditor\"", "path", "=", "path", ".", "sub", "(", "/", "/", ",", "payload", "[", ":audit_id", "]", ".", "to_s", "||", "\"\"", ")", "params", "=", "parameterize_audit", "(", "action", ",", "payload", ")", "options", "=", "{", ":filter_params", "=>", "AUDIT_FILTER_PARAMS", "}", "elsif", "actor", "==", "\"router\"", "&&", "action", "=~", "/", "/", "if", "action", "!=", "\"query_tags\"", "params", "[", ":resource_hrefs", "]", "=", "[", "@self_href", "]", "else", "params", "[", ":resource_hrefs", "]", "=", "Array", "(", "payload", "[", ":hrefs", "]", ")", ".", "flatten", ".", "compact", "if", "payload", "[", ":hrefs", "]", "end", "params", "[", ":tags", "]", "=", "Array", "(", "payload", "[", ":tags", "]", ")", ".", "flatten", ".", "compact", "if", "payload", "[", ":tags", "]", "else", "payload", ".", "each", "{", "|", "k", ",", "v", "|", "params", "[", "k", ".", "to_sym", "]", "=", "v", "if", "k", ".", "to_sym", "!=", ":agent_identity", "}", "if", "payload", ".", "is_a?", "(", "Hash", ")", "end", "[", "path", ",", "params", ",", "options", "]", "end" ]
Convert payload to HTTP parameters @param [String] actor from request type @param [String] action from request type @param [Hash, NilClass] payload for request @param [String] path in URI for desired resource @return [Array] path string and parameters and options hashes
[ "Convert", "payload", "to", "HTTP", "parameters" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L285-L304
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.parameterize_audit
def parameterize_audit(action, payload) params = {} summary = non_blank(payload[:summary]) detail = non_blank(payload[:detail]) case action when "create_entry" params[:audit_entry] = {:auditee_href => @self_href} params[:audit_entry][:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) if summary params[:audit_entry][:detail] = detail if detail if (user_email = non_blank(payload[:user_email])) params[:user_email] = user_email end params[:notify] = payload[:category] if payload[:category] when "update_entry" params[:offset] = payload[:offset] if payload[:offset] if summary params[:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) params[:notify] = payload[:category] if payload[:category] end params[:detail] = detail if detail else raise ArgumentError, "Unknown audit request action: #{action}" end params end
ruby
def parameterize_audit(action, payload) params = {} summary = non_blank(payload[:summary]) detail = non_blank(payload[:detail]) case action when "create_entry" params[:audit_entry] = {:auditee_href => @self_href} params[:audit_entry][:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) if summary params[:audit_entry][:detail] = detail if detail if (user_email = non_blank(payload[:user_email])) params[:user_email] = user_email end params[:notify] = payload[:category] if payload[:category] when "update_entry" params[:offset] = payload[:offset] if payload[:offset] if summary params[:summary] = truncate(summary, MAX_AUDIT_SUMMARY_LENGTH) params[:notify] = payload[:category] if payload[:category] end params[:detail] = detail if detail else raise ArgumentError, "Unknown audit request action: #{action}" end params end
[ "def", "parameterize_audit", "(", "action", ",", "payload", ")", "params", "=", "{", "}", "summary", "=", "non_blank", "(", "payload", "[", ":summary", "]", ")", "detail", "=", "non_blank", "(", "payload", "[", ":detail", "]", ")", "case", "action", "when", "\"create_entry\"", "params", "[", ":audit_entry", "]", "=", "{", ":auditee_href", "=>", "@self_href", "}", "params", "[", ":audit_entry", "]", "[", ":summary", "]", "=", "truncate", "(", "summary", ",", "MAX_AUDIT_SUMMARY_LENGTH", ")", "if", "summary", "params", "[", ":audit_entry", "]", "[", ":detail", "]", "=", "detail", "if", "detail", "if", "(", "user_email", "=", "non_blank", "(", "payload", "[", ":user_email", "]", ")", ")", "params", "[", ":user_email", "]", "=", "user_email", "end", "params", "[", ":notify", "]", "=", "payload", "[", ":category", "]", "if", "payload", "[", ":category", "]", "when", "\"update_entry\"", "params", "[", ":offset", "]", "=", "payload", "[", ":offset", "]", "if", "payload", "[", ":offset", "]", "if", "summary", "params", "[", ":summary", "]", "=", "truncate", "(", "summary", ",", "MAX_AUDIT_SUMMARY_LENGTH", ")", "params", "[", ":notify", "]", "=", "payload", "[", ":category", "]", "if", "payload", "[", ":category", "]", "end", "params", "[", ":detail", "]", "=", "detail", "if", "detail", "else", "raise", "ArgumentError", ",", "\"Unknown audit request action: #{action}\"", "end", "params", "end" ]
Translate audit request payload to HTTP parameters Truncate audit summary to MAX_AUDIT_SUMMARY_LENGTH, the limit imposed by RightApi @param [String] action requested: create_entry or update_entry @param [Hash] payload from submitted request @return [Hash] HTTP request parameters @raise [ArgumentError] unknown request action
[ "Translate", "audit", "request", "payload", "to", "HTTP", "parameters", "Truncate", "audit", "summary", "to", "MAX_AUDIT_SUMMARY_LENGTH", "the", "limit", "imposed", "by", "RightApi" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L315-L339
train
rightscale/right_agent
lib/right_agent/clients/api_client.rb
RightScale.ApiClient.truncate
def truncate(value, max_length) raise ArgumentError, "max_length must be greater than 3" if max_length <= 3 if value.is_a?(String) && value.bytesize > max_length max_truncated = max_length - 3 truncated = value[0, max_truncated] while truncated.bytesize > max_truncated do truncated.chop! end truncated + "..." else value end end
ruby
def truncate(value, max_length) raise ArgumentError, "max_length must be greater than 3" if max_length <= 3 if value.is_a?(String) && value.bytesize > max_length max_truncated = max_length - 3 truncated = value[0, max_truncated] while truncated.bytesize > max_truncated do truncated.chop! end truncated + "..." else value end end
[ "def", "truncate", "(", "value", ",", "max_length", ")", "raise", "ArgumentError", ",", "\"max_length must be greater than 3\"", "if", "max_length", "<=", "3", "if", "value", ".", "is_a?", "(", "String", ")", "&&", "value", ".", "bytesize", ">", "max_length", "max_truncated", "=", "max_length", "-", "3", "truncated", "=", "value", "[", "0", ",", "max_truncated", "]", "while", "truncated", ".", "bytesize", ">", "max_truncated", "do", "truncated", ".", "chop!", "end", "truncated", "+", "\"...\"", "else", "value", "end", "end" ]
Truncate string if it exceeds maximum length Do length check with bytesize rather than size since this method is only intended for use with ruby 1.9 and above, otherwise multi-byte characters could cause this code to be too lenient @param [String, NilClass] value to be truncated @param [Integer] max_length allowed; must be greater than 3 @return [String, NilClass] truncated string or original value if it is not a string @raise [ArgumentError] max_length too small
[ "Truncate", "string", "if", "it", "exceeds", "maximum", "length", "Do", "length", "check", "with", "bytesize", "rather", "than", "size", "since", "this", "method", "is", "only", "intended", "for", "use", "with", "ruby", "1", ".", "9", "and", "above", "otherwise", "multi", "-", "byte", "characters", "could", "cause", "this", "code", "to", "be", "too", "lenient" ]
64c68c162692f0a70543d10def5e4bf56505bd82
https://github.com/rightscale/right_agent/blob/64c68c162692f0a70543d10def5e4bf56505bd82/lib/right_agent/clients/api_client.rb#L352-L364
train
KatanaCode/kirigami
lib/kirigami/image.rb
Kirigami.Image.cut!
def cut! create_backup_copy MiniMagick::Tool::Mogrify.new do |mogrify| mogrify.resize(max_size) mogrify.strip if jpeg? mogrify.colorspace(Kirigami.config.jpeg_colorspace) mogrify.sampling_factor(Kirigami.config.jpeg_sampling_factor) mogrify.interlace(Kirigami.config.jpeg_interlacing) mogrify.quality(Kirigami.config.jpeg_compression_quality) end mogrify << target_filepath end end
ruby
def cut! create_backup_copy MiniMagick::Tool::Mogrify.new do |mogrify| mogrify.resize(max_size) mogrify.strip if jpeg? mogrify.colorspace(Kirigami.config.jpeg_colorspace) mogrify.sampling_factor(Kirigami.config.jpeg_sampling_factor) mogrify.interlace(Kirigami.config.jpeg_interlacing) mogrify.quality(Kirigami.config.jpeg_compression_quality) end mogrify << target_filepath end end
[ "def", "cut!", "create_backup_copy", "MiniMagick", "::", "Tool", "::", "Mogrify", ".", "new", "do", "|", "mogrify", "|", "mogrify", ".", "resize", "(", "max_size", ")", "mogrify", ".", "strip", "if", "jpeg?", "mogrify", ".", "colorspace", "(", "Kirigami", ".", "config", ".", "jpeg_colorspace", ")", "mogrify", ".", "sampling_factor", "(", "Kirigami", ".", "config", ".", "jpeg_sampling_factor", ")", "mogrify", ".", "interlace", "(", "Kirigami", ".", "config", ".", "jpeg_interlacing", ")", "mogrify", ".", "quality", "(", "Kirigami", ".", "config", ".", "jpeg_compression_quality", ")", "end", "mogrify", "<<", "target_filepath", "end", "end" ]
Create a new Image max_size - An ImageSize to specify the size and name of image. Cuts the File down to size! Creates a backup copy first, if required.
[ "Create", "a", "new", "Image" ]
191b8756869b09ad5a9afd4f30fc3c07e8373318
https://github.com/KatanaCode/kirigami/blob/191b8756869b09ad5a9afd4f30fc3c07e8373318/lib/kirigami/image.rb#L28-L41
train
Phybbit/dataflow-rb
lib/dataflow/schema_mixin.rb
Dataflow.SchemaMixin.infer_schema
def infer_schema(samples_count: 0, extended: false) if db_backend == :postgresql # Experimental sch = db_adapter.client.schema(read_dataset_name).to_h sch = sch.reject{ |k, v| k == :_id }.map { |k,v| [k, {type: v[:type].to_s}] }.to_h self.inferred_schema = sch save return sch end data_count = samples_count == 0 ? count : samples_count # invoked in the base class return {} if data_count == 0 # find out how many batches are needed max_per_process = 1000 max_per_process = limit_per_process if respond_to?(:limit_per_process) && limit_per_process > 0 equal_split_per_process = (data_count / Parallel.processor_count.to_f).ceil count_per_process = [max_per_process, equal_split_per_process].min queries = ordered_system_id_queries(batch_size: count_per_process)[0...data_count] self.inferred_schema_at = Time.now self.inferred_schema_from = samples_count on_schema_inference_started sch = schema_inferrer.infer_schema(batch_count: queries.count, extended: extended) do |idx| progress = (idx / queries.count.to_f * 100).ceil on_schema_inference_progressed(pct_complete: progress) all(where: queries[idx]) end self.inferred_schema = sch save on_schema_inference_finished sch end
ruby
def infer_schema(samples_count: 0, extended: false) if db_backend == :postgresql # Experimental sch = db_adapter.client.schema(read_dataset_name).to_h sch = sch.reject{ |k, v| k == :_id }.map { |k,v| [k, {type: v[:type].to_s}] }.to_h self.inferred_schema = sch save return sch end data_count = samples_count == 0 ? count : samples_count # invoked in the base class return {} if data_count == 0 # find out how many batches are needed max_per_process = 1000 max_per_process = limit_per_process if respond_to?(:limit_per_process) && limit_per_process > 0 equal_split_per_process = (data_count / Parallel.processor_count.to_f).ceil count_per_process = [max_per_process, equal_split_per_process].min queries = ordered_system_id_queries(batch_size: count_per_process)[0...data_count] self.inferred_schema_at = Time.now self.inferred_schema_from = samples_count on_schema_inference_started sch = schema_inferrer.infer_schema(batch_count: queries.count, extended: extended) do |idx| progress = (idx / queries.count.to_f * 100).ceil on_schema_inference_progressed(pct_complete: progress) all(where: queries[idx]) end self.inferred_schema = sch save on_schema_inference_finished sch end
[ "def", "infer_schema", "(", "samples_count", ":", "0", ",", "extended", ":", "false", ")", "if", "db_backend", "==", ":postgresql", "sch", "=", "db_adapter", ".", "client", ".", "schema", "(", "read_dataset_name", ")", ".", "to_h", "sch", "=", "sch", ".", "reject", "{", "|", "k", ",", "v", "|", "k", "==", ":_id", "}", ".", "map", "{", "|", "k", ",", "v", "|", "[", "k", ",", "{", "type", ":", "v", "[", ":type", "]", ".", "to_s", "}", "]", "}", ".", "to_h", "self", ".", "inferred_schema", "=", "sch", "save", "return", "sch", "end", "data_count", "=", "samples_count", "==", "0", "?", "count", ":", "samples_count", "return", "{", "}", "if", "data_count", "==", "0", "max_per_process", "=", "1000", "max_per_process", "=", "limit_per_process", "if", "respond_to?", "(", ":limit_per_process", ")", "&&", "limit_per_process", ">", "0", "equal_split_per_process", "=", "(", "data_count", "/", "Parallel", ".", "processor_count", ".", "to_f", ")", ".", "ceil", "count_per_process", "=", "[", "max_per_process", ",", "equal_split_per_process", "]", ".", "min", "queries", "=", "ordered_system_id_queries", "(", "batch_size", ":", "count_per_process", ")", "[", "0", "...", "data_count", "]", "self", ".", "inferred_schema_at", "=", "Time", ".", "now", "self", ".", "inferred_schema_from", "=", "samples_count", "on_schema_inference_started", "sch", "=", "schema_inferrer", ".", "infer_schema", "(", "batch_count", ":", "queries", ".", "count", ",", "extended", ":", "extended", ")", "do", "|", "idx", "|", "progress", "=", "(", "idx", "/", "queries", ".", "count", ".", "to_f", "*", "100", ")", ".", "ceil", "on_schema_inference_progressed", "(", "pct_complete", ":", "progress", ")", "all", "(", "where", ":", "queries", "[", "idx", "]", ")", "end", "self", ".", "inferred_schema", "=", "sch", "save", "on_schema_inference_finished", "sch", "end" ]
if this change, update the regex that use the character directly in this mixin Generate a schema based on this collection's records. We evaluate the schema of each record and then merge all the information together. @param extended [Boolean] Set to true to keep each field as a basic type. Set to false to reduce the terminal arrays to a single key (under the type array). @return [Hash] with one entry per 'column'/'field'. The values contains information about the type and usage.
[ "if", "this", "change", "update", "the", "regex", "that", "use", "the", "character", "directly", "in", "this", "mixin", "Generate", "a", "schema", "based", "on", "this", "collection", "s", "records", ".", "We", "evaluate", "the", "schema", "of", "each", "record", "and", "then", "merge", "all", "the", "information", "together", "." ]
6cedf006983f6ed1c72ccff5104bd47de38dd4f3
https://github.com/Phybbit/dataflow-rb/blob/6cedf006983f6ed1c72ccff5104bd47de38dd4f3/lib/dataflow/schema_mixin.rb#L13-L51
train
mumuki/mumukit-assistant
lib/mumukit/assistant.rb
Mumukit.Assistant.assist_with
def assist_with(submission) @rules .select { |it| it.matches?(submission) } .map { |it| it.message_for(submission.attemps_count) } end
ruby
def assist_with(submission) @rules .select { |it| it.matches?(submission) } .map { |it| it.message_for(submission.attemps_count) } end
[ "def", "assist_with", "(", "submission", ")", "@rules", ".", "select", "{", "|", "it", "|", "it", ".", "matches?", "(", "submission", ")", "}", ".", "map", "{", "|", "it", "|", "it", ".", "message_for", "(", "submission", ".", "attemps_count", ")", "}", "end" ]
Provides tips for the student for the given submission, based on the `rules`.
[ "Provides", "tips", "for", "the", "student", "for", "the", "given", "submission", "based", "on", "the", "rules", "." ]
a776ec594a209f3d04fc918426297adf30504f25
https://github.com/mumuki/mumukit-assistant/blob/a776ec594a209f3d04fc918426297adf30504f25/lib/mumukit/assistant.rb#L21-L25
train
danielsdeleo/deep_merge
lib/deep_merge/rails_compat.rb
DeepMerge.RailsCompat.ko_deeper_merge!
def ko_deeper_merge!(source, options = {}) default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false} DeepMerge::deep_merge!(source, self, default_opts.merge(options)) end
ruby
def ko_deeper_merge!(source, options = {}) default_opts = {:knockout_prefix => "--", :preserve_unmergeables => false} DeepMerge::deep_merge!(source, self, default_opts.merge(options)) end
[ "def", "ko_deeper_merge!", "(", "source", ",", "options", "=", "{", "}", ")", "default_opts", "=", "{", ":knockout_prefix", "=>", "\"--\"", ",", ":preserve_unmergeables", "=>", "false", "}", "DeepMerge", "::", "deep_merge!", "(", "source", ",", "self", ",", "default_opts", ".", "merge", "(", "options", ")", ")", "end" ]
ko_hash_merge! will merge and knockout elements prefixed with DEFAULT_FIELD_KNOCKOUT_PREFIX
[ "ko_hash_merge!", "will", "merge", "and", "knockout", "elements", "prefixed", "with", "DEFAULT_FIELD_KNOCKOUT_PREFIX" ]
9b15cc77c5954eebf67365d4f24ca44a9e2b2ca7
https://github.com/danielsdeleo/deep_merge/blob/9b15cc77c5954eebf67365d4f24ca44a9e2b2ca7/lib/deep_merge/rails_compat.rb#L6-L9
train
rails/activerecord-deprecated_finders
lib/active_record/deprecated_finders/base.rb
ActiveRecord.DeprecatedFinders.with_exclusive_scope
def with_exclusive_scope(method_scoping = {}, &block) if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } raise ArgumentError, <<-MSG New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: User.unscoped.where(:active => true) Or call unscoped with a block: User.unscoped do User.where(:active => true).all end MSG end with_scope(method_scoping, :overwrite, &block) end
ruby
def with_exclusive_scope(method_scoping = {}, &block) if method_scoping.values.any? { |e| e.is_a?(ActiveRecord::Relation) } raise ArgumentError, <<-MSG New finder API can not be used with_exclusive_scope. You can either call unscoped to get an anonymous scope not bound to the default_scope: User.unscoped.where(:active => true) Or call unscoped with a block: User.unscoped do User.where(:active => true).all end MSG end with_scope(method_scoping, :overwrite, &block) end
[ "def", "with_exclusive_scope", "(", "method_scoping", "=", "{", "}", ",", "&", "block", ")", "if", "method_scoping", ".", "values", ".", "any?", "{", "|", "e", "|", "e", ".", "is_a?", "(", "ActiveRecord", "::", "Relation", ")", "}", "raise", "ArgumentError", ",", "<<-MSG", "MSG", "end", "with_scope", "(", "method_scoping", ",", ":overwrite", ",", "&", "block", ")", "end" ]
Works like with_scope, but discards any nested properties.
[ "Works", "like", "with_scope", "but", "discards", "any", "nested", "properties", "." ]
041c83c9dce8e17b8e1216adfaff48cc9debac02
https://github.com/rails/activerecord-deprecated_finders/blob/041c83c9dce8e17b8e1216adfaff48cc9debac02/lib/active_record/deprecated_finders/base.rb#L124-L140
train
rdp/ruby_gnuplot
lib/gnuplot.rb
Gnuplot.Plot.set
def set ( var, value = "" ) value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/ @settings << [ :set, var, value ] end
ruby
def set ( var, value = "" ) value = "\"#{value}\"" if QUOTED.include? var unless value =~ /^'.*'$/ @settings << [ :set, var, value ] end
[ "def", "set", "(", "var", ",", "value", "=", "\"\"", ")", "value", "=", "\"\\\"#{value}\\\"\"", "if", "QUOTED", ".", "include?", "var", "unless", "value", "=~", "/", "/", "@settings", "<<", "[", ":set", ",", "var", ",", "value", "]", "end" ]
Set a variable to the given value. +Var+ must be a gnuplot variable and +value+ must be the value to set it to. Automatic quoting will be performed if the variable requires it. This is overloaded by the +method_missing+ method so see that for more readable code.
[ "Set", "a", "variable", "to", "the", "given", "value", ".", "+", "Var", "+", "must", "be", "a", "gnuplot", "variable", "and", "+", "value", "+", "must", "be", "the", "value", "to", "set", "it", "to", ".", "Automatic", "quoting", "will", "be", "performed", "if", "the", "variable", "requires", "it", "." ]
79eb51b46ae1a659292d3d4cc15c8a0e321a1c3e
https://github.com/rdp/ruby_gnuplot/blob/79eb51b46ae1a659292d3d4cc15c8a0e321a1c3e/lib/gnuplot.rb#L127-L130
train
potatosalad/ruby-jose
lib/jose/jwt.rb
JOSE.JWT.merge
def merge(object) object = case object when JOSE::Map, Hash object when String JOSE.decode(object) when JOSE::JWT object.to_map else raise ArgumentError, "'object' must be a Hash, String, or JOSE::JWT" end return JOSE::JWT.from_map(self.to_map.merge(object)) end
ruby
def merge(object) object = case object when JOSE::Map, Hash object when String JOSE.decode(object) when JOSE::JWT object.to_map else raise ArgumentError, "'object' must be a Hash, String, or JOSE::JWT" end return JOSE::JWT.from_map(self.to_map.merge(object)) end
[ "def", "merge", "(", "object", ")", "object", "=", "case", "object", "when", "JOSE", "::", "Map", ",", "Hash", "object", "when", "String", "JOSE", ".", "decode", "(", "object", ")", "when", "JOSE", "::", "JWT", "object", ".", "to_map", "else", "raise", "ArgumentError", ",", "\"'object' must be a Hash, String, or JOSE::JWT\"", "end", "return", "JOSE", "::", "JWT", ".", "from_map", "(", "self", ".", "to_map", ".", "merge", "(", "object", ")", ")", "end" ]
Merges object into current map. @param [JOSE::Map, Hash, String, JOSE::JWT] object @return [JOSE::JWT]
[ "Merges", "object", "into", "current", "map", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwt.rb#L243-L255
train
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.block_encrypt
def block_encrypt(plain_text, jwe = nil) jwe ||= block_encryptor return JOSE::JWE.block_encrypt(self, plain_text, jwe) end
ruby
def block_encrypt(plain_text, jwe = nil) jwe ||= block_encryptor return JOSE::JWE.block_encrypt(self, plain_text, jwe) end
[ "def", "block_encrypt", "(", "plain_text", ",", "jwe", "=", "nil", ")", "jwe", "||=", "block_encryptor", "return", "JOSE", "::", "JWE", ".", "block_encrypt", "(", "self", ",", "plain_text", ",", "jwe", ")", "end" ]
Encrypts the `plain_text` using the `jwk` and algorithms specified by the `jwe`. @see JOSE::JWE.block_encrypt @param [String] plain_text @param [JOSE::JWE] jwe @return [JOSE::EncryptedMap]
[ "Encrypts", "the", "plain_text", "using", "the", "jwk", "and", "algorithms", "specified", "by", "the", "jwe", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L644-L647
train
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.box_decrypt
def box_decrypt(encrypted, public_jwk = nil) if public_jwk return JOSE::JWE.block_decrypt([public_jwk, self], encrypted) else return JOSE::JWE.block_decrypt(self, encrypted) end end
ruby
def box_decrypt(encrypted, public_jwk = nil) if public_jwk return JOSE::JWE.block_decrypt([public_jwk, self], encrypted) else return JOSE::JWE.block_decrypt(self, encrypted) end end
[ "def", "box_decrypt", "(", "encrypted", ",", "public_jwk", "=", "nil", ")", "if", "public_jwk", "return", "JOSE", "::", "JWE", ".", "block_decrypt", "(", "[", "public_jwk", ",", "self", "]", ",", "encrypted", ")", "else", "return", "JOSE", "::", "JWE", ".", "block_decrypt", "(", "self", ",", "encrypted", ")", "end", "end" ]
Key Agreement decryption of the `encrypted` binary or map using `my_private_jwk`. @see JOSE::JWK.box_encrypt @see JOSE::JWE.block_decrypt @param [JOSE::EncryptedBinary, JOSE::EncryptedMap] encrypted @param [JOSE::JWK] public_jwk @return [[String, JOSE::JWE]]
[ "Key", "Agreement", "decryption", "of", "the", "encrypted", "binary", "or", "map", "using", "my_private_jwk", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L687-L693
train
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.box_encrypt
def box_encrypt(plain_text, jwk_secret = nil, jwe = nil) epk_secret = nil jwk_public = self if jwk_secret.nil? epk_secret = jwk_secret = jwk_public.generate_key end if not jwk_secret.is_a?(JOSE::JWK) jwk_secret = JOSE::JWK.from(jwk_secret) end if jwe.nil? jwe = jwk_public.block_encryptor end if jwe.is_a?(Hash) jwe = JOSE::Map.new(jwe) end if jwe.is_a?(JOSE::Map) if jwe['apu'].nil? jwe = jwe.put('apu', jwk_secret.fields['kid'] || jwk_secret.thumbprint) end if jwe['apv'].nil? jwe = jwe.put('apv', jwk_public.fields['kid'] || jwk_public.thumbprint) end if jwe['epk'].nil? jwe = jwe.put('epk', jwk_secret.to_public_map) end end if epk_secret return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe), epk_secret else return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe) end end
ruby
def box_encrypt(plain_text, jwk_secret = nil, jwe = nil) epk_secret = nil jwk_public = self if jwk_secret.nil? epk_secret = jwk_secret = jwk_public.generate_key end if not jwk_secret.is_a?(JOSE::JWK) jwk_secret = JOSE::JWK.from(jwk_secret) end if jwe.nil? jwe = jwk_public.block_encryptor end if jwe.is_a?(Hash) jwe = JOSE::Map.new(jwe) end if jwe.is_a?(JOSE::Map) if jwe['apu'].nil? jwe = jwe.put('apu', jwk_secret.fields['kid'] || jwk_secret.thumbprint) end if jwe['apv'].nil? jwe = jwe.put('apv', jwk_public.fields['kid'] || jwk_public.thumbprint) end if jwe['epk'].nil? jwe = jwe.put('epk', jwk_secret.to_public_map) end end if epk_secret return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe), epk_secret else return JOSE::JWE.block_encrypt([jwk_public, jwk_secret], plain_text, jwe) end end
[ "def", "box_encrypt", "(", "plain_text", ",", "jwk_secret", "=", "nil", ",", "jwe", "=", "nil", ")", "epk_secret", "=", "nil", "jwk_public", "=", "self", "if", "jwk_secret", ".", "nil?", "epk_secret", "=", "jwk_secret", "=", "jwk_public", ".", "generate_key", "end", "if", "not", "jwk_secret", ".", "is_a?", "(", "JOSE", "::", "JWK", ")", "jwk_secret", "=", "JOSE", "::", "JWK", ".", "from", "(", "jwk_secret", ")", "end", "if", "jwe", ".", "nil?", "jwe", "=", "jwk_public", ".", "block_encryptor", "end", "if", "jwe", ".", "is_a?", "(", "Hash", ")", "jwe", "=", "JOSE", "::", "Map", ".", "new", "(", "jwe", ")", "end", "if", "jwe", ".", "is_a?", "(", "JOSE", "::", "Map", ")", "if", "jwe", "[", "'apu'", "]", ".", "nil?", "jwe", "=", "jwe", ".", "put", "(", "'apu'", ",", "jwk_secret", ".", "fields", "[", "'kid'", "]", "||", "jwk_secret", ".", "thumbprint", ")", "end", "if", "jwe", "[", "'apv'", "]", ".", "nil?", "jwe", "=", "jwe", ".", "put", "(", "'apv'", ",", "jwk_public", ".", "fields", "[", "'kid'", "]", "||", "jwk_public", ".", "thumbprint", ")", "end", "if", "jwe", "[", "'epk'", "]", ".", "nil?", "jwe", "=", "jwe", ".", "put", "(", "'epk'", ",", "jwk_secret", ".", "to_public_map", ")", "end", "end", "if", "epk_secret", "return", "JOSE", "::", "JWE", ".", "block_encrypt", "(", "[", "jwk_public", ",", "jwk_secret", "]", ",", "plain_text", ",", "jwe", ")", ",", "epk_secret", "else", "return", "JOSE", "::", "JWE", ".", "block_encrypt", "(", "[", "jwk_public", ",", "jwk_secret", "]", ",", "plain_text", ",", "jwe", ")", "end", "end" ]
Key Agreement encryption of `plain_text` by generating an ephemeral private key based on `other_public_jwk` curve. If no private key has been specified in `my_private_key`, it generates an ephemeral private key based on other public key curve. @see JOSE::JWK.box_decrypt @see JOSE::JWE.block_encrypt @param [String] plain_text @param [JOSE::JWK] jwk_secret @param [JOSE::JWE] jwe @return [JOSE::EncryptedMap, [JOSE::EncryptedMap, JOSE::JWK]]
[ "Key", "Agreement", "encryption", "of", "plain_text", "by", "generating", "an", "ephemeral", "private", "key", "based", "on", "other_public_jwk", "curve", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L720-L751
train
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.shared_secret
def shared_secret(other_jwk) other_jwk = from(other_jwk) if not other_jwk.is_a?(JOSE::JWK) raise ArgumentError, "key types must match" if other_jwk.kty.class != kty.class raise ArgumentError, "key type does not support shared secret computations" if not kty.respond_to?(:derive_key) return kty.derive_key(other_jwk) end
ruby
def shared_secret(other_jwk) other_jwk = from(other_jwk) if not other_jwk.is_a?(JOSE::JWK) raise ArgumentError, "key types must match" if other_jwk.kty.class != kty.class raise ArgumentError, "key type does not support shared secret computations" if not kty.respond_to?(:derive_key) return kty.derive_key(other_jwk) end
[ "def", "shared_secret", "(", "other_jwk", ")", "other_jwk", "=", "from", "(", "other_jwk", ")", "if", "not", "other_jwk", ".", "is_a?", "(", "JOSE", "::", "JWK", ")", "raise", "ArgumentError", ",", "\"key types must match\"", "if", "other_jwk", ".", "kty", ".", "class", "!=", "kty", ".", "class", "raise", "ArgumentError", ",", "\"key type does not support shared secret computations\"", "if", "not", "kty", ".", "respond_to?", "(", ":derive_key", ")", "return", "kty", ".", "derive_key", "(", "other_jwk", ")", "end" ]
Computes the shared secret between two keys. Currently only works for `"EC"` keys and `"OKP"` keys with `"crv"` set to `"X25519"` or `"X448"`. @param [JOSE::JWK] other_jwk @return [String]
[ "Computes", "the", "shared", "secret", "between", "two", "keys", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L875-L880
train
potatosalad/ruby-jose
lib/jose/jwk.rb
JOSE.JWK.sign
def sign(plain_text, jws = nil, header = nil) jws ||= signer return JOSE::JWS.sign(self, plain_text, jws, header) end
ruby
def sign(plain_text, jws = nil, header = nil) jws ||= signer return JOSE::JWS.sign(self, plain_text, jws, header) end
[ "def", "sign", "(", "plain_text", ",", "jws", "=", "nil", ",", "header", "=", "nil", ")", "jws", "||=", "signer", "return", "JOSE", "::", "JWS", ".", "sign", "(", "self", ",", "plain_text", ",", "jws", ",", "header", ")", "end" ]
Signs the `plain_text` using the `jwk` and the default signer algorithm `jws` for the key type. @see JOSE::JWS.sign @param [String] plain_text @param [JOSE::JWS] jws @param [JOSE::Map] header @return [JOSE::SignedMap]
[ "Signs", "the", "plain_text", "using", "the", "jwk", "and", "the", "default", "signer", "algorithm", "jws", "for", "the", "key", "type", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwk.rb#L905-L908
train
potatosalad/ruby-jose
lib/jose/jws.rb
JOSE.JWS.sign
def sign(jwk, plain_text, header = nil) protected_binary = JOSE.urlsafe_encode64(to_binary) payload = JOSE.urlsafe_encode64(plain_text) signing_input = signing_input(plain_text, protected_binary) signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input)) return signature_to_map(payload, protected_binary, header, jwk, signature) end
ruby
def sign(jwk, plain_text, header = nil) protected_binary = JOSE.urlsafe_encode64(to_binary) payload = JOSE.urlsafe_encode64(plain_text) signing_input = signing_input(plain_text, protected_binary) signature = JOSE.urlsafe_encode64(alg.sign(jwk, signing_input)) return signature_to_map(payload, protected_binary, header, jwk, signature) end
[ "def", "sign", "(", "jwk", ",", "plain_text", ",", "header", "=", "nil", ")", "protected_binary", "=", "JOSE", ".", "urlsafe_encode64", "(", "to_binary", ")", "payload", "=", "JOSE", ".", "urlsafe_encode64", "(", "plain_text", ")", "signing_input", "=", "signing_input", "(", "plain_text", ",", "protected_binary", ")", "signature", "=", "JOSE", ".", "urlsafe_encode64", "(", "alg", ".", "sign", "(", "jwk", ",", "signing_input", ")", ")", "return", "signature_to_map", "(", "payload", ",", "protected_binary", ",", "header", ",", "jwk", ",", "signature", ")", "end" ]
Signs the `plain_text` using the `jwk` and algorithm specified by the `jws`. @see JOSE::JWS.sign @param [JOSE::JWK] jwk @param [String] plain_text @param [JOSE::Map, Hash] header @return [JOSE::SignedMap]
[ "Signs", "the", "plain_text", "using", "the", "jwk", "and", "algorithm", "specified", "by", "the", "jws", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jws.rb#L572-L578
train
potatosalad/ruby-jose
lib/jose/jws.rb
JOSE.JWS.verify
def verify(jwk, plain_text, signature, protected_binary = nil) protected_binary ||= JOSE.urlsafe_encode64(to_binary) signing_input = signing_input(plain_text, protected_binary) return alg.verify(jwk, signing_input, signature), plain_text, self end
ruby
def verify(jwk, plain_text, signature, protected_binary = nil) protected_binary ||= JOSE.urlsafe_encode64(to_binary) signing_input = signing_input(plain_text, protected_binary) return alg.verify(jwk, signing_input, signature), plain_text, self end
[ "def", "verify", "(", "jwk", ",", "plain_text", ",", "signature", ",", "protected_binary", "=", "nil", ")", "protected_binary", "||=", "JOSE", ".", "urlsafe_encode64", "(", "to_binary", ")", "signing_input", "=", "signing_input", "(", "plain_text", ",", "protected_binary", ")", "return", "alg", ".", "verify", "(", "jwk", ",", "signing_input", ",", "signature", ")", ",", "plain_text", ",", "self", "end" ]
Verifies the `signature` using the `jwk`, `plain_text`, and `protected_binary`. @see JOSE::JWS.verify @see JOSE::JWS.verify_strict @param [JOSE::JWK] jwk @param [String] plain_text @param [String] signature @param [String] protected_binary @return [[Boolean, String, JOSE::JWS]]
[ "Verifies", "the", "signature", "using", "the", "jwk", "plain_text", "and", "protected_binary", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jws.rb#L645-L649
train
potatosalad/ruby-jose
lib/jose/jwa.rb
JOSE.JWA.supports
def supports jwe_enc = __jwe_enc_support_check__([ 'A128GCM', 'A192GCM', 'A256GCM', 'A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512' ]) jwe_alg = __jwe_alg_support_check__([ ['A128GCMKW', :block], ['A192GCMKW', :block], ['A256GCMKW', :block], ['A128KW', :block], ['A192KW', :block], ['A256KW', :block], ['ECDH-ES', :box], ['ECDH-ES+A128KW', :box], ['ECDH-ES+A192KW', :box], ['ECDH-ES+A256KW', :box], ['PBES2-HS256+A128KW', :block], ['PBES2-HS384+A192KW', :block], ['PBES2-HS512+A256KW', :block], ['RSA1_5', :rsa], ['RSA-OAEP', :rsa], ['RSA-OAEP-256', :rsa], ['dir', :direct] ], jwe_enc) jwe_zip = __jwe_zip_support_check__([ 'DEF' ], jwe_enc) jwk_kty, jwk_kty_EC_crv, jwk_kty_OKP_crv = __jwk_kty_support_check__([ ['EC', ['P-256', 'P-384', 'P-521']], ['OKP', ['Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'X25519', 'X448']], 'RSA', 'oct' ]) jws_alg = __jws_alg_support_check__([ 'Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'EdDSA', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'X25519', 'X448', 'none' ]) return { jwe: { alg: jwe_alg, enc: jwe_enc, zip: jwe_zip }, jwk: { kty: jwk_kty, kty_EC_crv: jwk_kty_EC_crv, kty_OKP_crv: jwk_kty_OKP_crv }, jws: { alg: jws_alg } } end
ruby
def supports jwe_enc = __jwe_enc_support_check__([ 'A128GCM', 'A192GCM', 'A256GCM', 'A128CBC-HS256', 'A192CBC-HS384', 'A256CBC-HS512' ]) jwe_alg = __jwe_alg_support_check__([ ['A128GCMKW', :block], ['A192GCMKW', :block], ['A256GCMKW', :block], ['A128KW', :block], ['A192KW', :block], ['A256KW', :block], ['ECDH-ES', :box], ['ECDH-ES+A128KW', :box], ['ECDH-ES+A192KW', :box], ['ECDH-ES+A256KW', :box], ['PBES2-HS256+A128KW', :block], ['PBES2-HS384+A192KW', :block], ['PBES2-HS512+A256KW', :block], ['RSA1_5', :rsa], ['RSA-OAEP', :rsa], ['RSA-OAEP-256', :rsa], ['dir', :direct] ], jwe_enc) jwe_zip = __jwe_zip_support_check__([ 'DEF' ], jwe_enc) jwk_kty, jwk_kty_EC_crv, jwk_kty_OKP_crv = __jwk_kty_support_check__([ ['EC', ['P-256', 'P-384', 'P-521']], ['OKP', ['Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'X25519', 'X448']], 'RSA', 'oct' ]) jws_alg = __jws_alg_support_check__([ 'Ed25519', 'Ed25519ph', 'Ed448', 'Ed448ph', 'EdDSA', 'ES256', 'ES384', 'ES512', 'HS256', 'HS384', 'HS512', 'PS256', 'PS384', 'PS512', 'RS256', 'RS384', 'RS512', 'X25519', 'X448', 'none' ]) return { jwe: { alg: jwe_alg, enc: jwe_enc, zip: jwe_zip }, jwk: { kty: jwk_kty, kty_EC_crv: jwk_kty_EC_crv, kty_OKP_crv: jwk_kty_OKP_crv }, jws: { alg: jws_alg } } end
[ "def", "supports", "jwe_enc", "=", "__jwe_enc_support_check__", "(", "[", "'A128GCM'", ",", "'A192GCM'", ",", "'A256GCM'", ",", "'A128CBC-HS256'", ",", "'A192CBC-HS384'", ",", "'A256CBC-HS512'", "]", ")", "jwe_alg", "=", "__jwe_alg_support_check__", "(", "[", "[", "'A128GCMKW'", ",", ":block", "]", ",", "[", "'A192GCMKW'", ",", ":block", "]", ",", "[", "'A256GCMKW'", ",", ":block", "]", ",", "[", "'A128KW'", ",", ":block", "]", ",", "[", "'A192KW'", ",", ":block", "]", ",", "[", "'A256KW'", ",", ":block", "]", ",", "[", "'ECDH-ES'", ",", ":box", "]", ",", "[", "'ECDH-ES+A128KW'", ",", ":box", "]", ",", "[", "'ECDH-ES+A192KW'", ",", ":box", "]", ",", "[", "'ECDH-ES+A256KW'", ",", ":box", "]", ",", "[", "'PBES2-HS256+A128KW'", ",", ":block", "]", ",", "[", "'PBES2-HS384+A192KW'", ",", ":block", "]", ",", "[", "'PBES2-HS512+A256KW'", ",", ":block", "]", ",", "[", "'RSA1_5'", ",", ":rsa", "]", ",", "[", "'RSA-OAEP'", ",", ":rsa", "]", ",", "[", "'RSA-OAEP-256'", ",", ":rsa", "]", ",", "[", "'dir'", ",", ":direct", "]", "]", ",", "jwe_enc", ")", "jwe_zip", "=", "__jwe_zip_support_check__", "(", "[", "'DEF'", "]", ",", "jwe_enc", ")", "jwk_kty", ",", "jwk_kty_EC_crv", ",", "jwk_kty_OKP_crv", "=", "__jwk_kty_support_check__", "(", "[", "[", "'EC'", ",", "[", "'P-256'", ",", "'P-384'", ",", "'P-521'", "]", "]", ",", "[", "'OKP'", ",", "[", "'Ed25519'", ",", "'Ed25519ph'", ",", "'Ed448'", ",", "'Ed448ph'", ",", "'X25519'", ",", "'X448'", "]", "]", ",", "'RSA'", ",", "'oct'", "]", ")", "jws_alg", "=", "__jws_alg_support_check__", "(", "[", "'Ed25519'", ",", "'Ed25519ph'", ",", "'Ed448'", ",", "'Ed448ph'", ",", "'EdDSA'", ",", "'ES256'", ",", "'ES384'", ",", "'ES512'", ",", "'HS256'", ",", "'HS384'", ",", "'HS512'", ",", "'PS256'", ",", "'PS384'", ",", "'PS512'", ",", "'RS256'", ",", "'RS384'", ",", "'RS512'", ",", "'X25519'", ",", "'X448'", ",", "'none'", "]", ")", "return", "{", "jwe", ":", "{", "alg", ":", "jwe_alg", ",", "enc", ":", "jwe_enc", ",", "zip", ":", "jwe_zip", "}", ",", "jwk", ":", "{", "kty", ":", "jwk_kty", ",", "kty_EC_crv", ":", "jwk_kty_EC_crv", ",", "kty_OKP_crv", ":", "jwk_kty_OKP_crv", "}", ",", "jws", ":", "{", "alg", ":", "jws_alg", "}", "}", "end" ]
Returns the current listing of supported JOSE algorithms. !!!ruby JOSE::JWA.supports # => {:jwe=> # {:alg=> # ["A128GCMKW", # "A192GCMKW", # "A256GCMKW", # "A128KW", # "A192KW", # "A256KW", # "ECDH-ES", # "ECDH-ES+A128KW", # "ECDH-ES+A192KW", # "ECDH-ES+A256KW", # "PBES2-HS256+A128KW", # "PBES2-HS384+A192KW", # "PBES2-HS512+A256KW", # "RSA1_5", # "RSA-OAEP", # "RSA-OAEP-256", # "dir"], # :enc=> # ["A128GCM", # "A192GCM", # "A256GCM", # "A128CBC-HS256", # "A192CBC-HS384", # "A256CBC-HS512"], # :zip=> # ["DEF"]}, # :jwk=> # {:kty=> # ["EC", # "OKP", # "RSA", # "oct"], # :kty_EC_crv=> # ["P-256", # "P-384", # "P-521"], # :kty_OKP_crv=> # ["Ed25519", # "Ed25519ph", # "Ed448", # "Ed448ph", # "X25519", # "X448"]}, # :jws=> # {:alg=> # ["Ed25519", # "Ed25519ph", # "Ed448", # "Ed448ph", # "EdDSA", # "ES256", # "ES384", # "ES512", # "HS256", # "HS384", # "HS512", # "PS256", # "PS384", # "PS512", # "RS256", # "RS384", # "RS512", # "none"]}} @return [Hash]
[ "Returns", "the", "current", "listing", "of", "supported", "JOSE", "algorithms", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwa.rb#L123-L197
train
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.block_decrypt
def block_decrypt(key, aad, cipher_text, cipher_tag, encrypted_key, iv) cek = key_decrypt(key, encrypted_key) return uncompress(enc.block_decrypt([aad, cipher_text, cipher_tag], cek, iv)) end
ruby
def block_decrypt(key, aad, cipher_text, cipher_tag, encrypted_key, iv) cek = key_decrypt(key, encrypted_key) return uncompress(enc.block_decrypt([aad, cipher_text, cipher_tag], cek, iv)) end
[ "def", "block_decrypt", "(", "key", ",", "aad", ",", "cipher_text", ",", "cipher_tag", ",", "encrypted_key", ",", "iv", ")", "cek", "=", "key_decrypt", "(", "key", ",", "encrypted_key", ")", "return", "uncompress", "(", "enc", ".", "block_decrypt", "(", "[", "aad", ",", "cipher_text", ",", "cipher_tag", "]", ",", "cek", ",", "iv", ")", ")", "end" ]
Decrypts the `cipher_text` binary using the `key`, `aad`, `cipher_tag`, `encrypted_key`, and `iv`. @see JOSE::JWE.block_decrypt @param [JOSE::JWK, [JOSE::JWK, JOSE::JWK]] key @param [String] aad @param [String] cipher_text @param [String] cipher_tag @param [String] encrypted_key @param [String] iv @return [[String, JOSE::JWE]]
[ "Decrypts", "the", "cipher_text", "binary", "using", "the", "key", "aad", "cipher_tag", "encrypted_key", "and", "iv", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L600-L603
train
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.block_encrypt
def block_encrypt(key, block, cek = nil, iv = nil) jwe = self if cek.nil? cek, jwe = next_cek(key) end iv ||= jwe.next_iv aad, plain_text = block if plain_text.nil? plain_text = aad aad = nil end encrypted_key, jwe = jwe.key_encrypt(key, cek) protected_binary = JOSE.urlsafe_encode64(jwe.to_binary) if aad.nil? cipher_text, cipher_tag = enc.block_encrypt([protected_binary, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] else aad_b64 = JOSE.urlsafe_encode64(aad) concat_aad = [protected_binary, '.', aad_b64].join cipher_text, cipher_tag = enc.block_encrypt([concat_aad, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'aad' => aad_b64, 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] end end
ruby
def block_encrypt(key, block, cek = nil, iv = nil) jwe = self if cek.nil? cek, jwe = next_cek(key) end iv ||= jwe.next_iv aad, plain_text = block if plain_text.nil? plain_text = aad aad = nil end encrypted_key, jwe = jwe.key_encrypt(key, cek) protected_binary = JOSE.urlsafe_encode64(jwe.to_binary) if aad.nil? cipher_text, cipher_tag = enc.block_encrypt([protected_binary, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] else aad_b64 = JOSE.urlsafe_encode64(aad) concat_aad = [protected_binary, '.', aad_b64].join cipher_text, cipher_tag = enc.block_encrypt([concat_aad, jwe.compress(plain_text)], cek, iv) return JOSE::EncryptedMap[ 'aad' => aad_b64, 'ciphertext' => JOSE.urlsafe_encode64(cipher_text), 'encrypted_key' => JOSE.urlsafe_encode64(encrypted_key), 'iv' => JOSE.urlsafe_encode64(iv), 'protected' => protected_binary, 'tag' => JOSE.urlsafe_encode64(cipher_tag) ] end end
[ "def", "block_encrypt", "(", "key", ",", "block", ",", "cek", "=", "nil", ",", "iv", "=", "nil", ")", "jwe", "=", "self", "if", "cek", ".", "nil?", "cek", ",", "jwe", "=", "next_cek", "(", "key", ")", "end", "iv", "||=", "jwe", ".", "next_iv", "aad", ",", "plain_text", "=", "block", "if", "plain_text", ".", "nil?", "plain_text", "=", "aad", "aad", "=", "nil", "end", "encrypted_key", ",", "jwe", "=", "jwe", ".", "key_encrypt", "(", "key", ",", "cek", ")", "protected_binary", "=", "JOSE", ".", "urlsafe_encode64", "(", "jwe", ".", "to_binary", ")", "if", "aad", ".", "nil?", "cipher_text", ",", "cipher_tag", "=", "enc", ".", "block_encrypt", "(", "[", "protected_binary", ",", "jwe", ".", "compress", "(", "plain_text", ")", "]", ",", "cek", ",", "iv", ")", "return", "JOSE", "::", "EncryptedMap", "[", "'ciphertext'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_text", ")", ",", "'encrypted_key'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "encrypted_key", ")", ",", "'iv'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "iv", ")", ",", "'protected'", "=>", "protected_binary", ",", "'tag'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_tag", ")", "]", "else", "aad_b64", "=", "JOSE", ".", "urlsafe_encode64", "(", "aad", ")", "concat_aad", "=", "[", "protected_binary", ",", "'.'", ",", "aad_b64", "]", ".", "join", "cipher_text", ",", "cipher_tag", "=", "enc", ".", "block_encrypt", "(", "[", "concat_aad", ",", "jwe", ".", "compress", "(", "plain_text", ")", "]", ",", "cek", ",", "iv", ")", "return", "JOSE", "::", "EncryptedMap", "[", "'aad'", "=>", "aad_b64", ",", "'ciphertext'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_text", ")", ",", "'encrypted_key'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "encrypted_key", ")", ",", "'iv'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "iv", ")", ",", "'protected'", "=>", "protected_binary", ",", "'tag'", "=>", "JOSE", ".", "urlsafe_encode64", "(", "cipher_tag", ")", "]", "end", "end" ]
Encrypts the `block` binary using the `key`, `cek`, and `iv`. @see JOSE::JWE.block_encrypt @param [JOSE::JWK, [JOSE::JWK, JOSE::JWK]] key @param [String, [String, String]] block @param [String] cek @param [String] iv @return [JOSE::EncryptedMap]
[ "Encrypts", "the", "block", "binary", "using", "the", "key", "cek", "and", "iv", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L639-L674
train
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.key_encrypt
def key_encrypt(key, decrypted_key) encrypted_key, new_alg = alg.key_encrypt(key, enc, decrypted_key) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return encrypted_key, new_jwe end
ruby
def key_encrypt(key, decrypted_key) encrypted_key, new_alg = alg.key_encrypt(key, enc, decrypted_key) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return encrypted_key, new_jwe end
[ "def", "key_encrypt", "(", "key", ",", "decrypted_key", ")", "encrypted_key", ",", "new_alg", "=", "alg", ".", "key_encrypt", "(", "key", ",", "enc", ",", "decrypted_key", ")", "new_jwe", "=", "JOSE", "::", "JWE", ".", "from_map", "(", "to_map", ")", "new_jwe", ".", "alg", "=", "new_alg", "return", "encrypted_key", ",", "new_jwe", "end" ]
Encrypts the `decrypted_key` using the `key` and the `"alg"` and `"enc"` specified by the `jwe`. @param [JOSE::JWK, [JOSE::JWK]] key @param [String] decrypted_key @return [[String, JOSE::JWE]]
[ "Encrypts", "the", "decrypted_key", "using", "the", "key", "and", "the", "alg", "and", "enc", "specified", "by", "the", "jwe", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L865-L870
train
potatosalad/ruby-jose
lib/jose/jwe.rb
JOSE.JWE.next_cek
def next_cek(key) decrypted_key, new_alg = alg.next_cek(key, enc) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return decrypted_key, new_jwe end
ruby
def next_cek(key) decrypted_key, new_alg = alg.next_cek(key, enc) new_jwe = JOSE::JWE.from_map(to_map) new_jwe.alg = new_alg return decrypted_key, new_jwe end
[ "def", "next_cek", "(", "key", ")", "decrypted_key", ",", "new_alg", "=", "alg", ".", "next_cek", "(", "key", ",", "enc", ")", "new_jwe", "=", "JOSE", "::", "JWE", ".", "from_map", "(", "to_map", ")", "new_jwe", ".", "alg", "=", "new_alg", "return", "decrypted_key", ",", "new_jwe", "end" ]
Returns the next `cek` using the `jwk` and the `"alg"` and `"enc"` specified by the `jwe`. @param [JOSE::JWK, [JOSE::JWK, JOSE::JWK]] key @return [[String, JOSE::JWE]]
[ "Returns", "the", "next", "cek", "using", "the", "jwk", "and", "the", "alg", "and", "enc", "specified", "by", "the", "jwe", "." ]
e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0
https://github.com/potatosalad/ruby-jose/blob/e1be589b889f1e59ac233a5d19a3fa13f1e4b8a0/lib/jose/jwe.rb#L940-L945
train
tas50/stove
lib/stove/validator.rb
Stove.Validator.run
def run(cookbook, options = {}) log.info("Running validations for `#{klass.id}.#{id}'") inside(cookbook) do instance = klass.new(cookbook, options) unless result = instance.instance_eval(&block) log.debug("Validation failed, result: #{result.inspect}") # Convert the class and id to their magical equivalents error = Error.const_get("#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed") raise error.new(path: Dir.pwd, result: result) end end log.debug("Validation #{id} passed!") end
ruby
def run(cookbook, options = {}) log.info("Running validations for `#{klass.id}.#{id}'") inside(cookbook) do instance = klass.new(cookbook, options) unless result = instance.instance_eval(&block) log.debug("Validation failed, result: #{result.inspect}") # Convert the class and id to their magical equivalents error = Error.const_get("#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed") raise error.new(path: Dir.pwd, result: result) end end log.debug("Validation #{id} passed!") end
[ "def", "run", "(", "cookbook", ",", "options", "=", "{", "}", ")", "log", ".", "info", "(", "\"Running validations for `#{klass.id}.#{id}'\"", ")", "inside", "(", "cookbook", ")", "do", "instance", "=", "klass", ".", "new", "(", "cookbook", ",", "options", ")", "unless", "result", "=", "instance", ".", "instance_eval", "(", "&", "block", ")", "log", ".", "debug", "(", "\"Validation failed, result: #{result.inspect}\"", ")", "error", "=", "Error", ".", "const_get", "(", "\"#{Util.camelize(klass.id)}#{Util.camelize(id)}ValidationFailed\"", ")", "raise", "error", ".", "new", "(", "path", ":", "Dir", ".", "pwd", ",", "result", ":", "result", ")", "end", "end", "log", ".", "debug", "(", "\"Validation #{id} passed!\"", ")", "end" ]
Create a new validator object. @param [~Class] klass the class that created this validator @param [Symbol] id the identifier or field this validator runs against @param [Proc] block the block to execute to see if the validation passes Execute this validation in the context of the creating class, inside the given cookbook's path. @param [Cookbook] the cookbook to run this validation against
[ "Create", "a", "new", "validator", "object", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/validator.rb#L51-L66
train
tas50/stove
lib/stove/packager.rb
Stove.Packager.tar
def tar(root, slip) io = StringIO.new('', 'r+b') Gem::Package::TarWriter.new(io) do |tar| slip.each do |original_file, tarball_file| mode = File.stat(original_file).mode if File.directory?(original_file) tar.mkdir(tarball_file, mode) else tar.add_file(tarball_file, mode) do |tf| File.open(original_file, 'rb') { |f| tf.write(f.read) } end end end end io.rewind io end
ruby
def tar(root, slip) io = StringIO.new('', 'r+b') Gem::Package::TarWriter.new(io) do |tar| slip.each do |original_file, tarball_file| mode = File.stat(original_file).mode if File.directory?(original_file) tar.mkdir(tarball_file, mode) else tar.add_file(tarball_file, mode) do |tf| File.open(original_file, 'rb') { |f| tf.write(f.read) } end end end end io.rewind io end
[ "def", "tar", "(", "root", ",", "slip", ")", "io", "=", "StringIO", ".", "new", "(", "''", ",", "'r+b'", ")", "Gem", "::", "Package", "::", "TarWriter", ".", "new", "(", "io", ")", "do", "|", "tar", "|", "slip", ".", "each", "do", "|", "original_file", ",", "tarball_file", "|", "mode", "=", "File", ".", "stat", "(", "original_file", ")", ".", "mode", "if", "File", ".", "directory?", "(", "original_file", ")", "tar", ".", "mkdir", "(", "tarball_file", ",", "mode", ")", "else", "tar", ".", "add_file", "(", "tarball_file", ",", "mode", ")", "do", "|", "tf", "|", "File", ".", "open", "(", "original_file", ",", "'rb'", ")", "{", "|", "f", "|", "tf", ".", "write", "(", "f", ".", "read", ")", "}", "end", "end", "end", "end", "io", ".", "rewind", "io", "end" ]
Create a tar file from the given root and packaging slip @param [String] root the root where the tar files are being created @param [Hash<String, String>] slip the map from physical file path to tarball file path @return [StringIO] the io object that contains the tarball contents
[ "Create", "a", "tar", "file", "from", "the", "given", "root", "and", "packaging", "slip" ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/packager.rb#L116-L134
train
tas50/stove
lib/stove/cli.rb
Stove.Cli.option_parser
def option_parser @option_parser ||= OptionParser.new do |opts| opts.banner = 'Usage: stove [OPTIONS]' opts.separator '' opts.separator 'Plugins:' opts.on('--no-git', 'Do not use the git plugin. Skips tagging if specified.') do options[:no_git] = true end opts.separator '' opts.separator 'Upload Options:' opts.on('--endpoint [URL]', 'Supermarket endpoint') do |v| options[:endpoint] = v end opts.on('--username [USERNAME]', 'Username to authenticate with') do |v| options[:username] = v end opts.on('--key [PATH]', 'Path to the private key on disk') do |v| options[:key] = v end opts.on('--[no-]extended-metadata', 'Include non-backwards compatible metadata keys such as `issues_url`') do |v| options[:extended_metadata] = v end opts.on('--no-ssl-verify', 'Turn off ssl verify') do options[:ssl_verify] = false end opts.separator '' opts.separator 'Git Options:' opts.on('--remote [REMOTE]', 'Name of the git remote') do |v| options[:remote] = v end opts.on('--branch [BRANCH]', 'Name of the git branch') do |v| options[:branch] = v end opts.on('--sign', 'Sign git tags') do options[:sign] = true end opts.separator '' opts.separator 'Artifactory Options:' opts.on('--artifactory [URL]', 'URL for the Artifactory repository') do |v| options[:artifactory] = v end opts.on('--artifactory-key [KEY]', 'Artifactory API key to use') do |v| options[:artifactory_key] = if v[0] == '@' # If passed a key looking like @foo, read it as a file. This allows # passing in the key securely. IO.read(File.expand_path(v[1..-1])) else v end end opts.separator '' opts.separator 'Global Options:' opts.on('--log-level [LEVEL]', 'Set the log verbosity') do |v| options[:log_level] = v end opts.on('--path [PATH]', 'Change the path to a cookbook') do |v| options[:path] = v end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('-v', '--version', 'Show version') do puts Stove::VERSION exit(0) end end end
ruby
def option_parser @option_parser ||= OptionParser.new do |opts| opts.banner = 'Usage: stove [OPTIONS]' opts.separator '' opts.separator 'Plugins:' opts.on('--no-git', 'Do not use the git plugin. Skips tagging if specified.') do options[:no_git] = true end opts.separator '' opts.separator 'Upload Options:' opts.on('--endpoint [URL]', 'Supermarket endpoint') do |v| options[:endpoint] = v end opts.on('--username [USERNAME]', 'Username to authenticate with') do |v| options[:username] = v end opts.on('--key [PATH]', 'Path to the private key on disk') do |v| options[:key] = v end opts.on('--[no-]extended-metadata', 'Include non-backwards compatible metadata keys such as `issues_url`') do |v| options[:extended_metadata] = v end opts.on('--no-ssl-verify', 'Turn off ssl verify') do options[:ssl_verify] = false end opts.separator '' opts.separator 'Git Options:' opts.on('--remote [REMOTE]', 'Name of the git remote') do |v| options[:remote] = v end opts.on('--branch [BRANCH]', 'Name of the git branch') do |v| options[:branch] = v end opts.on('--sign', 'Sign git tags') do options[:sign] = true end opts.separator '' opts.separator 'Artifactory Options:' opts.on('--artifactory [URL]', 'URL for the Artifactory repository') do |v| options[:artifactory] = v end opts.on('--artifactory-key [KEY]', 'Artifactory API key to use') do |v| options[:artifactory_key] = if v[0] == '@' # If passed a key looking like @foo, read it as a file. This allows # passing in the key securely. IO.read(File.expand_path(v[1..-1])) else v end end opts.separator '' opts.separator 'Global Options:' opts.on('--log-level [LEVEL]', 'Set the log verbosity') do |v| options[:log_level] = v end opts.on('--path [PATH]', 'Change the path to a cookbook') do |v| options[:path] = v end opts.on_tail('-h', '--help', 'Show this message') do puts opts exit end opts.on_tail('-v', '--version', 'Show version') do puts Stove::VERSION exit(0) end end end
[ "def", "option_parser", "@option_parser", "||=", "OptionParser", ".", "new", "do", "|", "opts", "|", "opts", ".", "banner", "=", "'Usage: stove [OPTIONS]'", "opts", ".", "separator", "''", "opts", ".", "separator", "'Plugins:'", "opts", ".", "on", "(", "'--no-git'", ",", "'Do not use the git plugin. Skips tagging if specified.'", ")", "do", "options", "[", ":no_git", "]", "=", "true", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Upload Options:'", "opts", ".", "on", "(", "'--endpoint [URL]'", ",", "'Supermarket endpoint'", ")", "do", "|", "v", "|", "options", "[", ":endpoint", "]", "=", "v", "end", "opts", ".", "on", "(", "'--username [USERNAME]'", ",", "'Username to authenticate with'", ")", "do", "|", "v", "|", "options", "[", ":username", "]", "=", "v", "end", "opts", ".", "on", "(", "'--key [PATH]'", ",", "'Path to the private key on disk'", ")", "do", "|", "v", "|", "options", "[", ":key", "]", "=", "v", "end", "opts", ".", "on", "(", "'--[no-]extended-metadata'", ",", "'Include non-backwards compatible metadata keys such as `issues_url`'", ")", "do", "|", "v", "|", "options", "[", ":extended_metadata", "]", "=", "v", "end", "opts", ".", "on", "(", "'--no-ssl-verify'", ",", "'Turn off ssl verify'", ")", "do", "options", "[", ":ssl_verify", "]", "=", "false", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Git Options:'", "opts", ".", "on", "(", "'--remote [REMOTE]'", ",", "'Name of the git remote'", ")", "do", "|", "v", "|", "options", "[", ":remote", "]", "=", "v", "end", "opts", ".", "on", "(", "'--branch [BRANCH]'", ",", "'Name of the git branch'", ")", "do", "|", "v", "|", "options", "[", ":branch", "]", "=", "v", "end", "opts", ".", "on", "(", "'--sign'", ",", "'Sign git tags'", ")", "do", "options", "[", ":sign", "]", "=", "true", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Artifactory Options:'", "opts", ".", "on", "(", "'--artifactory [URL]'", ",", "'URL for the Artifactory repository'", ")", "do", "|", "v", "|", "options", "[", ":artifactory", "]", "=", "v", "end", "opts", ".", "on", "(", "'--artifactory-key [KEY]'", ",", "'Artifactory API key to use'", ")", "do", "|", "v", "|", "options", "[", ":artifactory_key", "]", "=", "if", "v", "[", "0", "]", "==", "'@'", "IO", ".", "read", "(", "File", ".", "expand_path", "(", "v", "[", "1", "..", "-", "1", "]", ")", ")", "else", "v", "end", "end", "opts", ".", "separator", "''", "opts", ".", "separator", "'Global Options:'", "opts", ".", "on", "(", "'--log-level [LEVEL]'", ",", "'Set the log verbosity'", ")", "do", "|", "v", "|", "options", "[", ":log_level", "]", "=", "v", "end", "opts", ".", "on", "(", "'--path [PATH]'", ",", "'Change the path to a cookbook'", ")", "do", "|", "v", "|", "options", "[", ":path", "]", "=", "v", "end", "opts", ".", "on_tail", "(", "'-h'", ",", "'--help'", ",", "'Show this message'", ")", "do", "puts", "opts", "exit", "end", "opts", ".", "on_tail", "(", "'-v'", ",", "'--version'", ",", "'Show version'", ")", "do", "puts", "Stove", "::", "VERSION", "exit", "(", "0", ")", "end", "end", "end" ]
The option parser for handling command line flags. @return [OptionParser]
[ "The", "option", "parser", "for", "handling", "command", "line", "flags", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/cli.rb#L82-L169
train
tas50/stove
lib/stove/cli.rb
Stove.Cli.options
def options @options ||= { # Upload options :endpoint => nil, :username => Config.username, :key => Config.key, :extended_metadata => true, :ssl_verify => true, # Git options :remote => 'origin', :branch => 'master', :sign => false, # Artifactory options :artifactory => false, :artifactory_key => ENV['ARTIFACTORY_API_KEY'], # Global options :log_level => :warn, :path => Dir.pwd, } end
ruby
def options @options ||= { # Upload options :endpoint => nil, :username => Config.username, :key => Config.key, :extended_metadata => true, :ssl_verify => true, # Git options :remote => 'origin', :branch => 'master', :sign => false, # Artifactory options :artifactory => false, :artifactory_key => ENV['ARTIFACTORY_API_KEY'], # Global options :log_level => :warn, :path => Dir.pwd, } end
[ "def", "options", "@options", "||=", "{", ":endpoint", "=>", "nil", ",", ":username", "=>", "Config", ".", "username", ",", ":key", "=>", "Config", ".", "key", ",", ":extended_metadata", "=>", "true", ",", ":ssl_verify", "=>", "true", ",", ":remote", "=>", "'origin'", ",", ":branch", "=>", "'master'", ",", ":sign", "=>", "false", ",", ":artifactory", "=>", "false", ",", ":artifactory_key", "=>", "ENV", "[", "'ARTIFACTORY_API_KEY'", "]", ",", ":log_level", "=>", ":warn", ",", ":path", "=>", "Dir", ".", "pwd", ",", "}", "end" ]
The options to pass to the cookbook. Includes default values that are manipulated by the option parser. @return [Hash]
[ "The", "options", "to", "pass", "to", "the", "cookbook", ".", "Includes", "default", "values", "that", "are", "manipulated", "by", "the", "option", "parser", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/cli.rb#L175-L197
train
tas50/stove
lib/stove/supermarket.rb
Stove.Supermarket.upload
def upload(cookbook, extended_metadata = false) connection.post('cookbooks', { 'tarball' => cookbook.tarball(extended_metadata), # This is for legacy, backwards-compatability reasons. The new # Supermarket site does not require a category, but many of the testing # tools still assume a cookbook category is present. We just hardcode # "Other" here. 'cookbook' => JSON.fast_generate(category: 'Other'), }) end
ruby
def upload(cookbook, extended_metadata = false) connection.post('cookbooks', { 'tarball' => cookbook.tarball(extended_metadata), # This is for legacy, backwards-compatability reasons. The new # Supermarket site does not require a category, but many of the testing # tools still assume a cookbook category is present. We just hardcode # "Other" here. 'cookbook' => JSON.fast_generate(category: 'Other'), }) end
[ "def", "upload", "(", "cookbook", ",", "extended_metadata", "=", "false", ")", "connection", ".", "post", "(", "'cookbooks'", ",", "{", "'tarball'", "=>", "cookbook", ".", "tarball", "(", "extended_metadata", ")", ",", "'cookbook'", "=>", "JSON", ".", "fast_generate", "(", "category", ":", "'Other'", ")", ",", "}", ")", "end" ]
Upload a cookbook to the community site. @param [Cookbook] cookbook the cookbook to upload
[ "Upload", "a", "cookbook", "to", "the", "community", "site", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/supermarket.rb#L53-L63
train
tas50/stove
lib/stove/supermarket.rb
Stove.Supermarket.connection
def connection @connection ||= ChefAPI::Connection.new do |conn| conn.endpoint = ENV['STOVE_ENDPOINT'] || Config.endpoint || DEFAULT_ENDPOINT conn.client = ENV['STOVE_USERNAME'] || Config.username conn.key = ENV['STOVE_KEY'] || Config.key conn.ssl_verify = ENV['STOVE_NO_SSL_VERIFY'] || Config.ssl_verify end end
ruby
def connection @connection ||= ChefAPI::Connection.new do |conn| conn.endpoint = ENV['STOVE_ENDPOINT'] || Config.endpoint || DEFAULT_ENDPOINT conn.client = ENV['STOVE_USERNAME'] || Config.username conn.key = ENV['STOVE_KEY'] || Config.key conn.ssl_verify = ENV['STOVE_NO_SSL_VERIFY'] || Config.ssl_verify end end
[ "def", "connection", "@connection", "||=", "ChefAPI", "::", "Connection", ".", "new", "do", "|", "conn", "|", "conn", ".", "endpoint", "=", "ENV", "[", "'STOVE_ENDPOINT'", "]", "||", "Config", ".", "endpoint", "||", "DEFAULT_ENDPOINT", "conn", ".", "client", "=", "ENV", "[", "'STOVE_USERNAME'", "]", "||", "Config", ".", "username", "conn", ".", "key", "=", "ENV", "[", "'STOVE_KEY'", "]", "||", "Config", ".", "key", "conn", ".", "ssl_verify", "=", "ENV", "[", "'STOVE_NO_SSL_VERIFY'", "]", "||", "Config", ".", "ssl_verify", "end", "end" ]
The ChefAPI connection object with lots of pretty middleware.
[ "The", "ChefAPI", "connection", "object", "with", "lots", "of", "pretty", "middleware", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/supermarket.rb#L70-L77
train
tas50/stove
lib/stove/artifactory.rb
Stove.Artifactory.upload
def upload(cookbook, extended_metadata = false) # Artifactory doesn't prevent uploading over an existing release in # some cases so let's check for that. Seriously never do this, go delete # and then re-upload if you have to. response = request(:get, "api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}") # Artifactory's version of the cookbook_version endpoint returns an # empty 200 on an unknown version. unless response.code == '404' || (response.code == '200' && response.body.to_s == '') raise Error::CookbookAlreadyExists.new(cookbook: cookbook) end # Run the upload. response = request(:post, "api/v1/cookbooks/#{cookbook.name}.tgz") do |req| req.body_stream = cookbook.tarball(extended_metadata) req.content_length = req.body_stream.size req['Content-Type'] = 'application/x-binary' end response.error! unless response.code == '201' end
ruby
def upload(cookbook, extended_metadata = false) # Artifactory doesn't prevent uploading over an existing release in # some cases so let's check for that. Seriously never do this, go delete # and then re-upload if you have to. response = request(:get, "api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}") # Artifactory's version of the cookbook_version endpoint returns an # empty 200 on an unknown version. unless response.code == '404' || (response.code == '200' && response.body.to_s == '') raise Error::CookbookAlreadyExists.new(cookbook: cookbook) end # Run the upload. response = request(:post, "api/v1/cookbooks/#{cookbook.name}.tgz") do |req| req.body_stream = cookbook.tarball(extended_metadata) req.content_length = req.body_stream.size req['Content-Type'] = 'application/x-binary' end response.error! unless response.code == '201' end
[ "def", "upload", "(", "cookbook", ",", "extended_metadata", "=", "false", ")", "response", "=", "request", "(", ":get", ",", "\"api/v1/cookbooks/#{cookbook.name}/versions/#{cookbook.version}\"", ")", "unless", "response", ".", "code", "==", "'404'", "||", "(", "response", ".", "code", "==", "'200'", "&&", "response", ".", "body", ".", "to_s", "==", "''", ")", "raise", "Error", "::", "CookbookAlreadyExists", ".", "new", "(", "cookbook", ":", "cookbook", ")", "end", "response", "=", "request", "(", ":post", ",", "\"api/v1/cookbooks/#{cookbook.name}.tgz\"", ")", "do", "|", "req", "|", "req", ".", "body_stream", "=", "cookbook", ".", "tarball", "(", "extended_metadata", ")", "req", ".", "content_length", "=", "req", ".", "body_stream", ".", "size", "req", "[", "'Content-Type'", "]", "=", "'application/x-binary'", "end", "response", ".", "error!", "unless", "response", ".", "code", "==", "'201'", "end" ]
Upload a cookbook to an Artifactory server. @param [Cookbook] cookbook the cookbook to upload
[ "Upload", "a", "cookbook", "to", "an", "Artifactory", "server", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/artifactory.rb#L13-L31
train
tas50/stove
lib/stove/artifactory.rb
Stove.Artifactory.connection
def connection @connection ||= begin uri = URI(Config.artifactory.strip) # Open the HTTP connection to artifactory. http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.use_ssl = true # Mimic the behavior of the Cookbook uploader for SSL verification. if ENV['STOVE_NO_SSL_VERIFY'] || !Config.ssl_verify http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end http.start end end
ruby
def connection @connection ||= begin uri = URI(Config.artifactory.strip) # Open the HTTP connection to artifactory. http = Net::HTTP.new(uri.host, uri.port) if uri.scheme == 'https' http.use_ssl = true # Mimic the behavior of the Cookbook uploader for SSL verification. if ENV['STOVE_NO_SSL_VERIFY'] || !Config.ssl_verify http.verify_mode = OpenSSL::SSL::VERIFY_NONE end end http.start end end
[ "def", "connection", "@connection", "||=", "begin", "uri", "=", "URI", "(", "Config", ".", "artifactory", ".", "strip", ")", "http", "=", "Net", "::", "HTTP", ".", "new", "(", "uri", ".", "host", ",", "uri", ".", "port", ")", "if", "uri", ".", "scheme", "==", "'https'", "http", ".", "use_ssl", "=", "true", "if", "ENV", "[", "'STOVE_NO_SSL_VERIFY'", "]", "||", "!", "Config", ".", "ssl_verify", "http", ".", "verify_mode", "=", "OpenSSL", "::", "SSL", "::", "VERIFY_NONE", "end", "end", "http", ".", "start", "end", "end" ]
Create an HTTP connect to the Artifactory server. @return [Net::HTTP]
[ "Create", "an", "HTTP", "connect", "to", "the", "Artifactory", "server", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/artifactory.rb#L40-L54
train
tas50/stove
lib/stove/artifactory.rb
Stove.Artifactory.request
def request(method, path, &block) uri_string = Config.artifactory.strip # Make sure we end up with the right number of separators. uri_string << '/' unless uri_string.end_with?('/') uri_string << path uri = URI(uri_string) request = Net::HTTP.const_get(method.to_s.capitalize).new(uri) request['X-Jfrog-Art-Api'] = Config.artifactory_key.strip block.call(request) if block connection.request(request) end
ruby
def request(method, path, &block) uri_string = Config.artifactory.strip # Make sure we end up with the right number of separators. uri_string << '/' unless uri_string.end_with?('/') uri_string << path uri = URI(uri_string) request = Net::HTTP.const_get(method.to_s.capitalize).new(uri) request['X-Jfrog-Art-Api'] = Config.artifactory_key.strip block.call(request) if block connection.request(request) end
[ "def", "request", "(", "method", ",", "path", ",", "&", "block", ")", "uri_string", "=", "Config", ".", "artifactory", ".", "strip", "uri_string", "<<", "'/'", "unless", "uri_string", ".", "end_with?", "(", "'/'", ")", "uri_string", "<<", "path", "uri", "=", "URI", "(", "uri_string", ")", "request", "=", "Net", "::", "HTTP", ".", "const_get", "(", "method", ".", "to_s", ".", "capitalize", ")", ".", "new", "(", "uri", ")", "request", "[", "'X-Jfrog-Art-Api'", "]", "=", "Config", ".", "artifactory_key", ".", "strip", "block", ".", "call", "(", "request", ")", "if", "block", "connection", ".", "request", "(", "request", ")", "end" ]
Send an HTTP request to the Artifactory server. @param [Symbol] method HTTP method to use @param [String] path URI path to request @param [Proc] block Optional block to set request values @return [Net::HTTPResponse]
[ "Send", "an", "HTTP", "request", "to", "the", "Artifactory", "server", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/artifactory.rb#L70-L80
train
tas50/stove
lib/stove/cookbook.rb
Stove.Cookbook.released?
def released? Supermarket.cookbook(name, version) true rescue ChefAPI::Error::HTTPNotFound false end
ruby
def released? Supermarket.cookbook(name, version) true rescue ChefAPI::Error::HTTPNotFound false end
[ "def", "released?", "Supermarket", ".", "cookbook", "(", "name", ",", "version", ")", "true", "rescue", "ChefAPI", "::", "Error", "::", "HTTPNotFound", "false", "end" ]
Deterine if this cookbook version is released on the Supermarket @warn This is a fairly expensive operation and the result cannot be reliably cached! @return [Boolean] true if this cookbook at the current version exists on the community site, false otherwise
[ "Deterine", "if", "this", "cookbook", "version", "is", "released", "on", "the", "Supermarket" ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/cookbook.rb#L84-L89
train
tas50/stove
lib/stove/filter.rb
Stove.Filter.run
def run(cookbook, options = {}) log.info(message) instance = klass.new(cookbook, options) inside(cookbook) do instance.instance_eval(&block) end end
ruby
def run(cookbook, options = {}) log.info(message) instance = klass.new(cookbook, options) inside(cookbook) do instance.instance_eval(&block) end end
[ "def", "run", "(", "cookbook", ",", "options", "=", "{", "}", ")", "log", ".", "info", "(", "message", ")", "instance", "=", "klass", ".", "new", "(", "cookbook", ",", "options", ")", "inside", "(", "cookbook", ")", "do", "instance", ".", "instance_eval", "(", "&", "block", ")", "end", "end" ]
Create a new filter object. @param [~Plugin::Base] klass the class that created this filter @param [String] message the message given by the filter @param [Proc] block the block captured by this filter Execute this filter in the context of the creating class, inside the given cookbook's path. @param [Cookbook] the cookbook to run this filter against
[ "Create", "a", "new", "filter", "object", "." ]
cb66538c5d7f4885de829ef664361d7a33cc8370
https://github.com/tas50/stove/blob/cb66538c5d7f4885de829ef664361d7a33cc8370/lib/stove/filter.rb#L51-L58
train
kwatch/erubis
lib/erubis/evaluator.rb
Erubis.RubyEvaluator.evaluate
def evaluate(_context=Context.new) _context = Context.new(_context) if _context.is_a?(Hash) #return _context.instance_eval(@src, @filename || '(erubis)') #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)') @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)') return _context.instance_eval(&@_proc) end
ruby
def evaluate(_context=Context.new) _context = Context.new(_context) if _context.is_a?(Hash) #return _context.instance_eval(@src, @filename || '(erubis)') #@_proc ||= eval("proc { #{@src} }", Erubis::EMPTY_BINDING, @filename || '(erubis)') @_proc ||= eval("proc { #{@src} }", binding(), @filename || '(erubis)') return _context.instance_eval(&@_proc) end
[ "def", "evaluate", "(", "_context", "=", "Context", ".", "new", ")", "_context", "=", "Context", ".", "new", "(", "_context", ")", "if", "_context", ".", "is_a?", "(", "Hash", ")", "@_proc", "||=", "eval", "(", "\"proc { #{@src} }\"", ",", "binding", "(", ")", ",", "@filename", "||", "'(erubis)'", ")", "return", "_context", ".", "instance_eval", "(", "&", "@_proc", ")", "end" ]
invoke context.instance_eval(@src)
[ "invoke", "context", ".", "instance_eval", "(" ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/evaluator.rb#L69-L75
train
kwatch/erubis
lib/erubis/evaluator.rb
Erubis.RubyEvaluator.def_method
def def_method(object, method_name, filename=nil) m = object.is_a?(Module) ? :module_eval : :instance_eval object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)') end
ruby
def def_method(object, method_name, filename=nil) m = object.is_a?(Module) ? :module_eval : :instance_eval object.__send__(m, "def #{method_name}; #{@src}; end", filename || @filename || '(erubis)') end
[ "def", "def_method", "(", "object", ",", "method_name", ",", "filename", "=", "nil", ")", "m", "=", "object", ".", "is_a?", "(", "Module", ")", "?", ":module_eval", ":", ":instance_eval", "object", ".", "__send__", "(", "m", ",", "\"def #{method_name}; #{@src}; end\"", ",", "filename", "||", "@filename", "||", "'(erubis)'", ")", "end" ]
if object is an Class or Module then define instance method to it, else define singleton method to it.
[ "if", "object", "is", "an", "Class", "or", "Module", "then", "define", "instance", "method", "to", "it", "else", "define", "singleton", "method", "to", "it", "." ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/evaluator.rb#L79-L82
train
kwatch/erubis
lib/erubis/converter.rb
Erubis.Converter.convert
def convert(input) codebuf = "" # or [] @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble)) convert_input(codebuf, input) @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble)) @_proc = nil # clear cached proc object return codebuf # or codebuf.join() end
ruby
def convert(input) codebuf = "" # or [] @preamble.nil? ? add_preamble(codebuf) : (@preamble && (codebuf << @preamble)) convert_input(codebuf, input) @postamble.nil? ? add_postamble(codebuf) : (@postamble && (codebuf << @postamble)) @_proc = nil # clear cached proc object return codebuf # or codebuf.join() end
[ "def", "convert", "(", "input", ")", "codebuf", "=", "\"\"", "@preamble", ".", "nil?", "?", "add_preamble", "(", "codebuf", ")", ":", "(", "@preamble", "&&", "(", "codebuf", "<<", "@preamble", ")", ")", "convert_input", "(", "codebuf", ",", "input", ")", "@postamble", ".", "nil?", "?", "add_postamble", "(", "codebuf", ")", ":", "(", "@postamble", "&&", "(", "codebuf", "<<", "@postamble", ")", ")", "@_proc", "=", "nil", "return", "codebuf", "end" ]
convert input string into target language
[ "convert", "input", "string", "into", "target", "language" ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/converter.rb#L33-L40
train
kwatch/erubis
lib/erubis/converter.rb
Erubis.Converter.detect_spaces_at_bol
def detect_spaces_at_bol(text, is_bol) lspace = nil if text.empty? lspace = "" if is_bol elsif text[-1] == ?\n lspace = "" else rindex = text.rindex(?\n) if rindex s = text[rindex+1..-1] if s =~ /\A[ \t]*\z/ lspace = s #text = text[0..rindex] text[rindex+1..-1] = '' end else if is_bol && text =~ /\A[ \t]*\z/ #lspace = text #text = nil lspace = text.dup text[0..-1] = '' end end end return lspace end
ruby
def detect_spaces_at_bol(text, is_bol) lspace = nil if text.empty? lspace = "" if is_bol elsif text[-1] == ?\n lspace = "" else rindex = text.rindex(?\n) if rindex s = text[rindex+1..-1] if s =~ /\A[ \t]*\z/ lspace = s #text = text[0..rindex] text[rindex+1..-1] = '' end else if is_bol && text =~ /\A[ \t]*\z/ #lspace = text #text = nil lspace = text.dup text[0..-1] = '' end end end return lspace end
[ "def", "detect_spaces_at_bol", "(", "text", ",", "is_bol", ")", "lspace", "=", "nil", "if", "text", ".", "empty?", "lspace", "=", "\"\"", "if", "is_bol", "elsif", "text", "[", "-", "1", "]", "==", "?\\n", "lspace", "=", "\"\"", "else", "rindex", "=", "text", ".", "rindex", "(", "?\\n", ")", "if", "rindex", "s", "=", "text", "[", "rindex", "+", "1", "..", "-", "1", "]", "if", "s", "=~", "/", "\\A", "\\t", "\\z", "/", "lspace", "=", "s", "text", "[", "rindex", "+", "1", "..", "-", "1", "]", "=", "''", "end", "else", "if", "is_bol", "&&", "text", "=~", "/", "\\A", "\\t", "\\z", "/", "lspace", "=", "text", ".", "dup", "text", "[", "0", "..", "-", "1", "]", "=", "''", "end", "end", "end", "return", "lspace", "end" ]
detect spaces at beginning of line
[ "detect", "spaces", "at", "beginning", "of", "line" ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/converter.rb#L47-L72
train
kwatch/erubis
lib/erubis/engine.rb
Erubis.Engine.process
def process(input, context=nil, filename=nil) code = convert(input) filename ||= '(erubis)' if context.is_a?(Binding) return eval(code, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(code, filename) end end
ruby
def process(input, context=nil, filename=nil) code = convert(input) filename ||= '(erubis)' if context.is_a?(Binding) return eval(code, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(code, filename) end end
[ "def", "process", "(", "input", ",", "context", "=", "nil", ",", "filename", "=", "nil", ")", "code", "=", "convert", "(", "input", ")", "filename", "||=", "'(erubis)'", "if", "context", ".", "is_a?", "(", "Binding", ")", "return", "eval", "(", "code", ",", "context", ",", "filename", ")", "else", "context", "=", "Context", ".", "new", "(", "context", ")", "if", "context", ".", "is_a?", "(", "Hash", ")", "return", "context", ".", "instance_eval", "(", "code", ",", "filename", ")", "end", "end" ]
helper method to convert and evaluate input text with context object. context may be Binding, Hash, or Object.
[ "helper", "method", "to", "convert", "and", "evaluate", "input", "text", "with", "context", "object", ".", "context", "may", "be", "Binding", "Hash", "or", "Object", "." ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/engine.rb#L72-L81
train
kwatch/erubis
lib/erubis/engine.rb
Erubis.Engine.process_proc
def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end
ruby
def process_proc(proc_obj, context=nil, filename=nil) if context.is_a?(Binding) filename ||= '(erubis)' return eval(proc_obj, context, filename) else context = Context.new(context) if context.is_a?(Hash) return context.instance_eval(&proc_obj) end end
[ "def", "process_proc", "(", "proc_obj", ",", "context", "=", "nil", ",", "filename", "=", "nil", ")", "if", "context", ".", "is_a?", "(", "Binding", ")", "filename", "||=", "'(erubis)'", "return", "eval", "(", "proc_obj", ",", "context", ",", "filename", ")", "else", "context", "=", "Context", ".", "new", "(", "context", ")", "if", "context", ".", "is_a?", "(", "Hash", ")", "return", "context", ".", "instance_eval", "(", "&", "proc_obj", ")", "end", "end" ]
helper method evaluate Proc object with contect object. context may be Binding, Hash, or Object.
[ "helper", "method", "evaluate", "Proc", "object", "with", "contect", "object", ".", "context", "may", "be", "Binding", "Hash", "or", "Object", "." ]
14d3eab57fbc361312c8f3af350cbf9a5bafce17
https://github.com/kwatch/erubis/blob/14d3eab57fbc361312c8f3af350cbf9a5bafce17/lib/erubis/engine.rb#L88-L96
train
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.open
def open ppHandle = FFI::MemoryPointer.new :pointer res = Call.libusb_open(@pDev, ppHandle) LIBUSB.raise_error res, "in libusb_open" if res!=0 handle = DevHandle.new self, ppHandle.read_pointer return handle unless block_given? begin yield handle ensure handle.close end end
ruby
def open ppHandle = FFI::MemoryPointer.new :pointer res = Call.libusb_open(@pDev, ppHandle) LIBUSB.raise_error res, "in libusb_open" if res!=0 handle = DevHandle.new self, ppHandle.read_pointer return handle unless block_given? begin yield handle ensure handle.close end end
[ "def", "open", "ppHandle", "=", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "res", "=", "Call", ".", "libusb_open", "(", "@pDev", ",", "ppHandle", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_open\"", "if", "res!", "=", "0", "handle", "=", "DevHandle", ".", "new", "self", ",", "ppHandle", ".", "read_pointer", "return", "handle", "unless", "block_given?", "begin", "yield", "handle", "ensure", "handle", ".", "close", "end", "end" ]
Open the device and obtain a device handle. A handle allows you to perform I/O on the device in question. This is a non-blocking function; no requests are sent over the bus. If called with a block, the handle is passed to the block and is closed when the block has finished. You need proper device access: * Linux: read+write permissions to <tt>/dev/bus/usb/<bus>/<dev></tt> * Windows: by installing a WinUSB-driver for the device (see {file:README.rdoc#Usage_on_Windows} ) @return [DevHandle] Handle to the device.
[ "Open", "the", "device", "and", "obtain", "a", "device", "handle", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L55-L66
train
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.max_packet_size
def max_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_packet_size" unless res>=0 res end
ruby
def max_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_packet_size" unless res>=0 res end
[ "def", "max_packet_size", "(", "endpoint", ")", "endpoint", "=", "endpoint", ".", "bEndpointAddress", "if", "endpoint", ".", "respond_to?", ":bEndpointAddress", "res", "=", "Call", ".", "libusb_get_max_packet_size", "(", "@pDev", ",", "endpoint", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_max_packet_size\"", "unless", "res", ">=", "0", "res", "end" ]
Convenience function to retrieve the wMaxPacketSize value for a particular endpoint in the active device configuration. @param [Endpoint, Fixnum] endpoint (address of) the endpoint in question @return [Fixnum] the wMaxPacketSize value
[ "Convenience", "function", "to", "retrieve", "the", "wMaxPacketSize", "value", "for", "a", "particular", "endpoint", "in", "the", "active", "device", "configuration", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L156-L161
train
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.max_iso_packet_size
def max_iso_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_iso_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_iso_packet_size" unless res>=0 res end
ruby
def max_iso_packet_size(endpoint) endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress res = Call.libusb_get_max_iso_packet_size(@pDev, endpoint) LIBUSB.raise_error res, "in libusb_get_max_iso_packet_size" unless res>=0 res end
[ "def", "max_iso_packet_size", "(", "endpoint", ")", "endpoint", "=", "endpoint", ".", "bEndpointAddress", "if", "endpoint", ".", "respond_to?", ":bEndpointAddress", "res", "=", "Call", ".", "libusb_get_max_iso_packet_size", "(", "@pDev", ",", "endpoint", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_max_iso_packet_size\"", "unless", "res", ">=", "0", "res", "end" ]
Calculate the maximum packet size which a specific endpoint is capable is sending or receiving in the duration of 1 microframe. Only the active configution is examined. The calculation is based on the wMaxPacketSize field in the endpoint descriptor as described in section 9.6.6 in the USB 2.0 specifications. If acting on an isochronous or interrupt endpoint, this function will multiply the value found in bits 0:10 by the number of transactions per microframe (determined by bits 11:12). Otherwise, this function just returns the numeric value found in bits 0:10. This function is useful for setting up isochronous transfers, for example you might use the return value from this function to call IsoPacket#alloc_buffer in order to set the length field of an isochronous packet in a transfer. @param [Endpoint, Fixnum] endpoint (address of) the endpoint in question @return [Fixnum] the maximum packet size which can be sent/received on this endpoint
[ "Calculate", "the", "maximum", "packet", "size", "which", "a", "specific", "endpoint", "is", "capable", "is", "sending", "or", "receiving", "in", "the", "duration", "of", "1", "microframe", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L182-L187
train
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.config_descriptor
def config_descriptor(index) ppConfig = FFI::MemoryPointer.new :pointer res = Call.libusb_get_config_descriptor(@pDev, index, ppConfig) LIBUSB.raise_error res, "in libusb_get_config_descriptor" if res!=0 pConfig = ppConfig.read_pointer config = Configuration.new(self, pConfig) config end
ruby
def config_descriptor(index) ppConfig = FFI::MemoryPointer.new :pointer res = Call.libusb_get_config_descriptor(@pDev, index, ppConfig) LIBUSB.raise_error res, "in libusb_get_config_descriptor" if res!=0 pConfig = ppConfig.read_pointer config = Configuration.new(self, pConfig) config end
[ "def", "config_descriptor", "(", "index", ")", "ppConfig", "=", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "res", "=", "Call", ".", "libusb_get_config_descriptor", "(", "@pDev", ",", "index", ",", "ppConfig", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_config_descriptor\"", "if", "res!", "=", "0", "pConfig", "=", "ppConfig", ".", "read_pointer", "config", "=", "Configuration", ".", "new", "(", "self", ",", "pConfig", ")", "config", "end" ]
Obtain a config descriptor of the device. @param [Fixnum] index number of the config descriptor @return Configuration
[ "Obtain", "a", "config", "descriptor", "of", "the", "device", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L193-L200
train
larskanis/libusb
lib/libusb/device.rb
LIBUSB.Device.configurations
def configurations configs = [] bNumConfigurations.times do |config_index| begin configs << config_descriptor(config_index) rescue RuntimeError # On Windows some devices don't return it's configuration. end end configs end
ruby
def configurations configs = [] bNumConfigurations.times do |config_index| begin configs << config_descriptor(config_index) rescue RuntimeError # On Windows some devices don't return it's configuration. end end configs end
[ "def", "configurations", "configs", "=", "[", "]", "bNumConfigurations", ".", "times", "do", "|", "config_index", "|", "begin", "configs", "<<", "config_descriptor", "(", "config_index", ")", "rescue", "RuntimeError", "end", "end", "configs", "end" ]
Return configurations of the device. @return [Array<Configuration>]
[ "Return", "configurations", "of", "the", "device", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/device.rb#L337-L347
train
larskanis/libusb
lib/libusb/eventmachine.rb
LIBUSB.Context.eventmachine_register
def eventmachine_register @eventmachine_attached_fds = {} @eventmachine_timer = nil pollfds = self.pollfds if pollfds pollfds.each do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_added do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_removed do |pollfd| eventmachine_rm_pollfd(pollfd) end else # Libusb pollfd API is not available on this platform. # Use simple polling timer, instead: EventMachine.add_periodic_timer(0.01) do @eventmachine_timer = self.handle_events 0 end end end
ruby
def eventmachine_register @eventmachine_attached_fds = {} @eventmachine_timer = nil pollfds = self.pollfds if pollfds pollfds.each do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_added do |pollfd| eventmachine_add_pollfd(pollfd) end self.on_pollfd_removed do |pollfd| eventmachine_rm_pollfd(pollfd) end else # Libusb pollfd API is not available on this platform. # Use simple polling timer, instead: EventMachine.add_periodic_timer(0.01) do @eventmachine_timer = self.handle_events 0 end end end
[ "def", "eventmachine_register", "@eventmachine_attached_fds", "=", "{", "}", "@eventmachine_timer", "=", "nil", "pollfds", "=", "self", ".", "pollfds", "if", "pollfds", "pollfds", ".", "each", "do", "|", "pollfd", "|", "eventmachine_add_pollfd", "(", "pollfd", ")", "end", "self", ".", "on_pollfd_added", "do", "|", "pollfd", "|", "eventmachine_add_pollfd", "(", "pollfd", ")", "end", "self", ".", "on_pollfd_removed", "do", "|", "pollfd", "|", "eventmachine_rm_pollfd", "(", "pollfd", ")", "end", "else", "EventMachine", ".", "add_periodic_timer", "(", "0.01", ")", "do", "@eventmachine_timer", "=", "self", ".", "handle_events", "0", "end", "end", "end" ]
Register libusb's file descriptors and timeouts to EventMachine. @example require 'libusb/eventmachine' context = LIBUSB::Context.new EventMachine.run do context.eventmachine_register end @see DevHandle#eventmachine_bulk_transfer DevHandle#eventmachine_control_transfer DevHandle#eventmachine_interrupt_transfer
[ "Register", "libusb", "s", "file", "descriptors", "and", "timeouts", "to", "EventMachine", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/eventmachine.rb#L34-L58
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.claim_interface
def claim_interface(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_claim_interface(@pHandle, interface) LIBUSB.raise_error res, "in libusb_claim_interface" if res!=0 return self unless block_given? begin yield self ensure release_interface(interface) end end
ruby
def claim_interface(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_claim_interface(@pHandle, interface) LIBUSB.raise_error res, "in libusb_claim_interface" if res!=0 return self unless block_given? begin yield self ensure release_interface(interface) end end
[ "def", "claim_interface", "(", "interface", ")", "interface", "=", "interface", ".", "bInterfaceNumber", "if", "interface", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_claim_interface", "(", "@pHandle", ",", "interface", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_claim_interface\"", "if", "res!", "=", "0", "return", "self", "unless", "block_given?", "begin", "yield", "self", "ensure", "release_interface", "(", "interface", ")", "end", "end" ]
Claim an interface on a given device handle. You must claim the interface you wish to use before you can perform I/O on any of its endpoints. It is legal to attempt to claim an already-claimed interface, in which case libusb just returns without doing anything. Claiming of interfaces is a purely logical operation; it does not cause any requests to be sent over the bus. Interface claiming is used to instruct the underlying operating system that your application wishes to take ownership of the interface. This is a non-blocking function. If called with a block, the device handle is passed through to the block and the interface is released when the block has finished. @param [Interface, Fixnum] interface the interface or it's bInterfaceNumber you wish to claim
[ "Claim", "an", "interface", "on", "a", "given", "device", "handle", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L76-L86
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.set_configuration
def set_configuration(configuration) configuration = configuration.bConfigurationValue if configuration.respond_to? :bConfigurationValue res = Call.libusb_set_configuration(@pHandle, configuration || -1) LIBUSB.raise_error res, "in libusb_set_configuration" if res!=0 end
ruby
def set_configuration(configuration) configuration = configuration.bConfigurationValue if configuration.respond_to? :bConfigurationValue res = Call.libusb_set_configuration(@pHandle, configuration || -1) LIBUSB.raise_error res, "in libusb_set_configuration" if res!=0 end
[ "def", "set_configuration", "(", "configuration", ")", "configuration", "=", "configuration", ".", "bConfigurationValue", "if", "configuration", ".", "respond_to?", ":bConfigurationValue", "res", "=", "Call", ".", "libusb_set_configuration", "(", "@pHandle", ",", "configuration", "||", "-", "1", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_set_configuration\"", "if", "res!", "=", "0", "end" ]
Set the active configuration for a device. The operating system may or may not have already set an active configuration on the device. It is up to your application to ensure the correct configuration is selected before you attempt to claim interfaces and perform other operations. If you call this function on a device already configured with the selected configuration, then this function will act as a lightweight device reset: it will issue a SET_CONFIGURATION request using the current configuration, causing most USB-related device state to be reset (altsetting reset to zero, endpoint halts cleared, toggles reset). You cannot change/reset configuration if your application has claimed interfaces - you should free them with {DevHandle#release_interface} first. You cannot change/reset configuration if other applications or drivers have claimed interfaces. A configuration value of +nil+ will put the device in unconfigured state. The USB specifications state that a configuration value of 0 does this, however buggy devices exist which actually have a configuration 0. You should always use this function rather than formulating your own SET_CONFIGURATION control request. This is because the underlying operating system needs to know when such changes happen. This is a blocking function. @param [Configuration, Fixnum] configuration the configuration or it's bConfigurationValue you wish to activate, or +nil+ if you wish to put the device in unconfigured state
[ "Set", "the", "active", "configuration", "for", "a", "device", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L133-L137
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.set_interface_alt_setting
def set_interface_alt_setting(setting_or_interface_number, alternate_setting=nil) alternate_setting ||= setting_or_interface_number.bAlternateSetting if setting_or_interface_number.respond_to? :bAlternateSetting setting_or_interface_number = setting_or_interface_number.bInterfaceNumber if setting_or_interface_number.respond_to? :bInterfaceNumber res = Call.libusb_set_interface_alt_setting(@pHandle, setting_or_interface_number, alternate_setting) LIBUSB.raise_error res, "in libusb_set_interface_alt_setting" if res!=0 end
ruby
def set_interface_alt_setting(setting_or_interface_number, alternate_setting=nil) alternate_setting ||= setting_or_interface_number.bAlternateSetting if setting_or_interface_number.respond_to? :bAlternateSetting setting_or_interface_number = setting_or_interface_number.bInterfaceNumber if setting_or_interface_number.respond_to? :bInterfaceNumber res = Call.libusb_set_interface_alt_setting(@pHandle, setting_or_interface_number, alternate_setting) LIBUSB.raise_error res, "in libusb_set_interface_alt_setting" if res!=0 end
[ "def", "set_interface_alt_setting", "(", "setting_or_interface_number", ",", "alternate_setting", "=", "nil", ")", "alternate_setting", "||=", "setting_or_interface_number", ".", "bAlternateSetting", "if", "setting_or_interface_number", ".", "respond_to?", ":bAlternateSetting", "setting_or_interface_number", "=", "setting_or_interface_number", ".", "bInterfaceNumber", "if", "setting_or_interface_number", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_set_interface_alt_setting", "(", "@pHandle", ",", "setting_or_interface_number", ",", "alternate_setting", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_set_interface_alt_setting\"", "if", "res!", "=", "0", "end" ]
Activate an alternate setting for an interface. The interface must have been previously claimed with {DevHandle#claim_interface}. You should always use this function rather than formulating your own SET_INTERFACE control request. This is because the underlying operating system needs to know when such changes happen. This is a blocking function. @param [Setting, Fixnum] setting_or_interface_number the alternate setting to activate or the bInterfaceNumber of the previously-claimed interface @param [Fixnum, nil] alternate_setting the bAlternateSetting of the alternate setting to activate (only if first param is a Fixnum)
[ "Activate", "an", "alternate", "setting", "for", "an", "interface", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L154-L159
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.kernel_driver_active?
def kernel_driver_active?(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_kernel_driver_active(@pHandle, interface) LIBUSB.raise_error res, "in libusb_kernel_driver_active" unless res>=0 return res==1 end
ruby
def kernel_driver_active?(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_kernel_driver_active(@pHandle, interface) LIBUSB.raise_error res, "in libusb_kernel_driver_active" unless res>=0 return res==1 end
[ "def", "kernel_driver_active?", "(", "interface", ")", "interface", "=", "interface", ".", "bInterfaceNumber", "if", "interface", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_kernel_driver_active", "(", "@pHandle", ",", "interface", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_kernel_driver_active\"", "unless", "res", ">=", "0", "return", "res", "==", "1", "end" ]
Determine if a kernel driver is active on an interface. If a kernel driver is active, you cannot claim the interface, and libusb will be unable to perform I/O. @param [Interface, Fixnum] interface the interface to check or it's bInterfaceNumber @return [Boolean]
[ "Determine", "if", "a", "kernel", "driver", "is", "active", "on", "an", "interface", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L257-L262
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.detach_kernel_driver
def detach_kernel_driver(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_detach_kernel_driver(@pHandle, interface) LIBUSB.raise_error res, "in libusb_detach_kernel_driver" if res!=0 end
ruby
def detach_kernel_driver(interface) interface = interface.bInterfaceNumber if interface.respond_to? :bInterfaceNumber res = Call.libusb_detach_kernel_driver(@pHandle, interface) LIBUSB.raise_error res, "in libusb_detach_kernel_driver" if res!=0 end
[ "def", "detach_kernel_driver", "(", "interface", ")", "interface", "=", "interface", ".", "bInterfaceNumber", "if", "interface", ".", "respond_to?", ":bInterfaceNumber", "res", "=", "Call", ".", "libusb_detach_kernel_driver", "(", "@pHandle", ",", "interface", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_detach_kernel_driver\"", "if", "res!", "=", "0", "end" ]
Detach a kernel driver from an interface. If successful, you will then be able to claim the interface and perform I/O. @param [Interface, Fixnum] interface the interface to detach the driver from or it's bInterfaceNumber
[ "Detach", "a", "kernel", "driver", "from", "an", "interface", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L270-L274
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.bulk_transfer
def bulk_transfer(args={}, &block) timeout = args.delete(:timeout) || 1000 endpoint = args.delete(:endpoint) || raise(ArgumentError, "no endpoint given") endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress if endpoint&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || raise(ArgumentError, "no :dataIn given for bulk read") else dataOut = args.delete(:dataOut) || raise(ArgumentError, "no :dataOut given for bulk write") end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @bulk_transfer ||= BulkTransfer.new dev_handle: self, allow_device_memory: true tr = @bulk_transfer tr.endpoint = endpoint tr.timeout = timeout if dataOut tr.buffer = dataOut else tr.alloc_buffer(dataIn) end submit_transfer(tr, dataIn, 0, &block) end
ruby
def bulk_transfer(args={}, &block) timeout = args.delete(:timeout) || 1000 endpoint = args.delete(:endpoint) || raise(ArgumentError, "no endpoint given") endpoint = endpoint.bEndpointAddress if endpoint.respond_to? :bEndpointAddress if endpoint&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || raise(ArgumentError, "no :dataIn given for bulk read") else dataOut = args.delete(:dataOut) || raise(ArgumentError, "no :dataOut given for bulk write") end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @bulk_transfer ||= BulkTransfer.new dev_handle: self, allow_device_memory: true tr = @bulk_transfer tr.endpoint = endpoint tr.timeout = timeout if dataOut tr.buffer = dataOut else tr.alloc_buffer(dataIn) end submit_transfer(tr, dataIn, 0, &block) end
[ "def", "bulk_transfer", "(", "args", "=", "{", "}", ",", "&", "block", ")", "timeout", "=", "args", ".", "delete", "(", ":timeout", ")", "||", "1000", "endpoint", "=", "args", ".", "delete", "(", ":endpoint", ")", "||", "raise", "(", "ArgumentError", ",", "\"no endpoint given\"", ")", "endpoint", "=", "endpoint", ".", "bEndpointAddress", "if", "endpoint", ".", "respond_to?", ":bEndpointAddress", "if", "endpoint", "&", "ENDPOINT_IN", "!=", "0", "dataIn", "=", "args", ".", "delete", "(", ":dataIn", ")", "||", "raise", "(", "ArgumentError", ",", "\"no :dataIn given for bulk read\"", ")", "else", "dataOut", "=", "args", ".", "delete", "(", ":dataOut", ")", "||", "raise", "(", "ArgumentError", ",", "\"no :dataOut given for bulk write\"", ")", "end", "raise", "ArgumentError", ",", "\"invalid params #{args.inspect}\"", "unless", "args", ".", "empty?", "@bulk_transfer", "||=", "BulkTransfer", ".", "new", "dev_handle", ":", "self", ",", "allow_device_memory", ":", "true", "tr", "=", "@bulk_transfer", "tr", ".", "endpoint", "=", "endpoint", "tr", ".", "timeout", "=", "timeout", "if", "dataOut", "tr", ".", "buffer", "=", "dataOut", "else", "tr", ".", "alloc_buffer", "(", "dataIn", ")", "end", "submit_transfer", "(", "tr", ",", "dataIn", ",", "0", ",", "&", "block", ")", "end" ]
Perform a USB bulk transfer. When called without a block, the transfer is done synchronously - so all events are handled internally and the sent/received data will be returned after completion or an exception will be raised. When called with a block, the method returns immediately after submitting the transfer. You then have to ensure, that {Context#handle_events} is called properly. As soon as the transfer is completed, the block is called with the sent/received data in case of success or the exception instance in case of failure. The direction of the transfer is inferred from the direction bits of the endpoint address. For bulk reads, the +:dataIn+ param indicates the maximum length of data you are expecting to receive. If less data arrives than expected, this function will return that data. You should check the returned number of bytes for bulk writes. Not all of the data may have been written. Also check {Error#transferred} when dealing with a timeout exception. libusb may have to split your transfer into a number of chunks to satisfy underlying O/S requirements, meaning that the timeout may expire after the first few chunks have completed. libusb is careful not to lose any data that may have been transferred; do not assume that timeout conditions indicate a complete lack of I/O. @param [Hash] args @option args [Endpoint, Fixnum] :endpoint the (address of a) valid endpoint to communicate with @option args [String] :dataOut the data to send with an outgoing transfer @option args [Fixnum] :dataIn the number of bytes expected to receive with an ingoing transfer @option args [Fixnum] :timeout timeout (in millseconds) that this function should wait before giving up due to no response being received. For an unlimited timeout, use value 0. Defaults to 1000 ms. @return [Fixnum] Number of bytes sent for an outgoing transfer @return [String] Received data for an ingoing transfer @return [self] When called with a block @yieldparam [String, Integer, LIBUSB::Error] result result of the transfer is yielded to the block, when the asynchronous transfer has finished @raise [ArgumentError, LIBUSB::Error] in case of failure
[ "Perform", "a", "USB", "bulk", "transfer", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L375-L398
train
larskanis/libusb
lib/libusb/dev_handle.rb
LIBUSB.DevHandle.control_transfer
def control_transfer(args={}, &block) bmRequestType = args.delete(:bmRequestType) || raise(ArgumentError, "param :bmRequestType not given") bRequest = args.delete(:bRequest) || raise(ArgumentError, "param :bRequest not given") wValue = args.delete(:wValue) || raise(ArgumentError, "param :wValue not given") wIndex = args.delete(:wIndex) || raise(ArgumentError, "param :wIndex not given") timeout = args.delete(:timeout) || 1000 if bmRequestType&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || 0 dataOut = '' else dataOut = args.delete(:dataOut) || '' end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @control_transfer ||= ControlTransfer.new dev_handle: self, allow_device_memory: true tr = @control_transfer tr.timeout = timeout if dataIn setup_data = [bmRequestType, bRequest, wValue, wIndex, dataIn].pack('CCvvv') tr.alloc_buffer( dataIn + CONTROL_SETUP_SIZE, setup_data ) else tr.buffer = [bmRequestType, bRequest, wValue, wIndex, dataOut.bytesize, dataOut].pack('CCvvva*') end submit_transfer(tr, dataIn, CONTROL_SETUP_SIZE, &block) end
ruby
def control_transfer(args={}, &block) bmRequestType = args.delete(:bmRequestType) || raise(ArgumentError, "param :bmRequestType not given") bRequest = args.delete(:bRequest) || raise(ArgumentError, "param :bRequest not given") wValue = args.delete(:wValue) || raise(ArgumentError, "param :wValue not given") wIndex = args.delete(:wIndex) || raise(ArgumentError, "param :wIndex not given") timeout = args.delete(:timeout) || 1000 if bmRequestType&ENDPOINT_IN != 0 dataIn = args.delete(:dataIn) || 0 dataOut = '' else dataOut = args.delete(:dataOut) || '' end raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? # reuse transfer struct to speed up transfer @control_transfer ||= ControlTransfer.new dev_handle: self, allow_device_memory: true tr = @control_transfer tr.timeout = timeout if dataIn setup_data = [bmRequestType, bRequest, wValue, wIndex, dataIn].pack('CCvvv') tr.alloc_buffer( dataIn + CONTROL_SETUP_SIZE, setup_data ) else tr.buffer = [bmRequestType, bRequest, wValue, wIndex, dataOut.bytesize, dataOut].pack('CCvvva*') end submit_transfer(tr, dataIn, CONTROL_SETUP_SIZE, &block) end
[ "def", "control_transfer", "(", "args", "=", "{", "}", ",", "&", "block", ")", "bmRequestType", "=", "args", ".", "delete", "(", ":bmRequestType", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :bmRequestType not given\"", ")", "bRequest", "=", "args", ".", "delete", "(", ":bRequest", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :bRequest not given\"", ")", "wValue", "=", "args", ".", "delete", "(", ":wValue", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :wValue not given\"", ")", "wIndex", "=", "args", ".", "delete", "(", ":wIndex", ")", "||", "raise", "(", "ArgumentError", ",", "\"param :wIndex not given\"", ")", "timeout", "=", "args", ".", "delete", "(", ":timeout", ")", "||", "1000", "if", "bmRequestType", "&", "ENDPOINT_IN", "!=", "0", "dataIn", "=", "args", ".", "delete", "(", ":dataIn", ")", "||", "0", "dataOut", "=", "''", "else", "dataOut", "=", "args", ".", "delete", "(", ":dataOut", ")", "||", "''", "end", "raise", "ArgumentError", ",", "\"invalid params #{args.inspect}\"", "unless", "args", ".", "empty?", "@control_transfer", "||=", "ControlTransfer", ".", "new", "dev_handle", ":", "self", ",", "allow_device_memory", ":", "true", "tr", "=", "@control_transfer", "tr", ".", "timeout", "=", "timeout", "if", "dataIn", "setup_data", "=", "[", "bmRequestType", ",", "bRequest", ",", "wValue", ",", "wIndex", ",", "dataIn", "]", ".", "pack", "(", "'CCvvv'", ")", "tr", ".", "alloc_buffer", "(", "dataIn", "+", "CONTROL_SETUP_SIZE", ",", "setup_data", ")", "else", "tr", ".", "buffer", "=", "[", "bmRequestType", ",", "bRequest", ",", "wValue", ",", "wIndex", ",", "dataOut", ".", "bytesize", ",", "dataOut", "]", ".", "pack", "(", "'CCvvva*'", ")", "end", "submit_transfer", "(", "tr", ",", "dataIn", ",", "CONTROL_SETUP_SIZE", ",", "&", "block", ")", "end" ]
Perform a USB control transfer. When called without a block, the transfer is done synchronously - so all events are handled internally and the sent/received data will be returned after completion or an exception will be raised. When called with a block, the method returns immediately after submitting the transfer. You then have to ensure, that {Context#handle_events} is called properly. As soon as the transfer is completed, the block is called with the sent/received data in case of success or the exception instance in case of failure. The direction of the transfer is inferred from the +:bmRequestType+ field of the setup packet. @param [Hash] args @option args [Fixnum] :bmRequestType the request type field for the setup packet @option args [Fixnum] :bRequest the request field for the setup packet @option args [Fixnum] :wValue the value field for the setup packet @option args [Fixnum] :wIndex the index field for the setup packet @option args [String] :dataOut the data to send with an outgoing transfer, it is appended to the setup packet @option args [Fixnum] :dataIn the number of bytes expected to receive with an ingoing transfer (excluding setup packet) @option args [Fixnum] :timeout timeout (in millseconds) that this function should wait before giving up due to no response being received. For an unlimited timeout, use value 0. Defaults to 1000 ms. @return [Fixnum] Number of bytes sent (excluding setup packet) for outgoing transfer @return [String] Received data (without setup packet) for ingoing transfer @return [self] When called with a block @yieldparam [String, Integer, LIBUSB::Error] result result of the transfer is yielded to the block, when the asynchronous transfer has finished @raise [ArgumentError, LIBUSB::Error] in case of failure
[ "Perform", "a", "USB", "control", "transfer", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/dev_handle.rb#L500-L526
train
larskanis/libusb
lib/libusb/bos.rb
LIBUSB.Bos.device_capabilities
def device_capabilities pp_ext = FFI::MemoryPointer.new :pointer caps = [] # Capabilities are appended to the bos header ptr = pointer + offset_of(:dev_capability) bNumDeviceCaps.times do cap = DeviceCapability.new self, ptr.read_pointer case cap.bDevCapabilityType when LIBUSB::BT_WIRELESS_USB_DEVICE_CAPABILITY # no struct defined in libusb -> use generic DeviceCapability when LIBUSB::BT_USB_2_0_EXTENSION res = Call.libusb_get_usb_2_0_extension_descriptor(@ctx, cap.pointer, pp_ext) cap = Usb20Extension.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_SS_USB_DEVICE_CAPABILITY res = Call.libusb_get_ss_usb_device_capability_descriptor(@ctx, cap.pointer, pp_ext) cap = SsUsbDeviceCapability.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_CONTAINER_ID res = Call.libusb_get_container_id_descriptor(@ctx, cap.pointer, pp_ext) cap = ContainerId.new(pp_ext.read_pointer) if res==0 else # unknown capability -> use generic DeviceCapability end ptr += FFI.type_size(:pointer) caps << cap end caps end
ruby
def device_capabilities pp_ext = FFI::MemoryPointer.new :pointer caps = [] # Capabilities are appended to the bos header ptr = pointer + offset_of(:dev_capability) bNumDeviceCaps.times do cap = DeviceCapability.new self, ptr.read_pointer case cap.bDevCapabilityType when LIBUSB::BT_WIRELESS_USB_DEVICE_CAPABILITY # no struct defined in libusb -> use generic DeviceCapability when LIBUSB::BT_USB_2_0_EXTENSION res = Call.libusb_get_usb_2_0_extension_descriptor(@ctx, cap.pointer, pp_ext) cap = Usb20Extension.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_SS_USB_DEVICE_CAPABILITY res = Call.libusb_get_ss_usb_device_capability_descriptor(@ctx, cap.pointer, pp_ext) cap = SsUsbDeviceCapability.new(pp_ext.read_pointer) if res==0 when LIBUSB::BT_CONTAINER_ID res = Call.libusb_get_container_id_descriptor(@ctx, cap.pointer, pp_ext) cap = ContainerId.new(pp_ext.read_pointer) if res==0 else # unknown capability -> use generic DeviceCapability end ptr += FFI.type_size(:pointer) caps << cap end caps end
[ "def", "device_capabilities", "pp_ext", "=", "FFI", "::", "MemoryPointer", ".", "new", ":pointer", "caps", "=", "[", "]", "ptr", "=", "pointer", "+", "offset_of", "(", ":dev_capability", ")", "bNumDeviceCaps", ".", "times", "do", "cap", "=", "DeviceCapability", ".", "new", "self", ",", "ptr", ".", "read_pointer", "case", "cap", ".", "bDevCapabilityType", "when", "LIBUSB", "::", "BT_WIRELESS_USB_DEVICE_CAPABILITY", "when", "LIBUSB", "::", "BT_USB_2_0_EXTENSION", "res", "=", "Call", ".", "libusb_get_usb_2_0_extension_descriptor", "(", "@ctx", ",", "cap", ".", "pointer", ",", "pp_ext", ")", "cap", "=", "Usb20Extension", ".", "new", "(", "pp_ext", ".", "read_pointer", ")", "if", "res", "==", "0", "when", "LIBUSB", "::", "BT_SS_USB_DEVICE_CAPABILITY", "res", "=", "Call", ".", "libusb_get_ss_usb_device_capability_descriptor", "(", "@ctx", ",", "cap", ".", "pointer", ",", "pp_ext", ")", "cap", "=", "SsUsbDeviceCapability", ".", "new", "(", "pp_ext", ".", "read_pointer", ")", "if", "res", "==", "0", "when", "LIBUSB", "::", "BT_CONTAINER_ID", "res", "=", "Call", ".", "libusb_get_container_id_descriptor", "(", "@ctx", ",", "cap", ".", "pointer", ",", "pp_ext", ")", "cap", "=", "ContainerId", ".", "new", "(", "pp_ext", ".", "read_pointer", ")", "if", "res", "==", "0", "else", "end", "ptr", "+=", "FFI", ".", "type_size", "(", ":pointer", ")", "caps", "<<", "cap", "end", "caps", "end" ]
bNumDeviceCap Device Capability Descriptors @return [Array<Bos::DeviceCapability, Bos::Usb20Extension, Bos::SsUsbDeviceCapability, Bos::ContainerId>]
[ "bNumDeviceCap", "Device", "Capability", "Descriptors" ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/bos.rb#L256-L282
train
larskanis/libusb
lib/libusb/transfer.rb
LIBUSB.Transfer.submit!
def submit!(&block) self.callback = block if block_given? # puts "submit transfer #{@transfer.inspect} buffer: #{@transfer[:buffer].inspect} length: #{@transfer[:length].inspect} status: #{@transfer[:status].inspect} callback: #{@transfer[:callback].inspect} dev_handle: #{@transfer[:dev_handle].inspect}" res = Call.libusb_submit_transfer( @transfer ) LIBUSB.raise_error res, "in libusb_submit_transfer" if res!=0 end
ruby
def submit!(&block) self.callback = block if block_given? # puts "submit transfer #{@transfer.inspect} buffer: #{@transfer[:buffer].inspect} length: #{@transfer[:length].inspect} status: #{@transfer[:status].inspect} callback: #{@transfer[:callback].inspect} dev_handle: #{@transfer[:dev_handle].inspect}" res = Call.libusb_submit_transfer( @transfer ) LIBUSB.raise_error res, "in libusb_submit_transfer" if res!=0 end
[ "def", "submit!", "(", "&", "block", ")", "self", ".", "callback", "=", "block", "if", "block_given?", "res", "=", "Call", ".", "libusb_submit_transfer", "(", "@transfer", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_submit_transfer\"", "if", "res!", "=", "0", "end" ]
Submit a transfer. This function will fire off the USB transfer and then return immediately. This method can be called with block. It is called when the transfer completes, fails, or is cancelled.
[ "Submit", "a", "transfer", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/transfer.rb#L211-L218
train
larskanis/libusb
lib/libusb/transfer.rb
LIBUSB.Transfer.submit_and_wait
def submit_and_wait raise ArgumentError, "#{self.class}#dev_handle not set" unless @dev_handle @completion_flag.completed = false submit! do |tr2| @completion_flag.completed = true end until @completion_flag.completed? begin @dev_handle.device.context.handle_events nil, @completion_flag rescue ERROR_INTERRUPTED next rescue LIBUSB::Error cancel! until @completion_flag.completed? @dev_handle.device.context.handle_events nil, @completion_flag end raise end end end
ruby
def submit_and_wait raise ArgumentError, "#{self.class}#dev_handle not set" unless @dev_handle @completion_flag.completed = false submit! do |tr2| @completion_flag.completed = true end until @completion_flag.completed? begin @dev_handle.device.context.handle_events nil, @completion_flag rescue ERROR_INTERRUPTED next rescue LIBUSB::Error cancel! until @completion_flag.completed? @dev_handle.device.context.handle_events nil, @completion_flag end raise end end end
[ "def", "submit_and_wait", "raise", "ArgumentError", ",", "\"#{self.class}#dev_handle not set\"", "unless", "@dev_handle", "@completion_flag", ".", "completed", "=", "false", "submit!", "do", "|", "tr2", "|", "@completion_flag", ".", "completed", "=", "true", "end", "until", "@completion_flag", ".", "completed?", "begin", "@dev_handle", ".", "device", ".", "context", ".", "handle_events", "nil", ",", "@completion_flag", "rescue", "ERROR_INTERRUPTED", "next", "rescue", "LIBUSB", "::", "Error", "cancel!", "until", "@completion_flag", ".", "completed?", "@dev_handle", ".", "device", ".", "context", ".", "handle_events", "nil", ",", "@completion_flag", "end", "raise", "end", "end", "end" ]
Submit the transfer and wait until the transfer completes or fails. Inspect {#status} to check for transfer errors.
[ "Submit", "the", "transfer", "and", "wait", "until", "the", "transfer", "completes", "or", "fails", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/transfer.rb#L242-L263
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.handle_events
def handle_events(timeout=nil, completion_flag=nil) if completion_flag && !completion_flag.is_a?(Context::CompletionFlag) raise ArgumentError, "completion_flag is not a CompletionFlag" end if timeout timeval = Call::Timeval.new timeval.in_ms = timeout res = if Call.respond_to?(:libusb_handle_events_timeout_completed) Call.libusb_handle_events_timeout_completed(@ctx, timeval, completion_flag) else Call.libusb_handle_events_timeout(@ctx, timeval) end else res = if Call.respond_to?(:libusb_handle_events_completed) Call.libusb_handle_events_completed(@ctx, completion_flag ) else Call.libusb_handle_events(@ctx) end end LIBUSB.raise_error res, "in libusb_handle_events" if res<0 end
ruby
def handle_events(timeout=nil, completion_flag=nil) if completion_flag && !completion_flag.is_a?(Context::CompletionFlag) raise ArgumentError, "completion_flag is not a CompletionFlag" end if timeout timeval = Call::Timeval.new timeval.in_ms = timeout res = if Call.respond_to?(:libusb_handle_events_timeout_completed) Call.libusb_handle_events_timeout_completed(@ctx, timeval, completion_flag) else Call.libusb_handle_events_timeout(@ctx, timeval) end else res = if Call.respond_to?(:libusb_handle_events_completed) Call.libusb_handle_events_completed(@ctx, completion_flag ) else Call.libusb_handle_events(@ctx) end end LIBUSB.raise_error res, "in libusb_handle_events" if res<0 end
[ "def", "handle_events", "(", "timeout", "=", "nil", ",", "completion_flag", "=", "nil", ")", "if", "completion_flag", "&&", "!", "completion_flag", ".", "is_a?", "(", "Context", "::", "CompletionFlag", ")", "raise", "ArgumentError", ",", "\"completion_flag is not a CompletionFlag\"", "end", "if", "timeout", "timeval", "=", "Call", "::", "Timeval", ".", "new", "timeval", ".", "in_ms", "=", "timeout", "res", "=", "if", "Call", ".", "respond_to?", "(", ":libusb_handle_events_timeout_completed", ")", "Call", ".", "libusb_handle_events_timeout_completed", "(", "@ctx", ",", "timeval", ",", "completion_flag", ")", "else", "Call", ".", "libusb_handle_events_timeout", "(", "@ctx", ",", "timeval", ")", "end", "else", "res", "=", "if", "Call", ".", "respond_to?", "(", ":libusb_handle_events_completed", ")", "Call", ".", "libusb_handle_events_completed", "(", "@ctx", ",", "completion_flag", ")", "else", "Call", ".", "libusb_handle_events", "(", "@ctx", ")", "end", "end", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_handle_events\"", "if", "res", "<", "0", "end" ]
Handle any pending events in blocking mode. This method must be called when libusb is running asynchronous transfers. This gives libusb the opportunity to reap pending transfers, invoke callbacks, etc. If a zero timeout is passed, this function will handle any already-pending events and then immediately return in non-blocking style. If a non-zero timeout is passed and no events are currently pending, this method will block waiting for events to handle up until the specified timeout. If an event arrives or a signal is raised, this method will return early. If the parameter completion_flag is used, then after obtaining the event handling lock this function will return immediately if the flag is set to completed. This allows for race free waiting for the completion of a specific transfer. See source of {Transfer#submit_and_wait} for a use case of completion_flag. @param [Integer, nil] timeout the maximum time (in millseconds) to block waiting for events, or 0 for non-blocking mode @param [Context::CompletionFlag, nil] completion_flag CompletionFlag to check @see interrupt_event_handler
[ "Handle", "any", "pending", "events", "in", "blocking", "mode", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L195-L215
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.devices
def devices(filter_hash={}) device_list.select do |dev| ( !filter_hash[:bClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceClass).&([filter_hash[:bClass]].flatten).any? : [filter_hash[:bClass]].flatten.include?(dev.bDeviceClass))) && ( !filter_hash[:bSubClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceSubClass).&([filter_hash[:bSubClass]].flatten).any? : [filter_hash[:bSubClass]].flatten.include?(dev.bDeviceSubClass))) && ( !filter_hash[:bProtocol] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceProtocol).&([filter_hash[:bProtocol]].flatten).any? : [filter_hash[:bProtocol]].flatten.include?(dev.bDeviceProtocol))) && ( !filter_hash[:bMaxPacketSize0] || [filter_hash[:bMaxPacketSize0]].flatten.include?(dev.bMaxPacketSize0) ) && ( !filter_hash[:idVendor] || [filter_hash[:idVendor]].flatten.include?(dev.idVendor) ) && ( !filter_hash[:idProduct] || [filter_hash[:idProduct]].flatten.include?(dev.idProduct) ) && ( !filter_hash[:bcdUSB] || [filter_hash[:bcdUSB]].flatten.include?(dev.bcdUSB) ) && ( !filter_hash[:bcdDevice] || [filter_hash[:bcdDevice]].flatten.include?(dev.bcdDevice) ) end end
ruby
def devices(filter_hash={}) device_list.select do |dev| ( !filter_hash[:bClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceClass).&([filter_hash[:bClass]].flatten).any? : [filter_hash[:bClass]].flatten.include?(dev.bDeviceClass))) && ( !filter_hash[:bSubClass] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceSubClass).&([filter_hash[:bSubClass]].flatten).any? : [filter_hash[:bSubClass]].flatten.include?(dev.bDeviceSubClass))) && ( !filter_hash[:bProtocol] || (dev.bDeviceClass==CLASS_PER_INTERFACE ? dev.settings.map(&:bInterfaceProtocol).&([filter_hash[:bProtocol]].flatten).any? : [filter_hash[:bProtocol]].flatten.include?(dev.bDeviceProtocol))) && ( !filter_hash[:bMaxPacketSize0] || [filter_hash[:bMaxPacketSize0]].flatten.include?(dev.bMaxPacketSize0) ) && ( !filter_hash[:idVendor] || [filter_hash[:idVendor]].flatten.include?(dev.idVendor) ) && ( !filter_hash[:idProduct] || [filter_hash[:idProduct]].flatten.include?(dev.idProduct) ) && ( !filter_hash[:bcdUSB] || [filter_hash[:bcdUSB]].flatten.include?(dev.bcdUSB) ) && ( !filter_hash[:bcdDevice] || [filter_hash[:bcdDevice]].flatten.include?(dev.bcdDevice) ) end end
[ "def", "devices", "(", "filter_hash", "=", "{", "}", ")", "device_list", ".", "select", "do", "|", "dev", "|", "(", "!", "filter_hash", "[", ":bClass", "]", "||", "(", "dev", ".", "bDeviceClass", "==", "CLASS_PER_INTERFACE", "?", "dev", ".", "settings", ".", "map", "(", "&", ":bInterfaceClass", ")", ".", "&", "(", "[", "filter_hash", "[", ":bClass", "]", "]", ".", "flatten", ")", ".", "any?", ":", "[", "filter_hash", "[", ":bClass", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bDeviceClass", ")", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bSubClass", "]", "||", "(", "dev", ".", "bDeviceClass", "==", "CLASS_PER_INTERFACE", "?", "dev", ".", "settings", ".", "map", "(", "&", ":bInterfaceSubClass", ")", ".", "&", "(", "[", "filter_hash", "[", ":bSubClass", "]", "]", ".", "flatten", ")", ".", "any?", ":", "[", "filter_hash", "[", ":bSubClass", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bDeviceSubClass", ")", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bProtocol", "]", "||", "(", "dev", ".", "bDeviceClass", "==", "CLASS_PER_INTERFACE", "?", "dev", ".", "settings", ".", "map", "(", "&", ":bInterfaceProtocol", ")", ".", "&", "(", "[", "filter_hash", "[", ":bProtocol", "]", "]", ".", "flatten", ")", ".", "any?", ":", "[", "filter_hash", "[", ":bProtocol", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bDeviceProtocol", ")", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bMaxPacketSize0", "]", "||", "[", "filter_hash", "[", ":bMaxPacketSize0", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bMaxPacketSize0", ")", ")", "&&", "(", "!", "filter_hash", "[", ":idVendor", "]", "||", "[", "filter_hash", "[", ":idVendor", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "idVendor", ")", ")", "&&", "(", "!", "filter_hash", "[", ":idProduct", "]", "||", "[", "filter_hash", "[", ":idProduct", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "idProduct", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bcdUSB", "]", "||", "[", "filter_hash", "[", ":bcdUSB", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bcdUSB", ")", ")", "&&", "(", "!", "filter_hash", "[", ":bcdDevice", "]", "||", "[", "filter_hash", "[", ":bcdDevice", "]", "]", ".", "flatten", ".", "include?", "(", "dev", ".", "bcdDevice", ")", ")", "end", "end" ]
Obtain a list of devices currently attached to the USB system, optionally matching certain criteria. @param [Hash] filter_hash A number of criteria can be defined in key-value pairs. Only devices that equal all given criterions will be returned. If a criterion is not specified or its value is +nil+, any device will match that criterion. The following criteria can be filtered: * <tt>:idVendor</tt>, <tt>:idProduct</tt> (+FixNum+) for matching vendor/product ID, * <tt>:bClass</tt>, <tt>:bSubClass</tt>, <tt>:bProtocol</tt> (+FixNum+) for the device type - Devices using CLASS_PER_INTERFACE will match, if any of the interfaces match. * <tt>:bcdUSB</tt>, <tt>:bcdDevice</tt>, <tt>:bMaxPacketSize0</tt> (+FixNum+) for the USB and device release numbers. Criteria can also specified as Array of several alternative values. @example # Return all devices of vendor 0x0ab1 where idProduct is 3 or 4: context.device idVendor: 0x0ab1, idProduct: [0x0003, 0x0004] @return [Array<LIBUSB::Device>]
[ "Obtain", "a", "list", "of", "devices", "currently", "attached", "to", "the", "USB", "system", "optionally", "matching", "certain", "criteria", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L248-L265
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.pollfds
def pollfds ppPollfds = Call.libusb_get_pollfds(@ctx) return nil if ppPollfds.null? offs = 0 pollfds = [] while !(pPollfd=ppPollfds.get_pointer(offs)).null? pollfd = Call::Pollfd.new pPollfd pollfds << Pollfd.new(pollfd[:fd], pollfd[:events]) offs += FFI.type_size :pointer end if Call.respond_to?(:libusb_free_pollfds) Call.libusb_free_pollfds(ppPollfds) else Stdio.free(ppPollfds) end pollfds end
ruby
def pollfds ppPollfds = Call.libusb_get_pollfds(@ctx) return nil if ppPollfds.null? offs = 0 pollfds = [] while !(pPollfd=ppPollfds.get_pointer(offs)).null? pollfd = Call::Pollfd.new pPollfd pollfds << Pollfd.new(pollfd[:fd], pollfd[:events]) offs += FFI.type_size :pointer end if Call.respond_to?(:libusb_free_pollfds) Call.libusb_free_pollfds(ppPollfds) else Stdio.free(ppPollfds) end pollfds end
[ "def", "pollfds", "ppPollfds", "=", "Call", ".", "libusb_get_pollfds", "(", "@ctx", ")", "return", "nil", "if", "ppPollfds", ".", "null?", "offs", "=", "0", "pollfds", "=", "[", "]", "while", "!", "(", "pPollfd", "=", "ppPollfds", ".", "get_pointer", "(", "offs", ")", ")", ".", "null?", "pollfd", "=", "Call", "::", "Pollfd", ".", "new", "pPollfd", "pollfds", "<<", "Pollfd", ".", "new", "(", "pollfd", "[", ":fd", "]", ",", "pollfd", "[", ":events", "]", ")", "offs", "+=", "FFI", ".", "type_size", ":pointer", "end", "if", "Call", ".", "respond_to?", "(", ":libusb_free_pollfds", ")", "Call", ".", "libusb_free_pollfds", "(", "ppPollfds", ")", "else", "Stdio", ".", "free", "(", "ppPollfds", ")", "end", "pollfds", "end" ]
Retrieve a list of file descriptors that should be polled by your main loop as libusb event sources. As file descriptors are a Unix-specific concept, this function is not available on Windows and will always return +nil+. @return [Array<Pollfd>] list of Pollfd objects, +nil+ on error, +nil+ on platforms where the functionality is not available
[ "Retrieve", "a", "list", "of", "file", "descriptors", "that", "should", "be", "polled", "by", "your", "main", "loop", "as", "libusb", "event", "sources", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L277-L293
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.next_timeout
def next_timeout timeval = Call::Timeval.new res = Call.libusb_get_next_timeout @ctx, timeval LIBUSB.raise_error res, "in libusb_get_next_timeout" if res<0 res == 1 ? timeval.in_s : nil end
ruby
def next_timeout timeval = Call::Timeval.new res = Call.libusb_get_next_timeout @ctx, timeval LIBUSB.raise_error res, "in libusb_get_next_timeout" if res<0 res == 1 ? timeval.in_s : nil end
[ "def", "next_timeout", "timeval", "=", "Call", "::", "Timeval", ".", "new", "res", "=", "Call", ".", "libusb_get_next_timeout", "@ctx", ",", "timeval", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_get_next_timeout\"", "if", "res", "<", "0", "res", "==", "1", "?", "timeval", ".", "in_s", ":", "nil", "end" ]
Determine the next internal timeout that libusb needs to handle. You only need to use this function if you are calling poll() or select() or similar on libusb's file descriptors yourself - you do not need to use it if you are calling {#handle_events} directly. You should call this function in your main loop in order to determine how long to wait for select() or poll() to return results. libusb needs to be called into at this timeout, so you should use it as an upper bound on your select() or poll() call. When the timeout has expired, call into {#handle_events} (perhaps in non-blocking mode) so that libusb can handle the timeout. This function may return zero. If this is the case, it indicates that libusb has a timeout that has already expired so you should call {#handle_events} immediately. A return code of +nil+ indicates that there are no pending timeouts. On some platforms, this function will always returns +nil+ (no pending timeouts). See libusb's notes on time-based events. @return [Float, nil] the timeout in seconds
[ "Determine", "the", "next", "internal", "timeout", "that", "libusb", "needs", "to", "handle", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L318-L323
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.on_pollfd_added
def on_pollfd_added &block @on_pollfd_added = proc do |fd, events, _| pollfd = Pollfd.new fd, events block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
ruby
def on_pollfd_added &block @on_pollfd_added = proc do |fd, events, _| pollfd = Pollfd.new fd, events block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
[ "def", "on_pollfd_added", "&", "block", "@on_pollfd_added", "=", "proc", "do", "|", "fd", ",", "events", ",", "_", "|", "pollfd", "=", "Pollfd", ".", "new", "fd", ",", "events", "block", ".", "call", "pollfd", "end", "Call", ".", "libusb_set_pollfd_notifiers", "@ctx", ",", "@on_pollfd_added", ",", "@on_pollfd_removed", ",", "nil", "end" ]
Register a notification block for file descriptor additions. This block will be invoked for every new file descriptor that libusb uses as an event source. Note that file descriptors may have been added even before you register these notifiers (e.g. at {Context#initialize} time). @yieldparam [Pollfd] pollfd The added file descriptor is yielded to the block
[ "Register", "a", "notification", "block", "for", "file", "descriptor", "additions", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L334-L340
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.on_pollfd_removed
def on_pollfd_removed &block @on_pollfd_removed = proc do |fd, _| pollfd = Pollfd.new fd block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
ruby
def on_pollfd_removed &block @on_pollfd_removed = proc do |fd, _| pollfd = Pollfd.new fd block.call pollfd end Call.libusb_set_pollfd_notifiers @ctx, @on_pollfd_added, @on_pollfd_removed, nil end
[ "def", "on_pollfd_removed", "&", "block", "@on_pollfd_removed", "=", "proc", "do", "|", "fd", ",", "_", "|", "pollfd", "=", "Pollfd", ".", "new", "fd", "block", ".", "call", "pollfd", "end", "Call", ".", "libusb_set_pollfd_notifiers", "@ctx", ",", "@on_pollfd_added", ",", "@on_pollfd_removed", ",", "nil", "end" ]
Register a notification block for file descriptor removals. This block will be invoked for every removed file descriptor that libusb uses as an event source. Note that the removal notifier may be called during {Context#exit} (e.g. when it is closing file descriptors that were opened and added to the poll set at {Context#initialize} time). If you don't want this, overwrite the notifier immediately before calling {Context#exit}. @yieldparam [Pollfd] pollfd The removed file descriptor is yielded to the block
[ "Register", "a", "notification", "block", "for", "file", "descriptor", "removals", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L353-L359
train
larskanis/libusb
lib/libusb/context.rb
LIBUSB.Context.on_hotplug_event
def on_hotplug_event(args={}, &block) events = args.delete(:events) || (HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT) flags = args.delete(:flags) || 0 vendor_id = args.delete(:vendor_id) || HOTPLUG_MATCH_ANY product_id = args.delete(:product_id) || HOTPLUG_MATCH_ANY dev_class = args.delete(:dev_class) || HOTPLUG_MATCH_ANY raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? handle = HotplugCallback.new self, @ctx, @hotplug_callbacks block2 = proc do |ctx, pDevice, event, _user_data| raise "internal error: unexpected context" unless @ctx==ctx dev = Device.new @ctx, pDevice blres = block.call(dev, event) case blres when :finish 1 when :repeat 0 else raise ArgumentError, "hotplug event handler must return :finish or :repeat" end end res = Call.libusb_hotplug_register_callback(@ctx, events, flags, vendor_id, product_id, dev_class, block2, nil, handle) LIBUSB.raise_error res, "in libusb_hotplug_register_callback" if res<0 # Avoid GC'ing of the block: @hotplug_callbacks[handle[:handle]] = block2 return handle end
ruby
def on_hotplug_event(args={}, &block) events = args.delete(:events) || (HOTPLUG_EVENT_DEVICE_ARRIVED | HOTPLUG_EVENT_DEVICE_LEFT) flags = args.delete(:flags) || 0 vendor_id = args.delete(:vendor_id) || HOTPLUG_MATCH_ANY product_id = args.delete(:product_id) || HOTPLUG_MATCH_ANY dev_class = args.delete(:dev_class) || HOTPLUG_MATCH_ANY raise ArgumentError, "invalid params #{args.inspect}" unless args.empty? handle = HotplugCallback.new self, @ctx, @hotplug_callbacks block2 = proc do |ctx, pDevice, event, _user_data| raise "internal error: unexpected context" unless @ctx==ctx dev = Device.new @ctx, pDevice blres = block.call(dev, event) case blres when :finish 1 when :repeat 0 else raise ArgumentError, "hotplug event handler must return :finish or :repeat" end end res = Call.libusb_hotplug_register_callback(@ctx, events, flags, vendor_id, product_id, dev_class, block2, nil, handle) LIBUSB.raise_error res, "in libusb_hotplug_register_callback" if res<0 # Avoid GC'ing of the block: @hotplug_callbacks[handle[:handle]] = block2 return handle end
[ "def", "on_hotplug_event", "(", "args", "=", "{", "}", ",", "&", "block", ")", "events", "=", "args", ".", "delete", "(", ":events", ")", "||", "(", "HOTPLUG_EVENT_DEVICE_ARRIVED", "|", "HOTPLUG_EVENT_DEVICE_LEFT", ")", "flags", "=", "args", ".", "delete", "(", ":flags", ")", "||", "0", "vendor_id", "=", "args", ".", "delete", "(", ":vendor_id", ")", "||", "HOTPLUG_MATCH_ANY", "product_id", "=", "args", ".", "delete", "(", ":product_id", ")", "||", "HOTPLUG_MATCH_ANY", "dev_class", "=", "args", ".", "delete", "(", ":dev_class", ")", "||", "HOTPLUG_MATCH_ANY", "raise", "ArgumentError", ",", "\"invalid params #{args.inspect}\"", "unless", "args", ".", "empty?", "handle", "=", "HotplugCallback", ".", "new", "self", ",", "@ctx", ",", "@hotplug_callbacks", "block2", "=", "proc", "do", "|", "ctx", ",", "pDevice", ",", "event", ",", "_user_data", "|", "raise", "\"internal error: unexpected context\"", "unless", "@ctx", "==", "ctx", "dev", "=", "Device", ".", "new", "@ctx", ",", "pDevice", "blres", "=", "block", ".", "call", "(", "dev", ",", "event", ")", "case", "blres", "when", ":finish", "1", "when", ":repeat", "0", "else", "raise", "ArgumentError", ",", "\"hotplug event handler must return :finish or :repeat\"", "end", "end", "res", "=", "Call", ".", "libusb_hotplug_register_callback", "(", "@ctx", ",", "events", ",", "flags", ",", "vendor_id", ",", "product_id", ",", "dev_class", ",", "block2", ",", "nil", ",", "handle", ")", "LIBUSB", ".", "raise_error", "res", ",", "\"in libusb_hotplug_register_callback\"", "if", "res", "<", "0", "@hotplug_callbacks", "[", "handle", "[", ":handle", "]", "]", "=", "block2", "return", "handle", "end" ]
Register a hotplug event notification. Register a callback with the {LIBUSB::Context}. The callback will fire when a matching event occurs on a matching device. The callback is armed until either it is deregistered with {HotplugCallback#deregister} or the supplied block returns +:finish+ to indicate it is finished processing events. If the flag {Call::HotplugFlags HOTPLUG_ENUMERATE} is passed the callback will be called with a {Call::HotplugEvents :HOTPLUG_EVENT_DEVICE_ARRIVED} for all devices already plugged into the machine. Note that libusb modifies its internal device list from a separate thread, while calling hotplug callbacks from {#handle_events}, so it is possible for a device to already be present on, or removed from, its internal device list, while the hotplug callbacks still need to be dispatched. This means that when using {Call::HotplugFlags HOTPLUG_ENUMERATE}, your callback may be called twice for the arrival of the same device, once from {#on_hotplug_event} and once from {#handle_events}; and/or your callback may be called for the removal of a device for which an arrived call was never made. Since libusb version 1.0.16. @param [Hash] args @option args [Fixnum,Symbol] :events bitwise or of events that will trigger this callback. Default is +LIBUSB::HOTPLUG_EVENT_DEVICE_ARRIVED|LIBUSB::HOTPLUG_EVENT_DEVICE_LEFT+ . See {Call::HotplugEvents HotplugEvents} @option args [Fixnum,Symbol] :flags hotplug callback flags. Default is 0. See {Call::HotplugFlags HotplugFlags} @option args [Fixnum] :vendor_id the vendor id to match. Default is {HOTPLUG_MATCH_ANY}. @option args [Fixnum] :product_id the product id to match. Default is {HOTPLUG_MATCH_ANY}. @option args [Fixnum] :dev_class the device class to match. Default is {HOTPLUG_MATCH_ANY}. @return [HotplugCallback] The handle to the registered callback. @yieldparam [Device] device the attached or removed {Device} is yielded to the block @yieldparam [Symbol] event a {Call::HotplugEvents HotplugEvents} symbol @yieldreturn [Symbol] +:finish+ to deregister the callback, +:repeat+ to receive additional events @raise [ArgumentError, LIBUSB::Error] in case of failure
[ "Register", "a", "hotplug", "event", "notification", "." ]
ddeaa43f6cde868171fa08744e6c95e96a594766
https://github.com/larskanis/libusb/blob/ddeaa43f6cde868171fa08744e6c95e96a594766/lib/libusb/context.rb#L396-L433
train
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_message
def send_message(params) extra_params_validation = { text: { required: true, class: [String] }, parse_mode: { required: false, class: [String] }, disable_web_page_preview: { required: false, class: [TrueClass, FalseClass] } } send_something(:message, params, extra_params_validation) end
ruby
def send_message(params) extra_params_validation = { text: { required: true, class: [String] }, parse_mode: { required: false, class: [String] }, disable_web_page_preview: { required: false, class: [TrueClass, FalseClass] } } send_something(:message, params, extra_params_validation) end
[ "def", "send_message", "(", "params", ")", "extra_params_validation", "=", "{", "text", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", ",", "parse_mode", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", ",", "disable_web_page_preview", ":", "{", "required", ":", "false", ",", "class", ":", "[", "TrueClass", ",", "FalseClass", "]", "}", "}", "send_something", "(", ":message", ",", "params", ",", "extra_params_validation", ")", "end" ]
Send text messages to a user or group chat. @param [Hash] params hash of paramers to send to the sendMessage API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [String] :text Required. Text of the message to be sent @option params [String] :parse_mode Optional. Send Markdown, if you want Telegram apps to show bold, italic and inline URLs in your bot's message. @option params [Boolean] :disable_web_page_preview Optional. Disables link previews for links in this message @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.send_message( chat_id: 123456789, text: "Hello World!" ) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Send", "text", "messages", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L136-L144
train
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.forward_message
def forward_message(params) params_validation = { chat_id: { required: true, class: [Fixnum] }, from_chat_id: { required: true, class: [String] }, message_id: { required: true, class: [Fixnum] } } response = api_request('forwardMessage', params, params_validation) Telegrammer::DataTypes::Message.new(response.result) end
ruby
def forward_message(params) params_validation = { chat_id: { required: true, class: [Fixnum] }, from_chat_id: { required: true, class: [String] }, message_id: { required: true, class: [Fixnum] } } response = api_request('forwardMessage', params, params_validation) Telegrammer::DataTypes::Message.new(response.result) end
[ "def", "forward_message", "(", "params", ")", "params_validation", "=", "{", "chat_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Fixnum", "]", "}", ",", "from_chat_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "String", "]", "}", ",", "message_id", ":", "{", "required", ":", "true", ",", "class", ":", "[", "Fixnum", "]", "}", "}", "response", "=", "api_request", "(", "'forwardMessage'", ",", "params", ",", "params_validation", ")", "Telegrammer", "::", "DataTypes", "::", "Message", ".", "new", "(", "response", ".", "result", ")", "end" ]
Forward message to a user or group chat. @param [Hash] params hash of paramers to send to the forwardMessage API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [Integer,String] :from_chat_id Required. Unique identifier for the chat where the original message was sent (or channel username in the format @channelusername). @option params [Integer] :message_id Required. Message id to be forwarded. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') bot.forward_message( chat_id: 123456789, from_chat_id: 987654321 message_id: 111222333 ) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Forward", "message", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L166-L176
train
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_photo
def send_photo(params) extra_params_validation = { photo: { required: true, class: [File, String] }, caption: { required: false, class: [String] } } send_something(:photo, params, extra_params_validation) end
ruby
def send_photo(params) extra_params_validation = { photo: { required: true, class: [File, String] }, caption: { required: false, class: [String] } } send_something(:photo, params, extra_params_validation) end
[ "def", "send_photo", "(", "params", ")", "extra_params_validation", "=", "{", "photo", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "caption", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", "}", "send_something", "(", ":photo", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends a photo to a user or group chat. @param [Hash] params hash of paramers to send to the sendPhoto API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] :photo Required. Photo to send. You can either pass a file_id as String to resend a photo that is already on the Telegram servers, or upload a new photo using multipart/form-data. @option params [String] :caption Optional. Photo caption (may also be used when resending photos by file_id). @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') image_file = File.open("foo.jpg") bot.send_photo(chat_id: 123456789, photo: image_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "a", "photo", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L197-L204
train
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_audio
def send_audio(params) extra_params_validation = { audio: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] }, performer: { required: false, class: [String] }, title: { required: false, class: [String] } } send_something(:audio, params, extra_params_validation) end
ruby
def send_audio(params) extra_params_validation = { audio: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] }, performer: { required: false, class: [String] }, title: { required: false, class: [String] } } send_something(:audio, params, extra_params_validation) end
[ "def", "send_audio", "(", "params", ")", "extra_params_validation", "=", "{", "audio", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "duration", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Integer", "]", "}", ",", "performer", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", ",", "title", ":", "{", "required", ":", "false", ",", "class", ":", "[", "String", "]", "}", "}", "send_something", "(", ":audio", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends audio file to a user or group chat. At this moment, Telegram only allows Ogg files encoded with the OPUS codec. If you need to send another file format, you must use #send_document. @param [Hash] params hash of paramers to send to the sendAudio API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] audio Required. Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data @option params [Integer] duration Optional. Duration of the audio in seconds. @option params [String] performer Optional. Performer. @option params [String] title Optional. Track name. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') audio_file = File.open("foo.ogg") bot.send_audio(chat_id: 123456789, audio: audio_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "audio", "file", "to", "a", "user", "or", "group", "chat", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L229-L238
train
mayoral/telegrammer
lib/telegrammer/bot.rb
Telegrammer.Bot.send_voice
def send_voice(params) extra_params_validation = { voice: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] } } send_something(:audio, params, extra_params_validation) end
ruby
def send_voice(params) extra_params_validation = { voice: { required: true, class: [File, String] }, duration: { required: false, class: [Integer] } } send_something(:audio, params, extra_params_validation) end
[ "def", "send_voice", "(", "params", ")", "extra_params_validation", "=", "{", "voice", ":", "{", "required", ":", "true", ",", "class", ":", "[", "File", ",", "String", "]", "}", ",", "duration", ":", "{", "required", ":", "false", ",", "class", ":", "[", "Integer", "]", "}", "}", "send_something", "(", ":audio", ",", "params", ",", "extra_params_validation", ")", "end" ]
Sends audio files file to a user or group chat that the users will see as a playable voice message. At this moment, Telegram only allows Ogg files encoded with the OPUS codec. If you need to send another file format, you must use #send_document. @param [Hash] params hash of paramers to send to the sendAudio API operation. @option params [Integer,String] :chat_id Required. Unique identifier for the target chat or username of the target channel (in the format @channelusername). @option params [File,String] voice Required. Audio file to send. You can either pass a file_id as String to resend an audio that is already on the Telegram servers, or upload a new audio file using multipart/form-data @option params [Integer] duration Optional. Duration of sent audio in seconds. @option params [Integer] :reply_to_message_id Optional. If the message is a reply, ID of the original message @option params [Telegrammer::DataTypes::ReplyKeyboardMarkup,Telegrammer::DataTypes::ReplyKeyboardHide,Telegrammer::DataTypes::ForceReply] :reply_markup Optional. Additional interface options. A JSON-serialized object for a custom reply keyboard, instructions to hide keyboard or to force a reply from the user. @example bot = Telegrammer::Bot.new('[YOUR TELEGRAM TOKEN]') voice_file = File.open("foo.ogg") bot.send_voice(chat_id: 123456789, voice: audio_file) @raise [Telegrammer::Errors::BadRequestError] if something goes wrong in the Telegram API servers with the params received by the operation @raise [Telegrammer::Errors::ServiceUnavailableError] if Telegram servers are down @see #send_document @return [Telegrammer::DataTypes::Message] Message object sent to the user or group chat
[ "Sends", "audio", "files", "file", "to", "a", "user", "or", "group", "chat", "that", "the", "users", "will", "see", "as", "a", "playable", "voice", "message", "." ]
be85007a647fcebec7e0b5ed1ff86f4dd924a62a
https://github.com/mayoral/telegrammer/blob/be85007a647fcebec7e0b5ed1ff86f4dd924a62a/lib/telegrammer/bot.rb#L261-L268
train