@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.
@@ -0,0 +1,426 @@
1
+ import ReadyResource from 'ready-resource'
2
+ import Protomux from 'protomux'
3
+ import b4a from 'b4a'
4
+ import safetyCatch from 'safety-catch'
5
+ import { decode as decodeKey } from 'hypercore-id-encoding'
6
+
7
+ import { CeroError } from '../lib/errors.js'
8
+ import { getEncoding } from '../lib/spec/index.js'
9
+
10
+ const KEEP_ALIVE = 1000
11
+ const TICK = 500
12
+ const IDLE = 3000
13
+ const ESTABLISH = 3000
14
+ const STABLE = 5000
15
+ const RELAY_AFTER = 8000
16
+ const RELAY_ATTEMPTS = 3
17
+ const BACKOFFS = [500, 1000, 2000]
18
+ const JITTER = 250
19
+ const VERSION = 1
20
+ // no direct path will come, so the next dial goes through a relay
21
+ const UNPUNCHABLE = new Set([
22
+ 'HOLEPUNCH_ABORTED',
23
+ 'HOLEPUNCH_DOUBLE_RANDOMIZED_NATS',
24
+ 'CANNOT_HOLEPUNCH',
25
+ 'REMOTE_NOT_HOLEPUNCHABLE'
26
+ ])
27
+
28
+ const hello = getEncoding('@cero/call-hello')
29
+
30
+ /** @type {(key: string | Uint8Array) => Uint8Array} */
31
+ export function toKey(key) {
32
+ return typeof key === 'string' ? decodeKey(key) : key
33
+ }
34
+
35
+ /** @type {(key: string | Uint8Array) => string} */
36
+ export function toId(key) {
37
+ return b4a.toString(toKey(key), 'hex')
38
+ }
39
+
40
+ /**
41
+ * @typedef {object} Conn
42
+ * @property {import('@hyperswarm/secret-stream')} stream
43
+ * @property {number} local The timestamp this side sent.
44
+ * @property {number} remote The timestamp the other side sent, 0 until it does.
45
+ * @property {boolean} established
46
+ * @property {number} heard When a packet last came, 0 until it opens.
47
+ * @property {ReturnType<typeof setTimeout> | null} timer
48
+ * @property {ReturnType<typeof setInterval> | null} tick
49
+ *
50
+ * @typedef {object} Peer
51
+ * @property {string} id
52
+ * @property {Uint8Array} key
53
+ * @property {boolean} lower Whether this side holds the lower key, whose timestamps break ties.
54
+ * @property {number} attempts
55
+ * @property {boolean} forced A dial goes through a relay.
56
+ * @property {number} up When the open connection opened.
57
+ * @property {number} down When the last one closed.
58
+ * @property {ReturnType<typeof setTimeout> | null} timer
59
+ * @property {Conn | null} dialing
60
+ * @property {Conn | null} current
61
+ * @property {Set<Conn>} conns
62
+ */
63
+
64
+ /**
65
+ * One live connection to each key in a set, on a DHT the caller owns, under the caller's key pair.
66
+ * Both sides dial; of two connections opening at once, the newer by the lower key's clock stays,
67
+ * and one that still carries packets is never replaced. Events: `'connection'(stream)`,
68
+ * `'disconnection'(stream)`, `'gone'(key)` once no connection to the key is open or opening.
69
+ */
70
+ export class Peers extends ReadyResource {
71
+ /**
72
+ * @param {import('hyperdht')} dht
73
+ * @param {{ publicKey: Uint8Array, secretKey: Uint8Array }} keyPair
74
+ * @param {{ relayThrough?: Array<string | Uint8Array> | null }} [opts] Blind relay keys, for a pair that cannot connect directly.
75
+ */
76
+ constructor(dht, keyPair, { relayThrough } = {}) {
77
+ super()
78
+ if (!dht) throw CeroError.REQUIRED('dht')
79
+ if (!keyPair) throw CeroError.REQUIRED('keyPair')
80
+ /** @type {import('hyperdht')} */
81
+ this.dht = dht
82
+ this.keyPair = keyPair
83
+ /** @type {Uint8Array[] | null} */
84
+ this.relayThrough = relayThrough?.length ? relayThrough.map(toKey) : null
85
+ /** @type {Set<string>} The keys held, in hex. */
86
+ this.keys = new Set()
87
+ this.suspended = false
88
+ /** @private */
89
+ this._listening = false
90
+ /** @private @type {Map<string, Peer>} */
91
+ this._peers = new Map()
92
+ /** @private */
93
+ this._clock = 0
94
+ /** @private */
95
+ this._onupdate = () => this._update()
96
+ /** @private */
97
+ this._server = dht.createServer(
98
+ {
99
+ firewall: (key) => !this._wanted(b4a.toString(key, 'hex')),
100
+ relayThrough: () => this._relay(false)
101
+ },
102
+ (stream) => this._accept(stream)
103
+ )
104
+ }
105
+
106
+ /** @returns {Map<string, import('@hyperswarm/secret-stream')>} The open connection to each key, by key in hex. */
107
+ get connections() {
108
+ const map = new Map()
109
+ for (const peer of this._peers.values()) {
110
+ if (peer.current) map.set(peer.id, peer.current.stream)
111
+ }
112
+ return map
113
+ }
114
+
115
+ /**
116
+ * Whether a connection to `key` is open or opening.
117
+ *
118
+ * @param {string | Uint8Array} key
119
+ * @returns {boolean}
120
+ */
121
+ connecting(key) {
122
+ return this._peers.get(toId(key))?.conns.size > 0
123
+ }
124
+
125
+ /** @private */
126
+ async _open() {
127
+ await this._server.listen(this.keyPair)
128
+ this._listening = true
129
+ this.dht.on('network-update', this._onupdate)
130
+ for (const peer of this._peers.values()) this._dial(peer)
131
+ }
132
+
133
+ /** @private */
134
+ async _close() {
135
+ this.dht.off('network-update', this._onupdate)
136
+ this.keys.clear()
137
+ for (const peer of this._peers.values()) clearTimeout(peer.timer)
138
+ await this._drop()
139
+ await this._server.close()
140
+ }
141
+
142
+ /**
143
+ * Hold a connection to `key` until it is removed, dialed once the instance is open. Its own key
144
+ * is skipped.
145
+ *
146
+ * @param {string | Uint8Array} key
147
+ * @returns {void}
148
+ */
149
+ add(key) {
150
+ if (this.closing) throw CeroError.CLOSED('Peers')
151
+ const id = toId(key)
152
+ if (this.keys.has(id) || id === b4a.toString(this.keyPair.publicKey, 'hex')) return
153
+ this.keys.add(id)
154
+ let peer = this._peers.get(id)
155
+ if (!peer) {
156
+ const remote = toKey(key)
157
+ peer = {
158
+ id,
159
+ key: remote,
160
+ lower: b4a.compare(this.keyPair.publicKey, remote) < 0,
161
+ attempts: 0,
162
+ forced: false,
163
+ up: 0,
164
+ down: Date.now(),
165
+ timer: null,
166
+ dialing: null,
167
+ current: null,
168
+ conns: new Set()
169
+ }
170
+ this._peers.set(id, peer)
171
+ }
172
+ this._dial(peer)
173
+ }
174
+
175
+ /**
176
+ * Drop `key`: its connection closes and it is not dialed again.
177
+ *
178
+ * @param {string | Uint8Array} key
179
+ * @returns {void}
180
+ */
181
+ remove(key) {
182
+ const id = toId(key)
183
+ if (!this.keys.delete(id)) return
184
+ const peer = this._peers.get(id)
185
+ clearTimeout(peer.timer)
186
+ peer.timer = null
187
+ if (peer.conns.size === 0) this._peers.delete(id)
188
+ for (const conn of peer.conns) conn.stream.destroy()
189
+ }
190
+
191
+ /**
192
+ * Hold exactly these keys.
193
+ *
194
+ * @param {Array<string | Uint8Array>} keys
195
+ * @returns {void}
196
+ */
197
+ set(keys) {
198
+ const ids = new Set(keys.map(toId))
199
+ for (const id of this.keys) {
200
+ if (!ids.has(id)) this.remove(id)
201
+ }
202
+ for (const key of keys) this.add(key)
203
+ }
204
+
205
+ /**
206
+ * Close every connection and keep the keys: nothing dials or is let in until `resume()`.
207
+ *
208
+ * @returns {Promise<void>}
209
+ */
210
+ async suspend() {
211
+ this.suspended = true
212
+ for (const peer of this._peers.values()) {
213
+ clearTimeout(peer.timer)
214
+ peer.timer = null
215
+ }
216
+ await Promise.all([this._drop(), this._server.suspend()])
217
+ }
218
+
219
+ /**
220
+ * Dial every key again at once.
221
+ *
222
+ * @returns {Promise<void>}
223
+ */
224
+ async resume() {
225
+ this.suspended = false
226
+ await this._server.resume()
227
+ for (const peer of this._peers.values()) {
228
+ peer.attempts = 0
229
+ peer.down = Date.now()
230
+ this._dial(peer)
231
+ }
232
+ }
233
+
234
+ /** @private */
235
+ _wanted(id) {
236
+ return this._listening && !this.suspended && this.keys.has(id)
237
+ }
238
+
239
+ /** @private */
240
+ _relay(force) {
241
+ return force || this.dht.randomized ? this.relayThrough : null
242
+ }
243
+
244
+ /** @private */
245
+ _now() {
246
+ const now = Date.now()
247
+ this._clock = now > this._clock ? now : this._clock + 1
248
+ return this._clock
249
+ }
250
+
251
+ /** @private */
252
+ _dial(peer) {
253
+ if (!this._wanted(peer.id) || peer.current || peer.dialing) return
254
+ const late = Date.now() - peer.down >= RELAY_AFTER
255
+ const relayThrough = this._relay(peer.forced || peer.attempts >= RELAY_ATTEMPTS || late)
256
+ const stream = this.dht.connect(peer.key, { keyPair: this.keyPair, relayThrough })
257
+ peer.dialing = this._attach(peer, stream)
258
+ }
259
+
260
+ /** @private */
261
+ _accept(stream) {
262
+ const id = b4a.toString(stream.remotePublicKey, 'hex')
263
+ const peer = this._peers.get(id)
264
+ // a remove or a suspend can land between the firewall and the connection; and a connection that
265
+ // still carries packets stays, or two live instances of one key pair would take turns for good
266
+ if (!this._wanted(id) || (peer.current && alive(peer.current))) {
267
+ stream.on('error', safetyCatch)
268
+ stream.destroy()
269
+ return
270
+ }
271
+ this._attach(peer, stream)
272
+ }
273
+
274
+ /** @private */
275
+ _attach(peer, stream) {
276
+ /** @type {Conn} */
277
+ const conn = {
278
+ stream,
279
+ local: this._now(),
280
+ remote: 0,
281
+ established: false,
282
+ heard: 0,
283
+ timer: null,
284
+ tick: null
285
+ }
286
+ peer.conns.add(conn)
287
+ stream.on('error', (err) => {
288
+ if (!UNPUNCHABLE.has(err.code)) return
289
+ peer.forced = true
290
+ peer.attempts = 0
291
+ })
292
+ stream.on('close', () => this._closed(peer, conn))
293
+ const channel = Protomux.from(stream).createChannel({
294
+ protocol: 'cero/peers',
295
+ handshake: hello,
296
+ onopen: (m) => this._established(peer, conn, m)
297
+ })
298
+ channel.open({ version: VERSION, timestamp: conn.local })
299
+ this._watch(conn).catch(safetyCatch)
300
+ return conn
301
+ }
302
+
303
+ // both sides send a keepalive every second: no packet for IDLE ms is a dead path
304
+ /** @private */
305
+ async _watch(conn) {
306
+ const { stream } = conn
307
+ if (!(await stream.opened) || stream.destroying) return
308
+ stream.setKeepAlive(KEEP_ALIVE)
309
+ if (!conn.established) conn.timer = setTimeout(() => stream.destroy(), ESTABLISH)
310
+ let seen = stream.rawStream.packetsReceived
311
+ conn.heard = Date.now()
312
+ conn.tick = setInterval(() => {
313
+ const packets = stream.rawStream.packetsReceived
314
+ if (packets !== seen) {
315
+ seen = packets
316
+ conn.heard = Date.now()
317
+ } else if (!alive(conn)) {
318
+ stream.destroy()
319
+ }
320
+ }, TICK)
321
+ }
322
+
323
+ /** @private */
324
+ _established(peer, conn, { timestamp }) {
325
+ if (timestamp === 0) {
326
+ conn.stream.destroy()
327
+ return
328
+ }
329
+ clearTimeout(conn.timer)
330
+ conn.remote = timestamp
331
+ conn.established = true
332
+ if (peer.dialing === conn) peer.dialing = null
333
+ this._pick(peer)
334
+ }
335
+
336
+ // both sides read the lower key's timestamps, so both keep the same connection
337
+ /** @private */
338
+ _pick(peer) {
339
+ let best = null
340
+ for (const conn of peer.conns) {
341
+ if (!conn.established || conn.stream.destroying) continue
342
+ if (best === null || order(peer, conn) > order(peer, best)) best = conn
343
+ }
344
+ if (best === null) return
345
+ for (const conn of peer.conns) {
346
+ if (conn !== best && conn.established) conn.stream.destroy()
347
+ }
348
+ const prev = peer.current
349
+ if (prev === best) return
350
+ peer.current = best
351
+ peer.up = Date.now()
352
+ this.emit('connection', best.stream)
353
+ if (prev) this.emit('disconnection', prev.stream)
354
+ }
355
+
356
+ /** @private */
357
+ _closed(peer, conn) {
358
+ clearTimeout(conn.timer)
359
+ clearInterval(conn.tick)
360
+ peer.conns.delete(conn)
361
+ if (peer.dialing === conn) peer.dialing = null
362
+ if (peer.current === conn) {
363
+ peer.current = null
364
+ peer.down = Date.now()
365
+ // the time it carried packets: a silence counts only once it is cut
366
+ if (conn.heard - peer.up >= STABLE) {
367
+ peer.attempts = 0
368
+ peer.forced = false
369
+ }
370
+ this.emit('disconnection', conn.stream)
371
+ }
372
+ if (peer.conns.size === 0) {
373
+ if (!this.keys.has(peer.id)) this._peers.delete(peer.id)
374
+ this.emit('gone', peer.id)
375
+ }
376
+ if (peer.current) return
377
+ this._pick(peer)
378
+ if (!peer.current) this._retry(peer)
379
+ }
380
+
381
+ /** @private */
382
+ _retry(peer) {
383
+ if (!this._wanted(peer.id) || peer.dialing || peer.timer) return
384
+ const backoff = BACKOFFS[Math.min(peer.attempts++, BACKOFFS.length - 1)]
385
+ peer.timer = setTimeout(
386
+ () => {
387
+ peer.timer = null
388
+ this._dial(peer)
389
+ },
390
+ backoff + Math.round(Math.random() * JITTER)
391
+ )
392
+ }
393
+
394
+ // a new address: tell the DHT, probe the open connections, dial the waiting ones now
395
+ /** @private */
396
+ _update() {
397
+ this._server.refresh()
398
+ for (const peer of this._peers.values()) {
399
+ peer.current?.stream.sendKeepAlive()
400
+ if (peer.timer === null) continue
401
+ clearTimeout(peer.timer)
402
+ peer.timer = null
403
+ this._dial(peer)
404
+ }
405
+ }
406
+
407
+ /** @private */
408
+ _drop() {
409
+ const closing = []
410
+ for (const peer of this._peers.values()) {
411
+ for (const { stream } of peer.conns) {
412
+ closing.push(new Promise((resolve) => stream.once('close', resolve)))
413
+ stream.destroy()
414
+ }
415
+ }
416
+ return Promise.all(closing)
417
+ }
418
+ }
419
+
420
+ function order(peer, conn) {
421
+ return peer.lower ? conn.local : conn.remote
422
+ }
423
+
424
+ function alive(conn) {
425
+ return !conn.stream.destroying && Date.now() - conn.heard < IDLE
426
+ }
@@ -398,10 +398,14 @@ export function makeDispatcher({
398
398
  get: (ref, query) => read(ctx.view, refName(ref), query),
399
399
  put: async (ref, row) => {
400
400
  const name = refName(ref)
401
- if (single(name)) return write(name, 'set', held(name, row, stamp(row, null, ctx.ts)))
401
+ if (single(name)) {
402
+ await write(name, 'set', held(name, row, stamp(row, null, ctx.ts)))
403
+ return { data: await current(name) }
404
+ }
402
405
  const id = row.id ?? (await ctx.mint(ctx.view, col(name)))
403
406
  const stored = stamp({ ...row, id }, null, ctx.ts)
404
- return write(name, 'add', held(name, row, stored))
407
+ await write(name, 'add', held(name, row, stored))
408
+ return { data: await current(name, id) }
405
409
  },
406
410
  // an upsert, as the set operator appends it
407
411
  set: async (ref, row) => {
@@ -438,7 +442,8 @@ export function makeDispatcher({
438
442
  }
439
443
  const writer = await author(ctx)
440
444
  const base = { id: null, row: null, existing: null, ...meta }
441
- const hctx = { ...base, ...writer, ...operators(ctx) }
445
+ const device = ctx.key ? hid.encode(ctx.key) : null
446
+ const hctx = { ...base, ...writer, device, ts: ctx.ts ?? 0, ...operators(ctx) }
442
447
  const granted = await fire(fns.before, hctx, true)
443
448
  // a grant widens rank among the room's writers only: never for a reader, nor for someone who
444
449
  // is no member at all, whatever a rule wrote on ctx
@@ -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.
@@ -80,9 +81,11 @@ Hypercore.setRecoveryPeers(recovery)
80
81
  * @property {string | null} id The row id for a `del`.
81
82
  * @property {string | null} memberId The writer's member id, null for a core no member owns yet (a join, a claim, genesis).
82
83
  * @property {string | null} role The writer's role, null likewise.
84
+ * @property {string | null} device The writer's device, its id as `devices` holds it.
85
+ * @property {number} ts The op's time, the same on every peer.
83
86
  * @property {boolean} [ranked] On removing a member or changing her rank: whether the writer's rank alone allows it. A rule answers `'grant'` to allow what rank refuses, `false` to refuse.
84
87
  * @property {(ref: string | { name: string }, query?: string | Record<string, unknown>) => Promise<{ data: unknown }>} get
85
- * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} put
88
+ * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<{ data: Record<string, unknown> }>} put
86
89
  * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} set
87
90
  * @property {(ref: string | { name: string }, id?: string) => Promise<void>} del
88
91
  * @typedef {(ctx: HookContext) => unknown} HookFn
@@ -167,7 +170,13 @@ export class Database extends ReadyResource {
167
170
  this.bee = null
168
171
  this.dispatcher = null
169
172
  /** @private */
170
- this._presence = null
173
+ this._discovery = null
174
+ /** @private @type {Uint8Array[]} */
175
+ this._known = []
176
+ /** @private */
177
+ this._saved = ''
178
+ /** @private */
179
+ this._meeting = null
171
180
  /** @private */
172
181
  this._pushing = null
173
182
  /** @private */
@@ -225,6 +234,11 @@ export class Database extends ReadyResource {
225
234
  return this._behind ?? this.parent?.behind ?? null
226
235
  }
227
236
 
237
+ /** @returns {Uint8Array[]} the network keys of the devices this database last replicated with, the latest first */
238
+ get known() {
239
+ return this._known
240
+ }
241
+
228
242
  /** @returns {boolean} whether the bee accepts local writes */
229
243
  get writable() {
230
244
  return this._writable
@@ -290,6 +304,7 @@ export class Database extends ReadyResource {
290
304
 
291
305
  // a fresh db has no key until boot mints it
292
306
  if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
307
+ if (this.network) await this._recall()
293
308
  }
294
309
 
295
310
  /** @private */
@@ -298,6 +313,7 @@ export class Database extends ReadyResource {
298
313
  // falling edge: apps freeze the UI the moment access ends
299
314
  this.bee.on('unwritable', () => {
300
315
  this._writable = false
316
+ this._forget()
301
317
  this.emit('unwritable')
302
318
  })
303
319
  // without a listener autobee escalates apply/view errors to a process crash
@@ -328,10 +344,10 @@ export class Database extends ReadyResource {
328
344
  async _close() {
329
345
  this.rotation.close()
330
346
  this.network?.off('resume', this._onResume)
331
- if (this._presence) {
332
- this._presence.remove()
333
- this._presence = null
334
- }
347
+ this._meeting?.destroy()
348
+ this._meeting = null
349
+ this._discovery?.destroy().catch(safetyCatch)
350
+ this._discovery = null
335
351
  const held = [...this._held.values()]
336
352
  this._held.clear()
337
353
  for (const { range } of held) range.destroy()
@@ -343,15 +359,15 @@ export class Database extends ReadyResource {
343
359
  }
344
360
 
345
361
  /**
346
- * `true` ranks this database as just touched, `false` takes it out of the swarm until the
347
- * next update lands in it.
362
+ * `true` ranks this database as just touched, `false` ranks it last: it keeps its slot on the
363
+ * swarm only while one is spare, until the next update lands in it.
348
364
  *
349
365
  * @param {boolean} active
350
366
  */
351
367
  setActive(active) {
352
- if (!this._presence) return
353
- if (active) this._presence.touch()
354
- else this._presence.off()
368
+ if (!this._discovery) return
369
+ if (active) this._discovery.touch()
370
+ else this._discovery.release()
355
371
  }
356
372
 
357
373
  /**
@@ -489,8 +505,7 @@ export class Database extends ReadyResource {
489
505
  // one after the other, past each other's failures so one does not wedge the rest
490
506
  /** @private */
491
507
  _chain(fn) {
492
- const prev = this._txChain || Promise.resolve()
493
- this._txChain = prev.then(fn, fn)
508
+ this._txChain = inTurn(this._txChain, fn)
494
509
  return this._txChain
495
510
  }
496
511
 
@@ -1018,6 +1033,8 @@ export class Database extends ReadyResource {
1018
1033
  }
1019
1034
  if (this._writable || !this.bee.writable || this.closing || this.closed) return
1020
1035
  this._writable = true
1036
+ // the seat back after a reorder took it
1037
+ if (this.opened && this.network && !this._meeting) this._meet()
1021
1038
  this.emit('writable')
1022
1039
  }
1023
1040
 
@@ -1254,15 +1271,79 @@ export class Database extends ReadyResource {
1254
1271
  this._applied = false
1255
1272
  this._landed = false
1256
1273
  if (!quiet) this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
1257
- if (!quiet || landed) this._presence?.touch()
1274
+ if (!quiet || landed) this._discovery?.touch()
1258
1275
  }
1259
1276
 
1260
1277
  // every bee a boot opens is attached, but the topic is joined once: close leaves it once
1261
1278
  /** @private */
1262
1279
  _joinSwarm(bee, discoveryKey) {
1263
1280
  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 })
1281
+ if (this.push && !this._discovery) this.network.on('resume', this._onResume)
1282
+ this._discovery ??= this.network.join(discoveryKey, { pin: this.pinned })
1283
+ }
1284
+
1285
+ /** @private */
1286
+ async _recall() {
1287
+ const stored = await this.bee.local.getUserData(KNOWN)
1288
+ if (stored) this._known = c.decode(keys, stored)
1289
+ this._saved = signature(this._known)
1290
+ this._meet()
1291
+ }
1292
+
1293
+ // a device on the database's wakeup channel proved it holds the key. The latest are kept on this device's
1294
+ // writer core and dialed by their own keys: a device with many databases announces only a few of them
1295
+ /** @private */
1296
+ _meet() {
1297
+ const { key, discoveryKey } = this.bee.wakeupCapability
1298
+ const onpeeradd = (peer) => this._keep(this._met(this._known, [peer]))
1299
+ this._meeting = this.network.wakeup.session(key, { discoveryKey, active: false, onpeeradd })
1300
+ this._keep(this._met(this._known, this._meeting.peers))
1301
+ }
1302
+
1303
+ // the devices of these peers ahead of the ones known, the latest first. Only a connection the replicator made
1304
+ // proves a key it can dial: an injected stream may carry another, and a mirror is reached as a mirror
1305
+ /** @private */
1306
+ _met(known, peers) {
1307
+ for (const { stream } of peers) {
1308
+ const key = stream.remotePublicKey
1309
+ if (!this.network.replicator?.hasConnection(key)) continue
1310
+ if (this.network.mirrors.some((mirror) => b4a.equals(mirror, key))) continue
1311
+ known = [key, ...known.filter((k) => !b4a.equals(k, key))]
1312
+ }
1313
+ return known.slice(0, this.network.presence.known)
1314
+ }
1315
+
1316
+ // written when a device enters or leaves the list, never for its order: a reconnect writes nothing
1317
+ /** @private */
1318
+ _keep(known) {
1319
+ this._known = known
1320
+ this._discovery?.know(known)
1321
+ const saved = signature(known)
1322
+ if (saved === this._saved || this.closing || !this.bee) return
1323
+ this._saved = saved
1324
+ this._store(this.bee, known.length ? c.encode(keys, known) : null)
1325
+ }
1326
+
1327
+ // a bee has no writer core until it is ready. One replaced or closed under the write fails it: the next change
1328
+ // writes the list again
1329
+ /** @private */
1330
+ async _store(bee, value) {
1331
+ try {
1332
+ await bee.ready()
1333
+ await bee.local.setUserData(KNOWN, value)
1334
+ } catch (err) {
1335
+ this._saved = null
1336
+ if (bee === this.bee && !this.closing) this._onerror(err)
1337
+ }
1338
+ }
1339
+
1340
+ // a device that lost its seat keeps no key of the others
1341
+ /** @private */
1342
+ _forget() {
1343
+ if (!this._meeting) return
1344
+ this._meeting.destroy()
1345
+ this._meeting = null
1346
+ this._keep([])
1266
1347
  }
1267
1348
 
1268
1349
  // every writer the database ever had and every core its views read; only the system bee, an autobee
@@ -1367,6 +1448,8 @@ export class Database extends ReadyResource {
1367
1448
  name: op.name,
1368
1449
  row: op.value,
1369
1450
  writerKey: node.key,
1451
+ // the writer's length at the op: a reorder that applies it again names the same
1452
+ length: node.length,
1370
1453
  seq: this._seq++
1371
1454
  })
1372
1455
  }
@@ -1763,6 +1846,8 @@ async function rows(snap, col, from) {
1763
1846
  }
1764
1847
 
1765
1848
  const NO_HOOKS = []
1849
+ const KNOWN = 'cero/known'
1850
+ const keys = c.array(c.fixed32)
1766
1851
  const PUSH_RETRY = 5000
1767
1852
 
1768
1853
  // the refs whose writes push, by the verb their ops carry
@@ -1811,6 +1896,13 @@ function seatless(ops, id) {
1811
1896
 
1812
1897
  const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
1813
1898
 
1899
+ function signature(known) {
1900
+ return known
1901
+ .map((key) => b4a.toHex(key))
1902
+ .sort()
1903
+ .join()
1904
+ }
1905
+
1814
1906
  const byIndex = (a, b) => (a.index ?? 0) - (b.index ?? 0)
1815
1907
 
1816
1908
  // the index whose fields are exactly the query's equality keys, or those and then `index`: that
@@ -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