@dokebi/websocket 0.4.5 → 0.4.6
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/AI.md +23 -2
- package/README.md +1 -1
- package/dist/client.d.ts +44 -0
- package/dist/client.js +86 -0
- package/dist/gateway.js +11 -5
- package/dist/index.js +1 -1
- package/package.json +5 -1
package/AI.md
CHANGED
|
@@ -106,10 +106,31 @@ sessionStorage.setItem('cid', clientId);
|
|
|
106
106
|
const socket = new WebSocket(`/ws?clientId=${clientId}&dokebiVersion=${BUILD_VERSION}`);
|
|
107
107
|
socket.onmessage = ({ data }) => handle(JSON.parse(data)); // replies and broadcasts are both { type, data } text
|
|
108
108
|
socket.onopen = () => reloadState(); // after reconnecting, read what was missed from the server
|
|
109
|
-
setInterval(() => socket.send('{"$dokebi":"ping-v1"}'), 15000);
|
|
109
|
+
setInterval(() => socket.send('{"$dokebi":"ping-v1","pong":true}'), 15000); // keeps it open under idleTimeoutMs; asks for a pong
|
|
110
110
|
```
|
|
111
111
|
|
|
112
|
-
-
|
|
112
|
+
- **A dead server (0.4.6, [D-0232](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0232-websocket-pong.md)).** A server that died without closing (a silent network drop, a dev reload that left the TCP connection open) leaves the client's socket "open" until TCP gives up, often 15 minutes; protocol pings do not help, because Node's and browsers' `WebSocket` answer them out of sight of the script. A ping that asks — `{"$dokebi":"ping-v1","pong":true}` — is answered with `{"$dokebi":"pong-v1"}` (sealed on a sealed connection; never a route's message). A plain `ping-v1` stays unanswered (pages before @dokebi/seal 0.4.5 would report the answer as an unknown frame), and a gateway before 0.4.6 answers neither. When nothing at all (no pong, no other frame) arrived for twice the ping interval, the server is gone: reconnect at once, without waiting for `close()` to finish. `@dokebi/websocket/client` does this for any WHATWG `WebSocket` (Node's own, `ws`, a browser's) and has no imports: `heartbeat(socket, { intervalMs, onSilent, requirePong })` pings and calls `onSilent` once; silence counts only after the first pong (an older server is not taken for a dead one) unless `requirePong: true`. `isControlFrame(data)` tells a `$dokebi` frame from a message, and `PING_FRAME`, `PING_PONG_FRAME` and `PONG_FRAME` are the frames. The @dokebi/seal client does the same by itself (close 4001, reconnect).
|
|
113
|
+
|
|
114
|
+
```ts snippet
|
|
115
|
+
import { heartbeat, isControlFrame } from '@dokebi/websocket/client';
|
|
116
|
+
|
|
117
|
+
function connectAgent(): void {
|
|
118
|
+
const socket = new WebSocket(CENTER_URL);
|
|
119
|
+
socket.addEventListener('message', ({ data }) => {
|
|
120
|
+
if (!isControlFrame(data)) handle(JSON.parse(String(data)));
|
|
121
|
+
});
|
|
122
|
+
heartbeat(socket, {
|
|
123
|
+
intervalMs: 15_000,
|
|
124
|
+
requirePong: true, // the center runs @dokebi/websocket 0.4.6 or later
|
|
125
|
+
onSilent: () => {
|
|
126
|
+
socket.close(4001, 'Server silent');
|
|
127
|
+
connectAgent(); // now, not on the close event of a dead connection
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
}
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
- Broadcasts arrive as the bytes the server sent: a text frame when UTF-8 (`defineSocket`'s `{ type, data }` JSON), otherwise a binary frame. There is no envelope to unwrap (`delivery-v1`) and no ACK to send. The old browser entry `DeliveryReceiver` was removed in 0.2.0 (`@dokebi/websocket/client` is now the heartbeat above, 0.4.6). Use only the standard `WebSocket` API. The `{"$dokebi":"ack-v1"}` that old pages send is ignored, not closed (debug `ACK_IGNORED`).
|
|
113
134
|
- Broadcasts sent while disconnected or while closed as a slow consumer never come again. The screen reads the latest state from the server after reconnecting.
|
|
114
135
|
- Close codes: 4426 reload, 4409 `Replaced` (the same tenant, member and clientId connected again, on any server: the newest connection wins and the older one is closed; with a hub before that rule the newer one is refused instead, 4409 `Duplicate client`), 4408 idle, 1013 hub unavailable, slow consumer, or a replay nonce store that is full (D-0075) or failed (D-0096) (`Try again later`), 1012 server shutting down, 1011 unhandled handler error, 4415 sealed host but no `dokebi.seal` offered, 4400 sealed frame refused (§4a). 4400 and 4415 repeat on reconnect, so do not reconnect. Never reconnect after 4409 with the same clientId: it would replace the newer connection of that clientId, and the two would replace each other in turn. A tab that must stay live (a duplicated tab copies sessionStorage) takes a new clientId and connects again. A tab whose old socket was half open (a network switch) is not affected: its new connection is the newer one.
|
|
115
136
|
|
package/README.md
CHANGED
|
@@ -75,7 +75,7 @@ stop blocks new work, waits for received handlers and broadcasts being sent, the
|
|
|
75
75
|
- `defineSocket({ presence: true })` sends `{ type: 'presence', data: { tenant, joined, left } }` to each connection. Given a function, that function handles it as `(change, socket)`.
|
|
76
76
|
- The first notice a server receives may list connections that existed before as `joined`. Screens should read the list again when this message arrives.
|
|
77
77
|
|
|
78
|
-
**Is the page alive (`idleTimeoutMs`):** the browser's network layer answers WebSocket pings, so even a page frozen in bfcache or with stopped scripts looks alive. With `idleTimeoutMs` (default 0, off), a connection whose client sent nothing for that long is closed with `4408 Idle`. The client sends `{"$dokebi":"ping-v1"}` periodically from page script to show it is alive. This control frame never reaches the route.
|
|
78
|
+
**Is the page alive (`idleTimeoutMs`):** the browser's network layer answers WebSocket pings, so even a page frozen in bfcache or with stopped scripts looks alive. With `idleTimeoutMs` (default 0, off), a connection whose client sent nothing for that long is closed with `4408 Idle`. The client sends `{"$dokebi":"ping-v1"}` periodically from page script to show it is alive. This control frame never reaches the route. With `"pong": true` in it (0.4.6, D-0232) the gateway answers `{"$dokebi":"pong-v1"}`, so a client hears a server that died while its TCP connection stayed open: `heartbeat` of `@dokebi/websocket/client` pings and reports twice the interval of silence.
|
|
79
79
|
|
|
80
80
|
**Connection lifecycle logs:** at debug it logs connect (`WebSocket connected`: connection ID, tenant, member, clientId, remote address, User-Agent, `Sec-Purpose`) and close (`WebSocket closed`: close code, reason, duration).
|
|
81
81
|
|
package/dist/client.d.ts
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
/** App-level keep-alive (D-0033): keeps a connection open under `idleTimeoutMs`; no answer. */
|
|
2
|
+
export declare const PING_FRAME = "{\"$dokebi\":\"ping-v1\"}";
|
|
3
|
+
/** The same ping asking for an answer (@dokebi/websocket 0.4.6, D-0232). Older servers stay silent. */
|
|
4
|
+
export declare const PING_PONG_FRAME = "{\"$dokebi\":\"ping-v1\",\"pong\":true}";
|
|
5
|
+
/** The gateway's answer to {@link PING_PONG_FRAME}; never a route's message. */
|
|
6
|
+
export declare const PONG_FRAME = "{\"$dokebi\":\"pong-v1\"}";
|
|
7
|
+
/** A `$dokebi` control frame (a pong, a sealed hello): not a route's message. */
|
|
8
|
+
export declare function isControlFrame(data: unknown): boolean;
|
|
9
|
+
/** What the heartbeat needs of a socket: the WHATWG shape (`ws` has it too). */
|
|
10
|
+
export interface HeartbeatSocket {
|
|
11
|
+
readonly readyState: number;
|
|
12
|
+
send(data: string): void;
|
|
13
|
+
addEventListener(type: 'open' | 'message' | 'close', listener: () => void): void;
|
|
14
|
+
removeEventListener(type: 'open' | 'message' | 'close', listener: () => void): void;
|
|
15
|
+
}
|
|
16
|
+
export interface HeartbeatOptions {
|
|
17
|
+
/** Ping interval (default 15000). Silence is declared after twice this. */
|
|
18
|
+
readonly intervalMs?: number;
|
|
19
|
+
/**
|
|
20
|
+
* Called once when the server sent nothing for twice the interval (the heartbeat has stopped).
|
|
21
|
+
* Reconnect from here: `close()` on a dead connection may not end before TCP gives up, so do not
|
|
22
|
+
* wait for its `close` event.
|
|
23
|
+
*/
|
|
24
|
+
readonly onSilent: () => void;
|
|
25
|
+
/**
|
|
26
|
+
* Count silence from the start even before the first pong (default false: only after one, so an
|
|
27
|
+
* older server that never answers is not taken for a dead one). Set it when the server is known
|
|
28
|
+
* to run @dokebi/websocket 0.4.6 or later.
|
|
29
|
+
*/
|
|
30
|
+
readonly requirePong?: boolean;
|
|
31
|
+
}
|
|
32
|
+
export interface Heartbeat {
|
|
33
|
+
/** Stops pinging and watching (also done by the socket's `close` and by `onSilent`). */
|
|
34
|
+
stop(): void;
|
|
35
|
+
/** Whether the server has answered a ping on this connection. */
|
|
36
|
+
readonly answered: boolean;
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* Pings the server every `intervalMs` asking for a pong, and calls `onSilent` when nothing (no
|
|
40
|
+
* pong, no other frame) arrived for twice the interval. Any frame counts as a sign of life, so a
|
|
41
|
+
* busy connection is never declared silent. One heartbeat per socket; start it right after
|
|
42
|
+
* creating the socket (it waits for `open`).
|
|
43
|
+
*/
|
|
44
|
+
export declare function heartbeat(socket: HeartbeatSocket, options: HeartbeatOptions): Heartbeat;
|
package/dist/client.js
ADDED
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// @dokebi/websocket/client (D-0232): the keep-alive frames and a heartbeat for a client that talks
|
|
2
|
+
// to a Dokebi socket with a plain WebSocket — Node's built-in `WebSocket`, the `ws` package, or a
|
|
3
|
+
// browser's. No imports: it runs wherever a WebSocket does.
|
|
4
|
+
//
|
|
5
|
+
// A socket to a server that died without closing (a silent network drop, a dev reload that left
|
|
6
|
+
// the TCP connection open) stays "open" until TCP gives up, often many minutes. Protocol pings
|
|
7
|
+
// do not help: Node's and browsers' WebSocket answer them out of sight of the script. The client
|
|
8
|
+
// asks with each app-level ping (`pong: true`), the gateway answers `pong-v1`, and silence past
|
|
9
|
+
// twice the interval means the server is gone.
|
|
10
|
+
/** App-level keep-alive (D-0033): keeps a connection open under `idleTimeoutMs`; no answer. */
|
|
11
|
+
export const PING_FRAME = '{"$dokebi":"ping-v1"}';
|
|
12
|
+
/** The same ping asking for an answer (@dokebi/websocket 0.4.6, D-0232). Older servers stay silent. */
|
|
13
|
+
export const PING_PONG_FRAME = '{"$dokebi":"ping-v1","pong":true}';
|
|
14
|
+
/** The gateway's answer to {@link PING_PONG_FRAME}; never a route's message. */
|
|
15
|
+
export const PONG_FRAME = '{"$dokebi":"pong-v1"}';
|
|
16
|
+
/** A `$dokebi` control frame (a pong, a sealed hello): not a route's message. */
|
|
17
|
+
export function isControlFrame(data) {
|
|
18
|
+
return typeof data === 'string' && data.startsWith('{"$dokebi":');
|
|
19
|
+
}
|
|
20
|
+
const OPEN = 1;
|
|
21
|
+
const DEFAULT_INTERVAL_MS = 15_000;
|
|
22
|
+
/**
|
|
23
|
+
* Pings the server every `intervalMs` asking for a pong, and calls `onSilent` when nothing (no
|
|
24
|
+
* pong, no other frame) arrived for twice the interval. Any frame counts as a sign of life, so a
|
|
25
|
+
* busy connection is never declared silent. One heartbeat per socket; start it right after
|
|
26
|
+
* creating the socket (it waits for `open`).
|
|
27
|
+
*/
|
|
28
|
+
export function heartbeat(socket, options) {
|
|
29
|
+
const intervalMs = options.intervalMs ?? DEFAULT_INTERVAL_MS;
|
|
30
|
+
if (!Number.isSafeInteger(intervalMs) || intervalMs < 10)
|
|
31
|
+
throw new RangeError('heartbeat intervalMs must be an integer of at least 10');
|
|
32
|
+
if (typeof options.onSilent !== 'function')
|
|
33
|
+
throw new TypeError('heartbeat needs onSilent');
|
|
34
|
+
let answered = false;
|
|
35
|
+
let last = Date.now();
|
|
36
|
+
let timer;
|
|
37
|
+
let stopped = false;
|
|
38
|
+
const onMessage = (event) => {
|
|
39
|
+
last = Date.now();
|
|
40
|
+
const data = event?.data;
|
|
41
|
+
if (data === PONG_FRAME ||
|
|
42
|
+
(typeof data === 'string' && data.startsWith('{"$dokebi":"pong-v1"')))
|
|
43
|
+
answered = true;
|
|
44
|
+
};
|
|
45
|
+
const tick = () => {
|
|
46
|
+
if (stopped || socket.readyState !== OPEN)
|
|
47
|
+
return;
|
|
48
|
+
if ((answered || options.requirePong === true) && Date.now() - last > 2 * intervalMs) {
|
|
49
|
+
stop();
|
|
50
|
+
options.onSilent();
|
|
51
|
+
return;
|
|
52
|
+
}
|
|
53
|
+
socket.send(PING_PONG_FRAME);
|
|
54
|
+
};
|
|
55
|
+
const begin = () => {
|
|
56
|
+
if (stopped || timer !== undefined)
|
|
57
|
+
return;
|
|
58
|
+
last = Date.now();
|
|
59
|
+
timer = setInterval(tick, intervalMs);
|
|
60
|
+
// A process that only waits on its socket must still be able to exit when it closes.
|
|
61
|
+
timer.unref?.();
|
|
62
|
+
tick();
|
|
63
|
+
};
|
|
64
|
+
const stop = () => {
|
|
65
|
+
if (stopped)
|
|
66
|
+
return;
|
|
67
|
+
stopped = true;
|
|
68
|
+
if (timer !== undefined)
|
|
69
|
+
clearInterval(timer);
|
|
70
|
+
socket.removeEventListener('open', begin);
|
|
71
|
+
socket.removeEventListener('message', onMessage);
|
|
72
|
+
socket.removeEventListener('close', stop);
|
|
73
|
+
};
|
|
74
|
+
socket.addEventListener('message', onMessage);
|
|
75
|
+
socket.addEventListener('close', stop);
|
|
76
|
+
if (socket.readyState === OPEN)
|
|
77
|
+
begin();
|
|
78
|
+
else
|
|
79
|
+
socket.addEventListener('open', begin);
|
|
80
|
+
return {
|
|
81
|
+
stop,
|
|
82
|
+
get answered() {
|
|
83
|
+
return answered;
|
|
84
|
+
},
|
|
85
|
+
};
|
|
86
|
+
}
|
package/dist/gateway.js
CHANGED
|
@@ -3,6 +3,7 @@ import { randomUUID } from 'node:crypto';
|
|
|
3
3
|
import { setTimeout as delay, setImmediate as immediate } from 'node:timers/promises';
|
|
4
4
|
import { diagnostics } from '@dokebi/core/libraries';
|
|
5
5
|
import { runBeforeHijack } from '@dokebi/web/points';
|
|
6
|
+
import { PONG_FRAME } from './client.js';
|
|
6
7
|
import { WebsocketError } from './errors.js';
|
|
7
8
|
import { PLAIN_PROTOCOL, SEAL_PROTOCOL, } from './types.js';
|
|
8
9
|
/** `WebSocket.OPEN` of ws (a constant, so ws itself loads only when a route needs it). */
|
|
@@ -923,7 +924,7 @@ export class Gateway {
|
|
|
923
924
|
this.#refuse(value, id, error);
|
|
924
925
|
return;
|
|
925
926
|
}
|
|
926
|
-
if (text.charCodeAt(0) === 123 && this.#control(text, id))
|
|
927
|
+
if (text.charCodeAt(0) === 123 && this.#control(text, id, value))
|
|
927
928
|
return;
|
|
928
929
|
if (!this.#authorized(value) || !value.registration)
|
|
929
930
|
return;
|
|
@@ -932,7 +933,7 @@ export class Gateway {
|
|
|
932
933
|
return;
|
|
933
934
|
}
|
|
934
935
|
// Control frames are answered here, outside the route's message queue.
|
|
935
|
-
if (bytes[0] === 123 && this.#control(bytes.toString(), id))
|
|
936
|
+
if (bytes[0] === 123 && this.#control(bytes.toString(), id, value))
|
|
936
937
|
return;
|
|
937
938
|
if (this.#closing)
|
|
938
939
|
return;
|
|
@@ -970,7 +971,7 @@ export class Gateway {
|
|
|
970
971
|
* Answers a `$dokebi` control frame (ping-v1, ack-v1); false when `text` is not one, so the
|
|
971
972
|
* route gets it.
|
|
972
973
|
*/
|
|
973
|
-
#control(text, id) {
|
|
974
|
+
#control(text, id, value) {
|
|
974
975
|
let control;
|
|
975
976
|
try {
|
|
976
977
|
control = JSON.parse(text);
|
|
@@ -978,9 +979,14 @@ export class Gateway {
|
|
|
978
979
|
catch {
|
|
979
980
|
// dokebi-check: allow empty-catch a frame that is not JSON is the route's payload; the route owns its parsing
|
|
980
981
|
}
|
|
981
|
-
|
|
982
|
-
|
|
982
|
+
if (control?.$dokebi === 'ping-v1') {
|
|
983
|
+
// The client is alive (idleTimeoutMs). A ping that asks (`pong: true`, D-0232) is answered,
|
|
984
|
+
// so a client hears a dead server; a plain ping stays silent (pages before 0.4.6 of
|
|
985
|
+
// @dokebi/seal report an unknown frame). Sealed like every frame; #send logs its failures.
|
|
986
|
+
if (control.pong === true)
|
|
987
|
+
void this.#send(value, PONG_FRAME);
|
|
983
988
|
return true;
|
|
989
|
+
}
|
|
984
990
|
// A page loaded before D-0057 still acknowledges broadcasts: nothing to do, and no
|
|
985
991
|
// reason to close it. Counted at debug until it reloads.
|
|
986
992
|
if (control?.$dokebi === 'ack-v1') {
|
package/dist/index.js
CHANGED
|
@@ -59,7 +59,7 @@ class WebsocketRuntime {
|
|
|
59
59
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
60
60
|
export const createPlugin = definePlugin({
|
|
61
61
|
name: 'dokebi-websocket',
|
|
62
|
-
version: '0.4.
|
|
62
|
+
version: '0.4.6',
|
|
63
63
|
core: '^0.4.2',
|
|
64
64
|
options,
|
|
65
65
|
contributes: [realtime],
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/websocket",
|
|
3
|
-
"version": "0.4.
|
|
3
|
+
"version": "0.4.6",
|
|
4
4
|
"description": "WebSocket routes on @dokebi/web with rooms and broadcast across servers through @dokebi/websocket-hub.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"dokebi",
|
|
@@ -22,6 +22,10 @@
|
|
|
22
22
|
"./dependency": {
|
|
23
23
|
"types": "./dist/dependency.d.ts",
|
|
24
24
|
"import": "./dist/dependency.js"
|
|
25
|
+
},
|
|
26
|
+
"./client": {
|
|
27
|
+
"types": "./dist/client.d.ts",
|
|
28
|
+
"import": "./dist/client.js"
|
|
25
29
|
}
|
|
26
30
|
},
|
|
27
31
|
"files": [
|