@dokebi/websocket-hub 0.0.0-stage → 0.2.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 +76 -0
- package/LICENSE +21 -0
- package/README.md +101 -2
- package/dist/delivery.d.ts +51 -0
- package/dist/delivery.js +196 -0
- package/dist/event-queue.d.ts +12 -0
- package/dist/event-queue.js +66 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +66 -0
- package/dist/install.d.ts +11 -0
- package/dist/install.js +12 -0
- package/dist/leader.d.ts +16 -0
- package/dist/leader.js +331 -0
- package/dist/local.d.ts +20 -0
- package/dist/local.js +243 -0
- package/dist/node.d.ts +23 -0
- package/dist/node.js +294 -0
- package/dist/options.d.ts +35 -0
- package/dist/options.js +122 -0
- package/dist/peer-client.d.ts +24 -0
- package/dist/peer-client.js +489 -0
- package/dist/protocol.d.ts +13 -0
- package/dist/protocol.js +141 -0
- package/dist/status-cli.d.ts +2 -0
- package/dist/status-cli.js +95 -0
- package/dist/status.d.ts +22 -0
- package/dist/status.js +62 -0
- package/dist/store.d.ts +35 -0
- package/dist/store.js +180 -0
- package/dist/types.d.ts +125 -0
- package/dist/types.js +8 -0
- package/dist/wire.d.ts +10 -0
- package/dist/wire.js +62 -0
- package/options.schema.json +170 -0
- package/package.json +64 -4
|
@@ -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
|
+
});
|
package/dist/status.d.ts
ADDED
|
@@ -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
|
+
}
|
package/dist/store.d.ts
ADDED
|
@@ -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,180 @@
|
|
|
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=='renew' then redis.call('PEXPIRE',KEYS[1],ARGV[3]);return now end
|
|
39
|
+
if op=='release' then redis.call('DEL',KEYS[1]);return now end
|
|
40
|
+
if op=='snapshot' then return {redis.call('GET',KEYS[3]) or '0',redis.call('HGETALL',KEYS[2]),now} end
|
|
41
|
+
if op=='save' then
|
|
42
|
+
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}
|
|
43
|
+
end
|
|
44
|
+
if op=='touch' then
|
|
45
|
+
local saved=redis.call('HGET',KEYS[2],ARGV[5]);if not saved then return {'hub-error','OWNER_EXPIRED'} end
|
|
46
|
+
local value=cjson.decode(saved);if value.session~=ARGV[4] then return {'hub-error','STALE_PEER'} end
|
|
47
|
+
value.expires=now+tonumber(ARGV[3]);redis.call('HSET',KEYS[2],ARGV[5],cjson.encode(value));return value.expires
|
|
48
|
+
end
|
|
49
|
+
if op=='remove' then
|
|
50
|
+
local saved=redis.call('HGET',KEYS[2],ARGV[5]);if not saved then return 0 end
|
|
51
|
+
if cjson.decode(saved).session~=ARGV[4] then return 0 end
|
|
52
|
+
redis.call('HDEL',KEYS[2],ARGV[5]);return redis.call('INCR',KEYS[3])
|
|
53
|
+
end
|
|
54
|
+
return {'hub-error','INVALID_OPERATION'}
|
|
55
|
+
`;
|
|
56
|
+
export class HubStore {
|
|
57
|
+
redis;
|
|
58
|
+
options;
|
|
59
|
+
keys;
|
|
60
|
+
fingerprint;
|
|
61
|
+
// Loaded once per store: calls send the SHA1 and fall back to EVAL only on NOSCRIPT.
|
|
62
|
+
#script;
|
|
63
|
+
#prefix;
|
|
64
|
+
constructor(redis, options) {
|
|
65
|
+
this.redis = redis;
|
|
66
|
+
this.options = options;
|
|
67
|
+
this.#script = redis.script(script);
|
|
68
|
+
const hash = createHash('sha256').update(options.namespace).digest('hex');
|
|
69
|
+
const prefix = `dokebi:websocket-hub:{${hash}}`;
|
|
70
|
+
this.#prefix = prefix;
|
|
71
|
+
this.keys = ['leader', 'owners', 'revision', 'config'].map((x) => `${prefix}:${x}`);
|
|
72
|
+
this.fingerprint = createHash('sha256')
|
|
73
|
+
.update(JSON.stringify([
|
|
74
|
+
// D-0042: broadcasts live in leader memory; servers of the Redis-outbox version must
|
|
75
|
+
// not share a namespace with this one.
|
|
76
|
+
'delivery-memory-v2',
|
|
77
|
+
options.secret,
|
|
78
|
+
options.leaseMs,
|
|
79
|
+
options.ownerTtlMs,
|
|
80
|
+
options.maxConnections,
|
|
81
|
+
options.maxOwners,
|
|
82
|
+
options.maxTotalConnections,
|
|
83
|
+
options.maxFrameBytes,
|
|
84
|
+
options.maxPayloadBytes,
|
|
85
|
+
options.deliveryTimeoutMs,
|
|
86
|
+
options.maxDeliveries,
|
|
87
|
+
options.deliveryBytes,
|
|
88
|
+
]))
|
|
89
|
+
.digest('hex');
|
|
90
|
+
}
|
|
91
|
+
async run(op, token = '', arg3 = '', arg4 = '', arg5 = '') {
|
|
92
|
+
try {
|
|
93
|
+
const result = await this.#script.run({
|
|
94
|
+
keys: this.keys,
|
|
95
|
+
arguments: [op, token, arg3, arg4, arg5],
|
|
96
|
+
});
|
|
97
|
+
if (Array.isArray(result) && result[0] === 'hub-error' && typeof result[1] === 'string')
|
|
98
|
+
throw new HubError(result[1]);
|
|
99
|
+
return result;
|
|
100
|
+
}
|
|
101
|
+
catch (error) {
|
|
102
|
+
if (error instanceof HubError)
|
|
103
|
+
throw error;
|
|
104
|
+
throw new HubError('STORE_UNAVAILABLE');
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
/**
|
|
108
|
+
* What Redis says about the hub right now, in one round trip (D-0038): the leader record and
|
|
109
|
+
* its remaining lease, and the servers and connections of owners whose records are still live.
|
|
110
|
+
*/
|
|
111
|
+
async inspect() {
|
|
112
|
+
const result = (await this.run('inspect'));
|
|
113
|
+
const [leader, remaining, owners, now] = result;
|
|
114
|
+
const servers = new Set();
|
|
115
|
+
let connections = 0;
|
|
116
|
+
for (const value of Array.isArray(owners) ? owners : []) {
|
|
117
|
+
const owner = JSON.parse(String(value));
|
|
118
|
+
if (typeof owner.expires !== 'number' || owner.expires <= Number(now))
|
|
119
|
+
continue;
|
|
120
|
+
if (typeof owner.serverId === 'string')
|
|
121
|
+
servers.add(owner.serverId);
|
|
122
|
+
// Saved records carry the connection list as a JSON string (see 'save'), like snapshot reads it.
|
|
123
|
+
const list = typeof owner.connections === 'string' ? JSON.parse(owner.connections) : owner.connections;
|
|
124
|
+
connections += Array.isArray(list) ? list.length : 0;
|
|
125
|
+
}
|
|
126
|
+
const record = typeof leader === 'string' && leader !== '' ? JSON.parse(leader) : undefined;
|
|
127
|
+
return {
|
|
128
|
+
...(record ? { leader: record, remainingMs: Math.max(0, Number(remaining)) } : {}),
|
|
129
|
+
servers: servers.size,
|
|
130
|
+
connections,
|
|
131
|
+
};
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* One-time replay nonce shared by every server of this namespace (D-0038): `SET NX PX`, so the
|
|
135
|
+
* first server to see a nonce wins and every other one is told it was used.
|
|
136
|
+
*/
|
|
137
|
+
async claimNonce(key, ttlSeconds) {
|
|
138
|
+
try {
|
|
139
|
+
return await this.redis.set(`${this.#prefix}:nonce:${key}`, '1', {
|
|
140
|
+
NX: true,
|
|
141
|
+
PX: Math.max(1, ttlSeconds) * 1000,
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
throw new HubError('STORE_UNAVAILABLE');
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
async discover() {
|
|
149
|
+
const v = await this.run('discover', '', '', '', this.fingerprint);
|
|
150
|
+
return v ? Object.freeze(JSON.parse(String(v))) : undefined;
|
|
151
|
+
}
|
|
152
|
+
async elect(leader) {
|
|
153
|
+
return Object.freeze(JSON.parse(String(await this.run('elect', JSON.stringify(leader), String(this.options.leaseMs), '', this.fingerprint))));
|
|
154
|
+
}
|
|
155
|
+
async snapshot(leaderEpoch) {
|
|
156
|
+
const result = (await this.run('snapshot', leaderEpoch));
|
|
157
|
+
const owners = new Map();
|
|
158
|
+
for (let i = 0; i < result[1].length; i += 2) {
|
|
159
|
+
const key = result[1][i], value = result[1][i + 1];
|
|
160
|
+
if (key === undefined || value === undefined)
|
|
161
|
+
throw new HubError('CHECKPOINT_INVALID');
|
|
162
|
+
const owner = JSON.parse(value);
|
|
163
|
+
if (typeof owner.connections === 'string')
|
|
164
|
+
owner.connections = JSON.parse(owner.connections);
|
|
165
|
+
if (!Array.isArray(owner.connections))
|
|
166
|
+
throw new HubError('CHECKPOINT_INVALID');
|
|
167
|
+
epoch(key);
|
|
168
|
+
identifier(owner.serverId);
|
|
169
|
+
epoch(owner.session);
|
|
170
|
+
sequence(owner.expires);
|
|
171
|
+
owner.connections = records(owner.connections, key, this.options.maxConnections);
|
|
172
|
+
owners.set(key, owner);
|
|
173
|
+
}
|
|
174
|
+
if (owners.size > this.options.maxOwners ||
|
|
175
|
+
[...owners.values()].reduce((sum, owner) => sum + owner.connections.length, 0) >
|
|
176
|
+
this.options.maxTotalConnections)
|
|
177
|
+
throw new HubError('CHECKPOINT_INVALID');
|
|
178
|
+
return { revision: sequence(Number(result[0])), owners, now: sequence(result[2]) };
|
|
179
|
+
}
|
|
180
|
+
}
|
package/dist/types.d.ts
ADDED
|
@@ -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
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
|
+
}
|