@cero-base/cero 2.10.0 → 2.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +5 -5
- package/src/build/schemas.js +1 -1
- package/src/handle/index.js +68 -12
- package/src/index.js +57 -17
- package/src/lib/constants.js +3 -0
- package/src/lib/peek.js +3 -1
- package/src/lib/swap.js +121 -0
- package/src/push/index.js +2 -1
- package/src/rpc/server.js +39 -7
- package/types/handle/index.d.ts +17 -0
- package/types/index.d.ts +5 -0
- package/types/lib/constants.d.ts +1 -0
- package/types/lib/swap.d.ts +38 -0
- package/types/rpc/server.d.ts +8 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cero-base/cero",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.11.0",
|
|
4
4
|
"description": "The ideal p2p API — everything is a handle, handles contain refs, refs contain rows.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -113,7 +113,7 @@
|
|
|
113
113
|
"test:node": "find test -name '*.test.js' | sort | xargs -P4 -n1 brittle-node"
|
|
114
114
|
},
|
|
115
115
|
"dependencies": {
|
|
116
|
-
"@cero-base/core": "^2.
|
|
116
|
+
"@cero-base/core": "^2.11.0",
|
|
117
117
|
"b4a": "^1.9.0",
|
|
118
118
|
"bare-abort-controller": "^1.1.2",
|
|
119
119
|
"bare-crypto": "^1.15.4",
|
|
@@ -123,7 +123,7 @@
|
|
|
123
123
|
"compact-encoding": "^3.5.2",
|
|
124
124
|
"corestore": "^7.16.1",
|
|
125
125
|
"hrpc": "^4.3.1",
|
|
126
|
-
"hypercore": "^11.
|
|
126
|
+
"hypercore": "^11.40.0",
|
|
127
127
|
"hypercore-crypto": "^3.7.0",
|
|
128
128
|
"hypercore-id-encoding": "^1.3.0",
|
|
129
129
|
"hypercore-storage": "^3.4.0",
|
|
@@ -142,8 +142,8 @@
|
|
|
142
142
|
"bare-events": "^2.9.2",
|
|
143
143
|
"bare-fetch": "^3.4.1",
|
|
144
144
|
"bare-process": "^4.5.1",
|
|
145
|
-
"bare-url": "^2.5.
|
|
146
|
-
"blind-peer": "^3.
|
|
145
|
+
"bare-url": "^2.5.6",
|
|
146
|
+
"blind-peer": "^3.18.1",
|
|
147
147
|
"brittle": "^4.5.0",
|
|
148
148
|
"typescript": "^7.0.2"
|
|
149
149
|
},
|
package/src/build/schemas.js
CHANGED
|
@@ -242,7 +242,7 @@ export const local = {
|
|
|
242
242
|
|
|
243
243
|
// what a write means to apply. A release that changes it without changing what is stored bumps
|
|
244
244
|
// this, so an app's next build raises its contract and devices on the old release skip the new writes
|
|
245
|
-
export const contract = { version:
|
|
245
|
+
export const contract = { version: 2 }
|
|
246
246
|
|
|
247
247
|
export const rpc = {
|
|
248
248
|
'req-empty': {
|
package/src/handle/index.js
CHANGED
|
@@ -22,7 +22,7 @@ import { Blobs } from '@cero-base/core/blobs'
|
|
|
22
22
|
import { decodeId } from '@cero-base/core/blobs/codec'
|
|
23
23
|
import { FileServer } from '@cero-base/core/blobs/server'
|
|
24
24
|
|
|
25
|
-
import { NS, TIMEOUT } from '../lib/constants.js'
|
|
25
|
+
import { LINGER, NS, TIMEOUT } from '../lib/constants.js'
|
|
26
26
|
|
|
27
27
|
import { Ref } from '../lib/refs.js'
|
|
28
28
|
import { Join, wait } from './join.js'
|
|
@@ -146,6 +146,12 @@ export class Handle extends ReadyResource {
|
|
|
146
146
|
: new Suspendify({ suspend: () => this._sleep(), resume: () => this._wake() })
|
|
147
147
|
/** @private */
|
|
148
148
|
this._owned = new Set()
|
|
149
|
+
// a child's holders: open hands every caller on this device the same handle, so each close lets one go and the
|
|
150
|
+
// last one lets it linger
|
|
151
|
+
/** @private */
|
|
152
|
+
this._refs = 0
|
|
153
|
+
/** @private */
|
|
154
|
+
this._idle = null
|
|
149
155
|
|
|
150
156
|
this.store = new Database({
|
|
151
157
|
store: store,
|
|
@@ -303,24 +309,27 @@ export class Handle extends ReadyResource {
|
|
|
303
309
|
this._owned.clear()
|
|
304
310
|
if (this._discovery) this._discovery.destroy().catch(safetyCatch)
|
|
305
311
|
|
|
312
|
+
const root = !this.parent
|
|
306
313
|
const steps = [
|
|
307
314
|
...[...(this._joining?.values() || [])].map((join) => () => join.close()),
|
|
315
|
+
// mirroring stops before any database closes, once the mailbox is done with it: blind peering reads
|
|
316
|
+
// storage for each database it mirrors
|
|
317
|
+
...(root ? [() => this.mailbox.close(), () => this.network.closePeering()] : []),
|
|
308
318
|
() => this._blobs?.close(),
|
|
309
319
|
...[...(this._epochBlobs?.values() || [])].map((b) => () => b.close()),
|
|
310
|
-
...[...(this.children || [])].map((c) => () => c.
|
|
311
|
-
...[...(this._pending || [])].map((c) => () => c.
|
|
320
|
+
...[...(this.children || [])].map((c) => () => c._end()),
|
|
321
|
+
...[...(this._pending || [])].map((c) => () => c._end()),
|
|
312
322
|
() => this._pair?.close()
|
|
313
323
|
]
|
|
314
324
|
this._epochBlobs = null
|
|
315
325
|
this.children?.clear()
|
|
316
326
|
|
|
317
|
-
if (
|
|
327
|
+
if (!root) {
|
|
318
328
|
this.parent.children?.delete(this)
|
|
319
329
|
steps.push(() => this.store.close())
|
|
320
330
|
} else {
|
|
321
331
|
const store = this.store.store
|
|
322
332
|
steps.push(
|
|
323
|
-
() => this.mailbox.close(),
|
|
324
333
|
() => this._bluetooth?.close(),
|
|
325
334
|
() => this.local.close(),
|
|
326
335
|
async () => {
|
|
@@ -418,7 +427,45 @@ export class Handle extends ReadyResource {
|
|
|
418
427
|
if (!this.parent) throw CeroError.INVALID('the root cannot be left')
|
|
419
428
|
await this.store.del('members', this.identity.id)
|
|
420
429
|
await this.parent.store.call('del-handle', { id: hid.encode(this.store.key) })
|
|
421
|
-
await this.
|
|
430
|
+
await this._end()
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/**
|
|
434
|
+
* One holder done with it: a child stays open for the others. With its last it lingers `linger` ms (20s by
|
|
435
|
+
* default) and closes unless opened again meanwhile, so a quick reopen finds it still open. The root closes at once.
|
|
436
|
+
* @returns {Promise<void>}
|
|
437
|
+
*/
|
|
438
|
+
close() {
|
|
439
|
+
if (!this.parent) return this._end()
|
|
440
|
+
if (this._refs > 1) {
|
|
441
|
+
this._refs--
|
|
442
|
+
return Promise.resolve()
|
|
443
|
+
}
|
|
444
|
+
if (this._idle) return Promise.resolve()
|
|
445
|
+
const linger = this.root._opts.linger ?? LINGER
|
|
446
|
+
if (!linger || this._refs === 0) return this._end()
|
|
447
|
+
this._refs = 0
|
|
448
|
+
this._idle = setTimeout(() => this._end().catch(this._onerror), linger)
|
|
449
|
+
this._idle.unref?.()
|
|
450
|
+
return Promise.resolve()
|
|
451
|
+
}
|
|
452
|
+
|
|
453
|
+
/**
|
|
454
|
+
* Closed for every holder at once: its linger over, the parent closing, or the handle left for good.
|
|
455
|
+
* @private
|
|
456
|
+
*/
|
|
457
|
+
/** @private one more holder: a lingering handle is kept */
|
|
458
|
+
_hold() {
|
|
459
|
+
clearTimeout(this._idle)
|
|
460
|
+
this._idle = null
|
|
461
|
+
this._refs++
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
_end() {
|
|
465
|
+
clearTimeout(this._idle)
|
|
466
|
+
this._idle = null
|
|
467
|
+
this._refs = 0
|
|
468
|
+
return super.close()
|
|
422
469
|
}
|
|
423
470
|
|
|
424
471
|
// the app going to the background and back: networking, storage and the radio together
|
|
@@ -602,6 +649,7 @@ export class Handle extends ReadyResource {
|
|
|
602
649
|
|
|
603
650
|
/** @private */
|
|
604
651
|
async _send(address, value, { keep = true } = {}) {
|
|
652
|
+
if (this.root.closing) throw CeroError.CLOSED('Mailbox')
|
|
605
653
|
const to = decodeAddress(address)
|
|
606
654
|
await this.root.mailbox.send(to, seal(this.identity, to, value), { keep })
|
|
607
655
|
}
|
|
@@ -797,7 +845,7 @@ export class Handle extends ReadyResource {
|
|
|
797
845
|
const reason = this.closing || this.closed ? CeroError.CLOSED('Handle') : err
|
|
798
846
|
if (abort) abort(reason)
|
|
799
847
|
if (inflightId) this._loading?.delete(inflightId)
|
|
800
|
-
await child.
|
|
848
|
+
await child._end().catch(safetyCatch)
|
|
801
849
|
throw reason
|
|
802
850
|
}
|
|
803
851
|
}
|
|
@@ -820,7 +868,11 @@ export class Handle extends ReadyResource {
|
|
|
820
868
|
const join = this._start(invite, type)
|
|
821
869
|
join.waiting++
|
|
822
870
|
try {
|
|
823
|
-
|
|
871
|
+
const child = await wait(join.done, timeout)
|
|
872
|
+
// every caller holds the room: the first takes the open the join made, each other one its own
|
|
873
|
+
if (join.claimed) child._hold()
|
|
874
|
+
join.claimed = true
|
|
875
|
+
return child
|
|
824
876
|
} finally {
|
|
825
877
|
join.waiting--
|
|
826
878
|
}
|
|
@@ -864,7 +916,7 @@ export class Handle extends ReadyResource {
|
|
|
864
916
|
const { data: device } = await known.store.get('devices', hid.encode(known.store.writerKey))
|
|
865
917
|
// a reader never had a seat, a removed writer lost it
|
|
866
918
|
if (me && (device || me.role === 'reader')) return known
|
|
867
|
-
await known.
|
|
919
|
+
await known._end().catch(safetyCatch)
|
|
868
920
|
return null
|
|
869
921
|
}
|
|
870
922
|
|
|
@@ -924,7 +976,7 @@ export class Handle extends ReadyResource {
|
|
|
924
976
|
} catch (err) {
|
|
925
977
|
if (abort) abort(err)
|
|
926
978
|
if (inflightId) this._loading?.delete(inflightId)
|
|
927
|
-
await child.
|
|
979
|
+
await child._end().catch(safetyCatch)
|
|
928
980
|
throw err
|
|
929
981
|
}
|
|
930
982
|
}
|
|
@@ -960,7 +1012,10 @@ export class Handle extends ReadyResource {
|
|
|
960
1012
|
if (open && open.type !== type) {
|
|
961
1013
|
throw CeroError.INVALID(`handle ${id} is type ${open.type}, not ${type}`)
|
|
962
1014
|
}
|
|
963
|
-
if (open)
|
|
1015
|
+
if (open) {
|
|
1016
|
+
open._hold()
|
|
1017
|
+
return open
|
|
1018
|
+
}
|
|
964
1019
|
const reopening = this._reopen(type, id)
|
|
965
1020
|
this._loading.set(id, reopening)
|
|
966
1021
|
try {
|
|
@@ -1007,7 +1062,7 @@ export class Handle extends ReadyResource {
|
|
|
1007
1062
|
}
|
|
1008
1063
|
this._adopt(child, {})
|
|
1009
1064
|
} catch (err) {
|
|
1010
|
-
await child.
|
|
1065
|
+
await child._end().catch(safetyCatch)
|
|
1011
1066
|
throw err
|
|
1012
1067
|
}
|
|
1013
1068
|
return child
|
|
@@ -1045,6 +1100,7 @@ export class Handle extends ReadyResource {
|
|
|
1045
1100
|
if (this.closing || this.closed) throw CeroError.CLOSED('Handle')
|
|
1046
1101
|
this._pending.delete(child)
|
|
1047
1102
|
this.children.add(child)
|
|
1103
|
+
child._refs = 1
|
|
1048
1104
|
this._serve(child)
|
|
1049
1105
|
this._carry(child)
|
|
1050
1106
|
this._prune(child).catch(this._onerror)
|
package/src/index.js
CHANGED
|
@@ -6,6 +6,7 @@ import c from 'compact-encoding'
|
|
|
6
6
|
import b4a from 'b4a'
|
|
7
7
|
import hid from 'hypercore-id-encoding'
|
|
8
8
|
import fs from 'fs'
|
|
9
|
+
import AbortController from 'bare-abort-controller'
|
|
9
10
|
|
|
10
11
|
import { Identity } from '@cero-base/core/identity'
|
|
11
12
|
import { Network } from '@cero-base/core/network'
|
|
@@ -23,6 +24,7 @@ import { peek } from './lib/peek.js'
|
|
|
23
24
|
import { address } from './lib/mail.js'
|
|
24
25
|
import { t, schema } from './lib/spec.js'
|
|
25
26
|
import { FLUSH, TIMEOUT } from './lib/constants.js'
|
|
27
|
+
import { commit, nextOf, settle, staging } from './lib/swap.js'
|
|
26
28
|
|
|
27
29
|
export { Handle, Ref, Local }
|
|
28
30
|
export * from './lib/operators.js'
|
|
@@ -50,6 +52,7 @@ export { t, schema } from './lib/spec.js'
|
|
|
50
52
|
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Handles and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
|
|
51
53
|
* @property {{ active?: number, announced?: number, idle?: number }} [presence] How many handles search, how many only announce, and the idle ms before the rest leave the swarm.
|
|
52
54
|
* @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
|
|
55
|
+
* @property {number} [linger] Ms a handle stays open after its last close, for a quick reopen; 0 closes at once. Defaults to 20000.
|
|
53
56
|
* @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
|
|
54
57
|
* @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
|
|
55
58
|
* @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
|
|
@@ -72,6 +75,7 @@ async function start(dir, spec, opts = {}) {
|
|
|
72
75
|
throw CeroError.INVALID('bluetooth takes { on, topic, pipe, maxOutbound, maxInbound }')
|
|
73
76
|
}
|
|
74
77
|
|
|
78
|
+
await settle(dir)
|
|
75
79
|
const storage = new HypercoreStorage(`${dir}/main`)
|
|
76
80
|
let store = null
|
|
77
81
|
let local = null
|
|
@@ -168,6 +172,8 @@ async function start(dir, spec, opts = {}) {
|
|
|
168
172
|
await pointer.ready()
|
|
169
173
|
network.attach(pointer)
|
|
170
174
|
|
|
175
|
+
// a swap replaced while it waits stops reading
|
|
176
|
+
opts.signal?.addEventListener('abort', () => pointer.close().catch(safetyCatch))
|
|
171
177
|
const key = recovering ? await readPointer(pointer, timeout) : linked?.key
|
|
172
178
|
|
|
173
179
|
me = new Handle({
|
|
@@ -244,14 +250,7 @@ export async function restore(me, phrase) {
|
|
|
244
250
|
|
|
245
251
|
const current = await Identity.create({ seed: Identity.toSeed(phrase) })
|
|
246
252
|
if (current.id === me.identity.id) return me
|
|
247
|
-
|
|
248
|
-
// everything carries over except the identity, the channel above all
|
|
249
|
-
const { _dir: dir, spec, _opts: opts } = me
|
|
250
|
-
|
|
251
|
-
await me.close()
|
|
252
|
-
await fs.promises.rm(`${dir}/main`, { recursive: true, force: true })
|
|
253
|
-
|
|
254
|
-
return start(dir, spec, { ...opts, phrase })
|
|
253
|
+
return swap(me, { phrase })
|
|
255
254
|
}
|
|
256
255
|
|
|
257
256
|
/**
|
|
@@ -266,14 +265,48 @@ export async function restore(me, phrase) {
|
|
|
266
265
|
export async function link(me, invite, { onrequest } = {}) {
|
|
267
266
|
if (!me?._dir) throw CeroError.INVALID('me must be a cero instance')
|
|
268
267
|
if (!invite) throw CeroError.REQUIRED('invite')
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
await me.close()
|
|
273
|
-
await fs.promises.rm(`${dir}/main`, { recursive: true, force: true })
|
|
274
|
-
|
|
268
|
+
const device = Invite.parse(invite).data?.byteLength === 32
|
|
269
|
+
if (!device) throw CeroError.INVALID_INVITE('not a device invite')
|
|
275
270
|
// the other device is in someone's other hand: the wait is the invite's lifetime, deny ends it
|
|
276
|
-
return
|
|
271
|
+
return swap(me, { invite, onrequest, recoveryTimeout: 0 })
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
// Another identity comes in beside this one: `me` stays open and untouched until the new one has opened, so a
|
|
275
|
+
// failed, denied or replaced restore or link leaves the device as it was. A newer swap replaces one still waiting
|
|
276
|
+
async function swap(me, opts) {
|
|
277
|
+
await me._swap?.abort()
|
|
278
|
+
if (me.closing || me.closed) throw CeroError.CLOSED('Handle')
|
|
279
|
+
// everything carries over except the identity, the channel above all
|
|
280
|
+
const { _dir: dir, spec, _opts: was } = me
|
|
281
|
+
const carried = { ...was, phrase: undefined, invite: undefined, onrequest: undefined }
|
|
282
|
+
const ac = new AbortController()
|
|
283
|
+
let finished = () => {}
|
|
284
|
+
const done = new Promise((resolve) => (finished = resolve))
|
|
285
|
+
const running = { abort: () => (ac.abort(), done) }
|
|
286
|
+
me._swap = running
|
|
287
|
+
try {
|
|
288
|
+
// one radio: the incoming identity takes it while it opens, and gives it back if it does not
|
|
289
|
+
await me._bluetooth?.suspend()
|
|
290
|
+
await staging(dir, async () => {
|
|
291
|
+
let opened = null
|
|
292
|
+
try {
|
|
293
|
+
opened = await start(nextOf(dir), spec, { ...carried, ...opts, signal: ac.signal })
|
|
294
|
+
if (ac.signal.aborted) throw CeroError.CLOSED('Swap')
|
|
295
|
+
await opened.close()
|
|
296
|
+
} catch (err) {
|
|
297
|
+
await opened?.close().catch(safetyCatch)
|
|
298
|
+
await me._bluetooth?.resume().catch(safetyCatch)
|
|
299
|
+
throw ac.signal.aborted ? CeroError.CLOSED('Swap') : err
|
|
300
|
+
}
|
|
301
|
+
// past here the new identity is whole on disk: a failed rename leaves main.old for the next launch to settle
|
|
302
|
+
await me.close()
|
|
303
|
+
await commit(dir)
|
|
304
|
+
})
|
|
305
|
+
return await start(dir, spec, carried)
|
|
306
|
+
} finally {
|
|
307
|
+
if (me._swap === running) me._swap = null
|
|
308
|
+
finished()
|
|
309
|
+
}
|
|
277
310
|
}
|
|
278
311
|
|
|
279
312
|
// the facade: cero.put and import { put } are the same function
|
|
@@ -318,7 +351,7 @@ async function pendingLink(local) {
|
|
|
318
351
|
|
|
319
352
|
// the root's join: this device, bare, knocks with the invite and waits for a device of the identity
|
|
320
353
|
// to let it in. What it learns is kept in its joins row, so a killed launch resumes it
|
|
321
|
-
async function ask(local, network, spec, { invite, writer, onrequest, timeout }, pending) {
|
|
354
|
+
async function ask(local, network, spec, { invite, writer, onrequest, timeout, signal }, pending) {
|
|
322
355
|
const parsed = Invite.parse(invite ?? pending.invite)
|
|
323
356
|
if (parsed.data?.byteLength !== 32) throw CeroError.INVALID_INVITE('not a device invite')
|
|
324
357
|
const secret = pending?.device ?? Identity.randomKeyPair().secretKey
|
|
@@ -353,7 +386,14 @@ async function ask(local, network, spec, { invite, writer, onrequest, timeout },
|
|
|
353
386
|
await local.store.put('joins', kept)
|
|
354
387
|
}
|
|
355
388
|
const identity = await Identity.bare(device)
|
|
356
|
-
reply = await Pairing.join(mailbox, row.invite, {
|
|
389
|
+
reply = await Pairing.join(mailbox, row.invite, {
|
|
390
|
+
identity,
|
|
391
|
+
spec,
|
|
392
|
+
writer,
|
|
393
|
+
timeout,
|
|
394
|
+
keep,
|
|
395
|
+
signal
|
|
396
|
+
})
|
|
357
397
|
} finally {
|
|
358
398
|
await mailbox.close()
|
|
359
399
|
}
|
package/src/lib/constants.js
CHANGED
|
@@ -8,3 +8,6 @@ export const SPENT = 'spent'
|
|
|
8
8
|
// Writer-admission / pairing timeout (ms), and the initial discovery-flush wait (ms).
|
|
9
9
|
export const TIMEOUT = 30000
|
|
10
10
|
export const FLUSH = 500
|
|
11
|
+
|
|
12
|
+
// How long a handle its last holder closed stays open for a quick reopen (ms).
|
|
13
|
+
export const LINGER = 20000
|
package/src/lib/peek.js
CHANGED
|
@@ -5,6 +5,7 @@ import safetyCatch from 'safety-catch'
|
|
|
5
5
|
import { CeroError } from '@cero-base/core/errors'
|
|
6
6
|
|
|
7
7
|
import { Local } from '../local/index.js'
|
|
8
|
+
import { current } from './swap.js'
|
|
8
9
|
|
|
9
10
|
// outside operators.js so storage deps stay off the client's module graph
|
|
10
11
|
|
|
@@ -21,7 +22,8 @@ export async function peek(dir, spec) {
|
|
|
21
22
|
if (!spec) throw CeroError.REQUIRED('spec')
|
|
22
23
|
|
|
23
24
|
// construct first, ready inside the try: a corrupt dir must still close everything
|
|
24
|
-
|
|
25
|
+
// a swap killed between its renames: the store a launch will open, never a new empty one
|
|
26
|
+
const root = new HypercoreStorage(await current(dir))
|
|
25
27
|
const store = new Corestore(root, { manifestVersion: 2 })
|
|
26
28
|
const local = new Local(null, spec, { store })
|
|
27
29
|
try {
|
package/src/lib/swap.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import fs from 'fs'
|
|
2
|
+
|
|
3
|
+
// Another identity comes in beside `main`, in `main.next`, and takes its place only once it has opened: the new store
|
|
4
|
+
// is flushed to disk, then main moves to `main.old` and `main.next/main` to `main`, each rename atomic. A launch reads
|
|
5
|
+
// from what is on disk how far a killed swap got
|
|
6
|
+
const NEXT = 'main.next'
|
|
7
|
+
const OLD = 'main.old'
|
|
8
|
+
|
|
9
|
+
// the dirs a swap is running in, in this process: their `main.next` is in use
|
|
10
|
+
const running = new Set()
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Where the incoming identity opens.
|
|
14
|
+
*
|
|
15
|
+
* @param {string} dir
|
|
16
|
+
* @returns {string}
|
|
17
|
+
*/
|
|
18
|
+
export const nextOf = (dir) => `${dir}/${NEXT}`
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* The store a launch of `dir` opens, without moving anything: `main`, or with a swap killed between its renames,
|
|
22
|
+
* the identity `settle` will keep.
|
|
23
|
+
*
|
|
24
|
+
* @param {string} dir
|
|
25
|
+
* @returns {Promise<string>}
|
|
26
|
+
*/
|
|
27
|
+
export async function current(dir) {
|
|
28
|
+
const main = `${dir}/main`
|
|
29
|
+
if ((await exists(main)) || !(await exists(`${dir}/${OLD}`))) return main
|
|
30
|
+
return (await exists(`${nextOf(dir)}/main`)) ? `${nextOf(dir)}/main` : `${dir}/${OLD}`
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* A swap killed part way, finished or undone before anything opens `dir`: past its first rename the incoming
|
|
35
|
+
* identity had opened, so it takes main's place; without it the old one comes back. What a killed swap left
|
|
36
|
+
* in `main.next` goes, unless a swap is running there.
|
|
37
|
+
*
|
|
38
|
+
* @param {string} dir
|
|
39
|
+
*/
|
|
40
|
+
export async function settle(dir) {
|
|
41
|
+
const main = `${dir}/main`
|
|
42
|
+
const old = `${dir}/${OLD}`
|
|
43
|
+
if (await exists(old)) {
|
|
44
|
+
if (!(await exists(main))) await fs.promises.rename(await current(dir), main)
|
|
45
|
+
await rm(old)
|
|
46
|
+
}
|
|
47
|
+
if (!running.has(dir)) await rm(nextOf(dir))
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/**
|
|
51
|
+
* Run `fn` with `dir/main.next` set aside for it, emptied before and after.
|
|
52
|
+
*
|
|
53
|
+
* @template T
|
|
54
|
+
* @param {string} dir
|
|
55
|
+
* @param {() => Promise<T>} fn
|
|
56
|
+
* @returns {Promise<T>}
|
|
57
|
+
*/
|
|
58
|
+
export async function staging(dir, fn) {
|
|
59
|
+
running.add(dir)
|
|
60
|
+
try {
|
|
61
|
+
await rm(nextOf(dir))
|
|
62
|
+
return await fn()
|
|
63
|
+
} catch (err) {
|
|
64
|
+
await rm(nextOf(dir))
|
|
65
|
+
throw err
|
|
66
|
+
} finally {
|
|
67
|
+
running.delete(dir)
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* The identity opened and closed in `main.next` takes main's place. Both must be closed.
|
|
73
|
+
*
|
|
74
|
+
* @param {string} dir
|
|
75
|
+
*/
|
|
76
|
+
export async function commit(dir) {
|
|
77
|
+
const incoming = `${nextOf(dir)}/main`
|
|
78
|
+
await durable(incoming)
|
|
79
|
+
await fs.promises.rename(`${dir}/main`, `${dir}/${OLD}`)
|
|
80
|
+
await fs.promises.rename(incoming, `${dir}/main`)
|
|
81
|
+
await sync(dir, true)
|
|
82
|
+
await rm(`${dir}/${OLD}`)
|
|
83
|
+
await rm(nextOf(dir))
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
// every file and directory under `path` on disk, so a rename that follows never points at data still in a cache
|
|
87
|
+
async function durable(path) {
|
|
88
|
+
for (const entry of await fs.promises.readdir(path, { withFileTypes: true })) {
|
|
89
|
+
const at = `${path}/${entry.name}`
|
|
90
|
+
if (entry.isDirectory()) await durable(at)
|
|
91
|
+
else if (entry.isFile()) await sync(at, false)
|
|
92
|
+
}
|
|
93
|
+
await sync(path, true)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
// a platform that cannot open a directory to flush it (Windows) skips the directory; a file must flush
|
|
97
|
+
async function sync(path, dir) {
|
|
98
|
+
let handle
|
|
99
|
+
try {
|
|
100
|
+
handle = await fs.promises.open(path, 'r')
|
|
101
|
+
} catch (err) {
|
|
102
|
+
if (dir) return
|
|
103
|
+
throw err
|
|
104
|
+
}
|
|
105
|
+
try {
|
|
106
|
+
await handle.sync()
|
|
107
|
+
} finally {
|
|
108
|
+
await handle.close()
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function exists(path) {
|
|
113
|
+
return fs.promises.stat(path).then(
|
|
114
|
+
() => true,
|
|
115
|
+
() => false
|
|
116
|
+
)
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
function rm(path) {
|
|
120
|
+
return fs.promises.rm(path, { recursive: true, force: true })
|
|
121
|
+
}
|
package/src/push/index.js
CHANGED
|
@@ -9,6 +9,7 @@ import { CeroError } from '@cero-base/core/errors'
|
|
|
9
9
|
import { epochEntries } from '@cero-base/core/database/encryption'
|
|
10
10
|
|
|
11
11
|
import { Local } from '../local/index.js'
|
|
12
|
+
import { current } from '../lib/swap.js'
|
|
12
13
|
|
|
13
14
|
/**
|
|
14
15
|
* A push verified against the handles the topics rows name, with the row it wrote when the block
|
|
@@ -56,7 +57,7 @@ async function rowOf(storage, spec, hit, { encryptionKey, epochs }) {
|
|
|
56
57
|
* @returns {Promise<{ id: string, type: string, name: string | null, newer: boolean, ref: string | null, row: object | null } | null>}
|
|
57
58
|
*/
|
|
58
59
|
export async function receive(dir, spec, payload, { storageKey } = {}) {
|
|
59
|
-
const storage = new HypercoreStorage(
|
|
60
|
+
const storage = new HypercoreStorage(await current(dir), { readOnly: true })
|
|
60
61
|
let store = null
|
|
61
62
|
let local = null
|
|
62
63
|
try {
|
package/src/rpc/server.js
CHANGED
|
@@ -101,6 +101,8 @@ export class Server extends RPCServer {
|
|
|
101
101
|
this.handles = new Map()
|
|
102
102
|
/** @type {Map<string, Set<object>>} handle id → its open watch streams */
|
|
103
103
|
this._watchStreams = new Map()
|
|
104
|
+
/** @type {Map<string, number>} handle id → the opens the page holds on it, let go when it reloads */
|
|
105
|
+
this._held = new Map()
|
|
104
106
|
/** @private */
|
|
105
107
|
this._booting = null
|
|
106
108
|
this._wireInit()
|
|
@@ -190,8 +192,10 @@ export class Server extends RPCServer {
|
|
|
190
192
|
})
|
|
191
193
|
this.rpc.onInit(async () => {
|
|
192
194
|
await this._booting
|
|
193
|
-
// a reloaded UI is a new client on the same worker: it re-attaches, its old streams end
|
|
195
|
+
// a reloaded UI is a new client on the same worker: it re-attaches, its old streams end, and every open the old
|
|
196
|
+
// page held is let go for it, as it never closes them
|
|
194
197
|
for (const handle of this._watchStreams.keys()) this._endWatches(handle)
|
|
198
|
+
await this._letGo()
|
|
195
199
|
return this._identity()
|
|
196
200
|
})
|
|
197
201
|
}
|
|
@@ -205,6 +209,7 @@ export class Server extends RPCServer {
|
|
|
205
209
|
if (!this.me) throw CeroError.NOT_READY('Server', 'server')
|
|
206
210
|
this.me = await restore(this.me, phrase)
|
|
207
211
|
this.handles = new Map([[this.me.id, this.me]])
|
|
212
|
+
this._held.clear()
|
|
208
213
|
return this._identity()
|
|
209
214
|
})
|
|
210
215
|
}
|
|
@@ -222,6 +227,7 @@ export class Server extends RPCServer {
|
|
|
222
227
|
onrequest: (id) => stream.write({ request: id })
|
|
223
228
|
})
|
|
224
229
|
this.handles = new Map([[this.me.id, this.me]])
|
|
230
|
+
this._held.clear()
|
|
225
231
|
stream.write({ request: '', ...this._identity() })
|
|
226
232
|
stream.end()
|
|
227
233
|
}
|
|
@@ -339,7 +345,7 @@ export class Server extends RPCServer {
|
|
|
339
345
|
const opts = { name: wire.name }
|
|
340
346
|
const child = await this.me._create(ref, opts)
|
|
341
347
|
const id = child.id
|
|
342
|
-
this.
|
|
348
|
+
this._hold(id, child)
|
|
343
349
|
return { id, type: ref, name: opts.name || '' }
|
|
344
350
|
})
|
|
345
351
|
|
|
@@ -348,7 +354,7 @@ export class Server extends RPCServer {
|
|
|
348
354
|
const { data } = await this.me.store.get('handles', row)
|
|
349
355
|
if (!data) throw CeroError.UNKNOWN('handle', row)
|
|
350
356
|
const child = await this.me._load(type, row)
|
|
351
|
-
this.
|
|
357
|
+
this._hold(row, child)
|
|
352
358
|
return { id: row, type: data.type, name: data.name || '' }
|
|
353
359
|
})
|
|
354
360
|
|
|
@@ -362,27 +368,53 @@ export class Server extends RPCServer {
|
|
|
362
368
|
return { id: '', type: ref, denied: true, reason: err.reason || '' }
|
|
363
369
|
}
|
|
364
370
|
const id = child.id
|
|
365
|
-
this.
|
|
371
|
+
this._hold(id, child)
|
|
366
372
|
return { id, type: ref, name: '' }
|
|
367
373
|
})
|
|
368
374
|
|
|
369
375
|
this.rpc.onCloseHandle(async ({ handle }) => {
|
|
370
376
|
const h = this.handles.get(handle)
|
|
371
377
|
if (!h || h === this.me) return {}
|
|
372
|
-
this.
|
|
373
|
-
this.handles.delete(handle)
|
|
374
|
-
await h.close()
|
|
378
|
+
await this._release(handle, h)
|
|
375
379
|
return {}
|
|
376
380
|
})
|
|
377
381
|
|
|
378
382
|
this.rpc.onLeave(async ({ handle }) => {
|
|
379
383
|
await leave(this._resolve(handle))
|
|
384
|
+
this._held.delete(handle)
|
|
380
385
|
this._endWatches(handle)
|
|
381
386
|
this.handles.delete(handle)
|
|
382
387
|
return {}
|
|
383
388
|
})
|
|
384
389
|
}
|
|
385
390
|
|
|
391
|
+
/** @private one open the page holds on `id` */
|
|
392
|
+
_hold(id, h) {
|
|
393
|
+
this.handles.set(id, h)
|
|
394
|
+
this._held.set(id, (this._held.get(id) ?? 0) + 1)
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** @private one of the page's opens on `id` let go: the handle drops off the wire once nobody here holds it */
|
|
398
|
+
async _release(id, h) {
|
|
399
|
+
const n = (this._held.get(id) ?? 1) - 1
|
|
400
|
+
if (n > 0) this._held.set(id, n)
|
|
401
|
+
else this._held.delete(id)
|
|
402
|
+
await h.close()
|
|
403
|
+
// another holder on this device keeps it, with its watches; a reopen while it lingers registers it again
|
|
404
|
+
if (h._refs > 0) return
|
|
405
|
+
this._endWatches(id)
|
|
406
|
+
this.handles.delete(id)
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** @private every open the page holds let go: a reload, whose old page closes nothing */
|
|
410
|
+
async _letGo() {
|
|
411
|
+
for (const [id, n] of [...this._held]) {
|
|
412
|
+
const h = this.handles.get(id)
|
|
413
|
+
for (let i = 0; i < n && h; i++) await this._release(id, h).catch(safetyCatch)
|
|
414
|
+
}
|
|
415
|
+
this._held.clear()
|
|
416
|
+
}
|
|
417
|
+
|
|
386
418
|
/**
|
|
387
419
|
* Register the `verb` handler: the operator by its name, on the handle, as in the worker.
|
|
388
420
|
* @private
|
package/types/handle/index.d.ts
CHANGED
|
@@ -198,6 +198,10 @@ export declare class Handle extends ReadyResource {
|
|
|
198
198
|
_sus;
|
|
199
199
|
/** @private */
|
|
200
200
|
_owned;
|
|
201
|
+
/** @private */
|
|
202
|
+
_refs;
|
|
203
|
+
/** @private */
|
|
204
|
+
_idle;
|
|
201
205
|
store: Database;
|
|
202
206
|
/** @private */
|
|
203
207
|
_pair;
|
|
@@ -281,6 +285,19 @@ export declare class Handle extends ReadyResource {
|
|
|
281
285
|
private _tx;
|
|
282
286
|
/** @private */
|
|
283
287
|
private _leave;
|
|
288
|
+
/**
|
|
289
|
+
* One holder done with it: a child stays open for the others. With its last it lingers `linger` ms (20s by
|
|
290
|
+
* default) and closes unless opened again meanwhile, so a quick reopen finds it still open. The root closes at once.
|
|
291
|
+
* @returns {Promise<void>}
|
|
292
|
+
*/
|
|
293
|
+
close(): Promise<void>;
|
|
294
|
+
/**
|
|
295
|
+
* Closed for every holder at once: its linger over, the parent closing, or the handle left for good.
|
|
296
|
+
* @private
|
|
297
|
+
*/
|
|
298
|
+
/** @private one more holder: a lingering handle is kept */
|
|
299
|
+
private _hold;
|
|
300
|
+
_end(): Promise<void>;
|
|
284
301
|
/** @private */
|
|
285
302
|
private _suspend;
|
|
286
303
|
/** @private */
|
package/types/index.d.ts
CHANGED
|
@@ -73,6 +73,10 @@ export type CeroOpts = {
|
|
|
73
73
|
* Where background errors go; the console without one.
|
|
74
74
|
*/
|
|
75
75
|
onerror?: (err: Error) => void;
|
|
76
|
+
/**
|
|
77
|
+
* Ms a handle stays open after its last close, for a quick reopen; 0 closes at once. Defaults to 20000.
|
|
78
|
+
*/
|
|
79
|
+
linger?: number;
|
|
76
80
|
/**
|
|
77
81
|
* Max wait to find another device and be admitted, in ms. Defaults to 30000.
|
|
78
82
|
*/
|
|
@@ -116,6 +120,7 @@ export type CeroOpts = {
|
|
|
116
120
|
* @property {Array<string | Uint8Array>} [mirrors] Blind-peer public keys. Handles and files are mirrored through them so peers sync even when never online at the same time. Mirrors hold only encrypted blocks — they never read your data.
|
|
117
121
|
* @property {{ active?: number, announced?: number, idle?: number }} [presence] How many handles search, how many only announce, and the idle ms before the rest leave the swarm.
|
|
118
122
|
* @property {(err: Error) => void} [onerror] Where background errors go; the console without one.
|
|
123
|
+
* @property {number} [linger] Ms a handle stays open after its last close, for a quick reopen; 0 closes at once. Defaults to 20000.
|
|
119
124
|
* @property {number} [recoveryTimeout] Max wait to find another device and be admitted, in ms. Defaults to 30000.
|
|
120
125
|
* @property {Uint8Array} [storageKey] 32-byte key encrypting local key material (master seed, device keypairs) at rest. Source it from the OS keychain — cero never stores it.
|
|
121
126
|
* @property {import('./extensions/index.js').Extension[]} [extensions] The extensions this instance runs, instead of the ones the spec carries. Build with the same list.
|
package/types/lib/constants.d.ts
CHANGED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where the incoming identity opens.
|
|
3
|
+
*
|
|
4
|
+
* @param {string} dir
|
|
5
|
+
* @returns {string}
|
|
6
|
+
*/
|
|
7
|
+
export declare const nextOf: (dir: string) => string;
|
|
8
|
+
/**
|
|
9
|
+
* The store a launch of `dir` opens, without moving anything: `main`, or with a swap killed between its renames,
|
|
10
|
+
* the identity `settle` will keep.
|
|
11
|
+
*
|
|
12
|
+
* @param {string} dir
|
|
13
|
+
* @returns {Promise<string>}
|
|
14
|
+
*/
|
|
15
|
+
export declare function current(dir: string): Promise<string>;
|
|
16
|
+
/**
|
|
17
|
+
* A swap killed part way, finished or undone before anything opens `dir`: past its first rename the incoming
|
|
18
|
+
* identity had opened, so it takes main's place; without it the old one comes back. What a killed swap left
|
|
19
|
+
* in `main.next` goes, unless a swap is running there.
|
|
20
|
+
*
|
|
21
|
+
* @param {string} dir
|
|
22
|
+
*/
|
|
23
|
+
export declare function settle(dir: string): Promise<void>;
|
|
24
|
+
/**
|
|
25
|
+
* Run `fn` with `dir/main.next` set aside for it, emptied before and after.
|
|
26
|
+
*
|
|
27
|
+
* @template T
|
|
28
|
+
* @param {string} dir
|
|
29
|
+
* @param {() => Promise<T>} fn
|
|
30
|
+
* @returns {Promise<T>}
|
|
31
|
+
*/
|
|
32
|
+
export declare function staging<T>(dir: string, fn: () => Promise<T>): Promise<T>;
|
|
33
|
+
/**
|
|
34
|
+
* The identity opened and closed in `main.next` takes main's place. Both must be closed.
|
|
35
|
+
*
|
|
36
|
+
* @param {string} dir
|
|
37
|
+
*/
|
|
38
|
+
export declare function commit(dir: string): Promise<void>;
|
package/types/rpc/server.d.ts
CHANGED
|
@@ -88,6 +88,8 @@ export declare class Server extends RPCServer {
|
|
|
88
88
|
handles: Map<string, Context>;
|
|
89
89
|
/** @type {Map<string, Set<object>>} handle id → its open watch streams */
|
|
90
90
|
_watchStreams: Map<string, Set<object>>;
|
|
91
|
+
/** @type {Map<string, number>} handle id → the opens the page holds on it, let go when it reloads */
|
|
92
|
+
_held: Map<string, number>;
|
|
91
93
|
/** @private */
|
|
92
94
|
_booting;
|
|
93
95
|
/**
|
|
@@ -146,6 +148,12 @@ export declare class Server extends RPCServer {
|
|
|
146
148
|
* @private
|
|
147
149
|
*/
|
|
148
150
|
private _wireHandles;
|
|
151
|
+
/** @private one open the page holds on `id` */
|
|
152
|
+
private _hold;
|
|
153
|
+
/** @private one of the page's opens on `id` let go: the handle drops off the wire once nobody here holds it */
|
|
154
|
+
private _release;
|
|
155
|
+
/** @private every open the page holds let go: a reload, whose old page closes nothing */
|
|
156
|
+
private _letGo;
|
|
149
157
|
/**
|
|
150
158
|
* Register the `verb` handler: the operator by its name, on the handle, as in the worker.
|
|
151
159
|
* @private
|