centrifuge 2.8.5 → 3.0.0-beta.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (69) hide show
  1. package/README.md +348 -661
  2. package/build/centrifuge.d.ts +156 -0
  3. package/build/centrifuge.js +1526 -0
  4. package/build/centrifuge.js.map +1 -0
  5. package/build/codes.d.ts +35 -0
  6. package/build/codes.js +39 -0
  7. package/build/codes.js.map +1 -0
  8. package/build/index.d.ts +4 -0
  9. package/build/index.js +10 -0
  10. package/build/index.js.map +1 -0
  11. package/build/json.d.ts +1 -0
  12. package/build/json.js +18 -0
  13. package/build/json.js.map +1 -0
  14. package/build/protobuf/client.proto.json +791 -0
  15. package/build/protobuf/index.d.ts +18 -0
  16. package/build/protobuf/index.js +64 -0
  17. package/build/protobuf/index.js.map +1 -0
  18. package/build/subscription.d.ts +82 -0
  19. package/build/subscription.js +575 -0
  20. package/build/subscription.js.map +1 -0
  21. package/build/transport_http_stream.d.ts +1 -0
  22. package/build/transport_http_stream.js +207 -0
  23. package/build/transport_http_stream.js.map +1 -0
  24. package/build/transport_sockjs.d.ts +1 -0
  25. package/build/transport_sockjs.js +55 -0
  26. package/build/transport_sockjs.js.map +1 -0
  27. package/build/transport_sse.d.ts +1 -0
  28. package/build/transport_sse.js +95 -0
  29. package/build/transport_sse.js.map +1 -0
  30. package/build/transport_websocket.d.ts +1 -0
  31. package/build/transport_websocket.js +58 -0
  32. package/build/transport_websocket.js.map +1 -0
  33. package/build/types.d.ts +282 -0
  34. package/build/types.js +18 -0
  35. package/build/types.js.map +1 -0
  36. package/build/utils.d.ts +1 -0
  37. package/build/utils.js +52 -0
  38. package/build/utils.js.map +1 -0
  39. package/dist/centrifuge.js +5 -3564
  40. package/dist/centrifuge.js.map +7 -1
  41. package/dist/centrifuge.protobuf.js +8 -11394
  42. package/dist/centrifuge.protobuf.js.map +7 -1
  43. package/package.json +49 -34
  44. package/.babelrc +0 -4
  45. package/.editorconfig +0 -12
  46. package/.eslintrc +0 -179
  47. package/.gitattributes +0 -1
  48. package/.github/FUNDING.yml +0 -3
  49. package/.github/workflows/ci.yml +0 -23
  50. package/.github/workflows/release.yml +0 -24
  51. package/.nvmrc +0 -1
  52. package/CHANGELOG.md +0 -473
  53. package/dist/centrifuge.d.ts +0 -221
  54. package/dist/centrifuge.min.js +0 -2
  55. package/dist/centrifuge.min.js.map +0 -1
  56. package/dist/centrifuge.protobuf.d.ts +0 -3
  57. package/dist/centrifuge.protobuf.min.js +0 -2
  58. package/dist/centrifuge.protobuf.min.js.map +0 -1
  59. package/make-proto +0 -3
  60. package/src/centrifuge.js +0 -1918
  61. package/src/client.proto.json +0 -577
  62. package/src/index.js +0 -2
  63. package/src/index_protobuf.js +0 -2
  64. package/src/json.js +0 -48
  65. package/src/protobuf.js +0 -257
  66. package/src/subscription.js +0 -281
  67. package/src/utils.js +0 -40
  68. package/test/index.spec.js +0 -47
  69. package/webpack.config.js +0 -52
package/README.md CHANGED
@@ -1,33 +1,38 @@
1
- # Centrifuge client for NodeJS and browser
1
+ # Centrifuge and Centrifugo bidirectional SDK for NodeJS, React-Native and browser
2
2
 
3
- This client can connect to [Centrifuge](https://github.com/centrifugal/centrifuge) server (and [Centrifugo](https://github.com/centrifugal/centrifugo) in particular) using pure WebSocket or [SockJS](https://github.com/sockjs/sockjs-client) polyfill transports from web browser or NodeJS environments.
3
+ This SDK provides a client to connect to [Centrifugo](https://github.com/centrifugal/centrifugo) or any [Centrifuge-based](https://github.com/centrifugal/centrifuge) server using pure WebSocket or one of the fallback transports from web browser, ReactNative, or NodeJS environments.
4
4
 
5
- * [Install and quick start](#install-and-quick-start)
6
- * [Connection Token](#connection-token)
7
- * [Configuration parameters](#configuration-parameters)
5
+ The client behaves according to a common [Centrifigo SDK spec](https://centrifugal.dev/docs/transports/client_api). It's recommended to read that before starting to work with this SDK as the spec covers common SDK behavior - describes client and subscription state transitions, main options and methods. Then proceed with this readme for more specifics about `centrifuge-js`.
6
+
7
+ * [Install](#install)
8
+ * [Quick start](#quick-start)
9
+ * [WebSocket transport](#websocket-transport)
10
+ * [Using fallbacks](#using-fallbacks)
11
+ * [SockJS](#using-fallbacks)
12
+ * [Bidirectional emulation](#bidirectional-emulation)
8
13
  * [Client API](#client-api)
9
- * [Private channels subscription](#private-channels-subscription)
14
+ * [Client methods and events](#client-methods-and-events)
15
+ * [Connection token](#connection-token)
16
+ * [Subscription API](#subscription-api)
17
+ * [Subscription methods and events](#client-methods-and-events)
18
+ * [Subscription token](#connection-token)
19
+ * [Message batching](#message-batching)
10
20
  * [Server-side subscriptions](#server-side-subscriptions)
11
- * [Connection expiration](#connection-expiration)
21
+ * [Configuration parameters](#configuration-parameters)
12
22
  * [Protobuf support](#protobuf-support)
13
23
  * [Browser support](#browser-support)
14
24
  * [Using with NodeJS](#using-with-nodejs)
15
- * [Custom XMLHttpRequest](#custom-xmlhttprequest)
16
25
  * [Custom WebSocket constructor](#custom-websocket-constructor)
17
- * [Subscribe since known position](#subscribe-since-known-position)
18
- * [Feature Matrix](#feature-matrix)
19
26
 
20
- ## Install and quick start
27
+ ## Install
21
28
 
22
- The simplest way is to include `centrifuge-js` into your web page using `script` tag. For example, from CDN (replace `X` to concrete version number):
29
+ Using cdn (replace `X` to a concrete version number):
23
30
 
24
31
  ```html
25
- <script src="https://cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@2.X.X/dist/centrifuge.min.js"></script>
32
+ <script src="https://cdn.jsdelivr.net/gh/centrifugal/centrifuge-js@3.X.X/dist/centrifuge.min.js"></script>
26
33
  ```
27
34
 
28
- Or check out [centrifuge-js on cdnjs.com](https://cdnjs.com/libraries/centrifuge).
29
-
30
- Client is also available via `npm`:
35
+ Also available via `npm`:
31
36
 
32
37
  ```bash
33
38
  npm install centrifuge
@@ -36,274 +41,170 @@ npm install centrifuge
36
41
  And then:
37
42
 
38
43
  ```javascript
39
- var Centrifuge = require("centrifuge");
40
- ```
41
-
42
- Default library works with JSON only, see `Protobuf support` section to see how to import client with Protobuf support.
43
-
44
- As soon as you installed and imported `centrifuge-js` you can create new `Centrifuge` object instance, subscribe on channel and call `.connect()` method to make actual connection to server:
45
-
46
- ```javascript
47
- var centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
48
-
49
- centrifuge.subscribe("news", function(message) {
50
- console.log(message);
51
- });
52
-
53
- centrifuge.connect();
54
- ```
55
-
56
- In example above we initialize `Centrifuge` object instance, subscribe on channel `news`, print all new messages received from channel `news` into console and actually make connection to server. And that's all for basic real-time messaging on client side!
57
-
58
- If you want to use SockJS you must also import SockJS client before centrifuge.js
59
-
60
- ```html
61
- <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.3/dist/sockjs.min.js" type="text/javascript"></script>
62
- <script src="centrifuge.js" type="text/javascript"></script>
63
- ```
64
-
65
- Or provide it explicitly:
66
-
67
- ```javascript
68
- var Centrifuge = require("centrifuge");
69
- var SockJS = require('sockjs-client');
70
-
71
- var centrifuge = new Centrifuge("http://localhost:8000/connection/sockjs", {
72
- sockjs: SockJS
73
- })
44
+ import { Centrifuge } from 'centrifuge';
74
45
  ```
75
46
 
76
- **`Centrifuge` object is an instance of [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).**
47
+ By default, library works with JSON only, see [Protobuf support](#protobuf-support) section to see how to import client with Protobuf support.
77
48
 
78
- ## Connection Token
49
+ ## Quick start
79
50
 
80
- If you are connecting to Centrifugo **you must also provide connection token**:
51
+ The basic usage example may look like this:
81
52
 
82
53
  ```javascript
83
- var centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
54
+ // Use WebSocket transport endpoint.
55
+ const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
84
56
 
85
- centrifuge.setToken(YOUR_TOKEN);
57
+ // Allocate Subscription to a channel.
58
+ const sub = centrifuge.newSubscription('news');
86
59
 
87
- centrifuge.subscribe("news", function(message) {
88
- console.log(message);
60
+ // React on `news` channel real-time publications.
61
+ sub.on('publication', function(ctx) {
62
+ console.log(ctx.data);
89
63
  });
90
64
 
65
+ // Trigger subscribe process.
66
+ sub.subscribe();
67
+
68
+ // Trigger actual connection establishement.
91
69
  centrifuge.connect();
92
70
  ```
93
71
 
94
- This token contains information about user of your application that tries to connect. See [server authentication documentation](https://centrifugal.github.io/centrifugo/server/authentication/) for details on how to generate it on your backend side.
72
+ Note, that we explicitly call `.connect()` method to initiate connection establishement with a server and `.subscribe()` method to move Subscription to `subsribing` state (which should transform into `subscribed` state soon after connection with a server is established). The order of `.connect()` and `.subscribe` calls does not actually matter here.
95
73
 
96
- **Connection JWT comes to Javascript code from application backend - i.e. must be generated on backend**.
74
+ **`Centrifuge` object and `Subscription` object are both instances of [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).** Below we will describe events that can be exposed in detail.
97
75
 
98
- ## Configuration parameters
76
+ ## Websocket transport
99
77
 
100
- Let's also look at optional configuration parameters available when initializing `Centrifuge` object instance.
78
+ WebSocket is the main protocol used by `centrifuge-js` to communicate with a server. In browser environment it's available globally, but if you want to connect from NodeJS env – then you need to provide WebSocket constructor to `centrifuge-js` explicitly. [See below](#using-with-nodejs) more information about this.
101
79
 
102
- #### websocket
80
+ ## Using fallbacks
103
81
 
104
- `websocket` option allows to explicitly provide custom WebSocket client to use. By default centrifuge-js will try to use global WebSocket object, so if you are in web browser – it will just use native WebSocket implementation. See notes about using `centrifuge-js` with NodeJS below.
82
+ In the quick start example above we used WebSocket endpoint to configure Centrifuge. WebSocket is the main transport – it's bidirectional out of the box.
105
83
 
106
- #### sockjs
84
+ In some cases though, WebSocket connection may not be established (for example, due to corporate firewalls and proxies). For such situations `centrifuge-js` offers several WebSocket fallback options.
107
85
 
108
- `sockjs` option allows to explicitly provide SockJS client object to Centrifuge client.
86
+ ### Using SockJS
109
87
 
110
- For example this can be useful if you develop in ES6 with imports:
111
-
112
- ```javascript
113
- import Centrifuge from 'centrifuge'
114
- import SockJS from 'sockjs-client'
88
+ If you want to use SockJS you must also import SockJS client before centrifuge.js
115
89
 
116
- var centrifuge = new Centrifuge('https://centrifuge.example.com/connection/sockjs', {
117
- sockjs: SockJS
118
- });
90
+ ```html
91
+ <script src="https://cdn.jsdelivr.net/npm/sockjs-client@1.3/dist/sockjs.min.js" type="text/javascript"></script>
92
+ <script src="centrifuge.js" type="text/javascript"></script>
119
93
  ```
120
94
 
121
- #### sockjsTransports
122
-
123
- In case of using SockJS additional configuration parameter can be used - `sockjsTransports`.
124
-
125
- It defines allowed SockJS transports and by default equals
95
+ Or provide it explicitly as a dependency:
126
96
 
127
97
  ```javascript
128
- var centrifuge = new Centrifuge(
129
- 'http://centrifuge.example.com/connection/sockjs',
130
- {
131
- sockjsTransports: [
132
- 'websocket',
133
- 'xdr-streaming',
134
- 'xhr-streaming',
135
- 'eventsource',
136
- 'iframe-eventsource',
137
- 'iframe-htmlfile',
138
- 'xdr-polling',
139
- 'xhr-polling',
140
- 'iframe-xhr-polling',
141
- 'jsonp-polling'
142
- ]
143
- });
144
- ```
145
-
146
- i.e. all possible SockJS transports.
147
-
148
- So to say `centrifuge-js` to use only `websocket` and `xhr-streaming` transports when
149
- using SockJS endpoint:
98
+ import { Centrifuge } from 'centrifuge'
99
+ import SockJS from 'sockjs-client'
150
100
 
151
- ```javascript
152
- var centrifuge = new Centrifuge('http://centrifuge.example.com/connection/sockjs', {
153
- sockjsTransports: ["websocket", "xhr-streaming"]
154
- });
101
+ const centrifuge = new Centrifuge("http://localhost:8000/connection/sockjs", {
102
+ sockjs: SockJS
103
+ })
155
104
  ```
156
105
 
157
- #### sockjsServer
158
-
159
- `sockjsServer` is SockJS specific option to set server name into connection urls instead
160
- of random chars. See SockJS docs for more info.
161
-
162
- #### debug
163
-
164
- `debug` is a boolean option which is `false` by default. When enabled lots of various debug
165
- messages will be logged into javascript console. Mostly useful for development or
166
- troubleshooting.
167
-
168
- #### minRetry
169
-
170
- When client disconnected from server it will automatically try to reconnect using exponential
171
- backoff algorithm to get interval between reconnect attempts which value grows exponentially.
172
- `minRetry` option sets minimal interval value in milliseconds. Default is `1000` milliseconds.
173
-
174
- #### maxRetry
175
-
176
- `maxRetry` sets upper interval value limit when reconnecting. Or your clients will never reconnect
177
- as exponent grows very fast:) Default is `20000` milliseconds.
106
+ Note, that in SockJS case endpoint starts with `http://`, not with `ws://` as we used above when connecting to a pure WebSocket endpoint.
178
107
 
179
- #### subscribeEndpoint
108
+ ### Bidirectional emulation
180
109
 
181
- `subscribeEndpoint` is url to use when sending auth request for authorizing subscription on private channel. By default `/centrifuge/subscribe`. See also useful related options:
110
+ SockJS is robust and stable product, but it's an extra dependency, it's pretty old, comes with some overhead and sticky sessions requirement for a distributed backend case. In most scenarios these days clients are fine to use WebSocket protocol for messaging. There are rare connection issues though which are caused by corporate firewall and proxy software. To deal with users behind such proxies Centrifuge SDK offers its own bidirectional emulation layer. This layer uses two HTTP-based transports:
182
111
 
183
- * `subscribeHeaders` - map of headers to send with subscribe request (default `{}`)
184
- * `subscribeParams` - map of params to include in subscribe endpoint url (default `{}`)
112
+ * HTTP-streaming based on ReadableStream API
113
+ * SSE (EventSource).
185
114
 
186
- #### refreshEndpoint
187
-
188
- `refreshEndpoint` is url to use when refreshing client connection parameters when connection check mechanism enabled in Centrifugo configuration. See also related options:
189
-
190
- * `refreshHeaders` - map of headers to send with refresh request (default `{}`)
191
- * `refreshParams` - map of params to include in refresh url (default `{}`)
192
- * `refreshData` - send extra data in body (as JSON payload) when sending AJAX POST refresh request.
193
- * `refreshAttempts` - limit amount of refresh requests before giving up (by default `null` - unlimited)
194
- * `onRefreshFailed` - callback function called when `refreshAttempts` came to the end. By default `null` - i.e. nothing called.
195
- * `onRefresh` - optional callback to fully control refresh behaviour. This function will ve called as soon as connection token needs to be refreshed. After this it's up to application to get new token in a way it needs. As soon as application got token it must call callback passed as argument with proper data - see example below. *In this case `centrifuge-js` will not send automatic AJAX requests to your application*.
196
-
197
- Here is an example of using custom `onRefresh` function:
115
+ Bidirectional emulation must be first enabled on a server-side. For example, see Centrifugo docs to find out how. Then in Javascript you can slightly change client initialization and point it to a list of endpoints and transports you want to use:
198
116
 
199
117
  ```javascript
200
- centrifuge = new Centrifuge("http://localhost:8000/connection/websocket", {
201
- debug: true,
202
- onRefresh: function(ctx, cb) {
203
- let promise = fetch("http://localhost:3000/centrifuge/refresh", {
204
- method: "POST"
205
- }).then(function(resp) {
206
- resp.json().then(function(data) {
207
- // Data must be like {"status": 200, "data": {"token": "JWT"}} - see
208
- // type definitions in dist folder. Note that setting status to 200 is
209
- // required at moment. Any other status will result in refresh process
210
- // failure so client will eventually be disconnected by server.
211
- cb(data);
212
- });
213
- });
118
+ const transports = [
119
+ {
120
+ transport: 'websocket',
121
+ endpoint: 'ws://example.com/connection/websocket'
122
+ },
123
+ {
124
+ transport: 'http_stream',
125
+ endpoint: 'http://example.com/connection/http_stream'
126
+ },
127
+ {
128
+ transport: 'sse',
129
+ endpoint: 'http://example.com/connection/sse'
214
130
  }
215
- });
131
+ ];
132
+ const centrifuge = new Centrifuge(transports);
133
+ centrifuge.connect()
216
134
  ```
217
135
 
218
- #### disableWithCredentials
136
+ In this case, client will try transports in order, one by one, during the initial handshake. Until success. Then will only use a successful transport during reconnects.
137
+
138
+ Supported transports are:
219
139
 
220
- `disableWithCredentials` is a reverse boolean option for control
221
- [withCredentials](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/withCredentials)
222
- property of XMLHttpRequest. By default `false` - i.e. `withCredentials` property is enabled.
140
+ * `websocket`
141
+ * `http_stream`
142
+ * `sse`
143
+ * `sockjs` (yes, SockJS can also be used as a fallback in the bidirectional emulation layer, but sticky session must be used on the backend in distributed case).
223
144
 
224
145
  ## Client API
225
146
 
226
- When `Centrifuge` object properly initialized then it is ready to start communicating with server.
147
+ Let's look at top-level API of `Centrifuge` client.
148
+
149
+ ### Client methods and events
227
150
 
228
151
  #### connect method
229
152
 
230
- As we showed before, we must call `connect()` method to make an actual connection
153
+ As we already showed above, we must call `connect()` method to make an actual connection
231
154
  request to Centrifugo server:
232
155
 
233
156
  ```javascript
234
- var centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
235
-
157
+ const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
236
158
  centrifuge.connect();
237
159
  ```
238
160
 
239
161
  `connect()` triggers an actual connection request to server.
240
162
 
241
- #### connect event
163
+ #### connected event
242
164
 
243
- After connection will be established and client credentials you provided authorized
244
- then `connect` event on `Centrifuge` object instance will be called.
165
+ As soon as connection is established and client successfully authenticated `connected` event on `Centrifuge` object instance will be called.
245
166
 
246
- You can listen to this setting event listener function on `connect` event:
167
+ It's possible to listen to this event by setting event listener function on `connected` event:
247
168
 
248
169
  ```javascript
249
- centrifuge.on('connect', function(context) {
250
- // now client connected to Centrifugo and authorized
170
+ centrifuge.on('connected', function(ctx) {
171
+ // now client connected to Centrifugo and authenticated.
251
172
  });
252
173
  ```
253
174
 
254
- What's in `context`:
175
+ #### connecting event
176
+
177
+ `connecting` event fired when Centrifuge object goes to connecting state. This may be called during initial connect, or after being `connected` due to temporary connection loss.
255
178
 
256
179
  ```javascript
257
- {
258
- client: "79ec54fa-8348-4671-650b-d299c193a8a3",
259
- transport: "raw-websocket",
260
- latency: 21
261
- }
180
+ centrifuge.on('connecting', function(ctx) {
181
+ // do whatever you need in case of connecting to a server
182
+ });
262
183
  ```
263
184
 
264
- * `client` – client ID Centrifugo gave to this connection (string)
265
- * `transport` – name of transport used to establish connection with server (string)
266
- * `latency` – latency in milliseconds (int). This measures time passed between sending
267
- `connect` client protocol command and receiving connect response.
268
-
269
- #### disconnect event
185
+ #### disconnected event
270
186
 
271
- `disconnect` event fired on centrifuge object every time client disconnects for
272
- some reason. This can be network disconnect or disconnect initiated by Centrifugo server.
187
+ `disconnected` event fired on Centrifuge object every time client disconnects for some reason. This can be terminal disconnect due to advice from a server or disconnect initiated by client-side.
273
188
 
274
189
  ```javascript
275
- centrifuge.on('disconnect', function(context) {
190
+ centrifuge.on('disconnected', function(ctx) {
276
191
  // do whatever you need in case of disconnect from server
277
192
  });
278
193
  ```
279
194
 
280
- What's in `context`?
281
-
282
- ```javascript
283
- {
284
- reason: "connection closed",
285
- reconnect: true
286
- }
287
- ```
288
-
289
- * `reason` – the reason of client's disconnect (string)
290
- * `reconnect` – flag indicating if client will reconnect or not (boolean)
291
-
292
195
  #### disconnect method
293
196
 
294
- In some cases you may need to disconnect your client from server, use `disconnect` method to
295
- do this:
197
+ In some cases you may need to disconnect your client from server, use `.disconnect()` method to do this:
296
198
 
297
199
  ```javascript
298
200
  centrifuge.disconnect();
299
201
  ```
300
202
 
301
- After calling this client will not try to reestablish connection periodically. You must call
302
- `connect` method manually again.
203
+ After calling this client will not try to reestablish connection periodically. You must call `.connect()` method manually again.
303
204
 
304
205
  #### publish method
305
206
 
306
- Sometimes you need to publish into channel with `publish` option set to `true` without actually being subscribed to it. In this case you can use `publish` method:
207
+ Sometimes you need to publish into channel without actually being subscribed to it. In this case you can use `publish` method:
307
208
 
308
209
  ```javascript
309
210
  centrifuge.publish("channel", {"input": "hello"}).then(function(res) {
@@ -315,7 +216,7 @@ centrifuge.publish("channel", {"input": "hello"}).then(function(res) {
315
216
 
316
217
  #### send method
317
218
 
318
- This is only valid for Centrifuge library and does not work for Centrifugo server. `send` method allows to send asynchronous message from client to server.
219
+ This is only valid for Centrifuge library and does not work for Centrifugo server at the moment. `send` method allows sending asynchronous message from a client to a server.
319
220
 
320
221
  ```javascript
321
222
  centrifuge.send({"input": "hello"}).then(function(res) {
@@ -327,22 +228,10 @@ centrifuge.send({"input": "hello"}).then(function(res) {
327
228
 
328
229
  #### rpc method
329
230
 
330
- `rpc` method allows to send RPC request from client to server and wait for data response.
231
+ `rpc` method allows to send rpc request from client to server and wait for data response.
331
232
 
332
233
  ```javascript
333
- centrifuge.rpc({"input": "hello"}).then(function(res) {
334
- console.log('rpc result', res);
335
- }, function(err) {
336
- console.log('rpc error', err);
337
- });
338
- ```
339
-
340
- #### namedRPC method
341
-
342
- `namedRPC` method allows to send rpc request from client to server and wait for data response. Unlike `rpc` it additionally allows to provide method name string (which can be handy to have on RPC request top level).
343
-
344
- ```javascript
345
- centrifuge.namedRPC("my.method.name", {"input": "hello"}).then(function(res) {
234
+ centrifuge.rpc("my.method.name", {"input": "hello"}).then(function(res) {
346
235
  console.log('rpc result', res);
347
236
  }, function(err) {
348
237
  console.log('rpc error', err);
@@ -351,8 +240,6 @@ centrifuge.namedRPC("my.method.name", {"input": "hello"}).then(function(res) {
351
240
 
352
241
  #### history method
353
242
 
354
- Available since v2.7.0
355
-
356
243
  Allows to get history from a server. This is a top-level analogue of `Subscription.history` method. But accepts a channel as first argument.
357
244
 
358
245
  ```javascript
@@ -365,8 +252,6 @@ centrifuge.history("channel", {since: {offset: 0, epoch: "xyz"}, limit: 10}).the
365
252
 
366
253
  #### presence method
367
254
 
368
- Available since v2.7.0
369
-
370
255
  Allows to get presence info from a server. This is a top-level analogue of `Subscription.presence` method. But accepts a channel as first argument.
371
256
 
372
257
  ```javascript
@@ -379,8 +264,6 @@ centrifuge.presence("channel").then(function(resp) {
379
264
 
380
265
  #### presenceStats method
381
266
 
382
- Available since v2.7.0
383
-
384
267
  Allows to get presence stats from a server. This is a top-level analogue of `Subscription.presenceStats` method. But accepts a channel as first argument.
385
268
 
386
269
  ```javascript
@@ -391,243 +274,139 @@ centrifuge.presenceStats("channel").then(function(resp) {
391
274
  });
392
275
  ```
393
276
 
394
- ### setConnectData method
395
-
396
- Allows setting custom data sent to a server in first message. This data will be available on a server side in OnConnecting callback (if using Centrifugo library) or proxied to application backend (in using Centrifugo with connect proxy enabled).
397
-
398
- ```
399
- centrifuge.setConnectData({"any": "key"});
400
- ```
401
-
402
- ## Subscriptions
277
+ #### ready method
403
278
 
404
- Of course being just connected is useless. What we usually want from Centrifugo is to
405
- receive new messages published into channels. So our next step is `subscribe` on channel
406
- from which we want to receive real-time messages.
279
+ Returns a Promise which will be resolved upon connection establishement (i.e. when Client goes to `connected` state).
407
280
 
408
- ### subscribe method
281
+ #### error event
409
282
 
410
- To subscribe on channel we must use `subscribe` method of `Centrifuge` object instance.
411
-
412
- The simplest usage that allow to subscribe on channel and listen to new messages is:
283
+ To listen asynchronous error happening internally while Centrifuge client works you can set an `error` handler:
413
284
 
414
285
  ```javascript
415
- var subscription = centrifuge.subscribe("news", function(message) {
416
- // handle new message coming from channel "news"
417
- console.log(message);
418
- });
419
- ```
420
-
421
- And that's all! For lots of cases it's enough! But let's look at possible events that
422
- can happen with subscription:
423
-
424
- * `publish` – called when new publication message received (callback function in our previous example is `publish` event callback btw)
425
- * `join` – called when someone joined channel
426
- * `leave` – called when someone left channel
427
- * `subscribe` – called when subscription on channel successful and acknowledged by Centrifugo
428
- server. It can be called several times during lifetime as browser client automatically resubscribes on channels after successful reconnect (caused by temporary network disconnect for example or Centrifugo server restart)
429
- * `error` – called when subscription on channel failed with error. It can be called several times
430
- during lifetime as browser client automatically resubscribes on channels after successful reconnect
431
- (caused by temporary network disconnect for example or Centrifugo server restart)
432
- * `unsubscribe` – called every time subscription that was successfully subscribed
433
- unsubscribes from channel (can be caused by network disconnect or by calling
434
- `unsubscribe` method of subscription object)
286
+ const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket');
435
287
 
436
- Don't be frightened by amount of events available. In most cases you only need some of them
437
- until you need full control to what happens with your subscriptions. We will look at format
438
- of messages for this event callbacks later below.
439
-
440
- There are 2 ways setting callback functions for events above.
441
-
442
- First is providing object containing event callbacks as second argument to `subscribe` method.
443
-
444
- ```javascript
445
- var callbacks = {
446
- "publish": function(message) {
447
- // See below description of message format
448
- console.log(message);
449
- },
450
- "join": function(message) {
451
- // See below description of join message format
452
- console.log(message);
453
- },
454
- "leave": function(message) {
455
- // See below description of leave message format
456
- console.log(message);
457
- },
458
- "subscribe": function(context) {
459
- // See below description of subscribe callback context format
460
- console.log(context);
461
- },
462
- "error": function(errContext) {
463
- // See below description of subscribe error callback context format
464
- console.log(err);
465
- },
466
- "unsubscribe": function(context) {
467
- // See below description of unsubscribe event callback context format
468
- console.log(context);
469
- }
470
- }
471
-
472
- var subscription = centrifuge.subscribe("news", callbacks);
473
- ```
474
-
475
- Another way is setting callbacks using `on` method of subscription. Subscription object
476
- is event emitter so you can simply do the following:
477
-
478
- ```javascript
479
- var subscription = centrifuge.subscribe("news");
480
-
481
- subscription.on("publish", publishHandlerFunction);
482
- subscription.on("subscribe", subscribeHandlerFunction);
483
- subscription.on("error", subscribeErrorHandlerFunction);
288
+ centrifuge.on('error', function(ctx) {
289
+ console.log(ctx);
290
+ });
484
291
  ```
485
292
 
486
- **`Subscription` objects are instances of [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).**
293
+ This can help you to log failed connection attempts, or token refresh errors, etc.
487
294
 
488
- ### join and leave events of subscription
295
+ ### Connection Token
489
296
 
490
- As you know you can enable `join_leave` option for channel in Centrifugo configuration.
491
- This gives you an opportunity to listen to `join` and `leave` events in those channels.
492
- Just set event handlers on `join` and `leave` events of subscription.
297
+ Depending on authentication scheme used by a server you may also want to provide connection token:
493
298
 
494
299
  ```javascript
495
- var subscription = centrifuge.subscribe("news", function(message) {
496
- // handle message
497
- }).on("join", function(message) {
498
- console.log("Client joined channel", message);
499
- }).on("leave", function(message) {
500
- console.log("Client left channel", message);
300
+ const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket', {
301
+ token: '<CONNECTION_TOKEN>'
501
302
  });
502
303
  ```
503
304
 
504
- *Note, that in order join/leave events to work corresponding options must be enabled in server channel configuration (on top level or for channel namespace)*
505
-
506
- ### subscription event context formats
305
+ In case of Centrifugo on a server side this may be a JSON Web Token - see [authentication documentation](https://centrifugal.github.io/centrifugo/server/authentication/) for details on how to generate it on your backend side.
507
306
 
508
- We already know how to listen for events on subscription. Let's look at format of
509
- messages event callback functions receive as arguments.
307
+ **Connection token must come to the frontend from application backend - i.e. must be generated on the backend side**. The way to deliver token to the application frontend is up to the developer. Usually you can pass it in template rendering context or issue a separate call to request a connection token from the backend.
510
308
 
511
- #### format of message event context
309
+ If the token sets connection expiration then the client SDK will keep the token refreshed. It does this by calling a special callback function. This callback must return a new token. If a new token with updated connection expiration is returned from callback then it's sent to Centrifugo. If your callback returns an empty string – this means the user has no permission to connect to Centrifugo and the Client will move to a disconnected state. In case of error returned by your callback SDK will retry the operation after some jittered time.
512
310
 
513
- Let's look at message format of new message received from channel:
311
+ An example of possible `getToken` function implementation:
514
312
 
515
313
  ```javascript
516
- {
517
- "data":{"input":"hello"},
314
+ function getToken(url, ctx) {
315
+ return new Promise((resolve, reject) => {
316
+ fetch(url, {
317
+ method: 'POST',
318
+ headers: new Headers({ 'Content-Type': 'application/json' }),
319
+ body: JSON.stringify(ctx)
320
+ })
321
+ .then(res => {
322
+ if (!res.ok) {
323
+ throw new Error(`Unexpected status code ${res.status}`);
324
+ }
325
+ return res.json();
326
+ })
327
+ .then(data => {
328
+ resolve(data.token);
329
+ })
330
+ .catch(err => {
331
+ reject(err);
332
+ });
333
+ });
518
334
  }
519
- ```
520
-
521
- I.e. `data` field contains actual data that was published.
522
335
 
523
- Message can optionally contain additional client `info` in case when this message was published by javascript client directly using `publish` method (see details below):
524
-
525
- ```javascript
526
- {
527
- "info":{
528
- "user":"2694",
529
- "client":"7080fd2a-bd69-4f1f-6648-5f3ceba4b643",
530
- "conn_info":{"name":"Alexandr"},
531
- "chan_info":{"extra":"extra JSON data when authorizing private channel"}
532
- },
533
- "data":{"input":"hello"}
534
- }
336
+ const client = new Centrifuge(
337
+ 'ws://localhost:8000/connection/websocket',
338
+ {
339
+ token: 'JWT-GENERATED-ON-BACKEND-SIDE',
340
+ getToken: function (ctx) {
341
+ return getToken('/centrifuge/connection_token', ctx);
342
+ }
343
+ }
344
+ );
535
345
  ```
536
346
 
537
- #### format of join/leave event message
347
+ :::tip
538
348
 
539
- I.e. `on("join", function(message) {...})` or `on("leave", function(message) {...})`
349
+ If initial token is not provided, but `getToken` is specified then SDK assumes that developer wants to use token authentication. In this case SDK attempts to get a connection token before establishing an initial connection.
540
350
 
541
- ```javascript
542
- {
543
- "info":{
544
- "user":"2694",
545
- "client":"2724adea-6e9b-460b-4430-a9f999e94c36",
546
- "conn_info":{"first_name":"Alexandr"},
547
- "chan_info":{"extra":"extra JSON data when authorizing"}
548
- }
549
- }
550
- ```
351
+ :::
551
352
 
552
- `conn_info` and `chan_info` exist in message only if not empty.
353
+ ## Subscription API
553
354
 
554
- #### format of subscribe event context
355
+ What we usually want from Centrifugo is to receive new messages published into channels. To do this we must create `Subscription` object.
555
356
 
556
- I.e. `on("subscribe", function(context) {...})`
357
+ ### Subscription methods and events
557
358
 
558
- ```javascript
559
- {
560
- "channel": "$public:chat",
561
- "isResubscribe": true,
562
- "recovered": false
563
- }
564
- ```
359
+ #### Subscribe to a channel
565
360
 
566
- `isResubscribe` boolean flag showing if this was initial subscribe (`false`) or resubscribe (`true`)
567
- `recovered` – boolean flag that indicated whether missed messages were recovered on reconnect or not (recovery works according to Centrifugo channel configuration)
361
+ The simplest usage that allow to subscribe on channel and listen to new messages is:
568
362
 
569
- #### format of subscription error event context
363
+ ```javascript
364
+ const sub = centrifuge.newSubscription('example');
570
365
 
571
- I.e. `on("error", function(err) {...})`
366
+ sub.on('publication', function(ctx) {
367
+ // handle new Publication data coming from channel "news".
368
+ console.log(ctx.data);
369
+ });
572
370
 
573
- ```javascript
574
- {
575
- "error": "permission denied",
576
- "channel": "$public:chat",
577
- "isResubscribe": true
578
- }
371
+ sub.subscribe();
579
372
  ```
580
373
 
581
- `error` - error description
582
- `isResubscribe` – flag showing if this was initial subscribe (`false`) or resubscribe (`true`)
374
+ #### Subscription events
375
+
376
+ Some events which can be listened on Subscription object are:
583
377
 
584
- #### format of unsubscribe event context
378
+ * `publication` called when new publication received from a Subscription channel
379
+ * `join` – called when someone joined channel
380
+ * `leave` – called when someone left channel
381
+ * `subscribing` - called when Subscription goes to `subscribing` state (initial subscribe and re-subscribes)
382
+ * `subscribed` – called when Subscription goes to `subscribed` state
383
+ * `unsubscribed` – called when Subscription goes to `unsubscribed` state
384
+ * `error` – called when subscription on channel failed with error. It can be called several times
385
+ during lifetime as browser client automatically resubscribes on channels after successful reconnect
386
+ (caused by temporary network disconnect for example or Centrifugo server restart)
585
387
 
586
- I.e `on("unsubscribe", function(context) {...})`
388
+ Don't be frightened by amount of events available. In most cases you only need some of them until you need full control to what happens with your subscriptions.
587
389
 
588
- ```javascript
589
- {
590
- "channel": "$public:chat"
591
- }
592
- ```
390
+ **`Subscription` objects are instances of [EventEmitter](https://nodejs.org/api/events.html#events_class_eventemitter).**
593
391
 
594
- ### presence method of subscription
392
+ #### presence method of Subscription
595
393
 
596
394
  `presence` allows to get information about clients which are subscribed on channel at
597
395
  this moment. Note that this information is only available if `presence` option enabled
598
396
  in Centrifugo configuration for all channels or for channel namespace.
599
397
 
600
398
  ```javascript
601
- var subscription = centrifuge.subscribe("news", function(message) {
602
- // handle message
603
- });
399
+ const sub = centrifuge.newSubscription("news");
400
+ sub.subscribe()
604
401
 
605
- subscription.presence().then(function(message) {
606
- // presence data received
402
+ sub.presence().then(function(ctx) {
403
+ console.log(ctx.clients);
607
404
  }, function(err) {
608
405
  // presence call failed with error
609
406
  });
610
407
  ```
611
408
 
612
- `presence` is internally a promise that will be resolved with data or error only
613
- when subscription actually subscribed.
614
-
615
- Format of success callback `message`:
616
-
617
- ```javascript
618
- {
619
- "presence":{
620
- "2724adea-6e9b-460b-4430-a9f999e94c36": {
621
- "user":"2694",
622
- "client":"2724adea-6e9b-460b-4430-a9f999e94c36"
623
- },
624
- "d274505c-ce63-4e24-77cf-971fd8a59f00":{
625
- "user":"2694",
626
- "client":"d274505c-ce63-4e24-77cf-971fd8a59f00"
627
- }
628
- }
629
- }
630
- ```
409
+ `presence` is internally a promise that will be waiting for subscription subscribe success if required.
631
410
 
632
411
  As you can see presence data is a map where keys are client IDs and values are objects
633
412
  with client information.
@@ -636,8 +415,8 @@ Format of `err` in error callback:
636
415
 
637
416
  ```javascript
638
417
  {
639
- "code": 0,
640
- "message": "timeout"
418
+ "code": 108,
419
+ "message": "not available"
641
420
  }
642
421
  ```
643
422
 
@@ -646,68 +425,37 @@ Format of `err` in error callback:
646
425
 
647
426
  *Note, that in order presence to work corresponding options must be enabled in server channel configuration (on top level or for channel namespace)*
648
427
 
649
- ### presenceStats method of subscription
428
+ #### presenceStats method of subscription
650
429
 
651
430
  `presenceStats` allows to get two counters from a server: number of total clients currently subscribed and number of unique users currently subscribed. Note that this information is only available if `presence` option enabled in server configuration for a channel.
652
431
 
653
432
  ```javascript
654
- var subscription = centrifuge.subscribe("news", function(message) {
655
- // handle message
656
- });
657
-
658
- subscription.presenceStats().then(function(resp) {
659
- // presence stats data received
433
+ sub.presenceStats().then(function(ctx) {
434
+ console.log(ctx.numClients);
660
435
  }, function(err) {
661
436
  // presence stats call failed with error
662
437
  });
663
438
  ```
664
439
 
665
- ### history method of subscription
440
+ #### history method of subscription
666
441
 
667
- `history` method allows to get last messages published into channel. Note that history
668
- for channel must be configured in Centrifugo to be available for `history` calls from
669
- client.
442
+ `history` method allows to get last messages published into channel. Note that history for channel must be configured in Centrifugo to be available for `history` calls from client.
670
443
 
671
444
  ```javascript
672
- var subscription = centrifuge.subscribe("news", function(message) {
673
- // handle message
674
- });
675
-
676
- subscription.history().then(function(response) {
677
- // history messages received
445
+ sub.history({limit: 100}).then(function(ctx) {
446
+ console.log(ctx.publications);
678
447
  }, function(err) {
679
448
  // history call failed with error
680
449
  });
681
450
  ```
682
451
 
683
- Success callback `response` format:
684
-
685
- ```javascript
686
- {
687
- "publications": [
688
- {
689
- "data": {"input": "hello2"},
690
- "offset": 1
691
- },
692
- {
693
- "data": {"input": "hello1"},
694
- "offset": 2
695
- }
696
- ],
697
- "offset": 2,
698
- "epoch": "xcf4w"
699
- }
700
- ```
701
-
702
- Where `publications` is an array of messages published into channel, `offset` is a current stream top offset (added in v2.7.0), `epoch` is a current stream epoch (added in v2.7.0).
703
-
704
- Note that also additional fields can be included in publication objects - `client`, `info` if those fields were set in original publications.
705
-
706
- `err` format – the same as for `presence` method.
707
-
708
452
  *Note, that in order history to work corresponding options must be enabled in server channel configuration (on top level or for channel namespace)*
709
453
 
710
- Starting from v2.7.0 it's possible to iterate over history stream:
454
+ Some history options available:
455
+
456
+ * `limit` (number)
457
+ * `since` (StreamPosition)
458
+ * `reverse` (boolean)
711
459
 
712
460
  ```javascript
713
461
  resp = await subscription.history({'since': {'offset': 2, 'epoch': 'xcf4w'}, limit: 100});
@@ -723,22 +471,16 @@ resp = await subscription.history({limit: 0});
723
471
 
724
472
  I.e. not providing `since` and using zero `limit`.
725
473
 
726
- **For now history pagination feature only works with [Centrifuge](https://github.com/centrifugal/centrifuge) library based server and not available in Centrifugo**.
474
+ #### publish method of subscription
727
475
 
728
- ### publish method of subscription
476
+ `publish` method of Subscription object allows publishing data into channel directly from a client.
729
477
 
730
- `publish` method of subscription object allows to publish data into channel directly from client. The main idea of Centrifugo is server side only push. Usually your application backend receives new event (for example new comment created, someone clicked like button etc) and then backend posts that event into Centrifugo over API. But in some cases you may need to allow clients to publish data into channels themselves. This can be used for demo projects, when prototyping ideas for example, for personal usage. And this allow to make something with real-time features without any application backend at all. Just Javascript code and Centrifugo.
478
+ **Using client-side publish is not an idiomatic Centrifugo usage in many cases. Centrifugo is standalone server and when publishing from a client you won't get the message on the backend side (except using publish proxy feature of Centrifugo). In most real-life apps you need to send new data to your application backend first (using the convenient way, for example AJAX request in web app) and then publish data to Centrifugo over Centrifugo API.**
731
479
 
732
- **So to emphasize: using client publish is not an idiomatic Centrifugo usage. It's not for production applications but in some cases (demos, personal usage, Centrifugo as backend microservice) can be justified and convenient. In most real-life apps you need to send new data to your application backend first (using the convenient way, for example AJAX request in web app) and then publish data to Centrifugo over Centrifugo API.**
733
-
734
- To do this you can use `publish` method. Note that just like presence and history publish must be allowed in Centrifugo configuration for all channels or for channel namespace. When using `publish` data will go through Centrifugo to all clients in channel. Your application backend won't receive this message.
480
+ *Just like presence and history publish must be allowed in Centrifugo configuration for all channels or for channel namespace.*
735
481
 
736
482
  ```javascript
737
- var subscription = centrifuge.subscribe("news", function(message) {
738
- // handle message
739
- });
740
-
741
- subscription.publish({"input": "hello world"}).then(function() {
483
+ sub.publish({"input": "hello world"}).then(function() {
742
484
  // success ack from Centrifugo received
743
485
  }, function(err) {
744
486
  // publish call failed with error
@@ -746,78 +488,91 @@ subscription.publish({"input": "hello world"}).then(function() {
746
488
  });
747
489
  ```
748
490
 
749
- `err` format the same as for `presence` method.
491
+ *Note, that in order publish to work in Centrifugo corresponding option must be enabled in server channel configuration or client should have capability to publish*.
750
492
 
751
- *Note, that in order publish to work corresponding option must be enabled in server channel configuration (on top level or for channel namespace), by default client can not publish into channel*
493
+ #### unsubscribe method of subscription
752
494
 
753
- ### unsubscribe method of subscription
754
-
755
- You can call `unsubscribe` method to unsubscribe from subscription:
495
+ You can call `unsubscribe` method to unsubscribe from a channel:
756
496
 
757
497
  ```javascript
758
- subscription.unsubscribe();
498
+ sub.unsubscribe();
759
499
  ```
760
500
 
761
- **Important thing to know** is that unsubscribing from subscription does not remove event hanlers you already set to that subscription object. This allows to simply subscribe to channel again later calling `.subscribe()` method of subscription (see below). But there are cases when your code structured in a way that you need to remove event handlers after unsubscribe **to prevent them be executed twice** in the future. To do this remove event listeners explicitly after calling `unsubscribe()`:
501
+ **Important thing to know** is that unsubscribing from subscription does not remove event handlers you already set to that Subscription object. This allows to simply subscribe to channel again later calling `.subscribe()` method of subscription (see below). But there are cases when your code structured in a way that you need to remove event handlers after unsubscribe **to prevent them be executed twice** in the future. To do this remove event listeners explicitly after calling `unsubscribe()`:
762
502
 
763
503
  ```javascript
764
- subscription.unsubscribe();
765
- subscription.removeAllListeners();
504
+ sub.unsubscribe();
505
+ sub.removeAllListeners();
766
506
  ```
767
507
 
768
- ### subscribe method of subscription
508
+ #### ready method of subscription
509
+
510
+ Returns a Promise which will be resolved upon subscription success (i.e. when Subscription goes to `subscribed` state).
769
511
 
770
- You can restore subscription after unsubscribing calling `.subscribe()` method:
512
+ ### Subscription token
513
+
514
+ You may want to provide subscription token:
771
515
 
772
516
  ```javascript
773
- subscription.subscribe();
517
+ const sub = centrifuge.newSubscription("news", {
518
+ token: '<SUBSCRIPTION_TOKEN>'
519
+ });
774
520
  ```
775
521
 
776
- ### ready method of subscription
522
+ In case of Centrifugo on a server side this may be a JSON Web Token - see [channel token auth documentation](https://centrifugal.github.io/centrifugo/server/channel_token_auth) for details on how to generate it on your backend side.
777
523
 
778
- A small drawback of setting event handlers on subscription using `on` method is that event
779
- handlers can be set after `subscribe` event of underlying subscription already fired. This
780
- is not a problem in general but can be actual if you use one subscription (i.e. subscription
781
- to the same channel) from different parts of your javascript application - so be careful.
524
+ **Subscription token must come to the frontend from application backend - i.e. must be generated on the backend side**. The way to deliver token to the application frontend is up to the developer. Usually you can pass it in template rendering context or issue a separate call to request a connection token from the backend.
782
525
 
783
- For this case one extra helper method `.ready(callback, errback)` exists. This method calls
784
- `callback` if subscription already subscribed and calls `errback` if subscription already
785
- failed to subscribe with some error (because you subscribed on this channel before). So
786
- when you want to call subscribe on channel already subscribed before you may find `ready()`
787
- method useful:
526
+ If token sets subscription expiration client SDK will keep token refreshed. It does this by calling special callback function. This callback must return a new token. If new token with updated subscription expiration returned from a calbback then it's sent to Centrifugo. If your callback returns an empty string – this means user has no permission to subscribe to a channel anymore and subscription will be unsubscribed. In case of error returned by your callback SDK will retry operation after some jittered time.
788
527
 
789
- ```javascript
790
- var subscription = centrifuge.subscribe("news", function(message) {
791
- // handle message;
792
- });
528
+ An example:
793
529
 
794
- // artificially model subscription to the same channel that happen after
795
- // first subscription successfully subscribed - subscribe on the same
796
- // channel after 5 seconds.
797
- setTimeout(function() {
798
- var anotherSubscription = centrifuge.subscribe("news", function(message) {
799
- // another listener of channel "news"
800
- }).on("subscribe", function() {
801
- // won't be called on first subscribe because subscription already subscribed!
802
- // but will be called every time automatic resubscribe after network disconnect
803
- // happens
530
+ ```javascript
531
+ function getToken(url, ctx) {
532
+ return new Promise((resolve, reject) => {
533
+ fetch(url, {
534
+ method: 'POST',
535
+ headers: new Headers({ 'Content-Type': 'application/json' }),
536
+ body: JSON.stringify(ctx)
537
+ })
538
+ .then(res => {
539
+ if (!res.ok) {
540
+ throw new Error(`Unexpected status code ${res.status}`);
541
+ }
542
+ return res.json();
543
+ })
544
+ .then(data => {
545
+ resolve(data.token);
546
+ })
547
+ .catch(err => {
548
+ reject(err);
549
+ });
804
550
  });
805
- // one of subscribeSuccessHandler (or subscribeErrorHandler) will be called
806
- // only if subscription already subscribed (or subscribe request already failed).
807
- anotherSubscription.ready(subscribeSuccessHandler, subscribeErrorHandler);
808
- }, 5000);
551
+ }
552
+
553
+ const client = new Centrifuge('ws://localhost:8000/connection/websocket', {});
554
+
555
+ const sub = centrifuge.newSubscription(channel, {
556
+ token: 'JWT-GENERATED-ON-BACKEND-SIDE',
557
+ getToken: function (ctx) {
558
+ // ctx has channel in the Subscription token case.
559
+ return getToken('/centrifuge/subscription_token', ctx);
560
+ },
561
+ });
562
+ sub.subscribe();
809
563
  ```
810
564
 
811
- When called `callback` and `errback` of `ready` method receive the same arguments as
812
- callback functions for `subscribe` and `error` events of subscription.
565
+ :::tip
566
+
567
+ If initial token is not provided, but `getToken` is specified – then SDK assumes that developer wants to use token authorization for a channel subscription. In this case SDK attempts to get a subscription token before initial subscribe.
568
+
569
+ :::
813
570
 
814
- ### Message batching
571
+ ## Message batching
815
572
 
816
- There is also message batching support. It allows to send several messages to server
817
- in one request - this can be especially useful when connection established via one of
818
- SockJS polling transports.
573
+ There is also a command batching support. It allows to send several commands to a server in one request - may be especially useful when connection established via one of HTTP-based transports.
819
574
 
820
- You can start collecting messages to send calling `startBatching()` method:
575
+ You can start collecting commands by calling `startBatching()` method:
821
576
 
822
577
  ```javascript
823
578
  centrifuge.startBatching();
@@ -829,98 +584,111 @@ Finally if you don't want batching anymore call `stopBatching()` method:
829
584
  centrifuge.stopBatching();
830
585
  ```
831
586
 
832
- This call will flush all collected messages to network.
587
+ This call will flush all collected commands to a network.
833
588
 
834
- ## Private channels subscription
589
+ ## Server-side subscriptions
835
590
 
836
- If channel name starts with `$` then subscription on this channel will be checked via AJAX POST request from Javascript client to your web application backend.
591
+ TODO.
837
592
 
838
- You can subscribe on private channel as usual:
593
+ ## Configuration parameters
839
594
 
840
- ```javascript
841
- centrifuge.subscribe('$private', function(message) {
842
- // process message
843
- });
844
- ```
595
+ Let's look at available configuration parameters when initializing `Centrifuge` object instance.
845
596
 
846
- But in this case Javascript client will first check subscription via your backend sending AJAX POST request to `/centrifuge/subscribe` endpoint (by default, can be changed via configuration option `subscribeEndpoint`). As said this is a POST request with JSON body. Request will contain `client` field on top level of JSON which is your connection client ID and array `channels` field - one or multiple private channels client wants to subscribe to.
597
+ ### debug
847
598
 
848
- ```javascript
849
- {
850
- "client": "<CLIENT ID>",
851
- "channels": ["$chan1", "$chan2"]
852
- }
853
- ```
599
+ `debug` is a boolean option which is `false` by default. When enabled lots of various debug
600
+ messages will be logged into javascript console. Mostly useful for development or
601
+ troubleshooting.
854
602
 
855
- Your server should validate all these subscriptions and return properly constructed response.
603
+ ### minReconnectDelay
856
604
 
857
- Response is a JSON with array `channels` field on top level:
605
+ When client disconnected from a server it will automatically try to reconnect using a backoff algorithm with jitter. `minReconnectDelay` option sets minimal interval value in milliseconds before first reconnect attempt. Default is `500` milliseconds.
858
606
 
859
- ```javascript
860
- {
861
- "channels": [
862
- {
863
- "channel": "$chan1",
864
- "token": "<SUBSCRIPTION JWT TOKEN>"
865
- },
866
- {
867
- "channel": "$chan2",
868
- "token": <SUBSCRIPTION JWT TOKEN>
869
- }
870
- ]
871
- }
872
- ```
607
+ ### maxReconnectDelay
873
608
 
874
- I.e. you need to return individual subscription tokens for each private channel in request. See [how to generate private channel tokens](https://centrifugal.github.io/centrifugo/server/private_channels/) in Centrifugo docs.
609
+ `maxReconnectDelay` sets an upper reconnect delay value. Default is `20000` milliseconds - i.e. clients won't have delays between reconnect attempts which are larger than 20 seconds.
875
610
 
876
- If you don't want to give client access to channel then just do not include it into response.
611
+ ### maxServerPingDelay
877
612
 
878
- There are also two public API methods which can help to subscribe to many private channels sending only one POST request to your web application backend: `startSubscribeBatching` and `stopSubscribeBatching`. When you `startSubscribeBatching` javascript client will collect private subscriptions until `stopSubscribeBatching()` called – and then send them all at once.
613
+ `maxServerPingDelay` sets the maximum delay of server pings after which connection is considered broken and client reconnects.
879
614
 
880
- As we just described when client subscribes on private channel by default AJAX request will be sent to `subscribeEndpoint` automatically if channel starts with `$`. In this case developer only needs to return proper response from server. But there is a way to override default behaviour and take full control on authorizing private channels. To do this it's possible to provide custom `onPrivateSubscribe` function in configuration options. This function will be called with all data required to authorize private channels client subscribes to and should call callback (will be provided by centrifuge-js as second argument) with authorization data when done. See our type declarations in `dist` folder to find out data format (**for `onPrivateSubscribe` it is slightly different** - like `{"status": 200, "data": {"channels": [...]}}`).
615
+ ### protocol
881
616
 
882
- ## Server-side subscriptions
617
+ By default, client works using `json` protocol. If you want to use binary transfer with Protobuf-based protocol this option must be set to `protobuf`. See more details about Protobuf communication in a special chapter.
883
618
 
884
- `centrifuge-js` v2.4.0 added support for server-side subscriptions. This means several new event handlers have been added.
619
+ ### token
885
620
 
886
- The main one is `publish` event of Centrifuge instance to handle publications coming from server-side channels:
621
+ Set initial connection token.
887
622
 
888
- ```javascript
889
- var centrifuge = new Centrifuge(address);
623
+ ### getToken
890
624
 
891
- centrifuge.on('publish', function(ctx) {
892
- const channel = ctx.channel;
893
- const payload = JSON.stringify(ctx.data);
894
- console.log('Publication from server-side channel', channel, payload);
895
- });
625
+ Set function for getting connection token. This may be used for initial token loading and token refresh mechanism (when initial token is going to expire).
896
626
 
897
- centrifuge.connect();
898
- ```
627
+ ### data
628
+
629
+ Set custom data to send to a server withing every connect command.
630
+
631
+ ### name
632
+
633
+ Set custom client name. By default, it's set to `js`. This is useful for analitycs and semantically must identify an environment from which client establishes a connection.
899
634
 
900
- Also there are event handlers for `join`, `leave`, `subscribe` and `unsubscribe` events. Actually they work the same way as analogues from Subscription instance but binded to Centrifuge instance instead.
635
+ ### version
901
636
 
902
- For example:
637
+ Version of your application - useful for analitycs.
638
+
639
+ ### timeout
640
+
641
+ Timeout for operations.
642
+
643
+ ### websocket
644
+
645
+ `websocket` option allows to explicitly provide custom WebSocket client to use. By default centrifuge-js will try to use global WebSocket object, so if you are in web browser – it will just use native WebSocket implementation. See notes about using `centrifuge-js` with NodeJS below.
646
+
647
+ ### sockjs
648
+
649
+ `sockjs` option allows to explicitly provide SockJS client object to Centrifuge client.
650
+
651
+ For example this can be useful if you develop in ES6 with imports:
903
652
 
904
653
  ```javascript
905
- centrifuge.on('subscribe', function(ctx) {
906
- console.log('Subscribe to server-side channel ' + ctx.channel);
907
- });
654
+ import Centrifuge from 'centrifuge'
655
+ import SockJS from 'sockjs-client'
908
656
 
909
- centrifuge.on('unsubscribe', function(ctx) {
910
- console.log('Unsubscribe from server-side channel ' + ctx.channel);
657
+ const centrifuge = new Centrifuge('https://centrifuge.example.com/connection/sockjs', {
658
+ sockjs: SockJS
911
659
  });
912
660
  ```
913
661
 
914
- ## Connection expiration
662
+ ### sockjsTransports
663
+
664
+ In case of using SockJS additional configuration parameter can be used - `sockjsTransports`.
915
665
 
916
- When connection expiration mechanism is on on server client will automatically ask your backend for updated connection credentials sending AJAX HTTP POST request to `/centrifuge/refresh` endpoint (by default, can be changed using `refreshEndpoint` option). Client will send that request when connection ttl is close to the end. In response backend should return response with JSON like this:
666
+ It defines allowed SockJS transports.
917
667
 
918
668
  ```javascript
919
- {
920
- "token": "<ACTUAL JWT TOKEN>"
921
- }
669
+ const centrifuge = new Centrifuge(
670
+ 'http://centrifuge.example.com/connection/sockjs',
671
+ {
672
+ sockjsTransports: [
673
+ 'websocket',
674
+ 'xdr-streaming',
675
+ 'xhr-streaming',
676
+ 'eventsource',
677
+ 'iframe-eventsource',
678
+ 'iframe-htmlfile',
679
+ 'xdr-polling',
680
+ 'xhr-polling',
681
+ 'iframe-xhr-polling',
682
+ 'jsonp-polling'
683
+ ]
684
+ });
922
685
  ```
923
686
 
687
+ ### sockjsServer
688
+
689
+ `sockjsServer` is SockJS specific option to set server name into connection urls instead
690
+ of random chars. See SockJS docs for more info.
691
+
924
692
  ## Protobuf support
925
693
 
926
694
  To import client with Protobuf protocol support:
@@ -932,42 +700,28 @@ To import client with Protobuf protocol support:
932
700
  Or if you are developing with npm:
933
701
 
934
702
  ```javascript
935
- import Centrifuge from 'centrifuge/dist/centrifuge.protobuf';
703
+ import Centrifuge from 'centrifuge/build/protobuf';
936
704
  ```
937
705
 
938
706
  This client uses [protobuf.js](https://github.com/dcodeIO/ProtoBuf.js/) under the hood.
939
707
 
940
- Centrifuge client with Protobuf support also works with JSON. To enable binary websocket add `format` query param with `protobuf` value to Websocket endpoint URL:
941
-
942
- ```javascript
943
- var centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket?format=protobuf');
944
- ```
945
-
946
- When using Centrifugo v3 or Centrifuge >= v0.18.0 on server side prefer using client options instead of setting format in URL (available in `centrifuge-js` >= v2.8.0):
708
+ Centrifuge client with Protobuf support also works with JSON. To enable binary websocket add `protocol: "protobuf"` option to Centrifuge configuration options:
947
709
 
948
710
  ```javascript
949
- var centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket', {
711
+ const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket", {
950
712
  protocol: 'protobuf'
951
713
  });
952
714
  ```
953
715
 
954
716
  ## Browser support
955
717
 
956
- This client intended to work in all modern browsers with Websocket support: https://caniuse.com/#search=websocket.
957
-
958
- **To support IE 11** you must additionally polyfill `Promise` as this library uses `Promise`.
959
-
960
- You can easily polyfill `Promise` via CDN (example here uses [es6-promise](https://github.com/stefanpenner/es6-promise) library):
961
-
962
- ```html
963
- <script src="https://cdn.jsdelivr.net/npm/es6-promise@4/dist/es6-promise.auto.min.js"></script>
964
- ```
965
-
966
- Or you can explicitly polyfill `Promise` in your code, see [auto-polyfill of es6-promise](https://github.com/stefanpenner/es6-promise#auto-polyfill)
718
+ TODO.
967
719
 
968
720
  ## Using with NodeJS
969
721
 
970
- NodeJS does not have native WebSocket library in std lib. To use `centrifuge-js` on Node you need to provide WebSocket object. You need to install WebSocket dependency:
722
+ NodeJS does not have native WebSocket library in std lib. To use `centrifuge-js` on Node you need to explicitly provide WebSocket constructor to the library.
723
+
724
+ First, install WebSocket dependency:
971
725
 
972
726
  ```
973
727
  npm install ws
@@ -1004,24 +758,7 @@ var centrifuge = new Centrifuge('ws://localhost:8000/connection/sockjs', {
1004
758
  })
1005
759
  ```
1006
760
 
1007
- ### Custom XMLHttpRequest
1008
-
1009
- To work with private channels you may need to pass `XMLHttpRequest` object to library:
1010
-
1011
- ```javascript
1012
- const Centrifuge = require('centrifuge');
1013
- const WebSocket = require('ws');
1014
- const XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
1015
-
1016
- var centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket', {
1017
- websocket: WebSocket,
1018
- xmlhttprequest: XMLHttpRequest
1019
- })
1020
- ```
1021
-
1022
- Or define XMLHttpRequest globally over `global.XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;`
1023
-
1024
- ### Custom WebSocket constructor
761
+ ## Custom WebSocket constructor
1025
762
 
1026
763
  If you are building a client for a non-browser environment and want to pass custom headers then you can use the following approach to wrap a WebSocket constructor and let custom options to be used on connection initialization:
1027
764
 
@@ -1045,53 +782,3 @@ var centrifuge = new Centrifuge('ws://localhost:8000/connection/websocket', {
1045
782
  websocket: myWs({ headers: { Authorization: '<token or key>' } }),
1046
783
  });
1047
784
  ```
1048
-
1049
- ### Subscribe since known position
1050
-
1051
- Available in `centrifuge-js` >= v2.8.0.
1052
-
1053
- Subscribe API supports setting known StreamPosition object to use server recovery feature on the connection start (otherwise recovery only used upon client reconnections due to temporary connection problems).
1054
-
1055
- ```javascript
1056
- centrifuge.subscribe('channel', function(messageCtx) {
1057
- console.log('new message', messageCtx);
1058
- }, {'since': {'offset': 0, 'epoch': '<EPOCH>'}});
1059
- ```
1060
-
1061
- ## Feature matrix
1062
-
1063
- - [x] connect to server using JSON protocol format
1064
- - [x] connect to server using Protobuf protocol format
1065
- - [x] connect with token (JWT)
1066
- - [ ] connect with custom header (not supported by browser API, though [possible for a non-browser target env](https://github.com/centrifugal/centrifuge-js#custom-websocket-constructor))
1067
- - [x] automatic reconnect in case of errors, network problems etc
1068
- - [x] an exponential backoff for reconnect
1069
- - [x] connect and disconnect events
1070
- - [x] handle disconnect reason
1071
- - [x] subscribe on a channel and handle asynchronous Publications
1072
- - [x] handle Join and Leave messages
1073
- - [x] handle Unsubscribe notifications
1074
- - [x] reconnect on subscribe timeout
1075
- - [x] publish method of Subscription
1076
- - [x] unsubscribe method of Subscription
1077
- - [x] presence method of Subscription
1078
- - [x] presence stats method of Subscription
1079
- - [x] history method of Subscription
1080
- - [x] top-level publish method
1081
- - [x] top-level presence method
1082
- - [x] top-level presence stats method
1083
- - [x] top-level history method
1084
- - [ ] top-level unsubscribe method
1085
- - [x] send asynchronous messages to server
1086
- - [x] handle asynchronous messages from server
1087
- - [x] send RPC commands
1088
- - [x] subscribe to private channels with token (JWT)
1089
- - [x] connection token (JWT) refresh
1090
- - [x] private channel subscription token (JWT) refresh
1091
- - [x] handle connection expired error
1092
- - [x] handle subscription expired error
1093
- - [x] ping/pong to find broken connection
1094
- - [x] message recovery mechanism for client-side subscriptions
1095
- - [x] server-side subscriptions
1096
- - [x] message recovery mechanism for server-side subscriptions
1097
- - [x] history stream pagination