ably

package
v1.1.5 Latest Latest
Warning

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

Go to latest
Published: May 27, 2020 License: Apache-2.0 Imports: 32 Imported by: 21

Documentation

Index

Constants

View Source
const (
	ErrNoError                                                                 = 10000
	ErrBadRequest                                                              = 40000
	ErrInvalidRequestBody                                                      = 40001
	ErrInvalidParameterName                                                    = 40002
	ErrInvalidParameterValue                                                   = 40003
	ErrInvalidHeader                                                           = 40004
	ErrInvalidCredential                                                       = 40005
	ErrInvalidConnectionID                                                     = 40006
	ErrInvalidMessageID                                                        = 40007
	ErrInvalidContentLength                                                    = 40008
	ErrMaximumMessageLengthExceeded                                            = 40009
	ErrInvalidChannelName                                                      = 40010
	ErrStaleRingState                                                          = 40011
	ErrInvalidClientID                                                         = 40012
	ErrInvalidMessageDataOrEncoding                                            = 40013
	ErrResourceDisposed                                                        = 40014
	ErrInvalidDeviceID                                                         = 40015
	ErrBatchError                                                              = 40020
	ErrInvalidPublishRequestUnspecified                                        = 40030
	ErrInvalidPublishRequestInvalidClientSpecifiedID                           = 40031
	ErrUnauthorized                                                            = 40100
	ErrInvalidCredentials                                                      = 40101
	ErrIncompatibleCredentials                                                 = 40102
	ErrInvalidUseOfBasicAuthOverNonTLSTransport                                = 40103
	ErrTimestampNotCurrent                                                     = 40104
	ErrNonceValueReplayed                                                      = 40105
	ErrUnableToObtainCredentialsFromGivenParameters                            = 40106
	ErrAccountDisabled                                                         = 40110
	ErrAccountRestrictedConnectionLimitsExceeded                               = 40111
	ErrAccountBlockedMessageLimitsExceeded                                     = 40112
	ErrAccountBlocked                                                          = 40113
	ErrAccountRestrictedChannelLimitsExceeded                                  = 40114
	ErrApplicationDisabled                                                     = 40120
	ErrKeyErrorUnspecified                                                     = 40130
	ErrKeyRevoked                                                              = 40131
	ErrKeyExpired                                                              = 40132
	ErrKeyDisabled                                                             = 40133
	ErrTokenErrorUnspecified                                                   = 40140
	ErrTokenRevoked                                                            = 40141
	ErrTokenExpired                                                            = 40142
	ErrTokenUnrecognised                                                       = 40143
	ErrInvalidJWTFormat                                                        = 40144
	ErrInvalidTokenFormat                                                      = 40145
	ErrConnectionBlockedLimitsExceeded                                         = 40150
	ErrOperationNotPermittedWithProvidedCapability                             = 40160
	ErrErrorFromClientTokenCallback                                            = 40170
	ErrForbidden                                                               = 40300
	ErrAccountDoesNotPermitTLSConnection                                       = 40310
	ErrOperationRequiresTLSConnection                                          = 40311
	ErrApplicationRequiresAuthentication                                       = 40320
	ErrNotFound                                                                = 40400
	ErrMethodNotAllowed                                                        = 40500
	ErrRateLimitExceededNonfatal                                               = 42910
	ErrMaxPerConnectionPublishRateLimitExceededNonfatal                        = 42911
	ErrRateLimitExceededFatal                                                  = 42920
	ErrMaxPerConnectionPublishRateLimitExceededFatal                           = 42921
	ErrInternalError                                                           = 50000
	ErrInternalChannelError                                                    = 50001
	ErrInternalConnectionError                                                 = 50002
	ErrTimeoutError                                                            = 50003
	ErrRequestFailedDueToOverloadedInstance                                    = 50004
	ErrReactorOperationFailed                                                  = 70000
	ErrReactorOperationFailedPostOperationFailed                               = 70001
	ErrReactorOperationFailedPostOperationReturnedUnexpectedCode               = 70002
	ErrReactorOperationFailedMaximumNumberOfConcurrentInFlightRequestsExceeded = 70003
	ErrExchangeErrorUnspecified                                                = 71000
	ErrForcedReAttachmentDueToPermissionsChange                                = 71001
	ErrExchangePublisherErrorUnspecified                                       = 71100
	ErrNoSuchPublisher                                                         = 71101
	ErrPublisherNotEnabledAsAnExchangePublisher                                = 71102
	ErrExchangeProductErrorUnspecified                                         = 71200
	ErrNoSuchProduct                                                           = 71201
	ErrProductDisabled                                                         = 71202
	ErrNoSuchChannelInThisProduct                                              = 71203
	ErrExchangeSubscriptionErrorUnspecified                                    = 71300
	ErrSubscriptionDisabled                                                    = 71301
	ErrRequesterHasNoSubscriptionToThisProduct                                 = 71302
	ErrConnectionFailed                                                        = 80000
	ErrConnectionFailedNoCompatibleTransport                                   = 80001
	ErrConnectionSuspended                                                     = 80002
	ErrDisconnected                                                            = 80003
	ErrAlreadyConnected                                                        = 80004
	ErrInvalidConnectionIDRemoteNotFound                                       = 80005
	ErrUnableToRecoverConnectionMessagesExpired                                = 80006
	ErrUnableToRecoverConnectionMessageLimitExceeded                           = 80007
	ErrUnableToRecoverConnectionConnectionExpired                              = 80008
	ErrConnectionNotEstablishedNoTransportHandle                               = 80009
	ErrInvalidOperationInvalidTransportHandle                                  = 80010
	ErrUnableToRecoverConnectionIncompatibleAuthParams                         = 80011
	ErrUnableToRecoverConnectionInvalidOrUnspecifiedConnectionSerial           = 80012
	ErrProtocolError                                                           = 80013
	ErrConnectionTimedOut                                                      = 80014
	ErrIncompatibleConnectionParameters                                        = 80015
	ErrOperationOnSupersededTransport                                          = 80016
	ErrConnectionClosed                                                        = 80017
	ErrInvalidConnectionIDInvalidFormat                                        = 80018
	ErrClientConfiguredAuthenticationProviderRequestFailed                     = 80019
	ErrContinuityLossDueToMaximumSubscribeMessageRateExceeded                  = 80020
	ErrClientRestrictionNotSatisfied                                           = 80030
	ErrChannelOperationFailed                                                  = 90000
	ErrChannelOperationFailedInvalidChannelState                               = 90001
	ErrChannelOperationFailedEpochExpiredOrNeverExisted                        = 90002
	ErrUnableToRecoverChannelMessagesExpired                                   = 90003
	ErrUnableToRecoverChannelMessageLimitExceeded                              = 90004
	ErrUnableToRecoverChannelNoMatchingEpoch                                   = 90005
	ErrUnableToRecoverChannelUnboundedRequest                                  = 90006
	ErrChannelOperationFailedNoResponseFromServer                              = 90007
	ErrMaximumNumberOfChannelsPerConnectionExceeded                            = 90010
	ErrUnableToEnterPresenceChannelNoClientID                                  = 91000
	ErrUnableToEnterPresenceChannelInvalidChannelState                         = 91001
	ErrUnableToLeavePresenceChannelThatIsNotEntered                            = 91002
	ErrUnableToEnterPresenceChannelMaximumMemberLimitExceeded                  = 91003
	ErrUnableToAutomaticallyReEnterPresenceChannel                             = 91004
	ErrPresenceStateIsOutOfSync                                                = 91005
	ErrMemberImplicitlyLeftPresenceChannelConnectionClosed                     = 91100
)

ably error codes

View Source
const (
	AblyVersionHeader      = "X-Ably-Version"
	AblyLibHeader          = "X-Ably-Lib"
	AblyErrorCodeHeader    = "X-Ably-Errorcode"
	AblyErrormessageHeader = "X-Ably-Errormessage"
	LibraryVersion         = "1.1.5"
	LibraryName            = "ably-go"
	LibraryString          = LibraryName + "-" + LibraryVersion
	AblyVersion            = "1.0"
	AblyClientIDHeader     = "X-Ably-ClientId"
)

constants for rsc7

View Source
const HostHeader = "Host"
View Source
const (

	// RestHost is the primary ably host .
	RestHost = "rest.ably.io"
)

Variables

This section is empty.

Functions

func DefaultFallbackHosts added in v1.1.0

func DefaultFallbackHosts() []string

func Duration

func Duration(d time.Duration) int64

Duration returns converts the given duration to milliseconds.

func Time

func Time(t time.Time) int64

Time returns the given time as a timestamp in milliseconds since epoch.

func TimeNow

func TimeNow() int64

TimeNow returns current time as a timestamp in milliseconds since epoch.

Types

type Auth

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

Auth

func (*Auth) Authorise

func (a *Auth) Authorise(params *TokenParams, opts *AuthOptions) (*TokenDetails, error)

Authorise performs authorization with ably service and returns the authorization token details.

This method is an alias to Auth.Authorize and it is DEPRECATED use Auth.Authorize instead.

Refers to RSA10l

func (*Auth) Authorize added in v1.1.0

func (a *Auth) Authorize(params *TokenParams, opts *AuthOptions) (*TokenDetails, error)

Authorize performs authorization with ably service and returns the authorization token details.

Refers to RSA10

func (*Auth) ClientID

func (a *Auth) ClientID() string

ClientID

func (*Auth) CreateTokenRequest

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

CreateTokenRequest

func (*Auth) RequestToken

func (a *Auth) RequestToken(params *TokenParams, opts *AuthOptions) (*TokenDetails, error)

RequestToken

type AuthOptions

type AuthOptions struct {
	// AuthCallback is called in order to obtain a signed token request.
	//
	// This enables a client to obtain token requests from another entity,
	// so tokens can be renewed without the client requiring access to keys.
	//
	// The returned value of the token is expected to be one of the following
	// types:
	//
	//   - string, which is then used as token string
	//   - *ably.TokenRequest, which is then used as an already signed request
	//   - *ably.TokenDetails, which is then used as a token
	//
	AuthCallback func(params *TokenParams) (token interface{}, err error)

	// URL which is queried to obtain a signed token request.
	//
	// 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
	//
	AuthURL string

	// Key obtained from the dashboard.
	Key string

	// Token is an authentication token issued for this application against
	// a specific key and TokenParams.
	Token string

	// TokenDetails is an authentication token issued for this application against
	// a specific key and TokenParams.
	TokenDetails *TokenDetails

	// AuthMethod specifies which method, GET or POST, is used to query AuthURL
	// for the token information (*ably.TokenRequest or *ablyTokenDetails).
	//
	// If empty, GET is used by default.
	AuthMethod string

	// AuthHeaders are HTTP request headers to be included in any request made
	// to the AuthURL.
	AuthHeaders http.Header

	// AuthParams are HTTP query parameters to be included in any requset made
	// to the AuthURL.
	AuthParams url.Values

	// UseQueryTime when set to true, the time queried from Ably servers will
	// be used to sign the TokenRequest instead of using local time.
	UseQueryTime bool

	// Spec: TO3j11
	DefaultTokenParams *TokenParams

	// UseTokenAuth makes the Rest and Realtime clients always use token
	// authentication method.
	UseTokenAuth bool

	// Force when true makes the client request new token unconditionally.
	//
	// By default the client does not request new token if the current one
	// is still valid.
	Force bool
}

func (*AuthOptions) KeyName

func (opts *AuthOptions) KeyName() string

KeyName gives the key name parsed from the Key field.

func (*AuthOptions) KeySecret

func (opts *AuthOptions) KeySecret() string

KeySecret gives the key secret parsed from the Key field.

type Capability

type Capability map[string][]string

Capability

func ParseCapability

func ParseCapability(capability string) (c Capability, err error)

ParseCapability

func (Capability) Encode

func (c Capability) Encode() string

Encode

type Channels

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

Channels is a goroutine-safe container for realtime channels that allows for creating, deleting and iterating over existing channels.

func (*Channels) All

func (ch *Channels) All() []*RealtimeChannel

All returns a list of created channels.

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

The returned list is sorted by channel names.

func (*Channels) Get

func (ch *Channels) Get(name string) *RealtimeChannel

Get looks up a channel given by the name and creates it if it does not exist already.

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.

func (*Channels) Release

func (ch *Channels) Release(name string) error

Release closes a channel looked up by the name.

It is safe to call Release from multiple goroutines - if a channel happened to be already concurrently released, the method is a nop.

type ClientOptions

type ClientOptions struct {
	AuthOptions

	RestHost                string // optional; overwrite endpoint hostname for REST client
	FallbackHostsUseDefault bool

	FallbackHosts   []string
	RealtimeHost    string        // optional; overwrite endpoint hostname for Realtime client
	Environment     string        // optional; prefixes both hostname with the environment string
	Port            int           // optional: port to use for non-TLS connections and requests
	TLSPort         int           // optional: port to use for TLS connections and requests
	ClientID        string        // optional; required for managing realtime presence of the current client
	Recover         string        // optional; used to recover client state
	Logger          LoggerOptions // optional; overwrite logging defaults
	TransportParams map[string]string

	// max number of fallback hosts to use as a fallback.
	HTTPMaxRetryCount int

	// The period in milliseconds before HTTP requests are retried against the
	// default endpoint
	//
	// spec TO3l10
	FallbackRetryTimeout time.Duration

	NoTLS            bool // when true REST and realtime client won't use TLS
	NoConnect        bool // when true realtime client will not attempt to connect automatically
	NoEcho           bool // when true published messages will not be echoed back
	NoQueueing       bool // when true drops messages published during regaining connection
	NoBinaryProtocol bool // when true uses JSON for network serialization protocol instead of MsgPack

	// When true idempotent rest publishing will be enabled.
	// Spec TO3n
	IdempotentRestPublishing bool

	// TimeoutConnect is the time period after which connect request is failed.
	//
	// Deprecated: use RealtimeRequestTimeout instead.
	TimeoutConnect    time.Duration
	TimeoutDisconnect time.Duration // time period after which disconnect request is failed
	TimeoutSuspended  time.Duration // time period after which no more reconnection attempts are performed

	// RealtimeRequestTimeout is the timeout for realtime connection establishment
	// and each subsequent operation.
	RealtimeRequestTimeout time.Duration

	// DisconnectedRetryTimeout is the time to wait after a disconnection before
	// attempting an automatic reconnection, if still disconnected.
	DisconnectedRetryTimeout time.Duration

	// Dial specifies the dial function for creating message connections used
	// by RealtimeClient.
	//
	// If Dial is nil, the default websocket connection is used.
	Dial func(protocol string, u *url.URL) (proto.Conn, error)

	// Listener if set, will be automatically registered with On method for every
	// realtime connection and realtime channel created by realtime client.
	// The listener will receive events for all state transitions.
	Listener chan<- State

	// HTTPClient specifies the client used for HTTP communication by RestClient.
	//
	// If HTTPClient is nil, the http.DefaultClient is used.
	HTTPClient *http.Client

	//When provided this will be used on every request.
	Trace *httptrace.ClientTrace
}

func NewClientOptions

func NewClientOptions(key string) *ClientOptions

type Conn

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

Conn represents a single connection RealtimeClient instantiates for communication with Ably servers.

func (*Conn) Close

func (c *Conn) Close() error

Close initiates closing sequence for the connection; it waits until the operation is complete.

If connection is already closed, this method is a nop.

func (*Conn) Connect

func (c *Conn) Connect() (Result, error)

Connect is used to connect to Ably servers manually, when the client owning the connection was created with NoConnect option. The connect request is being processed on a separate goroutine.

If client is already connected, this method is a nop. If connecting fail due to authorization error, the returned error value is non-nil. If authorization succeeds, the returned Result value can be used to wait until connection confirmation is received from a server.

func (*Conn) ID

func (c *Conn) 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 StateConnConnected event previously obtained ID is no longer valid.

func (*Conn) Key

func (c *Conn) 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 (*Conn) Off

func (c *Conn) Off(ch chan<- State, states ...StateEnum)

Off removes c from listening on the given connection state transitions.

If no states are given, c is removed for all of the connection's states. If c is nil, the method panics. If c was not registered or is already removed, the method is a nop.

func (*Conn) On

func (c *Conn) On(ch chan<- State, states ...StateEnum)

On relays request connection states to the given channel; on state transition connection will not block sending to c - the caller must ensure the incoming values are read at proper pace or the c is sufficiently buffered.

If no states are given, c is registered for all of them. If c is nil, the method panics. If c is already registered, its state set is expanded.

func (*Conn) Ping

func (c *Conn) Ping() (ping, pong time.Duration, err error)

Ping issues a ping request against configured endpoint and returns TTR times for ping request and pong response.

Ping returns non-nil error without any attempt of communication with Ably if the connection state is StateConnClosed or StateConnFailed.

func (*Conn) Reason

func (c *Conn) Reason() error

Reason gives last known error that caused connection transit to StateConnFailed state.

func (*Conn) Serial

func (c *Conn) Serial() int64

Serial gives serial number of a message received most recently. Last known serial number is used when recovering connection state.

func (*Conn) State

func (c *Conn) State() StateEnum

State returns current state of the connection.

type Error

type Error struct {
	Code       int    // internal error code
	StatusCode int    // HTTP status code
	Err        error  // underlying error responsible for the failure; may be nil
	Server     string // non-empty ID of the Ably server which the error was received from
}

Error describes error returned from Ably API. It always has non-zero error code. It may contain underlying error value which caused the failure condition.

func (*Error) Error

func (err *Error) Error() string

Error implements builtin error interface.

type HTTPPaginatedResponse added in v1.1.0

type HTTPPaginatedResponse struct {
	*PaginatedResult
	StatusCode   int         //spec HP4
	Success      bool        //spec HP5
	ErrorCode    int         //spec HP6
	ErrorMessage string      //spec HP7
	Headers      http.Header //spec HP8
}

HTTPPaginatedResponse represent a response from an http request.

func (*HTTPPaginatedResponse) Next added in v1.1.0

Next overrides PaginatedResult.Next spec HP2

type LogLevel added in v1.1.0

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

type Logger

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

Logger is an interface for ably loggers.

type LoggerOptions added in v1.1.0

type LoggerOptions struct {
	Logger Logger
	Level  LogLevel
}

LoggerOptions defines options for ably logging.

func (LoggerOptions) GetLogger added in v1.1.0

func (l LoggerOptions) GetLogger() Logger

GetLogger returns the custom logger if any. This will return the default logger if custom logger was not specified.

func (LoggerOptions) Is added in v1.1.0

func (l LoggerOptions) Is(level LogLevel) bool

func (LoggerOptions) Print added in v1.1.0

func (l LoggerOptions) Print(level LogLevel, v ...interface{})

func (LoggerOptions) Printf added in v1.1.0

func (l LoggerOptions) Printf(level LogLevel, format string, v ...interface{})

func (LoggerOptions) Sugar added in v1.1.5

func (l LoggerOptions) Sugar() *SugaredLogger

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 represents a single page coming back from the REST API. Any call to create a new page will generate a new instance.

func (*PaginatedResult) Items

func (p *PaginatedResult) Items() []interface{}

Items gives a slice of results of the current page.

func (*PaginatedResult) Messages

func (p *PaginatedResult) Messages() []*proto.Message

Messages gives a slice of messages for the current page. The method panics if the underlying paginated result is not a message.

func (*PaginatedResult) Next

func (p *PaginatedResult) Next() (*PaginatedResult, error)

Next returns the path to the next page as found in the response headers. The response headers from the REST API contains a relative link to the next result. (Link: <./path>; rel="next").

func (*PaginatedResult) PresenceMessages

func (p *PaginatedResult) PresenceMessages() []*proto.PresenceMessage

PresenceMessages gives a slice of presence messages for the current path. The method panics if the underlying paginated result is not a presence message.

func (*PaginatedResult) Stats

func (p *PaginatedResult) Stats() []*proto.Stats

Stats gives a slice of statistics for the current page. The method panics if the underlying paginated result is not statistics.

type QueryFunc

type QueryFunc func(url string) (*http.Response, error)

QueryFunc queries the given URL and gives non-nil HTTP response if no error occurred.

type RealtimeChannel

type RealtimeChannel struct {
	Name     string            // name used to create the channel
	Presence *RealtimePresence //
	// contains filtered or unexported fields
}

RealtimeChannel represents a single named message channel.

func (*RealtimeChannel) Attach

func (c *RealtimeChannel) Attach() (Result, error)

Attach initiates attach request, which is being processed on a separate goroutine.

If channel is already attached, this method is a nop. If sending attach message failed, the returned error value is non-nil. If sending attach message succeed, the returned Result value can be used to wait until ack from server is received.

func (*RealtimeChannel) Close

func (c *RealtimeChannel) Close() error

Closes initiates closing sequence for the channel; it waits until the operation is complete.

If connection is already closed, this method is a nop. If sending close message succeeds, it closes and unsubscribes all channels.

func (*RealtimeChannel) Detach

func (c *RealtimeChannel) Detach() (Result, error)

Detach initiates detach request, which is being processed on a separate goroutine.

If channel is already detached, this method is a nop. If sending detach message failed, the returned error value is non-nil. If sending detach message succeed, the returned Result value can be used to wait until ack from server is received.

func (*RealtimeChannel) History

func (c *RealtimeChannel) History(params *PaginateParams) (*PaginatedResult, error)

History gives the channel's message history according to the given parameters. The returned result can be inspected for the messages via the Messages() method.

func (*RealtimeChannel) Off

func (c *RealtimeChannel) Off(ch chan<- State, states ...StateEnum)

Off removes c from listening on the given channel state transitions.

If no states are given, c is removed for all of the connection's states. If c is nil, the method panics.

func (*RealtimeChannel) On

func (c *RealtimeChannel) On(ch chan<- State, states ...StateEnum)

On relays request channel states to c; on state transition connection will not block sending to c - the caller must ensure the incoming values are read at proper pace or the c is sufficiently buffered.

If no states are given, c is registered for all of them. If c is nil, the method panics. If c is already registered, its state set is expanded.

func (*RealtimeChannel) Publish

func (c *RealtimeChannel) Publish(name string, data interface{}) (Result, error)

Publish publishes a message on the channel, which is send on separate goroutine. Publish does not block.

This implicitly attaches the channel if it's not already attached.

func (*RealtimeChannel) PublishAll

func (c *RealtimeChannel) PublishAll(messages []*proto.Message) (Result, error)

PublishAll publishes all given messages on the channel at once. PublishAll does not block.

This implicitly attaches the channel if it's not already attached.

func (*RealtimeChannel) Reason

func (c *RealtimeChannel) Reason() error

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

func (*RealtimeChannel) State

func (c *RealtimeChannel) State() StateEnum

State gives current state of the channel.

func (*RealtimeChannel) Subscribe

func (c *RealtimeChannel) Subscribe(names ...string) (*Subscription, error)

Subscribe subscribes to a realtime channel, which makes any newly received messages relayed to the returned Subscription value.

If no names are given, returned Subscription will receive all messages. If ch is non-nil and it was already registered to receive messages with different names than the ones given, it will be added to receive also the new ones.

func (*RealtimeChannel) Unsubscribe

func (c *RealtimeChannel) Unsubscribe(sub *Subscription, names ...string)

Unsubscribe removes previous Subscription for the given message names.

Unsubscribe panics if the given sub was subscribed for presence messages and not for regular channel messages.

If sub was already unsubscribed, the method is a nop.

type RealtimeClient

type RealtimeClient struct {
	Auth       *Auth
	Channels   *Channels
	Connection *Conn
	// contains filtered or unexported fields
}

The RealtimeClient libraries establish and maintain a persistent connection to Ably enabling extremely low latency broadcasting of messages and presence state.

func NewRealtimeClient

func NewRealtimeClient(opts *ClientOptions) (*RealtimeClient, error)

NewRealtimeClient

func (*RealtimeClient) Close

func (c *RealtimeClient) Close() error

Close

func (*RealtimeClient) Stats

func (c *RealtimeClient) Stats(params *PaginateParams) (*PaginatedResult, error)

Stats gives the clients metrics according to the given parameters. The returned result can be inspected for the statistics via the Stats() method.

func (*RealtimeClient) Time

func (c *RealtimeClient) Time() (time.Time, error)

Time

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.

func (*RealtimePresence) Enter

func (pres *RealtimePresence) Enter(data string) (Result, error)

Enter announces presence of the current client with an enter message for the associated channel.

func (*RealtimePresence) EnterClient

func (pres *RealtimePresence) EnterClient(clientID string, data interface{}) (Result, error)

EnterClient announces presence of the given clientID altogether with an enter message for the associated channel.

func (*RealtimePresence) Get

func (pres *RealtimePresence) Get(wait bool) ([]*proto.PresenceMessage, error)

Get returns a list of current members on the channel.

If wait is true it blocks until undergoing sync operation completes. If wait is false or sync already completed, the function returns immediately.

func (*RealtimePresence) Leave

func (pres *RealtimePresence) Leave(data string) (Result, error)

Leave announces current client leave the channel altogether with a leave message if data is non-empty.

func (*RealtimePresence) LeaveClient

func (pres *RealtimePresence) LeaveClient(clientID string, data interface{}) (Result, error)

LeaveClient announces the given clientID leave the associated channel altogether with a leave message if data is non-empty.

func (*RealtimePresence) Subscribe

func (pres *RealtimePresence) Subscribe(states ...proto.PresenceState) (*Subscription, error)

Subscribe subscribes to presence events on the associated channel.

If the channel is not attached, Subscribe implicitly attaches it. If no presence states are given, Subscribe subscribes to all of them.

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) Unsubscribe

func (pres *RealtimePresence) Unsubscribe(sub *Subscription, states ...proto.PresenceState)

Unsubscribe removes previous Subscription for the given presence states.

If sub was already unsubscribed, the method is a nop.

func (*RealtimePresence) Update

func (pres *RealtimePresence) Update(data string) (Result, error)

Update announces an updated presence message for the current client.

If the current client is not present on the channel, Update will behave as Enter method.

func (*RealtimePresence) UpdateClient

func (pres *RealtimePresence) UpdateClient(clientID string, data interface{}) (Result, 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.

type Request added in v1.1.0

type Request struct {
	Method string
	Path   string
	In     interface{} // value to be encoded and sent with request body
	Out    interface{} // value to store decoded response body

	// NoAuth when set to true, makes the request not being authenticated.
	NoAuth bool

	// when true token is not refreshed when request fails with token expired response
	NoRenew bool
	// contains filtered or unexported fields
}

Request this contains fields necessary to compose http request that will be sent ably endpoints.

type RestChannel

type RestChannel struct {
	Name     string
	Presence *RestPresence
	// contains filtered or unexported fields
}

func (*RestChannel) History

func (c *RestChannel) History(params *PaginateParams) (*PaginatedResult, error)

History gives the channel's message history according to the given parameters. The returned result can be inspected for the messages via the Messages() method.

func (*RestChannel) Publish

func (c *RestChannel) Publish(name string, data interface{}) error

func (*RestChannel) PublishAll

func (c *RestChannel) PublishAll(messages []*proto.Message) error

PublishAll sends multiple messages in the same http call. This is the more efficient way of transmitting a batch of messages using the Rest API.

type RestChannels added in v1.1.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.1.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.1.0

func (c *RestChannels) Get(name string, opts *proto.ChannelOptions) *RestChannel

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

RSN3a: 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) Len added in v1.1.0

func (c *RestChannels) Len() (size int)

Len returns the number of channels stored.

func (*RestChannels) Range added in v1.1.0

func (c *RestChannels) Range(fn func(name string, channel *RestChannel) bool)

Range iterates over the channels calling fn on every iteration. If fn returns false then the iteration is stopped.

This uses locking to take a snapshot of the underlying RestChannel map before iteration to avoid any deadlock, meaning any modification (like creating new RestChannel, or removing one) that occurs during iteration will not have any effect to the values passed to the fn.

func (*RestChannels) Release added in v1.1.0

func (c *RestChannels) Release(ch *RestChannel)

Release deletes the channel from the cache.

type RestClient

type RestClient struct {
	Auth     *Auth
	Channels *RestChannels
	// contains filtered or unexported fields
}

func NewRestClient

func NewRestClient(opts *ClientOptions) (*RestClient, error)

func (*RestClient) NewHTTPRequest added in v1.1.0

func (c *RestClient) NewHTTPRequest(r *Request) (*http.Request, error)

NewHTTPRequest creates a new http.Request that can be sent to ably endpoints. This makes sure necessary headers are set.

func (*RestClient) Request added in v1.1.0

func (c *RestClient) Request(method string, path string, params *PaginateParams, body interface{}, headers http.Header) (*HTTPPaginatedResponse, error)

Request sends http request to ably. spec RSC19

func (*RestClient) Stats

func (c *RestClient) Stats(params *PaginateParams) (*PaginatedResult, error)

Stats gives the channel's metrics according to the given parameters. The returned result can be inspected for the statistics via the Stats() method.

func (*RestClient) Time

func (c *RestClient) Time() (time.Time, error)

type RestPresence

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

func (*RestPresence) Get

func (p *RestPresence) Get(params *PaginateParams) (*PaginatedResult, error)

Get gives the channel's presence messages according to the given parameters. The returned result can be inspected for the presence messages via the PresenceMessages() method.

func (*RestPresence) History

func (p *RestPresence) History(params *PaginateParams) (*PaginatedResult, error)

History gives the channel's presence messages history according to the given parameters. The returned result can be inspected for the presence messages via the PresenceMessages() method.

type Result

type Result interface {
	// Wait blocks until asynchronous operation is completed. Upon its completion,
	// the method returns nil error if it was successful and non-nil error otherwise.
	// It's allowed to call Wait multiple times.
	Wait() error
}

Result awaits completion of asynchronous operation.

type ScopeParams

type ScopeParams struct {
	Start int64
	End   int64
	Unit  string
}

This needs to use a timestamp in millisecond Use the previous function to generate them from a time.Time struct.

func (*ScopeParams) EncodeValues

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

type State

type State struct {
	Channel string    // channel name or empty if Type is StateConn
	Err     error     // eventual error value associated with transition
	State   StateEnum // state which connection or channel has transitioned to
	Type    StateType // whether transition happened on connection or channel
}

State describes a single state transition of either realtime connection or channel that occurred due to some external condition (dropped connection, retried etc.).

Each realtime connection and channel maintains its state to ensure high availability and resilience, which is inherently asynchronous. In order to listen to transition between states for both realtime connection and realtime channel user may provide a channel, which will get notified with single State value for each transition than takes place.

type StateEnum

type StateEnum int

StateEnum is an enumeration type for connection and channel states.

const (
	StateConnInitialized StateEnum = 1 << iota
	StateConnConnecting
	StateConnConnected
	StateConnDisconnected
	StateConnSuspended
	StateConnClosing
	StateConnClosed
	StateConnFailed
)

StateConn describes states of realtime connection.

const (
	StateChanInitialized StateEnum = 1 << (iota + 8)
	StateChanAttaching
	StateChanAttached
	StateChanDetaching
	StateChanDetached
	StateChanClosing
	StateChanClosed
	StateChanFailed
)

StateChan describes states of realtime channel.

func (StateEnum) String

func (sc StateEnum) String() string

String implements the fmt.Stringer interface.

type StateType

type StateType int

StateType specifies which group of states is relevant in given context; either:

  • StateConn* group describing Conn states
  • StateChan* group describing RealtimeChannel states
const (
	StateConn StateType = 1 + iota
	StateChan
)

func (StateType) Contains

func (st StateType) Contains(state StateEnum) bool

Contains returns true when the state belongs to the given type.

func (StateType) String

func (st StateType) String() string

Strings implements the fmt.Stringer interface.

type StdLogger added in v1.1.0

type StdLogger struct {
	*log.Logger
}

StdLogger wraps log.Logger to satisfy the Logger interface.

func (*StdLogger) Print added in v1.1.0

func (s *StdLogger) Print(level LogLevel, v ...interface{})

func (*StdLogger) Printf added in v1.1.0

func (s *StdLogger) Printf(level LogLevel, format string, v ...interface{})

type Subscription

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

Subscription queues messages received from a realtime channel.

func (*Subscription) Close

func (sub *Subscription) Close() error

Close unsubscribes from the realtime channel the sub was previously subscribed. It closes the chan returned by C method.

func (*Subscription) Len

func (sub *Subscription) Len() int

Len gives a number of messages currently queued.

func (*Subscription) MessageChannel

func (sub *Subscription) MessageChannel() <-chan *proto.Message

MessageChannel gives a channel on which the messages are delivered. It panics when sub was not subscribed to receive channel's messages.

func (*Subscription) PresenceChannel

func (sub *Subscription) PresenceChannel() <-chan *proto.PresenceMessage

PresenceChannel gives a channel on which the presence messages are delivered. It panics when sub was not subscribed to receive channel's presence messages.

type SugaredLogger added in v1.1.5

type SugaredLogger struct {
	LoggerOptions
}

func (SugaredLogger) Debug added in v1.1.5

func (s SugaredLogger) Debug(v ...interface{})

func (SugaredLogger) Debugf added in v1.1.5

func (s SugaredLogger) Debugf(fmt string, v ...interface{})

func (SugaredLogger) Error added in v1.1.5

func (s SugaredLogger) Error(v ...interface{})

func (SugaredLogger) Errorf added in v1.1.5

func (s SugaredLogger) Errorf(fmt string, v ...interface{})

func (SugaredLogger) Info added in v1.1.5

func (s SugaredLogger) Info(v ...interface{})

func (SugaredLogger) Infof added in v1.1.5

func (s SugaredLogger) Infof(fmt string, v ...interface{})

func (SugaredLogger) Verbose added in v1.1.5

func (s SugaredLogger) Verbose(v ...interface{})

func (SugaredLogger) Verbosef added in v1.1.5

func (s SugaredLogger) Verbosef(fmt string, v ...interface{})

func (SugaredLogger) Warn added in v1.1.5

func (s SugaredLogger) Warn(v ...interface{})

func (SugaredLogger) Warnf added in v1.1.5

func (s SugaredLogger) Warnf(fmt string, v ...interface{})

type TokenDetails

type TokenDetails struct {
	// Token
	Token string `json:"token,omitempty" codec:"token,omitempty"`

	// KeyName
	KeyName string `json:"keyName,omitempty" codec:"keyName,omitempty"`

	// Expires
	Expires int64 `json:"expires,omitempty" codec:"expires,omitempty"`

	// ClientID
	ClientID string `json:"clientId,omitempty" codec:"clientId,omitempty"`

	// Issued
	Issued int64 `json:"issued,omitempty" codec:"issued,omitempty"`

	// RawCapability
	RawCapability string `json:"capability,omitempty" codec:"capability,omitempty"`
}

TokenDetails

func (*TokenDetails) Capability

func (tok *TokenDetails) Capability() Capability

Capability

func (*TokenDetails) ExpireTime

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

func (*TokenDetails) Expired

func (tok *TokenDetails) Expired() bool

Expired

func (*TokenDetails) IssueTime

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

type TokenParams

type TokenParams struct {
	// TTL is a requested time to live for the token. 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.
	TTL int64 `json:"ttl,omitempty" codec:"ttl,omitempty"`

	// RawCapability represents encoded access rights of the token.
	RawCapability string `json:"capability,omitempty" codec:"capability,omitempty"`

	// ClientID represents a client, whom the token is generated for.
	ClientID string `json:"clientId,omitempty" codec:"clientId,omitempty"`

	// Timestamp of the token request. It's used, in conjunction with the nonce,
	// are used to prevent token requests from being replayed.
	Timestamp int64 `json:"timestamp,omitempty" codec:"timestamp,omitempty"`
}

TokenParams

func (*TokenParams) Capability

func (params *TokenParams) Capability() Capability

Capability

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 string `json:"keyName,omitempty" codec:"keyName,omitempty"`
	Nonce   string `json:"nonce,omitempty" codec:"nonce,omitempty"` // should be at least 16 characters long
	Mac     string `json:"mac,omitempty" codec:"mac,omitempty"`     // message authentication code for the request
}

TokenRequest

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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