Debian Codegraph @

README.md

raw
1 [![Join the chat at https://t.me/joinchat/ABFVWBE0AhkyyhREoaboXQ](https://img.shields.io/badge/Telegram-Group-blue.svg)](https://t.me/joinchat/ABFVWBE0AhkyyhREoaboXQ)
2 [![Build Status](https://github.com/centrifugal/centrifuge/workflows/build/badge.svg?branch=master)](https://github.com/centrifugal/centrifuge/actions)
3 [![codecov.io](https://codecov.io/gh/centrifugal/centrifuge/branch/master/graphs/badge.svg)](https://codecov.io/github/centrifugal/centrifuge?branch=master)
4 [![GoDoc](https://pkg.go.dev/badge/centrifugal/centrifuge)](https://pkg.go.dev/github.com/centrifugal/centrifuge)
5
6 **This library has no v1 release yet, API still evolves. Use with strict versioning.** At this moment patch version updates only have backwards compatible changes and fixes, minor version updates can have backwards-incompatible API changes. See [v1.0.0 milestone](https://github.com/centrifugal/centrifuge/milestone/1). Master branch can have unreleased code.
7
8 Centrifuge library is a real-time core of [Centrifugo](https://github.com/centrifugal/centrifugo) server. It's also supposed to be a general purpose real-time messaging library for Go programming language. The library built on top of strict client-server protocol schema and exposes various real-time oriented primitives for a developer. Centrifuge solves several problems a developer may come across when building complex real-time applications – like scalability (millions of connections), proper persistent connection management and invalidation, fast reconnect with message recovery, WebSocket fallback option.
9
10 Library highlights:
11
12 * Fast and optimized for low-latency communication with millions of client connections. See [test stand with 1 million connections in Kubernetes](https://centrifugal.github.io/centrifugo/misc/benchmark/)
13 * WebSocket with JSON or binary Protobuf protocol
14 * SockJS polyfill library support for browsers where WebSocket not available (JSON only)
15 * Built-in horizontal scalability with Redis PUB/SUB, consistent Redis sharding, Sentinel and Redis Cluster for HA
16 * Possibility to register custom PUB/SUB broker and presence storage implementations
17 * Native authentication over HTTP middleware or custom token-based
18 * Bidirectional asynchronous message communication and RPC calls
19 * Channel concept to broadcast message to all active subscribers
20 * Client-side and server-side channel subscriptions
21 * Presence information for channels (show all active clients in channel)
22 * History information for channels (stream of messages published into channel)
23 * Join/leave events for channels (aka client goes online/offline)
24 * Message recovery mechanism for channels to survive PUB/SUB delivery problems, short network disconnects or node restart
25 * Prometheus instrumentation
26 * Client libraries for main application environments (see below)
27
28 Client libraries:
29
30 * [centrifuge-js](https://github.com/centrifugal/centrifuge-js) – for a browser, NodeJS and React Native
31 * [centrifuge-go](https://github.com/centrifugal/centrifuge-go) - for Go language
32 * [centrifuge-mobile](https://github.com/centrifugal/centrifuge-mobile) - for iOS/Android with `centrifuge-go` as basis and [gomobile](https://github.com/golang/mobile)
33 * [centrifuge-dart](https://github.com/centrifugal/centrifuge-dart) - for Dart and Flutter
34 * [centrifuge-swift](https://github.com/centrifugal/centrifuge-swift) – for native iOS development
35 * [centrifuge-java](https://github.com/centrifugal/centrifuge-java) – for native Android development and general Java
36
37 ### Explore Centrifuge
38
39 * see Centrifuge [Documentation on pkg.go.dev](https://pkg.go.dev/github.com/centrifugal/centrifuge)
40 * check out [examples](https://github.com/centrifugal/centrifuge/tree/master/_examples) folder
41 * read [Centrifuge introduction post](https://centrifugal.github.io/centrifugo/blog/intro_centrifuge/) in Centrifugo blog
42 * you can also consider [Centrifugo server documentation](https://centrifugal.github.io/centrifugo/) as extra doc for this package (since Centrifugo is built on top of Centrifuge library)
43 * read this README to the end for [installation](#installation) details, [quick example](#quick-example) and [Tips and tricks](#tips-and-tricks) section
44
45 ### Installation
46
47 To install use:
48
49 ```bash
50 go get github.com/centrifugal/centrifuge
51 ```
52
53 `go mod` is a recommended way of adding this library to your project dependencies.
54
55 ### Quick example
56
57 Let's take a look on how to build the simplest real-time chat ever with Centrifuge library. Clients will be able to connect to server over Websocket, send a message into channel and this message will be instantly delivered to all active channel subscribers. On server side we will accept all connections and will work as simple PUB/SUB proxy without worrying too much about permissions. In this example we will use Centrifuge Javascript client on a frontend.
58
59 Create file `main.go` with the following code:
60
61 ```go
62 package main
63
64 import (
65 "log"
66 "net/http"
67
68 // Import this library.
69 "github.com/centrifugal/centrifuge"
70 )
71
72 // Authentication middleware example. Centrifuge expects Credentials
73 // with current user ID set. Without provided Credentials client
74 // connection won't be accepted. Another way to authenticate connection
75 // is reacting to node.OnConnecting event where you may authenticate
76 // connection based on a custom token sent by a client in first protocol
77 // frame. See _examples folder in repo to find real-life auth samples
78 // (OAuth2, Gin sessions, JWT etc).
79 func auth(h http.Handler) http.Handler {
80 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
81 ctx := r.Context()
82 // Put authentication Credentials into request Context.
83 // Since we don't have any session backend here we simply
84 // set user ID as empty string. Users with empty ID called
85 // anonymous users, in real app you should decide whether
86 // anonymous users allowed to connect to your server or not.
87 cred := &centrifuge.Credentials{
88 UserID: "",
89 }
90 newCtx := centrifuge.SetCredentials(ctx, cred)
91 r = r.WithContext(newCtx)
92 h.ServeHTTP(w, r)
93 })
94 }
95
96 func main() {
97 // We use default config here as a starting point. Default config
98 // contains reasonable values for available options.
99 cfg := centrifuge.DefaultConfig
100
101 // Node is the core object in Centrifuge library responsible for
102 // many useful things. For example Node allows to publish messages
103 // to channels with its Publish method.
104 node, err := centrifuge.New(cfg)
105 if err != nil {
106 log.Fatal(err)
107 }
108
109 // Set ConnectHandler called when client successfully connected to Node.
110 // Your code inside a handler must be synchronized since it will be called
111 // concurrently from different goroutines (belonging to different client
112 // connections). See information about connection life cycle in library readme.
113 // This handler should not block – so do minimal work here, set required
114 // connection event handlers and return.
115 node.OnConnect(func(client *centrifuge.Client) {
116 // In our example transport will always be Websocket but it can also be SockJS.
117 transportName := client.Transport().Name()
118 // In our example clients connect with JSON protocol but it can also be Protobuf.
119 transportProto := client.Transport().Protocol()
120 log.Printf("client connected via %s (%s)", transportName, transportProto)
121
122 // Set SubscribeHandler to react on every channel subscription attempt
123 // initiated by a client. Here you can theoretically return an error or
124 // disconnect a client from a server if needed. But here we just accept
125 // all subscriptions to all channels. In real life you may use a more
126 // complex permission check here. The reason why we use callback style
127 // inside client event handlers is that it gives a possibility to control
128 // operation concurrency to developer and still control order of events.
129 client.OnSubscribe(func(e centrifuge.SubscribeEvent, cb centrifuge.SubscribeCallback) {
130 log.Printf("client subscribes on channel %s", e.Channel)
131 cb(centrifuge.SubscribeReply{}, nil)
132 })
133
134 // By default, clients can not publish messages into channels. By setting
135 // PublishHandler we tell Centrifuge that publish from a client-side is
136 // possible. Now each time client calls publish method this handler will be
137 // called and you have a possibility to validate publication request. After
138 // returning from this handler Publication will be published to a channel and
139 // reach active subscribers with at most once delivery guarantee. In our simple
140 // chat app we allow everyone to publish into any channel but in real case
141 // you may have more validation.
142 client.OnPublish(func(e centrifuge.PublishEvent, cb centrifuge.PublishCallback) {
143 log.Printf("client publishes into channel %s: %s", e.Channel, string(e.Data))
144 cb(centrifuge.PublishReply{}, nil)
145 })
146
147 // Set Disconnect handler to react on client disconnect events.
148 client.OnDisconnect(func(e centrifuge.DisconnectEvent) {
149 log.Printf("client disconnected")
150 })
151 })
152
153 // Run node. This method does not block. See also node.Shutdown method
154 // to finish application gracefully.
155 if err := node.Run(); err != nil {
156 log.Fatal(err)
157 }
158
159 // Now configure HTTP routes.
160
161 // Serve Websocket connections using WebsocketHandler.
162 wsHandler := centrifuge.NewWebsocketHandler(node, centrifuge.WebsocketConfig{})
163 http.Handle("/connection/websocket", auth(wsHandler))
164
165 // The second route is for serving index.html file.
166 http.Handle("/", http.FileServer(http.Dir("./")))
167
168 log.Printf("Starting server, visit http://localhost:8000")
169 if err := http.ListenAndServe(":8000", nil); err != nil {
170 log.Fatal(err)
171 }
172 }
173 ```
174
175 Also create file `index.html` near `main.go` with content:
176
177 ```html
178 <!DOCTYPE html>
179 <html lang="en">
180 <head>
181 <meta charset="utf-8">
182 <script type="text/javascript" src="https://rawgit.com/centrifugal/centrifuge-js/master/dist/centrifuge.min.js"></script>
183 <title>Centrifuge library chat example</title>
184 </head>
185 <body>
186 <input type="text" id="input" />
187 <script type="text/javascript">
188 // Create Centrifuge object with Websocket endpoint address set in main.go
189 const centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket');
190 function drawText(text) {
191 const div = document.createElement('div');
192 div.innerHTML = text + '<br>';
193 document.body.appendChild(div);
194 }
195 centrifuge.on('connect', function(ctx){
196 drawText('Connected over ' + ctx.transport);
197 });
198 centrifuge.on('disconnect', function(ctx){
199 drawText('Disconnected: ' + ctx.reason);
200 });
201 const sub = centrifuge.subscribe("chat", function(ctx) {
202 drawText(JSON.stringify(ctx.data));
203 })
204 const input = document.getElementById("input");
205 input.addEventListener('keyup', function(e) {
206 if (e.keyCode === 13) {
207 sub.publish(this.value);
208 input.value = '';
209 }
210 });
211 // After setting event handlers – initiate actual connection with server.
212 centrifuge.connect();
213 </script>
214 </body>
215 </html>
216 ```
217
218 Then run as usual:
219
220 ```bash
221 go run main.go
222 ```
223
224 Open several browser tabs with http://localhost:8000 and see chat in action.
225
226 This example is only the top of an iceberg. Though it should give you an insight on library API.
227
228 Keep in mind that Centrifuge library is not a framework to build chat apps. 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.
229
230 ### Tips and tricks
231
232 Some useful advices about library here.
233
234 #### Connection life cycle
235
236 Let's describe some aspects related to connection life cycle and event handling in Centrifuge:
237
238 * If you set middleware for transport handlers (`WebsocketHandler`, `SockjsHandler`) – 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.
239 * `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`.
240 * `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.
241 * 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`.
242 * Other handlers like `OnAlive`, `OnDisconnect`, server-side `OnSubRefresh`, server-side `OnRefresh` called from separate internal goroutines.
243 * `OnAlive` handler must not be called after `OnDisconnect`.
244 * Client initiated request handlers can be processed asynchronously in goroutines to manage operation concurrency. This is achieved using callback functions. See [concurrency](https://github.com/centrifugal/centrifuge/tree/master/_examples/concurrency) example for more details.
245
246 #### Channel history stream
247
248 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.
249
250 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.
251
252 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.
253
254 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.
255
256 #### Logging
257
258 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.
259
260 ```go
261 // Function to handle Centrifuge internal logs.
262 func handleLog(e centrifuge.LogEntry) {
263 log.Printf("%s: %v", e.Message, e.Fields)
264 }
265
266 cfg := centrifuge.DefaultConfig
267 cfg.LogLevel = centrifuge.LogLevelDebug
268 cfg.LogHandler = handleLog
269 ```