@cero-base/core 1.16.1 → 1.17.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/package.json +2 -2
- package/src/database/dispatch.js +69 -35
- package/src/database/index.js +26 -7
- package/src/lib/errors.js +12 -0
- package/types/database/index.d.ts +2 -1
- package/types/lib/errors.d.ts +10 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cero-base/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.17.0",
|
|
4
4
|
"description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -136,7 +136,7 @@
|
|
|
136
136
|
},
|
|
137
137
|
"dependencies": {
|
|
138
138
|
"@hyperswarm/secret-stream": "^6.9.1",
|
|
139
|
-
"autobee": "2.0.0-rc.
|
|
139
|
+
"autobee": "^2.0.0-rc.29",
|
|
140
140
|
"autobee-encryption": "0.1.3",
|
|
141
141
|
"b4a": "^1.8.1",
|
|
142
142
|
"bare-crypto": "^1.15.3",
|
package/src/database/dispatch.js
CHANGED
|
@@ -96,9 +96,6 @@ export function makeDispatcher(
|
|
|
96
96
|
await view.insert(col, op)
|
|
97
97
|
}
|
|
98
98
|
|
|
99
|
-
// Being an admitted writer is not a licence to write rows: a demoted member
|
|
100
|
-
// keeps its writer seat, and an unenrolled one resolves to no role at all.
|
|
101
|
-
// Genesis is exempt — the room has no members to check against yet.
|
|
102
99
|
// Being an admitted writer is not a licence to write rows: a member demoted
|
|
103
100
|
// to reader keeps its writer seat (set-member does not revoke it), and would
|
|
104
101
|
// otherwise keep writing every collection.
|
|
@@ -107,45 +104,50 @@ export function makeDispatcher(
|
|
|
107
104
|
// optimistic, so a recovering device's first ops can apply before its own
|
|
108
105
|
// add-writer has been adopted in this view, and refusing those would drop
|
|
109
106
|
// them permanently. Being an admitted writer is the gate in that window.
|
|
110
|
-
const
|
|
107
|
+
const requireWrite = async (ctx) => {
|
|
111
108
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
112
|
-
|
|
109
|
+
if (r !== null && !can(r, WRITE)) throw CeroError.REFUSED('write')
|
|
113
110
|
}
|
|
114
111
|
|
|
115
112
|
// Every row records the member who wrote it, so ownership is already known —
|
|
116
113
|
// an `own` collection just enforces it: the author may change their own rows,
|
|
117
114
|
// and anyone who can REMOVE may moderate the rest.
|
|
118
|
-
const
|
|
119
|
-
if (
|
|
120
|
-
if (existing.memberId === (await getSignerMember(ctx.view, ctx.key))) return
|
|
121
|
-
|
|
115
|
+
const requireOwn = async (ctx, existing) => {
|
|
116
|
+
if (existing?.memberId == null) return
|
|
117
|
+
if (existing.memberId === (await getSignerMember(ctx.view, ctx.key))) return
|
|
118
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE)) throw CeroError.REFUSED('own')
|
|
122
119
|
}
|
|
123
120
|
|
|
124
121
|
const upsert = (name, col, kind, own) => async (op, ctx) => {
|
|
125
|
-
|
|
122
|
+
await requireWrite(ctx)
|
|
126
123
|
const d = ctx.key && (await getDevice(ctx.view, toId(ctx.key)))
|
|
127
124
|
op.memberId = d?.memberId || null
|
|
128
125
|
if (kind !== COLLECTION) return ctx.view.insert(col, op)
|
|
129
126
|
// `add` on an id that already exists is an overwrite, so it answers to the
|
|
130
127
|
// same ownership rule as `set`
|
|
131
|
-
if (own
|
|
128
|
+
if (own) await requireOwn(ctx, await ctx.view.get(col, { id: op.id }))
|
|
132
129
|
await insert(ctx.view, name, col, op)
|
|
133
130
|
}
|
|
134
131
|
const update = (name, col, own) => async (op, ctx) => {
|
|
135
|
-
|
|
132
|
+
await requireWrite(ctx)
|
|
136
133
|
const existing = await ctx.view.get(col, { id: op.id })
|
|
137
134
|
if (!existing) return
|
|
138
|
-
if (
|
|
135
|
+
if (own) await requireOwn(ctx, existing)
|
|
139
136
|
// memberId is attribution, so it is derived here and never merged off the
|
|
140
137
|
// wire — otherwise an edit could leave the row credited to its victim
|
|
141
138
|
const d = ctx.key && (await getDevice(ctx.view, toId(ctx.key)))
|
|
142
139
|
await insert(ctx.view, name, col, { ...existing, ...op, memberId: d?.memberId || null })
|
|
143
140
|
}
|
|
144
141
|
const remove = (col, own) => async (op, ctx) => {
|
|
145
|
-
|
|
146
|
-
if (own
|
|
142
|
+
await requireWrite(ctx)
|
|
143
|
+
if (own) await requireOwn(ctx, await ctx.view.get(col, { id: op.id }))
|
|
147
144
|
return ctx.view.delete(col, op)
|
|
148
145
|
}
|
|
146
|
+
// Only a REFUSED verdict may abort a batch: it is derived from the node and
|
|
147
|
+
// the view alone, so every peer reaches it. Decode failures and unknown routes
|
|
148
|
+
// must not — an older peer would drop a batch its newer neighbour applies.
|
|
149
|
+
const isRefusal = (err) => err?.isCeroError === true && err.code === 'REFUSED'
|
|
150
|
+
|
|
149
151
|
const add = (verb, fn) => dispatcher.add(`@${ns}/${verb}`, fn)
|
|
150
152
|
|
|
151
153
|
add('add-writer', async (op, ctx) => {
|
|
@@ -153,13 +155,9 @@ export function makeDispatcher(
|
|
|
153
155
|
if (!Identity.verify(op.master, addWriterPayload(ctx.dbKey, op.writer, ctx.key), op.sig)) return
|
|
154
156
|
const genesis = await isGenesis(ctx.view)
|
|
155
157
|
const inviter = await getRole(ctx.view, op.master)
|
|
156
|
-
if (!genesis && !can(inviter, INVITE))
|
|
157
|
-
//
|
|
158
|
-
//
|
|
159
|
-
// that resolves, through its device row, to the inviter's own authority.
|
|
160
|
-
// Genesis is exempt for the same reason the INVITE check is — the room has
|
|
161
|
-
// no members yet to grant from.
|
|
162
|
-
if (!genesis && op.role && !grants(inviter, op.role)) return
|
|
158
|
+
if (!genesis && !can(inviter, INVITE)) throw CeroError.REFUSED('invite')
|
|
159
|
+
// the rank is add-member's decision, made in the same transaction: a grant
|
|
160
|
+
// it refuses discards this admission with it, host call included
|
|
163
161
|
// always an indexer, like claim-writer below. The op's optional isIndexer
|
|
164
162
|
// bool decodes to false when absent (nothing sets it), which silently made
|
|
165
163
|
// every device a weight-1 writer — autobee 2.0 gc's caught-up non-indexer
|
|
@@ -180,7 +178,9 @@ export function makeDispatcher(
|
|
|
180
178
|
if (!isKey(op.writer)) return
|
|
181
179
|
const target = await getDevice(ctx.view, toId(op.writer))
|
|
182
180
|
if (target?.memberId !== (await getSignerMember(ctx.view, ctx.key))) {
|
|
183
|
-
if (!(await canRemoveMember(ctx.view, ctx.key, target?.memberId)))
|
|
181
|
+
if (!(await canRemoveMember(ctx.view, ctx.key, target?.memberId))) {
|
|
182
|
+
throw CeroError.REFUSED('remove')
|
|
183
|
+
}
|
|
184
184
|
}
|
|
185
185
|
await ctx.host.removeWriter(op.writer)
|
|
186
186
|
await ctx.view.delete(`@${ns}/devices`, { id: toId(op.writer) })
|
|
@@ -189,9 +189,11 @@ export function makeDispatcher(
|
|
|
189
189
|
add('claim-writer', async (op, ctx) => {
|
|
190
190
|
if (!isKey(op.identity) || !isKey(op.writer) || !isSig(op.sig)) return
|
|
191
191
|
if (!Identity.verify(op.identity, claimWriterPayload(ctx.dbKey, op.writer), op.sig)) return
|
|
192
|
+
// a claim is only meaningful from the claiming core — from any other it is
|
|
193
|
+
// inapplicable, not refused, so it must not abort that writer's batch
|
|
192
194
|
if (!b4a.equals(ctx.key, op.writer)) return
|
|
193
195
|
const memberId = toId(op.identity)
|
|
194
|
-
if (!can(await getRole(ctx.view, op.identity), WRITE))
|
|
196
|
+
if (!can(await getRole(ctx.view, op.identity), WRITE)) throw CeroError.REFUSED('write')
|
|
195
197
|
await ctx.host.addWriter(op.writer, { isIndexer: true })
|
|
196
198
|
const ts = op.ts || 0
|
|
197
199
|
await insert(ctx.view, 'devices', `@${ns}/devices`, {
|
|
@@ -206,7 +208,7 @@ export function makeDispatcher(
|
|
|
206
208
|
if (!isKey(op.key)) return
|
|
207
209
|
if (!(await isGenesis(ctx.view))) {
|
|
208
210
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
209
|
-
if (!can(r, INVITE) || !grants(r, op.role))
|
|
211
|
+
if (!can(r, INVITE) || !grants(r, op.role)) throw CeroError.REFUSED('invite')
|
|
210
212
|
}
|
|
211
213
|
await insert(ctx.view, 'members', `@${ns}/members`, op)
|
|
212
214
|
const deviceId = toId(op.key)
|
|
@@ -240,9 +242,10 @@ export function makeDispatcher(
|
|
|
240
242
|
|
|
241
243
|
if (op.role && op.role !== existing.role) {
|
|
242
244
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
243
|
-
if (can(r, ASSIGN) && grants(r, op.role) && outranks(r, existing.role)) {
|
|
244
|
-
|
|
245
|
+
if (!(can(r, ASSIGN) && grants(r, op.role) && outranks(r, existing.role))) {
|
|
246
|
+
throw CeroError.REFUSED('assign')
|
|
245
247
|
}
|
|
248
|
+
next.role = op.role
|
|
246
249
|
}
|
|
247
250
|
await insert(ctx.view, 'members', `@${ns}/members`, next)
|
|
248
251
|
// a demotion that takes WRITE away must take the writer seat with it —
|
|
@@ -265,7 +268,7 @@ export function makeDispatcher(
|
|
|
265
268
|
if (!existing) return
|
|
266
269
|
if (op.id !== (await getSignerMember(ctx.view, ctx.key))) {
|
|
267
270
|
const r = await getSignerRole(ctx.view, ctx.key)
|
|
268
|
-
if (!can(r, REMOVE) || !outranks(r, existing.role))
|
|
271
|
+
if (!can(r, REMOVE) || !outranks(r, existing.role)) throw CeroError.REFUSED('remove')
|
|
269
272
|
}
|
|
270
273
|
if (existing.key) await ctx.host.removeWriter(existing.key)
|
|
271
274
|
// every device of the member goes with them — a removed member must not
|
|
@@ -292,7 +295,8 @@ export function makeDispatcher(
|
|
|
292
295
|
// reorder epochs freely without ever changing which key a block header
|
|
293
296
|
// points at. Uniqueness is enforced here, deterministically.
|
|
294
297
|
if (!Number.isInteger(op.stamp) || op.stamp <= 0 || op.stamp > 0xffffffff) return
|
|
295
|
-
if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE))
|
|
298
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), REMOVE))
|
|
299
|
+
throw CeroError.REFUSED('rotate', 'rotate requires the remove permission')
|
|
296
300
|
const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
|
|
297
301
|
if (rows.some((r) => r.stamp === op.stamp)) return
|
|
298
302
|
// sequence numbers order epochs; concurrent rotations linearize as
|
|
@@ -329,7 +333,9 @@ export function makeDispatcher(
|
|
|
329
333
|
const existing = await getDevice(ctx.view, op.id)
|
|
330
334
|
if (!existing) return
|
|
331
335
|
if (existing.memberId !== (await getSignerMember(ctx.view, ctx.key))) {
|
|
332
|
-
if (!(await canRemoveMember(ctx.view, ctx.key, existing.memberId)))
|
|
336
|
+
if (!(await canRemoveMember(ctx.view, ctx.key, existing.memberId))) {
|
|
337
|
+
throw CeroError.REFUSED('remove')
|
|
338
|
+
}
|
|
333
339
|
}
|
|
334
340
|
await ctx.host.removeWriter(toKey(existing.id))
|
|
335
341
|
await ctx.view.delete(`@${ns}/devices`, op)
|
|
@@ -365,7 +371,7 @@ export function makeDispatcher(
|
|
|
365
371
|
}
|
|
366
372
|
if (b.verb === 'file') {
|
|
367
373
|
add('add-file', async (op, ctx) => {
|
|
368
|
-
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE))
|
|
374
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
|
|
369
375
|
const memberId = await getSignerMember(ctx.view, ctx.key)
|
|
370
376
|
await insert(ctx.view, b.name, col, {
|
|
371
377
|
id: op.id,
|
|
@@ -412,15 +418,43 @@ export function makeDispatcher(
|
|
|
412
418
|
dispatcher,
|
|
413
419
|
async apply(nodes, view, host) {
|
|
414
420
|
const dbKey = getDbKey()
|
|
421
|
+
// Nodes land in a transaction this loop owns, so a refusal can discard the
|
|
422
|
+
// whole batch — a batch is one writer's contiguous run (autobee keys it on
|
|
423
|
+
// batch[0].key), so an abort only ever drops the offending writer's ops.
|
|
424
|
+
const tx = view.transaction()
|
|
425
|
+
// Admitting or removing a writer is a host call, not a row — it would
|
|
426
|
+
// survive a discarded transaction and leave a writer with no device row,
|
|
427
|
+
// which the WRITE gate reads as "not yet enrolled". So host calls are
|
|
428
|
+
// recorded and replayed only once the batch is known to commit.
|
|
429
|
+
const calls = []
|
|
430
|
+
const deferred = Object.create(host)
|
|
431
|
+
deferred.addWriter = (...args) => void calls.push(['addWriter', args])
|
|
432
|
+
deferred.removeWriter = (...args) => void calls.push(['removeWriter', args])
|
|
433
|
+
let refusal = null
|
|
415
434
|
for (const node of nodes) {
|
|
416
435
|
try {
|
|
417
|
-
await dispatcher.dispatch(node.value, { view, host, key: node.key, dbKey })
|
|
436
|
+
await dispatcher.dispatch(node.value, { view: tx, host: deferred, key: node.key, dbKey })
|
|
418
437
|
} catch (err) {
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
|
|
438
|
+
// A refusal is the verdict every peer reaches from the same node and
|
|
439
|
+
// the same view, so discarding the batch keeps them convergent — and
|
|
440
|
+
// the batch is one writer's own run. Anything else (undecodable bytes,
|
|
441
|
+
// a route this version lacks) skips a single node instead: an older
|
|
442
|
+
// peer must not drop a batch its newer neighbour applies.
|
|
443
|
+
if (!isRefusal(err)) {
|
|
444
|
+
onerror(err)
|
|
445
|
+
continue
|
|
446
|
+
}
|
|
447
|
+
refusal = err
|
|
448
|
+
break
|
|
422
449
|
}
|
|
423
450
|
}
|
|
451
|
+
if (refusal) {
|
|
452
|
+
await tx.close()
|
|
453
|
+
onerror(refusal)
|
|
454
|
+
} else {
|
|
455
|
+
await tx.flush()
|
|
456
|
+
for (const [fn, args] of calls) await host[fn](...args)
|
|
457
|
+
}
|
|
424
458
|
await view.flush()
|
|
425
459
|
}
|
|
426
460
|
}
|
package/src/database/index.js
CHANGED
|
@@ -652,7 +652,9 @@ export class Database extends ReadyResource {
|
|
|
652
652
|
this._rotation = null
|
|
653
653
|
return this.rotate(true)
|
|
654
654
|
}
|
|
655
|
-
|
|
655
|
+
// permission is refused before the append now, so reaching this means
|
|
656
|
+
// the op applied as a no-op for a reason the dry-run could not foresee
|
|
657
|
+
throw CeroError.INVALID('rotation was not applied')
|
|
656
658
|
}
|
|
657
659
|
// Invariant check, not an assumption: no block appended during this
|
|
658
660
|
// rotation may carry the stamp it announces — that would make the
|
|
@@ -840,19 +842,29 @@ export class Database extends ReadyResource {
|
|
|
840
842
|
for (const op of ops) this.txQueue.push(op)
|
|
841
843
|
return
|
|
842
844
|
}
|
|
843
|
-
|
|
845
|
+
// `closing` flips the moment close() starts; `bee` only goes null once it
|
|
846
|
+
// has finished, and everything in between is a torn-down bee behind a
|
|
847
|
+
// truthy flag
|
|
848
|
+
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
844
849
|
if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
|
|
845
850
|
const encoded = ops.map(([op, payload]) =>
|
|
846
851
|
this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
|
|
847
852
|
)
|
|
853
|
+
// the dry-run rejects what apply would refuse, and says whether the ops
|
|
854
|
+
// change anything at all — one that touches nothing never reaches the log.
|
|
855
|
+
// An action is the exception: what it does lives in the routes of every
|
|
856
|
+
// peer, not in the rows this dry-run can see, so it always ships.
|
|
857
|
+
const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
|
|
858
|
+
let changes
|
|
848
859
|
try {
|
|
849
|
-
await this._dryRun(encoded)
|
|
860
|
+
changes = await this._dryRun(encoded)
|
|
850
861
|
} catch (err) {
|
|
851
|
-
if (
|
|
862
|
+
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
852
863
|
throw err
|
|
853
864
|
}
|
|
854
|
-
// the dry-run awaits —
|
|
855
|
-
if (
|
|
865
|
+
// the dry-run awaits — close can start underneath it
|
|
866
|
+
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
867
|
+
if (!changes && !action) return
|
|
856
868
|
const wrapped = encoded.map((value) => wrap(this.version, value))
|
|
857
869
|
await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
|
|
858
870
|
}
|
|
@@ -879,6 +891,7 @@ export class Database extends ReadyResource {
|
|
|
879
891
|
* linearization time.
|
|
880
892
|
*
|
|
881
893
|
* @param {Uint8Array[]} encoded
|
|
894
|
+
* @returns {Promise<boolean>} whether the ops change anything
|
|
882
895
|
*/
|
|
883
896
|
async _dryRun(encoded) {
|
|
884
897
|
const tx = this.view.transaction()
|
|
@@ -893,8 +906,14 @@ export class Database extends ReadyResource {
|
|
|
893
906
|
dryRun: true
|
|
894
907
|
})
|
|
895
908
|
}
|
|
909
|
+
return tx.updated()
|
|
896
910
|
} finally {
|
|
897
|
-
|
|
911
|
+
// a failing close must not mask the handler's own rejection
|
|
912
|
+
try {
|
|
913
|
+
await tx.close()
|
|
914
|
+
} catch (err) {
|
|
915
|
+
safetyCatch(err)
|
|
916
|
+
}
|
|
898
917
|
}
|
|
899
918
|
}
|
|
900
919
|
|
package/src/lib/errors.js
CHANGED
|
@@ -147,6 +147,18 @@ export class CeroError extends Error {
|
|
|
147
147
|
static DENIED(reason = null, msg = 'pairing denied') {
|
|
148
148
|
return new CeroError('DENIED', msg, { reason })
|
|
149
149
|
}
|
|
150
|
+
/**
|
|
151
|
+
* An apply-time rule refused the op. Every peer reaches this verdict from the
|
|
152
|
+
* same node and the same view, so it aborts the writer's whole batch — which
|
|
153
|
+
* is what makes a transaction atomic. Reserve it for deterministic decisions:
|
|
154
|
+
* anything that could differ between peers must not abort, or they fork.
|
|
155
|
+
*
|
|
156
|
+
* @param {string} rule Which rule refused, e.g. 'write' or 'own'.
|
|
157
|
+
* @param {string} [msg]
|
|
158
|
+
*/
|
|
159
|
+
static REFUSED(rule, msg = `refused by ${rule}`) {
|
|
160
|
+
return new CeroError('REFUSED', msg, { rule })
|
|
161
|
+
}
|
|
150
162
|
/**
|
|
151
163
|
* Pairing handshake did not complete in time.
|
|
152
164
|
*
|
|
@@ -297,8 +297,9 @@ export class Database extends ReadyResource {
|
|
|
297
297
|
* linearization time.
|
|
298
298
|
*
|
|
299
299
|
* @param {Uint8Array[]} encoded
|
|
300
|
+
* @returns {Promise<boolean>} whether the ops change anything
|
|
300
301
|
*/
|
|
301
|
-
_dryRun(encoded: Uint8Array[]): Promise<
|
|
302
|
+
_dryRun(encoded: Uint8Array[]): Promise<boolean>;
|
|
302
303
|
/**
|
|
303
304
|
* Read a row. With no `query`: list all (collection) or fetch the one
|
|
304
305
|
* record (single). With a string id: fetch that specific row.
|
package/types/lib/errors.d.ts
CHANGED
|
@@ -98,6 +98,16 @@ export class CeroError extends Error {
|
|
|
98
98
|
* @param {string} [msg]
|
|
99
99
|
*/
|
|
100
100
|
static DENIED(reason?: string | null, msg?: string): CeroError;
|
|
101
|
+
/**
|
|
102
|
+
* An apply-time rule refused the op. Every peer reaches this verdict from the
|
|
103
|
+
* same node and the same view, so it aborts the writer's whole batch — which
|
|
104
|
+
* is what makes a transaction atomic. Reserve it for deterministic decisions:
|
|
105
|
+
* anything that could differ between peers must not abort, or they fork.
|
|
106
|
+
*
|
|
107
|
+
* @param {string} rule Which rule refused, e.g. 'write' or 'own'.
|
|
108
|
+
* @param {string} [msg]
|
|
109
|
+
*/
|
|
110
|
+
static REFUSED(rule: string, msg?: string): CeroError;
|
|
101
111
|
/**
|
|
102
112
|
* Pairing handshake did not complete in time.
|
|
103
113
|
*
|