@cero-base/core 3.5.0 → 3.6.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.
@@ -1,12 +1,12 @@
1
1
  // This file is autogenerated by the hyperschema compiler
2
- // Schema Version: 4
2
+ // Schema Version: 5
3
3
  /* eslint-disable camelcase */
4
4
  /* eslint-disable quotes */
5
5
  /* eslint-disable space-before-function-paren */
6
6
 
7
7
  import { c } from 'hyperschema/runtime'
8
8
 
9
- const VERSION = 4
9
+ const VERSION = 5
10
10
 
11
11
  // eslint-disable-next-line no-unused-vars
12
12
  let version = VERSION
@@ -356,6 +356,65 @@ const encoding9 = {
356
356
  }
357
357
  }
358
358
 
359
+ // @cero/call-hello
360
+ const encoding10 = {
361
+ preencode(state, m) {
362
+ c.uint.preencode(state, m.version)
363
+ c.uint.preencode(state, m.timestamp)
364
+ },
365
+ encode(state, m) {
366
+ c.uint.encode(state, m.version)
367
+ c.uint.encode(state, m.timestamp)
368
+ },
369
+ decode(state) {
370
+ const r0 = c.uint.decode(state)
371
+ const r1 = c.uint.decode(state)
372
+
373
+ return {
374
+ version: r0,
375
+ timestamp: r1
376
+ }
377
+ }
378
+ }
379
+
380
+ // @cero/call-open
381
+ const encoding11 = {
382
+ preencode(state, m) {
383
+ c.uint.preencode(state, m.alias)
384
+ },
385
+ encode(state, m) {
386
+ c.uint.encode(state, m.alias)
387
+ },
388
+ decode(state) {
389
+ const r0 = c.uint.decode(state)
390
+
391
+ return {
392
+ alias: r0
393
+ }
394
+ }
395
+ }
396
+
397
+ // @cero/call-signal
398
+ const encoding12 = {
399
+ preencode(state, m) {
400
+ c.uint.preencode(state, m.type)
401
+ c.string.preencode(state, m.sdp)
402
+ },
403
+ encode(state, m) {
404
+ c.uint.encode(state, m.type)
405
+ c.string.encode(state, m.sdp)
406
+ },
407
+ decode(state) {
408
+ const r0 = c.uint.decode(state)
409
+ const r1 = c.string.decode(state)
410
+
411
+ return {
412
+ type: r0,
413
+ sdp: r1
414
+ }
415
+ }
416
+ }
417
+
359
418
  function setVersion(v) {
360
419
  version = v
361
420
  }
@@ -399,6 +458,12 @@ function getEncoding(name) {
399
458
  return encoding8
400
459
  case '@cero/pass':
401
460
  return encoding9
461
+ case '@cero/call-hello':
462
+ return encoding10
463
+ case '@cero/call-open':
464
+ return encoding11
465
+ case '@cero/call-signal':
466
+ return encoding12
402
467
  default:
403
468
  throw new Error('Encoder not found ' + name)
404
469
  }
@@ -1,5 +1,5 @@
1
1
  {
2
- "version": 4,
2
+ "version": 5,
3
3
  "schema": [
4
4
  {
5
5
  "name": "link",
@@ -331,6 +331,60 @@
331
331
  "version": 4
332
332
  }
333
333
  ]
334
+ },
335
+ {
336
+ "name": "call-hello",
337
+ "namespace": "cero",
338
+ "compact": true,
339
+ "flagsPosition": -1,
340
+ "fields": [
341
+ {
342
+ "name": "version",
343
+ "required": true,
344
+ "type": "uint",
345
+ "version": 5
346
+ },
347
+ {
348
+ "name": "timestamp",
349
+ "required": true,
350
+ "type": "uint",
351
+ "version": 5
352
+ }
353
+ ]
354
+ },
355
+ {
356
+ "name": "call-open",
357
+ "namespace": "cero",
358
+ "compact": true,
359
+ "flagsPosition": -1,
360
+ "fields": [
361
+ {
362
+ "name": "alias",
363
+ "required": true,
364
+ "type": "uint",
365
+ "version": 5
366
+ }
367
+ ]
368
+ },
369
+ {
370
+ "name": "call-signal",
371
+ "namespace": "cero",
372
+ "compact": false,
373
+ "flagsPosition": -1,
374
+ "fields": [
375
+ {
376
+ "name": "type",
377
+ "required": true,
378
+ "type": "uint",
379
+ "version": 5
380
+ },
381
+ {
382
+ "name": "sdp",
383
+ "required": true,
384
+ "type": "string",
385
+ "version": 5
386
+ }
387
+ ]
334
388
  }
335
389
  ]
336
390
  }
@@ -56,6 +56,8 @@ export class Mailbox extends ReadyResource {
56
56
  this.onerror = onerror
57
57
  /** @private */
58
58
  this._resources = new Set() // inboxes, and posts not read yet
59
+ /** @private */
60
+ this._erasing = new Set()
59
61
  }
60
62
 
61
63
  /**
@@ -81,13 +83,13 @@ export class Mailbox extends ReadyResource {
81
83
 
82
84
  /** @private */
83
85
  async _open() {
84
- await this.network.ready()
85
- // at any address, one received at again or not: handled rows that aged go, and a core its
86
- // inbox had to leave as it closed is erased
86
+ // at any address, one received at again or not: handled rows that aged go, and a core its inbox
87
+ // had to leave as it closed is erased before the network is up, so no peer reopens it mid-erase
87
88
  for (const mail of await this.inbox.list()) {
88
89
  if (aged(mail)) await this.inbox.del(mail.id)
89
90
  else if (mail.handled && mail.fetched) await this._owed(mail)
90
91
  }
92
+ await this.network.ready()
91
93
  for (const mail of await this.outbox.list()) this._deliver(mail)
92
94
  }
93
95
 
@@ -95,7 +97,7 @@ export class Mailbox extends ReadyResource {
95
97
  async _close() {
96
98
  const open = [...this._resources]
97
99
  this._resources.clear()
98
- await Promise.allSettled(open.map((resource) => resource.close()))
100
+ await Promise.allSettled([...open.map((resource) => resource.close()), ...this._erasing])
99
101
  }
100
102
 
101
103
  /**
@@ -181,9 +183,16 @@ export class Mailbox extends ReadyResource {
181
183
  .catch(safetyCatch)
182
184
  }
183
185
 
186
+ // none once closing, and close waits for one under way: its store closes after it
184
187
  /** @private */
185
- _erase(key) {
186
- return erase(this.network.store, key, () => !this.closing)
188
+ async _erase(key) {
189
+ const erasing = erase(this.network.store, key, () => !this.closing)
190
+ this._erasing.add(erasing)
191
+ try {
192
+ return await erasing
193
+ } finally {
194
+ this._erasing.delete(erasing)
195
+ }
187
196
  }
188
197
 
189
198
  // an erase its inbox had to leave, done once and then no longer owed
@@ -41,8 +41,8 @@ export class Discovery {
41
41
  /** @private */
42
42
  this._destroyed = false
43
43
  this._pin(pin)
44
- // opening counts as a touch
45
- this.touch()
44
+ // an open ranks it first, and takes no slot from a topic in use
45
+ this._rank(stamp())
46
46
  }
47
47
 
48
48
  /** @returns {Session} */
@@ -90,9 +90,21 @@ export class Discovery {
90
90
  await this.network._rotate()
91
91
  }
92
92
 
93
- /** Rank the topic first in the rotation, as just used. */
93
+ /** The topic was just used: it ranks first, and announces from now until `idle` ms after its last use, slot or not. */
94
94
  touch() {
95
95
  this._rank(stamp())
96
+ this.network._use(this.entry)
97
+ }
98
+
99
+ /**
100
+ * The devices that held the topic before, by their network keys: each is dialed by its key whenever the
101
+ * topic is on the network, whether it announces the topic or not.
102
+ *
103
+ * @param {Uint8Array[]} keys
104
+ */
105
+ know(keys) {
106
+ this.entry.known = keys
107
+ this.network._dial(this.entry)
96
108
  }
97
109
 
98
110
  /** Rank the topic last: it keeps a slot only while one is spare. */
@@ -127,9 +139,8 @@ export class Discovery {
127
139
  _pin(pinned) {
128
140
  if (pinned === this._pinned) return
129
141
  this._pinned = pinned
130
- if (pinned && this.entry.pins++ === 0) this.session.pin()
131
- if (!pinned && --this.entry.pins === 0) this.session.unpin()
132
- this.network._refresh()
142
+ this.entry.pins += pinned ? 1 : -1
143
+ this.network._apply(this.entry)
133
144
  }
134
145
 
135
146
  /** @private */
@@ -17,6 +17,8 @@ import { Discovery } from './discovery.js'
17
17
  const SILENT_TIMEOUT = 3000
18
18
  // the replicator runs a failed query again only in 10 min: after these, then the last over and over, while it keeps failing
19
19
  const RELOOKUPS = [1000, 5000, 20000, 60000]
20
+ const DIALED = 30
21
+ const REDIAL = 1000
20
22
 
21
23
  function toKey(k) {
22
24
  return typeof k === 'string' ? decodeKey(k) : k
@@ -36,7 +38,7 @@ export function channelTopic(topic, channel) {
36
38
  * @property {import('corestore')} store Corestore; every connection replicates it, so every core it holds rides every peer.
37
39
  * @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached database/blob core is mirrored through them for offline sync.
38
40
  * @property {(err: Error) => void} [onerror] Background-task error handler.
39
- * @property {{ active?: number, idle?: number }} [presence] The budget for topics in the rotation: how many announce at once, and the ms one keeps its slot before a touched one may take it.
41
+ * @property {{ active?: number, idle?: number, known?: number, connections?: number }} [presence] The budget for topics in the rotation: how many announce at once besides the ones in use, and the ms a topic keeps announcing after its last use, or keeps a slot. `known` is how many devices a database remembers to dial by their keys, 0 for none. `connections` is how many connections the network keeps at once: a device that dials in past it is told to try later.
40
42
  *
41
43
  * @typedef {object} Entry One replicator session per topic, shared by every join of it.
42
44
  * @property {string} id
@@ -44,6 +46,10 @@ export function channelTopic(topic, channel) {
44
46
  * @property {import('corestore')} store The store session the replicator session lives on.
45
47
  * @property {number} refs Joins holding the topic.
46
48
  * @property {number} pins Joins pinning it.
49
+ * @property {number} used When it was last touched.
50
+ * @property {ReturnType<typeof setTimeout> | null} held Set while a touch keeps it announcing.
51
+ * @property {Uint8Array[]} known Network keys of devices that held the topic before.
52
+ * @property {number} dialed When they were last dialed.
47
53
  */
48
54
 
49
55
  /**
@@ -72,8 +78,11 @@ export class Network extends ReadyResource {
72
78
  this.store = store
73
79
  /** @type {Uint8Array[]} */
74
80
  this.mirrors = (mirrors || []).map(toKey)
75
- /** @type {{ active: number, idle: number }} */
76
- this.presence = { active: 8, idle: 30_000, ...presence }
81
+ /** @type {{ active: number, idle: number, known: number, connections: number }} */
82
+ this.presence = { active: 8, idle: 30_000, known: 8, connections: 40 }
83
+ for (const [name, value] of Object.entries(presence || {})) {
84
+ if (value !== undefined) this.presence[name] = value
85
+ }
77
86
 
78
87
  /** @private */
79
88
  this._replicator = null
@@ -142,6 +151,9 @@ export class Network extends ReadyResource {
142
151
  dht,
143
152
  slots: this.presence.active,
144
153
  minActiveTime: this.presence.idle,
154
+ maxConnections: this.presence.connections,
155
+ // it dials the peers it finds up to this many, or up to the cap when that is lower
156
+ minConnections: Math.min(DIALED, this.presence.connections),
145
157
  // a join owns its topic until it is destroyed
146
158
  gcIdleTime: Infinity,
147
159
  // dial a peer the moment it is found, where the replicator waits up to 500 ms
@@ -156,6 +168,7 @@ export class Network extends ReadyResource {
156
168
  if (!dht.online) return
157
169
  // the queries sent while it was away failed
158
170
  this._watch(this._lookup()).catch(safetyCatch)
171
+ this._redial()
159
172
  // a tick later: the dht's own wake-up in this event would clear a refresh made now
160
173
  setTimeout(() => this.closing || rep.server.refresh(), 0)
161
174
  })
@@ -328,6 +341,7 @@ export class Network extends ReadyResource {
328
341
  await this._blindPeering?.resume()
329
342
  // the queries the replicator runs at resume fail when they go out before the network is back
330
343
  this._watch(this._active()).catch(safetyCatch)
344
+ this._redial()
331
345
  this.emit('resume')
332
346
  }
333
347
 
@@ -361,7 +375,18 @@ export class Network extends ReadyResource {
361
375
  // a store session per topic: the root store collects no listener per topic
362
376
  const store = this.store.session()
363
377
  const session = this._replicator.join(store, key, { deferSwarming: false })
364
- entry = { id, session, store, refs: 0, pins: 0 }
378
+ const made = (entry = {
379
+ id,
380
+ session,
381
+ store,
382
+ refs: 0,
383
+ pins: 0,
384
+ used: 0,
385
+ held: null,
386
+ known: [],
387
+ dialed: 0
388
+ })
389
+ session.on('activate', () => this._dial(made))
365
390
  this._sessions.set(id, entry)
366
391
  }
367
392
  entry.refs++
@@ -442,6 +467,60 @@ export class Network extends ReadyResource {
442
467
  }
443
468
  }
444
469
 
470
+ // up at once, down only after idle: a topic just used does not wait for a slot, and one at the edge of the
471
+ // budget does not churn the DHT
472
+ /** @private */
473
+ _use(entry) {
474
+ entry.used = Date.now()
475
+ if (entry.held === null) {
476
+ this._hold(entry, this.presence.idle)
477
+ this._apply(entry)
478
+ }
479
+ // a topic in steady use, or pinned by a join, starts no more: the devices it knows are dialed again, a round a
480
+ // second at most
481
+ if (entry.used - entry.dialed >= REDIAL) this._dial(entry)
482
+ }
483
+
484
+ /** @private */
485
+ _hold(entry, ms) {
486
+ entry.held = setTimeout(() => {
487
+ const left = entry.used + this.presence.idle - Date.now()
488
+ if (left > 0) {
489
+ this._hold(entry, left)
490
+ } else {
491
+ entry.held = null
492
+ this._apply(entry)
493
+ }
494
+ }, ms)
495
+ entry.held.unref()
496
+ }
497
+
498
+ // pinned while a join pins it or a use holds it up
499
+ /** @private */
500
+ _apply(entry) {
501
+ const pinned = entry.pins > 0 || entry.held !== null
502
+ if (pinned === (entry.session.state === 'pinned')) return
503
+ if (pinned) entry.session.pin()
504
+ else entry.session.unpin()
505
+ this._refresh()
506
+ }
507
+
508
+ // a device that held the topic before is dialed by its key: its own slots may all be on other topics, so a
509
+ // lookup of this one finds nobody. The replicator has no public way to dial a key
510
+ /** @private */
511
+ _dial(entry) {
512
+ const dialer = this._replicator?.dialer
513
+ if (!dialer || !entry.session.active) return
514
+ const now = (entry.dialed = Date.now())
515
+ for (const publicKey of entry.known) dialer.seen({ publicKey }, entry.session.topic, now, true)
516
+ }
517
+
518
+ // the replicator drops a device it has not seen for 15 minutes, and a resume or a new address starts no topic
519
+ /** @private */
520
+ _redial() {
521
+ for (const entry of this._sessions.values()) this._dial(entry)
522
+ }
523
+
445
524
  // an announce starts when the rotation runs, and only once the server listens
446
525
  /** @private */
447
526
  async _settle(session) {
@@ -0,0 +1,95 @@
1
+ import EventEmitter from 'events';
2
+ /**
3
+ * A signal as it crosses: `INVALID` for what is no offer or answer, or is over 64 KiB.
4
+ *
5
+ * @param {{ type: 'offer' | 'answer', sdp: string }} signal
6
+ * @returns {{ type: number, sdp: string }}
7
+ */
8
+ export declare function encode(signal: {
9
+ type: 'offer' | 'answer';
10
+ sdp: string;
11
+ }): {
12
+ type: number;
13
+ sdp: string;
14
+ };
15
+ /**
16
+ * A local UDP port for one call over one open connection: what is sent to `port` from this host
17
+ * reaches the bridge of the same `id` on the other end, which hands it to the local port that last
18
+ * sent to it. Media goes as it is, may be dropped and never waits behind other media. Signals are
19
+ * WebRTC descriptions, in order.
20
+ */
21
+ export declare class Bridge extends EventEmitter {
22
+ /** @type {import('@hyperswarm/secret-stream')} */
23
+ stream: import('@hyperswarm/secret-stream');
24
+ id: Uint8Array<ArrayBufferLike>;
25
+ /** This side's alias, at the head of each datagram it sends. */
26
+ alias: number;
27
+ /** The other side's, -1 until the channel opens. */
28
+ remote: number;
29
+ opened: boolean;
30
+ /** The other end routes this side's datagrams: media flows. */
31
+ routed: boolean;
32
+ closed: boolean;
33
+ /** The local port media last came from; 0 before any. */
34
+ sender: number;
35
+ /** @type {import('udx-native/lib/socket.js')} */
36
+ socket: import('udx-native/lib/socket.js');
37
+ /** @type {number} The port to send media to. */
38
+ port: number;
39
+ /** @private */
40
+ _key;
41
+ /** @private */
42
+ _link;
43
+ /** @private */
44
+ _prefix;
45
+ /** @private */
46
+ _out;
47
+ /** @private */
48
+ _in;
49
+ /** @private */
50
+ _signals;
51
+ /** @private */
52
+ _closing;
53
+ /** @private */
54
+ _channel;
55
+ /** @private */
56
+ _mux;
57
+ /** @private */
58
+ _onclose;
59
+ /**
60
+ * @param {import('@hyperswarm/secret-stream')} stream An open connection.
61
+ * @param {{ id: Uint8Array, udx: import('udx-native') }} opts `id` names the call on both ends; `udx` makes the socket, the DHT's.
62
+ */
63
+ constructor(stream: import('@hyperswarm/secret-stream'), { id, udx }: {
64
+ id: Uint8Array;
65
+ udx: import('udx-native');
66
+ });
67
+ /**
68
+ * Send a description to the other end, in order; kept until the channel opens.
69
+ *
70
+ * @param {{ type: 'offer' | 'answer', sdp: string }} signal
71
+ * @returns {void}
72
+ */
73
+ signal(signal: {
74
+ type: 'offer' | 'answer';
75
+ sdp: string;
76
+ }): void;
77
+ /** @returns {Promise<void>} Resolves once the socket is closed. */
78
+ close(): Promise<void>;
79
+ /** @private */
80
+ private _connect;
81
+ /** @private */
82
+ private _signal;
83
+ /** @private */
84
+ private _open;
85
+ /** @private */
86
+ private _routed;
87
+ /** @private */
88
+ private _outbound;
89
+ /** @private */
90
+ private _follow;
91
+ /** @private */
92
+ private _inbound;
93
+ /** @private */
94
+ private _forward;
95
+ }
@@ -0,0 +1,91 @@
1
+ import ReadyResource from 'ready-resource';
2
+ import { Peers } from './peers.js';
3
+ import { Bridge } from './bridge.js';
4
+ export { Peers, Bridge };
5
+ export type CallOpts = {
6
+ /**
7
+ * The DHT to connect on, the network's.
8
+ */
9
+ dht: import('hyperdht');
10
+ /**
11
+ * This device's call key pair: the key the others hold.
12
+ */
13
+ keyPair: {
14
+ publicKey: Uint8Array;
15
+ secretKey: Uint8Array;
16
+ };
17
+ /**
18
+ * Names the call on every device in it.
19
+ */
20
+ id: string | Uint8Array;
21
+ /**
22
+ * Blind relay keys, the network's.
23
+ */
24
+ relayThrough?: Array<string | Uint8Array> | null;
25
+ };
26
+ /**
27
+ * @typedef {object} CallOpts
28
+ * @property {import('hyperdht')} dht The DHT to connect on, the network's.
29
+ * @property {{ publicKey: Uint8Array, secretKey: Uint8Array }} keyPair This device's call key pair: the key the others hold.
30
+ * @property {string | Uint8Array} id Names the call on every device in it.
31
+ * @property {Array<string | Uint8Array> | null} [relayThrough] Blind relay keys, the network's.
32
+ */
33
+ /**
34
+ * The media transport of one call: a connection to each device in it and, over each, a local port
35
+ * for the app's WebRTC to send to. Events: `'peer'(key, port)` when a device's port opens or
36
+ * changes, also for the ones already open when a listener is added; `'peer-close'(key)` once no
37
+ * connection to it is open or opening; `'signal'(key, { type, sdp })`.
38
+ */
39
+ export declare class Call extends ReadyResource {
40
+ /** @private */
41
+ _peers;
42
+ /** @type {import('hyperdht')} */
43
+ dht: import('hyperdht');
44
+ id: Uint8Array<ArrayBufferLike>;
45
+ /** @type {Map<string, number>} The local port of each device, by key in hex, from its `'peer'` to its `'peer-close'`. */
46
+ peers: Map<string, number>;
47
+ /** @private @type {Map<Bridge, string>} Oldest first. */
48
+ _bridges;
49
+ /** @param {CallOpts} opts */
50
+ constructor({ dht, keyPair, id, relayThrough }?: CallOpts);
51
+ /** @returns {Map<string, import('@hyperswarm/secret-stream')>} The open connection to each device. */
52
+ get connections(): Map<string, import('@hyperswarm/secret-stream')>;
53
+ /** @private */
54
+ private _open;
55
+ /** @private */
56
+ private _close;
57
+ /**
58
+ * The devices to hold: the call's other participants, by their call keys.
59
+ *
60
+ * @param {Array<string | Uint8Array>} keys
61
+ * @returns {void}
62
+ */
63
+ set(keys: Array<string | Uint8Array>): void;
64
+ /**
65
+ * Send a WebRTC description to a device, on its newest connection; dropped when there is none.
66
+ *
67
+ * @param {string | Uint8Array} key
68
+ * @param {{ type: 'offer' | 'answer', sdp: string }} signal
69
+ * @returns {void}
70
+ */
71
+ signal(key: string | Uint8Array, signal: {
72
+ type: 'offer' | 'answer';
73
+ sdp: string;
74
+ }): void;
75
+ /** @returns {Promise<void>} */
76
+ suspend(): Promise<void>;
77
+ /** @returns {Promise<void>} */
78
+ resume(): Promise<void>;
79
+ /** @private */
80
+ private _bridge;
81
+ /** @private */
82
+ private _heard;
83
+ /** @private */
84
+ private _current;
85
+ /** @private */
86
+ private _newest;
87
+ /** @private */
88
+ private _announce;
89
+ /** @private */
90
+ private _replay;
91
+ }