@cero-base/cero 2.11.0 → 3.0.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.
@@ -1,7 +1,7 @@
1
1
  import AbortController from 'bare-abort-controller'
2
2
  import b4a from 'b4a'
3
3
  import c from 'compact-encoding'
4
- import { discoveryKey } from 'hypercore-crypto'
4
+ import { discoveryKey, hash } from 'hypercore-crypto'
5
5
  import ReadyResource from 'ready-resource'
6
6
  import safetyCatch from 'safety-catch'
7
7
  import Suspendify from 'suspendify'
@@ -16,16 +16,15 @@ import { Invite } from '@cero-base/core/invite'
16
16
  import { Mailbox } from '@cero-base/core/mailbox'
17
17
  import { seal, unseal, decodeAddress } from '../lib/mail.js'
18
18
  import hid from 'hypercore-id-encoding'
19
- import { admission, onAbort, filter } from '@cero-base/core/utils'
19
+ import { admission, onAbort, filter, can, WRITE } from '@cero-base/core/utils'
20
20
  import { CeroError } from '@cero-base/core/errors'
21
21
  import { Blobs } from '@cero-base/core/blobs'
22
- import { decodeId } from '@cero-base/core/blobs/codec'
22
+ import { decodeId, servedType } from '@cero-base/core/blobs/codec'
23
23
  import { FileServer } from '@cero-base/core/blobs/server'
24
24
 
25
- import { LINGER, NS, TIMEOUT } from '../lib/constants.js'
25
+ import { KEEP_OPEN, NS, TIMEOUT } from '../lib/constants.js'
26
26
 
27
27
  import { Ref } from '../lib/refs.js'
28
- import { Join, wait } from './join.js'
29
28
  import { box } from '../local/index.js'
30
29
  import { extensionsOf } from '../extensions/index.js'
31
30
 
@@ -43,7 +42,7 @@ export { Ref } from '../lib/refs.js'
43
42
  * @property {Network} [network] Shared swarm. Inherited from `parent` if omitted.
44
43
  * @property {import('corestore')} [store] Pre-existing Corestore. Falls back to `parent.store.store`.
45
44
  * @property {Spec} [spec] Built cero spec.
46
- * @property {Local} [local] Root only, and required there: the device store for handle keypairs, joins and mail.
45
+ * @property {Local} [local] Root only, and required there: the device store for handle keypairs and mail.
47
46
  * @property {import('hypercore-storage')} [storage] Owned HypercoreStorage to close on shutdown.
48
47
  * @property {{ destroy(): Promise<void> }} [discovery] Owned identity discovery to destroy on shutdown.
49
48
  * @property {string} [dir] Data directory (root handles only).
@@ -106,7 +105,8 @@ export class Handle extends ReadyResource {
106
105
  ? parent.root.mailbox
107
106
  : new Mailbox(network, {
108
107
  inbox: box(this.local.store, 'inbox'),
109
- outbox: box(this.local.store, 'outbox')
108
+ outbox: box(this.local.store, 'outbox'),
109
+ onerror: (err) => this._onerror(err)
110
110
  })
111
111
  /** @private */
112
112
  this._storage = opts.storage || null
@@ -118,22 +118,34 @@ export class Handle extends ReadyResource {
118
118
  this._opts = opts.opts || {}
119
119
  /** @type {import('../extensions/index.js').Extension[]} */
120
120
  this.extensions = parent?.extensions || extensionsOf(spec, this._opts.extensions)
121
+ // one for the app: what a handle does on its own reaches the root's
121
122
  /** @private */
122
- this._onerror = this._opts.onerror || ((err) => console.error(err))
123
+ this._onerror = parent ? parent._onerror : this._opts.onerror || ((err) => console.error(err))
123
124
  /** @type {Set<Handle> | null} */
124
125
  this.children = parent ? null : new Set()
125
126
  // children still opening, not adopted yet: a close must close them too
126
127
  /** @private */
127
128
  this._pending = parent ? null : new Set()
129
+ // children closing on their own: a close waits for them, they still read its stores
130
+ /** @private */
131
+ this._ending = parent ? null : new Set()
128
132
  /** @private */
129
133
  this._typeHooks = parent ? null : new Set()
130
134
  /** @private */
131
135
  this._loading = parent ? null : new Map()
132
136
  /** @private */
133
- this._joining = parent ? null : new Map() // type/discovery key → Join
137
+ this._joining = parent ? null : new Map() // handle id → its join in flight
138
+ /** @private */
139
+ this._taking = parent ? null : new Set() // the requests being taken back, by writer
134
140
  /** @private */
135
141
  this._coreKeys = parent ? null : new Map()
136
142
  /** @private */
143
+ this._offJoins = null
144
+ /** @private */
145
+ this._departing = parent ? null : new Map()
146
+ /** @private */
147
+ this._leaving = parent ? null : new Map()
148
+ /** @private */
137
149
  this._fileServer = null
138
150
  /** @private */
139
151
  this._blobs = null
@@ -144,14 +156,40 @@ export class Handle extends ReadyResource {
144
156
  this._sus = parent
145
157
  ? null
146
158
  : new Suspendify({ suspend: () => this._sleep(), resume: () => this._wake() })
159
+ // what its holders tied to it, a watch: gone with the last of them
147
160
  /** @private */
148
161
  this._owned = new Set()
162
+ // what follows it for as long as it is open, an extension's watch
163
+ /** @private */
164
+ this._kept = new Set()
165
+ /** @private */
166
+ this._arriving = false
149
167
  // 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
168
+ // last one leaves it idle
151
169
  /** @private */
152
170
  this._refs = 0
171
+ // a child's compare with the root's device keys, the next one behind it
172
+ /** @private */
173
+ this._pruning = null
174
+ // the children nobody holds, the least recently used first
175
+ /** @private */
176
+ this._idle = parent ? null : new Set()
177
+ // the closed rooms a pass is telling, by id: an open of one waits for it to close
178
+ /** @private */
179
+ this._tellings = parent ? null : new Map()
180
+ // the closed rooms no peer served when a pass reached them, by id, and the turns telling them
153
181
  /** @private */
154
- this._idle = null
182
+ this._waiting = parent ? null : new Map()
183
+ /** @private */
184
+ this._waiters = 0
185
+ /** @private */
186
+ this._telling = null
187
+ // what an extension tells the rooms closed here, through the same pass: `stamp` names it,
188
+ // `tell` writes it into a room opened for it
189
+ /** @private @type {Array<{ stamp: () => Promise<string | null>, tell: (child: Handle) => Promise<void> }> | null} */
190
+ this._tellers = parent ? null : []
191
+ /** @private */
192
+ this._retell = false
155
193
 
156
194
  this.store = new Database({
157
195
  store: store,
@@ -165,8 +203,11 @@ export class Handle extends ReadyResource {
165
203
  namespace: opts.namespace,
166
204
  keyPair: opts.keyPair,
167
205
  pinned: !parent,
206
+ root: !parent,
168
207
  // the root has no topic to push to
169
208
  push: !!parent,
209
+ // the root says which of this identity's devices are removed: behind there, behind here
210
+ parent: parent?.root.store,
170
211
  onerror: this._onerror
171
212
  })
172
213
  /** @private */
@@ -181,9 +222,8 @@ export class Handle extends ReadyResource {
181
222
  this._live = {
182
223
  status: { get: () => this._status(), watch: (fn) => this._onStatus(fn) },
183
224
  ...(!this.parent && {
184
- joins: { get: (q) => this._joins(q), watch: (fn) => this._onLocal(fn) },
185
225
  nearby: { get: () => this._peers(), watch: (fn) => this._onRadio(fn) },
186
- topics: { get: (q) => this._topics(q), watch: (fn) => this._onLocal(fn) }
226
+ topics: { get: (q) => this._topics(q), watch: (fn) => this._onTopics(fn) }
187
227
  })
188
228
  }
189
229
  }
@@ -281,15 +321,23 @@ export class Handle extends ReadyResource {
281
321
  if (!this.parent) {
282
322
  await this.fileServer.listen()
283
323
  await this.mailbox.ready()
284
- const prune = this.store.onUpdate('devices', () => this._pruneAll().catch(this._onerror))
324
+ const prune = this.store.onUpdate('devices', () => {
325
+ this._pruneAll().catch(this._onerror)
326
+ this._tellClosed()
327
+ })
285
328
  this.once('close', prune)
286
329
  if (this._bluetooth) {
287
330
  const off = this.store.onUpdate('profile', () => this._tell().catch(this._onerror))
288
331
  this.once('close', off)
289
332
  await this._tell()
290
333
  }
291
- await this._carryOn().catch(this._onerror)
334
+ // the joins on their way, at launch and as their rows move
335
+ const report = (err) => this.closing || this._onerror(err)
336
+ this._offJoins = this.store.onUpdate('handles', () => this._carryOn().catch(report))
337
+ await this._carryOn().catch(report)
338
+ await this._sweep().catch(this._onerror)
292
339
  this._reserve().catch(this._onerror)
340
+ this._tellClosed()
293
341
  // the handles rows, keyed by push topic, for a cold push process that cannot read the root
294
342
  const off = this.store.onUpdate('handles', () => this._index().catch(this._onerror))
295
343
  this.once('close', off)
@@ -299,19 +347,23 @@ export class Handle extends ReadyResource {
299
347
 
300
348
  /** @private */
301
349
  async _close() {
350
+ // a write that raced a suspend holds the close until the storage resumes, once a suspend still running settled
351
+ if (this._sus) await this._sus.resume()
302
352
  this.root._coreKeys.delete(b4a.toHex(this.store.key))
303
353
  if (this._blobs?.key) this.root._coreKeys.delete(b4a.toHex(this._blobs.key))
304
354
  for (const b of this._epochBlobs?.values() || []) {
305
355
  if (b.key) this.root._coreKeys.delete(b4a.toHex(b.key))
306
356
  }
307
357
  for (const hex of this._blobKeys || []) this.root._coreKeys.delete(hex)
308
- for (const r of [...this._owned]) r.destroy?.()
309
- this._owned.clear()
358
+ this._disown()
359
+ for (const r of [...this._kept]) r.destroy?.()
360
+ this._kept.clear()
310
361
  if (this._discovery) this._discovery.destroy().catch(safetyCatch)
311
362
 
312
363
  const root = !this.parent
364
+ this._offJoins?.()
313
365
  const steps = [
314
- ...[...(this._joining?.values() || [])].map((join) => () => join.close()),
366
+ ...[...(this._joining?.values() || [])].map((join) => () => join.running?.abort()),
315
367
  // mirroring stops before any database closes, once the mailbox is done with it: blind peering reads
316
368
  // storage for each database it mirrors
317
369
  ...(root ? [() => this.mailbox.close(), () => this.network.closePeering()] : []),
@@ -319,6 +371,7 @@ export class Handle extends ReadyResource {
319
371
  ...[...(this._epochBlobs?.values() || [])].map((b) => () => b.close()),
320
372
  ...[...(this.children || [])].map((c) => () => c._end()),
321
373
  ...[...(this._pending || [])].map((c) => () => c._end()),
374
+ ...[...(this._ending || [])].map((c) => () => c.closing),
322
375
  () => this._pair?.close()
323
376
  ]
324
377
  this._epochBlobs = null
@@ -326,7 +379,11 @@ export class Handle extends ReadyResource {
326
379
 
327
380
  if (!root) {
328
381
  this.parent.children?.delete(this)
329
- steps.push(() => this.store.close())
382
+ this.parent._ending?.add(this)
383
+ steps.push(
384
+ () => this.parent._seal(this).catch(this._onerror),
385
+ () => this.store.close()
386
+ )
330
387
  } else {
331
388
  const store = this.store.store
332
389
  steps.push(
@@ -342,13 +399,17 @@ export class Handle extends ReadyResource {
342
399
  () => this._storage?.close()
343
400
  )
344
401
  }
345
- await settle(steps)
402
+ try {
403
+ await settle(steps)
404
+ } finally {
405
+ this.parent?._ending?.delete(this)
406
+ }
346
407
  }
347
408
 
348
409
  /**
349
- * Tie a destroyable resource (a `watch` stream, a timer, any `{ destroy }`) to this
350
- * handle's lifecycle — it's destroyed automatically on close, so callers don't track
351
- * cleanup.
410
+ * Tie a destroyable resource (a `watch` stream, a timer, any `{ destroy }`) to this handle, so callers
411
+ * don't track cleanup. Tied by a holder, it is destroyed once the last holder closes the handle; tied by
412
+ * a `handle` listener as it runs, an extension's watch, it follows the handle for as long as it is open.
352
413
  *
353
414
  * @template {{ destroy?: Function, once?: Function }} T
354
415
  * @param {T} resource
@@ -359,11 +420,18 @@ export class Handle extends ReadyResource {
359
420
  resource.destroy?.()
360
421
  return resource
361
422
  }
362
- this._owned.add(resource)
363
- resource.once?.('close', () => this._owned.delete(resource))
423
+ const tied = this._arriving ? this._kept : this._owned
424
+ tied.add(resource)
425
+ resource.once?.('close', () => tied.delete(resource))
364
426
  return resource
365
427
  }
366
428
 
429
+ /** @private */
430
+ _disown() {
431
+ for (const r of [...this._owned]) r.destroy?.()
432
+ this._owned.clear()
433
+ }
434
+
367
435
  // a file's url on this device's file server, for the rows that name it
368
436
  /** @private */
369
437
  _link(id) {
@@ -406,6 +474,11 @@ export class Handle extends ReadyResource {
406
474
  return this.store.rotate()
407
475
  }
408
476
 
477
+ /** @private */
478
+ _removed(id) {
479
+ return this.store.removed(id)
480
+ }
481
+
409
482
  // the same context, its refs writing into one batch; a fn that ignores it would write outside
410
483
  /** @private */
411
484
  async _tx(fn) {
@@ -425,45 +498,113 @@ export class Handle extends ReadyResource {
425
498
  /** @private */
426
499
  async _leave() {
427
500
  if (!this.parent) throw CeroError.INVALID('the root cannot be left')
428
- await this.store.del('members', this.identity.id)
429
- await this.parent.store.call('del-handle', { id: hid.encode(this.store.key) })
430
- await this._end()
501
+ // leaving is written on the root row: behind there, nothing is done
502
+ if (this.parent.store.behind !== null) throw CeroError.BEHIND(this.parent.store.behind)
503
+ // what the room refuses of her removal is refused here, before the row says leaving
504
+ const { data: members } = await this.store.get('members')
505
+ const others = members.filter((m) => m.id !== this.identity.id)
506
+ const owner = members.some((m) => m.id === this.identity.id && m.role === 'owner')
507
+ if (owner && others.length && !others.some((m) => m.role === 'owner')) {
508
+ throw CeroError.INVALID('the last owner cannot leave: make another member an owner first')
509
+ }
510
+ const root = this.root
511
+ // her removal is on the room's log before the call resolves: the row carries the rest
512
+ const out = root.store
513
+ .set('handles', { id: this.id, state: 'leaving' })
514
+ .then(() => this.store.del('members', this.identity.id))
515
+ root._leaving.set(this.id, out)
516
+ try {
517
+ await out
518
+ } finally {
519
+ root._leaving.delete(this.id)
520
+ }
521
+ }
522
+
523
+ // a leaving row is carried by every device of the identity seated in its room: its removal of
524
+ // herself, held by another device or a mirror, then the row goes
525
+ /** @private */
526
+ _depart(type, id) {
527
+ if (this._departing.has(id)) return
528
+ const run = async () => {
529
+ if (!(await this._loadKeyPair(id))) return
530
+ await this._leaving.get(id)?.catch(safetyCatch)
531
+ const child = await this._load(type, id)
532
+ try {
533
+ const out = await child.store.removed(this.identity.id)
534
+ // a launch finds a leave the app closed under before her removal was appended
535
+ if (!out) await child.store.del('members', this.identity.id)
536
+ await child.store.held()
537
+ if (out === 'removed') return
538
+ const { data: row } = await this.store.get('handles', id)
539
+ if (row?.state !== 'leaving') return
540
+ await this.store.tx(async (tx) => {
541
+ await tx.set('handles', { id, state: 'left' })
542
+ await tx.del('handles', id)
543
+ })
544
+ } finally {
545
+ await child._end()
546
+ }
547
+ }
548
+ const going = run()
549
+ .catch((err) => err.code !== 'CLOSED' && this._onerror(err))
550
+ .finally(() => this._departing.delete(id))
551
+ this._departing.set(id, going)
552
+ }
553
+
554
+ // a device that applies its own identity's removal writes it on the row, with who removed her
555
+ /** @private */
556
+ async _ousted(child) {
557
+ const removal = await child.store.removal(this.identity.id)
558
+ if (!removal) return
559
+ const { data: row } = await this.store.get('handles', child.id)
560
+ // only a seat held is lost: a row asking or joining is a rejoin under way, one ended is over
561
+ if (!row || !['in', 'leaving'].includes(row.state || 'in')) return
562
+ const fields = { by: removal.by, reason: null, encryptionKey: null, epochs: null }
563
+ await this.store.set('handles', { id: child.id, state: 'removed', ...fields })
431
564
  }
432
565
 
433
566
  /**
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.
567
+ * One holder done with it: a child stays open for the others. With its last, what they tied to it ends and it
568
+ * stays open, idle, so a reopen finds it as it is; the root keeps `keepOpen` of them (16 by default) and one more
569
+ * closes the least recently used, on its own. The root closes at once, after any `cero.link` or `cero.restore` on
570
+ * it: one still waiting stops, one taking its place finishes first.
436
571
  * @returns {Promise<void>}
437
572
  */
438
- close() {
439
- if (!this.parent) return this._end()
573
+ async close() {
574
+ if (!this.parent) {
575
+ // one swap may wait behind another: the root ends once none is left
576
+ const swap = this._swap
577
+ if (swap) return (swap.committing ? swap.done : swap.abort()).then(() => this.close())
578
+ return this._end()
579
+ }
440
580
  if (this._refs > 1) {
441
581
  this._refs--
442
- return Promise.resolve()
582
+ return
443
583
  }
444
- if (this._idle) return Promise.resolve()
445
- const linger = this.root._opts.linger ?? LINGER
446
- if (!linger || this._refs === 0) return this._end()
584
+ const idle = this.root._idle
585
+ if (idle.has(this)) return
586
+ const max = this.root._opts.keepOpen ?? KEEP_OPEN
587
+ if (!max || this._refs === 0) return this._end()
447
588
  this._refs = 0
448
- this._idle = setTimeout(() => this._end().catch(this._onerror), linger)
449
- this._idle.unref?.()
450
- return Promise.resolve()
589
+ this._disown()
590
+ idle.add(this)
591
+ if (idle.size <= max) return
592
+ const [oldest] = idle
593
+ oldest._end().catch(this._onerror)
451
594
  }
452
595
 
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 */
596
+ /** @private one more holder: an idle handle is kept */
458
597
  _hold() {
459
- clearTimeout(this._idle)
460
- this._idle = null
598
+ this.root._idle.delete(this)
461
599
  this._refs++
462
600
  }
463
601
 
602
+ /**
603
+ * Closed for every holder at once: pushed out past `keepOpen`, the parent closing, or the handle left for good.
604
+ * @private
605
+ */
464
606
  _end() {
465
- clearTimeout(this._idle)
466
- this._idle = null
607
+ this.root._idle.delete(this)
467
608
  this._refs = 0
468
609
  return super.close()
469
610
  }
@@ -507,7 +648,9 @@ export class Handle extends ReadyResource {
507
648
  epoch: (current && seqs.get(current)) || 0,
508
649
  suspended: this.root._sus.suspended,
509
650
  behind: this.store.behind || 0,
510
- nearby: this.root._bluetooth?.state ?? null
651
+ version: await this.store.dispatcher.version(this.store.view),
652
+ nearby: this.root._bluetooth?.state ?? null,
653
+ owed: await this.store.owed()
511
654
  }
512
655
  if (this.parent) data.topic = b4a.toHex(this.store.discoveryKey)
513
656
  return { data }
@@ -522,7 +665,7 @@ export class Handle extends ReadyResource {
522
665
  [this.store, 'unwritable'],
523
666
  [this.store, 'behind']
524
667
  ]
525
- if (this.parent) sources.push([this.root, 'status'])
668
+ if (this.parent) sources.push([this.root, 'status'], [this.root.store, 'behind'])
526
669
  for (const [emitter, event] of sources) emitter.on(event, fn)
527
670
  const off = this._onRadio(fn)
528
671
  return () => {
@@ -574,63 +717,135 @@ export class Handle extends ReadyResource {
574
717
  return () => bt.off('update', fn)
575
718
  }
576
719
 
577
- // the joins this device waits on, without the keys the local store keeps for them
578
720
  /** @private */
579
- async _joins(query = {}) {
580
- const rows = (await this.local.store.get('joins')).data
581
- const data = filter(
582
- rows.map(({ id, type, invite }) => ({ id, type, invite })),
583
- query
584
- )
585
- return { data, total: data.length, size: data.length }
721
+ _onTopics(fn) {
722
+ this.on('topics', fn)
723
+ return () => this.off('topics', fn)
586
724
  }
587
725
 
588
726
  /** @private */
589
- _onLocal(fn) {
590
- this.local.store.db.watch(fn)
591
- return () => this.local.store.db.unwatch(fn)
727
+ async _topics(query) {
728
+ if (typeof query === 'string') {
729
+ const { data } = await this.local.store.get('topics', query)
730
+ return { data: data && listing(data) }
731
+ }
732
+ const rows = (await this.local.store.get('topics')).data
733
+ return listed(rows.map(listing), query)
592
734
  }
593
735
 
736
+ // one pass at a time, failed or not: two overlapping could put back a row the later one deleted. A call while a
737
+ // pass waits to start joins it; `child` is the handle whose writers changed, none follows the root's rows
594
738
  /** @private */
595
- async _topics(query = {}) {
596
- const rows = (await this.local.store.get('topics')).data
597
- const data = filter(
598
- rows.map(({ id, handle, type, name }) => ({ id, handle, type, name })),
599
- query
600
- )
601
- return { data, total: data.length, size: data.length }
739
+ _index(child = null) {
740
+ if (this._queued) {
741
+ if (child) this._queued.children.add(child)
742
+ else this._queued.root = true
743
+ // a failed pass reaches onerror once, through the call that queued it: joined calls only wait for it
744
+ return this._indexing.catch(() => {})
745
+ }
746
+ const queued = (this._queued = { root: !child, children: new Set(child ? [child] : []) })
747
+ const run = async () => {
748
+ this._queued = null
749
+ if (this.closing || this.closed) return
750
+ try {
751
+ if (queued.root) await this._follow()
752
+ } finally {
753
+ // their writers are read whether or not the root's rows were, each on its own
754
+ for (const child of queued.children) await this._topic(child).catch(this._onerror)
755
+ }
756
+ }
757
+ this._indexing = (this._indexing ?? Promise.resolve()).then(run, run)
758
+ return this._indexing
602
759
  }
603
760
 
604
- // one pass at a time: two overlapping could put back a row the later one deleted
761
+ // a handle on its way to closing writes the writers it last applied while its store still reads, so a removal that
762
+ // landed just before is kept; the root's local store closes after its handles
605
763
  /** @private */
606
- _index() {
607
- this._indexing = (this._indexing ?? Promise.resolve()).then(() => this._reindex())
764
+ _seal(child) {
765
+ const run = () => this._topic(child, true)
766
+ this._indexing = (this._indexing ?? Promise.resolve()).then(run, run)
608
767
  return this._indexing
609
768
  }
610
769
 
770
+ // the topics rows follow the root's handles row by row: those that changed since the last pass that finished, so
771
+ // a launch reads none of the others. A pass with no point to go on from reads them all and drops the rows of
772
+ // handles that are gone
611
773
  /** @private */
612
- async _reindex() {
613
- if (this.closing || this.closed) return
614
- const { data: handles } = await this.store.get('handles')
615
- const { data: rows } = await this.local.store.get('topics')
616
- const wanted = new Map(handles.map((h) => [b4a.toHex(discoveryKey(h.key)), h]))
617
- const have = new Map(rows.map((row) => [row.id, row]))
618
- for (const row of rows) {
619
- if (!wanted.has(row.id)) await this.local.store.del('topics', row.id)
774
+ async _follow() {
775
+ const { changes, reset, settle } = await this.store.since('handles', 'topics')
776
+ let rows = null
777
+ if (reset) {
778
+ const wanted = new Set(
779
+ changes.filter(({ next }) => topical(next)).map(({ next }) => topicOf(next))
780
+ )
781
+ rows = new Map((await this.local.store.get('topics')).data.map((row) => [row.id, row]))
782
+ for (const id of rows.keys()) {
783
+ if (!wanted.has(id)) await this._drop(id)
784
+ }
620
785
  }
621
- for (const [id, h] of wanted) {
622
- const row = {
623
- id,
624
- handle: h.id,
625
- type: h.type,
626
- key: h.key,
627
- name: h.name ?? null,
628
- encryptionKey: h.encryptionKey ?? null,
629
- epochs: h.epochs && c.decode(epochEntries, h.epochs).length ? h.epochs : null
786
+ for (const { prev, next } of changes) {
787
+ if (!topical(next)) {
788
+ if (prev?.encryptionKey || !next) await this._drop(topicOf(prev))
789
+ continue
630
790
  }
631
- if (same(have.get(id), row)) continue
632
- await this.local.store.put('topics', row)
791
+ await this._row(next, rows ? (rows.get(topicOf(next)) ?? null) : undefined)
792
+ }
793
+ await settle()
794
+ }
795
+
796
+ // a topics row written or dropped wakes what watches them
797
+ /** @private */
798
+ async _put(row) {
799
+ await this.local.store.put('topics', row)
800
+ this.emit('topics')
801
+ }
802
+
803
+ /** @private */
804
+ async _drop(id) {
805
+ await this.local.store.del('topics', id)
806
+ this.emit('topics')
807
+ }
808
+
809
+ // who may write to an open handle, on the row the root's pass wrote for it; a handle on its way out is its
810
+ // seal's to read
811
+ /** @private */
812
+ async _topic(child, sealing = false) {
813
+ if (!child.opened || (child.closing && !sealing)) return
814
+ const id = b4a.toHex(child.store.discoveryKey)
815
+ let { data: have } = await this.local.store.get('topics', id)
816
+ if (!have) {
817
+ // the root's pass has not written its row, or failed to: it does now, so the handle's writers are kept
818
+ await this._follow()
819
+ have = (await this.local.store.get('topics', id)).data
820
+ if (!have) return
821
+ }
822
+ const writers = await writersOf(child.store).catch(unread)
823
+ if (sameBytes(have.writers, writers)) return
824
+ // me.topics shows no writers: this one wakes no watch
825
+ await this.local.store.put('topics', { ...have, writers })
826
+ }
827
+
828
+ // one handle's topics row, written when it differs from `have`, the row there is, read when not given. Who may
829
+ // write is read off the handle while it is open here, and kept as it was otherwise
830
+ /** @private */
831
+ async _row(h, have) {
832
+ const id = topicOf(h)
833
+ // a handle on its way out is its seal's to read
834
+ const child = [...this.children, ...this._pending].find(
835
+ (c) => c.opened && !c.closing && c.id === h.id
836
+ )
837
+ if (have === undefined) have = (await this.local.store.get('topics', id)).data
838
+ const row = {
839
+ id,
840
+ handle: h.id,
841
+ type: h.type,
842
+ key: h.key,
843
+ name: h.name ?? null,
844
+ encryptionKey: h.encryptionKey ?? null,
845
+ epochs: h.epochs && c.decode(epochEntries, h.epochs).length ? h.epochs : null,
846
+ writers: child ? await writersOf(child.store).catch(unread) : (have?.writers ?? null)
633
847
  }
848
+ if (!same(have, row)) await this._put(row)
634
849
  }
635
850
 
636
851
  // a push about one of this device's handles, verified against its own cores
@@ -638,8 +853,7 @@ export class Handle extends ReadyResource {
638
853
  async _receive(payload) {
639
854
  // a suspended storage answers no read: the cold entry serves a push while the app sleeps
640
855
  if (this._sus.suspended) throw CeroError.INVALID('receive: the app is suspended')
641
- const { data: rows } = await this.local.store.get('topics')
642
- return read(this.store.store.storage, this.spec, payload, rows)
856
+ return read(this.store.store.storage, this.spec, payload, this.local.store)
643
857
  }
644
858
 
645
859
  /** @private */
@@ -659,7 +873,8 @@ export class Handle extends ReadyResource {
659
873
  const to = Mailbox.getAddress(secret)
660
874
  const onmessage = async (bytes) => {
661
875
  const mail = unseal(to, bytes)
662
- if (mail) await fn(mail.value, { id: mail.id, from: mail.from, device: mail.device })
876
+ if (!mail) return false
877
+ await fn(mail.value, { id: mail.id, from: mail.from, device: mail.device })
663
878
  }
664
879
  const inbox = this.root.mailbox.receive(secret, onmessage, { keep })
665
880
  return () => inbox.close()
@@ -672,8 +887,11 @@ export class Handle extends ReadyResource {
672
887
  * @private
673
888
  */
674
889
  _resolveCore(coreKey, info) {
675
- const hex = b4a.toHex(coreKey)
676
- const encryptionKey = this.root._coreKeys.get(hex)
890
+ const keys = this.root._coreKeys
891
+ const file = (type) => (info.blob ? keys.get(fileEntry(coreKey, info.blob, type)) : undefined)
892
+ // a row typed '' keys its file ahead of one whose type no header carries, served as '' too
893
+ const encryptionKey =
894
+ file(info.type) ?? (info.type ? undefined : file(UNSERVED)) ?? keys.get(b4a.toHex(coreKey))
677
895
  if (encryptionKey !== undefined) return { key: coreKey, encryptionKey }
678
896
  return null
679
897
  }
@@ -715,9 +933,12 @@ export class Handle extends ReadyResource {
715
933
  _registerBlobCore(id, stamp) {
716
934
  if (!id || !this.root?._coreKeys) return
717
935
  try {
718
- const { coreKey } = decodeId(id)
719
- const hex = b4a.toHex(coreKey)
720
- if (!this.root._coreKeys.has(hex)) {
936
+ // a row's stamp keys its own file: a member's row cannot pick the key of another's on the same core
937
+ const { coreKey, blobId, type } = decodeId(id)
938
+ // a core this device keys itself serves every file on it
939
+ if (this.root._coreKeys.has(b4a.toHex(coreKey))) return
940
+ const entry = fileEntry(coreKey, blobId, servedType(type) === type ? type : UNSERVED)
941
+ if (!this.root._coreKeys.has(entry)) {
721
942
  // no stamp on a file-field value, look it up (fire-and-forget, idempotent)
722
943
  if (stamp === undefined) {
723
944
  this.store
@@ -730,10 +951,10 @@ export class Handle extends ReadyResource {
730
951
  }
731
952
  const key = this._blobCoreKey(stamp)
732
953
  if (!key) return // unknown epoch — this device is not entitled to the core
733
- this.root._coreKeys.set(hex, key)
954
+ this.root._coreKeys.set(entry, key)
734
955
  }
735
956
  // remember which handle read it, so close prunes the entry
736
- if (this !== this.root) (this._blobKeys ??= new Set()).add(hex)
957
+ if (this !== this.root) (this._blobKeys ??= new Set()).add(entry)
737
958
  } catch {
738
959
  // ignore invalid ids
739
960
  }
@@ -809,8 +1030,15 @@ export class Handle extends ReadyResource {
809
1030
 
810
1031
  const ts = Date.now()
811
1032
  const writerKey = child.store.writerKey
812
- // one batch, so a handle's first two ops land together
1033
+ const { meta, ns, target } = child.store
1034
+ const lists =
1035
+ (meta.since?.routes[`@${ns}/revoke`] ?? 0) <= target ? await this._lists() : null
1036
+ // its key goes in a root row the removed device reads until the root rotates
1037
+ const owed = lists && !(await this.store.rotated())
1038
+ // one batch, so a handle's first ops land together
813
1039
  await child.store.tx(async (tx) => {
1040
+ // first, so the rest is written at the version
1041
+ await tx.call('upgrade', { version: child.store.target })
814
1042
  await tx.call('add-writer', {
815
1043
  master: this.identity.publicKey,
816
1044
  writer: writerKey,
@@ -825,7 +1053,14 @@ export class Handle extends ReadyResource {
825
1053
  createdAt: ts,
826
1054
  updatedAt: ts
827
1055
  })
1056
+ // the removals the root holds are in the room from its start: told later, they would rotate it
1057
+ if (lists && !owed) {
1058
+ await tx.call('revoke', { removed: lists.removed, standing: lists.standing })
1059
+ }
828
1060
  })
1061
+ if (owed) {
1062
+ await child.store.call('revoke', { removed: lists.removed, standing: lists.standing })
1063
+ }
829
1064
  await this.store.call('add-handle', {
830
1065
  id,
831
1066
  type,
@@ -862,61 +1097,325 @@ export class Handle extends ReadyResource {
862
1097
  * @private
863
1098
  */
864
1099
  async _join(invite, type, { timeout = TIMEOUT } = {}) {
865
- const known = await this._joined(type, Invite.parse(invite).discoveryKey)
1100
+ const { key } = Invite.parse(invite)
1101
+ const known = await this._joined(type, key)
866
1102
  if (known) return known
867
1103
 
868
- const join = this._start(invite, type)
869
- join.waiting++
870
- try {
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
876
- } finally {
877
- join.waiting--
1104
+ const id = hid.encode(key)
1105
+ const start = Date.now()
1106
+ let { data: row } = await this.store.get('handles', id)
1107
+ // a room being left is asked again once it is left
1108
+ if (row?.state === 'leaving') {
1109
+ await wait(null, this._left(id), timeout)
1110
+ row = (await this.store.get('handles', id)).data
878
1111
  }
1112
+ // a join another device of this identity asks with is waited on here, not asked again
1113
+ const theirs =
1114
+ row?.state === 'asking' &&
1115
+ row.invite === invite &&
1116
+ !(await this._asked(id, invite, row.writer))
1117
+ const join = theirs ? null : this._start(invite, type)
1118
+ // a row in a room this identity lost its seat in is not the join landing: it lands once it moved on
1119
+ const stale = !!row && (row.state || 'in') === 'in'
1120
+ const left = timeout && Math.max(1, timeout - (Date.now() - start))
1121
+ await wait(join, this._landed(id, invite, join, stale), left)
1122
+ return this._load(type, id)
1123
+ }
1124
+
1125
+ /** @private */
1126
+ _left(id) {
1127
+ return new Promise((resolve, reject) => {
1128
+ const done = (err) => {
1129
+ off()
1130
+ this.off('close', onclose)
1131
+ if (err) reject(err)
1132
+ else resolve()
1133
+ }
1134
+ const check = async () => {
1135
+ const { data: row } = await this.store.get('handles', id)
1136
+ if (row?.state !== 'leaving') done(null)
1137
+ }
1138
+ const off = this.store.onUpdate('handles', () => check().catch(done))
1139
+ const onclose = () => done(CeroError.CLOSED('Handle'))
1140
+ this.once('close', onclose)
1141
+ check().catch(done)
1142
+ })
1143
+ }
1144
+
1145
+ // what an open waits on: the row, wherever the join is carried, or an error here its row has no state for
1146
+ /** @private */
1147
+ _landed(id, invite, join, stale) {
1148
+ return new Promise((resolve, reject) => {
1149
+ const done = (err) => {
1150
+ off()
1151
+ this.off('close', onclose)
1152
+ if (err) reject(err)
1153
+ else resolve()
1154
+ }
1155
+ const check = async () => {
1156
+ const { data: row } = await this.store.get('handles', id)
1157
+ // the row of another invite is a join this one takes over, unless it took this one over
1158
+ const ours = row?.invite === invite || (!!join && row?.invite === join.invite)
1159
+ const state = ours && (row.state || 'in')
1160
+ if (state && state !== 'in') stale = false
1161
+ if (state === 'in' && !stale && row.encryptionKey) done(null)
1162
+ else if (OVER[state && state.toUpperCase()]) done(ENDS[state](row.reason))
1163
+ }
1164
+ const off = this.store.onUpdate('handles', () => check().catch(done))
1165
+ const onclose = () => done(CeroError.CLOSED('Handle'))
1166
+ this.once('close', onclose)
1167
+ join?.done.catch(done)
1168
+ check().catch(done)
1169
+ })
879
1170
  }
880
1171
 
1172
+ // the device that asked holds the writer the answer is sealed to
1173
+ /** @private */
1174
+ async _asked(id, invite, writer) {
1175
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1176
+ // a row from before rows named their writer is the ask of the device that kept its invite
1177
+ return kept?.invite === invite && (!writer || hid.encode(kept.publicKey) === writer)
1178
+ }
1179
+
1180
+ // one join a handle, whoever waits on it: it goes on until its row says how it ended, and a close only pauses it
881
1181
  /** @private */
882
1182
  _start(invite, type) {
883
- const target = Invite.parse(invite).discoveryKey
884
- const key = `${type}/${b4a.toHex(target)}`
885
- let join = this._joining.get(key)
1183
+ const id = hid.encode(Invite.parse(invite).key)
1184
+ let join = this._joining.get(id)
886
1185
  if (!join) {
887
- join = new Join(this, {
888
- type,
889
- spec: pickHandle(this.spec, type),
890
- discoveryKey: target,
891
- onend: () => this._joining.delete(key)
1186
+ join = { id, type, invite: null, writer: null, waiting: 0, end: null, running: null }
1187
+ join.done = new Promise((resolve, reject) => {
1188
+ join.resolve = resolve
1189
+ join.reject = reject
892
1190
  })
893
- this._joining.set(key, join)
1191
+ join.done.catch(safetyCatch)
1192
+ this._joining.set(id, join)
894
1193
  }
895
- if (join.invite !== invite) join.start(invite)
1194
+ if (join.invite !== invite) this._run(join, invite)
896
1195
  return join
897
1196
  }
898
1197
 
1198
+ // a newer invite takes over from an older attempt: the writer stays, so a reply to the older one still lands
1199
+ /** @private */
1200
+ async _run(join, invite) {
1201
+ join.invite = invite
1202
+ join.writer = null
1203
+ join.running?.abort()
1204
+ const running = (join.running = new AbortController())
1205
+ const settle = (end, value) => {
1206
+ this._joining.delete(join.id)
1207
+ end(value)
1208
+ }
1209
+ try {
1210
+ const id = await this._ask(join.type, invite)
1211
+ const writer = (join.writer = await this._loadKeyPair(id))
1212
+ const { data: row } = await this.store.get('handles', id)
1213
+ // the keys are on the row before the reply is let go: a restart opens the handle without joining again
1214
+ const keep = async (answer) => {
1215
+ if (!(answer instanceof Error)) await this._stand(id, 'joining', keys(answer))
1216
+ }
1217
+ const spec = pickHandle(this.spec, join.type)
1218
+ const { identity, mailbox } = this
1219
+ const opts = { identity, spec, writer, keep, timeout: 0, signal: running.signal }
1220
+ const reply = row.encryptionKey
1221
+ ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [], writer }
1222
+ : await Pairing.join(mailbox, invite, opts)
1223
+ await this._stand(id, 'joining', keys(reply))
1224
+ const child = await this._enter(join.type, reply, invite)
1225
+ // every waiter takes its own hold once the row reads in: this one is let go, idle until the app opens it
1226
+ child.close().catch(this._onerror)
1227
+ settle(join.resolve, child)
1228
+ } catch (err) {
1229
+ if (running !== join.running) return
1230
+ const end = join.end || err
1231
+ // counted before its row says how it ended: a waiter hears that row
1232
+ const alone = !join.waiting
1233
+ // a close pauses the join, anything else ends it, and its row says how
1234
+ const report = (err) => this.closing || this._onerror(err)
1235
+ if (end.code !== 'CLOSED') {
1236
+ await this._over(join.id, end, { invite, writer: join.writer }).catch(report)
1237
+ }
1238
+ if (err.code !== 'CLOSED' && alone) this._onerror(err)
1239
+ settle(join.reject, end)
1240
+ }
1241
+ }
1242
+
1243
+ // ends it for good from any device: its row reads cancelled, so no device and no restart carries it on
899
1244
  /** @private */
900
1245
  async _cancel(invite) {
901
- const id = b4a.toHex(Invite.parse(invite).discoveryKey)
902
- const join = [...this.root._joining.values()].find((join) => join.id === id)
903
- await join?.cancel()
904
- return !!join
1246
+ const root = this.root
1247
+ const id = hid.encode(Invite.parse(invite).key)
1248
+ if (!(await root._over(id, CeroError.CANCELLED()))) return false
1249
+ const join = root._joining.get(id)
1250
+ if (join) {
1251
+ root._stop(join, CeroError.CANCELLED())
1252
+ await join.done.catch(safetyCatch)
1253
+ }
1254
+ return true
1255
+ }
1256
+
1257
+ // the latest ask stands: a request of this device's writer its row no longer carries, cancelled,
1258
+ // deleted or asked again under another invite on any device, is taken back. One whose row ended
1259
+ // otherwise is let go
1260
+ /** @private */
1261
+ async _check(ask) {
1262
+ const { data: row } = await this.store.get('handles', ask.handle)
1263
+ const { data: kept } = await this.local.store.get('handle-keypairs', ask.handle)
1264
+ const state = row && (row.state || 'in')
1265
+ const mine = !!kept && b4a.equals(kept.publicKey, ask.publicKey)
1266
+ const asks = state === 'asking' || state === 'joining'
1267
+ if (mine && asks && row.writer === ask.id) return
1268
+ // a seated row names no writer
1269
+ const ended = row && !asks && state !== 'cancelled' && (!row.writer || row.writer === ask.id)
1270
+ if (ended && row.invite === ask.invite) return this.local.store.del('asks', ask.id)
1271
+ // only the join that asks with this writer stops: one still choosing its writer may ask anew
1272
+ const join = this._joining.get(ask.handle)
1273
+ if (join?.writer && b4a.equals(join.writer.publicKey, ask.publicKey)) {
1274
+ this._stop(join, CeroError.CANCELLED())
1275
+ }
1276
+ if (this._taking.has(ask.id)) return
1277
+ this._taking.add(ask.id)
1278
+ this._takeBack(ask)
1279
+ .catch((err) => this.closing || this._onerror(err))
1280
+ .finally(() => this._taking.delete(ask.id))
1281
+ }
1282
+
1283
+ // announced until a peer or a mirror holds it, `KEPT` at most; its writer goes with it, unless its
1284
+ // cancelled row tells a launch this device asked
1285
+ /** @private */
1286
+ async _takeBack(ask) {
1287
+ if (ask.createdAt >= Date.now() - KEPT) await this._announce(ask.type, ask)
1288
+ await this.local.store.del('asks', ask.id)
1289
+ const { data: row } = await this.store.get('handles', ask.handle)
1290
+ if (row?.state !== 'cancelled' || row.writer !== ask.id) await this._forget(ask.handle, ask)
1291
+ }
1292
+
1293
+ // a launch of the device that asked announces the cancel again, and once a peer or a mirror holds
1294
+ // it, the writer and the cancelled row go
1295
+ /** @private */
1296
+ async _retract({ id, type }) {
1297
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1298
+ if (!kept?.invite) return
1299
+ this._announce(type, kept)
1300
+ .then(() => this._forget(id, kept))
1301
+ .catch((err) => this.closing || this._onerror(err))
1302
+ }
1303
+
1304
+ /** @private */
1305
+ _announce(type, { invite, publicKey, secretKey }) {
1306
+ const spec = pickHandle(this.spec, type)
1307
+ return Pairing.cancel(this.mailbox, invite, { spec, writer: { publicKey, secretKey } })
1308
+ }
1309
+
1310
+ // a held cancel takes its writer, and the row it ended, unless a join since took them over
1311
+ /** @private */
1312
+ async _forget(id, { publicKey, invite }) {
1313
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1314
+ if (kept?.invite !== invite || !b4a.equals(kept.publicKey, publicKey)) return
1315
+ await this.local.store.del('handle-keypairs', id)
1316
+ const { data: row } = await this.store.get('handles', id)
1317
+ if (row?.state === 'cancelled' && row.writer === hid.encode(publicKey)) {
1318
+ await this.store.del('handles', id)
1319
+ }
1320
+ }
1321
+
1322
+ /** @private */
1323
+ _stop(join, end) {
1324
+ join.end = end
1325
+ join.running?.abort()
1326
+ }
1327
+
1328
+ // a join's row: `asking` with its invite and no keys. A join that ended under this invite ends the same way again
1329
+ /** @private */
1330
+ async _ask(type, invite) {
1331
+ const { key } = Invite.parse(invite)
1332
+ const id = hid.encode(key)
1333
+ const { data: row } = await this.store.get('handles', id)
1334
+ const state = row && (row.state || 'in')
1335
+ // the writer this device asks with: fixed before the join is written, so a resumed one hears the reply to it
1336
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1337
+ // an ask another device made since is the one that stands: this device asks anew in its place
1338
+ const latest =
1339
+ state === 'asking' &&
1340
+ !!kept &&
1341
+ (row.writer ? row.writer === hid.encode(kept.publicKey) : kept.invite === row.invite)
1342
+ const mine = !!kept?.invite && (state === 'joining' || latest)
1343
+ if (mine && (state === 'joining' || row.invite === invite)) return id
1344
+ if (ENDS[state] && row.invite === invite) throw ENDS[state](row.reason)
1345
+ const writer = mine ? kept : Identity.randomKeyPair()
1346
+ await this._saveKeyPair(id, writer, invite)
1347
+ // a room another device of this identity already has the keys of is joined with them
1348
+ if (state === 'joining') return id
1349
+ // a room she left is asked again under any invite, the one she came in with too
1350
+ if (state === 'left' && row.invite === invite) await this.store.call('del-handle', { id })
1351
+ const ts = Date.now()
1352
+ const { publicKey, secretKey } = writer
1353
+ await this.store.call('add-handle', {
1354
+ id,
1355
+ type,
1356
+ key,
1357
+ name: null,
1358
+ createdAt: ts,
1359
+ updatedAt: ts,
1360
+ state: 'asking',
1361
+ invite,
1362
+ writer: hid.encode(publicKey)
1363
+ })
1364
+ const ask = { id: hid.encode(publicKey), handle: id, type, invite, publicKey, secretKey }
1365
+ await this.local.store.put('asks', ask)
1366
+ return id
1367
+ }
1368
+
1369
+ // a join's row moves on once: a step run again finds it there
1370
+ /** @private */
1371
+ async _stand(id, state, fields) {
1372
+ const { data: row } = await this.store.get('handles', id)
1373
+ if (!row || row.state === state) return
1374
+ await this.store.set('handles', { id, state, ...fields })
1375
+ }
1376
+
1377
+ // how a join ended, on its row, which keeps none of the keys it was handed, and whether it did. A
1378
+ // join ends only its own ask, a cancel the one that stands under any invite of the room
1379
+ /** @private */
1380
+ async _over(id, err, join) {
1381
+ const state = OVER[err.code]
1382
+ const { data: row } = await this.store.get('handles', id)
1383
+ // a join ends its own request once it chose its writer, one seated or over stays as it reads
1384
+ const own = !join || (!!join.writer && row?.writer === hid.encode(join.writer.publicKey))
1385
+ const ends =
1386
+ (row?.state === 'asking' && own) || (row?.state === 'joining' && state === 'denied')
1387
+ if (!state || !ends || (join && row.invite !== join.invite)) return false
1388
+ const reason = err.reason ?? null
1389
+ try {
1390
+ await this.store.set('handles', { id, state, reason, encryptionKey: null, epochs: null })
1391
+ } catch (err) {
1392
+ // an answer that landed since the read moved the row on
1393
+ if (err.code === 'REFUSED') return false
1394
+ throw err
1395
+ }
1396
+ return true
905
1397
  }
906
1398
 
907
1399
  // a stored writer still admitted reopens without pairing; a removed writer's core is frozen,
908
1400
  // so that one pairs again with a fresh keypair
909
1401
  /** @private */
910
- async _joined(type, target) {
911
- const { data: joined } = await this.store.get('handles')
912
- const existing = joined.find((h) => h.type === type && b4a.equals(discoveryKey(h.key), target))
1402
+ async _joined(type, key) {
1403
+ const { data: existing } = await this.store.get('handles', hid.encode(key))
913
1404
  if (!existing) return null
1405
+ if (existing.type !== type) {
1406
+ throw CeroError.INVALID(`handle ${existing.id} is type ${existing.type}, not ${type}`)
1407
+ }
1408
+ // a join on its way, or one that is over, is its row's to tell
1409
+ if (!existing.encryptionKey || (existing.state || 'in') !== 'in') return null
914
1410
  const known = await this._load(type, existing.id)
915
1411
  const { data: me } = await known.store.get('members', this.identity.id)
916
1412
  const { data: device } = await known.store.get('devices', hid.encode(known.store.writerKey))
917
1413
  // a reader never had a seat, a removed writer lost it
918
1414
  if (me && (device || me.role === 'reader')) return known
1415
+ // the identity's removal is its row's, every device's; a device that alone lost its seat is refused here
1416
+ if (!me) await this._ousted(known).catch(safetyCatch)
919
1417
  await known._end().catch(safetyCatch)
1418
+ if (me) throw ENDS.removed()
920
1419
  return null
921
1420
  }
922
1421
 
@@ -928,7 +1427,12 @@ export class Handle extends ReadyResource {
928
1427
  * @returns {Promise<Handle>}
929
1428
  * @private
930
1429
  */
931
- async _enter(type, reply) {
1430
+ async _enter(type, reply, invite) {
1431
+ const id = hid.encode(reply.key)
1432
+ // a room this identity lost its seat in stays open on its old writer: it ends before the new seat opens it
1433
+ const stale = [...this.children].find((c) => c.id === id && !c.closing)
1434
+ const out = stale && (await stale.store.removed(this.identity.id))
1435
+ if (out) await stale._end().catch(safetyCatch)
932
1436
  const child = /** @type {Child} */ (
933
1437
  this._room({
934
1438
  spec: pickHandle(this.spec, type),
@@ -936,27 +1440,26 @@ export class Handle extends ReadyResource {
936
1440
  ...delivered(reply)
937
1441
  })
938
1442
  )
1443
+ // its row is listed while it joins: an open by id shares this child, a second on the same core deadlocks
939
1444
  let publish = null
940
1445
  let abort = null
941
- let inflightId = null
1446
+ const inflight = new Promise((resolve, reject) => {
1447
+ publish = resolve
1448
+ abort = reject
1449
+ })
1450
+ inflight.catch(safetyCatch)
1451
+ this._loading?.set(id, inflight)
942
1452
  try {
943
1453
  await child.ready()
1454
+ // let in by a promise, this device seats itself: its claim writes the member row
1455
+ await child.store.claim({ timeout: 0 })
944
1456
  // admitted once our member row lands; the same apply seats a writer, a reader has no seat
945
1457
  const member = await admitted(child.store, this.identity.id)
946
1458
  if (member.role !== 'reader' && !child.store.writable) {
947
1459
  await child.store.whenWritable({ timeout: 0 })
948
1460
  }
949
1461
 
950
- const id = hid.encode(child.store.key)
951
- // same create/open race as _create, a concurrent _load must share this child
952
- const inflight = new Promise((resolve, reject) => {
953
- publish = resolve
954
- abort = reject
955
- })
956
- inflight.catch(safetyCatch)
957
- inflightId = id
958
- this._loading?.set(id, inflight)
959
- await this._saveKeyPair(id, child.store.keyPair)
1462
+ await this._saveKeyPair(id, child.store.keyPair, invite)
960
1463
 
961
1464
  const ts = Date.now()
962
1465
  await this.store.call('add-handle', {
@@ -967,33 +1470,64 @@ export class Handle extends ReadyResource {
967
1470
  epochs: c.encode(epochEntries, child.store.keyring.all()),
968
1471
  name: null,
969
1472
  createdAt: ts,
970
- updatedAt: ts
1473
+ updatedAt: ts,
1474
+ state: 'in',
1475
+ invite
971
1476
  })
972
1477
  this._adopt(child, {})
973
1478
  publish(child)
974
1479
  this._loading?.delete(id)
975
1480
  return child
976
1481
  } catch (err) {
977
- if (abort) abort(err)
978
- if (inflightId) this._loading?.delete(inflightId)
1482
+ abort(err)
1483
+ this._loading?.delete(id)
979
1484
  await child._end().catch(safetyCatch)
980
1485
  throw err
981
1486
  }
982
1487
  }
983
1488
 
984
- // joins not answered at the last close go on, with nobody waiting; the mailbox sends what its
985
- // outbox kept
1489
+ // the rows that ended go, with their keypairs, once the app had `KEPT` to show why; a cancel sooner,
1490
+ // at a launch of the device that asked once a peer holds it: another device may yet owe it
1491
+ /** @private */
1492
+ async _sweep() {
1493
+ const old = Date.now() - KEPT
1494
+ const gone = []
1495
+ for (const state of SWEPT) {
1496
+ for (const row of (await this.store.get('handles', { state })).data) {
1497
+ if (row.updatedAt < old) gone.push(row.id)
1498
+ else if (state === 'cancelled') await this._retract(row)
1499
+ }
1500
+ }
1501
+ if (!gone.length) return
1502
+ await this.store.tx(async (tx) => {
1503
+ for (const id of gone) await tx.del('handles', id)
1504
+ })
1505
+ for (const id of gone) await this.local.store.del('handle-keypairs', id)
1506
+ }
1507
+
1508
+ // the joins on their way go on, with nobody waiting; the mailbox sends what its outbox kept
986
1509
  /** @private */
987
1510
  async _carryOn() {
988
- for (const { id, invite, type } of (await this.local.store.get('joins')).data) {
989
- // the root's own device link row has no handle type: the launch resumes that one
990
- if (!this.spec.handles?.[type]) continue
991
- if (await this._joined(type, Invite.parse(invite).discoveryKey)) {
992
- await this.local.store.del('joins', id)
993
- continue
1511
+ // the rows not settled, through their index: never every handle
1512
+ for (const state of ['asking', 'joining']) {
1513
+ for (const { id, type, invite, writer, encryptionKey } of (
1514
+ await this.store.get('handles', { state })
1515
+ ).data) {
1516
+ // an answer is heard by the device that asked, and the keys on a row seat any device
1517
+ if (encryptionKey || (await this._asked(id, invite, writer))) this._start(invite, type)
994
1518
  }
995
- this._start(invite, type)
996
1519
  }
1520
+ for (const { id, type } of (await this.store.get('handles', { state: 'leaving' })).data) {
1521
+ this._depart(type, id)
1522
+ }
1523
+ // a join another device ended stops here
1524
+ for (const join of [...this._joining.values()]) {
1525
+ const { data: row } = await this.store.get('handles', join.id)
1526
+ if (row?.invite === join.invite && OVER[row.state?.toUpperCase()]) {
1527
+ this._stop(join, ENDS[row.state](row.reason))
1528
+ }
1529
+ }
1530
+ for (const ask of (await this.local.store.get('asks')).data) await this._check(ask)
997
1531
  }
998
1532
 
999
1533
  /**
@@ -1035,42 +1569,45 @@ export class Handle extends ReadyResource {
1035
1569
  * @private
1036
1570
  */
1037
1571
  async _reopen(type, id) {
1038
- const { data } = await this.store.get('handles', id)
1039
- if (!data) throw CeroError.UNKNOWN('handle', id)
1040
- if (data.type !== type) {
1041
- throw CeroError.INVALID(`handle ${id} is type ${data.type}, not ${type}`)
1042
- }
1043
- let writer = await this._loadKeyPair(id)
1044
- if (!writer) {
1045
- writer = Identity.randomKeyPair()
1572
+ let child = null
1573
+ try {
1574
+ const { data } = await this.store.get('handles', id)
1575
+ // a join with no keys yet is no room to open
1576
+ if (!data?.encryptionKey) throw CeroError.UNKNOWN('handle', id)
1577
+ if (data.type !== type) {
1578
+ throw CeroError.INVALID(`handle ${id} is type ${data.type}, not ${type}`)
1579
+ }
1580
+ await this._tellings.get(id)
1046
1581
  // stored before its claim is on the log: a retry claims with it, never with another
1582
+ const writer = (await this._loadKeyPair(id)) || Identity.randomKeyPair()
1047
1583
  await this._saveKeyPair(id, writer)
1048
- }
1049
- const child = this._room({
1050
- spec: pickHandle(this.spec, type),
1051
- namespace: `${NS}/handle/${type}/${id}`,
1052
- key: data.key,
1053
- encryptionKey: data.encryptionKey,
1054
- epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
1055
- keyPair: /** @type {KeyPair} */ (writer)
1056
- })
1057
- try {
1584
+ child = this._room({
1585
+ spec: pickHandle(this.spec, type),
1586
+ namespace: `${NS}/handle/${type}/${id}`,
1587
+ key: data.key,
1588
+ encryptionKey: data.encryptionKey,
1589
+ epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
1590
+ keyPair: /** @type {KeyPair} */ (writer)
1591
+ })
1058
1592
  await child.ready()
1059
1593
  // a writer that never wrote has not claimed yet
1060
1594
  if (!child.store.writable && child.store.length === 0) {
1061
1595
  await child.store.claim({ timeout: TIMEOUT })
1062
1596
  }
1063
1597
  this._adopt(child, {})
1598
+ return child
1064
1599
  } catch (err) {
1065
- await child._end().catch(safetyCatch)
1066
- throw err
1600
+ await child?._end().catch(safetyCatch)
1601
+ // a reopen the root's close broke fails with CLOSED, whichever store went first
1602
+ throw this.closing || this.closed ? CeroError.CLOSED('Handle') : err
1067
1603
  }
1068
- return child
1069
1604
  }
1070
1605
 
1071
1606
  // a handle has its type's hooks before it opens, so no op it applies runs without them
1072
1607
  /** @private */
1073
1608
  _room(opts) {
1609
+ // a closing root has listed the rooms it closes: one opened now would outlive its stores
1610
+ if (this.closing || this.closed) throw CeroError.CLOSED('Handle')
1074
1611
  const child = new Handle({ parent: this, ...opts })
1075
1612
  for (const hook of this._typeHooks) hook.apply(child)
1076
1613
  this._pending.add(child)
@@ -1088,8 +1625,10 @@ export class Handle extends ReadyResource {
1088
1625
 
1089
1626
  /** @private */
1090
1627
  async _wake() {
1091
- if (this.closing || this.closed) return
1628
+ if (this.closed) return
1092
1629
  await this.store.store.resume().catch(this._onerror)
1630
+ // a close takes its storage back and nothing else: the network stays down
1631
+ if (this.closing) return
1093
1632
  await this.network.resume().catch(this._onerror)
1094
1633
  await this._bluetooth?.resume().catch(this._onerror)
1095
1634
  }
@@ -1103,19 +1642,133 @@ export class Handle extends ReadyResource {
1103
1642
  child._refs = 1
1104
1643
  this._serve(child)
1105
1644
  this._carry(child)
1106
- this._prune(child).catch(this._onerror)
1107
- this.emit('handle', child, info)
1645
+ // it tells a handle nothing before it has a seat there
1646
+ const prune = () => this._prune(child).catch(this._onerror)
1647
+ child.store.on('writable', prune)
1648
+ child.once('close', () => child.store.off('writable', prune))
1649
+ prune()
1650
+ this._seats(child)
1651
+ // what a listener ties to the handle as it runs is no holder's: it stays through their last close
1652
+ child._arriving = true
1653
+ try {
1654
+ this.emit('handle', child, info)
1655
+ } finally {
1656
+ child._arriving = false
1657
+ }
1658
+ }
1659
+
1660
+ // a handle's topics row follows who may write to it while it is open, so a push is checked
1661
+ // against the room as this device last applied it
1662
+ /** @private */
1663
+ _seats(child) {
1664
+ const onchange = (touched) => {
1665
+ if (touched.has('*') || touched.has('devices') || touched.has('members')) {
1666
+ this._index(child).catch(this._onerror)
1667
+ this._ousted(child).catch(this._onerror)
1668
+ }
1669
+ }
1670
+ child.store.on('update', onchange)
1671
+ child.once('close', () => child.store.off('update', onchange))
1672
+ this._index(child).catch(this._onerror)
1673
+ }
1674
+
1675
+ // a device removed from the root is out of every handle: its chain is static, so a handle is
1676
+ // told the identity's keys the root removed and those it seats, by a device that stands there,
1677
+ // when that is not what it was told. One compare at a time: two would tell it twice. It is
1678
+ // marked told only once a peer holds what was written within `timeout`: null till then
1679
+ /** @private */
1680
+ _prune(child, stamp, timeout = SERVED) {
1681
+ const run = async () => {
1682
+ try {
1683
+ const told = await this._compare(child, timeout)
1684
+ return told && (stamp === undefined || (await this._teach(child, stamp, timeout)))
1685
+ } catch (err) {
1686
+ // one that closes as it is told is told again, at its next open or pass
1687
+ if (this.closing || child.closing || child.closed) return false
1688
+ throw err
1689
+ }
1690
+ }
1691
+ const pruning = child._pruning ? child._pruning.then(run) : run()
1692
+ child._pruning = pruning.catch(safetyCatch)
1693
+ return pruning
1694
+ }
1695
+
1696
+ // covered once it holds what the root holds, or this device has nothing to tell it by: a reader
1697
+ // tells from her own core, a seatless write, in a room at the version that brings it. One below
1698
+ // it is marked for this build, so a pass opens it again only for a build that may bring it there
1699
+ /** @private */
1700
+ async _compare(child, timeout) {
1701
+ if (child.closing || child.closed) return false
1702
+ const removed = await this.store.removals()
1703
+ if (removed.length === 0) return true
1704
+ const { data: rows } = await this.store.get('devices')
1705
+ const standing = rows.filter((row) => row.key).map((row) => row.key)
1706
+ const { store } = child
1707
+ const at = Math.min(store.version, await store.dispatcher.version(store.view))
1708
+ if ((store.meta.since?.routes[`@${store.ns}/revoke`] ?? 0) > at) {
1709
+ if (store.writable) await this._unseat(child, removed)
1710
+ return this._record(child, { told: below(digest(removed, standing), store.meta) }, timeout)
1711
+ }
1712
+ if (!has(standing, this.identity.device.publicKey)) return false
1713
+ // a root that lags has fewer removed than the handle was told: those add up, and stay
1714
+ const told = await store.told(this.identity.id)
1715
+ const same =
1716
+ removed.every((key) => has(told.removed, key)) &&
1717
+ standing.length === told.standing.length &&
1718
+ standing.every((key) => has(told.standing, key))
1719
+ if (child.closing || child.closed) return false
1720
+ if (!same) {
1721
+ // a row with no key, or no member, tells nothing by: the proof does
1722
+ const { data: seat } = await store.get('devices', hid.encode(store.writerKey))
1723
+ const proof =
1724
+ seat?.key && seat.memberId
1725
+ ? null
1726
+ : this.identity.sign(admission(store.key, store.writerKey, store.writerKey))
1727
+ await store.call('revoke', {
1728
+ removed: b4a.concat(removed),
1729
+ standing: b4a.concat(standing),
1730
+ proof
1731
+ })
1732
+ }
1733
+ return this._record(child, { told: digest(removed, standing) }, timeout)
1734
+ }
1735
+
1736
+ // what the extensions tell a room this device may write in, stamped once it is told
1737
+ /** @private */
1738
+ async _teach(child, stamp, timeout) {
1739
+ if (child.store.writable) for (const { tell } of this._tellers) await tell(child)
1740
+ return this._record(child, { stamp }, timeout)
1741
+ }
1742
+
1743
+ // an open room too: the app may close it before a peer holds what it was told
1744
+ /** @private */
1745
+ async _record(child, marks, timeout) {
1746
+ const { data } = await this.local.store.get('handle-keypairs', child.id)
1747
+ if (data && Object.keys(marks).every((k) => sameBytes(data[k], marks[k]))) return true
1748
+ // a removal counts once a device that stands has it: a peer that holds it may be the removed one
1749
+ const removed = marks.told ? await this.store.removals() : null
1750
+ const holds = await reached(child.store, this.identity.id, removed, timeout)
1751
+ if (child.closing || child.closed) return false
1752
+ if (!holds) return null
1753
+ await this._mark(child.id, marks)
1754
+ return true
1755
+ }
1756
+
1757
+ // what a room was told, kept on its keypair row
1758
+ /** @private */
1759
+ async _mark(id, marks) {
1760
+ const { data } = await this.local.store.get('handle-keypairs', id)
1761
+ if (!data || Object.keys(marks).every((k) => sameBytes(data[k], marks[k]))) return
1762
+ await this.local.store.put('handle-keypairs', { ...data, ...marks })
1108
1763
  }
1109
1764
 
1110
- // a device removed from the root loses its seats in every handle: its chain is static, so the
1111
- // handles are told by whichever device of the identity has them open
1765
+ // a handle that has no route to be told by loses the removed device's seats one by one
1112
1766
  /** @private */
1113
- async _prune(child) {
1114
- const { data: mine } = await this.store.get('devices')
1115
- const kept = new Set(mine.filter((d) => d.key).map((d) => b4a.toHex(d.key)))
1767
+ async _unseat(child, removed) {
1116
1768
  const { data: rows } = await child.store.get('devices')
1117
1769
  for (const row of rows) {
1118
- if (row.memberId !== this.identity.id || !row.key || kept.has(b4a.toHex(row.key))) continue
1770
+ // a sibling this root has not heard of yet is no removal: only its record is
1771
+ if (row.memberId !== this.identity.id || !row.key || !has(removed, row.key)) continue
1119
1772
  if (child.closing || child.closed) return
1120
1773
  await child.store.del('devices', row.id)
1121
1774
  }
@@ -1126,14 +1779,215 @@ export class Handle extends ReadyResource {
1126
1779
  for (const child of this.children) await this._prune(child)
1127
1780
  }
1128
1781
 
1782
+ // the closed rooms are told too, by a pass over those this device has a writer in, and every room
1783
+ // the identity is in for a removal since this device stood, when the root's device lists or the
1784
+ // extensions' stamp are not the ones last told to all of them. One pass at a time: a call while
1785
+ // one waits to start joins it
1786
+ /** @private */
1787
+ _tellClosed() {
1788
+ if (this._retell) return this._telling
1789
+ this._retell = true
1790
+ const run = () => {
1791
+ this._retell = false
1792
+ return this._pass().catch((err) => this.closing || this._onerror(err))
1793
+ }
1794
+ this._telling = (this._telling ?? Promise.resolve()).then(run)
1795
+ return this._telling
1796
+ }
1797
+
1798
+ /** @private */
1799
+ async _pass() {
1800
+ if (this.closing) return
1801
+ const lists = await this._lists()
1802
+ const stamp = await this._stamp()
1803
+ // the build too: one that may bring revoke to a room found below it opens that room again
1804
+ const seen = hash([stamp ?? b4a.alloc(0), built(this.spec)])
1805
+ const { data: told } = await this.local.store.get('told')
1806
+ const listed =
1807
+ told &&
1808
+ (!lists ||
1809
+ (sameBytes(told.removed, lists.removed) && sameBytes(told.standing, lists.standing)))
1810
+ if (listed && sameBytes(told.stamp, seen)) return
1811
+ // a writer in a room is the writer keypair this device keeps for it
1812
+ const rooms = []
1813
+ const held = new Set()
1814
+ for (let after; ;) {
1815
+ const { data } = await this.local.store.get('handle-keypairs', { gt: after, limit: PAGE })
1816
+ for (const row of data) {
1817
+ held.add(row.id)
1818
+ if ((lists && !(await this._marked(row, lists))) || !sameBytes(row.stamp, stamp)) {
1819
+ rooms.push({ id: row.id, used: row.used ?? 0 })
1820
+ }
1821
+ }
1822
+ if (data.length < PAGE) break
1823
+ after = data[data.length - 1].id
1824
+ }
1825
+ // a room no device that stands may have opened is told a removal too: this device takes a seat.
1826
+ // One the root held when this device first stood is told by the devices that stood then
1827
+ if (lists && told && keysIn(lists.removed).some((key) => !has(keysIn(told.removed), key))) {
1828
+ for (const { id } of (await this.store.get('handles', { state: 'in' })).data) {
1829
+ if (!held.has(id)) rooms.push({ id, used: 0 })
1830
+ }
1831
+ }
1832
+ rooms.sort((a, b) => b.used - a.used)
1833
+ let next = 0
1834
+ let covered = true
1835
+ const tell = async () => {
1836
+ while (next < rooms.length && !this.closing) {
1837
+ const { id } = rooms[next++]
1838
+ const done = await this._tellOne(id, stamp, lists?.marked).catch((err) => {
1839
+ if (!this.closing) this._onerror(err)
1840
+ return false
1841
+ })
1842
+ if (!done) covered = false
1843
+ }
1844
+ }
1845
+ await Promise.all(Array.from({ length: TELLING }, tell))
1846
+ if (!covered || this.closing) return
1847
+ const { removed, standing } = lists ?? told ?? {}
1848
+ await this.local.store.set('told', { removed, standing, stamp: seen })
1849
+ }
1850
+
1851
+ // a room told what the root holds, or found below the version that brings revoke by this build
1852
+ /** @private */
1853
+ async _marked(row, lists) {
1854
+ if (sameBytes(row.told, lists.marked)) return true
1855
+ if (!row.told) return false
1856
+ const { data: handle } = await this.store.get('handles', row.id)
1857
+ const spec = handle && this.spec.handles?.[handle.type]
1858
+ return Boolean(spec) && sameBytes(row.told, below(lists.marked, spec.meta))
1859
+ }
1860
+
1861
+ // the root's device lists, 32-byte keys back to back, when there is a removal to tell and this
1862
+ // device stands to tell it
1863
+ /** @private */
1864
+ async _lists() {
1865
+ const removed = await this.store.removals()
1866
+ if (removed.length === 0) return null
1867
+ const { data: devices } = await this.store.get('devices')
1868
+ const standing = devices.filter((row) => row.key).map((row) => row.key)
1869
+ if (!has(standing, this.identity.device.publicKey)) return null
1870
+ const marked = digest(removed, standing)
1871
+ return { removed: b4a.concat(removed), standing: b4a.concat(standing), marked }
1872
+ }
1873
+
1874
+ // what the extensions tell the rooms, as one digest: null when they tell nothing
1875
+ /** @private */
1876
+ async _stamp() {
1877
+ const stamps = await Promise.all(this._tellers.map(({ stamp }) => stamp()))
1878
+ if (stamps.every((s) => s === null)) return null
1879
+ return hash(b4a.from(JSON.stringify(stamps)))
1880
+ }
1881
+
1882
+ // a closed room opened only to be told: nothing handed to the app. One open here runs the same
1883
+ // compare, behind its own. One no peer serves yet is untold for now and holds no other room:
1884
+ // it waits closed for its turn, a few at a time, and reports its wait once per removal
1885
+ /** @private */
1886
+ async _tellOne(id, stamp, marked, turn = false) {
1887
+ const open = [...this.children].find((c) => c.id === id)
1888
+ if (open) return this._prune(open, stamp)
1889
+ const loading = this._loading.get(id)
1890
+ if (loading) {
1891
+ const child = await loading.catch(() => null)
1892
+ return child ? this._prune(child, stamp) : false
1893
+ }
1894
+ if (this._tellings.has(id)) return false
1895
+ if (!turn && this._waiting.has(id)) {
1896
+ this._waiting.set(id, { stamp, marked })
1897
+ return false
1898
+ }
1899
+ const telling = this._tellRoom(id, stamp, marked, turn)
1900
+ const done = () => this._tellings.delete(id)
1901
+ this._tellings.set(id, telling.then(done, done))
1902
+ // set aside once it is closed, so its turn opens it again
1903
+ const told = await telling
1904
+ if (told !== null) return told
1905
+ this._wait(id, stamp, marked)
1906
+ return false
1907
+ }
1908
+
1909
+ /** @private */
1910
+ _wait(id, stamp, marked) {
1911
+ this._waiting.set(id, { stamp, marked })
1912
+ if (this._waiters >= TELLING) return
1913
+ this._waiters++
1914
+ this._turns()
1915
+ }
1916
+
1917
+ /** @private */
1918
+ async _turns() {
1919
+ try {
1920
+ while (this._waiting.size && !this.closing) {
1921
+ const [[id, { stamp, marked }]] = this._waiting
1922
+ this._waiting.delete(id)
1923
+ await this._tellOne(id, stamp, marked, true).catch((err) => {
1924
+ if (!this.closing) this._onerror(err)
1925
+ })
1926
+ }
1927
+ } finally {
1928
+ this._waiters--
1929
+ }
1930
+ }
1931
+
1932
+ // null when no peer serves it yet, or holds what it was told: set aside for a turn
1933
+ /** @private */
1934
+ async _tellRoom(id, stamp, marked, turn) {
1935
+ const { data: row } = await this.store.get('handles', id)
1936
+ // a room left on another device has no row; one still being joined is told by its own open
1937
+ if (!row?.encryptionKey) return true
1938
+ const { type, key, encryptionKey, epochs } = row
1939
+ const kept = await this._loadKeyPair(id)
1940
+ const keyPair = kept || Identity.randomKeyPair()
1941
+ // stored before its claim is on the log: a retry claims with it, never with another
1942
+ if (!kept) {
1943
+ const { publicKey, secretKey } = keyPair
1944
+ await this.local.store.put('handle-keypairs', { id, publicKey, secretKey })
1945
+ }
1946
+ const child = this._room({
1947
+ spec: pickHandle(this.spec, type),
1948
+ namespace: `${NS}/handle/${type}/${id}`,
1949
+ key,
1950
+ encryptionKey,
1951
+ epochs: epochs ? c.decode(epochEntries, epochs) : undefined,
1952
+ keyPair: /** @type {KeyPair} */ (keyPair)
1953
+ })
1954
+ try {
1955
+ await child.ready()
1956
+ if (!child.store.writable && child.store.length === 0) {
1957
+ if (!turn && !(await served(child.store, SERVED))) return null
1958
+ try {
1959
+ await child.store.claim({ timeout: TIMEOUT })
1960
+ } catch (err) {
1961
+ if (this.closing || child.closing || child.closed) return false
1962
+ if (err.code === 'TIMEOUT') {
1963
+ const { data } = await this.local.store.get('handle-keypairs', id)
1964
+ if (!marked || sameBytes(data?.waited, marked)) return false
1965
+ await this._mark(id, { waited: marked })
1966
+ }
1967
+ this._onerror(err)
1968
+ return false
1969
+ }
1970
+ }
1971
+ const told = await this._prune(child, stamp, turn ? TIMEOUT : SERVED)
1972
+ // told after its pass ended: the next one records the rooms covered
1973
+ if (told && turn) this._tellClosed()
1974
+ // one no peer held on its turn waits for the next pass, not another turn
1975
+ return turn ? Boolean(told) : told
1976
+ } finally {
1977
+ await child._end().catch(safetyCatch)
1978
+ }
1979
+ }
1980
+
1129
1981
  // a handle's epochs ride in its root row, which only the identity's devices read: one that
1130
- // opens the handle later reads history with them, since envelopes in the log address a device
1982
+ // opens the handle later reads history with them, since envelopes in the log address a device.
1983
+ // Written once the root holds no device it removed, which would read them there
1131
1984
  /** @private */
1132
1985
  _carry(child) {
1133
1986
  const save = async () => {
1134
1987
  const epochs = c.encode(epochEntries, child.store.keyring.all())
1135
1988
  const { data: row } = await this.store.get('handles', child.id)
1136
1989
  if (!row || b4a.equals(row.epochs || b4a.alloc(0), epochs)) return
1990
+ if (!(await this.store.rotated())) return
1137
1991
  await this.store.set('handles', { id: row.id, epochs })
1138
1992
  }
1139
1993
  // read when the row changes, and when an announcement applies: it is learned only after that
@@ -1148,11 +2002,15 @@ export class Handle extends ReadyResource {
1148
2002
  child.store.on('epoch', onepoch)
1149
2003
  child.store.on('update', onchild)
1150
2004
  this.store.on('update', onroot)
2005
+ this.store.on('epoch', onepoch)
1151
2006
  child.once('close', () => {
1152
2007
  child.store.off('epoch', onepoch)
1153
2008
  child.store.off('update', onchild)
1154
2009
  this.store.off('update', onroot)
2010
+ this.store.off('epoch', onepoch)
1155
2011
  })
2012
+ // one that rotated before it is carried, as a room made while the root owes a rotation
2013
+ if (child.store.keyring.seq > 0) read().then(save).catch(this._onerror)
1156
2014
  }
1157
2015
 
1158
2016
  // before(me.room.notes, fn): on every handle open now and every one opened later
@@ -1167,7 +2025,7 @@ export class Handle extends ReadyResource {
1167
2025
  }
1168
2026
  }
1169
2027
  this._typeHooks.add(hook)
1170
- for (const child of this.children) hook.apply(child)
2028
+ for (const child of [...this.children, ...this._pending]) hook.apply(child)
1171
2029
  const off = () => {
1172
2030
  this._typeHooks.delete(hook)
1173
2031
  for (const o of offs.values()) o()
@@ -1200,8 +2058,10 @@ export class Handle extends ReadyResource {
1200
2058
  /** @private */
1201
2059
  async _reserve() {
1202
2060
  for (const { id, type } of (await this.local.store.get('serving')).data) {
1203
- this._load(type, id).catch((err) => {
2061
+ this._load(type, id).then(reserved, (err) => {
1204
2062
  if (err.code === 'UNKNOWN') return this.local.store.del('serving', id).catch(safetyCatch)
2063
+ // a close cut it short: the room is served again at the next launch
2064
+ if (err.code === 'CLOSED') return
1205
2065
  this._onerror(err)
1206
2066
  })
1207
2067
  }
@@ -1213,12 +2073,17 @@ export class Handle extends ReadyResource {
1213
2073
  * @returns {Promise<void>}
1214
2074
  * @private
1215
2075
  */
1216
- async _saveKeyPair(id, keyPair) {
2076
+ async _saveKeyPair(id, keyPair, invite) {
1217
2077
  if (!keyPair) return
2078
+ // a reopen stamps the row: what a join keeps on it stays
2079
+ const { data: was } = await this.local.store.get('handle-keypairs', id)
1218
2080
  await this.local.store.put('handle-keypairs', {
2081
+ ...was,
1219
2082
  id,
1220
2083
  publicKey: keyPair.publicKey,
1221
- secretKey: keyPair.secretKey
2084
+ secretKey: keyPair.secretKey,
2085
+ ...(invite !== undefined && { invite }),
2086
+ used: Date.now()
1222
2087
  })
1223
2088
  }
1224
2089
 
@@ -1237,11 +2102,149 @@ export class Handle extends ReadyResource {
1237
2102
  }
1238
2103
  }
1239
2104
 
2105
+ // the states a row ends in, read through their index at launch, and how long one stays
2106
+ const SWEPT = ['cancelled', 'denied', 'expired', 'removed', 'left']
2107
+ const KEPT = 30 * 24 * 60 * 60 * 1000
2108
+
2109
+ // how a join ends, as its row says it and as `open` throws it
2110
+ const OVER = { DENIED: 'denied', EXPIRED: 'expired', CANCELLED: 'cancelled' }
2111
+ const ENDS = {
2112
+ denied: (reason) => CeroError.DENIED(reason || null),
2113
+ expired: () => CeroError.EXPIRED(),
2114
+ cancelled: () => CeroError.CANCELLED(),
2115
+ // the invite it was let in with is one minted before its removal
2116
+ removed: () => CeroError.DENIED('removed')
2117
+ }
2118
+
2119
+ // a push is heard only for a handle this identity is in or joining, with its keys
2120
+ const TOPICAL = new Set(['in', 'joining'])
2121
+
2122
+ function topical(row) {
2123
+ return !!row?.encryptionKey && TOPICAL.has(row.state || 'in')
2124
+ }
2125
+
2126
+ // the keys a pairing reply delivered, as a join's row keeps them
2127
+ const keys = ({ encryptionKey, epochs }) => ({
2128
+ encryptionKey,
2129
+ epochs: c.encode(epochEntries, epochs)
2130
+ })
2131
+
2132
+ /**
2133
+ * Wait for a join as one of its waiters, but stop waiting after `ms`; the join itself goes on.
2134
+ *
2135
+ * @param {{ waiting: number } | null} join The join carried here, which reports its errors to the app with none waiting.
2136
+ * @param {Promise<void>} landed
2137
+ * @param {number} ms `0` waits as long as the join takes.
2138
+ * @returns {Promise<void>}
2139
+ */
2140
+ async function wait(join, landed, ms) {
2141
+ if (join) join.waiting++
2142
+ let timer = null
2143
+ const timeout = new Promise((resolve, reject) => {
2144
+ if (!ms) return
2145
+ timer = setTimeout(() => reject(CeroError.TIMEOUT('join')), ms)
2146
+ })
2147
+ try {
2148
+ return await Promise.race([landed, timeout])
2149
+ } finally {
2150
+ clearTimeout(timer)
2151
+ if (join) join.waiting--
2152
+ }
2153
+ }
2154
+
1240
2155
  // the keys a pairing reply delivered, as a handle opens with them
1241
2156
  function delivered({ key, encryptionKey, epochs, writer }) {
1242
2157
  return { key, encryptionKey, epochs, keyPair: writer }
1243
2158
  }
1244
2159
 
2160
+ // the hold a boot took on a handle to serve its invites goes back once it serves none
2161
+ function reserved(child) {
2162
+ const release = (serving) => {
2163
+ if (serving) return
2164
+ child._pair.off('serving', release)
2165
+ child.close().catch(child._onerror)
2166
+ }
2167
+ child._pair.on('serving', release)
2168
+ release(child._pair.serving)
2169
+ }
2170
+
2171
+ // the entry type of a row whose type no header carries: no file server url builds it
2172
+ const UNSERVED = '\n'
2173
+
2174
+ // what a room is told of an identity's device keys, as one value to hold it against
2175
+ function digest(removed, standing) {
2176
+ return hash([hash(b4a.concat(removed)), hash(b4a.concat(standing))])
2177
+ }
2178
+
2179
+ // the mark of a room below the version that brings revoke, for the build that found it there
2180
+ function below(marked, meta = {}) {
2181
+ return hash([marked, b4a.from(JSON.stringify([meta.version, meta.since?.routes]))])
2182
+ }
2183
+
2184
+ function built(spec) {
2185
+ const handles = Object.values(spec.handles ?? {})
2186
+ return hash(b4a.from(JSON.stringify(handles.map(({ meta = {} }) => [meta.version, meta.since]))))
2187
+ }
2188
+
2189
+ // the closed rooms a pass tells at once, and those that wait for a peer at once; the keypairs it
2190
+ // reads at a time; how long a pass waits for a peer to serve a room, or to hold what it wrote
2191
+ // there, before it sets it aside
2192
+ const TELLING = 4
2193
+ const PAGE = 1000
2194
+ const SERVED = 2000
2195
+
2196
+ // whether a peer serves a room within `timeout`: its members reach the view
2197
+ function served(store, timeout) {
2198
+ return new Promise((resolve) => {
2199
+ const done = (found) => {
2200
+ clearTimeout(timer)
2201
+ store.off('update', check)
2202
+ store.off('close', done)
2203
+ resolve(!!found)
2204
+ }
2205
+ const check = () =>
2206
+ store.get('members', { limit: 1 }).then(
2207
+ (res) => res.data.length > 0 && done(true),
2208
+ () => done(false)
2209
+ )
2210
+ const timer = setTimeout(done, timeout)
2211
+ store.on('update', check)
2212
+ store.once('close', done)
2213
+ check()
2214
+ })
2215
+ }
2216
+
2217
+ // whether a peer holds every block this device wrote to a room within `timeout`, or with `removed`
2218
+ // a device there that is neither this one nor a removed one applied them: one where only the
2219
+ // identity's own devices write has no other member to hear it
2220
+ async function reached(store, id, removed, timeout) {
2221
+ const { data: devices } = await store.get('devices')
2222
+ // an empty view has not shown yet who else writes there
2223
+ if (devices.length > 0 && devices.every((row) => row.memberId === id)) return true
2224
+ if (removed) return store.heard(removed, timeout).catch(() => false)
2225
+ let timer = null
2226
+ const late = new Promise((resolve) => (timer = setTimeout(resolve, timeout, false)))
2227
+ try {
2228
+ return await Promise.race([store.held().then(() => true), late])
2229
+ } catch {
2230
+ return false
2231
+ } finally {
2232
+ clearTimeout(timer)
2233
+ }
2234
+ }
2235
+
2236
+ // a file as its url names it to the file server
2237
+ function fileEntry(coreKey, { blockOffset, blockLength, byteOffset, byteLength }, type) {
2238
+ return [b4a.toHex(coreKey), blockOffset, blockLength, byteOffset, byteLength, type].join('/')
2239
+ }
2240
+
2241
+ // a local list read as a collection reads: one row by id, or the rows a query keeps
2242
+ function listed(rows, query = {}) {
2243
+ if (typeof query === 'string') return { data: rows.find((row) => row.id === query) ?? null }
2244
+ const data = filter(rows, query)
2245
+ return { data, total: data.length, size: data.length }
2246
+ }
2247
+
1245
2248
  function admitted(db, id) {
1246
2249
  return new Promise((resolve, reject) => {
1247
2250
  const done = (err, member) => {
@@ -1272,6 +2275,12 @@ function randomNs() {
1272
2275
  return z32.encode(Identity.randomBytes(8))
1273
2276
  }
1274
2277
 
2278
+ // the push topic of a handles row, which keys its topics row
2279
+ const topicOf = ({ key }) => b4a.toHex(discoveryKey(key))
2280
+
2281
+ // what me.topics shows of a topics row: none of the keys it keeps
2282
+ const listing = ({ id, handle, type, name }) => ({ id, handle, type, name })
2283
+
1275
2284
  // a topics row still describes its handle
1276
2285
  function same(row, next) {
1277
2286
  return (
@@ -1281,10 +2290,34 @@ function same(row, next) {
1281
2290
  (row.name ?? null) === next.name &&
1282
2291
  b4a.equals(row.key, next.key) &&
1283
2292
  sameBytes(row.encryptionKey, next.encryptionKey) &&
1284
- sameBytes(row.epochs, next.epochs)
2293
+ sameBytes(row.epochs, next.epochs) &&
2294
+ sameBytes(row.writers, next.writers)
1285
2295
  )
1286
2296
  }
1287
2297
 
2298
+ // the keys that may write to a handle now: the devices of its members whose role writes
2299
+ async function writersOf(db) {
2300
+ const [devices, members] = await Promise.all([db.get('devices'), db.get('members')])
2301
+ const writes = new Set(members.data.filter((m) => can(m.role, WRITE)).map((m) => m.id))
2302
+ return b4a.concat(devices.data.filter((d) => writes.has(d.memberId)).map((d) => hid.decode(d.id)))
2303
+ }
2304
+
2305
+ // a handle whose writers do not read accepts nobody
2306
+ function unread(err) {
2307
+ safetyCatch(err)
2308
+ return null
2309
+ }
2310
+
2311
+ function has(keys, key) {
2312
+ return keys.some((k) => b4a.equals(k, key))
2313
+ }
2314
+
2315
+ function keysIn(bytes) {
2316
+ const keys = []
2317
+ for (let i = 0; i < (bytes?.byteLength || 0); i += 32) keys.push(bytes.subarray(i, i + 32))
2318
+ return keys
2319
+ }
2320
+
1288
2321
  function sameBytes(a, b) {
1289
2322
  return a && b ? b4a.equals(a, b) : (a ?? null) === (b ?? null)
1290
2323
  }