@cero-base/core 2.0.0 → 2.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -45,7 +45,7 @@ me.toPhrase() // back to words
45
45
 
46
46
  ## Storage
47
47
 
48
- Hyperbee or Rocks-backed local table store with a uniform put/set/get/del/count/watch surface.
48
+ Hyperbee or Rocks-backed local table store with a uniform put/set/get/del/watch surface.
49
49
 
50
50
  ```js
51
51
  import { Storage } from '@cero-base/core/storage'
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/core",
3
- "version": "2.0.0",
3
+ "version": "2.1.1",
4
4
  "description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
5
5
  "type": "module",
6
6
  "sideEffects": false,
@@ -139,7 +139,7 @@
139
139
  },
140
140
  "dependencies": {
141
141
  "@hyperswarm/secret-stream": "^6.9.1",
142
- "autobee": "^2.0.1",
142
+ "autobee": "^2.1.1",
143
143
  "autobee-encryption": "0.1.3",
144
144
  "b4a": "^1.8.1",
145
145
  "bare-crypto": "^1.15.3",
@@ -20,7 +20,7 @@ export function makeChanges(db, name, col, matches) {
20
20
  dirty = true
21
21
  if (wake !== null) wake()
22
22
  }
23
- const off = db.onUpdate(mark, name)
23
+ const off = db.onUpdate(name, mark)
24
24
 
25
25
  const stream = new Readable({
26
26
  async read(cb) {
@@ -1,4 +1,7 @@
1
1
  import b4a from 'b4a'
2
+ import c from 'compact-encoding'
3
+ import crypto from 'hypercore-crypto'
4
+ import z32 from 'z32'
2
5
  import hid from 'hypercore-id-encoding'
3
6
 
4
7
  import {
@@ -31,9 +34,24 @@ const isSig = (b) => b?.byteLength === 64
31
34
  * @param {(err: Error) => void} opts.onerror Called when a malformed node is skipped.
32
35
  * @param {() => Uint8Array | null} opts.key The database key, null until the bee booted.
33
36
  * @param {(row: { epoch: number, stamp: number, wrapped: Uint8Array, commit: Uint8Array }) => Promise<void>} opts.onepoch Per-peer side of an applied rotation (skipped in dry runs).
37
+ * @param {(phase: 'before' | 'after', op: string) => Function[]} [opts.hooks] Registered hooks for an op, run inside its transaction.
38
+ * @param {(name: string) => void} [opts.touch] Marks a ref written by a hook, so its watchers tick.
39
+ * @param {(view: object, name: string, query?: any) => Promise<any>} [opts.read] Planned read against a given view, for a hook's `ctx.get`.
40
+ * @param {(fn: Function) => Function} [opts.inHook] Wraps a route so operators called inside it throw, like a hook.
34
41
  * @returns {{ dispatch: (value: Buffer, ctx: object) => Promise<void>, apply: (nodes: Array<{ value: Buffer, key: Buffer }>, view: object, host: object) => Promise<void> }}
35
42
  */
36
- export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
43
+ export function makeDispatcher({
44
+ spec,
45
+ ns,
46
+ routes,
47
+ onerror,
48
+ key,
49
+ onepoch,
50
+ hooks,
51
+ touch,
52
+ read,
53
+ inHook = (fn) => fn
54
+ }) {
37
55
  const router = new spec.dispatch.Router()
38
56
 
39
57
  const countersCol = `@${ns}/${COUNTERS}`
@@ -72,11 +90,101 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
72
90
  await view.insert(col, op)
73
91
  }
74
92
 
75
- // a demoted member keeps its writer seat, so rows are gated by role. An unresolved signer
76
- // passes: optimistic admission applies a recovering device's ops before its add-writer
93
+ const pick = (op) => {
94
+ if (!hooks || !op) return null
95
+ const before = hooks('before', op)
96
+ const after = hooks('after', op)
97
+ return before.length || after.length ? { before, after } : null
98
+ }
99
+
100
+ const refName = (ref) => (typeof ref === 'string' ? ref : ref?.name)
101
+ const single = (name) => spec.meta?.refs?.[name]?.kind === SINGLE
102
+
103
+ // the operators developers know, bound to the open transaction and this op's stamps
104
+ function operators(view, memberId, ts, seed) {
105
+ let n = 0
106
+ // every peer must mint the same id: hash the applying op and a per-op counter
107
+ const mint = () => z32.encode(crypto.hash([seed, c.encode(c.uint, n++)]).subarray(0, 16))
108
+ const col = (name) => `@${ns}/${name}`
109
+ const current = (name, id) =>
110
+ single(name) ? view.findOne(col(name), {}) : view.get(col(name), { id })
111
+ const stamp = (row, was) => ({
112
+ ...was,
113
+ createdAt: was?.createdAt ?? ts,
114
+ ...row,
115
+ updatedAt: row.updatedAt ?? ts,
116
+ memberId
117
+ })
118
+ const store = (name, row) => {
119
+ touch?.(name)
120
+ return single(name) ? view.insert(col(name), row) : insert(view, name, col(name), row)
121
+ }
122
+ return {
123
+ get: (ref, query) => read(view, refName(ref), query),
124
+ put: (ref, row) => {
125
+ const name = refName(ref)
126
+ return store(name, stamp(single(name) ? row : { ...row, id: row.id ?? mint() }, null))
127
+ },
128
+ set: async (ref, row) => {
129
+ const name = refName(ref)
130
+ if (!single(name) && !row.id) throw CeroError.INVALID(`set('${name}') needs an id`)
131
+ return store(name, stamp(row, await current(name, row.id)))
132
+ },
133
+ del: (ref, id) => {
134
+ const name = refName(ref)
135
+ touch?.(name)
136
+ return view.delete(col(name), single(name) ? {} : { id })
137
+ }
138
+ }
139
+ }
140
+
141
+ // hooks run inside the op's transaction on every peer, so their verdict is part of the op
142
+ // a rule never meets a nameless writer: an admitted core with no member row is refused
143
+ // where a hook or route would have to judge it
144
+ async function signer(ctx) {
145
+ const memberId = await getSignerMember(ctx.view, ctx.key)
146
+ const role = memberId ? (await getMember(ctx.view, memberId))?.role : null
147
+ if (!memberId || !role) throw CeroError.REFUSED('member')
148
+ return { memberId, role }
149
+ }
150
+
151
+ async function hooked(fns, { op, name, id = null, row = null, existing = null }, ctx, write) {
152
+ if (!fns) return write(row)
153
+ const { memberId, role } = await signer(ctx)
154
+ // never a clock: a derived row must stamp the same timestamp on every peer
155
+ const ts = row?.updatedAt || existing?.updatedAt || 0
156
+ const hctx = {
157
+ op,
158
+ name,
159
+ row,
160
+ existing,
161
+ id,
162
+ memberId,
163
+ role,
164
+ ...operators(ctx.view, memberId, ts, ctx.seed)
165
+ }
166
+ await fire(fns.before, hctx, true)
167
+ await write(hctx.row)
168
+ await fire(fns.after, hctx, false)
169
+ }
170
+
171
+ // a rule that errors must not diverge peers: a throw refuses exactly like a false verdict
172
+ async function fire(fns, hctx, vote) {
173
+ for (const fn of fns) {
174
+ let verdict
175
+ try {
176
+ verdict = await fn(hctx)
177
+ } catch (err) {
178
+ throw CeroError.REFUSED('hook', err.message)
179
+ }
180
+ if (vote && verdict === false) throw CeroError.REFUSED('hook')
181
+ }
182
+ }
183
+
184
+ // a demoted member keeps its writer seat, so rows are gated by role; a writer with no
185
+ // member row is not a member and writes nothing
77
186
  const requireWrite = async (ctx) => {
78
- const r = await getSignerRole(ctx.view, ctx.key)
79
- if (r !== null && !can(r, WRITE)) throw CeroError.REFUSED('write')
187
+ if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
80
188
  }
81
189
 
82
190
  // own: the author may change their rows, anyone with REMOVE may moderate the rest
@@ -86,28 +194,40 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
86
194
  if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('own')
87
195
  }
88
196
 
89
- const upsert = (name, col, kind, own) => async (op, ctx) => {
197
+ const upsert = (name, col, kind, own, hook) => async (op, ctx) => {
90
198
  await requireWrite(ctx)
91
199
  const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
92
200
  op.memberId = d?.memberId || null
93
- if (kind !== COLLECTION) return ctx.view.insert(col, op)
201
+ const fns = pick(hook)
202
+ if (kind !== COLLECTION) {
203
+ const existing = fns ? await ctx.view.findOne(col, {}) : null
204
+ const meta = { op: hook, name, row: op, existing }
205
+ return hooked(fns, meta, ctx, (row) => ctx.view.insert(col, row))
206
+ }
207
+ const existing = own || fns ? await ctx.view.get(col, { id: op.id }) : null
94
208
  // add on an existing id is an overwrite, same ownership rule as set
95
- if (own) await requireOwn(ctx, await ctx.view.get(col, { id: op.id }))
96
- await insert(ctx.view, name, col, op)
209
+ if (own) await requireOwn(ctx, existing)
210
+ const meta = { op: hook, name, id: op.id, row: op, existing }
211
+ await hooked(fns, meta, ctx, (row) => insert(ctx.view, name, col, row))
97
212
  }
98
- const update = (name, col, own) => async (op, ctx) => {
213
+ const update = (name, col, own, hook) => async (op, ctx) => {
99
214
  await requireWrite(ctx)
100
215
  const existing = await ctx.view.get(col, { id: op.id })
101
216
  if (!existing) return
102
217
  if (own) await requireOwn(ctx, existing)
103
218
  // memberId is attribution: derived here, never merged off the wire
104
219
  const d = ctx.key && (await getDevice(ctx.view, hid.encode(ctx.key)))
105
- await insert(ctx.view, name, col, { ...existing, ...op, memberId: d?.memberId || null })
220
+ const merged = { ...existing, ...op, memberId: d?.memberId || null }
221
+ const meta = { op: hook, name, id: op.id, row: merged, existing }
222
+ await hooked(pick(hook), meta, ctx, (row) => insert(ctx.view, name, col, row))
106
223
  }
107
- const remove = (col, own) => async (op, ctx) => {
224
+ const remove = (name, col, own, hook) => async (op, ctx) => {
108
225
  await requireWrite(ctx)
109
- if (own) await requireOwn(ctx, await ctx.view.get(col, { id: op.id }))
110
- return ctx.view.delete(col, op)
226
+ const fns = pick(hook)
227
+ const existing = own || fns ? await ctx.view.get(col, { id: op.id }) : null
228
+ if (own) await requireOwn(ctx, existing)
229
+ const meta = { op: hook, name, id: op.id, existing }
230
+ return hooked(fns, meta, ctx, () => ctx.view.delete(col, op))
111
231
  }
112
232
  // only REFUSED aborts a batch: every peer derives it. Decode failures and unknown routes skip one node
113
233
  const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
@@ -122,12 +242,16 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
122
242
  if (!genesis && !can(inviter, INVITE)) throw CeroError.REFUSED('invite')
123
243
  // the rank is add-member's decision in the same transaction: a refused grant discards this admission.
124
244
  // Always an indexer: autobee gc's caught-up non-indexer sessions and they miss later appends
245
+ // a writer belongs to a member: its own identity, or the member named by the op
246
+ const memberId = op.memberId || hid.encode(op.master)
247
+ if (op.memberId && !(await getMember(ctx.view, op.memberId))) {
248
+ throw CeroError.REFUSED('member')
249
+ }
125
250
  await ctx.host.addWriter(op.writer, { isIndexer: true })
126
251
  const ts = op.ts || 0
127
252
  await insert(ctx.view, 'devices', `@${ns}/devices`, {
128
253
  id: hid.encode(op.writer),
129
- // a member row that never lands must resolve to nobody, not to the inviter
130
- memberId: op.memberId || hid.encode(op.master),
254
+ memberId,
131
255
  createdAt: ts,
132
256
  updatedAt: ts
133
257
  })
@@ -306,10 +430,8 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
306
430
  if (await ctx.view.get(invites, { id: op.id })) throw CeroError.REFUSED('invite')
307
431
  await insert(ctx.view, 'invites', invites, op)
308
432
  })
309
- // like requireWrite, a signer with no resolvable role yet is not refused
310
433
  const moderate = async (ctx) => {
311
- const r = await getSignerRole(ctx.view, ctx.key)
312
- if (r !== null && !can(r, REMOVE)) throw CeroError.REFUSED('invite')
434
+ if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('invite')
313
435
  }
314
436
  add('set-invite', async (op, ctx) => {
315
437
  await moderate(ctx)
@@ -322,9 +444,7 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
322
444
  const existing = await ctx.view.get(invites, { id: op.id })
323
445
  const consume = existing && existing.reuse !== true
324
446
  const r = await getSignerRole(ctx.view, ctx.key)
325
- if (r !== null && !can(r, REMOVE) && !(consume && can(r, INVITE))) {
326
- throw CeroError.REFUSED('invite')
327
- }
447
+ if (!can(r, REMOVE) && !(consume && can(r, INVITE))) throw CeroError.REFUSED('invite')
328
448
  return ctx.view.delete(invites, op)
329
449
  })
330
450
 
@@ -340,37 +460,54 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
340
460
  })
341
461
  })
342
462
  add('set-file', update('files', files))
343
- add('del-file', remove(files))
463
+ add('del-file', remove('files', files))
344
464
 
345
465
  const handles = `@${ns}/handles`
346
466
  add('add-handle', upsert('handles', handles, COLLECTION))
347
467
  add('set-handle', update('handles', handles))
348
- add('del-handle', remove(handles))
468
+ add('del-handle', remove('handles', handles))
349
469
 
350
470
  for (const [name, info] of Object.entries(spec.meta?.refs || {})) {
351
471
  if (info.internal) continue
352
472
  if (info.kind === 'handle') continue
353
473
  if (info.kind === ACTION) {
474
+ const route = routes[name]
354
475
  // an action with no local route diverges this peer from those that ran it: surface it
355
- add(
356
- name,
357
- routes[name] ||
358
- (async () => {
359
- onerror(CeroError.UNKNOWN('route', name))
360
- })
361
- )
476
+ if (!route) {
477
+ add(name, async () => onerror(CeroError.UNKNOWN('route', name)))
478
+ continue
479
+ }
480
+ // a route is a hook with no row: the same ctx, the same refusal semantics
481
+ add(name, async (op, ctx) => {
482
+ const { memberId, role } = await signer(ctx)
483
+ const hctx = {
484
+ op: name,
485
+ name,
486
+ row: op,
487
+ memberId,
488
+ role,
489
+ ...operators(ctx.view, memberId, op.updatedAt || op.ts || 0, ctx.seed)
490
+ }
491
+ await fire([inHook(route)], hctx, true)
492
+ })
362
493
  continue
363
494
  }
364
495
  const col = `@${ns}/${name}`
365
496
  const kind = info.kind === SINGLE ? SINGLE : COLLECTION
366
- add(`set-${name}`, kind === SINGLE ? upsert(name, col, kind) : update(name, col, info.own))
497
+ const set =
498
+ kind === SINGLE ? upsert(name, col, kind, false, 'set') : update(name, col, info.own, 'set')
499
+ add(`set-${name}`, set)
367
500
  if (info.kind === SINGLE) {
368
501
  // wipe the keyless single row (the dummy id in the op is ignored)
369
- add(`del-${name}`, async (op, ctx) => ctx.view.delete(col, {}))
502
+ add(`del-${name}`, async (op, ctx) => {
503
+ const fns = pick('del')
504
+ const existing = fns ? await ctx.view.findOne(col, {}) : null
505
+ return hooked(fns, { op: 'del', name, existing }, ctx, () => ctx.view.delete(col, {}))
506
+ })
370
507
  continue
371
508
  }
372
- add(`add-${name}`, upsert(name, col, COLLECTION, info.own))
373
- add(`del-${name}`, remove(col, info.own))
509
+ add(`add-${name}`, upsert(name, col, COLLECTION, info.own, 'put'))
510
+ add(`del-${name}`, remove(name, col, info.own, 'del'))
374
511
  }
375
512
 
376
513
  return {
@@ -387,7 +524,14 @@ export function makeDispatcher({ spec, ns, routes, onerror, key, onepoch }) {
387
524
  let refusal = null
388
525
  for (const node of nodes) {
389
526
  try {
390
- await router.dispatch(node.value, { view: tx, host: deferred, key: node.key, dbKey })
527
+ const seed = crypto.hash([node.key, node.value])
528
+ await router.dispatch(node.value, {
529
+ view: tx,
530
+ host: deferred,
531
+ key: node.key,
532
+ dbKey,
533
+ seed
534
+ })
391
535
  } catch (err) {
392
536
  // anything but a refusal skips one node, so an older peer never drops a batch its newer neighbour applies
393
537
  if (!isRefusal(err)) {