@dokebi/websocket-hub 0.0.0-stage → 0.1.1

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.
@@ -0,0 +1,95 @@
1
+ #!/usr/bin/env node
2
+ // `dokebi-hub-status` — "how is the hub right now?" asked from outside every application process
3
+ // (D-0038 · original `x hubserver:status`). It reads the leader record and the owner records from
4
+ // Redis only; it does not start a hub, register anything or join the election.
5
+ import { resolve } from 'node:path';
6
+ import { parseArgs } from 'node:util';
7
+ import { Application, ConsoleLogger, loadConfig } from '@dokebi/core';
8
+ import { createPlugin as createRedis } from '@dokebi/redis';
9
+ import { parseOptions } from './options.js';
10
+ import { hubStatus } from './status.js';
11
+ import { HubStore } from './store.js';
12
+ const help = `Usage: dokebi-hub-status [options]
13
+
14
+ --config PATH YAML file (default: dokebi.yaml)
15
+ --json Emit the status as JSON
16
+ --help Show this help
17
+
18
+ Reads the hub's leader record and owner records from Redis (cluster mode) and says who leads,
19
+ how long the lease has left, and how many servers and connections are live. A local-mode hub
20
+ lives inside one process and has no state to read from outside.
21
+ `;
22
+ function describe(status) {
23
+ if (status.mode === 'local')
24
+ return 'Local hub: its state lives inside the application process (use hub.status() there).\n';
25
+ if (status.leaseState === 'unreachable')
26
+ return [
27
+ 'Hub leader: unknown — Redis did not answer.',
28
+ ' Check the dokebi-redis connection named by redisConnection and that the server is up.',
29
+ '',
30
+ ].join('\n');
31
+ const lines = [];
32
+ if (status.leaseState === 'none')
33
+ lines.push('Hub leader: none — no server holds the lease (failover in progress, or no server started).');
34
+ else if (status.leader)
35
+ lines.push(`Hub leader: ${status.leader.serverId} at ${status.leader.address}` +
36
+ (status.leaseRemainingMs === undefined
37
+ ? ''
38
+ : ` (lease ${(status.leaseRemainingMs / 1000).toFixed(1)}s left)`));
39
+ lines.push(` Live servers : ${status.servers}`, ` Live connections : ${status.connections}`, '');
40
+ return lines.join('\n');
41
+ }
42
+ async function main() {
43
+ const { values } = parseArgs({
44
+ options: {
45
+ config: { type: 'string' },
46
+ json: { type: 'boolean', default: false },
47
+ help: { type: 'boolean', default: false },
48
+ },
49
+ strict: true,
50
+ allowPositionals: false,
51
+ });
52
+ if (values.help) {
53
+ process.stdout.write(help);
54
+ return;
55
+ }
56
+ const document = await loadConfig(resolve(values.config ?? 'dokebi.yaml'));
57
+ const options = parseOptions(document.options['dokebi-websocket-hub'] ?? {});
58
+ let status;
59
+ if (options.mode === 'local')
60
+ status = hubStatus({ mode: 'local', state: 'closed', role: 'standby' });
61
+ else {
62
+ // Only the Redis plugin: the connection settings (TLS, auth) are the application's own.
63
+ const app = new Application({
64
+ logger: new ConsoleLogger({ level: 'silent' }),
65
+ config: { 'dokebi-redis': document.options['dokebi-redis'] },
66
+ });
67
+ const redis = createRedis({ app: app.view });
68
+ app.register(redis);
69
+ let lease;
70
+ try {
71
+ await app.start();
72
+ lease = await new HubStore(app.get(redis).connection(options.redisConnection), options).inspect();
73
+ }
74
+ catch {
75
+ lease = 'unreachable';
76
+ }
77
+ finally {
78
+ await app.stop().catch(() => { });
79
+ }
80
+ // This process is not a hub: state/role describe the asker, so they are left neutral.
81
+ status = hubStatus({ mode: 'cluster', state: 'closed', role: 'standby', lease });
82
+ }
83
+ if (values.json) {
84
+ const { state: _state, role: _role, ...outside } = status;
85
+ process.stdout.write(`${JSON.stringify(outside, null, 2)}\n`);
86
+ }
87
+ else
88
+ process.stdout.write(describe(status));
89
+ if (status.leaseState === 'unreachable')
90
+ process.exitCode = 1;
91
+ }
92
+ await main().catch((error) => {
93
+ process.stderr.write(`${error instanceof Error ? error.message : String(error)}\n`);
94
+ process.exitCode = 1;
95
+ });
@@ -0,0 +1,22 @@
1
+ import type { HubApi, HubLease, HubStatus } from './types.js';
2
+ /**
3
+ * The one place that turns facts into a status (D-0038 · original x-hubserver `hubStatus`).
4
+ * `HubApi.status()` and `dokebi-hub-status` both call it, so a health check, a dashboard and the
5
+ * CLI cannot give different answers. Nothing unknown is filled with 0.
6
+ */
7
+ export declare function hubStatus(input: {
8
+ mode: 'local' | 'cluster';
9
+ state: HubApi['state'];
10
+ role: HubApi['role'];
11
+ serverId?: string;
12
+ /** cluster only: what Redis said, or `unreachable` when it did not answer. */
13
+ lease?: HubLease | 'unreachable';
14
+ }): HubStatus;
15
+ /** In-process nonce store for local mode: correct for one process only (`shared: false`). */
16
+ export declare class LocalNonceStore {
17
+ #private;
18
+ readonly max: number;
19
+ readonly shared = false;
20
+ constructor(max?: number);
21
+ setIfNotExists(key: string, ttlSeconds: number): Promise<boolean>;
22
+ }
package/dist/status.js ADDED
@@ -0,0 +1,62 @@
1
+ /**
2
+ * The one place that turns facts into a status (D-0038 · original x-hubserver `hubStatus`).
3
+ * `HubApi.status()` and `dokebi-hub-status` both call it, so a health check, a dashboard and the
4
+ * CLI cannot give different answers. Nothing unknown is filled with 0.
5
+ */
6
+ export function hubStatus(input) {
7
+ const base = {
8
+ mode: input.mode,
9
+ state: input.state,
10
+ role: input.role,
11
+ ...(input.serverId === undefined ? {} : { serverId: input.serverId }),
12
+ };
13
+ if (input.mode === 'local' || input.lease === undefined)
14
+ return Object.freeze(base);
15
+ if (input.lease === 'unreachable')
16
+ return Object.freeze({ ...base, leaseState: 'unreachable' });
17
+ const lease = input.lease;
18
+ return Object.freeze({
19
+ ...base,
20
+ leaseState: lease.leader ? 'leader' : 'none',
21
+ ...(lease.leader
22
+ ? {
23
+ leader: Object.freeze({
24
+ serverId: lease.leader.serverId,
25
+ address: `${lease.leader.host}:${lease.leader.port}`,
26
+ epoch: lease.leader.epoch,
27
+ }),
28
+ ...(lease.remainingMs === undefined ? {} : { leaseRemainingMs: lease.remainingMs }),
29
+ }
30
+ : {}),
31
+ servers: lease.servers,
32
+ connections: lease.connections,
33
+ });
34
+ }
35
+ /** In-process nonce store for local mode: correct for one process only (`shared: false`). */
36
+ export class LocalNonceStore {
37
+ max;
38
+ shared = false;
39
+ #entries = new Map();
40
+ #inserts = 0;
41
+ constructor(max = 100_000) {
42
+ this.max = max;
43
+ }
44
+ async setIfNotExists(key, ttlSeconds) {
45
+ const now = Date.now();
46
+ const existing = this.#entries.get(key);
47
+ if (existing !== undefined && existing > now)
48
+ return false;
49
+ this.#entries.set(key, now + ttlSeconds * 1000);
50
+ if (++this.#inserts % 500 === 0)
51
+ for (const [entry, expires] of this.#entries)
52
+ if (expires <= now)
53
+ this.#entries.delete(entry);
54
+ // Beyond the cap the oldest go first: a thinner defence beats running out of memory.
55
+ for (const entry of this.#entries.keys()) {
56
+ if (this.#entries.size <= this.max)
57
+ break;
58
+ this.#entries.delete(entry);
59
+ }
60
+ return true;
61
+ }
62
+ }
@@ -0,0 +1,35 @@
1
+ import type { RedisConnection } from '@dokebi/redis';
2
+ import type { HubOptions } from './options.js';
3
+ import { type HubLeader, type HubLease, type HubRecord } from './types.js';
4
+ export interface Owner {
5
+ serverId: string;
6
+ session: string;
7
+ expires: number;
8
+ connections: readonly HubRecord[];
9
+ }
10
+ export declare class HubStore {
11
+ #private;
12
+ readonly redis: RedisConnection;
13
+ readonly options: HubOptions;
14
+ readonly keys: readonly string[];
15
+ readonly fingerprint: string;
16
+ constructor(redis: RedisConnection, options: HubOptions);
17
+ run(op: string, token?: string, arg3?: string, arg4?: string, arg5?: string): Promise<unknown>;
18
+ /**
19
+ * What Redis says about the hub right now, in one round trip (D-0038): the leader record and
20
+ * its remaining lease, and the servers and connections of owners whose records are still live.
21
+ */
22
+ inspect(): Promise<HubLease>;
23
+ /**
24
+ * One-time replay nonce shared by every server of this namespace (D-0038): `SET NX PX`, so the
25
+ * first server to see a nonce wins and every other one is told it was used.
26
+ */
27
+ claimNonce(key: string, ttlSeconds: number): Promise<boolean>;
28
+ discover(): Promise<HubLeader | undefined>;
29
+ elect(leader: HubLeader): Promise<HubLeader>;
30
+ snapshot(leaderEpoch: string): Promise<{
31
+ revision: number;
32
+ owners: Map<string, Owner>;
33
+ now: number;
34
+ }>;
35
+ }
package/dist/store.js ADDED
@@ -0,0 +1,212 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { epoch, identifier, records, sequence } from './protocol.js';
3
+ import { HubError } from './types.js';
4
+ // One hash slot, Redis time, and leader-token checks fence every authoritative mutation.
5
+ const script = `
6
+ local op=ARGV[1]
7
+ local t=redis.call('TIME');local now=tonumber(t[1])*1000+math.floor(tonumber(t[2])/1000)
8
+ local leader=redis.call('GET',KEYS[1])
9
+ if op=='elect' or op=='discover' then
10
+ local fingerprint=redis.call('GET',KEYS[4])
11
+ if fingerprint and fingerprint~=ARGV[5] then
12
+ -- A different configuration is refused only while servers of the old one are alive.
13
+ local alive=leader and true or false
14
+ if not alive then
15
+ for _,v in ipairs(redis.call('HVALS',KEYS[2])) do
16
+ if tonumber(cjson.decode(v).expires)>now then alive=true;break end
17
+ end
18
+ end
19
+ if alive then return {'hub-error','CONFIG_MISMATCH'} end
20
+ redis.call('DEL',KEYS[4])
21
+ end
22
+ end
23
+ if op=='elect' then
24
+ if not leader then redis.call('SET',KEYS[4],ARGV[5]);redis.call('SET',KEYS[1],ARGV[2],'PX',ARGV[3]);leader=ARGV[2] end
25
+ return leader
26
+ end
27
+ if op=='discover' then return leader or '' end
28
+ -- Read-only facts for status (D-0038): the lease, its remaining time and every owner record.
29
+ if op=='inspect' then return {leader or '',redis.call('PTTL',KEYS[1]),redis.call('HVALS',KEYS[2]),now} end
30
+ -- An owner leaving on shutdown removes only its own record of the same session; no leader is
31
+ -- needed, so a full cluster stop does not leave records until ownerTtlMs.
32
+ if op=='leave' then
33
+ local saved=redis.call('HGET',KEYS[2],ARGV[5])
34
+ if not saved or cjson.decode(saved).session~=ARGV[4] then return 0 end
35
+ redis.call('HDEL',KEYS[2],ARGV[5]);return redis.call('INCR',KEYS[3])
36
+ end
37
+ if not leader or cjson.decode(leader).epoch~=ARGV[2] then return {'hub-error','STALE_LEADER'} end
38
+ if op=='deliveries' or op=='put-delivery' or op=='finish-delivery' then
39
+ local expired=redis.call('ZRANGEBYSCORE',KEYS[6],'-inf',now,'LIMIT',0,256)
40
+ for _,id in ipairs(expired) do
41
+ local old=redis.call('HGET',KEYS[5],id)
42
+ if old then redis.call('DECRBY',KEYS[7],string.len(old));redis.call('HDEL',KEYS[5],id) end
43
+ redis.call('ZREM',KEYS[6],id)
44
+ end
45
+ if op=='deliveries' then return redis.call('HVALS',KEYS[5]) end
46
+ local value=cjson.decode(ARGV[4]);local old=redis.call('HGET',KEYS[5],ARGV[5])
47
+ if op=='put-delivery' then
48
+ if old then
49
+ local saved=cjson.decode(old)
50
+ if saved.digest~=value.digest or saved.producer~=value.producer then return {'hub-error','ID_CONFLICT'} end
51
+ return old
52
+ end
53
+ local limits=cjson.decode(ARGV[3])
54
+ if value.expiresAt<=now or value.expiresAt>now+limits.timeout+5000 then return {'hub-error','DELIVERY_TIMEOUT'} end
55
+ if redis.call('HLEN',KEYS[5])>=limits.count or tonumber(redis.call('GET',KEYS[7]) or '0')+string.len(ARGV[4])>limits.bytes then return {'hub-error','OUTBOX_FULL'} end
56
+ else
57
+ if not old then return {'hub-error','DELIVERY_TIMEOUT'} end
58
+ if value.status=='done' and value.expiresAt<=now then return {'hub-error','DELIVERY_TIMEOUT'} end
59
+ end
60
+ redis.call('HSET',KEYS[5],ARGV[5],ARGV[4]);redis.call('ZADD',KEYS[6],value.expiresAt+60000,ARGV[5])
61
+ redis.call('INCRBY',KEYS[7],string.len(ARGV[4])-(old and string.len(old) or 0))
62
+ return ARGV[4]
63
+ end
64
+ if op=='renew' then redis.call('PEXPIRE',KEYS[1],ARGV[3]);return now end
65
+ if op=='release' then redis.call('DEL',KEYS[1]);return now end
66
+ if op=='snapshot' then return {redis.call('GET',KEYS[3]) or '0',redis.call('HGETALL',KEYS[2]),now} end
67
+ if op=='save' then
68
+ local value=cjson.decode(ARGV[4]);value.expires=now+tonumber(ARGV[3]);redis.call('HSET',KEYS[2],ARGV[5],cjson.encode(value));return {redis.call('INCR',KEYS[3]),value.expires}
69
+ end
70
+ if op=='touch' then
71
+ local saved=redis.call('HGET',KEYS[2],ARGV[5]);if not saved then return {'hub-error','OWNER_EXPIRED'} end
72
+ local value=cjson.decode(saved);if value.session~=ARGV[4] then return {'hub-error','STALE_PEER'} end
73
+ value.expires=now+tonumber(ARGV[3]);redis.call('HSET',KEYS[2],ARGV[5],cjson.encode(value));return value.expires
74
+ end
75
+ if op=='remove' then
76
+ local saved=redis.call('HGET',KEYS[2],ARGV[5]);if not saved then return 0 end
77
+ if cjson.decode(saved).session~=ARGV[4] then return 0 end
78
+ redis.call('HDEL',KEYS[2],ARGV[5]);return redis.call('INCR',KEYS[3])
79
+ end
80
+ return {'hub-error','INVALID_OPERATION'}
81
+ `;
82
+ export class HubStore {
83
+ redis;
84
+ options;
85
+ keys;
86
+ fingerprint;
87
+ // Loaded once per store: calls send the SHA1 and fall back to EVAL only on NOSCRIPT.
88
+ #script;
89
+ #prefix;
90
+ constructor(redis, options) {
91
+ this.redis = redis;
92
+ this.options = options;
93
+ this.#script = redis.script(script);
94
+ const hash = createHash('sha256').update(options.namespace).digest('hex');
95
+ const prefix = `dokebi:websocket-hub:{${hash}}`;
96
+ this.#prefix = prefix;
97
+ this.keys = [
98
+ 'leader',
99
+ 'owners',
100
+ 'revision',
101
+ 'config',
102
+ 'deliveries',
103
+ 'delivery-expiry',
104
+ 'delivery-bytes',
105
+ ].map((x) => `${prefix}:${x}`);
106
+ this.fingerprint = createHash('sha256')
107
+ .update(JSON.stringify([
108
+ 'delivery-ack-v1',
109
+ options.secret,
110
+ options.leaseMs,
111
+ options.ownerTtlMs,
112
+ options.maxConnections,
113
+ options.maxOwners,
114
+ options.maxTotalConnections,
115
+ options.maxFrameBytes,
116
+ options.maxPayloadBytes,
117
+ options.deliveryTimeoutMs,
118
+ options.maxDeliveries,
119
+ options.deliveryBytes,
120
+ ]))
121
+ .digest('hex');
122
+ }
123
+ async run(op, token = '', arg3 = '', arg4 = '', arg5 = '') {
124
+ try {
125
+ const result = await this.#script.run({
126
+ keys: this.keys,
127
+ arguments: [op, token, arg3, arg4, arg5],
128
+ });
129
+ if (Array.isArray(result) && result[0] === 'hub-error' && typeof result[1] === 'string')
130
+ throw new HubError(result[1]);
131
+ return result;
132
+ }
133
+ catch (error) {
134
+ if (error instanceof HubError)
135
+ throw error;
136
+ throw new HubError('STORE_UNAVAILABLE');
137
+ }
138
+ }
139
+ /**
140
+ * What Redis says about the hub right now, in one round trip (D-0038): the leader record and
141
+ * its remaining lease, and the servers and connections of owners whose records are still live.
142
+ */
143
+ async inspect() {
144
+ const result = (await this.run('inspect'));
145
+ const [leader, remaining, owners, now] = result;
146
+ const servers = new Set();
147
+ let connections = 0;
148
+ for (const value of Array.isArray(owners) ? owners : []) {
149
+ const owner = JSON.parse(String(value));
150
+ if (typeof owner.expires !== 'number' || owner.expires <= Number(now))
151
+ continue;
152
+ if (typeof owner.serverId === 'string')
153
+ servers.add(owner.serverId);
154
+ // Saved records carry the connection list as a JSON string (see 'save'), like snapshot reads it.
155
+ const list = typeof owner.connections === 'string' ? JSON.parse(owner.connections) : owner.connections;
156
+ connections += Array.isArray(list) ? list.length : 0;
157
+ }
158
+ const record = typeof leader === 'string' && leader !== '' ? JSON.parse(leader) : undefined;
159
+ return {
160
+ ...(record ? { leader: record, remainingMs: Math.max(0, Number(remaining)) } : {}),
161
+ servers: servers.size,
162
+ connections,
163
+ };
164
+ }
165
+ /**
166
+ * One-time replay nonce shared by every server of this namespace (D-0038): `SET NX PX`, so the
167
+ * first server to see a nonce wins and every other one is told it was used.
168
+ */
169
+ async claimNonce(key, ttlSeconds) {
170
+ try {
171
+ return await this.redis.set(`${this.#prefix}:nonce:${key}`, '1', {
172
+ NX: true,
173
+ PX: Math.max(1, ttlSeconds) * 1000,
174
+ });
175
+ }
176
+ catch {
177
+ throw new HubError('STORE_UNAVAILABLE');
178
+ }
179
+ }
180
+ async discover() {
181
+ const v = await this.run('discover', '', '', '', this.fingerprint);
182
+ return v ? Object.freeze(JSON.parse(String(v))) : undefined;
183
+ }
184
+ async elect(leader) {
185
+ return Object.freeze(JSON.parse(String(await this.run('elect', JSON.stringify(leader), String(this.options.leaseMs), '', this.fingerprint))));
186
+ }
187
+ async snapshot(leaderEpoch) {
188
+ const result = (await this.run('snapshot', leaderEpoch));
189
+ const owners = new Map();
190
+ for (let i = 0; i < result[1].length; i += 2) {
191
+ const key = result[1][i], value = result[1][i + 1];
192
+ if (key === undefined || value === undefined)
193
+ throw new HubError('CHECKPOINT_INVALID');
194
+ const owner = JSON.parse(value);
195
+ if (typeof owner.connections === 'string')
196
+ owner.connections = JSON.parse(owner.connections);
197
+ if (!Array.isArray(owner.connections))
198
+ throw new HubError('CHECKPOINT_INVALID');
199
+ epoch(key);
200
+ identifier(owner.serverId);
201
+ epoch(owner.session);
202
+ sequence(owner.expires);
203
+ owner.connections = records(owner.connections, key, this.options.maxConnections);
204
+ owners.set(key, owner);
205
+ }
206
+ if (owners.size > this.options.maxOwners ||
207
+ [...owners.values()].reduce((sum, owner) => sum + owner.connections.length, 0) >
208
+ this.options.maxTotalConnections)
209
+ throw new HubError('CHECKPOINT_INVALID');
210
+ return { revision: sequence(Number(result[0])), owners, now: sequence(result[2]) };
211
+ }
212
+ }
@@ -0,0 +1,125 @@
1
+ export declare class HubError extends Error {
2
+ readonly code: string;
3
+ constructor(code: string);
4
+ }
5
+ export interface HubRegistration {
6
+ readonly tenant: string;
7
+ readonly member: string;
8
+ readonly connection: string;
9
+ readonly clientId?: string;
10
+ readonly rooms?: readonly string[];
11
+ readonly metadata?: Readonly<Record<string, string>>;
12
+ }
13
+ export interface HubRecord extends HubRegistration {
14
+ readonly ownerEpoch: string;
15
+ readonly rooms: readonly string[];
16
+ readonly metadata: Readonly<Record<string, string>>;
17
+ }
18
+ export interface HubQuery {
19
+ readonly tenant: string;
20
+ readonly room?: string;
21
+ readonly member?: string;
22
+ readonly connection?: {
23
+ readonly ownerEpoch: string;
24
+ readonly connection: string;
25
+ };
26
+ }
27
+ export interface HubLeader {
28
+ readonly epoch: string;
29
+ readonly host: string;
30
+ readonly port: number;
31
+ readonly serverId: string;
32
+ }
33
+ export interface HubSnapshot {
34
+ readonly authorityEpoch: string;
35
+ readonly revision: number;
36
+ readonly connections: readonly HubRecord[];
37
+ }
38
+ export interface HubReceipt {
39
+ readonly recipients?: readonly string[];
40
+ readonly authorityEpoch: string;
41
+ readonly id: string;
42
+ }
43
+ export type HubEvent = {
44
+ readonly kind: 'message';
45
+ readonly id: string;
46
+ readonly connections: readonly string[];
47
+ readonly data: Uint8Array;
48
+ readonly expiresAt: number;
49
+ } | {
50
+ readonly kind: 'kick';
51
+ readonly id: string;
52
+ readonly connections: readonly string[];
53
+ readonly code: number;
54
+ readonly reason: string;
55
+ } | {
56
+ readonly kind: 'presence';
57
+ readonly revision: number;
58
+ readonly ownerEpoch: string;
59
+ readonly connections: readonly HubRecord[];
60
+ };
61
+ export interface HubConnection {
62
+ readonly identity: {
63
+ readonly ownerEpoch: string;
64
+ readonly connection: string;
65
+ };
66
+ join(room: string): Promise<void>;
67
+ leave(room: string): Promise<void>;
68
+ updateMetadata(value: Readonly<Record<string, string>>): Promise<void>;
69
+ close(): Promise<void>;
70
+ }
71
+ /** What Redis says about the hub (D-0038). `leader` is absent when nobody holds the lease. */
72
+ export interface HubLease {
73
+ readonly leader?: HubLeader;
74
+ readonly remainingMs?: number;
75
+ /** Servers and connections of owner records that are still live. */
76
+ readonly servers: number;
77
+ readonly connections: number;
78
+ }
79
+ /**
80
+ * Operational status (D-0038). A value this process cannot know is left out, never filled with
81
+ * 0 — "0 connections" and "unknown" lead to different actions.
82
+ */
83
+ export interface HubStatus {
84
+ readonly mode: 'local' | 'cluster';
85
+ readonly state: HubApi['state'];
86
+ readonly role: HubApi['role'];
87
+ readonly serverId?: string;
88
+ /** cluster: `leader` (someone holds the lease) · `none` (failover or nobody started) · `unreachable` (Redis did not answer). */
89
+ readonly leaseState?: 'leader' | 'none' | 'unreachable';
90
+ readonly leader?: {
91
+ readonly serverId: string;
92
+ readonly address: string;
93
+ readonly epoch: string;
94
+ };
95
+ readonly leaseRemainingMs?: number;
96
+ readonly servers?: number;
97
+ readonly connections?: number;
98
+ }
99
+ /** One-time nonce store for sealed frames (structurally the @dokebi/crypto NonceStore · D-0038). */
100
+ export interface HubNonceStore {
101
+ setIfNotExists(key: string, ttlSeconds: number): Promise<boolean>;
102
+ /** true only when every server of the namespace shares it (cluster mode). */
103
+ readonly shared: boolean;
104
+ }
105
+ export interface HubApi {
106
+ readonly state: 'starting' | 'ready' | 'recovering' | 'closing' | 'closed';
107
+ readonly role: 'active' | 'standby';
108
+ readonly ownerEpoch: string;
109
+ readonly leader: HubLeader | undefined;
110
+ register(value: HubRegistration): Promise<HubConnection>;
111
+ list(query: HubQuery): Promise<HubSnapshot>;
112
+ broadcast(query: HubQuery, data: Uint8Array): Promise<HubReceipt>;
113
+ acknowledge(id: string, connections: readonly string[]): void;
114
+ kick(query: HubQuery, code?: number, reason?: string): Promise<HubReceipt>;
115
+ events(): AsyncIterableIterator<HubEvent>;
116
+ /**
117
+ * Resolves true once the hub is ready (now, or after a reconnect such as a leader change),
118
+ * false after `timeoutMs` or when it closes. Lets callers ride out a short recovery.
119
+ */
120
+ whenReady(timeoutMs: number): Promise<boolean>;
121
+ /** Operational status (D-0038): this process plus what Redis says about the hub. */
122
+ status(): Promise<HubStatus>;
123
+ /** Replay nonce store for sealed frames (D-0038): Redis in cluster mode, this process in local mode. */
124
+ nonces(): HubNonceStore;
125
+ }
package/dist/types.js ADDED
@@ -0,0 +1,8 @@
1
+ export class HubError extends Error {
2
+ code;
3
+ constructor(code) {
4
+ super(`WebSocket hub: ${code}`);
5
+ this.code = code;
6
+ this.name = 'HubError';
7
+ }
8
+ }
package/dist/wire.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ import type { Socket } from 'node:net';
2
+ export declare class Wire {
3
+ #private;
4
+ readonly socket: Socket;
5
+ readonly limit: number;
6
+ readonly queueBytes: number;
7
+ constructor(socket: Socket, limit: number, queueBytes: number, onFrame: (frame: Record<string, unknown>) => void, onClose: () => void);
8
+ send(value: unknown): void;
9
+ close(): void;
10
+ }
package/dist/wire.js ADDED
@@ -0,0 +1,62 @@
1
+ import { decode, encode } from './protocol.js';
2
+ import { HubError } from './types.js';
3
+ export class Wire {
4
+ socket;
5
+ limit;
6
+ queueBytes;
7
+ #chunks = [];
8
+ #bytes = 0;
9
+ #closed = false;
10
+ constructor(socket, limit, queueBytes, onFrame, onClose) {
11
+ this.socket = socket;
12
+ this.limit = limit;
13
+ this.queueBytes = queueBytes;
14
+ socket.setNoDelay(true);
15
+ socket.on('error', () => { });
16
+ socket.on('data', (data) => {
17
+ try {
18
+ let start = 0;
19
+ for (let i = 0; i < data.length; i++) {
20
+ if (data[i] !== 10)
21
+ continue;
22
+ this.#append(data.subarray(start, i));
23
+ const frame = Buffer.concat(this.#chunks, this.#bytes);
24
+ this.#chunks = [];
25
+ this.#bytes = 0;
26
+ start = i + 1;
27
+ if (frame.length)
28
+ onFrame(decode(frame, limit));
29
+ }
30
+ this.#append(data.subarray(start));
31
+ }
32
+ catch {
33
+ socket.destroy();
34
+ }
35
+ });
36
+ socket.once('close', () => {
37
+ this.#closed = true;
38
+ onClose();
39
+ });
40
+ }
41
+ #append(chunk) {
42
+ if (!chunk.length)
43
+ return;
44
+ if (this.#bytes + chunk.length > this.limit)
45
+ throw new HubError('FRAME_LIMIT');
46
+ this.#chunks.push(Buffer.from(chunk));
47
+ this.#bytes += chunk.length;
48
+ }
49
+ send(value) {
50
+ if (this.#closed || this.socket.destroyed)
51
+ throw new HubError('DISCONNECTED');
52
+ const frame = Buffer.concat([encode(value, this.limit), Buffer.from('\n')]);
53
+ if (this.socket.writableLength + frame.length > this.queueBytes) {
54
+ this.socket.destroy();
55
+ throw new HubError('BACKPRESSURE');
56
+ }
57
+ this.socket.write(frame);
58
+ }
59
+ close() {
60
+ this.socket.destroy();
61
+ }
62
+ }