@dokebi/websocket 0.2.0 → 0.4.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 +144 -68
- package/README.md +86 -43
- package/dist/errors.d.ts +11 -0
- package/dist/errors.js +38 -0
- package/dist/gateway.d.ts +3 -2
- package/dist/gateway.js +487 -90
- package/dist/index.d.ts +3 -0
- package/dist/index.js +31 -19
- package/dist/options.d.ts +15 -20
- package/dist/options.js +38 -38
- package/dist/router.d.ts +3 -1
- package/dist/router.js +33 -10
- package/dist/transport.d.ts +30 -0
- package/dist/transport.js +72 -0
- package/dist/types.d.ts +108 -0
- package/dist/types.js +7 -1
- package/options.schema.json +40 -6
- package/package.json +39 -11
- package/dist/log.d.ts +0 -25
- package/dist/log.js +0 -102
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import type { WebsocketApi } from './types.js';
|
|
2
|
+
export { WebsocketError, type WebsocketErrorCode } from './errors.js';
|
|
3
|
+
export { type Options as WebsocketOptions, options } from './options.js';
|
|
2
4
|
export * from './router.js';
|
|
5
|
+
export type { WebsocketNamespaceHandle, WebsocketNamespaceTarget, WebsocketTransport, } from './transport.js';
|
|
3
6
|
export * from './types.js';
|
|
4
7
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
5
8
|
export declare const createPlugin: import("@dokebi/core").PluginFactory<WebsocketApi>;
|
package/dist/index.js
CHANGED
|
@@ -1,20 +1,22 @@
|
|
|
1
|
-
import { definePlugin,
|
|
1
|
+
import { definePlugin, optionalDependency } from '@dokebi/core';
|
|
2
|
+
import { dependency as web } from '@dokebi/web/dependency';
|
|
3
|
+
import { realtime } from '@dokebi/web/points';
|
|
4
|
+
// Always installed with this plugin (peer, required in the manifest): the provider's own file
|
|
5
|
+
// holds the name, package and range (D-0063 §6).
|
|
6
|
+
import { dependency as hub } from '@dokebi/websocket-hub/dependency';
|
|
7
|
+
import { WebsocketError } from './errors.js';
|
|
2
8
|
import { Gateway } from './gateway.js';
|
|
3
|
-
import {
|
|
9
|
+
import { options } from './options.js';
|
|
10
|
+
import { websocketTransport } from './transport.js';
|
|
11
|
+
export { WebsocketError } from './errors.js';
|
|
12
|
+
export { options } from './options.js';
|
|
4
13
|
export * from './router.js';
|
|
5
14
|
export * from './types.js';
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
});
|
|
12
|
-
const web = providerDependency({
|
|
13
|
-
name: 'dokebi-web',
|
|
14
|
-
version: '^0.1.0',
|
|
15
|
-
packageName: '@dokebi/web',
|
|
16
|
-
load: () => import('@dokebi/web'),
|
|
17
|
-
});
|
|
15
|
+
/**
|
|
16
|
+
* The socket codec provider (D-0059 §4): the private dokebi-seal plugin when it is registered.
|
|
17
|
+
* Looked up by name only; this package never imports @dokebi/seal.
|
|
18
|
+
*/
|
|
19
|
+
const seal = optionalDependency({ name: 'dokebi-seal', version: '^0.4.0' });
|
|
18
20
|
class WebsocketRuntime {
|
|
19
21
|
#options;
|
|
20
22
|
#gateway;
|
|
@@ -22,7 +24,16 @@ class WebsocketRuntime {
|
|
|
22
24
|
this.#options = options;
|
|
23
25
|
}
|
|
24
26
|
setup(context) {
|
|
25
|
-
|
|
27
|
+
const codecs = context.getOptionalDependency(seal);
|
|
28
|
+
if (codecs !== undefined && typeof codecs?.forConnection !== 'function')
|
|
29
|
+
throw new WebsocketError('SEAL_PROVIDER_INVALID', 'dokebi-seal does not provide forConnection');
|
|
30
|
+
context.logger.log('debug', 'WebSocket seal provider', {
|
|
31
|
+
present: codecs !== undefined,
|
|
32
|
+
sealDriftMs: this.#options.sealDriftMs,
|
|
33
|
+
});
|
|
34
|
+
this.#gateway = new Gateway(context, context.getDependency(web), context.getDependency(hub), this.#options, codecs);
|
|
35
|
+
// D-0063 §5: the `websocket` transport for dokebi-app (inert until a plugin collects it).
|
|
36
|
+
context.contribute(realtime, websocketTransport(this.#gateway.api, context.logger));
|
|
26
37
|
return this.#gateway.api;
|
|
27
38
|
}
|
|
28
39
|
start() {
|
|
@@ -35,9 +46,10 @@ class WebsocketRuntime {
|
|
|
35
46
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket']`. */
|
|
36
47
|
export const createPlugin = definePlugin({
|
|
37
48
|
name: 'dokebi-websocket',
|
|
38
|
-
version: '0.
|
|
39
|
-
core: '^0.
|
|
40
|
-
options
|
|
41
|
-
|
|
49
|
+
version: '0.4.0',
|
|
50
|
+
core: '^0.4.0',
|
|
51
|
+
options,
|
|
52
|
+
contributes: [realtime],
|
|
53
|
+
dependencies: () => [hub, web, seal],
|
|
42
54
|
instance: ({ options }) => new WebsocketRuntime(options),
|
|
43
55
|
});
|
package/dist/options.d.ts
CHANGED
|
@@ -1,21 +1,16 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
* How long an upgrade waits for the hub while it reconnects (a leader change, a rolling
|
|
17
|
-
* restart) before it is refused with 503 HUB_RECOVERING. 0 refuses at once.
|
|
18
|
-
*/
|
|
19
|
-
hubWaitMs: number;
|
|
20
|
-
}
|
|
1
|
+
import { type OptionsOf } from '@dokebi/core';
|
|
2
|
+
export declare const options: import("@dokebi/core").OptionsDeclaration<{
|
|
3
|
+
readonly heartbeatMs: number;
|
|
4
|
+
readonly hubWaitMs: number;
|
|
5
|
+
readonly idleTimeoutMs: number;
|
|
6
|
+
readonly maxBufferedBytes: number;
|
|
7
|
+
readonly maxConnections: number;
|
|
8
|
+
readonly maxPayloadBytes: number;
|
|
9
|
+
readonly maxPending: number;
|
|
10
|
+
readonly sealDriftMs: number;
|
|
11
|
+
readonly shutdownTimeoutMs: number;
|
|
12
|
+
}>;
|
|
13
|
+
/** The parsed options of dokebi-websocket (`options.dokebi-websocket`). */
|
|
14
|
+
export type Options = OptionsOf<typeof options>;
|
|
15
|
+
/** Parses `options.dokebi-websocket`; fails with core `INVALID_OPTIONS` (`details.issues`). */
|
|
21
16
|
export declare function parseOptions(input: unknown): Options;
|
package/dist/options.js
CHANGED
|
@@ -1,40 +1,40 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { defineOptions, option as o } from '@dokebi/core';
|
|
2
|
+
/*
|
|
3
|
+
* Options of dokebi-websocket (D-0063 §3): one declaration is the parser and, at build time,
|
|
4
|
+
* options.schema.json. The rules are the hand parser's before wave B.
|
|
5
|
+
*/
|
|
6
|
+
const LIMIT = 67108864;
|
|
7
|
+
const limit = (defaultValue, description) => o.integer({ minimum: 1, maximum: LIMIT, default: defaultValue, description });
|
|
8
|
+
export const options = defineOptions({
|
|
9
|
+
maxPayloadBytes: limit(65536, 'Largest incoming frame in bytes.'),
|
|
10
|
+
maxPayload: o.alias('maxPayloadBytes'),
|
|
11
|
+
maxConnections: limit(128, 'Open connections this process accepts at most.'),
|
|
12
|
+
maxPending: limit(32, 'Messages of one connection waiting for its handler at most.'),
|
|
13
|
+
maxPendingMessages: o.alias('maxPending'),
|
|
14
|
+
maxBufferedBytes: limit(1048576, 'Bytes waiting to be sent to one connection at most; a slower client is closed (SLOW_CONSUMER).'),
|
|
15
|
+
shutdownTimeoutMs: limit(2000, 'How long drain waits for closing connections (1012) before it cuts them, in ms.'),
|
|
16
|
+
closeTimeoutMs: o.alias('shutdownTimeoutMs'),
|
|
17
|
+
heartbeatMs: limit(10000, 'Interval of WebSocket pings, in ms.'),
|
|
18
|
+
idleTimeoutMs: o.integer({
|
|
19
|
+
minimum: 0,
|
|
20
|
+
maximum: LIMIT,
|
|
21
|
+
default: 0,
|
|
22
|
+
description: 'Close (4408 Idle) a connection that sent nothing for this long; 0 never. Clients send {"$dokebi":"ping-v1"} from their script to show the page still runs.',
|
|
23
|
+
}),
|
|
24
|
+
hubWaitMs: o.integer({
|
|
25
|
+
minimum: 0,
|
|
26
|
+
maximum: LIMIT,
|
|
27
|
+
default: 5000,
|
|
28
|
+
description: 'How long an upgrade waits for a reconnecting hub (leader change, rolling restart) before 503 HUB_RECOVERING; 0 refuses at once.',
|
|
29
|
+
}),
|
|
30
|
+
sealDriftMs: o.integer({
|
|
31
|
+
minimum: 1000,
|
|
32
|
+
maximum: 600000,
|
|
33
|
+
default: 60000,
|
|
34
|
+
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.',
|
|
35
|
+
}),
|
|
36
|
+
});
|
|
37
|
+
/** Parses `options.dokebi-websocket`; fails with core `INVALID_OPTIONS` (`details.issues`). */
|
|
2
38
|
export function parseOptions(input) {
|
|
3
|
-
|
|
4
|
-
input = {};
|
|
5
|
-
if (!input ||
|
|
6
|
-
typeof input !== 'object' ||
|
|
7
|
-
types.isProxy(input) ||
|
|
8
|
-
![Object.prototype, null].includes(Object.getPrototypeOf(input)))
|
|
9
|
-
throw new Error('Invalid websocket options');
|
|
10
|
-
const v = Object.create(null);
|
|
11
|
-
for (const key of Reflect.ownKeys(input)) {
|
|
12
|
-
const desc = Object.getOwnPropertyDescriptor(input, key);
|
|
13
|
-
if (typeof key !== 'string' || !desc || !('value' in desc) || !desc.enumerable)
|
|
14
|
-
throw new Error('Invalid websocket options');
|
|
15
|
-
v[key] = desc.value;
|
|
16
|
-
}
|
|
17
|
-
const defaults = {
|
|
18
|
-
maxPayload: 65536,
|
|
19
|
-
maxConnections: 128,
|
|
20
|
-
maxPendingMessages: 32,
|
|
21
|
-
maxBufferedBytes: 1048576,
|
|
22
|
-
closeTimeoutMs: 2000,
|
|
23
|
-
heartbeatMs: 10000,
|
|
24
|
-
idleTimeoutMs: 0,
|
|
25
|
-
hubWaitMs: 5000,
|
|
26
|
-
};
|
|
27
|
-
if (Object.keys(v).some((k) => !Object.hasOwn(defaults, k)))
|
|
28
|
-
throw new Error('Unknown websocket option');
|
|
29
|
-
const result = { ...defaults };
|
|
30
|
-
for (const key of Object.keys(defaults)) {
|
|
31
|
-
if (v[key] !== undefined) {
|
|
32
|
-
const x = v[key];
|
|
33
|
-
const min = key === 'idleTimeoutMs' || key === 'hubWaitMs' ? 0 : 1;
|
|
34
|
-
if (typeof x !== 'number' || !Number.isSafeInteger(x) || x < min || x > 67108864)
|
|
35
|
-
throw new Error('Invalid websocket limit');
|
|
36
|
-
result[key] = x;
|
|
37
|
-
}
|
|
38
|
-
}
|
|
39
|
-
return result;
|
|
39
|
+
return options.parse(input, { plugin: 'dokebi-websocket' });
|
|
40
40
|
}
|
package/dist/router.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type Awaitable } from '@dokebi/core';
|
|
2
2
|
import type { FastifyRequest } from 'fastify';
|
|
3
3
|
import type { WebsocketIdentity, WebsocketPresence, WebsocketRoute, WebsocketSession } from './types.js';
|
|
4
4
|
/** What a message handler receives besides the message data. */
|
|
@@ -28,6 +28,8 @@ export interface SocketDefinition {
|
|
|
28
28
|
readonly constraints?: WebsocketRoute['constraints'];
|
|
29
29
|
/** Client code version this route accepts; others are closed with 4426 (D-0033). */
|
|
30
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'];
|
|
31
33
|
authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
|
|
32
34
|
authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
|
|
33
35
|
/** Handlers by message type, e.g. `{ 'chat.send': (data, socket) => ... }`. */
|
package/dist/router.js
CHANGED
|
@@ -1,6 +1,8 @@
|
|
|
1
|
+
import { DokebiError, isDokebiError } from '@dokebi/core';
|
|
2
|
+
import { diagnostics } from '@dokebi/core/libraries';
|
|
3
|
+
import { WebsocketError } from './errors.js';
|
|
1
4
|
const TYPE = /^[A-Za-z][A-Za-z0-9._:-]{0,63}$/;
|
|
2
5
|
const ID = /^[A-Za-z0-9._:-]{1,64}$/;
|
|
3
|
-
const CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
4
6
|
const encoder = new TextEncoder();
|
|
5
7
|
const decoder = new TextDecoder('utf-8', { fatal: true });
|
|
6
8
|
function frame(value) {
|
|
@@ -14,9 +16,24 @@ function context(session) {
|
|
|
14
16
|
broadcast: (type, value, target) => session.broadcast(encoder.encode(frame(value === undefined ? { type } : { type, data: value })), target),
|
|
15
17
|
});
|
|
16
18
|
}
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
19
|
+
/**
|
|
20
|
+
* What an error frame says about a handler failure (D-0063 §1): the code always; for a Dokebi
|
|
21
|
+
* error (a DokebiError, or that shape naming its plugin) also `message` and `hint`, and `fix`
|
|
22
|
+
* outside production. Other errors send their code only: messages and stacks stay in the log.
|
|
23
|
+
*/
|
|
24
|
+
function errorFields(error, production) {
|
|
25
|
+
const code = diagnostics.errorCode(error, 'HANDLER_FAILED');
|
|
26
|
+
const known = error instanceof DokebiError || (isDokebiError(error) && typeof error.plugin === 'string')
|
|
27
|
+
? error
|
|
28
|
+
: undefined;
|
|
29
|
+
if (!known)
|
|
30
|
+
return { code };
|
|
31
|
+
return {
|
|
32
|
+
code,
|
|
33
|
+
message: known.message,
|
|
34
|
+
...(known.hint === undefined ? {} : { hint: known.hint }),
|
|
35
|
+
...(production || known.fix === undefined ? {} : { fix: known.fix }),
|
|
36
|
+
};
|
|
20
37
|
}
|
|
21
38
|
/**
|
|
22
39
|
* A WebSocket message router. Messages are JSON `{ type, data?, id? }`. A handler's return value
|
|
@@ -28,13 +45,14 @@ function errorCode(error) {
|
|
|
28
45
|
export function defineSocket(definition) {
|
|
29
46
|
const handlers = new Map();
|
|
30
47
|
if (!definition || typeof definition.on !== 'object' || definition.on === null)
|
|
31
|
-
throw new
|
|
48
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid socket definition');
|
|
32
49
|
const presence = definition.presence;
|
|
50
|
+
const production = process.env.NODE_ENV === 'production';
|
|
33
51
|
if (presence !== undefined && typeof presence !== 'boolean' && typeof presence !== 'function')
|
|
34
|
-
throw new
|
|
52
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid socket presence');
|
|
35
53
|
for (const [type, handler] of Object.entries(definition.on)) {
|
|
36
54
|
if (!TYPE.test(type) || type === 'reply' || type === 'error' || typeof handler !== 'function')
|
|
37
|
-
throw new
|
|
55
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid socket handler: ' + type);
|
|
38
56
|
handlers.set(type, handler);
|
|
39
57
|
}
|
|
40
58
|
return Object.freeze({
|
|
@@ -42,6 +60,7 @@ export function defineSocket(definition) {
|
|
|
42
60
|
...(definition.origins === undefined ? {} : { origins: definition.origins }),
|
|
43
61
|
...(definition.constraints === undefined ? {} : { constraints: definition.constraints }),
|
|
44
62
|
...(definition.version === undefined ? {} : { version: definition.version }),
|
|
63
|
+
...(definition.seal === undefined ? {} : { seal: definition.seal }),
|
|
45
64
|
authenticate: (request) => definition.authenticate(request),
|
|
46
65
|
...(definition.authorizeRoom
|
|
47
66
|
? {
|
|
@@ -92,9 +111,13 @@ export function defineSocket(definition) {
|
|
|
92
111
|
catch (error) {
|
|
93
112
|
// The client gets the code only; the whole error goes to the session's reporter (the
|
|
94
113
|
// gateway logs it, D-0047). A session without a reporter is used outside the gateway.
|
|
95
|
-
const
|
|
96
|
-
session.reportError?.(error, {
|
|
97
|
-
|
|
114
|
+
const fields = errorFields(error, production);
|
|
115
|
+
session.reportError?.(error, {
|
|
116
|
+
source: 'handler',
|
|
117
|
+
code: fields.code,
|
|
118
|
+
type: message.type,
|
|
119
|
+
});
|
|
120
|
+
return session.send(frame({ type: 'error', ...(id ? { id } : {}), ...fields }));
|
|
98
121
|
}
|
|
99
122
|
if (id)
|
|
100
123
|
await session.send(frame(result === undefined ? { type: 'reply', id } : { type: 'reply', id, data: result }));
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { Logger } from '@dokebi/core';
|
|
2
|
+
import type { WebRealtimeTransport } from '@dokebi/web/points';
|
|
3
|
+
import type { WebsocketApi, WebsocketConnectionInfo, WebsocketKickReceipt, WebsocketPresence, WebsocketReceipt, WebsocketRoute } from './types.js';
|
|
4
|
+
/** Whom a namespace call is about (D-0061): a tenant of the namespace, or all of them. */
|
|
5
|
+
export interface WebsocketNamespaceTarget {
|
|
6
|
+
readonly tenant?: string;
|
|
7
|
+
readonly member?: string;
|
|
8
|
+
readonly room?: string;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* The WebSocket operations on one realtime namespace (the hub tenants `<namespace>:<tenant>`):
|
|
12
|
+
* targets name tenants without the prefix and results come back without it.
|
|
13
|
+
*/
|
|
14
|
+
export interface WebsocketNamespaceHandle {
|
|
15
|
+
readonly namespace: string;
|
|
16
|
+
list(target?: WebsocketNamespaceTarget): Promise<readonly WebsocketConnectionInfo[]>;
|
|
17
|
+
send(target: WebsocketNamespaceTarget, type: string, data?: unknown): Promise<WebsocketReceipt>;
|
|
18
|
+
kick(target: WebsocketNamespaceTarget, code?: number, reason?: string): Promise<WebsocketKickReceipt>;
|
|
19
|
+
onPresence(listener: (change: WebsocketPresence) => unknown): () => void;
|
|
20
|
+
}
|
|
21
|
+
/** The `websocket` transport contributed to `dokebi-web:realtime` (D-0063 §5). */
|
|
22
|
+
export type WebsocketTransport = WebRealtimeTransport<WebsocketRoute, WebsocketNamespaceHandle> & {
|
|
23
|
+
readonly kind: 'websocket';
|
|
24
|
+
};
|
|
25
|
+
/**
|
|
26
|
+
* What dokebi-app needs to mount WebSocket routes of apps and modules and to reach a namespace,
|
|
27
|
+
* built on the public API: `mount` adds the scope's path, constraints, seal rule and tenant rule
|
|
28
|
+
* to a route; `handle` prefixes targets with `<namespace>:` and strips it from results.
|
|
29
|
+
*/
|
|
30
|
+
export declare function websocketTransport(api: WebsocketApi, logger: Logger): WebsocketTransport;
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { WebsocketError } from './errors.js';
|
|
2
|
+
const NAMESPACE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
|
|
3
|
+
function target(value) {
|
|
4
|
+
if (value === null || typeof value !== 'object')
|
|
5
|
+
throw new WebsocketError('INVALID_TARGET', 'A namespace target is { tenant?, member?, room? }.');
|
|
6
|
+
return value;
|
|
7
|
+
}
|
|
8
|
+
/**
|
|
9
|
+
* What dokebi-app needs to mount WebSocket routes of apps and modules and to reach a namespace,
|
|
10
|
+
* built on the public API: `mount` adds the scope's path, constraints, seal rule and tenant rule
|
|
11
|
+
* to a route; `handle` prefixes targets with `<namespace>:` and strips it from results.
|
|
12
|
+
*/
|
|
13
|
+
export function websocketTransport(api, logger) {
|
|
14
|
+
return Object.freeze({
|
|
15
|
+
kind: 'websocket',
|
|
16
|
+
mount(route, scope) {
|
|
17
|
+
if (route === null || typeof route !== 'object' || typeof route.authenticate !== 'function')
|
|
18
|
+
throw new WebsocketError('INVALID_ROUTE', 'Invalid websocket route');
|
|
19
|
+
const own = route.seal;
|
|
20
|
+
const sealed = scope.seal;
|
|
21
|
+
api.route({
|
|
22
|
+
...route,
|
|
23
|
+
path: scope.path,
|
|
24
|
+
constraints: { ...(route.constraints ?? {}), ...scope.constraints },
|
|
25
|
+
// The request's host decides (D-0059 §4) besides the route's own setting.
|
|
26
|
+
...(sealed
|
|
27
|
+
? {
|
|
28
|
+
seal: (request) => sealed(request) || own === true || (typeof own === 'function' && own(request)),
|
|
29
|
+
}
|
|
30
|
+
: {}),
|
|
31
|
+
authenticate: async (request) => {
|
|
32
|
+
const identity = await route.authenticate(request);
|
|
33
|
+
return identity ? scope.identity(identity) : undefined;
|
|
34
|
+
},
|
|
35
|
+
});
|
|
36
|
+
if (logger.isEnabled('debug'))
|
|
37
|
+
logger.log('debug', 'WebSocket route mounted by the realtime point', {
|
|
38
|
+
path: scope.path,
|
|
39
|
+
sealed: sealed !== undefined,
|
|
40
|
+
});
|
|
41
|
+
},
|
|
42
|
+
handle(namespace) {
|
|
43
|
+
if (typeof namespace !== 'string' || !NAMESPACE.test(namespace))
|
|
44
|
+
throw new WebsocketError('INVALID_TARGET', 'A realtime namespace is a name of 1 to 64 characters.');
|
|
45
|
+
const prefix = `${namespace}:`;
|
|
46
|
+
const filter = (input) => {
|
|
47
|
+
const { tenant, member, room } = target(input);
|
|
48
|
+
return {
|
|
49
|
+
...(tenant === undefined ? { tenantPrefix: prefix } : { tenant: prefix + tenant }),
|
|
50
|
+
...(room === undefined ? {} : { room }),
|
|
51
|
+
...(member === undefined ? {} : { member }),
|
|
52
|
+
};
|
|
53
|
+
};
|
|
54
|
+
return Object.freeze({
|
|
55
|
+
namespace,
|
|
56
|
+
list: async (input = {}) => {
|
|
57
|
+
const connections = await api.list(filter(input));
|
|
58
|
+
return Object.freeze(connections.map((connection) => Object.freeze({ ...connection, tenant: connection.tenant.slice(prefix.length) })));
|
|
59
|
+
},
|
|
60
|
+
send: async (input, type, data) => api.send(filter(input), type, data),
|
|
61
|
+
kick: async (input, code, reason) => api.kick(filter(input), code, reason),
|
|
62
|
+
onPresence: (listener) => {
|
|
63
|
+
if (typeof listener !== 'function')
|
|
64
|
+
throw new WebsocketError('INVALID_ARGUMENT', 'Invalid presence listener');
|
|
65
|
+
return api.onPresence((change) => change.tenant.startsWith(prefix)
|
|
66
|
+
? listener(Object.freeze({ ...change, tenant: change.tenant.slice(prefix.length) }))
|
|
67
|
+
: undefined);
|
|
68
|
+
},
|
|
69
|
+
});
|
|
70
|
+
},
|
|
71
|
+
});
|
|
72
|
+
}
|
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 {
|
|
@@ -84,6 +89,15 @@ export interface WebsocketRoute {
|
|
|
84
89
|
* instead of joining with an old protocol.
|
|
85
90
|
*/
|
|
86
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);
|
|
87
101
|
authenticate(request: FastifyRequest): Awaitable<WebsocketIdentity | undefined>;
|
|
88
102
|
authorizeRoom?(identity: WebsocketIdentity, room: string): Awaitable<boolean>;
|
|
89
103
|
message(data: Uint8Array, session: WebsocketSession): Awaitable<void>;
|
|
@@ -93,7 +107,101 @@ export interface WebsocketRoute {
|
|
|
93
107
|
*/
|
|
94
108
|
presence?(change: WebsocketPresence, session: WebsocketSession): Awaitable<void>;
|
|
95
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
|
+
}
|
|
96
137
|
export interface WebsocketApi {
|
|
97
138
|
route(definition: WebsocketRoute): void;
|
|
98
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;
|
|
99
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
|
@@ -3,41 +3,68 @@
|
|
|
3
3
|
"type": "object",
|
|
4
4
|
"additionalProperties": false,
|
|
5
5
|
"properties": {
|
|
6
|
+
"maxPayloadBytes": {
|
|
7
|
+
"type": "integer",
|
|
8
|
+
"minimum": 1,
|
|
9
|
+
"maximum": 67108864,
|
|
10
|
+
"default": 65536,
|
|
11
|
+
"description": "Largest incoming frame in bytes."
|
|
12
|
+
},
|
|
6
13
|
"maxPayload": {
|
|
7
14
|
"type": "integer",
|
|
8
15
|
"minimum": 1,
|
|
9
16
|
"maximum": 67108864,
|
|
10
|
-
"
|
|
17
|
+
"deprecated": true,
|
|
18
|
+
"description": "Deprecated name of maxPayloadBytes; use that key."
|
|
11
19
|
},
|
|
12
20
|
"maxConnections": {
|
|
13
21
|
"type": "integer",
|
|
14
22
|
"minimum": 1,
|
|
15
23
|
"maximum": 67108864,
|
|
16
|
-
"default": 128
|
|
24
|
+
"default": 128,
|
|
25
|
+
"description": "Open connections this process accepts at most."
|
|
26
|
+
},
|
|
27
|
+
"maxPending": {
|
|
28
|
+
"type": "integer",
|
|
29
|
+
"minimum": 1,
|
|
30
|
+
"maximum": 67108864,
|
|
31
|
+
"default": 32,
|
|
32
|
+
"description": "Messages of one connection waiting for its handler at most."
|
|
17
33
|
},
|
|
18
34
|
"maxPendingMessages": {
|
|
19
35
|
"type": "integer",
|
|
20
36
|
"minimum": 1,
|
|
21
37
|
"maximum": 67108864,
|
|
22
|
-
"
|
|
38
|
+
"deprecated": true,
|
|
39
|
+
"description": "Deprecated name of maxPending; use that key."
|
|
23
40
|
},
|
|
24
41
|
"maxBufferedBytes": {
|
|
25
42
|
"type": "integer",
|
|
26
43
|
"minimum": 1,
|
|
27
44
|
"maximum": 67108864,
|
|
28
|
-
"default": 1048576
|
|
45
|
+
"default": 1048576,
|
|
46
|
+
"description": "Bytes waiting to be sent to one connection at most; a slower client is closed (SLOW_CONSUMER)."
|
|
47
|
+
},
|
|
48
|
+
"shutdownTimeoutMs": {
|
|
49
|
+
"type": "integer",
|
|
50
|
+
"minimum": 1,
|
|
51
|
+
"maximum": 67108864,
|
|
52
|
+
"default": 2000,
|
|
53
|
+
"description": "How long drain waits for closing connections (1012) before it cuts them, in ms."
|
|
29
54
|
},
|
|
30
55
|
"closeTimeoutMs": {
|
|
31
56
|
"type": "integer",
|
|
32
57
|
"minimum": 1,
|
|
33
58
|
"maximum": 67108864,
|
|
34
|
-
"
|
|
59
|
+
"deprecated": true,
|
|
60
|
+
"description": "Deprecated name of shutdownTimeoutMs; use that key."
|
|
35
61
|
},
|
|
36
62
|
"heartbeatMs": {
|
|
37
63
|
"type": "integer",
|
|
38
64
|
"minimum": 1,
|
|
39
65
|
"maximum": 67108864,
|
|
40
|
-
"default": 10000
|
|
66
|
+
"default": 10000,
|
|
67
|
+
"description": "Interval of WebSocket pings, in ms."
|
|
41
68
|
},
|
|
42
69
|
"idleTimeoutMs": {
|
|
43
70
|
"type": "integer",
|
|
@@ -52,6 +79,13 @@
|
|
|
52
79
|
"maximum": 67108864,
|
|
53
80
|
"default": 5000,
|
|
54
81
|
"description": "How long an upgrade waits for a reconnecting hub (leader change, rolling restart) before 503 HUB_RECOVERING; 0 refuses at once."
|
|
82
|
+
},
|
|
83
|
+
"sealDriftMs": {
|
|
84
|
+
"type": "integer",
|
|
85
|
+
"minimum": 1000,
|
|
86
|
+
"maximum": 600000,
|
|
87
|
+
"default": 60000,
|
|
88
|
+
"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
89
|
}
|
|
56
90
|
}
|
|
57
91
|
}
|