ably

package
v1.2.17 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 2, 2024 License: Apache-2.0 Imports: 38 Imported by: 21

Documentation

Overview

Package ably

Ably Go Client Library SDK API Reference

The Go Client Library SDK supports a realtime and a REST interface. The Go API references are generated from the Ably Go Client Library SDK source code using godoc and structured by classes.

The realtime interface enables a client to maintain a persistent connection to Ably and publish, subscribe and be present on channels. The REST interface is stateless and typically implemented server-side. It is used to make requests such as retrieving statistics, token authentication and publishing to a channel.

View the Ably docs for conceptual information on using Ably, and for API references featuring all languages. The combined API references are organized by features and split between the realtime and REST interfaces.

Get started at https://github.com/ably/ably-go#using-the-realtime-api.

Event Emitters

An event emitter pattern appears in multiple places in the library.

The On method takes an event type identifier and a handler function to be called with the event's associated data whenever an event of that type is emitted in the event emitter. It also returns an "off" function to undo this operation, so that the handler function isn't called anymore.

The OnAll method is like On, but for events of all types.

The Once method works like On, except the handler is just called once, for the first matching event.

OnceAll is like OnAll in the same way Once is like On.

The Off method is like calling the "off" function returned by calls to On and Once methods with a matching event type identifier.

The OffAll method is like Off, except it is like calling all the "off" functions.

Each handler is assigned its own sequential queue of events. That is, any given handler function will not receive calls from different goroutines that run concurrently; you can count on the next call to a handler to happen after the previous call has returned, and you can count on events or messages to be delivered to the handler in the same order they were emitted. Different handlers may be called concurrently, though.

Calling any of these methods an "off" function inside a handler will only have effect for subsequent events.

For messages and presence messages, "on" is called "subscribe" and "off" is called "unsubscribe".

Paginated results

Most requests to the Ably REST API return a single page of results, with hyperlinks to the first and next pages in the whole collection of results. To facilitate navigating through these pages, the library provides access to such paginated results though a common pattern.

A method that prepares a paginated request returns a Request object with two methods: Pages and Items. Pages returns a PaginatedResult, an iterator that, on each iteration, yields a whole page of results. Items is simply a convenience wrapper that yields single results instead.

In both cases, calling the method validates the request and may return an error.

Then, for accessing the results, the Next method from the resulting iterator object must be called repeatedly; each time it returns true, the result that has been retrieved can be inspected with the Items or Item method from the iterator object. Finally, once it returns false, the Err method must be called to check if the iterator stopped due to some error, or else, it just finished going through all pages.

Calling the First method on the PaginatedResults returns the first page of the results. However, the Next method has to be called before inspecting the items.

For every page in the PaginatedResults, the HasNext method can be called to check if there are more page(s) available. IsLast method checks if the page is the last page. Both methods return a true or false value.

See the PaginatedResults example.

Example (PaginatedResults)
package main

import (
	"fmt"

	"context"
	"github.com/ably/ably-go/ably"
)

func main() {
	ctx := context.Background()
	client, err := ably.NewRealtime(ably.WithKey("xxx:xxx"))
	if err != nil {
		panic(err)
	}
	channel := client.Channels.Get("persisted:test")

	err = channel.Publish(ctx, "EventName1", "EventData1")
	if err != nil {
		panic(err)
	}

	pages, err := channel.History().Pages(ctx)
	if err != nil {
		panic(err)
	}

	// Returning and iterating over the first page
	pages.Next(ctx)
	pages.First(ctx)
	for _, message := range pages.Items() {
		fmt.Println(message)
	}

	// Iteration over pages in PaginatedResult
	for pages.Next(ctx) {
		fmt.Println(pages.HasNext(ctx))
		fmt.Println(pages.IsLast(ctx))
		for _, presence := range pages.Items() {
			fmt.Println(presence)
		}
	}
	if err := pages.Err(); err != nil {
		panic(err)
	}
}
Output:

Index

Examples

Constants

View Source
const (
	Port    = 80
	TLSPort = 443
)
View Source
const (
	// StatGranularityMinute specifies interval unit over which statistics are gathered as minutes.
	StatGranularityMinute = "minute"
	// StatGranularityHour specifies interval unit over which statistics are gathered as hours.
	StatGranularityHour = "hour"
	// StatGranularityDay specifies interval unit over which statistics are gathered as days.
	StatGranularityDay = "day"
	// StatGranularityMonth specifies interval unit over which statistics are gathered as months.
	StatGranularityMonth = "month"
)

Variables

View Source
var Crypto struct {

	// GenerateRandomKey returns a random key (as a binary/a byte array) to be used in the encryption of the channel.
	// If the language cryptographic randomness primitives are blocking or async, a callback is used.
	// The callback returns a generated binary key.
	// keyLength is passed as a param. It is a length of the key, in bits, to be generated.
	// If not specified, this is equal to the default keyLength of the default algorithm:
	// for AES this is 256 bits (RSE2).
	GenerateRandomKey func(keyLength int) ([]byte, error)

	// GetDefaultParams returns a [ably.CipherParams] object, using the default values for any fields
	// not supplied by the [ably.CipherParamOptions] object. The Key field must be provided (RSE1).
	GetDefaultParams func(CipherParams) CipherParams
}

Crypto contains the properties required to configure the encryption of ably.Message payloads.

Functions

This section is empty.

Types

type Auth

type Auth struct {
	// contains filtered or unexported fields
}

Auth creates Ably ably.TokenRequest objects and obtains Ably Tokens from Ably to subsequently issue to less trusted clients.

func (*Auth) Authorize added in v1.1.0

func (a *Auth) Authorize(ctx context.Context, params *TokenParams, setOpts ...AuthOption) (*TokenDetails, error)

Authorize instructs the library to get a new authorized token immediately from ably server. When using the realtime client, it upgrades the current realtime connection to use the new token, or if not connected, initiates a connection to Ably, once the new token has been obtained. Also stores any ably.TokenParams and ably.AuthOption passed in as the new defaults, to be used for all subsequent implicit or explicit token requests. Any ably.TokenParams and ably.AuthOption objects passed in entirely replace, as opposed to being merged with, the current client library saved values (RSA10).

func (*Auth) ClientID

func (a *Auth) ClientID() string

ClientID method returns clientId if not a wildcard string (*), otherwise returns an empty string. It is used for identifying this client when publishing messages or for presence purposes. The clientId can be any non-empty string, except it cannot contain a *. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a clientId may also be implicit in a token used to instantiate the library. An error is raised if a clientId specified here conflicts with the clientId implicit in the token. Find out more about identified clients (RSA7, RSC17, RSA12).

func (*Auth) CreateTokenRequest

func (a *Auth) CreateTokenRequest(params *TokenParams, opts ...AuthOption) (*TokenRequest, error)

CreateTokenRequest creates and signs an Ably ably.TokenRequest based on the specified (or if none specified, the client library stored) ably.TokenParams and ably.AuthOption. Note this can only be used when the API key value is available locally. Otherwise, the Ably ably.TokenRequest must be obtained from the key owner. Use this to generate an Ably ably.TokenRequest in order to implement an Ably Token request callback for use by other clients. Both ably.TokenParams and ably.AuthOption are optional. When omitted or null, the default token parameters and authentication options for the client library are used, as specified in the ably.ClientOption when the client library was instantiated, or later updated with an explicit authorize request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably ably.TokenRequest may be issued to clients in favor of a token, see Token Authentication explained (RSA9).

func (*Auth) RequestToken

func (a *Auth) RequestToken(ctx context.Context, params *TokenParams, opts ...AuthOption) (*TokenDetails, error)

RequestToken Calls the requestToken REST API endpoint to obtain an Ably Token according to the specified ably.TokenParams and ably.AuthOption. Both ably.TokenParams and ably.AuthOption are optional. When omitted or null, the default token parameters and authentication options for the client library are used, as specified in the ably.ClientOption when the client library was instantiated, or later updated with an explicit authorize request. Values passed in are used instead of, rather than being merged with, the default values. To understand why an Ably ably.TokenRequest may be issued to clients in favor of a token, see Token Authentication explained (RSA8e).

type AuthOption added in v1.2.0

type AuthOption func(*authOptions)

AuthOption configures authentication/authorization for a ably.REST or ably.Realtime instance or operation.

func AuthWithCallback added in v1.2.0

func AuthWithCallback(authCallback func(context.Context, TokenParams) (Tokener, error)) AuthOption

AuthWithCallback is used for setting AuthCallback function using ably.AuthOption.

AuthCallback function is called when a new token is required. The role of the callback is to obtain a fresh token, one of

  1. An Ably Token string (https://ably.com/docs/core-features/authentication#token-process)
  2. A signed ably.TokenRequest (https://ably.com/docs/core-features/authentication#token-request-process)
  3. An ably.TokenDetails (https://ably.com/docs/core-features/authentication#token-process)
  4. An Ably JWT.

See the authentication doc for more details and associated API calls (RSA4a, RSA4, TO3j5, AO2b).

func AuthWithDefaultTokenParams added in v1.2.0

func AuthWithDefaultTokenParams(params TokenParams) AuthOption

AuthWithDefaultTokenParams is used for setting DefaultTokenParams token using ably.AuthOption. DefaultTokenParams when provided, it overrides the client library defaults when issuing new Ably Tokens for multiple Ably ably.TokenRequest (TO3j11).

func AuthWithHeaders added in v1.2.0

func AuthWithHeaders(headers http.Header) AuthOption

AuthWithHeaders is used for setting AuthHeaders using ably.AuthOption. AuthHeaders are key-value pair HTTP request headers to be added to any request made to the AuthURL. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials is set on the XHR request. (RSA8c3, TO3j8, AO2e).

func AuthWithKey added in v1.2.0

func AuthWithKey(key string) AuthOption

AuthWithKey is used for setting root/non-root apikey using ably.AuthOption. Key is a full API key string, as obtained from the Ably 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 multiple ably.TokenRequest. Read more about Basic authentication (RSA11, RSA14, TO3j1, AO2a).

func AuthWithMethod added in v1.2.0

func AuthWithMethod(method string) AuthOption

AuthWithMethod is used for setting AuthMethod using ably.AuthOption AuthMethod specifies HTTP verb to use for any request made to the AuthURL, either GET or POST for getting token information ably.TokenRequest or ably.TokenDetails. The default value is GET (RSA8c, TO3j7, AO2d).

func AuthWithParams added in v1.2.0

func AuthWithParams(params url.Values) AuthOption

AuthWithParams is used for setting AuthParams using ably.AuthOption. AuthParams are key-value pair HTTP query params to be added to any request made to the AuthURL. When the authMethod is GET, query params are added to the URL, whereas when authMethod is POST, the params are sent as URL encoded form data. Useful when an application requires these to be added to validate the request or implement the response (RSA8c3, RSA8c1, TO3j9, AO2f).

func AuthWithQueryTime added in v1.2.0

func AuthWithQueryTime(queryTime bool) AuthOption

AuthWithQueryTime is used for setting UseQueryTime token using ably.AuthOption. UseQueryTime when set to true, the library queries the Ably servers for the current time when issuing multiple ably.TokenRequest instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably ably.TokenRequest, 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. The default is false (RSA9d, TO3j10, AO2a).

func AuthWithToken added in v1.2.0

func AuthWithToken(token string) AuthOption

AuthWithToken is used for setting authenticated token using ably.AuthOption. This can either be a token string (obtained from the token property of a ably.TokenDetails component of an Ably 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 enables the client library to renew the token automatically when the previous one expires, such as AuthURL or authCallback. Read more about Token authentication (RSA4a, RSA4, TO3j2).

func AuthWithTokenDetails added in v1.2.0

func AuthWithTokenDetails(details *TokenDetails) AuthOption

AuthWithTokenDetails is used for setting authenticated ably.TokenDetails object using ably.AuthOption. Only TokenDetails.Token can be set via token string (obtained from the token property of a ably.TokenDetails component of an Ably 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 enables the client library to renew the token automatically when the previous one expires, such as AuthURL or authCallback. Read more about Token authentication (RSA4a, RSA4, TO3j3).

func AuthWithURL added in v1.2.0

func AuthWithURL(url string) AuthOption

AuthWithURL is used for setting AuthURL using ably.AuthOption. AuthURL is a url that library will use to obtain

  1. An Ably Token string (https://ably.com/docs/core-features/authentication#token-process)
  2. A signed ably.TokenRequest (https://ably.com/docs/core-features/authentication#token-request-process)
  3. An ably.TokenDetails (https://ably.com/docs/core-features/authentication#token-process)
  4. An Ably JWT.

See the authentication doc for more details and associated API calls (RSA4a, RSA4, RSA8c, TO3j6, AO2c).

This enables a client to obtain token requests from another entity, so tokens can be renewed without the client requiring access to keys.

If AuthURL is non-empty and AuthCallback is nil, the Ably library builds a req (*http.Request) which then is issued against the given AuthURL in order to obtain authentication token. The response is expected to carry a single token string in the payload when Content-Type header is "text/plain" or JSON-encoded *ably.TokenDetails when the header is "application/json".

The req is built with the following values:

GET requests:

  • req.URL.RawQuery is encoded from *TokenParams and AuthParams
  • req.Header is set to AuthHeaders

POST requests:

  • req.Header is set to AuthHeaders
  • Content-Type is set to "application/x-www-form-urlencoded" and the payload is encoded from *TokenParams and AuthParams

func AuthWithUseTokenAuth added in v1.2.0

func AuthWithUseTokenAuth(use bool) AuthOption

AuthWithUseTokenAuth is used for setting UseTokenAuth using ably.AuthOption. UseTokenAuth when set to true, forces token authentication to be used by the library. If a clientId is not specified in the ably.ClientOption or ably.TokenParams, then the Ably Token issued is anonymous (RSA4, RSA14, TO3j4).

type ChannelDetails added in v1.2.7

type ChannelDetails struct {
	// ChannelId is the identifier of the channel (CHD2a).
	ChannelId string `json:"channelId" codec:"channelId"`
	// Status is a [ably.ChannelStatus] object (CHD2b).
	Status ChannelStatus `json:"status" codec:"status"`
}

ChannelDetails contains the details of a ably.RESTChannel or ably.RealtimeChannel object such as its ID and ably.ChannelStatus.

type ChannelEvent added in v1.2.0

type ChannelEvent struct {
	// contains filtered or unexported fields
}

ChannelEvent describes the events emitted by a ably.RESTChannel or ably.RealtimeChannel object. An event is either an UPDATE or a ably.ChannelState.

var (

	// ChannelEventInitialized is when the channel has been initialized but no attach has yet been attempted.
	ChannelEventInitialized ChannelEvent = ChannelEvent(ChannelStateInitialized)

	// ChannelEventAttaching is when the attach has been initiated by sending a request to Ably.
	// This is a transient state, followed either by a transition to ATTACHED, SUSPENDED, or FAILED.
	ChannelEventAttaching ChannelEvent = ChannelEvent(ChannelStateAttaching)

	// ChannelEventAttached is when the attach has succeeded.
	// In the ATTACHED state a client may publish and subscribe to messages, or be present on the channel.
	ChannelEventAttached ChannelEvent = ChannelEvent(ChannelStateAttached)

	// ChannelEventDetaching is when a detach has been initiated on an ATTACHED channel by sending a request to Ably.
	// This is a transient state, followed either by a transition to DETACHED or FAILED.
	ChannelEventDetaching ChannelEvent = ChannelEvent(ChannelStateDetaching)

	// ChannelEventDetached os when the channel, having previously been ATTACHED, has been detached by the user.
	ChannelEventDetached ChannelEvent = ChannelEvent(ChannelStateDetached)

	// ChannelEventSuspended is when the channel, having previously been ATTACHED, has lost continuity,
	// usually due to the client being disconnected from Ably for longer than two minutes.
	// It will automatically attempt to reattach as soon as connectivity is restored.
	ChannelEventSuspended ChannelEvent = ChannelEvent(ChannelStateSuspended)

	// ChannelEventFailed is an indefinite failure condition.
	// This state is entered if a channel error has been received from the Ably service,
	// such as an attempt to attach without the necessary access rights.
	ChannelEventFailed ChannelEvent = ChannelEvent(ChannelStateFailed)

	// ChannelEventUpdate is an event for changes to channel conditions that do not result
	// in a change in [ably.ChannelState] (RTL2g).
	ChannelEventUpdate ChannelEvent = ChannelEvent{/* contains filtered or unexported fields */}
)

func (ChannelEvent) String added in v1.2.0

func (e ChannelEvent) String() string

type ChannelEventEmitter added in v1.2.0

type ChannelEventEmitter struct {
	// contains filtered or unexported fields
}

func (ChannelEventEmitter) Off added in v1.2.0

Off deregisters event handlers for connection events of a specific kind.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (ChannelEventEmitter) OffAll added in v1.2.0

func (em ChannelEventEmitter) OffAll()

OffAll de-registers all event handlers.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (ChannelEventEmitter) On added in v1.2.0

func (em ChannelEventEmitter) On(e ChannelEvent, handle func(ChannelStateChange)) (off func())

On registers an event handler for connection events of a specific kind.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (ChannelEventEmitter) OnAll added in v1.2.0

func (em ChannelEventEmitter) OnAll(handle func(ChannelStateChange)) (off func())

OnAll registers an event handler for all connection events.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (ChannelEventEmitter) Once added in v1.2.0

func (em ChannelEventEmitter) Once(e ChannelEvent, handle func(ChannelStateChange)) (off func())

Once registers an one-off event handler for connection events of a specific kind.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (ChannelEventEmitter) OnceAll added in v1.2.0

func (em ChannelEventEmitter) OnceAll(handle func(ChannelStateChange)) (off func())

OnceAll registers an one-off event handler for all connection events.

See package-level documentation => ably Event Emitters for details about messages dispatch.

type ChannelMetrics added in v1.2.7

type ChannelMetrics struct {
	// Connections is the number of realtime connections attached to the channel (CHM2a).
	Connections int `json:"connections" codec:"connections"`

	// PresenceConnections is the number of realtime connections attached to the channel with permission
	// to enter the presence set, regardless of whether they have entered it. This requires the
	// presence capability and for a client to not have specified a [ably.ChannelMode] flag that excludes
	// [ably.ChannelModePresence] (CHM2b).
	PresenceConnections int `json:"presenceConnections" codec:"presenceConnections"`

	// PresenceMembers are the number of members in the presence set of the channel (CHM2c).
	PresenceMembers int `json:"presenceMembers" codec:"presenceMembers"`

	// PresenceSubscribers is the number of realtime attachments receiving presence messages on the channel.
	// This requires the subscribe capability and for a client to not have specified a [ably.ChannelMode]
	// flag that excludes [ably.ChannelModePresenceSubscribe] (CHM2d).
	PresenceSubscribers int `json:"presenceSubscribers" codec:"presenceSubscribers"`

	// Publishers is the number of realtime attachments permitted to publish messages on the channel.
	// This requires the publish capability and for a client to not have specified a [ably.ChannelMode]
	// flag that excludes [ably.ChannelModePublish] (CHM2e).
	Publishers int `json:"publishers" codec:"publishers"`

	// Subscribers is the number of realtime attachments receiving messages on the channel.
	// This requires the subscribe capability and for a client to not have specified a [ably.ChannelMode]
	// flag that excludes [ably.ChannelModeSubscribe].
	// CHM2f
	Subscribers int `json:"subscribers" codec:"subscribers"`
}

ChannelMetrics contains the metrics associated with a ably.RESTChannel or ably.RealtimeChannel, such as the number of publishers, subscribers and connections it has.

type ChannelMode added in v1.2.0

type ChannelMode int64

ChannelMode Describes the possible flags used to configure client capabilities, using ably.ChannelOption.

const (
	// ChannelModePresence allows the attached channel to enter Presence.
	ChannelModePresence ChannelMode = iota + 1
	// ChannelModePublish allows for messages to be published on the attached channel.
	ChannelModePublish
	// ChannelModeSubscribe allows the attached channel to subscribe to messages.
	ChannelModeSubscribe
	// ChannelModePresenceSubscribe allows the attached channel to subscribe to Presence updates.
	ChannelModePresenceSubscribe
)

type ChannelOccupancy added in v1.2.7

type ChannelOccupancy struct {
	// Metrics is a [ably.ChannelMetrics] object (CHO2a).
	Metrics ChannelMetrics `json:"metrics" codec:"metrics"`
}

ChannelOccupancy contains the metrics of a ably.RESTChannel or ably.RealtimeChannel object.

type ChannelOption added in v1.2.0

type ChannelOption func(*channelOptions)

ChannelOption configures a channel.

func ChannelWithCipher added in v1.2.0

func ChannelWithCipher(params CipherParams) ChannelOption

ChannelWithCipher requests encryption for this channel when not null, and specifies encryption-related parameters (such as algorithm, chaining mode, key length and key). See an example (RSL5a, TB2b).

func ChannelWithCipherKey added in v1.2.0

func ChannelWithCipherKey(key []byte) ChannelOption

ChannelWithCipherKey is a constructor that takes private key as a argument. It is used to encrypt and decrypt payloads (TB3)

func ChannelWithModes added in v1.2.0

func ChannelWithModes(modes ...ChannelMode) ChannelOption

ChannelWithModes set an array of ably.ChannelMode to a channel (TB2d).

func ChannelWithParams added in v1.2.0

func ChannelWithParams(key string, value string) ChannelOption

ChannelWithParams sets channel parameters that configure the behavior of the channel (TB2c).

type ChannelProperties added in v1.2.15

type ChannelProperties struct {
	// AttachSerial contains the channelSerial from latest ATTACHED ProtocolMessage received on the channel, see CP2a, RTL15a
	AttachSerial string

	// ChannelSerial contains the channelSerial from latest ProtocolMessage of action type Message/PresenceMessage received on the channel, see CP2b, RTL15b.
	ChannelSerial string
}

CP2

type ChannelState added in v1.2.0

type ChannelState struct {
	// contains filtered or unexported fields
}

ChannelState describes the possible states of a ably.RESTChannel or ably.RealtimeChannel object.

var (
	// ChannelStateInitialized is when the channel has been initialized but no attach has yet been attempted.
	ChannelStateInitialized ChannelState = ChannelState{/* contains filtered or unexported fields */}

	// ChannelStateAttaching is when the attach has been initiated by sending a request to Ably.
	// This is a transient state, followed either by a transition to ATTACHED, SUSPENDED, or FAILED.
	ChannelStateAttaching ChannelState = ChannelState{/* contains filtered or unexported fields */}

	// ChannelStateAttached is when the attach has succeeded.
	// In the ATTACHED state a client may publish and subscribe to messages, or be present on the channel.
	ChannelStateAttached ChannelState = ChannelState{/* contains filtered or unexported fields */}

	// ChannelStateDetaching is when a detach has been initiated on an ATTACHED channel by sending a request to Ably.
	// This is a transient state, followed either by a transition to DETACHED or FAILED.
	ChannelStateDetaching ChannelState = ChannelState{/* contains filtered or unexported fields */}

	// ChannelStateDetached os when the channel, having previously been ATTACHED, has been detached by the user.
	ChannelStateDetached ChannelState = ChannelState{/* contains filtered or unexported fields */}

	// ChannelStateSuspended is when the channel, having previously been ATTACHED, has lost continuity,
	// usually due to the client being disconnected from Ably for longer than two minutes.
	// It will automatically attempt to reattach as soon as connectivity is restored.
	ChannelStateSuspended ChannelState = ChannelState{/* contains filtered or unexported fields */}

	// ChannelStateFailed is an indefinite failure condition.
	// This state is entered if a channel error has been received from the Ably service,
	// such as an attempt to attach without the necessary access rights.
	ChannelStateFailed ChannelState = ChannelState{/* contains filtered or unexported fields */}
)

func (ChannelState) String added in v1.2.0

func (e ChannelState) String() string

type ChannelStateChange added in v1.2.0

type ChannelStateChange struct {

	// Current is the new current [ably.ChannelState] (RTL2a, RTL2b).
	Current ChannelState

	// Event is the event that triggered this [ably.ChannelState] change (TH5).
	Event ChannelEvent

	// Previous is the previous state.
	// For the [ably.ChannelEventUpdate] event, this is equal to the current [ably.ChannelState] (RTL2a, RTL2b).
	Previous ChannelState

	// Reason is an [ErrorInfo] object that caused the state change (RTL2e, TH3).
	Reason *ErrorInfo

	// Resumed is set to true for Attached and Update events when channel state has been maintained
	// without interruption in the server, so there has been no loss of message continuity.
	// Indicates whether message continuity on this channel is preserved, see Nonfatal channel errors for more info.
	// (RTL2f, TH4)
	Resumed bool
}

ChannelStateChange contains state change information emitted by ably.RESTChannel and ably.RealtimeChannel objects. A ChannelStateChange is the data associated with a ChannelEvent.

type ChannelStatus added in v1.2.7

type ChannelStatus struct {
	// IsActive if set to true, the channel is active, otherwise inactive (CHS2a).
	IsActive bool `json:"isActive" codec:"isActive"`

	// Occupancy is a [ably.ChannelOccupancy] object (CHS2b).
	Occupancy ChannelOccupancy `json:"occupancy" codec:"occupancy"`
}

ChannelStatus contains the status of a ably.RESTChannel or ably.RealtimeChannel object such as whether it is active and its ably.ChannelOccupancy.

type CipherAlgorithm added in v1.2.0

type CipherAlgorithm uint

CipherAlgorithm is a supported algorithm for channel encryption.

const (
	CipherAES CipherAlgorithm = 1 + iota
)

func (CipherAlgorithm) String added in v1.2.0

func (c CipherAlgorithm) String() string

type CipherMode added in v1.2.0

type CipherMode uint

CipherMode is a supported cipher mode for channel encryption.

const (
	CipherCBC CipherMode = 1 + iota
)

func (CipherMode) String added in v1.2.0

func (c CipherMode) String() string

type CipherParams added in v1.2.0

type CipherParams struct {
	// Algorithm is the algorithm to use for encryption. Only AES is supported and is the default value (TZ2a).
	Algorithm CipherAlgorithm
	// KeyLength is the length of the key in bits; for example 128 or 256 (TZ2b).
	KeyLength int
	// Key is the private key used to encrypt and decrypt payloads (TZ2d).
	Key []byte
	// Mode is the cipher mode.
	// Only CBC is supported and is the default value ((TZ2c).
	Mode CipherMode
	// contains filtered or unexported fields
}

CipherParams sets the properties to configure encryption for a ably.RESTChannel or ably.RealtimeChannel object (TZ1).

func DefaultCipherParams added in v1.2.0

func DefaultCipherParams() (*CipherParams, error)

DefaultCipherParams returns CipherParams with fields set to default values. This generates random secret key and iv values

type ClientOption added in v1.2.0

type ClientOption func(*clientOptions)

ClientOption configures a ably.REST or ably.Realtime instance.

See: https://www.ably.io/documentation/realtime/usage#client-options

func WithAgents added in v1.2.12

func WithAgents(agents map[string]string) ClientOption

WithAgents is used to add product/version key-value pairs to include in the agent library identifiers. This must only be used by Ably-authored SDKs.

func WithAuthCallback added in v1.2.0

func WithAuthCallback(authCallback func(context.Context, TokenParams) (Tokener, error)) ClientOption

WithAuthCallback is used for setting authCallback function using ably.ClientOption. AuthCallback function is called when a new token is required. The role of the callback is to obtain a fresh token, one of

  1. An Ably Token string (https://ably.com/docs/core-features/authentication#token-process)
  2. A signed ably.TokenRequest (https://ably.com/docs/core-features/authentication#token-request-process)
  3. An ably.TokenDetails (https://ably.com/docs/core-features/authentication#token-process)
  4. An Ably JWT.

See the authentication doc for more details and associated API calls (RSA4a, RSA4, TO3j5, AO2b).

func WithAuthHeaders added in v1.2.0

func WithAuthHeaders(headers http.Header) ClientOption

WithAuthHeaders is used for setting AuthHeaders using ably.ClientOption. AuthHeaders are key-value pair HTTP request headers to be added to any request made to the AuthURL. Useful when an application requires these to be added to validate the request or implement the response. If the authHeaders object contains an authorization key, then withCredentials is set on the XHR request. (RSA8c3, TO3j8, AO2e).

func WithAuthMethod added in v1.2.0

func WithAuthMethod(method string) ClientOption

WithAuthMethod is used for setting AuthMethod using ably.ClientOption. AuthMethod specifies HTTP verb to use for any request made to the AuthURL, either GET or POST for getting token information ably.TokenRequest or ably.TokenDetails. The default value is GET (RSA8c, TO3j7, AO2d)

func WithAuthParams added in v1.2.0

func WithAuthParams(params url.Values) ClientOption

WithAuthParams is used for setting AuthParams using ably.ClientOption. AuthParams are key-value pair HTTP query params to be added to any request made to the AuthURL. When the authMethod is GET, query params are added to the URL, whereas when authMethod is POST, the params are sent as URL encoded form data. Useful when an application requires these to be added to validate the request or implement the response (RSA8c3, RSA8c1, TO3j9, AO2f).

func WithAuthURL added in v1.2.0

func WithAuthURL(url string) ClientOption

WithAuthURL is used for setting AuthURL using ably.ClientOption. AuthURL is a url that library will use to obtain

  1. An Ably Token string (https://ably.com/docs/core-features/authentication#token-process)
  2. A signed ably.TokenRequest (https://ably.com/docs/core-features/authentication#token-request-process)
  3. An ably.TokenDetails (https://ably.com/docs/core-features/authentication#token-process)
  4. An Ably JWT.

See the authentication doc for more details and associated API calls (RSA4a, RSA4, RSA8c, TO3j6, AO2c).

This enables a client to obtain token requests from another entity, so tokens can be renewed without the client requiring access to keys.

If AuthURL is non-empty and AuthCallback is nil, the Ably library builds a req (*http.Request) which then is issued against the given AuthURL in order to obtain authentication token. The response is expected to carry a single token string in the payload when Content-Type header is "text/plain" or JSON-encoded *ably.TokenDetails when the header is "application/json".

The req is built with the following values:

GET requests:

  • req.URL.RawQuery is encoded from *TokenParams and AuthParams
  • req.Header is set to AuthHeaders

POST requests:

  • req.Header is set to AuthHeaders
  • Content-Type is set to "application/x-www-form-urlencoded" and the payload is encoded from *TokenParams and AuthParams

func WithAutoConnect added in v1.2.0

func WithAutoConnect(autoConnect bool) ClientOption

WithAutoConnect is used for setting NoConnect using ably.ClientOption. NoConnect when set to false, the client connects to Ably as soon as it is instantiated. You can set this to true and explicitly connect to Ably using the ably.Connection#connect() The default is false (RTC1b, TO3e).

func WithChannelRetryTimeout added in v1.2.0

func WithChannelRetryTimeout(d time.Duration) ClientOption

WithChannelRetryTimeout is used for setting ChannelRetryTimeout using ably.ClientOption. ChannelRetryTimeout when a channel becomes [ably.ChannelStateSuspended} following a server initiated ably.ChannelStateDetached, after this delay, if the channel is still ably.ChannelStateSuspended and the connection is in ably.ConnectionStateConnected, the client library will attempt to re-attach the channel automatically. The default is 15 seconds (RTL13b, TO3l7).

func WithClientID added in v1.2.0

func WithClientID(clientID string) ClientOption

WithClientID is used for setting ClientID using ably.ClientOption. ClientID is used for identifying this client when publishing messages or for presence purposes. The clientId can be any non-empty string, except it cannot contain a *. This option is primarily intended to be used in situations where the library is instantiated with a key. Note that a clientId may also be implicit in a token used to instantiate the library. An error will be raised if a clientId specified here conflicts with the clientId implicit in the token. (RSC17, RSA4, RSA15, TO3a).

func WithDefaultTokenParams added in v1.2.0

func WithDefaultTokenParams(params TokenParams) ClientOption

WithDefaultTokenParams is used for setting DefaultTokenParams token using ably.ClientOption. DefaultTokenParams when provided, it overrides the client library defaults when issuing new Ably Tokens for multiple Ably ably.TokenRequest (TO3j11).

func WithDial added in v1.2.0

func WithDial(dial func(protocol string, u *url.URL, timeout time.Duration) (conn, error)) ClientOption

WithDial is used for setting Dial using ably.ClientOption. Dial specifies the dial function for creating message connections used by Realtime. If Dial is nil, the default websocket connection is used.

func WithDisconnectedRetryTimeout added in v1.2.0

func WithDisconnectedRetryTimeout(d time.Duration) ClientOption

WithDisconnectedRetryTimeout is used for setting DisconnectedRetryTimeout using ably.ClientOption. DisconnectedRetryTimeout when the connection enters the ably.ConnectionStateDisconnected state, after this timeout, if the state is still ably.ConnectionStateDisconnected, the client library will attempt to reconnect automatically. The default is 15 seconds (TO3l1).

func WithEchoMessages added in v1.2.0

func WithEchoMessages(echo bool) ClientOption

WithEchoMessages is used for setting NoEcho using ably.ClientOption. NoEcho if set to true, prevents messages originating from this connection being echoed back on the same connection. The default is false (RTC1a, TO3h).

func WithEnvironment added in v1.2.0

func WithEnvironment(env string) ClientOption

WithEnvironment is used for setting Environment using ably.ClientOption. Environment enables a custom environment to be used with the Ably service. Optional: prefixes both hostname with the environment string (RSC15b, TO3k1).

func WithFallbackHosts added in v1.2.0

func WithFallbackHosts(hosts []string) ClientOption

WithFallbackHosts is used for setting FallbackHosts using ably.ClientOption. FallbackHosts is an array of fallback hosts to be used in the case of an error necessitating the use of an alternative host. If you have been provided a set of custom fallback hosts by Ably, please specify them here (RSC15b, RSC15a, TO3k6).

func WithFallbackHostsUseDefault deprecated added in v1.2.0

func WithFallbackHostsUseDefault(fallbackHostsUseDefault bool) ClientOption

Deprecated: This function is deprecated and will be removed in a future versions. WithFallbackHostsUseDefault is used for setting FallbackHostsUseDefault using ably.ClientOption. Deprecated: this property is deprecated and will be removed in a future version. Enables default fallback hosts to be used (TO3k7).

func WithFallbackRetryTimeout added in v1.2.11

func WithFallbackRetryTimeout(fallbackRetryTimeout time.Duration) ClientOption

WithFallbackRetryTimeout is used for setting FallbackRetryTimeout using ably.ClientOption. FallbackRetryTimeout is the max time in milliseconds before HTTP requests are retried against the default endpoint. The default is 600 seconds (TO3l10).

func WithHTTPClient added in v1.2.0

func WithHTTPClient(client *http.Client) ClientOption

WithHTTPClient is used for setting HTTPClient using ably.ClientOption. HTTPClient specifies the client used for HTTP communication by REST. When set to nil, a client configured with default settings is used.

func WithHTTPMaxRetryCount added in v1.2.0

func WithHTTPMaxRetryCount(count int) ClientOption

WithHTTPMaxRetryCount is used for setting HTTPMaxRetryCount using ably.ClientOption. HTTPMaxRetryCount denotes the maximum number of fallback hosts to use as a fallback when an HTTP request to the primary host is unreachable or indicates that it is unserviceable. The default value is 3 (TO3l5).

func WithHTTPOpenTimeout added in v1.2.0

func WithHTTPOpenTimeout(d time.Duration) ClientOption

WithHTTPOpenTimeout is used for setting HTTPOpenTimeout using ably.ClientOption. HTTPOpenTimeout is timeout for opening a connection to Ably to initiate an HTTP request. The default is 4 seconds (TO3l3).

func WithHTTPRequestTimeout added in v1.2.0

func WithHTTPRequestTimeout(timeout time.Duration) ClientOption

WithHTTPRequestTimeout is used for setting HTTPRequestTimeout using ably.ClientOption. HTTPRequestTimeout is a timeout for a client performing a complete HTTP request to Ably, including the connection phase. Will only be used if no custom HTTPClient is set. The default is 10 seconds (TO3l4).

func WithIdempotentRESTPublishing added in v1.2.0

func WithIdempotentRESTPublishing(idempotent bool) ClientOption

WithIdempotentRESTPublishing is used for setting IdempotentRESTPublishing using ably.ClientOption. IdempotentRESTPublishing when set to 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. The default is true (RSL1k1, RTL6a1, TO3n).

func WithKey added in v1.2.0

func WithKey(key string) ClientOption

WithKey is used for setting root/non-root apikey using ably.ClientOption. Key is a full API key string, as obtained from the Ably 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 multiple ably.TokenRequest. Read more about Basic authentication (RSC1, RSA11, RSA14, TO3j1, AO2a).

func WithLogHandler added in v1.2.0

func WithLogHandler(handler Logger) ClientOption

WithLogHandler is used for setting LogHandler using ably.ClientOption. LogHandler controls the log output of the library. This is a function to handle each line of log output. platform specific (TO3c)

func WithLogLevel added in v1.2.0

func WithLogLevel(level LogLevel) ClientOption

WithLogLevel is used for setting LogLevel using ably.ClientOption. LogLevel controls the verbosity of the logs output from the library. Levels include verbose, debug, info, warn and error. platform specific (TO3b)

func WithPort added in v1.2.0

func WithPort(port int) ClientOption

WithPort is used for setting custom Port using ably.ClientOption. Port is used for non-TLS connections and requests

func WithQueryTime added in v1.2.0

func WithQueryTime(queryTime bool) ClientOption

WithQueryTime is used for setting UseQueryTime token using ably.ClientOption. UseQueryTime when set to true, the library queries the Ably servers for the current time when issuing multiple ably.TokenRequest instead of relying on a locally-available time of day. Knowing the time accurately is needed to create valid signed Ably ably.TokenRequest, 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. The default is false (RSA9d, TO3j10, AO2a).

func WithQueueMessages added in v1.2.0

func WithQueueMessages(queue bool) ClientOption

WithQueueMessages is used for setting NoQueueing using ably.ClientOption. NoQueueing if set to true, this disables the default behavior whereby the library queues messages on a connection in the disconnected or connecting states. The default behavior enables applications to submit messages immediately upon instantiating 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. The default is false (RTP16b, TO3g).

func WithRESTHost added in v1.2.0

func WithRESTHost(host string) ClientOption

WithRESTHost is used for setting RESTHost using ably.ClientOption. RESTHost enables a non-default Ably host to be specified. For development environments only. The default value is rest.ably.io (RSC12, TO3k2).

func WithRealtimeHost added in v1.2.0

func WithRealtimeHost(host string) ClientOption

WithRealtimeHost is used for setting RealtimeHost using ably.ClientOption. RealtimeHost enables a non-default Ably host to be specified for realtime connections. For development environments only. The default value is realtime.ably.io (RTC1d, TO3k3).

func WithRealtimeRequestTimeout added in v1.2.0

func WithRealtimeRequestTimeout(d time.Duration) ClientOption

WithRealtimeRequestTimeout is used for setting RealtimeRequestTimeout using ably.ClientOption. RealtimeRequestTimeout is the timeout for the wait of acknowledgement for operations performed via a realtime connection, before the client library considers a request failed and triggers a failure condition. Operations include establishing a connection with Ably, or sending a HEARTBEAT, CONNECT, ATTACH, DETACH or CLOSE request. It is the equivalent of httpRequestTimeout but for realtime operations, rather than REST. The default is 10 seconds (TO3l11).

func WithRecover added in v1.2.0

func WithRecover(key string) ClientOption

WithRecover is used for setting Recover using ably.ClientOption. Recover enables a connection to inherit the state of a previous connection that may have existed under a different instance of the Realtime library. This might typically be used by clients of the browser library to ensure connection state can be preserved when the user refreshes the page. A recovery key string can be explicitly provided, or alternatively if a callback function is provided, the client library will automatically persist the recovery key between page reloads and call the callback when the connection is recoverable. The callback is then responsible for confirming whether the connection should be recovered or not. See connection state recovery for further information (RTC1c, TO3i).

func WithSuspendedRetryTimeout added in v1.2.0

func WithSuspendedRetryTimeout(d time.Duration) ClientOption

WithSuspendedRetryTimeout is used for setting SuspendedRetryTimeout using ably.ClientOption. SuspendedRetryTimeout is the timeout when the connection enters the ably.ConnectionStateSuspended state, after this timeout, if the state is still ably.ConnectionStateSuspended, the client library attempts to reconnect automatically. The default is 30 seconds (RTN14d, TO3l2).

func WithTLS added in v1.2.0

func WithTLS(tls bool) ClientOption

WithTLS is used for setting NoTLS using ably.ClientOption. NoTLS when set to true, the client will use an insecure connection. The default is false, meaning a TLS connection will be used to connect to Ably (RSC18, TO3d).

func WithTLSPort added in v1.2.0

func WithTLSPort(port int) ClientOption

WithTLSPort is used for setting TLSPort using ably.ClientOption. TLSPort enables a non-default Ably port to be specified. This is used for TLS connections and requests and restricted to development environments only. The default value is 80 (TO3k4)>

func WithToken added in v1.2.0

func WithToken(token string) ClientOption

WithToken is used for setting authenticated token using ably.ClientOption. This can either be a token string (obtained from the token property of a ably.TokenDetails component of an Ably 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 enables the client library to renew the token automatically when the previous one expires, such as AuthURL or authCallback. Read more about Token authentication (RSA4a, RSA4, TO3j2).

func WithTokenDetails added in v1.2.0

func WithTokenDetails(details *TokenDetails) ClientOption

WithTokenDetails is used for setting authenticated ably.TokenDetails object using ably.ClientOption. Only TokenDetails.Token can be set via token string (obtained from the token property of a ably.TokenDetails component of an Ably 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 enables the client library to renew the token automatically when the previous one expires, such as AuthURL or authCallback. Read more about Token authentication (RSA4a, RSA4, TO3j3).

func WithTransportParams added in v1.2.0

func WithTransportParams(params url.Values) ClientOption

WithTransportParams is used for setting TransportParams using ably.ClientOption. TransportParams is a set of key-value pairs that can be used to pass in arbitrary connection parameters, such as heartbeatInterval or remainPresentFor (RTC1f).

func WithUseBinaryProtocol added in v1.2.0

func WithUseBinaryProtocol(use bool) ClientOption

WithUseBinaryProtocol is used for setting NoBinaryProtocol using ably.ClientOption. NoBinaryProtocol when set to true, JSON text encoding is used. When false, the more efficient MsgPack binary encoding is used. The default is true (TO3f).

func WithUseTokenAuth added in v1.2.0

func WithUseTokenAuth(use bool) ClientOption

WithUseTokenAuth is used for setting UseTokenAuth using ably.ClientOption. UseTokenAuth when set to true, forces token authentication to be used by the library. If a clientId is not specified in the ably.ClientOption or ably.TokenParams, then the Ably Token issued is anonymous (RSA4, RSA14, TO3j4).

type Connection added in v1.2.0

type Connection struct {

	// ConnectionEventEmitter embeds an [ably.ConnectionEventEmitter] object (RTN4a, RTN4e, RTN4g).
	ConnectionEventEmitter
	// contains filtered or unexported fields
}

Connection represents a single connection Realtime instantiates for communication with Ably servers. It also enables the management of a connection to Ably.

func (*Connection) Close added in v1.2.0

func (c *Connection) Close()

Close causes the connection to close, entering the ably.ConnectionStateClosing state. Once connection state is ably.ConnectionStateClosed, the library does not attempt to re-establish the connection without an explicit call to Connection.Connect (RTN12).

func (*Connection) Connect added in v1.2.0

func (c *Connection) Connect()

Connect attempts to move the connection to the CONNECTED state, if it can and if it isn't already.

func (*Connection) CreateRecoveryKey added in v1.2.15

func (c *Connection) CreateRecoveryKey() string

CreateRecoveryKey is an attribute composed of the connectionKey, messageSerial and channelSerials (RTN16g, RTN16g1, RTN16h).

func (*Connection) ErrorReason added in v1.2.0

func (c *Connection) ErrorReason() *ErrorInfo

ErrorReason gives last known error that caused connection transition to ably.ConnectionStateFailed state.

func (*Connection) ID added in v1.2.0

func (c *Connection) ID() string

ID gives unique ID string obtained from Ably upon successful connection. The ID may change due to reconnection and recovery; on every received ConnectionStateConnected event previously obtained ID is no longer valid.

func (*Connection) Key added in v1.2.0

func (c *Connection) Key() string

Key gives unique key string obtained from Ably upon successful connection. The key may change due to reconnection and recovery; on every received StatConnConnected event previously obtained Key is no longer valid.

func (*Connection) RecoveryKey deprecated added in v1.2.0

func (c *Connection) RecoveryKey() string

Deprecated: this property is deprecated, use CreateRecoveryKey method instead.

func (*Connection) SetReadLimit added in v1.2.13

func (c *Connection) SetReadLimit(readLimit int64)

SetReadLimit is used to override internal websocket connection read limit. It sets the max number of bytes to read for a single message. By default, the connection has a message read limit of [ably.maxMessageSize] or 65536 bytes. When the limit is hit, the connection will be closed with StatusMessageTooBig.

func (*Connection) State added in v1.2.0

func (c *Connection) State() ConnectionState

State returns current state of the connection.

type ConnectionEvent added in v1.2.0

type ConnectionEvent struct {
	// contains filtered or unexported fields
}

ConnectionEvent describes the events emitted by a ably.Connection object. An event is either an ably.ConnectionEventUpdate or [ably.ConnectionState} change event.

var (
	// ConnectionEventInitialized - A connection with this state has been initialized
	// but no connection has yet been attempted.
	ConnectionEventInitialized ConnectionEvent = ConnectionEvent(ConnectionStateInitialized)

	// ConnectionEventConnecting - A connection attempt has been initiated.
	// The connecting state is entered as soon as the library has completed initialization,
	// and is reentered each time connection is re-attempted following disconnection.
	ConnectionEventConnecting ConnectionEvent = ConnectionEvent(ConnectionStateConnecting)

	// ConnectionEventConnected - A connection exists and is active.
	ConnectionEventConnected ConnectionEvent = ConnectionEvent(ConnectionStateConnected)

	// ConnectionEventDisconnected - A temporary failure condition. No current connection exists
	// because there is no network connectivity or no host is available.
	// The disconnected state is entered if an established connection is dropped,
	// or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt
	// to open a new connection (approximately every 15 seconds), anticipating that the connection will
	// be re-established soon and thus connection and channel continuity will be possible.
	// In this state, developers can continue to publish messages as they are automatically placed in a local queue,
	// to be sent as soon as a connection is reestablished. Messages published by other clients
	// while this client is disconnected will be delivered to it upon reconnection, so long as
	// the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible
	// and the connection will move to the SUSPENDED state.
	ConnectionEventDisconnected ConnectionEvent = ConnectionEvent(ConnectionStateDisconnected)

	// ConnectionEventSuspended - A long term failure condition. No current connection exists
	// because there is no network connectivity or no host is available. The suspended state is entered
	// after a failed connection attempt if there has then been no connection for a period of two minutes.
	// In the suspended state, the library will periodically attempt to open a new connection every 30 seconds.
	// Developers are unable to publish messages in this state. A new connection attempt can also be triggered
	// by an explicit call to Connection.Connect. Once the connection has been re-established,
	// channels will be automatically re-attached. The client has been disconnected for too long for them
	// to resume from where they left off, so if it wants to catch up on messages published by other clients
	// while it was disconnected, it needs to use the History API.
	ConnectionEventSuspended ConnectionEvent = ConnectionEvent(ConnectionStateSuspended)

	// ConnectionEventClosing is when an explicit request by the developer to close the connection has been sent to
	// the Ably service. If a reply is not received from Ably within a short period of time,
	// the connection is forcibly terminated and the connection state becomes CLOSED.
	ConnectionEventClosing ConnectionEvent = ConnectionEvent(ConnectionStateClosing)

	// ConnectionEventClosed - The connection has been explicitly closed by the client.
	// In the closed state, no reconnection attempts are made automatically by the library,
	// and clients may not publish messages. No connection state is preserved by the service or by the library.
	// A new connection attempt can be triggered by an explicit call to Connection.Connect,
	// which results in a new connection.
	ConnectionEventClosed ConnectionEvent = ConnectionEvent(ConnectionStateClosed)

	// ConnectionEventFailed - This state is entered if the client library encounters a failure condition
	// that it cannot recover from. This may be a fatal connection error received from the Ably service,
	// for example an attempt to connect with an incorrect API key, or a local terminal error,
	// for example the token in use has expired and the library does not have any way to renew it.
	// In the failed state, no reconnection attempts are made automatically by the library, and
	// clients may not publish messages. A new connection attempt can be triggered by an explicit call
	// to Connection.Connect.
	ConnectionEventFailed ConnectionEvent = ConnectionEvent(ConnectionStateFailed)

	// ConnectionEventUpdate is an event for changes to connection conditions for which the
	// [ably.ConnectionState] does not change (RTN4h).
	ConnectionEventUpdate ConnectionEvent = ConnectionEvent{/* contains filtered or unexported fields */}
)

func (ConnectionEvent) String added in v1.2.0

func (e ConnectionEvent) String() string

type ConnectionEventEmitter added in v1.2.0

type ConnectionEventEmitter struct {
	// contains filtered or unexported fields
}

func (ConnectionEventEmitter) Off added in v1.2.0

Off deregisters event handlers for connection events of a specific kind.

See package-level documentation => ably Event Emitters for more details.

func (ConnectionEventEmitter) OffAll added in v1.2.0

func (em ConnectionEventEmitter) OffAll()

OffAll deregisters all event handlers.

See package-level documentation => ably Event Emitters for more details.

func (ConnectionEventEmitter) On added in v1.2.0

func (em ConnectionEventEmitter) On(e ConnectionEvent, handle func(ConnectionStateChange)) (off func())

On registers an event handler for connection events of a specific kind.

See package-level documentation => ably Event Emitters for more details.

func (ConnectionEventEmitter) OnAll added in v1.2.0

func (em ConnectionEventEmitter) OnAll(handle func(ConnectionStateChange)) (off func())

OnAll registers an event handler for all connection events.

See package-level documentation => ably Event Emitters for more details.

func (ConnectionEventEmitter) Once added in v1.2.0

func (em ConnectionEventEmitter) Once(e ConnectionEvent, handle func(ConnectionStateChange)) (off func())

Once registers an one-off event handler for connection events of a specific kind.

See package-level documentation => ably Event Emitters for more details.

func (ConnectionEventEmitter) OnceAll added in v1.2.0

func (em ConnectionEventEmitter) OnceAll(handle func(ConnectionStateChange)) (off func())

OnceAll registers an one-off event handler for all connection events.

See package-level documentation => ably Event Emitters for more details.

type ConnectionState added in v1.2.0

type ConnectionState struct {
	// contains filtered or unexported fields
}

ConnectionState describes the realtime ably.Connection object states.

var (
	// ConnectionStateInitialized - A connection with this state has been initialized
	// but no connection has yet been attempted.
	ConnectionStateInitialized ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateConnecting - A connection attempt has been initiated.
	// The connecting state is entered as soon as the library has completed initialization,
	// and is reentered each time connection is re-attempted following disconnection.
	ConnectionStateConnecting ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateConnected - A connection exists and is active.
	ConnectionStateConnected ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateDisconnected - A temporary failure condition. No current connection exists
	// because there is no network connectivity or no host is available.
	// The disconnected state is entered if an established connection is dropped,
	// or if a connection attempt was unsuccessful. In the disconnected state the library will periodically attempt
	// to open a new connection (approximately every 15 seconds), anticipating that the connection will
	// be re-established soon and thus connection and channel continuity will be possible.
	// In this state, developers can continue to publish messages as they are automatically placed in a local queue,
	// to be sent as soon as a connection is reestablished. Messages published by other clients
	// while this client is disconnected will be delivered to it upon reconnection, so long as
	// the connection was resumed within 2 minutes. After 2 minutes have elapsed, recovery is no longer possible
	// and the connection will move to the SUSPENDED state.
	ConnectionStateDisconnected ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateSuspended - A long term failure condition. No current connection exists
	// because there is no network connectivity or no host is available. The suspended state is entered
	// after a failed connection attempt if there has then been no connection for a period of two minutes.
	// In the suspended state, the library will periodically attempt to open a new connection every 30 seconds.
	// Developers are unable to publish messages in this state. A new connection attempt can also be triggered
	// by an explicit call to Connection.Connect. Once the connection has been re-established,
	// channels will be automatically re-attached. The client has been disconnected for too long for them
	// to resume from where they left off, so if it wants to catch up on messages published by other clients
	// while it was disconnected, it needs to use the History API.
	ConnectionStateSuspended ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateClosing is when an explicit request by the developer to close the connection has been sent to
	// the Ably service. If a reply is not received from Ably within a short period of time,
	// the connection is forcibly terminated and the connection state becomes CLOSED.
	ConnectionStateClosing ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateClosed - The connection has been explicitly closed by the client.
	// In the closed state, no reconnection attempts are made automatically by the library,
	// and clients may not publish messages. No connection state is preserved by the service or by the library.
	// A new connection attempt can be triggered by an explicit call to Connection.Connect,
	// which results in a new connection.
	ConnectionStateClosed ConnectionState = ConnectionState{/* contains filtered or unexported fields */}

	// ConnectionStateFailed - This state is entered if the client library encounters a failure condition
	// that it cannot recover from. This may be a fatal connection error received from the Ably service,
	// for example an attempt to connect with an incorrect API key, or a local terminal error,
	// for example the token in use has expired and the library does not have any way to renew it.
	// In the failed state, no reconnection attempts are made automatically by the library, and
	// clients may not publish messages. A new connection attempt can be triggered by an explicit call
	// to Connection.Connect.
	ConnectionStateFailed ConnectionState = ConnectionState{/* contains filtered or unexported fields */}
)

func (ConnectionState) String added in v1.2.0

func (e ConnectionState) String() string

type ConnectionStateChange added in v1.2.0

type ConnectionStateChange struct {
	// Current is the new [ably.ConnectionState] (TA2).
	Current ConnectionState

	// Event is the event that triggered this [ably.ConnectionState] change (TA5).
	Event ConnectionEvent

	// Previous is the previous [ably.ConnectionState]. For the [ConnectionEventUpdate] event,
	// this is equal to the current [ably.ConnectionState] (TA2).
	Previous ConnectionState

	// RetryIn is duration in milliseconds,
	// after which the client retries a connection where applicable (RTN14d, TA2).
	RetryIn time.Duration

	// Reason is an [ably.ErrorInfo] object that caused the state change (RTN4f, TA3).
	Reason *ErrorInfo
}

ConnectionStateChange Contains [ably.ConnectionState]change information emitted by the ably.Connection object. A ConnectionStateChange is the data associated with a ConnectionEvent.

type DeriveOptions added in v1.2.12

type DeriveOptions struct {
	Filter string
}

DeriveOptions allows options to be used in creating a derived channel

type Direction added in v1.2.0

type Direction string
const (
	Backwards Direction = "backwards"
	Forwards  Direction = "forwards"
)

type ErrorCode added in v1.2.0

type ErrorCode int

ErrorCode is the type for predefined Ably error codes.

const (
	ErrNotSet                                    ErrorCode = 0
	ErrBadRequest                                ErrorCode = 40000
	ErrInvalidCredential                         ErrorCode = 40005
	ErrInvalidClientID                           ErrorCode = 40012
	ErrUnauthorized                              ErrorCode = 40100
	ErrInvalidCredentials                        ErrorCode = 40101
	ErrIncompatibleCredentials                   ErrorCode = 40102
	ErrInvalidUseOfBasicAuthOverNonTLSTransport  ErrorCode = 40103
	ErrTokenErrorUnspecified                     ErrorCode = 40140
	ErrErrorFromClientTokenCallback              ErrorCode = 40170
	ErrForbidden                                 ErrorCode = 40300
	ErrNotFound                                  ErrorCode = 40400
	ErrMethodNotAllowed                          ErrorCode = 40500
	ErrInternalError                             ErrorCode = 50000
	ErrInternalChannelError                      ErrorCode = 50001
	ErrInternalConnectionError                   ErrorCode = 50002
	ErrTimeoutError                              ErrorCode = 50003
	ErrConnectionFailed                          ErrorCode = 80000
	ErrConnectionSuspended                       ErrorCode = 80002
	ErrConnectionClosed                          ErrorCode = 80017
	ErrDisconnected                              ErrorCode = 80003
	ErrProtocolError                             ErrorCode = 80013
	ErrChannelOperationFailed                    ErrorCode = 90000
	ErrChannelOperationFailedInvalidChannelState ErrorCode = 90001
)

func (ErrorCode) String added in v1.2.0

func (c ErrorCode) String() string

type ErrorInfo added in v1.2.0

type ErrorInfo struct {
	// StatusCode is a http Status code corresponding to this error, where applicable (TI1).
	StatusCode int
	// Code is the standard [ably error code]
	// [ably error code]: https://github.com/ably/ably-common/blob/main/protocol/errors.json (TI1).
	Code ErrorCode
	// HRef is included for REST responses to provide a URL for additional help on the error code (TI4).
	HRef string
	// Cause provides Information pertaining to what caused the error where available (TI1).
	Cause *ErrorInfo
	// contains filtered or unexported fields
}

ErrorInfo is a generic Ably error object that contains an Ably-specific status code, and a generic status code. Errors returned from the Ably server are compatible with the ErrorInfo structure and should result in errors that inherit from ErrorInfo. It may contain underlying error value which caused the failure.

func (ErrorInfo) Error added in v1.2.0

func (e ErrorInfo) Error() string

Error implements the builtin error interface.

func (ErrorInfo) Message added in v1.2.0

func (e ErrorInfo) Message() string

Message returns the undecorated error message.

func (ErrorInfo) Unwrap added in v1.2.0

func (e ErrorInfo) Unwrap() error

Unwrap implements the implicit interface that errors.Unwrap understands.

type GetPresenceOption added in v1.2.0

type GetPresenceOption func(*getPresenceOptions)

GetPresenceOption configures a call to RESTPresence.Get or RealtimePresence.Get.

func GetPresenceWithClientID added in v1.2.0

func GetPresenceWithClientID(clientID string) GetPresenceOption

GetPresenceWithClientID filters the list of returned presence members by a specific client using its ID (RSP3a2).

func GetPresenceWithConnectionID added in v1.2.0

func GetPresenceWithConnectionID(connectionID string) GetPresenceOption

GetPresenceWithConnectionID filters the list of returned presence members by a specific connection using its ID. RSP3a3

func GetPresenceWithLimit added in v1.2.0

func GetPresenceWithLimit(limit int) GetPresenceOption

GetPresenceWithLimit sets an upper limit on the number of messages returned. The default is 100, and the maximum is 1000 (RSP3a).

type HTTPPaginatedResponse added in v1.1.0

type HTTPPaginatedResponse struct {
	PaginatedResult
	// contains filtered or unexported fields
}

HTTPPaginatedResponse is a superset of ably.PaginatedResult which 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. A HTTPPaginatedResponse is an iterator for the response of a REST request.

See package-level documentation => ably Pagination for more details.

func (*HTTPPaginatedResponse) ErrorCode added in v1.1.0

func (r *HTTPPaginatedResponse) ErrorCode() ErrorCode

ErrorCode is the error code if the X-Ably-Errorcode HTTP header is sent in the response (HP6).

func (*HTTPPaginatedResponse) ErrorMessage added in v1.1.0

func (r *HTTPPaginatedResponse) ErrorMessage() string

ErrorMessage is the error message if the X-Ably-Errormessage HTTP header is sent in the response (HP7).

func (*HTTPPaginatedResponse) HasNext added in v1.2.6

func (p *HTTPPaginatedResponse) HasNext(ctx context.Context) bool

HasNext returns true is there are more pages available.

See package-level documentation => ably Pagination for more details.

func (*HTTPPaginatedResponse) Headers added in v1.1.0

func (r *HTTPPaginatedResponse) Headers() http.Header

Headers are the headers of the response (HP8).

func (*HTTPPaginatedResponse) IsLast added in v1.2.6

func (p *HTTPPaginatedResponse) IsLast(ctx context.Context) bool

IsLast returns true if the page is last page.

See package-level documentation => ably Pagination for more details.

func (*HTTPPaginatedResponse) Items added in v1.2.0

func (p *HTTPPaginatedResponse) Items(dst interface{}) error

Items contains a page of results; for example, an array of ably.Message or ably.PresenceMessage objects for a channel history request (HP3)

See package-level documentation => ably Pagination for more details.

func (*HTTPPaginatedResponse) Next added in v1.1.0

Next retrieves the next page of results.

See package-level documentation => ably Pagination for more details.

func (*HTTPPaginatedResponse) StatusCode added in v1.1.0

func (r *HTTPPaginatedResponse) StatusCode() int

StatusCode is the HTTP status code of the response (HP4).

func (*HTTPPaginatedResponse) Success added in v1.1.0

func (r *HTTPPaginatedResponse) Success() bool

Success is whether statusCode indicates success. This is equivalent to 200 <= statusCode < 300 (HP5).

type HistoryOption added in v1.2.0

type HistoryOption func(*historyOptions)

A HistoryOption configures a call to RESTChannel.History or RealtimeChannel.History.

func HistoryWithDirection added in v1.2.0

func HistoryWithDirection(d Direction) HistoryOption

HistoryWithDirection sets the order for which messages are returned in. Valid values are backwards which orders messages from most recent to oldest, or forwards which orders messages from oldest to most recent. The default is backwards (RSL2b2).

func HistoryWithEnd added in v1.2.0

func HistoryWithEnd(t time.Time) HistoryOption

HistoryWithEnd sets time until messages are retrieved, specified as milliseconds since the Unix epoch (RSL2b1).

func HistoryWithLimit added in v1.2.0

func HistoryWithLimit(limit int) HistoryOption

HistoryWithLimit sets an upper limit on the number of messages returned. The default is 100, and the maximum is 1000 (RSL2b3).

func HistoryWithStart added in v1.2.0

func HistoryWithStart(t time.Time) HistoryOption

HistoryWithStart sets time from which messages are retrieved, specified as milliseconds since the Unix epoch. RSL2b1

type HistoryRequest added in v1.2.0

type HistoryRequest struct {
	// contains filtered or unexported fields
}

HistoryRequest represents a request prepared by the RESTChannel.History or RealtimeChannel.History method, ready to be performed by its Pages or Items methods.

func (HistoryRequest) Items added in v1.2.0

Items returns a convenience iterator for single History, over an underlying paginated iterator.

See package-level documentation => ably Pagination for details about history pagination.

func (HistoryRequest) Pages added in v1.2.0

Pages returns an iterator for whole pages of History.

See package-level documentation => ably Pagination for details about history pagination.

type LogLevel added in v1.1.0

type LogLevel uint
const (
	LogNone LogLevel = iota
	LogError
	LogWarning
	LogInfo
	LogVerbose
	LogDebug
)

func (LogLevel) String added in v1.2.0

func (l LogLevel) String() string

type Logger

type Logger interface {
	Printf(level LogLevel, format string, v ...interface{})
}

Logger is an interface for ably loggers.

type Message added in v1.2.0

type Message struct {
	// ID is a unique identifier assigned by Ably to this message (TM2a).
	ID string `json:"id,omitempty" codec:"id,omitempty"`
	// ClientID is of the publisher of this message (RSL1g1, TM2b).
	ClientID string `json:"clientId,omitempty" codec:"clientId,omitempty"`
	// ConnectionID of the publisher of this message (TM2c).
	ConnectionID string `json:"connectionId,omitempty" codec:"connectionID,omitempty"`
	// Deprecated: This attribute is deprecated and will be removed in future versions
	// ConnectionKey is a connectionKey of the active connection.
	ConnectionKey string `json:"connectionKey,omitempty" codec:"connectionKey,omitempty"`
	// Name is the event name (TM2g).
	Name string `json:"name,omitempty" codec:"name,omitempty"`
	// Data is the message payload, if provided (TM2d).
	Data interface{} `json:"data,omitempty" codec:"data,omitempty"`
	// Encoding is typically 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 contains the remaining
	// transformations not applied to the data payload (TM2e).
	Encoding string `json:"encoding,omitempty" codec:"encoding,omitempty"`
	// Timestamp of when the message was received by Ably, as milliseconds since the Unix epoch (TM2f).
	Timestamp int64 `json:"timestamp,omitempty" codec:"timestamp,omitempty"`
	// Extras is a JSON object of arbitrary key-value pairs that may contain metadata, and/or ancillary payloads.
	// Valid payloads include push, deltaExtras, ReferenceExtras and headers (TM2i).
	Extras map[string]interface{} `json:"extras,omitempty" codec:"extras,omitempty"`
}

Message contains an individual message that is sent to, or received from, Ably.

func (Message) String added in v1.2.0

func (m Message) String() string

type MessagesPaginatedItems added in v1.2.0

type MessagesPaginatedItems struct {
	PaginatedResult
	// contains filtered or unexported fields
}

func (*MessagesPaginatedItems) Item added in v1.2.0

func (p *MessagesPaginatedItems) Item() *Message

Item returns the current result.

See package-level documentation => ably Pagination for details about history pagination.

func (*MessagesPaginatedItems) Next added in v1.2.0

Next retrieves the next result.

See package-level documentation => ably Pagination for details about history pagination.

type MessagesPaginatedResult added in v1.2.0

type MessagesPaginatedResult struct {
	PaginatedResult
	// contains filtered or unexported fields
}

A MessagesPaginatedResult is an iterator for the result of a History request.

See package-level documentation => ably Pagination for details about history pagination.

func (*MessagesPaginatedResult) HasNext added in v1.2.6

func (p *MessagesPaginatedResult) HasNext(ctx context.Context) bool

HasNext returns true is there are more pages available.

See package-level documentation => ably Pagination for details about history pagination.

func (*MessagesPaginatedResult) IsLast added in v1.2.6

IsLast returns true if the page is last page.

See package-level documentation => ably Pagination for details about history pagination.

func (*MessagesPaginatedResult) Items added in v1.2.0

func (p *MessagesPaginatedResult) Items() []*Message

Items returns the current page of results.

See package-level documentation => ably Pagination for details about history pagination.

func (*MessagesPaginatedResult) Next added in v1.2.0

Next retrieves the next page of results.

See package-level documentation => ably Pagination for details about history pagination.

type PaginateParams

type PaginateParams struct {
	ScopeParams
	Limit     int
	Direction string
}

func (*PaginateParams) EncodeValues

func (p *PaginateParams) EncodeValues(out *url.Values) error

type PaginatedResult

type PaginatedResult struct {
	// contains filtered or unexported fields
}

PaginatedResult is a generic iterator for PaginatedResult pagination. Items decoding is delegated to type-specific wrappers.

See "Paginated results" section in the package-level documentation.

func (*PaginatedResult) Err added in v1.2.0

func (p *PaginatedResult) Err() error

Err returns the error that caused Next to fail, if there was one.

func (*PaginatedResult) First added in v1.2.0

func (p *PaginatedResult) First(ctx context.Context) error

First loads the first page of items. Next should be called before inspecting the Items.

type PeriodUnit added in v1.2.0

type PeriodUnit string
const (
	PeriodMinute PeriodUnit = "minute"
	PeriodHour   PeriodUnit = "hour"
	PeriodDay    PeriodUnit = "day"
	PeriodMonth  PeriodUnit = "month"
)

type PresenceAction added in v1.2.0

type PresenceAction int64

PresenceAction describes the possible actions members in the presence set can emit (TP2).

const (
	// PresenceActionAbsent specifies a member is not present in the channel.
	PresenceActionAbsent PresenceAction = iota
	// PresenceActionPresent denotes when subscribing to presence events on a channel that already has members present,
	// this event is emitted for every member already present on the channel before the subscribe listener was registered.
	PresenceActionPresent
	// PresenceActionEnter denotes that new member has entered the channel.
	PresenceActionEnter
	// PresenceActionLeave is a member who was present has now left the channel. This may be a result of an explicit
	// request to leave or implicitly when detaching from the channel. Alternatively, if a member's connection is
	// abruptly disconnected and they do not resume their connection within a minute, Ably treats this as a
	// leave event as the client is no longer present.
	PresenceActionLeave
	// PresenceActionUpdate is a already present member has updated their member data. Being notified of member data
	// updates can be very useful, for example, it can be used to update the status of a user when they are
	// typing a message.
	PresenceActionUpdate
)

func (PresenceAction) String added in v1.2.0

func (e PresenceAction) String() string

type PresenceGetOption added in v1.2.0

type PresenceGetOption func(*presenceGetOptions)

A PresenceGetOption is an optional parameter for RealtimePresence.GetWithOptions.

func PresenceGetWithWaitForSync added in v1.2.0

func PresenceGetWithWaitForSync(wait bool) PresenceGetOption

PresenceGetWithWaitForSync sets whether to wait for a full presence set synchronization between Ably and the clients on the channel to complete before returning the results. Synchronization begins as soon as the channel is ably.ChannelStateAttached. When set to true the results will be returned as soon as the sync is complete. When set to false the current list of members will be returned without the sync completing. The default is true (RTP11c1).

type PresenceHistoryOption added in v1.2.0

type PresenceHistoryOption func(*presenceHistoryOptions)

PresenceHistoryOption configures a call to RESTChannel.History or RealtimeChannel.History.

func PresenceHistoryWithDirection added in v1.2.0

func PresenceHistoryWithDirection(d Direction) PresenceHistoryOption

PresenceHistoryWithDirection sets the order for which messages are returned in. Valid values are backwards which orders messages from most recent to oldest, or forwards which orders messages from oldest to most recent. The default is backwards (RSP4b2).

func PresenceHistoryWithEnd added in v1.2.0

func PresenceHistoryWithEnd(t time.Time) PresenceHistoryOption

PresenceHistoryWithEnd sets the time until messages are retrieved, specified as milliseconds since the Unix epoch. (RSP4b1)

func PresenceHistoryWithLimit added in v1.2.0

func PresenceHistoryWithLimit(limit int) PresenceHistoryOption

PresenceHistoryWithLimit sets an upper limit on the number of messages returned. The default is 100, and the maximum is 1000 (RSP4b3).

func PresenceHistoryWithStart added in v1.2.0

func PresenceHistoryWithStart(t time.Time) PresenceHistoryOption

PresenceHistoryWithStart sets the time from which messages are retrieved, specified as milliseconds since the Unix epoch (RSP4b1).

type PresenceMessage added in v1.2.0

type PresenceMessage struct {
	Message
	Action PresenceAction `json:"action" codec:"action"`
}

func (*PresenceMessage) IsNewerThan added in v1.2.15

func (msg1 *PresenceMessage) IsNewerThan(msg2 *PresenceMessage) (bool, error)

RTP2b, RTP2c

func (PresenceMessage) String added in v1.2.0

func (m PresenceMessage) String() string

type PresencePaginatedItems added in v1.2.0

type PresencePaginatedItems struct {
	PaginatedResult
	// contains filtered or unexported fields
}

func (*PresencePaginatedItems) Item added in v1.2.0

Item returns the current result.

See package-level documentation => ably Pagination for more details.

func (*PresencePaginatedItems) Next added in v1.2.0

Next retrieves the next result.

See package-level documentation => ably Pagination for more details.

type PresencePaginatedResult added in v1.2.0

type PresencePaginatedResult struct {
	PaginatedResult
	// contains filtered or unexported fields
}

A PresencePaginatedResult is an iterator for the result of a PresenceHistory request.

See package-level documentation => ably Pagination for more details.

func (*PresencePaginatedResult) HasNext added in v1.2.6

func (p *PresencePaginatedResult) HasNext(ctx context.Context) bool

func (*PresencePaginatedResult) IsLast added in v1.2.6

IsLast returns true if the page is last page.

See package-level documentation => ably Pagination for more details.

func (*PresencePaginatedResult) Items added in v1.2.0

Items returns the current page of results.

See package-level documentation => ably Pagination for more details.

func (*PresencePaginatedResult) Next added in v1.2.0

Next retrieves the next page of results.

See package-level documentation => ably Pagination for more details.

type PresenceRequest added in v1.2.0

type PresenceRequest struct {
	// contains filtered or unexported fields
}

PresenceRequest represents a request prepared by the RESTPresence.History or RealtimePresence.History method, ready to be performed by its Pages or Items methods.

func (PresenceRequest) Items added in v1.2.0

Items returns a convenience iterator for single PresenceHistory, over an underlying paginated iterator.

See package-level documentation => ably Pagination for more details.

func (PresenceRequest) Pages added in v1.2.0

Pages returns an iterator for whole pages of presence messages.

See package-level documentation => ably Pagination for more details.

type PublishMultipleOption added in v1.2.0

type PublishMultipleOption func(*publishMultipleOptions)

PublishMultipleOption is an optional parameter for RESTChannel.Publish and RESTChannel.PublishMultiple.

TODO: This started out as just an option for PublishMultiple, but has since

been added as an option for Publish too, so it should be renamed to
PublishOption when we perform the next major version bump to 2.x.x.

func PublishMultipleWithParams deprecated added in v1.2.0

func PublishMultipleWithParams(params map[string]string) PublishMultipleOption

Deprecated: Use PublishWithParams instead. PublishMultipleWithParams is the same as PublishWithParams.

TODO: Remove this in the next major version bump to 2.x.x.

func PublishWithConnectionKey added in v1.2.4

func PublishWithConnectionKey(connectionKey string) PublishMultipleOption

PublishWithConnectionKey allows a message to be published for a specified connectionKey.

func PublishWithParams added in v1.2.4

func PublishWithParams(params map[string]string) PublishMultipleOption

PublishWithParams adds query parameters to the resulting HTTP request to the REST API.

type PushStats added in v1.2.0

type PushStats struct {
	// Messages are total number of push messages (TS10a).
	Messages float64 `json:"messages" codec:"messages"`
	// Notifications is the count of push notifications (TS10c).
	Notifications StatsPushNotifications `json:"notifications" codec:"notifications"`
	// DirectPublishes is the total number of direct publishes (TS10b).
	DirectPublishes float64 `json:"directPublishes" codec:"directPublishes"`
}

PushStats provides details the stats on push notifications.

type REST added in v1.2.0

type REST struct {
	// Auth is a  [ably.Auth] object (RSC5).
	Auth *Auth

	//Channels is a [ably.RESTChannels] object (RSN1).
	Channels *RESTChannels
	// contains filtered or unexported fields
}

REST is rest client that offers a simple stateless API to interact directly with Ably's REST API.

func NewREST added in v1.2.0

func NewREST(options ...ClientOption) (*REST, error)

NewREST construct a RestClient object using an ably.ClientOption object to configure the client connection to Ably (RSC1).

func (*REST) Request added in v1.2.0

func (c *REST) Request(method string, path string, o ...RequestOption) RESTRequest

Request makes a REST request with given http method (GET, POST) and url 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 directly handle features such as authentication, paging, fallback hosts, MsgPack and JSON support (RSC19).

func (*REST) Stats added in v1.2.0

func (c *REST) Stats(o ...StatsOption) StatsRequest

Stats queries the REST/stats API and retrieves your application's usage statistics. Returns a ably.PaginatedResult object, containing an array of Stats{@link Stats} objects (RSC6a).

See package-level documentation => ably Pagination for handling stats pagination.

func (*REST) Time added in v1.2.0

func (c *REST) Time(ctx context.Context) (time.Time, error)

Time retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably multiple ably.TokenRequest with a more accurate timestamp should use the ClientOptions.UseQueryTime property instead of this method (RSC16).

type RESTChannel added in v1.2.0

type RESTChannel struct {
	// Name is the channel name.
	Name string

	// Presence is a [ably.RESTPresence] object (RSL3).
	Presence *RESTPresence
	// contains filtered or unexported fields
}

RESTChannel is the interface for REST API operations on a channel. It enables messages to be published and historic messages to be retrieved for a channel.

func (*RESTChannel) History added in v1.2.0

func (c *RESTChannel) History(o ...HistoryOption) HistoryRequest

History gives the channel's message history (RSL2a)

See package-level documentation => ably Pagination for details about history pagination.

func (*RESTChannel) Publish added in v1.2.0

func (c *RESTChannel) Publish(ctx context.Context, name string, data interface{}, options ...PublishMultipleOption) error

Publish publishes a single message to the channel with the given event name and payload. Returns error if there is a problem performing message publish (RSL1).

Example

When publishing a message to a channel, data can be either a single string or a struct of type Message. This example shows the different ways to publish a message.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ably/ably-go/ably"
)

func main() {

	// Create a new REST client.
	client, err := ably.NewREST(
		ably.WithKey("ABLY_PRIVATE_KEY"),
		ably.WithClientID("Client A"),
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Initialise a new channel.
	channel := client.Channels.Get("chat")

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	// Publish a string to the channel.
	if err := channel.Publish(ctx, "chat_message", "Hello, how are you?"); err != nil {
		fmt.Println(err)
		return
	}

	// Publish a single message to the channel.
	newChatMessage := ably.Message{
		Name: "chat_message",
		Data: "Hello, how are you?",
	}

	if err := channel.Publish(ctx, "chat_message", newChatMessage); err != nil {
		fmt.Println(err)
		return
	}

	// Publish multiple messages in a single request.
	if err := channel.PublishMultiple(ctx, []*ably.Message{
		{Name: "HelloEvent", Data: "Hello!"},
		{Name: "ByeEvent", Data: "Bye!"},
	}); err != nil {
		fmt.Println(err)
		return
	}

	// Publish a message on behalf of a different client.
	if err := channel.Publish(ctx, "temperature", "12.7",
		ably.PublishWithConnectionKey("connectionKeyOfAnotherClient"),
	); err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*RESTChannel) PublishMultiple added in v1.2.0

func (c *RESTChannel) PublishMultiple(ctx context.Context, messages []*Message, options ...PublishMultipleOption) error

PublishMultiple publishes multiple messages in a batch. Returns error if there is a problem publishing message (RSL1).

func (*RESTChannel) PublishMultipleWithOptions deprecated added in v1.2.0

func (c *RESTChannel) PublishMultipleWithOptions(ctx context.Context, messages []*Message, options ...PublishMultipleOption) error

PublishMultipleWithOptions is the same as PublishMultiple.

Deprecated: Use PublishMultiple instead.

TODO: Remove this in the next major version bump to 2.x.x.

func (*RESTChannel) Status added in v1.2.7

func (c *RESTChannel) Status(ctx context.Context) (*ChannelDetails, error)

Status returns ChannelDetails representing information for a channel which includes status and occupancy metrics. (RSL8)

type RESTChannels added in v1.2.0

type RESTChannels struct {
	// contains filtered or unexported fields
}

RESTChannels provides an API for managing collection of RESTChannel. This is safe for concurrent use.

func (*RESTChannels) Exists added in v1.2.0

func (c *RESTChannels) Exists(name string) bool

Exists returns true if the channel by the given name exists.

func (*RESTChannels) Get added in v1.2.0

func (c *RESTChannels) Get(name string, options ...ChannelOption) *RESTChannel

Get returns an existing channel or creates a new one if it doesn't exist.

You can optionally pass ChannelOptions, if the channel exists it will updated with the options and when it doesn't a new channel will be created with the given options.

func (*RESTChannels) Iterate added in v1.2.0

func (c *RESTChannels) Iterate() []*RESTChannel

Iterate returns a list of created channels.

It is safe to call Iterate from multiple goroutines, however there's no guarantee the returned list would not list a channel that was already released from different goroutine.

func (*RESTChannels) Release added in v1.2.0

func (c *RESTChannels) Release(name string)

Release deletes the channel from the chans.

type RESTPaginatedItems added in v1.2.0

type RESTPaginatedItems struct {
	PaginatedResult
	// contains filtered or unexported fields
}

func (*RESTPaginatedItems) HasNext added in v1.2.6

func (p *RESTPaginatedItems) HasNext(ctx context.Context) bool

HasNext returns true is there are more pages available.

See package-level documentation => ably Pagination for more details.

func (*RESTPaginatedItems) IsLast added in v1.2.6

func (p *RESTPaginatedItems) IsLast(ctx context.Context) bool

IsLast returns true if the page is last page.

See package-level documentation => ably Pagination for more details.

func (*RESTPaginatedItems) Item added in v1.2.0

func (p *RESTPaginatedItems) Item(dst interface{}) error

Item unmarshal the current result into the provided variable.

See the "Paginated results" section in the package-level documentation.

func (*RESTPaginatedItems) Next added in v1.2.0

func (p *RESTPaginatedItems) Next(ctx context.Context) bool

Next retrieves the next result.

See the "Paginated results" section in the package-level documentation.

type RESTPresence added in v1.2.0

type RESTPresence struct {
	// contains filtered or unexported fields
}

RESTPresence enables the retrieval of the current and historic presence set for a channel.

func (*RESTPresence) Get added in v1.2.0

Get retrieves the current members present on the channel and the metadata for each member, such as their ably.PresenceAction and ID. Returns a ably.PaginatedResult object, containing an array of [ably.PresenceMessage]objects (RSPa).

See package-level documentation => ably Pagination for more details.

func (*RESTPresence) History added in v1.2.0

History retrieves a ably.PaginatedResult object, containing an array of historical ably.PresenceMessage objects for the channel. If the channel is configured to persist messages, then presence messages can be retrieved from history for up to 72 hours in the past. If not, presence messages can only be retrieved from history for up to two minutes in the past (RSP4a).

See package-level documentation => ably Pagination for details about history pagination.

type RESTRequest added in v1.2.0

type RESTRequest struct {
	// contains filtered or unexported fields
}

RESTRequest represents a request prepared by the REST.Request method, ready to be performed by its Pages or Items methods.

func (RESTRequest) Items added in v1.2.0

Items returns a convenience iterator for single items, over an underlying paginated iterator.

See package-level documentation => ably Pagination for more details.

func (RESTRequest) Pages added in v1.2.0

Pages returns an iterator for whole pages of results.

See package-level documentation => ably Pagination for more details.

type Realtime added in v1.2.0

type Realtime struct {
	// An [ably.Auth] object (RTC4).
	Auth *Auth
	// A [ably.RealtimeChannels] object (RTC3, RTS1).
	Channels *RealtimeChannels
	// A [ably.Connection] object (RTC2).
	Connection *Connection
	// contains filtered or unexported fields
}

Realtime is an ably realtime client that extends the functionality of the ably.REST and provides additional realtime-specific features.

func NewRealtime added in v1.2.0

func NewRealtime(options ...ClientOption) (*Realtime, error)

NewRealtime constructs a new ably.Realtime client object using an Ably ably.ClientOption object (RSC1)

func (*Realtime) Close added in v1.2.0

func (c *Realtime) Close()

Close 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 Connection.Connect proxy for RTN12

func (*Realtime) Connect added in v1.2.0

func (c *Realtime) Connect()

Connect calls Connection.Connect and causes the connection to open, entering the connecting state. Explicitly calling Connect() is needed if the ClientOptions.NoConnect is set true (proxy for RTN11).

func (*Realtime) Stats added in v1.2.0

func (c *Realtime) Stats(o ...StatsOption) StatsRequest

Stats queries the REST /stats API and retrieves your application's usage statistics. Returns a ably.PaginatedResult object, containing an array of ably.Stats objects (RTC5).

See package-level documentation => ably Pagination for handling stats pagination.

func (*Realtime) Time added in v1.2.0

func (c *Realtime) Time(ctx context.Context) (time.Time, error)

Time retrieves the time from the Ably service as milliseconds since the Unix epoch. Clients that do not have access to a sufficiently well maintained time source and wish to issue Ably multiple ably.TokenRequest with a more accurate timestamp should use the clientOptions.UseQueryTime property instead of this method (RTC6a).

type RealtimeChannel

type RealtimeChannel struct {

	// RealtimeChannel implements [ably.EventEmitter] and emits [ably.ChannelEvent] events, where a ChannelEvent is either
	// a [ably.ChannelState] or [ably.ChannelEventUpdate] (RTL2a, RTL2d, RTL2e).
	ChannelEventEmitter

	// Name is the channel name.
	Name string

	// Presence is a [ably.RealtimePresence] object, provides for entering and leaving client presence (RTL9).
	Presence *RealtimePresence
	// contains filtered or unexported fields
}

RealtimeChannel represents a single named message/presence channel. It enables messages to be published and subscribed to. Also enables historic messages to be retrieved and provides access to the ably.RealtimePresence object of a channel.

func (*RealtimeChannel) Attach

func (c *RealtimeChannel) Attach(ctx context.Context) error

Attach attaches the Realtime connection to the channel (ensuring the channel is created in the Ably system and all messages published on the channel are received by any channel listeners registered using RealtimeChannel#subscribe.) Any resulting channel state change will be emitted to any listeners registered using the EventEmitter#on or EventEmitter#once methods. A callback may optionally be passed in to this call to be notified of success or failure of the operation. As a convenience, attach() is called implicitly if RealtimeChannel#subscribe for the channel is called, or RealtimePresence#enter or RealtimePresence#subscribe are called on the ably.RealtimePresence object for this channel (RTL4d).

If the passed context is cancelled before the attach operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway.

func (*RealtimeChannel) Detach

func (c *RealtimeChannel) Detach(ctx context.Context) error

Detach detaches realtime connection to the channel, after which it stops receiving messages from it. Any resulting channel state change is emitted to any listeners registered using the EventEmitter#on or EventEmitter#once methods. A callback may optionally be passed in to this call to be notified of success or failure of the operation. Once all clients globally have detached from the channel, the channel will be released in the Ably service within two minutes (RTL5e).

If the context is canceled before the detach operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be detached anyway.

func (*RealtimeChannel) ErrorReason added in v1.2.0

func (c *RealtimeChannel) ErrorReason() *ErrorInfo

ErrorReason gives the last error that caused channel transition to failed state.

func (*RealtimeChannel) History

func (c *RealtimeChannel) History(o ...HistoryOption) HistoryRequest

History retrieves a ably.HistoryRequest object, containing an array of historical ably.Message objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.

See package-level documentation => ably Pagination for details about history pagination.

func (*RealtimeChannel) HistoryUntilAttach added in v1.2.15

func (c *RealtimeChannel) HistoryUntilAttach(o ...HistoryOption) (*HistoryRequest, error)

HistoryUntilAttach retrieves a ably.HistoryRequest object, containing an array of historical ably.Message objects for the channel. If the channel is configured to persist messages, then messages can be retrieved from history for up to 72 hours in the past. If not, messages can only be retrieved from history for up to two minutes in the past.

This function will only retrieve messages prior to the moment that the channel was attached or emitted an UPDATE indicating loss of continuity. This bound is specified by passing the querystring param fromSerial with the RealtimeChannel#properties.attachSerial assigned to the channel in the ATTACHED ProtocolMessage (see RTL15a). If the untilAttach param is specified when the channel is not attached, it results in an error.

See package-level documentation => ably Pagination for details about history pagination.

func (*RealtimeChannel) Modes added in v1.2.0

func (c *RealtimeChannel) Modes() []ChannelMode

func (*RealtimeChannel) Params added in v1.2.0

func (c *RealtimeChannel) Params() map[string]string

func (*RealtimeChannel) Publish

func (c *RealtimeChannel) Publish(ctx context.Context, name string, data interface{}) error

Publish publishes a single message to the channel with the given event name and message payload.

This will block until either the publish is acknowledged or fails to deliver.

If the context is cancelled before the attach operation finishes, the call returns an error but the publish will carry on in the background and may eventually be published anyway.

Example

When publishing a message to a channel, data can be either a single string or a struct of type Message. This example shows the different ways to publish a message.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ably/ably-go/ably"
)

func main() {

	// Create a new realtime client.
	client, err := ably.NewRealtime(
		ably.WithKey("ABLY_PRIVATE_KEY"),
		ably.WithClientID("Client A"),
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// Initialise a new channel.
	channel := client.Channels.Get("chat")

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	// Publish a string to the channel
	if err := channel.Publish(ctx, "chat_message", "Hello, how are you?"); err != nil {
		fmt.Println(err)
		return
	}

	// Publish a Message to the channel
	newChatMessage := ably.Message{
		Name: "chat_message",
		Data: "Hello, how are you?",
	}

	if err := channel.Publish(ctx, "chat_message", newChatMessage); err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*RealtimeChannel) PublishAsync added in v1.2.12

func (c *RealtimeChannel) PublishAsync(name string, data interface{}, onAck func(err error)) error

PublishAsync is the same as Publish except instead of blocking it calls onAck with nil if the publish was successful or the appropriate error.

Note onAck must not block as it would block the internal client.

func (*RealtimeChannel) PublishMultiple added in v1.2.0

func (c *RealtimeChannel) PublishMultiple(ctx context.Context, messages []*Message) error

PublishMultiple publishes all given messages on the channel at once.

If the context is cancelled before the attach operation finishes, the call returns an error but the publish will carry on in the background and may eventually be published anyway.

func (*RealtimeChannel) PublishMultipleAsync added in v1.2.12

func (c *RealtimeChannel) PublishMultipleAsync(messages []*Message, onAck func(err error)) error

PublishMultipleAsync is the same as PublishMultiple except it calls onAck instead of blocking (see PublishAsync).

func (*RealtimeChannel) State

func (c *RealtimeChannel) State() ChannelState

State gives the current state of the channel.

func (*RealtimeChannel) Subscribe

func (c *RealtimeChannel) Subscribe(ctx context.Context, name string, handle func(*Message)) (func(), error)

Subscribe registers an event listener for messages with a given event name on this channel. The caller supplies a listener function, which is called each time one or more matching messages arrives on the channel. A callback may optionally be passed in to this call to be notified of success or failure of the channel realtimeChannel#attach operation (RTL7a).

This implicitly attaches the channel if it's not already attached. If the context is canceled before the attach operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (*RealtimeChannel) SubscribeAll added in v1.2.0

func (c *RealtimeChannel) SubscribeAll(ctx context.Context, handle func(*Message)) (func(), error)

SubscribeAll registers an event listener for messages on this channel. The caller supplies a listener function, which is called each time one or more messages arrives on the channel. A callback may optionally be passed in to this call to be notified of success or failure of the channel RealtimeChannel#attach operation (RTL7a).

This implicitly attaches the channel if it's not already attached. If the context is canceled before the attach operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway.

See package-level documentation => ably Event Emitters for details about messages dispatch.

type RealtimeChannels added in v1.2.0

type RealtimeChannels struct {
	// contains filtered or unexported fields
}

RealtimeChannels is a goroutine-safe container for realtime channels that allows for creating, deleting and iterating over existing channels. Creates and destroys ably.RESTChannel and ably.RealtimeChannel objects.

func (*RealtimeChannels) Exists added in v1.2.0

func (c *RealtimeChannels) Exists(name string) bool

Exists returns true if the channel by the given name exists.

This function just checks the local channel map for existence. It can not check for the existence of channels created by other clients (RSN2, RTS2).

func (*RealtimeChannels) Get added in v1.2.0

func (ch *RealtimeChannels) Get(name string, options ...ChannelOption) *RealtimeChannel

Get creates a new ably.RealtimeChannel object for given channel name and provided ably.ChannelOption or returns the existing channel if already created with given channel name. Creating a channel only adds a new channel struct into the channel map. It does not perform any network communication until attached. It is safe to call Get from multiple goroutines - a single channel is guaranteed to be created only once for multiple calls to Get from different goroutines (RSN3a, RTS3a, RSN3c, RTS3c).

func (*RealtimeChannels) GetChannelSerials added in v1.2.15

func (channels *RealtimeChannels) GetChannelSerials() map[string]string

func (*RealtimeChannels) GetDerived added in v1.2.12

func (ch *RealtimeChannels) GetDerived(name string, deriveOptions DeriveOptions, options ...ChannelOption) (*RealtimeChannel, error)

GetDerived is a preview feature and may change in a future non-major release. It creates a new derived ably.RealtimeChannel object for given channel name, using the provided derive options and channel options if any. Returns error if any occurs.

func (*RealtimeChannels) Iterate added in v1.2.0

func (ch *RealtimeChannels) Iterate() []*RealtimeChannel

Iterate returns a ably.RealtimeChannel for each iteration on existing channels. It is safe to call Iterate from multiple goroutines, however there's no guarantee the returned list would not list a channel that was already released from different goroutine (RSN2, RTS2).

func (*RealtimeChannels) Release added in v1.2.0

func (ch *RealtimeChannels) Release(ctx context.Context, name string) error

Release releases a ably.RealtimeChannel object with given channel name (detaching it first), frees all resources associated, e.g. Removes any listeners associated with the channel. To release a channel, the ably.ChannelState must be INITIALIZED, DETACHED, or FAILED (RSN4, RTS4).

func (*RealtimeChannels) SetChannelSerialsFromRecoverOption added in v1.2.15

func (channels *RealtimeChannels) SetChannelSerialsFromRecoverOption(serials map[string]string)

RTN16j, RTL15b

type RealtimePresence

type RealtimePresence struct {
	// contains filtered or unexported fields
}

RealtimePresence represents a single presence map of a particular channel. It allows entering, leaving and updating presence state for the current client or on behalf of other client. It enables the presence set to be entered and subscribed to, and the historic presence set to be retrieved for a channel.

func (*RealtimePresence) Enter

func (pres *RealtimePresence) Enter(ctx context.Context, data interface{}) error

Enter announces the presence of the current client with optional data payload (enter message) on the channel. It enters client presence into the channel presence set. A clientId is required to be present on a channel (RTP8). If this connection has no clientID then this function will fail.

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and presence state may eventually be updated anyway.

Example

When a client is created with a ClientID, Enter is used to announce the client's presence. This example shows Client A entering their presence.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ably/ably-go/ably"
)

func main() {

	// A new realtime client is created with a ClientID.
	client, err := ably.NewRealtime(
		ably.WithKey("ABLY_PRIVATE_KEY"),
		ably.WithClientID("Client A"),
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// A new channel is initialised.
	channel := client.Channels.Get("chat")

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	// The client announces presence with Enter.
	if err := channel.Presence.Enter(ctx, nil); err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*RealtimePresence) EnterClient

func (pres *RealtimePresence) EnterClient(ctx context.Context, clientID string, data interface{}) error

EnterClient announces presence of the given clientID altogether with a enter message for the associated channel. It enters given clientId in the channel presence set. It enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard (*) clientId (RTP4, RTP14, RTP15).

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and presence state may eventually be updated anyway.

Example

When a client is created without a ClientID, EnterClient is used to announce the presence of a client. This example shows a client without a clientID announcing the presence of "Client A" using EnterClient.

package main

import (
	"context"
	"fmt"
	"time"

	"github.com/ably/ably-go/ably"
)

func main() {

	// A new realtime client is created without providing a ClientID.
	client, err := ably.NewRealtime(
		ably.WithKey("ABLY_PRIVATE_KEY"),
	)
	if err != nil {
		fmt.Println(err)
		return
	}

	// A new channel is initialised.
	channel := client.Channels.Get("chat")

	ctx, cancel := context.WithTimeout(context.Background(), time.Second*10)
	defer cancel()

	// The presence of Client A is announced using EnterClient.
	if err := channel.Presence.EnterClient(ctx, "Client A", nil); err != nil {
		fmt.Println(err)
		return
	}
}
Output:

func (*RealtimePresence) Get

func (pres *RealtimePresence) Get(ctx context.Context) ([]*PresenceMessage, error)

Get retrieves the current members (array of ably.PresenceMessage objects) present on the channel and the metadata for each member, such as their ably.PresenceAction and ID (RTP11). If the channel state is initialised or non-attached, it will be updated to ably.ChannelStateAttached.

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway (RTP11).

func (*RealtimePresence) GetWithOptions added in v1.2.0

func (pres *RealtimePresence) GetWithOptions(ctx context.Context, options ...PresenceGetOption) ([]*PresenceMessage, error)

GetWithOptions is Get with optional parameters. Retrieves the current members (array of ably.PresenceMessage objects) present on the channel and the metadata for each member, such as their ably.PresenceAction and ID (RTP11). If the channel state is initialised or non-attached, it will be updated to ably.ChannelStateAttached.

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway (RTP11).

func (*RealtimePresence) Leave

func (pres *RealtimePresence) Leave(ctx context.Context, data interface{}) error

Leave announces current client leave on the channel altogether with an optional data payload (leave message). It is removed from the channel presence members set. A client must have previously entered the presence set before they can leave it (RTP10).

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and presence state may eventually be updated anyway.

func (*RealtimePresence) LeaveClient

func (pres *RealtimePresence) LeaveClient(ctx context.Context, clientID string, data interface{}) error

LeaveClient announces the given clientID leave from the associated channel altogether with a optional leave message. Leaves the given clientId from channel presence set. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard (*) clientId (RTP15).

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and presence data may eventually be updated anyway.

func (*RealtimePresence) Subscribe

func (pres *RealtimePresence) Subscribe(ctx context.Context, action PresenceAction, handle func(*PresenceMessage)) (func(), error)

Subscribe registers a event listener that is called each time a received ably.PresenceMessage matches given ably.PresenceAction or an action within an array of ably.PresenceAction, such as a new member entering the presence set. A callback may optionally be passed in to this call to be notified of success or failure of the channel RealtimeChannel.Attach operation (RTP6b).

This implicitly attaches the channel if it's not already attached. If the context is cancelled before the attach operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (*RealtimePresence) SubscribeAll added in v1.2.0

func (pres *RealtimePresence) SubscribeAll(ctx context.Context, handle func(*PresenceMessage)) (func(), error)

SubscribeAll registers a event listener that is called each time a received ably.PresenceMessage such as a new member entering the presence set. A callback may optionally be passed in to this call to be notified of success or failure of the channel RealtimeChannel.Attach operation (RTP6a).

This implicitly attaches the channel if it's not already attached. If the context is cancelled before the attach operation finishes, the call returns with an error, but the operation carries on in the background and the channel may eventually be attached anyway.

See package-level documentation => ably Event Emitters for details about messages dispatch.

func (*RealtimePresence) SyncComplete

func (pres *RealtimePresence) SyncComplete() bool

SyncComplete gives true if the initial SYNC operation has completed for the members present on the channel.

func (*RealtimePresence) Update

func (pres *RealtimePresence) Update(ctx context.Context, data interface{}) error

Update announces an updated presence message for the current client. Updates the data payload for a presence member. If the current client is not present on the channel, Update will behave as Enter method, i.e. if called before entering the presence set, this is treated as an ably.PresenceActionEnter event (RTP9). If this connection has no clientID then this function will fail.

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and presence state may eventually be updated anyway.

func (*RealtimePresence) UpdateClient

func (pres *RealtimePresence) UpdateClient(ctx context.Context, clientID string, data interface{}) error

UpdateClient announces an updated presence message for the given clientID. If the given clientID is not present on the channel, Update will behave as Enter method. Updates the data payload for a presence member using a given clientId. Enables a single client to update presence on behalf of any number of clients using a single connection. The library must have been instantiated with an API key or a token bound to a wildcard (*) clientId (RTP15).

If the context is cancelled before the operation finishes, the call returns with an error, but the operation carries on in the background and presence data may eventually be updated anyway.

type RecoveryKeyContext added in v1.2.15

type RecoveryKeyContext struct {
	ConnectionKey  string            `json:"connectionKey" codec:"connectionKey"`
	MsgSerial      int64             `json:"msgSerial" codec:"msgSerial"`
	ChannelSerials map[string]string `json:"channelSerials" codec:"channelSerials"`
}

RecoveryKeyContext contains the properties required to recover existing connection.

func DecodeRecoveryKey added in v1.2.15

func DecodeRecoveryKey(recoveryKey string) (rCtx *RecoveryKeyContext, err error)

func (*RecoveryKeyContext) Encode added in v1.2.15

func (r *RecoveryKeyContext) Encode() (serializedRecoveryKey string, err error)

type RequestOption added in v1.2.0

type RequestOption func(*requestOptions)

RequestOption configures a call to REST.Request.

func RequestWithBody added in v1.2.0

func RequestWithBody(body interface{}) RequestOption

RequestWithBody sets the JSON body of the request.

func RequestWithHeaders added in v1.2.0

func RequestWithHeaders(headers http.Header) RequestOption

RequestWithHeaders sets additional HTTP headers to include in the request.

func RequestWithParams added in v1.2.0

func RequestWithParams(params url.Values) RequestOption

RequestWithParams sets the parameters to include in the URL query of the request. The parameters depend on the endpoint being queried. See the REST API reference for the available parameters of each endpoint.

type ScopeParams

type ScopeParams struct {
	Start time.Time
	End   time.Time
	Unit  string
}

func (ScopeParams) EncodeValues

func (s ScopeParams) EncodeValues(out *url.Values) error

type Stats added in v1.2.0

type Stats struct {

	// IntervalID is the UTC time at which the time period covered begins.
	// If unit is set to minute this will be in the format YYYY-mm-dd:HH:MM, if hour it will be YYYY-mm-dd:HH,
	// if day it will be YYYY-mm-dd:00 and if month it will be YYYY-mm-01:00 (TS12a).
	IntervalID string `json:"intervalId" codec:"intervalId"`

	// Unit is the length of the interval the stats span.
	// Values will be a [ably.StatGranularityMinute], [ably.StatGranularityMinute], [ably.StatGranularityMinute] or
	// [ably.StatGranularityMinute] (TS12c).
	Unit string `json:"unit" codec:"unit"`

	InProgress string `json:"inProgress" codec:"inProgress"`

	Count float64 `json:"count" codec:"count"`

	// All is a [ably.StatsMessageTypes] object containing the aggregate count of
	// all message stats (TS12e).
	All StatsMessageTypes `json:"all" codec:"all"`

	// Inbound is a [ably.StatsMessageTraffic] object containing the aggregate count of
	// inbound message stats (TS12f).
	Inbound StatsMessageTraffic `json:"inbound" codec:"inbound"`

	// Outbound is a [ably.StatsMessageTraffic] object containing the aggregate count of
	// outbound message stats (TS12g).
	Outbound StatsMessageTraffic `json:"outbound" codec:"outbound"`

	// Persisted is a [ably.StatsMessageTypes] object containing the aggregate count of
	// persisted message stats (TS12h).
	Persisted StatsMessageTypes `json:"persisted" codec:"persisted"`

	// Connections is a [ably.StatsConnectionTypes] object containing a breakdown of connection related stats, such as min,
	// mean and peak connections (TS12i).
	Connections StatsConnectionTypes `json:"connections" codec:"connections"`

	// Channels is a [ably.StatsResourceCount] object containing a breakdown of channels (TS12j).
	Channels StatsResourceCount `json:"channels" codec:"channels"`

	// APIRequests is a [ably.StatsRequestCount] object containing a breakdown of API Requests (TS12k).
	APIRequests StatsRequestCount `json:"apiRequests" codec:"apiRequests"`

	// TokenRequests is a [ably.StatsRequestCount] object containing a breakdown of Ably Token requests (TS12l).
	TokenRequests StatsRequestCount `json:"tokenRequests" codec:"tokenRequests"`

	// Push is a [ably.PushStats] object containing a breakdown of stats on push notifications (TS12m).
	Push PushStats `json:"push" codec:"push"`

	// XchgProducer is a [ably.StatsXchgMessages] is a object containing data about usage of
	// Ably API Streamer as a producer (TS12n).
	XchgProducer StatsXchgMessages `json:"xchgProducer" codec:"xchgProducer"`

	// XchgConsumer is a [ably.StatsXchgMessages] object containing data about usage of
	// Ably API Streamer as a consumer (TS12o).
	XchgConsumer StatsXchgMessages `json:"xchgConsumer" codec:"xchgConsumer"`

	PeakRates StatsRates `json:"peakRates" codec:"peakRates"`
}

Stats contains application statistics for a specified time interval and time period.

func (Stats) String added in v1.2.0

func (s Stats) String() string

type StatsConnectionTypes added in v1.2.0

type StatsConnectionTypes struct {
	// All is a [ably.StatsResourceCount] object containing a breakdown of usage by scope over
	// TLS connections (both TLS and non-TLS) (TS4c).
	All StatsResourceCount `json:"all" codec:"all"`
	// Plain is a [ably.StatsResourceCount] object containing a breakdown of usage by scope over non-TLS connections (TS4b).
	Plain StatsResourceCount `json:"plain" codec:"plain"`
	// TLS is a [ably.StatsResourceCount] object containing a breakdown of usage by scope over TLS connections (TS4a).
	TLS StatsResourceCount `json:"tls" codec:"tls"`
}

StatsConnectionTypes contains a breakdown of summary stats data for different (TLS vs non-TLS) connection types.

type StatsMessageCount added in v1.2.0

type StatsMessageCount struct {
	// Count is the count of all messages (TS5a).
	Count float64 `json:"count" codec:"count"`
	// Data is the total number of bytes transferred for all messages (TS5b).
	Data    float64 `json:"data" codec:"data"`
	Failed  float64 `json:"failed" codec:"failed"`
	Refused float64 `json:"refused" codec:"refused"`
}

StatsMessageCount contains the aggregate counts for messages and data transferred.

type StatsMessageDirections added in v1.2.0

type StatsMessageDirections struct {
	// All is a [ably.StatsMessageTypes] object containing a breakdown of usage by message type for
	// messages published and received (TS14a).
	All StatsMessageTypes `json:"all" codec:"all"`
	// Inbound is a [ably.StatsMessageTraffic] object containing a breakdown of usage by transport type
	// for received messages (TS14b).
	Inbound StatsMessageTraffic `json:"inbound" codec:"inbound"`
	// Outbound is a [ably.StatsMessageTraffic] object containing a breakdown of usage by transport type
	// for published messages (TS14c).
	Outbound StatsMessageTraffic `json:"outbound" codec:"outbound"`
}

type StatsMessageTraffic added in v1.2.0

type StatsMessageTraffic struct {
	// All is a [ably.StatsMessageTypes] object containing a breakdown of usage by message type for all messages
	// (includes realtime, rest and webhook messages) (TS7d).
	All StatsMessageTypes `json:"all" codec:"all"`
	// RealTime is a [ably.StatsMessageTypes] object containing a breakdown of usage by message type for messages
	// transferred over a realtime transport such as WebSocket (TS7a).
	RealTime StatsMessageTypes `json:"realtime" codec:"realtime"`
	// REST is a [ably.StatsMessageTypes] object containing a breakdown of usage by message type for messages
	// transferred over a rest transport such as WebSocket (TS7b).
	REST StatsMessageTypes `json:"rest" codec:"rest"`
	// Webhook is a [ably.StatsMessageTypes] object containing a breakdown of usage by message type for
	// messages delivered using webhooks (TS7c).
	Webhook StatsMessageTypes `json:"webhook" codec:"webhook"`

	Push StatsMessageTypes `json:"push" codec:"push"`

	ExternalQueue StatsMessageTypes `json:"externalQueue" codec:"externalQueue"`

	SharedQueue StatsMessageTypes `json:"sharedQueue" codec:"sharedQueue"`

	HTTPEvent StatsMessageTypes `json:"httpEvent" codec:"httpEvent"`
}

type StatsMessageTypes added in v1.2.0

type StatsMessageTypes struct {
	// All is a [ably.StatsMessageCount] object containing the count and byte value of messages and presence messages (TS6c).
	All StatsMessageCount `json:"all" codec:"all"`
	// Messages is a [ably.StatsMessageCount] object containing the count and byte value of messages (TS6a).
	Messages StatsMessageCount `json:"messages" codec:"messages"`
	// Presence is a [ably.StatsMessageCount] object containing the count and byte value of presence messages (TS6b).
	Presence StatsMessageCount `json:"presence" codec:"presence"`
}

StatsMessageTypes contains a breakdown of summary stats data for different (channel vs presence) message types.

type StatsOption added in v1.2.0

type StatsOption func(*statsOptions)

A StatsOption configures a call to REST.Stats or Realtime.Stats.

func StatsWithDirection added in v1.2.0

func StatsWithDirection(d Direction) StatsOption

StatsWithDirection sets the order for which stats are returned in. Valid values are backwards which orders stats from most recent to oldest, or forwards which orders stats from oldest to most recent. The default is backwards (RSC6b2).

func StatsWithEnd added in v1.2.0

func StatsWithEnd(t time.Time) StatsOption

StatsWithEnd sets the time until stats are retrieved, specified as milliseconds since the Unix epoch (RSC6b1).

func StatsWithLimit added in v1.2.0

func StatsWithLimit(limit int) StatsOption

StatsWithLimit sets an upper limit on the number of stats returned. The default is 100, and the maximum is 1000 (RSC6b3).

func StatsWithStart added in v1.2.0

func StatsWithStart(t time.Time) StatsOption

StatsWithStart sets the time from which stats are retrieved, specified as milliseconds since the Unix epoch (RSC6b1).

func StatsWithUnit added in v1.2.0

func StatsWithUnit(d PeriodUnit) StatsOption

StatsWithUnit sets 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 query (RSC6b4).

type StatsPaginatedItems added in v1.2.0

type StatsPaginatedItems struct {
	PaginatedResult
	// contains filtered or unexported fields
}

func (*StatsPaginatedItems) Item added in v1.2.0

func (p *StatsPaginatedItems) Item() *Stats

Item returns the current result.

See package-level documentation => ably Pagination for handling stats pagination.

func (*StatsPaginatedItems) Next added in v1.2.0

func (p *StatsPaginatedItems) Next(ctx context.Context) bool

Next retrieves the next result.

See package-level documentation => ably Pagination for handling stats pagination.

type StatsPaginatedResult added in v1.2.0

type StatsPaginatedResult struct {
	PaginatedResult
	// contains filtered or unexported fields
}

A StatsPaginatedResult is an iterator for the result of a Stats request.

See package-level documentation => ably Pagination for handling stats pagination.

func (*StatsPaginatedResult) HasNext added in v1.2.6

func (p *StatsPaginatedResult) HasNext(ctx context.Context) bool

HasNext returns true is there are more pages available.

See package-level documentation => ably Pagination for handling stats pagination.

func (*StatsPaginatedResult) IsLast added in v1.2.6

func (p *StatsPaginatedResult) IsLast(ctx context.Context) bool

IsLast returns true if the page is last page.

See package-level documentation => ably Pagination for handling stats pagination.

func (*StatsPaginatedResult) Items added in v1.2.0

func (p *StatsPaginatedResult) Items() []*Stats

Items returns the current page of results.

See package-level documentation => ably Pagination for handling stats pagination.

func (*StatsPaginatedResult) Next added in v1.2.0

Next retrieves the next page of results.

See package-level documentation => ably Pagination for handling stats pagination.

type StatsPushNotificationFailures added in v1.2.0

type StatsPushNotificationFailures struct {
	Retriable StatsPushTransportTypeCounter `json:"retriable" codec:"retriable"`

	Final StatsPushTransportTypeCounter `json:"final" codec:"final"`
}

type StatsPushNotifications added in v1.2.0

type StatsPushNotifications struct {
	Invalid float64 `json:"invalid" codec:"invalid"`

	Attempted StatsPushTransportTypeCounter `json:"attempted" codec:"attempted"`

	Successful StatsPushTransportTypeCounter `json:"successful" codec:"successful"`

	Failed StatsPushNotificationFailures `json:"failed" codec:"failed"`
}

type StatsPushTransportTypeCounter added in v1.2.0

type StatsPushTransportTypeCounter struct {
	Total float64 `json:"total" codec:"total"`

	GCM float64 `json:"gcm" codec:"gcm"`

	FCM float64 `json:"fcm" codec:"fcm"`

	APNS float64 `json:"apns" codec:"apns"`

	Web float64 `json:"web" codec:"web"`
}

type StatsRates added in v1.2.0

type StatsRates struct {
	Messages      float64           `json:"messages" codec:"messages"`
	APIRequests   float64           `json:"apiRequests" codec:"apiRequests"`
	TokenRequests float64           `json:"tokenRequests" codec:"tokenRequests"`
	Reactor       StatsReactorRates `json:"reactor" codec:"reactor"`
}

type StatsReactorRates added in v1.2.0

type StatsReactorRates struct {
	HTTPEvent float64 `json:"httpEvent" codec:"httpEvent"`
	AMQP      float64 `json:"amqp" codec:"amqp"`
}

type StatsRequest added in v1.2.0

type StatsRequest struct {
	// contains filtered or unexported fields
}

StatsRequest represents a request prepared by the REST.Stats or Realtime.Stats method, ready to be performed by its Pages or Items methods.

func (StatsRequest) Items added in v1.2.0

Items returns a convenience iterator for single Stats, over an underlying paginated iterator.

See package-level documentation => ably Pagination for handling stats pagination.

func (StatsRequest) Pages added in v1.2.0

Pages returns an iterator for whole pages of Stats.

See package-level documentation => ably Pagination for handling stats pagination.

type StatsRequestCount added in v1.2.0

type StatsRequestCount struct {
	// Failed is the number of requests that failed (TS8b).
	Failed float64 `json:"failed" codec:"failed"`
	// Refused is the number of requests that were refused, typically as a result of permissions or
	// a limit being exceeded (TS8c).
	Refused float64 `json:"refused" codec:"refused"`
	// Succeeded is the number of requests that succeeded (TS8a).
	Succeeded float64 `json:"succeeded" codec:"succeeded"`
}

type StatsResourceCount added in v1.2.0

type StatsResourceCount struct {
	// Peak is the peak number of resources of this type used for this period (TS9b).
	Peak float64 `json:"peak" codec:"peak"`
	// Min is the minimum total resources of this type used for this period (TS9d).
	Min float64 `json:"min" codec:"min"`
	// Mean is the average number of resources of this type used for this period (TS9c).
	Mean float64 `json:"mean" codec:"mean"`
	// Opened is the total number of resources opened of this type (TS9a).
	Opened float64 `json:"opened" codec:"opened"`
	Failed float64 `json:"failed" codec:"failed"`
	// Refused is the number of resource requests refused within this period (TS9e).
	Refused float64 `json:"refused" codec:"refused"`
}

type StatsXchgMessages added in v1.2.0

type StatsXchgMessages struct {
	// All is a [ably.StatsMessageTypes] object containing a breakdown of usage by message type
	// for the Ably API Streamer (TS11a).
	All StatsMessageTypes `json:"all" codec:"all"`

	// ProducerPaid is a [ably.StatsMessageDirections] object containing a breakdown of usage, by messages
	// published and received, for the API Streamer charged to the producer (TS11b).
	ProducerPaid StatsMessageDirections `json:"producerPaid" codec:"producerPaid"`

	// ConsumerPaid is a [ably.StatsMessageDirections] object containing a breakdown of usage, by messages
	// published and received, for the API Streamer charged to the consumer (TS11c).
	ConsumerPaid StatsMessageDirections `json:"consumerPaid" codec:"consumerPaid"`
}

type TokenDetails

type TokenDetails struct {

	// Token is the ably Token itself (TD2).
	// A typical Ably Token string appears with the form xVLyHw.A-pwh7wicf3afTfgiw4k2Ku33kcnSA7z6y8FjuYpe3QaNRTEo4.
	Token string `json:"token,omitempty" codec:"token,omitempty"`

	// KeyName is a string part of ABLY_KEY before :
	KeyName string `json:"keyName,omitempty" codec:"keyName,omitempty"`

	// Expires is the timestamp at which this token expires as milliseconds since the Unix epoch (TD3).
	Expires int64 `json:"expires,omitempty" codec:"expires,omitempty"`

	// ClientID, 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 client (TD6).
	ClientID string `json:"clientId,omitempty" codec:"clientId,omitempty"`

	// Issued is the timestamp at which this token was issued as milliseconds since the Unix epoch.
	Issued int64 `json:"issued,omitempty" codec:"issued,omitempty"`

	// Capability is the capabilities associated with this Ably Token.
	// The capabilities value is a JSON-encoded representation of the resource paths and associated operations.
	// Read more about capabilities in the [capabilities docs] (TD5).
	//
	// [capabilities docs]: https://ably.com/docs/core-features/authentication/#capabilities-explained
	Capability string `json:"capability,omitempty" codec:"capability,omitempty"`
}

TokenDetails contains an Ably Token and its associated metadata.

func (*TokenDetails) ExpireTime

func (tok *TokenDetails) ExpireTime() time.Time

func (TokenDetails) IsTokener added in v1.2.0

func (TokenDetails) IsTokener()

func (*TokenDetails) IssueTime

func (tok *TokenDetails) IssueTime() time.Time

type TokenParams

type TokenParams struct {
	// TTL is a requested time to live for the token in milliseconds. If the token request
	// is successful, the TTL of the returned token will be less than or equal
	// to this value depending on application settings and the attributes
	// of the issuing key.
	// The default is 60 minutes (RSA9e, TK2a).
	TTL int64 `json:"ttl,omitempty" codec:"ttl,omitempty"`

	// Capability represents encoded channel access rights associated with this Ably Token.
	// The capabilities value is a JSON-encoded representation of the resource paths and associated operations.
	// Read more about capabilities in the [capabilities docs].
	// default '{"*":["*"]}' (RSA9f, TK2b)
	//
	// [capabilities docs]: https://ably.com/docs/core-features/authentication/#capabilities-explained
	Capability string `json:"capability,omitempty" codec:"capability,omitempty"`

	// ClientID is used for identifying this client when publishing messages or for presence purposes.
	// The clientId can be any non-empty string, except it cannot contain a *. This option is primarily intended
	// to be used in situations where the library is instantiated with a key.
	// Note that a clientId may also be implicit in a token used to instantiate the library.
	// An error is raised if a clientId specified here conflicts with the clientId implicit in the token.
	// Find out more about [identified clients] (TK2c).
	//
	// [identified clients]: https://ably.com/docs/core-features/authentication#identified-clients
	ClientID string `json:"clientId,omitempty" codec:"clientId,omitempty"`

	// Timestamp of the token request as milliseconds since the Unix epoch.
	// Timestamps, in conjunction with the nonce, are used to prevent requests from being replayed.
	// timestamp is a "one-time" value, and is valid in a request, but is not validly a member of
	// any default token params such as ClientOptions.defaultTokenParams (RSA9d, Tk2d).
	Timestamp int64 `json:"timestamp,omitempty" codec:"timestamp,omitempty"`
}

TokenParams contains token params to be sent to ably to get auth token

func (*TokenParams) Query

func (params *TokenParams) Query() url.Values

Query encodes the params to query params value. If a field of params is a zero-value, it's omitted. If params is zero-value, nil is returned.

type TokenRequest

type TokenRequest struct {
	TokenParams `codec:",inline"`

	// KeyName is the name of the key against which this request is made.
	// The key name is public, whereas the key secret is private (TE2).
	KeyName string `json:"keyName,omitempty" codec:"keyName,omitempty"`

	// Nonce is a cryptographically secure random string of at least 16 characters,
	// used to ensure the TokenRequest cannot be reused (TE2).
	Nonce string `json:"nonce,omitempty" codec:"nonce,omitempty"`

	// MAC is the Message Authentication Code for this request.
	MAC string `json:"mac,omitempty" codec:"mac,omitempty"`
}

TokenRequest contains tokenparams with extra details, sent to ably for getting auth token

func (TokenRequest) IsTokener added in v1.2.0

func (TokenRequest) IsTokener()

type TokenString added in v1.2.0

type TokenString string

TokenString is the string representation of an authentication token.

func (TokenString) IsTokener added in v1.2.0

func (TokenString) IsTokener()

type Tokener added in v1.2.0

type Tokener interface {
	IsTokener()
	// contains filtered or unexported methods
}

Tokener is or can be used to get a ably.TokenDetails.

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL