@devanachat/sdk 0.12.0 → 0.13.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.
package/CHANGELOG.md CHANGED
@@ -6,6 +6,40 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [0.13.0]
10
+
11
+ ### Added
12
+
13
+ - `CreateMessage.allowedMentions` (`MessageMentions`): limits the users and roles the message mentions - empty lists
14
+ mention no one.
15
+
16
+ ### Changed
17
+
18
+ - Reconnecting spreads the clients dropped together: a retry waits a random time between 0 and the backoff delay
19
+ (it used to be 50-100% of it). After a closure by the server (close code 1001, 1012 or 1013, or after a `Bye`) the backoff
20
+ starts at `reconnect.serverCloseMinDelayMs` (5 s by default) instead of `reconnect.minDelayMs` (1 s). The backoff
21
+ starts over once a connection has stayed authenticated for `reconnect.stableConnectionMs` (30 s by default),
22
+ not as soon as it authenticates.
23
+ - `connectingTimeoutMs` (10 s) limits only the time until the socket opens. An open socket waits for `Session` up to
24
+ the new `sessionTimeoutMs` (60 s by default), so a client the server holds in its queue during a reconnect storm is
25
+ no longer dropped and sent back to the end of it.
26
+
27
+ ### Fixed
28
+
29
+ - A `Bye` with the `Service` reason (the server shutting down) is followed by a reconnect even when the server closes
30
+ the connection with code 1000; the client used to stop. `Bye` is emitted first, then `disconnect` with `true`; a
31
+ `connect()` still waiting for `Session` stays pending for the retry. Other `Bye` reasons behave as before.
32
+ - `Bye.retryAfterMs`: when the server sends it, the next reconnect waits that long instead of the backoff delay, without
33
+ further jitter; values that are not positive finite numbers are ignored and longer ones are capped at 60 s.
34
+ - A `Bye` with the `ServiceUnavailableException` error (the server too busy to take the connection) is followed by a
35
+ reconnect, like a `Service` one, instead of being treated as a rejected token: no `error` event, a pending
36
+ `connect()` stays pending for the retry. `AuthenticationException` still stops reconnecting.
37
+ - `disconnect()` called by a listener of the message being received (e.g. of `Session`, to refuse the protocol
38
+ version, or of `Bye`) is final: the client no longer authenticates the closed connection, emits `connect` or
39
+ schedules a retry afterwards, and emits `disconnect` once.
40
+
41
+ ## [0.12.0]
42
+
9
43
  ### Added
10
44
 
11
45
  - Editing messages: the `UpdateMessage` command (`{messageId, content?, embed?}` - a field left out stays, `embed: null`
@@ -39,6 +73,26 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
39
73
  `FoundGif` with its post `url`, size, poster and MP4/WebM sources; pass `next` as `position` for the following page),
40
74
  and the `GetGifCategories` command (`{locale?}`) resolving with `GifCategories` (`{categories}`, each `GifCategory`
41
75
  with the search `term`, its English `name` and an `imageUrl`). Available when the server runs GIF search.
76
+ - Reactions of sticky messages: `RoomsManager.getStickyMyReactions(location, messageId)` returns the reactions of the
77
+ connected user on sticky messages (`MessageUserReactions`, keyed by message id) - fetched once per message with `GetMessages` (`around`,
78
+ `limit: 1`, `includeMyReactions`), as a sticky message comes with its topic, then kept up to date with `Reacted`.
79
+ The topics tracked by `RoomsManager` follow the reaction counters of their sticky message with `ReactionUpdated`.
80
+
81
+ ### Changed
82
+
83
+ - **Breaking:** `Messages.myReactions` is a list of `MessageUserReactions` (`{messageId, reactions}`) instead of a map
84
+ keyed by message id, so this version needs a server sending the list; `TopicHistoryWindow.myReactions` keeps the map.
85
+ - **Breaking:** the `RedactMessages` permission is `ManageMessages` (the same bit, `1 << 19`; the `RedactMessages`
86
+ command keeps its name). Besides deleting messages it lets `UpdateMessage` with `embed: null` hide a preview
87
+ generated by the server in any message.
88
+ - State snapshots: version 3 (with the replied messages of the saved histories); older snapshots are rejected.
89
+ - `React` with a reaction the user already has fails with `ReactionExistsAlreadyException`; `Unreact` of a reaction the
90
+ user does not have resolves with `Ok`. Both used to get no answer.
91
+
92
+ ## [0.11.0]
93
+
94
+ ### Added
95
+
42
96
  - Typing notifications: the `Type` command and the `Typing` event (`{location, userId}`), for rooms other than
43
97
  `ClassicText`. `RoomsManager.typing.get(roomId, topicId)` returns the ids of the users typing in a topic, tracked from
44
98
  the first call, each leaving `TYPING_TIMEOUT_MS` after their last notification or with their message.
@@ -46,10 +100,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
46
100
  - Sticky messages: `Topic.stickyMessage`, `CreateMessage.sticky`, `NewMessage.sticky`, `UpdateTopic.stickyMessageId`
47
101
  (a message id sticks it, `null` unsticks it) and the `ManagePins` permission. The topics tracked by `RoomsManager`
48
102
  take a new sticky message from `NewMessage` and drop it when it is redacted.
49
- - Reactions of sticky messages: `RoomsManager.getStickyMyReactions(location, messageId)` returns the reactions of the
50
- connected user on sticky messages (`MessageUserReactions`, keyed by message id) - fetched once per message with `GetMessages` (`around`,
51
- `limit: 1`, `includeMyReactions`), as a sticky message comes with its topic, then kept up to date with `Reacted`.
52
- The topics tracked by `RoomsManager` follow the reaction counters of their sticky message with `ReactionUpdated`.
53
103
  - Role icons: `Role.icon` (`RoleIcon` - an emoji or an emoticon of the space, `{type, value}` like a reaction) and
54
104
  `UpdateRole.icon` (an icon sets it, `null` removes it).
55
105
  - Guests: `Space.guestRole` and `UpdateSpace.guestRole` (a role of the space given to temporary accounts when they
@@ -61,14 +111,6 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
61
111
 
62
112
  ### Changed
63
113
 
64
- - **Breaking:** `Messages.myReactions` is a list of `MessageUserReactions` (`{messageId, reactions}`) instead of a map
65
- keyed by message id, so this version needs a server sending the list; `TopicHistoryWindow.myReactions` keeps the map.
66
- - **Breaking:** the `RedactMessages` permission is `ManageMessages` (the same bit, `1 << 19`; the `RedactMessages`
67
- command keeps its name). Besides deleting messages it lets `UpdateMessage` with `embed: null` hide a preview
68
- generated by the server in any message.
69
- - State snapshots: version 3 (with the replied messages of the saved histories); older snapshots are rejected.
70
- - `React` with a reaction the user already has fails with `ReactionExistsAlreadyException`; `Unreact` of a reaction the
71
- user does not have resolves with `Ok`. Both used to get no answer.
72
114
  - `PermissionsManager.calculatePermissions` follows the server: on every layer the space default role (everyone) is
73
115
  applied before the other roles, so a deny of another role overrides what everyone allows. An allow of any role still
74
116
  wins over a deny of another one.
package/README.md CHANGED
@@ -161,19 +161,27 @@ client.on('NewMessage', async ({message}) => {
161
161
  ## Connection maintenance
162
162
 
163
163
  `WebSocketChatClient` keeps the connection alive: after any loss (error, connecting timeout, missing pong, closure with
164
- a code other than 1000) it reconnects indefinitely, with an exponential backoff between attempts. The `disconnect` event
164
+ a code other than 1000) it reconnects indefinitely, waiting a random time up to an exponentially growing delay between
165
+ attempts. The backoff starts higher when the server closed the connection than after a network drop, and starts over
166
+ once a connection has been stable for a while. The `disconnect` event
165
167
  tells whether a retry follows. A pending `connect()` promise resolves once an attempt authenticates, and is rejected by
166
168
  `disconnect()`, which also stops reconnecting. An invalid token (`Bye` with `AuthenticationException`) rejects `connect()`
167
- with the `Bye` data, emits an `error` event and stops reconnecting as well.
169
+ with the `Bye` data, emits an `error` event and stops reconnecting as well. A `Bye` with the `Service` reason (the server
170
+ going down) or with `ServiceUnavailableException` (the server overloaded) is always followed by a retry, emitted as
171
+ `Bye` and then `disconnect` with `true`, whatever the close code.
172
+ When a `Bye` carries `retryAfterMs`, the next retry waits that long (at most 60 s) instead of the backoff delay.
168
173
 
169
174
  ```ts
170
175
  const client = new WebSocketChatClient({
171
176
  url: 'wss://s1.devana.pl:1600/ws',
172
177
  token: 'your-access-token',
173
- connectingTimeoutMs: 10000, // Per attempt (default)
178
+ connectingTimeoutMs: 10000, // Until the socket opens (default)
179
+ sessionTimeoutMs: 60000, // Until Session arrives on an open socket; the server may queue connections (default)
174
180
  reconnect: {
175
- minDelayMs: 1000, // Delay before the first retry, doubled on every next one (default)
176
- maxDelayMs: 30000, // Maximum delay between retries (default)
181
+ minDelayMs: 1000, // Limit of the first delay after a lost connection, doubled on every next one (default)
182
+ serverCloseMinDelayMs: 5000, // The same after a closure by the server: 1001, 1012, 1013 or a Bye (default)
183
+ maxDelayMs: 30000, // Maximum delay between retries; a higher minimum delay wins over it (default)
184
+ stableConnectionMs: 30000, // A connection lasting this long starts the backoff over (default)
177
185
  },
178
186
  ping: {
179
187
  noActivityTimeoutMs: 15000, // Send a ping after this much silence (default)
@@ -4236,6 +4236,12 @@ class ChatStateTracker {
4236
4236
  ;// ./src/WebSocketChatClient.ts
4237
4237
 
4238
4238
 
4239
+ const MAX_RETRY_AFTER_MS = 60000;
4240
+ // Going Away, Service Restart, Try Again Later
4241
+ const SERVER_CLOSE_CODES = [1001, 1012, 1013];
4242
+ function normalizeRetryAfter(retryAfterMs) {
4243
+ return typeof retryAfterMs === 'number' && Number.isFinite(retryAfterMs) && retryAfterMs > 0 ? Math.min(retryAfterMs, MAX_RETRY_AFTER_MS) : undefined;
4244
+ }
4239
4245
  var WebSocketChatClientEvent = /*#__PURE__*/function (WebSocketChatClientEvent) {
4240
4246
  WebSocketChatClientEvent["connect"] = "connect";
4241
4247
  WebSocketChatClientEvent["disconnect"] = "disconnect";
@@ -4258,6 +4264,10 @@ class WebSocketChatClient extends AbstractChatClient {
4258
4264
  reconnectEnabled = false;
4259
4265
  reconnectTimeoutId;
4260
4266
  reconnectAttempts = 0;
4267
+ serverClosedSinceStable = false;
4268
+ byeReceived = false;
4269
+ byeRetryAfterMs;
4270
+ stableConnectionTimeoutId;
4261
4271
  constructor(options) {
4262
4272
  super();
4263
4273
  this.options = options;
@@ -4294,7 +4304,7 @@ class WebSocketChatClient extends AbstractChatClient {
4294
4304
  disconnect() {
4295
4305
  const wasActive = this.ws !== null || this.reconnectTimeoutId !== undefined;
4296
4306
  this.reconnectEnabled = false;
4297
- this.reconnectAttempts = 0;
4307
+ this.resetBackoff();
4298
4308
  this.cancelScheduledReconnect();
4299
4309
  this.releaseSocket(1000); // Normal closure
4300
4310
  this.failPendingCommands(new Error('Client disconnected before the command was answered'));
@@ -4336,9 +4346,16 @@ class WebSocketChatClient extends AbstractChatClient {
4336
4346
  // Not every implementation follows a failed handshake with a close
4337
4347
  // event (e.g. Node.js), so an error alone means the connection is lost.
4338
4348
  ws.onerror = () => ws === this.ws && this.handleConnectionLoss(true);
4349
+ ws.onopen = () => ws === this.ws && this.startConnectingTimeout(this.options.sessionTimeoutMs ?? 60000);
4339
4350
  this.ws = ws;
4340
4351
  this.authenticated = false;
4341
- this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), this.options.connectingTimeoutMs ?? 10000);
4352
+ this.byeReceived = false;
4353
+ this.byeRetryAfterMs = undefined;
4354
+ this.startConnectingTimeout(this.options.connectingTimeoutMs ?? 10000);
4355
+ }
4356
+ startConnectingTimeout(timeoutMs) {
4357
+ clearTimeout(this.connectingTimeoutId);
4358
+ this.connectingTimeoutId = setTimeout(() => this.triggerConnectionTimeout(), timeoutMs);
4342
4359
  }
4343
4360
  sendEnvelope(envelope) {
4344
4361
  if (this.isReady) {
@@ -4350,34 +4367,52 @@ class WebSocketChatClient extends AbstractChatClient {
4350
4367
  onMessage(event) {
4351
4368
  this.lastReceivedMessageAt = Date.now();
4352
4369
  const envelope = JSON.parse(event.data);
4370
+ const ws = this.ws;
4353
4371
  this.handleIncomingEnvelope(envelope);
4354
4372
  this.emit(envelope.type, envelope.data);
4355
4373
  this.emit(this.Event.message, envelope);
4356
4374
 
4375
+ // A listener has called disconnect() or connect(), which settled this socket already.
4376
+ if (ws !== this.ws) {
4377
+ return;
4378
+ }
4379
+ if (envelope.type === 'Bye') {
4380
+ this.onBye(envelope.data);
4381
+ return;
4382
+ }
4383
+
4357
4384
  // Login successfully
4358
4385
  if (!this.authenticated) {
4359
- const isAuthenticated = envelope.type !== 'Bye';
4360
- this.authenticated = isAuthenticated;
4361
- if (isAuthenticated) {
4362
- this.reconnectAttempts = 0;
4363
- this.startConnectionMonitor();
4364
- this.settleConnect();
4365
- this.emit(this.Event.connect);
4366
- this.sendFromQueue();
4367
- } else {
4368
- this.settleConnect(envelope.data);
4369
- const error = envelope.data?.reason?.error;
4370
- if (error?.code === 'AuthenticationException') {
4371
- // Invalid token - retrying would be rejected the same way.
4372
- this.handleConnectionLoss(false);
4373
- this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4374
- }
4375
- }
4386
+ this.authenticated = true;
4387
+ this.stableConnectionTimeoutId = setTimeout(() => this.resetBackoff(), this.options.reconnect?.stableConnectionMs ?? 30000);
4388
+ this.startConnectionMonitor();
4389
+ this.settleConnect();
4390
+ this.emit(this.Event.connect);
4391
+ this.sendFromQueue();
4392
+ }
4393
+ }
4394
+ onBye(bye) {
4395
+ this.byeReceived = true;
4396
+ this.byeRetryAfterMs = normalizeRetryAfter(bye?.retryAfterMs);
4397
+ if (bye?.reason?.type === 'Service' || bye?.reason?.error?.code === 'ServiceUnavailableException') {
4398
+ // Not left to the close code: the server may close with 1000 and some platforms rewrite the code.
4399
+ this.handleConnectionLoss(true, true);
4400
+ return;
4401
+ }
4402
+ if (this.authenticated) {
4403
+ return;
4404
+ }
4405
+ this.settleConnect(bye);
4406
+ const error = bye?.reason?.error;
4407
+ if (error?.code === 'AuthenticationException') {
4408
+ // Invalid token - retrying would be rejected the same way.
4409
+ this.handleConnectionLoss(false);
4410
+ this.emit(this.Event.error, new Error(`Authentication rejected: ${error.message}`));
4376
4411
  }
4377
4412
  }
4378
4413
  onClose(event) {
4379
4414
  // Connection was closed because of error
4380
- this.handleConnectionLoss(event.code !== 1000);
4415
+ this.handleConnectionLoss(event.code !== 1000, this.byeReceived || SERVER_CLOSE_CODES.includes(event.code));
4381
4416
  }
4382
4417
 
4383
4418
  /**
@@ -4385,7 +4420,7 @@ class WebSocketChatClient extends AbstractChatClient {
4385
4420
  * may never come, or take minutes on a dead TCP connection), settle
4386
4421
  * everything that depended on it and schedule a retry when requested.
4387
4422
  */
4388
- handleConnectionLoss(reconnect) {
4423
+ handleConnectionLoss(reconnect, closedByServer = false) {
4389
4424
  this.releaseSocket(reconnect ? 3000 : 1000);
4390
4425
 
4391
4426
  // The server can no longer answer anything that was queued or in
@@ -4395,7 +4430,7 @@ class WebSocketChatClient extends AbstractChatClient {
4395
4430
  if (reconnect) {
4396
4431
  // Keep a pending connect() promise unsettled - the retry below is
4397
4432
  // expected to authenticate and will resolve it.
4398
- this.scheduleReconnect();
4433
+ this.scheduleReconnect(closedByServer);
4399
4434
  } else {
4400
4435
  this.reconnectEnabled = false;
4401
4436
  this.settleConnect(new Error('Connection closed before authentication'));
@@ -4411,13 +4446,15 @@ class WebSocketChatClient extends AbstractChatClient {
4411
4446
  this.stopConnectionMonitor();
4412
4447
  clearTimeout(this.connectingTimeoutId);
4413
4448
  this.connectingTimeoutId = undefined;
4449
+ clearTimeout(this.stableConnectionTimeoutId);
4450
+ this.stableConnectionTimeoutId = undefined;
4414
4451
  this.authenticated = false;
4415
4452
  const ws = this.ws;
4416
4453
  this.ws = null;
4417
4454
  if (!ws) {
4418
4455
  return;
4419
4456
  }
4420
- ws.onmessage = ws.onclose = ws.onerror = null;
4457
+ ws.onmessage = ws.onclose = ws.onerror = ws.onopen = null;
4421
4458
  if (ws.readyState === ws.CONNECTING || ws.readyState === ws.OPEN) {
4422
4459
  try {
4423
4460
  ws.close(closeCode);
@@ -4426,19 +4463,27 @@ class WebSocketChatClient extends AbstractChatClient {
4426
4463
  }
4427
4464
  }
4428
4465
  }
4429
- scheduleReconnect() {
4466
+ scheduleReconnect(closedByServer) {
4430
4467
  this.cancelScheduledReconnect();
4431
- const minDelay = Math.max(0, this.options.reconnect?.minDelayMs ?? 1000);
4432
- const maxDelay = Math.max(minDelay, this.options.reconnect?.maxDelayMs ?? 30000);
4468
+
4469
+ // Once the server has closed a connection, the attempts that fail while it is still down
4470
+ // keep the longer backoff.
4471
+ this.serverClosedSinceStable ||= closedByServer;
4472
+ const reconnectOptions = this.options.reconnect;
4473
+ const minDelay = Math.max(0, this.serverClosedSinceStable ? reconnectOptions?.serverCloseMinDelayMs ?? 5000 : reconnectOptions?.minDelayMs ?? 1000);
4474
+ const maxDelay = Math.max(minDelay, reconnectOptions?.maxDelayMs ?? 30000);
4433
4475
  const delay = Math.min(maxDelay, minDelay * 2 ** Math.min(this.reconnectAttempts, 30));
4434
4476
  this.reconnectAttempts++;
4435
4477
 
4436
- // Random jitter (50-100% of the delay) keeps clients from reconnecting
4437
- // in lockstep after a server restart.
4478
+ // Full jitter spreads the clients dropped together over the whole delay; the server jitters its own hint.
4438
4479
  this.reconnectTimeoutId = setTimeout(() => {
4439
4480
  this.reconnectTimeoutId = undefined;
4440
4481
  this.connect().catch(() => undefined);
4441
- }, delay / 2 + Math.random() * delay / 2);
4482
+ }, this.byeRetryAfterMs ?? Math.random() * delay);
4483
+ }
4484
+ resetBackoff() {
4485
+ this.reconnectAttempts = 0;
4486
+ this.serverClosedSinceStable = false;
4442
4487
  }
4443
4488
  cancelScheduledReconnect() {
4444
4489
  clearTimeout(this.reconnectTimeoutId);