Constructor

Constructor

The Ably Realtime library constructor is overloaded allowing it to be instantiated using a ClientOptions object, or more simply using a string containing an API key or Token, as shown below:

Ably::Realtime.new(ClientOptions client_options)

This will instantiate the library and create a new Ably::Realtime::Client using the specified ClientOptions.

Ably::Realtime.new(String key_or_token_id)

This will instantiate the Realtime library with the provided API key or Token ID string.

The Realtime constructor is used to instantiate the library. The Realtime library may be instantiated multiple times with the same or different ClientOptions in any given context. Except where specified otherwise, instances operate independently of one another.

Authentication

The Realtime library needs to have credentials to be able to authenticate with the Ably service. Ably supports both Basic and Token based authentication schemes. Read more on authentication.

Basic Authentication

You can pass a full-length API key in as ClientOptions#key (or just straight into the constructor instead of a ClientOptions instance), as obtained from the application dashboard. Use this option if you wish to use Basic authentication, or if you want to be able to request Ably Tokens without needing to defer to a separate entity to sign Ably TokenRequests. Note that initializing the library with a key does not necessarily mean that the library will use Basic auth; it is also able to create and sign Ably TokenRequests, and can use token authentication for itself if it needs to or if ClientOptions#useTokenAuth is enabled.

Token Authentication

The ClientOptions#token option takes a token string or tokenDetails object, which may have been obtained from some other instance that requested the Ably Token. This option is rarely used in production since tokens are short-lived, so generally you would not start with a token without the means to refresh it. The :auth_url and :auth_callback options allow the library to request new Ably-compatible tokens or Ably TokenRequests as it needs to; using these options allows the library to be instantiated without a key or token, and an initial token will be obtained automatically when required.

Read more on authentication.

Ably::Realtime::Client Attributes

The Realtime client exposes the following public attributes:

auth

A reference to the Auth authentication object configured for this client library.

push

A reference to the Push object in this client library.

channels

Channels is a reference to the Channel collection instance for this library indexed by the channel name. You can use the Get method of this to get a Channel instance. See channels and messages for more information.

connection

A reference to the Connection object for this library instance.

rest_client

A reference to the REST Client configured with the same ClientOptions. The Realtime library is a super-set of the REST library, however accessing methods in the REST library, unlike the Realtime library, are blocking operations.

Ably::Realtime::Client Methods

connect

Deferrable connect -> yields Connection

Explicitly calling connect is unnecessary unless the ClientOptions auto_connect is disabled. This method calls connection.connect and causes the connection to open, entering the connecting state.

Returns

A Deferrable object is returned from this method.

On successfully connecting to Ably, the registered success callbacks for the Deferrable and any block provided to this method yields a Connection object.

Failure to connect will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

close

Deferrable close -> yields Connection

This calls connection.close and causes the connection to close, entering the closing state. Once closed, the library will not attempt to re-establish the connection without an explicit call to connect.

Returns

A Deferrable object is returned from this method.

On successfully closing the connection, the registered success callbacks for the Deferrable and any block provided to this method yields a Connection object.

Failure to close the connection will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

stats

Deferrable stats(Hash options) ->; yields PaginatedResult<Stats>;

This call queries the REST /stats API and retrieves your application's usage statistics. A PaginatedResult is returned, containing an array of Stats for the first page of results. PaginatedResult objects are iterable providing a means to page through historical statistics. See an example set of raw stats returned via the REST API.

See statistics for more information.

Parameters

ParameterDescriptionType
optionsAn optional object containing the query parametersHash
&blockYields a PaginatedResult<Stats> objectBlock

options parameters

The following options, as defined in the REST /stats API endpoint, are permitted:

PropertyDescriptionTypeDefault
:startEarliest Time or time in milliseconds since the epoch for any stats retrievedInt or Timebeginning of time
:endLatest Time or time in milliseconds since the epoch for any stats retrievedInt or Timecurrent time
:direction:forwards or :backwardsSymbolbackwards
:limitMaximum number of stats to retrieve up to 1,000Integer100
:unit:minute, :hour, :day or :month. Based on the unit selected, the given start or end times are rounded down to the start of the relevant interval depending on the unit granularity of the querySymbolminute

Returns

A Deferrable object is returned from the stats method.

On success, the registered success callbacks for the Deferrable and any block provided to the method yields a PaginatedResult that encapsulates an array of Stats objects corresponding to the current page of results. PaginatedResult supports pagination using next and first methods.

Failure to retrieve the stats will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

time

Deferrable time -> yields Time

Obtains the time from the Ably service as a Time object. (Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably TokenRequests with a more accurate timestamp should use the queryTime clientOptions instead of this method).

Returns

A Deferrable object is returned from this method.

On success, the registered success callbacks for the Deferrable and any block provided to the method yields a Time object.

Failure to retrieve the Ably server time will trigger the errback callbacks of the Deferrable with an ErrorInfo object containing an error response as defined in the Ably REST API documentation.

request

HttpPaginatedResponse request(String method, String path, Object params, Object body, Object headers)

Makes a REST request to a provided path. This is provided as a convenience for developers who wish to use REST API functionality that is either not documented or is not yet included in the public API, without having to handle authentication, paging, fallback hosts, MsgPack and JSON support, etc. themselves.

Parameters

ParameterDescriptionType
methodEither get, post, put, patch or deleteString
pathThe path to queryString
params(Optional) Any querystring parameters neededObject
body(Optional; for post, put and patch methods) The body of the request, as anything that can be serialized into JSON, such as an Object or ArraySerializable
headers(Optional) Any headers needed. If provided, these will be mixed in with the default library headersObject

Returns

On successfully receiving a response from Ably, the returned HttpPaginatedResponse contains a status_code and a success boolean, headers, and an items array containing the current page of results. It supports pagination using next and first methods, identically to PaginatedResult.

Failure to obtain a response will raise an AblyException. (Note that if a response is obtained, any response, even with a non-2xx status code, will result in an HTTP Paginated Response, not an exception).

ClientOptions

ClientOptions is a Hash object and is used in the Ably::Realtime constructor's options argument. The following key symbol values can be added to the Hash:

Attributes

PropertyDescription
:keyThe full key string, as obtained from the application dashboard. Use this option if you wish to use Basic authentication, or wish to be able to issue Ably Tokens without needing to defer to a separate entity to sign Ably TokenRequests. Read more about Basic authentication
Type: String
:tokenAn authenticated TokenDetails object, a TokenRequest object, or token string (obtained from the :token property of a TokenDetails component of an Ably TokenRequest response, or a JSON Web Token satisfying the Ably requirements for JWTs). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as :auth_url or :auth_callback. Read more about Token authentication
Type: String, TokenDetails or TokenRequest
:auth_callbackA proc / lambda (called synchronously in REST and Realtime but does not block EventMachine in the latter) which is called when a new token is required. The role of the callback is to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed TokenRequest; a TokenDetails (in JSON format); an Ably JWT. See our authentication documentation for details of the Ably TokenRequest format and associated API calls
Type: Proc
:auth_urlA URL that the library may use to obtain a fresh token, one of: an Ably Token string (in plain text format); a signed TokenRequest; a TokenDetails (in JSON format); an Ably JWT. For example, this can be used by a client to obtain signed Ably TokenRequests from an application server
Type: String
:auth_methodThe HTTP verb to use for the request, either :get or :post
Type: Symbol
Default: :get
:auth_headersA set of key value pair headers to be added to any request made to the :auth_url. Useful when an application requires these to be added to validate the request or implement the response
Type: Hash
:auth_paramsA set of key value pair params to be added to any request made to the :auth_url. When the :auth_method is GET, query params are added to the URL, whereas when :auth_method is POST, the params are sent as URL encoded form data. Useful when an application require these to be added to validate the request or implement the response
Type: Hash
:token_detailsAn authenticated TokenDetails object (most commonly obtained from an Ably Token Request response). This option is mostly useful for testing: since tokens are short-lived, in production you almost always want to use an authentication method that allows the client library to renew the token automatically when the previous one expires, such as :auth_url or :auth_callback. Use this option if you wish to use Token authentication. Read more about Token authentication
Type: TokenDetails
:tlsA boolean value, indicating whether or not a TLS ("SSL") secure connection should be used. An insecure connection cannot be used with Basic authentication as it would lead to a possible compromise of the private API key while in transit. Find out more about TLS
Type: Boolean
Default: true
:client_idA client ID, used for identifying this client when publishing messages or for presence purposes. The client_id can be any non-empty string. This option is primarily intended to be used in situations where the library is instantiated with a key; note that a client_id may also be implicit in a token used to instantiate the library; an error will be raised if a client_id specified here conflicts with the client_id implicit in the token. Find out more about client identities
Type: String
:use_token_authWhen true, forces Token authentication to be used by the library. Please note that if a client_id is not specified in the ClientOptions or TokenParams, then the Ably Token issued will be anonymous
Type: Boolean
Default: false
:endpointEnables enterprise customers to use their own custom endpoints, which support dedicated, isolated clusters and regional message routing and storage constraints. See our platform customization guide for more details
Type: String
Default: nil
:environmentDeprecated, use endpoint. Enables enterprise customers to use their own custom environments, which support dedicated, isolated clusters and regional message routing and storage constraints. See our platform customization guide for more details
Type: String
Default: nil
:idempotent_rest_publishingWhen true, enables idempotent publishing by assigning a unique message ID client-side, allowing the Ably servers to discard automatic publish retries following a failure such as a network fault. Enabled by default in all current Ably SDKs.
Type: Boolean
Default: true
:fallback_hostsAn array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. When a custom environment is specified, the fallback host functionality is disabled. If your customer success manager has provided you with a set of custom fallback hosts, please specify them here
Type: String[]
Default: [a.ably-realtime.com, b.ably-realtime.com, c.ably-realtime.com, d.ably-realtime.com, e.ably-realtime.com]
:transport_paramsOptional. Can be used to pass in arbitrary connection parameters, such as heartbeatInterval and remainPresentFor
Type: Hash
:log_levelLog level for the standard Logger that outputs to STDOUT. Can be set to :fatal, :error, :warn, :info, :debug or :none. Alternatively a Logger severity constant can be specified
Type: Symbol, Logger::SEVERITY
Default: :error
:loggerA Ruby Logger compatible object to handle each line of log output. If logger is not specified, STDOUT is used
Type: Ruby Logger
Default: STDOUT Logger
:use_binary_protocolIf set to false, will forcibly disable the binary protocol (MessagePack). The binary protocol is used by default unless it is not supported. Find out more about the benefits of binary encoding
Type: Boolean
Default: true
:queue_messagesIf false, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior allows applications to submit messages immediately upon instancing the library without having to wait for the connection to be established. Applications may use this option to disable queueing if they wish to have application-level control over the queueing under those conditions
Type: Boolean
Default: true
:echo_messagesIf false, prevents messages originating from this connection being echoed back on the same connection
Type: Boolean
Default: true
:auto_connectBy default as soon as the client library is instantiated it will connect to Ably. You can optionally set this to false and explicitly connect to Ably when require using the connect method
Type: Boolean
Default: true
:recoverThis option allows a connection to inherit the state of a previous connection that may have existed under a different instance of the library by providing that connection's recovery_key. This might typically be used by clients of an app to ensure connection state can be preserved following a reload. See connection state recovery for further information and example code
Type: String
:query_timeIf true, the library will query the Ably servers for the current time when issuing TokenRequests instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably TokenRequests, so this option is useful for library instances on auth servers where for some reason the server clock cannot be kept synchronized through normal means, such as an NTP daemon. The server is queried for the current time once per client library instance (which stores the offset from the local clock), so if using this option you should avoid instancing a new version of the library for each request
Type: Boolean
Default: false
:default_token_paramsWhen a TokenParams object is provided, it will override the client library defaults when issuing new Ably Tokens or Ably TokenRequests
Type: TokenParams
:disconnected_retry_timeoutWhen the connection enters the DISCONNECTED state, after this delay in seconds, if the state is still DISCONNECTED, the client library will attempt to reconnect automatically
Type: Integer
Default: 15s
:suspended_retry_timeoutWhen the connection enters the SUSPENDED state, after this delay in seconds, if the state is still SUSPENDED, the client library will attempt to reconnect automatically
Type: Integer
Default: 30s

Ably::Models::Stats

A Stats object represents an application's statistics for the specified interval and time period. Ably aggregates statistics globally for all accounts and applications, and makes these available both through our statistics API as well as your application dashboard.

Attributes

PropertyDescriptionType
unitThe length of the interval that this statistic covers, such as :minute, :hour, :day, :monthStats::GRANULARITY
interval_granularityDeprecated alias for unit; scheduled to be removed in version 2.x client library versionsStats::GRANULARITY
interval_idThe UTC time at which the time period covered by this Stats object starts. For example, an interval ID value of "2018-03-01:10" in a Stats object whose unit is day would indicate that the period covered is "2018-03-01:10 .. 2018-03-01:11". All Stats objects, except those whose unit is minute, have an interval ID with resolution of one hour and the time period covered will always begin and end at a UTC hour boundary. For this reason it is not possible to infer the unit by looking at the resolution of the intervalId. Stats objects covering an individual minute will have an interval ID indicating that time; for example "2018-03-01:10:02"String
interval_timeA Time object representing the parsed interval_id (the UTC time at which the time period covered by this Stats object starts)Time
allAggregate count of both inbound and outbound message statsMessageTypes
api_requestsBreakdown of API requests received via the Ably REST APIRequestCount
channelsBreakdown of channel related stats such as min, mean and peak channelsResourceCount
connectionsBreakdown of connection related stats such as min, mean and peak connections for TLS and non-TLS connectionsConnectionTypes
inboundStatistics such as count and data for all inbound messages received over REST and Realtime connections, organized into normal channel messages or presence messagesMessageTraffic
outboundStatistics such as count and data for all outbound messages retrieved via REST history requests, received over Realtime connections, or pushed with Webhooks, organized into normal channel messages or presence messagesMessageTraffic
persistedMessages persisted and later retrieved via the history APIMessageTypes
token_requestsBreakdown of Ably Token requests received via the Ably REST APIRequestCount
pushDetailed stats on push notifications, see our Push documentation for more detailsPushStats

HttpPaginatedResponse

An HttpPaginatedResponse is a superset of PaginatedResult, which is a type that represents a page of results plus metadata indicating the relative queries available to it. HttpPaginatedResponse additionally carries information about the response to an HTTP request. It is used when making custom HTTP requests.

Attributes

PropertyDescriptionType
status_codeThe HTTP status code of the responseNumber
successWhether the HTTP status code indicates success. This is equivalent to 200 <= status_code < 300Boolean
headersThe headers of the responseObject
error_codeThe error code if the X-Ably-Errorcode HTTP header is sent in the responseInt
error_messageThe error message if the X-Ably-Errormessage HTTP header is sent in the responseString

Methods

first

HttpPaginatedResponse first

Returns a new HttpPaginatedResponse for the first page of results. When using the Realtime library, the first method returns a Deferrable and yields an HttpPaginatedResponse.

has_next?

Boolean has_next?

Returns true if there are more pages available by calling next and returns false if this page is the last page available.

last?

Boolean last?

Returns true if this page is the last page and returns false if there are more pages available by calling next available.

next

HttpPaginatedResponse next

Returns a new HttpPaginatedResponse loaded with the next page of results. If there are no further pages, then null is returned. When using the Realtime library, the first method returns a Deferrable and yields an HttpPaginatedResponse.

Example

The HttpPaginatedResponse interface is a superset of PaginatedResult, see the PaginatedResult example