@dokebi/websocket-hub 0.3.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/dist/node.js CHANGED
@@ -1,9 +1,9 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { createServer } from 'node:net';
3
3
  import { setTimeout as delay } from 'node:timers/promises';
4
+ import { diagnostics } from '@dokebi/core/libraries';
4
5
  import { checkEviction } from './eviction.js';
5
6
  import { Leader } from './leader.js';
6
- import { errorText, LogThrottle } from './log.js';
7
7
  import { PeerClient } from './peer-client.js';
8
8
  import { hubStatus } from './status.js';
9
9
  import { HubStore } from './store.js';
@@ -32,14 +32,14 @@ export class HubNode {
32
32
  #startupCode;
33
33
  #throttle;
34
34
  constructor(context, options, redis,
35
- /** Optional (D-0029): without NATS, peers notice a new leader by Redis polling (pollMs). */
35
+ /** Optional (D-0029): without NATS, peers notice a new leader by Redis polling (pollIntervalMs). */
36
36
  nats) {
37
37
  this.context = context;
38
38
  this.options = options;
39
39
  this.redis = redis;
40
40
  this.nats = nats;
41
41
  this.store = new HubStore(redis, options);
42
- this.#throttle = new LogThrottle(context.logger);
42
+ this.#throttle = new diagnostics.Repeats({ logger: context.logger });
43
43
  // The client logs why a ready connection dropped (revision gap, stale leader, socket closed);
44
44
  // it is when upgrades see the hub recovering.
45
45
  this.client = new PeerClient(options, context.logger);
@@ -83,7 +83,7 @@ export class HubNode {
83
83
  }
84
84
  catch (error) {
85
85
  // Reported as leaseState 'unreachable'; the cause is only in this log.
86
- this.#throttle.report('error', 'Hub status could not read the lease from Redis', 'STATUS_UNREACHABLE', error);
86
+ this.#throttle.log('error', 'Hub status could not read the lease from Redis', 'STATUS_UNREACHABLE', error);
87
87
  lease = 'unreachable';
88
88
  }
89
89
  return hubStatus({
@@ -118,7 +118,7 @@ export class HubNode {
118
118
  server.on('error', (error) => {
119
119
  this.context.logger.log('error', 'Hub TCP server failed; reconnecting', {
120
120
  code: 'HUB_SERVER_ERROR',
121
- error: errorText(error),
121
+ error: diagnostics.describeError(error),
122
122
  });
123
123
  this.client.disconnect();
124
124
  });
@@ -136,21 +136,21 @@ export class HubNode {
136
136
  await this.#subscription.ready;
137
137
  this.#notifications = this.#readNotifications(this.#subscription);
138
138
  }
139
- const deadline = performance.now() + this.options.startupMs;
139
+ const deadline = performance.now() + this.options.startupTimeoutMs;
140
140
  while (!this.client.ready) {
141
141
  this.context.signal.throwIfAborted();
142
142
  await this.#poll();
143
143
  if (this.#configMismatch)
144
144
  throw this.#configMismatch;
145
145
  if (performance.now() > deadline) {
146
- this.context.logger.log('error', 'Hub did not become ready before startupMs', {
146
+ this.context.logger.log('error', 'Hub did not become ready before startupTimeoutMs', {
147
147
  code: 'STARTUP_TIMEOUT',
148
148
  lastError: this.#startupCode ?? 'NONE',
149
149
  });
150
150
  throw new HubError('STARTUP_TIMEOUT');
151
151
  }
152
152
  if (!this.client.ready)
153
- await delay(this.options.pollMs);
153
+ await delay(this.options.pollIntervalMs);
154
154
  }
155
155
  this.#started = true;
156
156
  this.context.logger.log('debug', 'Hub started', {
@@ -162,7 +162,7 @@ export class HubNode {
162
162
  });
163
163
  this.#timer = setInterval(() => {
164
164
  void this.#poll();
165
- }, this.options.pollMs);
165
+ }, this.options.pollIntervalMs);
166
166
  this.#timer.unref();
167
167
  }
168
168
  async #readNotifications(subscription) {
@@ -175,7 +175,7 @@ export class HubNode {
175
175
  }
176
176
  catch (error) {
177
177
  if (!this.#closing)
178
- this.context.logger.log('error', 'Hub control notifications unavailable; Redis discovery polling remains active', { code: 'NATS_SUBSCRIPTION_FAILED', error: errorText(error) });
178
+ this.context.logger.log('error', 'Hub control notifications unavailable; Redis discovery polling remains active', { code: 'NATS_SUBSCRIPTION_FAILED', error: diagnostics.describeError(error) });
179
179
  }
180
180
  }
181
181
  #poll() {
@@ -198,22 +198,22 @@ export class HubNode {
198
198
  this.#startupCode = hubCode(error);
199
199
  this.context.logger.log('debug', 'Hub startup attempt failed; retrying', {
200
200
  code: this.#startupCode,
201
- error: errorText(error),
201
+ error: diagnostics.describeError(error),
202
202
  });
203
203
  }
204
204
  else if (!this.#lastFailure) {
205
205
  this.#failingSince = performance.now();
206
206
  this.context.logger.log('error', 'Hub transport or store unavailable; recovering', {
207
207
  code: hubCode(error),
208
- error: errorText(error),
208
+ error: diagnostics.describeError(error),
209
209
  });
210
210
  }
211
- // Every further failure of the same outage (once per pollMs), so a long recovery shows
211
+ // Every further failure of the same outage (once per pollIntervalMs), so a long recovery shows
212
212
  // its causes.
213
213
  else
214
214
  this.context.logger.log('debug', 'Hub still recovering', {
215
215
  code: hubCode(error),
216
- error: errorText(error),
216
+ error: diagnostics.describeError(error),
217
217
  ms: Math.round(performance.now() - this.#failingSince),
218
218
  leader: this.client.leader?.serverId ?? null,
219
219
  });
@@ -259,7 +259,7 @@ export class HubNode {
259
259
  await this.nats.publish(`dokebi.websocket-hub.${this.options.namespace}.control`, Buffer.from(JSON.stringify({ kind: 'leader-changed', epoch: discovered.epoch })));
260
260
  }
261
261
  catch (error) {
262
- this.context.logger.log('error', 'Hub change notification failed; peers use Redis discovery', { code: 'NATS_PUBLISH_FAILED', error: errorText(error) });
262
+ this.context.logger.log('error', 'Hub change notification failed; peers use Redis discovery', { code: 'NATS_PUBLISH_FAILED', error: diagnostics.describeError(error) });
263
263
  }
264
264
  }
265
265
  if (this.#leader && this.#identity.epoch !== discovered.epoch) {
@@ -318,7 +318,7 @@ export class HubNode {
318
318
  if (left && GONE.has(hubCode(goodbye)))
319
319
  this.context.logger.log('debug', 'Hub goodbye not delivered; left through Redis', {
320
320
  code: hubCode(goodbye),
321
- error: errorText(goodbye),
321
+ error: diagnostics.describeError(goodbye),
322
322
  });
323
323
  else
324
324
  errors.unshift(goodbye);
package/dist/options.d.ts CHANGED
@@ -1,38 +1,33 @@
1
- export declare function object(value: unknown): Record<string, unknown>;
2
- export declare function keys(value: Record<string, unknown>, allowed: readonly string[]): void;
3
- export declare function integer(v: unknown, min: number, max: number): number;
1
+ import { type OptionsOf } from '@dokebi/core';
4
2
  /**
5
3
  * Options of 0.2 that D-0057 removed with client ACKs. A dokebi.yaml that still has them starts:
6
- * the hub logs warn `OPTION_REMOVED` once per key and ignores the value.
4
+ * core logs warn `OPTION_REMOVED` once per key at setup and the value is ignored.
7
5
  */
8
6
  export declare const REMOVED_OPTIONS: readonly ["deliveryTimeoutMs", "retryMs", "maxDeliveries", "deliveryBytes"];
9
- export interface HubOptions {
10
- /** `local` (default): one process, in memory. `cluster`: Redis leader and TCP (D-0029). */
11
- mode: 'local' | 'cluster';
12
- /** Lets `local` run in a node:cluster worker anyway (each worker then has its own hub). */
13
- allowInCluster: boolean;
14
- namespace: string;
15
- serverId: string;
16
- /** Required in cluster mode. */
17
- redisConnection: string | undefined;
18
- /** Optional: leader-change notifications; without it peers notice by Redis polling. */
19
- natsConnection: string | undefined;
20
- host: string;
21
- advertiseHost: string;
22
- port: number;
23
- secret: string;
24
- leaseMs: number;
25
- pollMs: number;
26
- ownerTtlMs: number;
27
- startupMs: number;
28
- maxFrameBytes: number;
29
- maxPayloadBytes: number;
30
- maxConnections: number;
31
- maxOwners: number;
32
- maxTotalConnections: number;
33
- maxPending: number;
34
- queueBytes: number;
35
- /** Removed options found in the input (REMOVED_OPTIONS), reported at setup and ignored. */
36
- removedOptions: readonly string[];
37
- }
7
+ export declare const options: import("@dokebi/core").OptionsDeclaration<{
8
+ readonly advertiseHost: string;
9
+ readonly allowInCluster: boolean;
10
+ readonly host: string;
11
+ readonly leaseMs: number;
12
+ readonly maxConnections: number;
13
+ readonly maxFrameBytes: number;
14
+ readonly maxOwners: number;
15
+ readonly maxPayloadBytes: number;
16
+ readonly maxPending: number;
17
+ readonly maxPendingBytes: number;
18
+ readonly maxTotalConnections: number;
19
+ readonly mode: "cluster" | "local";
20
+ readonly namespace: string;
21
+ readonly natsConnection?: string;
22
+ readonly ownerTtlMs: number;
23
+ readonly pollIntervalMs: number;
24
+ readonly port: number;
25
+ readonly redisConnection?: string;
26
+ readonly secret?: string;
27
+ readonly serverId: string;
28
+ readonly startupTimeoutMs: number;
29
+ }>;
30
+ /** Parsed hub options (frozen). `secret` is required in cluster mode. */
31
+ export type HubOptions = OptionsOf<typeof options>;
32
+ /** Validates hub options (status CLI and tests; definePlugin uses `options` itself). */
38
33
  export declare function parseOptions(input: unknown): HubOptions;
package/dist/options.js CHANGED
@@ -1,32 +1,20 @@
1
- import { types } from 'node:util';
2
- import { HubError } from './types.js';
3
- export function object(value) {
4
- if (!value ||
5
- typeof value !== 'object' ||
6
- types.isProxy(value) ||
7
- ![Object.prototype, null].includes(Object.getPrototypeOf(value)))
8
- throw new HubError('INVALID_OPTIONS');
9
- const result = Object.create(null);
10
- for (const key of Reflect.ownKeys(value)) {
11
- const desc = Object.getOwnPropertyDescriptor(value, key);
12
- if (typeof key !== 'string' || !desc || !('value' in desc) || !desc.enumerable)
13
- throw new HubError('INVALID_OPTIONS');
14
- result[key] = desc.value;
15
- }
16
- return result;
17
- }
18
- export function keys(value, allowed) {
19
- if (Object.keys(value).some((k) => !allowed.includes(k)))
20
- throw new HubError('INVALID_OPTIONS');
21
- }
22
- export function integer(v, min, max) {
23
- if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < min || v > max)
24
- throw new HubError('INVALID_OPTIONS');
25
- return v;
26
- }
1
+ import { defineOptions, option as o } from '@dokebi/core';
2
+ /*
3
+ * dokebi-websocket-hub options (D-0063 §3): this declaration is both the parser definePlugin runs
4
+ * and options.schema.json, which the build writes from it (scripts/options/check.ts compares).
5
+ * It replaced the hand parser of 0.3; what that parser enforced and the old file did not say is
6
+ * now in the schema too: connection-name and host patterns, and the defaults the parser filled.
7
+ */
8
+ const ID = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
9
+ /** No control characters or whitespace (the hand parser's per-character check). */
10
+ // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control characters is the point.
11
+ const HOST = /^[^\s\x00-\x1f]+$/;
12
+ const REMOVED = 'Removed in 0.3.0 with client ACKs (D-0057). Ignored: the hub logs warn OPTION_REMOVED once and starts. Delete it from dokebi.yaml.';
13
+ const ms = (minimum, maximum, fallback) => o.integer({ minimum, maximum, default: fallback });
14
+ const bytes = (value) => Buffer.byteLength(value);
27
15
  /**
28
16
  * Options of 0.2 that D-0057 removed with client ACKs. A dokebi.yaml that still has them starts:
29
- * the hub logs warn `OPTION_REMOVED` once per key and ignores the value.
17
+ * core logs warn `OPTION_REMOVED` once per key at setup and the value is ignored.
30
18
  */
31
19
  export const REMOVED_OPTIONS = Object.freeze([
32
20
  'deliveryTimeoutMs',
@@ -34,94 +22,96 @@ export const REMOVED_OPTIONS = Object.freeze([
34
22
  'maxDeliveries',
35
23
  'deliveryBytes',
36
24
  ]);
25
+ export const options = defineOptions({
26
+ mode: o.enum(['local', 'cluster'], {
27
+ default: 'local',
28
+ description: 'local: one process, in memory (no Redis/NATS). cluster: several processes or servers share presence through Redis (D-0029).',
29
+ }),
30
+ allowInCluster: o.boolean({
31
+ default: false,
32
+ description: 'Allow mode local in a node:cluster worker (each worker then has its own hub).',
33
+ }),
34
+ namespace: o.string({ minLength: 1, maxLength: 64, pattern: ID, default: 'local' }),
35
+ serverId: o.string({ minLength: 1, maxLength: 64, pattern: ID, default: 'local' }),
36
+ redisConnection: o.string({
37
+ minLength: 1,
38
+ maxLength: 64,
39
+ pattern: ID,
40
+ description: 'Required in cluster mode.',
41
+ }),
42
+ natsConnection: o.string({
43
+ minLength: 1,
44
+ maxLength: 64,
45
+ pattern: ID,
46
+ description: 'Optional in cluster mode: leader-change notifications; without it peers notice by Redis polling (pollIntervalMs).',
47
+ }),
48
+ host: o.string({ minLength: 1, maxLength: 253, pattern: HOST, default: '127.0.0.1' }),
49
+ advertiseHost: o.string({ minLength: 1, maxLength: 253, pattern: HOST, default: '127.0.0.1' }),
50
+ secret: o.string({
51
+ minLength: 32,
52
+ maxLength: 256,
53
+ secret: true,
54
+ env: 'DOKEBI_HUB_SECRET',
55
+ description: 'Shared private-network peer authentication secret. Configure explicitly; never send to WebSocket clients.',
56
+ // The old parser counted UTF-8 bytes and the old schema characters; both hold now.
57
+ refine: [
58
+ {
59
+ test: (value) => bytes(value) >= 32 && bytes(value) <= 256,
60
+ message: 'must be 32 to 256 bytes',
61
+ code: 'SECRET_REQUIRED',
62
+ },
63
+ ],
64
+ }),
65
+ port: o.integer({ minimum: 0, maximum: 65535, default: 0 }),
66
+ leaseMs: ms(500, 60000, 3000),
67
+ pollIntervalMs: ms(25, 10000, 500),
68
+ pollMs: o.alias('pollIntervalMs'),
69
+ ownerTtlMs: ms(1500, 120000, 15000),
70
+ startupTimeoutMs: ms(1000, 120000, 15000),
71
+ startupMs: o.alias('startupTimeoutMs'),
72
+ maxFrameBytes: ms(16384, 4194304, 1048576),
73
+ maxPayloadBytes: ms(1, 262144, 65536),
74
+ maxConnections: ms(1, 4096, 128),
75
+ maxOwners: ms(1, 1024, 64),
76
+ maxTotalConnections: ms(1, 100000, 8192),
77
+ maxPending: ms(1, 4096, 128),
78
+ maxPendingBytes: ms(16384, 67108864, 4194304),
79
+ queueBytes: o.alias('maxPendingBytes'),
80
+ deliveryTimeoutMs: o.removed({ type: 'integer', message: REMOVED }),
81
+ retryMs: o.removed({ type: 'integer', message: REMOVED }),
82
+ maxDeliveries: o.removed({ type: 'integer', message: REMOVED }),
83
+ deliveryBytes: o.removed({ type: 'integer', message: REMOVED }),
84
+ }, {
85
+ // The 0.3 parser's own codes stay as issue codes (D-0063 §8).
86
+ requirements: [
87
+ { when: { mode: 'cluster' }, require: ['namespace', 'serverId'] },
88
+ { when: { mode: 'cluster' }, require: ['redisConnection'], code: 'REDIS_REQUIRED' },
89
+ { when: { mode: 'cluster' }, require: ['secret'], code: 'SECRET_REQUIRED' },
90
+ ],
91
+ checks: [
92
+ {
93
+ path: 'pollIntervalMs',
94
+ message: 'pollIntervalMs * 3 must not exceed leaseMs',
95
+ test: (value) => value.pollIntervalMs * 3 <= value.leaseMs,
96
+ },
97
+ {
98
+ path: 'ownerTtlMs',
99
+ message: 'must be at least leaseMs * 3',
100
+ test: (value) => value.ownerTtlMs >= value.leaseMs * 3,
101
+ },
102
+ {
103
+ path: 'maxPayloadBytes',
104
+ message: 'base64 of maxPayloadBytes plus 8192 must fit in maxFrameBytes',
105
+ test: (value) => Math.ceil(value.maxPayloadBytes / 3) * 4 + 8192 <= value.maxFrameBytes,
106
+ },
107
+ {
108
+ path: 'maxPendingBytes',
109
+ message: 'must be at least maxFrameBytes',
110
+ test: (value) => value.maxPendingBytes >= value.maxFrameBytes,
111
+ },
112
+ ],
113
+ });
114
+ /** Validates hub options (status CLI and tests; definePlugin uses `options` itself). */
37
115
  export function parseOptions(input) {
38
- const v = object(input);
39
- keys(v, [
40
- 'mode',
41
- 'allowInCluster',
42
- 'namespace',
43
- 'serverId',
44
- 'redisConnection',
45
- 'natsConnection',
46
- 'host',
47
- 'advertiseHost',
48
- 'port',
49
- 'secret',
50
- 'leaseMs',
51
- 'pollMs',
52
- 'ownerTtlMs',
53
- 'startupMs',
54
- 'maxFrameBytes',
55
- 'maxPayloadBytes',
56
- 'maxConnections',
57
- 'maxOwners',
58
- 'maxTotalConnections',
59
- 'maxPending',
60
- 'queueBytes',
61
- ...REMOVED_OPTIONS,
62
- ]);
63
- const id = (key) => {
64
- const x = v[key];
65
- if (typeof x !== 'string' || !/^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/.test(x))
66
- throw new HubError('INVALID_OPTIONS');
67
- return x;
68
- };
69
- const host = (key, fallback) => {
70
- const x = v[key] === undefined ? fallback : v[key];
71
- if (typeof x !== 'string' ||
72
- !x ||
73
- x.length > 253 ||
74
- [...x].some((c) => c.charCodeAt(0) <= 32 || /\s/.test(c)))
75
- throw new HubError('INVALID_OPTIONS');
76
- return x;
77
- };
78
- const num = (k, d, min, max) => integer(v[k] === undefined ? d : v[k], min, max);
79
- const mode = v.mode === undefined ? 'local' : v.mode;
80
- if (mode !== 'local' && mode !== 'cluster')
81
- throw new HubError('INVALID_OPTIONS');
82
- if (v.allowInCluster !== undefined && typeof v.allowInCluster !== 'boolean')
83
- throw new HubError('INVALID_OPTIONS');
84
- const cluster = mode === 'cluster';
85
- // Cluster mode shares state through Redis and authenticates peers with the secret.
86
- if (cluster && (v.namespace === undefined || v.serverId === undefined))
87
- throw new HubError('INVALID_OPTIONS');
88
- if (cluster && v.redisConnection === undefined)
89
- throw new HubError('REDIS_REQUIRED');
90
- if ((cluster || v.secret !== undefined) &&
91
- (typeof v.secret !== 'string' ||
92
- Buffer.byteLength(v.secret) < 32 ||
93
- Buffer.byteLength(v.secret) > 256))
94
- throw new HubError('SECRET_REQUIRED');
95
- const optional = (key, fallback) => (v[key] === undefined ? fallback : id(key));
96
- const leaseMs = num('leaseMs', 3000, 500, 60000), pollMs = num('pollMs', 500, 25, 10000), ownerTtlMs = num('ownerTtlMs', 15000, 1500, 120000);
97
- if (pollMs * 3 > leaseMs || ownerTtlMs < leaseMs * 3)
98
- throw new HubError('INVALID_OPTIONS');
99
- const maxFrameBytes = num('maxFrameBytes', 1048576, 16384, 4194304), maxPayloadBytes = num('maxPayloadBytes', 65536, 1, 262144);
100
- if (Math.ceil(maxPayloadBytes / 3) * 4 + 8192 > maxFrameBytes)
101
- throw new HubError('INVALID_OPTIONS');
102
- return {
103
- mode,
104
- allowInCluster: v.allowInCluster === true,
105
- namespace: optional('namespace', 'local'),
106
- serverId: optional('serverId', 'local'),
107
- redisConnection: optional('redisConnection'),
108
- natsConnection: optional('natsConnection'),
109
- secret: typeof v.secret === 'string' ? v.secret : '',
110
- host: host('host', '127.0.0.1'),
111
- advertiseHost: host('advertiseHost', '127.0.0.1'),
112
- port: num('port', 0, 0, 65535),
113
- leaseMs,
114
- pollMs,
115
- ownerTtlMs,
116
- startupMs: num('startupMs', 15000, 1000, 120000),
117
- maxFrameBytes,
118
- maxPayloadBytes,
119
- maxConnections: num('maxConnections', 128, 1, 4096),
120
- maxOwners: num('maxOwners', 64, 1, 1024),
121
- maxTotalConnections: num('maxTotalConnections', 8192, 1, 100000),
122
- maxPending: num('maxPending', 128, 1, 4096),
123
- queueBytes: num('queueBytes', 4194304, maxFrameBytes, 67108864),
124
- // Not validated: the value is ignored whatever it is.
125
- removedOptions: Object.freeze(REMOVED_OPTIONS.filter((key) => v[key] !== undefined)),
126
- };
116
+ return options.parse(input ?? {}, { plugin: 'dokebi-websocket-hub' });
127
117
  }
@@ -1,8 +1,8 @@
1
1
  import { randomUUID } from 'node:crypto';
2
2
  import { createConnection } from 'node:net';
3
3
  import { ConsoleLogger } from '@dokebi/core';
4
+ import { diagnostics } from '@dokebi/core/libraries';
4
5
  import { EventQueue } from './event-queue.js';
5
- import { errorCode, LogThrottle } from './log.js';
6
6
  import { array, epoch, identifier, matches, metadata, PROTOCOL, payload, query, record, records, sequence, } from './protocol.js';
7
7
  import { HubError, } from './types.js';
8
8
  import { Wire } from './wire.js';
@@ -54,8 +54,8 @@ export class PeerClient {
54
54
  logger = new ConsoleLogger()) {
55
55
  this.options = options;
56
56
  this.logger = logger;
57
- this.events = new EventQueue(options.maxPending, options.queueBytes);
58
- this.#throttle = new LogThrottle(logger);
57
+ this.events = new EventQueue(options.maxPending, options.maxPendingBytes);
58
+ this.#throttle = new diagnostics.Repeats({ logger });
59
59
  }
60
60
  get ready() {
61
61
  return this.#ready && !this.#closing && !!this.#wire && !this.#wire.socket.destroyed;
@@ -68,7 +68,7 @@ export class PeerClient {
68
68
  }
69
69
  #fail(error) {
70
70
  if (this.#ready) {
71
- const code = error instanceof HubError ? error.code : errorCode(error, 'UNKNOWN');
71
+ const code = error instanceof HubError ? error.code : diagnostics.errorCode(error, 'UNKNOWN');
72
72
  // RECOVERING and CLOSED are this server's own decisions (reconnect, shutdown); any other
73
73
  // cause (revision gap, stale leader, socket closed) is a failure.
74
74
  if (code === 'RECOVERING' || code === 'CLOSED' || this.#leaving || this.#leaderLeaving)
@@ -77,7 +77,7 @@ export class PeerClient {
77
77
  leader: this.#leader?.serverId ?? null,
78
78
  });
79
79
  else
80
- this.#throttle.report('error', 'Hub connection dropped', code, error, {
80
+ this.#throttle.log('error', 'Hub connection dropped', code, error, {
81
81
  leader: this.#leader?.serverId ?? null,
82
82
  });
83
83
  }
@@ -118,7 +118,7 @@ export class PeerClient {
118
118
  // error as the cause. Only a connection that was up is reported here at error.
119
119
  let established = false;
120
120
  let socketError;
121
- const wire = new Wire(socket, this.options.maxFrameBytes, this.options.queueBytes, (f) => {
121
+ const wire = new Wire(socket, this.options.maxFrameBytes, this.options.maxPendingBytes, (f) => {
122
122
  if (this.#wire !== wire)
123
123
  return;
124
124
  try {
@@ -132,13 +132,13 @@ export class PeerClient {
132
132
  this.#fail(new HubError('DISCONNECTED', socketError === undefined ? undefined : { cause: socketError }));
133
133
  }, (code, error) => {
134
134
  if (established) {
135
- this.#throttle.report('error', 'Hub peer connection failed', code, error, {
135
+ this.#throttle.log('error', 'Hub peer connection failed', code, error, {
136
136
  leader: leader.serverId,
137
137
  });
138
138
  return;
139
139
  }
140
140
  socketError = error;
141
- this.#throttle.report('debug', 'Hub peer connection failed before it was established', code, error, { leader: leader.serverId });
141
+ this.#throttle.log('debug', 'Hub peer connection failed before it was established', code, error, { leader: leader.serverId });
142
142
  });
143
143
  this.#wire = wire;
144
144
  const timer = setTimeout(() => socket.destroy(new Error('Connect timeout')), this.options.leaseMs);
@@ -162,7 +162,7 @@ export class PeerClient {
162
162
  owner: this.ownerEpoch,
163
163
  session,
164
164
  serverId: this.options.serverId,
165
- secret: this.options.secret,
165
+ secret: this.options.secret ?? '',
166
166
  connections: [...this.#owned.values()],
167
167
  }));
168
168
  }
@@ -229,7 +229,7 @@ export class PeerClient {
229
229
  * versions, once per interval: the hub keeps retrying until every server runs the same version.
230
230
  */
231
231
  #protocolMismatch(leader, theirs, error) {
232
- this.#throttle.report('error', 'Hub protocol differs from the leader; retrying', 'PROTOCOL_MISMATCH', error, {
232
+ this.#throttle.log('error', 'Hub protocol differs from the leader; retrying', 'PROTOCOL_MISMATCH', error, {
233
233
  protocol: PROTOCOL,
234
234
  leaderProtocol: typeof theirs === 'number' ? theirs : null,
235
235
  leader: leader.serverId,
@@ -321,7 +321,7 @@ export class PeerClient {
321
321
  // of the queue stays for presence and kicks, which cannot be dropped.
322
322
  if (event.kind === 'message') {
323
323
  if (!this.events.offer(event, 0.5))
324
- this.#throttle.report('warn', 'Hub message dropped; event queue full', 'MESSAGE_DROPPED', undefined, {
324
+ this.#throttle.log('warn', 'Hub message dropped; event queue full', 'MESSAGE_DROPPED', undefined, {
325
325
  id,
326
326
  connections: connections.length,
327
327
  });
@@ -523,7 +523,7 @@ export class PeerClient {
523
523
  if (!this.ready)
524
524
  return Promise.reject(new HubError('RECOVERING'));
525
525
  if (this.#broadcasts >= this.options.maxPending) {
526
- this.#throttle.report('debug', 'Hub broadcast refused; too many in flight', 'BUSY', undefined, {
526
+ this.#throttle.log('debug', 'Hub broadcast refused; too many in flight', 'BUSY', undefined, {
527
527
  inFlight: this.#broadcasts,
528
528
  });
529
529
  return Promise.reject(new HubError('BUSY'));
@@ -552,7 +552,7 @@ export class PeerClient {
552
552
  (NOT_LEADER.has(code) || code === 'DISCONNECTED' || code === 'BACKPRESSURE'))
553
553
  throw new HubError('RECOVERING', { cause: error });
554
554
  if (code === 'OUTCOME_UNKNOWN')
555
- this.#throttle.report('debug', 'Hub broadcast outcome unknown; not resent', 'OUTCOME_UNKNOWN', error);
555
+ this.#throttle.log('debug', 'Hub broadcast outcome unknown; not resent', 'OUTCOME_UNKNOWN', error);
556
556
  throw error;
557
557
  })
558
558
  .finally(() => {
package/dist/protocol.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { types } from 'node:util';
2
- import { integer, keys, object } from './options.js';
3
2
  import { HubError } from './types.js';
3
+ import { integer, keys, object } from './values.js';
4
4
  /**
5
5
  * Version of the frames hub servers exchange, sent in hello (D-0057). 2: broadcasts without
6
6
  * client ACKs (no `accepted`, `ack` or resend). A leader refuses another version with
@@ -5,8 +5,8 @@
5
5
  import { resolve } from 'node:path';
6
6
  import { parseArgs } from 'node:util';
7
7
  import { Application, ConsoleLogger, loadConfig } from '@dokebi/core';
8
+ import { diagnostics } from '@dokebi/core/libraries';
8
9
  import { createPlugin as createRedis } from '@dokebi/redis';
9
- import { errorText } from './log.js';
10
10
  import { parseOptions } from './options.js';
11
11
  import { hubStatus } from './status.js';
12
12
  import { HubStore } from './store.js';
@@ -74,12 +74,12 @@ async function main() {
74
74
  }
75
75
  catch (error) {
76
76
  // Reported as `unreachable` (exit code 1); the cause goes to stderr, stdout stays parseable.
77
- process.stderr.write(`Redis unreachable (code STATUS_UNREACHABLE): ${errorText(error)}\n`);
77
+ process.stderr.write(`Redis unreachable (code STATUS_UNREACHABLE): ${diagnostics.describeError(error)}\n`);
78
78
  lease = 'unreachable';
79
79
  }
80
80
  finally {
81
81
  await app.stop().catch((error) => {
82
- process.stderr.write(`Redis client stop failed (code STOP_FAILED): ${errorText(error)}\n`);
82
+ process.stderr.write(`Redis client stop failed (code STOP_FAILED): ${diagnostics.describeError(error)}\n`);
83
83
  });
84
84
  }
85
85
  // This process is not a hub: state/role describe the asker, so they are left neutral.
package/dist/status.d.ts CHANGED
@@ -1,4 +1,5 @@
1
- import type { HubApi, HubLease, HubStatus } from './types.js';
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
- /** In-process nonce store for local mode: correct for one process only (`shared: false`). */
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
- constructor(max?: number);
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
  }