Types

The Ably client library defines both data types and option types. Data types are used to represent object such as messages. Option types are used in method arguments.

Where client libraries support both Realtime and REST APIs, the types are shared between both clients.

All types are always classes or their respective equivalent for each language implementation. Options on the other hand, may often support both typed option classes or more flexible key value objects such as a Hash or plain JavaScript object.

If you are interested in finding out more about the exact types and options definitions in each language, we recommend you download our open source libraries and review the code.

Data types

Ably::Exceptions::BaseAblyException

A BaseAblyException is an exception encapsulating error information containing an Ably-specific error code and generic status code, where applicable.

Attributes

PropertyDescriptionType
codeAbly error code (see ably-common/protocol/errors.json)Integer
status_codeHTTP Status Code corresponding to this error, where applicableInteger
messageAdditional message information, where availableString

ChannelDetails

ChannelDetails is an object returned when requesting or receiving channel metadata. It contains information on the channel itself, along with the current state of the channel in the ChannelStatus object.

PropertyDescriptionType
channelIdThe required name of the channel including any qualifier, if anystring
regionIn events relating to the activity of a channel in a specific region, this optionally identifies the regionstring
isGlobalMasterIn events relating to the activity of a channel in a specific region, this optionally identifies whether or not that region is responsible for global coordination of the channelboolean
statusAn optional ChannelStatus instanceChannelStatus

The following is an example of a ChannelDetails JSON object:

JSON

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

  {
    "channelId": "foo",
    "status": {
      "isActive": true,
      "occupancy": {
        "metrics": {
          "connections": 1,
          "publishers": 1,
          "subscribers": 1,
          "presenceConnections": 1,
          "presenceMembers": 0,
          "presenceSubscribers": 1,
          "objectPublishers": 1,
          "objectSubscribers": 1
        }
      }
    }
  }

ChannelDetails.ChannelStatus

ChannelStatus is contained within the ChannelDetails object, and optionally contains an Occupancy object.

PropertyDescriptionType
isActiveA required boolean value indicating whether the channel that is the subject of the event is active. For events indicating regional activity of a channel this indicates activity in that region, not global activityboolean
occupancyAn optional Occupancy instance indicating the occupancy of the channel. For events indicating regional activity of a channel this indicates activity in that region, not global activityOccupancy

ChannelDetails.ChannelStatus.Occupancy

Occupancy is optionally contained within the ChannelStatus object, and contains metadata relating to the occupants of the channel. This is usually contained within the occupancy attribute of the ChannelStatus object.

The occupancy attribute contains the metrics attribute, which contains the following members:

PropertyDescriptionType
connectionsThe number of connectionsinteger
publishersThe number of connections attached to the channel that are authorised to publishinteger
subscribersThe number of connections attached that are authorised to subscribe to messagesinteger
presenceSubscribersThe number of connections that are authorised to subscribe to presence messagesinteger
presenceConnectionsThe number of connections that are authorised to enter members into the presence channelinteger
presenceMembersThe number of members currently entered into the presence channelinteger
objectPublishersThe number of connections that are authorised to publish updates to objects on the channelinteger
objectSubscribersThe number of connections that are authorised to subscribe to objects on the channelinteger

Ably::Models::DeviceDetails

A DeviceDetails is a type encapsulating attributes of a device registered for push notifications.

Properties
PropertyDescriptionType
idunique identifier for the device generated by the device itselfString
client_idoptional trusted client identifier for the deviceString
form_factorform factor of the push device. Must be one of phone, tablet, desktop, tv, watch, car, or embeddedString
metadataoptional metadata object for this device. The metadata for a device may only be set by clients with push-admin privilegesObject
platformplatform of the push device. Must be one of ios or androidString
deviceSecretSecret value for the deviceString
push.recipientpush recipient details for this device. See the REST API push publish documentation for more detailsObject
push.statethe current state of the push device being either Active, Failing, or FailedString
push.error_reasonwhen the device's state is failing or failed, this attribute contains the reason for the most recent failureErrorInfo

Ably::Models::LocalDevice

An extension of DeviceDetails. In addition to the properties of DeviceDetails, it includes the following:

Properties
PropertyDescriptionType
deviceIdentityTokena unique identity token for the deviceString

Ably::Models::ErrorInfo

An ErrorInfo is a type encapsulating error information containing an Ably-specific error code and generic status code.

Properties

PropertyDescriptionType
codeAbly error code (see ably-common/protocol/errors.json)Integer
status_codeHTTP Status Code corresponding to this error, where applicableInteger
messageAdditional message information, where availableString
causeInformation pertaining to what caused the error where availableErrorInfo
hrefAbly may additionally include a URL to get more help on this errorString

Error nesting

ErrorInfo objects can contain nested errors through the cause property, allowing you to trace the root cause of failures. When an operation fails due to underlying system errors, the main ErrorInfo provides the high-level failure reason while the nested cause contains more specific details about what went wrong.

One example of ErrorInfo nesting is 80019: Auth server rejecting request where the main error indicates token renewal failed, while the nested cause contains the specific HTTP error from the auth server.

The following example demonstrates how to handle nested errors:

Ruby

1

2

3

4

5

6

7

8

9

10

11

def handle_error(error)
  puts "Main error: #{error.code} - #{error.message}"

  if error.cause
    puts "Root cause: #{error.cause.code} - #{error.cause.message}"

    if error.cause.cause
      puts "Deeper cause: #{error.cause.cause.code} - #{error.cause.cause.message}"
    end
  end
end

Ably::Models::Message

A Message represents an individual message that is sent to or received from Ably.

name

The event name, if provided.
Type: String

data

The message payload, if provided.

Type: String, Binary (ASCII-8BIT String), Hash, Array

extras

Metadata and/or ancillary payloads, if provided. Valid payloads include push, headers (a map of strings to strings for arbitrary customer-supplied metadata), ephemeral, and privileged objects.

Type: Hash, Array

id

A Unique ID assigned by Ably to this message.
Type: String

client_id

The client ID of the publisher of this message.
Type: String

connection_id

The connection ID of the publisher of this message.
Type: String

connectionKeyconnection_key

A connection key, which can optionally be included for a REST publish as part of the publishing on behalf of a realtime client functionality.
Type: String

timestamp

Timestamp when the message was first received by the Ably, as a Time object.

Type: Time

encoding

This will typically be empty as all messages received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payload.
Type: String

Message constructors

Message.fromEncoded

Message.fromEncoded(Object encodedMsg, ChannelOptions channelOptions?) -> Message

A static factory method to create a Message from a deserialized Message-like object encoded using Ably's wire protocol.

Parameters
ParameterDescriptionType
encodedMsgA Message-like deserialized objectObject
channelOptionsAn optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the dataObject
Returns

A Message object

Message.fromEncodedArray

Message.fromEncodedArray(Object[] encodedMsgs, ChannelOptions channelOptions?) -> Message[]

A static factory method to create an array of Messages from an array of deserialized Message-like object encoded using Ably's wire protocol.

Parameters
ParameterDescriptionType
encodedMsgsAn array of Message-like deserialized objectsArray
channelOptionsAn optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the dataObject
Returns

An Array of Message objects

MessageAnnotations

Attributes

PropertyDescriptionType
summaryAn object whose keys are annotation types, and whose values are aggregated summary entries for that annotation type. The structure of each value depends on the summarization method, for example a total.v1 entry will have a total field, while a flag.v1 entry will have total and clientIds fields. See annotation summaries for detailsRecord<String, JsonObject>

PublishResult

Contains the result of a publish operation.

Attributes

PropertyDescriptionType
serialsAn array of message serials corresponding 1:1 to the messages that were published. A serial may be null if the message was discarded due to a configured conflation rule.String[]

UpdateDeleteResult

Contains the result of an update, delete, or append message operation.

Attributes

PropertyDescriptionType
versionSerialThe serial of the version of the updated, deleted, or appended message. Will be null if the message was superseded by a subsequent update before it could be published.String

Ably::Models::PresenceMessage

A PresenceMessage represents an individual presence update that is sent to or received from Ably.

Properties

PropertyDescriptionType
actionThe event signified by a PresenceMessage. See PresenceMessage::ACTIONenum { :absent, :present, :enter, :leave, :update }
dataThe presence update payload, if providedString, Binary (ASCII-8BIT String), Hash, Array
extrasMetadata and/or ancillary payloads, if provided. The only currently valid payloads for extras are the push, ref and privileged objectsHash, Array
idUnique ID assigned by Ably to this presence updateString
client_idThe client ID of the publisher of this presence updateString
connection_idThe connection ID of the publisher of this presence updateString
timestampTimestamp when the presence update was received by AblyTime
encodingThis will typically be empty as all presence updates received from Ably are automatically decoded client-side using this value. However, if the message encoding cannot be processed, this attribute will contain the remaining transformations not applied to the data payloadString

PresenceMessage constructors

PresenceMessage.fromEncoded

PresenceMessage.fromEncoded(Object encodedPresMsg, ChannelOptions channelOptions?) -> PresenceMessage

A static factory method to create a PresenceMessage from a deserialized PresenceMessage-like object encoded using Ably's wire protocol.

Parameters
ParameterDescriptionType
encodedPresMsgA PresenceMessage-like deserialized objectObject
channelOptionsAn optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the dataObject
Returns

A PresenceMessage object

PresenceMessage.fromEncodedArray

PresenceMessage.fromEncodedArray(Object[] encodedPresMsgs, ChannelOptions channelOptions?) -> PresenceMessage[]

A static factory method to create an array of PresenceMessages from an array of deserialized PresenceMessage-like object encoded using Ably's wire protocol.

Parameters
ParameterDescriptionType
encodedPresMsgsAn array of PresenceMessage-like deserialized objectsArray
channelOptionsAn optional ChannelOptions. If you have an encrypted channel, use this to allow the library to decrypt the dataObject
Returns

An Array of PresenceMessage objects

Ably::Models::PresenceMessage::ACTION

Ably::Models::PresenceMessage::ACTION is an enum-like value representing all the Realtime Presence states & events. ACTION can be represented interchangeably as either symbols or constants.

Symbol states

Ruby

1

2

3

4

5

  :absent  # => 0 (reserved for internal use)
  :present # => 1
  :enter   # => 2
  :leave   # => 3
  :update  # => 4

Constant states

Ruby

1

2

3

4

5

  PresenceMessage::ACTION.Absent  # => 0 (internal use)
  PresenceMessage::ACTION.Present # => 1
  PresenceMessage::ACTION.Enter   # => 2
  PresenceMessage::ACTION.Leave   # => 3
  PresenceMessage::ACTION.Update  # => 4

Example usage

Ruby

1

2

3

4

5

6

7

8

  # Example with symbols
  presence.on(:attached) { ... }

  # Example with constants
  presence.on(Ably::Models::PresenceMessage::ACTION.Enter) { ... }

  # Interchangeable
  Ably::Models::PresenceMessage::ACTION.Enter == :enter # => true

Ably::Models::PaginatedResult

A PaginatedResult is a type that represents a page of results for all message and presence history, stats and REST presence requests. The response from a Ably REST API paginated query is accompanied by metadata that indicates the relative queries available to the PaginatedResult object.

Attributes

PropertyDescriptionType
itemsContains the current page of results (for example an Array of Message or PresenceMessage objects for a channel history request)Array <Message, Presence, Stats>

Methods

first

PaginatedResult first

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

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

PaginatedResult next

Returns a new PaginatedResult 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 a PaginatedResult.

Example

Ruby

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

# When using the REST sync library
first_page = channel.history
puts "Page 0 item 0: #{first_page.items[0].data}"
if first_page.has_next?
  next_page = first_page.next
  puts "Page 1 item 1: #{next_page.items[1].data}"
  puts "Last page?: #{next_page.is_last?}"
end

# When using the Realtime EventMachine library
channel.history do |first_page|
  puts "Page 0 item 0: #{first_page.items[0].data}"
  if first_page.has_next?
    first_page.next do |next_page|
      puts "Page 1 item 1: #{next_page.items[1].data}"
      puts "Last page?: #{next_page.is_last?}"
    end
  end
end

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
itemsContains a page of results; for example, an array of Message or PresenceMessage objects for a channel history requestArray<>
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

Ably::Models::PushChannelSubscription

An PushChannelSubscription is a type encapsulating the subscription of a device or group of devices sharing a client identifier to a channel in order to receive push notifications.

Properties

PropertyDescriptionType
channelThe channel that this push notification subscription is associated withString
device_idThe device with this identifier is linked to this channel subscription. When present, client_id is never presentString
client_idDevices with this client identifier are included in this channel subscription. When present, device_id is never presentString

Ably::Models::TokenDetails

TokenDetails is a type providing details of Ably Token string and its associated metadata.

Attributes

PropertyDescriptionType
tokenThe Ably Token itself. A typical Ably Token string may appear like {{TOKEN}}String
expiresThe time at which this token expiresTime
issuedThe time at which this token was issuedTime
capabilityThe capability associated with this Ably Token. The capability is a a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilitiesString
client_idThe client ID, if any, bound to this Ably Token. If a client ID is included, then the Ably Token authenticates its bearer as that client ID, and the Ably Token may only be used to perform operations on behalf of that client ID. The client is then considered to be an identified clientString

Methods

MethodDescriptionType
expired?True when the token has expiredBoolean

TokenDetails constructors

TokenDetails.from_json

TokenDetails.from_json(String json) -> TokenDetails

A static factory method to create a TokenDetails from a deserialized TokenDetails-like object or a JSON stringified TokenDetails. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenDetails object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenDetails, Ably ensures that all fields are consistently serialized and deserialized across platforms.

Parameters
ParameterDescriptionType
jsonA TokenDetails-like deserialized object or JSON stringified TokenDetailsObject, String
Returns

A TokenDetails object

Ably::Models::TokenRequest

TokenRequest is a type containing parameters for an Ably TokenRequest. Ably Tokens are requested using Auth#request_token

Attributes

PropertyDescriptionType
key_nameThe key name of the key against which this request is made. The key name is public, whereas the key secret is privateString
ttlRequested time to live for the Ably Token in seconds. If the Ably TokenRequest is successful, the TTL of the returned Ably Token will be less than or equal to this value depending on application settings and the attributes of the issuing key.Integer
timestampThe timestamp of this requestTime
capabilityCapability of the requested Ably Token. If the Ably TokenRequest is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. The capability is a JSON stringified canonicalized representation of the resource paths and associated operations. Read more about authentication and capabilitiesString
client_idThe client ID to associate with the requested Ably Token. When provided, the Ably Token may only be used to perform operations on behalf of that client IDString
nonceAn opaque nonce string of at least 16 charactersString
macThe Message Authentication Code for this requestString

TokenRequest constructors

TokenRequest.fromJson

TokenRequest.from_json(String json) -> TokenRequest

A static factory method to create a TokenRequest from a deserialized TokenRequest-like object or a JSON stringified TokenRequest. This method is provided to minimize bugs as a result of differing types by platform for fields such as timestamp or ttl. For example, in Ruby ttl in the TokenRequest object is exposed in seconds as that is idiomatic for the language, yet when serialized to JSON using to_json it is automatically converted to the Ably standard which is milliseconds. By using the fromJson method when constructing a TokenRequest, Ably ensures that all fields are consistently serialized and deserialized across platforms.

Parameters
ParameterDescriptionType
jsonA TokenRequest-like deserialized object or JSON stringified TokenRequestObject, String
Returns

A TokenRequest object

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.

Please note that most attributes of the Stats type below contain references to further stats types. This documentation is not exhaustive for all stats types, and as such, links to the stats types below will take you to the Ruby library stats documentation which contains exhaustive stats documentation. Ruby uses under_score case instead of the default camelCase in most languages, so please bear that in mind.

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 versions.Stats::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

Other types

AuthOptions Hash

AuthOptions is a Hash object and is used when making authentication requests. These options will supplement or override the corresponding options given when the library was instantiated. The following key symbol values can be added to the Hash:

Attributes

PropertyDescriptionType
:auth_callbackA functionproc / 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.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.String
:auth_method:get The HTTP verb to use for the request, either :get or :postSymbol
: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.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.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 authenticationTokenDetails
:keyOptionally the API key to use can be specified as a full key string; if not, the API key passed into ClientOptions when instancing the Realtime or REST library is usedString
:query_timefalse If 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.Boolean
:tokenAn authenticated token. This can either be a 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 authenticationString, TokenDetails or TokenRequest

ClientOptions Hash

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

PropertyDescriptionType
: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 authenticationString
: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 authenticationString, 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 callsProc
: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 serverString
:auth_methodThe HTTP verb to use for the request, either :get or :post
Default: :get
Symbol
: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 responseHash
: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 responseHash
: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 authenticationTokenDetails
: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
Default: true
Boolean
: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 identitiesString
: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
Default: false
Boolean
: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
Default: nil
String
: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
Default: nil
String
: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.
Default: true
Boolean
: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
Default: [a.ably-realtime.com, b.ably-realtime.com, c.ably-realtime.com, d.ably-realtime.com, e.ably-realtime.com]
String[]
:transport_paramsOptional. Can be used to pass in arbitrary connection parameters, such as heartbeatInterval and remainPresentForHash
: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
Default: :error
Symbol, Logger::SEVERITY
:loggerA Ruby Logger compatible object to handle each line of log output. If logger is not specified, STDOUT is used
Default: STDOUT Logger
Ruby 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
Default: true
Boolean
: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
Default: true
Boolean
:echo_messagesIf false, prevents messages originating from this connection being echoed back on the same connection
Default: true
Boolean
: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
Default: true
Boolean
: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 codeString
: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
Default: false
Boolean
:default_token_paramsWhen a TokenParams object is provided, it will override the client library defaults when issuing new Ably Tokens or Ably TokenRequestsTokenParams
: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
Default: 15s
Integer
: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
Default: 30s
Integer

ChannelOptions Hash

Channel options are used for configuring encryption.

ChannelOptions, a Hash object, may optionally be specified when instancing a Channel, and this may be used to specify channel-specific options. The following key symbol values can be added to the Hash:

Attributes

PropertyDescriptionType
:cipherRequests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an exampleCipherParams or an options hash containing at a minimum a key

Channel::STATE Enum

Ably::Realtime::Channel::STATE is an enum-like value representing all the Realtime Channel states. STATE can be represented interchangeably as either symbols or constants.

Symbol states

Ruby

1

2

3

4

5

6

:initialized # => 0
:attaching # =>   1
:attached # =>    2
:detaching # =>   3
:detached # =>    4
:failed # =>      5

Constant states

Ruby

1

2

3

4

5

6

Channel::STATE.Initialized # => 0
Channel::STATE.Attaching # =>   1
Channel::STATE.Attached # =>    2
Channel::STATE.Detaching # =>   3
Channel::STATE.Detached # =>    4
Channel::STATE.Failed # =>      5

Example usage

Ruby

1

2

3

4

5

6

7

8

# Example with symbols
channel.on(:attached) { ... }

# Example with constants
channel.on(Ably::Realtime::Channel::STATE.Attached) { ... }

# Interchangeable
Ably::Realtime::Channel::STATE.Attached == :attached # => true

Channel::EVENT Enum

Ably::Realtime::Channel::EVENT is an enum-like value representing all the events that can be emitted be the Channel; either a ChannelState or an :update event. EVENT can be represented interchangeably as either symbols or constants.

Symbol states

Ruby

1

2

3

4

5

6

7

:initialized # => 0
:attaching # =>   1
:attached # =>    2
:detaching # =>   3
:detached # =>    4
:failed # =>      5
:update # =>      6

Constant states

Ruby

1

2

3

4

5

6

7

Channel::EVENT.Initialized # => 0
Channel::EVENT.Attaching # =>   1
Channel::EVENT.Attached # =>    2
Channel::EVENT.Detaching # =>   3
Channel::EVENT.Detached # =>    4
Channel::EVENT.Failed # =>      5
Channel::EVENT.Update # =>      6

ChannelStateChange

A Ably::Models::ChannelStateChange is a type encapsulating state change information emitted by the Channel object. See Channel#on to register a listener for one or more events.

Properties

PropertyDescriptionType
currentThe new current stateChannel::STATE
previousThe previous state. (for the update event, this will be equal to the current state)Channel::STATE
eventThe event that triggered this state changeChannel::EVENT
reasonAn ErrorInfo containing any information relating to the transitionErrorInfo
resumedA boolean indicated whether message continuity on this channel is preserved, see Nonfatal channel errors for more info.Boolean

CipherParams Hash

A CipherParams contains configuration options for a channel cipher, including algorithm, mode, key length and key. Ably client libraries currently support AES with CBC, PKCS#7 with a default key length of 256 bits. All implementations also support AES128.

Individual client libraries may support either instancing a CipherParams directly, using Crypto.get_default_params(), or generating one automatically when initializing a channel, as in this example.

Properties

PropertyDescriptionType
:keyA binary (byte array) or base64-encoded String containing the secret key used for encryption and decryptionBinary or String
:algorithmAES The name of the algorithm in the default system provider, or the lower-cased version of it; eg "aes" or "AES"String
:key_length256 The key length in bits of the cipher, either 128 or 256Integer
:modeCBC The cipher modeString

Connection::STATE

Ably::Realtime::Connection::STATE is an enum-like value representing all the Realtime Connection states. STATE can be represented interchangeably as either symbols or constants.

Symbol states

Ruby

1

2

3

4

5

6

7

8

:initialized # =>  0
:connecting # =>   1
:connected # =>    2
:disconnected # => 3
:suspended # =>    4
:closing # =>      5
:closed # =>       6
:failed # =>       7

Constant states

Ruby

1

2

3

4

5

6

7

8

Connection::STATE.Initialized # =>  0
Connection::STATE.Connecting # =>   1
Connection::STATE.Connected # =>    2
Connection::STATE.Disconnected # => 3
Connection::STATE.Suspended # =>    4
Connection::STATE.Closing # =>      5
Connection::STATE.Closed # =>       6
Connection::STATE.Failed # =>       7

Example usage

Ruby

1

2

3

4

5

6

7

8

# Example with symbols
client.connection.on(:connected) { ... }

# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }

# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true

Connection::EVENT Enum

Ably::Realtime::Connection::EVENT is an enum-like value representing all the events that can be emitted be the Connection; either a Realtime Connection state or an :update event. EVENT can be represented interchangeably as either symbols or constants.

Symbol states

Ruby

1

2

3

4

5

6

7

8

9

:initialized # =>  0
:connecting # =>   1
:connected # =>    2
:disconnected # => 3
:suspended # =>    4
:closing # =>      5
:closed # =>       6
:failed # =>       7
:update # =>       8

Constant states

Ruby

1

2

3

4

5

6

7

8

9

Connection::EVENT.Initialized # =>  0
Connection::EVENT.Connecting # =>   1
Connection::EVENT.Connected # =>    2
Connection::EVENT.Disconnected # => 3
Connection::EVENT.Suspended # =>    4
Connection::EVENT.Closing # =>      5
Connection::EVENT.Closed # =>       6
Connection::EVENT.Failed # =>       7
Connection::EVENT.Update # =>       8

Example usage

Ruby

1

2

3

4

5

6

7

8

# Example with symbols
client.connection.on(:connected) { ... }

# Example with constants
client.connection.on(Ably::Realtime::Connection::STATE.Connected) { ... }

# Interchangeable
Ably::Realtime::Connection::STATE.Connected == :connected # => true

ConnectionStateChange

A Ably::Models::ConnectionStateChange is a type encapsulating state change information emitted by the Connection object. See Connection#on to register a listener for one or more events.

Attributes

PropertyDescriptionType
currentThe new stateConnection::STATE
previousThe previous state. (for the update event, this will be equal to the current state)Connection::STATE
eventThe event that triggered this state changeConnection::EVENT
reasonAn ErrorInfo containing any information relating to the transitionErrorInfo
retry_inDuration upon which the library will retry a connection where applicable, as secondsInteger

Ably::Util::SafeDeferrable

The SafeDeferrable class provides an EventMachine compatible Deferrable.

A SafeDeferrable ensures that any exceptions in callbacks provided by developers will not break the client library and stop further execution of code.

Methods

callback

callback(&block)

Specify a block to be executed if and when the Deferrable object receives a status of :succeeded. See the EventMachine callback documentation

errback

errback(&block)

Specify a block to be executed if and when the Deferrable object receives a status of :failed. See the EventMachine errback documentation

fail

fail(*args)

Mark the Deferrable as failed and trigger all callbacks. See the EventMachine fail documentation

succeed

succeed(*args)

Mark the Deferrable as succeeded and trigger all callbacks. See the EventMachine succeed documentation

TokenParams Hash

TokenParams is a Hash object and is used in the parameters of token authentication requests, corresponding to the desired attributes of the Ably Token. The following key symbol values can be added to the Hash:

Attributes

PropertyDescriptionType
:capabilityJSON stringified capability of the Ably Token. If the Ably Token request is successful, the capability of the returned Ably Token will be the intersection of this capability with the capability of the issuing key. Find our more about how to use capabilities to manage access privileges for clients.String
: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 identitiesString
:nonceAn optional opaque nonce string of at least 16 characters to ensure uniqueness of this request. Any subsequent request using the same nonce will be rejected.String
:timestampThe timestamp of this request. timestamp, in conjunction with the nonce, is used to prevent requests for Ably Token from being replayed.Time
:ttl1 hour Requested time to live for the Ably Token being created in seconds. When omitted, the Ably REST API default of 60 minutes is applied by AblyInteger (seconds)