libcentrifugo

package
v1.4.5 Latest Latest
Warning

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

Go to latest
Published: Apr 21, 2016 License: MIT Imports: 30 Imported by: 0

Documentation

Overview

Package libcentrifugo is a real-time core for Centrifugo server.

Index

Constants

View Source
const (
	// AuthTokenKey is a key for admin authorization token.
	AuthTokenKey = "token"
	// AuthTokenValue is a value for secure admin authorization token.
	AuthTokenValue = "authorized"
)
View Source
const (
	// RedisSubscribeChannelSize is the size for the internal buffered channels RedisEngine
	// uses to synchronize subscribe/unsubscribe. It allows for effective batching during bulk re-subscriptions,
	// and allows large volume of incoming subscriptions to not block when PubSub connection is reconnecting.
	// Two channels of this size will be allocated, one for Subscribe and one for Unsubscribe
	RedisSubscribeChannelSize = 4096
	// Maximum number of channels to include in a single subscribe call. Redis documentation doesn't specify a
	// maximum allowed but we think it probably makes sense to keep a sane limit given how many subscriptions a single
	// Centrifugo instance might be handling
	RedisSubscribeBatchLimit = 2048
	// RedisPublishChannelSize is the size for the internal buffered channel RedisEngine
	// uses to collect publish requests.
	RedisPublishChannelSize = 1024
	// RedisPublishBatchLimit is a maximum limit of publish requests one batched publish
	// operation can contain.
	RedisPublishBatchLimit = 2048
)
View Source
const (
	AdminWebsocketReadBufferSize  = 1024
	AdminWebsocketWriteBufferSize = 1024
)
View Source
const (
	// CloseStatus is status code set when closing client connections.
	CloseStatus = 3000
)

Variables

View Source
var (
	// ErrInvalidMessage means that you sent invalid message to Centrifugo.
	ErrInvalidMessage = errors.New("invalid message")
	// ErrInvalidToken means that client sent invalid token.
	ErrInvalidToken = errors.New("invalid token")
	// ErrUnauthorized means unauthorized access.
	ErrUnauthorized = errors.New("unauthorized")
	// ErrMethodNotFound means that method sent in command does not exist.
	ErrMethodNotFound = errors.New("method not found")
	// ErrPermissionDenied means that access to resource not allowed.
	ErrPermissionDenied = errors.New("permission denied")
	// ErrNamespaceNotFound means that namespace in channel name does not exist.
	ErrNamespaceNotFound = errors.New("namespace not found")
	// ErrInternalServerError means server error, if returned this is a signal that
	// something went wrong with Centrifugo itself.
	ErrInternalServerError = errors.New("internal server error")
	// ErrAlreadySubscribed returned when client wants to subscribe on channel
	// it already subscribed to.
	ErrAlreadySubscribed = errors.New("already subscribed")
	// ErrLimitExceeded says that some sort of limit exceeded, server logs should give
	// more detailed information.
	ErrLimitExceeded = errors.New("limit exceeded")
	// ErrNotAvailable means that resource is not enabled.
	ErrNotAvailable = errors.New("not available")
	// ErrSendTimeout means that timeout occurred when sending message into connection.
	ErrSendTimeout = errors.New("send timeout")
	// ErrClientClosed means that client connection already closed.
	ErrClientClosed = errors.New("client is closed")
)
View Source
var DefaultConfig = &Config{
	Version:                     "-",
	Name:                        defaultName,
	Debug:                       false,
	AdminPassword:               "",
	AdminSecret:                 "",
	ChannelPrefix:               defaultChannelPrefix,
	AdminChannel:                ChannelID(defaultChannelPrefix + ".admin"),
	ControlChannel:              ChannelID(defaultChannelPrefix + ".control"),
	MaxChannelLength:            255,
	PingInterval:                25 * time.Second,
	NodePingInterval:            defaultNodePingInterval * time.Second,
	NodeInfoCleanInterval:       defaultNodePingInterval * 3 * time.Second,
	NodeInfoMaxDelay:            defaultNodePingInterval*2*time.Second + 1*time.Second,
	NodeMetricsInterval:         60 * time.Second,
	PresencePingInterval:        25 * time.Second,
	PresenceExpireInterval:      60 * time.Second,
	MessageSendTimeout:          0,
	PrivateChannelPrefix:        "$",
	NamespaceChannelBoundary:    ":",
	ClientChannelBoundary:       "&",
	UserChannelBoundary:         "#",
	UserChannelSeparator:        ",",
	ExpiredConnectionCloseDelay: 25 * time.Second,
	StaleConnectionCloseDelay:   25 * time.Second,
	ClientRequestMaxSize:        65536,
	ClientQueueMaxSize:          10485760,
	ClientQueueInitialCapacity:  2,
	ClientChannelLimit:          100,
	Insecure:                    false,
}

DefaultConfig is Config initialized with default values for all fields.

View Source
var DefaultMuxOptions = MuxOptions{
	HandlerFlags:  HandlerRawWS | HandlerSockJS | HandlerAPI | HandlerAdmin,
	SockjsOptions: sockjs.DefaultOptions,
}

DefaultMuxOptions contain default SockJS options.

Functions

func DefaultMux added in v0.2.0

func DefaultMux(app *Application, muxOpts MuxOptions) *http.ServeMux

DefaultMux returns a mux including set of default handlers for Centrifugo server.

func NewSockJSHandler added in v0.2.0

func NewSockJSHandler(app *Application, sockjsPrefix string, sockjsOpts sockjs.Options) http.Handler

NewSockJSHandler returns SockJS handler bind to sockjsPrefix url prefix. SockJS handler has several handlers inside responsible for various tasks according to SockJS protocol.

Types

type Application added in v0.2.0

type Application struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

Application is a heart of Centrifugo – it internally manages client and admin hubs, maintains information about other Centrifugo nodes, keeps references to config, engine, metrics etc.

func NewApplication added in v0.2.0

func NewApplication(config *Config) (*Application, error)

NewApplication returns new Application instance, the only required argument is config, structure and engine must be set via corresponding methods.

func (*Application) APIHandler added in v0.2.3

func (app *Application) APIHandler(w http.ResponseWriter, r *http.Request)

APIHandler is responsible for receiving API commands over HTTP.

func (*Application) AdminWebsocketHandler added in v0.2.0

func (app *Application) AdminWebsocketHandler(w http.ResponseWriter, r *http.Request)

AdminWebsocketHandler handles admin websocket connections.

func (*Application) AuthHandler added in v0.2.0

func (app *Application) AuthHandler(w http.ResponseWriter, r *http.Request)

AuthHandler allows to get admin web interface token.

func (*Application) Disconnect added in v0.2.0

func (app *Application) Disconnect(user UserID) error

Disconnect allows to close all user connections to Centrifugo. Note that user still can try to reconnect to the server after being disconnected.

func (*Application) History added in v0.2.0

func (app *Application) History(ch Channel) ([]Message, error)

History returns a slice of last messages published into project channel.

func (*Application) Logged added in v0.2.0

func (app *Application) Logged(h http.Handler) http.Handler

Logged middleware logs request.

func (*Application) Presence added in v0.2.0

func (app *Application) Presence(ch Channel) (map[ConnID]ClientInfo, error)

Presence returns a map of active clients in project channel.

func (*Application) Publish added in v0.2.0

func (app *Application) Publish(ch Channel, data []byte, client ConnID, info *ClientInfo) error

Publish sends a message to all clients subscribed on channel with provided data, client and ClientInfo.

func (*Application) RawWebsocketHandler added in v0.2.0

func (app *Application) RawWebsocketHandler(w http.ResponseWriter, r *http.Request)

RawWebsocketHandler called when new client connection comes to raw Websocket endpoint.

func (*Application) Run added in v0.2.0

func (app *Application) Run() error

Run performs all startup actions. At moment must be called once on start after engine and structure set.

func (*Application) SetConfig added in v0.2.0

func (app *Application) SetConfig(c *Config)

SetConfig binds config to application.

func (*Application) SetEngine added in v0.2.0

func (app *Application) SetEngine(e Engine)

SetEngine binds engine to application.

func (*Application) SetMediator added in v0.2.0

func (app *Application) SetMediator(m Mediator)

SetMediator binds mediator to application.

func (*Application) Shutdown added in v0.2.0

func (app *Application) Shutdown()

Shutdown sets shutdown flag and does various connection clean ups (at moment only unsubscribes all clients from all channels and disconnects them).

func (*Application) Unsubscribe added in v0.2.0

func (app *Application) Unsubscribe(user UserID, ch Channel) error

Unsubscribe unsubscribes user from channel, if channel is equal to empty string then user will be unsubscribed from all channels.

func (*Application) WrapShutdown added in v0.2.0

func (app *Application) WrapShutdown(h http.Handler) http.Handler

WrapShutdown will return an http Handler. If Application in shutdown it will return http.StatusServiceUnavailable.

type Channel added in v0.1.1

type Channel string

Channel is a string channel name.

type ChannelID added in v0.1.1

type ChannelID string

ChannelID is unique channel identificator in Centrifugo.

type ChannelOptions

type ChannelOptions struct {
	// Watch determines if message published into channel will be also sent into admin channel.
	// Note that this option must be used carefully in channels with high rate of new messages
	// as admin client can not process all of those messages. Use this option for testing or for
	// channels with reasonable message rate.
	Watch bool `json:"watch"`

	// Publish determines if client can publish messages into channel directly. This allows to use
	// Centrifugo without backend. All messages go through Centrifugo and delivered to clients. But
	// in this case you lose everything your backend code could give - validation, persistence etc.
	// This option most useful for demos, testing real-time ideas.
	Publish bool `json:"publish"`

	// Anonymous determines is anonymous access (with empty user ID) allowed or not. In most
	// situations your application works with authorized users so every user has its own unique
	// id. But if you provide real-time features for public access you may need anauthorized
	// access to channels. Turn on this option and use empty string as user ID.
	Anonymous bool `json:"anonymous"`

	// Presence turns on(off) presence information for channels. Presense is a structure with
	// clients currently subscribed on channel.
	Presence bool `json:"presence"`

	// JoinLeave turns on(off) join/leave messages for channels. When client subscribes on channel
	// join message sent to all clients in this channel. When client leaves channel (unsubscribes)
	// leave message sent.
	JoinLeave bool `mapstructure:"join_leave" json:"join_leave"`

	// HistorySize determines max amount of history messages for channel, 0 means no history for channel.
	// Centrifugo history has auxiliary role – it can not replace your backend persistent storage.
	HistorySize int `mapstructure:"history_size" json:"history_size"`

	// HistoryLifetime determines time in seconds until expiration for history messages. As Centrifugo
	// keeps history in memory (in process memory or in Redis process memory) it's important to remove
	// old messages to prevent infinite memory grows.
	HistoryLifetime int `mapstructure:"history_lifetime" json:"history_lifetime"`

	// Recover enables recover mechanism for channels. This means that Centrifugo will
	// try to recover missed messages for resubscribing client. This option uses messages
	// from history and must be used with reasonable HistorySize and HistoryLifetime
	// configuration.
	Recover bool `json:"recover"`

	// HistoryDropInactive enables an optimization where history is only saved for channels that have at
	// least one active subscriber. This can give a huge memory saving, with only minor edgecases that are
	// different from without it as noted on https://github.com/centrifugal/centrifugo/issues/50.
	HistoryDropInactive bool `mapstructure:"history_drop_inactive" json:"history_drop_inactive"`
}

ChannelOptions represent channel specific configuration for namespace or project in a whole

type ChannelsBody added in v0.3.0

type ChannelsBody struct {
	Data []Channel `json:"data"`
}

ChannelsBody represents body of response in case of successful channels command.

type ClientInfo added in v0.1.1

type ClientInfo struct {
	User        UserID           `json:"user"`
	Client      ConnID           `json:"client"`
	DefaultInfo *json.RawMessage `json:"default_info,omitempty"`
	ChannelInfo *json.RawMessage `json:"channel_info,omitempty"`
}

ClientInfo contains information about client to use in message meta information, presence information, join/leave events etc.

type Config added in v0.2.0

type Config struct {
	// Version is a version of node as string, in most cases this will
	// be Centrifugo server version.
	Version string `json:"version"`

	// Name of this node - must be unique, used as human readable and
	// meaningful node identificator.
	Name string `json:"name"`

	// Debug turns on application debug mode.
	Debug bool `json:"debug"`

	// Admin enables admin socket.
	Admin bool
	// AdminPassword is an admin password.
	AdminPassword string `json:"-"`
	// AdminSecret is a secret to generate auth token for admin socket connection.
	AdminSecret string `json:"-"`
	// Web enables admin web interface.
	Web bool `json:"web"`

	// ChannelPrefix is a string prefix before each channel.
	ChannelPrefix string `json:"channel_prefix"`
	// AdminChannel is channel name for admin messages.
	AdminChannel ChannelID `json:"admin_channel"`
	// ControlChannel is a channel name for internal control messages between nodes.
	ControlChannel ChannelID `json:"control_channel"`
	// MaxChannelLength is a maximum length of channel name.
	MaxChannelLength int `json:"max_channel_length"`

	// PingInterval sets interval server will send ping messages to clients.
	PingInterval time.Duration `json:"ping_interval"`

	// NodePingInterval is an interval how often node must send ping
	// control message.
	NodePingInterval time.Duration `json:"node_ping_interval"`
	// NodeInfoCleanInterval is an interval in seconds, how often node must clean
	// information about other running nodes.
	NodeInfoCleanInterval time.Duration `json:"node_info_clean_interval"`
	// NodeInfoMaxDelay is an interval in seconds – how many seconds node info
	// considered actual.
	NodeInfoMaxDelay time.Duration `json:"node_info_max_delay"`
	// NodeMetricsInterval detects interval node will use to aggregate metrics.
	NodeMetricsInterval time.Duration `json:"node_metrics_interval"`

	// PresencePingInterval is an interval how often connected clients
	// must update presence info.
	PresencePingInterval time.Duration `json:"presence_ping_interval"`
	// PresenceExpireInterval is an interval how long to consider
	// presence info valid after receiving presence ping.
	PresenceExpireInterval time.Duration `json:"presence_expire_interval"`

	// ExpiredConnectionCloseDelay is an interval given to client to
	// refresh its connection in the end of connection lifetime.
	ExpiredConnectionCloseDelay time.Duration `json:"expired_connection_close_delay"`

	// StaleConnectionCloseDelay is an interval in seconds after which
	// connection will be closed if still not authenticated.
	StaleConnectionCloseDelay time.Duration `json:"stale_connection_close_delay"`

	// MessageSendTimeout is an interval how long time the node
	// may take to send a message to a client before disconnecting the client.
	MessageSendTimeout time.Duration `json:"message_send_timeout"`

	// ClientRequestMaxSize sets maximum size in bytes of allowed client request.
	ClientRequestMaxSize int `json:"client_request_max_size"`
	// ClientQueueMaxSize is a maximum size of client's message queue in bytes.
	// After this queue size exceeded Centrifugo closes client's connection.
	ClientQueueMaxSize int `json:"client_queue_max_size"`
	// ClientQueueInitialCapacity sets initial amount of slots in client message
	// queue. When these slots are full client queue is automatically resized to
	// a bigger size. This option can reduce amount of allocations when message
	// rate is very high and client queue resizes frequently. Note that memory
	// consumption per client connection grows with this option.
	ClientQueueInitialCapacity int `json:"client_queue_initial_capacity"`

	// ClientChannelLimit sets upper limit of channels each client can subscribe to.
	ClientChannelLimit int `json:"client_channel_limit"`

	// PrivateChannelPrefix is a prefix in channel name which indicates that
	// channel is private.
	PrivateChannelPrefix string `json:"private_channel_prefix"`
	// NamespaceChannelBoundary is a string separator which must be put after
	// namespace part in channel name.
	NamespaceChannelBoundary string `json:"namespace_channel_boundary"`
	// UserChannelBoundary is a string separator which must be set before allowed
	// users part in channel name.
	UserChannelBoundary string `json:"user_channel_boundary"`
	// UserChannelSeparator separates allowed users in user part of channel name.
	UserChannelSeparator string `json:"user_channel_separator"`
	// ClientChannelBoundary is a string separator which must be set before client
	// connection ID in channel name so only client with this ID can subscribe on
	// that channel.
	ClientChannelBoundary string `json:"client_channel_separator"`

	// Insecure turns on insecure mode - when it's turned on then no authentication
	// required at all when connecting to Centrifugo, anonymous access and publish
	// allowed for all channels, no connection check performed. This can be suitable
	// for demonstration or personal usage.
	Insecure bool `json:"insecure"`
	// InsecureAPI turns on insecure mode for HTTP API calls. This means that no
	// API sign required when sending commands. This can be useful if you don't want
	// to sign every request - for example if you closed API endpoint with firewall
	// or you want to play with API commands from command line using CURL.
	InsecureAPI bool `json:"insecure_api"`
	// InsecureAdmin turns on insecure mode for admin endpoints - no auth required to
	// connect to admin socket and web interface. Protect admin resources with firewall
	// rules in production when enabling this option.
	InsecureAdmin bool `json:"insecure_admin"`

	// Secret is a secret key, used to sign API requests and client connection tokens.
	Secret string `json:"secret"`

	// ConnLifetime determines time until connection expire, 0 means no connection expire at all.
	ConnLifetime int64 `json:"connection_lifetime"`

	// ChannelOptions embedded to config.
	ChannelOptions `json:"channel_options"`

	// Namespaces - list of namespaces for custom channel options.
	Namespaces []Namespace `json:"namespaces"`
}

Config contains Application configuration options.

func (*Config) Validate added in v1.0.0

func (c *Config) Validate() error

Validate validates config and returns error if problems found

type ConnID added in v0.1.1

type ConnID string

ConnID is a unique connection ID.

type ConnectBody added in v1.0.0

type ConnectBody struct {
	Version string `json:"version"`
	Client  ConnID `json:"client"`
	Expires bool   `json:"expires"`
	Expired bool   `json:"expired"`
	TTL     int64  `json:"ttl"`
}

ConnectBody represents body of response in case of successful connect command.

type ConnectClientCommand added in v1.0.0

type ConnectClientCommand struct {
	User      UserID `json:"user"`
	Timestamp string `json:"timestamp"`
	Info      string `json:"info"`
	Token     string `json:"token"`
}

ConnectClientCommand is a command to authorize connection - it contains user ID in web application, additional connection information as JSON string, timestamp with unix seconds on moment when connect parameters generated and HMAC token to prove correctness of all those parameters.

type DisconnectBody added in v1.3.0

type DisconnectBody struct {
	Reason    string `json:"reason"`
	Reconnect bool   `json:"reconnect"`
}

DisconnectBody represents body of disconnect response when we want to tell client to disconnect. Optionally we can give client an advice to continue reconnecting after receiving this message.

type Engine added in v0.2.0

type Engine interface {
	// contains filtered or unexported methods
}

Engine is an interface with all methods that can be used by client or application to publish message, handle subscriptions, save or retrieve presence and history data.

type HandlerFlag added in v1.3.0

type HandlerFlag int

HandlerFlag is a bit mask of handlers that must be enabled in mux.

const (
	// HandlerRawWS enables Raw Websocket handler.
	HandlerRawWS HandlerFlag = 1 << iota
	// HandlerSockJS enables SockJS handler.
	HandlerSockJS
	// HandlerAPI enables API handler.
	HandlerAPI
	// HandlerAdmin enables admin handlers - admin websocket, web interface endpoints.
	HandlerAdmin
	// HandlerDebug enables debug handlers.
	HandlerDebug
)

func (HandlerFlag) String added in v1.3.0

func (flags HandlerFlag) String() string

type HistoryBody added in v0.2.4

type HistoryBody struct {
	Channel Channel   `json:"channel"`
	Data    []Message `json:"data"`
}

HistoryBody represents body of response in case of successful history command.

type HistoryClientCommand added in v1.0.0

type HistoryClientCommand struct {
	Channel Channel `json:"channel"`
}

HistoryClientCommand is used to get history information for channel.

type JoinLeaveBody added in v1.0.0

type JoinLeaveBody struct {
	Channel Channel    `json:"channel"`
	Data    ClientInfo `json:"data"`
}

JoinLeaveBody represents body of response when join or leave async response sent to client.

type Mediator added in v0.2.0

type Mediator interface {
	Connect(client ConnID, user UserID)
	Subscribe(ch Channel, client ConnID, user UserID)
	Unsubscribe(ch Channel, client ConnID, user UserID)
	Disconnect(client ConnID, user UserID)
	Message(ch Channel, data []byte, client ConnID, info *ClientInfo) bool
}

Mediator is an interface to work with libcentrifugo events from Go code. Implemented Mediator must be set to Application via corresponding Application method SetMediator.

type MemoryEngine added in v0.2.0

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

MemoryEngine allows to run Centrifugo without using Redis at all. All data managed inside process memory. With this engine you can only run single Centrifugo node. If you need to scale you should use Redis engine instead.

func NewMemoryEngine added in v0.2.0

func NewMemoryEngine(app *Application) *MemoryEngine

NewMemoryEngine initializes Memory Engine.

type Message added in v0.1.1

type Message struct {
	UID       MessageID        `json:"uid"`
	Timestamp string           `json:"timestamp"`
	Info      *ClientInfo      `json:"info,omitempty"`
	Channel   Channel          `json:"channel"`
	Data      *json.RawMessage `json:"data"`
	Client    ConnID           `json:"client,omitempty"`
}

Message represents client message.

type MessageID added in v1.2.0

type MessageID string

MessageID is a unique message ID

type Metrics added in v1.0.0

type Metrics struct {
	// NumMsgPublished is how many messages were published into channels.
	NumMsgPublished int64 `json:"num_msg_published"`

	// NumMsgQueued is how many messages were put into client queues.
	NumMsgQueued int64 `json:"num_msg_queued"`

	// NumMsgSent is how many messages were actually sent into client connections.
	NumMsgSent int64 `json:"num_msg_sent"`

	// NumAPIRequests shows amount of requests to server API.
	NumAPIRequests int64 `json:"num_api_requests"`

	// NumClientRequests shows amount of requests to client API.
	NumClientRequests int64 `json:"num_client_requests"`

	// BytesClientIn shows amount of data in bytes coming into client API.
	BytesClientIn int64 `json:"bytes_client_in"`

	// BytesClientOut shows amount of data in bytes coming out if client API.
	BytesClientOut int64 `json:"bytes_client_out"`

	// TimeAPIMean shows mean response time in nanoseconds to API requests. DEPRECATED!
	TimeAPIMean int64 `json:"time_api_mean"`

	// TimeClientMean shows mean response time in nanoseconds to client requests. DEPRECATED!
	TimeClientMean int64 `json:"time_client_mean"`

	// TimeAPIMax shows maximum response time to API request. DEPRECATED!
	TimeAPIMax int64 `json:"time_api_max"`

	// TimeClientMax shows maximum response time to client request. DEPRECATED!
	TimeClientMax int64 `json:"time_client_max"`

	// MemSys shows system memory usage in bytes.
	MemSys int64 `json:"memory_sys"`

	// CPU shows cpu usage in percents.
	CPU int64 `json:"cpu_usage"`
}

Metrics contains various Centrifugo statistic and metric information aggregated once in a configurable interval.

type MuxOptions added in v0.3.0

type MuxOptions struct {
	Prefix        string
	Admin         bool
	Web           bool
	WebPath       string
	WebFS         http.FileSystem
	SockjsOptions sockjs.Options
	HandlerFlags  HandlerFlag
}

MuxOptions contain various options for DefaultMux.

type Namespace added in v0.2.0

type Namespace struct {
	// Name is a unique namespace name.
	Name NamespaceKey `json:"name"`

	// ChannelOptions for namespace determine channel options for channels belonging to this namespace.
	ChannelOptions `mapstructure:",squash"`
}

Namespace allows to create channels with different channel options within the Project

type NamespaceKey added in v0.1.1

type NamespaceKey string

NamespaceKey is a name of namespace unique for project.

type NodeBody added in v1.4.0

type NodeBody struct {
	Data NodeInfo `json:"data"`
}

NodeBody represents body of response in case of successful node command.

type NodeInfo added in v1.0.0

type NodeInfo struct {
	UID        string `json:"uid"`
	Name       string `json:"name"`
	Goroutines int    `json:"num_goroutine"`
	Clients    int    `json:"num_clients"`
	Unique     int    `json:"num_unique_clients"`
	Channels   int    `json:"num_channels"`
	Started    int64  `json:"started_at"`
	Gomaxprocs int    `json:"gomaxprocs"`
	NumCPU     int    `json:"num_cpu"`
	Metrics
	// contains filtered or unexported fields
}

NodeInfo contains information and statistics about Centrifugo node.

type PingBody added in v1.0.0

type PingBody struct {
	Data string `json:"data"`
}

PingBody represents body of response in case of successful ping command.

type PingClientCommand added in v1.0.0

type PingClientCommand struct {
	Data string
}

PingClientCommand is used to ping server.

type PresenceBody added in v0.2.4

type PresenceBody struct {
	Channel Channel               `json:"channel"`
	Data    map[ConnID]ClientInfo `json:"data"`
}

PresenceBody represents body of response in case of successful presence command.

type PresenceClientCommand added in v1.0.0

type PresenceClientCommand struct {
	Channel Channel `json:"channel"`
}

PresenceClientCommand is used to get presence (actual channel subscriptions). information for channel

type PublishBody added in v1.0.0

type PublishBody struct {
	Channel Channel `json:"channel"`
	Status  bool    `json:"status"`
}

PublishBody represents body of response in case of successful publish command.

type PublishClientCommand added in v1.0.0

type PublishClientCommand struct {
	Channel Channel         `json:"channel"`
	Data    json.RawMessage `json:"data"`
}

PublishClientCommand is used to publish messages into channel.

type RedisEngine added in v0.2.0

type RedisEngine struct {
	sync.RWMutex
	// contains filtered or unexported fields
}

RedisEngine uses Redis datastructures and PUB/SUB to manage Centrifugo logic. This engine allows to scale Centrifugo - you can run several Centrifugo instances connected to the same Redis and load balance clients between instances.

func NewRedisEngine added in v0.2.0

func NewRedisEngine(app *Application, conf *RedisEngineConfig) *RedisEngine

NewRedisEngine initializes Redis Engine.

type RedisEngineConfig added in v1.3.0

type RedisEngineConfig struct {
	// Host is Redis server host.
	Host string
	// Port is Redis server port.
	Port string
	// Password is password to use when connecting to Redis database. If empty then password not used.
	Password string
	// DB is Redis database number as string. If empty then database 0 used.
	DB string
	// URL to redis server in format redis://:password@hostname:port/db_number
	URL string
	// PoolSize is a size of Redis connection pool.
	PoolSize int
	// API enables listening for API queues to publish API commands into Centrifugo via pushing
	// commands into Redis queue.
	API bool
	// NumAPIShards is a number of sharded API queues in Redis to increase volume of commands
	// (most probably publish) that Centrifugo instance can process.
	NumAPIShards int

	// MasterName is a name of Redis instance master Sentinel monitors.
	MasterName string
	// SentinelAddrs is a slice of Sentinel addresses.
	SentinelAddrs []string

	// Timeout on read operations. Note that at moment it should be greater than node
	// ping interval in order to prevent timing out Pubsub connection's Receive call.
	ReadTimeout time.Duration
	// Timeout on write operations
	WriteTimeout time.Duration
	// Timeout on connect operation
	ConnectTimeout time.Duration
}

RedisEngineConfig is struct with Redis Engine options.

type RefreshClientCommand added in v1.0.0

type RefreshClientCommand struct {
	User      UserID `json:"user"`
	Timestamp string `json:"timestamp"`
	Info      string `json:"info"`
	Token     string `json:"token"`
}

RefreshClientCommand is used to prolong connection lifetime when connection check mechanism is enabled. It can only be sent by client after successfull connect.

type Stats added in v1.0.0

type Stats struct {
	Nodes           []NodeInfo `json:"nodes"`
	MetricsInterval int64      `json:"metrics_interval"`
}

Stats contains state and metrics information from running Centrifugo nodes.

type StatsBody added in v1.0.0

type StatsBody struct {
	Data Stats `json:"data"`
}

StatsBody represents body of response in case of successful stats command.

type SubscribeBody added in v1.0.0

type SubscribeBody struct {
	Channel   Channel   `json:"channel"`
	Status    bool      `json:"status"`
	Last      MessageID `json:"last"`
	Messages  []Message `json:"messages"`
	Recovered bool      `json:"recovered"`
}

SubscribeBody represents body of response in case of successful subscribe command.

type SubscribeClientCommand added in v1.0.0

type SubscribeClientCommand struct {
	Channel Channel   `json:"channel"`
	Client  ConnID    `json:"client"`
	Last    MessageID `json:"last"`
	Recover bool      `json:"recover"`
	Info    string    `json:"info"`
	Sign    string    `json:"sign"`
}

SubscribeClientCommand is used to subscribe on channel. It can only be sent by client after successfull connect. It also can have Client, Info and Sign properties when channel is private.

type UnsubscribeBody added in v1.0.0

type UnsubscribeBody struct {
	Channel Channel `json:"channel"`
	Status  bool    `json:"status"`
}

UnsubscribeBody represents body of response in case of successful unsubscribe command.

type UnsubscribeClientCommand added in v1.0.0

type UnsubscribeClientCommand struct {
	Channel Channel `json:"channel"`
}

UnsubscribeClientCommand is used to unsubscribe from channel.

type UserID added in v0.1.1

type UserID string

UserID is web application user ID as string.

Directories

Path Synopsis
Package auth provides functions to generate and check Centrifugo tokens and signs.
Package auth provides functions to generate and check Centrifugo tokens and signs.
Package bytequeue provides []byte queue for libcentrifugo package client messages.
Package bytequeue provides []byte queue for libcentrifugo package client messages.
Package priority provides priority queue for libcentrifugo package Memory Engine.
Package priority provides priority queue for libcentrifugo package Memory Engine.

Jump to

Keyboard shortcuts

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