@cero-base/core 1.16.1 → 1.18.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 +10 -9
- package/src/blobs/codec.js +2 -1
- package/src/database/dispatch.js +109 -35
- package/src/database/encryption.js +5 -3
- package/src/database/hooks.js +112 -0
- package/src/database/index.js +86 -463
- package/src/database/membership.js +67 -0
- package/src/database/rotation.js +228 -0
- package/src/lib/errors.js +12 -0
- package/src/lib/utils.js +19 -6
- package/src/network/index.js +68 -2
- package/src/pairing/index.js +3 -3
- package/src/pairing/invite.js +4 -2
- package/src/storage/index.js +12 -6
- package/types/database/encryption.d.ts +1 -1
- package/types/database/hooks.d.ts +8 -0
- package/types/database/index.d.ts +10 -57
- package/types/database/membership.d.ts +7 -0
- package/types/database/rotation.d.ts +32 -0
- package/types/lib/errors.d.ts +10 -0
- package/types/lib/utils.d.ts +6 -7
- package/types/network/index.d.ts +19 -0
- package/types/pairing/index.d.ts +1 -1
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cero-base/core",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.18.0",
|
|
4
4
|
"description": "cero p2p primitives — identity, storage, network, database, blobs, rpc, pairing.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -136,15 +136,15 @@
|
|
|
136
136
|
},
|
|
137
137
|
"dependencies": {
|
|
138
138
|
"@hyperswarm/secret-stream": "^6.9.1",
|
|
139
|
-
"autobee": "2.0.0
|
|
139
|
+
"autobee": "^2.0.0",
|
|
140
140
|
"autobee-encryption": "0.1.3",
|
|
141
141
|
"b4a": "^1.8.1",
|
|
142
142
|
"bare-crypto": "^1.15.3",
|
|
143
143
|
"bare-fs": "^4.8.1",
|
|
144
|
-
"bare-path": "^3.1.
|
|
144
|
+
"bare-path": "^3.1.2",
|
|
145
145
|
"bip39-mnemonic": "^2.5.0",
|
|
146
146
|
"blind-pairing": "^2.3.1",
|
|
147
|
-
"blind-peering": "^2.
|
|
147
|
+
"blind-peering": "^2.7.0",
|
|
148
148
|
"compact-encoding": "^3.3.2",
|
|
149
149
|
"corestore": "^7.12.2",
|
|
150
150
|
"framed-stream": "^1.0.1",
|
|
@@ -157,9 +157,10 @@
|
|
|
157
157
|
"hypercore-storage": "^3.2.1",
|
|
158
158
|
"hyperdb": "^6.9.0",
|
|
159
159
|
"hyperdispatch": "^1.6.0",
|
|
160
|
-
"hyperschema": "^1.
|
|
160
|
+
"hyperschema": "^1.23.0",
|
|
161
161
|
"hyperswarm": "^4.17.0",
|
|
162
162
|
"keet-identity-key": "^3.2.0",
|
|
163
|
+
"protomux": "^3.11.0",
|
|
163
164
|
"protomux-wakeup": "^2.9.0",
|
|
164
165
|
"ready-resource": "^1.2.0",
|
|
165
166
|
"safety-catch": "^1.0.3",
|
|
@@ -171,11 +172,11 @@
|
|
|
171
172
|
"@hyperswarm/testnet": "^3.1.4",
|
|
172
173
|
"bare-abort-controller": "^1.1.2",
|
|
173
174
|
"bare-events": "^2.9.2",
|
|
174
|
-
"bare-fetch": "^3.2.
|
|
175
|
+
"bare-fetch": "^3.2.1",
|
|
175
176
|
"bare-process": "^4.5.1",
|
|
176
|
-
"bare-url": "^2.5.
|
|
177
|
-
"blind-peer": "^3.14.
|
|
178
|
-
"brittle": "^4.1.
|
|
177
|
+
"bare-url": "^2.5.4",
|
|
178
|
+
"blind-peer": "^3.14.1",
|
|
179
|
+
"brittle": "^4.1.1",
|
|
179
180
|
"typescript": "^5.9.3",
|
|
180
181
|
"which-runtime": "^1.4.0"
|
|
181
182
|
},
|
package/src/blobs/codec.js
CHANGED
|
@@ -33,8 +33,9 @@ export function encodeId(coreKey, blobId, type) {
|
|
|
33
33
|
* @returns {{ coreKey: Uint8Array, blobId: RawBlobId, type: string }}
|
|
34
34
|
*/
|
|
35
35
|
export function decodeId(id) {
|
|
36
|
-
if (typeof id !== 'string' || id.length === 0)
|
|
36
|
+
if (typeof id !== 'string' || id.length === 0) {
|
|
37
37
|
throw CeroError.INVALID('id must be a non-empty string')
|
|
38
|
+
}
|
|
38
39
|
let buf
|
|
39
40
|
try {
|
|
40
41
|
buf = z32.decode(id)
|
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,9 @@ 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')
|
|
300
|
+
}
|
|
296
301
|
const rows = await ctx.view.find(`@${ns}/${EPOCHS}`, {}).toArray()
|
|
297
302
|
if (rows.some((r) => r.stamp === op.stamp)) return
|
|
298
303
|
// sequence numbers order epochs; concurrent rotations linearize as
|
|
@@ -329,7 +334,9 @@ export function makeDispatcher(
|
|
|
329
334
|
const existing = await getDevice(ctx.view, op.id)
|
|
330
335
|
if (!existing) return
|
|
331
336
|
if (existing.memberId !== (await getSignerMember(ctx.view, ctx.key))) {
|
|
332
|
-
if (!(await canRemoveMember(ctx.view, ctx.key, existing.memberId)))
|
|
337
|
+
if (!(await canRemoveMember(ctx.view, ctx.key, existing.memberId))) {
|
|
338
|
+
throw CeroError.REFUSED('remove')
|
|
339
|
+
}
|
|
333
340
|
}
|
|
334
341
|
await ctx.host.removeWriter(toKey(existing.id))
|
|
335
342
|
await ctx.view.delete(`@${ns}/devices`, op)
|
|
@@ -363,9 +370,46 @@ export function makeDispatcher(
|
|
|
363
370
|
})
|
|
364
371
|
continue
|
|
365
372
|
}
|
|
373
|
+
if (b.verb === 'invite') {
|
|
374
|
+
// Invite rows are served by every replica, so they are shared state with
|
|
375
|
+
// teeth. Any WRITE member may mint one — the rank it can grant is capped
|
|
376
|
+
// at admission — but an existing row is never overwritten (that only
|
|
377
|
+
// breaks the invite for everyone), and altering or revoking one is a
|
|
378
|
+
// moderation act: it needs REMOVE.
|
|
379
|
+
add(`add-${b.verb}`, async (op, ctx) => {
|
|
380
|
+
await requireWrite(ctx)
|
|
381
|
+
if (await ctx.view.get(col, { id: op.id })) throw CeroError.REFUSED('invite')
|
|
382
|
+
await insert(ctx.view, b.name, col, op)
|
|
383
|
+
})
|
|
384
|
+
// like requireWrite, a signer with no resolvable role yet (genesis, or
|
|
385
|
+
// the optimistic-admission window) is not refused
|
|
386
|
+
const moderate = async (ctx) => {
|
|
387
|
+
const r = await getSignerRole(ctx.view, ctx.key)
|
|
388
|
+
if (r !== null && !can(r, REMOVE)) throw CeroError.REFUSED('invite')
|
|
389
|
+
}
|
|
390
|
+
add(`set-${b.verb}`, async (op, ctx) => {
|
|
391
|
+
await moderate(ctx)
|
|
392
|
+
const existing = await ctx.view.get(col, { id: op.id })
|
|
393
|
+
if (!existing) return
|
|
394
|
+
await insert(ctx.view, b.name, col, { ...existing, ...op })
|
|
395
|
+
})
|
|
396
|
+
// deleting is two different acts: revoking (moderation, REMOVE) and
|
|
397
|
+
// consuming a single-use invite — which is done by whichever replica
|
|
398
|
+
// served the join, so any member who may serve invites may do it
|
|
399
|
+
add(`del-${b.verb}`, async (op, ctx) => {
|
|
400
|
+
const existing = await ctx.view.get(col, { id: op.id })
|
|
401
|
+
const consume = existing && existing.reuse !== true
|
|
402
|
+
const r = await getSignerRole(ctx.view, ctx.key)
|
|
403
|
+
if (r !== null && !can(r, REMOVE) && !(consume && can(r, INVITE))) {
|
|
404
|
+
throw CeroError.REFUSED('invite')
|
|
405
|
+
}
|
|
406
|
+
return ctx.view.delete(col, op)
|
|
407
|
+
})
|
|
408
|
+
continue
|
|
409
|
+
}
|
|
366
410
|
if (b.verb === 'file') {
|
|
367
411
|
add('add-file', async (op, ctx) => {
|
|
368
|
-
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE))
|
|
412
|
+
if (!can(await getSignerRole(ctx.view, ctx.key), WRITE)) throw CeroError.REFUSED('write')
|
|
369
413
|
const memberId = await getSignerMember(ctx.view, ctx.key)
|
|
370
414
|
await insert(ctx.view, b.name, col, {
|
|
371
415
|
id: op.id,
|
|
@@ -412,15 +456,45 @@ export function makeDispatcher(
|
|
|
412
456
|
dispatcher,
|
|
413
457
|
async apply(nodes, view, host) {
|
|
414
458
|
const dbKey = getDbKey()
|
|
459
|
+
// Nodes land in a transaction this loop owns, so a refusal can discard the
|
|
460
|
+
// whole batch — a batch is one writer's contiguous run (autobee keys it on
|
|
461
|
+
// batch[0].key), so an abort only ever drops the offending writer's ops.
|
|
462
|
+
const tx = view.transaction()
|
|
463
|
+
// Admitting or removing a writer is a host call, not a row — it would
|
|
464
|
+
// survive a discarded transaction and leave a writer with no device row,
|
|
465
|
+
// which the WRITE gate reads as "not yet enrolled". So host calls are
|
|
466
|
+
// recorded and replayed only once the batch is known to commit.
|
|
467
|
+
const calls = []
|
|
468
|
+
const deferred = Object.create(host)
|
|
469
|
+
deferred.addWriter = (...args) => void calls.push(['addWriter', args])
|
|
470
|
+
deferred.removeWriter = (...args) => void calls.push(['removeWriter', args])
|
|
471
|
+
let refusal = null
|
|
415
472
|
for (const node of nodes) {
|
|
416
473
|
try {
|
|
417
|
-
await dispatcher.dispatch(node.value, { view, host, key: node.key, dbKey })
|
|
474
|
+
await dispatcher.dispatch(node.value, { view: tx, host: deferred, key: node.key, dbKey })
|
|
418
475
|
} catch (err) {
|
|
419
|
-
//
|
|
420
|
-
//
|
|
421
|
-
|
|
476
|
+
// A refusal is the verdict every peer reaches from the same node and
|
|
477
|
+
// the same view, so discarding the batch keeps them convergent — and
|
|
478
|
+
// the batch is one writer's own run. Anything else (undecodable bytes,
|
|
479
|
+
// a route this version lacks) skips a single node instead: an older
|
|
480
|
+
// peer must not drop a batch its newer neighbour applies.
|
|
481
|
+
if (!isRefusal(err)) {
|
|
482
|
+
onerror(err)
|
|
483
|
+
continue
|
|
484
|
+
}
|
|
485
|
+
refusal = err
|
|
486
|
+
break
|
|
422
487
|
}
|
|
423
488
|
}
|
|
489
|
+
if (refusal) {
|
|
490
|
+
await tx.close()
|
|
491
|
+
onerror(refusal)
|
|
492
|
+
} else {
|
|
493
|
+
await tx.flush()
|
|
494
|
+
// replayed before apply() returns: autobee clears host.applying right
|
|
495
|
+
// after, and addWriter reads it (rc.31 derives coord/carrier from it)
|
|
496
|
+
for (const [fn, args] of calls) await host[fn](...args)
|
|
497
|
+
}
|
|
424
498
|
await view.flush()
|
|
425
499
|
}
|
|
426
500
|
}
|
|
@@ -224,9 +224,11 @@ export class EpochAutobee extends Autobee {
|
|
|
224
224
|
// haven't learned yet) parks the whole pass — the scheduled retry wakes the
|
|
225
225
|
// stalled cores once the announcement lands. Oplog blocks at unknown epochs
|
|
226
226
|
// never reach here: autobee's own reader freezes that writer.
|
|
227
|
-
|
|
227
|
+
// forwards its arguments: since autobee rc.31 the local drain passes
|
|
228
|
+
// { local: true }, and swallowing it would run the wrong branch
|
|
229
|
+
async _bumpPendingWriters(...args) {
|
|
228
230
|
try {
|
|
229
|
-
return await super._bumpPendingWriters()
|
|
231
|
+
return await super._bumpPendingWriters(...args)
|
|
230
232
|
} catch (err) {
|
|
231
233
|
if (err?.code !== 'UNKNOWN_EPOCH') throw err
|
|
232
234
|
this._scheduleEpochRetry()
|
|
@@ -242,7 +244,7 @@ export class EpochAutobee extends Autobee {
|
|
|
242
244
|
} catch (err) {
|
|
243
245
|
if (err?.code !== 'UNKNOWN_EPOCH') throw err
|
|
244
246
|
this._scheduleEpochRetry()
|
|
245
|
-
return
|
|
247
|
+
return []
|
|
246
248
|
}
|
|
247
249
|
}
|
|
248
250
|
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
import safetyCatch from 'safety-catch'
|
|
2
|
+
|
|
3
|
+
import { ACTION } from '../lib/constants.js'
|
|
4
|
+
import { CeroError } from '../lib/errors.js'
|
|
5
|
+
|
|
6
|
+
export function before(db, op, fn) {
|
|
7
|
+
return addHook(db.beforeHooks, op, fn)
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
export function after(db, op, fn) {
|
|
11
|
+
return addHook(db.afterHooks, op, fn)
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function onUpdate(db, fn, scope) {
|
|
15
|
+
db.updaters.set(fn, scope || null)
|
|
16
|
+
return () => db.updaters.delete(fn)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function touch(db, nodes) {
|
|
20
|
+
if (!db._byVerb) {
|
|
21
|
+
db._byVerb = new Map()
|
|
22
|
+
for (const [name, info] of Object.entries(db.refs)) {
|
|
23
|
+
db._byVerb.set(info.verb || name, name)
|
|
24
|
+
db._byVerb.set(name, name)
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
for (const node of nodes) {
|
|
28
|
+
try {
|
|
29
|
+
const { name } = db.spec.dispatch.decode(node.value)
|
|
30
|
+
const verb = name.slice(name.indexOf('/') + 1)
|
|
31
|
+
const dash = verb.indexOf('-')
|
|
32
|
+
const target = dash < 0 ? verb : verb.slice(dash + 1)
|
|
33
|
+
const ref = db._byVerb.get(target)
|
|
34
|
+
// an action's route handler writes wherever it wants, widen to all
|
|
35
|
+
if (!ref || db.refs[ref]?.kind === ACTION) db._touched.add('*')
|
|
36
|
+
else db._touched.add(ref)
|
|
37
|
+
} catch {
|
|
38
|
+
db._touched.add('*')
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function onApply(db, fn) {
|
|
44
|
+
if (typeof fn !== 'function') return () => {}
|
|
45
|
+
db.onApplyHooks.add(fn)
|
|
46
|
+
return () => db.onApplyHooks.delete(fn)
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function observe(db, nodes) {
|
|
50
|
+
for (const node of nodes) {
|
|
51
|
+
let event
|
|
52
|
+
try {
|
|
53
|
+
const { name, value } = db.spec.dispatch.decode(node.value)
|
|
54
|
+
const verb = name.slice(name.indexOf('/') + 1) // '@cero/set-messages' → 'set-messages'
|
|
55
|
+
const dash = verb.indexOf('-')
|
|
56
|
+
event = {
|
|
57
|
+
op: dash < 0 ? verb : verb.slice(0, dash),
|
|
58
|
+
name: dash < 0 ? verb : verb.slice(dash + 1),
|
|
59
|
+
row: value,
|
|
60
|
+
writerKey: node.key,
|
|
61
|
+
seq: db._applySeq++
|
|
62
|
+
}
|
|
63
|
+
} catch (err) {
|
|
64
|
+
safetyCatch(err)
|
|
65
|
+
continue
|
|
66
|
+
}
|
|
67
|
+
for (const fn of db.onApplyHooks) {
|
|
68
|
+
try {
|
|
69
|
+
fn(event)
|
|
70
|
+
} catch (err) {
|
|
71
|
+
db._onerror(err)
|
|
72
|
+
}
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function runBefore(db, op, ctx) {
|
|
78
|
+
const hooks = db.beforeHooks.get(op)
|
|
79
|
+
if (hooks) {
|
|
80
|
+
for (const fn of hooks) {
|
|
81
|
+
const out = await fn(ctx)
|
|
82
|
+
if (out === false) return false
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
db.emit(`before:${op}`, ctx)
|
|
86
|
+
return true
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function runAfter(db, op, ctx) {
|
|
90
|
+
const hooks = db.afterHooks.get(op)
|
|
91
|
+
if (hooks) {
|
|
92
|
+
for (const fn of hooks) {
|
|
93
|
+
try {
|
|
94
|
+
await fn(ctx)
|
|
95
|
+
} catch (err) {
|
|
96
|
+
db._onerror(err)
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
}
|
|
100
|
+
db.emit(`after:${op}`, ctx)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function addHook(map, op, fn) {
|
|
104
|
+
if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
|
|
105
|
+
let arr = map.get(op)
|
|
106
|
+
if (!arr) map.set(op, (arr = []))
|
|
107
|
+
arr.push(fn)
|
|
108
|
+
return () => {
|
|
109
|
+
const i = arr.indexOf(fn)
|
|
110
|
+
if (i >= 0) arr.splice(i, 1)
|
|
111
|
+
}
|
|
112
|
+
}
|