@dokebi/websocket-hub 0.4.0 → 0.4.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.
- package/AI.md +3 -2
- package/README.md +2 -2
- package/dist/event-queue.d.ts +6 -1
- package/dist/event-queue.js +9 -4
- package/dist/index.js +1 -1
- package/dist/local.js +55 -6
- package/dist/status.d.ts +16 -4
- package/dist/status.js +112 -16
- package/dist/types.d.ts +1 -0
- package/package.json +1 -1
package/AI.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# AI guide — @dokebi/websocket-hub 0.4.
|
|
1
|
+
# AI guide — @dokebi/websocket-hub 0.4.1
|
|
2
2
|
|
|
3
3
|
The hub that manages WebSocket connection lists, rooms, broadcasts and kicks (it replaces the old `dokebi-sync`). A broadcast is **at most once**, with no receipt ACK or resend ([D-0057](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0057-websocket-broadcast-without-ack.md)). Usually **@dokebi/websocket uses it alone**, and app code uses websocket's `defineSocket`. Direct use is mostly operational status (`status()`, `dokebi-hub-status`) and replay defense for sealed frames (`nonces()`). Node >=24, core ^0.4.0, peers: @dokebi/redis, @dokebi/nats (cluster mode). Details are in the [README](README.md).
|
|
4
4
|
|
|
@@ -64,7 +64,7 @@ The provider descriptor lives in the subpath `@dokebi/websocket-hub/dependency`
|
|
|
64
64
|
- `register(...)` → `HubConnection` (`identity`, `join`, `leave`, `updateMetadata`, `close`), `list(query)` → `HubSnapshot`, `broadcast(query, bytes)`, `kick(query)`, `events()`: the low-level API websocket uses. A query (`HubQuery`) is a required `tenant` plus optional `room`, `member`, `connection` (AND). **`events()` has a single consumer**; when websocket uses it, never read it separately. The `message` event (`{ id, connections, data }`) is the whole delivery: there is nothing to confirm (`acknowledge` was removed in 0.3.0).
|
|
65
65
|
- `broadcast` → receipt `HubReceipt` `{ id, recipients }`. Failures: `RECOVERING` (not connected to the leader, or the leader is changing; not sent), `OUTCOME_UNKNOWN` (the connection dropped after sending, before the answer; it may have been sent), `BUSY` (broadcasts in progress reached `maxPending`; in local mode, half of the event queue is still unread). The hub never resends. `kick` → `HubKickReceipt` `{ authorityEpoch, id }` (default code 4403).
|
|
66
66
|
- `status()` (D-0038) → `HubStatus` `{ mode, state, role, leaseState?, leader?, leaseRemainingMs?, servers?, connections?, serverId? }`. Unknown values are **left out**, not filled with 0 (`leaseState: 'unreachable'` when Redis does not answer).
|
|
67
|
-
- `nonces()` (D-0038) → `HubNonceStore` `{ shared, setIfNotExists(key, ttlSeconds) }`. cluster shares it between servers through Redis `SET NX PX` (`shared: true`); local keeps it in the process (`shared: false`; used in a cluster worker it warns `HUB_NONCES_NOT_SHARED` once). Pass it to the replay defense of sealed frames (@dokebi/seal `SealTerminator`). Only the shape matches; seal is never imported.
|
|
67
|
+
- `nonces()` (D-0038) → `HubNonceStore` `{ shared, setIfNotExists(key, ttlSeconds) }`. cluster shares it between servers through Redis `SET NX PX` (`shared: true`); local keeps it in the process (`shared: false`; used in a cluster worker it warns `HUB_NONCES_NOT_SHARED` once). Pass it to the replay defense of sealed frames (@dokebi/seal `SealTerminator`). Only the shape matches; seal is never imported. The local store holds at most 100000 live nonces and **fails closed** ([D-0075](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0075-replay-capacity.md)): it never forgets a live nonce; expired ones make room first (every expired entry, earliest expiry first, through an expiry heap), otherwise `setIfNotExists` rejects with `HubError` `NONCE_STORE_FULL` (seal answers it as a retryable `SEAL_REPLAY_CAPACITY`: web 503, websocket 1013) and warns `NONCE_STORE_FULL` once per 10 seconds with `max`, `live` and `repeated`. Nonces live 2 × the seal drift (120 s by default), so one local process takes about 830 sealed frames or bodies per second at most; above that use `mode: cluster` (Redis `SET NX PX`, no such limit).
|
|
68
68
|
- Exports: `createPlugin`, `dependency`, `HubError`, types `HubApi`, `HubConnection`, `HubRegistration`, `HubRecord`, `HubQuery`, `HubLeader`, `HubSnapshot`, `HubReceipt`, `HubKickReceipt`, `HubEvent`, `HubLease`, `HubStatus`, `HubNonceStore`.
|
|
69
69
|
|
|
70
70
|
## 4. Operations command `dokebi-hub-status`
|
|
@@ -106,6 +106,7 @@ From outside the app process it reads only Redis and shows the leader, the remai
|
|
|
106
106
|
| `RECOVERING` · `OUTCOME_UNKNOWN` · `BUSY` | Broadcast failures (§5) |
|
|
107
107
|
| `STORE_UNAVAILABLE` | Redis failure (the cause is in `cause`) |
|
|
108
108
|
| `INVALID_ARGUMENT` · `INVALID_OPTIONS` | Wrong API arguments or hub frame values (frame value codes are compared between servers, so they stay as in 0.3) |
|
|
109
|
+
| `NONCE_STORE_FULL` | The local nonce store holds 100000 live nonces: the new nonce is refused (fail closed, D-0075). Retryable; `fix`: `mode: cluster` or a smaller seal drift |
|
|
109
110
|
| `CONNECTION_LIMIT` · `MESSAGE_TOO_LARGE` · `DUPLICATE_CLIENT` · `DUPLICATE_CONNECTION` · `CLOSED` · `EVENT_OVERFLOW` | Limits, duplicates, shutdown |
|
|
110
111
|
|
|
111
112
|
## 8. Cautions
|
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @dokebi/websocket-hub
|
|
2
2
|
|
|
3
|
-
Node >=24, version 0.4.
|
|
3
|
+
Node >=24, version 0.4.1 (unreleased). An optional plugin of Dokebi `@dokebi/core ^0.4.0`: a TCP hub that replaces the former `@dokebi/sync`. AI agents start with [AI.md](AI.md).
|
|
4
4
|
|
|
5
5
|
There are two modes ([D-0029](https://git.nyx-zone.com/dokebi/framework/-/blob/main/docs/decisions/D-0029-hub-and-cluster-infrastructure.md)).
|
|
6
6
|
|
|
@@ -98,7 +98,7 @@ A full snapshot also stays within the frame limit. Check the [option schema](opt
|
|
|
98
98
|
|
|
99
99
|
- **`status()`:** returns this process (`mode`, `state`, `role`, `serverId`) together with the hub as Redis sees it (`leaseState`, `leader`, `leaseRemainingMs`, `servers`, `connections`). The calculation is one pure function, `hubStatus`. Unknown values are left out, not filled with 0 — with `leaseState: 'unreachable'` (Redis does not answer) there are no `servers` or `connections`. `none` means no leader (failover in progress, or no server is up).
|
|
100
100
|
- **`dokebi-hub-status --config dokebi.yaml [--json]`:** answers the same question from outside the app. It starts only the Redis plugin and reads the leader and owner records, without joining the election or registering. When Redis does not answer it exits with 1. In local mode it says the state lives only inside the process.
|
|
101
|
-
- **`nonces()`:** the one-time nonce store for sealed frames (passed as is to `nonces` of @dokebi/seal `SealTerminator`; only the shape matches and seal is never imported). cluster mode uses Redis `SET NX PX` (`shared: true`), so a frame replayed to another server is refused too. local mode keeps it in the process (`shared: false`) and warns `HUB_NONCES_NOT_SHARED` once when used in a cluster worker.
|
|
101
|
+
- **`nonces()`:** the one-time nonce store for sealed frames (passed as is to `nonces` of @dokebi/seal `SealTerminator`; only the shape matches and seal is never imported). cluster mode uses Redis `SET NX PX` (`shared: true`), so a frame replayed to another server is refused too. local mode keeps it in the process (`shared: false`) and warns `HUB_NONCES_NOT_SHARED` once when used in a cluster worker. The local store keeps at most 100000 live nonces and fails closed (D-0075): it never drops a live nonce to make room, so when it is full of live nonces (more than about 830 sealed frames or bodies per second for 2 × drift = 120 s) new ones are refused with `NONCE_STORE_FULL` (retryable: web 503 `SEAL_BUSY`, websocket 1013), with a warn `NONCE_STORE_FULL` once per 10 seconds. This keeps replay protection at the cost of availability under such a flood; use cluster mode (Redis) for more.
|
|
102
102
|
|
|
103
103
|
## Factory and dependencies (plugin contract v2)
|
|
104
104
|
|
package/dist/event-queue.d.ts
CHANGED
|
@@ -11,7 +11,12 @@ export declare class EventQueue implements AsyncIterableIterator<HubEvent> {
|
|
|
11
11
|
* rest of the queue to events that cannot be refused (presence).
|
|
12
12
|
*/
|
|
13
13
|
offer(value: HubEvent, share: number): boolean;
|
|
14
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Queues `value`, or hands it to a waiting reader. `bytes` is its size when the producer keeps
|
|
16
|
+
* it already (the local hub sums its roster as it changes): sizing a presence event here would
|
|
17
|
+
* serialize the whole roster on every change, O(N) per registration (review PERF-B).
|
|
18
|
+
*/
|
|
19
|
+
push(value: HubEvent, bytes?: number): void;
|
|
15
20
|
next(): Promise<IteratorResult<HubEvent>>;
|
|
16
21
|
finish(error?: unknown): void;
|
|
17
22
|
return(): Promise<IteratorResult<HubEvent>>;
|
package/dist/event-queue.js
CHANGED
|
@@ -27,17 +27,22 @@ export class EventQueue {
|
|
|
27
27
|
offer(value, share) {
|
|
28
28
|
if (this.#ended)
|
|
29
29
|
return false;
|
|
30
|
+
const bytes = this.#size(value);
|
|
30
31
|
if (!this.#waiter &&
|
|
31
32
|
(this.#values.length >= Math.ceil(this.capacity * share) ||
|
|
32
|
-
this.#bytes +
|
|
33
|
+
this.#bytes + bytes > this.maxBytes * share))
|
|
33
34
|
return false;
|
|
34
|
-
this.push(value);
|
|
35
|
+
this.push(value, bytes);
|
|
35
36
|
return true;
|
|
36
37
|
}
|
|
37
|
-
|
|
38
|
+
/**
|
|
39
|
+
* Queues `value`, or hands it to a waiting reader. `bytes` is its size when the producer keeps
|
|
40
|
+
* it already (the local hub sums its roster as it changes): sizing a presence event here would
|
|
41
|
+
* serialize the whole roster on every change, O(N) per registration (review PERF-B).
|
|
42
|
+
*/
|
|
43
|
+
push(value, bytes = this.#size(value)) {
|
|
38
44
|
if (this.#ended)
|
|
39
45
|
return;
|
|
40
|
-
const bytes = this.#size(value);
|
|
41
46
|
if (this.#waiter) {
|
|
42
47
|
const w = this.#waiter;
|
|
43
48
|
this.#waiter = undefined;
|
package/dist/index.js
CHANGED
|
@@ -57,7 +57,7 @@ class HubRuntime {
|
|
|
57
57
|
/** Factory input: `{ app, options? }`. Options default to `app.config['dokebi-websocket-hub']`. */
|
|
58
58
|
export const createPlugin = definePlugin({
|
|
59
59
|
name: 'dokebi-websocket-hub',
|
|
60
|
-
version: '0.4.
|
|
60
|
+
version: '0.4.1',
|
|
61
61
|
core: '^0.4.0',
|
|
62
62
|
options: declaration,
|
|
63
63
|
// local: nothing. cluster: Redis, and NATS only when natsConnection is set (D-0029).
|
package/dist/local.js
CHANGED
|
@@ -11,6 +11,12 @@ import { HubError, } from './types.js';
|
|
|
11
11
|
* are refused with BUSY; the rest stays for presence and kick events, which cannot be refused.
|
|
12
12
|
*/
|
|
13
13
|
const BROADCAST_SHARE = 0.5;
|
|
14
|
+
/** The JSON of a presence event around its connections: kind, revision, ownerEpoch, brackets. */
|
|
15
|
+
const PRESENCE_ENVELOPE_BYTES = 96;
|
|
16
|
+
/** The JSON size of one record, as the event queue's own sizing would count it. */
|
|
17
|
+
function recordBytes(record) {
|
|
18
|
+
return Buffer.byteLength(JSON.stringify(record));
|
|
19
|
+
}
|
|
14
20
|
/**
|
|
15
21
|
* The hub of one process (D-0029, `mode: 'local'`): the same HubApi as the cluster hub, kept in
|
|
16
22
|
* memory. A broadcast is handed to the event queue the websocket gateway reads and resolves at
|
|
@@ -29,6 +35,14 @@ export class LocalHub {
|
|
|
29
35
|
#events;
|
|
30
36
|
#revision = 0;
|
|
31
37
|
#closed = false;
|
|
38
|
+
/**
|
|
39
|
+
* JSON bytes of every record, kept as records come, change and go: the size of a presence
|
|
40
|
+
* event without serializing the roster on every change (review PERF-B).
|
|
41
|
+
*/
|
|
42
|
+
#rosterBytes = 0;
|
|
43
|
+
#sizes = new WeakMap();
|
|
44
|
+
/** A presence event is due at the end of this tick (changes of one tick share one event). */
|
|
45
|
+
#presenceDue = false;
|
|
32
46
|
/** Decisions on per-message paths (refusals), once per interval with a count. */
|
|
33
47
|
#throttle;
|
|
34
48
|
constructor(options,
|
|
@@ -42,7 +56,7 @@ export class LocalHub {
|
|
|
42
56
|
this.#throttle = new diagnostics.Repeats({ logger });
|
|
43
57
|
this.#events = new EventQueue(options.maxPending, options.maxPendingBytes);
|
|
44
58
|
const self = this;
|
|
45
|
-
const nonces = new LocalNonceStore();
|
|
59
|
+
const nonces = new LocalNonceStore({ logger });
|
|
46
60
|
let warned = false;
|
|
47
61
|
this.api = Object.freeze({
|
|
48
62
|
get state() {
|
|
@@ -75,9 +89,9 @@ export class LocalHub {
|
|
|
75
89
|
},
|
|
76
90
|
});
|
|
77
91
|
}
|
|
78
|
-
#push(event) {
|
|
92
|
+
#push(event, bytes) {
|
|
79
93
|
try {
|
|
80
|
-
this.#events.push(event);
|
|
94
|
+
this.#events.push(event, bytes);
|
|
81
95
|
}
|
|
82
96
|
catch (error) {
|
|
83
97
|
// The consumer fell too far behind: end the stream like the cluster client does. Its
|
|
@@ -91,14 +105,41 @@ export class LocalHub {
|
|
|
91
105
|
this.#closed = true;
|
|
92
106
|
}
|
|
93
107
|
}
|
|
108
|
+
#track(record) {
|
|
109
|
+
const bytes = recordBytes(record);
|
|
110
|
+
this.#sizes.set(record, bytes);
|
|
111
|
+
this.#rosterBytes += bytes;
|
|
112
|
+
}
|
|
113
|
+
#untrack(record) {
|
|
114
|
+
this.#rosterBytes -= this.#sizes.get(record) ?? 0;
|
|
115
|
+
this.#sizes.delete(record);
|
|
116
|
+
}
|
|
117
|
+
/**
|
|
118
|
+
* One more revision. Its presence event (the whole roster, like every hub's) goes out at the
|
|
119
|
+
* end of the tick, so changes of one tick (a burst of reconnects) share one event and one copy
|
|
120
|
+
* of the roster, like the cluster client's group commit; a broadcast or kick flushes it first,
|
|
121
|
+
* so events keep the order of the calls.
|
|
122
|
+
*/
|
|
94
123
|
#changed() {
|
|
95
124
|
this.#revision++;
|
|
125
|
+
if (this.#presenceDue)
|
|
126
|
+
return;
|
|
127
|
+
this.#presenceDue = true;
|
|
128
|
+
queueMicrotask(() => this.#flushPresence());
|
|
129
|
+
}
|
|
130
|
+
#flushPresence() {
|
|
131
|
+
if (!this.#presenceDue)
|
|
132
|
+
return;
|
|
133
|
+
this.#presenceDue = false;
|
|
134
|
+
if (this.#closed)
|
|
135
|
+
return;
|
|
136
|
+
const connections = Object.freeze([...this.#records.values()]);
|
|
96
137
|
this.#push({
|
|
97
138
|
kind: 'presence',
|
|
98
139
|
revision: this.#revision,
|
|
99
140
|
ownerEpoch: this.ownerEpoch,
|
|
100
|
-
connections
|
|
101
|
-
});
|
|
141
|
+
connections,
|
|
142
|
+
}, PRESENCE_ENVELOPE_BYTES + this.#rosterBytes + connections.length);
|
|
102
143
|
}
|
|
103
144
|
#ensureOpen() {
|
|
104
145
|
if (this.#closed)
|
|
@@ -116,6 +157,7 @@ export class LocalHub {
|
|
|
116
157
|
throw new HubError('CONNECTION_LIMIT');
|
|
117
158
|
this.#records.set(value.connection, value);
|
|
118
159
|
this.#index.add(value);
|
|
160
|
+
this.#track(value);
|
|
119
161
|
this.#changed();
|
|
120
162
|
if (this.logger.isEnabled('debug'))
|
|
121
163
|
this.logger.log('debug', 'Hub connection registered', {
|
|
@@ -130,6 +172,8 @@ export class LocalHub {
|
|
|
130
172
|
const updated = next(current);
|
|
131
173
|
this.#records.set(value.connection, updated);
|
|
132
174
|
this.#index.add(updated);
|
|
175
|
+
this.#untrack(current);
|
|
176
|
+
this.#track(updated);
|
|
133
177
|
this.#changed();
|
|
134
178
|
if (this.logger.isEnabled('debug'))
|
|
135
179
|
this.logger.log('debug', 'Hub connection changed', {
|
|
@@ -147,8 +191,10 @@ export class LocalHub {
|
|
|
147
191
|
return;
|
|
148
192
|
closed = true;
|
|
149
193
|
const current = this.#records.get(value.connection);
|
|
150
|
-
if (current)
|
|
194
|
+
if (current) {
|
|
151
195
|
this.#index.remove(current);
|
|
196
|
+
this.#untrack(current);
|
|
197
|
+
}
|
|
152
198
|
if (this.#records.delete(value.connection) && !this.#closed) {
|
|
153
199
|
this.#changed();
|
|
154
200
|
if (this.logger.isEnabled('debug'))
|
|
@@ -183,6 +229,8 @@ export class LocalHub {
|
|
|
183
229
|
return Promise.reject(error);
|
|
184
230
|
}
|
|
185
231
|
const id = randomUUID();
|
|
232
|
+
// Presence changes made before this call reach the gateway before this message.
|
|
233
|
+
this.#flushPresence();
|
|
186
234
|
const { recipients, owners } = this.#index.select(filter);
|
|
187
235
|
const connections = owners.get(this.ownerEpoch) ?? [];
|
|
188
236
|
// The caller may reuse its buffer once this resolves; the gateway reads the event later.
|
|
@@ -217,6 +265,7 @@ export class LocalHub {
|
|
|
217
265
|
throw new HubError('INVALID_ARGUMENT');
|
|
218
266
|
const id = randomUUID();
|
|
219
267
|
const connections = Array.from(this.#index.matching(filter), (r) => r.connection);
|
|
268
|
+
this.#flushPresence();
|
|
220
269
|
if (connections.length)
|
|
221
270
|
this.#push({ kind: 'kick', id, connections: Object.freeze(connections), code, reason });
|
|
222
271
|
this.logger.log('debug', 'Hub kick sent', { id, connections: connections.length, code });
|
package/dist/status.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
|
-
import type {
|
|
1
|
+
import type { Logger } from '@dokebi/core';
|
|
2
|
+
import { type HubApi, type HubLease, type HubStatus } from './types.js';
|
|
2
3
|
/**
|
|
3
4
|
* The one place that turns facts into a status (D-0038 · original x-hubserver `hubStatus`).
|
|
4
5
|
* `HubApi.status()` and `dokebi-hub-status` both call it, so a health check, a dashboard and the
|
|
@@ -12,11 +13,22 @@ export declare function hubStatus(input: {
|
|
|
12
13
|
/** cluster only: what Redis said, or `unreachable` when it did not answer. */
|
|
13
14
|
lease?: HubLease | 'unreachable';
|
|
14
15
|
}): HubStatus;
|
|
15
|
-
/**
|
|
16
|
+
/**
|
|
17
|
+
* In-process nonce store for local mode: correct for one process only (`shared: false`).
|
|
18
|
+
*
|
|
19
|
+
* Full of **live** nonces it refuses a new one with `NONCE_STORE_FULL` instead of forgetting a
|
|
20
|
+
* live one (D-0075, fail closed: a forgotten nonce lets its captured frame be replayed). Seal turns
|
|
21
|
+
* the refusal into a retryable `SEAL_REPLAY_CAPACITY`; room returns as the nonces expire.
|
|
22
|
+
*/
|
|
16
23
|
export declare class LocalNonceStore {
|
|
17
24
|
#private;
|
|
18
|
-
readonly max: number;
|
|
19
25
|
readonly shared = false;
|
|
20
|
-
|
|
26
|
+
readonly max: number;
|
|
27
|
+
constructor(options?: {
|
|
28
|
+
max?: number;
|
|
29
|
+
now?: () => number;
|
|
30
|
+
/** Warned once per 10 s, with counts, while the store is full (D-0047). */
|
|
31
|
+
logger?: Pick<Logger, 'log'> | undefined;
|
|
32
|
+
});
|
|
21
33
|
setIfNotExists(key: string, ttlSeconds: number): Promise<boolean>;
|
|
22
34
|
}
|
package/dist/status.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { HubError } from './types.js';
|
|
1
2
|
/**
|
|
2
3
|
* The one place that turns facts into a status (D-0038 · original x-hubserver `hubStatus`).
|
|
3
4
|
* `HubApi.status()` and `dokebi-hub-status` both call it, so a health check, a dashboard and the
|
|
@@ -32,31 +33,126 @@ export function hubStatus(input) {
|
|
|
32
33
|
connections: lease.connections,
|
|
33
34
|
});
|
|
34
35
|
}
|
|
35
|
-
/**
|
|
36
|
+
/**
|
|
37
|
+
* A min-heap of [expires, key] pairs by expiry (ISSUE-0006 recheck: a scan of the oldest
|
|
38
|
+
* insertions missed expired entries further back when TTLs differ). Pairs of keys that were
|
|
39
|
+
* renewed or removed since are skipped when they reach the top.
|
|
40
|
+
*/
|
|
41
|
+
class ExpiryHeap {
|
|
42
|
+
#items = [];
|
|
43
|
+
push(expires, key) {
|
|
44
|
+
const items = this.#items;
|
|
45
|
+
items.push([expires, key]);
|
|
46
|
+
let index = items.length - 1;
|
|
47
|
+
while (index > 0) {
|
|
48
|
+
const parent = (index - 1) >> 1;
|
|
49
|
+
const above = items[parent];
|
|
50
|
+
const here = items[index];
|
|
51
|
+
if (above[0] <= here[0])
|
|
52
|
+
break;
|
|
53
|
+
items[parent] = here;
|
|
54
|
+
items[index] = above;
|
|
55
|
+
index = parent;
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
peek() {
|
|
59
|
+
return this.#items[0];
|
|
60
|
+
}
|
|
61
|
+
pop() {
|
|
62
|
+
const items = this.#items;
|
|
63
|
+
const last = items.pop();
|
|
64
|
+
if (last === undefined || items.length === 0)
|
|
65
|
+
return;
|
|
66
|
+
items[0] = last;
|
|
67
|
+
let index = 0;
|
|
68
|
+
for (;;) {
|
|
69
|
+
const left = 2 * index + 1;
|
|
70
|
+
const right = left + 1;
|
|
71
|
+
let smallest = index;
|
|
72
|
+
if (left < items.length &&
|
|
73
|
+
items[left][0] < items[smallest][0])
|
|
74
|
+
smallest = left;
|
|
75
|
+
if (right < items.length &&
|
|
76
|
+
items[right][0] < items[smallest][0])
|
|
77
|
+
smallest = right;
|
|
78
|
+
if (smallest === index)
|
|
79
|
+
break;
|
|
80
|
+
const moved = items[smallest];
|
|
81
|
+
items[smallest] = items[index];
|
|
82
|
+
items[index] = moved;
|
|
83
|
+
index = smallest;
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const WARN_EVERY_MS = 10_000;
|
|
88
|
+
const FULL_FIX = 'More sealed frames arrived within 2 x drift than the local nonce store keeps: use mode: cluster (Redis, no such limit), or lower the seal drift window (dokebi-websocket sealDriftMs).';
|
|
89
|
+
/**
|
|
90
|
+
* In-process nonce store for local mode: correct for one process only (`shared: false`).
|
|
91
|
+
*
|
|
92
|
+
* Full of **live** nonces it refuses a new one with `NONCE_STORE_FULL` instead of forgetting a
|
|
93
|
+
* live one (D-0075, fail closed: a forgotten nonce lets its captured frame be replayed). Seal turns
|
|
94
|
+
* the refusal into a retryable `SEAL_REPLAY_CAPACITY`; room returns as the nonces expire.
|
|
95
|
+
*/
|
|
36
96
|
export class LocalNonceStore {
|
|
37
|
-
max;
|
|
38
97
|
shared = false;
|
|
98
|
+
max;
|
|
39
99
|
#entries = new Map();
|
|
100
|
+
#expiry = new ExpiryHeap();
|
|
101
|
+
#now;
|
|
102
|
+
#logger;
|
|
40
103
|
#inserts = 0;
|
|
41
|
-
|
|
42
|
-
|
|
104
|
+
#warnedAt = Number.NEGATIVE_INFINITY;
|
|
105
|
+
#refused = 0;
|
|
106
|
+
constructor(options = {}) {
|
|
107
|
+
this.max = options.max ?? 100_000;
|
|
108
|
+
this.#now = options.now ?? Date.now;
|
|
109
|
+
this.#logger = options.logger;
|
|
43
110
|
}
|
|
44
111
|
async setIfNotExists(key, ttlSeconds) {
|
|
45
|
-
const now =
|
|
112
|
+
const now = this.#now();
|
|
46
113
|
const existing = this.#entries.get(key);
|
|
47
|
-
if (existing !== undefined
|
|
48
|
-
|
|
114
|
+
if (existing !== undefined) {
|
|
115
|
+
if (existing > now)
|
|
116
|
+
return false;
|
|
117
|
+
// Expired: deleted first, so the renewed entry moves to the end (insertion order = age).
|
|
118
|
+
this.#entries.delete(key);
|
|
119
|
+
}
|
|
120
|
+
// Full: expired entries make room (earliest expiry first). A live nonce is never forgotten.
|
|
121
|
+
if (this.#entries.size >= this.max && !this.#evictExpired(now))
|
|
122
|
+
this.#full(now);
|
|
49
123
|
this.#entries.set(key, now + ttlSeconds * 1000);
|
|
124
|
+
this.#expiry.push(now + ttlSeconds * 1000, key);
|
|
50
125
|
if (++this.#inserts % 500 === 0)
|
|
51
|
-
|
|
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
|
-
}
|
|
126
|
+
this.#evictExpired(now);
|
|
60
127
|
return true;
|
|
61
128
|
}
|
|
129
|
+
/** Deletes every expired entry, earliest expiry first (each pair is popped once); true when that made room. */
|
|
130
|
+
#evictExpired(now) {
|
|
131
|
+
for (let top = this.#expiry.peek(); top !== undefined && top[0] <= now; top = this.#expiry.peek()) {
|
|
132
|
+
this.#expiry.pop();
|
|
133
|
+
// A renewed key has a newer pair; only the pair that matches the stored expiry deletes it.
|
|
134
|
+
if (this.#entries.get(top[1]) === top[0])
|
|
135
|
+
this.#entries.delete(top[1]);
|
|
136
|
+
}
|
|
137
|
+
return this.#entries.size < this.max;
|
|
138
|
+
}
|
|
139
|
+
#full(now) {
|
|
140
|
+
// Per frame: counted, and said once per interval with the count (D-0047).
|
|
141
|
+
this.#refused += 1;
|
|
142
|
+
if (this.#logger && now - this.#warnedAt >= WARN_EVERY_MS) {
|
|
143
|
+
this.#logger.log('warn', 'Replay nonce store full; sealed frames refused', {
|
|
144
|
+
code: 'NONCE_STORE_FULL',
|
|
145
|
+
max: this.max,
|
|
146
|
+
live: this.#entries.size,
|
|
147
|
+
repeated: this.#refused - 1,
|
|
148
|
+
fix: FULL_FIX,
|
|
149
|
+
});
|
|
150
|
+
this.#warnedAt = now;
|
|
151
|
+
this.#refused = 0;
|
|
152
|
+
}
|
|
153
|
+
throw new HubError('NONCE_STORE_FULL', {
|
|
154
|
+
fix: FULL_FIX,
|
|
155
|
+
details: { max: this.max },
|
|
156
|
+
});
|
|
157
|
+
}
|
|
62
158
|
}
|
package/dist/types.d.ts
CHANGED
|
@@ -110,6 +110,7 @@ export interface HubStatus {
|
|
|
110
110
|
}
|
|
111
111
|
/** One-time nonce store for sealed frames (structurally the @dokebi/seal NonceStore · D-0038, D-0059). */
|
|
112
112
|
export interface HubNonceStore {
|
|
113
|
+
/** false for a nonce seen before; rejects `NONCE_STORE_FULL` when a local store is full of live nonces (D-0075). */
|
|
113
114
|
setIfNotExists(key: string, ttlSeconds: number): Promise<boolean>;
|
|
114
115
|
/** true only when every server of the namespace shares it (cluster mode). */
|
|
115
116
|
readonly shared: boolean;
|