@cero-base/core 2.0.0 → 2.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/database/changes.js +1 -1
- package/src/database/dispatch.js +180 -36
- package/src/database/index.js +125 -142
- package/src/network/index.js +6 -1
- package/src/network/presence.js +131 -0
- package/src/storage/index.js +5 -20
- package/types/database/dispatch.d.ts +9 -1
- package/types/database/index.d.ts +101 -61
- package/types/network/index.d.ts +12 -1
- package/types/network/presence.d.ts +50 -0
- package/types/storage/index.d.ts +0 -10
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,15 +28,31 @@ 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
|
/**
|
|
@@ -77,7 +85,7 @@ export class Database extends ReadyResource {
|
|
|
77
85
|
if (opts.epochs) for (const e of opts.epochs) this.keyring.add(e.stamp, e.entropy, e.epoch)
|
|
78
86
|
this.rotation = new Rotation(this)
|
|
79
87
|
this.key = opts.key || null
|
|
80
|
-
this.
|
|
88
|
+
this.pinned = opts.pinned === true
|
|
81
89
|
this.keyPair = opts.keyPair || Identity.randomKeyPair()
|
|
82
90
|
if (b4a.equals(this.keyPair.publicKey, this.identity.publicKey)) {
|
|
83
91
|
throw CeroError.INVALID('the identity keypair is never a writer — use a device keypair')
|
|
@@ -86,16 +94,17 @@ export class Database extends ReadyResource {
|
|
|
86
94
|
this._onerror = opts.onerror || safetyCatch
|
|
87
95
|
this.bee = null
|
|
88
96
|
this.dispatcher = null
|
|
89
|
-
this.
|
|
97
|
+
this._presence = null
|
|
90
98
|
this._txChain = null
|
|
91
99
|
|
|
92
100
|
this._before = new Map()
|
|
93
101
|
this._after = new Map()
|
|
94
|
-
this.
|
|
95
|
-
this._observers = new Set()
|
|
102
|
+
this._hooking = 0
|
|
96
103
|
this._verbs = verbMap(this.refs)
|
|
97
104
|
this._touched = new Set()
|
|
98
105
|
this._seq = 0
|
|
106
|
+
// every watch and changes stream is an 'update' listener
|
|
107
|
+
this.setMaxListeners(0)
|
|
99
108
|
this.txQueue = null
|
|
100
109
|
}
|
|
101
110
|
|
|
@@ -134,7 +143,11 @@ export class Database extends ReadyResource {
|
|
|
134
143
|
routes: this.routes,
|
|
135
144
|
onerror: this._onerror,
|
|
136
145
|
key: () => this.key,
|
|
137
|
-
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)
|
|
138
151
|
})
|
|
139
152
|
|
|
140
153
|
const known = !!this.key
|
|
@@ -155,15 +168,13 @@ export class Database extends ReadyResource {
|
|
|
155
168
|
|
|
156
169
|
// a fresh db has no key until boot mints it
|
|
157
170
|
if (this.network && !known) this._joinSwarm(this.bee, this.bee.discoveryKey)
|
|
158
|
-
if (replayed) this.emit('rebuild')
|
|
159
171
|
}
|
|
160
172
|
|
|
161
173
|
async _close() {
|
|
162
174
|
this.rotation.close()
|
|
163
|
-
if (this.
|
|
164
|
-
|
|
165
|
-
this.
|
|
166
|
-
this._discovery = null
|
|
175
|
+
if (this._presence) {
|
|
176
|
+
this._presence.remove()
|
|
177
|
+
this._presence = null
|
|
167
178
|
}
|
|
168
179
|
if (this.bee) {
|
|
169
180
|
// detach first, else the closed bee replicates into every new connection
|
|
@@ -174,19 +185,20 @@ export class Database extends ReadyResource {
|
|
|
174
185
|
}
|
|
175
186
|
|
|
176
187
|
/**
|
|
177
|
-
*
|
|
178
|
-
*
|
|
188
|
+
* `true` ranks this database as just touched, `false` takes it out of the swarm until the
|
|
189
|
+
* next update lands in it.
|
|
179
190
|
*
|
|
180
191
|
* @param {boolean} active
|
|
181
|
-
* @returns {Promise<void>}
|
|
182
192
|
*/
|
|
183
|
-
|
|
184
|
-
if (!this.
|
|
185
|
-
|
|
193
|
+
setActive(active) {
|
|
194
|
+
if (!this._presence) return
|
|
195
|
+
if (active) this._presence.touch()
|
|
196
|
+
else this._presence.off()
|
|
186
197
|
}
|
|
187
198
|
|
|
188
199
|
/**
|
|
189
|
-
* 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.
|
|
190
202
|
*
|
|
191
203
|
* @param {string} op
|
|
192
204
|
* @param {HookFn} fn
|
|
@@ -197,7 +209,8 @@ export class Database extends ReadyResource {
|
|
|
197
209
|
}
|
|
198
210
|
|
|
199
211
|
/**
|
|
200
|
-
* 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`.
|
|
201
214
|
*
|
|
202
215
|
* @param {string} op
|
|
203
216
|
* @param {HookFn} fn
|
|
@@ -207,31 +220,6 @@ export class Database extends ReadyResource {
|
|
|
207
220
|
return addHook(this._after, op, fn)
|
|
208
221
|
}
|
|
209
222
|
|
|
210
|
-
/**
|
|
211
|
-
* Subscribe to local apply notifications. Fires whenever the view updates;
|
|
212
|
-
* pass `scope` (a ref name) to fire only when that ref was touched.
|
|
213
|
-
*
|
|
214
|
-
* @param {() => void} fn
|
|
215
|
-
* @param {string} [scope]
|
|
216
|
-
* @returns {() => void} disposer
|
|
217
|
-
*/
|
|
218
|
-
onUpdate(fn, scope) {
|
|
219
|
-
this._updaters.set(fn, scope || null)
|
|
220
|
-
return () => this._updaters.delete(fn)
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Observe every applied op — local AND replicated (apply processes the merged log).
|
|
225
|
-
*
|
|
226
|
-
* @param {(event: { op: string, name: string, row: any, writerKey: any, seq: number }) => void} fn
|
|
227
|
-
* @returns {() => void} disposer
|
|
228
|
-
*/
|
|
229
|
-
onApply(fn) {
|
|
230
|
-
if (typeof fn !== 'function') return () => {}
|
|
231
|
-
this._observers.add(fn)
|
|
232
|
-
return () => this._observers.delete(fn)
|
|
233
|
-
}
|
|
234
|
-
|
|
235
223
|
/**
|
|
236
224
|
* Insert (or overwrite by id) a row, stamping `id`/`createdAt`/`updatedAt`.
|
|
237
225
|
*
|
|
@@ -243,7 +231,7 @@ export class Database extends ReadyResource {
|
|
|
243
231
|
const ref = this._prepare(name, row)
|
|
244
232
|
const ts = Date.now()
|
|
245
233
|
const stored = { createdAt: ts, updatedAt: ts, ...row, id: row.id || genId() }
|
|
246
|
-
return this._done(
|
|
234
|
+
return this._done(await this._append(stored, `add-${ref.verb}`))
|
|
247
235
|
}
|
|
248
236
|
|
|
249
237
|
/**
|
|
@@ -255,7 +243,7 @@ export class Database extends ReadyResource {
|
|
|
255
243
|
* @returns {Promise<SingleResult | null>}
|
|
256
244
|
*/
|
|
257
245
|
async set(name, row, opts) {
|
|
258
|
-
return this._done(
|
|
246
|
+
return this._done(await this.tx((tx) => tx._merge(name, row, opts)))
|
|
259
247
|
}
|
|
260
248
|
|
|
261
249
|
/**
|
|
@@ -268,12 +256,9 @@ export class Database extends ReadyResource {
|
|
|
268
256
|
async del(name, id) {
|
|
269
257
|
this.guard()
|
|
270
258
|
const ref = this.ref(name)
|
|
271
|
-
const ctx = { op: 'del', name, id }
|
|
272
|
-
if ((await this._runBefore('del', ctx)) === false) return null
|
|
273
259
|
// singles have no id, the dummy one just satisfies the shared del-by-id encoding
|
|
274
260
|
const payload = ref.kind === SINGLE ? { id: '' } : { id }
|
|
275
261
|
await this.write([[`del-${ref.verb}`, payload]])
|
|
276
|
-
await this._runAfter('del', ctx)
|
|
277
262
|
}
|
|
278
263
|
|
|
279
264
|
/**
|
|
@@ -353,6 +338,8 @@ export class Database extends ReadyResource {
|
|
|
353
338
|
}
|
|
354
339
|
this.guard()
|
|
355
340
|
if (!this.bee.writable) throw CeroError.NOT_WRITABLE('Database')
|
|
341
|
+
// writable flips inside the apply that admits us, before its view flush lands our device row
|
|
342
|
+
await this.bee.updated()
|
|
356
343
|
const encoded = ops.map(([op, payload]) =>
|
|
357
344
|
this.spec.dispatch.encode(`@${this.ns}/${op}`, payload)
|
|
358
345
|
)
|
|
@@ -378,36 +365,28 @@ export class Database extends ReadyResource {
|
|
|
378
365
|
*/
|
|
379
366
|
async get(name, query) {
|
|
380
367
|
this.guard()
|
|
368
|
+
return this._read(this.view, name, query)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// the same read against any view: hooks read the transaction they run in
|
|
372
|
+
async _read(view, name, query) {
|
|
381
373
|
const ref = this.ref(name)
|
|
382
374
|
const col = this.col(ref)
|
|
383
375
|
|
|
384
376
|
if (ref.kind === SINGLE) {
|
|
385
|
-
return { data: await
|
|
377
|
+
return { data: await view.findOne(col, {}) }
|
|
386
378
|
}
|
|
387
379
|
|
|
388
380
|
if (typeof query === 'string') {
|
|
389
|
-
return { data: await
|
|
381
|
+
return { data: await view.get(col, { id: query }) }
|
|
390
382
|
}
|
|
391
383
|
|
|
392
384
|
const { path, range, rest, sorted } = this._plan(name, query)
|
|
393
|
-
const rows = await
|
|
385
|
+
const rows = await view.find(path, range).toArray()
|
|
394
386
|
if (!sorted) rows.sort(byIndex)
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
/**
|
|
400
|
-
* Number of rows that match `query` (or total if omitted).
|
|
401
|
-
*
|
|
402
|
-
* @param {string} name
|
|
403
|
-
* @param {Query} [query]
|
|
404
|
-
* @returns {Promise<{ data: number }>}
|
|
405
|
-
*/
|
|
406
|
-
async count(name, query) {
|
|
407
|
-
this.guard()
|
|
408
|
-
this.ref(name)
|
|
409
|
-
const { path, range, rest } = this._plan(name, query)
|
|
410
|
-
return { data: filter(await this.view.find(path, range).toArray(), rest).length }
|
|
387
|
+
const matched = filter(rows, { ...rest, limit: undefined })
|
|
388
|
+
const data = rest.limit === undefined ? matched : matched.slice(0, rest.limit)
|
|
389
|
+
return { data, total: await this._total(view, path, range, matched, query), size: data.length }
|
|
411
390
|
}
|
|
412
391
|
|
|
413
392
|
/**
|
|
@@ -422,7 +401,7 @@ export class Database extends ReadyResource {
|
|
|
422
401
|
this.guard()
|
|
423
402
|
return subscribe({
|
|
424
403
|
get: () => this.get(name, query),
|
|
425
|
-
watch: (fn) => this.onUpdate(
|
|
404
|
+
watch: (fn) => this.onUpdate(name, fn)
|
|
426
405
|
})
|
|
427
406
|
}
|
|
428
407
|
|
|
@@ -461,14 +440,23 @@ export class Database extends ReadyResource {
|
|
|
461
440
|
updatedAt: ts
|
|
462
441
|
}
|
|
463
442
|
]
|
|
464
|
-
if (
|
|
465
|
-
await this.write([['add-writer', writer], device])
|
|
466
|
-
} else {
|
|
443
|
+
if (recovering) {
|
|
467
444
|
await this._backfilled(timeout)
|
|
468
445
|
await this._optimistic(this.spec.dispatch.encode(`@${this.ns}/add-writer`, writer), {
|
|
469
446
|
timeout
|
|
470
447
|
})
|
|
471
448
|
await this.write([device])
|
|
449
|
+
} else {
|
|
450
|
+
// one batch: a writer is never on the log without its member row
|
|
451
|
+
const member = {
|
|
452
|
+
id: this.identity.id,
|
|
453
|
+
key: this.writerKey,
|
|
454
|
+
role: 'owner',
|
|
455
|
+
name: name || null,
|
|
456
|
+
createdAt: ts,
|
|
457
|
+
updatedAt: ts
|
|
458
|
+
}
|
|
459
|
+
await this.write([['add-writer', writer], ['add-member', member], device])
|
|
472
460
|
}
|
|
473
461
|
return { id: this.writerKey, writer: this.keyPair }
|
|
474
462
|
}
|
|
@@ -519,13 +507,15 @@ export class Database extends ReadyResource {
|
|
|
519
507
|
}
|
|
520
508
|
|
|
521
509
|
/**
|
|
522
|
-
*
|
|
510
|
+
* Admit a device as a writer for `memberId`, an existing member. Omit it to
|
|
511
|
+
* admit another device of this identity.
|
|
523
512
|
*
|
|
524
513
|
* @param {Uint8Array} publicKey
|
|
514
|
+
* @param {string} [memberId]
|
|
525
515
|
* @returns {Promise<void>}
|
|
526
516
|
*/
|
|
527
|
-
async addWriter(publicKey) {
|
|
528
|
-
return this._admit('add-writer',
|
|
517
|
+
async addWriter(publicKey, memberId) {
|
|
518
|
+
return this._admit('add-writer', publicKey, memberId)
|
|
529
519
|
}
|
|
530
520
|
|
|
531
521
|
/**
|
|
@@ -535,7 +525,7 @@ export class Database extends ReadyResource {
|
|
|
535
525
|
* @returns {Promise<void>}
|
|
536
526
|
*/
|
|
537
527
|
async removeWriter(publicKey) {
|
|
538
|
-
return this._admit('del-writer',
|
|
528
|
+
return this._admit('del-writer', publicKey)
|
|
539
529
|
}
|
|
540
530
|
|
|
541
531
|
/**
|
|
@@ -544,6 +534,9 @@ export class Database extends ReadyResource {
|
|
|
544
534
|
* @returns {void}
|
|
545
535
|
*/
|
|
546
536
|
guard() {
|
|
537
|
+
if (this._hooking) {
|
|
538
|
+
throw CeroError.INVALID('operators are not available inside a hook, use ctx.put / ctx.get')
|
|
539
|
+
}
|
|
547
540
|
if (this.closing || this.closed) throw CeroError.CLOSED('Database')
|
|
548
541
|
if (!this.bee) throw CeroError.NOT_READY('Database', 'db')
|
|
549
542
|
}
|
|
@@ -648,48 +641,49 @@ export class Database extends ReadyResource {
|
|
|
648
641
|
ready.push(version === 0 ? node : { ...node, value: body })
|
|
649
642
|
}
|
|
650
643
|
const result = await this.dispatcher.apply(ready, view, host)
|
|
651
|
-
|
|
644
|
+
this._notify(ready)
|
|
652
645
|
return result
|
|
653
646
|
}
|
|
654
647
|
|
|
648
|
+
// 'update' carries the refs the batch touched; '*' means any, so a scoped watcher can skip
|
|
655
649
|
async _update(db) {
|
|
656
650
|
await db.update()
|
|
657
651
|
const touched = this._touched
|
|
658
652
|
this._touched = new Set()
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
if (all || !scope || touched.has(scope)) fn()
|
|
662
|
-
}
|
|
663
|
-
this.emit('update')
|
|
653
|
+
this.emit('update', touched.size === 0 ? new Set(['*']) : touched)
|
|
654
|
+
this._presence?.touch()
|
|
664
655
|
}
|
|
665
656
|
|
|
666
|
-
// a writer swap re-opens the bee on the
|
|
657
|
+
// a writer swap re-opens the bee on the same topic, so the slot is the same one
|
|
667
658
|
_joinSwarm(bee, discoveryKey) {
|
|
668
659
|
this.network.attach(bee)
|
|
669
|
-
|
|
670
|
-
this._discovery = this.network.join(discoveryKey, {
|
|
671
|
-
mode: this.passive ? PASSIVE : ACTIVE
|
|
672
|
-
})
|
|
673
|
-
if (prev) prev.destroy().catch(safetyCatch)
|
|
660
|
+
this._presence = this.network.presence.add(discoveryKey, { pinned: this.pinned })
|
|
674
661
|
}
|
|
675
662
|
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
this.emit(`before:${op}`, ctx)
|
|
681
|
-
return true
|
|
663
|
+
// wrapped so an operator called from inside a hook fails instead of appending its own op
|
|
664
|
+
_hooks(phase, op) {
|
|
665
|
+
const fns = (phase === 'before' ? this._before : this._after).get(op)
|
|
666
|
+
return fns?.length ? fns.map((fn) => this._inHook(fn)) : NO_HOOKS
|
|
682
667
|
}
|
|
683
668
|
|
|
684
|
-
|
|
685
|
-
|
|
669
|
+
_inHook(fn) {
|
|
670
|
+
return async (ctx) => {
|
|
671
|
+
this._hooking++
|
|
686
672
|
try {
|
|
687
|
-
await fn(ctx)
|
|
688
|
-
}
|
|
689
|
-
this.
|
|
673
|
+
return await fn(ctx)
|
|
674
|
+
} finally {
|
|
675
|
+
this._hooking--
|
|
690
676
|
}
|
|
691
677
|
}
|
|
692
|
-
|
|
678
|
+
}
|
|
679
|
+
|
|
680
|
+
// an 'update' listener for one ref; the disposer detaches it
|
|
681
|
+
onUpdate(name, fn) {
|
|
682
|
+
const tick = (touched) => {
|
|
683
|
+
if (touched.has('*') || touched.has(name)) fn()
|
|
684
|
+
}
|
|
685
|
+
this.on('update', tick)
|
|
686
|
+
return () => this.off('update', tick)
|
|
693
687
|
}
|
|
694
688
|
|
|
695
689
|
// '@cero/set-messages' → { op: 'set', name: 'messages' }; an action has no dash
|
|
@@ -701,8 +695,9 @@ export class Database extends ReadyResource {
|
|
|
701
695
|
return { op: verb.slice(0, dash), name: verb.slice(dash + 1), value }
|
|
702
696
|
}
|
|
703
697
|
|
|
704
|
-
//
|
|
698
|
+
// marks the refs a batch touched and emits 'apply' per op, local and replicated alike
|
|
705
699
|
_notify(nodes) {
|
|
700
|
+
const listened = this.listenerCount('apply') > 0
|
|
706
701
|
for (const node of nodes) {
|
|
707
702
|
let op
|
|
708
703
|
try {
|
|
@@ -715,21 +710,14 @@ export class Database extends ReadyResource {
|
|
|
715
710
|
const ref = this._verbs.get(op.name)
|
|
716
711
|
// an action's route handler writes wherever it wants, widen to all
|
|
717
712
|
this._touched.add(ref && this.refs[ref].kind !== ACTION ? ref : '*')
|
|
718
|
-
if (!
|
|
719
|
-
|
|
713
|
+
if (!listened) continue
|
|
714
|
+
this.emit('apply', {
|
|
720
715
|
op: op.op,
|
|
721
716
|
name: op.name,
|
|
722
717
|
row: op.value,
|
|
723
718
|
writerKey: node.key,
|
|
724
719
|
seq: this._seq++
|
|
725
|
-
}
|
|
726
|
-
for (const fn of this._observers) {
|
|
727
|
-
try {
|
|
728
|
-
fn(event)
|
|
729
|
-
} catch (err) {
|
|
730
|
-
this._onerror(err)
|
|
731
|
-
}
|
|
732
|
-
}
|
|
720
|
+
})
|
|
733
721
|
}
|
|
734
722
|
}
|
|
735
723
|
|
|
@@ -741,7 +729,7 @@ export class Database extends ReadyResource {
|
|
|
741
729
|
const stored = { ...existing, ...row, createdAt: existing?.createdAt ?? ts, updatedAt: ts }
|
|
742
730
|
if (ref.kind === COLLECTION && !stored.id) stored.id = genId()
|
|
743
731
|
const insert = ref.kind === COLLECTION && upsert && !BESPOKE.has(ref.verb)
|
|
744
|
-
return this._append(
|
|
732
|
+
return this._append(stored, `${insert ? 'add' : 'set'}-${ref.verb}`)
|
|
745
733
|
}
|
|
746
734
|
|
|
747
735
|
_prepare(name, row) {
|
|
@@ -751,18 +739,13 @@ export class Database extends ReadyResource {
|
|
|
751
739
|
return ref
|
|
752
740
|
}
|
|
753
741
|
|
|
754
|
-
async _append(
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
await this.write([[verb, ctx.row]])
|
|
758
|
-
return ctx
|
|
742
|
+
async _append(stored, verb) {
|
|
743
|
+
await this.write([[verb, stored]])
|
|
744
|
+
return { row: stored }
|
|
759
745
|
}
|
|
760
746
|
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
const result = { data: ctx.row }
|
|
764
|
-
await this._runAfter(op, { ...ctx, result })
|
|
765
|
-
return result
|
|
747
|
+
_done(ctx) {
|
|
748
|
+
return ctx ? { data: ctx.row } : null
|
|
766
749
|
}
|
|
767
750
|
|
|
768
751
|
// ops from a newer app version: emit behind once per version, the marker survives restarts
|
|
@@ -784,6 +767,7 @@ export class Database extends ReadyResource {
|
|
|
784
767
|
view: tx,
|
|
785
768
|
key: this.writerKey,
|
|
786
769
|
dbKey: this.key,
|
|
770
|
+
seed: crypto.hash([this.writerKey, value]),
|
|
787
771
|
dryRun: true
|
|
788
772
|
})
|
|
789
773
|
}
|
|
@@ -827,12 +811,12 @@ export class Database extends ReadyResource {
|
|
|
827
811
|
return { path: col, range: {}, rest, sorted: false }
|
|
828
812
|
}
|
|
829
813
|
|
|
830
|
-
// rows
|
|
831
|
-
async _total(path, range,
|
|
832
|
-
if (range.limit === undefined ||
|
|
814
|
+
// matched rows; unknown once a pushed-down limit filled the page
|
|
815
|
+
async _total(view, path, range, matched, query) {
|
|
816
|
+
if (range.limit === undefined || matched.length < range.limit) return matched.length
|
|
833
817
|
if (!query?.total) return null
|
|
834
818
|
const { limit, reverse, ...bounds } = range
|
|
835
|
-
return (await
|
|
819
|
+
return (await view.find(path, bounds).toArray()).length
|
|
836
820
|
}
|
|
837
821
|
|
|
838
822
|
// an append by a core not yet admitted: apply verifies the signature and admits it
|
|
@@ -872,14 +856,11 @@ export class Database extends ReadyResource {
|
|
|
872
856
|
}
|
|
873
857
|
}
|
|
874
858
|
|
|
875
|
-
async _admit(verb,
|
|
859
|
+
async _admit(verb, publicKey, memberId) {
|
|
876
860
|
this.guard()
|
|
877
861
|
if (!b4a.isBuffer(publicKey)) throw CeroError.INVALID('publicKey must be a buffer')
|
|
878
|
-
const ctx = { op: hook, publicKey }
|
|
879
|
-
if ((await this._runBefore(hook, ctx)) === false) return
|
|
880
862
|
const writer = Hypercore.key({ version: this.store.manifestVersion, signers: [{ publicKey }] })
|
|
881
|
-
await this.write([[verb, this._admission(writer)]])
|
|
882
|
-
await this._runAfter(hook, ctx)
|
|
863
|
+
await this.write([[verb, { ...this._admission(writer), memberId }]])
|
|
883
864
|
}
|
|
884
865
|
}
|
|
885
866
|
|
|
@@ -891,6 +872,8 @@ function bounded(promise, ms = 2000) {
|
|
|
891
872
|
])
|
|
892
873
|
}
|
|
893
874
|
|
|
875
|
+
const NO_HOOKS = []
|
|
876
|
+
|
|
894
877
|
function addHook(map, op, fn) {
|
|
895
878
|
if (typeof fn !== 'function') throw CeroError.INVALID('hook fn must be a function')
|
|
896
879
|
let arr = map.get(op)
|
package/src/network/index.js
CHANGED
|
@@ -15,6 +15,7 @@ import c from 'compact-encoding'
|
|
|
15
15
|
import { ACTIVE, PASSIVE } from '../lib/constants.js'
|
|
16
16
|
import { CeroError } from '../lib/errors.js'
|
|
17
17
|
import { Discovery } from './discovery.js'
|
|
18
|
+
import { Presence } from './presence.js'
|
|
18
19
|
|
|
19
20
|
export function channelTopic(topic, channel) {
|
|
20
21
|
return channel ? hash([topic, b4a.from(channel)]) : topic
|
|
@@ -30,6 +31,7 @@ export function channelTopic(topic, channel) {
|
|
|
30
31
|
* @property {string} [channel] Optional network-isolation label; only same-channel peers meet.
|
|
31
32
|
* @property {any} [store] Corestore; required for mirrors (blind peers replicate its cores).
|
|
32
33
|
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys; each attached room/blob core is mirrored through them for offline sync.
|
|
34
|
+
* @property {{ active?: number, announced?: number, idle?: number }} [presence] Swarm budget for attached databases: how many search, how many only announce, and the idle ms before the rest leave.
|
|
33
35
|
*
|
|
34
36
|
* @typedef {{ replicate: (stream: any) => any }} Replicable
|
|
35
37
|
*/
|
|
@@ -48,7 +50,8 @@ export class Network extends ReadyResource {
|
|
|
48
50
|
backoffs,
|
|
49
51
|
channel,
|
|
50
52
|
store,
|
|
51
|
-
mirrors
|
|
53
|
+
mirrors,
|
|
54
|
+
presence
|
|
52
55
|
} = {}) {
|
|
53
56
|
super()
|
|
54
57
|
this.identity = identity || null
|
|
@@ -62,6 +65,7 @@ export class Network extends ReadyResource {
|
|
|
62
65
|
|
|
63
66
|
this._swarm = null
|
|
64
67
|
this.wakeup = new ProtomuxWakeup()
|
|
68
|
+
this.presence = new Presence(this, presence)
|
|
65
69
|
|
|
66
70
|
this.info = null
|
|
67
71
|
this._peerInfo = new Map()
|
|
@@ -137,6 +141,7 @@ export class Network extends ReadyResource {
|
|
|
137
141
|
this._injected.clear()
|
|
138
142
|
|
|
139
143
|
// stop discovery now, never await the DHT unannounce round-trips
|
|
144
|
+
this.presence.close()
|
|
140
145
|
for (const d of [...this._discoveries]) d.destroy().catch(safetyCatch)
|
|
141
146
|
this._discoveries.clear()
|
|
142
147
|
|