@cero-base/cero 2.10.0 → 2.12.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 CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cero-base/cero",
3
- "version": "2.10.0",
3
+ "version": "2.12.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.10.0",
116
+ "@cero-base/core": "^2.12.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.39.6",
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.5",
146
- "blind-peer": "^3.16.0",
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
  },
@@ -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: 1 }
245
+ export const contract = { version: 2 }
246
246
 
247
247
  export const rpc = {
248
248
  'req-empty': {
@@ -25,7 +25,8 @@ export async function mirror(from, row, fields, to, id) {
25
25
  const prev = idOf(was[k])
26
26
  if (!file) {
27
27
  out[k] = row[k]
28
- changed ||= was[k] !== row[k]
28
+ // a field the source never set is the null the row reads back
29
+ changed ||= (was[k] ?? null) !== (row[k] ?? null)
29
30
  } else if (prev && (await get(to.handle.files, prev)).data?.from === file) {
30
31
  out[k] = prev
31
32
  } else {
@@ -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.close()),
311
- ...[...(this._pending || [])].map((c) => () => c.close()),
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 (this.parent) {
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 () => {
@@ -397,6 +406,11 @@ export class Handle extends ReadyResource {
397
406
  return this.store.rotate()
398
407
  }
399
408
 
409
+ /** @private */
410
+ _removed(id) {
411
+ return this.store.removed(id)
412
+ }
413
+
400
414
  // the same context, its refs writing into one batch; a fn that ignores it would write outside
401
415
  /** @private */
402
416
  async _tx(fn) {
@@ -418,7 +432,45 @@ export class Handle extends ReadyResource {
418
432
  if (!this.parent) throw CeroError.INVALID('the root cannot be left')
419
433
  await this.store.del('members', this.identity.id)
420
434
  await this.parent.store.call('del-handle', { id: hid.encode(this.store.key) })
421
- await this.close()
435
+ await this._end()
436
+ }
437
+
438
+ /**
439
+ * One holder done with it: a child stays open for the others. With its last it lingers `linger` ms (20s by
440
+ * default) and closes unless opened again meanwhile, so a quick reopen finds it still open. The root closes at once.
441
+ * @returns {Promise<void>}
442
+ */
443
+ close() {
444
+ if (!this.parent) return this._end()
445
+ if (this._refs > 1) {
446
+ this._refs--
447
+ return Promise.resolve()
448
+ }
449
+ if (this._idle) return Promise.resolve()
450
+ const linger = this.root._opts.linger ?? LINGER
451
+ if (!linger || this._refs === 0) return this._end()
452
+ this._refs = 0
453
+ this._idle = setTimeout(() => this._end().catch(this._onerror), linger)
454
+ this._idle.unref?.()
455
+ return Promise.resolve()
456
+ }
457
+
458
+ /**
459
+ * Closed for every holder at once: its linger over, the parent closing, or the handle left for good.
460
+ * @private
461
+ */
462
+ /** @private one more holder: a lingering handle is kept */
463
+ _hold() {
464
+ clearTimeout(this._idle)
465
+ this._idle = null
466
+ this._refs++
467
+ }
468
+
469
+ _end() {
470
+ clearTimeout(this._idle)
471
+ this._idle = null
472
+ this._refs = 0
473
+ return super.close()
422
474
  }
423
475
 
424
476
  // the app going to the background and back: networking, storage and the radio together
@@ -602,6 +654,7 @@ export class Handle extends ReadyResource {
602
654
 
603
655
  /** @private */
604
656
  async _send(address, value, { keep = true } = {}) {
657
+ if (this.root.closing) throw CeroError.CLOSED('Mailbox')
605
658
  const to = decodeAddress(address)
606
659
  await this.root.mailbox.send(to, seal(this.identity, to, value), { keep })
607
660
  }
@@ -797,7 +850,7 @@ export class Handle extends ReadyResource {
797
850
  const reason = this.closing || this.closed ? CeroError.CLOSED('Handle') : err
798
851
  if (abort) abort(reason)
799
852
  if (inflightId) this._loading?.delete(inflightId)
800
- await child.close().catch(safetyCatch)
853
+ await child._end().catch(safetyCatch)
801
854
  throw reason
802
855
  }
803
856
  }
@@ -820,7 +873,11 @@ export class Handle extends ReadyResource {
820
873
  const join = this._start(invite, type)
821
874
  join.waiting++
822
875
  try {
823
- return await wait(join.done, timeout)
876
+ const child = await wait(join.done, timeout)
877
+ // every caller holds the room: the first takes the open the join made, each other one its own
878
+ if (join.claimed) child._hold()
879
+ join.claimed = true
880
+ return child
824
881
  } finally {
825
882
  join.waiting--
826
883
  }
@@ -864,7 +921,7 @@ export class Handle extends ReadyResource {
864
921
  const { data: device } = await known.store.get('devices', hid.encode(known.store.writerKey))
865
922
  // a reader never had a seat, a removed writer lost it
866
923
  if (me && (device || me.role === 'reader')) return known
867
- await known.close().catch(safetyCatch)
924
+ await known._end().catch(safetyCatch)
868
925
  return null
869
926
  }
870
927
 
@@ -924,7 +981,7 @@ export class Handle extends ReadyResource {
924
981
  } catch (err) {
925
982
  if (abort) abort(err)
926
983
  if (inflightId) this._loading?.delete(inflightId)
927
- await child.close().catch(safetyCatch)
984
+ await child._end().catch(safetyCatch)
928
985
  throw err
929
986
  }
930
987
  }
@@ -960,7 +1017,10 @@ export class Handle extends ReadyResource {
960
1017
  if (open && open.type !== type) {
961
1018
  throw CeroError.INVALID(`handle ${id} is type ${open.type}, not ${type}`)
962
1019
  }
963
- if (open) return open
1020
+ if (open) {
1021
+ open._hold()
1022
+ return open
1023
+ }
964
1024
  const reopening = this._reopen(type, id)
965
1025
  this._loading.set(id, reopening)
966
1026
  try {
@@ -1007,7 +1067,7 @@ export class Handle extends ReadyResource {
1007
1067
  }
1008
1068
  this._adopt(child, {})
1009
1069
  } catch (err) {
1010
- await child.close().catch(safetyCatch)
1070
+ await child._end().catch(safetyCatch)
1011
1071
  throw err
1012
1072
  }
1013
1073
  return child
@@ -1045,6 +1105,7 @@ export class Handle extends ReadyResource {
1045
1105
  if (this.closing || this.closed) throw CeroError.CLOSED('Handle')
1046
1106
  this._pending.delete(child)
1047
1107
  this.children.add(child)
1108
+ child._refs = 1
1048
1109
  this._serve(child)
1049
1110
  this._carry(child)
1050
1111
  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
- const { _dir: dir, spec, _opts: opts } = me
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 start(dir, spec, { ...opts, phrase: undefined, invite, onrequest, recoveryTimeout: 0 })
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, { identity, spec, writer, timeout, keep })
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
  }
@@ -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
@@ -417,6 +417,19 @@ export function deny(ctx, request, reason = '') {
417
417
  return ctx._answer(request.id, { accept: false, reason })
418
418
  }
419
419
 
420
+ /**
421
+ * Whether a member is out of a handle for good, as this device has seen it: `'removed'` by another
422
+ * member, `'left'` on her own, or null while she is a member, never was one, or her going has not
423
+ * reached this device. Someone let in again after is a member: null.
424
+ *
425
+ * @param {Context} ctx
426
+ * @param {string} id The member's id.
427
+ * @returns {Promise<'removed' | 'left' | null>}
428
+ */
429
+ export function removed(ctx, id) {
430
+ return ctx._removed(id)
431
+ }
432
+
420
433
  /**
421
434
  * Quit a handle for good: it leaves your list and closes on this device.
422
435
  *
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
- const root = new HypercoreStorage(`${dir}/main`)
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 {
@@ -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(`${dir}/main`, { readOnly: true })
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/client.js CHANGED
@@ -29,6 +29,7 @@ export const {
29
29
  accept,
30
30
  deny,
31
31
  leave,
32
+ removed,
32
33
  close,
33
34
  cancel,
34
35
  suspend,
@@ -365,6 +366,11 @@ const operators = {
365
366
  await this.rpc.leave({ handle: this.id })
366
367
  },
367
368
 
369
+ /** @private */
370
+ _removed(id) {
371
+ return this._verb('removed', id)
372
+ },
373
+
368
374
  /** @private */
369
375
  _cancel(invite) {
370
376
  return this._verb('cancel', invite)
package/src/rpc/server.js CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  invite,
16
16
  revoke,
17
17
  rotate,
18
+ removed,
18
19
  accept,
19
20
  deny,
20
21
  cancel,
@@ -35,6 +36,7 @@ const VERBS = new Map(
35
36
  invite,
36
37
  revoke,
37
38
  rotate,
39
+ removed,
38
40
  accept,
39
41
  deny,
40
42
  cancel,
@@ -101,6 +103,8 @@ export class Server extends RPCServer {
101
103
  this.handles = new Map()
102
104
  /** @type {Map<string, Set<object>>} handle id → its open watch streams */
103
105
  this._watchStreams = new Map()
106
+ /** @type {Map<string, number>} handle id → the opens the page holds on it, let go when it reloads */
107
+ this._held = new Map()
104
108
  /** @private */
105
109
  this._booting = null
106
110
  this._wireInit()
@@ -190,8 +194,10 @@ export class Server extends RPCServer {
190
194
  })
191
195
  this.rpc.onInit(async () => {
192
196
  await this._booting
193
- // a reloaded UI is a new client on the same worker: it re-attaches, its old streams end
197
+ // a reloaded UI is a new client on the same worker: it re-attaches, its old streams end, and every open the old
198
+ // page held is let go for it, as it never closes them
194
199
  for (const handle of this._watchStreams.keys()) this._endWatches(handle)
200
+ await this._letGo()
195
201
  return this._identity()
196
202
  })
197
203
  }
@@ -205,6 +211,7 @@ export class Server extends RPCServer {
205
211
  if (!this.me) throw CeroError.NOT_READY('Server', 'server')
206
212
  this.me = await restore(this.me, phrase)
207
213
  this.handles = new Map([[this.me.id, this.me]])
214
+ this._held.clear()
208
215
  return this._identity()
209
216
  })
210
217
  }
@@ -222,6 +229,7 @@ export class Server extends RPCServer {
222
229
  onrequest: (id) => stream.write({ request: id })
223
230
  })
224
231
  this.handles = new Map([[this.me.id, this.me]])
232
+ this._held.clear()
225
233
  stream.write({ request: '', ...this._identity() })
226
234
  stream.end()
227
235
  }
@@ -339,7 +347,7 @@ export class Server extends RPCServer {
339
347
  const opts = { name: wire.name }
340
348
  const child = await this.me._create(ref, opts)
341
349
  const id = child.id
342
- this.handles.set(id, child)
350
+ this._hold(id, child)
343
351
  return { id, type: ref, name: opts.name || '' }
344
352
  })
345
353
 
@@ -348,7 +356,7 @@ export class Server extends RPCServer {
348
356
  const { data } = await this.me.store.get('handles', row)
349
357
  if (!data) throw CeroError.UNKNOWN('handle', row)
350
358
  const child = await this.me._load(type, row)
351
- this.handles.set(row, child)
359
+ this._hold(row, child)
352
360
  return { id: row, type: data.type, name: data.name || '' }
353
361
  })
354
362
 
@@ -362,27 +370,53 @@ export class Server extends RPCServer {
362
370
  return { id: '', type: ref, denied: true, reason: err.reason || '' }
363
371
  }
364
372
  const id = child.id
365
- this.handles.set(id, child)
373
+ this._hold(id, child)
366
374
  return { id, type: ref, name: '' }
367
375
  })
368
376
 
369
377
  this.rpc.onCloseHandle(async ({ handle }) => {
370
378
  const h = this.handles.get(handle)
371
379
  if (!h || h === this.me) return {}
372
- this._endWatches(handle)
373
- this.handles.delete(handle)
374
- await h.close()
380
+ await this._release(handle, h)
375
381
  return {}
376
382
  })
377
383
 
378
384
  this.rpc.onLeave(async ({ handle }) => {
379
385
  await leave(this._resolve(handle))
386
+ this._held.delete(handle)
380
387
  this._endWatches(handle)
381
388
  this.handles.delete(handle)
382
389
  return {}
383
390
  })
384
391
  }
385
392
 
393
+ /** @private one open the page holds on `id` */
394
+ _hold(id, h) {
395
+ this.handles.set(id, h)
396
+ this._held.set(id, (this._held.get(id) ?? 0) + 1)
397
+ }
398
+
399
+ /** @private one of the page's opens on `id` let go: the handle drops off the wire once nobody here holds it */
400
+ async _release(id, h) {
401
+ const n = (this._held.get(id) ?? 1) - 1
402
+ if (n > 0) this._held.set(id, n)
403
+ else this._held.delete(id)
404
+ await h.close()
405
+ // another holder on this device keeps it, with its watches; a reopen while it lingers registers it again
406
+ if (h._refs > 0) return
407
+ this._endWatches(id)
408
+ this.handles.delete(id)
409
+ }
410
+
411
+ /** @private every open the page holds let go: a reload, whose old page closes nothing */
412
+ async _letGo() {
413
+ for (const [id, n] of [...this._held]) {
414
+ const h = this.handles.get(id)
415
+ for (let i = 0; i < n && h; i++) await this._release(id, h).catch(safetyCatch)
416
+ }
417
+ this._held.clear()
418
+ }
419
+
386
420
  /**
387
421
  * Register the `verb` handler: the operator by its name, on the handle, as in the worker.
388
422
  * @private
@@ -42,6 +42,7 @@ export declare const cero: {
42
42
  deny(ctx: operators.Context, request: {
43
43
  id: string;
44
44
  }, reason?: string): Promise<void>;
45
+ removed(ctx: operators.Context, id: string): Promise<'removed' | 'left' | null>;
45
46
  leave(ctx: operators.Context): Promise<void>;
46
47
  close(ctx: operators.Context): Promise<void>;
47
48
  cancel(me: operators.Context, code: string): Promise<boolean>;
@@ -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;
@@ -278,9 +282,24 @@ export declare class Handle extends ReadyResource {
278
282
  /** @private */
279
283
  private _rotate;
280
284
  /** @private */
285
+ private _removed;
286
+ /** @private */
281
287
  private _tx;
282
288
  /** @private */
283
289
  private _leave;
290
+ /**
291
+ * One holder done with it: a child stays open for the others. With its last it lingers `linger` ms (20s by
292
+ * default) and closes unless opened again meanwhile, so a quick reopen finds it still open. The root closes at once.
293
+ * @returns {Promise<void>}
294
+ */
295
+ close(): Promise<void>;
296
+ /**
297
+ * Closed for every holder at once: its linger over, the parent closing, or the handle left for good.
298
+ * @private
299
+ */
300
+ /** @private one more holder: a lingering handle is kept */
301
+ private _hold;
302
+ _end(): Promise<void>;
284
303
  /** @private */
285
304
  private _suspend;
286
305
  /** @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.
@@ -6,3 +6,4 @@ export declare const REFUSALS = "refusals";
6
6
  export declare const SPENT = "spent";
7
7
  export declare const TIMEOUT = 30000;
8
8
  export declare const FLUSH = 500;
9
+ export declare const LINGER = 20000;
@@ -177,6 +177,16 @@ export declare function accept(ctx: Context, request: {
177
177
  export declare function deny(ctx: Context, request: {
178
178
  id: string;
179
179
  }, reason?: string): Promise<void>;
180
+ /**
181
+ * Whether a member is out of a handle for good, as this device has seen it: `'removed'` by another
182
+ * member, `'left'` on her own, or null while she is a member, never was one, or her going has not
183
+ * reached this device. Someone let in again after is a member: null.
184
+ *
185
+ * @param {Context} ctx
186
+ * @param {string} id The member's id.
187
+ * @returns {Promise<'removed' | 'left' | null>}
188
+ */
189
+ export declare function removed(ctx: Context, id: string): Promise<'removed' | 'left' | null>;
180
190
  /**
181
191
  * Quit a handle for good: it leaves your list and closes on this device.
182
192
  *
@@ -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>;
@@ -34,6 +34,7 @@ declare const remote: {
34
34
  deny(ctx: verbs.Context, request: {
35
35
  id: string;
36
36
  }, reason?: string): Promise<void>;
37
+ removed(ctx: verbs.Context, id: string): Promise<'removed' | 'left' | null>;
37
38
  leave(ctx: verbs.Context): Promise<void>;
38
39
  close(ctx: verbs.Context): Promise<void>;
39
40
  cancel(me: verbs.Context, code: string): Promise<boolean>;
@@ -64,7 +65,7 @@ declare const remote: {
64
65
  topic?: string;
65
66
  }): Promise<void>;
66
67
  };
67
- export declare const put: typeof verbs.put, set: typeof verbs.set, get: typeof verbs.get, del: typeof verbs.del, watch: typeof verbs.watch, call: typeof verbs.call, open: typeof verbs.open, invite: typeof verbs.invite, revoke: typeof verbs.revoke, rotate: typeof verbs.rotate, accept: typeof verbs.accept, deny: typeof verbs.deny, leave: typeof verbs.leave, close: typeof verbs.close, cancel: typeof verbs.cancel, suspend: typeof verbs.suspend, resume: typeof verbs.resume, activate: typeof verbs.activate, deactivate: typeof verbs.deactivate, phrase: typeof verbs.phrase, nearby: typeof verbs.nearby;
68
+ export declare const put: typeof verbs.put, set: typeof verbs.set, get: typeof verbs.get, del: typeof verbs.del, watch: typeof verbs.watch, call: typeof verbs.call, open: typeof verbs.open, invite: typeof verbs.invite, revoke: typeof verbs.revoke, rotate: typeof verbs.rotate, accept: typeof verbs.accept, deny: typeof verbs.deny, leave: typeof verbs.leave, removed: typeof verbs.removed, close: typeof verbs.close, cancel: typeof verbs.cancel, suspend: typeof verbs.suspend, resume: typeof verbs.resume, activate: typeof verbs.activate, deactivate: typeof verbs.deactivate, phrase: typeof verbs.phrase, nearby: typeof verbs.nearby;
68
69
  export { t, schema };
69
70
  export type BaseRPCClient = import('@cero-base/core/rpc').RPCClient;
70
71
  export type RefInfo = import('../lib/spec.js').RefInfo;
@@ -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