@cero-base/core 2.11.0 → 3.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 (39) hide show
  1. package/package.json +8 -8
  2. package/src/blobs/codec.js +25 -0
  3. package/src/blobs/index.js +5 -2
  4. package/src/blobs/server.js +2 -2
  5. package/src/database/dispatch.js +805 -208
  6. package/src/database/encryption.js +25 -21
  7. package/src/database/index.js +747 -124
  8. package/src/database/rotation.js +333 -38
  9. package/src/lib/constants.js +10 -0
  10. package/src/lib/errors.js +8 -0
  11. package/src/lib/schema.js +12 -2
  12. package/src/lib/spec/index.js +10 -5
  13. package/src/lib/spec/schema.json +13 -1
  14. package/src/lib/utils.js +24 -3
  15. package/src/mailbox/inbox.js +368 -41
  16. package/src/mailbox/index.js +75 -20
  17. package/src/mailbox/post.js +13 -8
  18. package/src/network/index.js +12 -5
  19. package/src/pairing/index.js +347 -57
  20. package/src/pairing/invite.js +36 -12
  21. package/src/pairing/response.js +78 -0
  22. package/src/push/index.js +20 -2
  23. package/types/blobs/codec.d.ts +13 -0
  24. package/types/blobs/index.d.ts +2 -0
  25. package/types/database/dispatch.d.ts +52 -7
  26. package/types/database/encryption.d.ts +13 -5
  27. package/types/database/index.d.ts +199 -19
  28. package/types/database/rotation.d.ts +85 -2
  29. package/types/lib/constants.d.ts +4 -0
  30. package/types/lib/errors.d.ts +6 -0
  31. package/types/lib/schema.d.ts +11 -0
  32. package/types/lib/utils.d.ts +2 -0
  33. package/types/mailbox/inbox.d.ts +78 -10
  34. package/types/mailbox/index.d.ts +42 -16
  35. package/types/mailbox/post.d.ts +7 -5
  36. package/types/pairing/index.d.ts +53 -8
  37. package/types/pairing/invite.d.ts +27 -8
  38. package/types/pairing/response.d.ts +50 -0
  39. package/types/push/index.d.ts +12 -2
@@ -15,7 +15,13 @@ import {
15
15
  QUERY_RESERVED,
16
16
  RANK,
17
17
  ADMIN,
18
- WRITE
18
+ OWNER,
19
+ WRITE,
20
+ REMOVALS,
21
+ REFUSALS,
22
+ ASKS,
23
+ COUNTERS,
24
+ OWED
19
25
  } from '../lib/constants.js'
20
26
  import { genId } from '../lib/ids.js'
21
27
  import {
@@ -28,12 +34,12 @@ import {
28
34
  stamp
29
35
  } from '../lib/utils.js'
30
36
  import { wrap, unwrap } from './envelope.js'
31
- import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
37
+ import { EpochAutobee, Keyring, loadEpochs, plainId } from './encryption.js'
32
38
  import { CeroError } from '../lib/errors.js'
33
39
  import { Identity } from '../identity/index.js'
34
- import { Rotation } from './rotation.js'
40
+ import { Rotation, removes } from './rotation.js'
35
41
  import { makeChanges } from './changes.js'
36
- import { makeDispatcher, BESPOKE } from './dispatch.js'
42
+ import { makeDispatcher, BESPOKE, leftId, toldId, keysOf } from './dispatch.js'
37
43
  import { keyPair } from '../mailbox/inbox.js'
38
44
 
39
45
  // autobee remaps an older store once a recovery peer, a mirror, serves it; unset, it closes the store
@@ -45,19 +51,21 @@ Hypercore.setRecoveryPeers(recovery)
45
51
  * @property {import('corestore')} store Corestore (or compatible) used to materialize the autobee.
46
52
  * @property {import('../identity/index.js').Identity} identity Long-lived member identity used to sign writer changes.
47
53
  * @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication; `store` is its store or a session of it.
48
- * @property {{ database: object, dispatch: { Router: new () => object, encode: (name: string, value: unknown) => Uint8Array, decode: (buf: Uint8Array) => { name: string, value: unknown } }, meta?: { ns?: string, version?: number, refs?: Record<string, { kind?: string, verb?: string }> } }} spec Generated hyperdb + hyperdispatch spec.
54
+ * @property {{ database: object, dispatch: { Router: new () => object, encode: (name: string, value: unknown) => Uint8Array, decode: (buf: Uint8Array) => { name: string, value: unknown } }, meta?: { ns?: string, version?: number, rules?: number, start?: number, target?: number, refs?: Record<string, { kind?: string, verb?: string }> } }} spec Generated hyperdb + hyperdispatch spec.
49
55
  * @property {string} [namespace] Corestore namespace; defaults to `cero`.
50
56
  * @property {Uint8Array} encryptionKey Encrypts it; a join hands it out, so never the identity's on a database you pair.
51
57
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
52
58
  * @property {Uint8Array | null} [key] Existing autobee key to reopen.
53
59
  * @property {boolean} [pinned] Always search and announce, outside the network's presence budget. The root.
60
+ * @property {boolean} [root] The identity's own database: a device key past a removed one stands while a device of the identity is seated on it.
54
61
  * @property {boolean} [push] Push a notification through the mirrors after a local write to a ref whose meta declares `push`, naming the ref, so members learn of it while their app is dead.
55
62
  * @property {import('../identity/index.js').KeyPair} [keyPair] This device's writer keypair; a fresh random one by default. Never the identity's, never the database key.
63
+ * @property {Database | null} [parent] A database whose members this one follows: behind there, it is behind here too.
56
64
  * @property {(err: Error) => void} [onerror] Called when a node is skipped or refused, or the bee errors.
57
65
  *
58
- * Events: `update` (touched refs, a Set, after each applied batch), `apply` (one per applied
59
- * op: `{ op, name, row, writerKey, seq }`, local and replicated), `writable`, `unwritable`,
60
- * `behind` (an op from a newer app version was skipped).
66
+ * Events: `update` (touched refs, a Set, after each applied batch that changed a row), `apply`
67
+ * (one per applied op: `{ op, name, row, writerKey, seq }`, local and replicated), `writable`,
68
+ * `unwritable`, `behind` (the database's version passed this build's contract).
61
69
  *
62
70
  * @typedef {Record<string, unknown>} Row A row, fields by name.
63
71
  * @typedef {{ data: Row | null }} SingleResult
@@ -111,8 +119,24 @@ export class Database extends ReadyResource {
111
119
  this.ns = this.meta.ns || NAMESPACE
112
120
  this.refs = this.meta.refs || {}
113
121
  this.version = this.meta.version || 1
114
- /** @type {number | null} */
115
- this.behind = null
122
+ this.rules = this.meta.rules || 1
123
+ // the version of a database with no version row, and the one this build asks databases to use
124
+ this.start = this.meta.start || 1
125
+ this.target = this.meta.target || this.start
126
+ /** @type {Database | null} */
127
+ this.parent = opts.parent || null
128
+ /** @private */
129
+ this._behind = null
130
+ /** @private */
131
+ this._skipped = null
132
+ /** @private */
133
+ this._applied = false
134
+ /** @private */
135
+ this._landed = false
136
+ /** @private */
137
+ this._rebuilding = null
138
+ /** @private */
139
+ this._writes = new Set()
116
140
  this.namespace = opts.namespace || NAMESPACE
117
141
  this._writable = false
118
142
  this.encryptionKey = opts.encryptionKey
@@ -121,8 +145,10 @@ export class Database extends ReadyResource {
121
145
  /** @private */
122
146
  this._delivered = !!opts.epochs?.length
123
147
  this.rotation = new Rotation(this)
148
+ this.keyring.onmiss = (stamp) => this.rotation.meet(stamp)
124
149
  this.key = opts.key || null
125
150
  this.pinned = opts.pinned === true
151
+ this.root = opts.root === true
126
152
  this.push = opts.push === true
127
153
  /** @private */
128
154
  this._pushes = pushes(this.refs)
@@ -192,6 +218,11 @@ export class Database extends ReadyResource {
192
218
  return this.bee?.local?.key || null
193
219
  }
194
220
 
221
+ /** @returns {number | null} the database's version, or its parent's, while it is past this build's contract */
222
+ get behind() {
223
+ return this._behind ?? this.parent?.behind ?? null
224
+ }
225
+
195
226
  /** @returns {boolean} whether the bee accepts local writes */
196
227
  get writable() {
197
228
  return this._writable
@@ -215,28 +246,52 @@ export class Database extends ReadyResource {
215
246
  this.dispatcher = makeDispatcher({
216
247
  spec: this.spec,
217
248
  ns: this.ns,
249
+ start: this.start,
250
+ contract: () => this.version,
251
+ onskip: (stamp) => this._skip(stamp),
252
+ build: () => this._build(),
218
253
  onerror: this._onerror,
219
254
  key: () => this.key,
220
255
  onepoch: (row) => this.rotation.learn(row),
221
256
  room: () => this._room,
257
+ root: this.root,
222
258
  hooks: (phase, op) => this._hooks(phase, op),
223
259
  touch: (name) => this._touched.add(name),
224
260
  read: (view, name, query) => this._read(view, name, query)
225
261
  })
226
262
 
227
263
  const known = !!this.key
228
- await this._boot()
229
- const replayed = await this._replay()
230
- if (replayed) await this._boot()
231
-
232
- // before replication can deliver blocks at epochs we haven't learned yet
233
- await this.rotation.hydrate()
234
- // epochs handed over at join are sealed to nobody this device can read later: keep them
235
- if (this._delivered) await this.rotation._save()
264
+ try {
265
+ await this._boot()
266
+ const replayed = await this._replay()
267
+ if (replayed) await this._boot()
268
+
269
+ // before replication can deliver blocks at epochs we haven't learned yet
270
+ await this.rotation.hydrate()
271
+ // epochs handed over at join are sealed to nobody this device can read later: keep them
272
+ if (this._delivered) await this.rotation._save()
273
+ this._track(await this.dispatcher.version(this.view))
274
+ await this.rotation.pick()
275
+ } catch (err) {
276
+ // ready-resource runs no _close for an open that failed
277
+ await this._close().catch(safetyCatch)
278
+ throw err
279
+ }
236
280
 
237
- // REMOVE-capable devices re-key when the epoch drifts from the member set
281
+ // REMOVE-capable devices rotate when the epoch drifts from the member set, as it may have
282
+ // while this one was closed, or as a close cut its rotation short; an owner's device raises
283
+ // the version beside it
238
284
  this.on('update', () => this.rotation.heal())
285
+ this.rotation.heal()
239
286
  this._writable = this.bee.writable
287
+ this._wire()
288
+
289
+ // a fresh db has no key until boot mints it
290
+ if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
291
+ }
292
+
293
+ /** @private */
294
+ _wire() {
240
295
  this.bee.on('writable', () => this._onwritable())
241
296
  // falling edge: apps freeze the UI the moment access ends
242
297
  this.bee.on('unwritable', () => {
@@ -248,15 +303,14 @@ export class Database extends ReadyResource {
248
303
  // a failed background remap is only a warning: the store reads its old cores until a reopen or a fast-forward
249
304
  // tries again
250
305
  this.bee.on('warning', this._onerror)
306
+ const bee = this.bee
307
+ this.bee.on('move-to', () => this._onmove(bee))
251
308
 
252
309
  // with no mirror to hold the database, every member holds it: any member serves a joiner, offline
253
310
  if (this.network && !this.network.mirrors.length) {
254
311
  this.bee.on('move-to', () => this._holdRoom().catch(safetyCatch))
255
312
  this._holdRoom().catch(safetyCatch)
256
313
  }
257
-
258
- // a fresh db has no key until boot mints it
259
- if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
260
314
  }
261
315
 
262
316
  /** @private */
@@ -383,7 +437,7 @@ export class Database extends ReadyResource {
383
437
  * @returns {Promise<{ epoch: number }>}
384
438
  */
385
439
  async rotate() {
386
- // queued in tx() the epoch is unobservable, and a batched rekey blurs the epoch
440
+ // queued in tx() the epoch is unobservable, and a batched rotation blurs the epoch
387
441
  if (this.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
388
442
  return this.rotation.rotate()
389
443
  }
@@ -407,7 +461,12 @@ export class Database extends ReadyResource {
407
461
  const batch = Object.create(this)
408
462
  batch.txQueue = []
409
463
  try {
410
- const result = await fn(batch)
464
+ let result
465
+ try {
466
+ result = await fn(batch)
467
+ } finally {
468
+ batch.spent = true
469
+ }
411
470
  if (batch.txQueue.length) await this._chain(() => this.write(batch.txQueue))
412
471
  return result
413
472
  } catch (err) {
@@ -429,37 +488,73 @@ export class Database extends ReadyResource {
429
488
  * is open.
430
489
  *
431
490
  * @param {Array<[string, unknown]>} ops
432
- * @returns {Promise<void>}
491
+ * @returns {Promise<number | undefined>} The stamp the last op was appended with; nothing when queued or when nothing changed.
433
492
  */
434
493
  async write(ops) {
435
- // behind, a set merges from a view missing the newer writes and every device takes the stale
436
- // row: no writes until the update, but leaving, which touches nothing else
437
- if (this.behind !== null && !leaving(ops, this.identity.id)) throw CeroError.BEHIND(this.behind)
494
+ if (this._frozen(ops)) throw CeroError.BEHIND(this.behind)
438
495
  if (this.txQueue) {
496
+ if (this.spent) throw CeroError.INVALID('a write through tx after its fn returned')
439
497
  for (const op of ops) this.txQueue.push(op)
440
498
  return
441
499
  }
442
500
  this.guard()
443
- // leaving takes no seat: a reader's own removal goes in optimistically, apply admits it
444
- const optimistic = !this.bee.writable && leaving(ops, this.identity.id)
501
+ return removes(ops) ? this.rotation.carry(ops) : this._write(ops)
502
+ }
503
+
504
+ // behind, a set merges from a view missing the newer writes and every device takes the stale
505
+ // row: no writes until the update, but leaving, which touches nothing else
506
+ /** @private */
507
+ _frozen(ops) {
508
+ return this.behind !== null && !leaving(ops, this.identity.id)
509
+ }
510
+
511
+ // a removal and the rotation it carries are `queued`: every other write waits until both are in
512
+ /** @private */
513
+ async _write(ops, queued = false) {
514
+ // a write goes in on the bee it started on: a rebuild closes it once the write is done
515
+ for (;;) {
516
+ const busy = this._rebuilding || (!queued && this.rotation.carrying)
517
+ if (!busy) break
518
+ await busy
519
+ }
520
+ this.guard()
521
+ const writing = this._commit(ops)
522
+ this._writes.add(writing)
523
+ try {
524
+ return await writing
525
+ } finally {
526
+ this._writes.delete(writing)
527
+ }
528
+ }
529
+
530
+ /** @private */
531
+ async _commit(ops) {
532
+ // leaving takes no seat, nor does her profile or asking for keys: a reader's own goes in
533
+ // optimistically, apply admits it
534
+ const optimistic = !this.bee.writable && seatless(ops, this.identity.id)
445
535
  if (!this.bee.writable && !optimistic) throw CeroError.NOT_WRITABLE('Database')
446
536
  // writable flips inside the apply that admits us, before its view flush lands our device row
447
537
  await this.bee.updated()
448
- const encoded = ops.map(([op, payload]) =>
449
- this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
450
- )
538
+ // an owner's device raises first, in the same batch, as at genesis: its write may name what
539
+ // only the version its build asks for has
540
+ const raise = !ops.some(([op]) => op === 'upgrade') && (await this._raises())
541
+ const batch = raise ? [['upgrade', { version: this.target }], ...ops] : ops
451
542
  // the dry run refuses what apply would; a no-op never reaches the log, an action always does
452
543
  const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
453
544
  try {
454
- if (!(await this._dryRun(encoded)) && !action) return
455
- const wrapped = encoded.map((value) => wrap(this.version, value))
545
+ if (raise && !action && !(await this._changes(ops))) return
546
+ const { wrapped, changed, stamp } = await this._dryRun(batch)
547
+ if (!changed && !action) return
548
+ // a newer op may have applied while this write awaited
549
+ if (this._frozen(ops)) throw CeroError.BEHIND(this.behind)
456
550
  await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped, { optimistic })
551
+ const ref = this.push ? this._ref(ops) : null
552
+ if (ref) this._push(ref)
553
+ return stamp
457
554
  } catch (err) {
458
555
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
459
556
  throw err
460
557
  }
461
- const ref = this.push ? this._ref(ops) : null
462
- if (ref) this._push(ref)
463
558
  }
464
559
 
465
560
  /** @returns {boolean} Whether a push notification is on its way to the mirrors. */
@@ -533,9 +628,179 @@ export class Database extends ReadyResource {
533
628
  */
534
629
  async get(name, query) {
535
630
  this.guard()
631
+ // a view being applied again is empty meanwhile: a read waits for it, as a write does
632
+ while (this._rebuilding) await this._rebuilding
536
633
  return this._read(this.view, name, query)
537
634
  }
538
635
 
636
+ /**
637
+ * Whether a member is out for good, as this device has seen it: `'removed'` by another member, `'left'` on her
638
+ * own, or null while she is a member, never was one, or her going has not reached this device. A member let in
639
+ * again after is a member: null.
640
+ *
641
+ * @param {string} memberId
642
+ * @returns {Promise<'removed' | 'left' | null>}
643
+ */
644
+ async removed(memberId) {
645
+ this.guard()
646
+ if ((await this.get('members', memberId)).data) return null
647
+ const col = `@${this.ns}/${REMOVALS}`
648
+ if (await this.view.get(col, { id: memberId })) return 'removed'
649
+ if (await this.view.get(col, { id: leftId(memberId) })) return 'left'
650
+ return null
651
+ }
652
+
653
+ /**
654
+ * What a member's devices told this database of her device keys, 32 bytes each: those removed, and those that
655
+ * stand.
656
+ *
657
+ * @param {string} memberId
658
+ * @returns {Promise<{ removed: Uint8Array[], standing: Uint8Array[] }>}
659
+ */
660
+ async told(memberId) {
661
+ this.guard()
662
+ const row = await this.view.get(`@${this.ns}/${REMOVALS}`, { id: toldId(memberId) })
663
+ return { removed: keysOf(row?.removed), standing: keysOf(row?.standing) }
664
+ }
665
+
666
+ /**
667
+ * The keys this database holds as removed, 32 bytes each: a device's own, and a removed member's identity.
668
+ *
669
+ * @returns {Promise<Uint8Array[]>}
670
+ */
671
+ async removals() {
672
+ this.guard()
673
+ const rows = await this.view.find(`@${this.ns}/${REMOVALS}`, {}).toArray()
674
+ return rows.filter((row) => !row.id.includes(':')).map((row) => hid.decode(row.id))
675
+ }
676
+
677
+ /**
678
+ * Who removed a member, from the record of her removal: null while none reached this device, and
679
+ * for one who left on her own.
680
+ *
681
+ * @param {string} memberId
682
+ * @returns {Promise<{ by: string | null } | null>}
683
+ */
684
+ async removal(memberId) {
685
+ if ((await this.removed(memberId)) !== 'removed') return null
686
+ const row = await this.view.get(`@${this.ns}/${REMOVALS}`, { id: memberId })
687
+ return { by: row.by ?? null }
688
+ }
689
+
690
+ /**
691
+ * Resolves once another device or a mirror holds every block this device wrote.
692
+ *
693
+ * @returns {Promise<void>}
694
+ */
695
+ async held() {
696
+ this.guard()
697
+ const core = this.bee.local
698
+ const length = core.length
699
+ if (core.remoteContiguousLength >= length) return
700
+ await new Promise((resolve, reject) => {
701
+ const check = () => {
702
+ if (this.closing || core.closed) done(CeroError.CLOSED('Database'))
703
+ else if (core.remoteContiguousLength >= length) done(null)
704
+ }
705
+ const done = (err) => {
706
+ core.off('remote-contiguous-length', check)
707
+ core.off('close', check)
708
+ if (err) reject(err)
709
+ else resolve()
710
+ }
711
+ core.on('remote-contiguous-length', check)
712
+ core.on('close', check)
713
+ check()
714
+ })
715
+ }
716
+
717
+ /**
718
+ * Whether a device seated here, other than this one and those whose keys are `removed`, wrote a
719
+ * node this view applied with every block this device wrote in its causal past, within `timeout`.
720
+ * A peer that only holds those blocks may be a removed device, which passes them on to no one.
721
+ *
722
+ * @param {Uint8Array[]} removed
723
+ * @param {number} timeout
724
+ * @returns {Promise<boolean>}
725
+ */
726
+ async heard(removed, timeout) {
727
+ this.guard()
728
+ const length = this.length
729
+ if (length === 0) return true
730
+ return new Promise((resolve, reject) => {
731
+ let busy = false
732
+ let again = false
733
+ const check = async () => {
734
+ if (busy) return (again = true)
735
+ busy = true
736
+ try {
737
+ do {
738
+ again = false
739
+ if (this.closing || this.closed) return done(CeroError.CLOSED('Database'))
740
+ if (await this._heard(removed, length)) return done(null, true)
741
+ } while (again)
742
+ } catch (err) {
743
+ done(err)
744
+ } finally {
745
+ busy = false
746
+ }
747
+ }
748
+ const timer = setTimeout(() => done(null, false), timeout)
749
+ const done = (err, yes) => {
750
+ clearTimeout(timer)
751
+ this.off('update', check)
752
+ this.off('close', check)
753
+ if (err) reject(err)
754
+ else resolve(yes)
755
+ }
756
+ this.on('update', check)
757
+ this.on('close', check)
758
+ check()
759
+ })
760
+ }
761
+
762
+ // a walk back from the last node of each other device that stands here, through what it links,
763
+ // to this device's block at `length`: a node stamped before that block cannot link it
764
+ /** @private */
765
+ async _heard(removed, length) {
766
+ const local = this.bee.local
767
+ const floor = (await this.bee.readOplog(local, length)).op.timestamp
768
+ const own = hid.encode(local.key)
769
+ const { data: devices } = await this.get('devices')
770
+ const stack = []
771
+ for (const row of devices) {
772
+ if (row.id === own || !row.key || removed.some((key) => b4a.equals(key, row.key))) continue
773
+ const key = hid.decode(row.id)
774
+ const info = await this.bee.system.get(key)
775
+ if (info) stack.push({ key, length: info.length })
776
+ }
777
+ const cores = new Map()
778
+ const seen = new Set()
779
+ try {
780
+ while (stack.length) {
781
+ const link = stack.pop()
782
+ if (b4a.equals(link.key, local.key)) {
783
+ if (link.length >= length) return true
784
+ continue
785
+ }
786
+ const hex = b4a.toHex(link.key)
787
+ if (link.length === 0 || seen.has(`${hex}/${link.length}`)) continue
788
+ seen.add(`${hex}/${link.length}`)
789
+ let core = cores.get(hex)
790
+ if (!core) cores.set(hex, (core = this.bee.openCore(link.key)))
791
+ await core.ready()
792
+ if (!(await core.has(link.length - 1))) continue
793
+ const { op } = await this.bee.readOplog(core, link.length)
794
+ if (op.timestamp < floor) continue
795
+ stack.push(...op.links, { key: link.key, length: link.length - 1 })
796
+ if (op.witness) stack.push(op.witness.link)
797
+ }
798
+ return false
799
+ } finally {
800
+ for (const core of cores.values()) await core.close()
801
+ }
802
+ }
803
+
539
804
  // the same read against any view: hooks read the transaction they run in
540
805
  /** @private */
541
806
  async _read(view, name, query) {
@@ -550,12 +815,13 @@ export class Database extends ReadyResource {
550
815
  return { data: await view.get(col, { id: query }) }
551
816
  }
552
817
 
553
- const { path, range, rest, sorted } = this._plan(name, query)
818
+ const { path, range, rest, sorted, count = path } = this._plan(name, query)
554
819
  const rows = await view.find(path, range).toArray()
555
- if (!sorted) rows.sort(byIndex)
556
- const matched = filter(rows, { ...rest, limit: undefined })
820
+ const matched = filter(rows, { ...rest, reverse: undefined, limit: undefined })
821
+ if (!sorted) matched.sort(byIndex)
822
+ if (rest.reverse) matched.reverse()
557
823
  const data = rest.limit === undefined ? matched : matched.slice(0, rest.limit)
558
- return { data, total: await this._total(view, path, range, matched, query), size: data.length }
824
+ return { data, total: await this._total(view, count, range, matched, query), size: data.length }
559
825
  }
560
826
 
561
827
  /**
@@ -588,6 +854,41 @@ export class Database extends ReadyResource {
588
854
  return makeChanges(this, name, col, (row) => filter([row], rest).length > 0)
589
855
  }
590
856
 
857
+ /**
858
+ * The rows of a collection that changed since `settle` was last called under `mark`, a name of the
859
+ * caller's, so what follows a collection row by row goes on after a restart where it stopped. With no
860
+ * point to start from, `reset` is true and `changes` holds every row. A caller that takes changes and
861
+ * does not settle starts over at its next call. The point is kept on this device only.
862
+ *
863
+ * @param {string} name
864
+ * @param {string} mark
865
+ * @returns {Promise<{ changes: Array<{ prev: Row | null, next: Row | null }>, reset: boolean, settle: () => Promise<void> }>}
866
+ */
867
+ async since(name, mark) {
868
+ this.guard()
869
+ while (this._rebuilding) await this._rebuilding
870
+ const col = this.col(this.ref(name))
871
+ const at = `cero/since/${mark}`
872
+ const local = this.bee.local
873
+ // taken before any await: a view being applied again would be read half way
874
+ const snap = this.view.snapshot()
875
+ const head = this.view.engine.head()
876
+ try {
877
+ const from = decodePoint(await local.getUserData(at))
878
+ const told = from ? await rows(snap, col, from) : null
879
+ const changes = told ?? (await rows(snap, col, null))
880
+ // what the caller writes from here on is ahead of the point: unsettled, it starts over
881
+ if (changes.length) await local.setUserData(at, null)
882
+ const settle = async () => {
883
+ // another core since, after a view applied again or a writer changed: the next call starts over
884
+ if (this.bee?.local === local) await local.setUserData(at, c.encode(point, head))
885
+ }
886
+ return { changes, reset: told === null, settle }
887
+ } finally {
888
+ await snap.close().catch(safetyCatch)
889
+ }
890
+ }
891
+
591
892
  /**
592
893
  * Provision this device. Its writer core was minted when the database opened and this
593
894
  * device is its only author, ever.
@@ -610,9 +911,14 @@ export class Database extends ReadyResource {
610
911
  ]
611
912
  if (recovering) {
612
913
  await this.claim({ timeout })
613
- await this.write([device])
914
+ // an owner's device raises first, as at genesis; a member's leaves out what the version lacks
915
+ await this._raise()
916
+ const [op, row] = device
917
+ const stamp = await this._stamp(this.view)
918
+ await this.write([[op, this.dispatcher.cut(`@${this.ns}/${op}`, row, stamp)]])
614
919
  } else {
615
- // one batch: a writer is never on the log without its member row
920
+ // one batch: a writer is never on the log without its member row, nor the database without
921
+ // the version its build asks for, raised first so the rest is written at it
616
922
  const member = {
617
923
  id: this.identity.id,
618
924
  key: this.writerKey,
@@ -622,15 +928,20 @@ export class Database extends ReadyResource {
622
928
  updatedAt: ts
623
929
  }
624
930
  const writer = this._admission(this.writerKey, ts)
625
- await this.write([['add-writer', writer], ['add-member', member], device])
931
+ const upgrade = ['upgrade', { version: this.target }]
932
+ await this.write([upgrade, ['add-writer', writer], ['add-member', member], device])
626
933
  }
627
934
  return { id: this.writerKey, writer: this.keyPair }
628
935
  }
629
936
 
630
937
  /**
631
- * Seat this device's writer where its identity is a member: wait for the member row, append
632
- * the add-writer the identity signs from this device's own core, and resolve once it writes.
633
- * A member whose role cannot write takes no seat.
938
+ * Seat this device's writer where its identity is a member, or was promised to be one: wait
939
+ * for the member row or the promise, append the add-writer the identity signs from this
940
+ * device's own core, and resolve once it writes. A member whose role cannot write takes no
941
+ * seat; a promise made to her is kept all the same, and resolves at this device's row. A claim
942
+ * that left this device nothing is made again once her member row or a promise made to her is
943
+ * new. Rejects `DENIED`, with the reason, once the room shows this writer turned away: its
944
+ * promise withdrawn.
634
945
  *
635
946
  * @param {{ timeout?: number }} [opts]
636
947
  * @returns {Promise<void>}
@@ -638,13 +949,26 @@ export class Database extends ReadyResource {
638
949
  async claim({ timeout = 30000 } = {}) {
639
950
  this.guard()
640
951
  if (this.bee.writable) return
641
- const { role } = await this._member(timeout)
642
- if (!can(role, WRITE)) return
643
- const op = this.spec.dispatch.encode(`@${this.ns}/add-writer`, this._admission(this.writerKey))
644
- // from a core not yet admitted: apply verifies the identity's signature and seats it
645
- await this.bee.append(wrap(this.version, op), { optimistic: true })
646
- await this.bee.update()
647
- await this.whenWritable({ timeout })
952
+ try {
953
+ const { role, promised, against } = await this._member(timeout, () => this._standing())
954
+ // seated while it waited: a join that was admitted wrote the seat with the member row
955
+ if (this.bee.writable) return
956
+ if (!promised && !can(role, WRITE)) return
957
+ const stamp = await this._stamp(this.view)
958
+ const op = this.dispatcher.encode(
959
+ `@${this.ns}/add-writer`,
960
+ this._admission(this.writerKey),
961
+ stamp
962
+ )
963
+ // from a core not yet admitted: apply verifies the identity's signature and seats it
964
+ await this.bee.append(wrap(stamp, op), { optimistic: true })
965
+ await this.bee.local.setUserData('cero/claim', against)
966
+ await this.bee.update()
967
+ await this._member(timeout, () => this._kept(role))
968
+ } catch (err) {
969
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
970
+ throw err
971
+ }
648
972
  }
649
973
 
650
974
  /**
@@ -688,24 +1012,47 @@ export class Database extends ReadyResource {
688
1012
 
689
1013
  /**
690
1014
  * Learn epochs handed over after the open, as a root carries them for a handle. One is kept
691
- * once its announcement applied here and the secret meets the commitment it carries: hand them
692
- * over again when an announcement applies.
1015
+ * once its announcement applied here and the secret meets the commitment it carries; one whose
1016
+ * announcement has not applied yet waits for it, and is checked then.
693
1017
  *
694
1018
  * @param {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} epochs
1019
+ * @param {string} [from] The device that sent them, when one did.
695
1020
  * @returns {Promise<void>}
696
1021
  */
697
- async learn(epochs) {
1022
+ async learn(epochs, from) {
698
1023
  this.guard()
699
1024
  const rows = await this.rotation._epochs()
700
1025
  let added = false
701
1026
  for (const e of epochs) {
702
- if (this.keyring.entropy(e.stamp)) continue
1027
+ if (e.entropy?.byteLength !== 32) continue
703
1028
  const row = rows.find((r) => r.stamp === e.stamp)
704
- if (!row?.commit || !b4a.equals(crypto.hash(e.entropy), row.commit)) continue
1029
+ if (!row) this.rotation.keep(e, from)
1030
+ if (!row?.commit || this.rotation.held(row)) continue
1031
+ if (!b4a.equals(crypto.hash(e.entropy), row.commit)) continue
705
1032
  this.keyring.add(e.stamp, e.entropy, e.epoch)
706
1033
  added = true
707
1034
  }
708
- if (added) await this.rotation._save()
1035
+ if (!added) return
1036
+ await this.rotation.pick()
1037
+ await this.rotation._save()
1038
+ }
1039
+
1040
+ /**
1041
+ * @returns {Promise<boolean>} Whether this device asked for keys it lacks and its ask still stands.
1042
+ */
1043
+ async owed() {
1044
+ this.guard()
1045
+ return !!(await this.view.get(`@${this.ns}/${ASKS}`, { id: hid.encode(this.writerKey) }))
1046
+ }
1047
+
1048
+ /**
1049
+ * @returns {Promise<boolean>} Whether every device this database removed is out of the key this
1050
+ * device writes under: no rotation is owed, and this device holds the newest key.
1051
+ */
1052
+ async rotated() {
1053
+ this.guard()
1054
+ const owed = await this.view.get(`@${this.ns}/${COUNTERS}`, { name: OWED })
1055
+ return !owed?.value && !(await this.rotation.lacks())
709
1056
  }
710
1057
 
711
1058
  /**
@@ -759,7 +1106,21 @@ export class Database extends ReadyResource {
759
1106
  // the boot reads post-rotation state through the keyring, primed before the bee exists
760
1107
  /** @private */
761
1108
  async _preload() {
762
- const local = this.store.namespace(this.namespace).get({
1109
+ await this._onWriter(async (local) => {
1110
+ await loadEpochs(this.keyring, local)
1111
+ // read before the bee applies anything: an op applied as it opens adds to it, never over it
1112
+ const skipped = await local.getUserData('cero/skipped')
1113
+ this._skipped = skipped ? c.decode(c.uint, skipped) : null
1114
+ // behind is read from the view: a marker kept on the core says nothing
1115
+ if (await local.getUserData('cero/behind')) await local.setUserData('cero/behind', null)
1116
+ })
1117
+ }
1118
+
1119
+ // this device's writer core on its own, with no bee over it to apply a batch meanwhile
1120
+ /** @private */
1121
+ async _onWriter(fn) {
1122
+ const ns = this.store.namespace(this.namespace)
1123
+ const local = ns.get({
763
1124
  keyPair: this.keyPair,
764
1125
  manifest: {
765
1126
  version: this.store.manifestVersion,
@@ -768,17 +1129,22 @@ export class Database extends ReadyResource {
768
1129
  active: false
769
1130
  })
770
1131
  await local.ready()
771
- await loadEpochs(this.keyring, local)
772
- await local.close()
1132
+ try {
1133
+ await fn(local)
1134
+ } finally {
1135
+ // closing the session closes the core opened through it
1136
+ await ns.close()
1137
+ }
773
1138
  }
774
1139
 
775
1140
  /** @private */
776
- async _boot() {
1141
+ async _boot({ land = true } = {}) {
777
1142
  const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
778
1143
  keyPair: this.keyPair,
779
1144
  encryptionKey: this.encryptionKey,
780
1145
  keyring: this.keyring,
781
1146
  optimistic: true,
1147
+ fastForward: land ? undefined : false,
782
1148
  wakeup: this.network?.wakeup || undefined,
783
1149
  open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
784
1150
  isTrusted: this._isTrusted.bind(this),
@@ -787,31 +1153,21 @@ export class Database extends ReadyResource {
787
1153
  })
788
1154
  // swarm BEFORE boot so the boot has peers to pull from, not a cold open
789
1155
  if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
790
- await bee.ready()
791
- // apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
1156
+ // apply-time hooks (rotation.learn, _skip) must never see this.bee null mid-drain, and a failed open closes it
792
1157
  this.bee = bee
1158
+ await bee.ready()
793
1159
  this.key = bee.key
794
1160
  await bee.update()
795
1161
  }
796
1162
 
797
- // ops skipped as too new apply once this version caught up, and a view whose definition grew
798
- // since it was built (an index added by a rebuild) fills from the log: wipe the boot record and
799
- // reboot
1163
+ // a view another build applied, one with ops skipped this build now reaches among them, fills
1164
+ // from the log
800
1165
  /** @private */
801
1166
  async _replay() {
802
- const local = this.bee.local
803
- const behind = await local.getUserData('cero/behind')
804
- this.behind = behind ? c.decode(c.uint, behind) : null
805
- const caught = this.behind !== null && this.behind <= this.version
806
- const built = await local.getUserData('cero/view')
807
- const { db } = this.spec.database.versions
808
- const grown = !!built && c.decode(c.uint, built) < db
809
- if (!built || grown) await local.setUserData('cero/view', c.encode(c.uint, db))
810
- if (!caught && !grown) return false
811
- await local.setUserData('autobee/head', null)
812
- await local.setUserData('cero/behind', null)
813
- await this.bee.close()
814
- this.behind = null
1167
+ // an empty view names no build: what was skipped and is now reached still has to be applied
1168
+ const caught = this._skipped !== null && this._skipped <= this.version
1169
+ if (!caught && !(await this._foreign(this.view))) return false
1170
+ await this._wipe()
815
1171
  return true
816
1172
  }
817
1173
 
@@ -835,7 +1191,7 @@ export class Database extends ReadyResource {
835
1191
  }
836
1192
  }
837
1193
 
838
- // unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
1194
+ // unwrap once so the dispatcher sees op bytes and the stamp each was written with
839
1195
  /** @private */
840
1196
  async _apply(nodes, view, host) {
841
1197
  const ready = []
@@ -846,25 +1202,42 @@ export class Database extends ReadyResource {
846
1202
  this._onerror(CeroError.INVALID('an op with no envelope'))
847
1203
  continue
848
1204
  }
849
- if (op.version > this.version) {
850
- this._onfuture(op.version)
1205
+ // written without the key: a seat that holds none writes nothing
1206
+ const plain = this.bee.plain.has(plainId(node.key, node.length - 1))
1207
+ if (plain && !this._joins(op.body)) {
1208
+ this._onerror(
1209
+ CeroError.REFUSED(
1210
+ 'key',
1211
+ 'a block written without the key carries a join or its cancel only'
1212
+ )
1213
+ )
851
1214
  continue
852
1215
  }
853
- ready.push({ ...node, value: op.body })
1216
+ ready.push({ ...node, value: op.body, version: op.version })
854
1217
  }
855
- const result = await this.dispatcher.apply(ready, view, host)
856
- this._notify(ready)
857
- return result
1218
+ this._applied = true
1219
+ const { landed, changed } = await this.dispatcher.apply(ready, view, host)
1220
+ // a reorder may have dropped the epoch written under
1221
+ await this.rotation.pick(view)
1222
+ if (landed.length > 0) this._landed = true
1223
+ this._notify(landed, changed)
858
1224
  }
859
1225
 
860
- // 'update' carries the refs the batch touched; '*' means any, so a scoped watcher can skip
1226
+ // 'update' carries the refs the batch touched; '*' means any, so a scoped watcher can skip. A batch
1227
+ // that landed or changed nothing wakes nobody: anyone holding the key appends nodes apply refuses.
1228
+ // One that landed ranks its database all the same, changed or not: its ops have to reach the others
861
1229
  /** @private */
862
1230
  async _update(db) {
863
1231
  await db.update()
1232
+ this._track(await this.dispatcher.version(db))
864
1233
  const touched = this._touched
1234
+ const quiet = this._applied && touched.size === 0
1235
+ const landed = this._landed
865
1236
  this._touched = new Set()
866
- this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
867
- this._presence?.touch()
1237
+ this._applied = false
1238
+ this._landed = false
1239
+ if (!quiet) this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
1240
+ if (!quiet || landed) this._presence?.touch()
868
1241
  }
869
1242
 
870
1243
  // every bee a boot opens is attached, but the topic is joined once: close leaves it once
@@ -935,6 +1308,16 @@ export class Database extends ReadyResource {
935
1308
  return () => this.off('update', tick)
936
1309
  }
937
1310
 
1311
+ /** @private */
1312
+ _joins(body) {
1313
+ try {
1314
+ const { name } = this.spec.dispatch.decode(body)
1315
+ return name === `@${this.ns}/join` || name === `@${this.ns}/cancel-join`
1316
+ } catch {
1317
+ return false
1318
+ }
1319
+ }
1320
+
938
1321
  // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
939
1322
  /** @private */
940
1323
  _opOf(node) {
@@ -945,22 +1328,22 @@ export class Database extends ReadyResource {
945
1328
  return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
946
1329
  }
947
1330
 
948
- // marks the refs a batch touched and emits 'apply' per op, local and replicated alike
1331
+ // emits 'apply' per op, local and replicated alike, and marks the refs of a batch that changed a row
949
1332
  /** @private */
950
- _notify(nodes) {
1333
+ _notify(nodes, changed) {
951
1334
  const listened = this.listenerCount('apply') > 0
952
1335
  for (const node of nodes) {
953
1336
  let op
954
1337
  try {
955
1338
  op = this._opOf(node)
956
1339
  } catch (err) {
957
- this._touched.add('*')
1340
+ if (changed) this._touched.add('*')
958
1341
  safetyCatch(err)
959
1342
  continue
960
1343
  }
961
1344
  const ref = this._verbs.get(op.name)
962
1345
  // an action's hooks write wherever they want, widen to all
963
- this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
1346
+ if (changed) this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
964
1347
  if (!listened) continue
965
1348
  this.emit('apply', {
966
1349
  op: op.op,
@@ -983,7 +1366,20 @@ export class Database extends ReadyResource {
983
1366
  checkRequired(name, this.refs[name], stored)
984
1367
  if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
985
1368
  const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
986
- return this._append(stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
1369
+ const verb = `${insert ? 'add' : 'set'}-${ref.verb}`
1370
+ // a member's rank travels only when the caller names one: this device's view of it may predate a change another
1371
+ // device made, which a merged copy would undo or get refused for. An empty rank is no change, and apply keeps
1372
+ // the stored one
1373
+ if (ref.verb === 'member' && !('role' in row)) {
1374
+ await this._append({ ...stored, role: '' }, verb)
1375
+ return { row: stored }
1376
+ }
1377
+ // where a handle stands travels the same way, only when named, and apply keeps the stored one
1378
+ if (ref.verb === 'handle' && !('state' in row)) {
1379
+ await this._append({ ...stored, state: null }, verb)
1380
+ return { row: stored }
1381
+ }
1382
+ return this._append(stored, verb)
987
1383
  }
988
1384
 
989
1385
  /** @private */
@@ -1005,36 +1401,151 @@ export class Database extends ReadyResource {
1005
1401
  return ctx ? { data: ctx.row } : null
1006
1402
  }
1007
1403
 
1008
- // ops from a newer app version: emit behind once per version, the marker survives restarts
1404
+ // the row this build keeps in the view it applies
1405
+ /** @private */
1406
+ _build() {
1407
+ return [this.spec.database.versions.db, this.rules, this.version, this._skipped ?? 0]
1408
+ }
1409
+
1410
+ // a view another build applied: its row is not this build's, or it predates the row
1009
1411
  /** @private */
1010
- _onfuture(version) {
1011
- if (this.behind !== null && version <= this.behind) return
1012
- this.behind = version
1013
- this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
1014
- this.emit('behind', version)
1412
+ async _foreign(view) {
1413
+ const built = await this.dispatcher.built(view)
1414
+ const own = this._build()
1415
+ return built !== null && built.some((n, i) => n !== own[i])
1015
1416
  }
1016
1417
 
1017
- // every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
1418
+ // a fast-forward landed on a view: one another build applied is applied again here, from the
1419
+ // log. Writes wait from the landing on, and a second landing is checked once the first is done
1018
1420
  /** @private */
1019
- async _dryRun(encoded) {
1421
+ _onmove(bee = this.bee) {
1422
+ const prev = this._rebuilding
1423
+ const next = (async () => {
1424
+ await prev
1425
+ if (bee !== this.bee || this.closing) return
1426
+ if (await this._foreign(bee.view)) await this._rebuild()
1427
+ })()
1428
+ .catch(this._onerror)
1429
+ .finally(() => {
1430
+ if (this._rebuilding === next) this._rebuilding = null
1431
+ })
1432
+ this._rebuilding = next
1433
+ }
1434
+
1435
+ // as an open does past skipped ops, with no fast-forward until it closes: one would land on such
1436
+ // a view again
1437
+ /** @private */
1438
+ async _rebuild() {
1439
+ // peers announce their writers once, as they connect: the writers of the view it leaves are
1440
+ // where the new bee starts looking
1441
+ const heads = []
1442
+ for await (const { key, length } of this.bee.system.list()) heads.push({ key, length })
1443
+ await Promise.allSettled(this._writes)
1444
+ await this._wipe()
1445
+ if (this.closing) return
1446
+ await this._boot({ land: false })
1447
+ this.bee.hintWakeup(heads)
1448
+ this._wire()
1449
+ }
1450
+
1451
+ // the bee closes first: open, a batch it applied meanwhile would store what it applied again
1452
+ /** @private */
1453
+ async _wipe() {
1454
+ await this.bee.close()
1455
+ await this._onWriter(async (writer) => {
1456
+ await writer.setUserData('autobee/head', null)
1457
+ await writer.setUserData('cero/skipped', null)
1458
+ })
1459
+ this._skipped = null
1460
+ }
1461
+
1462
+ // the lowest version skipped: the replay runs once this device reaches it, whoever sent the highest
1463
+ /** @private */
1464
+ _skip(version) {
1465
+ if (this._skipped !== null && version >= this._skipped) return
1466
+ this._skipped = version
1467
+ this.bee.local.setUserData('cero/skipped', c.encode(c.uint, version)).catch(this._onerror)
1468
+ }
1469
+
1470
+ // behind while the version is past this build's contract, as the view says
1471
+ /** @private */
1472
+ _track(version) {
1473
+ const behind = version > this.version ? version : null
1474
+ if (behind === this._behind) return
1475
+ this._behind = behind
1476
+ if (behind !== null) this.emit('behind', behind)
1477
+ }
1478
+
1479
+ // an owner's device moves the database to the version its build asks for, a batch of its own
1480
+ /** @private */
1481
+ async _raise() {
1482
+ if (this.closing || this.closed || !(await this._raises())) return
1483
+ await this.write([['upgrade', { version: this.target }]])
1484
+ }
1485
+
1486
+ // read off the view, not through get: a write in flight would wait on a rebuild that waits on it
1487
+ /** @private */
1488
+ async _raises() {
1489
+ if (!this.writable || this.behind !== null) return false
1490
+ if (this.target <= (await this.dispatcher.version(this.view))) return false
1491
+ const me = await this.view.get(`@${this.ns}/members`, { id: this.identity.id })
1492
+ return me?.role === OWNER
1493
+ }
1494
+
1495
+ // a write that changes nothing appends no raise in front of it; one the view refuses may need the raise
1496
+ /** @private */
1497
+ async _changes(ops) {
1498
+ try {
1499
+ return (await this._dryRun(ops)).changed
1500
+ } catch {
1501
+ return true
1502
+ }
1503
+ }
1504
+
1505
+ // a device writes as the version, its own contract while it is behind
1506
+ /** @private */
1507
+ async _stamp(view) {
1508
+ return Math.min(this.version, await this.dispatcher.version(view))
1509
+ }
1510
+
1511
+ // whether a device with no seat writes its own member row at the version this room is at
1512
+ /** @private */
1513
+ async _seatless() {
1514
+ const since = this.meta.since?.routes[`@${this.ns}/ask-key`] ?? 0
1515
+ return since <= (await this._stamp(this.view))
1516
+ }
1517
+
1518
+ // every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the
1519
+ // write. Each is encoded and stamped as of the version it meets, an upgrade earlier in the batch
1520
+ // included, as apply will run it
1521
+ /** @private */
1522
+ async _dryRun(ops) {
1020
1523
  const tx = this.view.transaction()
1021
1524
  const host = {
1022
1525
  addWriter: async () => {},
1023
1526
  removeWriter: async () => {},
1024
1527
  genesis: this.bee.system.isGenesis()
1025
1528
  }
1529
+ const wrapped = []
1530
+ let stamp = 0
1026
1531
  try {
1027
- for (const value of encoded) {
1532
+ for (const [op, payload] of ops) {
1533
+ stamp = await this._stamp(tx)
1534
+ // closed while it was stamped: Bare ends the process on a hash of no key, where Node throws
1535
+ const key = this.writerKey
1536
+ if (!key) throw CeroError.CLOSED('Database')
1537
+ const value = this.dispatcher.encode(`@${this.ns}/${op}`, payload, stamp)
1028
1538
  await this.dispatcher.dispatch(value, {
1029
1539
  host,
1030
1540
  view: tx,
1031
- key: this.writerKey,
1541
+ key,
1032
1542
  dbKey: this.key,
1033
- seed: crypto.hash([this.writerKey, value]),
1034
- dryRun: true
1543
+ seed: crypto.hash([key, value]),
1544
+ stamp
1035
1545
  })
1546
+ wrapped.push(wrap(stamp, value))
1036
1547
  }
1037
- return tx.updated()
1548
+ return { wrapped, changed: tx.updated(), stamp }
1038
1549
  } finally {
1039
1550
  // a failing close must not mask the handler's own rejection
1040
1551
  try {
@@ -1072,7 +1583,11 @@ export class Database extends ReadyResource {
1072
1583
  if (ref?.orderIndex) {
1073
1584
  const range = {}
1074
1585
  pushWindow(range, rest)
1075
- return { path: `${col}-index`, range, rest, sorted: true }
1586
+ // a full read, and a count, scan the collection in about half the time the order index takes to walk
1587
+ if (range.limit !== undefined) {
1588
+ return { path: `${col}-index`, range, rest, sorted: true, count: col }
1589
+ }
1590
+ return { path: col, range: {}, rest: { ...rest, reverse: range.reverse }, sorted: false }
1076
1591
  }
1077
1592
  return { path: col, range: {}, rest, sorted: false }
1078
1593
  }
@@ -1086,30 +1601,84 @@ export class Database extends ReadyResource {
1086
1601
  return (await view.find(path, bounds).toArray()).length
1087
1602
  }
1088
1603
 
1089
- // this identity's member row, looked up again on every update until one lands it
1604
+ // what `find` reads of this identity's place, read again on every update and once this device
1605
+ // writes, until there is something; its throw ends the wait
1090
1606
  /** @private */
1091
- _member(timeout) {
1607
+ _member(timeout, find) {
1092
1608
  return new Promise((resolve, reject) => {
1093
- const done = (err, member) => {
1609
+ const done = (err, found) => {
1094
1610
  clearTimeout(timer)
1095
1611
  this.off('update', check)
1612
+ this.off('writable', check)
1096
1613
  this.off('close', onclose)
1097
1614
  if (err) reject(err)
1098
- else resolve(member)
1615
+ else resolve(found)
1099
1616
  }
1100
- const check = () =>
1101
- this.get('members', this.identity.id).then(({ data }) => data && done(null, data), done)
1617
+ const check = () => find().then((found) => found && done(null, found), done)
1102
1618
  const onclose = () => done(CeroError.CLOSED('Database'))
1103
1619
  const timer =
1104
1620
  timeout > 0
1105
1621
  ? setTimeout(() => done(CeroError.TIMEOUT('waiting for the member row')), timeout)
1106
1622
  : null
1107
1623
  this.on('update', check)
1624
+ this.on('writable', check)
1108
1625
  this.once('close', onclose)
1109
1626
  check()
1110
1627
  })
1111
1628
  }
1112
1629
 
1630
+ // the member's role, or that of the first promise made to the identity, as apply picks it, and
1631
+ // whether this device has a promise to keep
1632
+ /** @private */
1633
+ async _standing() {
1634
+ const { data: member } = await this.get('members', this.identity.id)
1635
+ const { data: requests } = await this.get('requests')
1636
+ // a core that wrote already, its join or an earlier claim, claims once the view holds what it
1637
+ // wrote: appended on a view still catching up with it, a claim is lost. Turned away, it hears.
1638
+ // What the view read and kept no row of, a claim refused where it landed, is made again
1639
+ const id = hid.encode(this.writerKey)
1640
+ const { data: device } = await this.get('devices', id)
1641
+ const landed = device || requests.some((row) => row.id === id)
1642
+ if (this.length > 0 && !landed) {
1643
+ await this._refused()
1644
+ const read = await this.bee.system.get(this.writerKey)
1645
+ if (!read || read.length < this.length) return null
1646
+ }
1647
+ const mine = (row) => row.promised && b4a.equals(row.identity, this.identity.publicKey)
1648
+ const made = requests.filter(mine)
1649
+ const [first] = made
1650
+ // a claim that left no row was refused: made again against the same member row and promises,
1651
+ // it would be refused again, a block at every launch
1652
+ const against = b4a.from(JSON.stringify([member?.role, made.map((row) => row.id)]))
1653
+ const claimed = device ? null : await this.bee.local.getUserData('cero/claim')
1654
+ if (claimed && b4a.equals(claimed, against)) return null
1655
+ // a member's device keeps what it was promised itself, once: its row is the promise kept
1656
+ const own = made.some((row) => b4a.equals(row.key, this.identity.device.publicKey))
1657
+ if (member) return { role: member.role, promised: own && !device, against }
1658
+ return first ? { role: first.role, promised: true, against } : null
1659
+ }
1660
+
1661
+ // a claim kept: this device's seat, or its row at a role with none
1662
+ /** @private */
1663
+ async _kept(role) {
1664
+ await this._refused()
1665
+ if (can(role, WRITE)) return this.writable
1666
+ return (await this.get('devices', hid.encode(this.writerKey))).data
1667
+ }
1668
+
1669
+ // a writer has a refusal only where it has no request: its join turned away, or what it was
1670
+ // promised withdrawn. One under another invite than the join its core carries answers a join
1671
+ // it made before, read while its view has yet to reach this one
1672
+ /** @private */
1673
+ async _refused() {
1674
+ const id = hid.encode(this.writerKey)
1675
+ const refusal = await this.view.get(`@${this.ns}/${REFUSALS}`, { id })
1676
+ if (!refusal) return
1677
+ const joined = refusal.invite && (await this.bee.local.getUserData('cero/join'))
1678
+ if (joined && b4a.toHex(joined) !== refusal.invite) return
1679
+ throw CeroError.DENIED(refusal.reason || null)
1680
+ }
1681
+
1113
1682
  // the add-writer row for `writer`, appended by this device and proven by its device key
1114
1683
  /** @private */
1115
1684
  _admission(writer, ts = Date.now()) {
@@ -1128,10 +1697,51 @@ export class Database extends ReadyResource {
1128
1697
 
1129
1698
  // an unbounded read of an old checkout wedges autobee's drain; null means untrusted
1130
1699
  function bounded(promise, ms = 2000) {
1131
- return Promise.race([
1132
- promise.then((v) => ({ v })),
1133
- new Promise((resolve) => setTimeout(() => resolve(null), ms))
1134
- ])
1700
+ let timer = null
1701
+ const bound = new Promise((resolve) => {
1702
+ timer = setTimeout(() => resolve(null), ms)
1703
+ timer.unref()
1704
+ })
1705
+ return Promise.race([promise.then((v) => ({ v })), bound]).finally(() => clearTimeout(timer))
1706
+ }
1707
+
1708
+ // a point of a view: its core and how long it was
1709
+ const point = {
1710
+ preencode(state, p) {
1711
+ c.fixed32.preencode(state, p.key)
1712
+ c.uint.preencode(state, p.length)
1713
+ },
1714
+ encode(state, p) {
1715
+ c.fixed32.encode(state, p.key)
1716
+ c.uint.encode(state, p.length)
1717
+ },
1718
+ decode(state) {
1719
+ return { key: c.fixed32.decode(state), length: c.uint.decode(state) }
1720
+ }
1721
+ }
1722
+
1723
+ // a kept point, null when there is none or it does not read
1724
+ function decodePoint(buf) {
1725
+ try {
1726
+ return buf ? c.decode(point, buf) : null
1727
+ } catch {
1728
+ return null
1729
+ }
1730
+ }
1731
+
1732
+ // the rows of a collection that differ from a point of its view, all of them with none; null when
1733
+ // the point's blocks do not come, as for one in a view this device never applied
1734
+ async function rows(snap, col, from) {
1735
+ const stream = snap.diff(col, from ? { from } : {})
1736
+ const read = async () => {
1737
+ const changes = []
1738
+ for await (const { left, right } of stream) changes.push({ prev: left, next: right })
1739
+ return changes
1740
+ }
1741
+ if (!from) return read()
1742
+ const done = await bounded(read())
1743
+ if (!done) stream.destroy()
1744
+ return done ? done.v : null
1135
1745
  }
1136
1746
 
1137
1747
  const NO_HOOKS = []
@@ -1165,19 +1775,32 @@ function verbMap(refs) {
1165
1775
  return map
1166
1776
  }
1167
1777
 
1168
- // the one op a device without a writer seat may append
1169
1778
  function leaving(ops, id) {
1170
1779
  return ops.length === 1 && ops[0][0] === 'del-member' && ops[0][1]?.id === id
1171
1780
  }
1172
1781
 
1782
+ // what a device without a writer seat may append: its leave, its own member row, what its
1783
+ // identity's devices are, its ask for keys and the close of it
1784
+ function seatless(ops, id) {
1785
+ if (ops.length !== 1) return false
1786
+ const [name, value] = ops[0]
1787
+ return (
1788
+ leaving(ops, id) ||
1789
+ (name === 'set-member' && value?.id === id) ||
1790
+ ['revoke', 'ask-key', 'del-owed'].includes(name)
1791
+ )
1792
+ }
1793
+
1173
1794
  const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
1174
1795
 
1175
1796
  const byIndex = (a, b) => (a.index ?? 0) - (b.index ?? 0)
1176
1797
 
1177
- // the index whose fields are exactly the query's equality keys
1798
+ // the index whose fields are exactly the query's equality keys, or those and then `index`: that
1799
+ // one reads the matches in list order
1178
1800
  function matchIndex(indexes, fields) {
1179
1801
  for (const [name, keys] of Object.entries(indexes || {})) {
1180
- if (keys.length === fields.length && keys.every((f) => fields.includes(f))) return name
1802
+ const eq = keys.at(-1) === 'index' && !fields.includes('index') ? keys.slice(0, -1) : keys
1803
+ if (eq.length === fields.length && eq.every((f) => fields.includes(f))) return name
1181
1804
  }
1182
1805
  return null
1183
1806
  }