@cero-base/core 3.4.1 → 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
  }
package/src/lib/utils.js CHANGED
@@ -191,6 +191,22 @@ function valueEq(a, b) {
191
191
  * @param {() => void} cb
192
192
  * @returns {(() => void) | undefined}
193
193
  */
194
+ /**
195
+ * Run `fn` once `prev` has ended, however it ended: one after the other. `fn` is awaited as it starts, so when
196
+ * it fails at once, as a write on a database that closed while it waited, the promise that rejects is the one the
197
+ * caller already holds. Returned from a `then`, it would be rejected for a turn with nobody holding it, and Bare
198
+ * reports that as uncaught when a stream is destroyed in that turn.
199
+ *
200
+ * @template T
201
+ * @param {Promise<unknown> | null | undefined} prev
202
+ * @param {() => Promise<T> | T} fn
203
+ * @returns {Promise<T>}
204
+ */
205
+ export async function inTurn(prev, fn) {
206
+ await prev?.catch(() => {})
207
+ return await fn()
208
+ }
209
+
194
210
  export function onAbort(signal, cb) {
195
211
  if (!signal) return
196
212
  if (signal.aborted) return void cb()
@@ -139,6 +139,8 @@ export class Inbox extends ReadyResource {
139
139
  this._session = null
140
140
  /** @private */
141
141
  this._discovery = null
142
+ /** @private */
143
+ this._core = null
142
144
  }
143
145
 
144
146
  /** @private */
@@ -168,6 +170,8 @@ export class Inbox extends ReadyResource {
168
170
  handled.sort((a, b) => a.handled - b.handled)
169
171
  for (const mail of handled) this._handled.set(mail.id, mail.handled)
170
172
  await this._prune()
173
+ const { mirrors } = this.network
174
+ const peering = mirrors.length ? this.network.peering() : null
171
175
  this._session = this.network.wakeup.session(this.address, {
172
176
  discoveryKey: crypto.discoveryKey(this.address),
173
177
  onannounce: (entries, peer) => this._onannounce(entries, peer),
@@ -175,6 +179,13 @@ export class Inbox extends ReadyResource {
175
179
  })
176
180
  // active on both ends: whichever side comes second is the one that looks the other up
177
181
  this._discovery = this.network.join(crypto.discoveryKey(this.address))
182
+ if (peering) {
183
+ // a mirror tells of an address only a peer that put a core under it, and the network stays
184
+ // connected to one only while it has a core there: the core of the address itself, empty
185
+ this._core = this.network.store.get({ key: this.address })
186
+ const opts = { keys: mirrors, pick: mirrors.length, referrer: this.address }
187
+ peering.addCoreBackground(this._core, opts)
188
+ }
178
189
  }
179
190
 
180
191
  /** @private */
@@ -184,7 +195,7 @@ export class Inbox extends ReadyResource {
184
195
  this._discovery?.destroy().catch(safetyCatch)
185
196
  // nothing more is fetched: its sender counts a message delivered once its block is stored
186
197
  for (const core of this._waiting) core.close().catch(safetyCatch)
187
- await Promise.allSettled([...this._landing.keys(), ...this._erasing])
198
+ await Promise.allSettled([...this._landing.keys(), ...this._erasing, this._core?.close()])
188
199
  }
189
200
 
190
201
  /**
@@ -214,6 +225,8 @@ export class Inbox extends ReadyResource {
214
225
  _onannounce(entries, peer) {
215
226
  const ids = this._turns.get(peer) || new Set()
216
227
  for (const { key } of entries) {
228
+ // a mirror lists the core of the address with the mail under it
229
+ if (b4a.equals(key, this.address)) continue
217
230
  const id = b4a.toHex(key)
218
231
  if (ids.has(id) || this._handled.has(id)) continue
219
232
  if (ids.size >= QUEUED) {
@@ -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
@@ -1,40 +1,63 @@
1
- import safetyCatch from 'safety-catch'
2
-
3
- import { ACTIVE, PASSIVE } from '../lib/constants.js'
4
1
  import { CeroError } from '../lib/errors.js'
5
2
 
3
+ let last = 0
4
+ // strictly increasing: topics at the same rank swap slots every rotation, the active one always ranks lower
5
+ function stamp() {
6
+ return (last = Math.max(Date.now(), last + 1))
7
+ }
8
+
6
9
  /**
7
- * Handle for a single topic membership on a {@link Network}. Wraps a hyperswarm
8
- * PeerDiscovery session and lets it switch between active/passive announce/lookup.
10
+ * @typedef {object} Session The hyperjoin session a topic has, as far as cero uses it.
11
+ * @property {'inactive' | 'pinned' | 'autostarted' | 'discovering' | 'destroyed'} state
12
+ * @property {boolean} active
13
+ * @property {number} priority
14
+ * @property {Promise<void> | null} closing
15
+ * @property {{ refresh(): void } | null} discovery
16
+ * @property {() => void} pin
17
+ * @property {() => void} unpin
18
+ * @property {() => void} discover
19
+ * @property {() => Promise<void>} flush
20
+ * @property {() => Promise<void>} destroy
21
+ * @property {(event: string, listener: (session: Session) => void) => void} on
9
22
  */
23
+
10
24
  /**
11
- * @typedef {{ refresh(opts?: object): Promise<void>, flushed(): Promise<boolean>, destroy(): Promise<void> }} Session
12
- * The hyperswarm session `swarm.join()` returns, as far as this file uses it.
25
+ * Handle for one topic membership on a {@link Network}: a view on the session the topic has,
26
+ * shared by every join of it. Pinned, it announces and looks up until released; in the
27
+ * rotation, it announces while it holds a slot, ranked by its last touch.
13
28
  */
14
-
15
29
  export class Discovery {
16
30
  /**
17
31
  * @param {import('./index.js').Network} network Owning network.
18
- * @param {Session} session Hyperswarm PeerDiscovery session from `swarm.join()`.
19
- * @param {'active' | 'passive'} mode
32
+ * @param {import('./index.js').Entry} entry The topic's session, shared by every join of it.
33
+ * @param {boolean} pin
20
34
  */
21
- constructor(network, session, mode) {
35
+ constructor(network, entry, pin) {
22
36
  this.network = network
23
- /** @type {Session} */
24
- this.session = session
25
37
  /** @private */
26
- this._mode = mode
38
+ this.entry = entry
27
39
  /** @private */
28
- this._destroyed = false
40
+ this._pinned = false
29
41
  /** @private */
30
- this._timer = null
31
- // a passive join only announces: the active peer's second lookup finds it
32
- if (mode === ACTIVE) this._requery().catch(safetyCatch)
42
+ this._destroyed = false
43
+ this._pin(pin)
44
+ // an open ranks it first, and takes no slot from a topic in use
45
+ this._rank(stamp())
33
46
  }
34
47
 
35
- /** @returns {'active' | 'passive'} */
36
- get mode() {
37
- return this._mode
48
+ /** @returns {Session} */
49
+ get session() {
50
+ return this.entry.session
51
+ }
52
+
53
+ /** @returns {'inactive' | 'pinned' | 'autostarted' | 'discovering' | 'destroyed'} */
54
+ get state() {
55
+ return this.session.state
56
+ }
57
+
58
+ /** @returns {boolean} Whether the topic announces or looks up right now. */
59
+ get active() {
60
+ return this.session.active
38
61
  }
39
62
 
40
63
  /** @returns {boolean} */
@@ -43,63 +66,86 @@ export class Discovery {
43
66
  }
44
67
 
45
68
  /**
46
- * Switch to active (client+server) announce/lookup.
69
+ * Pin the topic and look up now: it announces and looks up until `deactivate()`, outside the
70
+ * rotation's budget.
47
71
  *
48
72
  * @returns {Promise<void>}
49
73
  */
50
74
  async activate() {
51
75
  if (this._destroyed) throw CeroError.DESTROYED('Discovery')
52
- this._mode = ACTIVE
53
- await this.session.refresh({ client: true, server: true })
76
+ this._pin(true)
77
+ // on a pinned session this asks for a fresh query
78
+ this.session.discover()
79
+ await this.network._rotate()
54
80
  }
55
81
 
56
82
  /**
57
- * Switch to passive announce.
83
+ * Unpin the topic: the rotation decides, by its last touch.
58
84
  *
59
85
  * @returns {Promise<void>}
60
86
  */
61
87
  async deactivate() {
62
88
  if (this._destroyed) throw CeroError.DESTROYED('Discovery')
63
- this._mode = PASSIVE
64
- await this.session.refresh({ client: false, server: true })
89
+ this._pin(false)
90
+ await this.network._rotate()
91
+ }
92
+
93
+ /** The topic was just used: it ranks first, and announces from now until `idle` ms after its last use, slot or not. */
94
+ touch() {
95
+ this._rank(stamp())
96
+ this.network._use(this.entry)
65
97
  }
66
98
 
67
99
  /**
68
- * Wait for the current announce/lookup to settle.
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.
69
102
  *
70
- * @returns {Promise<void>}
103
+ * @param {Uint8Array[]} keys
71
104
  */
72
- async flush() {
73
- if (this._destroyed) return
74
- await this.session.flushed()
105
+ know(keys) {
106
+ this.entry.known = keys
107
+ this.network._dial(this.entry)
75
108
  }
76
109
 
77
- // peers joining at once look up before either announce lands; hyperswarm looks again in 10 min
78
- /** @private */
79
- async _requery() {
80
- await this.session.flushed()
110
+ /** Rank the topic last: it keeps a slot only while one is spare. */
111
+ release() {
112
+ this._rank(0)
113
+ }
114
+
115
+ /**
116
+ * Wait for the current announce or lookup to settle.
117
+ *
118
+ * @returns {Promise<void>}
119
+ */
120
+ async flush() {
81
121
  if (this._destroyed) return
82
- this._timer = setTimeout(
83
- () => this.session.refresh().catch(safetyCatch),
84
- 1000 + Math.random() * 2000
85
- )
86
- this._timer.unref()
122
+ await this.network._settle(this.session)
87
123
  }
88
124
 
89
125
  /**
90
- * Leave the topic and tear down the session. Idempotent.
126
+ * Leave the topic, once every join of it has. Idempotent.
91
127
  *
92
128
  * @returns {Promise<void>}
93
129
  */
94
130
  async destroy() {
95
131
  if (this._destroyed) return
96
132
  this._destroyed = true
97
- clearTimeout(this._timer)
98
- this.network._discoveries.delete(this)
99
- try {
100
- await this.session.destroy()
101
- } catch (err) {
102
- safetyCatch(err)
103
- }
133
+ this._pin(false)
134
+ await this.network._leave(this)
135
+ }
136
+
137
+ // the session stays pinned while any join of the topic pins it
138
+ /** @private */
139
+ _pin(pinned) {
140
+ if (pinned === this._pinned) return
141
+ this._pinned = pinned
142
+ this.entry.pins += pinned ? 1 : -1
143
+ this.network._apply(this.entry)
144
+ }
145
+
146
+ /** @private */
147
+ _rank(priority) {
148
+ this.session.priority = priority
149
+ if (!this.active) this.network._refresh()
104
150
  }
105
151
  }