@cero-base/core 3.4.1 → 3.5.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.
package/README.md CHANGED
@@ -26,7 +26,7 @@ Each primitive but `Identity` is a `ReadyResource`: construct it, `await x.ready
26
26
  | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
27
  | `@cero-base/core` | Every subpath below in one import, but `/database/encryption` and `/blobs/server` |
28
28
  | `@cero-base/core/identity` | `Identity`: a keypair from a seed; signs, verifies, seals, names a swarm topic |
29
- | `@cero-base/core/network` | `Network`: Hyperswarm plus wakeup, with managed discovery sessions; `channelTopic` |
29
+ | `@cero-base/core/network` | `Network`: Hyperjoin plus wakeup, one discovery session per topic; `channelTopic` |
30
30
  | `@cero-base/core/database` | `Database`: multi-writer, permissions checked at apply, hooks, key rotation |
31
31
  | `@cero-base/core/database/encryption` | `Keyring`, `EpochAutobee`, `blobEpochKey`, `loadEpochs`, `seal`, `opened`, `wraps`, `epochEntries`: the key epochs a `Database` rotates through |
32
32
  | `@cero-base/core/mailbox` | `Mailbox`: messages to an address, delivered directly or held by a mirror |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "3.4.1",
3
+ "version": "3.5.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -152,32 +152,32 @@
152
152
  },
153
153
  "dependencies": {
154
154
  "@hyperswarm/secret-stream": "^6.9.2",
155
- "autobee": "2.14.0",
155
+ "autobee": "2.15.0",
156
156
  "b4a": "^1.9.0",
157
157
  "bare-crypto": "^1.16.1",
158
- "bare-fs": "^4.8.5",
158
+ "bare-fs": "^4.8.7",
159
159
  "bare-path": "^3.1.3",
160
160
  "bip39-mnemonic": "^2.5.0",
161
- "blind-peering": "^2.14.0",
162
- "blind-push": "^1.2.1",
163
- "compact-encoding": "^3.7.0",
161
+ "blind-peering": "^2.15.0",
162
+ "blind-push": "^1.3.0",
163
+ "compact-encoding": "^3.7.1",
164
164
  "corestore": "^7.16.1",
165
165
  "framed-stream": "^1.0.1",
166
166
  "hrpc": "^4.3.2",
167
167
  "hyperblobs": "^2.13.0",
168
- "hypercore": "^11.40.4",
168
+ "hypercore": "^11.40.5",
169
169
  "hypercore-blob-server": "^1.15.1",
170
170
  "hypercore-crypto": "^3.7.0",
171
171
  "hypercore-id-encoding": "^1.3.0",
172
172
  "hypercore-storage": "^3.4.0",
173
173
  "hyperdb": "^6.11.2",
174
- "hyperdht": "^6.36.0",
174
+ "hyperdht": "^6.37.0",
175
175
  "hyperdispatch": "^1.6.0",
176
+ "hyperjoin": "^1.5.0",
176
177
  "hyperschema": "^1.26.2",
177
- "hyperswarm": "^4.17.2",
178
178
  "keet-identity-key": "^3.2.0",
179
179
  "ms": "^2.1.3",
180
- "protomux-wakeup": "^2.9.2",
180
+ "protomux-wakeup": "^2.9.3",
181
181
  "ready-resource": "^1.2.0",
182
182
  "safety-catch": "^1.0.3",
183
183
  "sodium-universal": "^5.0.1",
@@ -190,11 +190,12 @@
190
190
  "bare-events": "^2.9.2",
191
191
  "bare-fetch": "^3.5.0",
192
192
  "bare-process": "^4.5.1",
193
- "bare-subprocess": "^6.2.2",
193
+ "bare-subprocess": "^6.2.3",
194
194
  "bare-url": "^2.5.8",
195
- "blind-peer": "^3.18.3",
195
+ "blind-peer": "^3.20.1",
196
196
  "blind-push-gateway": "^1.0.0",
197
- "brittle": "^4.5.0",
197
+ "brittle": "^4.6.0",
198
+ "hyperswarm": "^4.17.2",
198
199
  "protomux": "^3.13.1",
199
200
  "protomux-rpc-router": "^1.3.0",
200
201
  "typescript": "^7.0.2",
@@ -31,7 +31,8 @@ import {
31
31
  filter,
32
32
  checkFields,
33
33
  checkRequired,
34
- stamp
34
+ stamp,
35
+ inTurn
35
36
  } from '../lib/utils.js'
36
37
  import { wrap, unwrap } from './envelope.js'
37
38
  import { EpochAutobee, Keyring, loadEpochs, plainId } from './encryption.js'
@@ -56,7 +57,7 @@ Hypercore.setRecoveryPeers(recovery)
56
57
  * @property {Uint8Array} encryptionKey Encrypts it; a join hands it out, so never the identity's on a database you pair.
57
58
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
58
59
  * @property {Uint8Array | null} [key] Existing autobee key to reopen.
59
- * @property {boolean} [pinned] Always search and announce, outside the network's presence budget. The root.
60
+ * @property {boolean} [pinned] Always announce and look up, outside the network's presence budget. The root.
60
61
  * @property {boolean} [root] The identity's own database: a device key past a removed one stands while a device of the identity is seated on it.
61
62
  * @property {boolean} [push] Push a notification through the mirrors after a local write to a ref whose meta declares `push`, naming the ref, so members learn of it while their app is dead.
62
63
  * @property {import('../identity/index.js').KeyPair} [keyPair] This device's writer keypair; a fresh random one by default. Never the identity's, never the database key.
@@ -167,7 +168,7 @@ export class Database extends ReadyResource {
167
168
  this.bee = null
168
169
  this.dispatcher = null
169
170
  /** @private */
170
- this._presence = null
171
+ this._discovery = null
171
172
  /** @private */
172
173
  this._pushing = null
173
174
  /** @private */
@@ -328,10 +329,8 @@ export class Database extends ReadyResource {
328
329
  async _close() {
329
330
  this.rotation.close()
330
331
  this.network?.off('resume', this._onResume)
331
- if (this._presence) {
332
- this._presence.remove()
333
- this._presence = null
334
- }
332
+ this._discovery?.destroy().catch(safetyCatch)
333
+ this._discovery = null
335
334
  const held = [...this._held.values()]
336
335
  this._held.clear()
337
336
  for (const { range } of held) range.destroy()
@@ -343,15 +342,15 @@ export class Database extends ReadyResource {
343
342
  }
344
343
 
345
344
  /**
346
- * `true` ranks this database as just touched, `false` takes it out of the swarm until the
347
- * next update lands in it.
345
+ * `true` ranks this database as just touched, `false` ranks it last: it keeps its slot on the
346
+ * swarm only while one is spare, until the next update lands in it.
348
347
  *
349
348
  * @param {boolean} active
350
349
  */
351
350
  setActive(active) {
352
- if (!this._presence) return
353
- if (active) this._presence.touch()
354
- else this._presence.off()
351
+ if (!this._discovery) return
352
+ if (active) this._discovery.touch()
353
+ else this._discovery.release()
355
354
  }
356
355
 
357
356
  /**
@@ -489,8 +488,7 @@ export class Database extends ReadyResource {
489
488
  // one after the other, past each other's failures so one does not wedge the rest
490
489
  /** @private */
491
490
  _chain(fn) {
492
- const prev = this._txChain || Promise.resolve()
493
- this._txChain = prev.then(fn, fn)
491
+ this._txChain = inTurn(this._txChain, fn)
494
492
  return this._txChain
495
493
  }
496
494
 
@@ -1254,15 +1252,15 @@ export class Database extends ReadyResource {
1254
1252
  this._applied = false
1255
1253
  this._landed = false
1256
1254
  if (!quiet) this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
1257
- if (!quiet || landed) this._presence?.touch()
1255
+ if (!quiet || landed) this._discovery?.touch()
1258
1256
  }
1259
1257
 
1260
1258
  // every bee a boot opens is attached, but the topic is joined once: close leaves it once
1261
1259
  /** @private */
1262
1260
  _joinSwarm(bee, discoveryKey) {
1263
1261
  this.network.attach(bee)
1264
- if (this.push && !this._presence) this.network.on('resume', this._onResume)
1265
- this._presence ??= this.network.presence.add(discoveryKey, { pinned: this.pinned })
1262
+ if (this.push && !this._discovery) this.network.on('resume', this._onResume)
1263
+ this._discovery ??= this.network.join(discoveryKey, { pin: this.pinned })
1266
1264
  }
1267
1265
 
1268
1266
  // every writer the database ever had and every core its views read; only the system bee, an autobee
@@ -3,9 +3,6 @@ export const COLLECTION = 'collection'
3
3
  export const HANDLE = 'handle'
4
4
  export const ACTION = 'action'
5
5
 
6
- export const ACTIVE = 'active'
7
- export const PASSIVE = 'passive'
8
-
9
6
  export const ROCKS = 'rocks'
10
7
  export const BEE = 'bee'
11
8
 
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) {
@@ -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
+ // opening counts as a touch
45
+ this.touch()
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,75 @@ 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
+ /** Rank the topic first in the rotation, as just used. */
94
+ touch() {
95
+ this._rank(stamp())
96
+ }
97
+
98
+ /** Rank the topic last: it keeps a slot only while one is spare. */
99
+ release() {
100
+ this._rank(0)
65
101
  }
66
102
 
67
103
  /**
68
- * Wait for the current announce/lookup to settle.
104
+ * Wait for the current announce or lookup to settle.
69
105
  *
70
106
  * @returns {Promise<void>}
71
107
  */
72
108
  async flush() {
73
109
  if (this._destroyed) return
74
- await this.session.flushed()
75
- }
76
-
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()
81
- if (this._destroyed) return
82
- this._timer = setTimeout(
83
- () => this.session.refresh().catch(safetyCatch),
84
- 1000 + Math.random() * 2000
85
- )
86
- this._timer.unref()
110
+ await this.network._settle(this.session)
87
111
  }
88
112
 
89
113
  /**
90
- * Leave the topic and tear down the session. Idempotent.
114
+ * Leave the topic, once every join of it has. Idempotent.
91
115
  *
92
116
  * @returns {Promise<void>}
93
117
  */
94
118
  async destroy() {
95
119
  if (this._destroyed) return
96
120
  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
- }
121
+ this._pin(false)
122
+ await this.network._leave(this)
123
+ }
124
+
125
+ // the session stays pinned while any join of the topic pins it
126
+ /** @private */
127
+ _pin(pinned) {
128
+ if (pinned === this._pinned) return
129
+ 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()
133
+ }
134
+
135
+ /** @private */
136
+ _rank(priority) {
137
+ this.session.priority = priority
138
+ if (!this.active) this.network._refresh()
104
139
  }
105
140
  }