@fluixi/realtime 0.0.0-stage → 1.0.0-alpha.109
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/LICENSE +21 -0
- package/README.md +24 -2
- package/dist/bus.cjs +127 -0
- package/dist/bus.d.ts +58 -0
- package/dist/bus.d.ts.map +1 -0
- package/dist/bus.js +118 -0
- package/dist/bus.mjs +8 -0
- package/dist/channel-protocol.cjs +42 -0
- package/dist/channel-protocol.d.ts +40 -0
- package/dist/channel-protocol.d.ts.map +1 -0
- package/dist/channel-protocol.js +24 -0
- package/dist/channel-protocol.mjs +8 -0
- package/dist/channel-server.cjs +291 -0
- package/dist/channel-server.d.ts +29 -0
- package/dist/channel-server.d.ts.map +1 -0
- package/dist/channel-server.js +122 -0
- package/dist/channel-server.mjs +9 -0
- package/dist/channels.cjs +426 -0
- package/dist/channels.d.ts +38 -0
- package/dist/channels.d.ts.map +1 -0
- package/dist/channels.js +82 -0
- package/dist/channels.mjs +9 -0
- package/dist/chunk-4CEAXWJN.mjs +31 -0
- package/dist/chunk-AWS4MP5D.mjs +107 -0
- package/dist/chunk-DNVSSCJA.mjs +22 -0
- package/dist/chunk-GAAZQJJ4.mjs +145 -0
- package/dist/chunk-MGON7IDW.mjs +77 -0
- package/dist/chunk-Q3NDGSX6.mjs +107 -0
- package/dist/chunk-UAZIXYV5.mjs +315 -0
- package/dist/chunk-X73D2DE2.mjs +19 -0
- package/dist/endpoint.cjs +165 -0
- package/dist/endpoint.d.ts +80 -0
- package/dist/endpoint.d.ts.map +1 -0
- package/dist/endpoint.js +168 -0
- package/dist/endpoint.mjs +8 -0
- package/dist/index.cjs +445 -0
- package/dist/index.d.ts +6 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.mjs +29 -0
- package/dist/serializers.cjs +39 -0
- package/dist/serializers.d.ts +12 -0
- package/dist/serializers.d.ts.map +1 -0
- package/dist/serializers.js +16 -0
- package/dist/serializers.mjs +8 -0
- package/dist/server.cjs +385 -0
- package/dist/server.d.ts +5 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +3 -0
- package/dist/server.mjs +20 -0
- package/dist/socket.cjs +362 -0
- package/dist/socket.d.ts +137 -0
- package/dist/socket.d.ts.map +1 -0
- package/dist/socket.js +351 -0
- package/dist/socket.mjs +16 -0
- package/dist/transport.cjs +51 -0
- package/dist/transport.d.ts +33 -0
- package/dist/transport.d.ts.map +1 -0
- package/dist/transport.js +36 -0
- package/dist/transport.mjs +8 -0
- package/dist/tsconfig.lib.tsbuildinfo +1 -0
- package/package.json +65 -3
|
@@ -0,0 +1,291 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
|
+
var __export = (target, all) => {
|
|
7
|
+
for (var name in all)
|
|
8
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
9
|
+
};
|
|
10
|
+
var __copyProps = (to, from, except, desc) => {
|
|
11
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
|
+
for (let key of __getOwnPropNames(from))
|
|
13
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
14
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
15
|
+
}
|
|
16
|
+
return to;
|
|
17
|
+
};
|
|
18
|
+
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
|
+
|
|
20
|
+
// src/channel-server.ts
|
|
21
|
+
var channel_server_exports = {};
|
|
22
|
+
__export(channel_server_exports, {
|
|
23
|
+
createChannelServer: () => createChannelServer
|
|
24
|
+
});
|
|
25
|
+
module.exports = __toCommonJS(channel_server_exports);
|
|
26
|
+
|
|
27
|
+
// src/bus.ts
|
|
28
|
+
function memoryBus() {
|
|
29
|
+
const handlers = /* @__PURE__ */ new Set();
|
|
30
|
+
return {
|
|
31
|
+
async publish(channel, message) {
|
|
32
|
+
for (const handler of handlers) handler(channel, message);
|
|
33
|
+
},
|
|
34
|
+
subscribe(handler) {
|
|
35
|
+
handlers.add(handler);
|
|
36
|
+
return () => void handlers.delete(handler);
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
// src/channel-protocol.ts
|
|
42
|
+
var PING_FRAME = '{"t":"ping"}';
|
|
43
|
+
function parseClientFrame(text) {
|
|
44
|
+
let frame;
|
|
45
|
+
try {
|
|
46
|
+
frame = JSON.parse(text);
|
|
47
|
+
} catch {
|
|
48
|
+
return void 0;
|
|
49
|
+
}
|
|
50
|
+
if (!frame || typeof frame !== "object") return void 0;
|
|
51
|
+
const { t, c, since } = frame;
|
|
52
|
+
if (typeof c !== "string" || !c || c.length > 200) return void 0;
|
|
53
|
+
if (t === "leave") return { t, c };
|
|
54
|
+
if (t !== "join") return void 0;
|
|
55
|
+
if (since === void 0) return { t, c };
|
|
56
|
+
return typeof since === "string" && since.length <= 200 ? { t, c, since } : void 0;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// src/endpoint.ts
|
|
60
|
+
var import_ws = require("ws");
|
|
61
|
+
var DRAIN_POLL_MS = 20;
|
|
62
|
+
var CLOSE_REAUTHENTICATE = 4100;
|
|
63
|
+
var REFUSALS = {
|
|
64
|
+
401: "Unauthorized",
|
|
65
|
+
403: "Forbidden",
|
|
66
|
+
503: "Service Unavailable"
|
|
67
|
+
};
|
|
68
|
+
function createWebSocketServer(options) {
|
|
69
|
+
const maxConnections = options.maxConnections ?? 1e4;
|
|
70
|
+
const maxMessageSize = options.maxMessageSize ?? 1024 * 1024;
|
|
71
|
+
const maxBuffered = options.maxBuffered ?? 4 * 1024 * 1024;
|
|
72
|
+
const pingInterval = options.pingInterval ?? 25e3;
|
|
73
|
+
const wss = new import_ws.WebSocketServer({ noServer: true, maxPayload: maxMessageSize });
|
|
74
|
+
const alive = /* @__PURE__ */ new WeakSet();
|
|
75
|
+
let pending = 0;
|
|
76
|
+
let closing = false;
|
|
77
|
+
const ping = setInterval(() => {
|
|
78
|
+
for (const ws of wss.clients) {
|
|
79
|
+
if (!alive.has(ws)) {
|
|
80
|
+
ws.terminate();
|
|
81
|
+
continue;
|
|
82
|
+
}
|
|
83
|
+
alive.delete(ws);
|
|
84
|
+
ws.ping();
|
|
85
|
+
if (options.keepAlive !== void 0) ws.send(options.keepAlive);
|
|
86
|
+
}
|
|
87
|
+
}, pingInterval);
|
|
88
|
+
ping.unref?.();
|
|
89
|
+
const allowedOrigin = (request) => {
|
|
90
|
+
const origin = request.headers.origin;
|
|
91
|
+
if (!origin) return true;
|
|
92
|
+
if (typeof options.origins === "function") return options.origins(origin, request);
|
|
93
|
+
if (options.origins) return options.origins.includes(origin);
|
|
94
|
+
try {
|
|
95
|
+
return new URL(origin).host === request.headers.host;
|
|
96
|
+
} catch {
|
|
97
|
+
return false;
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
const refuse = (socket, status) => {
|
|
101
|
+
if (socket.destroyed) return;
|
|
102
|
+
socket.end(`HTTP/1.1 ${status} ${REFUSALS[status]}\r
|
|
103
|
+
Connection: close\r
|
|
104
|
+
Content-Length: 0\r
|
|
105
|
+
\r
|
|
106
|
+
`);
|
|
107
|
+
};
|
|
108
|
+
const accept = async (request, socket, head) => {
|
|
109
|
+
if (closing || wss.clients.size + pending >= maxConnections) return refuse(socket, 503);
|
|
110
|
+
if (!allowedOrigin(request)) return refuse(socket, 403);
|
|
111
|
+
pending += 1;
|
|
112
|
+
let context;
|
|
113
|
+
try {
|
|
114
|
+
context = await options.authenticate(request);
|
|
115
|
+
} catch (error) {
|
|
116
|
+
console.error(error);
|
|
117
|
+
context = null;
|
|
118
|
+
} finally {
|
|
119
|
+
pending -= 1;
|
|
120
|
+
}
|
|
121
|
+
if (context === null) return refuse(socket, 401);
|
|
122
|
+
if (closing || socket.destroyed) return refuse(socket, 503);
|
|
123
|
+
wss.handleUpgrade(request, socket, head, (ws) => {
|
|
124
|
+
alive.add(ws);
|
|
125
|
+
ws.on("pong", () => alive.add(ws));
|
|
126
|
+
ws.on("error", () => {
|
|
127
|
+
});
|
|
128
|
+
if (options.maxAge) {
|
|
129
|
+
const timer = setTimeout(() => ws.close(CLOSE_REAUTHENTICATE, "reauthenticate"), options.maxAge);
|
|
130
|
+
timer.unref?.();
|
|
131
|
+
ws.once("close", () => clearTimeout(timer));
|
|
132
|
+
}
|
|
133
|
+
options.onConnection(wrap(ws, context, maxBuffered));
|
|
134
|
+
});
|
|
135
|
+
};
|
|
136
|
+
return {
|
|
137
|
+
upgrade(request, socket, head) {
|
|
138
|
+
const path = new URL(request.url ?? "/", "http://localhost").pathname;
|
|
139
|
+
if (path !== options.path) return false;
|
|
140
|
+
void accept(request, socket, head);
|
|
141
|
+
return true;
|
|
142
|
+
},
|
|
143
|
+
size: () => wss.clients.size,
|
|
144
|
+
close(timeout = 5e3) {
|
|
145
|
+
closing = true;
|
|
146
|
+
clearInterval(ping);
|
|
147
|
+
const open = [...wss.clients];
|
|
148
|
+
for (const ws of open) ws.close(1001, "server shutting down");
|
|
149
|
+
return new Promise((resolve) => {
|
|
150
|
+
const timer = setTimeout(() => {
|
|
151
|
+
for (const ws of wss.clients) ws.terminate();
|
|
152
|
+
}, timeout);
|
|
153
|
+
timer.unref?.();
|
|
154
|
+
const done = () => {
|
|
155
|
+
if (wss.clients.size) return;
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
wss.close(() => resolve());
|
|
158
|
+
};
|
|
159
|
+
for (const ws of open) ws.once("close", done);
|
|
160
|
+
done();
|
|
161
|
+
});
|
|
162
|
+
}
|
|
163
|
+
};
|
|
164
|
+
}
|
|
165
|
+
function wrap(ws, context, maxBuffered) {
|
|
166
|
+
return {
|
|
167
|
+
context,
|
|
168
|
+
get buffered() {
|
|
169
|
+
return ws.bufferedAmount;
|
|
170
|
+
},
|
|
171
|
+
send(data) {
|
|
172
|
+
if (ws.readyState !== ws.OPEN) return "closed";
|
|
173
|
+
if (ws.bufferedAmount > maxBuffered) return "buffer-full";
|
|
174
|
+
ws.send(data);
|
|
175
|
+
return "sent";
|
|
176
|
+
},
|
|
177
|
+
drained(bytes = maxBuffered / 2) {
|
|
178
|
+
return new Promise((resolve) => {
|
|
179
|
+
const check = () => {
|
|
180
|
+
if (ws.readyState !== ws.OPEN || ws.bufferedAmount <= bytes) return resolve();
|
|
181
|
+
setTimeout(check, DRAIN_POLL_MS);
|
|
182
|
+
};
|
|
183
|
+
check();
|
|
184
|
+
});
|
|
185
|
+
},
|
|
186
|
+
close(code = 1e3, reason = "") {
|
|
187
|
+
ws.close(code, reason);
|
|
188
|
+
},
|
|
189
|
+
on(event, handler) {
|
|
190
|
+
const listener = event === "message" ? (data, isBinary) => {
|
|
191
|
+
const bytes = Array.isArray(data) ? Buffer.concat(data) : Buffer.from(data);
|
|
192
|
+
handler(isBinary ? new Uint8Array(bytes) : bytes.toString("utf8"));
|
|
193
|
+
} : (code, reason) => handler(code, reason.toString("utf8"));
|
|
194
|
+
ws.on(event, listener);
|
|
195
|
+
return () => void ws.off(event, listener);
|
|
196
|
+
}
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
// src/channel-server.ts
|
|
201
|
+
function createChannelServer(options) {
|
|
202
|
+
const bus = options.bus ?? memoryBus();
|
|
203
|
+
const maxChannels = options.maxChannels ?? 100;
|
|
204
|
+
const members = /* @__PURE__ */ new Map();
|
|
205
|
+
const send = (connection, frame) => connection.send(JSON.stringify(frame));
|
|
206
|
+
const deliver = (channel, message) => {
|
|
207
|
+
for (const [connection, membership] of members.get(channel) ?? []) {
|
|
208
|
+
if (membership.held) membership.held.push(message);
|
|
209
|
+
else send(connection, { t: "msg", c: channel, m: message });
|
|
210
|
+
}
|
|
211
|
+
};
|
|
212
|
+
const unsubscribe = bus.subscribe(deliver);
|
|
213
|
+
const unwatchGaps = bus.onGap?.(() => {
|
|
214
|
+
for (const [channel, set] of members) for (const connection of set.keys()) send(connection, { t: "resync", c: channel });
|
|
215
|
+
});
|
|
216
|
+
const leave = (connection, channel) => {
|
|
217
|
+
const set = members.get(channel);
|
|
218
|
+
set?.delete(connection);
|
|
219
|
+
if (set && !set.size) members.delete(channel);
|
|
220
|
+
};
|
|
221
|
+
const join = async (connection, joined, channel, since) => {
|
|
222
|
+
if (joined.has(channel)) return;
|
|
223
|
+
if (joined.size >= maxChannels) return void send(connection, { t: "denied", c: channel });
|
|
224
|
+
joined.add(channel);
|
|
225
|
+
let allowed = false;
|
|
226
|
+
try {
|
|
227
|
+
allowed = await options.authorize(connection.context, channel);
|
|
228
|
+
} catch (error) {
|
|
229
|
+
console.error(error);
|
|
230
|
+
}
|
|
231
|
+
if (!joined.has(channel)) return;
|
|
232
|
+
if (!allowed) {
|
|
233
|
+
joined.delete(channel);
|
|
234
|
+
return void send(connection, { t: "denied", c: channel });
|
|
235
|
+
}
|
|
236
|
+
const membership = { held: since === void 0 ? null : [] };
|
|
237
|
+
if (!members.has(channel)) members.set(channel, /* @__PURE__ */ new Map());
|
|
238
|
+
members.get(channel).set(connection, membership);
|
|
239
|
+
send(connection, { t: "joined", c: channel });
|
|
240
|
+
if (since === void 0) return;
|
|
241
|
+
let missed = null;
|
|
242
|
+
try {
|
|
243
|
+
missed = options.replay ? await options.replay(channel, since, connection.context) : null;
|
|
244
|
+
} catch (error) {
|
|
245
|
+
console.error(error);
|
|
246
|
+
}
|
|
247
|
+
const held = membership.held ?? [];
|
|
248
|
+
membership.held = null;
|
|
249
|
+
if (!joined.has(channel)) return;
|
|
250
|
+
if (missed === null) {
|
|
251
|
+
send(connection, { t: "resync", c: channel });
|
|
252
|
+
return;
|
|
253
|
+
}
|
|
254
|
+
const replayed = new Set(missed.map((message) => message.id));
|
|
255
|
+
for (const message of missed) send(connection, { t: "msg", c: channel, m: message });
|
|
256
|
+
for (const message of held) if (!replayed.has(message.id)) send(connection, { t: "msg", c: channel, m: message });
|
|
257
|
+
};
|
|
258
|
+
const server = createWebSocketServer({
|
|
259
|
+
...options,
|
|
260
|
+
keepAlive: PING_FRAME,
|
|
261
|
+
onConnection(connection) {
|
|
262
|
+
const joined = /* @__PURE__ */ new Set();
|
|
263
|
+
connection.on("message", (data) => {
|
|
264
|
+
const frame = typeof data === "string" ? parseClientFrame(data) : void 0;
|
|
265
|
+
if (!frame) return connection.close(1008, "unexpected frame");
|
|
266
|
+
if (frame.t === "join") void join(connection, joined, frame.c, frame.since);
|
|
267
|
+
else {
|
|
268
|
+
joined.delete(frame.c);
|
|
269
|
+
leave(connection, frame.c);
|
|
270
|
+
}
|
|
271
|
+
});
|
|
272
|
+
connection.on("close", () => {
|
|
273
|
+
for (const channel of joined) leave(connection, channel);
|
|
274
|
+
joined.clear();
|
|
275
|
+
});
|
|
276
|
+
}
|
|
277
|
+
});
|
|
278
|
+
return {
|
|
279
|
+
...server,
|
|
280
|
+
async start() {
|
|
281
|
+
await bus.start?.();
|
|
282
|
+
},
|
|
283
|
+
publish: (channel, message) => bus.publish(channel, message),
|
|
284
|
+
async close(timeout) {
|
|
285
|
+
unsubscribe();
|
|
286
|
+
unwatchGaps?.();
|
|
287
|
+
await server.close(timeout);
|
|
288
|
+
await bus.close?.();
|
|
289
|
+
}
|
|
290
|
+
};
|
|
291
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { type RealtimeBus } from './bus.js';
|
|
2
|
+
import { type ChannelMessage } from './channel-protocol.js';
|
|
3
|
+
import { type RealtimeServer, type WebSocketServerOptions } from './endpoint.js';
|
|
4
|
+
export interface ChannelServerOptions<Context> extends Omit<WebSocketServerOptions<Context>, 'onConnection' | 'keepAlive'> {
|
|
5
|
+
/** Whether this connection may receive `channel`; asked on every join. */
|
|
6
|
+
authorize: (context: Context, channel: string) => boolean | Promise<boolean>;
|
|
7
|
+
/**
|
|
8
|
+
* The messages on `channel` after `since`, oldest first, for a client that reconnects. Null,
|
|
9
|
+
* or no `replay` at all, sends `resync`: the client refetches what it shows.
|
|
10
|
+
*/
|
|
11
|
+
replay?: (channel: string, since: string, context: Context) => ChannelMessage[] | null | Promise<ChannelMessage[] | null>;
|
|
12
|
+
/** Fan-out across server instances. Default: `memoryBus()`, one process. */
|
|
13
|
+
bus?: RealtimeBus;
|
|
14
|
+
/** Channels one connection may join at once; more are denied. Default: 100 */
|
|
15
|
+
maxChannels?: number;
|
|
16
|
+
}
|
|
17
|
+
export interface ChannelServer extends RealtimeServer {
|
|
18
|
+
/** Starts the bus; call it from the server module's `start`. */
|
|
19
|
+
start(): Promise<void>;
|
|
20
|
+
/** Sends `message` to every connection on `channel`, on every instance through the bus. */
|
|
21
|
+
publish<T>(channel: string, message: ChannelMessage<T>): Promise<void>;
|
|
22
|
+
}
|
|
23
|
+
/**
|
|
24
|
+
* Channels over a WebSocket endpoint: clients join by name, the app authorises each join,
|
|
25
|
+
* published messages reach every member, and a client coming back with the last id it saw gets
|
|
26
|
+
* what it missed, or `resync` when the app cannot replay.
|
|
27
|
+
*/
|
|
28
|
+
export declare function createChannelServer<Context>(options: ChannelServerOptions<Context>): ChannelServer;
|
|
29
|
+
//# sourceMappingURL=channel-server.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"channel-server.d.ts","sourceRoot":"","sources":["../src/channel-server.ts"],"names":[],"mappings":"AACA,OAAO,EAAa,KAAK,WAAW,EAAE,MAAM,UAAU,CAAC;AACvD,OAAO,EAAgC,KAAK,cAAc,EAAoB,MAAM,uBAAuB,CAAC;AAC5G,OAAO,EAAyB,KAAK,cAAc,EAAyB,KAAK,sBAAsB,EAAE,MAAM,eAAe,CAAC;AAE/H,MAAM,WAAW,oBAAoB,CAAC,OAAO,CAAE,SAAQ,IAAI,CAAC,sBAAsB,CAAC,OAAO,CAAC,EAAE,cAAc,GAAG,WAAW,CAAC;IACxH,0EAA0E;IAC1E,SAAS,EAAE,CAAC,OAAO,EAAE,OAAO,EAAE,OAAO,EAAE,MAAM,KAAK,OAAO,GAAG,OAAO,CAAC,OAAO,CAAC,CAAC;IAC7E;;;OAGG;IACH,MAAM,CAAC,EAAE,CAAC,OAAO,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,EAAE,OAAO,EAAE,OAAO,KAAK,cAAc,EAAE,GAAG,IAAI,GAAG,OAAO,CAAC,cAAc,EAAE,GAAG,IAAI,CAAC,CAAC;IAC1H,4EAA4E;IAC5E,GAAG,CAAC,EAAE,WAAW,CAAC;IAClB,8EAA8E;IAC9E,WAAW,CAAC,EAAE,MAAM,CAAC;CACtB;AAED,MAAM,WAAW,aAAc,SAAQ,cAAc;IACnD,gEAAgE;IAChE,KAAK,IAAI,OAAO,CAAC,IAAI,CAAC,CAAC;IACvB,2FAA2F;IAC3F,OAAO,CAAC,CAAC,EAAE,OAAO,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACxE;AAOD;;;;GAIG;AACH,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,OAAO,EAAE,oBAAoB,CAAC,OAAO,CAAC,GAAG,aAAa,CAoGlG"}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
import { memoryBus } from './bus.js';
|
|
3
|
+
import { parseClientFrame, PING_FRAME } from './channel-protocol.js';
|
|
4
|
+
import { createWebSocketServer } from './endpoint.js';
|
|
5
|
+
/**
|
|
6
|
+
* Channels over a WebSocket endpoint: clients join by name, the app authorises each join,
|
|
7
|
+
* published messages reach every member, and a client coming back with the last id it saw gets
|
|
8
|
+
* what it missed, or `resync` when the app cannot replay.
|
|
9
|
+
*/
|
|
10
|
+
export function createChannelServer(options) {
|
|
11
|
+
const bus = options.bus ?? memoryBus();
|
|
12
|
+
const maxChannels = options.maxChannels ?? 100;
|
|
13
|
+
const members = new Map();
|
|
14
|
+
const send = (connection, frame) => connection.send(JSON.stringify(frame));
|
|
15
|
+
const deliver = (channel, message) => {
|
|
16
|
+
for (const [connection, membership] of members.get(channel) ?? []) {
|
|
17
|
+
if (membership.held)
|
|
18
|
+
membership.held.push(message);
|
|
19
|
+
else
|
|
20
|
+
send(connection, { t: 'msg', c: channel, m: message });
|
|
21
|
+
}
|
|
22
|
+
};
|
|
23
|
+
const unsubscribe = bus.subscribe(deliver);
|
|
24
|
+
// The bus may have missed messages: every member refetches what it shows.
|
|
25
|
+
const unwatchGaps = bus.onGap?.(() => {
|
|
26
|
+
for (const [channel, set] of members)
|
|
27
|
+
for (const connection of set.keys())
|
|
28
|
+
send(connection, { t: 'resync', c: channel });
|
|
29
|
+
});
|
|
30
|
+
const leave = (connection, channel) => {
|
|
31
|
+
const set = members.get(channel);
|
|
32
|
+
set?.delete(connection);
|
|
33
|
+
if (set && !set.size)
|
|
34
|
+
members.delete(channel);
|
|
35
|
+
};
|
|
36
|
+
const join = async (connection, joined, channel, since) => {
|
|
37
|
+
if (joined.has(channel))
|
|
38
|
+
return;
|
|
39
|
+
if (joined.size >= maxChannels)
|
|
40
|
+
return void send(connection, { t: 'denied', c: channel });
|
|
41
|
+
joined.add(channel);
|
|
42
|
+
let allowed = false;
|
|
43
|
+
try {
|
|
44
|
+
allowed = await options.authorize(connection.context, channel);
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
console.error(error);
|
|
48
|
+
}
|
|
49
|
+
if (!joined.has(channel))
|
|
50
|
+
return; // left, or closed, while authorising
|
|
51
|
+
if (!allowed) {
|
|
52
|
+
joined.delete(channel);
|
|
53
|
+
return void send(connection, { t: 'denied', c: channel });
|
|
54
|
+
}
|
|
55
|
+
// Membership first, so nothing published during the replay is lost: it waits in `held`.
|
|
56
|
+
const membership = { held: since === undefined ? null : [] };
|
|
57
|
+
if (!members.has(channel))
|
|
58
|
+
members.set(channel, new Map());
|
|
59
|
+
members.get(channel).set(connection, membership);
|
|
60
|
+
send(connection, { t: 'joined', c: channel });
|
|
61
|
+
if (since === undefined)
|
|
62
|
+
return;
|
|
63
|
+
let missed = null;
|
|
64
|
+
try {
|
|
65
|
+
missed = options.replay ? await options.replay(channel, since, connection.context) : null;
|
|
66
|
+
}
|
|
67
|
+
catch (error) {
|
|
68
|
+
console.error(error);
|
|
69
|
+
}
|
|
70
|
+
const held = membership.held ?? [];
|
|
71
|
+
membership.held = null;
|
|
72
|
+
if (!joined.has(channel))
|
|
73
|
+
return;
|
|
74
|
+
if (missed === null) {
|
|
75
|
+
send(connection, { t: 'resync', c: channel });
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
const replayed = new Set(missed.map((message) => message.id));
|
|
79
|
+
for (const message of missed)
|
|
80
|
+
send(connection, { t: 'msg', c: channel, m: message });
|
|
81
|
+
for (const message of held)
|
|
82
|
+
if (!replayed.has(message.id))
|
|
83
|
+
send(connection, { t: 'msg', c: channel, m: message });
|
|
84
|
+
};
|
|
85
|
+
const server = createWebSocketServer({
|
|
86
|
+
...options,
|
|
87
|
+
keepAlive: PING_FRAME,
|
|
88
|
+
onConnection(connection) {
|
|
89
|
+
const joined = new Set();
|
|
90
|
+
connection.on('message', (data) => {
|
|
91
|
+
const frame = typeof data === 'string' ? parseClientFrame(data) : undefined;
|
|
92
|
+
// Only this protocol is spoken here: anything else is a client to stop talking to.
|
|
93
|
+
if (!frame)
|
|
94
|
+
return connection.close(1008, 'unexpected frame');
|
|
95
|
+
if (frame.t === 'join')
|
|
96
|
+
void join(connection, joined, frame.c, frame.since);
|
|
97
|
+
else {
|
|
98
|
+
joined.delete(frame.c);
|
|
99
|
+
leave(connection, frame.c);
|
|
100
|
+
}
|
|
101
|
+
});
|
|
102
|
+
connection.on('close', () => {
|
|
103
|
+
for (const channel of joined)
|
|
104
|
+
leave(connection, channel);
|
|
105
|
+
joined.clear();
|
|
106
|
+
});
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
return {
|
|
110
|
+
...server,
|
|
111
|
+
async start() {
|
|
112
|
+
await bus.start?.();
|
|
113
|
+
},
|
|
114
|
+
publish: (channel, message) => bus.publish(channel, message),
|
|
115
|
+
async close(timeout) {
|
|
116
|
+
unsubscribe();
|
|
117
|
+
unwatchGaps?.();
|
|
118
|
+
await server.close(timeout);
|
|
119
|
+
await bus.close?.();
|
|
120
|
+
},
|
|
121
|
+
};
|
|
122
|
+
}
|