@cero-base/core 2.2.0 → 2.3.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 (55) hide show
  1. package/README.md +32 -212
  2. package/package.json +19 -10
  3. package/src/blobs/index.js +9 -0
  4. package/src/blobs/server.js +2 -0
  5. package/src/database/changes.js +1 -1
  6. package/src/database/dispatch.js +341 -209
  7. package/src/database/encryption.js +83 -33
  8. package/src/database/index.js +184 -83
  9. package/src/database/rotation.js +43 -30
  10. package/src/identity/index.js +20 -78
  11. package/src/index.js +3 -10
  12. package/src/lib/constants.js +2 -0
  13. package/src/lib/errors.js +3 -11
  14. package/src/lib/spec/index.js +136 -132
  15. package/src/lib/spec/schema.json +84 -99
  16. package/src/lib/utils.js +57 -3
  17. package/src/mailbox/inbox.js +103 -0
  18. package/src/mailbox/index.js +146 -0
  19. package/src/mailbox/post.js +69 -0
  20. package/src/network/discovery.js +26 -1
  21. package/src/network/index.js +105 -64
  22. package/src/network/presence.js +6 -2
  23. package/src/pairing/index.js +330 -254
  24. package/src/pairing/invite.js +83 -144
  25. package/src/pairing/request.js +54 -56
  26. package/src/rpc/index.js +18 -93
  27. package/src/rpc/peer.js +4 -1
  28. package/src/storage/index.js +78 -39
  29. package/types/blobs/index.d.ts +22 -9
  30. package/types/blobs/server.d.ts +4 -2
  31. package/types/database/changes.d.ts +2 -2
  32. package/types/database/dispatch.d.ts +19 -13
  33. package/types/database/encryption.d.ts +67 -29
  34. package/types/database/index.d.ts +144 -119
  35. package/types/database/rotation.d.ts +32 -13
  36. package/types/identity/index.d.ts +6 -47
  37. package/types/index.d.ts +3 -16
  38. package/types/lib/constants.d.ts +1 -0
  39. package/types/lib/errors.d.ts +3 -9
  40. package/types/lib/spec/index.d.ts +52 -16
  41. package/types/lib/utils.d.ts +40 -8
  42. package/types/mailbox/inbox.d.ts +52 -0
  43. package/types/mailbox/index.d.ts +111 -0
  44. package/types/mailbox/post.d.ts +37 -0
  45. package/types/network/discovery.d.ts +21 -5
  46. package/types/network/index.d.ts +64 -48
  47. package/types/network/presence.d.ts +17 -4
  48. package/types/pairing/index.d.ts +143 -134
  49. package/types/pairing/invite.d.ts +70 -114
  50. package/types/pairing/request.d.ts +58 -98
  51. package/types/rpc/index.d.ts +26 -44
  52. package/types/rpc/peer.d.ts +10 -7
  53. package/types/storage/index.d.ts +64 -54
  54. package/src/pairing/candidate.js +0 -123
  55. package/types/pairing/candidate.d.ts +0 -36
@@ -7,24 +7,40 @@ import safetyCatch from 'safety-catch'
7
7
  import b4a from 'b4a'
8
8
  import hid from 'hypercore-id-encoding'
9
9
 
10
- import { NAMESPACE, SINGLE, COLLECTION, ACTION, QUERY_RESERVED } from '../lib/constants.js'
10
+ import {
11
+ NAMESPACE,
12
+ SINGLE,
13
+ COLLECTION,
14
+ ACTION,
15
+ QUERY_RESERVED,
16
+ RANK,
17
+ ADMIN
18
+ } from '../lib/constants.js'
11
19
  import { genId } from '../lib/ids.js'
12
- import { subscribe, admission, ownership, filter } from '../lib/utils.js'
20
+ import {
21
+ subscribe,
22
+ admission,
23
+ ownership,
24
+ filter,
25
+ checkFields,
26
+ checkRequired,
27
+ stamp
28
+ } from '../lib/utils.js'
13
29
  import { wrap, unwrap } from './envelope.js'
14
30
  import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
15
31
  import { CeroError } from '../lib/errors.js'
16
32
  import { Identity } from '../identity/index.js'
17
33
  import { Rotation } from './rotation.js'
18
34
  import { makeChanges } from './changes.js'
19
- import { makeDispatcher } from './dispatch.js'
35
+ import { makeDispatcher, BESPOKE } from './dispatch.js'
36
+ import { keyPair } from '../mailbox/inbox.js'
20
37
 
21
38
  /**
22
39
  * @typedef {object} DatabaseOpts
23
- * @property {any} store Corestore (or compatible) used to materialize the autobee.
40
+ * @property {import('corestore')} store Corestore (or compatible) used to materialize the autobee.
24
41
  * @property {import('../identity/index.js').Identity} identity Long-lived member identity used to sign writer changes.
25
42
  * @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication.
26
- * @property {{ database: any, dispatch: any, meta?: { ns?: string, refs?: Record<string, { kind?: string, verb?: string }> } }} spec Generated hyperdb + hyperdispatch spec.
27
- * @property {Record<string, Function>} [routes] Custom action handlers keyed by route name.
43
+ * @property {{ database: object, dispatch: { Router: new () => object, encode: (name: string, value: unknown) => Uint8Array, decode: (buf: Uint8Array) => { name: string, value: unknown } }, meta?: { ns?: string, version?: number, refs?: Record<string, { kind?: string, verb?: string }> } }} spec Generated hyperdb + hyperdispatch spec.
28
44
  * @property {string} [namespace] Corestore namespace; defaults to `cero`.
29
45
  * @property {Uint8Array | null} [encryptionKey] Optional encryption key; falls back to identity's key.
30
46
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
@@ -37,8 +53,9 @@ import { makeDispatcher } from './dispatch.js'
37
53
  * op: `{ op, name, row, writerKey, seq }`, local and replicated), `writable`, `unwritable`,
38
54
  * `behind` (an op from a newer app version was skipped).
39
55
  *
40
- * @typedef {{ data: any | null }} SingleResult
41
- * @typedef {{ data: any[], total: number | null, size: number }} ListResult `total` is null when a limited read skipped the full count — pass `{ total: true }` to force it.
56
+ * @typedef {Record<string, unknown>} Row A row, fields by name.
57
+ * @typedef {{ data: Row | null }} SingleResult
58
+ * @typedef {{ data: Row[], total: number | null, size: number }} ListResult `total` is null when a limited read skipped the full count — pass `{ total: true }` to force it.
42
59
  * @typedef {{ gt?: string, gte?: string, lt?: string, lte?: string, reverse?: boolean, limit?: number, search?: string, fields?: string[], total?: boolean }} Query
43
60
  * @typedef {{ kind: string, verb: string, name: string }} Ref
44
61
  * @typedef {object} HookContext
@@ -47,8 +64,8 @@ import { makeDispatcher } from './dispatch.js'
47
64
  * @property {Record<string, unknown> | null} row The incoming row; mutate it in `before` to change what lands.
48
65
  * @property {Record<string, unknown> | null} existing The stored row, or null.
49
66
  * @property {string | null} id The row id for a `del`.
50
- * @property {string} memberId The writer's member id.
51
- * @property {string} role The writer's role.
67
+ * @property {string | null} memberId The writer's member id, null for a core no member owns yet (a join, a claim, genesis).
68
+ * @property {string | null} role The writer's role, null likewise.
52
69
  * @property {(ref: string | { name: string }, query?: string | Record<string, unknown>) => Promise<{ data: unknown }>} get
53
70
  * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} put
54
71
  * @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} set
@@ -70,6 +87,7 @@ export class Database extends ReadyResource {
70
87
  throw CeroError.INVALID('spec must have database + dispatch')
71
88
  }
72
89
 
90
+ /** @type {import('corestore')} */
73
91
  this.store = opts.store
74
92
  this.identity = opts.identity
75
93
  this.network = opts.network || null
@@ -78,8 +96,8 @@ export class Database extends ReadyResource {
78
96
  this.ns = this.meta.ns || NAMESPACE
79
97
  this.refs = this.meta.refs || {}
80
98
  this.version = this.meta.version || 1
99
+ /** @type {number | null} */
81
100
  this.behind = null
82
- this.routes = opts.routes || {}
83
101
  this.namespace = opts.namespace || NAMESPACE
84
102
  this.encryptionKey = opts.encryptionKey || opts.identity.encryptionKey || null
85
103
  this.keyring = new Keyring()
@@ -92,20 +110,35 @@ export class Database extends ReadyResource {
92
110
  throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
93
111
  }
94
112
 
113
+ /** @private */
95
114
  this._onerror = opts.onerror || ((err) => console.error(err))
115
+ // a join is sealed to the address the encryption key owns: every member opens it, no one else
116
+ /** @private */
117
+ this._room = this.encryptionKey ? keyPair(this.encryptionKey) : null
96
118
  this.bee = null
97
119
  this.dispatcher = null
120
+ /** @private */
98
121
  this._presence = null
122
+ /** @private */
99
123
  this._txChain = null
124
+ /** @private */
125
+ this._held = new Map()
100
126
 
127
+ /** @private */
101
128
  this._before = new Map()
129
+ /** @private */
102
130
  this._after = new Map()
131
+ /** @private */
103
132
  this._hooking = 0
133
+ /** @private */
104
134
  this._verbs = verbMap(this.refs)
135
+ /** @private */
105
136
  this._touched = new Set()
137
+ /** @private */
106
138
  this._seq = 0
107
139
  // every watch and changes stream is an 'update' listener
108
140
  this.setMaxListeners(0)
141
+ /** @type {Array<[string, unknown]> | null} */
109
142
  this.txQueue = null
110
143
  }
111
144
 
@@ -114,6 +147,11 @@ export class Database extends ReadyResource {
114
147
  return this.bee?.discoveryKey || null
115
148
  }
116
149
 
150
+ /** @returns {Uint8Array | null} where a join is sealed to: the address the encryption key owns */
151
+ get address() {
152
+ return this._room?.publicKey || null
153
+ }
154
+
117
155
  /** @returns {Uint8Array | null} this device's local writer key */
118
156
  get writerKey() {
119
157
  return this.bee?.local?.key || null
@@ -134,6 +172,7 @@ export class Database extends ReadyResource {
134
172
  return this.bee?.view || null
135
173
  }
136
174
 
175
+ /** @private */
137
176
  async _open() {
138
177
  await this.store.ready()
139
178
  if (this.network) await this.network.ready()
@@ -141,12 +180,11 @@ export class Database extends ReadyResource {
141
180
  this.dispatcher = makeDispatcher({
142
181
  spec: this.spec,
143
182
  ns: this.ns,
144
- routes: this.routes,
145
183
  onerror: this._onerror,
146
184
  key: () => this.key,
147
185
  onepoch: (row) => this.rotation.learn(row),
186
+ room: () => this._room,
148
187
  hooks: (phase, op) => this._hooks(phase, op),
149
- inHook: (fn) => this._inHook(fn),
150
188
  touch: (name) => this._touched.add(name),
151
189
  read: (view, name, query) => this._read(view, name, query)
152
190
  })
@@ -167,16 +205,27 @@ export class Database extends ReadyResource {
167
205
  // without a listener autobee escalates apply/view errors to a process crash
168
206
  this.bee.on('error', this._onerror)
169
207
 
208
+ // with no mirror to hold the room, every member holds it: any member serves a joiner, offline
209
+ if (this.network && !this.network.mirrors.length) {
210
+ this.bee.on('move-to', () => this._holdRoom().catch(safetyCatch))
211
+ this._holdRoom().catch(safetyCatch)
212
+ }
213
+
170
214
  // a fresh db has no key until boot mints it
171
215
  if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
172
216
  }
173
217
 
218
+ /** @private */
174
219
  async _close() {
175
220
  this.rotation.close()
176
221
  if (this._presence) {
177
222
  this._presence.remove()
178
223
  this._presence = null
179
224
  }
225
+ const held = [...this._held.values()]
226
+ this._held.clear()
227
+ for (const { range } of held) range.destroy()
228
+ await Promise.allSettled(held.map(({ core }) => core.close()))
180
229
  if (this.bee) {
181
230
  // detach first, else the closed bee replicates into every new connection
182
231
  if (this.network) this.network.detach(this.bee)
@@ -201,7 +250,7 @@ export class Database extends ReadyResource {
201
250
  * Register a pre-op hook. It runs at apply on every peer, inside the op's transaction;
202
251
  * returning `false` (or throwing) refuses the op everywhere.
203
252
  *
204
- * @param {string} op
253
+ * @param {string} op A write (`put`, `set`, `del`), or an action's name.
205
254
  * @param {HookFn} fn
206
255
  * @returns {() => void} disposer
207
256
  */
@@ -211,9 +260,10 @@ export class Database extends ReadyResource {
211
260
 
212
261
  /**
213
262
  * Register a post-op hook. It runs at apply on every peer, in the op's transaction, so it
214
- * may write derived rows through `ctx.put` / `ctx.set` / `ctx.del`.
263
+ * may write derived rows through `ctx.put` / `ctx.set` / `ctx.del`. On an action it is what
264
+ * the action does.
215
265
  *
216
- * @param {string} op
266
+ * @param {string} op A write (`put`, `set`, `del`), or an action's name.
217
267
  * @param {HookFn} fn
218
268
  * @returns {() => void} disposer
219
269
  */
@@ -222,16 +272,18 @@ export class Database extends ReadyResource {
222
272
  }
223
273
 
224
274
  /**
225
- * Insert (or overwrite by id) a row, stamping `id`/`createdAt`/`updatedAt`.
275
+ * Insert (or overwrite by id) a row, stamping `id`/`createdAt`/`updatedAt`: an overwrite keeps
276
+ * the row's `createdAt`, and timestamps the caller passes are ignored.
226
277
  *
227
278
  * @param {string} name
228
- * @param {Record<string, any>} row
279
+ * @param {Record<string, unknown>} row
229
280
  * @returns {Promise<SingleResult | null>}
230
281
  */
231
282
  async put(name, row) {
232
283
  const ref = this._prepare(name, row)
233
- const ts = Date.now()
234
- const stored = { createdAt: ts, updatedAt: ts, ...row, id: row.id || genId() }
284
+ const was = row.id ? (await this.get(name, row.id)).data : null
285
+ const stored = stamp({ ...row, id: row.id || genId() }, was?.createdAt)
286
+ checkRequired(name, this.refs[name], stored)
235
287
  return this._done(await this._append(stored, `add-${ref.verb}`))
236
288
  }
237
289
 
@@ -239,12 +291,14 @@ export class Database extends ReadyResource {
239
291
  * Upsert by merging with the existing row, preserving `createdAt`.
240
292
  *
241
293
  * @param {string} name
242
- * @param {Record<string, any>} row
294
+ * @param {Record<string, unknown>} row
243
295
  * @param {{ upsert?: boolean }} [opts]
244
296
  * @returns {Promise<SingleResult | null>}
245
297
  */
246
298
  async set(name, row, opts) {
247
- return this._done(await this.tx((tx) => tx._merge(name, row, opts)))
299
+ if (this.txQueue) return this._done(await this._merge(name, row, opts))
300
+ // read, merge and append as one unit: two sets on one row see each other
301
+ return this._done(await this._chain(() => this._merge(name, row, opts)))
248
302
  }
249
303
 
250
304
  /**
@@ -263,19 +317,17 @@ export class Database extends ReadyResource {
263
317
  }
264
318
 
265
319
  /**
266
- * Dispatch a custom action route by name.
320
+ * Run a declared action: what the `after` hooks on its name do, at apply on every peer.
267
321
  *
268
322
  * @param {string} op
269
- * @param {Record<string, any>} [data]
323
+ * @param {Record<string, unknown>} [data]
270
324
  * @returns {Promise<void>}
271
325
  */
272
326
  async call(op, data = {}) {
273
327
  this.guard()
274
- // a declared action with no local route applies as a silent no-op (builtins pass)
275
- if (this.refs[op]?.kind === ACTION && typeof this.routes[op] !== 'function') {
276
- throw CeroError.INVALID(
277
- `action '${op}' has no route — pass { routes: { ${op} } } when opening the handle`
278
- )
328
+ // an action with nothing to run would write a dead op into the log
329
+ if (this.refs[op]?.kind === ACTION && !this._after.get(op)?.length) {
330
+ throw CeroError.INVALID(`action '${op}' has no after hook`)
279
331
  }
280
332
  await this.write([[op, data]])
281
333
  }
@@ -306,22 +358,25 @@ export class Database extends ReadyResource {
306
358
  throw CeroError.INVALID('tx(fn) — fn must accept the transaction handle: tx((tx) => ...)')
307
359
  }
308
360
  if (this.txQueue) return fn(this)
309
- // outer transactions serialize so their appends land in call order
310
- const run = async () => {
311
- const batch = Object.create(this)
312
- batch.txQueue = []
313
- try {
314
- const result = await fn(batch)
315
- if (batch.txQueue.length) await this.write(batch.txQueue)
316
- return result
317
- } catch (err) {
318
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
319
- throw err
320
- }
361
+ // only the commit is chained: a write the callback awaits outside the batch must not queue
362
+ // behind it
363
+ const batch = Object.create(this)
364
+ batch.txQueue = []
365
+ try {
366
+ const result = await fn(batch)
367
+ if (batch.txQueue.length) await this._chain(() => this.write(batch.txQueue))
368
+ return result
369
+ } catch (err) {
370
+ if (this.closing || this.closed) throw CeroError.CLOSED('Database')
371
+ throw err
321
372
  }
373
+ }
374
+
375
+ // one after the other, past each other's failures so one does not wedge the rest
376
+ /** @private */
377
+ _chain(fn) {
322
378
  const prev = this._txChain || Promise.resolve()
323
- // chain past prev's outcome so one failure doesn't wedge later transactions
324
- this._txChain = prev.then(run, run)
379
+ this._txChain = prev.then(fn, fn)
325
380
  return this._txChain
326
381
  }
327
382
 
@@ -329,7 +384,7 @@ export class Database extends ReadyResource {
329
384
  * Encode and append dispatch ops. Buffers into the active `tx` queue if one
330
385
  * is open.
331
386
  *
332
- * @param {Array<[string, any]>} ops
387
+ * @param {Array<[string, unknown]>} ops
333
388
  * @returns {Promise<void>}
334
389
  */
335
390
  async write(ops) {
@@ -338,7 +393,9 @@ export class Database extends ReadyResource {
338
393
  return
339
394
  }
340
395
  this.guard()
341
- if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
396
+ // leaving takes no seat: a reader's own removal goes in optimistically, apply admits it
397
+ const optimistic = !this.bee.writable && leaving(ops, this.identity.id)
398
+ if (!this.bee.writable && !optimistic) throw CeroError.NOT_WRITABLE('Database')
342
399
  // writable flips inside the apply that admits us, before its view flush lands our device row
343
400
  await this.bee.updated()
344
401
  const encoded = ops.map(([op, payload]) =>
@@ -349,7 +406,7 @@ export class Database extends ReadyResource {
349
406
  try {
350
407
  if (!(await this._dryRun(encoded)) && !action) return
351
408
  const wrapped = encoded.map((value) => wrap(this.version, value))
352
- await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
409
+ await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped, { optimistic })
353
410
  } catch (err) {
354
411
  if (this.closing || this.closed) throw CeroError.CLOSED('Database')
355
412
  throw err
@@ -370,6 +427,7 @@ export class Database extends ReadyResource {
370
427
  }
371
428
 
372
429
  // the same read against any view: hooks read the transaction they run in
430
+ /** @private */
373
431
  async _read(view, name, query) {
374
432
  const ref = this.ref(name)
375
433
  const col = this.col(ref)
@@ -501,22 +559,20 @@ export class Database extends ReadyResource {
501
559
  }
502
560
  const onclose = () => done(CeroError.CLOSED('Database'))
503
561
  const timer =
504
- timeout > 0 ? setTimeout(() => done(CeroError.TIMED_OUT('whenWritable')), timeout) : null
562
+ timeout > 0 ? setTimeout(() => done(CeroError.TIMEOUT('whenWritable')), timeout) : null
505
563
  bee.once('writable', done)
506
564
  this.once('close', onclose)
507
565
  })
508
566
  }
509
567
 
510
568
  /**
511
- * Admit a device as a writer for `memberId`, an existing member. Omit it to
512
- * admit another device of this identity.
569
+ * Admit another device of this identity as a writer. Another member's device seats itself.
513
570
  *
514
571
  * @param {Uint8Array} publicKey
515
- * @param {string} [memberId]
516
572
  * @returns {Promise<void>}
517
573
  */
518
- async addWriter(publicKey, memberId) {
519
- return this._admit('add-writer', publicKey, memberId)
574
+ async addWriter(publicKey) {
575
+ return this._admit('add-writer', publicKey)
520
576
  }
521
577
 
522
578
  /**
@@ -568,6 +624,7 @@ export class Database extends ReadyResource {
568
624
  }
569
625
 
570
626
  // the boot reads post-rotation state through the keyring, primed before the bee exists
627
+ /** @private */
571
628
  async _preload() {
572
629
  const local = this.store.namespace(this.namespace).get({
573
630
  keyPair: this.keyPair,
@@ -582,6 +639,7 @@ export class Database extends ReadyResource {
582
639
  await local.close()
583
640
  }
584
641
 
642
+ /** @private */
585
643
  async _boot() {
586
644
  const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
587
645
  keyPair: this.keyPair,
@@ -604,24 +662,31 @@ export class Database extends ReadyResource {
604
662
  }
605
663
 
606
664
  // ops skipped as too new apply once this version caught up: wipe the boot record and reboot
665
+ /** @private */
607
666
  async _replay() {
608
667
  const behind = await this.bee.local.getUserData('cero/behind')
609
668
  this.behind = behind ? c.decode(c.uint, behind) : null
610
669
  if (this.behind === null || this.behind > this.version) return false
611
670
  await this.bee.local.setUserData('autobee/head', null)
612
671
  await this.bee.local.setUserData('cero/behind', null)
672
+ if (this.network) this.network.detach(this.bee)
613
673
  await this.bee.close()
614
674
  this.behind = null
615
675
  return true
616
676
  }
617
677
 
618
- // without this hook autobee trusts every fast-forward candidate, a removed device's fork included
678
+ // only an admin's or an owner's device hands over a view: anyone else holding the key could serve
679
+ // a forged one that peers adopt without applying it
680
+ /** @private */
619
681
  async _isTrusted(writer, view) {
620
682
  try {
621
683
  const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
622
684
  if (!row) return false
623
- if (row.v) return true
624
- // only a provably empty view lets the genesis writer vouch: its core is the db key
685
+ if (row.v) {
686
+ const member = await bounded(view.get(`@${this.ns}/members`, { id: row.v.memberId }))
687
+ return RANK[member?.v?.role] >= RANK[ADMIN]
688
+ }
689
+ // only a provably empty view trusts the genesis writer: its core is the db key
625
690
  const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
626
691
  if (!any) return false
627
692
  return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
@@ -631,6 +696,7 @@ export class Database extends ReadyResource {
631
696
  }
632
697
 
633
698
  // unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
699
+ /** @private */
634
700
  async _apply(nodes, view, host) {
635
701
  const ready = []
636
702
  for (const node of nodes) {
@@ -647,6 +713,7 @@ export class Database extends ReadyResource {
647
713
  }
648
714
 
649
715
  // 'update' carries the refs the batch touched; '*' means any, so a scoped watcher can skip
716
+ /** @private */
650
717
  async _update(db) {
651
718
  await db.update()
652
719
  const touched = this._touched
@@ -655,18 +722,44 @@ export class Database extends ReadyResource {
655
722
  this._presence?.touch()
656
723
  }
657
724
 
658
- // a writer swap re-opens the bee on the same topic, so the slot is the same one
725
+ // every bee a boot opens is attached, but the topic is joined once: close leaves it once
726
+ /** @private */
659
727
  _joinSwarm(bee, discoveryKey) {
660
728
  this.network.attach(bee)
661
- this._presence = this.network.presence.add(discoveryKey, { pinned: this.pinned })
729
+ this._presence ??= this.network.presence.add(discoveryKey, { pinned: this.pinned })
730
+ }
731
+
732
+ // every writer the room ever had and every core its views read; only the system bee, an autobee
733
+ // internal, lists all the writers
734
+ /** @private */
735
+ async _holdRoom() {
736
+ const bee = this.bee
737
+ const { views } = await bee.cores({ all: true })
738
+ for (const key of views) this._hold(key)
739
+ for await (const writer of bee.system.list()) this._hold(writer.key, writer.length)
740
+ }
741
+
742
+ // a view live, a writer only as far as the room applied it: past that a stranger could grow a
743
+ // core every member pulls. Inactive, so a new connection stays silent: the range only asks peers
744
+ // already replicating the core
745
+ /** @private */
746
+ _hold(key, end = -1) {
747
+ const id = b4a.toHex(key)
748
+ const held = this._held.get(id)
749
+ if (this.closing || (held && (held.end === -1 || end <= held.end))) return
750
+ const core = held ? held.core : this.store.get({ key, active: false })
751
+ held?.range.destroy()
752
+ this._held.set(id, { core, end, range: core.download({ start: 0, end }) })
662
753
  }
663
754
 
664
755
  // wrapped so an operator called from inside a hook fails instead of appending its own op
756
+ /** @private */
665
757
  _hooks(phase, op) {
666
758
  const fns = (phase === 'before' ? this._before : this._after).get(op)
667
759
  return fns?.length ? fns.map((fn) => this._inHook(fn)) : NO_HOOKS
668
760
  }
669
761
 
762
+ /** @private */
670
763
  _inHook(fn) {
671
764
  return async (ctx) => {
672
765
  this._hooking++
@@ -679,6 +772,7 @@ export class Database extends ReadyResource {
679
772
  }
680
773
 
681
774
  // an 'update' listener for one ref; the disposer detaches it
775
+ /** @param {string} name @param {() => void} fn @returns {() => void} */
682
776
  onUpdate(name, fn) {
683
777
  const tick = (touched) => {
684
778
  if (touched.has('*') || touched.has(name)) fn()
@@ -688,6 +782,7 @@ export class Database extends ReadyResource {
688
782
  }
689
783
 
690
784
  // '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
785
+ /** @private */
691
786
  _opOf(node) {
692
787
  const { name, value } = this.spec.dispatch.decode(node.value)
693
788
  const verb = name.slice(name.indexOf('/') + 1)
@@ -697,6 +792,7 @@ export class Database extends ReadyResource {
697
792
  }
698
793
 
699
794
  // marks the refs a batch touched and emits 'apply' per op, local and replicated alike
795
+ /** @private */
700
796
  _notify(nodes) {
701
797
  const listened = this.listenerCount('apply') > 0
702
798
  for (const node of nodes) {
@@ -709,7 +805,7 @@ export class Database extends ReadyResource {
709
805
  continue
710
806
  }
711
807
  const ref = this._verbs.get(op.name)
712
- // an action's route handler writes wherever it wants, widen to all
808
+ // an action's hooks write wherever they want, widen to all
713
809
  this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
714
810
  if (!listened) continue
715
811
  this.emit('apply', {
@@ -722,34 +818,39 @@ export class Database extends ReadyResource {
722
818
  }
723
819
  }
724
820
 
821
+ /** @private */
725
822
  async _merge(name, row, { upsert = true } = {}) {
726
823
  const ref = this._prepare(name, row)
727
824
  const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
728
825
  if (!upsert && !existing) return null
729
- const ts = Date.now()
730
- const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
826
+ const stored = stamp({ ...existing, ...row }, existing?.createdAt)
827
+ checkRequired(name, this.refs[name], stored)
731
828
  if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
732
829
  const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
733
830
  return this._append(stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
734
831
  }
735
832
 
833
+ /** @private */
736
834
  _prepare(name, row) {
737
835
  this.guard()
738
836
  const ref = this.ref(name)
739
- this._checkFields(name, row)
837
+ checkFields(name, this.refs[name], row)
740
838
  return ref
741
839
  }
742
840
 
841
+ /** @private */
743
842
  async _append(stored, verb) {
744
843
  await this.write([[verb, stored]])
745
844
  return { row: stored }
746
845
  }
747
846
 
847
+ /** @private */
748
848
  _done(ctx) {
749
849
  return ctx ? { data: ctx.row } : null
750
850
  }
751
851
 
752
852
  // ops from a newer app version: emit behind once per version, the marker survives restarts
853
+ /** @private */
753
854
  _onfuture(version) {
754
855
  if (this.behind !== null && version <= this.behind) return
755
856
  this.behind = version
@@ -758,9 +859,14 @@ export class Database extends ReadyResource {
758
859
  }
759
860
 
760
861
  // every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
862
+ /** @private */
761
863
  async _dryRun(encoded) {
762
864
  const tx = this.view.transaction()
763
- const host = { addWriter: async () => {}, removeWriter: async () => {} }
865
+ const host = {
866
+ addWriter: async () => {},
867
+ removeWriter: async () => {},
868
+ genesis: this.bee.system.isGenesis()
869
+ }
764
870
  try {
765
871
  for (const value of encoded) {
766
872
  await this.dispatcher.dispatch(value, {
@@ -784,6 +890,7 @@ export class Database extends ReadyResource {
784
890
  }
785
891
 
786
892
  // one hyperdb read per query: index, bounds and window pushed down, the rest filtered in memory
893
+ /** @private */
787
894
  _plan(name, query = {}) {
788
895
  const ref = this.refs[name]
789
896
  const col = `@${this.ns}/${name}`
@@ -799,10 +906,12 @@ export class Database extends ReadyResource {
799
906
  return { path: `${col}-${idx}`, range, rest, sorted: true }
800
907
  }
801
908
  if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
909
+ // a range on the id reads in id order, so hyperdb serves the window and stops at the page
802
910
  if (bounded) {
803
911
  const range = {}
804
912
  for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
805
- return { path: col, range, rest, sorted: false }
913
+ pushWindow(range, rest)
914
+ return { path: col, range, rest, sorted: true }
806
915
  }
807
916
  if (ref?.orderIndex) {
808
917
  const range = {}
@@ -813,6 +922,7 @@ export class Database extends ReadyResource {
813
922
  }
814
923
 
815
924
  // matched rows; unknown once a pushed-down limit filled the page
925
+ /** @private */
816
926
  async _total(view, path, range, matched, query) {
817
927
  if (range.limit === undefined || matched.length < range.limit) return matched.length
818
928
  if (!query?.total) return null
@@ -821,6 +931,7 @@ export class Database extends ReadyResource {
821
931
  }
822
932
 
823
933
  // an append by a core not yet admitted: apply verifies the signature and admits it
934
+ /** @private */
824
935
  async _optimistic(op, opts) {
825
936
  await this.bee.append(wrap(this.version, op), { optimistic: true })
826
937
  await this.bee.update()
@@ -828,6 +939,7 @@ export class Database extends ReadyResource {
828
939
  }
829
940
 
830
941
  // the genesis device row is the first write of every database, so any device row means backfilled
942
+ /** @private */
831
943
  async _backfilled(timeout) {
832
944
  const deadline = Date.now() + timeout
833
945
  while (Date.now() < deadline) {
@@ -836,32 +948,22 @@ export class Database extends ReadyResource {
836
948
  await this.bee.update()
837
949
  await new Promise((resolve) => setTimeout(resolve, 50))
838
950
  }
839
- throw CeroError.TIMED_OUT('recovery — no peer replicated')
951
+ throw CeroError.TIMEOUT('recovery — no peer replicated')
840
952
  }
841
953
 
842
954
  // the add-writer row for `writer`, appended by this device and signed by the identity
955
+ /** @private */
843
956
  _admission(writer, ts = Date.now()) {
844
957
  const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
845
958
  return { master: this.identity.publicKey, writer, sig, ts }
846
959
  }
847
960
 
848
- // the encoder silently drops an undeclared field, so the returned row would lie
849
- _checkFields(name, row) {
850
- const declared = this.refs[name]?.fields
851
- if (!declared || !row) return
852
- for (const key of Object.keys(row)) {
853
- if (declared.includes(key) || SYSTEM_FIELDS.has(key)) continue
854
- throw CeroError.INVALID(
855
- `unknown field '${key}' on '${name}' — declared: ${declared.join(', ') || '(none)'}`
856
- )
857
- }
858
- }
859
-
860
- async _admit(verb, publicKey, memberId) {
961
+ /** @private */
962
+ async _admit(verb, publicKey) {
861
963
  this.guard()
862
964
  if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
863
965
  const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
864
- await this.write([[verb, { ...this._admission(writer), memberId }]])
966
+ await this.write([[verb, this._admission(writer)]])
865
967
  }
866
968
  }
867
969
 
@@ -896,11 +998,10 @@ function verbMap(refs) {
896
998
  return map
897
999
  }
898
1000
 
899
- // member and device have their own set handlers, every other collection upserts via add-
900
- const BESPOKE = new Set(['member', 'device'])
901
-
902
- // fields the write path stamps itself, always allowed
903
- const SYSTEM_FIELDS = new Set(['id', 'memberId', 'index', 'createdAt', 'updatedAt'])
1001
+ // the one op a device without a writer seat may append
1002
+ function leaving(ops, id) {
1003
+ return ops.length === 1 && ops[0][0] === 'del-member' && ops[0][1]?.id === id
1004
+ }
904
1005
 
905
1006
  const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
906
1007