@cero-base/core 1.19.0 → 2.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +9 -6
- package/src/blobs/index.js +15 -15
- package/src/blobs/server.js +0 -2
- package/src/database/changes.js +4 -8
- package/src/database/dispatch.js +296 -227
- package/src/database/encryption.js +22 -52
- package/src/database/envelope.js +1 -3
- package/src/database/index.js +406 -476
- package/src/database/rotation.js +56 -70
- package/src/identity/index.js +5 -9
- package/src/index.js +5 -9
- package/src/lib/constants.js +3 -12
- package/src/lib/errors.js +6 -10
- package/src/lib/schema.js +2 -5
- package/src/lib/utils.js +9 -24
- package/src/network/index.js +144 -167
- package/src/network/presence.js +131 -0
- package/src/pairing/candidate.js +2 -4
- package/src/pairing/index.js +41 -55
- package/src/pairing/invite.js +3 -4
- package/src/pairing/request.js +3 -9
- package/src/rpc/index.js +4 -14
- package/src/rpc/peer.js +3 -7
- package/src/storage/index.js +29 -50
- package/types/blobs/index.d.ts +5 -5
- package/types/blobs/server.d.ts +0 -2
- package/types/database/changes.d.ts +2 -5
- package/types/database/dispatch.d.ts +11 -7
- package/types/database/encryption.d.ts +8 -20
- package/types/database/index.d.ts +164 -141
- package/types/database/rotation.d.ts +14 -20
- package/types/identity/index.d.ts +5 -9
- package/types/index.d.ts +4 -3
- package/types/lib/errors.d.ts +6 -10
- package/types/lib/schema.d.ts +2 -5
- package/types/lib/utils.d.ts +3 -7
- package/types/network/index.d.ts +28 -27
- package/types/network/presence.d.ts +50 -0
- package/types/pairing/candidate.d.ts +1 -2
- package/types/pairing/index.d.ts +22 -30
- package/types/pairing/invite.d.ts +3 -3
- package/types/pairing/request.d.ts +1 -3
- package/types/rpc/index.d.ts +1 -4
- package/types/rpc/peer.d.ts +2 -4
- package/types/storage/index.d.ts +17 -30
package/src/database/index.js
CHANGED
|
@@ -7,15 +7,7 @@ import safetyCatch from 'safety-catch'
|
|
|
7
7
|
import b4a from 'b4a'
|
|
8
8
|
import hid from 'hypercore-id-encoding'
|
|
9
9
|
|
|
10
|
-
import {
|
|
11
|
-
NAMESPACE,
|
|
12
|
-
SINGLE,
|
|
13
|
-
COLLECTION,
|
|
14
|
-
ACTION,
|
|
15
|
-
ACTIVE,
|
|
16
|
-
PASSIVE,
|
|
17
|
-
QUERY_RESERVED
|
|
18
|
-
} from '../lib/constants.js'
|
|
10
|
+
import { NAMESPACE, SINGLE, COLLECTION, ACTION, QUERY_RESERVED } from '../lib/constants.js'
|
|
19
11
|
import { genId, subscribe, admission, ownership, filter } from '../lib/utils.js'
|
|
20
12
|
import { wrap, unwrap } from './envelope.js'
|
|
21
13
|
import { EpochAutobee, Keyring, loadEpochs } from './encryption.js'
|
|
@@ -36,22 +28,35 @@ import { makeDispatcher } from './dispatch.js'
|
|
|
36
28
|
* @property {Uint8Array | null} [encryptionKey] Optional encryption key; falls back to identity's key.
|
|
37
29
|
* @property {Array<{ epoch: number, entropy: Uint8Array }> | null} [epochs] Rotation epochs to prime the keyring with (delivered at join).
|
|
38
30
|
* @property {Uint8Array | null} [key] Existing autobee key to reopen.
|
|
39
|
-
* @property {boolean} [
|
|
31
|
+
* @property {boolean} [pinned] Always search and announce, outside the network's presence budget. The root.
|
|
40
32
|
* @property {import('../identity/index.js').KeyPair} [keyPair] This device's writer keypair; a fresh random one by default. Never the identity's, never the database key.
|
|
41
|
-
* @property {(err: Error) => void} [onerror] Called when a
|
|
33
|
+
* @property {(err: Error) => void} [onerror] Called when a node is skipped or refused, or the bee errors.
|
|
34
|
+
*
|
|
35
|
+
* Events: `update` (touched refs, a Set, after each applied batch), `apply` (one per applied
|
|
36
|
+
* op: `{ op, name, row, writerKey, seq }`, local and replicated), `writable`, `unwritable`,
|
|
37
|
+
* `behind` (an op from a newer app version was skipped).
|
|
42
38
|
*
|
|
43
39
|
* @typedef {{ data: any | null }} SingleResult
|
|
44
40
|
* @typedef {{ data: any[], total: number | null, size: number }} ListResult `total` is null when a limited read skipped the full count — pass `{ total: true }` to force it.
|
|
45
41
|
* @typedef {{ gt?: string, gte?: string, lt?: string, lte?: string, reverse?: boolean, limit?: number, search?: string, fields?: string[], total?: boolean }} Query
|
|
46
42
|
* @typedef {{ kind: string, verb: string, name: string }} Ref
|
|
47
|
-
* @typedef {
|
|
43
|
+
* @typedef {object} HookContext
|
|
44
|
+
* @property {string} op One of `put`, `set`, `del`, or an action name.
|
|
45
|
+
* @property {string} name The ref the op targets.
|
|
46
|
+
* @property {Record<string, unknown> | null} row The incoming row; mutate it in `before` to change what lands.
|
|
47
|
+
* @property {Record<string, unknown> | null} existing The stored row, or null.
|
|
48
|
+
* @property {string | null} id The row id for a `del`.
|
|
49
|
+
* @property {string} memberId The writer's member id.
|
|
50
|
+
* @property {string} role The writer's role.
|
|
51
|
+
* @property {(ref: string | { name: string }, query?: string | Record<string, unknown>) => Promise<{ data: unknown }>} get
|
|
52
|
+
* @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} put
|
|
53
|
+
* @property {(ref: string | { name: string }, row: Record<string, unknown>) => Promise<void>} set
|
|
54
|
+
* @property {(ref: string | { name: string }, id?: string) => Promise<void>} del
|
|
55
|
+
* @typedef {(ctx: HookContext) => unknown} HookFn
|
|
48
56
|
*/
|
|
49
57
|
|
|
50
58
|
/**
|
|
51
|
-
* Multi-writer database built on Autobee + HyperDB.
|
|
52
|
-
* hyperdispatch-encoded log and exposes a `put/get/...` surface mirroring
|
|
53
|
-
* `Storage`, plus writer ops (claim/addWriter/removeWriter) for the
|
|
54
|
-
* shared writer set.
|
|
59
|
+
* Multi-writer database built on Autobee + HyperDB.
|
|
55
60
|
*/
|
|
56
61
|
export class Database extends ReadyResource {
|
|
57
62
|
/** @param {Partial<DatabaseOpts>} [opts] */
|
|
@@ -80,10 +85,7 @@ export class Database extends ReadyResource {
|
|
|
80
85
|
if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
|
|
81
86
|
this.rotation = new Rotation(this)
|
|
82
87
|
this.key = opts.key || null
|
|
83
|
-
this.
|
|
84
|
-
// this device is the only author of its writer core, ever: a fresh keypair
|
|
85
|
-
// by default. The identity keypair is never a writer — every device can
|
|
86
|
-
// derive it, and two authors on one core is a fork
|
|
88
|
+
this.pinned = opts.pinned === true
|
|
87
89
|
this.keyPair = opts.keyPair || Identity.randomKeyPair()
|
|
88
90
|
if (b4a.equals(this.keyPair.publicKey, this.identity.publicKey)) {
|
|
89
91
|
throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
|
|
@@ -92,19 +94,45 @@ export class Database extends ReadyResource {
|
|
|
92
94
|
this._onerror = opts.onerror || safetyCatch
|
|
93
95
|
this.bee = null
|
|
94
96
|
this.dispatcher = null
|
|
95
|
-
this.
|
|
97
|
+
this._presence = null
|
|
96
98
|
this._txChain = null
|
|
97
99
|
|
|
98
100
|
this._before = new Map()
|
|
99
101
|
this._after = new Map()
|
|
100
|
-
this.
|
|
101
|
-
this._observers = new Set()
|
|
102
|
+
this._hooking = 0
|
|
102
103
|
this._verbs = verbMap(this.refs)
|
|
103
104
|
this._touched = new Set()
|
|
104
105
|
this._seq = 0
|
|
106
|
+
// every watch and changes stream is an 'update' listener
|
|
107
|
+
this.setMaxListeners(0)
|
|
105
108
|
this.txQueue = null
|
|
106
109
|
}
|
|
107
110
|
|
|
111
|
+
/** @returns {Uint8Array | null} discovery key of the underlying bee */
|
|
112
|
+
get discoveryKey() {
|
|
113
|
+
return this.bee?.discoveryKey || null
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** @returns {Uint8Array | null} this device's local writer key */
|
|
117
|
+
get writerKey() {
|
|
118
|
+
return this.bee?.local?.key || null
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** @returns {boolean} whether the bee accepts local writes */
|
|
122
|
+
get writable() {
|
|
123
|
+
return this.bee?.writable === true
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** @returns {number} number of ops in the local writer */
|
|
127
|
+
get length() {
|
|
128
|
+
return this.bee?.local?.length || 0
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/** @returns {object | null} the materialized HyperDB view */
|
|
132
|
+
get view() {
|
|
133
|
+
return this.bee?.view || null
|
|
134
|
+
}
|
|
135
|
+
|
|
108
136
|
async _open() {
|
|
109
137
|
await this.store.ready()
|
|
110
138
|
if (this.network) await this.network.ready()
|
|
@@ -115,7 +143,11 @@ export class Database extends ReadyResource {
|
|
|
115
143
|
routes: this.routes,
|
|
116
144
|
onerror: this._onerror,
|
|
117
145
|
key: () => this.key,
|
|
118
|
-
onepoch: (row) => this.rotation.learn(row)
|
|
146
|
+
onepoch: (row) => this.rotation.learn(row),
|
|
147
|
+
hooks: (phase, op) => this._hooks(phase, op),
|
|
148
|
+
inHook: (fn) => this._inHook(fn),
|
|
149
|
+
touch: (name) => this._touched.add(name),
|
|
150
|
+
read: (view, name, query) => this._read(view, name, query)
|
|
119
151
|
})
|
|
120
152
|
|
|
121
153
|
const known = !!this.key
|
|
@@ -136,15 +168,13 @@ export class Database extends ReadyResource {
|
|
|
136
168
|
|
|
137
169
|
// a fresh db has no key until boot mints it
|
|
138
170
|
if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
|
|
139
|
-
if (replayed) this.emit('rebuild')
|
|
140
171
|
}
|
|
141
172
|
|
|
142
173
|
async _close() {
|
|
143
174
|
this.rotation.close()
|
|
144
|
-
if (this.
|
|
145
|
-
|
|
146
|
-
this.
|
|
147
|
-
this._discovery = null
|
|
175
|
+
if (this._presence) {
|
|
176
|
+
this._presence.remove()
|
|
177
|
+
this._presence = null
|
|
148
178
|
}
|
|
149
179
|
if (this.bee) {
|
|
150
180
|
// detach first, else the closed bee replicates into every new connection
|
|
@@ -154,150 +184,21 @@ export class Database extends ReadyResource {
|
|
|
154
184
|
}
|
|
155
185
|
}
|
|
156
186
|
|
|
157
|
-
// the bee's boot reads post-rotation state through the keyring, so it is
|
|
158
|
-
// primed from the local core's userData before the bee exists
|
|
159
|
-
async _preload() {
|
|
160
|
-
const local = this.store.namespace(this.namespace).get({
|
|
161
|
-
keyPair: this.keyPair,
|
|
162
|
-
manifest: {
|
|
163
|
-
version: this.store.manifestVersion,
|
|
164
|
-
signers: [{ publicKey: this.keyPair.publicKey }]
|
|
165
|
-
},
|
|
166
|
-
active: false
|
|
167
|
-
})
|
|
168
|
-
await local.ready()
|
|
169
|
-
await loadEpochs(this.keyring, local)
|
|
170
|
-
await local.close()
|
|
171
|
-
}
|
|
172
|
-
|
|
173
|
-
async _boot() {
|
|
174
|
-
const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
|
|
175
|
-
keyPair: this.keyPair,
|
|
176
|
-
encryptionKey: this.encryptionKey,
|
|
177
|
-
keyring: this.keyring,
|
|
178
|
-
optimistic: true,
|
|
179
|
-
wakeup: this.network?.wakeup || undefined,
|
|
180
|
-
open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
|
|
181
|
-
isTrusted: this._isTrusted.bind(this),
|
|
182
|
-
apply: this._apply.bind(this),
|
|
183
|
-
update: this._update.bind(this)
|
|
184
|
-
})
|
|
185
|
-
// swarm BEFORE boot so the boot has peers to pull from, not a cold open
|
|
186
|
-
if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
|
|
187
|
-
await bee.ready()
|
|
188
|
-
// apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
|
|
189
|
-
this.bee = bee
|
|
190
|
-
this.key = bee.key
|
|
191
|
-
await bee.update()
|
|
192
|
-
}
|
|
193
|
-
|
|
194
|
-
// ops skipped as too new are in contract once this version caught up: wipe
|
|
195
|
-
// the boot record so the next boot replays them
|
|
196
|
-
async _replay() {
|
|
197
|
-
const behind = await this.bee.local.getUserData('cero/behind')
|
|
198
|
-
this.behind = behind ? c.decode(c.uint, behind) : null
|
|
199
|
-
if (this.behind === null || this.behind > this.version) return false
|
|
200
|
-
await this.bee.local.setUserData('autobee/head', null)
|
|
201
|
-
await this.bee.local.setUserData('cero/behind', null)
|
|
202
|
-
await this.bee.close()
|
|
203
|
-
this.behind = null
|
|
204
|
-
return true
|
|
205
|
-
}
|
|
206
|
-
|
|
207
|
-
// without this hook autobee trusts EVERY fast-forward candidate, so a removed
|
|
208
|
-
// device could serve a forked head. Decided against the reference view, not live
|
|
209
|
-
async _isTrusted(writer, view) {
|
|
210
|
-
try {
|
|
211
|
-
const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
|
|
212
|
-
if (!row) return false
|
|
213
|
-
if (row.v) return true
|
|
214
|
-
// only a PROVABLY empty view (genesis-era reference) lets the genesis
|
|
215
|
-
// writer vouch, its core IS the db key. Otherwise it is an ex-member's window
|
|
216
|
-
const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
|
|
217
|
-
if (!any) return false
|
|
218
|
-
return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
|
|
219
|
-
} catch {
|
|
220
|
-
return false
|
|
221
|
-
}
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
// unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
|
|
225
|
-
async _apply(nodes, view, host) {
|
|
226
|
-
const ready = []
|
|
227
|
-
for (const node of nodes) {
|
|
228
|
-
const { version, body } = unwrap(node.value)
|
|
229
|
-
if (version > this.version) {
|
|
230
|
-
this._onfuture(version)
|
|
231
|
-
continue
|
|
232
|
-
}
|
|
233
|
-
ready.push(version === 0 ? node : { ...node, value: body })
|
|
234
|
-
}
|
|
235
|
-
const result = await this.dispatcher.apply(ready, view, host)
|
|
236
|
-
if (this._updaters.size) this._touch(ready)
|
|
237
|
-
if (this._observers.size) this._observe(ready)
|
|
238
|
-
return result
|
|
239
|
-
}
|
|
240
|
-
|
|
241
|
-
async _update(db) {
|
|
242
|
-
await db.update()
|
|
243
|
-
const touched = this._touched
|
|
244
|
-
this._touched = new Set()
|
|
245
|
-
const all = touched.size === 0 || touched.has('*')
|
|
246
|
-
for (const [fn, scope] of this._updaters) {
|
|
247
|
-
if (all || !scope || touched.has(scope)) fn()
|
|
248
|
-
}
|
|
249
|
-
this.emit('update')
|
|
250
|
-
}
|
|
251
|
-
|
|
252
|
-
// a writer swap re-opens the bee on the SAME topic, join first so destroy is a detach
|
|
253
|
-
_joinSwarm(bee, discoveryKey) {
|
|
254
|
-
this.network.attach(bee)
|
|
255
|
-
const prev = this._discovery
|
|
256
|
-
this._discovery = this.network.join(discoveryKey, {
|
|
257
|
-
mode: this.passive ? PASSIVE : ACTIVE
|
|
258
|
-
})
|
|
259
|
-
if (prev) prev.destroy().catch(safetyCatch)
|
|
260
|
-
}
|
|
261
|
-
|
|
262
187
|
/**
|
|
263
|
-
*
|
|
264
|
-
*
|
|
188
|
+
* `true` ranks this database as just touched, `false` takes it out of the swarm until the
|
|
189
|
+
* next update lands in it.
|
|
265
190
|
*
|
|
266
191
|
* @param {boolean} active
|
|
267
|
-
* @returns {Promise<void>}
|
|
268
192
|
*/
|
|
269
|
-
|
|
270
|
-
if (!this.
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
/** @returns {Uint8Array | null} discovery key of the underlying bee */
|
|
275
|
-
get discoveryKey() {
|
|
276
|
-
return this.bee?.discoveryKey || null
|
|
277
|
-
}
|
|
278
|
-
|
|
279
|
-
/** @returns {Uint8Array | null} this device's local writer key */
|
|
280
|
-
get writerKey() {
|
|
281
|
-
return this.bee?.local?.key || null
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
/** @returns {boolean} whether the bee accepts local writes */
|
|
285
|
-
get writable() {
|
|
286
|
-
return this.bee?.writable === true
|
|
287
|
-
}
|
|
288
|
-
|
|
289
|
-
/** @returns {number} number of ops in the local writer */
|
|
290
|
-
get length() {
|
|
291
|
-
return this.bee?.local?.length || 0
|
|
292
|
-
}
|
|
293
|
-
|
|
294
|
-
/** @returns {object | null} the materialized HyperDB view */
|
|
295
|
-
get view() {
|
|
296
|
-
return this.bee?.view || null
|
|
193
|
+
setActive(active) {
|
|
194
|
+
if (!this._presence) return
|
|
195
|
+
if (active) this._presence.touch()
|
|
196
|
+
else this._presence.off()
|
|
297
197
|
}
|
|
298
198
|
|
|
299
199
|
/**
|
|
300
|
-
* Register a pre-op hook.
|
|
200
|
+
* Register a pre-op hook. It runs at apply on every peer, inside the op's transaction;
|
|
201
|
+
* returning `false` (or throwing) refuses the op everywhere.
|
|
301
202
|
*
|
|
302
203
|
* @param {string} op
|
|
303
204
|
* @param {HookFn} fn
|
|
@@ -308,7 +209,8 @@ export class Database extends ReadyResource {
|
|
|
308
209
|
}
|
|
309
210
|
|
|
310
211
|
/**
|
|
311
|
-
* Register a post-op hook,
|
|
212
|
+
* Register a post-op hook. It runs at apply on every peer, in the op's transaction, so it
|
|
213
|
+
* may write derived rows through `ctx.put` / `ctx.set` / `ctx.del`.
|
|
312
214
|
*
|
|
313
215
|
* @param {string} op
|
|
314
216
|
* @param {HookFn} fn
|
|
@@ -318,94 +220,6 @@ export class Database extends ReadyResource {
|
|
|
318
220
|
return addHook(this._after, op, fn)
|
|
319
221
|
}
|
|
320
222
|
|
|
321
|
-
/**
|
|
322
|
-
* Subscribe to local apply notifications. Fires whenever the view updates;
|
|
323
|
-
* pass `scope` (a ref name) to fire only when that ref was touched.
|
|
324
|
-
*
|
|
325
|
-
* @param {() => void} fn
|
|
326
|
-
* @param {string} [scope]
|
|
327
|
-
* @returns {() => void} disposer
|
|
328
|
-
*/
|
|
329
|
-
onUpdate(fn, scope) {
|
|
330
|
-
this._updaters.set(fn, scope || null)
|
|
331
|
-
return () => this._updaters.delete(fn)
|
|
332
|
-
}
|
|
333
|
-
|
|
334
|
-
/**
|
|
335
|
-
* Observe every applied op — local AND replicated (apply processes the merged
|
|
336
|
-
* log). The callback receives `{ op, name, row, writerKey, seq }` and runs
|
|
337
|
-
* synchronously, so it must be cheap and non-blocking (enqueue and return).
|
|
338
|
-
* Gated: zero cost when no subscriber is registered. Returns a disposer.
|
|
339
|
-
*
|
|
340
|
-
* @param {(event: { op: string, name: string, row: any, writerKey: any, seq: number }) => void} fn
|
|
341
|
-
* @returns {() => void} disposer
|
|
342
|
-
*/
|
|
343
|
-
onApply(fn) {
|
|
344
|
-
if (typeof fn !== 'function') return () => {}
|
|
345
|
-
this._observers.add(fn)
|
|
346
|
-
return () => this._observers.delete(fn)
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
async _runBefore(op, ctx) {
|
|
350
|
-
for (const fn of this._before.get(op) || []) {
|
|
351
|
-
if ((await fn(ctx)) === false) return false
|
|
352
|
-
}
|
|
353
|
-
this.emit(`before:${op}`, ctx)
|
|
354
|
-
return true
|
|
355
|
-
}
|
|
356
|
-
|
|
357
|
-
async _runAfter(op, ctx) {
|
|
358
|
-
for (const fn of this._after.get(op) || []) {
|
|
359
|
-
try {
|
|
360
|
-
await fn(ctx)
|
|
361
|
-
} catch (err) {
|
|
362
|
-
this._onerror(err)
|
|
363
|
-
}
|
|
364
|
-
}
|
|
365
|
-
this.emit(`after:${op}`, ctx)
|
|
366
|
-
}
|
|
367
|
-
|
|
368
|
-
// '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
|
|
369
|
-
_opOf(node) {
|
|
370
|
-
const { name, value } = this.spec.dispatch.decode(node.value)
|
|
371
|
-
const verb = name.slice(name.indexOf('/') + 1)
|
|
372
|
-
const dash = verb.indexOf('-')
|
|
373
|
-
if (dash < 0) return { op: verb, name: verb, value }
|
|
374
|
-
return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
|
|
375
|
-
}
|
|
376
|
-
|
|
377
|
-
// which refs an applied batch touched, for scoped update ticks
|
|
378
|
-
_touch(nodes) {
|
|
379
|
-
for (const node of nodes) {
|
|
380
|
-
let ref = null
|
|
381
|
-
try {
|
|
382
|
-
ref = this._verbs.get(this._opOf(node).name)
|
|
383
|
-
} catch {}
|
|
384
|
-
// an action's route handler writes wherever it wants, widen to all
|
|
385
|
-
this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
|
|
386
|
-
}
|
|
387
|
-
}
|
|
388
|
-
|
|
389
|
-
_observe(nodes) {
|
|
390
|
-
for (const node of nodes) {
|
|
391
|
-
let event
|
|
392
|
-
try {
|
|
393
|
-
const { op, name, value } = this._opOf(node)
|
|
394
|
-
event = { op, name, row: value, writerKey: node.key, seq: this._seq++ }
|
|
395
|
-
} catch (err) {
|
|
396
|
-
safetyCatch(err)
|
|
397
|
-
continue
|
|
398
|
-
}
|
|
399
|
-
for (const fn of this._observers) {
|
|
400
|
-
try {
|
|
401
|
-
fn(event)
|
|
402
|
-
} catch (err) {
|
|
403
|
-
this._onerror(err)
|
|
404
|
-
}
|
|
405
|
-
}
|
|
406
|
-
}
|
|
407
|
-
}
|
|
408
|
-
|
|
409
223
|
/**
|
|
410
224
|
* Insert (or overwrite by id) a row, stamping `id`/`createdAt`/`updatedAt`.
|
|
411
225
|
*
|
|
@@ -414,27 +228,14 @@ export class Database extends ReadyResource {
|
|
|
414
228
|
* @returns {Promise<SingleResult | null>}
|
|
415
229
|
*/
|
|
416
230
|
async put(name, row) {
|
|
417
|
-
this.
|
|
418
|
-
const ref = this.ref(name)
|
|
419
|
-
this._checkFields(name, row)
|
|
420
|
-
const id = row.id || genId()
|
|
231
|
+
const ref = this._prepare(name, row)
|
|
421
232
|
const ts = Date.now()
|
|
422
|
-
const stored = { createdAt: ts, updatedAt: ts, ...row, id }
|
|
423
|
-
|
|
424
|
-
const ctx = { op: 'put', name, row: stored }
|
|
425
|
-
if ((await this._runBefore('put', ctx)) === false) return null
|
|
426
|
-
|
|
427
|
-
await this.write([[`add-${ref.verb}`, ctx.row]])
|
|
428
|
-
|
|
429
|
-
const result = { data: ctx.row }
|
|
430
|
-
await this._runAfter('put', { ...ctx, result })
|
|
431
|
-
return result
|
|
233
|
+
const stored = { createdAt: ts, updatedAt: ts, ...row, id: row.id || genId() }
|
|
234
|
+
return this._done(await this._append(stored, `add-${ref.verb}`))
|
|
432
235
|
}
|
|
433
236
|
|
|
434
237
|
/**
|
|
435
|
-
* Upsert by merging with the existing row, preserving `createdAt`.
|
|
436
|
-
* `{ upsert: false }` to update-only — a missing row is left untouched
|
|
437
|
-
* (checked atomically in the dispatch, so it never resurrects a deleted row).
|
|
238
|
+
* Upsert by merging with the existing row, preserving `createdAt`.
|
|
438
239
|
*
|
|
439
240
|
* @param {string} name
|
|
440
241
|
* @param {Record<string, any>} row
|
|
@@ -442,27 +243,7 @@ export class Database extends ReadyResource {
|
|
|
442
243
|
* @returns {Promise<SingleResult | null>}
|
|
443
244
|
*/
|
|
444
245
|
async set(name, row, opts) {
|
|
445
|
-
|
|
446
|
-
if (!ctx) return null
|
|
447
|
-
const result = { data: ctx.row }
|
|
448
|
-
await this._runAfter('set', { ...ctx, result })
|
|
449
|
-
return result
|
|
450
|
-
}
|
|
451
|
-
|
|
452
|
-
async _merge(name, row, { upsert = true } = {}) {
|
|
453
|
-
this.guard()
|
|
454
|
-
const ref = this.ref(name)
|
|
455
|
-
this._checkFields(name, row)
|
|
456
|
-
const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
|
|
457
|
-
if (!upsert && !existing) return null
|
|
458
|
-
const ts = Date.now()
|
|
459
|
-
const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
|
|
460
|
-
if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
|
|
461
|
-
const ctx = { op: 'set', name, row: stored }
|
|
462
|
-
if ((await this._runBefore('set', ctx)) === false) return null
|
|
463
|
-
const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
|
|
464
|
-
await this.write([[`${insert ? 'add' : 'set'}-${ref.verb}`, ctx.row]])
|
|
465
|
-
return ctx
|
|
246
|
+
return this._done(await this.tx((tx) => tx._merge(name, row, opts)))
|
|
466
247
|
}
|
|
467
248
|
|
|
468
249
|
/**
|
|
@@ -475,12 +256,9 @@ export class Database extends ReadyResource {
|
|
|
475
256
|
async del(name, id) {
|
|
476
257
|
this.guard()
|
|
477
258
|
const ref = this.ref(name)
|
|
478
|
-
const ctx = { op: 'del', name, id }
|
|
479
|
-
if ((await this._runBefore('del', ctx)) === false) return null
|
|
480
259
|
// singles have no id, the dummy one just satisfies the shared del-by-id encoding
|
|
481
260
|
const payload = ref.kind === SINGLE ? { id: '' } : { id }
|
|
482
261
|
await this.write([[`del-${ref.verb}`, payload]])
|
|
483
|
-
await this._runAfter('del', ctx)
|
|
484
262
|
}
|
|
485
263
|
|
|
486
264
|
/**
|
|
@@ -502,12 +280,8 @@ export class Database extends ReadyResource {
|
|
|
502
280
|
}
|
|
503
281
|
|
|
504
282
|
/**
|
|
505
|
-
* Rotate the encryption epoch: generate a fresh 32-byte secret, seal it to
|
|
506
|
-
*
|
|
507
|
-
* The announcement is appended under the current epoch (so every member —
|
|
508
|
-
* even one offline for several rotations — can walk the chain forward),
|
|
509
|
-
* and blocks written after it use the new one. Members absent from the
|
|
510
|
-
* envelope set (removed before the rotation) never learn the new key.
|
|
283
|
+
* Rotate the encryption epoch: generate a fresh 32-byte secret, seal it to every current
|
|
284
|
+
* member's identity key, and announce it through the log.
|
|
511
285
|
*
|
|
512
286
|
* @returns {Promise<{ epoch: number }>}
|
|
513
287
|
*/
|
|
@@ -517,24 +291,9 @@ export class Database extends ReadyResource {
|
|
|
517
291
|
return this.rotation.rotate()
|
|
518
292
|
}
|
|
519
293
|
|
|
520
|
-
// apply-time hook: the log carries ops from a newer app version than this
|
|
521
|
-
// peer understands. Emits `behind` once per version so apps can prompt an
|
|
522
|
-
// upgrade; the marker survives restarts via local core userData
|
|
523
|
-
_onfuture(version) {
|
|
524
|
-
if (this.behind !== null && version <= this.behind) return
|
|
525
|
-
this.behind = version
|
|
526
|
-
this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
|
|
527
|
-
this.emit('behind', version)
|
|
528
|
-
}
|
|
529
|
-
|
|
530
294
|
/**
|
|
531
|
-
* Batch every write made through the transaction handle passed to `fn`
|
|
532
|
-
*
|
|
533
|
-
* write queue — same surface (`put`/`set`/`del`/`call`), but writes buffer
|
|
534
|
-
* until `fn` returns, and are discarded if it throws. Writes made on the
|
|
535
|
-
* database itself meanwhile append normally: an unrelated concurrent write
|
|
536
|
-
* can never be swallowed into (and rolled back with) a transaction.
|
|
537
|
-
* Nested `tx()` on the handle joins the same batch.
|
|
295
|
+
* Batch every write made through the transaction handle passed to `fn` into a single
|
|
296
|
+
* autobee append.
|
|
538
297
|
*
|
|
539
298
|
* @template T
|
|
540
299
|
* @param {(tx: Database) => Promise<T> | T} fn
|
|
@@ -577,55 +336,21 @@ export class Database extends ReadyResource {
|
|
|
577
336
|
for (const op of ops) this.txQueue.push(op)
|
|
578
337
|
return
|
|
579
338
|
}
|
|
580
|
-
|
|
581
|
-
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
339
|
+
this.guard()
|
|
582
340
|
if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
|
|
583
341
|
const encoded = ops.map(([op, payload]) =>
|
|
584
342
|
this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
|
|
585
343
|
)
|
|
586
|
-
// the dry
|
|
587
|
-
// reaches the log. An action ships anyway: it lives in routes, not in rows.
|
|
344
|
+
// the dry run refuses what apply would; a no-op never reaches the log, an action always does
|
|
588
345
|
const action = ops.some(([op]) => this.refs[op]?.kind === ACTION)
|
|
589
|
-
let changes
|
|
590
346
|
try {
|
|
591
|
-
|
|
347
|
+
if (!(await this._dryRun(encoded)) && !action) return
|
|
348
|
+
const wrapped = encoded.map((value) => wrap(this.version, value))
|
|
349
|
+
await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
|
|
592
350
|
} catch (err) {
|
|
593
351
|
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
594
352
|
throw err
|
|
595
353
|
}
|
|
596
|
-
// the dry-run awaits, close can start underneath it
|
|
597
|
-
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
598
|
-
if (!changes && !action) return
|
|
599
|
-
const wrapped = encoded.map((value) => wrap(this.version, value))
|
|
600
|
-
await this.bee.append(wrapped.length === 1 ? wrapped[0] : wrapped)
|
|
601
|
-
}
|
|
602
|
-
|
|
603
|
-
// every op runs in a throwaway transaction with host effects stubbed, so a
|
|
604
|
-
// throwing handler rejects the write and nothing enters the permanent log.
|
|
605
|
-
// Permission gates that `return` are not rejections, apply stays the
|
|
606
|
-
// authority at linearization time. Resolves whether the ops change anything
|
|
607
|
-
async _dryRun(encoded) {
|
|
608
|
-
const tx = this.view.transaction()
|
|
609
|
-
const host = { addWriter: async () => {}, removeWriter: async () => {} }
|
|
610
|
-
try {
|
|
611
|
-
for (const value of encoded) {
|
|
612
|
-
await this.dispatcher.dispatcher.dispatch(value, {
|
|
613
|
-
host,
|
|
614
|
-
view: tx,
|
|
615
|
-
key: this.writerKey,
|
|
616
|
-
dbKey: this.key,
|
|
617
|
-
dryRun: true
|
|
618
|
-
})
|
|
619
|
-
}
|
|
620
|
-
return tx.updated()
|
|
621
|
-
} finally {
|
|
622
|
-
// a failing close must not mask the handler's own rejection
|
|
623
|
-
try {
|
|
624
|
-
await tx.close()
|
|
625
|
-
} catch (err) {
|
|
626
|
-
safetyCatch(err)
|
|
627
|
-
}
|
|
628
|
-
}
|
|
629
354
|
}
|
|
630
355
|
|
|
631
356
|
/**
|
|
@@ -638,74 +363,28 @@ export class Database extends ReadyResource {
|
|
|
638
363
|
*/
|
|
639
364
|
async get(name, query) {
|
|
640
365
|
this.guard()
|
|
366
|
+
return this._read(this.view, name, query)
|
|
367
|
+
}
|
|
368
|
+
|
|
369
|
+
// the same read against any view: hooks read the transaction they run in
|
|
370
|
+
async _read(view, name, query) {
|
|
641
371
|
const ref = this.ref(name)
|
|
642
372
|
const col = this.col(ref)
|
|
643
373
|
|
|
644
374
|
if (ref.kind === SINGLE) {
|
|
645
|
-
return { data: await
|
|
375
|
+
return { data: await view.findOne(col, {}) }
|
|
646
376
|
}
|
|
647
377
|
|
|
648
378
|
if (typeof query === 'string') {
|
|
649
|
-
return { data: await
|
|
379
|
+
return { data: await view.get(col, { id: query }) }
|
|
650
380
|
}
|
|
651
381
|
|
|
652
382
|
const { path, range, rest, sorted } = this._plan(name, query)
|
|
653
|
-
const rows = await
|
|
383
|
+
const rows = await view.find(path, range).toArray()
|
|
654
384
|
if (!sorted) rows.sort(byIndex)
|
|
655
|
-
const
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
// one hyperdb read per query: the index that serves it, the bounds and the
|
|
660
|
-
// window pushed down when nothing else narrows the read, the rest in memory
|
|
661
|
-
_plan(name, query = {}) {
|
|
662
|
-
const ref = this.refs[name]
|
|
663
|
-
const col = `@${this.ns}/${name}`
|
|
664
|
-
const rest = { ...query }
|
|
665
|
-
const eq = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
|
|
666
|
-
const bounded = [...RANGE].some((k) => query[k] !== undefined)
|
|
667
|
-
const idx = eq.length ? matchIndex(ref?.indexes, eq) : null
|
|
668
|
-
if (idx) {
|
|
669
|
-
const point = {}
|
|
670
|
-
for (const f of eq) point[f] = query[f]
|
|
671
|
-
const range = { gte: point, lte: point }
|
|
672
|
-
if (!query.search && !bounded) pushWindow(range, rest)
|
|
673
|
-
return { path: `${col}-${idx}`, range, rest, sorted: true }
|
|
674
|
-
}
|
|
675
|
-
if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
|
|
676
|
-
if (bounded) {
|
|
677
|
-
const range = {}
|
|
678
|
-
for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
|
|
679
|
-
return { path: col, range, rest, sorted: false }
|
|
680
|
-
}
|
|
681
|
-
if (ref?.orderIndex) {
|
|
682
|
-
const range = {}
|
|
683
|
-
pushWindow(range, rest)
|
|
684
|
-
return { path: `${col}-index`, range, rest, sorted: true }
|
|
685
|
-
}
|
|
686
|
-
return { path: col, range: {}, rest, sorted: false }
|
|
687
|
-
}
|
|
688
|
-
|
|
689
|
-
// rows before the in-memory pass; unknown once a pushed-down limit filled the page
|
|
690
|
-
async _total(path, range, rows, query) {
|
|
691
|
-
if (range.limit === undefined || rows.length < range.limit) return rows.length
|
|
692
|
-
if (!query?.total) return null
|
|
693
|
-
const { limit, reverse, ...bounds } = range
|
|
694
|
-
return (await this.view.find(path, bounds).toArray()).length
|
|
695
|
-
}
|
|
696
|
-
|
|
697
|
-
/**
|
|
698
|
-
* Number of rows that match `query` (or total if omitted).
|
|
699
|
-
*
|
|
700
|
-
* @param {string} name
|
|
701
|
-
* @param {Query} [query]
|
|
702
|
-
* @returns {Promise<{ data: number }>}
|
|
703
|
-
*/
|
|
704
|
-
async count(name, query) {
|
|
705
|
-
this.guard()
|
|
706
|
-
this.ref(name)
|
|
707
|
-
const { path, range, rest } = this._plan(name, query)
|
|
708
|
-
return { data: filter(await this.view.find(path, range).toArray(), rest).length }
|
|
385
|
+
const matched = filter(rows, { ...rest, limit: undefined })
|
|
386
|
+
const data = rest.limit === undefined ? matched : matched.slice(0, rest.limit)
|
|
387
|
+
return { data, total: await this._total(view, path, range, matched, query), size: data.length }
|
|
709
388
|
}
|
|
710
389
|
|
|
711
390
|
/**
|
|
@@ -720,16 +399,12 @@ export class Database extends ReadyResource {
|
|
|
720
399
|
this.guard()
|
|
721
400
|
return subscribe({
|
|
722
401
|
get: () => this.get(name, query),
|
|
723
|
-
watch: (fn) => this.onUpdate(
|
|
402
|
+
watch: (fn) => this.onUpdate(name, fn)
|
|
724
403
|
})
|
|
725
404
|
}
|
|
726
405
|
|
|
727
406
|
/**
|
|
728
|
-
* Delta subscription: batches of `{ prev, next }` row pairs instead of
|
|
729
|
-
* full snapshots. The first batch (and any batch after a view swap) carries
|
|
730
|
-
* the current matching rows as inserts with `reset: true` — replaying every
|
|
731
|
-
* batch into a Map keyed by row id always reconstructs current state.
|
|
732
|
-
* `limit`/`reverse` are not applied; deltas are unwindowed by design.
|
|
407
|
+
* Delta subscription: batches of `{ prev, next }` row pairs instead of full snapshots.
|
|
733
408
|
*
|
|
734
409
|
* @param {string} name
|
|
735
410
|
* @param {Query} [query]
|
|
@@ -737,21 +412,14 @@ export class Database extends ReadyResource {
|
|
|
737
412
|
*/
|
|
738
413
|
changes(name, query = {}) {
|
|
739
414
|
this.guard()
|
|
740
|
-
const col =
|
|
741
|
-
if (!this.view.definition.resolveCollection(col)) {
|
|
742
|
-
throw CeroError.UNKNOWN('collection', name)
|
|
743
|
-
}
|
|
415
|
+
const col = this.col(this.ref(name))
|
|
744
416
|
const { limit, reverse, total, ...rest } = query
|
|
745
|
-
|
|
746
|
-
return makeChanges(this, name, col, matches)
|
|
417
|
+
return makeChanges(this, name, col, (row) => filter([row], rest).length > 0)
|
|
747
418
|
}
|
|
748
419
|
|
|
749
420
|
/**
|
|
750
|
-
* Provision this device. Its writer core was minted when the database opened
|
|
751
|
-
*
|
|
752
|
-
* a writer and a device in one write. A recovering device waits for the other
|
|
753
|
-
* devices' state, admits itself with the same master-signed add-writer
|
|
754
|
-
* appended optimistically, then records the device.
|
|
421
|
+
* Provision this device. Its writer core was minted when the database opened and this
|
|
422
|
+
* device is its only author, ever.
|
|
755
423
|
*
|
|
756
424
|
* @param {{ name?: string | null, isMobile?: boolean, recovering?: boolean, timeout?: number }} [opts]
|
|
757
425
|
* @returns {Promise<{ id: Uint8Array, writer: import('../identity/index.js').KeyPair }>}
|
|
@@ -770,22 +438,30 @@ export class Database extends ReadyResource {
|
|
|
770
438
|
updatedAt: ts
|
|
771
439
|
}
|
|
772
440
|
]
|
|
773
|
-
if (
|
|
774
|
-
await this.write([['add-writer', writer], device])
|
|
775
|
-
} else {
|
|
441
|
+
if (recovering) {
|
|
776
442
|
await this._backfilled(timeout)
|
|
777
443
|
await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
|
|
778
444
|
timeout
|
|
779
445
|
})
|
|
780
446
|
await this.write([device])
|
|
447
|
+
} else {
|
|
448
|
+
// one batch: a writer is never on the log without its member row
|
|
449
|
+
const member = {
|
|
450
|
+
id: this.identity.id,
|
|
451
|
+
key: this.writerKey,
|
|
452
|
+
role: 'owner',
|
|
453
|
+
name: name || null,
|
|
454
|
+
createdAt: ts,
|
|
455
|
+
updatedAt: ts
|
|
456
|
+
}
|
|
457
|
+
await this.write([['add-writer', writer], ['add-member', member], device])
|
|
781
458
|
}
|
|
782
459
|
return { id: this.writerKey, writer: this.keyPair }
|
|
783
460
|
}
|
|
784
461
|
|
|
785
462
|
/**
|
|
786
|
-
* Claim writership on an existing room by signing our writer key with the
|
|
787
|
-
*
|
|
788
|
-
* Admission only — the device is named separately (bootstrap → set-device).
|
|
463
|
+
* Claim writership on an existing room by signing our writer key with the member identity;
|
|
464
|
+
* the claim rides in the device core as an optimistic node.
|
|
789
465
|
*
|
|
790
466
|
* @returns {Promise<void>}
|
|
791
467
|
*/
|
|
@@ -829,13 +505,15 @@ export class Database extends ReadyResource {
|
|
|
829
505
|
}
|
|
830
506
|
|
|
831
507
|
/**
|
|
832
|
-
*
|
|
508
|
+
* Admit a device as a writer for `memberId`, an existing member. Omit it to
|
|
509
|
+
* admit another device of this identity.
|
|
833
510
|
*
|
|
834
511
|
* @param {Uint8Array} publicKey
|
|
512
|
+
* @param {string} [memberId]
|
|
835
513
|
* @returns {Promise<void>}
|
|
836
514
|
*/
|
|
837
|
-
async addWriter(publicKey) {
|
|
838
|
-
return this._admit('add-writer',
|
|
515
|
+
async addWriter(publicKey, memberId) {
|
|
516
|
+
return this._admit('add-writer', publicKey, memberId)
|
|
839
517
|
}
|
|
840
518
|
|
|
841
519
|
/**
|
|
@@ -845,34 +523,7 @@ export class Database extends ReadyResource {
|
|
|
845
523
|
* @returns {Promise<void>}
|
|
846
524
|
*/
|
|
847
525
|
async removeWriter(publicKey) {
|
|
848
|
-
return this._admit('del-writer',
|
|
849
|
-
}
|
|
850
|
-
|
|
851
|
-
// an append by a core not yet admitted: apply verifies the master signature
|
|
852
|
-
// and admits it, then the bee turns writable
|
|
853
|
-
async _optimistic(op, opts) {
|
|
854
|
-
await this.bee.append(wrap(this.version, op), { optimistic: true })
|
|
855
|
-
await this.bee.update()
|
|
856
|
-
if (!this.bee.writable) await this.whenWritable(opts)
|
|
857
|
-
}
|
|
858
|
-
|
|
859
|
-
// the genesis device row is the first thing every database writes, so any
|
|
860
|
-
// device row means the other devices' state has replicated and applied
|
|
861
|
-
async _backfilled(timeout) {
|
|
862
|
-
const deadline = Date.now() + timeout
|
|
863
|
-
while (Date.now() < deadline) {
|
|
864
|
-
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
865
|
-
if ((await this.get('devices')).data.length > 0) return
|
|
866
|
-
await this.bee.update()
|
|
867
|
-
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
868
|
-
}
|
|
869
|
-
throw CeroError.TIMED_OUT('recovery — no peer replicated')
|
|
870
|
-
}
|
|
871
|
-
|
|
872
|
-
// the add-writer row for `writer`, appended by this device and signed by the identity
|
|
873
|
-
_admission(writer, ts = Date.now()) {
|
|
874
|
-
const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
|
|
875
|
-
return { master: this.identity.publicKey, writer, sig, ts }
|
|
526
|
+
return this._admit('del-writer', publicKey)
|
|
876
527
|
}
|
|
877
528
|
|
|
878
529
|
/**
|
|
@@ -881,6 +532,9 @@ export class Database extends ReadyResource {
|
|
|
881
532
|
* @returns {void}
|
|
882
533
|
*/
|
|
883
534
|
guard() {
|
|
535
|
+
if (this._hooking) {
|
|
536
|
+
throw CeroError.INVALID('operators are not available inside a hook, use ctx.put / ctx.get')
|
|
537
|
+
}
|
|
884
538
|
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
885
539
|
if (!this.bee) throw CeroError.NOT_READY('Database', 'db')
|
|
886
540
|
}
|
|
@@ -910,6 +564,284 @@ export class Database extends ReadyResource {
|
|
|
910
564
|
return `@${this.ns}/${ref.name}`
|
|
911
565
|
}
|
|
912
566
|
|
|
567
|
+
// the boot reads post-rotation state through the keyring, primed before the bee exists
|
|
568
|
+
async _preload() {
|
|
569
|
+
const local = this.store.namespace(this.namespace).get({
|
|
570
|
+
keyPair: this.keyPair,
|
|
571
|
+
manifest: {
|
|
572
|
+
version: this.store.manifestVersion,
|
|
573
|
+
signers: [{ publicKey: this.keyPair.publicKey }]
|
|
574
|
+
},
|
|
575
|
+
active: false
|
|
576
|
+
})
|
|
577
|
+
await local.ready()
|
|
578
|
+
await loadEpochs(this.keyring, local)
|
|
579
|
+
await local.close()
|
|
580
|
+
}
|
|
581
|
+
|
|
582
|
+
async _boot() {
|
|
583
|
+
const bee = new EpochAutobee(this.store.namespace(this.namespace), this.key, {
|
|
584
|
+
keyPair: this.keyPair,
|
|
585
|
+
encryptionKey: this.encryptionKey,
|
|
586
|
+
keyring: this.keyring,
|
|
587
|
+
optimistic: true,
|
|
588
|
+
wakeup: this.network?.wakeup || undefined,
|
|
589
|
+
open: (b) => HyperDB.bee2(b, this.spec.database, { autoUpdate: true }),
|
|
590
|
+
isTrusted: this._isTrusted.bind(this),
|
|
591
|
+
apply: this._apply.bind(this),
|
|
592
|
+
update: this._update.bind(this)
|
|
593
|
+
})
|
|
594
|
+
// swarm BEFORE boot so the boot has peers to pull from, not a cold open
|
|
595
|
+
if (this.network && this.key) this._joinSwarm(bee, crypto.discoveryKey(this.key))
|
|
596
|
+
await bee.ready()
|
|
597
|
+
// apply-time hooks (rotation.learn, _onfuture) must never see this.bee null mid-drain
|
|
598
|
+
this.bee = bee
|
|
599
|
+
this.key = bee.key
|
|
600
|
+
await bee.update()
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
// ops skipped as too new apply once this version caught up: wipe the boot record and reboot
|
|
604
|
+
async _replay() {
|
|
605
|
+
const behind = await this.bee.local.getUserData('cero/behind')
|
|
606
|
+
this.behind = behind ? c.decode(c.uint, behind) : null
|
|
607
|
+
if (this.behind === null || this.behind > this.version) return false
|
|
608
|
+
await this.bee.local.setUserData('autobee/head', null)
|
|
609
|
+
await this.bee.local.setUserData('cero/behind', null)
|
|
610
|
+
await this.bee.close()
|
|
611
|
+
this.behind = null
|
|
612
|
+
return true
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// without this hook autobee trusts every fast-forward candidate, a removed device's fork included
|
|
616
|
+
async _isTrusted(writer, view) {
|
|
617
|
+
try {
|
|
618
|
+
const row = await bounded(view.get(`@${this.ns}/devices`, { id: hid.encode(writer) }))
|
|
619
|
+
if (!row) return false
|
|
620
|
+
if (row.v) return true
|
|
621
|
+
// only a provably empty view lets the genesis writer vouch: its core is the db key
|
|
622
|
+
const any = await bounded(view.find(`@${this.ns}/devices`, { limit: 1 }).toArray())
|
|
623
|
+
if (!any) return false
|
|
624
|
+
return any.v.length === 0 && !!this.key && b4a.equals(writer, this.key)
|
|
625
|
+
} catch {
|
|
626
|
+
return false
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
|
|
630
|
+
// unwrap once so the dispatcher sees op bytes. Skipping a newer version is deterministic
|
|
631
|
+
async _apply(nodes, view, host) {
|
|
632
|
+
const ready = []
|
|
633
|
+
for (const node of nodes) {
|
|
634
|
+
const { version, body } = unwrap(node.value)
|
|
635
|
+
if (version > this.version) {
|
|
636
|
+
this._onfuture(version)
|
|
637
|
+
continue
|
|
638
|
+
}
|
|
639
|
+
ready.push(version === 0 ? node : { ...node, value: body })
|
|
640
|
+
}
|
|
641
|
+
const result = await this.dispatcher.apply(ready, view, host)
|
|
642
|
+
this._notify(ready)
|
|
643
|
+
return result
|
|
644
|
+
}
|
|
645
|
+
|
|
646
|
+
// 'update' carries the refs the batch touched; '*' means any, so a scoped watcher can skip
|
|
647
|
+
async _update(db) {
|
|
648
|
+
await db.update()
|
|
649
|
+
const touched = this._touched
|
|
650
|
+
this._touched = new Set()
|
|
651
|
+
this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
|
|
652
|
+
this._presence?.touch()
|
|
653
|
+
}
|
|
654
|
+
|
|
655
|
+
// a writer swap re-opens the bee on the same topic, so the slot is the same one
|
|
656
|
+
_joinSwarm(bee, discoveryKey) {
|
|
657
|
+
this.network.attach(bee)
|
|
658
|
+
this._presence = this.network.presence.add(discoveryKey, { pinned: this.pinned })
|
|
659
|
+
}
|
|
660
|
+
|
|
661
|
+
// wrapped so an operator called from inside a hook fails instead of appending its own op
|
|
662
|
+
_hooks(phase, op) {
|
|
663
|
+
const fns = (phase === 'before' ? this._before : this._after).get(op)
|
|
664
|
+
return fns?.length ? fns.map((fn) => this._inHook(fn)) : NO_HOOKS
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
_inHook(fn) {
|
|
668
|
+
return async (ctx) => {
|
|
669
|
+
this._hooking++
|
|
670
|
+
try {
|
|
671
|
+
return await fn(ctx)
|
|
672
|
+
} finally {
|
|
673
|
+
this._hooking--
|
|
674
|
+
}
|
|
675
|
+
}
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
// an 'update' listener for one ref; the disposer detaches it
|
|
679
|
+
onUpdate(name, fn) {
|
|
680
|
+
const tick = (touched) => {
|
|
681
|
+
if (touched.has('*') || touched.has(name)) fn()
|
|
682
|
+
}
|
|
683
|
+
this.on('update', tick)
|
|
684
|
+
return () => this.off('update', tick)
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
// '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
|
|
688
|
+
_opOf(node) {
|
|
689
|
+
const { name, value } = this.spec.dispatch.decode(node.value)
|
|
690
|
+
const verb = name.slice(name.indexOf('/') + 1)
|
|
691
|
+
const dash = verb.indexOf('-')
|
|
692
|
+
if (dash < 0) return { op: verb, name: verb, value }
|
|
693
|
+
return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
// marks the refs a batch touched and emits 'apply' per op, local and replicated alike
|
|
697
|
+
_notify(nodes) {
|
|
698
|
+
const listened = this.listenerCount('apply') > 0
|
|
699
|
+
for (const node of nodes) {
|
|
700
|
+
let op
|
|
701
|
+
try {
|
|
702
|
+
op = this._opOf(node)
|
|
703
|
+
} catch (err) {
|
|
704
|
+
this._touched.add('*')
|
|
705
|
+
safetyCatch(err)
|
|
706
|
+
continue
|
|
707
|
+
}
|
|
708
|
+
const ref = this._verbs.get(op.name)
|
|
709
|
+
// an action's route handler writes wherever it wants, widen to all
|
|
710
|
+
this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
|
|
711
|
+
if (!listened) continue
|
|
712
|
+
this.emit('apply', {
|
|
713
|
+
op: op.op,
|
|
714
|
+
name: op.name,
|
|
715
|
+
row: op.value,
|
|
716
|
+
writerKey: node.key,
|
|
717
|
+
seq: this._seq++
|
|
718
|
+
})
|
|
719
|
+
}
|
|
720
|
+
}
|
|
721
|
+
|
|
722
|
+
async _merge(name, row, { upsert = true } = {}) {
|
|
723
|
+
const ref = this._prepare(name, row)
|
|
724
|
+
const existing = ref.kind === SINGLE || row?.id ? (await this.get(name, row?.id)).data : null
|
|
725
|
+
if (!upsert && !existing) return null
|
|
726
|
+
const ts = Date.now()
|
|
727
|
+
const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
|
|
728
|
+
if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
|
|
729
|
+
const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
|
|
730
|
+
return this._append(stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
|
|
731
|
+
}
|
|
732
|
+
|
|
733
|
+
_prepare(name, row) {
|
|
734
|
+
this.guard()
|
|
735
|
+
const ref = this.ref(name)
|
|
736
|
+
this._checkFields(name, row)
|
|
737
|
+
return ref
|
|
738
|
+
}
|
|
739
|
+
|
|
740
|
+
async _append(stored, verb) {
|
|
741
|
+
await this.write([[verb, stored]])
|
|
742
|
+
return { row: stored }
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
_done(ctx) {
|
|
746
|
+
return ctx ? { data: ctx.row } : null
|
|
747
|
+
}
|
|
748
|
+
|
|
749
|
+
// ops from a newer app version: emit behind once per version, the marker survives restarts
|
|
750
|
+
_onfuture(version) {
|
|
751
|
+
if (this.behind !== null && version <= this.behind) return
|
|
752
|
+
this.behind = version
|
|
753
|
+
this.bee.local.setUserData('cero/behind', c.encode(c.uint, version)).catch(this._onerror)
|
|
754
|
+
this.emit('behind', version)
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// every op runs in a throwaway transaction with host effects stubbed; a throwing handler rejects the write
|
|
758
|
+
async _dryRun(encoded) {
|
|
759
|
+
const tx = this.view.transaction()
|
|
760
|
+
const host = { addWriter: async () => {}, removeWriter: async () => {} }
|
|
761
|
+
try {
|
|
762
|
+
for (const value of encoded) {
|
|
763
|
+
await this.dispatcher.dispatch(value, {
|
|
764
|
+
host,
|
|
765
|
+
view: tx,
|
|
766
|
+
key: this.writerKey,
|
|
767
|
+
dbKey: this.key,
|
|
768
|
+
seed: crypto.hash([this.writerKey, value]),
|
|
769
|
+
dryRun: true
|
|
770
|
+
})
|
|
771
|
+
}
|
|
772
|
+
return tx.updated()
|
|
773
|
+
} finally {
|
|
774
|
+
// a failing close must not mask the handler's own rejection
|
|
775
|
+
try {
|
|
776
|
+
await tx.close()
|
|
777
|
+
} catch (err) {
|
|
778
|
+
safetyCatch(err)
|
|
779
|
+
}
|
|
780
|
+
}
|
|
781
|
+
}
|
|
782
|
+
|
|
783
|
+
// one hyperdb read per query: index, bounds and window pushed down, the rest filtered in memory
|
|
784
|
+
_plan(name, query = {}) {
|
|
785
|
+
const ref = this.refs[name]
|
|
786
|
+
const col = `@${this.ns}/${name}`
|
|
787
|
+
const rest = { ...query }
|
|
788
|
+
const eq = Object.keys(query).filter((k) => !QUERY_RESERVED.has(k))
|
|
789
|
+
const bounded = [...RANGE].some((k) => query[k] !== undefined)
|
|
790
|
+
const idx = eq.length ? matchIndex(ref?.indexes, eq) : null
|
|
791
|
+
if (idx) {
|
|
792
|
+
const point = {}
|
|
793
|
+
for (const f of eq) point[f] = query[f]
|
|
794
|
+
const range = { gte: point, lte: point }
|
|
795
|
+
if (!query.search && !bounded) pushWindow(range, rest)
|
|
796
|
+
return { path: `${col}-${idx}`, range, rest, sorted: true }
|
|
797
|
+
}
|
|
798
|
+
if (eq.length || query.search) return { path: col, range: {}, rest, sorted: false }
|
|
799
|
+
if (bounded) {
|
|
800
|
+
const range = {}
|
|
801
|
+
for (const k of RANGE) if (query[k] !== undefined) range[k] = { id: query[k] }
|
|
802
|
+
return { path: col, range, rest, sorted: false }
|
|
803
|
+
}
|
|
804
|
+
if (ref?.orderIndex) {
|
|
805
|
+
const range = {}
|
|
806
|
+
pushWindow(range, rest)
|
|
807
|
+
return { path: `${col}-index`, range, rest, sorted: true }
|
|
808
|
+
}
|
|
809
|
+
return { path: col, range: {}, rest, sorted: false }
|
|
810
|
+
}
|
|
811
|
+
|
|
812
|
+
// matched rows; unknown once a pushed-down limit filled the page
|
|
813
|
+
async _total(view, path, range, matched, query) {
|
|
814
|
+
if (range.limit === undefined || matched.length < range.limit) return matched.length
|
|
815
|
+
if (!query?.total) return null
|
|
816
|
+
const { limit, reverse, ...bounds } = range
|
|
817
|
+
return (await view.find(path, bounds).toArray()).length
|
|
818
|
+
}
|
|
819
|
+
|
|
820
|
+
// an append by a core not yet admitted: apply verifies the signature and admits it
|
|
821
|
+
async _optimistic(op, opts) {
|
|
822
|
+
await this.bee.append(wrap(this.version, op), { optimistic: true })
|
|
823
|
+
await this.bee.update()
|
|
824
|
+
if (!this.bee.writable) await this.whenWritable(opts)
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
// the genesis device row is the first write of every database, so any device row means backfilled
|
|
828
|
+
async _backfilled(timeout) {
|
|
829
|
+
const deadline = Date.now() + timeout
|
|
830
|
+
while (Date.now() < deadline) {
|
|
831
|
+
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
832
|
+
if ((await this.get('devices')).data.length > 0) return
|
|
833
|
+
await this.bee.update()
|
|
834
|
+
await new Promise((resolve) => setTimeout(resolve, 50))
|
|
835
|
+
}
|
|
836
|
+
throw CeroError.TIMED_OUT('recovery — no peer replicated')
|
|
837
|
+
}
|
|
838
|
+
|
|
839
|
+
// the add-writer row for `writer`, appended by this device and signed by the identity
|
|
840
|
+
_admission(writer, ts = Date.now()) {
|
|
841
|
+
const sig = this.identity.sign(admission(this.key, writer, this.writerKey))
|
|
842
|
+
return { master: this.identity.publicKey, writer, sig, ts }
|
|
843
|
+
}
|
|
844
|
+
|
|
913
845
|
// the encoder silently drops an undeclared field, so the returned row would lie
|
|
914
846
|
_checkFields(name, row) {
|
|
915
847
|
const declared = this.refs[name]?.fields
|
|
@@ -922,19 +854,15 @@ export class Database extends ReadyResource {
|
|
|
922
854
|
}
|
|
923
855
|
}
|
|
924
856
|
|
|
925
|
-
async _admit(verb,
|
|
857
|
+
async _admit(verb, publicKey, memberId) {
|
|
926
858
|
this.guard()
|
|
927
859
|
if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
|
|
928
|
-
const ctx = { op: hook, publicKey }
|
|
929
|
-
if ((await this._runBefore(hook, ctx)) === false) return
|
|
930
860
|
const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
|
|
931
|
-
await this.write([[verb, this._admission(writer)]])
|
|
932
|
-
await this._runAfter(hook, ctx)
|
|
861
|
+
await this.write([[verb, { ...this._admission(writer), memberId }]])
|
|
933
862
|
}
|
|
934
863
|
}
|
|
935
864
|
|
|
936
|
-
//
|
|
937
|
-
// and an unbounded read there wedges autobee's drain forever. null means untrusted.
|
|
865
|
+
// an unbounded read of an old checkout wedges autobee's drain; null means untrusted
|
|
938
866
|
function bounded(promise, ms = 2000) {
|
|
939
867
|
return Promise.race([
|
|
940
868
|
promise.then((v) => ({ v })),
|
|
@@ -942,6 +870,8 @@ function bounded(promise, ms = 2000) {
|
|
|
942
870
|
])
|
|
943
871
|
}
|
|
944
872
|
|
|
873
|
+
const NO_HOOKS = []
|
|
874
|
+
|
|
945
875
|
function addHook(map, op, fn) {
|
|
946
876
|
if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
|
|
947
877
|
let arr = map.get(op)
|