@dim24/servin 0.2.2 → 1.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.md +805 -77
- package/index.js +1 -1
- package/package.json +1 -1
- package/src/server.js +229 -24
- package/src/servin.test.js +118 -1
- package/src/tree.js +641 -20
- package/src/utils.js +10 -0
- package/src/websocket.js +332 -6
package/src/utils.js
CHANGED
|
@@ -78,6 +78,16 @@ export class RedirectDescriptor {
|
|
|
78
78
|
}
|
|
79
79
|
}
|
|
80
80
|
|
|
81
|
+
export class AliasDescriptor {
|
|
82
|
+
constructor(target, options = {}) {
|
|
83
|
+
if (!target || (typeof target !== 'string' && typeof target !== 'function')) {
|
|
84
|
+
throw new TypeError('alias(target, options) requires a target URL/path string or resolver function');
|
|
85
|
+
}
|
|
86
|
+
this.target = target;
|
|
87
|
+
this.options = options;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
81
91
|
export function parseDuration(input, fallbackMs = 0) {
|
|
82
92
|
if (typeof input === 'number') return input;
|
|
83
93
|
if (typeof input !== 'string') return fallbackMs;
|
package/src/websocket.js
CHANGED
|
@@ -3,6 +3,40 @@ import { parseBytes, parseDuration } from './utils.js';
|
|
|
3
3
|
|
|
4
4
|
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11';
|
|
5
5
|
|
|
6
|
+
function createRingBuffer(capacity = 100) {
|
|
7
|
+
const cap = Math.max(1, capacity);
|
|
8
|
+
const items = new Array(cap);
|
|
9
|
+
let start = 0;
|
|
10
|
+
let size = 0;
|
|
11
|
+
|
|
12
|
+
return {
|
|
13
|
+
push(entry) {
|
|
14
|
+
const idx = (start + size) % cap;
|
|
15
|
+
items[idx] = entry;
|
|
16
|
+
if (size === cap) {
|
|
17
|
+
start = (start + 1) % cap;
|
|
18
|
+
} else {
|
|
19
|
+
size += 1;
|
|
20
|
+
}
|
|
21
|
+
},
|
|
22
|
+
getSince(afterSeq) {
|
|
23
|
+
if (afterSeq <= 0) return [];
|
|
24
|
+
if (size === 0) return null;
|
|
25
|
+
const oldestSeq = items[start].seq;
|
|
26
|
+
const newestSeq = items[(start + size - 1) % cap].seq;
|
|
27
|
+
if (afterSeq < oldestSeq - 1 || afterSeq > newestSeq) {
|
|
28
|
+
return null;
|
|
29
|
+
}
|
|
30
|
+
const out = [];
|
|
31
|
+
for (let i = 0; i < size; i += 1) {
|
|
32
|
+
const item = items[(start + i) % cap];
|
|
33
|
+
if (item.seq > afterSeq) out.push(item);
|
|
34
|
+
}
|
|
35
|
+
return out;
|
|
36
|
+
}
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
6
40
|
function encodeFrame(data, isBinary = false) {
|
|
7
41
|
const payload = isBinary
|
|
8
42
|
? Buffer.from(data)
|
|
@@ -38,6 +72,18 @@ function encodeControlFrame(opcode, payload = Buffer.alloc(0)) {
|
|
|
38
72
|
return Buffer.concat([header, payload]);
|
|
39
73
|
}
|
|
40
74
|
|
|
75
|
+
function setExclusiveRoom(socket, targetRoom) {
|
|
76
|
+
if (!targetRoom) return;
|
|
77
|
+
for (const joined of [...socket.rooms]) {
|
|
78
|
+
if (joined !== targetRoom) {
|
|
79
|
+
socket.leave(joined);
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
if (!socket.rooms.has(targetRoom)) {
|
|
83
|
+
socket.join(targetRoom);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
|
|
41
87
|
export class WebSocketBroker {
|
|
42
88
|
constructor() {
|
|
43
89
|
this.topics = new Map();
|
|
@@ -69,6 +115,28 @@ export class WebSocketBroker {
|
|
|
69
115
|
}
|
|
70
116
|
}
|
|
71
117
|
|
|
118
|
+
publishAll(data, excludeSocket = null, maxBufferedBytes = 0) {
|
|
119
|
+
const isBinary = data instanceof Uint8Array;
|
|
120
|
+
const envelope = isBinary
|
|
121
|
+
? data
|
|
122
|
+
: { type: 'broadcast', global: true, payload: data };
|
|
123
|
+
const frame = encodeFrame(envelope, isBinary);
|
|
124
|
+
const sentTo = new Set();
|
|
125
|
+
|
|
126
|
+
for (const set of this.topics.values()) {
|
|
127
|
+
for (const client of set) {
|
|
128
|
+
if (sentTo.has(client)) continue;
|
|
129
|
+
sentTo.add(client);
|
|
130
|
+
if (client === excludeSocket || !client.isOpen) continue;
|
|
131
|
+
if (maxBufferedBytes && client.bufferedAmount > maxBufferedBytes) {
|
|
132
|
+
client.close(1008, 'Backpressure limit exceeded');
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
client.rawSocket.write(frame);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
}
|
|
139
|
+
|
|
72
140
|
bindSession(sid, socket) {
|
|
73
141
|
if (!sid) return;
|
|
74
142
|
if (!this.sessionSockets.has(sid)) this.sessionSockets.set(sid, new Set());
|
|
@@ -95,7 +163,17 @@ export class WebSocketBroker {
|
|
|
95
163
|
}
|
|
96
164
|
|
|
97
165
|
export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, sessionId = null) {
|
|
98
|
-
|
|
166
|
+
if (typeof tcpSocket.setNoDelay === 'function') {
|
|
167
|
+
tcpSocket.setNoDelay(true);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const maxPayload = typeof config.maxPayloadBytes === 'number'
|
|
171
|
+
? config.maxPayloadBytes
|
|
172
|
+
: parseBytes(config.maxPayload || '1mb', 1024 ** 2);
|
|
173
|
+
const maxEventsPerSec = config.maxEventsPerSec ?? 0;
|
|
174
|
+
const maxBufferedBytes = typeof config.maxBufferedBytes === 'number'
|
|
175
|
+
? config.maxBufferedBytes
|
|
176
|
+
: parseBytes(config.maxBuffered || '1mb', 1024 ** 2);
|
|
99
177
|
const heartbeatMs = config.heartbeat ? parseDuration(config.heartbeat, 0) : 0;
|
|
100
178
|
const binaryMode = Boolean(config.binary);
|
|
101
179
|
|
|
@@ -107,6 +185,8 @@ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, s
|
|
|
107
185
|
let recvBuffer = headBuffer && headBuffer.length > 0 ? Buffer.from(headBuffer) : Buffer.alloc(0);
|
|
108
186
|
let fragmentedChunks = [];
|
|
109
187
|
let fragmentedOpcode = 0;
|
|
188
|
+
let rateWindowStart = Date.now();
|
|
189
|
+
let rateCount = 0;
|
|
110
190
|
|
|
111
191
|
const wakeReader = () => {
|
|
112
192
|
if (waitResolver) {
|
|
@@ -130,6 +210,8 @@ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, s
|
|
|
130
210
|
|
|
131
211
|
const sessionSocket = {
|
|
132
212
|
rawSocket: tcpSocket,
|
|
213
|
+
state: {},
|
|
214
|
+
rooms: joinedTopics,
|
|
133
215
|
get isOpen() {
|
|
134
216
|
return !closed && !tcpSocket.destroyed;
|
|
135
217
|
},
|
|
@@ -144,13 +226,53 @@ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, s
|
|
|
144
226
|
joinedTopics.delete(topic);
|
|
145
227
|
broker.unsubscribe(topic, sessionSocket);
|
|
146
228
|
},
|
|
147
|
-
broadcast(
|
|
148
|
-
|
|
229
|
+
broadcast(topicOrData, maybeData, opts = {}) {
|
|
230
|
+
if (typeof topicOrData === 'string') {
|
|
231
|
+
const topic = topicOrData;
|
|
232
|
+
const data = maybeData;
|
|
233
|
+
const options = (opts && typeof opts === 'object') ? opts : {};
|
|
234
|
+
const set = broker.topics.get(topic);
|
|
235
|
+
if (!set || set.size === 0) return;
|
|
236
|
+
|
|
237
|
+
const isBinary = data instanceof Uint8Array;
|
|
238
|
+
const envelope = isBinary
|
|
239
|
+
? data
|
|
240
|
+
: { type: 'broadcast', room: topic, global: false, payload: data };
|
|
241
|
+
const frame = encodeFrame(envelope, isBinary);
|
|
242
|
+
const exclude = options.except ?? null;
|
|
243
|
+
|
|
244
|
+
for (const client of set) {
|
|
245
|
+
if (client === exclude || closed || client.rawSocket.destroyed) continue;
|
|
246
|
+
if (maxBufferedBytes && (client.rawSocket.writableLength || 0) > maxBufferedBytes) {
|
|
247
|
+
client.close(1008, 'Backpressure limit exceeded');
|
|
248
|
+
continue;
|
|
249
|
+
}
|
|
250
|
+
client.rawSocket.write(frame);
|
|
251
|
+
}
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
const data = topicOrData;
|
|
256
|
+
const options = (maybeData && typeof maybeData === 'object') ? maybeData : {};
|
|
257
|
+
const exclude = options.except ?? null;
|
|
258
|
+
broker.publishAll(data, exclude, maxBufferedBytes);
|
|
259
|
+
},
|
|
260
|
+
to(topic) {
|
|
261
|
+
return {
|
|
262
|
+
broadcast(data, opts = {}) {
|
|
263
|
+
sessionSocket.broadcast(topic, data, opts);
|
|
264
|
+
}
|
|
265
|
+
};
|
|
149
266
|
},
|
|
150
267
|
send(data) {
|
|
151
|
-
if (
|
|
268
|
+
if (closed || tcpSocket.destroyed) return false;
|
|
269
|
+
if (maxBufferedBytes && (tcpSocket.writableLength || 0) > maxBufferedBytes) {
|
|
270
|
+
sessionSocket.close(1008, 'Backpressure limit exceeded');
|
|
271
|
+
return false;
|
|
272
|
+
}
|
|
152
273
|
const isBin = data instanceof Uint8Array || binaryMode;
|
|
153
274
|
tcpSocket.write(encodeFrame(data, isBin));
|
|
275
|
+
return true;
|
|
154
276
|
},
|
|
155
277
|
close(code = 1000, reason = '') {
|
|
156
278
|
if (closed) return;
|
|
@@ -187,13 +309,26 @@ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, s
|
|
|
187
309
|
return;
|
|
188
310
|
}
|
|
189
311
|
alive = false;
|
|
190
|
-
if (
|
|
312
|
+
if (!closed && !tcpSocket.destroyed) {
|
|
191
313
|
tcpSocket.write(encodeControlFrame(0x9));
|
|
192
314
|
}
|
|
193
315
|
}, heartbeatMs);
|
|
194
316
|
}
|
|
195
317
|
|
|
196
318
|
const deliverMessage = (opcode, payload) => {
|
|
319
|
+
if (maxEventsPerSec > 0) {
|
|
320
|
+
const now = Date.now();
|
|
321
|
+
if (now - rateWindowStart >= 1000) {
|
|
322
|
+
rateWindowStart = now;
|
|
323
|
+
rateCount = 0;
|
|
324
|
+
}
|
|
325
|
+
rateCount += 1;
|
|
326
|
+
if (rateCount > maxEventsPerSec) {
|
|
327
|
+
sessionSocket.send({ type: 'error', message: 'RATE_LIMIT_EXCEEDED' });
|
|
328
|
+
return;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
|
|
197
332
|
if (opcode === 0x2 || binaryMode) {
|
|
198
333
|
messageQueue.push(new Uint8Array(payload));
|
|
199
334
|
} else {
|
|
@@ -254,7 +389,7 @@ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, s
|
|
|
254
389
|
return;
|
|
255
390
|
}
|
|
256
391
|
if (opcode === 0x9) {
|
|
257
|
-
if (
|
|
392
|
+
if (!closed && !tcpSocket.destroyed) tcpSocket.write(encodeControlFrame(0xa, payload));
|
|
258
393
|
continue;
|
|
259
394
|
}
|
|
260
395
|
if (opcode === 0xa) {
|
|
@@ -289,6 +424,197 @@ export function createLinearSocket(tcpSocket, headBuffer, broker, config = {}, s
|
|
|
289
424
|
return sessionSocket;
|
|
290
425
|
}
|
|
291
426
|
|
|
427
|
+
export function createDeclarativeWsRuntime(broker, routeConfig = {}) {
|
|
428
|
+
const activeSockets = new Set();
|
|
429
|
+
const roomStates = new Map();
|
|
430
|
+
const bufferSize = routeConfig.sync?.bufferSize ?? 100;
|
|
431
|
+
|
|
432
|
+
function ensureRoomState(roomName, initialState = {}) {
|
|
433
|
+
if (!roomStates.has(roomName)) {
|
|
434
|
+
roomStates.set(roomName, {
|
|
435
|
+
state: structuredClone(initialState),
|
|
436
|
+
seq: 0,
|
|
437
|
+
ring: createRingBuffer(bufferSize)
|
|
438
|
+
});
|
|
439
|
+
}
|
|
440
|
+
return roomStates.get(roomName);
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
function sendSnapshot(socket, roomName) {
|
|
444
|
+
const entry = roomStates.get(roomName);
|
|
445
|
+
if (!entry || !socket.isOpen) return;
|
|
446
|
+
socket.send({
|
|
447
|
+
type: 'sync_snapshot',
|
|
448
|
+
room: roomName,
|
|
449
|
+
seq: entry.seq,
|
|
450
|
+
state: entry.state
|
|
451
|
+
});
|
|
452
|
+
}
|
|
453
|
+
|
|
454
|
+
function commit(roomName, meta, mutator, initialState = {}) {
|
|
455
|
+
const entry = ensureRoomState(roomName, initialState);
|
|
456
|
+
mutator(entry.state);
|
|
457
|
+
entry.seq += 1;
|
|
458
|
+
|
|
459
|
+
entry.ring.push({
|
|
460
|
+
seq: entry.seq,
|
|
461
|
+
meta: meta ?? null,
|
|
462
|
+
state: structuredClone(entry.state)
|
|
463
|
+
});
|
|
464
|
+
|
|
465
|
+
const members = broker.topics.get(roomName);
|
|
466
|
+
if (!members) return entry.seq;
|
|
467
|
+
|
|
468
|
+
for (const peer of members) {
|
|
469
|
+
if (peer.isOpen) {
|
|
470
|
+
peer.send({
|
|
471
|
+
type: 'sync_patch',
|
|
472
|
+
room: roomName,
|
|
473
|
+
seq: entry.seq,
|
|
474
|
+
meta: meta ?? null,
|
|
475
|
+
state: entry.state
|
|
476
|
+
});
|
|
477
|
+
}
|
|
478
|
+
}
|
|
479
|
+
return entry.seq;
|
|
480
|
+
}
|
|
481
|
+
|
|
482
|
+
function createSocketsCollection(excludeSocket = null) {
|
|
483
|
+
return {
|
|
484
|
+
where(predicate) {
|
|
485
|
+
const matched = [];
|
|
486
|
+
for (const s of activeSockets) {
|
|
487
|
+
if (!s.isOpen) continue;
|
|
488
|
+
if (excludeSocket && s === excludeSocket) continue;
|
|
489
|
+
if (!predicate || predicate(s)) matched.push(s);
|
|
490
|
+
}
|
|
491
|
+
return {
|
|
492
|
+
sockets: matched,
|
|
493
|
+
count: matched.length,
|
|
494
|
+
send(data) {
|
|
495
|
+
for (const s of matched) {
|
|
496
|
+
s.send({ type: 'event', payload: data });
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
};
|
|
500
|
+
}
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
return async function runDeclarativeSocket(socket, reqInfo = {}) {
|
|
505
|
+
activeSockets.add(socket);
|
|
506
|
+
const connData = reqInfo.data || {};
|
|
507
|
+
const clientLastSeq = Number(reqInfo.lastSeq || 0);
|
|
508
|
+
|
|
509
|
+
if (connData.room && !socket.state.room) {
|
|
510
|
+
socket.state.room = String(connData.room);
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
const resolveRoom = (explicitRoom) =>
|
|
514
|
+
explicitRoom || socket.state?.room || connData.room || 'default';
|
|
515
|
+
|
|
516
|
+
const activeRoom = resolveRoom();
|
|
517
|
+
if (activeRoom) {
|
|
518
|
+
socket.state.room = activeRoom;
|
|
519
|
+
setExclusiveRoom(socket, activeRoom);
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
if (typeof routeConfig.open === 'function') {
|
|
523
|
+
await routeConfig.open(socket, reqInfo);
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
const postOpenRoom = resolveRoom();
|
|
527
|
+
if (postOpenRoom) {
|
|
528
|
+
socket.state.room = postOpenRoom;
|
|
529
|
+
setExclusiveRoom(socket, postOpenRoom);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
if (typeof routeConfig.state === 'function') {
|
|
533
|
+
const initState = await routeConfig.state(socket, reqInfo);
|
|
534
|
+
const entry = ensureRoomState(postOpenRoom, initState || {});
|
|
535
|
+
|
|
536
|
+
if (clientLastSeq > 0) {
|
|
537
|
+
const missed = entry.ring.getSince(clientLastSeq);
|
|
538
|
+
if (Array.isArray(missed)) {
|
|
539
|
+
for (const item of missed) {
|
|
540
|
+
socket.send({
|
|
541
|
+
type: 'sync_patch',
|
|
542
|
+
room: postOpenRoom,
|
|
543
|
+
seq: item.seq,
|
|
544
|
+
meta: item.meta,
|
|
545
|
+
state: item.state,
|
|
546
|
+
replayed: true
|
|
547
|
+
});
|
|
548
|
+
}
|
|
549
|
+
} else {
|
|
550
|
+
sendSnapshot(socket, postOpenRoom);
|
|
551
|
+
}
|
|
552
|
+
} else {
|
|
553
|
+
sendSnapshot(socket, postOpenRoom);
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
const helpers = {
|
|
558
|
+
commit,
|
|
559
|
+
sockets: createSocketsCollection(socket),
|
|
560
|
+
resync(roomName) {
|
|
561
|
+
const target = resolveRoom(roomName);
|
|
562
|
+
if (target) {
|
|
563
|
+
socket.state.room = target;
|
|
564
|
+
setExclusiveRoom(socket, target);
|
|
565
|
+
}
|
|
566
|
+
sendSnapshot(socket, target);
|
|
567
|
+
}
|
|
568
|
+
};
|
|
569
|
+
|
|
570
|
+
try {
|
|
571
|
+
for await (const msg of socket) {
|
|
572
|
+
if (!msg || typeof msg !== 'object') continue;
|
|
573
|
+
|
|
574
|
+
if (msg.type === 'resync') {
|
|
575
|
+
const target = resolveRoom(msg.room);
|
|
576
|
+
if (target) {
|
|
577
|
+
socket.state.room = target;
|
|
578
|
+
setExclusiveRoom(socket, target);
|
|
579
|
+
}
|
|
580
|
+
sendSnapshot(socket, target);
|
|
581
|
+
continue;
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (msg.type === 'action' && routeConfig.actions && routeConfig.actions[msg.name]) {
|
|
585
|
+
const actionDef = routeConfig.actions[msg.name];
|
|
586
|
+
try {
|
|
587
|
+
if (typeof actionDef === 'function') {
|
|
588
|
+
await actionDef(msg.payload, socket, helpers);
|
|
589
|
+
} else if (actionDef && typeof actionDef.run === 'function') {
|
|
590
|
+
const validPayload = typeof actionDef.validate === 'function'
|
|
591
|
+
? await actionDef.validate(msg.payload, socket)
|
|
592
|
+
: msg.payload;
|
|
593
|
+
await actionDef.run(validPayload, socket, helpers);
|
|
594
|
+
}
|
|
595
|
+
const nextRoom = resolveRoom();
|
|
596
|
+
if (nextRoom) {
|
|
597
|
+
socket.state.room = nextRoom;
|
|
598
|
+
setExclusiveRoom(socket, nextRoom);
|
|
599
|
+
}
|
|
600
|
+
} catch (err) {
|
|
601
|
+
socket.send({
|
|
602
|
+
type: 'error',
|
|
603
|
+
action: msg.name,
|
|
604
|
+
message: err?.message || 'Action failed'
|
|
605
|
+
});
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
} finally {
|
|
610
|
+
activeSockets.delete(socket);
|
|
611
|
+
if (typeof routeConfig.close === 'function') {
|
|
612
|
+
await routeConfig.close(socket, reqInfo);
|
|
613
|
+
}
|
|
614
|
+
}
|
|
615
|
+
};
|
|
616
|
+
}
|
|
617
|
+
|
|
292
618
|
export function performWsHandshake(req, tcpSocket, extraHeaders = new Headers()) {
|
|
293
619
|
const key = req.headers['sec-websocket-key'];
|
|
294
620
|
if (!key) return false;
|