@thomas57/rennari-client-js 0.0.0-stage → 0.1.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/README +224 -0
- package/package.json +9 -4
- package/src/index.js +1 -0
- package/src/protocol.js +104 -0
- package/src/rennari.js +356 -0
- package/src/serializer.js +28 -0
- package/src/transport.js +72 -0
- package/README.md +0 -3
package/README
ADDED
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
Rennari Client JS
|
|
2
|
+
=================
|
|
3
|
+
|
|
4
|
+
JavaScript client for the Rennari protocol. Wire-compatible with
|
|
5
|
+
Mojo::Rennari::Server (Perl) and rennari-server-js (Node).
|
|
6
|
+
|
|
7
|
+
Small, secure, MessagePack- or JSON-framed WebSocket event layer with
|
|
8
|
+
custom events, namespaces, acknowledgements, automatic reconnection, and
|
|
9
|
+
connection state recovery.
|
|
10
|
+
|
|
11
|
+
Works in Node 18+ and any modern browser. No build step. No bundler.
|
|
12
|
+
|
|
13
|
+
STATUS
|
|
14
|
+
|
|
15
|
+
Working. Tested against both server implementations.
|
|
16
|
+
|
|
17
|
+
INSTALL
|
|
18
|
+
|
|
19
|
+
npm install @thomas/rennari-client-js
|
|
20
|
+
|
|
21
|
+
Or import directly from src if you clone the repo.
|
|
22
|
+
|
|
23
|
+
QUICK START
|
|
24
|
+
|
|
25
|
+
import { Rennari } from '@thomas/rennari-client-js';
|
|
26
|
+
|
|
27
|
+
const client = new Rennari('wss://example.com/ws?token=secret');
|
|
28
|
+
|
|
29
|
+
client.on('connect', () => {
|
|
30
|
+
console.log('connected', client.sessionId);
|
|
31
|
+
client.emit('chat', { room: 'lobby', text: 'hi' });
|
|
32
|
+
});
|
|
33
|
+
|
|
34
|
+
client.on('chat', (p) => console.log(p.from, ':', p.text));
|
|
35
|
+
client.on('disconnect', ({ code, reason }) => console.log(code, reason));
|
|
36
|
+
|
|
37
|
+
await client.connect();
|
|
38
|
+
|
|
39
|
+
CORE CONCEPTS
|
|
40
|
+
|
|
41
|
+
Frames
|
|
42
|
+
|
|
43
|
+
Every message is a map:
|
|
44
|
+
|
|
45
|
+
{ e, d, id?, o?, n? }
|
|
46
|
+
|
|
47
|
+
- e - event name, [A-Za-z0-9_.:-]{1,64}
|
|
48
|
+
- d - payload
|
|
49
|
+
- id - optional acknowledgement id
|
|
50
|
+
- o - optional offset, present when the server has recovery enabled
|
|
51
|
+
- n - optional namespace, omitted for /
|
|
52
|
+
|
|
53
|
+
The wire format is identical on both server implementations. If the
|
|
54
|
+
server is configured with serializer: 'json', the client must be too:
|
|
55
|
+
|
|
56
|
+
new Rennari(url, { serializer: 'json' });
|
|
57
|
+
|
|
58
|
+
Events
|
|
59
|
+
|
|
60
|
+
client.on(event, handler);
|
|
61
|
+
client.off(event, handler);
|
|
62
|
+
client.emit(event, payload);
|
|
63
|
+
|
|
64
|
+
The client-level methods operate on the default / namespace. Local
|
|
65
|
+
lifecycle events also fire there:
|
|
66
|
+
|
|
67
|
+
client.on('connect', () => {});
|
|
68
|
+
client.on('disconnect', ({ code, reason }) => {});
|
|
69
|
+
client.on('error', (err) => {});
|
|
70
|
+
client.on('ack_timeout', ({ event, payload }) => {});
|
|
71
|
+
client.on('reconnect_attempt', ({ attempt, delay }) => {});
|
|
72
|
+
client.on('reconnect_failed', () => {});
|
|
73
|
+
client.on('recovered', ({ offset }) => {});
|
|
74
|
+
|
|
75
|
+
Namespaces
|
|
76
|
+
|
|
77
|
+
const chat = client.of('/chat');
|
|
78
|
+
|
|
79
|
+
chat.on('message', (p) => {});
|
|
80
|
+
chat.emit('message', { text: 'hi' });
|
|
81
|
+
|
|
82
|
+
Every non-default namespace is declared to the server on connect and on
|
|
83
|
+
reconnect. Incoming frames are dispatched by their n field. A frame for
|
|
84
|
+
a namespace the client has not joined on the server causes a close with
|
|
85
|
+
code 4005.
|
|
86
|
+
|
|
87
|
+
Acknowledgements
|
|
88
|
+
|
|
89
|
+
const ack = await client.emitWithAck('chat', { text: 'hi' }, {
|
|
90
|
+
timeout: 3000,
|
|
91
|
+
retries: 2,
|
|
92
|
+
});
|
|
93
|
+
|
|
94
|
+
The client assigns an id, sends the frame, and waits for rennari_ack.
|
|
95
|
+
If no ack arrives within timeout milliseconds, the frame is resent up to
|
|
96
|
+
retries times. When retries are exhausted, the promise rejects and the
|
|
97
|
+
ack_timeout local event fires.
|
|
98
|
+
|
|
99
|
+
Duplicate delivery is possible by design. Handlers on the server should
|
|
100
|
+
be idempotent if the application uses retries.
|
|
101
|
+
|
|
102
|
+
Reconnection
|
|
103
|
+
|
|
104
|
+
On by default:
|
|
105
|
+
|
|
106
|
+
new Rennari(url, {
|
|
107
|
+
reconnection: true,
|
|
108
|
+
reconnectionDelay: 1000,
|
|
109
|
+
reconnectionDelayMax: 5000,
|
|
110
|
+
reconnectionAttempts: Infinity,
|
|
111
|
+
reconnectionJitter: 0.5,
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
When the WebSocket closes unexpectedly, the client reconnects with
|
|
115
|
+
exponential backoff plus jitter. Before each attempt, reconnect_attempt
|
|
116
|
+
fires. When attempts are exhausted, reconnect_failed fires. On
|
|
117
|
+
successful reconnect, connect fires again.
|
|
118
|
+
|
|
119
|
+
While disconnected, emit() queues the frame in an outbox. The queue is
|
|
120
|
+
flushed on the next connect. If reconnection is off, emit() throws when
|
|
121
|
+
not connected.
|
|
122
|
+
|
|
123
|
+
Recovery
|
|
124
|
+
|
|
125
|
+
When the server has recovery enabled, it issues a session id at
|
|
126
|
+
handshake. The client stores it as client.sessionId and tracks the
|
|
127
|
+
server's offset as client.lastOffset.
|
|
128
|
+
|
|
129
|
+
If the connection drops and reconnects within the server's recovery
|
|
130
|
+
window, the client sends rennari_resume with the session id and last
|
|
131
|
+
offset. The server replays missed frames, re-attaches namespaces and
|
|
132
|
+
rooms, and replies rennari_resumed with the transferred session id. The
|
|
133
|
+
client then fires recovered.
|
|
134
|
+
|
|
135
|
+
new Rennari(url, {
|
|
136
|
+
recovery: true,
|
|
137
|
+
recoveryWindow: 120000,
|
|
138
|
+
});
|
|
139
|
+
|
|
140
|
+
Both recovery and reconnection must be enabled for session recovery to
|
|
141
|
+
work. Without reconnection, the client never tries to resume.
|
|
142
|
+
|
|
143
|
+
DISCONNECT
|
|
144
|
+
|
|
145
|
+
client.disconnect();
|
|
146
|
+
client.disconnect(4000, 'user_exit');
|
|
147
|
+
|
|
148
|
+
Intentional disconnect does not trigger reconnection.
|
|
149
|
+
|
|
150
|
+
CONFIGURATION
|
|
151
|
+
|
|
152
|
+
new Rennari(url, {
|
|
153
|
+
serializer: 'msgpack', // or 'json'
|
|
154
|
+
maxBytes: 64 * 1024, // max incoming frame size
|
|
155
|
+
ackTimeout: 5000, // ms, default per emitWithAck
|
|
156
|
+
retries: 3, // default per emitWithAck
|
|
157
|
+
reconnection: true,
|
|
158
|
+
reconnectionDelay: 1000,
|
|
159
|
+
reconnectionDelayMax: 5000,
|
|
160
|
+
reconnectionAttempts: Infinity,
|
|
161
|
+
reconnectionJitter: 0.5,
|
|
162
|
+
recovery: true,
|
|
163
|
+
recoveryWindow: 120000,
|
|
164
|
+
});
|
|
165
|
+
|
|
166
|
+
NODE VERSUS BROWSER
|
|
167
|
+
|
|
168
|
+
In the browser, globalThis.WebSocket exists. In Node 18 and 20, it
|
|
169
|
+
does not, so the ws package must be provided:
|
|
170
|
+
|
|
171
|
+
import { WebSocket } from 'ws';
|
|
172
|
+
import { setWebSocket, Rennari } from '@thomas/rennari-client-js';
|
|
173
|
+
|
|
174
|
+
setWebSocket(WebSocket);
|
|
175
|
+
|
|
176
|
+
Node 22+ has a built-in WebSocket and does not need the ws package.
|
|
177
|
+
|
|
178
|
+
In both environments, binary WebSocket frames are used. binaryType is
|
|
179
|
+
set to 'arraybuffer' by the transport.
|
|
180
|
+
|
|
181
|
+
CLOSE CODES
|
|
182
|
+
|
|
183
|
+
The server closes with:
|
|
184
|
+
|
|
185
|
+
- 4002 - bad frame
|
|
186
|
+
- 4003 - unknown event
|
|
187
|
+
- 4004 - handler error
|
|
188
|
+
- 4005 - unknown namespace
|
|
189
|
+
- 4006 - recovery disabled but client sent rennari_resume
|
|
190
|
+
|
|
191
|
+
These arrive in the disconnect local event as { code, reason }.
|
|
192
|
+
|
|
193
|
+
SECURITY NOTES
|
|
194
|
+
|
|
195
|
+
The token is passed in the URL query string in the examples. That is
|
|
196
|
+
for demonstration only. In production, use one of:
|
|
197
|
+
|
|
198
|
+
- HttpOnly cookies with an Origin check on the server.
|
|
199
|
+
- First-message auth: connect without credentials, then emit an 'auth'
|
|
200
|
+
event with the token as the first message. The server enforces a
|
|
201
|
+
timeout and closes the connection if no valid auth arrives.
|
|
202
|
+
|
|
203
|
+
The framework does not store tokens. It does not log frame payloads. It
|
|
204
|
+
rejects frames larger than maxBytes before decoding. It rejects event
|
|
205
|
+
names, ids, offsets, and namespaces that do not match the protocol
|
|
206
|
+
grammar.
|
|
207
|
+
|
|
208
|
+
EXAMPLES
|
|
209
|
+
|
|
210
|
+
A Node smoke test is in examples/node.mjs. It connects to a running
|
|
211
|
+
Rennari server, exercises custom events, namespaces, acks, and recovery
|
|
212
|
+
across a forced disconnect.
|
|
213
|
+
|
|
214
|
+
node examples/node.mjs <port>
|
|
215
|
+
|
|
216
|
+
Integration tests in tests/integration.test.js run the same client
|
|
217
|
+
against a server spawned from the Perl repo. Skipped if
|
|
218
|
+
RENNARI_PERL_DIR is unset.
|
|
219
|
+
|
|
220
|
+
RENNARI_PERL_DIR=/path/to/mojo-rennari npm test
|
|
221
|
+
|
|
222
|
+
LICENSE
|
|
223
|
+
|
|
224
|
+
MIT.
|
package/package.json
CHANGED
|
@@ -1,6 +1,11 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@thomas57/rennari-client-js",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"main": "src/index.js",
|
|
6
|
+
"files": ["src"],
|
|
7
|
+
"dependencies": {
|
|
8
|
+
"@msgpack/msgpack": "^3.0.0",
|
|
9
|
+
"ws": "^8.18.0"
|
|
10
|
+
}
|
|
11
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export const VERSION = '0.1.0';
|
package/src/protocol.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
import { encode, decode } from '@msgpack/msgpack';
|
|
2
|
+
|
|
3
|
+
export const DEFAULT_MAX_BYTES = 64 * 1024;
|
|
4
|
+
|
|
5
|
+
const EVENT_RE = /^[A-Za-z0-9_.:-]{1,64}$/;
|
|
6
|
+
const NSP_RE = /^\/[A-Za-z0-9_.:/-]{0,63}$/;
|
|
7
|
+
const ID_RE = /^[0-9]{1,20}$/;
|
|
8
|
+
const OFFSET_RE = /^[0-9]+$/;
|
|
9
|
+
|
|
10
|
+
export function validEventName(name) {
|
|
11
|
+
return typeof name === 'string' && EVENT_RE.test(name);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function validId(id) {
|
|
15
|
+
if (id === undefined || id === null) return false;
|
|
16
|
+
return ID_RE.test(String(id));
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function validOffset(o) {
|
|
20
|
+
if (o === undefined || o === null) return false;
|
|
21
|
+
return OFFSET_RE.test(String(o));
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function validNamespaceName(name) {
|
|
25
|
+
return typeof name === 'string' && NSP_RE.test(name);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function checkSerializer(s) {
|
|
29
|
+
const v = s ?? 'msgpack';
|
|
30
|
+
if (v !== 'msgpack' && v !== 'json') {
|
|
31
|
+
throw new Error(`unsupported serializer '${v}'`);
|
|
32
|
+
}
|
|
33
|
+
return v;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function encodeFrame(event, payload, opts = {}) {
|
|
37
|
+
if (!validEventName(event)) {
|
|
38
|
+
throw new Error('encodeFrame: invalid event name');
|
|
39
|
+
}
|
|
40
|
+
const serializer = checkSerializer(opts.serializer);
|
|
41
|
+
const frame = { e: event, d: payload };
|
|
42
|
+
|
|
43
|
+
if (opts.id !== undefined && opts.id !== null) {
|
|
44
|
+
if (!validId(opts.id)) throw new Error('encodeFrame: invalid id');
|
|
45
|
+
frame.id = Number(opts.id);
|
|
46
|
+
}
|
|
47
|
+
if (opts.offset !== undefined && opts.offset !== null) {
|
|
48
|
+
if (!validOffset(opts.offset)) throw new Error('encodeFrame: invalid offset');
|
|
49
|
+
frame.o = Number(opts.offset);
|
|
50
|
+
}
|
|
51
|
+
if (opts.namespace !== undefined && opts.namespace !== null && opts.namespace !== '/') {
|
|
52
|
+
if (!validNamespaceName(opts.namespace)) {
|
|
53
|
+
throw new Error('encodeFrame: invalid namespace');
|
|
54
|
+
}
|
|
55
|
+
frame.n = opts.namespace;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
if (serializer === 'json') {
|
|
59
|
+
return new TextEncoder().encode(JSON.stringify(frame));
|
|
60
|
+
}
|
|
61
|
+
return encode(frame);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function decodeFrame(bytes, opts = {}) {
|
|
65
|
+
if (bytes === undefined || bytes === null) return null;
|
|
66
|
+
let buf;
|
|
67
|
+
if (bytes instanceof Uint8Array) buf = bytes;
|
|
68
|
+
else if (bytes instanceof ArrayBuffer) buf = new Uint8Array(bytes);
|
|
69
|
+
else return null;
|
|
70
|
+
|
|
71
|
+
const max = opts.max_bytes ?? DEFAULT_MAX_BYTES;
|
|
72
|
+
if (buf.length > max) return null;
|
|
73
|
+
|
|
74
|
+
const serializer = checkSerializer(opts.serializer);
|
|
75
|
+
|
|
76
|
+
let frame;
|
|
77
|
+
try {
|
|
78
|
+
if (serializer === 'json') {
|
|
79
|
+
frame = JSON.parse(new TextDecoder().decode(buf));
|
|
80
|
+
} else {
|
|
81
|
+
frame = decode(buf);
|
|
82
|
+
}
|
|
83
|
+
} catch (_e) {
|
|
84
|
+
return null;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (!frame || typeof frame !== 'object' || Array.isArray(frame)) return null;
|
|
88
|
+
if (!validEventName(frame.e)) return null;
|
|
89
|
+
if (!Object.prototype.hasOwnProperty.call(frame, 'd')) return null;
|
|
90
|
+
|
|
91
|
+
if (Object.prototype.hasOwnProperty.call(frame, 'o')) {
|
|
92
|
+
if (!validOffset(frame.o)) return null;
|
|
93
|
+
frame.o = Number(frame.o);
|
|
94
|
+
}
|
|
95
|
+
if (Object.prototype.hasOwnProperty.call(frame, 'id')) {
|
|
96
|
+
if (!validId(frame.id)) return null;
|
|
97
|
+
frame.id = Number(frame.id);
|
|
98
|
+
}
|
|
99
|
+
if (Object.prototype.hasOwnProperty.call(frame, 'n')) {
|
|
100
|
+
if (!validNamespaceName(frame.n)) return null;
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
return frame;
|
|
104
|
+
}
|
package/src/rennari.js
ADDED
|
@@ -0,0 +1,356 @@
|
|
|
1
|
+
import { Transport, setWebSocket } from './transport.js';
|
|
2
|
+
import { resolveSerializer } from './serializer.js';
|
|
3
|
+
import {
|
|
4
|
+
encodeFrame,
|
|
5
|
+
decodeFrame,
|
|
6
|
+
validEventName,
|
|
7
|
+
} from './protocol.js';
|
|
8
|
+
|
|
9
|
+
export { setWebSocket };
|
|
10
|
+
|
|
11
|
+
const LOCAL_EVENTS = new Set([
|
|
12
|
+
'connect',
|
|
13
|
+
'disconnect',
|
|
14
|
+
'error',
|
|
15
|
+
'ack_timeout',
|
|
16
|
+
'reconnect_attempt',
|
|
17
|
+
'reconnect_failed',
|
|
18
|
+
'recovered',
|
|
19
|
+
]);
|
|
20
|
+
|
|
21
|
+
export class Rennari {
|
|
22
|
+
constructor(url, opts = {}) {
|
|
23
|
+
this.url = url;
|
|
24
|
+
this.serializer = resolveSerializer(opts.serializer);
|
|
25
|
+
this.maxBytes = opts.maxBytes ?? 64 * 1024;
|
|
26
|
+
this.defaultAckTimeout = opts.ackTimeout ?? 5000;
|
|
27
|
+
this.defaultRetries = opts.retries ?? 3;
|
|
28
|
+
this.defaultNamespace = '/';
|
|
29
|
+
|
|
30
|
+
this.reconnection = opts.reconnection ?? true;
|
|
31
|
+
this.reconnectionDelay = opts.reconnectionDelay ?? 1000;
|
|
32
|
+
this.reconnectionDelayMax = opts.reconnectionDelayMax ?? 5000;
|
|
33
|
+
this.reconnectionAttempts = opts.reconnectionAttempts ?? Infinity;
|
|
34
|
+
this.reconnectionJitter = opts.reconnectionJitter ?? 0.5;
|
|
35
|
+
|
|
36
|
+
this.recovery = opts.recovery ?? true;
|
|
37
|
+
this.recoveryWindow = opts.recoveryWindow ?? 120000;
|
|
38
|
+
|
|
39
|
+
this._transport = null;
|
|
40
|
+
this._handlers = new Map();
|
|
41
|
+
this._namespaces = new Map();
|
|
42
|
+
this._namespaces.set('/', this._makeNamespace('/'));
|
|
43
|
+
|
|
44
|
+
this._nextId = 0;
|
|
45
|
+
this._pending = new Map();
|
|
46
|
+
|
|
47
|
+
this._lastOffset = -1;
|
|
48
|
+
this._sessionId = null;
|
|
49
|
+
this._sessionExpiresAt = 0;
|
|
50
|
+
|
|
51
|
+
this._connectQueue = [];
|
|
52
|
+
this._outbox = [];
|
|
53
|
+
this._intentionalDisconnect = false;
|
|
54
|
+
this._reconnectAttempts = 0;
|
|
55
|
+
this._reconnectTimer = null;
|
|
56
|
+
this._connected = false;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
on(event, cb) { this._onEvent('/', event, cb); return this; }
|
|
60
|
+
off(event, cb) { this._offEvent('/', event, cb); return this; }
|
|
61
|
+
emit(event, payload) { return this._emit('/', event, payload, null); }
|
|
62
|
+
emitWithAck(event, payload, opts = {}) {
|
|
63
|
+
return this._emitWithAck('/', event, payload, opts);
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
of(name) {
|
|
67
|
+
let ns = this._namespaces.get(name);
|
|
68
|
+
if (!ns) {
|
|
69
|
+
ns = this._makeNamespace(name);
|
|
70
|
+
this._namespaces.set(name, ns);
|
|
71
|
+
}
|
|
72
|
+
return ns;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
get sessionId() { return this._sessionId; }
|
|
76
|
+
get lastOffset() { return this._lastOffset; }
|
|
77
|
+
get connected() { return this._connected; }
|
|
78
|
+
|
|
79
|
+
connect() {
|
|
80
|
+
this._intentionalDisconnect = false;
|
|
81
|
+
return this._open();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
disconnect(code = 1000, reason = 'client_disconnect') {
|
|
85
|
+
this._intentionalDisconnect = true;
|
|
86
|
+
if (this._reconnectTimer) {
|
|
87
|
+
clearTimeout(this._reconnectTimer);
|
|
88
|
+
this._reconnectTimer = null;
|
|
89
|
+
}
|
|
90
|
+
if (this._transport) this._transport.close(code, reason);
|
|
91
|
+
this._connected = false;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
_newTransport() {
|
|
95
|
+
return new Transport(this.url);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
_open() {
|
|
99
|
+
return new Promise((resolve, reject) => {
|
|
100
|
+
const transport = this._newTransport();
|
|
101
|
+
this._transport = transport;
|
|
102
|
+
let opened = false;
|
|
103
|
+
const stale = () => this._transport !== transport;
|
|
104
|
+
|
|
105
|
+
transport.on('open', () => {
|
|
106
|
+
if (stale()) return;
|
|
107
|
+
opened = true;
|
|
108
|
+
this._connected = true;
|
|
109
|
+
this._reconnectAttempts = 0;
|
|
110
|
+
|
|
111
|
+
const useResume = this.recovery
|
|
112
|
+
&& this._sessionId
|
|
113
|
+
&& Date.now() <= this._sessionExpiresAt;
|
|
114
|
+
if (useResume) {
|
|
115
|
+
transport.send(encodeFrame('rennari_resume', {
|
|
116
|
+
session_id: this._sessionId,
|
|
117
|
+
offset: this._lastOffset,
|
|
118
|
+
}, { serializer: this.serializer.name }));
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
for (const [name] of this._namespaces) {
|
|
122
|
+
if (name === '/') continue;
|
|
123
|
+
transport.send(encodeFrame('rennari_nsp', { name }, {
|
|
124
|
+
serializer: this.serializer.name,
|
|
125
|
+
}));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
const queued = this._outbox;
|
|
129
|
+
this._outbox = [];
|
|
130
|
+
for (const op of queued) {
|
|
131
|
+
try { op(transport); } catch (e) {
|
|
132
|
+
this._fireLocal('/', 'error', e);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
for (const fn of this._connectQueue) fn();
|
|
137
|
+
this._connectQueue = [];
|
|
138
|
+
|
|
139
|
+
this._fireLocal('/', 'connect');
|
|
140
|
+
resolve();
|
|
141
|
+
});
|
|
142
|
+
|
|
143
|
+
transport.on('message', (bytes) => {
|
|
144
|
+
if (stale()) return;
|
|
145
|
+
this._onMessage(bytes);
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
transport.on('close', (code, reason) => {
|
|
149
|
+
if (stale()) return;
|
|
150
|
+
this._connected = false;
|
|
151
|
+
if (this._sessionId) {
|
|
152
|
+
this._sessionExpiresAt = Date.now() + this.recoveryWindow;
|
|
153
|
+
}
|
|
154
|
+
this._fireLocal('/', 'disconnect', { code, reason });
|
|
155
|
+
|
|
156
|
+
if (!opened) {
|
|
157
|
+
reject(new Error(`rennari: connection closed before open (${code})`));
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
if (!this._intentionalDisconnect && this.reconnection) {
|
|
161
|
+
this._scheduleReconnect();
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
transport.on('error', (err) => {
|
|
166
|
+
if (stale()) return;
|
|
167
|
+
this._fireLocal('/', 'error', err);
|
|
168
|
+
if (!opened) reject(err);
|
|
169
|
+
});
|
|
170
|
+
|
|
171
|
+
transport.connect();
|
|
172
|
+
});
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
_scheduleReconnect() {
|
|
176
|
+
if (this._reconnectAttempts >= this.reconnectionAttempts) {
|
|
177
|
+
this._fireLocal('/', 'reconnect_failed');
|
|
178
|
+
return;
|
|
179
|
+
}
|
|
180
|
+
this._reconnectAttempts++;
|
|
181
|
+
const base = Math.min(
|
|
182
|
+
this.reconnectionDelay * Math.pow(2, this._reconnectAttempts - 1),
|
|
183
|
+
this.reconnectionDelayMax
|
|
184
|
+
);
|
|
185
|
+
const jitter = base * this.reconnectionJitter * (Math.random() * 2 - 1);
|
|
186
|
+
const delay = Math.max(
|
|
187
|
+
0,
|
|
188
|
+
Math.min(Math.floor(base + jitter), this.reconnectionDelayMax)
|
|
189
|
+
);
|
|
190
|
+
|
|
191
|
+
this._fireLocal('/', 'reconnect_attempt', {
|
|
192
|
+
attempt: this._reconnectAttempts,
|
|
193
|
+
delay,
|
|
194
|
+
});
|
|
195
|
+
|
|
196
|
+
this._reconnectTimer = setTimeout(() => {
|
|
197
|
+
this._reconnectTimer = null;
|
|
198
|
+
this._open().catch((e) => this._fireLocal('/', 'error', e));
|
|
199
|
+
}, delay);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
_makeNamespace(name) {
|
|
203
|
+
const self = this;
|
|
204
|
+
return {
|
|
205
|
+
name,
|
|
206
|
+
on(event, cb) { self._onEvent(name, event, cb); return this; },
|
|
207
|
+
off(event, cb) { self._offEvent(name, event, cb); return this; },
|
|
208
|
+
emit(event, payload) { return self._emit(name, event, payload, null); },
|
|
209
|
+
emitWithAck(event, payload, opts) {
|
|
210
|
+
return self._emitWithAck(name, event, payload, opts);
|
|
211
|
+
},
|
|
212
|
+
};
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
_onEvent(nsp, event, cb) {
|
|
216
|
+
if (!LOCAL_EVENTS.has(event) && !validEventName(event)) {
|
|
217
|
+
throw new Error(`invalid event name '${event}'`);
|
|
218
|
+
}
|
|
219
|
+
if (typeof cb !== 'function') throw new Error('handler must be a function');
|
|
220
|
+
const key = `${nsp}\u0000${event}`;
|
|
221
|
+
let list = this._handlers.get(key);
|
|
222
|
+
if (!list) {
|
|
223
|
+
list = [];
|
|
224
|
+
this._handlers.set(key, list);
|
|
225
|
+
}
|
|
226
|
+
list.push(cb);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
_offEvent(nsp, event, cb) {
|
|
230
|
+
const key = `${nsp}\u0000${event}`;
|
|
231
|
+
const list = this._handlers.get(key);
|
|
232
|
+
if (!list) return;
|
|
233
|
+
if (!cb) { this._handlers.delete(key); return; }
|
|
234
|
+
const i = list.indexOf(cb);
|
|
235
|
+
if (i >= 0) list.splice(i, 1);
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
_fireLocal(nsp, event, ...args) {
|
|
239
|
+
const list = this._handlers.get(`${nsp}\u0000${event}`) || [];
|
|
240
|
+
for (const cb of list.slice()) {
|
|
241
|
+
try { cb(...args); } catch (e) { console.error('rennari handler error', e); }
|
|
242
|
+
}
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
_emit(nsp, event, payload, id) {
|
|
246
|
+
if (!validEventName(event)) {
|
|
247
|
+
throw new Error(`invalid event name '${event}'`);
|
|
248
|
+
}
|
|
249
|
+
const writer = (transport) => {
|
|
250
|
+
const bytes = encodeFrame(event, payload, {
|
|
251
|
+
serializer: this.serializer.name,
|
|
252
|
+
id,
|
|
253
|
+
namespace: nsp,
|
|
254
|
+
});
|
|
255
|
+
transport.send(bytes);
|
|
256
|
+
};
|
|
257
|
+
if (this._transport && this._transport.isOpen()) {
|
|
258
|
+
writer(this._transport);
|
|
259
|
+
return;
|
|
260
|
+
}
|
|
261
|
+
if (!this.reconnection) {
|
|
262
|
+
throw new Error('rennari: not connected');
|
|
263
|
+
}
|
|
264
|
+
this._outbox.push(writer);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
_emitWithAck(nsp, event, payload, opts = {}) {
|
|
268
|
+
return new Promise((resolve, reject) => {
|
|
269
|
+
const timeout = opts.timeout ?? this.defaultAckTimeout;
|
|
270
|
+
const retries = opts.retries ?? this.defaultRetries;
|
|
271
|
+
const id = ++this._nextId;
|
|
272
|
+
const entry = {
|
|
273
|
+
nsp, event, payload, id, timeout, retries,
|
|
274
|
+
attempt: 0, resolve, reject, timer: null,
|
|
275
|
+
};
|
|
276
|
+
this._pending.set(id, entry);
|
|
277
|
+
this._sendPending(id);
|
|
278
|
+
});
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
_sendPending(id) {
|
|
282
|
+
const entry = this._pending.get(id);
|
|
283
|
+
if (!entry) return;
|
|
284
|
+
if (entry.attempt > entry.retries) {
|
|
285
|
+
this._pending.delete(id);
|
|
286
|
+
this._fireLocal('/', 'ack_timeout', {
|
|
287
|
+
event: entry.event,
|
|
288
|
+
payload: entry.payload,
|
|
289
|
+
});
|
|
290
|
+
entry.reject(new Error(`ack timeout for '${entry.event}'`));
|
|
291
|
+
return;
|
|
292
|
+
}
|
|
293
|
+
entry.attempt++;
|
|
294
|
+
try {
|
|
295
|
+
this._emit(entry.nsp, entry.event, entry.payload, entry.id);
|
|
296
|
+
} catch (e) {
|
|
297
|
+
this._pending.delete(id);
|
|
298
|
+
entry.reject(e);
|
|
299
|
+
return;
|
|
300
|
+
}
|
|
301
|
+
if (entry.timer) clearTimeout(entry.timer);
|
|
302
|
+
entry.timer = setTimeout(() => this._sendPending(id), entry.timeout);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
_onMessage(bytes) {
|
|
306
|
+
const frame = decodeFrame(bytes, {
|
|
307
|
+
serializer: this.serializer.name,
|
|
308
|
+
max_bytes: this.maxBytes,
|
|
309
|
+
});
|
|
310
|
+
if (!frame) {
|
|
311
|
+
this._fireLocal('/', 'error', new Error('bad frame'));
|
|
312
|
+
return;
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
if (frame.o !== undefined && frame.o > this._lastOffset) {
|
|
316
|
+
this._lastOffset = frame.o;
|
|
317
|
+
}
|
|
318
|
+
|
|
319
|
+
if (frame.e === 'rennari_session') {
|
|
320
|
+
this._sessionId = frame.d.id;
|
|
321
|
+
this._sessionExpiresAt = Date.now() + this.recoveryWindow;
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
if (frame.e === 'rennari_resumed') {
|
|
325
|
+
if (frame.d.session_id) {
|
|
326
|
+
this._sessionId = frame.d.session_id;
|
|
327
|
+
this._sessionExpiresAt = Date.now() + this.recoveryWindow;
|
|
328
|
+
}
|
|
329
|
+
this._fireLocal('/', 'recovered', { offset: frame.d.offset });
|
|
330
|
+
return;
|
|
331
|
+
}
|
|
332
|
+
if (frame.e === 'rennari_resume_failed') {
|
|
333
|
+
this._sessionId = null;
|
|
334
|
+
this._sessionExpiresAt = 0;
|
|
335
|
+
this._lastOffset = -1;
|
|
336
|
+
return;
|
|
337
|
+
}
|
|
338
|
+
if (frame.e === 'rennari_nsp_ok') {
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
if (frame.e === 'rennari_ack') {
|
|
342
|
+
const entry = this._pending.get(frame.d.id);
|
|
343
|
+
if (entry) {
|
|
344
|
+
clearTimeout(entry.timer);
|
|
345
|
+
this._pending.delete(frame.d.id);
|
|
346
|
+
entry.resolve(frame.d);
|
|
347
|
+
}
|
|
348
|
+
return;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
const nsp = frame.n ?? '/';
|
|
352
|
+
this._fireLocal(nsp, frame.e, frame.d, frame);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
export default Rennari;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { encode as mpEncode, decode as mpDecode } from '@msgpack/msgpack';
|
|
2
|
+
|
|
3
|
+
export function resolveSerializer(name) {
|
|
4
|
+
const s = name ?? 'msgpack';
|
|
5
|
+
if (s === 'msgpack') return msgpackSerializer;
|
|
6
|
+
if (s === 'json') return jsonSerializer;
|
|
7
|
+
throw new Error(`unsupported serializer '${s}'`);
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export const msgpackSerializer = {
|
|
11
|
+
name: 'msgpack',
|
|
12
|
+
encode(frame) {
|
|
13
|
+
return mpEncode(frame);
|
|
14
|
+
},
|
|
15
|
+
decode(bytes) {
|
|
16
|
+
return mpDecode(bytes);
|
|
17
|
+
},
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
export const jsonSerializer = {
|
|
21
|
+
name: 'json',
|
|
22
|
+
encode(frame) {
|
|
23
|
+
return new TextEncoder().encode(JSON.stringify(frame));
|
|
24
|
+
},
|
|
25
|
+
decode(bytes) {
|
|
26
|
+
return JSON.parse(new TextDecoder().decode(bytes));
|
|
27
|
+
},
|
|
28
|
+
};
|
package/src/transport.js
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
export class Transport {
|
|
2
|
+
constructor(url) {
|
|
3
|
+
this.url = url;
|
|
4
|
+
this.socket = null;
|
|
5
|
+
this.listeners = {
|
|
6
|
+
open: [],
|
|
7
|
+
message: [],
|
|
8
|
+
close: [],
|
|
9
|
+
error: [],
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
on(event, cb) {
|
|
14
|
+
if (!this.listeners[event]) throw new Error(`unknown transport event '${event}'`);
|
|
15
|
+
this.listeners[event].push(cb);
|
|
16
|
+
return this;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
emit(event, ...args) {
|
|
20
|
+
for (const cb of this.listeners[event] || []) {
|
|
21
|
+
try { cb(...args) } catch (_e) { /* listener errors do not break transport */ }
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
connect() {
|
|
26
|
+
const Ctor = pickWebSocketCtor();
|
|
27
|
+
const socket = new Ctor(this.url);
|
|
28
|
+
if ('binaryType' in socket) socket.binaryType = 'arraybuffer';
|
|
29
|
+
|
|
30
|
+
socket.addEventListener('open', () => this.emit('open'));
|
|
31
|
+
socket.addEventListener('message', (e) => this.emit('message', toBytes(e.data)));
|
|
32
|
+
socket.addEventListener('close', (e) => this.emit('close', e.code, e.reason));
|
|
33
|
+
socket.addEventListener('error', (e) => this.emit('error', e));
|
|
34
|
+
|
|
35
|
+
this.socket = socket;
|
|
36
|
+
return this;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
send(bytes) {
|
|
40
|
+
if (!this.socket) throw new Error('transport not connected');
|
|
41
|
+
this.socket.send(bytes);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
close(code, reason) {
|
|
45
|
+
if (!this.socket) return;
|
|
46
|
+
try { this.socket.close(code, reason) } catch (_e) { /* already closed */ }
|
|
47
|
+
this.socket = null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
isOpen() {
|
|
51
|
+
return !!(this.socket && this.socket.readyState === 1);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function toBytes(data) {
|
|
56
|
+
if (data instanceof Uint8Array) return data;
|
|
57
|
+
if (data instanceof ArrayBuffer) return new Uint8Array(data);
|
|
58
|
+
if (typeof data === 'string') return new TextEncoder().encode(data);
|
|
59
|
+
if (data && typeof data.arrayBuffer === 'function') {
|
|
60
|
+
return data.arrayBuffer().then((ab) => new Uint8Array(ab));
|
|
61
|
+
}
|
|
62
|
+
throw new Error('unsupported message data type');
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function pickWebSocketCtor() {
|
|
66
|
+
if (typeof globalThis.WebSocket === 'function') return globalThis.WebSocket;
|
|
67
|
+
throw new Error('no WebSocket implementation available; install the ws package and call setWebSocket');
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function setWebSocket(ctor) {
|
|
71
|
+
globalThis.WebSocket = ctor;
|
|
72
|
+
}
|
package/README.md
DELETED