ably

package
v0.8.1 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2018 License: Apache-2.0 Imports: 29 Imported by: 31

Documentation

Index

Constants

View Source
const (
	// generic error codes
	ErrCodeNoError = 10000

	// error codes for HTTP 400
	ErrCodeBadRequest                   = 40000
	ErrCodeInvalidRequestBody           = 40001
	ErrCodeInvalidParameterName         = 40002
	ErrCodeInvalidParameterValue        = 40003
	ErrCodeInvalidHeader                = 40004
	ErrCodeInvalidCredential            = 40005
	ErrCodeInvalidConnectionID          = 40006
	ErrCodeInvalidMessageID             = 40007
	ErrCodeInvalidContentLength         = 40008
	ErrCodeMaximumMessageLengthExceeded = 40009
	ErrCodeInvalidChannelName           = 40010

	// error codes for HTTP 401
	ErrCodeUnauthorized                                = 40100
	ErrCodeInvalidCredentials                          = 40101
	ErrCodeIncompatibleCredentials                     = 40102
	ErrCodeInvalidUseOfBasicAuthOverNonTLSTransport    = 40103
	ErrCodeAccountDisabled                             = 40110
	ErrCodeAccountBlockedConnectionLimitsExceeded      = 40111
	ErrCodeAccountBlockedMessageLimitsExceeded         = 40112
	ErrCodeAccountBlocked                              = 40113
	ErrCodeApplicationDisabled                         = 40120
	ErrCodeKeyDisabled                                 = 40130
	ErrCodeKeyRevoked                                  = 40131
	ErrCodeKeyExpired                                  = 40132
	ErrCodeTokenExpired                                = 40140
	ErrCodeConnectionBlockedLimitsExceeded             = 40150
	ErrCodeOperationNotPermittedWithProvidedCapability = 40160
	ErrCodeClientTokenCallback                         = 40170

	// error codes for HTTP 403
	ErrCodeForbidden                         = 40300
	ErrCodeAccountDoesNotPermitTlsConnection = 40310
	ErrCodeOperationRequiresTlsConnection    = 40311
	ErrCodeApplicationRequiresAuthentication = 40320

	// error codes for HTTP 404
	ErrCodeNotFound = 40400

	// error codes for HTTP 405
	ErrCodeMethodNotAllowed = 40500

	// error codes for HTTP 500
	ErrCodeInternal           = 50000
	ErrCodeInternalChannel    = 50001
	ErrCodeInternalConnection = 50002
	ErrCodeTimeout            = 50003

	// error codes for webhook failures
	ErrCodeWebhookOperationFailed                                       = 70000
	ErrCodeWebhookOperationFailedPostOperationFailed                    = 70001
	ErrCodeWebhookOperationFailedPostOperationReturnedUnexpectedErrCode = 70002
	ErrCodeWebhookChannelRecoveryMessagesExpired                        = 70003
	ErrCodeWebhookChannelRecoveryMessageLimitExceeded                   = 70004
	ErrCodeWebhookChannelRecoveryHistoryIncomplete                      = 70005

	// error codes for connection failures
	ErrCodeConnectionFailed                                       = 80000
	ErrCodeConnectionFailedNoCompatibleTransport                  = 80001
	ErrCodeConnectionSuspended                                    = 80002
	ErrCodeDisconnected                                           = 80003
	ErrCodeAlreadyConnected                                       = 80004
	ErrCodeInvalidConnectionIDRemoteNotFound                      = 80005
	ErrCodeConnectionRecoveryMessagesExpired                      = 80006
	ErrCodeConnectionRecoveryMessageLimitExceeded                 = 80007
	ErrCodeConnectionRecoveryConnectionExpired                    = 80008
	ErrCodeConnectionNotEstablishedNoTransportHandle              = 80009
	ErrCodeInvalidOperationInvalidTransportHandle                 = 80010
	ErrCodeConnectionRecoveryIncompatibleAuthParams               = 80011
	ErrCodeConnectionRecoveryInvalidOrUnspecifiedConnectionSerial = 80012
	ErrCodeProtocol                                               = 80013
	ErrCodeConnectionTimedOut                                     = 80014
	ErrCodeIncompatibleConnectionParameters                       = 80015
	ErrCodeOperationOnSupersededTransport                         = 80016

	// error codes for channel failures
	ErrCodeChannelOperationFailed                           = 90000
	ErrCodeChannelOperationFailedInvalidChannelState        = 90001
	ErrCodeChannelOperationFailedEpochExpiredOrNeverExisted = 90002
	ErrCodeChannelRecoveryMessagesExpired                   = 90003
	ErrCodeChannelRecoveryMessageLimitExceeded              = 90004
	ErrCodeChannelRecoveryNoMatchingEpoch                   = 90005
	ErrCodeChannelRecoveryUnboundedRequest                  = 90006
	ErrCodeUnableToEnterPresenceChannelNoClientID           = 91000
	ErrCodeUnableToEnterPresenceChannelInvalidChannelState  = 91001
	ErrCodeUnableToLeavePresenceChannelThatIsNotEntered     = 91002
)
View Source
const (
	LogNone = iota
	LogError
	LogWarning
	LogInfo
	LogVerbose
	LogDebug
)

Variables

This section is empty.

Functions

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

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 instread of using local time.
	UseQueryTime bool

	// 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
	RealtimeHost    string // optional; overwrite endpoint hostname for Realtime client
	Environment     string // optional; prefixes both hostname with the environment string
	ClientID        string // optional; required for managing realtime presence of the current client
	Recover         string // optional; used to recover client state
	Logger          Logger // optional; overwrite logging defaults
	TransportParams map[string]string

	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

	TimeoutConnect    time.Duration // time period after which connect request is failed
	TimeoutDisconnect time.Duration // time period after which disconnect request is failed
	TimeoutSuspended  time.Duration // time period after which no more reconnection attempts are performed

	// 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
}

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 listetning 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 alreadt 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 attemp 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 Logger

type Logger struct {
	Logger *log.Logger
	Level  int
}

func (Logger) Is

func (l Logger) Is(level int) bool

func (Logger) Print

func (l Logger) Print(level int, v ...interface{})

func (Logger) Printf

func (l Logger) Printf(level int, format string, v ...interface{})

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 initiaties 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 string) (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 prarticular 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, data string) (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, data string) (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, data string) (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 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 string) 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 RestClient

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

func NewRestClient

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

func (*RestClient) Channel

func (c *RestClient) Channel(name string) *RestChannel

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 occured 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 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 TokenDetails

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

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

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

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

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

	// RawCapability
	RawCapability string `json:"capability,omitempty" msgpack:"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" msgpack:"ttl,omitempty"`

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

	// ClientID represents a client, whom the token is generated for.
	ClientID string `json:"clientId,omitempty" msgpack:"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" msgpack:"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 `msgpack:",inline"`

	KeyName string `json:"keyName,omitempty" msgpack:"keyName,omitempty"`
	Nonce   string `json:"nonce,omitempty" msgpack:"nonce,omitempty"` // should be at least 16 characters long
	Mac     string `json:"mac,omitempty" msgpack:"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