webrocket

package
v0.2.1-0...-cb188be Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2012 License: AGPL-3.0 Imports: 27 Imported by: 0

README

The `webrocket` core library
============================

This package contains core functionality of the WebRocket server and all
related tools.

Documentation

Index

Constants

View Source
const (
	BackendSocketReq    = "req"
	BackendSocketDealer = "dlr"
)

The backend socket types.

View Source
const (
	ChannelNormal   = 0
	ChannelPrivate  = 2
	ChannelPresence = 3
)

Possible channel types

View Source
const (
	VerMajor = 0
	VerMinor = 3
	VerPatch = 0
)

The version information.

View Source
const CookieSize = 40

The length of the cookie string.

Variables

This section is empty.

Functions

func DefaultNodeName

func DefaultNodeName() string

DefaultNodeName discovers name of the node from the host name configured in the operating system. Basically the result of the 'uname -n' command will be returned.

func ReadCookie

func ReadCookie(node string) string

ReadCookie reads cookie string from the node's cookie file.

Example:

node := webrocket.DefaultNodeName()
cookie := webrocket.ReadCookie(node)

Returns cookie string.

func Version

func Version() string

Version returns current version of the package.

Types

type AdminEndpoint

type AdminEndpoint struct {
	*http.Server
	// contains filtered or unexported fields
}

AdminEndpoint implements a wrapper for the http server instance which provides admin's RESTful interface.

func (*AdminEndpoint) Addr

func (a *AdminEndpoint) Addr() string

Addr returns an address to which the endpoint is bound.

func (*AdminEndpoint) IsAlive

func (a *AdminEndpoint) IsAlive() bool

Returns true if this endpoint is activated.

func (*AdminEndpoint) Kill

func (a *AdminEndpoint) Kill()

Kill stops execution of this endpoint.

func (*AdminEndpoint) ListenAndServe

func (a *AdminEndpoint) ListenAndServe() error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections.

Returns an error if something went wrong.

func (*AdminEndpoint) ListenAndServeTLS

func (a *AdminEndpoint) ListenAndServeTLS(certFile, certKey string) error

One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.

certFile - Path to the TLS certificate file. certKey - Path to the certificate's private key.

Returns an error if something went wrong.

type AdminServeMux

type AdminServeMux map[string]adminHandlerFunc

AdminServeMux is a simple wrapper for map of admin handler functions, which allows to effectively search for the handlers.

func (AdminServeMux) Match

func (mux AdminServeMux) Match(method, path string) (adminHandlerFunc, bool)

Match looks for the handler matching given request method and path.

method - A HTTP request method. path - A path to be found.

Returns matching handler function and status.

type BackendEndpoint

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

BackendEndpoint implements a TCP server supporting the Backend Worker Protocol. It acts like a broker for both - backend clients (REQ) and workers (DEALER) using the majordomo pattern.

func (*BackendEndpoint) Addr

func (w *BackendEndpoint) Addr() string

Addr returns an address to which this endpoint is bound.

func (*BackendEndpoint) IsAlive

func (w *BackendEndpoint) IsAlive() bool

IsAlive Returns whether the endpoint is alive or not.

func (*BackendEndpoint) Kill

func (w *BackendEndpoint) Kill()

Kill terminates execution of this endpoint, kills all registered lobbys and closes all open worker connections.

func (*BackendEndpoint) ListenAndServe

func (b *BackendEndpoint) ListenAndServe() (err error)

ListenAndServe setups endpoint's TCP listener for handling incoming backend worker's and client's connections.

func (*BackendEndpoint) ListenAndServeTLS

func (b *BackendEndpoint) ListenAndServeTLS(certFile, certKey string) (err error)

TODO: ...

func (*BackendEndpoint) Trigger

func (b *BackendEndpoint) Trigger(vhost *Vhost, payload interface{}) error

Trigger enqueues the message in the internal lobby queue. Given message is load ballanced across all workers waiting in there.

vhost - Related vhost. payload - The payload to be enqueued.

Returns an error if something went wrong.

type BackendLobbyMux

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

BackendLobbyMux is an request multiplexer for backend lobbys.

func NewBackendLobbyMux

func NewBackendLobbyMux() *BackendLobbyMux

NewBackendLobbyMux allocates and returns a new BackendLobbyMux.

func (*BackendLobbyMux) AddLobby

func (mux *BackendLobbyMux) AddLobby(pattern string, lobby *backendLobby)

AddLobby registers the lobby for the given pattern.

pattern - A path to which this lobby will be bound lobby - A http lobby that will be registered

Examples:

helloLobby = websocket.Lobby(func(ws *websocket.Conn) { /* ... */ })
mux.AddLobby("/hello", helloLobby)

func (*BackendLobbyMux) DeleteLobby

func (mux *BackendLobbyMux) DeleteLobby(pattern string) bool

DeleteLobby removes matching lobby from the lobby map.

pattern - A pattern under which the lobby has been registered.

Examples:

mux.DeleteLobby("/hello")

Returns whether the lobby has been removed or not.

func (*BackendLobbyMux) KillAll

func (mux *BackendLobbyMux) KillAll()

KillAll terminates all registered lobbys..

func (*BackendLobbyMux) Match

func (mux *BackendLobbyMux) Match(path string) *backendLobby

Match finds a lobby on a handler map given a path string.

p - A path to match against.

Returns matching lobby.

type BackendWorker

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

BackendWorker is a wrapper for the backend worker's connection with majordomo's keep alive mechanism.

func (*BackendWorker) Id

func (a *BackendWorker) Id() string

Id returns the worker's unique identifier.

func (*BackendWorker) IsAlive

func (a *BackendWorker) IsAlive() bool

IsAlive returns whether this worker is working or not. Threadsafe, may be called from the various handlers.

func (*BackendWorker) Kill

func (a *BackendWorker) Kill()

Kill terminates execution of this worker and closes its underlaying connection. Threadsafe, may be called from the many handlers or affect other functions.

func (*BackendWorker) Trigger

func (a *BackendWorker) Trigger(payload interface{}) (err error)

Trigger sends given payload directly to the worker.

payload - The data to be send

type Channel

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

Channel keeps information about specified channel and it's subscriptions. It's hub is used to broadcast messages.

func (*Channel) Broadcast

func (ch *Channel) Broadcast(x map[string]interface{}, includeHidden bool)

Broadcast sends given payload to all active subscribers of this channel. Threadsafe, May be called from many websocket client's handlers.

x - The data to be broadcasted to all the subscribers.

func (*Channel) HasSubscriber

func (ch *Channel) HasSubscriber(client *WebsocketConnection) bool

HasSubscriber checks whether specified client is subscribing to this channel or not. Threadsafe, May be called from many places and depends on the Subscribe and Unsubscribe funcs.

client - The websocket client to be checked.

Returns whether client is subscribing this channel or not.

func (*Channel) IsAlive

func (ch *Channel) IsAlive() bool

IsAlive returns whether the channels is alive or not. Threadsafe, May be called from many places and depends on the Kill func.

func (*Channel) IsPresence

func (ch *Channel) IsPresence() bool

IsPresence returns whether this channel is a presence one or not.

func (*Channel) IsPrivate

func (ch *Channel) IsPrivate() bool

IsPrivate returns whether this channel requires authenticaion or not.

func (*Channel) Kill

func (ch *Channel) Kill()

Kill closes the channel's broadcaster and marks it as dead. Threadsafe, May be called from the backend protocol or admin interface and affects the IsAlive func.

func (*Channel) Name

func (ch *Channel) Name() string

Name returns name of the channel.

func (*Channel) Subscribers

func (ch *Channel) Subscribers() map[string]*Subscription

Subscribers returns list of the clients subsribing to the channel. Threadsafe, May be called from many places and depends on the Subscribe and Unsubscribe funcs.

func (*Channel) Type

func (ch *Channel) Type() ChannelType

Type returns flag representing the channel's type.

type ChannelType

type ChannelType int

ChannelType represents a type of the channel. Can be normal, private or presence.

type Context

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

Context implements a placeholder for general WebRocket's configuration and shared data. It's not possible to create any of the components without providing a context. If context is dead, then everything else should be gracefully closed as well.

func NewContext

func NewContext() *Context

NewContext creates and preconfigures new context.

Returns a new context.

func (*Context) AddVhost

func (ctx *Context) AddVhost(path string) (v *Vhost, err error)

AddVhost registers new vhost under the specified path. Threadsafe, may be called from the admin endpoint or storage loader and its execution affects Vhost, Vhosts and DeleteVhost functions.

path - The path to register the vhost under.

Returns new vhost or an error if something went wrong.

func (*Context) Cookie

func (ctx *Context) Cookie() string

Cookie returns the value of the node admin's cookie hash.

func (*Context) DeleteVhost

func (ctx *Context) DeleteVhost(path string) (err error)

DeleteVhost removes and unregisters vhost from the specified path. Threadsafe, may be called from the admin endpoint or storage loader and its execution affects Vhost, Vhosts and AddVhost functions.

path - The path to the vhost to be deleted.

Returns an error if something went wrong.

func (*Context) GenerateCookie

func (ctx *Context) GenerateCookie(force bool) (err error)

GenerateCookie generates new random node admin's cookie hash and saves it to the storage dir in the 'cookie' file. If no force flag specified then cookie will be not overwritten during the further calls of this function.

force - If true, then generates new cookie and overwrites existing one.

Returns an error if something went wrong.

func (*Context) Kill

func (ctx *Context) Kill() (err error)

Kill closes the context and cleans up all internal endpoints, closes all connections and in general makes everyone happy. Not threadsafe, no need to lock while this func shall be called only in one place - when exiting from the application.

Returns an error if something went wrong.

func (*Context) Load

func (ctx *Context) Load() (err error)

Load reads existing information about the vhosts, channels, etc. Storage will be automatically marked as available if everything's fine at return. Not threadsafe, storage directory shall be set only once from the main goroutine.

Returns an error if something went wrong.

func (*Context) Lock

func (ctx *Context) Lock() (err error)

Lock creates a lockfile which prevents to open more than one instance of the same node (on the same machine).

func (*Context) Log

func (ctx *Context) Log() *log.Logger

Log returns a configured logger.

func (*Context) NewAdminEndpoint

func (ctx *Context) NewAdminEndpoint(addr string) Endpoint

NewAdminEndpoint creates a new admin endpoint.

addr - The host and port to which this endpoint will be bound.

Examples

e := ctx.NewAdminEndpoint(":8082")
if err := e.ListenAndServe(); err != nil {
    println(err.Error())
}

Returns a configured endpoint.

func (*Context) NewBackendEndpoint

func (ctx *Context) NewBackendEndpoint(addr string) Endpoint

NewBackendEndpoint creates a new backend endpoint, registers handlers for all the existing vhosts and registers it within the context.

addr - The host and port to which this endpoint will be bound.

Examples

e := ctx.NewBackendEndpoint(":8081")
if err := e.ListenAndServe(); err != nil {
    println(err.Error())
}

Returns a configured endpoint.

func (*Context) NewWebsocketEndpoint

func (ctx *Context) NewWebsocketEndpoint(addr string) Endpoint

NewWebsocketEndpoint creates a new websocket endpoint, registers handlers for all the existing vhosts and registers it within the context.

addr - The host and port to which this endpoint will be bound.

Examples

e := ctx.NewWebsocketEndpoint(":8080")
if err := e.ListenAndServe(); err != nil {
    println(err.Error())
}

Returns a configured endpoint.

func (*Context) NodeName

func (ctx *Context) NodeName() string

NodeName returns a configured node name.

func (*Context) SetLog

func (ctx *Context) SetLog(newLog *log.Logger)

SetLog configures custom logger.

newLog - The logger instance to be assigned with the context.

Examples

logger := log.NewLogger(os.Stderr, "My Logger!", log.LstdFlags)
ctx.SetLog(logger)

func (*Context) SetNodeName

func (ctx *Context) SetNodeName(newName string) error

SetNodeName changes node name to given one.

newName - The new node name to be set.

func (*Context) SetStorageDir

func (ctx *Context) SetStorageDir(dir string) (err error)

SetStorage sets the storage directory to specified value. It's not possible to change storage dir while app is running.

dir - A path to the storage directory.

Returns an error when something went wrong.

func (*Context) StorageDir

func (ctx *Context) StorageDir() string

StorageDir returns path to the configured storage directory.

func (*Context) Vhost

func (ctx *Context) Vhost(path string) (vhost *Vhost, err error)

Vhost finds a vhost registered under the specified path and returns it if exists. Threadsafe, may be called from the admin endpoint or storage loader and its execution affects Vhosts, DeleteVhost and AddVhost functions.

path - The vhost's path to be found.

Returns vhost from specified path or an error if something went wrong or vhost doesn't exist.

func (*Context) Vhosts

func (ctx *Context) Vhosts() map[string]*Vhost

Vhosts returns list of all the registered vhosts. Threadsafe, may be called from the admin endpoint or storage loader and its execution affects Vhost, DeleteVhost and AddVhost functions.

type Endpoint

type Endpoint interface {
	ListenAndServe() error
	ListenAndServeTLS(certFile, certKey string) error
	Addr() string
	IsAlive() bool
}

Endpoint is an interface defining basic access and control function for the server endpoints.

type Permission

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

Permission is represents single access token and permission pattern assigned to it.

func NewPermission

func NewPermission(uid string, pattern string) (p *Permission, err error)

Creates new permission for specified pattern.

uid - An ID of the permission assignee. pattern - The regexp string to be used to match against the channels.

Returns new permission or error if something went wrong.

func (*Permission) IsMatching

func (p *Permission) IsMatching(channel string) bool

IsMatching checks if permission description allows to operate on the specified channel. Speaking shortly just matches permission regexp with the channel name.

channel - The channel to be checked for permission.

Examples:

p := NewPermission("joe", "(foo|bar)")
p.IsMatching("foo")
// => true
p.IsMatching("hello")

Returns whether you have permission to operate on the channel or not.

func (*Permission) Token

func (p *Permission) Token() string

Token returns single access token generate for this permission.

func (*Permission) Uid

func (p *Permission) Uid() string

Uid returns user defined identifier.

type Status

type Status struct {
	Status string
	Code   int
}

Status represents client response statuses.

func (*Status) Map

func (s *Status) Map() map[string]interface{}

Map returns status as a map.

func (*Status) String

func (s *Status) String() string

Status returns full status message.

type Subscription

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

Subscription represents single subscription entry.

func (*Subscription) Client

func (s *Subscription) Client() *WebsocketConnection

Client returns the subscribers's connection.

func (*Subscription) Data

func (s *Subscription) Data() map[string]interface{}

Data returns a data attached to this subscription.

func (*Subscription) Id

func (s *Subscription) Id() (id string)

Id returns an unique id of the subscriber's connection.

func (*Subscription) IsHidden

func (s *Subscription) IsHidden() bool

IsHidden returns whether this subscription is hidden or not.

func (*Subscription) Uid

func (s *Subscription) Uid() string

Uid returns an unique id of the subscriber.

type Vhost

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

Vhost implements a standalone, independent component of the WebRocket server which contains it's own users with permissions, channels, and other related settings.

func (*Vhost) AccessToken

func (v *Vhost) AccessToken() string

AccessToken returns vhost's access token. Threadsafe, called from various backend connection's handlers.

func (*Vhost) Channel

func (v *Vhost) Channel(name string) (ch *Channel, err error)

Channel returns specified channel if exists. Threadsafe, may be called from many places and being affected by other functions.

name - The name of the channel to find.

Returns a channel with given name and existance status.

func (*Vhost) Channels

func (v *Vhost) Channels() map[string]*Channel

Channels returns list of the channels registered within the vhost.

func (*Vhost) DeleteChannel

func (v *Vhost) DeleteChannel(name string) (err error)

DeleteChannel removes channel with the specified name from the vhost. Threadsafe, may be called from the admin interface and affect other functions.

name - The name of the channel to be deleted.

Returns an error if something went wrong.

func (*Vhost) GenerateAccessToken

func (v *Vhost) GenerateAccessToken() string

GenerateAccessToken create a new access token for the backend connections. Threadsafe, called from main context and admin interface.

func (*Vhost) GenerateSingleAccessToken

func (v *Vhost) GenerateSingleAccessToken(uid, pattern string) (token string)

GenerateSingleAccessToken generates new single access token for the specified permissions. Threadsafe, called from various connection's handlers.

uid - An ID of the permission assignee. pattern - The permission regexp to be attached to the token.

Examples

token := v.GenerateSingleAccessToken("joe", "(foo|bar)")
println(token)
// => "f74fda...f54abd3"

func (*Vhost) Kill

func (v *Vhost) Kill()

Kill stops execution of this vhost.

func (*Vhost) OpenChannel

func (v *Vhost) OpenChannel(name string, kind ChannelType) (ch *Channel, err error)

OpenChannel creates new channel and registers it within the vhost. Threadsafe, may be called from the admin interface and affects other functions.

name - The name of the new channel. kind - The type of the new channel.

Examples

ch, _ = v.OpenChannel("hello")
println(ch.Name())
// => "hello"

Returns new channel or error if something went wrong.

func (*Vhost) Path

func (v *Vhost) Path() string

Path returns configured path of this vhost.

func (*Vhost) Permissions

func (v *Vhost) Permissions() map[string]*Permission

Permissions returns list of all permissions allocated by single access token requests.

func (*Vhost) ValidateSingleAccessToken

func (v *Vhost) ValidateSingleAccessToken(token string) (p *Permission, ok bool)

ValidateSingleAccessToken checks if the specified token allows to access this vhost, and if so then returns associated permission. Threadsafe, called from the various connection's handlers.

token - The token to be checked.

Returns related permission object and boolean status.

type WebsocketConnection

type WebsocketConnection struct {
	*websocket.Conn
	// contains filtered or unexported fields
}

WebsocketConnection represents a single WebSockets connection and implements an API for managing its subscriptions and authentication.

func (*WebsocketConnection) Id

func (c *WebsocketConnection) Id() string

Id returns an unique session identifier attached to this connection.

func (*WebsocketConnection) IsAlive

func (c *WebsocketConnection) IsAlive() bool

IsAlive returns whether the connection is alive or not. Threadsafe, so far used internally only, but the related Kill function may be called from many goroutines.

func (*WebsocketConnection) IsAllowed

func (c *WebsocketConnection) IsAllowed(channel string) bool

IsAllowed returns whether this connections is authenticated and has sufficient permissions to operate on a given channel. Not threadsafe, used only from within websocket protocol's handlers which is blocking for specified connection.

channel - The channel to check permissions for.

func (*WebsocketConnection) IsAuthenticated

func (c *WebsocketConnection) IsAuthenticated() bool

IsAuthenticated returns whether this connection is authenticated or not. Not threadsafe, Used only from within websocket protocol's handlers which is blocking for specified connection.

func (*WebsocketConnection) Kill

func (c *WebsocketConnection) Kill()

Kill cleans up all subscriptions and closes the connection. This operation will mark connection as dead. Threadsafe, Used in the websocket endpoint and handlers.

func (*WebsocketConnection) Receive

func (c *WebsocketConnection) Receive() (*WebsocketMessage, error)

Receive reads a message from the client and parses it into the internal message object. If there is no data to read from the connection then it shall block until new data arrive. Not threadsafe, used only from within websocket handler's event loop.

Returns message received from the connection.

func (*WebsocketConnection) Send

func (c *WebsocketConnection) Send(payload interface{})

Send serializes given payload with JSON and sends it to the client. Threadsafe, may be used from the websocket protocol's handlers and the channel's broadcaster.

payload - A data to be send to the client.

func (*WebsocketConnection) Uid

func (c *WebsocketConnection) Uid() string

Uid returns user-defined identifier of this connection.

type WebsocketEndpoint

type WebsocketEndpoint struct {
	*http.Server
	// contains filtered or unexported fields
}

WebsocketEndpoint implements a wrapper for the websockets server instance. For now, it extends the standard http.Server functionality with WebRocket specific stuff.

func (*WebsocketEndpoint) Addr

func (w *WebsocketEndpoint) Addr() string

Addr returns an address to which the endpoint is bound.

func (*WebsocketEndpoint) IsAlive

func (w *WebsocketEndpoint) IsAlive() bool

IsAlive returns whether the endpoint is alive or not.

func (*WebsocketEndpoint) Kill

func (w *WebsocketEndpoint) Kill()

Kill stops all registered vhost handlers and marks this endpoint as dead.

func (*WebsocketEndpoint) ListenAndServe

func (w *WebsocketEndpoint) ListenAndServe() error

ListenAndServe listens on the TCP network address addr and then calls Serve with handler to handle requests on incoming connections.

Returns an error if something went wrong.

func (*WebsocketEndpoint) ListenAndServeTLS

func (w *WebsocketEndpoint) ListenAndServeTLS(certFile, certKey string) (err error)

One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.

certFile - Path to the TLS certificate file. certKey - Path to the certificate's private key.

Returns an error if something went wrong.

type WebsocketMessage

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

WebsocketMessage implements representation of the decoded message sent by the websocket client.

func (*WebsocketMessage) Data

func (m *WebsocketMessage) Data() map[string]interface{}

Data returns a data's payload.

func (*WebsocketMessage) Event

func (m *WebsocketMessage) Event() string

Event returns an event name.

func (*WebsocketMessage) Get

func (m *WebsocketMessage) Get(key string) (value interface{})

Get returns a value from the specified data field. If the key is not defined then nil will be returned.

key - A key to find in the data

Examples

foo, ok := msg.Get("foo").(string)
bar, ok := msg.Get("bar").(int)

Returns value of the specified key.

func (*WebsocketMessage) JSON

func (m *WebsocketMessage) JSON() string

JSON returns message encoded into a JSON string.

type WebsocketServeMux

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

WebsocketServeMux is an HTTP request multiplexer. Basically works the same as the http.WebsocketServeMux from the standar library, but allows for dynamic adding and removing handlers.

func NewWebsocketServeMux

func NewWebsocketServeMux() *WebsocketServeMux

NewWebsocketServeMux allocates and returns a new WebsocketServeMux.

func (*WebsocketServeMux) AddHandler

func (mux *WebsocketServeMux) AddHandler(pattern string, handler *websocketHandler)

AddHandler registers the handler for the given pattern.

pattern - A path to which this handler will be bound handler - A http handler that will be registered

Examples:

helloHandler = websocket.Handler(func(ws *websocket.Conn) { /* ... */ })
mux.AddHandler("/hello", helloHandler)

func (*WebsocketServeMux) DeleteHandler

func (mux *WebsocketServeMux) DeleteHandler(pattern string) bool

DeleteHandler removes matching handler from the handler map.

pattern - A pattern under which the handler has been registered.

Examples:

mux.DeleteHandler("/hello")

Returns whether the handler has been removed or not.

func (*WebsocketServeMux) KillAll

func (mux *WebsocketServeMux) KillAll()

KillAll terminates all registered handlers.

func (*WebsocketServeMux) Match

func (mux *WebsocketServeMux) Match(path string) *websocketHandler

Match finds a handler on a handler map given a path string.

p - A path to match against

Returns matching handler.

func (*WebsocketServeMux) ServeHTTP

func (mux *WebsocketServeMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP dispatches the request to the handler whose pattern matches the request URL.

w - The response writer r - The request to handle

Jump to

Keyboard shortcuts

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