@cero-base/core 1.17.0 → 1.18.1

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.
@@ -13,24 +13,16 @@ import {
13
13
  ACTION,
14
14
  ACTIVE,
15
15
  PASSIVE,
16
- REMOVE,
17
16
  QUERY_RESERVED
18
17
  } from '../lib/constants.js'
19
- import {
20
- genId,
21
- toId,
22
- toKey,
23
- can,
24
- subscribe,
25
- addWriterPayload,
26
- claimWriterPayload,
27
- searchHit
28
- } from '../lib/utils.js'
18
+ import { genId, toId, subscribe, addWriterPayload, searchHit } from '../lib/utils.js'
29
19
  import { wrap, unwrap } from './envelope.js'
30
- import { EpochAutobee, Keyring, wraps, epochEntries, loadEpochs } from './encryption.js'
31
- import { Identity } from '../identity/index.js'
20
+ import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
32
21
  import { CeroError } from '../lib/errors.js'
33
22
  import { bootstrap } from './bootstrap.js'
23
+ import { claim, claimOp, whenWritable, addWriter, removeWriter } from './membership.js'
24
+ import { before, after, onUpdate, onApply, runBefore, runAfter, touch, observe } from './hooks.js'
25
+ import { rotate, onepoch, hydrateEpochs, scheduleHeal, onfuture } from './rotation.js'
34
26
  import { makeChanges } from './changes.js'
35
27
  import { makeDispatcher } from './dispatch.js'
36
28
 
@@ -91,10 +83,8 @@ export class Database extends ReadyResource {
91
83
  this._rotation = null
92
84
  this._healTimer = null
93
85
  this._healedFor = null
94
- // membership and epochs both change through apply — after each update,
95
- // REMOVE-capable devices verify the current epoch still matches the
96
- // member set and re-key when it does not (see _healEpochs)
97
- this.on('update', () => this._scheduleHeal())
86
+ // REMOVE-capable devices re-key when the epoch drifts from the member set
87
+ this.on('update', () => scheduleHeal(this))
98
88
  this.applyOverride = opts.apply || null
99
89
  this.key = opts.key || null
100
90
  this.passive = opts.passive === true
@@ -129,14 +119,12 @@ export class Database extends ReadyResource {
129
119
  this._healTimer = null
130
120
  }
131
121
  if (this._discovery) {
132
- // unannounce in the background — awaiting the DHT round-trip here
133
- // blocks every close (and the writer-swap reboot) for seconds
122
+ // unannounce in the background, the DHT round-trip would block close for seconds
134
123
  this._discovery.destroy().catch(safetyCatch)
135
124
  this._discovery = null
136
125
  }
137
126
  if (this.bee) {
138
- // detach before closing — else the closed bee lingers in the network's
139
- // _replicateables set and gets replicated into every new connection
127
+ // detach first, else the closed bee replicates into every new connection
140
128
  if (this.network) this.network.detach(this.bee)
141
129
  await this.bee.close()
142
130
  this.bee = null
@@ -145,8 +133,7 @@ export class Database extends ReadyResource {
145
133
 
146
134
  /** Open the underlying autobee, wire dispatcher + apply, attach to network. */
147
135
  async openBee() {
148
- // prime the keyring from the local core's epoch stash BEFORE boot — the
149
- // bee's own boot reads post-rotation state through the epoch provider
136
+ // before boot: the bee's boot reads post-rotation state via the epoch provider
150
137
  const local = this.store.namespace(this.namespace).get({
151
138
  keyPair: this.keyPair,
152
139
  manifest: {
@@ -165,43 +152,25 @@ export class Database extends ReadyResource {
165
152
  this.routes,
166
153
  this._onerror,
167
154
  () => this.key,
168
- { onEpoch: (row) => this._onEpoch(row) }
155
+ { onEpoch: (row) => this._onepoch(row) }
169
156
  )
170
157
 
171
- // autobee-wakeup destroys whatever wakeup it is handed (its _owner guard is
172
- // computed but never consulted upstream) — closing one bee must not tear
173
- // down the network-shared protocol, so each bee gets a non-owning facade.
174
- // Drop the facade once upstream honors _owner.
175
- const shared = this.network?.wakeup
176
- const wakeup = shared && {
177
- addStream: (s) => shared.addStream(s),
178
- session: (...args) => shared.session(...args),
179
- destroy: () => {}
180
- }
181
-
182
158
  const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
183
159
  keyPair: this.keyPair,
184
160
  encryptionKey: this.encryptionKey,
185
161
  keyring: this.keyring,
186
162
  optimistic: true,
187
- wakeup: wakeup || undefined,
163
+ wakeup: this.network?.wakeup || undefined,
188
164
  open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
189
- // without this hook autobee trusts EVERY fast-forward candidate, so a
190
- // removed device could serve a stale or forked head and we would boot
191
- // onto it. A head is only worth following if its writer is still a
192
- // device — decided against the reference view autobee hands us (its own
193
- // state at the point of the decision), never the live view. Untrusted
194
- // heads are then skipped outright: mostRecentTrusted stays unset because
195
- // no cero row records another writer's oplog length to fall back to.
165
+ // without this hook autobee trusts EVERY fast-forward candidate, so a removed
166
+ // device could serve a forked head. Decided against the reference view, not live.
196
167
  isTrusted: async (writer, view) => {
197
168
  try {
198
169
  const row = await bounded(view.get(`@${this.ns}/devices`, { id: toId(writer) }))
199
170
  if (!row) return false
200
171
  if (row.v) return true
201
- // only where the view PROVABLY holds no device yet (a boot's
202
- // genesis-era reference) may the genesis writer vouch — its core IS
203
- // the db key, and its signatures are unforgeable. Everyone else
204
- // stays refused: an empty view is the window an ex-member targets.
172
+ // only a PROVABLY empty view (genesis-era reference) lets the genesis
173
+ // writer vouch, its core IS the db key. Otherwise it is an ex-member's window.
205
174
  const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
206
175
  if (!any) return false
207
176
  return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
@@ -210,27 +179,23 @@ export class Database extends ReadyResource {
210
179
  }
211
180
  },
212
181
  apply: async (nodes, view, host) => {
213
- // envelope handling lives here, once: unwrap every node and skip ops
214
- // from a newer app version (deterministic — they stay in the log), so
215
- // the dispatcher AND custom apply overrides see plain op bytes
182
+ // unwrap once so overrides see op bytes. Skipping a newer version is deterministic.
216
183
  const ready = []
217
184
  for (const node of nodes) {
218
185
  const { version, body } = unwrap(node.value)
219
186
  if (version > this.version) {
220
- this._onFuture(version)
187
+ onfuture(this, version)
221
188
  continue
222
189
  }
223
190
  ready.push(version === 0 ? node : { ...node, value: body })
224
191
  }
225
192
  const result = await (this.applyOverride || this.dispatcher.apply)(ready, view, host)
226
- if (this.updaters.size) this._touch(ready)
227
- if (this.onApplyHooks.size) this._observe(ready)
193
+ if (this.updaters.size) touch(this, ready)
194
+ if (this.onApplyHooks.size) observe(this, ready)
228
195
  return result
229
196
  },
230
197
  update: async (db) => {
231
198
  await db.update()
232
- // fire only watchers whose ref was touched by this apply batch —
233
- // unscoped watchers (and undecodable nodes, '*') fire everything
234
199
  const touched = this._touched
235
200
  this._touched = new Set()
236
201
  const all = touched.size === 0 || touched.has('*')
@@ -241,15 +206,12 @@ export class Database extends ReadyResource {
241
206
  }
242
207
  })
243
208
 
244
- // swarm BEFORE boot when the key is known: replication is live while the
245
- // bee opens, so the boot (and a future fast-forward boot) has peers to
246
- // pull from instead of opening cold and waiting for discovery
209
+ // swarm BEFORE boot so the boot has peers to pull from, not a cold open
247
210
  const known = !!this.key
248
211
  if (this.network && known) this._joinSwarm(bee, crypto.discoveryKey(this.key))
249
212
 
250
213
  await bee.ready()
251
- // assigned before the first update: apply-time hooks (_onEpoch's save,
252
- // _onFuture) dereference this.bee and must never see it null mid-drain
214
+ // apply-time hooks (_onepoch, _onfuture) must never see this.bee null mid-drain
253
215
  this.bee = bee
254
216
  this.key = bee.key
255
217
  await bee.update()
@@ -257,8 +219,7 @@ export class Database extends ReadyResource {
257
219
  const behind = await bee.local.getUserData('cero/behind')
258
220
  this.behind = behind ? c.decode(c.uint, behind) : null
259
221
 
260
- // ops we once skipped are now within our contract — wipe the boot record
261
- // so the next open replays the whole log through the current handlers
222
+ // skipped ops are now in contract, wipe the boot record so the next open replays
262
223
  if (this.behind !== null && this.behind <= this.version) {
263
224
  await bee.local.setUserData('autobee/head', null)
264
225
  await bee.local.setUserData('cero/behind', null)
@@ -269,24 +230,20 @@ export class Database extends ReadyResource {
269
230
  return
270
231
  }
271
232
 
272
- // prime the keyring from local userData before replication can deliver
273
- // blocks at epochs this session hasn't learned yet
233
+ // before replication can deliver blocks at epochs we haven't learned yet
274
234
  await this._loadEpochs()
275
235
 
276
236
  bee.on('writable', () => this.emit('writable'))
277
- // the falling edge: this device's writer was removed (or its member was).
278
- // Apps need it to freeze a UI the moment access ends, rather than
279
- // discovering it from a failed write or by scanning `members`.
237
+ // falling edge: apps freeze the UI the moment access ends
280
238
  bee.on('unwritable', () => this.emit('unwritable'))
281
239
  // without a listener autobee escalates apply/view errors to a process crash
282
240
  bee.on('error', this._onerror)
283
241
 
284
- // a fresh db has no key until boot mints it — join once it exists
242
+ // a fresh db has no key until boot mints it
285
243
  if (this.network && !known) this._joinSwarm(bee, bee.discoveryKey)
286
244
  }
287
245
 
288
- // a writer swap re-opens the bee on the SAME topic — join first so the old
289
- // session's destroy is a refcounted detach, not a DHT unannounce round-trip
246
+ // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
290
247
  _joinSwarm(bee, discoveryKey) {
291
248
  this.network.attach(bee)
292
249
  const prev = this._discovery
@@ -341,7 +298,7 @@ export class Database extends ReadyResource {
341
298
  * @returns {() => void} disposer
342
299
  */
343
300
  before(op, fn) {
344
- return this._addHook(this.beforeHooks, op, fn)
301
+ return before(this, op, fn)
345
302
  }
346
303
 
347
304
  /**
@@ -352,7 +309,7 @@ export class Database extends ReadyResource {
352
309
  * @returns {() => void} disposer
353
310
  */
354
311
  after(op, fn) {
355
- return this._addHook(this.afterHooks, op, fn)
312
+ return after(this, op, fn)
356
313
  }
357
314
 
358
315
  /**
@@ -364,33 +321,7 @@ export class Database extends ReadyResource {
364
321
  * @returns {() => void} disposer
365
322
  */
366
323
  onUpdate(fn, scope) {
367
- this.updaters.set(fn, scope || null)
368
- return () => this.updaters.delete(fn)
369
- }
370
-
371
- // record which refs an apply batch mutated, so update only wakes their watchers
372
- _touch(nodes) {
373
- if (!this._byVerb) {
374
- this._byVerb = new Map()
375
- for (const [name, info] of Object.entries(this.refs)) {
376
- this._byVerb.set(info.verb || name, name)
377
- this._byVerb.set(name, name)
378
- }
379
- }
380
- for (const node of nodes) {
381
- try {
382
- const { name } = this.spec.dispatch.decode(node.value)
383
- const verb = name.slice(name.indexOf('/') + 1)
384
- const dash = verb.indexOf('-')
385
- const target = dash < 0 ? verb : verb.slice(dash + 1)
386
- const ref = this._byVerb.get(target)
387
- // an action's route handler writes wherever it wants — widen to all
388
- if (!ref || this.refs[ref]?.kind === ACTION) this._touched.add('*')
389
- else this._touched.add(ref)
390
- } catch {
391
- this._touched.add('*')
392
- }
393
- }
324
+ return onUpdate(this, fn, scope)
394
325
  }
395
326
 
396
327
  /**
@@ -403,37 +334,7 @@ export class Database extends ReadyResource {
403
334
  * @returns {() => void} disposer
404
335
  */
405
336
  onApply(fn) {
406
- if (typeof fn !== 'function') return () => {}
407
- this.onApplyHooks.add(fn)
408
- return () => this.onApplyHooks.delete(fn)
409
- }
410
-
411
- _observe(nodes) {
412
- for (const node of nodes) {
413
- let event
414
- try {
415
- const { name, value } = this.spec.dispatch.decode(node.value)
416
- const verb = name.slice(name.indexOf('/') + 1) // '@cero/set-messages' → 'set-messages'
417
- const dash = verb.indexOf('-')
418
- event = {
419
- op: dash < 0 ? verb : verb.slice(0, dash),
420
- name: dash < 0 ? verb : verb.slice(dash + 1),
421
- row: value,
422
- writerKey: node.key,
423
- seq: this._applySeq++
424
- }
425
- } catch (err) {
426
- safetyCatch(err)
427
- continue
428
- }
429
- for (const fn of this.onApplyHooks) {
430
- try {
431
- fn(event)
432
- } catch (err) {
433
- this._onerror(err)
434
- }
435
- }
436
- }
337
+ return onApply(this, fn)
437
338
  }
438
339
 
439
340
  /**
@@ -444,15 +345,7 @@ export class Database extends ReadyResource {
444
345
  * @returns {Promise<boolean>} `false` if any hook vetoed the op
445
346
  */
446
347
  async runBefore(op, ctx) {
447
- const hooks = this.beforeHooks.get(op)
448
- if (hooks) {
449
- for (const fn of hooks) {
450
- const out = await fn(ctx)
451
- if (out === false) return false
452
- }
453
- }
454
- this.emit(`before:${op}`, ctx)
455
- return true
348
+ return runBefore(this, op, ctx)
456
349
  }
457
350
 
458
351
  /**
@@ -463,17 +356,7 @@ export class Database extends ReadyResource {
463
356
  * @returns {Promise<void>}
464
357
  */
465
358
  async runAfter(op, ctx) {
466
- const hooks = this.afterHooks.get(op)
467
- if (hooks) {
468
- for (const fn of hooks) {
469
- try {
470
- await fn(ctx)
471
- } catch (err) {
472
- this._onerror(err)
473
- }
474
- }
475
- }
476
- this.emit(`after:${op}`, ctx)
359
+ return runAfter(this, op, ctx)
477
360
  }
478
361
 
479
362
  /**
@@ -535,7 +418,7 @@ export class Database extends ReadyResource {
535
418
  const ctx = { op: 'set', name, row: stored }
536
419
  if ((await this.runBefore('set', ctx)) === false) return null
537
420
 
538
- // member/device have bespoke set handlers — only generic collections upsert via add-
421
+ // member/device have bespoke set handlers, only generic collections upsert via add-
539
422
  const special = ref.verb === 'member' || ref.verb === 'device'
540
423
  const verb =
541
424
  ref.kind === COLLECTION && upsert && !special ? `add-${ref.verb}` : `set-${ref.verb}`
@@ -559,8 +442,7 @@ export class Database extends ReadyResource {
559
442
  const ctx = { op: 'del', name, id }
560
443
  if ((await this.runBefore('del', ctx)) === false) return null
561
444
 
562
- // Singles have no id — the apply handler wipes the keyless row; the dummy id
563
- // just satisfies the shared del-by-id encoding.
445
+ // singles have no id, the dummy one just satisfies the shared del-by-id encoding
564
446
  const payload = ref.kind === SINGLE ? { id: '' } : { id }
565
447
  await this.write([[`del-${ref.verb}`, payload]])
566
448
 
@@ -576,8 +458,7 @@ export class Database extends ReadyResource {
576
458
  */
577
459
  async call(op, data = {}) {
578
460
  this.guard()
579
- // A declared action with no local route would apply as a silent no-op — fail
580
- // loud before writing a dead op. (Builtin verbs aren't refs, so they pass.)
461
+ // a declared action with no local route applies as a silent no-op (builtins pass)
581
462
  if (this.refs[op]?.kind === ACTION && typeof this.routes[op] !== 'function') {
582
463
  throw CeroError.INVALID(
583
464
  `action '${op}' has no route — pass { routes: { ${op} } } when opening the handle`
@@ -597,202 +478,15 @@ export class Database extends ReadyResource {
597
478
  * @returns {Promise<{ epoch: number }>}
598
479
  */
599
480
  async rotate(retried = false) {
600
- this.guard()
601
- if (!this.writable) throw CeroError.NOT_WRITABLE('Database')
602
- // inside tx() the op would only be queued — the epoch could never be
603
- // observed before returning, and batching a rekey with app writes would
604
- // blur which epoch those writes land in
605
- if (this.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
606
- if (this._rotation) throw CeroError.INVALID('a rotation is already in progress')
607
- // compat-path (manifest v1) blocks carry no key id — rotation would be a
608
- // silent downgrade there, so refuse deterministically
609
- if (this.bee.local.manifest?.version < 2) {
610
- throw CeroError.INVALID('rotation requires manifest v2 cores')
611
- }
612
- // claimed synchronously — no await may separate the check from the claim
613
- this._rotation = { entropy: null, stamp: 0, epoch: 0 }
614
- try {
615
- const { data: members } = await this.get('members')
616
- if (!Array.isArray(members) || members.length === 0) {
617
- throw CeroError.INVALID('cannot rotate a database with no members')
618
- }
619
- const entropy = Identity.randomBytes(32)
620
- const stamp = this._randomStamp()
621
- const wrapped = []
622
- for (const m of members) {
623
- let key
624
- try {
625
- key = toKey(m.id)
626
- } catch {
627
- throw CeroError.INVALID(`member id is not an identity key: ${m.id}`)
628
- }
629
- wrapped.push({ id: m.id, box: Identity.seal(key, entropy) })
630
- }
631
- // Defer our own hydration until the append has flushed: the local block
632
- // is encrypted at drain time, AFTER our optimistic apply runs — advancing
633
- // the keyring there would encrypt the announcement itself under the new
634
- // epoch, which nobody else could read (the chain rule would break).
635
- this._rotation.entropy = entropy
636
- this._rotation.stamp = stamp
637
- const appendedFrom = this.bee.local.length
638
- await this.call('rotate-key', {
639
- epoch: 0, // sequence assigned deterministically at apply time
640
- stamp,
641
- wrapped: c.encode(wraps, wrapped),
642
- createdAt: Date.now(),
643
- commit: crypto.hash(entropy)
644
- })
645
- await this.bee.update()
646
- const { epoch } = this._rotation
647
- if (!epoch) {
648
- // distinguish a stamp collision (another epoch owns our random stamp
649
- // — ~2^-32, or an adversarial pre-claim) from a permission rejection
650
- const rows = await this.view.find(`@${this.ns}/epochs`, {}).toArray()
651
- if (!retried && rows.some((r) => r.stamp === stamp)) {
652
- this._rotation = null
653
- return this.rotate(true)
654
- }
655
- // permission is refused before the append now, so reaching this means
656
- // the op applied as a no-op for a reason the dry-run could not foresee
657
- throw CeroError.INVALID('rotation was not applied')
658
- }
659
- // Invariant check, not an assumption: no block appended during this
660
- // rotation may carry the stamp it announces — that would make the
661
- // announcement unreadable to every other member.
662
- for (let i = appendedFrom; i < this.bee.local.length; i++) {
663
- const raw = await this.bee.local.get(i, { raw: true })
664
- const id = c.uint32.decode({ start: 4, end: 8, buffer: raw.subarray(0, 8) })
665
- if (id === stamp) {
666
- throw CeroError.INVALID('announcement encrypted under its own epoch — aborting rotation')
667
- }
668
- }
669
- this.keyring.add(stamp, entropy, epoch)
670
- await this._saveEpochs()
671
- return { epoch }
672
- } finally {
673
- this._rotation = null
674
- }
481
+ return rotate(this, retried)
675
482
  }
676
483
 
677
- /** Fresh nonzero uint32 block-header stamp not already used by a known epoch. */
678
- _randomStamp() {
679
- for (;;) {
680
- const buf = Identity.randomBytes(4)
681
- const stamp = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]) >>> 0
682
- if (stamp !== 0 && !this.keyring.entropy(stamp)) return stamp
683
- }
484
+ async _onepoch(row) {
485
+ return onepoch(this, row)
684
486
  }
685
487
 
686
- /**
687
- * Per-peer side of an applied rotation: open our envelope, learn the epoch
688
- * secret, persist it locally. Peers without an envelope (removed members)
689
- * simply stop here — every block after the announcement is noise to them.
690
- * Our own in-flight rotation is deferred to `rotate()` (see above).
691
- *
692
- * @param {{ epoch: number, wrapped: Uint8Array, createdAt: number }} row
693
- */
694
- async _onEpoch(row) {
695
- if (this.keyring.entropy(row.stamp)) {
696
- // idempotent re-apply — but record the sequence if it was unknown
697
- this.keyring.add(row.stamp, this.keyring.entropy(row.stamp), row.epoch)
698
- this._scheduleHeal()
699
- return
700
- }
701
- for (const w of c.decode(wraps, row.wrapped)) {
702
- if (w.id !== this.identity.id) continue
703
- const entropy = this.identity.unseal(w.box)
704
- // skip malformed or mis-sealed envelopes and keep scanning — a bad
705
- // envelope ahead of a good one must not lock this member out
706
- if (entropy?.byteLength !== 32) continue
707
- // the secret must match the row's public commitment — otherwise a
708
- // rotator sealed different secrets to different members
709
- if (!row.commit || !b4a.equals(crypto.hash(entropy), row.commit)) {
710
- this._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
711
- continue
712
- }
713
- if (this._rotation?.entropy && b4a.equals(entropy, this._rotation.entropy)) {
714
- this._rotation.epoch = row.epoch
715
- } else {
716
- this.keyring.add(row.stamp, entropy, row.epoch)
717
- try {
718
- await this._saveEpochs()
719
- } catch (err) {
720
- // an epoch this device cannot reload after a restart must not be
721
- // used for writes — undo the add and surface the storage failure
722
- this.keyring.remove(row.stamp)
723
- this._onerror(err)
724
- }
725
- }
726
- break
727
- }
728
- this._scheduleHeal()
729
- }
730
-
731
- /**
732
- * Safety net after boot (userData priming happens in EpochAutobee's
733
- * `_bootState`): scan the epochs collection for anything applied but never
734
- * hydrated — e.g. a crash between a rotation's append and its save.
735
- */
736
488
  async _loadEpochs() {
737
- try {
738
- const rows = await this.view.find(`@${this.ns}/epochs`, {}).toArray()
739
- for (const row of rows) {
740
- if (this.keyring.entropy(row.stamp)) continue
741
- await this._onEpoch(row)
742
- }
743
- } catch {
744
- // pre-rotation spec (no epochs collection), or rows beyond our newest
745
- // known epoch — those hydrate through apply when announcements sync
746
- }
747
- }
748
-
749
- /** Persist known epoch secrets to local userData (device-only, never replicates). */
750
- _saveEpochs() {
751
- return this.bee.local.setUserData('cero/epochs', c.encode(epochEntries, this.keyring.all()))
752
- }
753
-
754
- /** Debounced trigger for the epoch/membership consistency check. */
755
- _scheduleHeal() {
756
- if (this._healTimer || this.closing || this.closed) return
757
- this._healTimer = setTimeout(() => {
758
- this._healTimer = null
759
- this._healEpochs().catch(this._onerror)
760
- }, 500)
761
- }
762
-
763
- /**
764
- * Convergence rotation: rotations author their envelope set against the
765
- * rotator's possibly-stale local view, so after linearization the current
766
- * epoch may include a since-removed member (who then still holds the
767
- * current key) or miss a since-added one (who is locked out). Every
768
- * REMOVE-capable writable device audits the current epoch's recipients
769
- * against canonical membership and re-keys on mismatch. Only rooms that
770
- * have rotated at least once are audited — rotation stays opt-in.
771
- */
772
- async _healEpochs() {
773
- if (this.closing || this.closed || !this.writable || this._rotation) return
774
- if (!this.keyring.current) return
775
- const { data: device } = await this.get('devices', toId(this.writerKey))
776
- const me = device?.memberId ? (await this.get('members', device.memberId)).data : null
777
- if (!can(me?.role, REMOVE)) return
778
-
779
- const rows = await this.view.find(`@${this.ns}/epochs`, {}).toArray()
780
- if (!rows.length) return
781
- const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
782
- const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
783
- const { data: members } = await this.get('members')
784
- const ids = new Set(members.map((m) => m.id))
785
- const clean = recipients.size === ids.size && [...recipients].every((id) => ids.has(id))
786
- if (clean) {
787
- this._healedFor = null
788
- return
789
- }
790
- // one attempt per (epoch, membership) state — a failing rotate (e.g. a
791
- // permission race) must not loop; any state change re-arms the audit
792
- const state = `${top.stamp}:${[...ids].sort().join(',')}`
793
- if (this._healedFor === state) return
794
- this._healedFor = state
795
- await this.rotate()
489
+ return hydrateEpochs(this)
796
490
  }
797
491
 
798
492
  /**
@@ -809,14 +503,12 @@ export class Database extends ReadyResource {
809
503
  * @returns {Promise<T>}
810
504
  */
811
505
  async tx(fn) {
812
- // The old form batched ambiently — writes on the database itself would
813
- // silently lose atomicity now, so refuse a fn that ignores the handle.
506
+ // refuse a fn that ignores the handle, ambient batching silently loses atomicity
814
507
  if (typeof fn !== 'function' || fn.length < 1) {
815
508
  throw CeroError.INVALID('tx(fn) — fn must accept the transaction handle: tx((tx) => ...)')
816
509
  }
817
- // Nested tx() (called on a transaction handle) joins the same batch.
818
510
  if (this.txQueue) return fn(this)
819
- // Outer transactions serialize so their appends land in call order.
511
+ // outer transactions serialize so their appends land in call order
820
512
  const run = async () => {
821
513
  const batch = Object.create(this)
822
514
  batch.txQueue = []
@@ -842,18 +534,14 @@ export class Database extends ReadyResource {
842
534
  for (const op of ops) this.txQueue.push(op)
843
535
  return
844
536
  }
845
- // `closing` flips the moment close() starts; `bee` only goes null once it
846
- // has finished, and everything in between is a torn-down bee behind a
847
- // truthy flag
537
+ // between `closing` and a null `bee` sits a torn-down bee behind a truthy flag
848
538
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
849
539
  if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
850
540
  const encoded = ops.map(([op, payload]) =>
851
541
  this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
852
542
  )
853
- // the dry-run rejects what apply would refuse, and says whether the ops
854
- // change anything at all — one that touches nothing never reaches the log.
855
- // An action is the exception: what it does lives in the routes of every
856
- // peer, not in the rows this dry-run can see, so it always ships.
543
+ // the dry-run rejects what apply would refuse, and an op touching nothing never
544
+ // reaches the log. An action ships anyway: it lives in routes, not in rows.
857
545
  const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
858
546
  let changes
859
547
  try {
@@ -862,27 +550,13 @@ export class Database extends ReadyResource {
862
550
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
863
551
  throw err
864
552
  }
865
- // the dry-run awaits — close can start underneath it
553
+ // the dry-run awaits, close can start underneath it
866
554
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
867
555
  if (!changes && !action) return
868
556
  const wrapped = encoded.map((value) => wrap(this.version, value))
869
557
  await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
870
558
  }
871
559
 
872
- /**
873
- * Record that the log contains ops from a newer app version than this
874
- * peer understands. Fires `'behind'` once per version so apps can prompt
875
- * an upgrade; the marker survives restarts via local core userData.
876
- *
877
- * @param {number} version
878
- */
879
- _onFuture(version) {
880
- if (this.behind !== null && version <= this.behind) return
881
- this.behind = version
882
- this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
883
- this.emit('behind', version)
884
- }
885
-
886
560
  /**
887
561
  * Validate ops against the committed view before appending: each op runs in
888
562
  * a throwaway transaction with host effects stubbed, so a throwing handler
@@ -945,10 +619,7 @@ export class Database extends ReadyResource {
945
619
  return { data, total: rows.length, size: data.length }
946
620
  }
947
621
 
948
- // Hot path — reverse/limit only ("latest 50 messages"): read straight off
949
- // the implicit `index` order index, touching ≤ limit rows instead of the
950
- // whole collection. `total` is then lazy: pass { total: true } to pay for
951
- // the full count, otherwise it's null when unknowable for free.
622
+ // read off the implicit `index` order index, touching ≤ limit rows. total goes lazy.
952
623
  if (this.refs[name]?.orderIndex && pushable(query) && (await this._orderReady(name, col))) {
953
624
  const rows = await this.view
954
625
  .find(`@${this.ns}/${name}-index`, {
@@ -960,7 +631,6 @@ export class Database extends ReadyResource {
960
631
  return { data: rows, total, size: rows.length }
961
632
  }
962
633
 
963
- // id-range cursor: push the range down (bounded read), keep index order.
964
634
  if (this.refs[name]?.orderIndex && pushableRange(query)) {
965
635
  const range = {}
966
636
  for (const k of ['gt', 'gte', 'lt', 'lte']) {
@@ -974,17 +644,14 @@ export class Database extends ReadyResource {
974
644
  }
975
645
 
976
646
  const all = await this.view.find(col, {}).toArray()
977
- // collections carry an auto-increment `index`; return them in that order
978
647
  all.sort((a, b) => (a.index ?? 0) - (b.index ?? 0))
979
648
  const total = all.length
980
649
  const data = paginate(all, query)
981
650
  return { data, total, size: data.length }
982
651
  }
983
652
 
984
- // hyperdb never backfills an index added after rows were written — a store
985
- // upgraded to a spec with the implicit order index would silently drop its
986
- // legacy rows from pushed-down reads. Verify completeness ONCE per open
987
- // (two scans, cached), then trust the index; incomplete → fall back + warn.
653
+ // hyperdb never backfills an index added after rows were written, so an upgraded
654
+ // store would drop legacy rows. Verify completeness once per open, then trust it.
988
655
  async _orderReady(name, col) {
989
656
  if (!this._orderOk) this._orderOk = new Map()
990
657
  let ok = this._orderOk.get(name)
@@ -1006,9 +673,6 @@ export class Database extends ReadyResource {
1006
673
  return ok
1007
674
  }
1008
675
 
1009
- // total for a pushed-down read: free when the page IS the whole set (no
1010
- // limit, or a non-full page), a full count only when explicitly requested
1011
- // via { total: true }, null otherwise.
1012
676
  async _total(col, query, rows) {
1013
677
  if (query?.total) return (await this.view.find(col, {}).toArray()).length
1014
678
  if (query?.limit === undefined || rows.length < query.limit) return rows.length
@@ -1083,26 +747,18 @@ export class Database extends ReadyResource {
1083
747
 
1084
748
  /**
1085
749
  * Claim writership on an existing room by signing our writer key with the
1086
- * member identity and appending optimistically. Admission only — the device
1087
- * is named separately (bootstrap → set-device).
750
+ * member identity; the claim rides in the device core as an optimistic node.
751
+ * Admission only — the device is named separately (bootstrap → set-device).
1088
752
  *
1089
753
  * @returns {Promise<void>}
1090
754
  */
1091
755
  async claim() {
1092
- this.guard()
1093
- if (this.bee.writable) return
1094
-
1095
- const writerKey = this.writerKey
1096
- const sig = this.identity.sign(claimWriterPayload(this.key, writerKey))
1097
- const encoded = this.spec.dispatch.encode(`@${this.ns}/claim-writer`, {
1098
- identity: this.identity.publicKey,
1099
- writer: writerKey,
1100
- sig,
1101
- ts: Date.now()
1102
- })
1103
- await this.bee.append(wrap(this.version, encoded), { optimistic: true })
1104
- await this.bee.update()
1105
- if (!this.bee.writable) await this.whenWritable()
756
+ return claim(this)
757
+ }
758
+
759
+ /** The claim-writer op for this device, signed by the member identity. */
760
+ claimOp() {
761
+ return claimOp(this)
1106
762
  }
1107
763
 
1108
764
  /**
@@ -1111,42 +767,8 @@ export class Database extends ReadyResource {
1111
767
  * @param {{ timeout?: number }} [opts]
1112
768
  * @returns {Promise<void>}
1113
769
  */
1114
- async whenWritable({ timeout = 30000 } = {}) {
1115
- this.guard()
1116
- if (this.bee.writable) return
1117
- return new Promise((resolve, reject) => {
1118
- let timer = null
1119
- let pollTimer = null
1120
- let done = false
1121
-
1122
- const finish = (err) => {
1123
- if (done) return
1124
- done = true
1125
- if (timer) clearTimeout(timer)
1126
- if (pollTimer) clearInterval(pollTimer)
1127
- if (this.bee) this.bee.off('writable', onWritable)
1128
- this.off('close', onClose)
1129
- if (err) reject(err)
1130
- else resolve()
1131
- }
1132
-
1133
- const onWritable = () => finish()
1134
- const onClose = () => finish(CeroError.CLOSED('Database'))
1135
- const poll = async () => {
1136
- if (done || !this.bee) return
1137
- try {
1138
- await this.bee.update()
1139
- if (!done && this.bee.writable) finish()
1140
- } catch {}
1141
- }
1142
-
1143
- this.bee.on('writable', onWritable)
1144
- this.on('close', onClose)
1145
- pollTimer = setInterval(poll, 1000)
1146
- if (timeout > 0) {
1147
- timer = setTimeout(() => finish(CeroError.TIMED_OUT('whenWritable')), timeout)
1148
- }
1149
- })
770
+ async whenWritable(opts) {
771
+ return whenWritable(this, opts)
1150
772
  }
1151
773
 
1152
774
  /**
@@ -1156,7 +778,7 @@ export class Database extends ReadyResource {
1156
778
  * @returns {Promise<void>}
1157
779
  */
1158
780
  async addWriter(publicKey) {
1159
- return this._write('add-writer', 'addWriter', publicKey)
781
+ return addWriter(this, publicKey)
1160
782
  }
1161
783
 
1162
784
  /**
@@ -1166,7 +788,7 @@ export class Database extends ReadyResource {
1166
788
  * @returns {Promise<void>}
1167
789
  */
1168
790
  async removeWriter(publicKey) {
1169
- return this._write('del-writer', 'removeWriter', publicKey)
791
+ return removeWriter(this, publicKey)
1170
792
  }
1171
793
 
1172
794
  /**
@@ -1186,8 +808,9 @@ export class Database extends ReadyResource {
1186
808
  * @returns {Ref}
1187
809
  */
1188
810
  ref(name) {
1189
- if (typeof name !== 'string' || !name)
811
+ if (typeof name !== 'string' || !name) {
1190
812
  throw CeroError.INVALID('name must be a non-empty string')
813
+ }
1191
814
  const ref = this.refs[name]
1192
815
  if (!ref) throw CeroError.UNKNOWN('ref', name)
1193
816
  return { name, kind: ref.kind || COLLECTION, verb: ref.verb || name }
@@ -1203,9 +826,7 @@ export class Database extends ReadyResource {
1203
826
  return `@${this.ns}/${ref.name}`
1204
827
  }
1205
828
 
1206
- // Reject a write that carries a field the schema doesn't declare — the encoder
1207
- // would silently drop it, so the returned row would lie. Builtins (and specs
1208
- // built before field info shipped) carry no `fields`, so they skip validation.
829
+ // the encoder silently drops an undeclared field, so the returned row would lie
1209
830
  _checkFields(name, row) {
1210
831
  const declared = this.refs[name]?.fields
1211
832
  if (!declared || !row) return
@@ -1233,24 +854,13 @@ export class Database extends ReadyResource {
1233
854
  if (idxFields.length === fields.length && idxFields.every((f) => fields.includes(f))) {
1234
855
  const point = {}
1235
856
  for (const f of idxFields) point[f] = query[f]
1236
- // point lookup only — search/range/reverse/limit are applied by paginate
857
+ // point lookup only, paginate applies search/range/reverse/limit
1237
858
  return { path: `@${this.ns}/${name}-${idx}`, range: { gte: point, lte: point } }
1238
859
  }
1239
860
  }
1240
861
  return null
1241
862
  }
1242
863
 
1243
- _addHook(map, op, fn) {
1244
- if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
1245
- let arr = map.get(op)
1246
- if (!arr) map.set(op, (arr = []))
1247
- arr.push(fn)
1248
- return () => {
1249
- const i = arr.indexOf(fn)
1250
- if (i >= 0) arr.splice(i, 1)
1251
- }
1252
- }
1253
-
1254
864
  async _write(verb, hook, publicKey) {
1255
865
  this.guard()
1256
866
  if (!b4a.isBuffer(publicKey)) {
@@ -1270,33 +880,29 @@ export class Database extends ReadyResource {
1270
880
  }
1271
881
  }
1272
882
 
1273
- // A trust decision reads a historic checkout view, whose blocks may not be
1274
- // servable yet — an unbounded read there wedges autobee's drain forever. The
1275
- // value is wrapped so a timeout (null) is never mistaken for what the read
1276
- // would have returned; undecidable in time means "not trusted", and the
1277
- // caller retries.
883
+ // a trust decision reads a historic checkout whose blocks may not be servable yet,
884
+ // and an unbounded read there wedges autobee's drain forever. null means untrusted.
1278
885
  const bounded = (promise, ms = 2000) =>
1279
886
  Promise.race([
1280
887
  promise.then((v) => ({ v })),
1281
888
  new Promise((resolve) => setTimeout(() => resolve(null), ms))
1282
889
  ])
1283
890
 
1284
- // Fields the write path stamps itself — always allowed even if not user-declared.
891
+ // fields the write path stamps itself, always allowed
1285
892
  const SYSTEM_FIELDS = new Set(['id', 'memberId', 'index', 'createdAt', 'updatedAt'])
1286
893
 
1287
- // Match a query value against a stored value (bytes compared by content).
1288
894
  const valueEq = (a, b) => {
1289
895
  if (a instanceof Uint8Array && b instanceof Uint8Array) return b4a.equals(a, b)
1290
896
  return a === b
1291
897
  }
1292
898
 
1293
- // reverse/limit (+ the total flag) only — safe to serve straight off the order index
899
+ // reverse/limit (+ total) only, safe to serve straight off the order index
1294
900
  function pushable(query) {
1295
901
  if (!query) return true
1296
902
  return Object.keys(query).every((k) => k === 'reverse' || k === 'limit' || k === 'total')
1297
903
  }
1298
904
 
1299
- // an id-range with no equality/search — the range pushes down, order stays in memory
905
+ // an id-range with no equality/search, the range pushes down, order stays in memory
1300
906
  function pushableRange(query) {
1301
907
  if (!query) return false
1302
908
  const keys = Object.keys(query)
@@ -1316,9 +922,7 @@ function pushableRange(query) {
1316
922
  function paginate(rows, query) {
1317
923
  if (!query) return rows
1318
924
  let out = rows
1319
- // Exact-field equality: every non-reserved key filters in memory. The secondary
1320
- // index is an optimization, not a correctness gate — so an unindexed field, or
1321
- // one passed alongside search/range, still filters instead of silently dropping.
925
+ // the secondary index is an optimization, not a correctness gate
1322
926
  for (const key of Object.keys(query)) {
1323
927
  if (QUERY_RESERVED.has(key)) continue
1324
928
  out = out.filter((r) => valueEq(r[key], query[key]))