@dokebi/websocket 0.1.3 → 0.3.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/AI.md +67 -20
- package/README.md +43 -13
- package/dist/gateway.d.ts +3 -2
- package/dist/gateway.js +593 -87
- package/dist/index.js +20 -6
- package/dist/log.d.ts +25 -0
- package/dist/log.js +102 -0
- package/dist/options.d.ts +5 -0
- package/dist/options.js +4 -2
- package/dist/router.d.ts +10 -5
- package/dist/router.js +20 -4
- package/dist/types.d.ts +134 -0
- package/dist/types.js +7 -1
- package/options.schema.json +7 -0
- package/package.json +12 -11
- package/dist/client.d.ts +0 -7
- package/dist/client.js +0 -60
package/dist/index.js
CHANGED
|
@@ -1,17 +1,22 @@
|
|
|
1
|
-
import { definePlugin, providerDependency } from '@dokebi/core';
|
|
1
|
+
import { definePlugin, optionalDependency, providerDependency, } from '@dokebi/core';
|
|
2
2
|
import { Gateway } from './gateway.js';
|
|
3
3
|
import { parseOptions } from './options.js';
|
|
4
4
|
export * from './router.js';
|
|
5
5
|
export * from './types.js';
|
|
6
6
|
const hub = providerDependency({
|
|
7
7
|
name: 'dokebi-websocket-hub',
|
|
8
|
-
version: '^0.
|
|
8
|
+
version: '^0.3.0',
|
|
9
9
|
packageName: '@dokebi/websocket-hub',
|
|
10
10
|
load: () => import('@dokebi/websocket-hub'),
|
|
11
11
|
});
|
|
12
|
+
/**
|
|
13
|
+
* The socket codec provider (D-0059 §4): the private dokebi-seal plugin when it is registered.
|
|
14
|
+
* Looked up by name only; this package never imports @dokebi/seal.
|
|
15
|
+
*/
|
|
16
|
+
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.1.0' });
|
|
12
17
|
const web = providerDependency({
|
|
13
18
|
name: 'dokebi-web',
|
|
14
|
-
version: '^0.1.0',
|
|
19
|
+
version: '^0.1.0 || ^0.2.0',
|
|
15
20
|
packageName: '@dokebi/web',
|
|
16
21
|
load: () => import('@dokebi/web'),
|
|
17
22
|
});
|
|
@@ -22,7 +27,16 @@ class WebsocketRuntime {
|
|
|
22
27
|
this.#options = options;
|
|
23
28
|
}
|
|
24
29
|
setup(context) {
|
|
25
|
-
|
|
30
|
+
const codecs = context.getOptionalDependency(seal);
|
|
31
|
+
if (codecs !== undefined && typeof codecs?.forConnection !== 'function')
|
|
32
|
+
throw Object.assign(new Error('dokebi-seal does not provide forConnection'), {
|
|
33
|
+
code: 'SEAL_PROVIDER_INVALID',
|
|
34
|
+
});
|
|
35
|
+
context.logger.log('debug', 'WebSocket seal provider', {
|
|
36
|
+
present: codecs !== undefined,
|
|
37
|
+
sealDriftMs: this.#options.sealDriftMs,
|
|
38
|
+
});
|
|
39
|
+
this.#gateway = new Gateway(context, context.getDependency(web), context.getDependency(hub), this.#options, codecs);
|
|
26
40
|
return this.#gateway.api;
|
|
27
41
|
}
|
|
28
42
|
start() {
|
|
@@ -35,9 +49,9 @@ class WebsocketRuntime {
|
|
|
35
49
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
36
50
|
export const createPlugin = definePlugin({
|
|
37
51
|
name: 'dokebi-websocket',
|
|
38
|
-
version: '0.
|
|
52
|
+
version: '0.3.0',
|
|
39
53
|
core: '^0.2.0',
|
|
40
54
|
options: parseOptions,
|
|
41
|
-
dependencies: () => [hub, web],
|
|
55
|
+
dependencies: () => [hub, web, seal],
|
|
42
56
|
instance: ({ options }) => new WebsocketRuntime(options),
|
|
43
57
|
});
|
package/dist/log.d.ts
ADDED
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { LogFields, Logger, LogLevel } from '@dokebi/core';
|
|
2
|
+
/**
|
|
3
|
+
* The full text of a caught value for the `error` log field (D-0047): name, whole message and
|
|
4
|
+
* stack, then each `cause` the same way. Only credentials in URLs (`//user:password@`) are
|
|
5
|
+
* removed; a text over 16 KB is cut and marked.
|
|
6
|
+
*/
|
|
7
|
+
export declare function errorText(error: unknown): string;
|
|
8
|
+
/** A stable code of an error (hub, ws or errno code), or `fallback`. */
|
|
9
|
+
export declare function errorCode(error: unknown, fallback: string): string;
|
|
10
|
+
/**
|
|
11
|
+
* Logs a repeating event once per interval (D-0047): the first occurrence at once, the following
|
|
12
|
+
* ones of the same message and code (and `group`, when given) are counted and reported together
|
|
13
|
+
* (`repeated`) when the interval ends. `group` must come from a bounded set (e.g. registered
|
|
14
|
+
* handler types), never from client input, since each value keeps an entry for an interval. Hot paths (per message, per frame) can report every failure without a burst
|
|
15
|
+
* flooding the log. Field and error text are built only for lines that are written.
|
|
16
|
+
*/
|
|
17
|
+
export declare class LogThrottle {
|
|
18
|
+
#private;
|
|
19
|
+
readonly logger: Logger;
|
|
20
|
+
readonly intervalMs: number;
|
|
21
|
+
constructor(logger: Logger, intervalMs?: number);
|
|
22
|
+
report(level: LogLevel, message: string, code: string, error?: unknown, fields?: LogFields, group?: string): void;
|
|
23
|
+
/** Writes the counts still pending (on close), so a burst at shutdown is not lost. */
|
|
24
|
+
flush(): void;
|
|
25
|
+
}
|
package/dist/log.js
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
2
|
+
/**
|
|
3
|
+
* The full text of a caught value for the `error` log field (D-0047): name, whole message and
|
|
4
|
+
* stack, then each `cause` the same way. Only credentials in URLs (`//user:password@`) are
|
|
5
|
+
* removed; a text over 16 KB is cut and marked.
|
|
6
|
+
*/
|
|
7
|
+
export function errorText(error) {
|
|
8
|
+
const parts = [];
|
|
9
|
+
let current = error;
|
|
10
|
+
for (let depth = 0; current !== undefined && depth < 5; depth++) {
|
|
11
|
+
let text;
|
|
12
|
+
if (current instanceof Error)
|
|
13
|
+
text = current.stack ?? `${current.name}: ${current.message}`;
|
|
14
|
+
else if (typeof current === 'string')
|
|
15
|
+
text = current;
|
|
16
|
+
else {
|
|
17
|
+
try {
|
|
18
|
+
text = `NonError: ${JSON.stringify(current)}`;
|
|
19
|
+
}
|
|
20
|
+
catch {
|
|
21
|
+
text = `NonError: ${String(current)}`; // not serialisable (cycle, BigInt): its string form
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
parts.push(depth ? `Caused by: ${text}` : text);
|
|
25
|
+
current = current instanceof Error ? current.cause : undefined;
|
|
26
|
+
}
|
|
27
|
+
const text = parts.join('\n').replace(/\/\/[^\s/@]*@/g, '//***@');
|
|
28
|
+
return text.length > 16_384
|
|
29
|
+
? `${text.slice(0, 16_384)}… [truncated ${text.length - 16_384} characters]`
|
|
30
|
+
: text;
|
|
31
|
+
}
|
|
32
|
+
/** A stable code of an error (hub, ws or errno code), or `fallback`. */
|
|
33
|
+
export function errorCode(error, fallback) {
|
|
34
|
+
const code = error?.code;
|
|
35
|
+
return typeof code === 'string' && CODE.test(code) ? code : fallback;
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Logs a repeating event once per interval (D-0047): the first occurrence at once, the following
|
|
39
|
+
* ones of the same message and code (and `group`, when given) are counted and reported together
|
|
40
|
+
* (`repeated`) when the interval ends. `group` must come from a bounded set (e.g. registered
|
|
41
|
+
* handler types), never from client input, since each value keeps an entry for an interval. Hot paths (per message, per frame) can report every failure without a burst
|
|
42
|
+
* flooding the log. Field and error text are built only for lines that are written.
|
|
43
|
+
*/
|
|
44
|
+
export class LogThrottle {
|
|
45
|
+
logger;
|
|
46
|
+
intervalMs;
|
|
47
|
+
#entries = new Map();
|
|
48
|
+
constructor(logger, intervalMs = 10_000) {
|
|
49
|
+
this.logger = logger;
|
|
50
|
+
this.intervalMs = intervalMs;
|
|
51
|
+
}
|
|
52
|
+
report(level, message, code, error, fields, group) {
|
|
53
|
+
if (!this.logger.isEnabled(level))
|
|
54
|
+
return;
|
|
55
|
+
const key = `${level}\u0000${code}\u0000${message}${group === undefined ? '' : `\u0000${group}`}`;
|
|
56
|
+
const entry = this.#entries.get(key);
|
|
57
|
+
if (entry) {
|
|
58
|
+
entry.count++;
|
|
59
|
+
entry.error = error;
|
|
60
|
+
entry.fields = fields;
|
|
61
|
+
return;
|
|
62
|
+
}
|
|
63
|
+
this.#write(level, message, code, error, fields, 0);
|
|
64
|
+
const value = {
|
|
65
|
+
count: 0,
|
|
66
|
+
error: undefined,
|
|
67
|
+
fields: undefined,
|
|
68
|
+
timer: setTimeout(() => this.#elapsed(key, value, level, message, code), this.intervalMs),
|
|
69
|
+
};
|
|
70
|
+
value.timer.unref();
|
|
71
|
+
this.#entries.set(key, value);
|
|
72
|
+
}
|
|
73
|
+
#elapsed(key, entry, level, message, code) {
|
|
74
|
+
if (!entry.count) {
|
|
75
|
+
this.#entries.delete(key);
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this.#write(level, message, code, entry.error, entry.fields, entry.count);
|
|
79
|
+
entry.count = 0;
|
|
80
|
+
entry.timer = setTimeout(() => this.#elapsed(key, entry, level, message, code), this.intervalMs);
|
|
81
|
+
entry.timer.unref();
|
|
82
|
+
}
|
|
83
|
+
#write(level, message, code, error, fields, repeated) {
|
|
84
|
+
this.logger.log(level, message, {
|
|
85
|
+
...fields,
|
|
86
|
+
code,
|
|
87
|
+
...(error === undefined ? {} : { error: errorText(error) }),
|
|
88
|
+
...(repeated ? { repeated, intervalMs: this.intervalMs } : {}),
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
/** Writes the counts still pending (on close), so a burst at shutdown is not lost. */
|
|
92
|
+
flush() {
|
|
93
|
+
for (const [key, entry] of this.#entries) {
|
|
94
|
+
clearTimeout(entry.timer);
|
|
95
|
+
if (entry.count) {
|
|
96
|
+
const [level, code, message] = key.split('\u0000');
|
|
97
|
+
this.#write(level, message, code, entry.error, entry.fields, entry.count);
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
this.#entries.clear();
|
|
101
|
+
}
|
|
102
|
+
}
|
package/dist/options.d.ts
CHANGED
|
@@ -17,5 +17,10 @@ export interface Options {
|
|
|
17
17
|
* restart) before it is refused with 503 HUB_RECOVERING. 0 refuses at once.
|
|
18
18
|
*/
|
|
19
19
|
hubWaitMs: number;
|
|
20
|
+
/**
|
|
21
|
+
* How far the timestamp of a sealed frame may differ from this server's clock (D-0059 §4):
|
|
22
|
+
* older or newer frames are refused (4400). Replay nonces are kept twice as long.
|
|
23
|
+
*/
|
|
24
|
+
sealDriftMs: number;
|
|
20
25
|
}
|
|
21
26
|
export declare function parseOptions(input: unknown): Options;
|
package/dist/options.js
CHANGED
|
@@ -23,6 +23,7 @@ export function parseOptions(input) {
|
|
|
23
23
|
heartbeatMs: 10000,
|
|
24
24
|
idleTimeoutMs: 0,
|
|
25
25
|
hubWaitMs: 5000,
|
|
26
|
+
sealDriftMs: 60000,
|
|
26
27
|
};
|
|
27
28
|
if (Object.keys(v).some((k) => !Object.hasOwn(defaults, k)))
|
|
28
29
|
throw new Error('Unknown websocket option');
|
|
@@ -30,8 +31,9 @@ export function parseOptions(input) {
|
|
|
30
31
|
for (const key of Object.keys(defaults)) {
|
|
31
32
|
if (v[key] !== undefined) {
|
|
32
33
|
const x = v[key];
|
|
33
|
-
const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : 1;
|
|
34
|
-
|
|
34
|
+
const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : key === 'sealDriftMs' ? 1000 : 1;
|
|
35
|
+
const max = key === 'sealDriftMs' ? 600000 : 67108864;
|
|
36
|
+
if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < min || x > max)
|
|
35
37
|
throw new Error('Invalid websocket limit');
|
|
36
38
|
result[key] = x;
|
|
37
39
|
}
|
package/dist/router.d.ts
CHANGED
|
@@ -8,10 +8,12 @@ export interface SocketContext {
|
|
|
8
8
|
/** Sends `{ type, data }` to this connection only. */
|
|
9
9
|
send(type: string, data?: unknown): Promise<void>;
|
|
10
10
|
/**
|
|
11
|
-
* Sends `{ type, data }` through the hub to the tenant, a room or a member
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
11
|
+
* Sends `{ type, data }` through the hub to the tenant, a room or a member: each recipient
|
|
12
|
+
* socket gets it as a text frame, like `send`. Resolves with the receipt `{ id, recipients }`
|
|
13
|
+
* once the hub handed it out (D-0057): at most once, no client ACK and no resend, so a socket
|
|
14
|
+
* that is reconnecting or too slow (1013) misses it. Fails with RECOVERING, BUSY or
|
|
15
|
+
* OUTCOME_UNKNOWN (it may have been delivered); sending again is the caller's decision. For
|
|
16
|
+
* what must not be missed, save it and let pages read the current state when they reconnect.
|
|
15
17
|
*/
|
|
16
18
|
broadcast(type: string, data?: unknown, target?: {
|
|
17
19
|
room?: string;
|
|
@@ -26,6 +28,8 @@ export interface SocketDefinition {
|
|
|
26
28
|
readonly constraints?: WebsocketRoute['constraints'];
|
|
27
29
|
/** Client code version this route accepts; others are closed with 4426 (D-0033). */
|
|
28
30
|
readonly version?: string;
|
|
31
|
+
/** Seals this route's frames (D-0059 §4; needs the dokebi-seal plugin). See `WebsocketRoute.seal`. */
|
|
32
|
+
readonly seal?: WebsocketRoute['seal'];
|
|
29
33
|
authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
|
|
30
34
|
authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
|
|
31
35
|
/** Handlers by message type, e.g. `{ 'chat.send': (data, socket) => ... }`. */
|
|
@@ -40,6 +44,7 @@ export interface SocketDefinition {
|
|
|
40
44
|
* A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
|
|
41
45
|
* is sent back as `{ type: 'reply', id, data }` when the message had an `id`. Unknown types,
|
|
42
46
|
* malformed messages and handler failures answer `{ type: 'error', id?, code }`; error messages
|
|
43
|
-
* and stacks are never sent.
|
|
47
|
+
* and stacks are never sent: they go to `session.reportError` when the session has it (the
|
|
48
|
+
* gateway's sessions log them). Use the result with `websocket.route(...)`.
|
|
44
49
|
*/
|
|
45
50
|
export declare function defineSocket(definition: SocketDefinition): WebsocketRoute;
|
package/dist/router.js
CHANGED
|
@@ -22,7 +22,8 @@ function errorCode(error) {
|
|
|
22
22
|
* A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
|
|
23
23
|
* is sent back as `{ type: 'reply', id, data }` when the message had an `id`. Unknown types,
|
|
24
24
|
* malformed messages and handler failures answer `{ type: 'error', id?, code }`; error messages
|
|
25
|
-
* and stacks are never sent.
|
|
25
|
+
* and stacks are never sent: they go to `session.reportError` when the session has it (the
|
|
26
|
+
* gateway's sessions log them). Use the result with `websocket.route(...)`.
|
|
26
27
|
*/
|
|
27
28
|
export function defineSocket(definition) {
|
|
28
29
|
const handlers = new Map();
|
|
@@ -41,6 +42,7 @@ export function defineSocket(definition) {
|
|
|
41
42
|
...(definition.origins === undefined ? {} : { origins: definition.origins }),
|
|
42
43
|
...(definition.constraints === undefined ? {} : { constraints: definition.constraints }),
|
|
43
44
|
...(definition.version === undefined ? {} : { version: definition.version }),
|
|
45
|
+
...(definition.seal === undefined ? {} : { seal: definition.seal }),
|
|
44
46
|
authenticate: (request) => definition.authenticate(request),
|
|
45
47
|
...(definition.authorizeRoom
|
|
46
48
|
? {
|
|
@@ -60,6 +62,8 @@ export function defineSocket(definition) {
|
|
|
60
62
|
message = JSON.parse(decoder.decode(data));
|
|
61
63
|
}
|
|
62
64
|
catch {
|
|
65
|
+
// Answered to the client (its own error); counted by the session's reporter.
|
|
66
|
+
session.reportError?.(undefined, { source: 'client', code: 'INVALID_MESSAGE' });
|
|
63
67
|
return session.send(frame({ type: 'error', code: 'INVALID_MESSAGE' }));
|
|
64
68
|
}
|
|
65
69
|
const id = message !== null &&
|
|
@@ -68,18 +72,30 @@ export function defineSocket(definition) {
|
|
|
68
72
|
ID.test(message.id)
|
|
69
73
|
? message.id
|
|
70
74
|
: undefined;
|
|
71
|
-
if (message === null || typeof message !== 'object' || typeof message.type !== 'string')
|
|
75
|
+
if (message === null || typeof message !== 'object' || typeof message.type !== 'string') {
|
|
76
|
+
session.reportError?.(undefined, { source: 'client', code: 'INVALID_MESSAGE' });
|
|
72
77
|
return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: 'INVALID_MESSAGE' }));
|
|
78
|
+
}
|
|
73
79
|
const handler = handlers.get(message.type);
|
|
74
|
-
if (!handler)
|
|
80
|
+
if (!handler) {
|
|
81
|
+
session.reportError?.(undefined, {
|
|
82
|
+
source: 'client',
|
|
83
|
+
code: 'UNKNOWN_TYPE',
|
|
84
|
+
type: message.type,
|
|
85
|
+
});
|
|
75
86
|
return session.send(frame({ type: 'error', ...(id ? { id } : {}), code: 'UNKNOWN_TYPE' }));
|
|
87
|
+
}
|
|
76
88
|
const socket = context(session);
|
|
77
89
|
let result;
|
|
78
90
|
try {
|
|
79
91
|
result = await handler(message.data, socket);
|
|
80
92
|
}
|
|
81
93
|
catch (error) {
|
|
82
|
-
|
|
94
|
+
// The client gets the code only; the whole error goes to the session's reporter (the
|
|
95
|
+
// gateway logs it, D-0047). A session without a reporter is used outside the gateway.
|
|
96
|
+
const code = errorCode(error);
|
|
97
|
+
session.reportError?.(error, { source: 'handler', code, type: message.type });
|
|
98
|
+
return session.send(frame({ type: 'error', ...(id ? { id } : {}), code }));
|
|
83
99
|
}
|
|
84
100
|
if (id)
|
|
85
101
|
await session.send(frame(result === undefined ? { type: 'reply', id } : { type: 'reply', id, data: result }));
|
package/dist/types.d.ts
CHANGED
|
@@ -7,6 +7,11 @@ export interface WebsocketIdentity {
|
|
|
7
7
|
readonly clientId?: string;
|
|
8
8
|
readonly rooms?: readonly string[];
|
|
9
9
|
readonly metadata?: Readonly<Record<string, string>>;
|
|
10
|
+
/**
|
|
11
|
+
* Which realtime namespace of the app the connection joins (D-0061). Read and removed by
|
|
12
|
+
* @dokebi/app; this package never sends it to the hub.
|
|
13
|
+
*/
|
|
14
|
+
readonly namespace?: string;
|
|
10
15
|
}
|
|
11
16
|
/** A connection of the hub as presence changes report it (any server of the cluster). */
|
|
12
17
|
export interface WebsocketPeer {
|
|
@@ -26,10 +31,29 @@ export interface WebsocketPresence {
|
|
|
26
31
|
readonly joined: readonly WebsocketPeer[];
|
|
27
32
|
readonly left: readonly WebsocketPeer[];
|
|
28
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* What a message router answered with an error frame instead of a reply (D-0047), passed to
|
|
36
|
+
* `WebsocketSession.reportError` so the cause reaches the server log.
|
|
37
|
+
*/
|
|
38
|
+
export interface WebsocketErrorDetails {
|
|
39
|
+
/** `handler`: a message handler threw. `client`: the message was malformed or of an unknown type. */
|
|
40
|
+
readonly source: 'handler' | 'client';
|
|
41
|
+
/** The code sent to the client, e.g. the error's code, `HANDLER_FAILED` or `UNKNOWN_TYPE`. */
|
|
42
|
+
readonly code: string;
|
|
43
|
+
/** The message type, when the message had one. */
|
|
44
|
+
readonly type?: string;
|
|
45
|
+
}
|
|
29
46
|
export interface WebsocketSession {
|
|
30
47
|
readonly id: string;
|
|
31
48
|
readonly identity: WebsocketIdentity;
|
|
32
49
|
send(data: string | Uint8Array): Promise<void>;
|
|
50
|
+
/**
|
|
51
|
+
* Hands `data` to the connections of this tenant (or a room or member of it) through the hub,
|
|
52
|
+
* at most once (D-0057). Each recipient socket gets the bytes as they are: a text frame when
|
|
53
|
+
* they are valid UTF-8, a binary frame otherwise. The receipt `{ id, recipients }` lists the
|
|
54
|
+
* connections that matched when it was sent, not ones that confirmed it. Fails with
|
|
55
|
+
* RECOVERING, BUSY or OUTCOME_UNKNOWN; nothing is resent.
|
|
56
|
+
*/
|
|
33
57
|
broadcast(data: Uint8Array, target?: {
|
|
34
58
|
room?: string;
|
|
35
59
|
member?: string;
|
|
@@ -37,6 +61,13 @@ export interface WebsocketSession {
|
|
|
37
61
|
join(room: string): Promise<void>;
|
|
38
62
|
leave(room: string): Promise<void>;
|
|
39
63
|
close(code?: number, reason?: string): void;
|
|
64
|
+
/**
|
|
65
|
+
* Reports a failure the route turned into a client error frame (D-0047). The gateway logs it
|
|
66
|
+
* (handler failures at error, client errors at debug, repeats counted); a session without it
|
|
67
|
+
* (a custom or test session) leaves reporting to the route. `error` is undefined for client
|
|
68
|
+
* errors that have no cause worth logging.
|
|
69
|
+
*/
|
|
70
|
+
reportError?(error: unknown, details: WebsocketErrorDetails): void;
|
|
40
71
|
}
|
|
41
72
|
export interface WebsocketRoute {
|
|
42
73
|
readonly path: string;
|
|
@@ -58,6 +89,15 @@ export interface WebsocketRoute {
|
|
|
58
89
|
* instead of joining with an old protocol.
|
|
59
90
|
*/
|
|
60
91
|
readonly version?: string;
|
|
92
|
+
/**
|
|
93
|
+
* Seals every frame of the connections this decides for (D-0059 §4): `true`, or a function of
|
|
94
|
+
* the upgrade request (dokebi-app sets one from `domains.<host>.seal`). A sealed connection
|
|
95
|
+
* needs a codec provider (the dokebi-seal plugin; without it setup fails with
|
|
96
|
+
* SEAL_PROVIDER_MISSING), must offer the `dokebi.seal` subprotocol (otherwise 4415
|
|
97
|
+
* `Seal required`), gets a sealed `{"$dokebi":"hello-v1"}` first, and is closed with 4400
|
|
98
|
+
* `Bad frame` on a frame that does not open. Routes and handlers see plain text either way.
|
|
99
|
+
*/
|
|
100
|
+
readonly seal?: boolean | ((request: FastifyRequest) => boolean);
|
|
61
101
|
authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
|
|
62
102
|
authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
|
|
63
103
|
message(data: Uint8Array, session: WebsocketSession): Awaitable<void>;
|
|
@@ -67,7 +107,101 @@ export interface WebsocketRoute {
|
|
|
67
107
|
*/
|
|
68
108
|
presence?(change: WebsocketPresence, session: WebsocketSession): Awaitable<void>;
|
|
69
109
|
}
|
|
110
|
+
/** A connection as the hub lists it (any server of the cluster). */
|
|
111
|
+
export interface WebsocketConnectionInfo extends WebsocketPeer {
|
|
112
|
+
readonly tenant: string;
|
|
113
|
+
readonly rooms: readonly string[];
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* Which connections a server-side call is about (D-0061): one tenant (`tenant`) or every tenant
|
|
117
|
+
* whose name starts with `tenantPrefix` (exactly one of the two), optionally narrowed to a room,
|
|
118
|
+
* a member, or a member in a room. Strings are 1 to 256 bytes.
|
|
119
|
+
*/
|
|
120
|
+
export interface WebsocketFilter {
|
|
121
|
+
readonly tenant?: string;
|
|
122
|
+
readonly tenantPrefix?: string;
|
|
123
|
+
readonly room?: string;
|
|
124
|
+
readonly member?: string;
|
|
125
|
+
}
|
|
126
|
+
/** What a server-side broadcast resolves with: one hub broadcast per tenant it went to. */
|
|
127
|
+
export interface WebsocketReceipt {
|
|
128
|
+
/** The hub broadcast ids (one per tenant); empty when no tenant matched (nothing was sent). */
|
|
129
|
+
readonly ids: readonly string[];
|
|
130
|
+
/** The connections the hub matched when it was sent (not a confirmation, D-0057). */
|
|
131
|
+
readonly recipients: readonly string[];
|
|
132
|
+
}
|
|
133
|
+
/** What a server-side kick resolves with: one hub kick per tenant. */
|
|
134
|
+
export interface WebsocketKickReceipt {
|
|
135
|
+
readonly ids: readonly string[];
|
|
136
|
+
}
|
|
70
137
|
export interface WebsocketApi {
|
|
71
138
|
route(definition: WebsocketRoute): void;
|
|
72
139
|
readonly connections: number;
|
|
140
|
+
/** True when a socket codec provider (the dokebi-seal plugin) is registered: sealed routes work. */
|
|
141
|
+
readonly sealing: boolean;
|
|
142
|
+
/**
|
|
143
|
+
* Connections of the cluster that match (D-0061). With `tenant`: asked from the hub (the
|
|
144
|
+
* leader in cluster mode; fails with the hub's code, e.g. RECOVERING). With `tenantPrefix`: read
|
|
145
|
+
* from the presence the hub reported to this server (every server, eventually consistent;
|
|
146
|
+
* empty before start), since the hub has no query across tenants.
|
|
147
|
+
*/
|
|
148
|
+
list(filter: WebsocketFilter): Promise<readonly WebsocketConnectionInfo[]>;
|
|
149
|
+
/**
|
|
150
|
+
* Hands `data` through the hub to the matching connections, like `session.broadcast` but from
|
|
151
|
+
* server code (D-0061): at most once, text frames for UTF-8 and binary otherwise, sealed per
|
|
152
|
+
* sealed socket (binary is not sent to sealed sockets). `tenantPrefix` sends one hub broadcast
|
|
153
|
+
* per tenant this server knows from presence. Fails with the hub's code (RECOVERING, BUSY,
|
|
154
|
+
* OUTCOME_UNKNOWN); with `tenantPrefix` the error has `receipt` for the tenants that worked.
|
|
155
|
+
*/
|
|
156
|
+
broadcast(filter: WebsocketFilter, data: string | Uint8Array): Promise<WebsocketReceipt>;
|
|
157
|
+
/** `broadcast` of the `{ type, data }` text frame `defineSocket` handlers send. */
|
|
158
|
+
send(filter: WebsocketFilter, type: string, data?: unknown): Promise<WebsocketReceipt>;
|
|
159
|
+
/** Closes the matching connections on every server (hub kick; code 4000-4999, default 4403). */
|
|
160
|
+
kick(filter: WebsocketFilter, code?: number, reason?: string): Promise<WebsocketKickReceipt>;
|
|
161
|
+
/**
|
|
162
|
+
* Calls `listener` with each tenant's joins and leaves (every server, as routes' `presence`
|
|
163
|
+
* gets them) until the returned function is called. A listener that throws or rejects is
|
|
164
|
+
* logged at error (PRESENCE_LISTENER_FAILED); the others still run.
|
|
165
|
+
*/
|
|
166
|
+
onPresence(listener: (change: WebsocketPresence) => unknown): () => void;
|
|
167
|
+
}
|
|
168
|
+
/** The subprotocol a client offers when it can seal frames; a sealed connection selects it. */
|
|
169
|
+
export declare const SEAL_PROTOCOL = "dokebi.seal";
|
|
170
|
+
/**
|
|
171
|
+
* Offered together with `dokebi.seal` by a client that can seal; a plain connection selects it,
|
|
172
|
+
* so the same client runs plain there (a sealed connection never selects it).
|
|
173
|
+
*/
|
|
174
|
+
export declare const PLAIN_PROTOCOL = "dokebi.plain";
|
|
175
|
+
/** One-time nonce store for sealed frames: the hub's `nonces()` (D-0038). */
|
|
176
|
+
export interface SocketNonceStore {
|
|
177
|
+
setIfNotExists(key: string, ttlSeconds: number): Promise<boolean>;
|
|
178
|
+
readonly shared: boolean;
|
|
179
|
+
}
|
|
180
|
+
/** What a codec provider is told about one sealed connection (D-0059 §4). */
|
|
181
|
+
export interface SocketCodecConnection {
|
|
182
|
+
/** The request host without port, lower case (dokebi-web `requestHost`, honours trustProxy). */
|
|
183
|
+
readonly host: string;
|
|
184
|
+
/** The upgrade request path without the query. */
|
|
185
|
+
readonly path: string;
|
|
186
|
+
readonly userAgent: string;
|
|
187
|
+
/** Replay nonces: Redis shared in cluster mode, this process in local mode. */
|
|
188
|
+
readonly nonces: SocketNonceStore;
|
|
189
|
+
/** Accepted clock difference of a frame (`sealDriftMs`). */
|
|
190
|
+
readonly driftMs: number;
|
|
191
|
+
}
|
|
192
|
+
/** Turns the frames of one connection into text and back. Its errors never reach the client. */
|
|
193
|
+
export interface SocketCodec {
|
|
194
|
+
/** Opens one incoming text frame; rejects (with a `reason` such as `drift` or `replay`) to refuse it. */
|
|
195
|
+
decode(frame: string): Promise<string>;
|
|
196
|
+
/** Seals one outgoing text message. */
|
|
197
|
+
encode(text: string): string;
|
|
198
|
+
/** The sealed `{"$dokebi":"hello-v1"}` frame sent first on the connection. */
|
|
199
|
+
hello(): string;
|
|
200
|
+
}
|
|
201
|
+
/**
|
|
202
|
+
* The shape the dokebi-seal plugin provides (looked up by name, never imported: this public
|
|
203
|
+
* package does not depend on @dokebi/seal).
|
|
204
|
+
*/
|
|
205
|
+
export interface SocketCodecProvider {
|
|
206
|
+
forConnection(connection: SocketCodecConnection): SocketCodec;
|
|
73
207
|
}
|
package/dist/types.js
CHANGED
|
@@ -1 +1,7 @@
|
|
|
1
|
-
|
|
1
|
+
/** The subprotocol a client offers when it can seal frames; a sealed connection selects it. */
|
|
2
|
+
export const SEAL_PROTOCOL = 'dokebi.seal';
|
|
3
|
+
/**
|
|
4
|
+
* Offered together with `dokebi.seal` by a client that can seal; a plain connection selects it,
|
|
5
|
+
* so the same client runs plain there (a sealed connection never selects it).
|
|
6
|
+
*/
|
|
7
|
+
export const PLAIN_PROTOCOL = 'dokebi.plain';
|
package/options.schema.json
CHANGED
|
@@ -52,6 +52,13 @@
|
|
|
52
52
|
"maximum": 67108864,
|
|
53
53
|
"default": 5000,
|
|
54
54
|
"description": "How long an upgrade waits for a reconnecting hub (leader change, rolling restart) before 503 HUB_RECOVERING; 0 refuses at once."
|
|
55
|
+
},
|
|
56
|
+
"sealDriftMs": {
|
|
57
|
+
"type": "integer",
|
|
58
|
+
"minimum": 1000,
|
|
59
|
+
"maximum": 600000,
|
|
60
|
+
"default": 60000,
|
|
61
|
+
"description": "Sealed connections (route.seal, dokebi-app domains.<host>.seal): how far a frame timestamp may differ from the server clock before the frame is refused (4400). Needs the dokebi-seal plugin."
|
|
55
62
|
}
|
|
56
63
|
}
|
|
57
64
|
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dokebi/websocket",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
@@ -10,10 +10,6 @@
|
|
|
10
10
|
".": {
|
|
11
11
|
"types": "./dist/index.d.ts",
|
|
12
12
|
"import": "./dist/index.js"
|
|
13
|
-
},
|
|
14
|
-
"./client": {
|
|
15
|
-
"types": "./dist/client.d.ts",
|
|
16
|
-
"import": "./dist/client.js"
|
|
17
13
|
}
|
|
18
14
|
},
|
|
19
15
|
"files": [
|
|
@@ -37,12 +33,12 @@
|
|
|
37
33
|
},
|
|
38
34
|
"peerDependencies": {
|
|
39
35
|
"@dokebi/core": "^0.2.0",
|
|
40
|
-
"@dokebi/web": "^0.1.0",
|
|
41
|
-
"@dokebi/websocket-hub": "^0.
|
|
36
|
+
"@dokebi/web": "^0.1.0 || ^0.2.0",
|
|
37
|
+
"@dokebi/websocket-hub": "^0.3.0"
|
|
42
38
|
},
|
|
43
39
|
"devDependencies": {
|
|
44
|
-
"@dokebi/web": "0.
|
|
45
|
-
"@dokebi/websocket-hub": "0.
|
|
40
|
+
"@dokebi/web": "0.2.0",
|
|
41
|
+
"@dokebi/websocket-hub": "0.3.0"
|
|
46
42
|
},
|
|
47
43
|
"dokebi": {
|
|
48
44
|
"schemaVersion": 2,
|
|
@@ -51,11 +47,16 @@
|
|
|
51
47
|
"dependencies": [
|
|
52
48
|
{
|
|
53
49
|
"name": "dokebi-websocket-hub",
|
|
54
|
-
"version": "^0.
|
|
50
|
+
"version": "^0.3.0"
|
|
55
51
|
},
|
|
56
52
|
{
|
|
57
53
|
"name": "dokebi-web",
|
|
58
|
-
"version": "^0.1.0"
|
|
54
|
+
"version": "^0.1.0 || ^0.2.0"
|
|
55
|
+
},
|
|
56
|
+
{
|
|
57
|
+
"name": "dokebi-seal",
|
|
58
|
+
"version": "^0.1.0",
|
|
59
|
+
"optional": true
|
|
59
60
|
}
|
|
60
61
|
],
|
|
61
62
|
"optionsSchema": "options.schema.json",
|
package/dist/client.d.ts
DELETED
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/** Keep one receiver per authenticated clientId across socket reconnects. No Node dependencies. */
|
|
2
|
-
export declare class DeliveryReceiver {
|
|
3
|
-
#private;
|
|
4
|
-
readonly capacity: number;
|
|
5
|
-
constructor(capacity?: number);
|
|
6
|
-
receive(raw: string | Uint8Array, deliver: (data: Uint8Array, id: string) => void | Promise<void>, acknowledge: (frame: string) => void): Promise<boolean>;
|
|
7
|
-
}
|
package/dist/client.js
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
const decoder = new TextDecoder();
|
|
2
|
-
/** Keep one receiver per authenticated clientId across socket reconnects. No Node dependencies. */
|
|
3
|
-
export class DeliveryReceiver {
|
|
4
|
-
capacity;
|
|
5
|
-
#seen = new Map();
|
|
6
|
-
#sweepAt = 0;
|
|
7
|
-
constructor(capacity = 10000) {
|
|
8
|
-
this.capacity = capacity;
|
|
9
|
-
if (!Number.isSafeInteger(capacity) || capacity < 1)
|
|
10
|
-
throw new Error('Invalid capacity');
|
|
11
|
-
}
|
|
12
|
-
async receive(raw, deliver, acknowledge) {
|
|
13
|
-
const text = typeof raw === 'string' ? raw : decoder.decode(raw);
|
|
14
|
-
let frame;
|
|
15
|
-
try {
|
|
16
|
-
frame = JSON.parse(text);
|
|
17
|
-
}
|
|
18
|
-
catch {
|
|
19
|
-
return false;
|
|
20
|
-
}
|
|
21
|
-
if (frame?.$dokebi !== 'delivery-v1')
|
|
22
|
-
return false;
|
|
23
|
-
if (typeof frame.id !== 'string' ||
|
|
24
|
-
!/^[a-f0-9-]{36}$/.test(frame.id) ||
|
|
25
|
-
typeof frame.expiresAt !== 'number' ||
|
|
26
|
-
!Number.isSafeInteger(frame.expiresAt) ||
|
|
27
|
-
typeof frame.data !== 'string')
|
|
28
|
-
throw new Error('Invalid delivery');
|
|
29
|
-
const now = Date.now();
|
|
30
|
-
if (now > frame.expiresAt)
|
|
31
|
-
return true;
|
|
32
|
-
if (now >= this.#sweepAt) {
|
|
33
|
-
for (const [id, entry] of this.#seen)
|
|
34
|
-
if (entry.expiresAt + 5000 < now)
|
|
35
|
-
this.#seen.delete(id);
|
|
36
|
-
this.#sweepAt = now + 1000;
|
|
37
|
-
}
|
|
38
|
-
const id = frame.id;
|
|
39
|
-
let entry = this.#seen.get(id);
|
|
40
|
-
if (!entry) {
|
|
41
|
-
if (this.#seen.size >= this.capacity)
|
|
42
|
-
throw new Error('Delivery receiver capacity exceeded');
|
|
43
|
-
const binary = atob(frame.data), bytes = new Uint8Array(binary.length);
|
|
44
|
-
for (let index = 0; index < binary.length; index++)
|
|
45
|
-
bytes[index] = binary.charCodeAt(index);
|
|
46
|
-
entry = {
|
|
47
|
-
expiresAt: frame.expiresAt,
|
|
48
|
-
work: Promise.resolve().then(() => deliver(bytes, id)),
|
|
49
|
-
};
|
|
50
|
-
this.#seen.set(id, entry);
|
|
51
|
-
void entry.work?.catch(() => {
|
|
52
|
-
this.#seen.delete(id);
|
|
53
|
-
});
|
|
54
|
-
}
|
|
55
|
-
await entry.work;
|
|
56
|
-
entry.work = undefined;
|
|
57
|
-
acknowledge(JSON.stringify({ $dokebi: 'ack-v1', id }));
|
|
58
|
-
return true;
|
|
59
|
-
}
|
|
60
|
-
}
|