@cero-base/core 2.2.1 → 2.3.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 +32 -212
- package/package.json +18 -9
- package/src/blobs/index.js +9 -0
- package/src/blobs/server.js +2 -0
- package/src/database/changes.js +1 -1
- package/src/database/dispatch.js +341 -209
- package/src/database/encryption.js +83 -33
- package/src/database/index.js +188 -84
- package/src/database/rotation.js +43 -30
- package/src/identity/index.js +20 -78
- package/src/index.js +3 -10
- package/src/lib/constants.js +2 -0
- package/src/lib/errors.js +3 -11
- package/src/lib/spec/index.js +136 -132
- package/src/lib/spec/schema.json +84 -99
- package/src/lib/utils.js +57 -3
- package/src/mailbox/inbox.js +103 -0
- package/src/mailbox/index.js +146 -0
- package/src/mailbox/post.js +69 -0
- package/src/network/discovery.js +26 -1
- package/src/network/index.js +105 -64
- package/src/network/presence.js +6 -2
- package/src/pairing/index.js +330 -254
- package/src/pairing/invite.js +83 -144
- package/src/pairing/request.js +54 -56
- package/src/rpc/index.js +18 -93
- package/src/rpc/peer.js +4 -1
- package/src/storage/index.js +78 -39
- package/types/blobs/index.d.ts +22 -9
- package/types/blobs/server.d.ts +4 -2
- package/types/database/changes.d.ts +2 -2
- package/types/database/dispatch.d.ts +19 -13
- package/types/database/encryption.d.ts +67 -29
- package/types/database/index.d.ts +144 -119
- package/types/database/rotation.d.ts +32 -13
- package/types/identity/index.d.ts +6 -47
- package/types/index.d.ts +3 -16
- package/types/lib/constants.d.ts +1 -0
- package/types/lib/errors.d.ts +3 -9
- package/types/lib/spec/index.d.ts +52 -16
- package/types/lib/utils.d.ts +40 -8
- package/types/mailbox/inbox.d.ts +52 -0
- package/types/mailbox/index.d.ts +111 -0
- package/types/mailbox/post.d.ts +37 -0
- package/types/network/discovery.d.ts +21 -5
- package/types/network/index.d.ts +64 -48
- package/types/network/presence.d.ts +17 -4
- package/types/pairing/index.d.ts +143 -134
- package/types/pairing/invite.d.ts +70 -114
- package/types/pairing/request.d.ts +58 -98
- package/types/rpc/index.d.ts +26 -44
- package/types/rpc/peer.d.ts +10 -7
- package/types/storage/index.d.ts +64 -54
- package/src/pairing/candidate.js +0 -123
- package/types/pairing/candidate.d.ts +0 -36
package/src/database/index.js
CHANGED
|
@@ -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 {
|
|
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 {
|
|
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 {
|
|
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:
|
|
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 {
|
|
41
|
-
* @typedef {{ data:
|
|
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
|
|
51
|
-
* @property {string} 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,
|
|
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
|
|
234
|
-
const stored = {
|
|
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,
|
|
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.
|
|
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
|
-
*
|
|
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,
|
|
323
|
+
* @param {Record<string, unknown>} [data]
|
|
270
324
|
* @returns {Promise<void>}
|
|
271
325
|
*/
|
|
272
326
|
async call(op, data = {}) {
|
|
273
327
|
this.guard()
|
|
274
|
-
//
|
|
275
|
-
if (this.refs[op]?.kind === ACTION &&
|
|
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
|
-
//
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
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
|
-
|
|
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,
|
|
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
|
-
|
|
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.
|
|
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
|
|
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
|
|
519
|
-
return this._admit('add-writer', publicKey
|
|
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
|
-
//
|
|
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)
|
|
624
|
-
|
|
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,30 +722,60 @@ export class Database extends ReadyResource {
|
|
|
655
722
|
this._presence?.touch()
|
|
656
723
|
}
|
|
657
724
|
|
|
658
|
-
// a
|
|
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
|
|
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) => {
|
|
765
|
+
// only the hook's own synchronous run is inside it: other work interleaves at its awaits
|
|
672
766
|
this._hooking++
|
|
767
|
+
let result
|
|
673
768
|
try {
|
|
674
|
-
|
|
769
|
+
result = fn(ctx)
|
|
675
770
|
} finally {
|
|
676
771
|
this._hooking--
|
|
677
772
|
}
|
|
773
|
+
return await result
|
|
678
774
|
}
|
|
679
775
|
}
|
|
680
776
|
|
|
681
777
|
// an 'update' listener for one ref; the disposer detaches it
|
|
778
|
+
/** @param {string} name @param {() => void} fn @returns {() => void} */
|
|
682
779
|
onUpdate(name, fn) {
|
|
683
780
|
const tick = (touched) => {
|
|
684
781
|
if (touched.has('*') || touched.has(name)) fn()
|
|
@@ -688,6 +785,7 @@ export class Database extends ReadyResource {
|
|
|
688
785
|
}
|
|
689
786
|
|
|
690
787
|
// '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
|
|
788
|
+
/** @private */
|
|
691
789
|
_opOf(node) {
|
|
692
790
|
const { name, value } = this.spec.dispatch.decode(node.value)
|
|
693
791
|
const verb = name.slice(name.indexOf('/') + 1)
|
|
@@ -697,6 +795,7 @@ export class Database extends ReadyResource {
|
|
|
697
795
|
}
|
|
698
796
|
|
|
699
797
|
// marks the refs a batch touched and emits 'apply' per op, local and replicated alike
|
|
798
|
+
/** @private */
|
|
700
799
|
_notify(nodes) {
|
|
701
800
|
const listened = this.listenerCount('apply') > 0
|
|
702
801
|
for (const node of nodes) {
|
|
@@ -709,7 +808,7 @@ export class Database extends ReadyResource {
|
|
|
709
808
|
continue
|
|
710
809
|
}
|
|
711
810
|
const ref = this._verbs.get(op.name)
|
|
712
|
-
// an action's
|
|
811
|
+
// an action's hooks write wherever they want, widen to all
|
|
713
812
|
this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
|
|
714
813
|
if (!listened) continue
|
|
715
814
|
this.emit('apply', {
|
|
@@ -722,34 +821,39 @@ export class Database extends ReadyResource {
|
|
|
722
821
|
}
|
|
723
822
|
}
|
|
724
823
|
|
|
824
|
+
/** @private */
|
|
725
825
|
async _merge(name, row, { upsert = true } = {}) {
|
|
726
826
|
const ref = this._prepare(name, row)
|
|
727
827
|
const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
|
|
728
828
|
if (!upsert && !existing) return null
|
|
729
|
-
const
|
|
730
|
-
|
|
829
|
+
const stored = stamp({ ...existing, ...row }, existing?.createdAt)
|
|
830
|
+
checkRequired(name, this.refs[name], stored)
|
|
731
831
|
if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
|
|
732
832
|
const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
|
|
733
833
|
return this._append(stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
|
|
734
834
|
}
|
|
735
835
|
|
|
836
|
+
/** @private */
|
|
736
837
|
_prepare(name, row) {
|
|
737
838
|
this.guard()
|
|
738
839
|
const ref = this.ref(name)
|
|
739
|
-
this.
|
|
840
|
+
checkFields(name, this.refs[name], row)
|
|
740
841
|
return ref
|
|
741
842
|
}
|
|
742
843
|
|
|
844
|
+
/** @private */
|
|
743
845
|
async _append(stored, verb) {
|
|
744
846
|
await this.write([[verb, stored]])
|
|
745
847
|
return { row: stored }
|
|
746
848
|
}
|
|
747
849
|
|
|
850
|
+
/** @private */
|
|
748
851
|
_done(ctx) {
|
|
749
852
|
return ctx ? { data: ctx.row } : null
|
|
750
853
|
}
|
|
751
854
|
|
|
752
855
|
// ops from a newer app version: emit behind once per version, the marker survives restarts
|
|
856
|
+
/** @private */
|
|
753
857
|
_onfuture(version) {
|
|
754
858
|
if (this.behind !== null && version <= this.behind) return
|
|
755
859
|
this.behind = version
|
|
@@ -758,9 +862,14 @@ export class Database extends ReadyResource {
|
|
|
758
862
|
}
|
|
759
863
|
|
|
760
864
|
// every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
|
|
865
|
+
/** @private */
|
|
761
866
|
async _dryRun(encoded) {
|
|
762
867
|
const tx = this.view.transaction()
|
|
763
|
-
const host = {
|
|
868
|
+
const host = {
|
|
869
|
+
addWriter: async () => {},
|
|
870
|
+
removeWriter: async () => {},
|
|
871
|
+
genesis: this.bee.system.isGenesis()
|
|
872
|
+
}
|
|
764
873
|
try {
|
|
765
874
|
for (const value of encoded) {
|
|
766
875
|
await this.dispatcher.dispatch(value, {
|
|
@@ -784,6 +893,7 @@ export class Database extends ReadyResource {
|
|
|
784
893
|
}
|
|
785
894
|
|
|
786
895
|
// one hyperdb read per query: index, bounds and window pushed down, the rest filtered in memory
|
|
896
|
+
/** @private */
|
|
787
897
|
_plan(name, query = {}) {
|
|
788
898
|
const ref = this.refs[name]
|
|
789
899
|
const col = `@${this.ns}/${name}`
|
|
@@ -799,10 +909,12 @@ export class Database extends ReadyResource {
|
|
|
799
909
|
return { path: `${col}-${idx}`, range, rest, sorted: true }
|
|
800
910
|
}
|
|
801
911
|
if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
|
|
912
|
+
// a range on the id reads in id order, so hyperdb serves the window and stops at the page
|
|
802
913
|
if (bounded) {
|
|
803
914
|
const range = {}
|
|
804
915
|
for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
|
|
805
|
-
|
|
916
|
+
pushWindow(range, rest)
|
|
917
|
+
return { path: col, range, rest, sorted: true }
|
|
806
918
|
}
|
|
807
919
|
if (ref?.orderIndex) {
|
|
808
920
|
const range = {}
|
|
@@ -813,6 +925,7 @@ export class Database extends ReadyResource {
|
|
|
813
925
|
}
|
|
814
926
|
|
|
815
927
|
// matched rows; unknown once a pushed-down limit filled the page
|
|
928
|
+
/** @private */
|
|
816
929
|
async _total(view, path, range, matched, query) {
|
|
817
930
|
if (range.limit === undefined || matched.length < range.limit) return matched.length
|
|
818
931
|
if (!query?.total) return null
|
|
@@ -821,6 +934,7 @@ export class Database extends ReadyResource {
|
|
|
821
934
|
}
|
|
822
935
|
|
|
823
936
|
// an append by a core not yet admitted: apply verifies the signature and admits it
|
|
937
|
+
/** @private */
|
|
824
938
|
async _optimistic(op, opts) {
|
|
825
939
|
await this.bee.append(wrap(this.version, op), { optimistic: true })
|
|
826
940
|
await this.bee.update()
|
|
@@ -828,6 +942,7 @@ export class Database extends ReadyResource {
|
|
|
828
942
|
}
|
|
829
943
|
|
|
830
944
|
// the genesis device row is the first write of every database, so any device row means backfilled
|
|
945
|
+
/** @private */
|
|
831
946
|
async _backfilled(timeout) {
|
|
832
947
|
const deadline = Date.now() + timeout
|
|
833
948
|
while (Date.now() < deadline) {
|
|
@@ -836,32 +951,22 @@ export class Database extends ReadyResource {
|
|
|
836
951
|
await this.bee.update()
|
|
837
952
|
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
838
953
|
}
|
|
839
|
-
throw CeroError.
|
|
954
|
+
throw CeroError.TIMEOUT('recovery — no peer replicated')
|
|
840
955
|
}
|
|
841
956
|
|
|
842
957
|
// the add-writer row for `writer`, appended by this device and signed by the identity
|
|
958
|
+
/** @private */
|
|
843
959
|
_admission(writer, ts = Date.now()) {
|
|
844
960
|
const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
|
|
845
961
|
return { master: this.identity.publicKey, writer, sig, ts }
|
|
846
962
|
}
|
|
847
963
|
|
|
848
|
-
|
|
849
|
-
|
|
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) {
|
|
964
|
+
/** @private */
|
|
965
|
+
async _admit(verb, publicKey) {
|
|
861
966
|
this.guard()
|
|
862
967
|
if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
|
|
863
968
|
const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
|
|
864
|
-
await this.write([[verb,
|
|
969
|
+
await this.write([[verb, this._admission(writer)]])
|
|
865
970
|
}
|
|
866
971
|
}
|
|
867
972
|
|
|
@@ -896,11 +1001,10 @@ function verbMap(refs) {
|
|
|
896
1001
|
return map
|
|
897
1002
|
}
|
|
898
1003
|
|
|
899
|
-
//
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
const SYSTEM_FIELDS = new Set(['id', 'memberId', 'index', 'createdAt', 'updatedAt'])
|
|
1004
|
+
// the one op a device without a writer seat may append
|
|
1005
|
+
function leaving(ops, id) {
|
|
1006
|
+
return ops.length === 1 && ops[0][0] === 'del-member' && ops[0][1]?.id === id
|
|
1007
|
+
}
|
|
904
1008
|
|
|
905
1009
|
const RANGE = new Set(['gt', 'gte', 'lt', 'lte'])
|
|
906
1010
|
|