Since centrifuge-js 5.0.2 we do not maintain CHANGELOG.md file.
All changes may be found on releases page on Github.
- Add missing
.hasOwnProperty
check when iterating over arrays
In v5 release we are moving to Rollup to build the library. For centrifuge-js
this means both ESM and CommonJS support and thus solve some issues when users could not use SDK with their existing toolchains. The migration includes some changes in how we provide Protobuf version of Centrifuge client. That's why we are making a new major v5 release.
For users which work with JSON-based Centrifuge client (default behaviour) the migration to v5 should be smooth and require no code changes.
Users of Protobuf version of the client need to change how they import Centrifuge
when using the library. Also, we removed protocol
option of Centrifuge instance config object. Imported Protobuf client now automatically uses Protobuf protocol under the hood.
For example, previously, when using Protobuf version of Centrifuge client, you have to import Protobuf client and then provide an option to constructor:
import Centrifuge from 'centrifuge/build/protobuf';
const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket", {
protocol: 'protobuf'
});
Now this simplifies to:
import { Centrifuge } from 'centrifuge/build/protobuf';
const centrifuge = new Centrifuge('ws://centrifuge.example.com/connection/websocket", {});
Note - changed import and no need to pass protocol: 'protobuf'
. See readme for more information about using Protobuf client and constructing binary payloads.
- Fix types: use
Record
instead ofMap
for publication tags andclients
field ofPresenceResult
.
- Update dependencies. In particular: migrate to the latest protobufjs 7.2.4.
This release changes the semantics of working with connection tokens described in Centrifugo v5 release post.
Previously, returning an empty token string from getToken
callback resulted in client disconnection with unauthorized reason.
Now returning an empty string from getToken
is a valid scenario which won't result into disconnect on the client side. It's still possible to disconnect client by throwing a special UnauthorizedError()
error from getToken
function.
And we are putting back setToken
method to the SDK – so it's now possible to reset the token to be empty upon user logout.
Also, centrifuge-js v4 contains the reworked reconnect code where we schedule reconnect task from the disconnect function instead of transport close event handler - see #234.
This release contains important connection stability improvements. If you experience disconnections due to bad request or stale reasons – this release may fix if not all but most of them.
- Fix connection leak due to transport close race, #225.
- Use network events in connecting state, #227. This allows immediately close transport upon offline event while SDK is in connecting state. Previously we only started handling these events after successful connect. Also fixes setting duplicate onlne/offline event handlers.
- Fix missing connInfo and chanInfo in presence data, see #220
- React on network online/offline events #204. In browser environment
centrifuge-js
will automatically listen to windowonline
andoffline
events, onoffline
event client will immediately disconnect, ononline
event reconnect attempt will be forced - Fix non-working HTTP-streaming in browser build due to esbuild minification issue
- Avoid using
tslib
and fix global object checks, see issue #193 and PR #194.
Breaking changes
This release adopts a new iteration of Centrifugal protocol and a new iteration of API. Client now behaves according to the client SDK API specification. The work has been done according to Centrifugo v4 roadmap.
Check out Centrifugo v4 release post that covers the reasoning behind changes here.
New release only works with Centrifugo >= v4.0.0 and Centrifuge >= 0.25.0. See Centrifugo v4 migration guide for details about the changes in the ecosystem.
Note, that Centrifugo v4 supports clients working over the previous protocol iteration, so you can update Centrifugo to v4 without any changes on the client side (but you need to turn on use_client_protocol_v1_by_default
option in the configuration of Centrifugo, see Centrifugo v4 migration guide for details).
Release notes:
- new API according to the new SDK API specification
- client migrated to Typescript, all public API is strictly typed, including
EventEmitter
callbacks - SockJS is now DEPRECATED in Centrifugal ecosystem and requires explicit configuration, see the library readme
- introducing our own WebSocket emulation layer - based on HTTP-streaming and SSE (Eventsource) fallbacks
- experimental WebTransport support (only works with Centrifugo v4 experimental HTTP/3 support)
- optimistic subscriptions to reduce connect latency
- redesigned PING-PONG (pings are only sent from server to client now)
- resilient subscriptions which handle temporary server errors and re-subscribe (with full jitter backoff)
- Support setting a custom
data
attached to a subscribe request. Thisdata
will be then available inOnSubscribe
callback on the server side (in the case of Centrifugo subscribe proxy will be able to access this data). #171.
- Fix regression of 2.8.0: handle server-side subscribe and unsubscribe pushes.
- Fix TypeScript definitions for subscribe (
A rest parameter must be last in a parameter list.
).
- Support
sockjsTimeout
(number) option which translates to SockJS.timeout option - i.e. a minimum timeout in milliseconds to use for the transport connections. By default SockJS uses timeout determined automatically based on calculating round trip time during info request.
Update to work with Centrifuge >= v0.18.0 and Centrifugo v3.
Breaking change in server behavior. Client History API behavior changed in Centrifuge >= v0.18.0 and Centrifugo >= v3.0.0. When using history call it won't return all publications in a stream by default. See Centrifuge v0.18.0 release notes or Centrifugo v3 migration guide for more information and workaround on server-side. If you are using centrifuge-js
with older server versions then everything without using history options like limit
and since
then everything should work the same way. Since this is a change in a server behavior we don't release a new major centrifuge-js
version.
Other changes:
- Protocol definitions updated to the latest version
- When working with Centrifugo v3 or Centrifuge >= v0.18.0 it's now possible to avoid using
?format=protobuf
in connection URL when using Protobuf protocol. The intent to use binary Protobuf protocol can now be set explicitly in client options. In this case client will negotiate Protobuf protocol with a server using WebSocket subprotocol mechanism (in request headers). Pull request. - It's now possible to call subscribe and provide custom subscribe options. One subscribe option available now is
since
– which allows setting knownStreamPosition
and initiate automatic recovery. Pull request.
- possibility to set
disableWithCredentials
boolean option (false
by default) to controlwithCredentials
option ofXMLHttpRequest
. See #155.
xmlhttprequest
option to explicitly pass XMLHttpRequest (for NodeJS environment)
- Fix regression of 2.7.4 -
Unexpected end of JSON input
- Optimize & simplify json encode/decode, see #138
SubscribeSuccessContext
can containdata
field if custom data returned from a server in a subscribe result.
- Handle server-side SUB push in Protobuf case (previously ignored). Sub push is a message that contains information about server-side subscription made after connection already established.
- Fix type definitions - see #133
- add missing
offset
to TS definitions forPublicationContext
, note thatseq
andgen
fields considered deprecated and will go away with next majorcentrifuge-js
release - add top-level methods:
history
,presence
,presenceStats
– those are useful when using sever-side subscriptions - fix wrong error format of top-level
publish
Promise reject branch – it now contains protocol error object (withcode
andmessage
fields) - possibility to set
name
andversion
protocol fields over Centrifuge config options - remove unused
promise
option from configuration - add history iteration API (usage limited to Centrifuge library for Go at the moment) - see example below
- subscribe success event context in positioned subscriptions (added in Centrifuge library v0.15.0) now contains
streamPosition
object (with currentoffset
andepoch
fields) - updated
protobuf-js
dependency (now^6.10.2
) - all dev-dependencies updated and now use the latest versions of webpack, babel, eslint, mocha etc
- internal code refactoring of Subscrption methods - code is simplified and more reusable now
Let's look at history pagination feature in more detail. It's now possible to iterate over channel history this way:
resp = await subscription.history({'since': {'offset': 2, 'epoch': 'xcf4w'}, limit: 100});
If server can't fulfill a query for history (due to stream retention - size or expiration, or malformed offset, or stream already has another epoch) then an Unrecoverable Position Error will be returned (code 112
).
To only call for current offset
and epoch
use:
resp = await subscription.history({limit: 0});
I.e. not providing since
and using zero limit
.
Due to backward compatibility history
call without arguments will return full existing history in channel (though it's possible to limit max number of publications to return on server side).
For now history pagination feature only works with Centrifuge library based server and not available in Centrifugo.
- fix missing
info
in Publication context - add
namedRPC
method to call RPC with method string
- fix possible event loss in server-side subscriptions due to Promise execution order
- fix TypeError in subRefresh method, #109
- fix TypeError on refresh token with protobuf, #107
- Support
Offset
protocol field which is replacingSeq
andGen
, client will work with bothOffset
andSeq/Gen
based servers until next major release. Then support forSeq/Gen
will be removed.
- Remove subscription from internal
_subs
map after.unsubscribe()
called, see this discussion for more details - Make sure that server-side subscription exists before calling server-side subscription events
- Server-side subscriptions support, see related README section
- Fix fulfilling Promise when RPC error happens. Before this fix RPC error did not properly called Promise error handler, now it does.
- Fix type declarations for
onPrivateSubscribe
callback. See #94 for details.
- Do not reconnect after disconnect called in disconnected state, more details in #92.
- Fix error on resolving
EventEmitter
import while building TypeScript project with definitions added in 2.2.0.
- fix wrong case of fields in Publication info and in result of
presence()
andpresenceStats()
responses in Protobuf format case. Those fields were not compliant with JSON format due to the fact that Protobuf compiler does not keep original case defined in proto schema by default. If you are using Protobuf this can be a breaking change - see this commit for fix details and all fields that now use snake_case instead of camelCase in Protobuf case. If you are using JSON you are not affected with these changes - fix unhandled promise exceptions on NodeJS when calling subscription methods
- add TypeScript type definitions, thanks to @jekaspekas for contribution
- add
websocket
option to explicitly provide custom WebSocket implementation to use
- fix subscribe after clearing connection state, see #83 for details
- fix wrong error object format (on timeout, disconnect and connection closed errors) introduced in 2.1.4
- fix broken iteration over several replies in one frame if one of replies had error field set
- fix setting setInterval with value greater than
2,147,483,647
which resulted in immediate refresh callback firing. Thi means that maximum possible TTL for JWT is about 25 days in Javascript.
- fix private subscription races after reconnect, see #76 for issue and solution details
- fix websocket transport state check - see #74
- new
publish
method of Centrifuge object to publish into channels without being subscribed - check connection state to prevent writing to closed connection and thus unhandled errors
send
method now sends message to server immediately and returns Promise
- Prevent unhandled errors to be raised after failed subscription (#70)
This is a new major release of library updated to work with Centrifugo v2 and Centrifuge library. Library is now written using more actual Javascript instruments - with Webpack and ES6 classes. See readme for more information about new API and how to use library in general.
Highlights:
- Webpack and ES6 for code base
- JSON and Protobuf (only Websocket) serialization formats supported
- new
presenceStats
method of subscription
- fix isResubscribe flag behaviour to only be
true
after resubscribe on reconnect. See more details in #62 - fix resubscribe behaviour after
unsubscribe
sent from server - this is th remaining part of #46
- support new private subscription response format. Now it's possible to return JSON of this kind:
{
"channels": [
{
"channel": "$one",
"sign": "..."
}
]
}
I.e. object with channels
on top level which is an array of objects with channel data. This resolves issues with API generators that do not support map on top level. This is also a bit more extendable and most probably will be default format in v2.
withCredentials
support for XHR requests - #39.- fix resubscribe bug introduced in 1.4.7
- fix undesired resubscribe after reconnect. See #45
- add
onRefresh
andonPrivateChannelAuth
callback functions to config to replace built-in refresh and private channel auth behaviour with you own logic. See #45 for motivation and initial pull request sent by @skyborn8 onTransportClose
callback should be executed every time transport was closed - see #33 for motivation.- fix refresh workflow in case client offline for a while
- export
recovered
flag in successful subscribe event context. It indicates that Centrifugo thinks all messages were successfully recovered (i.e. client did not miss any messages) after successful resubscribe on channel. See centrifugal/centrifugo#165 for motivation.
So it's possible to use it like this:
function handleSubscribe(ctx) {
console.log('Subscribed on channel ' + ctx.channel);
if (ctx.isResubscribe && !ctx.recovered) {
console.log("you need to restore messages from app backend");
} else {
console.log("no need to restore state");
}
}
var sub = centrifuge.subscribe(channel, handleMessage).on("subscribe", handleSubscribe)
Note that asking your backend about actual state after every reconnect is still the most reliable way to recover your app state. Relying on recovered
flag can be an acceptable trade off for some applications though.
- update
es6-promise
dependency to^4.0.5
- removing
ping
field from connect message as it not used by Centrifugo >= 1.6.3
It's recommended to update SockJS library to latest version - 1.1.2
- Use public SockJS API to get transport name. See #26
- Do not send ping to server for a while after receiving SockJS heartbeat frame.
- fix ReferenceError - see #25
This release works with Centrifugo >= 1.6.0
- automatic client to server pings.
Ping will be sent to server only when connection was idle - i.e. if there was no wire activity
for pingInterval
period so it should not affect performance much.
You can disable automatic pings using "ping": false
option. But before turning it off make
sure you've read chapter about pings in docs.
Also there is an adjustable pongWaitTimeout
option to control how long to wait for pong
response before closing connection.
- do not try to refresh after disconnected. See #24
- properly handle disconnect API command - do not reconnect.
- Adapt to use in ES6 style
- new
sockJS
option to explicitly provide SockJS client object - npm entry point is
src/centrifuge.js
now to prevent webpack warning.
ES6 example:
import Centrifuge from 'centrifuge'
import SockJS from 'sockjs-client'
var c = new Centrifuge({
"url": "...",
"user": "...",
"token": "...",
"timestamp": "...",
"sockJS": SockJS
});
c.connect();
refreshData
option to send extra data in body when sending AJAX POST refresh requestrefreshAttempts
option to limit amount of refresh requests before giving uprefreshFailed
options to set callback function called whenrefreshAttempts
came to the end.
- fix using centrifuge-js in SharedWorker - there is no
window
object, so usingself
instead ofwindow
when we in SharedWorker context.
- only call
subscribe
for existing subscription if its in unsubscribed state.
- fix
centrifuge.subscribe
method when calling on channel for which subscription already exists but in unsubscribe state. See this pull request for more details.
- use browserify to build library
- fix import over requirejs introduced in 1.3.0
- add
latency
field (in milliseconds) toconnect
event context. This measures time passed between sendingconnect
client protocol command and receiving connect response.
Also there was debug logging statement in 1.3.0 left in source code occasionally. 1.3.0 was rebuilt with fix, but I am not sure that it was not cached somewhere in bower. So here is 1.3.1
Client API completely refactored in this release. You can still use previous versions to communicate with Centrifugo server from browser environment but new implementation much more comfortable to use in our opinion and will be supported in future releases so consider upgrading!
Highlights of this release:
- automatic resubscribe, no need to subscribe manually in
connect
event handler - more opaque error handling
- drop support for SockJS < 1.0.0 (but if you still use SockJS 0.3.4 then feel free to open issue and we will return its support to client)
Please, read new documentation for Javascript browser client.
Also, DOM plugin was removed from repository as new client API design solves most of problems that DOM plugin existed for - i.e. abstracting subscribe on many channels and automatically resubscribe on them. With new client you can have one global connection to Centrifugo and subscribe on channels at any moment from any part of your javascript code.
Also we updated examples to fit new changes.
If you are searching for old API docs (centrifuge-js
<= 1.2.0) - you can find it here
- use exponential backoff when reconnecting
- follow disconnect advice from Centrifugo
- support for
recover
option (introduced in Centrifugo v1.2.0) - fix removing subscription when unsubscribing from channel
One backwards incompatible change here. Centrifuge-js now sends JSON (application/json
)
request instead of application/x-www-form-urlencoded
when client wants to subscribe on
private channel. See in docs how to deal with JSON in this case.
- send JSON instead of form when subscribing on private channel.
- simple reconnect strategy
The only change in 0.9.0
is changing private channel request POST parameter name
channels
to channels[]
. If you are using private channels then you should update
your backend code to fit new parameter name. This change was required because of how
PHP and Ruby on Rails handle POST parameter names when POST request contains multiple
values for the same parameter name.
channels
parameter renamed tochannels[]
in private subscription POST request to application.
- Support SockJS 1.0. Use
transports
instead ofprotocols_whitelist
. - auto detect connection endpoint when
url
without endpoint path provided - properly handle auth request failure