@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.
@@ -0,0 +1,489 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { createConnection } from 'node:net';
3
+ import { setTimeout as delay } from 'node:timers/promises';
4
+ import { EventQueue } from './event-queue.js';
5
+ import { array, epoch, identifier, matches, metadata, payload, query, record, records, sequence, } from './protocol.js';
6
+ import { HubError, } from './types.js';
7
+ import { Wire } from './wire.js';
8
+ export class PeerClient {
9
+ options;
10
+ ownerEpoch = randomUUID();
11
+ #session;
12
+ /** Session of the last hello; the owner record in Redis carries the same value. */
13
+ get session() {
14
+ return this.#session;
15
+ }
16
+ events;
17
+ #owned = new Map();
18
+ #tokens = new Map();
19
+ #peers = new Map();
20
+ #revision = 0;
21
+ #broadcasts = 0;
22
+ /** Unfinished broadcasts by message id; the leader's recipient list is added when accepted. */
23
+ #outgoing = new Map();
24
+ #acks = new Map();
25
+ #ackBytes = 0;
26
+ #ackTimer;
27
+ #beforeReady = [];
28
+ #wire;
29
+ #leader;
30
+ #ready = false;
31
+ #closing = false;
32
+ #next = 0;
33
+ #pending = new Map();
34
+ #tail = Promise.resolve();
35
+ #queued = 0;
36
+ #connecting;
37
+ #readyWaiters = new Set();
38
+ /** Told why the connection to the leader was dropped (logged by the hub node). */
39
+ #onFail;
40
+ constructor(options, onFail = () => { }) {
41
+ this.options = options;
42
+ this.events = new EventQueue(options.maxPending, options.queueBytes);
43
+ this.#onFail = onFail;
44
+ }
45
+ get ready() {
46
+ return this.#ready && !this.#closing && !!this.#wire && !this.#wire.socket.destroyed;
47
+ }
48
+ get leader() {
49
+ return this.#leader;
50
+ }
51
+ get connections() {
52
+ return this.#owned;
53
+ }
54
+ #fail(error) {
55
+ if (this.#ready)
56
+ this.#onFail(error instanceof HubError ? error.code : 'UNKNOWN');
57
+ this.#ready = false;
58
+ this.#wire?.close();
59
+ for (const p of this.#pending.values()) {
60
+ clearTimeout(p.timer);
61
+ p.reject(error);
62
+ }
63
+ this.#pending.clear();
64
+ }
65
+ async connect(leader) {
66
+ if (this.#closing)
67
+ return;
68
+ if (this.#connecting)
69
+ return this.#connecting;
70
+ if (this.ready && this.#leader?.epoch === leader.epoch) {
71
+ const result = (await this.#rpc('ping'));
72
+ if (sequence(result.revision) > this.#revision)
73
+ this.#fail(new HubError('REVISION_GAP'));
74
+ return;
75
+ }
76
+ this.#connecting = this.#connect(leader).finally(() => {
77
+ this.#connecting = undefined;
78
+ });
79
+ return this.#connecting;
80
+ }
81
+ async #connect(leader) {
82
+ this.#fail(new HubError('RECOVERING'));
83
+ await this.#tail;
84
+ this.#beforeReady = [];
85
+ this.#leader = leader;
86
+ const socket = createConnection({ host: leader.host, port: leader.port });
87
+ const wire = new Wire(socket, this.options.maxFrameBytes, this.options.queueBytes, (f) => {
88
+ if (this.#wire !== wire)
89
+ return;
90
+ try {
91
+ this.#receive(f);
92
+ }
93
+ catch (error) {
94
+ this.#fail(error);
95
+ }
96
+ }, () => {
97
+ if (this.#wire === wire)
98
+ this.#fail(new HubError('DISCONNECTED'));
99
+ });
100
+ this.#wire = wire;
101
+ const timer = setTimeout(() => socket.destroy(new Error('Connect timeout')), this.options.leaseMs);
102
+ try {
103
+ await new Promise((resolve, reject) => {
104
+ socket.once('connect', resolve);
105
+ socket.once('error', reject);
106
+ });
107
+ }
108
+ finally {
109
+ clearTimeout(timer);
110
+ }
111
+ await this.#operation(async () => {
112
+ const session = randomUUID();
113
+ this.#session = session;
114
+ const value = (await this.#rpc('hello', {
115
+ owner: this.ownerEpoch,
116
+ session,
117
+ serverId: this.options.serverId,
118
+ secret: this.options.secret,
119
+ connections: [...this.#owned.values()],
120
+ }));
121
+ const peers = new Map();
122
+ for (const row of array(value.owners, this.options.maxOwners)) {
123
+ const pair = array(row, 2);
124
+ const owner = epoch(pair[0]);
125
+ peers.set(owner, records(pair[1], owner, this.options.maxConnections));
126
+ }
127
+ if (this.#wire !== wire || socket.destroyed || this.#closing)
128
+ throw new HubError('DISCONNECTED');
129
+ // The snapshot replaces the mirror at once; report each owner whose list differs, and
130
+ // owners that are gone, as presence events so consumers (websocket presence) resync after
131
+ // a reconnect or a leader change instead of keeping connections that left meanwhile.
132
+ const previous = this.#peers;
133
+ this.#peers = peers;
134
+ this.#revision = sequence(value.revision);
135
+ for (const [owner, connections] of peers)
136
+ if (JSON.stringify(previous.get(owner) ?? []) !== JSON.stringify(connections))
137
+ this.#resync(owner, connections);
138
+ for (const owner of previous.keys())
139
+ if (!peers.has(owner))
140
+ this.#resync(owner, []);
141
+ this.#ready = true;
142
+ for (const resolve of this.#readyWaiters)
143
+ resolve(true);
144
+ this.#readyWaiters.clear();
145
+ const buffered = this.#beforeReady;
146
+ this.#beforeReady = [];
147
+ for (const frame of buffered)
148
+ this.#receive(frame);
149
+ }, true);
150
+ }
151
+ #resync(owner, connections) {
152
+ try {
153
+ this.events.push({
154
+ kind: 'presence',
155
+ revision: this.#revision,
156
+ ownerEpoch: owner,
157
+ connections,
158
+ });
159
+ }
160
+ catch (error) {
161
+ this.events.finish(error);
162
+ this.#closing = true;
163
+ throw error;
164
+ }
165
+ }
166
+ #receive(f) {
167
+ if (f.epoch !== this.#leader?.epoch)
168
+ throw new HubError('STALE_LEADER');
169
+ if (f.kind === 'reply') {
170
+ const id = Number(f.id), pending = this.#pending.get(id);
171
+ if (!pending)
172
+ return;
173
+ this.#pending.delete(id);
174
+ clearTimeout(pending.timer);
175
+ if (f.ok === true)
176
+ pending.resolve(f.result);
177
+ else
178
+ pending.reject(new HubError(typeof f.code === 'string' ? f.code : 'PROTOCOL_ERROR'));
179
+ return;
180
+ }
181
+ if (f.kind === 'accepted') {
182
+ // D-0042: the leader keeps broadcasts in memory only. The recipient list it chose rides
183
+ // along when this broadcast is resent to the next leader.
184
+ const body = this.#outgoing.get(epoch(f.id));
185
+ if (body && body.recipients === undefined)
186
+ body.recipients = array(f.recipients, this.options.maxTotalConnections).map((key) => {
187
+ if (typeof key !== 'string' || !/^[A-Za-z0-9_-]{43}$/.test(key))
188
+ throw new HubError('PROTOCOL_ERROR');
189
+ return key;
190
+ });
191
+ return;
192
+ }
193
+ if (f.kind === 'presence') {
194
+ const rev = sequence(f.revision);
195
+ if (!this.#ready) {
196
+ if (this.#beforeReady.length >= this.options.maxPending)
197
+ throw new HubError('EVENT_OVERFLOW');
198
+ this.#beforeReady.push(f);
199
+ return;
200
+ }
201
+ if (rev !== this.#revision + 1)
202
+ throw new HubError('REVISION_GAP');
203
+ const owner = epoch(f.owner), values = records(f.connections, owner, this.options.maxConnections);
204
+ this.#revision = rev;
205
+ if (values.length)
206
+ this.#peers.set(owner, values);
207
+ else
208
+ this.#peers.delete(owner);
209
+ this.events.push({ kind: 'presence', revision: rev, ownerEpoch: owner, connections: values });
210
+ return;
211
+ }
212
+ const connections = array(f.connections, this.options.maxConnections).map(identifier), id = identifier(f.id);
213
+ let event;
214
+ if (f.kind === 'message')
215
+ event = {
216
+ kind: 'message',
217
+ id,
218
+ connections,
219
+ data: payload(f.data, this.options.maxPayloadBytes),
220
+ expiresAt: sequence(f.expiresAt),
221
+ };
222
+ else if (f.kind === 'kick')
223
+ event = { kind: 'kick', id, connections, code: Number(f.code), reason: identifier(f.reason) };
224
+ else
225
+ throw new HubError('PROTOCOL_ERROR');
226
+ try {
227
+ this.events.push(event);
228
+ }
229
+ catch (error) {
230
+ this.events.finish(error);
231
+ this.#closing = true;
232
+ throw error;
233
+ }
234
+ }
235
+ #rpc(op, body = {}, timeout = this.options.leaseMs) {
236
+ const wire = this.#wire;
237
+ if (!wire || wire.socket.destroyed)
238
+ return Promise.reject(new HubError('RECOVERING'));
239
+ if (this.#pending.size >= this.options.maxPending + (op === 'broadcast' ? 0 : 32))
240
+ return Promise.reject(new HubError('BUSY'));
241
+ const id = ++this.#next;
242
+ return new Promise((resolve, reject) => {
243
+ const timer = setTimeout(() => {
244
+ this.#pending.delete(id);
245
+ if (op !== 'broadcast')
246
+ this.#fail(new HubError('OUTCOME_UNKNOWN'));
247
+ reject(new HubError('OUTCOME_UNKNOWN'));
248
+ }, timeout);
249
+ this.#pending.set(id, { resolve, reject, timer });
250
+ try {
251
+ wire.send({ id, op, epoch: this.#leader?.epoch, ...body });
252
+ }
253
+ catch (error) {
254
+ clearTimeout(timer);
255
+ this.#pending.delete(id);
256
+ reject(error);
257
+ }
258
+ });
259
+ }
260
+ #operation(fn, allowRecovery = false) {
261
+ if (!allowRecovery && this.#queued >= this.options.maxPending)
262
+ return Promise.reject(new HubError('BUSY'));
263
+ this.#queued++;
264
+ const result = this.#tail.then(() => {
265
+ if (!allowRecovery && !this.ready)
266
+ throw new HubError('RECOVERING');
267
+ return fn();
268
+ });
269
+ this.#tail = result
270
+ .then(() => { }, () => { })
271
+ .finally(() => {
272
+ this.#queued--;
273
+ });
274
+ return result;
275
+ }
276
+ async #replace(id, value) {
277
+ const next = new Map(this.#owned);
278
+ if (value)
279
+ next.set(id, value);
280
+ else
281
+ next.delete(id);
282
+ if (next.size > this.options.maxConnections)
283
+ throw new HubError('CONNECTION_LIMIT');
284
+ await this.#rpc('set', { connections: [...next.values()] });
285
+ this.#owned.clear();
286
+ for (const [key, v] of next)
287
+ this.#owned.set(key, v);
288
+ }
289
+ register(input) {
290
+ return this.#operation(async () => {
291
+ const value = record(input, this.ownerEpoch);
292
+ if (this.#owned.has(value.connection))
293
+ throw new HubError('DUPLICATE_CONNECTION');
294
+ await this.#replace(value.connection, value);
295
+ const token = Symbol();
296
+ this.#tokens.set(value.connection, token);
297
+ let closed = false;
298
+ let closing;
299
+ const change = (fn) => this.#operation(async () => {
300
+ const current = this.#owned.get(value.connection);
301
+ if (closed || !current || this.#tokens.get(value.connection) !== token)
302
+ throw new HubError('UNKNOWN_CONNECTION');
303
+ const replacement = fn(current);
304
+ await this.#replace(value.connection, replacement);
305
+ if (!replacement) {
306
+ closed = true;
307
+ this.#tokens.delete(value.connection);
308
+ }
309
+ });
310
+ return Object.freeze({
311
+ identity: Object.freeze({ ownerEpoch: this.ownerEpoch, connection: value.connection }),
312
+ join: (room) => change((current) => record({ ...current, rooms: [...new Set([...current.rooms, identifier(room)])] }, this.ownerEpoch)),
313
+ leave: (room) => change((current) => record({ ...current, rooms: current.rooms.filter((x) => x !== identifier(room)) }, this.ownerEpoch)),
314
+ updateMetadata: (meta) => change((current) => record({ ...current, metadata: metadata(meta) }, this.ownerEpoch)),
315
+ close: () => (closing ??= this.#operation(async () => {
316
+ if (closed || this.#tokens.get(value.connection) !== token)
317
+ return;
318
+ closed = true;
319
+ this.#tokens.delete(value.connection);
320
+ this.#owned.delete(value.connection);
321
+ if (this.ready) {
322
+ try {
323
+ await this.#rpc('set', { connections: [...this.#owned.values()] });
324
+ }
325
+ catch (error) {
326
+ this.disconnect();
327
+ throw error;
328
+ }
329
+ }
330
+ }, true)),
331
+ });
332
+ });
333
+ }
334
+ list(input) {
335
+ if (!this.ready)
336
+ return Promise.reject(new HubError('RECOVERING'));
337
+ const filter = query(input);
338
+ return Promise.resolve(Object.freeze({
339
+ authorityEpoch: this.#leader?.epoch ?? '',
340
+ revision: this.#revision,
341
+ connections: Object.freeze([...this.#peers.values()].flat().filter((r) => matches(r, filter))),
342
+ }));
343
+ }
344
+ broadcast(input, data) {
345
+ if (!(data instanceof Uint8Array) || data.byteLength > this.options.maxPayloadBytes)
346
+ return Promise.reject(new HubError('INVALID_ARGUMENT'));
347
+ const filter = query(input), encoded = Buffer.from(data).toString('base64');
348
+ if (this.#broadcasts >= this.options.maxPending)
349
+ return Promise.reject(new HubError('BUSY'));
350
+ this.#broadcasts++;
351
+ const body = {
352
+ query: filter,
353
+ data: encoded,
354
+ messageId: randomUUID(),
355
+ expiresAt: Date.now() + this.options.deliveryTimeoutMs,
356
+ };
357
+ const expiresAt = body.expiresAt;
358
+ this.#outgoing.set(body.messageId, body);
359
+ return (async () => {
360
+ try {
361
+ while (!this.#closing && Date.now() < expiresAt) {
362
+ try {
363
+ if (this.ready)
364
+ return (await this.#rpc('broadcast', body, Math.max(1, expiresAt - Date.now())));
365
+ }
366
+ catch (error) {
367
+ if (!(error instanceof HubError) ||
368
+ ![
369
+ 'RECOVERING',
370
+ 'DISCONNECTED',
371
+ 'STALE_LEADER',
372
+ 'STALE_PEER',
373
+ 'STORE_UNAVAILABLE',
374
+ 'OUTCOME_UNKNOWN',
375
+ 'BUSY',
376
+ ].includes(error.code))
377
+ throw error;
378
+ }
379
+ await delay(Math.min(100, Math.max(1, expiresAt - Date.now())));
380
+ }
381
+ throw new HubError(this.#closing ? 'CLOSED' : 'DELIVERY_TIMEOUT');
382
+ }
383
+ finally {
384
+ this.#broadcasts--;
385
+ this.#outgoing.delete(body.messageId);
386
+ }
387
+ })();
388
+ }
389
+ acknowledge(id, connections) {
390
+ epoch(id);
391
+ if (this.#closing)
392
+ return;
393
+ if (!this.#acks.has(id) && this.#acks.size >= 256)
394
+ return; // The durable sender retries unacknowledged deliveries.
395
+ const selected = this.#acks.get(id) ?? new Set();
396
+ for (const connection of array(connections, this.options.maxConnections).map(identifier)) {
397
+ if (this.#owned.has(connection) &&
398
+ !selected.has(connection) &&
399
+ this.#ackBytes + Buffer.byteLength(connection) + 64 <= this.options.queueBytes) {
400
+ selected.add(connection);
401
+ this.#ackBytes += Buffer.byteLength(connection) + 64;
402
+ }
403
+ }
404
+ this.#acks.set(id, selected);
405
+ if (!this.#ackTimer)
406
+ this.#ackTimer = setTimeout(() => {
407
+ this.#ackTimer = undefined;
408
+ const acks = this.#acks;
409
+ this.#acks = new Map();
410
+ this.#ackBytes = 0;
411
+ if (!this.ready)
412
+ return;
413
+ // Split at the encoded frame boundary; oversize ACKs must not cause endless full-frame retries.
414
+ let batch = [], bytes = 256;
415
+ const flush = () => {
416
+ if (batch.length)
417
+ void this.#rpc('ack', { acks: batch }).catch(() => { });
418
+ batch = [];
419
+ bytes = 256;
420
+ };
421
+ for (const [id, connections] of acks) {
422
+ let row = { id, connections: [] };
423
+ for (const connection of connections) {
424
+ const size = Buffer.byteLength(JSON.stringify(connection)) + 1;
425
+ if (bytes + size + 128 > this.options.maxFrameBytes || batch.length >= 255) {
426
+ if (row.connections.length)
427
+ batch.push(row);
428
+ flush();
429
+ row = { id, connections: [] };
430
+ }
431
+ if (!row.connections.length)
432
+ bytes += 96;
433
+ row.connections.push(connection);
434
+ bytes += size;
435
+ }
436
+ if (row.connections.length)
437
+ batch.push(row);
438
+ }
439
+ flush();
440
+ }, 10);
441
+ }
442
+ kick(input, code = 4403, reason = 'Disconnected by hub') {
443
+ const filter = query(input);
444
+ return this.#operation(async () => (await this.#rpc('kick', { query: filter, code, reason })));
445
+ }
446
+ async close() {
447
+ if (this.#ackTimer)
448
+ clearTimeout(this.#ackTimer);
449
+ this.#acks.clear();
450
+ this.#ackBytes = 0;
451
+ if (this.#closing) {
452
+ this.#fail(new HubError('CLOSED'));
453
+ this.events.finish();
454
+ for (const resolve of [...this.#readyWaiters])
455
+ resolve(false);
456
+ return;
457
+ }
458
+ await this.#tail;
459
+ try {
460
+ if (this.ready)
461
+ await this.#rpc('bye');
462
+ }
463
+ finally {
464
+ this.#closing = true;
465
+ this.#fail(new HubError('CLOSED'));
466
+ this.events.finish();
467
+ for (const resolve of [...this.#readyWaiters])
468
+ resolve(false);
469
+ }
470
+ }
471
+ disconnect() {
472
+ this.#fail(new HubError('RECOVERING'));
473
+ }
474
+ whenReady(timeoutMs) {
475
+ if (this.ready)
476
+ return Promise.resolve(true);
477
+ if (this.#closing)
478
+ return Promise.resolve(false);
479
+ return new Promise((resolve) => {
480
+ const done = (ready) => {
481
+ clearTimeout(timer);
482
+ this.#readyWaiters.delete(done);
483
+ resolve(ready);
484
+ };
485
+ const timer = setTimeout(() => done(false), Math.max(0, timeoutMs));
486
+ this.#readyWaiters.add(done);
487
+ });
488
+ }
489
+ }
@@ -0,0 +1,13 @@
1
+ import { type HubQuery, type HubRecord } from './types.js';
2
+ export declare function encode(value: unknown, limit: number): Uint8Array;
3
+ export declare function decode(data: Uint8Array, limit: number): Record<string, unknown>;
4
+ export declare function identifier(value: unknown): string;
5
+ export declare function epoch(value: unknown): string;
6
+ export declare function array(value: unknown, limit: number): readonly unknown[];
7
+ export declare function metadata(value?: unknown): Readonly<Record<string, string>>;
8
+ export declare function record(value: unknown, ownerEpoch: string): HubRecord;
9
+ export declare function records(value: unknown, ownerEpoch: string, limit: number): readonly HubRecord[];
10
+ export declare function query(value: unknown): HubQuery;
11
+ export declare function matches(item: HubRecord, filter: HubQuery): boolean;
12
+ export declare function sequence(value: unknown): number;
13
+ export declare function payload(value: unknown, maxBytes: number): Uint8Array;
@@ -0,0 +1,141 @@
1
+ import { types } from 'node:util';
2
+ import { integer, keys, object } from './options.js';
3
+ import { HubError } from './types.js';
4
+ const decoder = new TextDecoder('utf-8', { fatal: true });
5
+ export function encode(value, limit) {
6
+ try {
7
+ const data = Buffer.from(JSON.stringify(value), 'utf8');
8
+ if (data.byteLength > limit)
9
+ throw new HubError('MESSAGE_TOO_LARGE');
10
+ return data;
11
+ }
12
+ catch (error) {
13
+ if (error instanceof HubError)
14
+ throw error;
15
+ throw new HubError('INVALID_ARGUMENT');
16
+ }
17
+ }
18
+ export function decode(data, limit) {
19
+ if (data.byteLength > limit)
20
+ throw new HubError('MESSAGE_TOO_LARGE');
21
+ try {
22
+ return object(JSON.parse(decoder.decode(data)));
23
+ }
24
+ catch {
25
+ throw new HubError('PROTOCOL_ERROR');
26
+ }
27
+ }
28
+ export function identifier(value) {
29
+ if (typeof value !== 'string' ||
30
+ value.length === 0 ||
31
+ Buffer.byteLength(value, 'utf8') > 256 ||
32
+ Buffer.from(value, 'utf8').toString('utf8') !== value)
33
+ throw new HubError('INVALID_ARGUMENT');
34
+ return value;
35
+ }
36
+ export function epoch(value) {
37
+ if (typeof value !== 'string' ||
38
+ !/^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$/.test(value))
39
+ throw new HubError('PROTOCOL_ERROR');
40
+ return value;
41
+ }
42
+ export function array(value, limit) {
43
+ if (types.isProxy(value) || !Array.isArray(value) || value.length > limit)
44
+ throw new HubError('INVALID_ARGUMENT');
45
+ if (Reflect.ownKeys(value).length !== value.length + 1)
46
+ throw new HubError('INVALID_ARGUMENT');
47
+ const output = [];
48
+ for (let index = 0; index < value.length; index += 1) {
49
+ const descriptor = Object.getOwnPropertyDescriptor(value, String(index));
50
+ if (descriptor === undefined || !('value' in descriptor) || !descriptor.enumerable)
51
+ throw new HubError('INVALID_ARGUMENT');
52
+ output.push(descriptor.value);
53
+ }
54
+ return output;
55
+ }
56
+ export function metadata(value = {}) {
57
+ const input = object(value);
58
+ const entries = Object.entries(input);
59
+ if (entries.length > 16)
60
+ throw new HubError('INVALID_ARGUMENT');
61
+ const result = Object.create(null);
62
+ for (const [key, item] of entries) {
63
+ if (Buffer.byteLength(identifier(key), 'utf8') > 64 ||
64
+ typeof item !== 'string' ||
65
+ Buffer.byteLength(item, 'utf8') > 1024 ||
66
+ Buffer.from(item, 'utf8').toString('utf8') !== item)
67
+ throw new HubError('INVALID_ARGUMENT');
68
+ Object.defineProperty(result, key, { value: item, enumerable: true });
69
+ }
70
+ encode(result, 4096);
71
+ return Object.freeze(result);
72
+ }
73
+ export function record(value, ownerEpoch) {
74
+ const input = object(value);
75
+ keys(input, ['ownerEpoch', 'tenant', 'member', 'connection', 'clientId', 'rooms', 'metadata']);
76
+ if (input.ownerEpoch !== undefined && input.ownerEpoch !== ownerEpoch)
77
+ throw new HubError('INVALID_ARGUMENT');
78
+ const rooms = input.rooms === undefined ? [] : array(input.rooms, 32).map(identifier);
79
+ if (new Set(rooms).size !== rooms.length)
80
+ throw new HubError('INVALID_ARGUMENT');
81
+ return Object.freeze({
82
+ ownerEpoch,
83
+ tenant: identifier(input.tenant),
84
+ member: identifier(input.member),
85
+ connection: identifier(input.connection),
86
+ ...(input.clientId === undefined ? {} : { clientId: identifier(input.clientId) }),
87
+ rooms: Object.freeze(rooms),
88
+ metadata: metadata(input.metadata),
89
+ });
90
+ }
91
+ export function records(value, ownerEpoch, limit) {
92
+ const output = array(value, limit).map((item) => record(item, ownerEpoch));
93
+ if (new Set(output.map((item) => item.connection)).size !== output.length)
94
+ throw new HubError('INVALID_ARGUMENT');
95
+ return Object.freeze(output);
96
+ }
97
+ export function query(value) {
98
+ const input = object(value);
99
+ keys(input, ['tenant', 'room', 'member', 'connection']);
100
+ let connection;
101
+ if (input.connection !== undefined) {
102
+ const item = object(input.connection);
103
+ keys(item, ['ownerEpoch', 'connection']);
104
+ connection = Object.freeze({
105
+ ownerEpoch: epoch(item.ownerEpoch),
106
+ connection: identifier(item.connection),
107
+ });
108
+ }
109
+ return Object.freeze({
110
+ tenant: identifier(input.tenant),
111
+ ...(input.room === undefined ? {} : { room: identifier(input.room) }),
112
+ ...(input.member === undefined ? {} : { member: identifier(input.member) }),
113
+ ...(connection === undefined ? {} : { connection }),
114
+ });
115
+ }
116
+ export function matches(item, filter) {
117
+ return (item.tenant === filter.tenant &&
118
+ (filter.room === undefined || item.rooms.includes(filter.room)) &&
119
+ (filter.member === undefined || item.member === filter.member) &&
120
+ (filter.connection === undefined ||
121
+ (item.ownerEpoch === filter.connection.ownerEpoch &&
122
+ item.connection === filter.connection.connection)));
123
+ }
124
+ export function sequence(value) {
125
+ try {
126
+ return integer(value, 0, Number.MAX_SAFE_INTEGER - 1);
127
+ }
128
+ catch {
129
+ throw new HubError('PROTOCOL_ERROR');
130
+ }
131
+ }
132
+ export function payload(value, maxBytes) {
133
+ if (typeof value !== 'string' ||
134
+ value.length > Math.ceil(maxBytes / 3) * 4 ||
135
+ !/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(value))
136
+ throw new HubError('INVALID_ARGUMENT');
137
+ const result = Buffer.from(value, 'base64');
138
+ if (result.byteLength > maxBytes || result.toString('base64') !== value)
139
+ throw new HubError('INVALID_ARGUMENT');
140
+ return result;
141
+ }
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};