@cero-base/core 2.12.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
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 +803 -204
  6. package/src/database/encryption.js +25 -21
  7. package/src/database/index.js +720 -123
  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 +343 -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 +51 -7
  26. package/types/database/encryption.d.ts +13 -5
  27. package/types/database/index.d.ts +190 -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,8 +15,13 @@ import {
15
15
  QUERY_RESERVED,
16
16
  RANK,
17
17
  ADMIN,
18
+ OWNER,
18
19
  WRITE,
19
- REMOVALS
20
+ REMOVALS,
21
+ REFUSALS,
22
+ ASKS,
23
+ COUNTERS,
24
+ OWED
20
25
  } from '../lib/constants.js'
21
26
  import { genId } from '../lib/ids.js'
22
27
  import {
@@ -29,12 +34,12 @@ import {
29
34
  stamp
30
35
  } from '../lib/utils.js'
31
36
  import { wrap, unwrap } from './envelope.js'
32
- import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
37
+ import { EpochAutobee, Keyring, loadEpochs, plainId } from './encryption.js'
33
38
  import { CeroError } from '../lib/errors.js'
34
39
  import { Identity } from '../identity/index.js'
35
- import { Rotation } from './rotation.js'
40
+ import { Rotation, removes } from './rotation.js'
36
41
  import { makeChanges } from './changes.js'
37
- import { makeDispatcher, BESPOKE, leftId } from './dispatch.js'
42
+ import { makeDispatcher, BESPOKE, leftId, toldId, keysOf } from './dispatch.js'
38
43
  import { keyPair } from '../mailbox/inbox.js'
39
44
 
40
45
  // autobee remaps an older store once a recovery peer, a mirror, serves it; unset, it closes the store
@@ -46,19 +51,21 @@ Hypercore.setRecoveryPeers(recovery)
46
51
  * @property {import('corestore')} store Corestore (or compatible) used to materialize the autobee.
47
52
  * @property {import('../identity/index.js').Identity} identity Long-lived member identity used to sign writer changes.
48
53
  * @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication; `store` is its store or a session of it.
49
- * @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.
50
55
  * @property {string} [namespace] Corestore namespace; defaults to `cero`.
51
56
  * @property {Uint8Array} encryptionKey Encrypts it; a join hands it out, so never the identity's on a database you pair.
52
57
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
53
58
  * @property {Uint8Array | null} [key] Existing autobee key to reopen.
54
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.
55
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.
56
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.
57
64
  * @property {(err: Error) => void} [onerror] Called when a node is skipped or refused, or the bee errors.
58
65
  *
59
- * Events: `update` (touched refs, a Set, after each applied batch), `apply` (one per applied
60
- * op: `{ op, name, row, writerKey, seq }`, local and replicated), `writable`, `unwritable`,
61
- * `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).
62
69
  *
63
70
  * @typedef {Record<string, unknown>} Row A row, fields by name.
64
71
  * @typedef {{ data: Row | null }} SingleResult
@@ -112,8 +119,24 @@ export class Database extends ReadyResource {
112
119
  this.ns = this.meta.ns || NAMESPACE
113
120
  this.refs = this.meta.refs || {}
114
121
  this.version = this.meta.version || 1
115
- /** @type {number | null} */
116
- 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()
117
140
  this.namespace = opts.namespace || NAMESPACE
118
141
  this._writable = false
119
142
  this.encryptionKey = opts.encryptionKey
@@ -122,8 +145,10 @@ export class Database extends ReadyResource {
122
145
  /** @private */
123
146
  this._delivered = !!opts.epochs?.length
124
147
  this.rotation = new Rotation(this)
148
+ this.keyring.onmiss = (stamp) => this.rotation.meet(stamp)
125
149
  this.key = opts.key || null
126
150
  this.pinned = opts.pinned === true
151
+ this.root = opts.root === true
127
152
  this.push = opts.push === true
128
153
  /** @private */
129
154
  this._pushes = pushes(this.refs)
@@ -193,6 +218,11 @@ export class Database extends ReadyResource {
193
218
  return this.bee?.local?.key || null
194
219
  }
195
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
+
196
226
  /** @returns {boolean} whether the bee accepts local writes */
197
227
  get writable() {
198
228
  return this._writable
@@ -216,28 +246,52 @@ export class Database extends ReadyResource {
216
246
  this.dispatcher = makeDispatcher({
217
247
  spec: this.spec,
218
248
  ns: this.ns,
249
+ start: this.start,
250
+ contract: () => this.version,
251
+ onskip: (stamp) => this._skip(stamp),
252
+ build: () => this._build(),
219
253
  onerror: this._onerror,
220
254
  key: () => this.key,
221
255
  onepoch: (row) => this.rotation.learn(row),
222
256
  room: () => this._room,
257
+ root: this.root,
223
258
  hooks: (phase, op) => this._hooks(phase, op),
224
259
  touch: (name) => this._touched.add(name),
225
260
  read: (view, name, query) => this._read(view, name, query)
226
261
  })
227
262
 
228
263
  const known = !!this.key
229
- await this._boot()
230
- const replayed = await this._replay()
231
- if (replayed) await this._boot()
232
-
233
- // before replication can deliver blocks at epochs we haven't learned yet
234
- await this.rotation.hydrate()
235
- // epochs handed over at join are sealed to nobody this device can read later: keep them
236
- 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
+ }
237
280
 
238
- // 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
239
284
  this.on('update', () => this.rotation.heal())
285
+ this.rotation.heal()
240
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() {
241
295
  this.bee.on('writable', () => this._onwritable())
242
296
  // falling edge: apps freeze the UI the moment access ends
243
297
  this.bee.on('unwritable', () => {
@@ -249,15 +303,14 @@ export class Database extends ReadyResource {
249
303
  // a failed background remap is only a warning: the store reads its old cores until a reopen or a fast-forward
250
304
  // tries again
251
305
  this.bee.on('warning', this._onerror)
306
+ const bee = this.bee
307
+ this.bee.on('move-to', () => this._onmove(bee))
252
308
 
253
309
  // with no mirror to hold the database, every member holds it: any member serves a joiner, offline
254
310
  if (this.network && !this.network.mirrors.length) {
255
311
  this.bee.on('move-to', () => this._holdRoom().catch(safetyCatch))
256
312
  this._holdRoom().catch(safetyCatch)
257
313
  }
258
-
259
- // a fresh db has no key until boot mints it
260
- if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
261
314
  }
262
315
 
263
316
  /** @private */
@@ -384,7 +437,7 @@ export class Database extends ReadyResource {
384
437
  * @returns {Promise<{ epoch: number }>}
385
438
  */
386
439
  async rotate() {
387
- // 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
388
441
  if (this.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
389
442
  return this.rotation.rotate()
390
443
  }
@@ -408,7 +461,12 @@ export class Database extends ReadyResource {
408
461
  const batch = Object.create(this)
409
462
  batch.txQueue = []
410
463
  try {
411
- const result = await fn(batch)
464
+ let result
465
+ try {
466
+ result = await fn(batch)
467
+ } finally {
468
+ batch.spent = true
469
+ }
412
470
  if (batch.txQueue.length) await this._chain(() => this.write(batch.txQueue))
413
471
  return result
414
472
  } catch (err) {
@@ -430,37 +488,73 @@ export class Database extends ReadyResource {
430
488
  * is open.
431
489
  *
432
490
  * @param {Array<[string, unknown]>} ops
433
- * @returns {Promise<void>}
491
+ * @returns {Promise<number | undefined>} The stamp the last op was appended with; nothing when queued or when nothing changed.
434
492
  */
435
493
  async write(ops) {
436
- // behind, a set merges from a view missing the newer writes and every device takes the stale
437
- // row: no writes until the update, but leaving, which touches nothing else
438
- if (this.behind !== null && !leaving(ops, this.identity.id)) throw CeroError.BEHIND(this.behind)
494
+ if (this._frozen(ops)) throw CeroError.BEHIND(this.behind)
439
495
  if (this.txQueue) {
496
+ if (this.spent) throw CeroError.INVALID('a write through tx after its fn returned')
440
497
  for (const op of ops) this.txQueue.push(op)
441
498
  return
442
499
  }
443
500
  this.guard()
444
- // leaving takes no seat: a reader's own removal goes in optimistically, apply admits it
445
- 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)
446
535
  if (!this.bee.writable && !optimistic) throw CeroError.NOT_WRITABLE('Database')
447
536
  // writable flips inside the apply that admits us, before its view flush lands our device row
448
537
  await this.bee.updated()
449
- const encoded = ops.map(([op, payload]) =>
450
- this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
451
- )
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
452
542
  // the dry run refuses what apply would; a no-op never reaches the log, an action always does
453
543
  const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
454
544
  try {
455
- if (!(await this._dryRun(encoded)) && !action) return
456
- 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)
457
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
458
554
  } catch (err) {
459
555
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
460
556
  throw err
461
557
  }
462
- const ref = this.push ? this._ref(ops) : null
463
- if (ref) this._push(ref)
464
558
  }
465
559
 
466
560
  /** @returns {boolean} Whether a push notification is on its way to the mirrors. */
@@ -534,6 +628,8 @@ export class Database extends ReadyResource {
534
628
  */
535
629
  async get(name, query) {
536
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
537
633
  return this._read(this.view, name, query)
538
634
  }
539
635
 
@@ -554,6 +650,157 @@ export class Database extends ReadyResource {
554
650
  return null
555
651
  }
556
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
+
557
804
  // the same read against any view: hooks read the transaction they run in
558
805
  /** @private */
559
806
  async _read(view, name, query) {
@@ -568,12 +815,13 @@ export class Database extends ReadyResource {
568
815
  return { data: await view.get(col, { id: query }) }
569
816
  }
570
817
 
571
- const { path, range, rest, sorted } = this._plan(name, query)
818
+ const { path, range, rest, sorted, count = path } = this._plan(name, query)
572
819
  const rows = await view.find(path, range).toArray()
573
- if (!sorted) rows.sort(byIndex)
574
- 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()
575
823
  const data = rest.limit === undefined ? matched : matched.slice(0, rest.limit)
576
- 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 }
577
825
  }
578
826
 
579
827
  /**
@@ -606,6 +854,41 @@ export class Database extends ReadyResource {
606
854
  return makeChanges(this, name, col, (row) => filter([row], rest).length > 0)
607
855
  }
608
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
+
609
892
  /**
610
893
  * Provision this device. Its writer core was minted when the database opened and this
611
894
  * device is its only author, ever.
@@ -628,9 +911,14 @@ export class Database extends ReadyResource {
628
911
  ]
629
912
  if (recovering) {
630
913
  await this.claim({ timeout })
631
- 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)]])
632
919
  } else {
633
- // 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
634
922
  const member = {
635
923
  id: this.identity.id,
636
924
  key: this.writerKey,
@@ -640,15 +928,20 @@ export class Database extends ReadyResource {
640
928
  updatedAt: ts
641
929
  }
642
930
  const writer = this._admission(this.writerKey, ts)
643
- 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])
644
933
  }
645
934
  return { id: this.writerKey, writer: this.keyPair }
646
935
  }
647
936
 
648
937
  /**
649
- * Seat this device's writer where its identity is a member: wait for the member row, append
650
- * the add-writer the identity signs from this device's own core, and resolve once it writes.
651
- * 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.
652
945
  *
653
946
  * @param {{ timeout?: number }} [opts]
654
947
  * @returns {Promise<void>}
@@ -656,13 +949,26 @@ export class Database extends ReadyResource {
656
949
  async claim({ timeout = 30000 } = {}) {
657
950
  this.guard()
658
951
  if (this.bee.writable) return
659
- const { role } = await this._member(timeout)
660
- if (!can(role, WRITE)) return
661
- const op = this.spec.dispatch.encode(`@${this.ns}/add-writer`, this._admission(this.writerKey))
662
- // from a core not yet admitted: apply verifies the identity's signature and seats it
663
- await this.bee.append(wrap(this.version, op), { optimistic: true })
664
- await this.bee.update()
665
- 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
+ }
666
972
  }
667
973
 
668
974
  /**
@@ -706,24 +1012,47 @@ export class Database extends ReadyResource {
706
1012
 
707
1013
  /**
708
1014
  * Learn epochs handed over after the open, as a root carries them for a handle. One is kept
709
- * once its announcement applied here and the secret meets the commitment it carries: hand them
710
- * 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.
711
1017
  *
712
1018
  * @param {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} epochs
1019
+ * @param {string} [from] The device that sent them, when one did.
713
1020
  * @returns {Promise<void>}
714
1021
  */
715
- async learn(epochs) {
1022
+ async learn(epochs, from) {
716
1023
  this.guard()
717
1024
  const rows = await this.rotation._epochs()
718
1025
  let added = false
719
1026
  for (const e of epochs) {
720
- if (this.keyring.entropy(e.stamp)) continue
1027
+ if (e.entropy?.byteLength !== 32) continue
721
1028
  const row = rows.find((r) => r.stamp === e.stamp)
722
- 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
723
1032
  this.keyring.add(e.stamp, e.entropy, e.epoch)
724
1033
  added = true
725
1034
  }
726
- 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())
727
1056
  }
728
1057
 
729
1058
  /**
@@ -777,7 +1106,21 @@ export class Database extends ReadyResource {
777
1106
  // the boot reads post-rotation state through the keyring, primed before the bee exists
778
1107
  /** @private */
779
1108
  async _preload() {
780
- 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({
781
1124
  keyPair: this.keyPair,
782
1125
  manifest: {
783
1126
  version: this.store.manifestVersion,
@@ -786,17 +1129,22 @@ export class Database extends ReadyResource {
786
1129
  active: false
787
1130
  })
788
1131
  await local.ready()
789
- await loadEpochs(this.keyring, local)
790
- 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
+ }
791
1138
  }
792
1139
 
793
1140
  /** @private */
794
- async _boot() {
1141
+ async _boot({ land = true } = {}) {
795
1142
  const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
796
1143
  keyPair: this.keyPair,
797
1144
  encryptionKey: this.encryptionKey,
798
1145
  keyring: this.keyring,
799
1146
  optimistic: true,
1147
+ fastForward: land ? undefined : false,
800
1148
  wakeup: this.network?.wakeup || undefined,
801
1149
  open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
802
1150
  isTrusted: this._isTrusted.bind(this),
@@ -805,31 +1153,21 @@ export class Database extends ReadyResource {
805
1153
  })
806
1154
  // swarm BEFORE boot so the boot has peers to pull from, not a cold open
807
1155
  if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
808
- await bee.ready()
809
- // 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
810
1157
  this.bee = bee
1158
+ await bee.ready()
811
1159
  this.key = bee.key
812
1160
  await bee.update()
813
1161
  }
814
1162
 
815
- // ops skipped as too new apply once this version caught up, and a view whose definition grew
816
- // since it was built (an index added by a rebuild) fills from the log: wipe the boot record and
817
- // reboot
1163
+ // a view another build applied, one with ops skipped this build now reaches among them, fills
1164
+ // from the log
818
1165
  /** @private */
819
1166
  async _replay() {
820
- const local = this.bee.local
821
- const behind = await local.getUserData('cero/behind')
822
- this.behind = behind ? c.decode(c.uint, behind) : null
823
- const caught = this.behind !== null && this.behind <= this.version
824
- const built = await local.getUserData('cero/view')
825
- const { db } = this.spec.database.versions
826
- const grown = !!built && c.decode(c.uint, built) < db
827
- if (!built || grown) await local.setUserData('cero/view', c.encode(c.uint, db))
828
- if (!caught && !grown) return false
829
- await local.setUserData('autobee/head', null)
830
- await local.setUserData('cero/behind', null)
831
- await this.bee.close()
832
- 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()
833
1171
  return true
834
1172
  }
835
1173
 
@@ -853,7 +1191,7 @@ export class Database extends ReadyResource {
853
1191
  }
854
1192
  }
855
1193
 
856
- // 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
857
1195
  /** @private */
858
1196
  async _apply(nodes, view, host) {
859
1197
  const ready = []
@@ -864,25 +1202,42 @@ export class Database extends ReadyResource {
864
1202
  this._onerror(CeroError.INVALID('an op with no envelope'))
865
1203
  continue
866
1204
  }
867
- if (op.version > this.version) {
868
- 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
+ )
869
1214
  continue
870
1215
  }
871
- ready.push({ ...node, value: op.body })
1216
+ ready.push({ ...node, value: op.body, version: op.version })
872
1217
  }
873
- const result = await this.dispatcher.apply(ready, view, host)
874
- this._notify(ready)
875
- 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)
876
1224
  }
877
1225
 
878
- // '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
879
1229
  /** @private */
880
1230
  async _update(db) {
881
1231
  await db.update()
1232
+ this._track(await this.dispatcher.version(db))
882
1233
  const touched = this._touched
1234
+ const quiet = this._applied && touched.size === 0
1235
+ const landed = this._landed
883
1236
  this._touched = new Set()
884
- this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
885
- 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()
886
1241
  }
887
1242
 
888
1243
  // every bee a boot opens is attached, but the topic is joined once: close leaves it once
@@ -953,6 +1308,16 @@ export class Database extends ReadyResource {
953
1308
  return () => this.off('update', tick)
954
1309
  }
955
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
+
956
1321
  // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
957
1322
  /** @private */
958
1323
  _opOf(node) {
@@ -963,22 +1328,22 @@ export class Database extends ReadyResource {
963
1328
  return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
964
1329
  }
965
1330
 
966
- // 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
967
1332
  /** @private */
968
- _notify(nodes) {
1333
+ _notify(nodes, changed) {
969
1334
  const listened = this.listenerCount('apply') > 0
970
1335
  for (const node of nodes) {
971
1336
  let op
972
1337
  try {
973
1338
  op = this._opOf(node)
974
1339
  } catch (err) {
975
- this._touched.add('*')
1340
+ if (changed) this._touched.add('*')
976
1341
  safetyCatch(err)
977
1342
  continue
978
1343
  }
979
1344
  const ref = this._verbs.get(op.name)
980
1345
  // an action's hooks write wherever they want, widen to all
981
- this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
1346
+ if (changed) this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
982
1347
  if (!listened) continue
983
1348
  this.emit('apply', {
984
1349
  op: op.op,
@@ -1009,6 +1374,11 @@ export class Database extends ReadyResource {
1009
1374
  await this._append({ ...stored, role: '' }, verb)
1010
1375
  return { row: stored }
1011
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
+ }
1012
1382
  return this._append(stored, verb)
1013
1383
  }
1014
1384
 
@@ -1031,36 +1401,151 @@ export class Database extends ReadyResource {
1031
1401
  return ctx ? { data: ctx.row } : null
1032
1402
  }
1033
1403
 
1034
- // 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
1411
+ /** @private */
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])
1416
+ }
1417
+
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
1035
1420
  /** @private */
1036
- _onfuture(version) {
1037
- if (this.behind !== null && version <= this.behind) return
1038
- this.behind = version
1039
- this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
1040
- this.emit('behind', version)
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)
1041
1477
  }
1042
1478
 
1043
- // every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
1479
+ // an owner's device moves the database to the version its build asks for, a batch of its own
1044
1480
  /** @private */
1045
- async _dryRun(encoded) {
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) {
1046
1523
  const tx = this.view.transaction()
1047
1524
  const host = {
1048
1525
  addWriter: async () => {},
1049
1526
  removeWriter: async () => {},
1050
1527
  genesis: this.bee.system.isGenesis()
1051
1528
  }
1529
+ const wrapped = []
1530
+ let stamp = 0
1052
1531
  try {
1053
- 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)
1054
1538
  await this.dispatcher.dispatch(value, {
1055
1539
  host,
1056
1540
  view: tx,
1057
- key: this.writerKey,
1541
+ key,
1058
1542
  dbKey: this.key,
1059
- seed: crypto.hash([this.writerKey, value]),
1060
- dryRun: true
1543
+ seed: crypto.hash([key, value]),
1544
+ stamp
1061
1545
  })
1546
+ wrapped.push(wrap(stamp, value))
1062
1547
  }
1063
- return tx.updated()
1548
+ return { wrapped, changed: tx.updated(), stamp }
1064
1549
  } finally {
1065
1550
  // a failing close must not mask the handler's own rejection
1066
1551
  try {
@@ -1098,7 +1583,11 @@ export class Database extends ReadyResource {
1098
1583
  if (ref?.orderIndex) {
1099
1584
  const range = {}
1100
1585
  pushWindow(range, rest)
1101
- 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 }
1102
1591
  }
1103
1592
  return { path: col, range: {}, rest, sorted: false }
1104
1593
  }
@@ -1112,30 +1601,84 @@ export class Database extends ReadyResource {
1112
1601
  return (await view.find(path, bounds).toArray()).length
1113
1602
  }
1114
1603
 
1115
- // 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
1116
1606
  /** @private */
1117
- _member(timeout) {
1607
+ _member(timeout, find) {
1118
1608
  return new Promise((resolve, reject) => {
1119
- const done = (err, member) => {
1609
+ const done = (err, found) => {
1120
1610
  clearTimeout(timer)
1121
1611
  this.off('update', check)
1612
+ this.off('writable', check)
1122
1613
  this.off('close', onclose)
1123
1614
  if (err) reject(err)
1124
- else resolve(member)
1615
+ else resolve(found)
1125
1616
  }
1126
- const check = () =>
1127
- this.get('members', this.identity.id).then(({ data }) => data && done(null, data), done)
1617
+ const check = () => find().then((found) => found && done(null, found), done)
1128
1618
  const onclose = () => done(CeroError.CLOSED('Database'))
1129
1619
  const timer =
1130
1620
  timeout > 0
1131
1621
  ? setTimeout(() => done(CeroError.TIMEOUT('waiting for the member row')), timeout)
1132
1622
  : null
1133
1623
  this.on('update', check)
1624
+ this.on('writable', check)
1134
1625
  this.once('close', onclose)
1135
1626
  check()
1136
1627
  })
1137
1628
  }
1138
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
+
1139
1682
  // the add-writer row for `writer`, appended by this device and proven by its device key
1140
1683
  /** @private */
1141
1684
  _admission(writer, ts = Date.now()) {
@@ -1154,10 +1697,51 @@ export class Database extends ReadyResource {
1154
1697
 
1155
1698
  // an unbounded read of an old checkout wedges autobee's drain; null means untrusted
1156
1699
  function bounded(promise, ms = 2000) {
1157
- return Promise.race([
1158
- promise.then((v) => ({ v })),
1159
- new Promise((resolve) => setTimeout(() => resolve(null), ms))
1160
- ])
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
1161
1745
  }
1162
1746
 
1163
1747
  const NO_HOOKS = []
@@ -1191,19 +1775,32 @@ function verbMap(refs) {
1191
1775
  return map
1192
1776
  }
1193
1777
 
1194
- // the one op a device without a writer seat may append
1195
1778
  function leaving(ops, id) {
1196
1779
  return ops.length === 1 && ops[0][0] === 'del-member' && ops[0][1]?.id === id
1197
1780
  }
1198
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
+
1199
1794
  const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
1200
1795
 
1201
1796
  const byIndex = (a, b) => (a.index ?? 0) - (b.index ?? 0)
1202
1797
 
1203
- // 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
1204
1800
  function matchIndex(indexes, fields) {
1205
1801
  for (const [name, keys] of Object.entries(indexes || {})) {
1206
- 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
1207
1804
  }
1208
1805
  return null
1209
1806
  }