@cero-base/cero 2.12.0 → 3.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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) {
@@ -430,45 +498,113 @@ export class Handle extends ReadyResource {
430
498
  /** @private */
431
499
  async _leave() {
432
500
  if (!this.parent) throw CeroError.INVALID('the root cannot be left')
433
- await this.store.del('members', this.identity.id)
434
- await this.parent.store.call('del-handle', { id: hid.encode(this.store.key) })
435
- 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 })
436
564
  }
437
565
 
438
566
  /**
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.
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.
441
571
  * @returns {Promise<void>}
442
572
  */
443
- close() {
444
- 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
+ }
445
580
  if (this._refs > 1) {
446
581
  this._refs--
447
- return Promise.resolve()
582
+ return
448
583
  }
449
- if (this._idle) return Promise.resolve()
450
- const linger = this.root._opts.linger ?? LINGER
451
- 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()
452
588
  this._refs = 0
453
- this._idle = setTimeout(() => this._end().catch(this._onerror), linger)
454
- this._idle.unref?.()
455
- 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)
456
594
  }
457
595
 
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 */
596
+ /** @private one more holder: an idle handle is kept */
463
597
  _hold() {
464
- clearTimeout(this._idle)
465
- this._idle = null
598
+ this.root._idle.delete(this)
466
599
  this._refs++
467
600
  }
468
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
+ */
469
606
  _end() {
470
- clearTimeout(this._idle)
471
- this._idle = null
607
+ this.root._idle.delete(this)
472
608
  this._refs = 0
473
609
  return super.close()
474
610
  }
@@ -512,7 +648,9 @@ export class Handle extends ReadyResource {
512
648
  epoch: (current && seqs.get(current)) || 0,
513
649
  suspended: this.root._sus.suspended,
514
650
  behind: this.store.behind || 0,
515
- 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()
516
654
  }
517
655
  if (this.parent) data.topic = b4a.toHex(this.store.discoveryKey)
518
656
  return { data }
@@ -527,7 +665,7 @@ export class Handle extends ReadyResource {
527
665
  [this.store, 'unwritable'],
528
666
  [this.store, 'behind']
529
667
  ]
530
- if (this.parent) sources.push([this.root, 'status'])
668
+ if (this.parent) sources.push([this.root, 'status'], [this.root.store, 'behind'])
531
669
  for (const [emitter, event] of sources) emitter.on(event, fn)
532
670
  const off = this._onRadio(fn)
533
671
  return () => {
@@ -579,63 +717,135 @@ export class Handle extends ReadyResource {
579
717
  return () => bt.off('update', fn)
580
718
  }
581
719
 
582
- // the joins this device waits on, without the keys the local store keeps for them
583
720
  /** @private */
584
- async _joins(query = {}) {
585
- const rows = (await this.local.store.get('joins')).data
586
- const data = filter(
587
- rows.map(({ id, type, invite }) => ({ id, type, invite })),
588
- query
589
- )
590
- return { data, total: data.length, size: data.length }
721
+ _onTopics(fn) {
722
+ this.on('topics', fn)
723
+ return () => this.off('topics', fn)
591
724
  }
592
725
 
593
726
  /** @private */
594
- _onLocal(fn) {
595
- this.local.store.db.watch(fn)
596
- 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)
597
734
  }
598
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
599
738
  /** @private */
600
- async _topics(query = {}) {
601
- const rows = (await this.local.store.get('topics')).data
602
- const data = filter(
603
- rows.map(({ id, handle, type, name }) => ({ id, handle, type, name })),
604
- query
605
- )
606
- 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
607
759
  }
608
760
 
609
- // 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
610
763
  /** @private */
611
- _index() {
612
- 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)
613
767
  return this._indexing
614
768
  }
615
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
616
773
  /** @private */
617
- async _reindex() {
618
- if (this.closing || this.closed) return
619
- const { data: handles } = await this.store.get('handles')
620
- const { data: rows } = await this.local.store.get('topics')
621
- const wanted = new Map(handles.map((h) => [b4a.toHex(discoveryKey(h.key)), h]))
622
- const have = new Map(rows.map((row) => [row.id, row]))
623
- for (const row of rows) {
624
- 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
+ }
625
785
  }
626
- for (const [id, h] of wanted) {
627
- const row = {
628
- id,
629
- handle: h.id,
630
- type: h.type,
631
- key: h.key,
632
- name: h.name ?? null,
633
- encryptionKey: h.encryptionKey ?? null,
634
- 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
635
790
  }
636
- if (same(have.get(id), row)) continue
637
- 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)
638
847
  }
848
+ if (!same(have, row)) await this._put(row)
639
849
  }
640
850
 
641
851
  // a push about one of this device's handles, verified against its own cores
@@ -643,8 +853,7 @@ export class Handle extends ReadyResource {
643
853
  async _receive(payload) {
644
854
  // a suspended storage answers no read: the cold entry serves a push while the app sleeps
645
855
  if (this._sus.suspended) throw CeroError.INVALID('receive: the app is suspended')
646
- const { data: rows } = await this.local.store.get('topics')
647
- return read(this.store.store.storage, this.spec, payload, rows)
856
+ return read(this.store.store.storage, this.spec, payload, this.local.store)
648
857
  }
649
858
 
650
859
  /** @private */
@@ -664,7 +873,8 @@ export class Handle extends ReadyResource {
664
873
  const to = Mailbox.getAddress(secret)
665
874
  const onmessage = async (bytes) => {
666
875
  const mail = unseal(to, bytes)
667
- 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 })
668
878
  }
669
879
  const inbox = this.root.mailbox.receive(secret, onmessage, { keep })
670
880
  return () => inbox.close()
@@ -677,8 +887,11 @@ export class Handle extends ReadyResource {
677
887
  * @private
678
888
  */
679
889
  _resolveCore(coreKey, info) {
680
- const hex = b4a.toHex(coreKey)
681
- 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))
682
895
  if (encryptionKey !== undefined) return { key: coreKey, encryptionKey }
683
896
  return null
684
897
  }
@@ -720,9 +933,12 @@ export class Handle extends ReadyResource {
720
933
  _registerBlobCore(id, stamp) {
721
934
  if (!id || !this.root?._coreKeys) return
722
935
  try {
723
- const { coreKey } = decodeId(id)
724
- const hex = b4a.toHex(coreKey)
725
- 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)) {
726
942
  // no stamp on a file-field value, look it up (fire-and-forget, idempotent)
727
943
  if (stamp === undefined) {
728
944
  this.store
@@ -735,10 +951,10 @@ export class Handle extends ReadyResource {
735
951
  }
736
952
  const key = this._blobCoreKey(stamp)
737
953
  if (!key) return // unknown epoch — this device is not entitled to the core
738
- this.root._coreKeys.set(hex, key)
954
+ this.root._coreKeys.set(entry, key)
739
955
  }
740
956
  // remember which handle read it, so close prunes the entry
741
- if (this !== this.root) (this._blobKeys ??= new Set()).add(hex)
957
+ if (this !== this.root) (this._blobKeys ??= new Set()).add(entry)
742
958
  } catch {
743
959
  // ignore invalid ids
744
960
  }
@@ -814,8 +1030,15 @@ export class Handle extends ReadyResource {
814
1030
 
815
1031
  const ts = Date.now()
816
1032
  const writerKey = child.store.writerKey
817
- // 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
818
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 })
819
1042
  await tx.call('add-writer', {
820
1043
  master: this.identity.publicKey,
821
1044
  writer: writerKey,
@@ -830,7 +1053,14 @@ export class Handle extends ReadyResource {
830
1053
  createdAt: ts,
831
1054
  updatedAt: ts
832
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
+ }
833
1060
  })
1061
+ if (owed) {
1062
+ await child.store.call('revoke', { removed: lists.removed, standing: lists.standing })
1063
+ }
834
1064
  await this.store.call('add-handle', {
835
1065
  id,
836
1066
  type,
@@ -867,61 +1097,329 @@ export class Handle extends ReadyResource {
867
1097
  * @private
868
1098
  */
869
1099
  async _join(invite, type, { timeout = TIMEOUT } = {}) {
870
- const known = await this._joined(type, Invite.parse(invite).discoveryKey)
1100
+ const { key } = Invite.parse(invite)
1101
+ const known = await this._joined(type, key)
871
1102
  if (known) return known
872
1103
 
873
- const join = this._start(invite, type)
874
- join.waiting++
875
- try {
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
881
- } finally {
882
- 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
883
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
+ })
1170
+ }
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)
884
1178
  }
885
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
886
1181
  /** @private */
887
1182
  _start(invite, type) {
888
- const target = Invite.parse(invite).discoveryKey
889
- const key = `${type}/${b4a.toHex(target)}`
890
- let join = this._joining.get(key)
1183
+ const id = hid.encode(Invite.parse(invite).key)
1184
+ let join = this._joining.get(id)
891
1185
  if (!join) {
892
- join = new Join(this, {
893
- type,
894
- spec: pickHandle(this.spec, type),
895
- discoveryKey: target,
896
- 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
897
1190
  })
898
- this._joining.set(key, join)
1191
+ join.done.catch(safetyCatch)
1192
+ this._joining.set(id, join)
899
1193
  }
900
- if (join.invite !== invite) join.start(invite)
1194
+ // a join past its reply enters with those keys: a newer invite waits on it
1195
+ if (join.invite !== invite && !join.entering) this._run(join, invite)
901
1196
  return join
902
1197
  }
903
1198
 
1199
+ // a newer invite takes over from an older attempt: the writer stays, so a reply to the older one still lands
1200
+ /** @private */
1201
+ async _run(join, invite) {
1202
+ join.invite = invite
1203
+ join.writer = null
1204
+ join.running?.abort()
1205
+ const running = (join.running = new AbortController())
1206
+ const settle = (end, value) => {
1207
+ this._joining.delete(join.id)
1208
+ end(value)
1209
+ }
1210
+ try {
1211
+ const id = await this._ask(join.type, invite)
1212
+ const writer = (join.writer = await this._loadKeyPair(id))
1213
+ const { data: row } = await this.store.get('handles', id)
1214
+ // the keys are on the row before the reply is let go: a restart opens the handle without joining again
1215
+ const keep = async (answer) => {
1216
+ if (!(answer instanceof Error)) await this._stand(id, 'joining', keys(answer))
1217
+ }
1218
+ const spec = pickHandle(this.spec, join.type)
1219
+ const { identity, mailbox } = this
1220
+ const opts = { identity, spec, writer, keep, timeout: 0, signal: running.signal }
1221
+ const reply = row.encryptionKey
1222
+ ? { ...row, epochs: row.epochs ? c.decode(epochEntries, row.epochs) : [], writer }
1223
+ : await Pairing.join(mailbox, invite, opts)
1224
+ // an abort stops no reply already in hand: the newer attempt enters
1225
+ if (running !== join.running) return
1226
+ join.entering = true
1227
+ await this._stand(id, 'joining', keys(reply))
1228
+ const child = await this._enter(join.type, reply, invite)
1229
+ // every waiter takes its own hold once the row reads in: this one is let go, idle until the app opens it
1230
+ child.close().catch(this._onerror)
1231
+ settle(join.resolve, child)
1232
+ } catch (err) {
1233
+ if (running !== join.running) return
1234
+ const end = join.end || err
1235
+ // counted before its row says how it ended: a waiter hears that row
1236
+ const alone = !join.waiting
1237
+ // a close pauses the join, anything else ends it, and its row says how
1238
+ const report = (err) => this.closing || this._onerror(err)
1239
+ if (end.code !== 'CLOSED') {
1240
+ await this._over(join.id, end, { invite, writer: join.writer }).catch(report)
1241
+ }
1242
+ if (err.code !== 'CLOSED' && alone) this._onerror(err)
1243
+ settle(join.reject, end)
1244
+ }
1245
+ }
1246
+
1247
+ // ends it for good from any device: its row reads cancelled, so no device and no restart carries it on
904
1248
  /** @private */
905
1249
  async _cancel(invite) {
906
- const id = b4a.toHex(Invite.parse(invite).discoveryKey)
907
- const join = [...this.root._joining.values()].find((join) => join.id === id)
908
- await join?.cancel()
909
- return !!join
1250
+ const root = this.root
1251
+ const id = hid.encode(Invite.parse(invite).key)
1252
+ if (!(await root._over(id, CeroError.CANCELLED()))) return false
1253
+ const join = root._joining.get(id)
1254
+ if (join) {
1255
+ root._stop(join, CeroError.CANCELLED())
1256
+ await join.done.catch(safetyCatch)
1257
+ }
1258
+ return true
1259
+ }
1260
+
1261
+ // the latest ask stands: a request of this device's writer its row no longer carries, cancelled,
1262
+ // deleted or asked again under another invite on any device, is taken back. One whose row ended
1263
+ // otherwise is let go
1264
+ /** @private */
1265
+ async _check(ask) {
1266
+ const { data: row } = await this.store.get('handles', ask.handle)
1267
+ const { data: kept } = await this.local.store.get('handle-keypairs', ask.handle)
1268
+ const state = row && (row.state || 'in')
1269
+ const mine = !!kept && b4a.equals(kept.publicKey, ask.publicKey)
1270
+ const asks = state === 'asking' || state === 'joining'
1271
+ if (mine && asks && row.writer === ask.id) return
1272
+ // a seated row names no writer
1273
+ const ended = row && !asks && state !== 'cancelled' && (!row.writer || row.writer === ask.id)
1274
+ if (ended && row.invite === ask.invite) return this.local.store.del('asks', ask.id)
1275
+ // only the join that asks with this writer stops: one still choosing its writer may ask anew
1276
+ const join = this._joining.get(ask.handle)
1277
+ if (join?.writer && b4a.equals(join.writer.publicKey, ask.publicKey)) {
1278
+ this._stop(join, CeroError.CANCELLED())
1279
+ }
1280
+ if (this._taking.has(ask.id)) return
1281
+ this._taking.add(ask.id)
1282
+ this._takeBack(ask)
1283
+ .catch((err) => this.closing || this._onerror(err))
1284
+ .finally(() => this._taking.delete(ask.id))
1285
+ }
1286
+
1287
+ // announced until a peer or a mirror holds it, `KEPT` at most; its writer goes with it, unless its
1288
+ // cancelled row tells a launch this device asked
1289
+ /** @private */
1290
+ async _takeBack(ask) {
1291
+ if (ask.createdAt >= Date.now() - KEPT) await this._announce(ask.type, ask)
1292
+ await this.local.store.del('asks', ask.id)
1293
+ const { data: row } = await this.store.get('handles', ask.handle)
1294
+ if (row?.state !== 'cancelled' || row.writer !== ask.id) await this._forget(ask.handle, ask)
1295
+ }
1296
+
1297
+ // a launch of the device that asked announces the cancel again, and once a peer or a mirror holds
1298
+ // it, the writer and the cancelled row go
1299
+ /** @private */
1300
+ async _retract({ id, type }) {
1301
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1302
+ if (!kept?.invite) return
1303
+ this._announce(type, kept)
1304
+ .then(() => this._forget(id, kept))
1305
+ .catch((err) => this.closing || this._onerror(err))
1306
+ }
1307
+
1308
+ /** @private */
1309
+ _announce(type, { invite, publicKey, secretKey }) {
1310
+ const spec = pickHandle(this.spec, type)
1311
+ return Pairing.cancel(this.mailbox, invite, { spec, writer: { publicKey, secretKey } })
1312
+ }
1313
+
1314
+ // a held cancel takes its writer, and the row it ended, unless a join since took them over
1315
+ /** @private */
1316
+ async _forget(id, { publicKey, invite }) {
1317
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1318
+ if (kept?.invite !== invite || !b4a.equals(kept.publicKey, publicKey)) return
1319
+ await this.local.store.del('handle-keypairs', id)
1320
+ const { data: row } = await this.store.get('handles', id)
1321
+ if (row?.state === 'cancelled' && row.writer === hid.encode(publicKey)) {
1322
+ await this.store.del('handles', id)
1323
+ }
1324
+ }
1325
+
1326
+ /** @private */
1327
+ _stop(join, end) {
1328
+ join.end = end
1329
+ join.running?.abort()
1330
+ }
1331
+
1332
+ // a join's row: `asking` with its invite and no keys. A join that ended under this invite ends the same way again
1333
+ /** @private */
1334
+ async _ask(type, invite) {
1335
+ const { key } = Invite.parse(invite)
1336
+ const id = hid.encode(key)
1337
+ const { data: row } = await this.store.get('handles', id)
1338
+ const state = row && (row.state || 'in')
1339
+ // the writer this device asks with: fixed before the join is written, so a resumed one hears the reply to it
1340
+ const { data: kept } = await this.local.store.get('handle-keypairs', id)
1341
+ // an ask another device made since is the one that stands: this device asks anew in its place
1342
+ const latest =
1343
+ state === 'asking' &&
1344
+ !!kept &&
1345
+ (row.writer ? row.writer === hid.encode(kept.publicKey) : kept.invite === row.invite)
1346
+ const mine = !!kept?.invite && (state === 'joining' || latest)
1347
+ if (mine && (state === 'joining' || row.invite === invite)) return id
1348
+ if (ENDS[state] && row.invite === invite) throw ENDS[state](row.reason)
1349
+ const writer = mine ? kept : Identity.randomKeyPair()
1350
+ await this._saveKeyPair(id, writer, invite)
1351
+ // a room another device of this identity already has the keys of is joined with them
1352
+ if (state === 'joining') return id
1353
+ // a room she left is asked again under any invite, the one she came in with too
1354
+ if (state === 'left' && row.invite === invite) await this.store.call('del-handle', { id })
1355
+ const ts = Date.now()
1356
+ const { publicKey, secretKey } = writer
1357
+ await this.store.call('add-handle', {
1358
+ id,
1359
+ type,
1360
+ key,
1361
+ name: null,
1362
+ createdAt: ts,
1363
+ updatedAt: ts,
1364
+ state: 'asking',
1365
+ invite,
1366
+ writer: hid.encode(publicKey)
1367
+ })
1368
+ const ask = { id: hid.encode(publicKey), handle: id, type, invite, publicKey, secretKey }
1369
+ await this.local.store.put('asks', ask)
1370
+ return id
1371
+ }
1372
+
1373
+ // a join's row moves on once: a step run again finds it there
1374
+ /** @private */
1375
+ async _stand(id, state, fields) {
1376
+ const { data: row } = await this.store.get('handles', id)
1377
+ if (!row || row.state === state) return
1378
+ await this.store.set('handles', { id, state, ...fields })
1379
+ }
1380
+
1381
+ // how a join ended, on its row, which keeps none of the keys it was handed, and whether it did. A
1382
+ // join ends only its own ask, a cancel the one that stands under any invite of the room
1383
+ /** @private */
1384
+ async _over(id, err, join) {
1385
+ const state = OVER[err.code]
1386
+ const { data: row } = await this.store.get('handles', id)
1387
+ // a join ends its own request once it chose its writer, one seated or over stays as it reads
1388
+ const own = !join || (!!join.writer && row?.writer === hid.encode(join.writer.publicKey))
1389
+ const ends =
1390
+ (row?.state === 'asking' && own) || (row?.state === 'joining' && state === 'denied')
1391
+ if (!state || !ends || (join && row.invite !== join.invite)) return false
1392
+ const reason = err.reason ?? null
1393
+ try {
1394
+ await this.store.set('handles', { id, state, reason, encryptionKey: null, epochs: null })
1395
+ } catch (err) {
1396
+ // an answer that landed since the read moved the row on
1397
+ if (err.code === 'REFUSED') return false
1398
+ throw err
1399
+ }
1400
+ return true
910
1401
  }
911
1402
 
912
1403
  // a stored writer still admitted reopens without pairing; a removed writer's core is frozen,
913
1404
  // so that one pairs again with a fresh keypair
914
1405
  /** @private */
915
- async _joined(type, target) {
916
- const { data: joined } = await this.store.get('handles')
917
- const existing = joined.find((h) => h.type === type && b4a.equals(discoveryKey(h.key), target))
1406
+ async _joined(type, key) {
1407
+ const { data: existing } = await this.store.get('handles', hid.encode(key))
918
1408
  if (!existing) return null
1409
+ if (existing.type !== type) {
1410
+ throw CeroError.INVALID(`handle ${existing.id} is type ${existing.type}, not ${type}`)
1411
+ }
1412
+ // a join on its way, or one that is over, is its row's to tell
1413
+ if (!existing.encryptionKey || (existing.state || 'in') !== 'in') return null
919
1414
  const known = await this._load(type, existing.id)
920
1415
  const { data: me } = await known.store.get('members', this.identity.id)
921
1416
  const { data: device } = await known.store.get('devices', hid.encode(known.store.writerKey))
922
1417
  // a reader never had a seat, a removed writer lost it
923
1418
  if (me && (device || me.role === 'reader')) return known
1419
+ // the identity's removal is its row's, every device's; a device that alone lost its seat is refused here
1420
+ if (!me) await this._ousted(known).catch(safetyCatch)
924
1421
  await known._end().catch(safetyCatch)
1422
+ if (me) throw ENDS.removed()
925
1423
  return null
926
1424
  }
927
1425
 
@@ -933,7 +1431,12 @@ export class Handle extends ReadyResource {
933
1431
  * @returns {Promise<Handle>}
934
1432
  * @private
935
1433
  */
936
- async _enter(type, reply) {
1434
+ async _enter(type, reply, invite) {
1435
+ const id = hid.encode(reply.key)
1436
+ // a room this identity lost its seat in stays open on its old writer: it ends before the new seat opens it
1437
+ const stale = [...this.children].find((c) => c.id === id && !c.closing)
1438
+ const out = stale && (await stale.store.removed(this.identity.id))
1439
+ if (out) await stale._end().catch(safetyCatch)
937
1440
  const child = /** @type {Child} */ (
938
1441
  this._room({
939
1442
  spec: pickHandle(this.spec, type),
@@ -941,27 +1444,26 @@ export class Handle extends ReadyResource {
941
1444
  ...delivered(reply)
942
1445
  })
943
1446
  )
1447
+ // its row is listed while it joins: an open by id shares this child, a second on the same core deadlocks
944
1448
  let publish = null
945
1449
  let abort = null
946
- let inflightId = null
1450
+ const inflight = new Promise((resolve, reject) => {
1451
+ publish = resolve
1452
+ abort = reject
1453
+ })
1454
+ inflight.catch(safetyCatch)
1455
+ this._loading?.set(id, inflight)
947
1456
  try {
948
1457
  await child.ready()
1458
+ // let in by a promise, this device seats itself: its claim writes the member row
1459
+ await child.store.claim({ timeout: 0 })
949
1460
  // admitted once our member row lands; the same apply seats a writer, a reader has no seat
950
1461
  const member = await admitted(child.store, this.identity.id)
951
1462
  if (member.role !== 'reader' && !child.store.writable) {
952
1463
  await child.store.whenWritable({ timeout: 0 })
953
1464
  }
954
1465
 
955
- const id = hid.encode(child.store.key)
956
- // same create/open race as _create, a concurrent _load must share this child
957
- const inflight = new Promise((resolve, reject) => {
958
- publish = resolve
959
- abort = reject
960
- })
961
- inflight.catch(safetyCatch)
962
- inflightId = id
963
- this._loading?.set(id, inflight)
964
- await this._saveKeyPair(id, child.store.keyPair)
1466
+ await this._saveKeyPair(id, child.store.keyPair, invite)
965
1467
 
966
1468
  const ts = Date.now()
967
1469
  await this.store.call('add-handle', {
@@ -972,33 +1474,64 @@ export class Handle extends ReadyResource {
972
1474
  epochs: c.encode(epochEntries, child.store.keyring.all()),
973
1475
  name: null,
974
1476
  createdAt: ts,
975
- updatedAt: ts
1477
+ updatedAt: ts,
1478
+ state: 'in',
1479
+ invite
976
1480
  })
977
1481
  this._adopt(child, {})
978
1482
  publish(child)
979
1483
  this._loading?.delete(id)
980
1484
  return child
981
1485
  } catch (err) {
982
- if (abort) abort(err)
983
- if (inflightId) this._loading?.delete(inflightId)
1486
+ abort(err)
1487
+ this._loading?.delete(id)
984
1488
  await child._end().catch(safetyCatch)
985
1489
  throw err
986
1490
  }
987
1491
  }
988
1492
 
989
- // joins not answered at the last close go on, with nobody waiting; the mailbox sends what its
990
- // outbox kept
1493
+ // the rows that ended go, with their keypairs, once the app had `KEPT` to show why; a cancel sooner,
1494
+ // at a launch of the device that asked once a peer holds it: another device may yet owe it
1495
+ /** @private */
1496
+ async _sweep() {
1497
+ const old = Date.now() - KEPT
1498
+ const gone = []
1499
+ for (const state of SWEPT) {
1500
+ for (const row of (await this.store.get('handles', { state })).data) {
1501
+ if (row.updatedAt < old) gone.push(row.id)
1502
+ else if (state === 'cancelled') await this._retract(row)
1503
+ }
1504
+ }
1505
+ if (!gone.length) return
1506
+ await this.store.tx(async (tx) => {
1507
+ for (const id of gone) await tx.del('handles', id)
1508
+ })
1509
+ for (const id of gone) await this.local.store.del('handle-keypairs', id)
1510
+ }
1511
+
1512
+ // the joins on their way go on, with nobody waiting; the mailbox sends what its outbox kept
991
1513
  /** @private */
992
1514
  async _carryOn() {
993
- for (const { id, invite, type } of (await this.local.store.get('joins')).data) {
994
- // the root's own device link row has no handle type: the launch resumes that one
995
- if (!this.spec.handles?.[type]) continue
996
- if (await this._joined(type, Invite.parse(invite).discoveryKey)) {
997
- await this.local.store.del('joins', id)
998
- continue
1515
+ // the rows not settled, through their index: never every handle
1516
+ for (const state of ['asking', 'joining']) {
1517
+ for (const { id, type, invite, writer, encryptionKey } of (
1518
+ await this.store.get('handles', { state })
1519
+ ).data) {
1520
+ // an answer is heard by the device that asked, and the keys on a row seat any device
1521
+ if (encryptionKey || (await this._asked(id, invite, writer))) this._start(invite, type)
1522
+ }
1523
+ }
1524
+ for (const { id, type } of (await this.store.get('handles', { state: 'leaving' })).data) {
1525
+ this._depart(type, id)
1526
+ }
1527
+ // a join another device ended stops here
1528
+ for (const join of [...this._joining.values()]) {
1529
+ const { data: row } = await this.store.get('handles', join.id)
1530
+ if (row?.invite === join.invite && OVER[row.state?.toUpperCase()]) {
1531
+ this._stop(join, ENDS[row.state](row.reason))
999
1532
  }
1000
- this._start(invite, type)
1001
1533
  }
1534
+ for (const ask of (await this.local.store.get('asks')).data) await this._check(ask)
1002
1535
  }
1003
1536
 
1004
1537
  /**
@@ -1040,42 +1573,45 @@ export class Handle extends ReadyResource {
1040
1573
  * @private
1041
1574
  */
1042
1575
  async _reopen(type, id) {
1043
- const { data } = await this.store.get('handles', id)
1044
- if (!data) throw CeroError.UNKNOWN('handle', id)
1045
- if (data.type !== type) {
1046
- throw CeroError.INVALID(`handle ${id} is type ${data.type}, not ${type}`)
1047
- }
1048
- let writer = await this._loadKeyPair(id)
1049
- if (!writer) {
1050
- writer = Identity.randomKeyPair()
1576
+ let child = null
1577
+ try {
1578
+ const { data } = await this.store.get('handles', id)
1579
+ // a join with no keys yet is no room to open
1580
+ if (!data?.encryptionKey) throw CeroError.UNKNOWN('handle', id)
1581
+ if (data.type !== type) {
1582
+ throw CeroError.INVALID(`handle ${id} is type ${data.type}, not ${type}`)
1583
+ }
1584
+ await this._tellings.get(id)
1051
1585
  // stored before its claim is on the log: a retry claims with it, never with another
1586
+ const writer = (await this._loadKeyPair(id)) || Identity.randomKeyPair()
1052
1587
  await this._saveKeyPair(id, writer)
1053
- }
1054
- const child = this._room({
1055
- spec: pickHandle(this.spec, type),
1056
- namespace: `${NS}/handle/${type}/${id}`,
1057
- key: data.key,
1058
- encryptionKey: data.encryptionKey,
1059
- epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
1060
- keyPair: /** @type {KeyPair} */ (writer)
1061
- })
1062
- try {
1588
+ child = this._room({
1589
+ spec: pickHandle(this.spec, type),
1590
+ namespace: `${NS}/handle/${type}/${id}`,
1591
+ key: data.key,
1592
+ encryptionKey: data.encryptionKey,
1593
+ epochs: data.epochs ? c.decode(epochEntries, data.epochs) : undefined,
1594
+ keyPair: /** @type {KeyPair} */ (writer)
1595
+ })
1063
1596
  await child.ready()
1064
1597
  // a writer that never wrote has not claimed yet
1065
1598
  if (!child.store.writable && child.store.length === 0) {
1066
1599
  await child.store.claim({ timeout: TIMEOUT })
1067
1600
  }
1068
1601
  this._adopt(child, {})
1602
+ return child
1069
1603
  } catch (err) {
1070
- await child._end().catch(safetyCatch)
1071
- throw err
1604
+ await child?._end().catch(safetyCatch)
1605
+ // a reopen the root's close broke fails with CLOSED, whichever store went first
1606
+ throw this.closing || this.closed ? CeroError.CLOSED('Handle') : err
1072
1607
  }
1073
- return child
1074
1608
  }
1075
1609
 
1076
1610
  // a handle has its type's hooks before it opens, so no op it applies runs without them
1077
1611
  /** @private */
1078
1612
  _room(opts) {
1613
+ // a closing root has listed the rooms it closes: one opened now would outlive its stores
1614
+ if (this.closing || this.closed) throw CeroError.CLOSED('Handle')
1079
1615
  const child = new Handle({ parent: this, ...opts })
1080
1616
  for (const hook of this._typeHooks) hook.apply(child)
1081
1617
  this._pending.add(child)
@@ -1093,8 +1629,10 @@ export class Handle extends ReadyResource {
1093
1629
 
1094
1630
  /** @private */
1095
1631
  async _wake() {
1096
- if (this.closing || this.closed) return
1632
+ if (this.closed) return
1097
1633
  await this.store.store.resume().catch(this._onerror)
1634
+ // a close takes its storage back and nothing else: the network stays down
1635
+ if (this.closing) return
1098
1636
  await this.network.resume().catch(this._onerror)
1099
1637
  await this._bluetooth?.resume().catch(this._onerror)
1100
1638
  }
@@ -1108,19 +1646,133 @@ export class Handle extends ReadyResource {
1108
1646
  child._refs = 1
1109
1647
  this._serve(child)
1110
1648
  this._carry(child)
1111
- this._prune(child).catch(this._onerror)
1112
- this.emit('handle', child, info)
1649
+ // it tells a handle nothing before it has a seat there
1650
+ const prune = () => this._prune(child).catch(this._onerror)
1651
+ child.store.on('writable', prune)
1652
+ child.once('close', () => child.store.off('writable', prune))
1653
+ prune()
1654
+ this._seats(child)
1655
+ // what a listener ties to the handle as it runs is no holder's: it stays through their last close
1656
+ child._arriving = true
1657
+ try {
1658
+ this.emit('handle', child, info)
1659
+ } finally {
1660
+ child._arriving = false
1661
+ }
1662
+ }
1663
+
1664
+ // a handle's topics row follows who may write to it while it is open, so a push is checked
1665
+ // against the room as this device last applied it
1666
+ /** @private */
1667
+ _seats(child) {
1668
+ const onchange = (touched) => {
1669
+ if (touched.has('*') || touched.has('devices') || touched.has('members')) {
1670
+ this._index(child).catch(this._onerror)
1671
+ this._ousted(child).catch((err) => this.closing || this._onerror(err))
1672
+ }
1673
+ }
1674
+ child.store.on('update', onchange)
1675
+ child.once('close', () => child.store.off('update', onchange))
1676
+ this._index(child).catch(this._onerror)
1113
1677
  }
1114
1678
 
1115
- // a device removed from the root loses its seats in every handle: its chain is static, so the
1116
- // handles are told by whichever device of the identity has them open
1679
+ // a device removed from the root is out of every handle: its chain is static, so a handle is
1680
+ // told the identity's keys the root removed and those it seats, by a device that stands there,
1681
+ // when that is not what it was told. One compare at a time: two would tell it twice. It is
1682
+ // marked told only once a peer holds what was written within `timeout`: null till then
1117
1683
  /** @private */
1118
- async _prune(child) {
1119
- const { data: mine } = await this.store.get('devices')
1120
- const kept = new Set(mine.filter((d) => d.key).map((d) => b4a.toHex(d.key)))
1684
+ _prune(child, stamp, timeout = SERVED) {
1685
+ const run = async () => {
1686
+ try {
1687
+ const told = await this._compare(child, timeout)
1688
+ return told && (stamp === undefined || (await this._teach(child, stamp, timeout)))
1689
+ } catch (err) {
1690
+ // one that closes as it is told is told again, at its next open or pass
1691
+ if (this.closing || child.closing || child.closed) return false
1692
+ throw err
1693
+ }
1694
+ }
1695
+ const pruning = child._pruning ? child._pruning.then(run) : run()
1696
+ child._pruning = pruning.catch(safetyCatch)
1697
+ return pruning
1698
+ }
1699
+
1700
+ // covered once it holds what the root holds, or this device has nothing to tell it by: a reader
1701
+ // tells from her own core, a seatless write, in a room at the version that brings it. One below
1702
+ // it is marked for this build, so a pass opens it again only for a build that may bring it there
1703
+ /** @private */
1704
+ async _compare(child, timeout) {
1705
+ if (child.closing || child.closed) return false
1706
+ const removed = await this.store.removals()
1707
+ if (removed.length === 0) return true
1708
+ const { data: rows } = await this.store.get('devices')
1709
+ const standing = rows.filter((row) => row.key).map((row) => row.key)
1710
+ const { store } = child
1711
+ const at = Math.min(store.version, await store.dispatcher.version(store.view))
1712
+ if ((store.meta.since?.routes[`@${store.ns}/revoke`] ?? 0) > at) {
1713
+ if (store.writable) await this._unseat(child, removed)
1714
+ return this._record(child, { told: below(digest(removed, standing), store.meta) }, timeout)
1715
+ }
1716
+ if (!has(standing, this.identity.device.publicKey)) return false
1717
+ // a root that lags has fewer removed than the handle was told: those add up, and stay
1718
+ const told = await store.told(this.identity.id)
1719
+ const same =
1720
+ removed.every((key) => has(told.removed, key)) &&
1721
+ standing.length === told.standing.length &&
1722
+ standing.every((key) => has(told.standing, key))
1723
+ if (child.closing || child.closed) return false
1724
+ if (!same) {
1725
+ // a row with no key, or no member, tells nothing by: the proof does
1726
+ const { data: seat } = await store.get('devices', hid.encode(store.writerKey))
1727
+ const proof =
1728
+ seat?.key && seat.memberId
1729
+ ? null
1730
+ : this.identity.sign(admission(store.key, store.writerKey, store.writerKey))
1731
+ await store.call('revoke', {
1732
+ removed: b4a.concat(removed),
1733
+ standing: b4a.concat(standing),
1734
+ proof
1735
+ })
1736
+ }
1737
+ return this._record(child, { told: digest(removed, standing) }, timeout)
1738
+ }
1739
+
1740
+ // what the extensions tell a room this device may write in, stamped once it is told
1741
+ /** @private */
1742
+ async _teach(child, stamp, timeout) {
1743
+ if (child.store.writable) for (const { tell } of this._tellers) await tell(child)
1744
+ return this._record(child, { stamp }, timeout)
1745
+ }
1746
+
1747
+ // an open room too: the app may close it before a peer holds what it was told
1748
+ /** @private */
1749
+ async _record(child, marks, timeout) {
1750
+ const { data } = await this.local.store.get('handle-keypairs', child.id)
1751
+ if (data && Object.keys(marks).every((k) => sameBytes(data[k], marks[k]))) return true
1752
+ // a removal counts once a device that stands has it: a peer that holds it may be the removed one
1753
+ const removed = marks.told ? await this.store.removals() : null
1754
+ const holds = await reached(child.store, this.identity.id, removed, timeout)
1755
+ if (child.closing || child.closed) return false
1756
+ if (!holds) return null
1757
+ await this._mark(child.id, marks)
1758
+ return true
1759
+ }
1760
+
1761
+ // what a room was told, kept on its keypair row
1762
+ /** @private */
1763
+ async _mark(id, marks) {
1764
+ const { data } = await this.local.store.get('handle-keypairs', id)
1765
+ if (!data || Object.keys(marks).every((k) => sameBytes(data[k], marks[k]))) return
1766
+ await this.local.store.put('handle-keypairs', { ...data, ...marks })
1767
+ }
1768
+
1769
+ // a handle that has no route to be told by loses the removed device's seats one by one
1770
+ /** @private */
1771
+ async _unseat(child, removed) {
1121
1772
  const { data: rows } = await child.store.get('devices')
1122
1773
  for (const row of rows) {
1123
- if (row.memberId !== this.identity.id || !row.key || kept.has(b4a.toHex(row.key))) continue
1774
+ // a sibling this root has not heard of yet is no removal: only its record is
1775
+ if (row.memberId !== this.identity.id || !row.key || !has(removed, row.key)) continue
1124
1776
  if (child.closing || child.closed) return
1125
1777
  await child.store.del('devices', row.id)
1126
1778
  }
@@ -1131,14 +1783,215 @@ export class Handle extends ReadyResource {
1131
1783
  for (const child of this.children) await this._prune(child)
1132
1784
  }
1133
1785
 
1786
+ // the closed rooms are told too, by a pass over those this device has a writer in, and every room
1787
+ // the identity is in for a removal since this device stood, when the root's device lists or the
1788
+ // extensions' stamp are not the ones last told to all of them. One pass at a time: a call while
1789
+ // one waits to start joins it
1790
+ /** @private */
1791
+ _tellClosed() {
1792
+ if (this._retell) return this._telling
1793
+ this._retell = true
1794
+ const run = () => {
1795
+ this._retell = false
1796
+ return this._pass().catch((err) => this.closing || this._onerror(err))
1797
+ }
1798
+ this._telling = (this._telling ?? Promise.resolve()).then(run)
1799
+ return this._telling
1800
+ }
1801
+
1802
+ /** @private */
1803
+ async _pass() {
1804
+ if (this.closing) return
1805
+ const lists = await this._lists()
1806
+ const stamp = await this._stamp()
1807
+ // the build too: one that may bring revoke to a room found below it opens that room again
1808
+ const seen = hash([stamp ?? b4a.alloc(0), built(this.spec)])
1809
+ const { data: told } = await this.local.store.get('told')
1810
+ const listed =
1811
+ told &&
1812
+ (!lists ||
1813
+ (sameBytes(told.removed, lists.removed) && sameBytes(told.standing, lists.standing)))
1814
+ if (listed && sameBytes(told.stamp, seen)) return
1815
+ // a writer in a room is the writer keypair this device keeps for it
1816
+ const rooms = []
1817
+ const held = new Set()
1818
+ for (let after; ;) {
1819
+ const { data } = await this.local.store.get('handle-keypairs', { gt: after, limit: PAGE })
1820
+ for (const row of data) {
1821
+ held.add(row.id)
1822
+ if ((lists && !(await this._marked(row, lists))) || !sameBytes(row.stamp, stamp)) {
1823
+ rooms.push({ id: row.id, used: row.used ?? 0 })
1824
+ }
1825
+ }
1826
+ if (data.length < PAGE) break
1827
+ after = data[data.length - 1].id
1828
+ }
1829
+ // a room no device that stands may have opened is told a removal too: this device takes a seat.
1830
+ // One the root held when this device first stood is told by the devices that stood then
1831
+ if (lists && told && keysIn(lists.removed).some((key) => !has(keysIn(told.removed), key))) {
1832
+ for (const { id } of (await this.store.get('handles', { state: 'in' })).data) {
1833
+ if (!held.has(id)) rooms.push({ id, used: 0 })
1834
+ }
1835
+ }
1836
+ rooms.sort((a, b) => b.used - a.used)
1837
+ let next = 0
1838
+ let covered = true
1839
+ const tell = async () => {
1840
+ while (next < rooms.length && !this.closing) {
1841
+ const { id } = rooms[next++]
1842
+ const done = await this._tellOne(id, stamp, lists?.marked).catch((err) => {
1843
+ if (!this.closing) this._onerror(err)
1844
+ return false
1845
+ })
1846
+ if (!done) covered = false
1847
+ }
1848
+ }
1849
+ await Promise.all(Array.from({ length: TELLING }, tell))
1850
+ if (!covered || this.closing) return
1851
+ const { removed, standing } = lists ?? told ?? {}
1852
+ await this.local.store.set('told', { removed, standing, stamp: seen })
1853
+ }
1854
+
1855
+ // a room told what the root holds, or found below the version that brings revoke by this build
1856
+ /** @private */
1857
+ async _marked(row, lists) {
1858
+ if (sameBytes(row.told, lists.marked)) return true
1859
+ if (!row.told) return false
1860
+ const { data: handle } = await this.store.get('handles', row.id)
1861
+ const spec = handle && this.spec.handles?.[handle.type]
1862
+ return Boolean(spec) && sameBytes(row.told, below(lists.marked, spec.meta))
1863
+ }
1864
+
1865
+ // the root's device lists, 32-byte keys back to back, when there is a removal to tell and this
1866
+ // device stands to tell it
1867
+ /** @private */
1868
+ async _lists() {
1869
+ const removed = await this.store.removals()
1870
+ if (removed.length === 0) return null
1871
+ const { data: devices } = await this.store.get('devices')
1872
+ const standing = devices.filter((row) => row.key).map((row) => row.key)
1873
+ if (!has(standing, this.identity.device.publicKey)) return null
1874
+ const marked = digest(removed, standing)
1875
+ return { removed: b4a.concat(removed), standing: b4a.concat(standing), marked }
1876
+ }
1877
+
1878
+ // what the extensions tell the rooms, as one digest: null when they tell nothing
1879
+ /** @private */
1880
+ async _stamp() {
1881
+ const stamps = await Promise.all(this._tellers.map(({ stamp }) => stamp()))
1882
+ if (stamps.every((s) => s === null)) return null
1883
+ return hash(b4a.from(JSON.stringify(stamps)))
1884
+ }
1885
+
1886
+ // a closed room opened only to be told: nothing handed to the app. One open here runs the same
1887
+ // compare, behind its own. One no peer serves yet is untold for now and holds no other room:
1888
+ // it waits closed for its turn, a few at a time, and reports its wait once per removal
1889
+ /** @private */
1890
+ async _tellOne(id, stamp, marked, turn = false) {
1891
+ const open = [...this.children].find((c) => c.id === id)
1892
+ if (open) return this._prune(open, stamp)
1893
+ const loading = this._loading.get(id)
1894
+ if (loading) {
1895
+ const child = await loading.catch(() => null)
1896
+ return child ? this._prune(child, stamp) : false
1897
+ }
1898
+ if (this._tellings.has(id)) return false
1899
+ if (!turn && this._waiting.has(id)) {
1900
+ this._waiting.set(id, { stamp, marked })
1901
+ return false
1902
+ }
1903
+ const telling = this._tellRoom(id, stamp, marked, turn)
1904
+ const done = () => this._tellings.delete(id)
1905
+ this._tellings.set(id, telling.then(done, done))
1906
+ // set aside once it is closed, so its turn opens it again
1907
+ const told = await telling
1908
+ if (told !== null) return told
1909
+ this._wait(id, stamp, marked)
1910
+ return false
1911
+ }
1912
+
1913
+ /** @private */
1914
+ _wait(id, stamp, marked) {
1915
+ this._waiting.set(id, { stamp, marked })
1916
+ if (this._waiters >= TELLING) return
1917
+ this._waiters++
1918
+ this._turns()
1919
+ }
1920
+
1921
+ /** @private */
1922
+ async _turns() {
1923
+ try {
1924
+ while (this._waiting.size && !this.closing) {
1925
+ const [[id, { stamp, marked }]] = this._waiting
1926
+ this._waiting.delete(id)
1927
+ await this._tellOne(id, stamp, marked, true).catch((err) => {
1928
+ if (!this.closing) this._onerror(err)
1929
+ })
1930
+ }
1931
+ } finally {
1932
+ this._waiters--
1933
+ }
1934
+ }
1935
+
1936
+ // null when no peer serves it yet, or holds what it was told: set aside for a turn
1937
+ /** @private */
1938
+ async _tellRoom(id, stamp, marked, turn) {
1939
+ const { data: row } = await this.store.get('handles', id)
1940
+ // a room left on another device has no row; one still being joined is told by its own open
1941
+ if (!row?.encryptionKey) return true
1942
+ const { type, key, encryptionKey, epochs } = row
1943
+ const kept = await this._loadKeyPair(id)
1944
+ const keyPair = kept || Identity.randomKeyPair()
1945
+ // stored before its claim is on the log: a retry claims with it, never with another
1946
+ if (!kept) {
1947
+ const { publicKey, secretKey } = keyPair
1948
+ await this.local.store.put('handle-keypairs', { id, publicKey, secretKey })
1949
+ }
1950
+ const child = this._room({
1951
+ spec: pickHandle(this.spec, type),
1952
+ namespace: `${NS}/handle/${type}/${id}`,
1953
+ key,
1954
+ encryptionKey,
1955
+ epochs: epochs ? c.decode(epochEntries, epochs) : undefined,
1956
+ keyPair: /** @type {KeyPair} */ (keyPair)
1957
+ })
1958
+ try {
1959
+ await child.ready()
1960
+ if (!child.store.writable && child.store.length === 0) {
1961
+ if (!turn && !(await served(child.store, SERVED))) return null
1962
+ try {
1963
+ await child.store.claim({ timeout: TIMEOUT })
1964
+ } catch (err) {
1965
+ if (this.closing || child.closing || child.closed) return false
1966
+ if (err.code === 'TIMEOUT') {
1967
+ const { data } = await this.local.store.get('handle-keypairs', id)
1968
+ if (!marked || sameBytes(data?.waited, marked)) return false
1969
+ await this._mark(id, { waited: marked })
1970
+ }
1971
+ this._onerror(err)
1972
+ return false
1973
+ }
1974
+ }
1975
+ const told = await this._prune(child, stamp, turn ? TIMEOUT : SERVED)
1976
+ // told after its pass ended: the next one records the rooms covered
1977
+ if (told && turn) this._tellClosed()
1978
+ // one no peer held on its turn waits for the next pass, not another turn
1979
+ return turn ? Boolean(told) : told
1980
+ } finally {
1981
+ await child._end().catch(safetyCatch)
1982
+ }
1983
+ }
1984
+
1134
1985
  // a handle's epochs ride in its root row, which only the identity's devices read: one that
1135
- // opens the handle later reads history with them, since envelopes in the log address a device
1986
+ // opens the handle later reads history with them, since envelopes in the log address a device.
1987
+ // Written once the root holds no device it removed, which would read them there
1136
1988
  /** @private */
1137
1989
  _carry(child) {
1138
1990
  const save = async () => {
1139
1991
  const epochs = c.encode(epochEntries, child.store.keyring.all())
1140
1992
  const { data: row } = await this.store.get('handles', child.id)
1141
1993
  if (!row || b4a.equals(row.epochs || b4a.alloc(0), epochs)) return
1994
+ if (!(await this.store.rotated())) return
1142
1995
  await this.store.set('handles', { id: row.id, epochs })
1143
1996
  }
1144
1997
  // read when the row changes, and when an announcement applies: it is learned only after that
@@ -1153,11 +2006,15 @@ export class Handle extends ReadyResource {
1153
2006
  child.store.on('epoch', onepoch)
1154
2007
  child.store.on('update', onchild)
1155
2008
  this.store.on('update', onroot)
2009
+ this.store.on('epoch', onepoch)
1156
2010
  child.once('close', () => {
1157
2011
  child.store.off('epoch', onepoch)
1158
2012
  child.store.off('update', onchild)
1159
2013
  this.store.off('update', onroot)
2014
+ this.store.off('epoch', onepoch)
1160
2015
  })
2016
+ // one that rotated before it is carried, as a room made while the root owes a rotation
2017
+ if (child.store.keyring.seq > 0) read().then(save).catch(this._onerror)
1161
2018
  }
1162
2019
 
1163
2020
  // before(me.room.notes, fn): on every handle open now and every one opened later
@@ -1172,7 +2029,7 @@ export class Handle extends ReadyResource {
1172
2029
  }
1173
2030
  }
1174
2031
  this._typeHooks.add(hook)
1175
- for (const child of this.children) hook.apply(child)
2032
+ for (const child of [...this.children, ...this._pending]) hook.apply(child)
1176
2033
  const off = () => {
1177
2034
  this._typeHooks.delete(hook)
1178
2035
  for (const o of offs.values()) o()
@@ -1205,8 +2062,10 @@ export class Handle extends ReadyResource {
1205
2062
  /** @private */
1206
2063
  async _reserve() {
1207
2064
  for (const { id, type } of (await this.local.store.get('serving')).data) {
1208
- this._load(type, id).catch((err) => {
2065
+ this._load(type, id).then(reserved, (err) => {
1209
2066
  if (err.code === 'UNKNOWN') return this.local.store.del('serving', id).catch(safetyCatch)
2067
+ // a close cut it short: the room is served again at the next launch
2068
+ if (err.code === 'CLOSED') return
1210
2069
  this._onerror(err)
1211
2070
  })
1212
2071
  }
@@ -1218,12 +2077,17 @@ export class Handle extends ReadyResource {
1218
2077
  * @returns {Promise<void>}
1219
2078
  * @private
1220
2079
  */
1221
- async _saveKeyPair(id, keyPair) {
2080
+ async _saveKeyPair(id, keyPair, invite) {
1222
2081
  if (!keyPair) return
2082
+ // a reopen stamps the row: what a join keeps on it stays
2083
+ const { data: was } = await this.local.store.get('handle-keypairs', id)
1223
2084
  await this.local.store.put('handle-keypairs', {
2085
+ ...was,
1224
2086
  id,
1225
2087
  publicKey: keyPair.publicKey,
1226
- secretKey: keyPair.secretKey
2088
+ secretKey: keyPair.secretKey,
2089
+ ...(invite !== undefined && { invite }),
2090
+ used: Date.now()
1227
2091
  })
1228
2092
  }
1229
2093
 
@@ -1242,11 +2106,149 @@ export class Handle extends ReadyResource {
1242
2106
  }
1243
2107
  }
1244
2108
 
2109
+ // the states a row ends in, read through their index at launch, and how long one stays
2110
+ const SWEPT = ['cancelled', 'denied', 'expired', 'removed', 'left']
2111
+ const KEPT = 30 * 24 * 60 * 60 * 1000
2112
+
2113
+ // how a join ends, as its row says it and as `open` throws it
2114
+ const OVER = { DENIED: 'denied', EXPIRED: 'expired', CANCELLED: 'cancelled' }
2115
+ const ENDS = {
2116
+ denied: (reason) => CeroError.DENIED(reason || null),
2117
+ expired: () => CeroError.EXPIRED(),
2118
+ cancelled: () => CeroError.CANCELLED(),
2119
+ // the invite it was let in with is one minted before its removal
2120
+ removed: () => CeroError.DENIED('removed')
2121
+ }
2122
+
2123
+ // a push is heard only for a handle this identity is in or joining, with its keys
2124
+ const TOPICAL = new Set(['in', 'joining'])
2125
+
2126
+ function topical(row) {
2127
+ return !!row?.encryptionKey && TOPICAL.has(row.state || 'in')
2128
+ }
2129
+
2130
+ // the keys a pairing reply delivered, as a join's row keeps them
2131
+ const keys = ({ encryptionKey, epochs }) => ({
2132
+ encryptionKey,
2133
+ epochs: c.encode(epochEntries, epochs)
2134
+ })
2135
+
2136
+ /**
2137
+ * Wait for a join as one of its waiters, but stop waiting after `ms`; the join itself goes on.
2138
+ *
2139
+ * @param {{ waiting: number } | null} join The join carried here, which reports its errors to the app with none waiting.
2140
+ * @param {Promise<void>} landed
2141
+ * @param {number} ms `0` waits as long as the join takes.
2142
+ * @returns {Promise<void>}
2143
+ */
2144
+ async function wait(join, landed, ms) {
2145
+ if (join) join.waiting++
2146
+ let timer = null
2147
+ const timeout = new Promise((resolve, reject) => {
2148
+ if (!ms) return
2149
+ timer = setTimeout(() => reject(CeroError.TIMEOUT('join')), ms)
2150
+ })
2151
+ try {
2152
+ return await Promise.race([landed, timeout])
2153
+ } finally {
2154
+ clearTimeout(timer)
2155
+ if (join) join.waiting--
2156
+ }
2157
+ }
2158
+
1245
2159
  // the keys a pairing reply delivered, as a handle opens with them
1246
2160
  function delivered({ key, encryptionKey, epochs, writer }) {
1247
2161
  return { key, encryptionKey, epochs, keyPair: writer }
1248
2162
  }
1249
2163
 
2164
+ // the hold a boot took on a handle to serve its invites goes back once it serves none
2165
+ function reserved(child) {
2166
+ const release = (serving) => {
2167
+ if (serving) return
2168
+ child._pair.off('serving', release)
2169
+ child.close().catch(child._onerror)
2170
+ }
2171
+ child._pair.on('serving', release)
2172
+ release(child._pair.serving)
2173
+ }
2174
+
2175
+ // the entry type of a row whose type no header carries: no file server url builds it
2176
+ const UNSERVED = '\n'
2177
+
2178
+ // what a room is told of an identity's device keys, as one value to hold it against
2179
+ function digest(removed, standing) {
2180
+ return hash([hash(b4a.concat(removed)), hash(b4a.concat(standing))])
2181
+ }
2182
+
2183
+ // the mark of a room below the version that brings revoke, for the build that found it there
2184
+ function below(marked, meta = {}) {
2185
+ return hash([marked, b4a.from(JSON.stringify([meta.version, meta.since?.routes]))])
2186
+ }
2187
+
2188
+ function built(spec) {
2189
+ const handles = Object.values(spec.handles ?? {})
2190
+ return hash(b4a.from(JSON.stringify(handles.map(({ meta = {} }) => [meta.version, meta.since]))))
2191
+ }
2192
+
2193
+ // the closed rooms a pass tells at once, and those that wait for a peer at once; the keypairs it
2194
+ // reads at a time; how long a pass waits for a peer to serve a room, or to hold what it wrote
2195
+ // there, before it sets it aside
2196
+ const TELLING = 4
2197
+ const PAGE = 1000
2198
+ const SERVED = 2000
2199
+
2200
+ // whether a peer serves a room within `timeout`: its members reach the view
2201
+ function served(store, timeout) {
2202
+ return new Promise((resolve) => {
2203
+ const done = (found) => {
2204
+ clearTimeout(timer)
2205
+ store.off('update', check)
2206
+ store.off('close', done)
2207
+ resolve(!!found)
2208
+ }
2209
+ const check = () =>
2210
+ store.get('members', { limit: 1 }).then(
2211
+ (res) => res.data.length > 0 && done(true),
2212
+ () => done(false)
2213
+ )
2214
+ const timer = setTimeout(done, timeout)
2215
+ store.on('update', check)
2216
+ store.once('close', done)
2217
+ check()
2218
+ })
2219
+ }
2220
+
2221
+ // whether a peer holds every block this device wrote to a room within `timeout`, or with `removed`
2222
+ // a device there that is neither this one nor a removed one applied them: one where only the
2223
+ // identity's own devices write has no other member to hear it
2224
+ async function reached(store, id, removed, timeout) {
2225
+ const { data: devices } = await store.get('devices')
2226
+ // an empty view has not shown yet who else writes there
2227
+ if (devices.length > 0 && devices.every((row) => row.memberId === id)) return true
2228
+ if (removed) return store.heard(removed, timeout).catch(() => false)
2229
+ let timer = null
2230
+ const late = new Promise((resolve) => (timer = setTimeout(resolve, timeout, false)))
2231
+ try {
2232
+ return await Promise.race([store.held().then(() => true), late])
2233
+ } catch {
2234
+ return false
2235
+ } finally {
2236
+ clearTimeout(timer)
2237
+ }
2238
+ }
2239
+
2240
+ // a file as its url names it to the file server
2241
+ function fileEntry(coreKey, { blockOffset, blockLength, byteOffset, byteLength }, type) {
2242
+ return [b4a.toHex(coreKey), blockOffset, blockLength, byteOffset, byteLength, type].join('/')
2243
+ }
2244
+
2245
+ // a local list read as a collection reads: one row by id, or the rows a query keeps
2246
+ function listed(rows, query = {}) {
2247
+ if (typeof query === 'string') return { data: rows.find((row) => row.id === query) ?? null }
2248
+ const data = filter(rows, query)
2249
+ return { data, total: data.length, size: data.length }
2250
+ }
2251
+
1250
2252
  function admitted(db, id) {
1251
2253
  return new Promise((resolve, reject) => {
1252
2254
  const done = (err, member) => {
@@ -1277,6 +2279,12 @@ function randomNs() {
1277
2279
  return z32.encode(Identity.randomBytes(8))
1278
2280
  }
1279
2281
 
2282
+ // the push topic of a handles row, which keys its topics row
2283
+ const topicOf = ({ key }) => b4a.toHex(discoveryKey(key))
2284
+
2285
+ // what me.topics shows of a topics row: none of the keys it keeps
2286
+ const listing = ({ id, handle, type, name }) => ({ id, handle, type, name })
2287
+
1280
2288
  // a topics row still describes its handle
1281
2289
  function same(row, next) {
1282
2290
  return (
@@ -1286,10 +2294,34 @@ function same(row, next) {
1286
2294
  (row.name ?? null) === next.name &&
1287
2295
  b4a.equals(row.key, next.key) &&
1288
2296
  sameBytes(row.encryptionKey, next.encryptionKey) &&
1289
- sameBytes(row.epochs, next.epochs)
2297
+ sameBytes(row.epochs, next.epochs) &&
2298
+ sameBytes(row.writers, next.writers)
1290
2299
  )
1291
2300
  }
1292
2301
 
2302
+ // the keys that may write to a handle now: the devices of its members whose role writes
2303
+ async function writersOf(db) {
2304
+ const [devices, members] = await Promise.all([db.get('devices'), db.get('members')])
2305
+ const writes = new Set(members.data.filter((m) => can(m.role, WRITE)).map((m) => m.id))
2306
+ return b4a.concat(devices.data.filter((d) => writes.has(d.memberId)).map((d) => hid.decode(d.id)))
2307
+ }
2308
+
2309
+ // a handle whose writers do not read accepts nobody
2310
+ function unread(err) {
2311
+ safetyCatch(err)
2312
+ return null
2313
+ }
2314
+
2315
+ function has(keys, key) {
2316
+ return keys.some((k) => b4a.equals(k, key))
2317
+ }
2318
+
2319
+ function keysIn(bytes) {
2320
+ const keys = []
2321
+ for (let i = 0; i < (bytes?.byteLength || 0); i += 32) keys.push(bytes.subarray(i, i + 32))
2322
+ return keys
2323
+ }
2324
+
1293
2325
  function sameBytes(a, b) {
1294
2326
  return a && b ? b4a.equals(a, b) : (a ?? null) === (b ?? null)
1295
2327
  }