@cero-base/core 1.18.1 → 1.19.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 (46) hide show
  1. package/README.md +5 -6
  2. package/package.json +9 -9
  3. package/src/blobs/index.js +2 -2
  4. package/src/database/changes.js +37 -59
  5. package/src/database/dispatch.js +31 -45
  6. package/src/database/index.js +395 -343
  7. package/src/database/rotation.js +201 -189
  8. package/src/identity/index.js +3 -3
  9. package/src/lib/utils.js +50 -18
  10. package/src/pairing/candidate.js +125 -0
  11. package/src/pairing/index.js +6 -223
  12. package/src/pairing/request.js +102 -0
  13. package/src/storage/index.js +11 -18
  14. package/types/blobs/codec.d.ts +8 -8
  15. package/types/blobs/index.d.ts +34 -33
  16. package/types/blobs/server.d.ts +8 -8
  17. package/types/database/changes.d.ts +5 -7
  18. package/types/database/dispatch.d.ts +30 -23
  19. package/types/database/encryption.d.ts +14 -10
  20. package/types/database/envelope.d.ts +2 -2
  21. package/types/database/index.d.ts +173 -181
  22. package/types/database/rotation.d.ts +53 -30
  23. package/types/identity/index.d.ts +81 -81
  24. package/types/index.d.ts +37 -51
  25. package/types/lib/constants.d.ts +34 -38
  26. package/types/lib/errors.d.ts +10 -10
  27. package/types/lib/schema.d.ts +47 -37
  28. package/types/lib/spec/index.d.ts +29 -55
  29. package/types/lib/utils.d.ts +27 -17
  30. package/types/network/discovery.d.ts +7 -7
  31. package/types/network/index.d.ts +50 -48
  32. package/types/pairing/candidate.d.ts +37 -0
  33. package/types/pairing/index.d.ts +87 -139
  34. package/types/pairing/invite.d.ts +88 -88
  35. package/types/pairing/request.d.ts +135 -0
  36. package/types/rpc/client.d.ts +2 -2
  37. package/types/rpc/index.d.ts +33 -33
  38. package/types/rpc/peer.d.ts +9 -7
  39. package/types/rpc/server.d.ts +2 -2
  40. package/types/storage/index.d.ts +70 -68
  41. package/src/database/bootstrap.js +0 -133
  42. package/src/database/hooks.js +0 -112
  43. package/src/database/membership.js +0 -67
  44. package/types/database/bootstrap.d.ts +0 -20
  45. package/types/database/hooks.d.ts +0 -8
  46. package/types/database/membership.d.ts +0 -7
@@ -5,6 +5,7 @@ import Hypercore from 'hypercore'
5
5
  import ReadyResource from 'ready-resource'
6
6
  import safetyCatch from 'safety-catch'
7
7
  import b4a from 'b4a'
8
+ import hid from 'hypercore-id-encoding'
8
9
 
9
10
  import {
10
11
  NAMESPACE,
@@ -15,14 +16,12 @@ import {
15
16
  PASSIVE,
16
17
  QUERY_RESERVED
17
18
  } from '../lib/constants.js'
18
- import { genId, toId, subscribe, addWriterPayload, searchHit } from '../lib/utils.js'
19
+ import { genId, subscribe, admission, ownership, filter } from '../lib/utils.js'
19
20
  import { wrap, unwrap } from './envelope.js'
20
21
  import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
21
22
  import { CeroError } from '../lib/errors.js'
22
- import { bootstrap } from './bootstrap.js'
23
- import { claim, claimOp, whenWritable, addWriter, removeWriter } from './membership.js'
24
- import { before, after, onUpdate, onApply, runBefore, runAfter, touch, observe } from './hooks.js'
25
- import { rotate, onepoch, hydrateEpochs, scheduleHeal, onfuture } from './rotation.js'
23
+ import { Identity } from '../identity/index.js'
24
+ import { Rotation } from './rotation.js'
26
25
  import { makeChanges } from './changes.js'
27
26
  import { makeDispatcher } from './dispatch.js'
28
27
 
@@ -36,10 +35,9 @@ import { makeDispatcher } from './dispatch.js'
36
35
  * @property {string} [namespace] Corestore namespace; defaults to `cero`.
37
36
  * @property {Uint8Array | null} [encryptionKey] Optional encryption key; falls back to identity's key.
38
37
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
39
- * @property {(nodes: any, view: any, host: any) => Promise<void>} [apply] Override the default apply function.
40
38
  * @property {Uint8Array | null} [key] Existing autobee key to reopen.
41
39
  * @property {boolean} [passive] Join discovery server-only (reachable but not searching). Flip at runtime with `setActive`.
42
- * @property {import('../identity/index.js').KeyPair} [keyPair] Device writer keypair; defaults to identity's keypair.
40
+ * @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.
43
41
  * @property {(err: Error) => void} [onerror] Called when a background after-hook or onApply callback fails, a malformed node is skipped, or the bee errors.
44
42
  *
45
43
  * @typedef {{ data: any | null }} SingleResult
@@ -52,7 +50,7 @@ import { makeDispatcher } from './dispatch.js'
52
50
  /**
53
51
  * Multi-writer database built on Autobee + HyperDB. Persists rows via a
54
52
  * hyperdispatch-encoded log and exposes a `put/get/...` surface mirroring
55
- * `Storage`, plus membership ops (claim/addWriter/removeWriter) for the
53
+ * `Storage`, plus writer ops (claim/addWriter/removeWriter) for the
56
54
  * shared writer set.
57
55
  */
58
56
  export class Database extends ReadyResource {
@@ -80,44 +78,69 @@ export class Database extends ReadyResource {
80
78
  this.encryptionKey = opts.encryptionKey || opts.identity.encryptionKey || null
81
79
  this.keyring = new Keyring()
82
80
  if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
83
- this._rotation = null
84
- this._healTimer = null
85
- this._healedFor = null
86
- // REMOVE-capable devices re-key when the epoch drifts from the member set
87
- this.on('update', () => scheduleHeal(this))
88
- this.applyOverride = opts.apply || null
81
+ this.rotation = new Rotation(this)
89
82
  this.key = opts.key || null
90
83
  this.passive = opts.passive === true
91
- this.keyPair = opts.keyPair || {
92
- publicKey: opts.identity.publicKey,
93
- secretKey: opts.identity.secretKey
84
+ // this device is the only author of its writer core, ever: a fresh keypair
85
+ // by default. The identity keypair is never a writer — every device can
86
+ // derive it, and two authors on one core is a fork
87
+ this.keyPair = opts.keyPair || Identity.randomKeyPair()
88
+ if (b4a.equals(this.keyPair.publicKey, this.identity.publicKey)) {
89
+ throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
94
90
  }
95
91
 
96
92
  this._onerror = opts.onerror || safetyCatch
97
93
  this.bee = null
98
94
  this.dispatcher = null
99
-
100
- this.beforeHooks = new Map()
101
- this.afterHooks = new Map()
102
- this.updaters = new Map()
103
- this.onApplyHooks = new Set()
104
- this._applySeq = 0
95
+ this._discovery = null
96
+ this._txChain = null
97
+
98
+ this._before = new Map()
99
+ this._after = new Map()
100
+ this._updaters = new Map()
101
+ this._observers = new Set()
102
+ this._verbs = verbMap(this.refs)
105
103
  this._touched = new Set()
104
+ this._seq = 0
106
105
  this.txQueue = null
107
106
  }
108
107
 
109
108
  async _open() {
110
109
  await this.store.ready()
111
110
  if (this.network) await this.network.ready()
111
+ await this._preload()
112
+ this.dispatcher = makeDispatcher({
113
+ spec: this.spec,
114
+ ns: this.ns,
115
+ routes: this.routes,
116
+ onerror: this._onerror,
117
+ key: () => this.key,
118
+ onepoch: (row) => this.rotation.learn(row)
119
+ })
120
+
121
+ const known = !!this.key
122
+ await this._boot()
123
+ const replayed = await this._replay()
124
+ if (replayed) await this._boot()
125
+
126
+ // before replication can deliver blocks at epochs we haven't learned yet
127
+ await this.rotation.hydrate()
128
+
129
+ // REMOVE-capable devices re-key when the epoch drifts from the member set
130
+ this.on('update', () => this.rotation.heal())
131
+ this.bee.on('writable', () => this.emit('writable'))
132
+ // falling edge: apps freeze the UI the moment access ends
133
+ this.bee.on('unwritable', () => this.emit('unwritable'))
134
+ // without a listener autobee escalates apply/view errors to a process crash
135
+ this.bee.on('error', this._onerror)
112
136
 
113
- await this.openBee()
137
+ // a fresh db has no key until boot mints it
138
+ if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
139
+ if (replayed) this.emit('rebuild')
114
140
  }
115
141
 
116
142
  async _close() {
117
- if (this._healTimer) {
118
- clearTimeout(this._healTimer)
119
- this._healTimer = null
120
- }
143
+ this.rotation.close()
121
144
  if (this._discovery) {
122
145
  // unannounce in the background, the DHT round-trip would block close for seconds
123
146
  this._discovery.destroy().catch(safetyCatch)
@@ -131,9 +154,9 @@ export class Database extends ReadyResource {
131
154
  }
132
155
  }
133
156
 
134
- /** Open the underlying autobee, wire dispatcher + apply, attach to network. */
135
- async openBee() {
136
- // before boot: the bee's boot reads post-rotation state via the epoch provider
157
+ // the bee's boot reads post-rotation state through the keyring, so it is
158
+ // primed from the local core's userData before the bee exists
159
+ async _preload() {
137
160
  const local = this.store.namespace(this.namespace).get({
138
161
  keyPair: this.keyPair,
139
162
  manifest: {
@@ -145,16 +168,9 @@ export class Database extends ReadyResource {
145
168
  await local.ready()
146
169
  await loadEpochs(this.keyring, local)
147
170
  await local.close()
171
+ }
148
172
 
149
- this.dispatcher = makeDispatcher(
150
- this.spec,
151
- this.ns,
152
- this.routes,
153
- this._onerror,
154
- () => this.key,
155
- { onEpoch: (row) => this._onepoch(row) }
156
- )
157
-
173
+ async _boot() {
158
174
  const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
159
175
  keyPair: this.keyPair,
160
176
  encryptionKey: this.encryptionKey,
@@ -162,85 +178,75 @@ export class Database extends ReadyResource {
162
178
  optimistic: true,
163
179
  wakeup: this.network?.wakeup || undefined,
164
180
  open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
165
- // without this hook autobee trusts EVERY fast-forward candidate, so a removed
166
- // device could serve a forked head. Decided against the reference view, not live.
167
- isTrusted: async (writer, view) => {
168
- try {
169
- const row = await bounded(view.get(`@${this.ns}/devices`, { id: toId(writer) }))
170
- if (!row) return false
171
- if (row.v) return true
172
- // only a PROVABLY empty view (genesis-era reference) lets the genesis
173
- // writer vouch, its core IS the db key. Otherwise it is an ex-member's window.
174
- const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
175
- if (!any) return false
176
- return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
177
- } catch {
178
- return false
179
- }
180
- },
181
- apply: async (nodes, view, host) => {
182
- // unwrap once so overrides see op bytes. Skipping a newer version is deterministic.
183
- const ready = []
184
- for (const node of nodes) {
185
- const { version, body } = unwrap(node.value)
186
- if (version > this.version) {
187
- onfuture(this, version)
188
- continue
189
- }
190
- ready.push(version === 0 ? node : { ...node, value: body })
191
- }
192
- const result = await (this.applyOverride || this.dispatcher.apply)(ready, view, host)
193
- if (this.updaters.size) touch(this, ready)
194
- if (this.onApplyHooks.size) observe(this, ready)
195
- return result
196
- },
197
- update: async (db) => {
198
- await db.update()
199
- const touched = this._touched
200
- this._touched = new Set()
201
- const all = touched.size === 0 || touched.has('*')
202
- for (const [fn, scope] of this.updaters) {
203
- if (all || !scope || touched.has(scope)) fn()
204
- }
205
- this.emit('update')
206
- }
181
+ isTrusted: this._isTrusted.bind(this),
182
+ apply: this._apply.bind(this),
183
+ update: this._update.bind(this)
207
184
  })
208
-
209
185
  // swarm BEFORE boot so the boot has peers to pull from, not a cold open
210
- const known = !!this.key
211
- if (this.network && known) this._joinSwarm(bee, crypto.discoveryKey(this.key))
212
-
186
+ if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
213
187
  await bee.ready()
214
- // apply-time hooks (_onepoch, _onfuture) must never see this.bee null mid-drain
188
+ // apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
215
189
  this.bee = bee
216
190
  this.key = bee.key
217
191
  await bee.update()
192
+ }
218
193
 
219
- const behind = await bee.local.getUserData('cero/behind')
194
+ // ops skipped as too new are in contract once this version caught up: wipe
195
+ // the boot record so the next boot replays them
196
+ async _replay() {
197
+ const behind = await this.bee.local.getUserData('cero/behind')
220
198
  this.behind = behind ? c.decode(c.uint, behind) : null
199
+ if (this.behind === null || this.behind > this.version) return false
200
+ await this.bee.local.setUserData('autobee/head', null)
201
+ await this.bee.local.setUserData('cero/behind', null)
202
+ await this.bee.close()
203
+ this.behind = null
204
+ return true
205
+ }
221
206
 
222
- // skipped ops are now in contract, wipe the boot record so the next open replays
223
- if (this.behind !== null && this.behind <= this.version) {
224
- await bee.local.setUserData('autobee/head', null)
225
- await bee.local.setUserData('cero/behind', null)
226
- await bee.close()
227
- this.behind = null
228
- await this.openBee()
229
- this.emit('rebuild')
230
- return
207
+ // without this hook autobee trusts EVERY fast-forward candidate, so a removed
208
+ // device could serve a forked head. Decided against the reference view, not live
209
+ async _isTrusted(writer, view) {
210
+ try {
211
+ const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
212
+ if (!row) return false
213
+ if (row.v) return true
214
+ // only a PROVABLY empty view (genesis-era reference) lets the genesis
215
+ // writer vouch, its core IS the db key. Otherwise it is an ex-member's window
216
+ const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
217
+ if (!any) return false
218
+ return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
219
+ } catch {
220
+ return false
231
221
  }
222
+ }
232
223
 
233
- // before replication can deliver blocks at epochs we haven't learned yet
234
- await this._loadEpochs()
235
-
236
- bee.on('writable', () => this.emit('writable'))
237
- // falling edge: apps freeze the UI the moment access ends
238
- bee.on('unwritable', () => this.emit('unwritable'))
239
- // without a listener autobee escalates apply/view errors to a process crash
240
- bee.on('error', this._onerror)
224
+ // unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
225
+ async _apply(nodes, view, host) {
226
+ const ready = []
227
+ for (const node of nodes) {
228
+ const { version, body } = unwrap(node.value)
229
+ if (version > this.version) {
230
+ this._onfuture(version)
231
+ continue
232
+ }
233
+ ready.push(version === 0 ? node : { ...node, value: body })
234
+ }
235
+ const result = await this.dispatcher.apply(ready, view, host)
236
+ if (this._updaters.size) this._touch(ready)
237
+ if (this._observers.size) this._observe(ready)
238
+ return result
239
+ }
241
240
 
242
- // a fresh db has no key until boot mints it
243
- if (this.network && !known) this._joinSwarm(bee, bee.discoveryKey)
241
+ async _update(db) {
242
+ await db.update()
243
+ const touched = this._touched
244
+ this._touched = new Set()
245
+ const all = touched.size === 0 || touched.has('*')
246
+ for (const [fn, scope] of this._updaters) {
247
+ if (all || !scope || touched.has(scope)) fn()
248
+ }
249
+ this.emit('update')
244
250
  }
245
251
 
246
252
  // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
@@ -298,7 +304,7 @@ export class Database extends ReadyResource {
298
304
  * @returns {() => void} disposer
299
305
  */
300
306
  before(op, fn) {
301
- return before(this, op, fn)
307
+ return addHook(this._before, op, fn)
302
308
  }
303
309
 
304
310
  /**
@@ -309,7 +315,7 @@ export class Database extends ReadyResource {
309
315
  * @returns {() => void} disposer
310
316
  */
311
317
  after(op, fn) {
312
- return after(this, op, fn)
318
+ return addHook(this._after, op, fn)
313
319
  }
314
320
 
315
321
  /**
@@ -321,7 +327,8 @@ export class Database extends ReadyResource {
321
327
  * @returns {() => void} disposer
322
328
  */
323
329
  onUpdate(fn, scope) {
324
- return onUpdate(this, fn, scope)
330
+ this._updaters.set(fn, scope || null)
331
+ return () => this._updaters.delete(fn)
325
332
  }
326
333
 
327
334
  /**
@@ -334,29 +341,69 @@ export class Database extends ReadyResource {
334
341
  * @returns {() => void} disposer
335
342
  */
336
343
  onApply(fn) {
337
- return onApply(this, fn)
344
+ if (typeof fn !== 'function') return () => {}
345
+ this._observers.add(fn)
346
+ return () => this._observers.delete(fn)
338
347
  }
339
348
 
340
- /**
341
- * Run all registered `before:op` hooks and emit the corresponding event.
342
- *
343
- * @param {string} op
344
- * @param {any} ctx
345
- * @returns {Promise<boolean>} `false` if any hook vetoed the op
346
- */
347
- async runBefore(op, ctx) {
348
- return runBefore(this, op, ctx)
349
+ async _runBefore(op, ctx) {
350
+ for (const fn of this._before.get(op) || []) {
351
+ if ((await fn(ctx)) === false) return false
352
+ }
353
+ this.emit(`before:${op}`, ctx)
354
+ return true
349
355
  }
350
356
 
351
- /**
352
- * Run all registered `after:op` hooks and emit the corresponding event.
353
- *
354
- * @param {string} op
355
- * @param {any} ctx
356
- * @returns {Promise<void>}
357
- */
358
- async runAfter(op, ctx) {
359
- return runAfter(this, op, ctx)
357
+ async _runAfter(op, ctx) {
358
+ for (const fn of this._after.get(op) || []) {
359
+ try {
360
+ await fn(ctx)
361
+ } catch (err) {
362
+ this._onerror(err)
363
+ }
364
+ }
365
+ this.emit(`after:${op}`, ctx)
366
+ }
367
+
368
+ // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
369
+ _opOf(node) {
370
+ const { name, value } = this.spec.dispatch.decode(node.value)
371
+ const verb = name.slice(name.indexOf('/') + 1)
372
+ const dash = verb.indexOf('-')
373
+ if (dash < 0) return { op: verb, name: verb, value }
374
+ return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
375
+ }
376
+
377
+ // which refs an applied batch touched, for scoped update ticks
378
+ _touch(nodes) {
379
+ for (const node of nodes) {
380
+ let ref = null
381
+ try {
382
+ ref = this._verbs.get(this._opOf(node).name)
383
+ } catch {}
384
+ // an action's route handler writes wherever it wants, widen to all
385
+ this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
386
+ }
387
+ }
388
+
389
+ _observe(nodes) {
390
+ for (const node of nodes) {
391
+ let event
392
+ try {
393
+ const { op, name, value } = this._opOf(node)
394
+ event = { op, name, row: value, writerKey: node.key, seq: this._seq++ }
395
+ } catch (err) {
396
+ safetyCatch(err)
397
+ continue
398
+ }
399
+ for (const fn of this._observers) {
400
+ try {
401
+ fn(event)
402
+ } catch (err) {
403
+ this._onerror(err)
404
+ }
405
+ }
406
+ }
360
407
  }
361
408
 
362
409
  /**
@@ -375,12 +422,12 @@ export class Database extends ReadyResource {
375
422
  const stored = { createdAt: ts, updatedAt: ts, ...row, id }
376
423
 
377
424
  const ctx = { op: 'put', name, row: stored }
378
- if ((await this.runBefore('put', ctx)) === false) return null
425
+ if ((await this._runBefore('put', ctx)) === false) return null
379
426
 
380
427
  await this.write([[`add-${ref.verb}`, ctx.row]])
381
428
 
382
429
  const result = { data: ctx.row }
383
- await this.runAfter('put', { ...ctx, result })
430
+ await this._runAfter('put', { ...ctx, result })
384
431
  return result
385
432
  }
386
433
 
@@ -394,39 +441,28 @@ export class Database extends ReadyResource {
394
441
  * @param {{ upsert?: boolean }} [opts]
395
442
  * @returns {Promise<SingleResult | null>}
396
443
  */
397
- async set(name, row, { upsert = true } = {}) {
444
+ async set(name, row, opts) {
445
+ const ctx = await this.tx((tx) => tx._merge(name, row, opts))
446
+ if (!ctx) return null
447
+ const result = { data: ctx.row }
448
+ await this._runAfter('set', { ...ctx, result })
449
+ return result
450
+ }
451
+
452
+ async _merge(name, row, { upsert = true } = {}) {
398
453
  this.guard()
399
454
  const ref = this.ref(name)
400
455
  this._checkFields(name, row)
401
- const col = this.col(ref)
402
- const ts = Date.now()
403
- const existing =
404
- ref.kind === SINGLE
405
- ? await this.view.findOne(col, {})
406
- : row?.id
407
- ? ((await this.view.get(col, { id: row.id })) ?? null)
408
- : null
456
+ const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
409
457
  if (!upsert && !existing) return null
410
- const stored = {
411
- ...existing,
412
- ...row,
413
- createdAt: existing?.createdAt ?? ts,
414
- updatedAt: ts
415
- }
458
+ const ts = Date.now()
459
+ const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
416
460
  if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
417
-
418
461
  const ctx = { op: 'set', name, row: stored }
419
- if ((await this.runBefore('set', ctx)) === false) return null
420
-
421
- // member/device have bespoke set handlers, only generic collections upsert via add-
422
- const special = ref.verb === 'member' || ref.verb === 'device'
423
- const verb =
424
- ref.kind === COLLECTION && upsert && !special ? `add-${ref.verb}` : `set-${ref.verb}`
425
- await this.write([[verb, ctx.row]])
426
-
427
- const result = { data: ctx.row }
428
- await this.runAfter('set', { ...ctx, result })
429
- return result
462
+ if ((await this._runBefore('set', ctx)) === false) return null
463
+ const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
464
+ await this.write([[`${insert ? 'add' : 'set'}-${ref.verb}`, ctx.row]])
465
+ return ctx
430
466
  }
431
467
 
432
468
  /**
@@ -440,13 +476,11 @@ export class Database extends ReadyResource {
440
476
  this.guard()
441
477
  const ref = this.ref(name)
442
478
  const ctx = { op: 'del', name, id }
443
- if ((await this.runBefore('del', ctx)) === false) return null
444
-
479
+ if ((await this._runBefore('del', ctx)) === false) return null
445
480
  // singles have no id, the dummy one just satisfies the shared del-by-id encoding
446
481
  const payload = ref.kind === SINGLE ? { id: '' } : { id }
447
482
  await this.write([[`del-${ref.verb}`, payload]])
448
-
449
- await this.runAfter('del', ctx)
483
+ await this._runAfter('del', ctx)
450
484
  }
451
485
 
452
486
  /**
@@ -477,16 +511,20 @@ export class Database extends ReadyResource {
477
511
  *
478
512
  * @returns {Promise<{ epoch: number }>}
479
513
  */
480
- async rotate(retried = false) {
481
- return rotate(this, retried)
514
+ async rotate() {
515
+ // queued in tx() the epoch is unobservable, and a batched rekey blurs the epoch
516
+ if (this.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
517
+ return this.rotation.rotate()
482
518
  }
483
519
 
484
- async _onepoch(row) {
485
- return onepoch(this, row)
486
- }
487
-
488
- async _loadEpochs() {
489
- return hydrateEpochs(this)
520
+ // apply-time hook: the log carries ops from a newer app version than this
521
+ // peer understands. Emits `behind` once per version so apps can prompt an
522
+ // upgrade; the marker survives restarts via local core userData
523
+ _onfuture(version) {
524
+ if (this.behind !== null && version <= this.behind) return
525
+ this.behind = version
526
+ this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
527
+ this.emit('behind', version)
490
528
  }
491
529
 
492
530
  /**
@@ -512,9 +550,14 @@ export class Database extends ReadyResource {
512
550
  const run = async () => {
513
551
  const batch = Object.create(this)
514
552
  batch.txQueue = []
515
- const result = await fn(batch)
516
- if (batch.txQueue.length) await this.write(batch.txQueue)
517
- return result
553
+ try {
554
+ const result = await fn(batch)
555
+ if (batch.txQueue.length) await this.write(batch.txQueue)
556
+ return result
557
+ } catch (err) {
558
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
559
+ throw err
560
+ }
518
561
  }
519
562
  const prev = this._txChain || Promise.resolve()
520
563
  // chain past prev's outcome so one failure doesn't wedge later transactions
@@ -557,24 +600,18 @@ export class Database extends ReadyResource {
557
600
  await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
558
601
  }
559
602
 
560
- /**
561
- * Validate ops against the committed view before appending: each op runs in
562
- * a throwaway transaction with host effects stubbed, so a throwing handler
563
- * rejects the write and nothing enters the permanent log. Permission gates
564
- * that `return` are not rejections — apply stays the authority at
565
- * linearization time.
566
- *
567
- * @param {Uint8Array[]} encoded
568
- * @returns {Promise<boolean>} whether the ops change anything
569
- */
603
+ // every op runs in a throwaway transaction with host effects stubbed, so a
604
+ // throwing handler rejects the write and nothing enters the permanent log.
605
+ // Permission gates that `return` are not rejections, apply stays the
606
+ // authority at linearization time. Resolves whether the ops change anything
570
607
  async _dryRun(encoded) {
571
608
  const tx = this.view.transaction()
572
609
  const host = { addWriter: async () => {}, removeWriter: async () => {} }
573
610
  try {
574
611
  for (const value of encoded) {
575
612
  await this.dispatcher.dispatcher.dispatch(value, {
576
- view: tx,
577
613
  host,
614
+ view: tx,
578
615
  key: this.writerKey,
579
616
  dbKey: this.key,
580
617
  dryRun: true
@@ -612,71 +649,49 @@ export class Database extends ReadyResource {
612
649
  return { data: await this.view.get(col, { id: query }) }
613
650
  }
614
651
 
615
- const idx = this.matchIndex(name, query)
616
- if (idx) {
617
- const rows = await this.view.find(idx.path, idx.range).toArray()
618
- const data = paginate(rows, query)
619
- return { data, total: rows.length, size: data.length }
620
- }
652
+ const { path, range, rest, sorted } = this._plan(name, query)
653
+ const rows = await this.view.find(path, range).toArray()
654
+ if (!sorted) rows.sort(byIndex)
655
+ const data = filter(rows, rest)
656
+ return { data, total: await this._total(path, range, rows, query), size: data.length }
657
+ }
621
658
 
622
- // read off the implicit `index` order index, touching ≤ limit rows. total goes lazy.
623
- if (this.refs[name]?.orderIndex && pushable(query) && (await this._orderReady(name, col))) {
624
- const rows = await this.view
625
- .find(`@${this.ns}/${name}-index`, {
626
- reverse: query?.reverse === true,
627
- limit: query?.limit
628
- })
629
- .toArray()
630
- const total = await this._total(col, query, rows)
631
- return { data: rows, total, size: rows.length }
659
+ // one hyperdb read per query: the index that serves it, the bounds and the
660
+ // window pushed down when nothing else narrows the read, the rest in memory
661
+ _plan(name, query = {}) {
662
+ const ref = this.refs[name]
663
+ const col = `@${this.ns}/${name}`
664
+ const rest = { ...query }
665
+ const eq = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
666
+ const bounded = [...RANGE].some((k) => query[k] !== undefined)
667
+ const idx = eq.length ? matchIndex(ref?.indexes, eq) : null
668
+ if (idx) {
669
+ const point = {}
670
+ for (const f of eq) point[f] = query[f]
671
+ const range = { gte: point, lte: point }
672
+ if (!query.search && !bounded) pushWindow(range, rest)
673
+ return { path: `${col}-${idx}`, range, rest, sorted: true }
632
674
  }
633
-
634
- if (this.refs[name]?.orderIndex && pushableRange(query)) {
675
+ if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
676
+ if (bounded) {
635
677
  const range = {}
636
- for (const k of ['gt', 'gte', 'lt', 'lte']) {
637
- if (query[k] !== undefined) range[k] = { id: query[k] }
638
- }
639
- const rows = await this.view.find(col, range).toArray()
640
- rows.sort((a, b) => (a.index ?? 0) - (b.index ?? 0))
641
- if (query.reverse) rows.reverse()
642
- const data = query.limit !== undefined ? rows.slice(0, query.limit) : rows
643
- return { data, total: rows.length, size: data.length }
678
+ for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
679
+ return { path: col, range, rest, sorted: false }
644
680
  }
645
-
646
- const all = await this.view.find(col, {}).toArray()
647
- all.sort((a, b) => (a.index ?? 0) - (b.index ?? 0))
648
- const total = all.length
649
- const data = paginate(all, query)
650
- return { data, total, size: data.length }
651
- }
652
-
653
- // hyperdb never backfills an index added after rows were written, so an upgraded
654
- // store would drop legacy rows. Verify completeness once per open, then trust it.
655
- async _orderReady(name, col) {
656
- if (!this._orderOk) this._orderOk = new Map()
657
- let ok = this._orderOk.get(name)
658
- if (ok === undefined) {
659
- const [rows, indexed] = await Promise.all([
660
- this.view.find(col, {}).toArray(),
661
- this.view.find(`@${this.ns}/${name}-index`, {}).toArray()
662
- ])
663
- ok = rows.length === indexed.length
664
- this._orderOk.set(name, ok)
665
- if (!ok) {
666
- this._onerror(
667
- CeroError.INVALID(
668
- `order index for '${name}' is incomplete (store predates it) — reads fall back to full scans; recreate the store to accelerate`
669
- )
670
- )
671
- }
681
+ if (ref?.orderIndex) {
682
+ const range = {}
683
+ pushWindow(range, rest)
684
+ return { path: `${col}-index`, range, rest, sorted: true }
672
685
  }
673
- return ok
686
+ return { path: col, range: {}, rest, sorted: false }
674
687
  }
675
688
 
676
- async _total(col, query, rows) {
677
- if (query?.total) return (await this.view.find(col, {}).toArray()).length
678
- if (query?.limit === undefined || rows.length < query.limit) return rows.length
679
- return null
689
+ // rows before the in-memory pass; unknown once a pushed-down limit filled the page
690
+ async _total(path, range, rows, query) {
691
+ if (range.limit === undefined || rows.length < range.limit) return rows.length
692
+ if (!query?.total) return null
693
+ const { limit, reverse, ...bounds } = range
694
+ return (await this.view.find(path, bounds).toArray()).length
680
695
  }
681
696
 
682
697
  /**
@@ -688,9 +703,9 @@ export class Database extends ReadyResource {
688
703
  */
689
704
  async count(name, query) {
690
705
  this.guard()
691
- const ref = this.ref(name)
692
- const all = await this.view.find(this.col(ref), {}).toArray()
693
- return { data: paginate(all, query).length }
706
+ this.ref(name)
707
+ const { path, range, rest } = this._plan(name, query)
708
+ return { data: filter(await this.view.find(path, range).toArray(), rest).length }
694
709
  }
695
710
 
696
711
  /**
@@ -726,23 +741,45 @@ export class Database extends ReadyResource {
726
741
  if (!this.view.definition.resolveCollection(col)) {
727
742
  throw CeroError.UNKNOWN('collection', name)
728
743
  }
729
- const filter = { ...query }
730
- delete filter.limit
731
- delete filter.reverse
732
- delete filter.total
733
- const matches = (row) => paginate([row], filter).length > 0
744
+ const { limit, reverse, total, ...rest } = query
745
+ const matches = (row) => filter([row], rest).length > 0
734
746
  return makeChanges(this, name, col, matches)
735
747
  }
736
748
 
737
749
  /**
738
- * First-run bootstrap: create the device writer, save it, and swap into it.
750
+ * Provision this device. Its writer core was minted when the database opened
751
+ * and this device is its only author, ever. A first device records itself as
752
+ * a writer and a device in one write. A recovering device waits for the other
753
+ * devices' state, admits itself with the same master-signed add-writer
754
+ * appended optimistically, then records the device.
739
755
  *
740
- * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean }} [opts]
756
+ * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean, timeout?: number }} [opts]
741
757
  * @returns {Promise<{ id: Uint8Array, writer: import('../identity/index.js').KeyPair }>}
742
758
  */
743
- bootstrap(opts) {
759
+ async bootstrap({ name, isMobile, recovering = false, timeout = 30000 } = {}) {
744
760
  this.guard()
745
- return bootstrap(this, opts)
761
+ const ts = Date.now()
762
+ const writer = this._admission(this.writerKey, ts)
763
+ const device = [
764
+ 'set-device',
765
+ {
766
+ id: hid.encode(this.writerKey),
767
+ name: name || null,
768
+ isMobile: isMobile === true,
769
+ createdAt: ts,
770
+ updatedAt: ts
771
+ }
772
+ ]
773
+ if (!recovering) {
774
+ await this.write([['add-writer', writer], device])
775
+ } else {
776
+ await this._backfilled(timeout)
777
+ await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
778
+ timeout
779
+ })
780
+ await this.write([device])
781
+ }
782
+ return { id: this.writerKey, writer: this.keyPair }
746
783
  }
747
784
 
748
785
  /**
@@ -753,12 +790,16 @@ export class Database extends ReadyResource {
753
790
  * @returns {Promise<void>}
754
791
  */
755
792
  async claim() {
756
- return claim(this)
757
- }
758
-
759
- /** The claim-writer op for this device, signed by the member identity. */
760
- claimOp() {
761
- return claimOp(this)
793
+ this.guard()
794
+ if (this.bee.writable) return
795
+ const writer = this.writerKey
796
+ const op = this.spec.dispatch.encode(`@${this.ns}/claim-writer`, {
797
+ identity: this.identity.publicKey,
798
+ writer,
799
+ sig: this.identity.sign(ownership(this.key, writer)),
800
+ ts: Date.now()
801
+ })
802
+ await this._optimistic(op)
762
803
  }
763
804
 
764
805
  /**
@@ -767,8 +808,24 @@ export class Database extends ReadyResource {
767
808
  * @param {{ timeout?: number }} [opts]
768
809
  * @returns {Promise<void>}
769
810
  */
770
- async whenWritable(opts) {
771
- return whenWritable(this, opts)
811
+ async whenWritable({ timeout = 30000 } = {}) {
812
+ this.guard()
813
+ const { bee } = this
814
+ if (bee.writable) return
815
+ return new Promise((resolve, reject) => {
816
+ const done = (err) => {
817
+ clearTimeout(timer)
818
+ bee.off('writable', done)
819
+ this.off('close', onclose)
820
+ if (err) reject(err)
821
+ else resolve()
822
+ }
823
+ const onclose = () => done(CeroError.CLOSED('Database'))
824
+ const timer =
825
+ timeout > 0 ? setTimeout(() => done(CeroError.TIMED_OUT('whenWritable')), timeout) : null
826
+ bee.once('writable', done)
827
+ this.once('close', onclose)
828
+ })
772
829
  }
773
830
 
774
831
  /**
@@ -778,7 +835,7 @@ export class Database extends ReadyResource {
778
835
  * @returns {Promise<void>}
779
836
  */
780
837
  async addWriter(publicKey) {
781
- return addWriter(this, publicKey)
838
+ return this._admit('add-writer', 'addWriter', publicKey)
782
839
  }
783
840
 
784
841
  /**
@@ -788,7 +845,34 @@ export class Database extends ReadyResource {
788
845
  * @returns {Promise<void>}
789
846
  */
790
847
  async removeWriter(publicKey) {
791
- return removeWriter(this, publicKey)
848
+ return this._admit('del-writer', 'removeWriter', publicKey)
849
+ }
850
+
851
+ // an append by a core not yet admitted: apply verifies the master signature
852
+ // and admits it, then the bee turns writable
853
+ async _optimistic(op, opts) {
854
+ await this.bee.append(wrap(this.version, op), { optimistic: true })
855
+ await this.bee.update()
856
+ if (!this.bee.writable) await this.whenWritable(opts)
857
+ }
858
+
859
+ // the genesis device row is the first thing every database writes, so any
860
+ // device row means the other devices' state has replicated and applied
861
+ async _backfilled(timeout) {
862
+ const deadline = Date.now() + timeout
863
+ while (Date.now() < deadline) {
864
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
865
+ if ((await this.get('devices')).data.length > 0) return
866
+ await this.bee.update()
867
+ await new Promise((resolve) => setTimeout(resolve, 50))
868
+ }
869
+ throw CeroError.TIMED_OUT('recovery — no peer replicated')
870
+ }
871
+
872
+ // the add-writer row for `writer`, appended by this device and signed by the identity
873
+ _admission(writer, ts = Date.now()) {
874
+ const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
875
+ return { master: this.identity.publicKey, writer, sig, ts }
792
876
  }
793
877
 
794
878
  /**
@@ -838,101 +922,69 @@ export class Database extends ReadyResource {
838
922
  }
839
923
  }
840
924
 
841
- /**
842
- * Find a secondary index whose fields exactly match the query's equality keys.
843
- *
844
- * @param {string} name
845
- * @param {Query} [query]
846
- * @returns {{ path: string, range: { gte: object, lte: object } } | null}
847
- */
848
- matchIndex(name, query) {
849
- const indexes = this.refs[name]?.indexes
850
- if (!indexes || !query) return null
851
- const fields = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
852
- if (fields.length === 0) return null
853
- for (const [idx, idxFields] of Object.entries(indexes)) {
854
- if (idxFields.length === fields.length && idxFields.every((f) => fields.includes(f))) {
855
- const point = {}
856
- for (const f of idxFields) point[f] = query[f]
857
- // point lookup only, paginate applies search/range/reverse/limit
858
- return { path: `@${this.ns}/${name}-${idx}`, range: { gte: point, lte: point } }
859
- }
860
- }
861
- return null
862
- }
863
-
864
- async _write(verb, hook, publicKey) {
925
+ async _admit(verb, hook, publicKey) {
865
926
  this.guard()
866
- if (!b4a.isBuffer(publicKey)) {
867
- throw CeroError.INVALID('publicKey must be a buffer')
868
- }
927
+ if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
869
928
  const ctx = { op: hook, publicKey }
870
- if ((await this.runBefore(hook, ctx)) === false) return
871
- const writerKey = Hypercore.key({
872
- version: this.store.manifestVersion,
873
- signers: [{ publicKey }]
874
- })
875
- const sig = this.identity.sign(addWriterPayload(this.key, writerKey, this.writerKey))
876
- await this.write([
877
- [verb, { master: this.identity.publicKey, writer: writerKey, sig, ts: Date.now() }]
878
- ])
879
- await this.runAfter(hook, ctx)
929
+ if ((await this._runBefore(hook, ctx)) === false) return
930
+ const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
931
+ await this.write([[verb, this._admission(writer)]])
932
+ await this._runAfter(hook, ctx)
880
933
  }
881
934
  }
882
935
 
883
936
  // a trust decision reads a historic checkout whose blocks may not be servable yet,
884
937
  // and an unbounded read there wedges autobee's drain forever. null means untrusted.
885
- const bounded = (promise, ms = 2000) =>
886
- Promise.race([
938
+ function bounded(promise, ms = 2000) {
939
+ return Promise.race([
887
940
  promise.then((v) => ({ v })),
888
941
  new Promise((resolve) => setTimeout(() => resolve(null), ms))
889
942
  ])
943
+ }
944
+
945
+ function addHook(map, op, fn) {
946
+ if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
947
+ let arr = map.get(op)
948
+ if (!arr) map.set(op, (arr = []))
949
+ arr.push(fn)
950
+ return () => {
951
+ const i = arr.indexOf(fn)
952
+ if (i >= 0) arr.splice(i, 1)
953
+ }
954
+ }
955
+
956
+ // verb and name both resolve to the ref, ops are named by verb
957
+ function verbMap(refs) {
958
+ const map = new Map()
959
+ for (const [name, info] of Object.entries(refs)) {
960
+ map.set(info.verb || name, name)
961
+ map.set(name, name)
962
+ }
963
+ return map
964
+ }
965
+
966
+ // member and device have their own set handlers, every other collection upserts via add-
967
+ const BESPOKE = new Set(['member', 'device'])
890
968
 
891
969
  // fields the write path stamps itself, always allowed
892
970
  const SYSTEM_FIELDS = new Set(['id', 'memberId', 'index', 'createdAt', 'updatedAt'])
893
971
 
894
- const valueEq = (a, b) => {
895
- if (a instanceof Uint8Array && b instanceof Uint8Array) return b4a.equals(a, b)
896
- return a === b
897
- }
972
+ const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
898
973
 
899
- // reverse/limit (+ total) only, safe to serve straight off the order index
900
- function pushable(query) {
901
- if (!query) return true
902
- return Object.keys(query).every((k) => k === 'reverse' || k === 'limit' || k === 'total')
903
- }
974
+ const byIndex = (a, b) => (a.index ?? 0) - (b.index ?? 0)
904
975
 
905
- // an id-range with no equality/search, the range pushes down, order stays in memory
906
- function pushableRange(query) {
907
- if (!query) return false
908
- const keys = Object.keys(query)
909
- if (!keys.some((k) => k === 'gt' || k === 'gte' || k === 'lt' || k === 'lte')) return false
910
- return keys.every(
911
- (k) =>
912
- k === 'gt' ||
913
- k === 'gte' ||
914
- k === 'lt' ||
915
- k === 'lte' ||
916
- k === 'reverse' ||
917
- k === 'limit' ||
918
- k === 'total'
919
- )
976
+ // the index whose fields are exactly the query's equality keys
977
+ function matchIndex(indexes, fields) {
978
+ for (const [name, keys] of Object.entries(indexes || {})) {
979
+ if (keys.length === fields.length && keys.every((f) => fields.includes(f))) return name
980
+ }
981
+ return null
920
982
  }
921
983
 
922
- function paginate(rows, query) {
923
- if (!query) return rows
924
- let out = rows
925
- // the secondary index is an optimization, not a correctness gate
926
- for (const key of Object.keys(query)) {
927
- if (QUERY_RESERVED.has(key)) continue
928
- out = out.filter((r) => valueEq(r[key], query[key]))
929
- }
930
- if (query.gt !== undefined) out = out.filter((r) => r.id > query.gt)
931
- if (query.gte !== undefined) out = out.filter((r) => r.id >= query.gte)
932
- if (query.lt !== undefined) out = out.filter((r) => r.id < query.lt)
933
- if (query.lte !== undefined) out = out.filter((r) => r.id <= query.lte)
934
- if (query.search) out = out.filter((r) => searchHit(r, query.search, query.fields))
935
- if (query.reverse) out = [...out].reverse()
936
- if (query.limit !== undefined) out = out.slice(0, query.limit)
937
- return out
984
+ // reverse and limit served by hyperdb, so the in-memory pass must not repeat them
985
+ function pushWindow(range, rest) {
986
+ if (rest.reverse === true) range.reverse = true
987
+ if (rest.limit !== undefined) range.limit = rest.limit
988
+ delete rest.reverse
989
+ delete rest.limit
938
990
  }