@cero-base/core 2.3.4 → 2.4.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.
package/README.md CHANGED
@@ -22,24 +22,24 @@ Each primitive but `Identity` is a `ReadyResource`: construct it, `await x.ready
22
22
 
23
23
  ## Exports
24
24
 
25
- | Subpath | What it gives you |
26
- | ------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
- | `@cero-base/core` | Every subpath below in one import, but `/database/encryption` and `/blobs/server` |
28
- | `@cero-base/core/identity` | `Identity`: a keypair from a seed; signs, verifies, seals, names a swarm topic |
29
- | `@cero-base/core/network` | `Network`: Hyperswarm plus wakeup, with managed discovery sessions; `channelTopic` |
30
- | `@cero-base/core/database` | `Database`: multi-writer, permissions checked at apply, hooks, key rotation |
31
- | `@cero-base/core/database/encryption` | `Keyring`, `EpochAutobee`, `blobEpochKey`, `loadEpochs`, `seal`, `opened`, `wraps`, `epochEntries`: the key epochs a `Database` rotates through |
32
- | `@cero-base/core/mailbox` | `Mailbox`: messages to an address, delivered directly or held by a mirror |
33
- | `@cero-base/core/pairing` | `Pairing`: invites into a database, joins admitted at apply; `sealJoin` |
34
- | `@cero-base/core/invite` | `Invite`: parse an invite string, read its `data` before joining |
35
- | `@cero-base/core/storage` | `Storage`: local tables on Hyperbee or RocksDB, for device-only data |
36
- | `@cero-base/core/blobs` | `Blobs`: bytes in a Hyperblobs core, addressed by position, encrypted; `encodeId`, `decodeId` |
37
- | `@cero-base/core/blobs/codec` | `encodeId`, `decodeId`: a core key, blob id and type as one string |
38
- | `@cero-base/core/blobs/server` | `FileServer`: a file id served at a local url |
39
- | `@cero-base/core/rpc` | `RPCServer`, `RPCClient`, `bindCodec`: a typed channel over any duplex stream |
40
- | `@cero-base/core/schema` | `t`, `schema`: the field types and the wrapper a build takes |
41
- | `@cero-base/core/utils` | `WRITE`, `INVITE`, `ASSIGN`, `REMOVE`, `can`, `grants`, `outranks`, `isRank`, `filter`, `searchHit`, `onAbort`, `subscribe`, `admission`, `ownership`, `joining`, `checkFields`, `checkRequired`, `stamp` |
42
- | `@cero-base/core/errors` | `CeroError` |
25
+ | Subpath | What it gives you |
26
+ | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
27
+ | `@cero-base/core` | Every subpath below in one import, but `/database/encryption` and `/blobs/server` |
28
+ | `@cero-base/core/identity` | `Identity`: a keypair from a seed; signs, verifies, seals, names a swarm topic |
29
+ | `@cero-base/core/network` | `Network`: Hyperswarm plus wakeup, with managed discovery sessions; `channelTopic` |
30
+ | `@cero-base/core/database` | `Database`: multi-writer, permissions checked at apply, hooks, key rotation |
31
+ | `@cero-base/core/database/encryption` | `Keyring`, `EpochAutobee`, `blobEpochKey`, `loadEpochs`, `seal`, `opened`, `wraps`, `epochEntries`: the key epochs a `Database` rotates through |
32
+ | `@cero-base/core/mailbox` | `Mailbox`: messages to an address, delivered directly or held by a mirror |
33
+ | `@cero-base/core/pairing` | `Pairing`: invites into a database, joins admitted at apply; `sealJoin` |
34
+ | `@cero-base/core/invite` | `Invite`: parse an invite string, read its `data` before joining |
35
+ | `@cero-base/core/storage` | `Storage`: local tables on Hyperbee or RocksDB, for device-only data |
36
+ | `@cero-base/core/blobs` | `Blobs`: bytes in a Hyperblobs core, addressed by position, encrypted; `encodeId`, `decodeId` |
37
+ | `@cero-base/core/blobs/codec` | `encodeId`, `decodeId`: a core key, blob id and type as one string |
38
+ | `@cero-base/core/blobs/server` | `FileServer`: a file id served at a local url |
39
+ | `@cero-base/core/rpc` | `RPCServer`, `RPCClient`, `bindCodec`: a typed channel over any duplex stream |
40
+ | `@cero-base/core/schema` | `t`, `schema`: the field types and the wrapper a build takes |
41
+ | `@cero-base/core/utils` | `WRITE`, `INVITE`, `ASSIGN`, `REMOVE`, `can`, `grants`, `outranks`, `isRank`, `filter`, `searchHit`, `onAbort`, `subscribe`, `admission`, `joining`, `checkFields`, `checkRequired`, `stamp` |
42
+ | `@cero-base/core/errors` | `CeroError` |
43
43
 
44
44
  Runs on Node and Bare, with TypeScript declarations.
45
45
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "2.3.4",
3
+ "version": "2.4.0",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -172,7 +172,6 @@
172
172
  "hyperswarm": "^4.17.2",
173
173
  "keet-identity-key": "^3.2.0",
174
174
  "ms": "^2.1.3",
175
- "protomux": "^3.12.1",
176
175
  "protomux-wakeup": "^2.9.0",
177
176
  "ready-resource": "^1.2.0",
178
177
  "safety-catch": "^1.0.3",
@@ -190,6 +189,7 @@
190
189
  "bare-url": "^2.5.4",
191
190
  "blind-peer": "^3.15.1",
192
191
  "brittle": "^4.2.0",
192
+ "protomux": "^3.12.1",
193
193
  "typescript": "^7.0.2",
194
194
  "which-runtime": "^1.4.0"
195
195
  },
@@ -12,10 +12,9 @@ const NS = `${NAMESPACE}/blobs`
12
12
  /**
13
13
  * @typedef {object} BlobsOpts
14
14
  * @property {object} store Corestore (or compatible) used to host the blob core.
15
- * @property {import('../identity/index.js').Identity} [identity] Identity supplying the default encryption key.
16
- * @property {import('../network/index.js').Network} [network] Optional network used to announce + replicate the core.
15
+ * @property {import('../network/index.js').Network} [network] Optional network on this store: the core rides its connections and mirrors.
17
16
  * @property {Uint8Array} [key] Pre-existing blob core key — joins an existing blob feed.
18
- * @property {Uint8Array} [encryptionKey] Explicit encryption key, overrides `identity.encryptionKey`.
17
+ * @property {Uint8Array} encryptionKey Encrypts the core.
19
18
  * @property {string} [name] Core name in the store when no `key` is given; `blobs` by default.
20
19
  *
21
20
  * @typedef {import('./codec.js').RawBlobId} RawBlobId
@@ -24,15 +23,18 @@ const NS = `${NAMESPACE}/blobs`
24
23
  /** Thin wrapper over a single Hyperblobs core; deals only in raw blobIds. */
25
24
  export class Blobs extends ReadyResource {
26
25
  /** @param {BlobsOpts} [opts] */
27
- constructor({ store, identity, network, key, encryptionKey, name } = {}) {
26
+ constructor({ store, network, key, encryptionKey, name } = {}) {
28
27
  super()
29
28
  if (!store) throw CeroError.REQUIRED('store')
30
- if (!identity && !encryptionKey) throw CeroError.REQUIRED('identity or encryptionKey')
29
+ if (!encryptionKey) throw CeroError.REQUIRED('encryptionKey')
30
+ // a network replicates its own store only: a core in another would never leave the device
31
+ if (network && !network.replicates(store)) {
32
+ throw CeroError.INVALID("store must be the network's store or a session of it")
33
+ }
31
34
 
32
35
  this.store = store
33
- this.identity = identity || null
34
36
  this.network = network || null
35
- this.encryptionKey = encryptionKey || (identity && identity.encryptionKey) || null
37
+ this.encryptionKey = encryptionKey
36
38
  this.name = name || 'blobs'
37
39
 
38
40
  /** @private */
@@ -41,8 +43,6 @@ export class Blobs extends ReadyResource {
41
43
  this.core = null
42
44
  /** @type {import('hyperblobs') | null} */
43
45
  this.hyperblobs = null
44
- /** @private */
45
- this._discovery = null
46
46
  }
47
47
 
48
48
  /**
@@ -88,16 +88,12 @@ export class Blobs extends ReadyResource {
88
88
  this.hyperblobs = new Hyperblobs(this.core)
89
89
  await this.hyperblobs.ready()
90
90
 
91
- if (this.network) {
92
- this.network.attach(this.core)
93
- this._discovery = this.network.join(this.core.discoveryKey)
94
- }
91
+ // files ride the connections the network already has, and mirrors through attach
92
+ if (this.network) this.network.attach(this.core)
95
93
  }
96
94
 
97
95
  /** @private */
98
96
  async _close() {
99
- if (this._discovery) await this._discovery.destroy()
100
- if (this.network && this.core) this.network.detach(this.core)
101
97
  if (this.hyperblobs) await this.hyperblobs.close()
102
98
  if (this.core) await this.core.close()
103
99
  }
@@ -24,7 +24,6 @@ import {
24
24
  grants,
25
25
  outranks,
26
26
  admission,
27
- ownership,
28
27
  joining,
29
28
  checkFields,
30
29
  checkRequired,
@@ -319,18 +318,6 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
319
318
  await drop(ctx, 'devices', hid.encode(op.writer))
320
319
  })
321
320
 
322
- add('claim-writer', async (op, ctx) => {
323
- if (!isKey(op.identity) || !isKey(op.writer) || !isSig(op.sig)) return
324
- if (!Identity.verify(op.identity, ownership(ctx.dbKey, op.writer), op.sig)) return
325
- // from any other core a claim is inapplicable, not refused: it must not abort that writer's batch
326
- if (!b4a.equals(ctx.key, op.writer)) return
327
- const memberId = hid.encode(op.identity)
328
- if (!can(await getRole(ctx.view, op.identity), WRITE)) throw CeroError.REFUSED('write')
329
- if (await boundElsewhere(ctx.view, op.writer, memberId)) throw CeroError.REFUSED('member')
330
- await ctx.host.addWriter(op.writer, { isIndexer: true })
331
- await seat(ctx, op.writer, memberId, op.ts || 0)
332
- })
333
-
334
321
  // the genesis batch names the creator; everyone after comes in through a signed join
335
322
  add('add-member', async (op, ctx) => {
336
323
  if (!isKey(op.key)) return
@@ -380,7 +367,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
380
367
  const r = await getSignerRole(ctx.view, ctx.key)
381
368
  if (!can(r, REMOVE) || !outranks(r, existing.role)) throw CeroError.REFUSED('remove')
382
369
  } else if (existing.role === OWNER && (await orphans(ctx.view, op.id))) {
383
- throw CeroError.INVALID('the last owner cannot leave: hand the room to another owner first')
370
+ throw CeroError.INVALID('the last owner cannot leave: make another member an owner first')
384
371
  }
385
372
  if (existing.key) await ctx.host.removeWriter(existing.key)
386
373
  // every device of the member goes with them, and any keys they were still owed
@@ -398,7 +385,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
398
385
 
399
386
  add('rotate-key', async (op, ctx) => {
400
387
  if (!op.wrapped?.byteLength) return
401
- // the commitment lets every member verify the sealed secret, so a rotator cannot split the room
388
+ // the commitment lets every member verify the sealed secret, so a rotator cannot split the database
402
389
  if (op.commit?.byteLength !== 32) return
403
390
  // the stamp is picked before any block is written, so epochs reorder freely; uniqueness is enforced here
404
391
  if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
@@ -440,7 +427,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
440
427
  })
441
428
 
442
429
  // a device row is the writer→role mapping, so memberId never comes off the wire; a core no
443
- // member owns writes none, or any stranger's optimistic node would plant a device in the room
430
+ // member owns writes none, or any stranger's optimistic node would plant a device in the database
444
431
  const bind = async (ctx) => {
445
432
  const { memberId } = await author(ctx)
446
433
  if (!memberId) throw CeroError.REFUSED('member')
@@ -571,7 +558,7 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
571
558
  const id = hid.encode(ctx.key)
572
559
  const invite = await ctx.view.get(invites, { id: b4a.toHex(join.invite) })
573
560
  if (!invite) {
574
- // an invite the room never held could be anyone's: nobody answers it
561
+ // an invite the database never held could be anyone's: nobody answers it
575
562
  const record = await ctx.view.get(spent, { id: b4a.toHex(join.invite) })
576
563
  if (!record) return
577
564
  return refuse(ctx, { id, reply: join.reply, expires: record.expires }, record.reason)
@@ -610,6 +597,14 @@ export function makeDispatcher({ spec, ns, onerror, key, onepoch, room, hooks, t
610
597
  const { identity, reply, createdAt: ts = 0 } = waiting
611
598
  await admit(ctx, { invite, identity, writer: hid.decode(op.id), reply, role, ts })
612
599
  })
600
+ // answered through the log like every refusal; a deny that lost the race to an accept is nothing
601
+ add('deny', async (op, ctx) => {
602
+ const waiting = await ctx.view.get(requests, { id: op.id })
603
+ if (!waiting || waiting.admitted) return
604
+ if (!can(await getSignerRole(ctx.view, ctx.key), INVITE)) throw CeroError.REFUSED('invite')
605
+ await drop(ctx, 'requests', op.id)
606
+ await refuse(ctx, waiting, op.reason || '')
607
+ })
613
608
  // only a join writes a request
614
609
  const joinsOnly = async () => {
615
610
  throw CeroError.REFUSED('request')
@@ -140,8 +140,10 @@ export class Keyring {
140
140
  this.current = 0
141
141
  /** highest adopted apply-order sequence (0 = base era) */
142
142
  this.seq = 0
143
- /** bumped on every add/remove — cheap change detection for retries */
143
+ /** bumped on every add/remove — cheap change detection */
144
144
  this.version = 0
145
+ /** @type {(() => void) | null} called when an epoch is learned or dropped */
146
+ this.onchange = null
145
147
  }
146
148
 
147
149
  /** @returns {Array<{ epoch: number, stamp: number, entropy: Uint8Array }>} ascending by seq */
@@ -171,6 +173,7 @@ export class Keyring {
171
173
  this.current = stamp
172
174
  }
173
175
  this.version++
176
+ this.onchange?.()
174
177
  }
175
178
 
176
179
  /**
@@ -198,6 +201,7 @@ export class Keyring {
198
201
  }
199
202
  }
200
203
  this.version++
204
+ this.onchange?.()
201
205
  }
202
206
  }
203
207
 
@@ -216,14 +220,14 @@ export class EpochAutobee extends Autobee {
216
220
  super(store, key, handlers)
217
221
  /** @type {Keyring | null} */
218
222
  this.keyring = handlers.keyring || null
223
+ // a block from an unknown epoch parks what read it until the keyring learns something
224
+ if (this.keyring) this.keyring.onchange = () => this._scheduleEpochWake()
219
225
  /** @private */
220
226
  this._epochStalled = new Set()
221
227
  /** @private */
222
- this._epochRetry = null
228
+ this._epochParked = false
223
229
  /** @private */
224
- this._epochRetryDelay = 1000
225
- /** @private */
226
- this._epochRetrySeen = 0
230
+ this._epochWake = null
227
231
  }
228
232
 
229
233
  /** @returns {number} the key id new blocks are written with */
@@ -231,35 +235,25 @@ export class EpochAutobee extends Autobee {
231
235
  return this.keyring ? this.keyring.current : 0
232
236
  }
233
237
 
234
- // a block from an epoch not learned yet: the writer freezes over the throw, and the retry
235
- // wakes it once the announcement lands
238
+ // a block from an epoch not learned yet: the writer freezes over the throw, and the keyring
239
+ // learning an epoch wakes it
236
240
  /** @param {number} id @param {{ key?: Uint8Array }} [ctx] @returns {Promise<Uint8Array>} */
237
241
  async getEntropy(id, ctx) {
238
242
  const entropy = this.keyring && this.keyring.entropy(id)
239
243
  if (entropy) return entropy
240
- if (ctx?.key) {
241
- this._epochStalled.add(b4a.toHex(ctx.key))
242
- this._scheduleEpochRetry()
243
- }
244
+ if (ctx?.key) this._epochStalled.add(b4a.toHex(ctx.key))
244
245
  throw CeroError.UNKNOWN_EPOCH(id)
245
246
  }
246
247
 
247
- /** @private */
248
- async _close() {
249
- if (this._epochRetry) clearTimeout(this._epochRetry)
250
- this._epochRetry = null
251
- return super._close()
252
- }
253
-
254
- // an UNKNOWN_EPOCH from the drain parks the pass; the retry wakes the stalled cores once the
255
- // announcement lands. Forward the arguments: the local drain passes { local: true }
248
+ // an UNKNOWN_EPOCH from the drain parks the pass until the keyring learns an epoch. Forward
249
+ // the arguments: the local drain passes { local: true }
256
250
  /** @private */
257
251
  async _bumpPendingWriters(...args) {
258
252
  try {
259
253
  return await super._bumpPendingWriters(...args)
260
254
  } catch (err) {
261
255
  if (err?.code !== 'UNKNOWN_EPOCH') throw err
262
- this._scheduleEpochRetry()
256
+ this._epochParked = true
263
257
  return false
264
258
  }
265
259
  }
@@ -271,30 +265,28 @@ export class EpochAutobee extends Autobee {
271
265
  return await super._applyWakeupHints()
272
266
  } catch (err) {
273
267
  if (err?.code !== 'UNKNOWN_EPOCH') throw err
274
- this._scheduleEpochRetry()
268
+ this._epochParked = true
275
269
  return []
276
270
  }
277
271
  }
278
272
 
279
- // a stalled core produces no wake-up of its own, only wakeup() re-adds it; exponential backoff
273
+ // a stalled core produces no wake-up of its own, only wakeup() re-adds it. The keyring learns
274
+ // inside a drain pass, which may itself have frozen a writer: let that pass finish and detach it,
275
+ // then wake what stalled
280
276
  /** @private */
281
- _scheduleEpochRetry() {
282
- if (this._epochRetry || this.closing) return
283
- const version = this.keyring ? this.keyring.version : 0
284
- if (version !== this._epochRetrySeen) {
285
- this._epochRetrySeen = version
286
- this._epochRetryDelay = 1000
287
- }
288
- this._epochRetry = setTimeout(() => {
289
- this._epochRetry = null
277
+ _scheduleEpochWake() {
278
+ if (this._epochWake || this.closing) return
279
+ if (!this._epochParked && !this._epochStalled.size) return
280
+ this._epochWake = setTimeout(async () => {
281
+ await this.update().catch(noop)
282
+ this._epochWake = null
290
283
  if (this.closing) return
291
- for (const hex of this._epochStalled) {
292
- this.wakeup({ key: b4a.from(hex, 'hex'), length: 0 }).catch(noop)
293
- }
284
+ const stalled = [...this._epochStalled]
294
285
  this._epochStalled.clear()
286
+ this._epochParked = false
287
+ for (const hex of stalled) this.wakeup({ key: b4a.from(hex, 'hex'), length: 0 }).catch(noop)
295
288
  this.update().catch(noop)
296
- }, this._epochRetryDelay)
297
- this._epochRetryDelay = Math.min(this._epochRetryDelay * 2, 60000)
289
+ }, 0)
298
290
  }
299
291
  }
300
292
 
@@ -16,15 +16,19 @@ export function wrap(version, body) {
16
16
  }
17
17
 
18
18
  /**
19
- * Split an op into contract version and payload. Ops written before the
20
- * envelope existed carry no sentinel and read as version 0.
19
+ * Split an op into contract version and payload, or `null` for bytes with no envelope or a cut one.
21
20
  *
22
21
  * @param {Uint8Array} buf
23
- * @returns {{ version: number, body: Uint8Array }}
22
+ * @returns {{ version: number, body: Uint8Array } | null}
24
23
  */
25
24
  export function unwrap(buf) {
26
- if (buf.byteLength === 0 || buf[0] !== SENTINEL) return { version: 0, body: buf }
25
+ if (buf.byteLength === 0 || buf[0] !== SENTINEL) return null
27
26
  const state = { buffer: buf, start: 1, end: buf.byteLength }
28
- const version = c.uint.decode(state)
29
- return { version, body: buf.subarray(state.start) }
27
+ try {
28
+ const version = c.uint.decode(state)
29
+ return { version, body: buf.subarray(state.start) }
30
+ } catch {
31
+ // any writer can append bytes: a version cut short must not throw inside apply
32
+ return null
33
+ }
30
34
  }
@@ -14,13 +14,14 @@ import {
14
14
  ACTION,
15
15
  QUERY_RESERVED,
16
16
  RANK,
17
- ADMIN
17
+ ADMIN,
18
+ WRITE
18
19
  } from '../lib/constants.js'
19
20
  import { genId } from '../lib/ids.js'
20
21
  import {
21
22
  subscribe,
22
23
  admission,
23
- ownership,
24
+ can,
24
25
  filter,
25
26
  checkFields,
26
27
  checkRequired,
@@ -39,10 +40,10 @@ import { keyPair } from '../mailbox/inbox.js'
39
40
  * @typedef {object} DatabaseOpts
40
41
  * @property {import('corestore')} store Corestore (or compatible) used to materialize the autobee.
41
42
  * @property {import('../identity/index.js').Identity} identity Long-lived member identity used to sign writer changes.
42
- * @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication.
43
+ * @property {import('../network/index.js').Network} [network] Optional swarm; required for multi-writer replication; `store` is its store or a session of it.
43
44
  * @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.
44
45
  * @property {string} [namespace] Corestore namespace; defaults to `cero`.
45
- * @property {Uint8Array | null} [encryptionKey] Optional encryption key; falls back to identity's key.
46
+ * @property {Uint8Array} encryptionKey Encrypts it; a join hands it out, so never the identity's on a database you pair.
46
47
  * @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
47
48
  * @property {Uint8Array | null} [key] Existing autobee key to reopen.
48
49
  * @property {boolean} [pinned] Always search and announce, outside the network's presence budget. The root.
@@ -86,6 +87,11 @@ export class Database extends ReadyResource {
86
87
  if (!opts.spec || !opts.spec.database || !opts.spec.dispatch) {
87
88
  throw CeroError.INVALID('spec must have database + dispatch')
88
89
  }
90
+ if (!opts.encryptionKey) throw CeroError.REQUIRED('encryptionKey')
91
+ // a network replicates its own store only: a database in another would never leave the device
92
+ if (opts.network && !opts.network.replicates(opts.store)) {
93
+ throw CeroError.INVALID("store must be the network's store or a session of it")
94
+ }
89
95
 
90
96
  /** @type {import('corestore')} */
91
97
  this.store = opts.store
@@ -99,7 +105,7 @@ export class Database extends ReadyResource {
99
105
  /** @type {number | null} */
100
106
  this.behind = null
101
107
  this.namespace = opts.namespace || NAMESPACE
102
- this.encryptionKey = opts.encryptionKey || opts.identity.encryptionKey || null
108
+ this.encryptionKey = opts.encryptionKey
103
109
  this.keyring = new Keyring()
104
110
  if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
105
111
  /** @private */
@@ -116,7 +122,7 @@ export class Database extends ReadyResource {
116
122
  this._onerror = opts.onerror || ((err) => console.error(err))
117
123
  // a join is sealed to the address the encryption key owns: every member opens it, no one else
118
124
  /** @private */
119
- this._room = this.encryptionKey ? keyPair(this.encryptionKey) : null
125
+ this._room = keyPair(this.encryptionKey)
120
126
  this.bee = null
121
127
  this.dispatcher = null
122
128
  /** @private */
@@ -209,7 +215,7 @@ export class Database extends ReadyResource {
209
215
  // without a listener autobee escalates apply/view errors to a process crash
210
216
  this.bee.on('error', this._onerror)
211
217
 
212
- // with no mirror to hold the room, every member holds it: any member serves a joiner, offline
218
+ // with no mirror to hold the database, every member holds it: any member serves a joiner, offline
213
219
  if (this.network && !this.network.mirrors.length) {
214
220
  this.bee.on('move-to', () => this._holdRoom().catch(safetyCatch))
215
221
  this._holdRoom().catch(safetyCatch)
@@ -231,8 +237,6 @@ export class Database extends ReadyResource {
231
237
  for (const { range } of held) range.destroy()
232
238
  await Promise.allSettled(held.map(({ core }) => core.close()))
233
239
  if (this.bee) {
234
- // detach first, else the closed bee replicates into every new connection
235
- if (this.network) this.network.detach(this.bee)
236
240
  await this.bee.close()
237
241
  this.bee = null
238
242
  }
@@ -285,6 +289,7 @@ export class Database extends ReadyResource {
285
289
  */
286
290
  async put(name, row) {
287
291
  const ref = this._prepare(name, row)
292
+ if (ref.kind === SINGLE) throw CeroError.INVALID(`${name} is a single: write it with set`)
288
293
  const was = row.id ? (await this.get(name, row.id)).data : null
289
294
  const stored = stamp({ ...row, id: row.id || genId() }, was?.createdAt)
290
295
  checkRequired(name, this.refs[name], stored)
@@ -492,7 +497,6 @@ export class Database extends ReadyResource {
492
497
  async bootstrap({ name, isMobile, recovering = false, timeout = 30000 } = {}) {
493
498
  this.guard()
494
499
  const ts = Date.now()
495
- const writer = this._admission(this.writerKey, ts)
496
500
  const device = [
497
501
  'set-device',
498
502
  {
@@ -504,10 +508,7 @@ export class Database extends ReadyResource {
504
508
  }
505
509
  ]
506
510
  if (recovering) {
507
- await this._backfilled(timeout)
508
- await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
509
- timeout
510
- })
511
+ await this.claim({ timeout })
511
512
  await this.write([device])
512
513
  } else {
513
514
  // one batch: a writer is never on the log without its member row
@@ -519,28 +520,30 @@ export class Database extends ReadyResource {
519
520
  createdAt: ts,
520
521
  updatedAt: ts
521
522
  }
523
+ const writer = this._admission(this.writerKey, ts)
522
524
  await this.write([['add-writer', writer], ['add-member', member], device])
523
525
  }
524
526
  return { id: this.writerKey, writer: this.keyPair }
525
527
  }
526
528
 
527
529
  /**
528
- * Claim writership on an existing room by signing our writer key with the member identity;
529
- * the claim rides in the device core as an optimistic node.
530
+ * Seat this device's writer where its identity is a member: wait for the member row, append
531
+ * the add-writer the identity signs from this device's own core, and resolve once it writes.
532
+ * A member whose role cannot write takes no seat.
530
533
  *
534
+ * @param {{ timeout?: number }} [opts]
531
535
  * @returns {Promise<void>}
532
536
  */
533
- async claim() {
537
+ async claim({ timeout = 30000 } = {}) {
534
538
  this.guard()
535
539
  if (this.bee.writable) return
536
- const writer = this.writerKey
537
- const op = this.spec.dispatch.encode(`@${this.ns}/claim-writer`, {
538
- identity: this.identity.publicKey,
539
- writer,
540
- sig: this.identity.sign(ownership(this.key, writer)),
541
- ts: Date.now()
542
- })
543
- await this._optimistic(op)
540
+ const { role } = await this._member(timeout)
541
+ if (!can(role, WRITE)) return
542
+ const op = this.spec.dispatch.encode(`@${this.ns}/add-writer`, this._admission(this.writerKey))
543
+ // from a core not yet admitted: apply verifies the identity's signature and seats it
544
+ await this.bee.append(wrap(this.version, op), { optimistic: true })
545
+ await this.bee.update()
546
+ await this.whenWritable({ timeout })
544
547
  }
545
548
 
546
549
  /**
@@ -673,7 +676,6 @@ export class Database extends ReadyResource {
673
676
  if (this.behind === null || this.behind > this.version) return false
674
677
  await this.bee.local.setUserData('autobee/head', null)
675
678
  await this.bee.local.setUserData('cero/behind', null)
676
- if (this.network) this.network.detach(this.bee)
677
679
  await this.bee.close()
678
680
  this.behind = null
679
681
  return true
@@ -704,12 +706,17 @@ export class Database extends ReadyResource {
704
706
  async _apply(nodes, view, host) {
705
707
  const ready = []
706
708
  for (const node of nodes) {
707
- const { version, body } = unwrap(node.value)
708
- if (version > this.version) {
709
- this._onfuture(version)
709
+ const op = unwrap(node.value)
710
+ // bytes with no envelope, or a cut one, are no op: skipped and surfaced like any node that does not decode
711
+ if (!op) {
712
+ this._onerror(CeroError.INVALID('an op with no envelope'))
710
713
  continue
711
714
  }
712
- ready.push(version === 0 ? node : { ...node, value: body })
715
+ if (op.version > this.version) {
716
+ this._onfuture(op.version)
717
+ continue
718
+ }
719
+ ready.push({ ...node, value: op.body })
713
720
  }
714
721
  const result = await this.dispatcher.apply(ready, view, host)
715
722
  this._notify(ready)
@@ -733,7 +740,7 @@ export class Database extends ReadyResource {
733
740
  this._presence ??= this.network.presence.add(discoveryKey, { pinned: this.pinned })
734
741
  }
735
742
 
736
- // every writer the room ever had and every core its views read; only the system bee, an autobee
743
+ // every writer the database ever had and every core its views read; only the system bee, an autobee
737
744
  // internal, lists all the writers
738
745
  /** @private */
739
746
  async _holdRoom() {
@@ -743,7 +750,7 @@ export class Database extends ReadyResource {
743
750
  for await (const writer of bee.system.list()) this._hold(writer.key, writer.length)
744
751
  }
745
752
 
746
- // a view live, a writer only as far as the room applied it: past that a stranger could grow a
753
+ // a view live, a writer only as far as the database applied it: past that a stranger could grow a
747
754
  // core every member pulls. Inactive, so a new connection stays silent: the range only asks peers
748
755
  // already replicating the core
749
756
  /** @private */
@@ -830,7 +837,9 @@ export class Database extends ReadyResource {
830
837
  const ref = this._prepare(name, row)
831
838
  const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
832
839
  if (!upsert && !existing) return null
833
- const stored = stamp({ ...existing, ...row }, existing?.createdAt)
840
+ // a single is one record with no fields of Cero's
841
+ const merged = { ...existing, ...row }
842
+ const stored = ref.kind === SINGLE ? merged : stamp(merged, existing?.createdAt)
834
843
  checkRequired(name, this.refs[name], stored)
835
844
  if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
836
845
  const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
@@ -937,25 +946,28 @@ export class Database extends ReadyResource {
937
946
  return (await view.find(path, bounds).toArray()).length
938
947
  }
939
948
 
940
- // an append by a core not yet admitted: apply verifies the signature and admits it
941
- /** @private */
942
- async _optimistic(op, opts) {
943
- await this.bee.append(wrap(this.version, op), { optimistic: true })
944
- await this.bee.update()
945
- if (!this.bee.writable) await this.whenWritable(opts)
946
- }
947
-
948
- // the genesis device row is the first write of every database, so any device row means backfilled
949
+ // this identity's member row, looked up again on every update until one lands it
949
950
  /** @private */
950
- async _backfilled(timeout) {
951
- const deadline = Date.now() + timeout
952
- while (Date.now() < deadline) {
953
- if (this.closing || this.closed) throw CeroError.CLOSED('Database')
954
- if ((await this.get('devices')).data.length > 0) return
955
- await this.bee.update()
956
- await new Promise((resolve) => setTimeout(resolve, 50))
957
- }
958
- throw CeroError.TIMEOUT('recovery — no peer replicated')
951
+ _member(timeout) {
952
+ return new Promise((resolve, reject) => {
953
+ const done = (err, member) => {
954
+ clearTimeout(timer)
955
+ this.off('update', check)
956
+ this.off('close', onclose)
957
+ if (err) reject(err)
958
+ else resolve(member)
959
+ }
960
+ const check = () =>
961
+ this.get('members', this.identity.id).then(({ data }) => data && done(null, data), done)
962
+ const onclose = () => done(CeroError.CLOSED('Database'))
963
+ const timer =
964
+ timeout > 0
965
+ ? setTimeout(() => done(CeroError.TIMEOUT('waiting for the member row')), timeout)
966
+ : null
967
+ this.on('update', check)
968
+ this.once('close', onclose)
969
+ check()
970
+ })
959
971
  }
960
972
 
961
973
  // the add-writer row for `writer`, appended by this device and signed by the identity
@@ -207,7 +207,7 @@ export class Rotation {
207
207
  if (!can(me?.role, REMOVE)) return
208
208
 
209
209
  const rows = await this._epochs()
210
- // a room still on its creation key re-keys at its first removal
210
+ // a database still on its creation key re-keys at its first removal
211
211
  if (!rows.length) {
212
212
  if (await db.view.findOne(`@${db.ns}/removals`, {})) await this._heal('first removal')
213
213
  return