@cero-base/core 1.19.0 → 2.0.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.
Files changed (43) hide show
  1. package/package.json +8 -5
  2. package/src/blobs/index.js +15 -15
  3. package/src/blobs/server.js +0 -2
  4. package/src/database/changes.js +3 -7
  5. package/src/database/dispatch.js +128 -203
  6. package/src/database/encryption.js +22 -52
  7. package/src/database/envelope.js +1 -3
  8. package/src/database/index.js +336 -387
  9. package/src/database/rotation.js +56 -70
  10. package/src/identity/index.js +5 -9
  11. package/src/index.js +5 -9
  12. package/src/lib/constants.js +3 -12
  13. package/src/lib/errors.js +6 -10
  14. package/src/lib/schema.js +2 -5
  15. package/src/lib/utils.js +9 -24
  16. package/src/network/index.js +138 -166
  17. package/src/pairing/candidate.js +2 -4
  18. package/src/pairing/index.js +41 -55
  19. package/src/pairing/invite.js +3 -4
  20. package/src/pairing/request.js +3 -9
  21. package/src/rpc/index.js +4 -14
  22. package/src/rpc/peer.js +3 -7
  23. package/src/storage/index.js +25 -31
  24. package/types/blobs/index.d.ts +5 -5
  25. package/types/blobs/server.d.ts +0 -2
  26. package/types/database/changes.d.ts +2 -5
  27. package/types/database/dispatch.d.ts +2 -6
  28. package/types/database/encryption.d.ts +8 -20
  29. package/types/database/index.d.ts +79 -96
  30. package/types/database/rotation.d.ts +14 -20
  31. package/types/identity/index.d.ts +5 -9
  32. package/types/index.d.ts +4 -3
  33. package/types/lib/errors.d.ts +6 -10
  34. package/types/lib/schema.d.ts +2 -5
  35. package/types/lib/utils.d.ts +3 -7
  36. package/types/network/index.d.ts +16 -26
  37. package/types/pairing/candidate.d.ts +1 -2
  38. package/types/pairing/index.d.ts +22 -30
  39. package/types/pairing/invite.d.ts +3 -3
  40. package/types/pairing/request.d.ts +1 -3
  41. package/types/rpc/index.d.ts +1 -4
  42. package/types/rpc/peer.d.ts +2 -4
  43. package/types/storage/index.d.ts +17 -20
@@ -48,10 +48,7 @@ import { makeDispatcher } from './dispatch.js'
48
48
  */
49
49
 
50
50
  /**
51
- * Multi-writer database built on Autobee + HyperDB. Persists rows via a
52
- * hyperdispatch-encoded log and exposes a `put/get/...` surface mirroring
53
- * `Storage`, plus writer ops (claim/addWriter/removeWriter) for the
54
- * shared writer set.
51
+ * Multi-writer database built on Autobee + HyperDB.
55
52
  */
56
53
  export class Database extends ReadyResource {
57
54
  /** @param {Partial<DatabaseOpts>} [opts] */
@@ -81,9 +78,6 @@ export class Database extends ReadyResource {
81
78
  this.rotation = new Rotation(this)
82
79
  this.key = opts.key || null
83
80
  this.passive = opts.passive === true
84
- // this device is the only author of its writer core, ever: a fresh keypair
85
- // by default. The identity keypair is never a writer — every device can
86
- // derive it, and two authors on one core is a fork
87
81
  this.keyPair = opts.keyPair || Identity.randomKeyPair()
88
82
  if (b4a.equals(this.keyPair.publicKey, this.identity.publicKey)) {
89
83
  throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
@@ -105,6 +99,31 @@ export class Database extends ReadyResource {
105
99
  this.txQueue = null
106
100
  }
107
101
 
102
+ /** @returns {Uint8Array | null} discovery key of the underlying bee */
103
+ get discoveryKey() {
104
+ return this.bee?.discoveryKey || null
105
+ }
106
+
107
+ /** @returns {Uint8Array | null} this device's local writer key */
108
+ get writerKey() {
109
+ return this.bee?.local?.key || null
110
+ }
111
+
112
+ /** @returns {boolean} whether the bee accepts local writes */
113
+ get writable() {
114
+ return this.bee?.writable === true
115
+ }
116
+
117
+ /** @returns {number} number of ops in the local writer */
118
+ get length() {
119
+ return this.bee?.local?.length || 0
120
+ }
121
+
122
+ /** @returns {object | null} the materialized HyperDB view */
123
+ get view() {
124
+ return this.bee?.view || null
125
+ }
126
+
108
127
  async _open() {
109
128
  await this.store.ready()
110
129
  if (this.network) await this.network.ready()
@@ -154,111 +173,6 @@ export class Database extends ReadyResource {
154
173
  }
155
174
  }
156
175
 
157
- // the bee's boot reads post-rotation state through the keyring, so it is
158
- // primed from the local core's userData before the bee exists
159
- async _preload() {
160
- const local = this.store.namespace(this.namespace).get({
161
- keyPair: this.keyPair,
162
- manifest: {
163
- version: this.store.manifestVersion,
164
- signers: [{ publicKey: this.keyPair.publicKey }]
165
- },
166
- active: false
167
- })
168
- await local.ready()
169
- await loadEpochs(this.keyring, local)
170
- await local.close()
171
- }
172
-
173
- async _boot() {
174
- const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
175
- keyPair: this.keyPair,
176
- encryptionKey: this.encryptionKey,
177
- keyring: this.keyring,
178
- optimistic: true,
179
- wakeup: this.network?.wakeup || undefined,
180
- open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
181
- isTrusted: this._isTrusted.bind(this),
182
- apply: this._apply.bind(this),
183
- update: this._update.bind(this)
184
- })
185
- // swarm BEFORE boot so the boot has peers to pull from, not a cold open
186
- if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
187
- await bee.ready()
188
- // apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
189
- this.bee = bee
190
- this.key = bee.key
191
- await bee.update()
192
- }
193
-
194
- // ops skipped as too new are in contract once this version caught up: wipe
195
- // the boot record so the next boot replays them
196
- async _replay() {
197
- const behind = await this.bee.local.getUserData('cero/behind')
198
- this.behind = behind ? c.decode(c.uint, behind) : null
199
- if (this.behind === null || this.behind > this.version) return false
200
- await this.bee.local.setUserData('autobee/head', null)
201
- await this.bee.local.setUserData('cero/behind', null)
202
- await this.bee.close()
203
- this.behind = null
204
- return true
205
- }
206
-
207
- // without this hook autobee trusts EVERY fast-forward candidate, so a removed
208
- // device could serve a forked head. Decided against the reference view, not live
209
- async _isTrusted(writer, view) {
210
- try {
211
- const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
212
- if (!row) return false
213
- if (row.v) return true
214
- // only a PROVABLY empty view (genesis-era reference) lets the genesis
215
- // writer vouch, its core IS the db key. Otherwise it is an ex-member's window
216
- const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
217
- if (!any) return false
218
- return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
219
- } catch {
220
- return false
221
- }
222
- }
223
-
224
- // unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
225
- async _apply(nodes, view, host) {
226
- const ready = []
227
- for (const node of nodes) {
228
- const { version, body } = unwrap(node.value)
229
- if (version > this.version) {
230
- this._onfuture(version)
231
- continue
232
- }
233
- ready.push(version === 0 ? node : { ...node, value: body })
234
- }
235
- const result = await this.dispatcher.apply(ready, view, host)
236
- if (this._updaters.size) this._touch(ready)
237
- if (this._observers.size) this._observe(ready)
238
- return result
239
- }
240
-
241
- async _update(db) {
242
- await db.update()
243
- const touched = this._touched
244
- this._touched = new Set()
245
- const all = touched.size === 0 || touched.has('*')
246
- for (const [fn, scope] of this._updaters) {
247
- if (all || !scope || touched.has(scope)) fn()
248
- }
249
- this.emit('update')
250
- }
251
-
252
- // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
253
- _joinSwarm(bee, discoveryKey) {
254
- this.network.attach(bee)
255
- const prev = this._discovery
256
- this._discovery = this.network.join(discoveryKey, {
257
- mode: this.passive ? PASSIVE : ACTIVE
258
- })
259
- if (prev) prev.destroy().catch(safetyCatch)
260
- }
261
-
262
176
  /**
263
177
  * Flip announce mode at runtime — passive stays reachable (server) but
264
178
  * stops actively looking (client). Cheap; use it to demote idle rooms.
@@ -271,31 +185,6 @@ export class Database extends ReadyResource {
271
185
  await (active ? this._discovery.activate() : this._discovery.deactivate())
272
186
  }
273
187
 
274
- /** @returns {Uint8Array | null} discovery key of the underlying bee */
275
- get discoveryKey() {
276
- return this.bee?.discoveryKey || null
277
- }
278
-
279
- /** @returns {Uint8Array | null} this device's local writer key */
280
- get writerKey() {
281
- return this.bee?.local?.key || null
282
- }
283
-
284
- /** @returns {boolean} whether the bee accepts local writes */
285
- get writable() {
286
- return this.bee?.writable === true
287
- }
288
-
289
- /** @returns {number} number of ops in the local writer */
290
- get length() {
291
- return this.bee?.local?.length || 0
292
- }
293
-
294
- /** @returns {object | null} the materialized HyperDB view */
295
- get view() {
296
- return this.bee?.view || null
297
- }
298
-
299
188
  /**
300
189
  * Register a pre-op hook. Returning `false` from `fn` aborts the op.
301
190
  *
@@ -332,10 +221,7 @@ export class Database extends ReadyResource {
332
221
  }
333
222
 
334
223
  /**
335
- * Observe every applied op — local AND replicated (apply processes the merged
336
- * log). The callback receives `{ op, name, row, writerKey, seq }` and runs
337
- * synchronously, so it must be cheap and non-blocking (enqueue and return).
338
- * Gated: zero cost when no subscriber is registered. Returns a disposer.
224
+ * Observe every applied op — local AND replicated (apply processes the merged log).
339
225
  *
340
226
  * @param {(event: { op: string, name: string, row: any, writerKey: any, seq: number }) => void} fn
341
227
  * @returns {() => void} disposer
@@ -346,66 +232,6 @@ export class Database extends ReadyResource {
346
232
  return () => this._observers.delete(fn)
347
233
  }
348
234
 
349
- async _runBefore(op, ctx) {
350
- for (const fn of this._before.get(op) || []) {
351
- if ((await fn(ctx)) === false) return false
352
- }
353
- this.emit(`before:${op}`, ctx)
354
- return true
355
- }
356
-
357
- async _runAfter(op, ctx) {
358
- for (const fn of this._after.get(op) || []) {
359
- try {
360
- await fn(ctx)
361
- } catch (err) {
362
- this._onerror(err)
363
- }
364
- }
365
- this.emit(`after:${op}`, ctx)
366
- }
367
-
368
- // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
369
- _opOf(node) {
370
- const { name, value } = this.spec.dispatch.decode(node.value)
371
- const verb = name.slice(name.indexOf('/') + 1)
372
- const dash = verb.indexOf('-')
373
- if (dash < 0) return { op: verb, name: verb, value }
374
- return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
375
- }
376
-
377
- // which refs an applied batch touched, for scoped update ticks
378
- _touch(nodes) {
379
- for (const node of nodes) {
380
- let ref = null
381
- try {
382
- ref = this._verbs.get(this._opOf(node).name)
383
- } catch {}
384
- // an action's route handler writes wherever it wants, widen to all
385
- this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
386
- }
387
- }
388
-
389
- _observe(nodes) {
390
- for (const node of nodes) {
391
- let event
392
- try {
393
- const { op, name, value } = this._opOf(node)
394
- event = { op, name, row: value, writerKey: node.key, seq: this._seq++ }
395
- } catch (err) {
396
- safetyCatch(err)
397
- continue
398
- }
399
- for (const fn of this._observers) {
400
- try {
401
- fn(event)
402
- } catch (err) {
403
- this._onerror(err)
404
- }
405
- }
406
- }
407
- }
408
-
409
235
  /**
410
236
  * Insert (or overwrite by id) a row, stamping `id`/`createdAt`/`updatedAt`.
411
237
  *
@@ -414,27 +240,14 @@ export class Database extends ReadyResource {
414
240
  * @returns {Promise<SingleResult | null>}
415
241
  */
416
242
  async put(name, row) {
417
- this.guard()
418
- const ref = this.ref(name)
419
- this._checkFields(name, row)
420
- const id = row.id || genId()
243
+ const ref = this._prepare(name, row)
421
244
  const ts = Date.now()
422
- const stored = { createdAt: ts, updatedAt: ts, ...row, id }
423
-
424
- const ctx = { op: 'put', name, row: stored }
425
- if ((await this._runBefore('put', ctx)) === false) return null
426
-
427
- await this.write([[`add-${ref.verb}`, ctx.row]])
428
-
429
- const result = { data: ctx.row }
430
- await this._runAfter('put', { ...ctx, result })
431
- return result
245
+ const stored = { createdAt: ts, updatedAt: ts, ...row, id: row.id || genId() }
246
+ return this._done('put', await this._append('put', name, stored, `add-${ref.verb}`))
432
247
  }
433
248
 
434
249
  /**
435
- * Upsert by merging with the existing row, preserving `createdAt`. Pass
436
- * `{ upsert: false }` to update-only — a missing row is left untouched
437
- * (checked atomically in the dispatch, so it never resurrects a deleted row).
250
+ * Upsert by merging with the existing row, preserving `createdAt`.
438
251
  *
439
252
  * @param {string} name
440
253
  * @param {Record<string, any>} row
@@ -442,27 +255,7 @@ export class Database extends ReadyResource {
442
255
  * @returns {Promise<SingleResult | null>}
443
256
  */
444
257
  async set(name, row, opts) {
445
- const ctx = await this.tx((tx) => tx._merge(name, row, opts))
446
- if (!ctx) return null
447
- const result = { data: ctx.row }
448
- await this._runAfter('set', { ...ctx, result })
449
- return result
450
- }
451
-
452
- async _merge(name, row, { upsert = true } = {}) {
453
- this.guard()
454
- const ref = this.ref(name)
455
- this._checkFields(name, row)
456
- const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
457
- if (!upsert && !existing) return null
458
- const ts = Date.now()
459
- const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
460
- if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
461
- const ctx = { op: 'set', name, row: stored }
462
- if ((await this._runBefore('set', ctx)) === false) return null
463
- const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
464
- await this.write([[`${insert ? 'add' : 'set'}-${ref.verb}`, ctx.row]])
465
- return ctx
258
+ return this._done('set', await this.tx((tx) => tx._merge(name, row, opts)))
466
259
  }
467
260
 
468
261
  /**
@@ -502,12 +295,8 @@ export class Database extends ReadyResource {
502
295
  }
503
296
 
504
297
  /**
505
- * Rotate the encryption epoch: generate a fresh 32-byte secret, seal it to
506
- * every current member's identity key, and announce it through the log.
507
- * The announcement is appended under the current epoch (so every member —
508
- * even one offline for several rotations — can walk the chain forward),
509
- * and blocks written after it use the new one. Members absent from the
510
- * envelope set (removed before the rotation) never learn the new key.
298
+ * Rotate the encryption epoch: generate a fresh 32-byte secret, seal it to every current
299
+ * member's identity key, and announce it through the log.
511
300
  *
512
301
  * @returns {Promise<{ epoch: number }>}
513
302
  */
@@ -517,24 +306,9 @@ export class Database extends ReadyResource {
517
306
  return this.rotation.rotate()
518
307
  }
519
308
 
520
- // apply-time hook: the log carries ops from a newer app version than this
521
- // peer understands. Emits `behind` once per version so apps can prompt an
522
- // upgrade; the marker survives restarts via local core userData
523
- _onfuture(version) {
524
- if (this.behind !== null && version <= this.behind) return
525
- this.behind = version
526
- this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
527
- this.emit('behind', version)
528
- }
529
-
530
309
  /**
531
- * Batch every write made through the transaction handle passed to `fn`
532
- * into a single autobee append. The handle is this database with its own
533
- * write queue — same surface (`put`/`set`/`del`/`call`), but writes buffer
534
- * until `fn` returns, and are discarded if it throws. Writes made on the
535
- * database itself meanwhile append normally: an unrelated concurrent write
536
- * can never be swallowed into (and rolled back with) a transaction.
537
- * Nested `tx()` on the handle joins the same batch.
310
+ * Batch every write made through the transaction handle passed to `fn` into a single
311
+ * autobee append.
538
312
  *
539
313
  * @template T
540
314
  * @param {(tx: Database) => Promise<T> | T} fn
@@ -577,55 +351,21 @@ export class Database extends ReadyResource {
577
351
  for (const op of ops) this.txQueue.push(op)
578
352
  return
579
353
  }
580
- // between `closing` and a null `bee` sits a torn-down bee behind a truthy flag
581
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
354
+ this.guard()
582
355
  if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
583
356
  const encoded = ops.map(([op, payload]) =>
584
357
  this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
585
358
  )
586
- // the dry-run rejects what apply would refuse, and an op touching nothing never
587
- // reaches the log. An action ships anyway: it lives in routes, not in rows.
359
+ // the dry run refuses what apply would; a no-op never reaches the log, an action always does
588
360
  const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
589
- let changes
590
361
  try {
591
- changes = await this._dryRun(encoded)
362
+ if (!(await this._dryRun(encoded)) && !action) return
363
+ const wrapped = encoded.map((value) => wrap(this.version, value))
364
+ await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
592
365
  } catch (err) {
593
366
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
594
367
  throw err
595
368
  }
596
- // the dry-run awaits, close can start underneath it
597
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
598
- if (!changes && !action) return
599
- const wrapped = encoded.map((value) => wrap(this.version, value))
600
- await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
601
- }
602
-
603
- // every op runs in a throwaway transaction with host effects stubbed, so a
604
- // throwing handler rejects the write and nothing enters the permanent log.
605
- // Permission gates that `return` are not rejections, apply stays the
606
- // authority at linearization time. Resolves whether the ops change anything
607
- async _dryRun(encoded) {
608
- const tx = this.view.transaction()
609
- const host = { addWriter: async () => {}, removeWriter: async () => {} }
610
- try {
611
- for (const value of encoded) {
612
- await this.dispatcher.dispatcher.dispatch(value, {
613
- host,
614
- view: tx,
615
- key: this.writerKey,
616
- dbKey: this.key,
617
- dryRun: true
618
- })
619
- }
620
- return tx.updated()
621
- } finally {
622
- // a failing close must not mask the handler's own rejection
623
- try {
624
- await tx.close()
625
- } catch (err) {
626
- safetyCatch(err)
627
- }
628
- }
629
369
  }
630
370
 
631
371
  /**
@@ -656,44 +396,6 @@ export class Database extends ReadyResource {
656
396
  return { data, total: await this._total(path, range, rows, query), size: data.length }
657
397
  }
658
398
 
659
- // one hyperdb read per query: the index that serves it, the bounds and the
660
- // window pushed down when nothing else narrows the read, the rest in memory
661
- _plan(name, query = {}) {
662
- const ref = this.refs[name]
663
- const col = `@${this.ns}/${name}`
664
- const rest = { ...query }
665
- const eq = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
666
- const bounded = [...RANGE].some((k) => query[k] !== undefined)
667
- const idx = eq.length ? matchIndex(ref?.indexes, eq) : null
668
- if (idx) {
669
- const point = {}
670
- for (const f of eq) point[f] = query[f]
671
- const range = { gte: point, lte: point }
672
- if (!query.search && !bounded) pushWindow(range, rest)
673
- return { path: `${col}-${idx}`, range, rest, sorted: true }
674
- }
675
- if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
676
- if (bounded) {
677
- const range = {}
678
- for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
679
- return { path: col, range, rest, sorted: false }
680
- }
681
- if (ref?.orderIndex) {
682
- const range = {}
683
- pushWindow(range, rest)
684
- return { path: `${col}-index`, range, rest, sorted: true }
685
- }
686
- return { path: col, range: {}, rest, sorted: false }
687
- }
688
-
689
- // rows before the in-memory pass; unknown once a pushed-down limit filled the page
690
- async _total(path, range, rows, query) {
691
- if (range.limit === undefined || rows.length < range.limit) return rows.length
692
- if (!query?.total) return null
693
- const { limit, reverse, ...bounds } = range
694
- return (await this.view.find(path, bounds).toArray()).length
695
- }
696
-
697
399
  /**
698
400
  * Number of rows that match `query` (or total if omitted).
699
401
  *
@@ -725,11 +427,7 @@ export class Database extends ReadyResource {
725
427
  }
726
428
 
727
429
  /**
728
- * Delta subscription: batches of `{ prev, next }` row pairs instead of
729
- * full snapshots. The first batch (and any batch after a view swap) carries
730
- * the current matching rows as inserts with `reset: true` — replaying every
731
- * batch into a Map keyed by row id always reconstructs current state.
732
- * `limit`/`reverse` are not applied; deltas are unwindowed by design.
430
+ * Delta subscription: batches of `{ prev, next }` row pairs instead of full snapshots.
733
431
  *
734
432
  * @param {string} name
735
433
  * @param {Query} [query]
@@ -737,21 +435,14 @@ export class Database extends ReadyResource {
737
435
  */
738
436
  changes(name, query = {}) {
739
437
  this.guard()
740
- const col = `@${this.ns}/${name}`
741
- if (!this.view.definition.resolveCollection(col)) {
742
- throw CeroError.UNKNOWN('collection', name)
743
- }
438
+ const col = this.col(this.ref(name))
744
439
  const { limit, reverse, total, ...rest } = query
745
- const matches = (row) => filter([row], rest).length > 0
746
- return makeChanges(this, name, col, matches)
440
+ return makeChanges(this, name, col, (row) => filter([row], rest).length > 0)
747
441
  }
748
442
 
749
443
  /**
750
- * Provision this device. Its writer core was minted when the database opened
751
- * and this device is its only author, ever. A first device records itself as
752
- * a writer and a device in one write. A recovering device waits for the other
753
- * devices' state, admits itself with the same master-signed add-writer
754
- * appended optimistically, then records the device.
444
+ * Provision this device. Its writer core was minted when the database opened and this
445
+ * device is its only author, ever.
755
446
  *
756
447
  * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean, timeout?: number }} [opts]
757
448
  * @returns {Promise<{ id: Uint8Array, writer: import('../identity/index.js').KeyPair }>}
@@ -783,9 +474,8 @@ export class Database extends ReadyResource {
783
474
  }
784
475
 
785
476
  /**
786
- * Claim writership on an existing room by signing our writer key with the
787
- * member identity; the claim rides in the device core as an optimistic node.
788
- * Admission only — the device is named separately (bootstrap → set-device).
477
+ * Claim writership on an existing room by signing our writer key with the member identity;
478
+ * the claim rides in the device core as an optimistic node.
789
479
  *
790
480
  * @returns {Promise<void>}
791
481
  */
@@ -848,33 +538,6 @@ export class Database extends ReadyResource {
848
538
  return this._admit('del-writer', 'removeWriter', publicKey)
849
539
  }
850
540
 
851
- // an append by a core not yet admitted: apply verifies the master signature
852
- // and admits it, then the bee turns writable
853
- async _optimistic(op, opts) {
854
- await this.bee.append(wrap(this.version, op), { optimistic: true })
855
- await this.bee.update()
856
- if (!this.bee.writable) await this.whenWritable(opts)
857
- }
858
-
859
- // the genesis device row is the first thing every database writes, so any
860
- // device row means the other devices' state has replicated and applied
861
- async _backfilled(timeout) {
862
- const deadline = Date.now() + timeout
863
- while (Date.now() < deadline) {
864
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
865
- if ((await this.get('devices')).data.length > 0) return
866
- await this.bee.update()
867
- await new Promise((resolve) => setTimeout(resolve, 50))
868
- }
869
- throw CeroError.TIMED_OUT('recovery — no peer replicated')
870
- }
871
-
872
- // the add-writer row for `writer`, appended by this device and signed by the identity
873
- _admission(writer, ts = Date.now()) {
874
- const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
875
- return { master: this.identity.publicKey, writer, sig, ts }
876
- }
877
-
878
541
  /**
879
542
  * Throw if the handle is closing/closed or the bee isn't ready yet.
880
543
  *
@@ -910,6 +573,293 @@ export class Database extends ReadyResource {
910
573
  return `@${this.ns}/${ref.name}`
911
574
  }
912
575
 
576
+ // the boot reads post-rotation state through the keyring, primed before the bee exists
577
+ async _preload() {
578
+ const local = this.store.namespace(this.namespace).get({
579
+ keyPair: this.keyPair,
580
+ manifest: {
581
+ version: this.store.manifestVersion,
582
+ signers: [{ publicKey: this.keyPair.publicKey }]
583
+ },
584
+ active: false
585
+ })
586
+ await local.ready()
587
+ await loadEpochs(this.keyring, local)
588
+ await local.close()
589
+ }
590
+
591
+ async _boot() {
592
+ const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
593
+ keyPair: this.keyPair,
594
+ encryptionKey: this.encryptionKey,
595
+ keyring: this.keyring,
596
+ optimistic: true,
597
+ wakeup: this.network?.wakeup || undefined,
598
+ open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
599
+ isTrusted: this._isTrusted.bind(this),
600
+ apply: this._apply.bind(this),
601
+ update: this._update.bind(this)
602
+ })
603
+ // swarm BEFORE boot so the boot has peers to pull from, not a cold open
604
+ if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
605
+ await bee.ready()
606
+ // apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
607
+ this.bee = bee
608
+ this.key = bee.key
609
+ await bee.update()
610
+ }
611
+
612
+ // ops skipped as too new apply once this version caught up: wipe the boot record and reboot
613
+ async _replay() {
614
+ const behind = await this.bee.local.getUserData('cero/behind')
615
+ this.behind = behind ? c.decode(c.uint, behind) : null
616
+ if (this.behind === null || this.behind > this.version) return false
617
+ await this.bee.local.setUserData('autobee/head', null)
618
+ await this.bee.local.setUserData('cero/behind', null)
619
+ await this.bee.close()
620
+ this.behind = null
621
+ return true
622
+ }
623
+
624
+ // without this hook autobee trusts every fast-forward candidate, a removed device's fork included
625
+ async _isTrusted(writer, view) {
626
+ try {
627
+ const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
628
+ if (!row) return false
629
+ if (row.v) return true
630
+ // only a provably empty view lets the genesis writer vouch: its core is the db key
631
+ const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
632
+ if (!any) return false
633
+ return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
634
+ } catch {
635
+ return false
636
+ }
637
+ }
638
+
639
+ // unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
640
+ async _apply(nodes, view, host) {
641
+ const ready = []
642
+ for (const node of nodes) {
643
+ const { version, body } = unwrap(node.value)
644
+ if (version > this.version) {
645
+ this._onfuture(version)
646
+ continue
647
+ }
648
+ ready.push(version === 0 ? node : { ...node, value: body })
649
+ }
650
+ const result = await this.dispatcher.apply(ready, view, host)
651
+ if (this._updaters.size || this._observers.size) this._notify(ready)
652
+ return result
653
+ }
654
+
655
+ async _update(db) {
656
+ await db.update()
657
+ const touched = this._touched
658
+ this._touched = new Set()
659
+ const all = touched.size === 0 || touched.has('*')
660
+ for (const [fn, scope] of this._updaters) {
661
+ if (all || !scope || touched.has(scope)) fn()
662
+ }
663
+ this.emit('update')
664
+ }
665
+
666
+ // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
667
+ _joinSwarm(bee, discoveryKey) {
668
+ this.network.attach(bee)
669
+ const prev = this._discovery
670
+ this._discovery = this.network.join(discoveryKey, {
671
+ mode: this.passive ? PASSIVE : ACTIVE
672
+ })
673
+ if (prev) prev.destroy().catch(safetyCatch)
674
+ }
675
+
676
+ async _runBefore(op, ctx) {
677
+ for (const fn of this._before.get(op) || []) {
678
+ if ((await fn(ctx)) === false) return false
679
+ }
680
+ this.emit(`before:${op}`, ctx)
681
+ return true
682
+ }
683
+
684
+ async _runAfter(op, ctx) {
685
+ for (const fn of this._after.get(op) || []) {
686
+ try {
687
+ await fn(ctx)
688
+ } catch (err) {
689
+ this._onerror(err)
690
+ }
691
+ }
692
+ this.emit(`after:${op}`, ctx)
693
+ }
694
+
695
+ // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
696
+ _opOf(node) {
697
+ const { name, value } = this.spec.dispatch.decode(node.value)
698
+ const verb = name.slice(name.indexOf('/') + 1)
699
+ const dash = verb.indexOf('-')
700
+ if (dash < 0) return { op: verb, name: verb, value }
701
+ return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
702
+ }
703
+
704
+ // which refs the batch touched, for scoped update ticks, and one event per op
705
+ _notify(nodes) {
706
+ for (const node of nodes) {
707
+ let op
708
+ try {
709
+ op = this._opOf(node)
710
+ } catch (err) {
711
+ this._touched.add('*')
712
+ safetyCatch(err)
713
+ continue
714
+ }
715
+ const ref = this._verbs.get(op.name)
716
+ // an action's route handler writes wherever it wants, widen to all
717
+ this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
718
+ if (!this._observers.size) continue
719
+ const event = {
720
+ op: op.op,
721
+ name: op.name,
722
+ row: op.value,
723
+ writerKey: node.key,
724
+ seq: this._seq++
725
+ }
726
+ for (const fn of this._observers) {
727
+ try {
728
+ fn(event)
729
+ } catch (err) {
730
+ this._onerror(err)
731
+ }
732
+ }
733
+ }
734
+ }
735
+
736
+ async _merge(name, row, { upsert = true } = {}) {
737
+ const ref = this._prepare(name, row)
738
+ const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
739
+ if (!upsert && !existing) return null
740
+ const ts = Date.now()
741
+ const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
742
+ if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
743
+ const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
744
+ return this._append('set', name, stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
745
+ }
746
+
747
+ _prepare(name, row) {
748
+ this.guard()
749
+ const ref = this.ref(name)
750
+ this._checkFields(name, row)
751
+ return ref
752
+ }
753
+
754
+ async _append(op, name, stored, verb) {
755
+ const ctx = { op, name, row: stored }
756
+ if ((await this._runBefore(op, ctx)) === false) return null
757
+ await this.write([[verb, ctx.row]])
758
+ return ctx
759
+ }
760
+
761
+ async _done(op, ctx) {
762
+ if (!ctx) return null
763
+ const result = { data: ctx.row }
764
+ await this._runAfter(op, { ...ctx, result })
765
+ return result
766
+ }
767
+
768
+ // ops from a newer app version: emit behind once per version, the marker survives restarts
769
+ _onfuture(version) {
770
+ if (this.behind !== null && version <= this.behind) return
771
+ this.behind = version
772
+ this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
773
+ this.emit('behind', version)
774
+ }
775
+
776
+ // every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
777
+ async _dryRun(encoded) {
778
+ const tx = this.view.transaction()
779
+ const host = { addWriter: async () => {}, removeWriter: async () => {} }
780
+ try {
781
+ for (const value of encoded) {
782
+ await this.dispatcher.dispatch(value, {
783
+ host,
784
+ view: tx,
785
+ key: this.writerKey,
786
+ dbKey: this.key,
787
+ dryRun: true
788
+ })
789
+ }
790
+ return tx.updated()
791
+ } finally {
792
+ // a failing close must not mask the handler's own rejection
793
+ try {
794
+ await tx.close()
795
+ } catch (err) {
796
+ safetyCatch(err)
797
+ }
798
+ }
799
+ }
800
+
801
+ // one hyperdb read per query: index, bounds and window pushed down, the rest filtered in memory
802
+ _plan(name, query = {}) {
803
+ const ref = this.refs[name]
804
+ const col = `@${this.ns}/${name}`
805
+ const rest = { ...query }
806
+ const eq = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
807
+ const bounded = [...RANGE].some((k) => query[k] !== undefined)
808
+ const idx = eq.length ? matchIndex(ref?.indexes, eq) : null
809
+ if (idx) {
810
+ const point = {}
811
+ for (const f of eq) point[f] = query[f]
812
+ const range = { gte: point, lte: point }
813
+ if (!query.search && !bounded) pushWindow(range, rest)
814
+ return { path: `${col}-${idx}`, range, rest, sorted: true }
815
+ }
816
+ if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
817
+ if (bounded) {
818
+ const range = {}
819
+ for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
820
+ return { path: col, range, rest, sorted: false }
821
+ }
822
+ if (ref?.orderIndex) {
823
+ const range = {}
824
+ pushWindow(range, rest)
825
+ return { path: `${col}-index`, range, rest, sorted: true }
826
+ }
827
+ return { path: col, range: {}, rest, sorted: false }
828
+ }
829
+
830
+ // rows before the in-memory pass; unknown once a pushed-down limit filled the page
831
+ async _total(path, range, rows, query) {
832
+ if (range.limit === undefined || rows.length < range.limit) return rows.length
833
+ if (!query?.total) return null
834
+ const { limit, reverse, ...bounds } = range
835
+ return (await this.view.find(path, bounds).toArray()).length
836
+ }
837
+
838
+ // an append by a core not yet admitted: apply verifies the signature and admits it
839
+ async _optimistic(op, opts) {
840
+ await this.bee.append(wrap(this.version, op), { optimistic: true })
841
+ await this.bee.update()
842
+ if (!this.bee.writable) await this.whenWritable(opts)
843
+ }
844
+
845
+ // the genesis device row is the first write of every database, so any device row means backfilled
846
+ async _backfilled(timeout) {
847
+ const deadline = Date.now() + timeout
848
+ while (Date.now() < deadline) {
849
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
850
+ if ((await this.get('devices')).data.length > 0) return
851
+ await this.bee.update()
852
+ await new Promise((resolve) => setTimeout(resolve, 50))
853
+ }
854
+ throw CeroError.TIMED_OUT('recovery — no peer replicated')
855
+ }
856
+
857
+ // the add-writer row for `writer`, appended by this device and signed by the identity
858
+ _admission(writer, ts = Date.now()) {
859
+ const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
860
+ return { master: this.identity.publicKey, writer, sig, ts }
861
+ }
862
+
913
863
  // the encoder silently drops an undeclared field, so the returned row would lie
914
864
  _checkFields(name, row) {
915
865
  const declared = this.refs[name]?.fields
@@ -933,8 +883,7 @@ export class Database extends ReadyResource {
933
883
  }
934
884
  }
935
885
 
936
- // a trust decision reads a historic checkout whose blocks may not be servable yet,
937
- // and an unbounded read there wedges autobee's drain forever. null means untrusted.
886
+ // an unbounded read of an old checkout wedges autobee's drain; null means untrusted
938
887
  function bounded(promise, ms = 2000) {
939
888
  return Promise.race([
940
889
  promise.then((v) => ({ v })),