libcentrifugo

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Jun 25, 2015 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

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

Index

Constants

View Source
const (
	AuthTokenKey   = "token"
	AuthTokenValue = "authorized"
)
View Source
const (
	CloseStatus = 3000
)

Variables

View Source
var (
	ErrInvalidMessage      = errors.New("invalid message")
	ErrInvalidToken        = errors.New("invalid token")
	ErrUnauthorized        = errors.New("unauthorized")
	ErrMethodNotFound      = errors.New("method not found")
	ErrPermissionDenied    = errors.New("permission denied")
	ErrProjectNotFound     = errors.New("project not found")
	ErrNamespaceNotFound   = errors.New("namespace not found")
	ErrInternalServerError = errors.New("internal server error")
	ErrLimitExceeded       = errors.New("limit exceeded")
	ErrNotAvailable        = errors.New("not available")
	ErrConnectionExpired   = errors.New("connection expired")
	ErrSendTimeout         = errors.New("send timeout")
	ErrClientClosed        = errors.New("client is closed")
)
View Source
var DefaultConfig = &Config{
	Version:                     "-",
	Name:                        defaultName,
	WebPassword:                 "",
	WebSecret:                   "",
	ChannelPrefix:               defaultChannelPrefix,
	AdminChannel:                ChannelID(defaultChannelPrefix + ".admin"),
	ControlChannel:              ChannelID(defaultChannelPrefix + ".control"),
	MaxChannelLength:            255,
	NodePingInterval:            int64(defaultNodePingInterval),
	NodeInfoCleanInterval:       int64(defaultNodePingInterval) * 3,
	NodeInfoMaxDelay:            int64(defaultNodePingInterval)*2 + 1,
	PresencePingInterval:        int64(25),
	PresenceExpireInterval:      int64(60),
	MessageSendTimeout:          int64(60),
	PrivateChannelPrefix:        "$",
	NamespaceChannelBoundary:    ":",
	ClientChannelBoundary:       "&",
	UserChannelBoundary:         "#",
	UserChannelSeparator:        ",",
	ExpiredConnectionCloseDelay: int64(10),
	Insecure:                    false,
}

DefaultConfig is Config initialized with default values for all fields.

Functions

func DefaultMux added in v0.2.0

func DefaultMux(app *Application, prefix, webDir, sockjsURL string) *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, sockjsUrl string) 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 connection, subscription and admin hubs, maintains information about other Centrifugo nodes, keeps references to config, engine and structure.

func NewApplication added in v0.2.0

func NewApplication(c *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) ActionHandler added in v0.2.0

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

ActionHandler allows to call API commands via submitting a form.

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) ApiHandler added in v0.2.0

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

ApiHandler is responsible for receiving API commands over HTTP.

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) Authenticated added in v0.2.0

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

Authenticated middleware checks that request contains valid auth token in headers.

func (*Application) Disconnect added in v0.2.0

func (app *Application) Disconnect(pk ProjectKey, 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(pk ProjectKey, ch Channel) ([]Message, error)

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

func (*Application) InfoHandler added in v0.2.0

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

InfoHahdler allows to get actual information about Centrifugo nodes running.

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(pk ProjectKey, 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(pk ProjectKey, ch Channel, data []byte, client ConnID, info *ClientInfo) error

Publish sends a message to all clients subscribed on project 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()

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) SetStructure added in v0.2.0

func (app *Application) SetStructure(s *Structure)

SetEngine binds structure 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(pk ProjectKey, user UserID, ch Channel) error

Unsubscribe unsubscribes project 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, can be the same for different projects.

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 sent into admin channel
	Watch bool `json:"watch"`

	// Publish determines if client can publish messages into channel directly
	Publish bool `json:"publish"`

	// Anonymous determines is anonymous access (with empty user ID) allowed or not
	Anonymous bool `json:"anonymous"`

	// Presence turns on(off) presence information for channels
	Presence bool `json:"presence"`

	// HistorySize determines max amount of history messages for channel, 0 means no history for channel
	HistorySize int64 `mapstructure:"history_size" json:"history_size"`

	// HistoryLifetime determines time in seconds until expiration for history messages
	HistoryLifetime int64 `mapstructure:"history_lifetime" json:"history_lifetime"`

	// JoinLeave turns on(off) join/leave messages for channels
	JoinLeave bool `mapstructure:"join_leave" json:"join_leave"`
}

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

type ClientInfo added in v0.1.1

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

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

	// Name of this node - must be unique, used as human readable and
	// meaningful node identificator.
	Name string

	// WebPassword is an admin web interface password.
	WebPassword string
	// WebSecret is a secret to generate auth token for admin web interface.
	WebSecret string

	// ChannelPrefix is a string prefix before each channel.
	ChannelPrefix string
	// AdminChannel is channel name for admin messages.
	AdminChannel ChannelID
	// ControlChannel is a channel name for internal control messages between nodes.
	ControlChannel ChannelID
	// MaxChannelLength is a maximum length of channel name.
	MaxChannelLength int

	// NodePingInterval is an interval in seconds, how often node must send ping
	// control message.
	NodePingInterval int64
	// NodeInfoCleanInterval is an interval in seconds, how often node must clean
	// information about other running nodes.
	NodeInfoCleanInterval int64
	// NodeInfoMaxDelay is an interval in seconds – how many seconds node info
	// considered actual.
	NodeInfoMaxDelay int64

	// PresencePingInterval is an interval in seconds – how often connected clients
	// must update presence info.
	PresencePingInterval int64
	// PresenceExpireInterval is an interval in seconds – how long to consider
	// presence info valid after receiving presence ping.
	PresenceExpireInterval int64

	// ExpiredConnectionCloseDelay is an interval in seconds given to client to
	// refresh its connection in the end of connection lifetime.
	ExpiredConnectionCloseDelay int64

	// MessageSendTimeout is an interval in seconds setting how long time the node
	// may take to send a message to a client before disconnecting the client.
	MessageSendTimeout int64

	// PrivateChannelPrefix is a prefix in channel name which indicates that
	// channel is private.
	PrivateChannelPrefix string
	// NamespaceChannelBoundary is a string separator which must be put after
	// namespace part in channel name.
	NamespaceChannelBoundary string
	// UserChannelBoundary is a string separator which must be set before allowed
	// users part in channel name.
	UserChannelBoundary string
	// UserChannelSeparator separates allowed users in user part of channel name.
	UserChannelSeparator string
	// 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

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

Config contains Application configuration options.

type ConnID added in v0.1.1

type ConnID string

ConnID is a unique connection ID.

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 Mediator added in v0.2.0

type Mediator interface {
	Connect(pk ProjectKey, client ConnID, user UserID)
	Subscribe(pk ProjectKey, ch Channel, client ConnID, user UserID)
	Unsubscribe(pk ProjectKey, ch Channel, client ConnID, user UserID)
	Disconnect(pk ProjectKey, client ConnID, user UserID)
	Message(pk ProjectKey, 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       string           `json:"uid"`
	Timestamp string           `json:"timestamp"`
	Info      *ClientInfo      `json:"info"`
	Channel   Channel          `json:"channel"`
	Data      *json.RawMessage `json:"data"`
	Client    ConnID           `json:"client"`
}

Message represents client message

type Namespace added in v0.2.0

type Namespace struct {
	// Name is a unique namespace name in project
	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 Project added in v0.2.0

type Project struct {
	// Name is unique project name, used as project key for client connections and API requests
	Name ProjectKey `json:"name"`

	// Secret is a secret key for project, 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 `mapstructure:"connection_lifetime" json:"connection_lifetime"`

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

	// ChannelOptions - default project channel options
	ChannelOptions `mapstructure:",squash"`
}

Project represents single project that uses Centrifugo. Note that although Centrifugo can work with several projects but it's recommended to have separate Centrifugo installation for every project (maybe except copy of your project for development).

type ProjectKey added in v0.1.1

type ProjectKey string

ProjectKey is a name of project.

type RedisEngine added in v0.2.0

type RedisEngine struct {
	// 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, host, port, password, db, redisURL string, api bool, psize int) *RedisEngine

NewRedisEngine initializes Redis Engine.

type Structure added in v0.2.0

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

Structure contains project structure related fields - it allows to work with Projects and Namespaces.

func NewStructure added in v0.2.0

func NewStructure(pl []Project) *Structure

NewStructure allows to create fully initialized structure from a slice of Projects.

func (*Structure) Validate added in v0.2.0

func (s *Structure) Validate() error

validate validates structure and return error if problems found

type UserID added in v0.1.1

type UserID string // User ID

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 logger provides a logger for Centrifugo server.
Package logger provides a logger for Centrifugo server.
Package priority provides priority queue for libcentrifugo package Memory Engine.
Package priority provides priority queue for libcentrifugo package Memory Engine.
Package stringqueue provides string queue for libcentrifugo package client messages.
Package stringqueue provides string queue for libcentrifugo package client messages.

Jump to

Keyboard shortcuts

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