@cero-base/core 1.18.2 → 2.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/README.md +5 -6
  2. package/package.json +14 -11
  3. package/src/blobs/index.js +17 -17
  4. package/src/blobs/server.js +0 -2
  5. package/src/database/changes.js +34 -60
  6. package/src/database/dispatch.js +156 -245
  7. package/src/database/encryption.js +22 -52
  8. package/src/database/envelope.js +1 -3
  9. package/src/database/index.js +514 -513
  10. package/src/database/rotation.js +191 -193
  11. package/src/identity/index.js +8 -12
  12. package/src/index.js +5 -9
  13. package/src/lib/constants.js +3 -12
  14. package/src/lib/errors.js +6 -10
  15. package/src/lib/schema.js +2 -5
  16. package/src/lib/utils.js +55 -38
  17. package/src/network/index.js +138 -166
  18. package/src/pairing/candidate.js +123 -0
  19. package/src/pairing/index.js +36 -267
  20. package/src/pairing/invite.js +3 -4
  21. package/src/pairing/request.js +96 -0
  22. package/src/rpc/index.js +4 -14
  23. package/src/rpc/peer.js +3 -7
  24. package/src/storage/index.js +36 -49
  25. package/types/blobs/codec.d.ts +8 -8
  26. package/types/blobs/index.d.ts +38 -37
  27. package/types/blobs/server.d.ts +8 -10
  28. package/types/database/changes.d.ts +3 -8
  29. package/types/database/dispatch.d.ts +28 -25
  30. package/types/database/encryption.d.ts +22 -30
  31. package/types/database/envelope.d.ts +2 -2
  32. package/types/database/index.d.ts +196 -221
  33. package/types/database/rotation.d.ts +47 -30
  34. package/types/identity/index.d.ts +83 -87
  35. package/types/index.d.ts +42 -55
  36. package/types/lib/constants.d.ts +34 -38
  37. package/types/lib/errors.d.ts +16 -20
  38. package/types/lib/schema.d.ts +49 -42
  39. package/types/lib/spec/index.d.ts +29 -55
  40. package/types/lib/utils.d.ts +26 -20
  41. package/types/network/discovery.d.ts +7 -7
  42. package/types/network/index.d.ts +64 -72
  43. package/types/pairing/candidate.d.ts +36 -0
  44. package/types/pairing/index.d.ts +91 -151
  45. package/types/pairing/invite.d.ts +91 -91
  46. package/types/pairing/request.d.ts +133 -0
  47. package/types/rpc/client.d.ts +2 -2
  48. package/types/rpc/index.d.ts +30 -33
  49. package/types/rpc/peer.d.ts +11 -11
  50. package/types/rpc/server.d.ts +2 -2
  51. package/types/storage/index.d.ts +70 -71
  52. package/src/database/bootstrap.js +0 -133
  53. package/src/database/hooks.js +0 -112
  54. package/src/database/membership.js +0 -67
  55. package/types/database/bootstrap.d.ts +0 -20
  56. package/types/database/hooks.d.ts +0 -8
  57. 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
@@ -50,10 +48,7 @@ import { makeDispatcher } from './dispatch.js'
50
48
  */
51
49
 
52
50
  /**
53
- * Multi-writer database built on Autobee + HyperDB. Persists rows via a
54
- * hyperdispatch-encoded log and exposes a `put/get/...` surface mirroring
55
- * `Storage`, plus membership ops (claim/addWriter/removeWriter) for the
56
- * shared writer set.
51
+ * Multi-writer database built on Autobee + HyperDB.
57
52
  */
58
53
  export class Database extends ReadyResource {
59
54
  /** @param {Partial<DatabaseOpts>} [opts] */
@@ -80,177 +75,102 @@ export class Database extends ReadyResource {
80
75
  this.encryptionKey = opts.encryptionKey || opts.identity.encryptionKey || null
81
76
  this.keyring = new Keyring()
82
77
  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
78
+ this.rotation = new Rotation(this)
89
79
  this.key = opts.key || null
90
80
  this.passive = opts.passive === true
91
- this.keyPair = opts.keyPair || {
92
- publicKey: opts.identity.publicKey,
93
- secretKey: opts.identity.secretKey
81
+ this.keyPair = opts.keyPair || Identity.randomKeyPair()
82
+ if (b4a.equals(this.keyPair.publicKey, this.identity.publicKey)) {
83
+ throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
94
84
  }
95
85
 
96
86
  this._onerror = opts.onerror || safetyCatch
97
87
  this.bee = null
98
88
  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
89
+ this._discovery = null
90
+ this._txChain = null
91
+
92
+ this._before = new Map()
93
+ this._after = new Map()
94
+ this._updaters = new Map()
95
+ this._observers = new Set()
96
+ this._verbs = verbMap(this.refs)
105
97
  this._touched = new Set()
98
+ this._seq = 0
106
99
  this.txQueue = null
107
100
  }
108
101
 
109
- async _open() {
110
- await this.store.ready()
111
- if (this.network) await this.network.ready()
102
+ /** @returns {Uint8Array | null} discovery key of the underlying bee */
103
+ get discoveryKey() {
104
+ return this.bee?.discoveryKey || null
105
+ }
112
106
 
113
- await this.openBee()
107
+ /** @returns {Uint8Array | null} this device's local writer key */
108
+ get writerKey() {
109
+ return this.bee?.local?.key || null
114
110
  }
115
111
 
116
- async _close() {
117
- if (this._healTimer) {
118
- clearTimeout(this._healTimer)
119
- this._healTimer = null
120
- }
121
- if (this._discovery) {
122
- // unannounce in the background, the DHT round-trip would block close for seconds
123
- this._discovery.destroy().catch(safetyCatch)
124
- this._discovery = null
125
- }
126
- if (this.bee) {
127
- // detach first, else the closed bee replicates into every new connection
128
- if (this.network) this.network.detach(this.bee)
129
- await this.bee.close()
130
- this.bee = null
131
- }
112
+ /** @returns {boolean} whether the bee accepts local writes */
113
+ get writable() {
114
+ return this.bee?.writable === true
132
115
  }
133
116
 
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
137
- const local = this.store.namespace(this.namespace).get({
138
- keyPair: this.keyPair,
139
- manifest: {
140
- version: this.store.manifestVersion,
141
- signers: [{ publicKey: this.keyPair.publicKey }]
142
- },
143
- active: false
144
- })
145
- await local.ready()
146
- await loadEpochs(this.keyring, local)
147
- await local.close()
117
+ /** @returns {number} number of ops in the local writer */
118
+ get length() {
119
+ return this.bee?.local?.length || 0
120
+ }
148
121
 
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
- )
122
+ /** @returns {object | null} the materialized HyperDB view */
123
+ get view() {
124
+ return this.bee?.view || null
125
+ }
157
126
 
158
- const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
159
- keyPair: this.keyPair,
160
- encryptionKey: this.encryptionKey,
161
- keyring: this.keyring,
162
- optimistic: true,
163
- wakeup: this.network?.wakeup || undefined,
164
- 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
- }
127
+ async _open() {
128
+ await this.store.ready()
129
+ if (this.network) await this.network.ready()
130
+ await this._preload()
131
+ this.dispatcher = makeDispatcher({
132
+ spec: this.spec,
133
+ ns: this.ns,
134
+ routes: this.routes,
135
+ onerror: this._onerror,
136
+ key: () => this.key,
137
+ onepoch: (row) => this.rotation.learn(row)
207
138
  })
208
139
 
209
- // swarm BEFORE boot so the boot has peers to pull from, not a cold open
210
140
  const known = !!this.key
211
- if (this.network && known) this._joinSwarm(bee, crypto.discoveryKey(this.key))
212
-
213
- await bee.ready()
214
- // apply-time hooks (_onepoch, _onfuture) must never see this.bee null mid-drain
215
- this.bee = bee
216
- this.key = bee.key
217
- await bee.update()
218
-
219
- const behind = await bee.local.getUserData('cero/behind')
220
- this.behind = behind ? c.decode(c.uint, behind) : null
221
-
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
231
- }
141
+ await this._boot()
142
+ const replayed = await this._replay()
143
+ if (replayed) await this._boot()
232
144
 
233
145
  // before replication can deliver blocks at epochs we haven't learned yet
234
- await this._loadEpochs()
146
+ await this.rotation.hydrate()
235
147
 
236
- bee.on('writable', () => this.emit('writable'))
148
+ // REMOVE-capable devices re-key when the epoch drifts from the member set
149
+ this.on('update', () => this.rotation.heal())
150
+ this.bee.on('writable', () => this.emit('writable'))
237
151
  // falling edge: apps freeze the UI the moment access ends
238
- bee.on('unwritable', () => this.emit('unwritable'))
152
+ this.bee.on('unwritable', () => this.emit('unwritable'))
239
153
  // without a listener autobee escalates apply/view errors to a process crash
240
- bee.on('error', this._onerror)
154
+ this.bee.on('error', this._onerror)
241
155
 
242
156
  // a fresh db has no key until boot mints it
243
- if (this.network && !known) this._joinSwarm(bee, bee.discoveryKey)
157
+ if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
158
+ if (replayed) this.emit('rebuild')
244
159
  }
245
160
 
246
- // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
247
- _joinSwarm(bee, discoveryKey) {
248
- this.network.attach(bee)
249
- const prev = this._discovery
250
- this._discovery = this.network.join(discoveryKey, {
251
- mode: this.passive ? PASSIVE : ACTIVE
252
- })
253
- if (prev) prev.destroy().catch(safetyCatch)
161
+ async _close() {
162
+ this.rotation.close()
163
+ if (this._discovery) {
164
+ // unannounce in the background, the DHT round-trip would block close for seconds
165
+ this._discovery.destroy().catch(safetyCatch)
166
+ this._discovery = null
167
+ }
168
+ if (this.bee) {
169
+ // detach first, else the closed bee replicates into every new connection
170
+ if (this.network) this.network.detach(this.bee)
171
+ await this.bee.close()
172
+ this.bee = null
173
+ }
254
174
  }
255
175
 
256
176
  /**
@@ -265,31 +185,6 @@ export class Database extends ReadyResource {
265
185
  await (active ? this._discovery.activate() : this._discovery.deactivate())
266
186
  }
267
187
 
268
- /** @returns {Uint8Array | null} discovery key of the underlying bee */
269
- get discoveryKey() {
270
- return this.bee?.discoveryKey || null
271
- }
272
-
273
- /** @returns {Uint8Array | null} this device's local writer key */
274
- get writerKey() {
275
- return this.bee?.local?.key || null
276
- }
277
-
278
- /** @returns {boolean} whether the bee accepts local writes */
279
- get writable() {
280
- return this.bee?.writable === true
281
- }
282
-
283
- /** @returns {number} number of ops in the local writer */
284
- get length() {
285
- return this.bee?.local?.length || 0
286
- }
287
-
288
- /** @returns {object | null} the materialized HyperDB view */
289
- get view() {
290
- return this.bee?.view || null
291
- }
292
-
293
188
  /**
294
189
  * Register a pre-op hook. Returning `false` from `fn` aborts the op.
295
190
  *
@@ -298,7 +193,7 @@ export class Database extends ReadyResource {
298
193
  * @returns {() => void} disposer
299
194
  */
300
195
  before(op, fn) {
301
- return before(this, op, fn)
196
+ return addHook(this._before, op, fn)
302
197
  }
303
198
 
304
199
  /**
@@ -309,7 +204,7 @@ export class Database extends ReadyResource {
309
204
  * @returns {() => void} disposer
310
205
  */
311
206
  after(op, fn) {
312
- return after(this, op, fn)
207
+ return addHook(this._after, op, fn)
313
208
  }
314
209
 
315
210
  /**
@@ -321,42 +216,20 @@ export class Database extends ReadyResource {
321
216
  * @returns {() => void} disposer
322
217
  */
323
218
  onUpdate(fn, scope) {
324
- return onUpdate(this, fn, scope)
219
+ this._updaters.set(fn, scope || null)
220
+ return () => this._updaters.delete(fn)
325
221
  }
326
222
 
327
223
  /**
328
- * Observe every applied op — local AND replicated (apply processes the merged
329
- * log). The callback receives `{ op, name, row, writerKey, seq }` and runs
330
- * synchronously, so it must be cheap and non-blocking (enqueue and return).
331
- * Gated: zero cost when no subscriber is registered. Returns a disposer.
224
+ * Observe every applied op — local AND replicated (apply processes the merged log).
332
225
  *
333
226
  * @param {(event: { op: string, name: string, row: any, writerKey: any, seq: number }) => void} fn
334
227
  * @returns {() => void} disposer
335
228
  */
336
229
  onApply(fn) {
337
- return onApply(this, fn)
338
- }
339
-
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
- }
350
-
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)
230
+ if (typeof fn !== 'function') return () => {}
231
+ this._observers.add(fn)
232
+ return () => this._observers.delete(fn)
360
233
  }
361
234
 
362
235
  /**
@@ -367,66 +240,22 @@ export class Database extends ReadyResource {
367
240
  * @returns {Promise<SingleResult | null>}
368
241
  */
369
242
  async put(name, row) {
370
- this.guard()
371
- const ref = this.ref(name)
372
- this._checkFields(name, row)
373
- const id = row.id || genId()
243
+ const ref = this._prepare(name, row)
374
244
  const ts = Date.now()
375
- const stored = { createdAt: ts, updatedAt: ts, ...row, id }
376
-
377
- const ctx = { op: 'put', name, row: stored }
378
- if ((await this.runBefore('put', ctx)) === false) return null
379
-
380
- await this.write([[`add-${ref.verb}`, ctx.row]])
381
-
382
- const result = { data: ctx.row }
383
- await this.runAfter('put', { ...ctx, result })
384
- return result
245
+ const stored = { createdAt: ts, updatedAt: ts, ...row, id: row.id || genId() }
246
+ return this._done('put', await this._append('put', name, stored, `add-${ref.verb}`))
385
247
  }
386
248
 
387
249
  /**
388
- * Upsert by merging with the existing row, preserving `createdAt`. Pass
389
- * `{ upsert: false }` to update-only — a missing row is left untouched
390
- * (checked atomically in the dispatch, so it never resurrects a deleted row).
250
+ * Upsert by merging with the existing row, preserving `createdAt`.
391
251
  *
392
252
  * @param {string} name
393
253
  * @param {Record<string, any>} row
394
254
  * @param {{ upsert?: boolean }} [opts]
395
255
  * @returns {Promise<SingleResult | null>}
396
256
  */
397
- async set(name, row, { upsert = true } = {}) {
398
- this.guard()
399
- const ref = this.ref(name)
400
- 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
409
- if (!upsert && !existing) return null
410
- const stored = {
411
- ...existing,
412
- ...row,
413
- createdAt: existing?.createdAt ?? ts,
414
- updatedAt: ts
415
- }
416
- if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
417
-
418
- 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
257
+ async set(name, row, opts) {
258
+ return this._done('set', await this.tx((tx) => tx._merge(name, row, opts)))
430
259
  }
431
260
 
432
261
  /**
@@ -440,13 +269,11 @@ export class Database extends ReadyResource {
440
269
  this.guard()
441
270
  const ref = this.ref(name)
442
271
  const ctx = { op: 'del', name, id }
443
- if ((await this.runBefore('del', ctx)) === false) return null
444
-
272
+ if ((await this._runBefore('del', ctx)) === false) return null
445
273
  // singles have no id, the dummy one just satisfies the shared del-by-id encoding
446
274
  const payload = ref.kind === SINGLE ? { id: '' } : { id }
447
275
  await this.write([[`del-${ref.verb}`, payload]])
448
-
449
- await this.runAfter('del', ctx)
276
+ await this._runAfter('del', ctx)
450
277
  }
451
278
 
452
279
  /**
@@ -468,35 +295,20 @@ export class Database extends ReadyResource {
468
295
  }
469
296
 
470
297
  /**
471
- * Rotate the encryption epoch: generate a fresh 32-byte secret, seal it to
472
- * every current member's identity key, and announce it through the log.
473
- * The announcement is appended under the current epoch (so every member —
474
- * even one offline for several rotations — can walk the chain forward),
475
- * and blocks written after it use the new one. Members absent from the
476
- * envelope set (removed before the rotation) never learn the new key.
298
+ * Rotate the encryption epoch: generate a fresh 32-byte secret, seal it to every current
299
+ * member's identity key, and announce it through the log.
477
300
  *
478
301
  * @returns {Promise<{ epoch: number }>}
479
302
  */
480
- async rotate(retried = false) {
481
- return rotate(this, retried)
482
- }
483
-
484
- async _onepoch(row) {
485
- return onepoch(this, row)
486
- }
487
-
488
- async _loadEpochs() {
489
- return hydrateEpochs(this)
303
+ async rotate() {
304
+ // queued in tx() the epoch is unobservable, and a batched rekey blurs the epoch
305
+ if (this.txQueue) throw CeroError.INVALID('rotate() cannot run inside tx()')
306
+ return this.rotation.rotate()
490
307
  }
491
308
 
492
309
  /**
493
- * Batch every write made through the transaction handle passed to `fn`
494
- * into a single autobee append. The handle is this database with its own
495
- * write queue — same surface (`put`/`set`/`del`/`call`), but writes buffer
496
- * until `fn` returns, and are discarded if it throws. Writes made on the
497
- * database itself meanwhile append normally: an unrelated concurrent write
498
- * can never be swallowed into (and rolled back with) a transaction.
499
- * Nested `tx()` on the handle joins the same batch.
310
+ * Batch every write made through the transaction handle passed to `fn` into a single
311
+ * autobee append.
500
312
  *
501
313
  * @template T
502
314
  * @param {(tx: Database) => Promise<T> | T} fn
@@ -512,9 +324,14 @@ export class Database extends ReadyResource {
512
324
  const run = async () => {
513
325
  const batch = Object.create(this)
514
326
  batch.txQueue = []
515
- const result = await fn(batch)
516
- if (batch.txQueue.length) await this.write(batch.txQueue)
517
- return result
327
+ try {
328
+ const result = await fn(batch)
329
+ if (batch.txQueue.length) await this.write(batch.txQueue)
330
+ return result
331
+ } catch (err) {
332
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
333
+ throw err
334
+ }
518
335
  }
519
336
  const prev = this._txChain || Promise.resolve()
520
337
  // chain past prev's outcome so one failure doesn't wedge later transactions
@@ -534,61 +351,21 @@ export class Database extends ReadyResource {
534
351
  for (const op of ops) this.txQueue.push(op)
535
352
  return
536
353
  }
537
- // between `closing` and a null `bee` sits a torn-down bee behind a truthy flag
538
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
354
+ this.guard()
539
355
  if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
540
356
  const encoded = ops.map(([op, payload]) =>
541
357
  this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
542
358
  )
543
- // the dry-run rejects what apply would refuse, and an op touching nothing never
544
- // reaches the log. An action ships anyway: it lives in routes, not in rows.
359
+ // the dry run refuses what apply would; a no-op never reaches the log, an action always does
545
360
  const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
546
- let changes
547
361
  try {
548
- changes = await this._dryRun(encoded)
362
+ if (!(await this._dryRun(encoded)) && !action) return
363
+ const wrapped = encoded.map((value) => wrap(this.version, value))
364
+ await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
549
365
  } catch (err) {
550
366
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
551
367
  throw err
552
368
  }
553
- // the dry-run awaits, close can start underneath it
554
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
555
- if (!changes && !action) return
556
- const wrapped = encoded.map((value) => wrap(this.version, value))
557
- await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
558
- }
559
-
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
- */
570
- async _dryRun(encoded) {
571
- const tx = this.view.transaction()
572
- const host = { addWriter: async () => {}, removeWriter: async () => {} }
573
- try {
574
- for (const value of encoded) {
575
- await this.dispatcher.dispatcher.dispatch(value, {
576
- view: tx,
577
- host,
578
- key: this.writerKey,
579
- dbKey: this.key,
580
- dryRun: true
581
- })
582
- }
583
- return tx.updated()
584
- } finally {
585
- // a failing close must not mask the handler's own rejection
586
- try {
587
- await tx.close()
588
- } catch (err) {
589
- safetyCatch(err)
590
- }
591
- }
592
369
  }
593
370
 
594
371
  /**
@@ -612,71 +389,11 @@ export class Database extends ReadyResource {
612
389
  return { data: await this.view.get(col, { id: query }) }
613
390
  }
614
391
 
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
- }
621
-
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 }
632
- }
633
-
634
- if (this.refs[name]?.orderIndex && pushableRange(query)) {
635
- 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 }
644
- }
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
- }
672
- }
673
- return ok
674
- }
675
-
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
392
+ const { path, range, rest, sorted } = this._plan(name, query)
393
+ const rows = await this.view.find(path, range).toArray()
394
+ if (!sorted) rows.sort(byIndex)
395
+ const data = filter(rows, rest)
396
+ return { data, total: await this._total(path, range, rows, query), size: data.length }
680
397
  }
681
398
 
682
399
  /**
@@ -688,9 +405,9 @@ export class Database extends ReadyResource {
688
405
  */
689
406
  async count(name, query) {
690
407
  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 }
408
+ this.ref(name)
409
+ const { path, range, rest } = this._plan(name, query)
410
+ return { data: filter(await this.view.find(path, range).toArray(), rest).length }
694
411
  }
695
412
 
696
413
  /**
@@ -710,11 +427,7 @@ export class Database extends ReadyResource {
710
427
  }
711
428
 
712
429
  /**
713
- * Delta subscription: batches of `{ prev, next }` row pairs instead of
714
- * full snapshots. The first batch (and any batch after a view swap) carries
715
- * the current matching rows as inserts with `reset: true` — replaying every
716
- * batch into a Map keyed by row id always reconstructs current state.
717
- * `limit`/`reverse` are not applied; deltas are unwindowed by design.
430
+ * Delta subscription: batches of `{ prev, next }` row pairs instead of full snapshots.
718
431
  *
719
432
  * @param {string} name
720
433
  * @param {Query} [query]
@@ -722,43 +435,61 @@ export class Database extends ReadyResource {
722
435
  */
723
436
  changes(name, query = {}) {
724
437
  this.guard()
725
- const col = `@${this.ns}/${name}`
726
- if (!this.view.definition.resolveCollection(col)) {
727
- throw CeroError.UNKNOWN('collection', name)
728
- }
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
734
- return makeChanges(this, name, col, matches)
438
+ const col = this.col(this.ref(name))
439
+ const { limit, reverse, total, ...rest } = query
440
+ return makeChanges(this, name, col, (row) => filter([row], rest).length > 0)
735
441
  }
736
442
 
737
443
  /**
738
- * First-run bootstrap: create the device writer, save it, and swap into it.
444
+ * Provision this device. Its writer core was minted when the database opened and this
445
+ * device is its only author, ever.
739
446
  *
740
- * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean }} [opts]
447
+ * @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean, timeout?: number }} [opts]
741
448
  * @returns {Promise<{ id: Uint8Array, writer: import('../identity/index.js').KeyPair }>}
742
449
  */
743
- bootstrap(opts) {
450
+ async bootstrap({ name, isMobile, recovering = false, timeout = 30000 } = {}) {
744
451
  this.guard()
745
- return bootstrap(this, opts)
452
+ const ts = Date.now()
453
+ const writer = this._admission(this.writerKey, ts)
454
+ const device = [
455
+ 'set-device',
456
+ {
457
+ id: hid.encode(this.writerKey),
458
+ name: name || null,
459
+ isMobile: isMobile === true,
460
+ createdAt: ts,
461
+ updatedAt: ts
462
+ }
463
+ ]
464
+ if (!recovering) {
465
+ await this.write([['add-writer', writer], device])
466
+ } else {
467
+ await this._backfilled(timeout)
468
+ await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
469
+ timeout
470
+ })
471
+ await this.write([device])
472
+ }
473
+ return { id: this.writerKey, writer: this.keyPair }
746
474
  }
747
475
 
748
476
  /**
749
- * Claim writership on an existing room by signing our writer key with the
750
- * member identity; the claim rides in the device core as an optimistic node.
751
- * Admission only — the device is named separately (bootstrap → set-device).
477
+ * Claim writership on an existing room by signing our writer key with the member identity;
478
+ * the claim rides in the device core as an optimistic node.
752
479
  *
753
480
  * @returns {Promise<void>}
754
481
  */
755
482
  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)
483
+ this.guard()
484
+ if (this.bee.writable) return
485
+ const writer = this.writerKey
486
+ const op = this.spec.dispatch.encode(`@${this.ns}/claim-writer`, {
487
+ identity: this.identity.publicKey,
488
+ writer,
489
+ sig: this.identity.sign(ownership(this.key, writer)),
490
+ ts: Date.now()
491
+ })
492
+ await this._optimistic(op)
762
493
  }
763
494
 
764
495
  /**
@@ -767,8 +498,24 @@ export class Database extends ReadyResource {
767
498
  * @param {{ timeout?: number }} [opts]
768
499
  * @returns {Promise<void>}
769
500
  */
770
- async whenWritable(opts) {
771
- return whenWritable(this, opts)
501
+ async whenWritable({ timeout = 30000 } = {}) {
502
+ this.guard()
503
+ const { bee } = this
504
+ if (bee.writable) return
505
+ return new Promise((resolve, reject) => {
506
+ const done = (err) => {
507
+ clearTimeout(timer)
508
+ bee.off('writable', done)
509
+ this.off('close', onclose)
510
+ if (err) reject(err)
511
+ else resolve()
512
+ }
513
+ const onclose = () => done(CeroError.CLOSED('Database'))
514
+ const timer =
515
+ timeout > 0 ? setTimeout(() => done(CeroError.TIMED_OUT('whenWritable')), timeout) : null
516
+ bee.once('writable', done)
517
+ this.once('close', onclose)
518
+ })
772
519
  }
773
520
 
774
521
  /**
@@ -778,7 +525,7 @@ export class Database extends ReadyResource {
778
525
  * @returns {Promise<void>}
779
526
  */
780
527
  async addWriter(publicKey) {
781
- return addWriter(this, publicKey)
528
+ return this._admit('add-writer', 'addWriter', publicKey)
782
529
  }
783
530
 
784
531
  /**
@@ -788,7 +535,7 @@ export class Database extends ReadyResource {
788
535
  * @returns {Promise<void>}
789
536
  */
790
537
  async removeWriter(publicKey) {
791
- return removeWriter(this, publicKey)
538
+ return this._admit('del-writer', 'removeWriter', publicKey)
792
539
  }
793
540
 
794
541
  /**
@@ -826,6 +573,293 @@ export class Database extends ReadyResource {
826
573
  return `@${this.ns}/${ref.name}`
827
574
  }
828
575
 
576
+ // the boot reads post-rotation state through the keyring, primed before the bee exists
577
+ async _preload() {
578
+ const local = this.store.namespace(this.namespace).get({
579
+ keyPair: this.keyPair,
580
+ manifest: {
581
+ version: this.store.manifestVersion,
582
+ signers: [{ publicKey: this.keyPair.publicKey }]
583
+ },
584
+ active: false
585
+ })
586
+ await local.ready()
587
+ await loadEpochs(this.keyring, local)
588
+ await local.close()
589
+ }
590
+
591
+ async _boot() {
592
+ const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
593
+ keyPair: this.keyPair,
594
+ encryptionKey: this.encryptionKey,
595
+ keyring: this.keyring,
596
+ optimistic: true,
597
+ wakeup: this.network?.wakeup || undefined,
598
+ open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
599
+ isTrusted: this._isTrusted.bind(this),
600
+ apply: this._apply.bind(this),
601
+ update: this._update.bind(this)
602
+ })
603
+ // swarm BEFORE boot so the boot has peers to pull from, not a cold open
604
+ if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
605
+ await bee.ready()
606
+ // apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
607
+ this.bee = bee
608
+ this.key = bee.key
609
+ await bee.update()
610
+ }
611
+
612
+ // ops skipped as too new apply once this version caught up: wipe the boot record and reboot
613
+ async _replay() {
614
+ const behind = await this.bee.local.getUserData('cero/behind')
615
+ this.behind = behind ? c.decode(c.uint, behind) : null
616
+ if (this.behind === null || this.behind > this.version) return false
617
+ await this.bee.local.setUserData('autobee/head', null)
618
+ await this.bee.local.setUserData('cero/behind', null)
619
+ await this.bee.close()
620
+ this.behind = null
621
+ return true
622
+ }
623
+
624
+ // without this hook autobee trusts every fast-forward candidate, a removed device's fork included
625
+ async _isTrusted(writer, view) {
626
+ try {
627
+ const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
628
+ if (!row) return false
629
+ if (row.v) return true
630
+ // only a provably empty view lets the genesis writer vouch: its core is the db key
631
+ const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
632
+ if (!any) return false
633
+ return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
634
+ } catch {
635
+ return false
636
+ }
637
+ }
638
+
639
+ // unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
640
+ async _apply(nodes, view, host) {
641
+ const ready = []
642
+ for (const node of nodes) {
643
+ const { version, body } = unwrap(node.value)
644
+ if (version > this.version) {
645
+ this._onfuture(version)
646
+ continue
647
+ }
648
+ ready.push(version === 0 ? node : { ...node, value: body })
649
+ }
650
+ const result = await this.dispatcher.apply(ready, view, host)
651
+ if (this._updaters.size || this._observers.size) this._notify(ready)
652
+ return result
653
+ }
654
+
655
+ async _update(db) {
656
+ await db.update()
657
+ const touched = this._touched
658
+ this._touched = new Set()
659
+ const all = touched.size === 0 || touched.has('*')
660
+ for (const [fn, scope] of this._updaters) {
661
+ if (all || !scope || touched.has(scope)) fn()
662
+ }
663
+ this.emit('update')
664
+ }
665
+
666
+ // a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
667
+ _joinSwarm(bee, discoveryKey) {
668
+ this.network.attach(bee)
669
+ const prev = this._discovery
670
+ this._discovery = this.network.join(discoveryKey, {
671
+ mode: this.passive ? PASSIVE : ACTIVE
672
+ })
673
+ if (prev) prev.destroy().catch(safetyCatch)
674
+ }
675
+
676
+ async _runBefore(op, ctx) {
677
+ for (const fn of this._before.get(op) || []) {
678
+ if ((await fn(ctx)) === false) return false
679
+ }
680
+ this.emit(`before:${op}`, ctx)
681
+ return true
682
+ }
683
+
684
+ async _runAfter(op, ctx) {
685
+ for (const fn of this._after.get(op) || []) {
686
+ try {
687
+ await fn(ctx)
688
+ } catch (err) {
689
+ this._onerror(err)
690
+ }
691
+ }
692
+ this.emit(`after:${op}`, ctx)
693
+ }
694
+
695
+ // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
696
+ _opOf(node) {
697
+ const { name, value } = this.spec.dispatch.decode(node.value)
698
+ const verb = name.slice(name.indexOf('/') + 1)
699
+ const dash = verb.indexOf('-')
700
+ if (dash < 0) return { op: verb, name: verb, value }
701
+ return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
702
+ }
703
+
704
+ // which refs the batch touched, for scoped update ticks, and one event per op
705
+ _notify(nodes) {
706
+ for (const node of nodes) {
707
+ let op
708
+ try {
709
+ op = this._opOf(node)
710
+ } catch (err) {
711
+ this._touched.add('*')
712
+ safetyCatch(err)
713
+ continue
714
+ }
715
+ const ref = this._verbs.get(op.name)
716
+ // an action's route handler writes wherever it wants, widen to all
717
+ this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
718
+ if (!this._observers.size) continue
719
+ const event = {
720
+ op: op.op,
721
+ name: op.name,
722
+ row: op.value,
723
+ writerKey: node.key,
724
+ seq: this._seq++
725
+ }
726
+ for (const fn of this._observers) {
727
+ try {
728
+ fn(event)
729
+ } catch (err) {
730
+ this._onerror(err)
731
+ }
732
+ }
733
+ }
734
+ }
735
+
736
+ async _merge(name, row, { upsert = true } = {}) {
737
+ const ref = this._prepare(name, row)
738
+ const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
739
+ if (!upsert && !existing) return null
740
+ const ts = Date.now()
741
+ const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
742
+ if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
743
+ const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
744
+ return this._append('set', name, stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
745
+ }
746
+
747
+ _prepare(name, row) {
748
+ this.guard()
749
+ const ref = this.ref(name)
750
+ this._checkFields(name, row)
751
+ return ref
752
+ }
753
+
754
+ async _append(op, name, stored, verb) {
755
+ const ctx = { op, name, row: stored }
756
+ if ((await this._runBefore(op, ctx)) === false) return null
757
+ await this.write([[verb, ctx.row]])
758
+ return ctx
759
+ }
760
+
761
+ async _done(op, ctx) {
762
+ if (!ctx) return null
763
+ const result = { data: ctx.row }
764
+ await this._runAfter(op, { ...ctx, result })
765
+ return result
766
+ }
767
+
768
+ // ops from a newer app version: emit behind once per version, the marker survives restarts
769
+ _onfuture(version) {
770
+ if (this.behind !== null && version <= this.behind) return
771
+ this.behind = version
772
+ this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
773
+ this.emit('behind', version)
774
+ }
775
+
776
+ // every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
777
+ async _dryRun(encoded) {
778
+ const tx = this.view.transaction()
779
+ const host = { addWriter: async () => {}, removeWriter: async () => {} }
780
+ try {
781
+ for (const value of encoded) {
782
+ await this.dispatcher.dispatch(value, {
783
+ host,
784
+ view: tx,
785
+ key: this.writerKey,
786
+ dbKey: this.key,
787
+ dryRun: true
788
+ })
789
+ }
790
+ return tx.updated()
791
+ } finally {
792
+ // a failing close must not mask the handler's own rejection
793
+ try {
794
+ await tx.close()
795
+ } catch (err) {
796
+ safetyCatch(err)
797
+ }
798
+ }
799
+ }
800
+
801
+ // one hyperdb read per query: index, bounds and window pushed down, the rest filtered in memory
802
+ _plan(name, query = {}) {
803
+ const ref = this.refs[name]
804
+ const col = `@${this.ns}/${name}`
805
+ const rest = { ...query }
806
+ const eq = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
807
+ const bounded = [...RANGE].some((k) => query[k] !== undefined)
808
+ const idx = eq.length ? matchIndex(ref?.indexes, eq) : null
809
+ if (idx) {
810
+ const point = {}
811
+ for (const f of eq) point[f] = query[f]
812
+ const range = { gte: point, lte: point }
813
+ if (!query.search && !bounded) pushWindow(range, rest)
814
+ return { path: `${col}-${idx}`, range, rest, sorted: true }
815
+ }
816
+ if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
817
+ if (bounded) {
818
+ const range = {}
819
+ for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
820
+ return { path: col, range, rest, sorted: false }
821
+ }
822
+ if (ref?.orderIndex) {
823
+ const range = {}
824
+ pushWindow(range, rest)
825
+ return { path: `${col}-index`, range, rest, sorted: true }
826
+ }
827
+ return { path: col, range: {}, rest, sorted: false }
828
+ }
829
+
830
+ // rows before the in-memory pass; unknown once a pushed-down limit filled the page
831
+ async _total(path, range, rows, query) {
832
+ if (range.limit === undefined || rows.length < range.limit) return rows.length
833
+ if (!query?.total) return null
834
+ const { limit, reverse, ...bounds } = range
835
+ return (await this.view.find(path, bounds).toArray()).length
836
+ }
837
+
838
+ // an append by a core not yet admitted: apply verifies the signature and admits it
839
+ async _optimistic(op, opts) {
840
+ await this.bee.append(wrap(this.version, op), { optimistic: true })
841
+ await this.bee.update()
842
+ if (!this.bee.writable) await this.whenWritable(opts)
843
+ }
844
+
845
+ // the genesis device row is the first write of every database, so any device row means backfilled
846
+ async _backfilled(timeout) {
847
+ const deadline = Date.now() + timeout
848
+ while (Date.now() < deadline) {
849
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
850
+ if ((await this.get('devices')).data.length > 0) return
851
+ await this.bee.update()
852
+ await new Promise((resolve) => setTimeout(resolve, 50))
853
+ }
854
+ throw CeroError.TIMED_OUT('recovery — no peer replicated')
855
+ }
856
+
857
+ // the add-writer row for `writer`, appended by this device and signed by the identity
858
+ _admission(writer, ts = Date.now()) {
859
+ const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
860
+ return { master: this.identity.publicKey, writer, sig, ts }
861
+ }
862
+
829
863
  // the encoder silently drops an undeclared field, so the returned row would lie
830
864
  _checkFields(name, row) {
831
865
  const declared = this.refs[name]?.fields
@@ -838,101 +872,68 @@ export class Database extends ReadyResource {
838
872
  }
839
873
  }
840
874
 
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) {
875
+ async _admit(verb, hook, publicKey) {
865
876
  this.guard()
866
- if (!b4a.isBuffer(publicKey)) {
867
- throw CeroError.INVALID('publicKey must be a buffer')
868
- }
877
+ if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
869
878
  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)
879
+ if ((await this._runBefore(hook, ctx)) === false) return
880
+ const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
881
+ await this.write([[verb, this._admission(writer)]])
882
+ await this._runAfter(hook, ctx)
880
883
  }
881
884
  }
882
885
 
883
- // a trust decision reads a historic checkout whose blocks may not be servable yet,
884
- // and an unbounded read there wedges autobee's drain forever. null means untrusted.
885
- const bounded = (promise, ms = 2000) =>
886
- Promise.race([
886
+ // an unbounded read of an old checkout wedges autobee's drain; null means untrusted
887
+ function bounded(promise, ms = 2000) {
888
+ return Promise.race([
887
889
  promise.then((v) => ({ v })),
888
890
  new Promise((resolve) => setTimeout(() => resolve(null), ms))
889
891
  ])
892
+ }
893
+
894
+ function addHook(map, op, fn) {
895
+ if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
896
+ let arr = map.get(op)
897
+ if (!arr) map.set(op, (arr = []))
898
+ arr.push(fn)
899
+ return () => {
900
+ const i = arr.indexOf(fn)
901
+ if (i >= 0) arr.splice(i, 1)
902
+ }
903
+ }
904
+
905
+ // verb and name both resolve to the ref, ops are named by verb
906
+ function verbMap(refs) {
907
+ const map = new Map()
908
+ for (const [name, info] of Object.entries(refs)) {
909
+ map.set(info.verb || name, name)
910
+ map.set(name, name)
911
+ }
912
+ return map
913
+ }
914
+
915
+ // member and device have their own set handlers, every other collection upserts via add-
916
+ const BESPOKE = new Set(['member', 'device'])
890
917
 
891
918
  // fields the write path stamps itself, always allowed
892
919
  const SYSTEM_FIELDS = new Set(['id', 'memberId', 'index', 'createdAt', 'updatedAt'])
893
920
 
894
- const valueEq = (a, b) => {
895
- if (a instanceof Uint8Array && b instanceof Uint8Array) return b4a.equals(a, b)
896
- return a === b
897
- }
921
+ const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
898
922
 
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
- }
923
+ const byIndex = (a, b) => (a.index ?? 0) - (b.index ?? 0)
904
924
 
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
- )
925
+ // the index whose fields are exactly the query's equality keys
926
+ function matchIndex(indexes, fields) {
927
+ for (const [name, keys] of Object.entries(indexes || {})) {
928
+ if (keys.length === fields.length && keys.every((f) => fields.includes(f))) return name
929
+ }
930
+ return null
920
931
  }
921
932
 
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
933
+ // reverse and limit served by hyperdb, so the in-memory pass must not repeat them
934
+ function pushWindow(range, rest) {
935
+ if (rest.reverse === true) range.reverse = true
936
+ if (rest.limit !== undefined) range.limit = rest.limit
937
+ delete rest.reverse
938
+ delete rest.limit
938
939
  }