@cero-base/core 1.16.1 → 1.18.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.
@@ -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,200 +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
- throw CeroError.INVALID('rotation was not applied — requires the remove permission')
656
- }
657
- // Invariant check, not an assumption: no block appended during this
658
- // rotation may carry the stamp it announces — that would make the
659
- // announcement unreadable to every other member.
660
- for (let i = appendedFrom; i < this.bee.local.length; i++) {
661
- const raw = await this.bee.local.get(i, { raw: true })
662
- const id = c.uint32.decode({ start: 4, end: 8, buffer: raw.subarray(0, 8) })
663
- if (id === stamp) {
664
- throw CeroError.INVALID('announcement encrypted under its own epoch — aborting rotation')
665
- }
666
- }
667
- this.keyring.add(stamp, entropy, epoch)
668
- await this._saveEpochs()
669
- return { epoch }
670
- } finally {
671
- this._rotation = null
672
- }
481
+ return rotate(this, retried)
673
482
  }
674
483
 
675
- /** Fresh nonzero uint32 block-header stamp not already used by a known epoch. */
676
- _randomStamp() {
677
- for (;;) {
678
- const buf = Identity.randomBytes(4)
679
- const stamp = ((buf[0] << 24) | (buf[1] << 16) | (buf[2] << 8) | buf[3]) >>> 0
680
- if (stamp !== 0 && !this.keyring.entropy(stamp)) return stamp
681
- }
484
+ async _onepoch(row) {
485
+ return onepoch(this, row)
682
486
  }
683
487
 
684
- /**
685
- * Per-peer side of an applied rotation: open our envelope, learn the epoch
686
- * secret, persist it locally. Peers without an envelope (removed members)
687
- * simply stop here — every block after the announcement is noise to them.
688
- * Our own in-flight rotation is deferred to `rotate()` (see above).
689
- *
690
- * @param {{ epoch: number, wrapped: Uint8Array, createdAt: number }} row
691
- */
692
- async _onEpoch(row) {
693
- if (this.keyring.entropy(row.stamp)) {
694
- // idempotent re-apply — but record the sequence if it was unknown
695
- this.keyring.add(row.stamp, this.keyring.entropy(row.stamp), row.epoch)
696
- this._scheduleHeal()
697
- return
698
- }
699
- for (const w of c.decode(wraps, row.wrapped)) {
700
- if (w.id !== this.identity.id) continue
701
- const entropy = this.identity.unseal(w.box)
702
- // skip malformed or mis-sealed envelopes and keep scanning — a bad
703
- // envelope ahead of a good one must not lock this member out
704
- if (entropy?.byteLength !== 32) continue
705
- // the secret must match the row's public commitment — otherwise a
706
- // rotator sealed different secrets to different members
707
- if (!row.commit || !b4a.equals(crypto.hash(entropy), row.commit)) {
708
- this._onerror(CeroError.INVALID(`epoch ${row.epoch} envelope fails its commitment`))
709
- continue
710
- }
711
- if (this._rotation?.entropy && b4a.equals(entropy, this._rotation.entropy)) {
712
- this._rotation.epoch = row.epoch
713
- } else {
714
- this.keyring.add(row.stamp, entropy, row.epoch)
715
- try {
716
- await this._saveEpochs()
717
- } catch (err) {
718
- // an epoch this device cannot reload after a restart must not be
719
- // used for writes — undo the add and surface the storage failure
720
- this.keyring.remove(row.stamp)
721
- this._onerror(err)
722
- }
723
- }
724
- break
725
- }
726
- this._scheduleHeal()
727
- }
728
-
729
- /**
730
- * Safety net after boot (userData priming happens in EpochAutobee's
731
- * `_bootState`): scan the epochs collection for anything applied but never
732
- * hydrated — e.g. a crash between a rotation's append and its save.
733
- */
734
488
  async _loadEpochs() {
735
- try {
736
- const rows = await this.view.find(`@${this.ns}/epochs`, {}).toArray()
737
- for (const row of rows) {
738
- if (this.keyring.entropy(row.stamp)) continue
739
- await this._onEpoch(row)
740
- }
741
- } catch {
742
- // pre-rotation spec (no epochs collection), or rows beyond our newest
743
- // known epoch — those hydrate through apply when announcements sync
744
- }
745
- }
746
-
747
- /** Persist known epoch secrets to local userData (device-only, never replicates). */
748
- _saveEpochs() {
749
- return this.bee.local.setUserData('cero/epochs', c.encode(epochEntries, this.keyring.all()))
750
- }
751
-
752
- /** Debounced trigger for the epoch/membership consistency check. */
753
- _scheduleHeal() {
754
- if (this._healTimer || this.closing || this.closed) return
755
- this._healTimer = setTimeout(() => {
756
- this._healTimer = null
757
- this._healEpochs().catch(this._onerror)
758
- }, 500)
759
- }
760
-
761
- /**
762
- * Convergence rotation: rotations author their envelope set against the
763
- * rotator's possibly-stale local view, so after linearization the current
764
- * epoch may include a since-removed member (who then still holds the
765
- * current key) or miss a since-added one (who is locked out). Every
766
- * REMOVE-capable writable device audits the current epoch's recipients
767
- * against canonical membership and re-keys on mismatch. Only rooms that
768
- * have rotated at least once are audited — rotation stays opt-in.
769
- */
770
- async _healEpochs() {
771
- if (this.closing || this.closed || !this.writable || this._rotation) return
772
- if (!this.keyring.current) return
773
- const { data: device } = await this.get('devices', toId(this.writerKey))
774
- const me = device?.memberId ? (await this.get('members', device.memberId)).data : null
775
- if (!can(me?.role, REMOVE)) return
776
-
777
- const rows = await this.view.find(`@${this.ns}/epochs`, {}).toArray()
778
- if (!rows.length) return
779
- const top = rows.reduce((a, b) => (b.epoch > a.epoch ? b : a))
780
- const recipients = new Set(c.decode(wraps, top.wrapped).map((w) => w.id))
781
- const { data: members } = await this.get('members')
782
- const ids = new Set(members.map((m) => m.id))
783
- const clean = recipients.size === ids.size && [...recipients].every((id) => ids.has(id))
784
- if (clean) {
785
- this._healedFor = null
786
- return
787
- }
788
- // one attempt per (epoch, membership) state — a failing rotate (e.g. a
789
- // permission race) must not loop; any state change re-arms the audit
790
- const state = `${top.stamp}:${[...ids].sort().join(',')}`
791
- if (this._healedFor === state) return
792
- this._healedFor = state
793
- await this.rotate()
489
+ return hydrateEpochs(this)
794
490
  }
795
491
 
796
492
  /**
@@ -807,14 +503,12 @@ export class Database extends ReadyResource {
807
503
  * @returns {Promise<T>}
808
504
  */
809
505
  async tx(fn) {
810
- // The old form batched ambiently — writes on the database itself would
811
- // 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
812
507
  if (typeof fn !== 'function' || fn.length < 1) {
813
508
  throw CeroError.INVALID('tx(fn) — fn must accept the transaction handle: tx((tx) => ...)')
814
509
  }
815
- // Nested tx() (called on a transaction handle) joins the same batch.
816
510
  if (this.txQueue) return fn(this)
817
- // Outer transactions serialize so their appends land in call order.
511
+ // outer transactions serialize so their appends land in call order
818
512
  const run = async () => {
819
513
  const batch = Object.create(this)
820
514
  batch.txQueue = []
@@ -840,37 +534,29 @@ export class Database extends ReadyResource {
840
534
  for (const op of ops) this.txQueue.push(op)
841
535
  return
842
536
  }
843
- if (!this.bee) throw CeroError.CLOSED('Database')
537
+ // between `closing` and a null `bee` sits a torn-down bee behind a truthy flag
538
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
844
539
  if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
845
540
  const encoded = ops.map(([op, payload]) =>
846
541
  this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
847
542
  )
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.
545
+ const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
546
+ let changes
848
547
  try {
849
- await this._dryRun(encoded)
548
+ changes = await this._dryRun(encoded)
850
549
  } catch (err) {
851
- if (!this.bee) throw CeroError.CLOSED('Database')
550
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
852
551
  throw err
853
552
  }
854
- // the dry-run awaits — the bee can close underneath it
855
- if (!this.bee) throw CeroError.CLOSED('Database')
553
+ // the dry-run awaits, close can start underneath it
554
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
555
+ if (!changes && !action) return
856
556
  const wrapped = encoded.map((value) => wrap(this.version, value))
857
557
  await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
858
558
  }
859
559
 
860
- /**
861
- * Record that the log contains ops from a newer app version than this
862
- * peer understands. Fires `'behind'` once per version so apps can prompt
863
- * an upgrade; the marker survives restarts via local core userData.
864
- *
865
- * @param {number} version
866
- */
867
- _onFuture(version) {
868
- if (this.behind !== null && version <= this.behind) return
869
- this.behind = version
870
- this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
871
- this.emit('behind', version)
872
- }
873
-
874
560
  /**
875
561
  * Validate ops against the committed view before appending: each op runs in
876
562
  * a throwaway transaction with host effects stubbed, so a throwing handler
@@ -879,6 +565,7 @@ export class Database extends ReadyResource {
879
565
  * linearization time.
880
566
  *
881
567
  * @param {Uint8Array[]} encoded
568
+ * @returns {Promise<boolean>} whether the ops change anything
882
569
  */
883
570
  async _dryRun(encoded) {
884
571
  const tx = this.view.transaction()
@@ -893,8 +580,14 @@ export class Database extends ReadyResource {
893
580
  dryRun: true
894
581
  })
895
582
  }
583
+ return tx.updated()
896
584
  } finally {
897
- await tx.close()
585
+ // a failing close must not mask the handler's own rejection
586
+ try {
587
+ await tx.close()
588
+ } catch (err) {
589
+ safetyCatch(err)
590
+ }
898
591
  }
899
592
  }
900
593
 
@@ -926,10 +619,7 @@ export class Database extends ReadyResource {
926
619
  return { data, total: rows.length, size: data.length }
927
620
  }
928
621
 
929
- // Hot path — reverse/limit only ("latest 50 messages"): read straight off
930
- // the implicit `index` order index, touching ≤ limit rows instead of the
931
- // whole collection. `total` is then lazy: pass { total: true } to pay for
932
- // 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.
933
623
  if (this.refs[name]?.orderIndex && pushable(query) && (await this._orderReady(name, col))) {
934
624
  const rows = await this.view
935
625
  .find(`@${this.ns}/${name}-index`, {
@@ -941,7 +631,6 @@ export class Database extends ReadyResource {
941
631
  return { data: rows, total, size: rows.length }
942
632
  }
943
633
 
944
- // id-range cursor: push the range down (bounded read), keep index order.
945
634
  if (this.refs[name]?.orderIndex && pushableRange(query)) {
946
635
  const range = {}
947
636
  for (const k of ['gt', 'gte', 'lt', 'lte']) {
@@ -955,17 +644,14 @@ export class Database extends ReadyResource {
955
644
  }
956
645
 
957
646
  const all = await this.view.find(col, {}).toArray()
958
- // collections carry an auto-increment `index`; return them in that order
959
647
  all.sort((a, b) => (a.index ?? 0) - (b.index ?? 0))
960
648
  const total = all.length
961
649
  const data = paginate(all, query)
962
650
  return { data, total, size: data.length }
963
651
  }
964
652
 
965
- // hyperdb never backfills an index added after rows were written — a store
966
- // upgraded to a spec with the implicit order index would silently drop its
967
- // legacy rows from pushed-down reads. Verify completeness ONCE per open
968
- // (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.
969
655
  async _orderReady(name, col) {
970
656
  if (!this._orderOk) this._orderOk = new Map()
971
657
  let ok = this._orderOk.get(name)
@@ -987,9 +673,6 @@ export class Database extends ReadyResource {
987
673
  return ok
988
674
  }
989
675
 
990
- // total for a pushed-down read: free when the page IS the whole set (no
991
- // limit, or a non-full page), a full count only when explicitly requested
992
- // via { total: true }, null otherwise.
993
676
  async _total(col, query, rows) {
994
677
  if (query?.total) return (await this.view.find(col, {}).toArray()).length
995
678
  if (query?.limit === undefined || rows.length < query.limit) return rows.length
@@ -1064,26 +747,18 @@ export class Database extends ReadyResource {
1064
747
 
1065
748
  /**
1066
749
  * Claim writership on an existing room by signing our writer key with the
1067
- * member identity and appending optimistically. Admission only — the device
1068
- * 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).
1069
752
  *
1070
753
  * @returns {Promise<void>}
1071
754
  */
1072
755
  async claim() {
1073
- this.guard()
1074
- if (this.bee.writable) return
1075
-
1076
- const writerKey = this.writerKey
1077
- const sig = this.identity.sign(claimWriterPayload(this.key, writerKey))
1078
- const encoded = this.spec.dispatch.encode(`@${this.ns}/claim-writer`, {
1079
- identity: this.identity.publicKey,
1080
- writer: writerKey,
1081
- sig,
1082
- ts: Date.now()
1083
- })
1084
- await this.bee.append(wrap(this.version, encoded), { optimistic: true })
1085
- await this.bee.update()
1086
- 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)
1087
762
  }
1088
763
 
1089
764
  /**
@@ -1092,42 +767,8 @@ export class Database extends ReadyResource {
1092
767
  * @param {{ timeout?: number }} [opts]
1093
768
  * @returns {Promise<void>}
1094
769
  */
1095
- async whenWritable({ timeout = 30000 } = {}) {
1096
- this.guard()
1097
- if (this.bee.writable) return
1098
- return new Promise((resolve, reject) => {
1099
- let timer = null
1100
- let pollTimer = null
1101
- let done = false
1102
-
1103
- const finish = (err) => {
1104
- if (done) return
1105
- done = true
1106
- if (timer) clearTimeout(timer)
1107
- if (pollTimer) clearInterval(pollTimer)
1108
- if (this.bee) this.bee.off('writable', onWritable)
1109
- this.off('close', onClose)
1110
- if (err) reject(err)
1111
- else resolve()
1112
- }
1113
-
1114
- const onWritable = () => finish()
1115
- const onClose = () => finish(CeroError.CLOSED('Database'))
1116
- const poll = async () => {
1117
- if (done || !this.bee) return
1118
- try {
1119
- await this.bee.update()
1120
- if (!done && this.bee.writable) finish()
1121
- } catch {}
1122
- }
1123
-
1124
- this.bee.on('writable', onWritable)
1125
- this.on('close', onClose)
1126
- pollTimer = setInterval(poll, 1000)
1127
- if (timeout > 0) {
1128
- timer = setTimeout(() => finish(CeroError.TIMED_OUT('whenWritable')), timeout)
1129
- }
1130
- })
770
+ async whenWritable(opts) {
771
+ return whenWritable(this, opts)
1131
772
  }
1132
773
 
1133
774
  /**
@@ -1137,7 +778,7 @@ export class Database extends ReadyResource {
1137
778
  * @returns {Promise<void>}
1138
779
  */
1139
780
  async addWriter(publicKey) {
1140
- return this._write('add-writer', 'addWriter', publicKey)
781
+ return addWriter(this, publicKey)
1141
782
  }
1142
783
 
1143
784
  /**
@@ -1147,7 +788,7 @@ export class Database extends ReadyResource {
1147
788
  * @returns {Promise<void>}
1148
789
  */
1149
790
  async removeWriter(publicKey) {
1150
- return this._write('del-writer', 'removeWriter', publicKey)
791
+ return removeWriter(this, publicKey)
1151
792
  }
1152
793
 
1153
794
  /**
@@ -1167,8 +808,9 @@ export class Database extends ReadyResource {
1167
808
  * @returns {Ref}
1168
809
  */
1169
810
  ref(name) {
1170
- if (typeof name !== 'string' || !name)
811
+ if (typeof name !== 'string' || !name) {
1171
812
  throw CeroError.INVALID('name must be a non-empty string')
813
+ }
1172
814
  const ref = this.refs[name]
1173
815
  if (!ref) throw CeroError.UNKNOWN('ref', name)
1174
816
  return { name, kind: ref.kind || COLLECTION, verb: ref.verb || name }
@@ -1184,9 +826,7 @@ export class Database extends ReadyResource {
1184
826
  return `@${this.ns}/${ref.name}`
1185
827
  }
1186
828
 
1187
- // Reject a write that carries a field the schema doesn't declare — the encoder
1188
- // would silently drop it, so the returned row would lie. Builtins (and specs
1189
- // 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
1190
830
  _checkFields(name, row) {
1191
831
  const declared = this.refs[name]?.fields
1192
832
  if (!declared || !row) return
@@ -1214,24 +854,13 @@ export class Database extends ReadyResource {
1214
854
  if (idxFields.length === fields.length && idxFields.every((f) => fields.includes(f))) {
1215
855
  const point = {}
1216
856
  for (const f of idxFields) point[f] = query[f]
1217
- // point lookup only — search/range/reverse/limit are applied by paginate
857
+ // point lookup only, paginate applies search/range/reverse/limit
1218
858
  return { path: `@${this.ns}/${name}-${idx}`, range: { gte: point, lte: point } }
1219
859
  }
1220
860
  }
1221
861
  return null
1222
862
  }
1223
863
 
1224
- _addHook(map, op, fn) {
1225
- if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
1226
- let arr = map.get(op)
1227
- if (!arr) map.set(op, (arr = []))
1228
- arr.push(fn)
1229
- return () => {
1230
- const i = arr.indexOf(fn)
1231
- if (i >= 0) arr.splice(i, 1)
1232
- }
1233
- }
1234
-
1235
864
  async _write(verb, hook, publicKey) {
1236
865
  this.guard()
1237
866
  if (!b4a.isBuffer(publicKey)) {
@@ -1251,33 +880,29 @@ export class Database extends ReadyResource {
1251
880
  }
1252
881
  }
1253
882
 
1254
- // A trust decision reads a historic checkout view, whose blocks may not be
1255
- // servable yet — an unbounded read there wedges autobee's drain forever. The
1256
- // value is wrapped so a timeout (null) is never mistaken for what the read
1257
- // would have returned; undecidable in time means "not trusted", and the
1258
- // 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.
1259
885
  const bounded = (promise, ms = 2000) =>
1260
886
  Promise.race([
1261
887
  promise.then((v) => ({ v })),
1262
888
  new Promise((resolve) => setTimeout(() => resolve(null), ms))
1263
889
  ])
1264
890
 
1265
- // Fields the write path stamps itself — always allowed even if not user-declared.
891
+ // fields the write path stamps itself, always allowed
1266
892
  const SYSTEM_FIELDS = new Set(['id', 'memberId', 'index', 'createdAt', 'updatedAt'])
1267
893
 
1268
- // Match a query value against a stored value (bytes compared by content).
1269
894
  const valueEq = (a, b) => {
1270
895
  if (a instanceof Uint8Array && b instanceof Uint8Array) return b4a.equals(a, b)
1271
896
  return a === b
1272
897
  }
1273
898
 
1274
- // 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
1275
900
  function pushable(query) {
1276
901
  if (!query) return true
1277
902
  return Object.keys(query).every((k) => k === 'reverse' || k === 'limit' || k === 'total')
1278
903
  }
1279
904
 
1280
- // 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
1281
906
  function pushableRange(query) {
1282
907
  if (!query) return false
1283
908
  const keys = Object.keys(query)
@@ -1297,9 +922,7 @@ function pushableRange(query) {
1297
922
  function paginate(rows, query) {
1298
923
  if (!query) return rows
1299
924
  let out = rows
1300
- // Exact-field equality: every non-reserved key filters in memory. The secondary
1301
- // index is an optimization, not a correctness gate — so an unindexed field, or
1302
- // one passed alongside search/range, still filters instead of silently dropping.
925
+ // the secondary index is an optimization, not a correctness gate
1303
926
  for (const key of Object.keys(query)) {
1304
927
  if (QUERY_RESERVED.has(key)) continue
1305
928
  out = out.filter((r) => valueEq(r[key], query[key]))