Categorygithub.com/centrifugal/centrifuge
modulepackage
0.34.4
Repository: https://github.com/centrifugal/centrifuge.git
Documentation: pkg.go.dev

# README

Join the chat at https://t.me/joinchat/ABFVWBE0AhkyyhREoaboXQ codecov.io GoDoc

This library has no v1 release, API may change. Before v1 release patch version updates only have backwards compatible changes and fixes, minor version updates can have backwards-incompatible API changes. Master branch can have unreleased code. Only two last Go minor versions are officially supported by this library.

The Centrifuge library is a general purpose real-time messaging library for Go programming language. Real-time messaging can help create interactive applications where events are delivered to online users with milliseconds delay. Chats apps, live comments, multiplayer games, real-time data visualizations, telemetry, collaborative tools, etc. can all be built on top of Centrifuge library.

The library is built on top of efficient client-server protocol schema and exposes various real-time oriented primitives for a developer. Centrifuge solves problems developers may come across when building complex real-time applications – like scalability to many server nodes, proper persistent connection management and invalidation, subscription multiplexing, fast reconnect with message recovery, WebSocket fallback options (without sticky sessions requirement in distributed scenario). And it all comes with ready to use client SDKs for both web and mobile development. See the full list of highlighs below.

Centrifuge library is used by:

  • Centrifugo - the main product of Centrifugal Labs. Centrifuge was decoupled into separate library from Centrifugo at some point.
  • Grafana - the most popular observability platform. Centrifuge library powers Grafana Live subsystem to stream data to panels. See cool demo of WebSocket telemetry from the Assetto Corsa racing simulator to the Grafana dashboard.

Why using Centrifuge

As said, Centrifuge provides a lot of top of raw WebSocket transport. Important library highlights:

  • Fast and optimized for low-latency communication with millions of client connections. See test stand with 1 million connections in Kubernetes
  • WebSocket bidirectional transport using JSON or binary Protobuf formats, both based on a strict Protobuf schema. Code generation is used to push both JSON and Protobuf serialization performance to the limits
  • Our own WebSocket emulation layer over HTTP-streaming (JSON + Protobuf) and Eventsource (JSON) without sticky sessions requirement for distributed setup
  • Possibility to use unidirectional transports without using custom Centrifuge SDK library: see examples for GRPC, EventSource(SSE), HTTP-streaming, Unidirectional WebSocket
  • Built-in horizontal scalability with Redis PUB/SUB, consistent Redis sharding, Redis Sentinel and Redis Cluster support, super-optimized Redis communication layer
  • Effective non-blocking broadcasts towards client connections using individual queues
  • Native authentication over HTTP middleware or custom token-based (ex. JWT)
  • Channel concept to broadcast message to all active subscribers
  • Client-side and server-side channel subscriptions
  • Bidirectional asynchronous message communication, RPC calls, builtin PING/PONG
  • Presence information for channels (show all active clients in a channel)
  • History information for channels (ephemeral streams with size and TTL retention)
  • Join/leave events for channels (aka client goes online/offline)
  • Possibility to register a custom PUB/SUB Broker and PresenceManager implementations
  • Option to register custom Transport, like Centrifugo does with WebTransport
  • Message recovery mechanism for channels to survive PUB/SUB delivery problems, short network disconnects or node restart
  • Cache channels – a way to quickly deliver latest publication from channel history to the client upon subscription
  • Delta compression using Fossil algorithm for publications inside a channel to reduce bandwidth usage
  • Out-of-the-box observability using Prometheus instrumentation
  • Client SDKs for main application environments all following single behaviour spec (see list of SDKs below).

Real-time SDK

For bidirectional communication between a client and a Centrifuge-based server we have a set of official client real-time SDKs:

These SDKs abstract asynchronous communication complexity from the developer: handle framing, reconnect with backoff, timeouts, multiplex channel subscriptions over single connection, etc.

If you opt for a unidirectional communication then you may leverage Centrifuge possibilities without any specific SDK on client-side - simply by using native browser API or GRPC-generated code. See examples of unidirectional communication over GRPC, EventSource(SSE), HTTP-streaming, WebSocket.

Explore Centrifuge

Installation

go get github.com/centrifugal/centrifuge

Tutorial

Let's take a look on how to build the simplest real-time chat with Centrifuge library. Clients will be able to connect to a server over Websocket, send a message into a channel and this message will be instantly delivered to all active channel subscribers. On a server side we will accept all connections and will work as a simple PUB/SUB proxy without worrying too much about permissions. In this example we will use Centrifuge Javascript client (centrifuge-js) on a frontend.

Start a new Go project and create main.go:

package main

import (
	"log"
	"net/http"

	// Import this library.
	"github.com/centrifugal/centrifuge"
)

// Authentication middleware example. Centrifuge expects Credentials
// with current user ID set. Without provided Credentials client
// connection won't be accepted. Another way to authenticate connection
// is reacting to node.OnConnecting event where you may authenticate
// connection based on a custom token sent by a client in first protocol
// frame. See _examples folder in repo to find real-life auth samples
// (OAuth2, Gin sessions, JWT etc).
func auth(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		ctx := r.Context()
		// Put authentication Credentials into request Context.
		// Since we don't have any session backend here we simply
		// set user ID as empty string. Users with empty ID called
		// anonymous users, in real app you should decide whether
		// anonymous users allowed to connect to your server or not.
		cred := &centrifuge.Credentials{
			UserID: "",
		}
		newCtx := centrifuge.SetCredentials(ctx, cred)
		r = r.WithContext(newCtx)
		h.ServeHTTP(w, r)
	})
}

func main() {
	// Node is the core object in Centrifuge library responsible for
	// many useful things. For example Node allows publishing messages
	// into channels with its Publish method. Here we initialize Node
	// with Config which has reasonable defaults for zero values.
	node, err := centrifuge.New(centrifuge.Config{})
	if err != nil {
		log.Fatal(err)
	}

	// Set ConnectHandler called when client successfully connected to Node.
	// Your code inside a handler must be synchronized since it will be called
	// concurrently from different goroutines (belonging to different client
	// connections). See information about connection life cycle in library readme.
	// This handler should not block – so do minimal work here, set required
	// connection event handlers and return.
	node.OnConnect(func(client *centrifuge.Client) {
		// In our example transport will always be Websocket but it can be different.
		transportName := client.Transport().Name()
		// In our example clients connect with JSON protocol but it can also be Protobuf.
		transportProto := client.Transport().Protocol()
		log.Printf("client connected via %s (%s)", transportName, transportProto)

		// Set SubscribeHandler to react on every channel subscription attempt
		// initiated by a client. Here you can theoretically return an error or
		// disconnect a client from a server if needed. But here we just accept
		// all subscriptions to all channels. In real life you may use a more
		// complex permission check here. The reason why we use callback style
		// inside client event handlers is that it gives a possibility to control
		// operation concurrency to developer and still control order of events.
		client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) {
			log.Printf("client subscribes on channel %s", e.Channel)
			cb(centrifuge.SubscribeReply{}, nil)
		})

		// By default, clients can not publish messages into channels. By setting
		// PublishHandler we tell Centrifuge that publish from a client-side is
		// possible. Now each time client calls publish method this handler will be
		// called and you have a possibility to validate publication request. After
		// returning from this handler Publication will be published to a channel and
		// reach active subscribers with at most once delivery guarantee. In our simple
		// chat app we allow everyone to publish into any channel but in real case
		// you may have more validation.
		client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) {
			log.Printf("client publishes into channel %s: %s", e.Channel, string(e.Data))
			cb(centrifuge.PublishReply{}, nil)
		})

		// Set Disconnect handler to react on client disconnect events.
		client.OnDisconnect(func(e centrifuge.DisconnectEvent) {
			log.Printf("client disconnected")
		})
	})

	// Run node. This method does not block. See also node.Shutdown method
	// to finish application gracefully.
	if err := node.Run(); err != nil {
		log.Fatal(err)
	}

	// Now configure HTTP routes.

	// Serve Websocket connections using WebsocketHandler.
	wsHandler := centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{})
	http.Handle("/connection/websocket", auth(wsHandler))

	// The second route is for serving index.html file.
	http.Handle("/", http.FileServer(http.Dir("./")))

	log.Printf("Starting server, visit http://localhost:8000")
	if err := http.ListenAndServe(":8000", nil); err != nil {
		log.Fatal(err)
	}
}

Also create file index.html near main.go with content:

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <script type="text/javascript" src="https://unpkg.com/centrifuge@^5/dist/centrifuge.js"></script>
        <title>Centrifuge chat example</title>
    </head>
    <body>
        <input type="text" id="input" />
        <script type="text/javascript">
            function drawText(text) {
                const div = document.createElement('div');
                div.innerHTML = text + '<br>';
                document.body.appendChild(div);
            }
            
            // Create Centrifuge object with Websocket endpoint address set in main.go
            const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket');

            centrifuge.on('connected', function(ctx){
                drawText('Connected over ' + ctx.transport);
            });
            
            const sub = centrifuge.newSubscription("chat");
            sub.on('publication', function(ctx) {
                drawText(JSON.stringify(ctx.data));
            });
            // Move subscription to subscribing state.
            sub.subscribe();
            
            const input = document.getElementById("input");
            input.addEventListener('keyup', function(e) {
                if (e.key === "Enter") {
                    e.preventDefault();
                    sub.publish(this.value);
                    input.value = '';
                }
            });
            // After setting event handlers – initiate actual connection with server.
            centrifuge.connect();
        </script>
    </body>
</html>

Then run Go app as usual:

go run main.go

Open several browser tabs with http://localhost:8000 and see chat in action.

While this example is only the top of an iceberg, it should give you a good insight on library API. Check out examples folder for more. We recommend to start looking from chat_json example, which extends the basics shown here and demonstrates more possibilities of Centrifuge protocol:

Chat example

[!IMPORTANT]
Keep in mind that Centrifuge library is not a framework to build chat applications. It's a general purpose real-time transport for your messages with some helpful primitives. You can build many kinds of real-time apps on top of this library including chats but depending on application you may need to write business logic yourself.

Tips and tricks

Some useful advices about library here.

Connection life cycle

Let's describe some aspects related to connection life cycle and event handling in Centrifuge:

  • If you set middleware for transport handlers (like WebsocketHandler) – then it will be called first before a client sent any command to a server and handler had a chance to start working. Just like a regular HTTP middleware. You can put Credentials to Context to authenticate connection.
  • node.OnConnecting called as soon as client sent Connect command to server. At this point no Client instance exists. You have incoming Context and Transport information. You still can authenticate Client at this point (based on string token sent from client side or any other way). Also, you can add extra data to context and return modified context to Centrifuge. Context cancelled as soon as client connection closes. This handler is synchronous and connection read loop can't proceed until you return ConnectReply.
  • node.OnConnect then called (after a reply to Connect command already written to connection). Inside OnConnect closure you have a possibility to define per-connection event handlers. If particular handler not set then client will get ErrorNotAvailable errors requesting it. Remember that none of event handlers available in Centrifuge should block forever – do minimal work, start separate goroutines if you need blocking code.
  • Client initiated request handlers called one by one from connection reading goroutine. This includes OnSubscribe, OnPublish, OnPresence, OnPresenceStats, OnHistory, client-side OnRefresh, client-side OnSubRefresh.
  • Other handlers like OnAlive, OnDisconnect, server-side OnSubRefresh, server-side OnRefresh called from separate internal goroutines.
  • OnAlive handler must not be called after OnDisconnect.
  • Client initiated request handlers can be processed asynchronously in goroutines to manage operation concurrency. This is achieved using callback functions. See concurrency example for more details.

Channel history stream

Centrifuge Broker interface supports saving Publication to history stream on publish. Depending on Broker implementation this feature can be missing though. Builtin Memory and Redis brokers support keeping Publication stream.

When using default MemoryBroker Publication stream kept in process memory and lost as soon as process restarts. RedisBroker keeps Publication stream in Redis LIST or STREAM data structures – reliability inherited from Redis configuration in this case.

Centrifuge library publication stream not meant to be used as the only source of missed Publications for a client. It mostly exists to help many clients reconnect at once (load balancer reload, application deploy) without creating a massive spike in load on your main application database. So application database still required in idiomatic use case.

Centrifuge message recovery protocol feature designed to be used together with reasonably small Publication stream size as all missed publications sent towards client in one protocol frame on resubscribe to channel.

Logging

Centrifuge library exposes logs with different log level. In your app you can set special function to handle these log entries in a way you want.

// Function to handle Centrifuge internal logs.
func handleLog(e centrifuge.LogEntry) {
	log.Printf("%s: %v", e.Message, e.Fields)
}

cfg := centrifuge.DefaultConfig
cfg.LogLevel = centrifuge.LogLevelDebug
cfg.LogHandler = handleLog

Allowed origin for WebSocket

When connecting to Centrifuge WebSocket endpoint from web browsers you need to configure allowed Origin. This is important to prevent CSRF-like/WebSocket hijacking attacks. See this post for example.

By default, CheckOrigin function of WebSocket handler will ensure that connection request originates from same host as your service. To override this behaviour you can provide your own implementation of CheckOrigin function to allow origins you trust. For example, your Centrifuge runs on http://localhost:8000 but you want it to allow WebSocket connections from http://localhost:3000:

centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{
	CheckOrigin: func(r *http.Request) bool {
		originHeader := r.Header.Get("Origin")
		if originHeader == "" {
			return true
		}
		return originHeader == "http://localhost:3000"
	},
})

Note, that if WebSocket Upgrade does not contain Origin header – it means it does not come from web browser and security concerns outlined above are not applied in that case. So we can safely return true in this case in the example above.

CORS for HTTP-based transports

Centrifuge has two HTTP-based fallback transports for WebSocket – see HTTPStreamHandler and SSEHandler. To connect to those from web browser from the domain which is different from your transport endpoint domain you may need to wrap handlers with CORS middleware:

func CORS(h http.Handler) http.Handler {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		header := w.Header()
		if originAllowed(r) {
			header.Set("Access-Control-Allow-Origin", r.Header.Get("origin"))
			if allowHeaders := r.Header.Get("Access-Control-Request-Headers"); allowHeaders != "" && allowHeaders != "null" {
				header.Add("Access-Control-Allow-Headers", allowHeaders)
			}
			header.Set("Access-Control-Allow-Credentials", "true")
		}
		h.ServeHTTP(w, r)
	})
}

http.Handle("/connection/http_stream", CORS(centrifuge.NewHTTPStreamHandler(node, centrifuge.HTTPStreamHandlerConfig{})))

You can also configure CORS on load-balancer/reverse-proxy level.

Server timeouts and HTTP-based real-time transports

Centrifuge uses http.ResponseController when working with timeouts in HTTP-streaming and Server-Sent Events (SSE) handlers. This allows having custom timeouts for HTTP server. But if you are using HTTP middlewares which provide a custom implementation of http.ResponseWriter – then make sure they implement Unwrap method to access original http.ResponseWriter for ResponseController to work correctly. As per http package documentation:

The ResponseWriter should be the original value passed to the [Handler.ServeHTTP] method, or have an Unwrap method returning the original ResponseWriter.

If handlers can't access original http.ResponseWriter – then you will observe connection closing corresponding to your HTTP server's ReadTimeout setting.

For contributors

Running integration tests locally

To run integration tests over Redis, Redis + Sentinel, Redis Cluster:

docker compose up
go test -tags integration ./...

To clean up container state:

docker compose down -v

# Functions

GetCredentials allows extracting Credentials from Context (if set previously).
HandleReadFrame is a helper to read Centrifuge commands from frame-based io.Reader and process them.
LogLevelToString transforms Level to its string representation.
New creates Node with provided Config.
NewClient initializes new Client.
NewEmulationHandler creates new EmulationHandler.
NewHTTPStreamHandler creates new HTTPStreamHandler.
NewMemoryBroker initializes MemoryBroker.
NewMemoryPresenceManager initializes MemoryPresenceManager.
NewRedisBroker initializes Redis Broker.
NewRedisPresenceManager creates new RedisPresenceManager.
NewRedisShard initializes new Redis shard.
NewSSEHandler creates new SSEHandler.
NewWebsocketHandler creates new WebsocketHandler.
SetCredentials allows setting connection Credentials to Context.
WithChannelInfo ...
WithClientInfo adds ClientInfo to Publication.
WithCustomDisconnect allows setting custom Disconnect.
WithCustomUnsubscribe allows setting custom Unsubscribe.
WithDelta tells Broker to use delta streaming.
WithDisconnectClient allows setting Client.
WithDisconnectClientWhitelist allows setting ClientWhitelist.
WithDisconnectSession allows setting session ID to disconnect.
WithEmitJoinLeave ...
WithEmitPresence ...
WithExpireAt allows setting ExpireAt field.
WithHistory tells Broker to save message to history stream with provided size and ttl.
No description provided by the author
No description provided by the author
WithIdempotencyKey tells Broker the idempotency key for the publication.
WithIdempotentResultTTL sets the time of expiration for results of idempotent publications.
WithLimit allows setting HistoryOptions.Limit.
WithPositioning ...
WithPushJoinLeave ...
WithRecoverSince allows setting SubscribeOptions.RecoverFrom.
WithRecovery ...
WithRecoveryMode ...
WithRefreshClient to limit refresh only for specified client ID.
WithRefreshExpireAt to set unix seconds in the future when connection should expire.
WithRefreshExpired to set expired flag - connection will be closed with DisconnectExpired.
WithRefreshInfo to override connection info.
WithRefreshSession to limit refresh only for specified session ID.
WithReverse allows setting HistoryOptions.Reverse option.
WithSince allows setting HistoryOptions.Since option.
WithSubscribeClient allows setting client ID that should be subscribed.
WithSubscribeData allows setting custom data to send with subscribe push.
WithSubscribeHistoryMetaTTL allows setting SubscribeOptions.HistoryMetaTTL.
WithSubscribeSession allows setting session ID that should be subscribed.
WithSubscribeSource allows setting SubscribeOptions.Source.
WithTags allows setting Publication.Tags.
WithUnsubscribeClient allows setting client ID that should be unsubscribed.
WithUnsubscribeSession allows setting session ID that should be unsubscribed.

# Constants

DeltaTypeFossil is Fossil delta encoding.
LogLevelDebug turns on debug logs - it's generally too much for production in normal conditions but can help when developing and investigating problems in production.
LogLevelError level logs only server errors.
LogLevelInfo logs useful server information.
LogLevelNone means no logging.
LogLevelTrace turns on trace logs - should only be used during development.
LogLevelWarn logs server warnings.
NoLimit defines that limit should not be applied.
ProtocolTypeJSON means JSON-based protocol.
ProtocolTypeProtobuf means Protobuf protocol.
ProtocolVersion2 is the current stable client protocol.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
It's possible to disable certain types of pushes to be sent to a client connection by using ClientConfig.DisabledPushFlags.
No description provided by the author
No description provided by the author
UnsubscribeCodeClient set when unsubscribe event was initiated by an explicit client-side unsubscribe call.
UnsubscribeCodeDisconnect set when unsubscribe event was initiated by a client disconnect process.
UnsubscribeCodeExpired set when client subscription expired.
UnsubscribeCodeInsufficient set when client unsubscribed from a channel due to insufficient state in a stream.
UnsubscribeCodeServer set when unsubscribe event was initiated by an explicit server-side unsubscribe call.

# Variables

DisconnectBadRequest issued when client uses malformed protocol frames.
DisconnectChannelLimit can be issued when client connection exceeds a configured channel limit.
DisconnectConnectionClosed is a special Disconnect object used when client connection was closed without any advice from a server side.
DisconnectConnectionLimit can be issued when client connection exceeds a configured connection limit (per user ID or due to other rule).
DisconnectExpired issued when client connection expired.
DisconnectForceNoReconnect issued when server disconnects connection and asks it to not reconnect again.
DisconnectForceReconnect issued when server disconnects connection.
DisconnectInappropriateProtocol can be issued when client connection format can not handle incoming data.
DisconnectInsufficientState issued when server detects wrong client position in channel Publication stream.
DisconnectInvalidToken issued when client came with invalid token.
DisconnectNoPong may be issued when server disconnects bidirectional connection due to no pong received to application-level server-to-client pings in a configured time.
DisconnectNotAvailable may be issued when ErrorNotAvailable does not fit message type, for example we issue DisconnectNotAvailable when client sends asynchronous message without MessageHandler set on server side.
DisconnectPermissionDenied may be issued when client attempts accessing a server without enough permissions.
DisconnectServerError issued when internal error occurred on server.
DisconnectShutdown issued when node is going to shut down.
DisconnectSlow issued when client can't read messages fast enough.
DisconnectStale issued to close connection that did not become authenticated in configured interval after dialing.
DisconnectSubExpired issued when client subscription expired.
DisconnectTooManyErrors may be issued when client generates too many errors.
DisconnectTooManyRequests may be issued when client sends too many commands to a server.
DisconnectWriteError issued when an error occurred while writing to client connection.
ErrorAlreadySubscribed returned when client wants to subscribe on channel it already subscribed to.
ErrorBadRequest says that server can not process received data because it is malformed.
ErrorExpired indicates that connection expired (no token involved).
ErrorInternal means server error, if returned this is a signal that something went wrong with server itself and client most probably not guilty.
ErrorLimitExceeded says that some sort of limit exceeded, server logs should give more detailed information.
ErrorMethodNotFound means that method sent in command does not exist.
ErrorNotAvailable means that resource is not enabled.
ErrorPermissionDenied means that access to resource not allowed.
ErrorTokenExpired indicates that connection or subscription token expired.
ErrorTooManyRequests means that server rejected request due to its rate limiting strategies.
ErrorUnauthorized says that request is unauthorized.
ErrorUnknownChannel means that channel name does not exist.
ErrorUnrecoverablePosition means that stream does not contain required range of publications to fulfill a history query.

# Structs

CacheEmptyEvent is issued when recovery mode is used but Centrifuge can't find Publication in history to recover from.
CacheEmptyReply contains fields determining the reaction on cache empty event.
ChannelContext contains extra context for channel connection subscribed to.
ChannelMediumOptions is an EXPERIMENTAL way to enable using a channel medium layer in Centrifuge.
Client represents client connection to server.
ClientInfo contains information about client connection.
CommandProcessedEvent contains protocol.Command processed by Client.
CommandReadEvent contains protocol.Command processed by Client.
Config contains Node configuration options.
ConnectEvent contains fields related to connecting event (when a server received Connect protocol command from client).
ConnectReply contains reaction to ConnectEvent.
ConnectRequest can be used in a unidirectional connection case to pass initial connection information from a client-side.
Credentials allow authenticating connection when set into context.
Disconnect allows configuring how client will be disconnected from a server.
DisconnectEvent contains fields related to disconnect event.
DisconnectOptions define some fields to alter behaviour of Disconnect operation.
EmulationConfig is a config for EmulationHandler.
EmulationHandler allows receiving client protocol commands from client and proxy them to the right node (where client session lives).
Error represents client reply error.
HistoryEvent has channel operation called for.
HistoryFilter allows filtering history according to fields set.
HistoryOptions define some fields to alter History method behaviour.
HistoryReply contains fields determining the reaction on history request.
HistoryResult contains Publications and current stream top StreamPosition.
HTTPStreamConfig represents config for HTTPStreamHandler.
HTTPStreamHandler handles WebSocket client connections.
Hub tracks Client connections on the current Node.
Info contains information about all known server nodes.
LogEntry represents log entry.
MemoryBroker is builtin default Broker which allows running Centrifuge-based server without any external broker.
MemoryBrokerConfig is a memory broker config.
MemoryPresenceManager is builtin default PresenceManager which allows running Centrifuge-based server without any external storage.
MemoryPresenceManagerConfig is a MemoryPresenceManager config.
MessageEvent contains fields related to message request.
Metrics aggregation over time interval for node.
No description provided by the author
Node is a heart of Centrifuge library – it keeps and manages client connections, maintains information about other Centrifuge nodes in cluster, keeps references to common things (like Broker and PresenceManager, Hub) etc.
NodeInfo contains information about node.
NodeInfoSendReply can modify sending Node control frame in some ways.
NotificationEvent with Op and Data.
PingPongConfig allows configuring application level ping-pong behavior.
PresenceEvent has channel operation called for.
PresenceReply contains fields determining the reaction on presence request.
PresenceResult wraps presence.
PresenceStats represents a short presence information for channel.
PresenceStatsEvent has channel operation called for.
PresenceStatsReply contains fields determining the reaction on presence request.
PresenceStatsResult wraps presence stats.
Publication is a data sent to a channel.
PublishEvent contains fields related to publish event.
PublishOptions define some fields to alter behaviour of Publish operation.
PublishReply contains fields determining the result on publish.
PublishResult returned from Publish operation.
RedisBroker uses Redis to implement Broker functionality.
RedisBrokerConfig is a config for Broker.
RedisPresenceManager keeps presence in Redis thus allows scaling nodes.
RedisPresenceManagerConfig is a config for RedisPresenceManager.
No description provided by the author
RedisShardConfig contains Redis connection options.
RefreshEvent contains fields related to refresh event.
RefreshOptions ...
RefreshReply contains fields determining the reaction on refresh event.
RPCEvent contains fields related to rpc request.
RPCReply contains fields determining the reaction on rpc request.
SSEConfig represents config for SSEHandler.
SSEHandler handles WebSocket client connections.
StreamPosition contains fields to describe position in stream.
SubRefreshEvent contains fields related to subscription refresh event.
SubRefreshReply contains fields determining the reaction on subscription refresh event.
SubscribeEvent contains fields related to subscribe event.
SubscribeOptions define per-subscription options.
SubscribeReply contains fields determining the reaction on subscribe event.
SubscribeRequest contains state of subscription to a channel.
SurveyEvent with Op and Data of survey.
SurveyReply contains survey reply fields.
SurveyResult from node.
TransportWriteEvent called just before sending data into the client connection.
Unsubscribe describes how client must be unsubscribed (or was unsubscribed) from a channel.
UnsubscribeEvent contains fields related to unsubscribe event.
UnsubscribeOptions ...
WebsocketConfig represents config for WebsocketHandler.
WebsocketHandler handles WebSocket client connections.

# Interfaces

Broker is responsible for PUB/SUB mechanics.
BrokerEventHandler can handle messages received from PUB/SUB system.
Closer is an interface that Broker and PresenceManager can optionally implement if they need to close any resources on Centrifuge Node graceful shutdown.
PresenceManager is responsible for channel presence management.
RegistererGatherer defines an interface that combines Registerer and Gatherer from Prometheus.
Transport abstracts a connection transport between server and client.
TransportInfo has read-only transport description methods.

# Type aliases

AliveHandler called periodically while connection alive.
CacheEmptyHandler allows setting cache empty handler function.
ClientCloseFunc must be called on Transport handler close to clean up Client.
CommandProcessedHandler allows setting a callback which will be called after Client processed a protocol.Command.
CommandReadHandler allows setting a callback which will be called before Client processed a protocol.Command read from the connection.
ConnectHandler called when client connected to server and ready to communicate.
ConnectingHandler called when new client authenticates on server.
No description provided by the author
DisconnectHandler called when client disconnects from server.
DisconnectOption is a type to represent various Disconnect options.
HistoryCallback should be called with HistoryReply or error.
HistoryHandler must handle incoming command from client.
HistoryOption is a type to represent various History options.
LogHandler handles log entries - i.e.
LogLevel describes the chosen log level.
MessageHandler must handle incoming async message from client.
NodeInfoSendHandler called every time the control node frame is published and allows modifying Node control frame sending.
NotificationHandler allows handling notifications.
PresenceCallback should be called with PresenceReply or error.
PresenceHandler called when presence request received from client.
PresenceStatsCallback should be called with PresenceStatsReply or error.
PresenceStatsHandler must handle incoming command from client.
ProtocolType represents client connection transport encoding format.
ProtocolVersion defines protocol behavior.
PublishCallback should be called with PublishReply or error.
PublishHandler called when client publishes into channel.
PublishOption is a type to represent various Publish options.
No description provided by the author
RefreshCallback should be called as soon as handler decides what to do with connection refresh event.
RefreshHandler called when it's time to validate client connection and update its expiration time if it's still actual.
RefreshOption is a type to represent various Refresh options.
RPCCallback should be called as soon as handler decides what to do with connection RPCEvent.
RPCHandler must handle incoming command from client.
StateSnapshotHandler must return a copy of current client's internal state.
SubRefreshCallback should be called as soon as handler decides what to do with connection SubRefreshEvent.
SubRefreshHandler called when it's time to validate client subscription to channel and update it's state if needed.
SubscribeCallback should be called as soon as handler decides what to do with connection subscribe event.
SubscribeHandler called when client wants to subscribe on channel.
SubscribeOption is a type to represent various Subscribe options.
SurveyCallback should be called with SurveyReply as soon as survey completed.
SurveyHandler allows setting survey handler function.
TransportWriteHandler called just before writing data to the Transport.
UnsubscribeHandler called when client unsubscribed from channel.
UnsubscribeOption is a type to represent various Unsubscribe options.