Class: Ably::Rest::Client
- Inherits:
-
Object
- Object
- Ably::Rest::Client
- Extended by:
- Forwardable
- Includes:
- Modules::Conversions, Modules::HttpHelpers
- Defined in:
- lib/submodules/ably-ruby/lib/ably/rest/client.rb
Overview
Client for the Ably REST API
Constant Summary collapse
- DOMAIN =
Default Ably domain for REST
'rest.ably.io'- CONNECTION_RETRY =
Configuration for connection retry attempts
{ single_request_open_timeout: 4, single_request_timeout: 15, cumulative_request_open_timeout: 10, max_retry_attempts: 3 }.freeze
Instance Attribute Summary collapse
-
#auth ⇒ Ably::Auth
readonly
Auth authentication object configured for this connection.
-
#auth_options ⇒ Hash
readonly
Auth options configured for this client.
-
#channels ⇒ Aby::Rest::Channels
readonly
The collection of Channels that have been created.
-
#client_id ⇒ String
readonly
A client ID, used for identifying this client for presence purposes.
-
#custom_host ⇒ String, Nil
readonly
The custom host that is being used if it was provided with the option ‘:rest_host` when the Client was created.
-
#encoders ⇒ Array<Ably::Models::MessageEncoder::Base>
readonly
private
The registered encoders that are used to encode and decode message payloads.
-
#endpoint ⇒ URI::Generic
readonly
Default Ably REST endpoint used for all requests.
-
#environment ⇒ String
readonly
Custom environment to use such as ‘sandbox’ when testing the client library against an alternate Ably environment.
-
#log_level ⇒ Logger::Severity
readonly
Log level configured for this Client.
-
#logger ⇒ Logger
readonly
The Logger for this client.
-
#mime_type ⇒ String
readonly
Mime type used for HTTP requests.
-
#options ⇒ Hash
readonly
private
The additional options passed to this Client’s #initialize method not available as attributes of this class.
-
#protocol ⇒ Symbol
readonly
The protocol configured for this client, either binary ‘:msgpack` or text based `:json`.
-
#protocol_binary? ⇒ Boolean
readonly
True of the transport #protocol communicates with Ably with a binary protocol.
-
#use_tls? ⇒ Boolean
readonly
True if client is configured to use TLS for all Ably communication.
Instance Method Summary collapse
-
#channel(name, channel_options = {}) ⇒ Ably::Rest::Channel
Return a REST Channel for the given name.
-
#connection(options = {}) ⇒ Faraday::Connection
private
Connection used to make HTTP requests.
-
#fallback_connection ⇒ Faraday::Connection
private
Fallback connection used to make HTTP requests.
-
#get(path, params = {}, options = {}) ⇒ Faraday::Response
Perform an HTTP GET request to the API using configured authentication.
-
#initialize(options) ⇒ Ably::Rest::Client
constructor
Creates a Rest Client and configures the Auth object for the connection.
-
#post(path, params, options = {}) ⇒ Faraday::Response
Perform an HTTP POST request to the API using configured authentication.
-
#register_encoder(encoder) ⇒ void
private
Register a message encoder and decoder that implements Ably::Models::MessageEncoders::Base interface.
-
#stats(options = {}) ⇒ Ably::Models::PaginatedResult<Ably::Models::Stats>
Retrieve the Stats for the application.
-
#time ⇒ Time
Retrieve the Ably service time.
Constructor Details
#initialize(options) ⇒ Ably::Rest::Client
Creates a Rest Client and configures the Auth object for the connection.
92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 92 def initialize() raise ArgumentError, 'Options Hash is expected' if .nil? = .clone if .kind_of?(String) = if .match(/^[\w]{2,}\.[\w]{2,}:[\w]{2,}$/) { key: } else { token: } end end @tls = .delete(:tls) == false ? false : true @environment = .delete(:environment) # nil is production @protocol = .delete(:protocol) || :msgpack @debug_http = .delete(:debug_http) @log_level = .delete(:log_level) || ::Logger::ERROR @custom_logger = .delete(:logger) @custom_host = .delete(:rest_host) if @log_level == :none @custom_logger = Ably::Models::NilLogger.new else @log_level = ::Logger.const_get(log_level.to_s.upcase) if log_level.kind_of?(Symbol) || log_level.kind_of?(String) end .delete(:use_binary_protocol).tap do |use_binary_protocol| if use_binary_protocol == true @protocol = :msgpack elsif use_binary_protocol == false @protocol = :json end end raise ArgumentError, 'Protocol is invalid. Must be either :msgpack or :json' unless [:msgpack, :json].include?(@protocol) = .freeze @auth = Auth.new(self, ) @channels = Ably::Rest::Channels.new(self) @encoders = [] initialize_default_encoders end |
Instance Attribute Details
#auth ⇒ Ably::Auth (readonly)
Auth authentication object configured for this connection
44 45 46 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 44 def auth @auth end |
#auth_options ⇒ Hash (readonly)
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 16 class Client include Ably::Modules::Conversions include Ably::Modules::HttpHelpers extend Forwardable # Default Ably domain for REST DOMAIN = 'rest.ably.io' # Configuration for connection retry attempts CONNECTION_RETRY = { single_request_open_timeout: 4, single_request_timeout: 15, cumulative_request_open_timeout: 10, max_retry_attempts: 3 }.freeze def_delegators :auth, :client_id, :auth_options # Custom environment to use such as 'sandbox' when testing the client library against an alternate Ably environment # @return [String] attr_reader :environment # The protocol configured for this client, either binary `:msgpack` or text based `:json` # @return [Symbol] attr_reader :protocol # {Ably::Auth} authentication object configured for this connection # @return [Ably::Auth] attr_reader :auth # The collection of {Ably::Rest::Channel}s that have been created # @return [Aby::Rest::Channels] attr_reader :channels # Log level configured for this {Client} # @return [Logger::Severity] attr_reader :log_level # The custom host that is being used if it was provided with the option `:rest_host` when the {Client} was created # @return [String,Nil] attr_reader :custom_host # The registered encoders that are used to encode and decode message payloads # @return [Array<Ably::Models::MessageEncoder::Base>] # @api private attr_reader :encoders # The additional options passed to this Client's #initialize method not available as attributes of this class # @return [Hash] # @api private attr_reader :options # Creates a {Ably::Rest::Client Rest Client} and configures the {Ably::Auth} object for the connection. # # @param [Hash,String] options an options Hash used to configure the client and the authentication, or String with an API key or Token ID # @option options (see Ably::Auth#authorise) # @option options [Boolean] :tls TLS is used by default, providing a value of false disables TLS. Please note Basic Auth is disallowed without TLS as secrets cannot be transmitted over unsecured connections. # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [String] :token Token string or {Models::TokenDetails} used to authenticate requests # @option options [String] :token_details {Models::TokenDetails} used to authenticate requests # @option options [Boolean] :use_token_auth Will force Basic Auth if set to false, and Token auth if set to true # @option options [String] :environment Specify 'sandbox' when testing the client library against an alternate Ably environment # @option options [Symbol] :protocol Protocol used to communicate with Ably, :json and :msgpack currently supported. Defaults to :msgpack # @option options [Boolean] :use_binary_protocol Protocol used to communicate with Ably, defaults to true and uses MessagePack protocol. This option will overide :protocol option # @option options [Logger::Severity,Symbol] :log_level Log level for the standard Logger that outputs to STDOUT. Defaults to Logger::ERROR, can be set to :fatal (Logger::FATAL), :error (Logger::ERROR), :warn (Logger::WARN), :info (Logger::INFO), :debug (Logger::DEBUG) or :none # @option options [Logger] :logger A custom logger can be used however it must adhere to the Ruby Logger interface, see http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html # # @return [Ably::Rest::Client] # # @example # # create a new client authenticating with basic auth # client = Ably::Rest::Client.new('key.id:secret') # # # create a new client and configure a client ID used for presence # client = Ably::Rest::Client.new(key: 'key.id:secret', client_id: 'john') # def initialize() raise ArgumentError, 'Options Hash is expected' if .nil? = .clone if .kind_of?(String) = if .match(/^[\w]{2,}\.[\w]{2,}:[\w]{2,}$/) { key: } else { token: } end end @tls = .delete(:tls) == false ? false : true @environment = .delete(:environment) # nil is production @protocol = .delete(:protocol) || :msgpack @debug_http = .delete(:debug_http) @log_level = .delete(:log_level) || ::Logger::ERROR @custom_logger = .delete(:logger) @custom_host = .delete(:rest_host) if @log_level == :none @custom_logger = Ably::Models::NilLogger.new else @log_level = ::Logger.const_get(log_level.to_s.upcase) if log_level.kind_of?(Symbol) || log_level.kind_of?(String) end .delete(:use_binary_protocol).tap do |use_binary_protocol| if use_binary_protocol == true @protocol = :msgpack elsif use_binary_protocol == false @protocol = :json end end raise ArgumentError, 'Protocol is invalid. Must be either :msgpack or :json' unless [:msgpack, :json].include?(@protocol) = .freeze @auth = Auth.new(self, ) @channels = Ably::Rest::Channels.new(self) @encoders = [] initialize_default_encoders end # Return a REST {Ably::Rest::Channel} for the given name # # @param (see Ably::Rest::Channels#get) # # @return (see Ably::Rest::Channels#get) def channel(name, = {}) channels.get(name, ) end # Retrieve the Stats for the application # # @param [Hash] options the options for the stats request # @option options [Integer,Time] :start Ensure earliest time or millisecond since epoch for any stats retrieved is +:start+ # @option options [Integer,Time] :end Ensure latest time or millisecond since epoch for any stats retrieved is +:end+ # @option options [Symbol] :direction +:forwards+ or +:backwards+, defaults to +:backwards+ # @option options [Integer] :limit Maximum number of messages to retrieve up to 1,000, defaults to 100 # @option options [Symbol] :unit `:minute`, `:hour`, `:day` or `:month`. Defaults to `:minute` # # @return [Ably::Models::PaginatedResult<Ably::Models::Stats>] An Array of Stats # def stats( = {}) = { :direction => :backwards, :unit => :minute, :limit => 100 }.merge() [:start, :end].each { |option| [option] = as_since_epoch([option]) if .has_key?(option) } = { coerce_into: 'Ably::Models::Stats' } url = '/stats' response = get(url, ) Ably::Models::PaginatedResult.new(response, url, self, ) end # Retrieve the Ably service time # # @return [Time] The time as reported by the Ably service def time response = get('/time', {}, send_auth_header: false) as_time_from_epoch(response.body.first) end # @!attribute [r] use_tls? # @return [Boolean] True if client is configured to use TLS for all Ably communication def use_tls? @tls == true end # Perform an HTTP GET request to the API using configured authentication # # @return [Faraday::Response] def get(path, params = {}, = {}) request(:get, path, params, ) end # Perform an HTTP POST request to the API using configured authentication # # @return [Faraday::Response] def post(path, params, = {}) request(:post, path, params, ) end # @!attribute [r] endpoint # @return [URI::Generic] Default Ably REST endpoint used for all requests def endpoint endpoint_for_host(custom_host || [@environment, DOMAIN].compact.join('-')) end # @!attribute [r] logger # @return [Logger] The {Ably::Logger} for this client. # Configure the log_level with the `:log_level` option, refer to {Client#initialize} def logger @logger ||= Ably::Logger.new(self, log_level, @custom_logger) end # @!attribute [r] mime_type # @return [String] Mime type used for HTTP requests def mime_type case protocol when :json 'application/json' else 'application/x-msgpack' end end # Register a message encoder and decoder that implements Ably::Models::MessageEncoders::Base interface. # Message encoders are used to encode and decode message payloads automatically. # @note Encoders and decoders are processed in the order they are added so the first encoder will be given priority when encoding and decoding # # @param [Ably::Models::MessageEncoders::Base] encoder # @return [void] # # @api private def register_encoder(encoder) encoder_klass = if encoder.kind_of?(String) encoder.split('::').inject(Kernel) do |base, klass_name| base.public_send(:const_get, klass_name) end else encoder end raise "Encoder must inherit from `Ably::Models::MessageEncoders::Base`" unless encoder_klass.ancestors.include?(Ably::Models::MessageEncoders::Base) encoders << encoder_klass.new(self) end # @!attribute [r] protocol_binary? # @return [Boolean] True of the transport #protocol communicates with Ably with a binary protocol def protocol_binary? protocol == :msgpack end # Connection used to make HTTP requests # # @param [Hash] options # @option options [Boolean] :use_fallback when true, one of the fallback connections is used randomly, see {Ably::FALLBACK_HOSTS} # # @return [Faraday::Connection] # # @api private def connection( = {}) if [:use_fallback] fallback_connection else @connection ||= Faraday.new(endpoint.to_s, ) end end # Fallback connection used to make HTTP requests. # Note, each request uses a random and then subsequent random {Ably::FALLBACK_HOSTS fallback host} # # @return [Faraday::Connection] # # @api private def fallback_connection unless @fallback_connections @fallback_connections = Ably::FALLBACK_HOSTS.shuffle.map { |host| Faraday.new(endpoint_for_host(host).to_s, ) } end @fallback_index ||= 0 @fallback_connections[@fallback_index % @fallback_connections.count].tap do @fallback_index += 1 end end private def request(method, path, params = {}, = {}) = .clone if .delete(:disable_automatic_reauthorise) == true send_request(method, path, params, ) else do send_request(method, path, params, ) end end end # Sends HTTP request to connection end point # Connection failures will automatically be reattempted until thresholds are met def send_request(method, path, params, ) max_retry_attempts = CONNECTION_RETRY.fetch(:max_retry_attempts) cumulative_timeout = CONNECTION_RETRY.fetch(:cumulative_request_open_timeout) requested_at = Time.now retry_count = 0 begin use_fallback = can_fallback_to_alternate_ably_host? && retry_count > 0 connection(use_fallback: use_fallback).send(method, path, params) do |request| unless [:send_auth_header] == false request.headers[:authorization] = auth.auth_header end end rescue Faraday::TimeoutError, Faraday::ClientError => error time_passed = Time.now - requested_at if can_fallback_to_alternate_ably_host? && retry_count < max_retry_attempts && time_passed <= cumulative_timeout retry_count += 1 retry end case error when Faraday::TimeoutError raise Ably::Exceptions::ConnectionTimeoutError.new(error., nil, 80014, error) when Faraday::ClientError raise Ably::Exceptions::ConnectionError.new(error., nil, 80000, error) end end end def yield rescue Ably::Exceptions::InvalidRequest => e if e.code == 40140 if auth.token_renewable? auth. force: true yield else raise Ably::Exceptions::InvalidToken.new(e., e.status, e.code) end else raise e end end def endpoint_for_host(host) URI::Generic.build( scheme: use_tls? ? 'https' : 'http', host: host ) end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def ||= { builder: middleware, headers: { content_type: mime_type, accept: mime_type, user_agent: user_agent }, request: { open_timeout: CONNECTION_RETRY.fetch(:single_request_open_timeout), timeout: CONNECTION_RETRY.fetch(:single_request_timeout) } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::Exceptions setup_incoming_middleware builder, logger, fail_if_unsupported_mime_type: true # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def can_fallback_to_alternate_ably_host? !custom_host && !environment end def initialize_default_encoders Ably::Models::MessageEncoders.register_default_encoders self end end |
#channels ⇒ Aby::Rest::Channels (readonly)
The collection of Ably::Rest::Channels that have been created
48 49 50 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 48 def channels @channels end |
#client_id ⇒ String (readonly)
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 16 class Client include Ably::Modules::Conversions include Ably::Modules::HttpHelpers extend Forwardable # Default Ably domain for REST DOMAIN = 'rest.ably.io' # Configuration for connection retry attempts CONNECTION_RETRY = { single_request_open_timeout: 4, single_request_timeout: 15, cumulative_request_open_timeout: 10, max_retry_attempts: 3 }.freeze def_delegators :auth, :client_id, :auth_options # Custom environment to use such as 'sandbox' when testing the client library against an alternate Ably environment # @return [String] attr_reader :environment # The protocol configured for this client, either binary `:msgpack` or text based `:json` # @return [Symbol] attr_reader :protocol # {Ably::Auth} authentication object configured for this connection # @return [Ably::Auth] attr_reader :auth # The collection of {Ably::Rest::Channel}s that have been created # @return [Aby::Rest::Channels] attr_reader :channels # Log level configured for this {Client} # @return [Logger::Severity] attr_reader :log_level # The custom host that is being used if it was provided with the option `:rest_host` when the {Client} was created # @return [String,Nil] attr_reader :custom_host # The registered encoders that are used to encode and decode message payloads # @return [Array<Ably::Models::MessageEncoder::Base>] # @api private attr_reader :encoders # The additional options passed to this Client's #initialize method not available as attributes of this class # @return [Hash] # @api private attr_reader :options # Creates a {Ably::Rest::Client Rest Client} and configures the {Ably::Auth} object for the connection. # # @param [Hash,String] options an options Hash used to configure the client and the authentication, or String with an API key or Token ID # @option options (see Ably::Auth#authorise) # @option options [Boolean] :tls TLS is used by default, providing a value of false disables TLS. Please note Basic Auth is disallowed without TLS as secrets cannot be transmitted over unsecured connections. # @option options [String] :key API key comprising the key name and key secret in a single string # @option options [String] :token Token string or {Models::TokenDetails} used to authenticate requests # @option options [String] :token_details {Models::TokenDetails} used to authenticate requests # @option options [Boolean] :use_token_auth Will force Basic Auth if set to false, and Token auth if set to true # @option options [String] :environment Specify 'sandbox' when testing the client library against an alternate Ably environment # @option options [Symbol] :protocol Protocol used to communicate with Ably, :json and :msgpack currently supported. Defaults to :msgpack # @option options [Boolean] :use_binary_protocol Protocol used to communicate with Ably, defaults to true and uses MessagePack protocol. This option will overide :protocol option # @option options [Logger::Severity,Symbol] :log_level Log level for the standard Logger that outputs to STDOUT. Defaults to Logger::ERROR, can be set to :fatal (Logger::FATAL), :error (Logger::ERROR), :warn (Logger::WARN), :info (Logger::INFO), :debug (Logger::DEBUG) or :none # @option options [Logger] :logger A custom logger can be used however it must adhere to the Ruby Logger interface, see http://www.ruby-doc.org/stdlib-1.9.3/libdoc/logger/rdoc/Logger.html # # @return [Ably::Rest::Client] # # @example # # create a new client authenticating with basic auth # client = Ably::Rest::Client.new('key.id:secret') # # # create a new client and configure a client ID used for presence # client = Ably::Rest::Client.new(key: 'key.id:secret', client_id: 'john') # def initialize() raise ArgumentError, 'Options Hash is expected' if .nil? = .clone if .kind_of?(String) = if .match(/^[\w]{2,}\.[\w]{2,}:[\w]{2,}$/) { key: } else { token: } end end @tls = .delete(:tls) == false ? false : true @environment = .delete(:environment) # nil is production @protocol = .delete(:protocol) || :msgpack @debug_http = .delete(:debug_http) @log_level = .delete(:log_level) || ::Logger::ERROR @custom_logger = .delete(:logger) @custom_host = .delete(:rest_host) if @log_level == :none @custom_logger = Ably::Models::NilLogger.new else @log_level = ::Logger.const_get(log_level.to_s.upcase) if log_level.kind_of?(Symbol) || log_level.kind_of?(String) end .delete(:use_binary_protocol).tap do |use_binary_protocol| if use_binary_protocol == true @protocol = :msgpack elsif use_binary_protocol == false @protocol = :json end end raise ArgumentError, 'Protocol is invalid. Must be either :msgpack or :json' unless [:msgpack, :json].include?(@protocol) = .freeze @auth = Auth.new(self, ) @channels = Ably::Rest::Channels.new(self) @encoders = [] initialize_default_encoders end # Return a REST {Ably::Rest::Channel} for the given name # # @param (see Ably::Rest::Channels#get) # # @return (see Ably::Rest::Channels#get) def channel(name, = {}) channels.get(name, ) end # Retrieve the Stats for the application # # @param [Hash] options the options for the stats request # @option options [Integer,Time] :start Ensure earliest time or millisecond since epoch for any stats retrieved is +:start+ # @option options [Integer,Time] :end Ensure latest time or millisecond since epoch for any stats retrieved is +:end+ # @option options [Symbol] :direction +:forwards+ or +:backwards+, defaults to +:backwards+ # @option options [Integer] :limit Maximum number of messages to retrieve up to 1,000, defaults to 100 # @option options [Symbol] :unit `:minute`, `:hour`, `:day` or `:month`. Defaults to `:minute` # # @return [Ably::Models::PaginatedResult<Ably::Models::Stats>] An Array of Stats # def stats( = {}) = { :direction => :backwards, :unit => :minute, :limit => 100 }.merge() [:start, :end].each { |option| [option] = as_since_epoch([option]) if .has_key?(option) } = { coerce_into: 'Ably::Models::Stats' } url = '/stats' response = get(url, ) Ably::Models::PaginatedResult.new(response, url, self, ) end # Retrieve the Ably service time # # @return [Time] The time as reported by the Ably service def time response = get('/time', {}, send_auth_header: false) as_time_from_epoch(response.body.first) end # @!attribute [r] use_tls? # @return [Boolean] True if client is configured to use TLS for all Ably communication def use_tls? @tls == true end # Perform an HTTP GET request to the API using configured authentication # # @return [Faraday::Response] def get(path, params = {}, = {}) request(:get, path, params, ) end # Perform an HTTP POST request to the API using configured authentication # # @return [Faraday::Response] def post(path, params, = {}) request(:post, path, params, ) end # @!attribute [r] endpoint # @return [URI::Generic] Default Ably REST endpoint used for all requests def endpoint endpoint_for_host(custom_host || [@environment, DOMAIN].compact.join('-')) end # @!attribute [r] logger # @return [Logger] The {Ably::Logger} for this client. # Configure the log_level with the `:log_level` option, refer to {Client#initialize} def logger @logger ||= Ably::Logger.new(self, log_level, @custom_logger) end # @!attribute [r] mime_type # @return [String] Mime type used for HTTP requests def mime_type case protocol when :json 'application/json' else 'application/x-msgpack' end end # Register a message encoder and decoder that implements Ably::Models::MessageEncoders::Base interface. # Message encoders are used to encode and decode message payloads automatically. # @note Encoders and decoders are processed in the order they are added so the first encoder will be given priority when encoding and decoding # # @param [Ably::Models::MessageEncoders::Base] encoder # @return [void] # # @api private def register_encoder(encoder) encoder_klass = if encoder.kind_of?(String) encoder.split('::').inject(Kernel) do |base, klass_name| base.public_send(:const_get, klass_name) end else encoder end raise "Encoder must inherit from `Ably::Models::MessageEncoders::Base`" unless encoder_klass.ancestors.include?(Ably::Models::MessageEncoders::Base) encoders << encoder_klass.new(self) end # @!attribute [r] protocol_binary? # @return [Boolean] True of the transport #protocol communicates with Ably with a binary protocol def protocol_binary? protocol == :msgpack end # Connection used to make HTTP requests # # @param [Hash] options # @option options [Boolean] :use_fallback when true, one of the fallback connections is used randomly, see {Ably::FALLBACK_HOSTS} # # @return [Faraday::Connection] # # @api private def connection( = {}) if [:use_fallback] fallback_connection else @connection ||= Faraday.new(endpoint.to_s, ) end end # Fallback connection used to make HTTP requests. # Note, each request uses a random and then subsequent random {Ably::FALLBACK_HOSTS fallback host} # # @return [Faraday::Connection] # # @api private def fallback_connection unless @fallback_connections @fallback_connections = Ably::FALLBACK_HOSTS.shuffle.map { |host| Faraday.new(endpoint_for_host(host).to_s, ) } end @fallback_index ||= 0 @fallback_connections[@fallback_index % @fallback_connections.count].tap do @fallback_index += 1 end end private def request(method, path, params = {}, = {}) = .clone if .delete(:disable_automatic_reauthorise) == true send_request(method, path, params, ) else do send_request(method, path, params, ) end end end # Sends HTTP request to connection end point # Connection failures will automatically be reattempted until thresholds are met def send_request(method, path, params, ) max_retry_attempts = CONNECTION_RETRY.fetch(:max_retry_attempts) cumulative_timeout = CONNECTION_RETRY.fetch(:cumulative_request_open_timeout) requested_at = Time.now retry_count = 0 begin use_fallback = can_fallback_to_alternate_ably_host? && retry_count > 0 connection(use_fallback: use_fallback).send(method, path, params) do |request| unless [:send_auth_header] == false request.headers[:authorization] = auth.auth_header end end rescue Faraday::TimeoutError, Faraday::ClientError => error time_passed = Time.now - requested_at if can_fallback_to_alternate_ably_host? && retry_count < max_retry_attempts && time_passed <= cumulative_timeout retry_count += 1 retry end case error when Faraday::TimeoutError raise Ably::Exceptions::ConnectionTimeoutError.new(error., nil, 80014, error) when Faraday::ClientError raise Ably::Exceptions::ConnectionError.new(error., nil, 80000, error) end end end def yield rescue Ably::Exceptions::InvalidRequest => e if e.code == 40140 if auth.token_renewable? auth. force: true yield else raise Ably::Exceptions::InvalidToken.new(e., e.status, e.code) end else raise e end end def endpoint_for_host(host) URI::Generic.build( scheme: use_tls? ? 'https' : 'http', host: host ) end # Return a Hash of connection options to initiate the Faraday::Connection with # # @return [Hash] def ||= { builder: middleware, headers: { content_type: mime_type, accept: mime_type, user_agent: user_agent }, request: { open_timeout: CONNECTION_RETRY.fetch(:single_request_open_timeout), timeout: CONNECTION_RETRY.fetch(:single_request_timeout) } } end # Return a Faraday middleware stack to initiate the Faraday::Connection with # # @see http://mislav.uniqpath.com/2011/07/faraday-advanced-http/ def middleware @middleware ||= Faraday::RackBuilder.new do |builder| setup_outgoing_middleware builder # Raise exceptions if response code is invalid builder.use Ably::Rest::Middleware::Exceptions setup_incoming_middleware builder, logger, fail_if_unsupported_mime_type: true # Set Faraday's HTTP adapter builder.adapter Faraday.default_adapter end end def can_fallback_to_alternate_ably_host? !custom_host && !environment end def initialize_default_encoders Ably::Models::MessageEncoders.register_default_encoders self end end |
#custom_host ⇒ String, Nil (readonly)
The custom host that is being used if it was provided with the option ‘:rest_host` when the Ably::Rest::Client was created
56 57 58 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 56 def custom_host @custom_host end |
#encoders ⇒ Array<Ably::Models::MessageEncoder::Base> (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The registered encoders that are used to encode and decode message payloads
61 62 63 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 61 def encoders @encoders end |
#endpoint ⇒ URI::Generic (readonly)
205 206 207 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 205 def endpoint endpoint_for_host(custom_host || [@environment, DOMAIN].compact.join('-')) end |
#environment ⇒ String (readonly)
Custom environment to use such as ‘sandbox’ when testing the client library against an alternate Ably environment
36 37 38 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 36 def environment @environment end |
#log_level ⇒ Logger::Severity (readonly)
Log level configured for this Ably::Rest::Client
52 53 54 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 52 def log_level @log_level end |
#logger ⇒ Logger (readonly)
212 213 214 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 212 def logger @logger ||= Ably::Logger.new(self, log_level, @custom_logger) end |
#mime_type ⇒ String (readonly)
218 219 220 221 222 223 224 225 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 218 def mime_type case protocol when :json 'application/json' else 'application/x-msgpack' end end |
#options ⇒ Hash (readonly)
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
The additional options passed to this Client’s #initialize method not available as attributes of this class
66 67 68 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 66 def end |
#protocol ⇒ Symbol (readonly)
The protocol configured for this client, either binary ‘:msgpack` or text based `:json`
40 41 42 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 40 def protocol @protocol end |
#protocol_binary? ⇒ Boolean (readonly)
251 252 253 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 251 def protocol_binary? protocol == :msgpack end |
#use_tls? ⇒ Boolean (readonly)
185 186 187 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 185 def use_tls? @tls == true end |
Instance Method Details
#channel(name, channel_options = {}) ⇒ Ably::Rest::Channel
Return a REST Ably::Rest::Channel for the given name
140 141 142 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 140 def channel(name, = {}) channels.get(name, ) end |
#connection(options = {}) ⇒ Faraday::Connection
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Connection used to make HTTP requests
263 264 265 266 267 268 269 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 263 def connection( = {}) if [:use_fallback] fallback_connection else @connection ||= Faraday.new(endpoint.to_s, ) end end |
#fallback_connection ⇒ Faraday::Connection
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Fallback connection used to make HTTP requests. Note, each request uses a random and then subsequent random fallback host
277 278 279 280 281 282 283 284 285 286 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 277 def fallback_connection unless @fallback_connections @fallback_connections = Ably::FALLBACK_HOSTS.shuffle.map { |host| Faraday.new(endpoint_for_host(host).to_s, ) } end @fallback_index ||= 0 @fallback_connections[@fallback_index % @fallback_connections.count].tap do @fallback_index += 1 end end |
#get(path, params = {}, options = {}) ⇒ Faraday::Response
Perform an HTTP GET request to the API using configured authentication
192 193 194 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 192 def get(path, params = {}, = {}) request(:get, path, params, ) end |
#post(path, params, options = {}) ⇒ Faraday::Response
Perform an HTTP POST request to the API using configured authentication
199 200 201 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 199 def post(path, params, = {}) request(:post, path, params, ) end |
#register_encoder(encoder) ⇒ void
This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.
Encoders and decoders are processed in the order they are added so the first encoder will be given priority when encoding and decoding
This method returns an undefined value.
Register a message encoder and decoder that implements Ably::Models::MessageEncoders::Base interface. Message encoders are used to encode and decode message payloads automatically.
235 236 237 238 239 240 241 242 243 244 245 246 247 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 235 def register_encoder(encoder) encoder_klass = if encoder.kind_of?(String) encoder.split('::').inject(Kernel) do |base, klass_name| base.public_send(:const_get, klass_name) end else encoder end raise "Encoder must inherit from `Ably::Models::MessageEncoders::Base`" unless encoder_klass.ancestors.include?(Ably::Models::MessageEncoders::Base) encoders << encoder_klass.new(self) end |
#stats(options = {}) ⇒ Ably::Models::PaginatedResult<Ably::Models::Stats>
Retrieve the Stats for the application
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 155 def stats( = {}) = { :direction => :backwards, :unit => :minute, :limit => 100 }.merge() [:start, :end].each { |option| [option] = as_since_epoch([option]) if .has_key?(option) } = { coerce_into: 'Ably::Models::Stats' } url = '/stats' response = get(url, ) Ably::Models::PaginatedResult.new(response, url, self, ) end |
#time ⇒ Time
Retrieve the Ably service time
177 178 179 180 181 |
# File 'lib/submodules/ably-ruby/lib/ably/rest/client.rb', line 177 def time response = get('/time', {}, send_auth_header: false) as_time_from_epoch(response.body.first) end |