@cero-base/cero 3.4.1 → 3.6.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.
@@ -4,8 +4,11 @@ import { encodeId, decodeId, checkType } from '@cero-base/core/blobs/codec'
4
4
  import { onAbort, subscribe, isOptions } from '@cero-base/core/utils'
5
5
  import { CeroError } from '@cero-base/core/errors'
6
6
 
7
+ import { LANES } from './line.js'
8
+
7
9
  /**
8
10
  * @typedef {import('./refs.js').Ref} Ref
11
+ * @typedef {import('../extensions/calls.js').Line} Line
9
12
  * @typedef {import('@cero-base/core/database').HookContext} HookContext
10
13
  * @typedef {import('../handle/index.js').Context | import('../rpc/client.js').Context} Context
11
14
  * @typedef {import('@cero-base/core/database').Row} Row
@@ -109,8 +112,9 @@ const ENDED = new Set(['left', 'removed', 'denied', 'expired', 'cancelled'])
109
112
  /**
110
113
  * Rule that runs before a write to `ref` lands, or before an action does: at apply, on every
111
114
  * peer, inside the op's transaction. Return `false` to refuse it: the writer's own call rejects
112
- * with `REFUSED`. `ctx` is `{ op, name, row, existing, id, memberId, role, get, put, set, del }`;
113
- * mutate `ctx.row` to rewrite what is stored. `op` is the op as it applies, so an upsert on a
115
+ * with `REFUSED`. `ctx` is
116
+ * `{ op, name, row, existing, id, memberId, role, device, ts, get, put, set, del }`; mutate
117
+ * `ctx.row` to rewrite what is stored. `op` is the op as it applies, so an upsert on a
114
118
  * collection is a `put`. The four operators on `ctx` read and write the handle as it stands at this
115
119
  * op, inside the transaction. Must be deterministic: read only `ctx`, never a clock or local
116
120
  * state. On a type ref (`me.room.notes`) it reaches every handle of the type before the handle
@@ -275,7 +279,7 @@ export function watch(ref, query, opts) {
275
279
  const q = id ? query : rest
276
280
  const owner = ref.handle
277
281
  const from = owner.opened === false ? owner.ready().then(() => source(ref, q)) : source(ref, q)
278
- const diff = changes ? differ(ref.kind === 'single') : null
282
+ const diff = changes ? differ(ref.kind === 'single' || ref.kind === 'lane') : null
279
283
  return bindStream(owner, snapshotStream(from, diff), opts)
280
284
  }
281
285
 
@@ -449,10 +453,12 @@ export function accept(ctx, request, { role } = {}) {
449
453
  }
450
454
 
451
455
  /**
452
- * Turn away a join waiting on a `confirm` invite. The joiner's `open` rejects with `DENIED`.
456
+ * Turn away a join waiting on a `confirm` invite. The joiner's `open` rejects with `DENIED`. On a
457
+ * ring of `me.local.rings`, turn down the room's call: it stops ringing your devices, and goes on
458
+ * for the others unless every member it rang turned it down before anyone answered.
453
459
  *
454
460
  * @param {Context} ctx
455
- * @param {{ id: string }} request A row of `ctx.requests`.
461
+ * @param {{ id: string }} request A row of `ctx.requests`, or the room's ring.
456
462
  * @param {string} [reason]
457
463
  * @returns {Promise<void>}
458
464
  */
@@ -484,15 +490,110 @@ export function leave(ctx) {
484
490
  }
485
491
 
486
492
  /**
487
- * Stop using a context on this device; everything stays. Closing the root closes it all.
493
+ * Stop using a context on this device; everything stays. Closing the root closes it all. On a line,
494
+ * this device leaves the call: it goes on for the others, and ends with the last device on it.
488
495
  *
489
- * @param {Context} ctx
496
+ * @param {Context | Line} ctx
490
497
  * @returns {Promise<void>}
491
498
  */
492
499
  export function close(ctx) {
493
500
  return ctx.close()
494
501
  }
495
502
 
503
+ /**
504
+ * Start a call in a room, ringing the members `to` names, every other member without it, or join
505
+ * the call going there. The same room gives the same line until it closes. Needs the `calls()`
506
+ * extension in the build: without it `INVALID`. `stream`, the camera and microphone, goes to every
507
+ * device on the call where WebRTC runs, the UI.
508
+ *
509
+ * @param {Context} room
510
+ * @param {{ to?: string[], stream?: MediaStream }} [opts]
511
+ * @returns {Promise<Line>}
512
+ */
513
+ export async function dial(room, opts = {}) {
514
+ if (!isOptions(opts)) throw CeroError.INVALID('dial options are an object')
515
+ if (opts.stream != null) media(opts.stream)
516
+ return room._dial(opts)
517
+ }
518
+
519
+ /**
520
+ * Send a stream on a line where WebRTC runs: on `line` the camera and microphone, in place of the
521
+ * ones before; on `line.screen` a screen, beside them. In a worker with no UI it does nothing.
522
+ *
523
+ * @param {Line | Ref} target A line, or its `screen`.
524
+ * @param {MediaStream} stream
525
+ * @returns {Promise<void>}
526
+ */
527
+ export function share(target, stream) {
528
+ const [line, kind] = shared(target)
529
+ return line._share(kind, media(stream))
530
+ }
531
+
532
+ /**
533
+ * Stop the stream `share` or `dial` sent on `line`, or the screen on `line.screen`. The app's tracks
534
+ * stay as they are.
535
+ *
536
+ * @param {Line | Ref} target
537
+ * @returns {Promise<void>}
538
+ */
539
+ export function unshare(target) {
540
+ const [line, kind] = shared(target)
541
+ return line._share(kind, null)
542
+ }
543
+
544
+ function shared(target) {
545
+ if (target?.kind === 'lane' && target.name === 'screen' && target.handle?._share) {
546
+ return [target.handle, 'screen']
547
+ }
548
+ if (typeof target?._share === 'function') return [target, 'camera']
549
+ throw CeroError.INVALID('share takes a line or line.screen')
550
+ }
551
+
552
+ function media(stream) {
553
+ if (typeof stream?.getTracks !== 'function') throw CeroError.INVALID('a stream is a MediaStream')
554
+ return stream
555
+ }
556
+
557
+ /**
558
+ * End a call for everyone on it: every line of it closes.
559
+ *
560
+ * @param {Line} line
561
+ * @returns {Promise<void>}
562
+ */
563
+ export function end(line) {
564
+ if (typeof line?._finish !== 'function') {
565
+ throw CeroError.INVALID('end takes a line, as cero.dial gives it')
566
+ }
567
+ return line._finish()
568
+ }
569
+
570
+ /**
571
+ * Pause a lane of a line, `line.audio` or `line.video`: every device on the call sees it.
572
+ *
573
+ * @param {Ref} lane
574
+ * @returns {Promise<void>}
575
+ */
576
+ export function mute(lane) {
577
+ return toggle(lane, false)
578
+ }
579
+
580
+ /**
581
+ * Turn a lane paused with `mute` back on.
582
+ *
583
+ * @param {Ref} lane
584
+ * @returns {Promise<void>}
585
+ */
586
+ export function unmute(lane) {
587
+ return toggle(lane, true)
588
+ }
589
+
590
+ function toggle(lane, on) {
591
+ if (!LANES.includes(lane?.name) || typeof lane.handle?._lane !== 'function') {
592
+ throw CeroError.INVALID(`mute takes line.${LANES.join(' or line.')}`)
593
+ }
594
+ return lane.handle._lane(lane.name, on)
595
+ }
596
+
496
597
  /**
497
598
  * Give up a join still waiting for an answer, for good: it is not resumed on the next boot.
498
599
  *
@@ -537,7 +638,7 @@ export async function activate(ctx) {
537
638
  }
538
639
 
539
640
  /**
540
- * Take a handle off the swarm until something lands in it.
641
+ * Rank a handle last: it is on the swarm only while a slot is spare, until something lands in it.
541
642
  *
542
643
  * @param {Context} ctx
543
644
  * @returns {Promise<void>}
@@ -0,0 +1,5 @@
1
+ import { CeroError } from '@cero-base/core/errors'
2
+
3
+ export function follow() {
4
+ throw CeroError.INVALID('pulse runs in the worker')
5
+ }
@@ -0,0 +1,505 @@
1
+ import Client from 'hypertracker/client'
2
+ import crypto from 'hypercore-crypto'
3
+ import c from 'compact-encoding'
4
+ import b4a from 'b4a'
5
+ import hid from 'hypercore-id-encoding'
6
+
7
+ import { CeroError } from '@cero-base/core/errors'
8
+ import { epochEntries } from '@cero-base/core/database/encryption'
9
+
10
+ import { get, set, del, open, close, activate } from './operators.js'
11
+
12
+ // a handle's key pair on the service comes from the newest epoch key this device holds for it, its
13
+ // encryption key before the first rotation: a member removed since cannot sign for it, and the
14
+ // service sees its public key, never the handle's topic
15
+ const [NS] = crypto.namespace('cero/bump', 1)
16
+
17
+ // a handle's own writes are told at most once in EVERY ms, and writes from other devices landing
18
+ // in it kept and told to the app at most once in HEARD ms. WAKING handles are woken at once, each
19
+ // open until a write from another device lands in it or WAIT ms pass. Of the handles a connection
20
+ // brings as due, the newest REPLAYED are woken. A time arriving within DIRECT ms of a write from
21
+ // another device landing is that write. A connection that died goes unnoticed for up to ~20 s,
22
+ // so what was told in the UNSURE ms before it closed is told again
23
+ const EVERY = 100
24
+ const HEARD = 1000
25
+ const WAKING = 4
26
+ const WAIT = 10000
27
+ const REPLAYED = 32
28
+ const DIRECT = 5000
29
+ const UNSURE = 30000
30
+
31
+ /**
32
+ * Follow every handle this device is in on the service at `key`: tell it of this device's writes,
33
+ * and wake a handle when another device tells of one. A best effort: a notice may come late or
34
+ * twice, and the data is Cero's sync's. `me` emits `'pulse'` with the handle's id and the local
35
+ * time a write from another device landed in it.
36
+ *
37
+ * @param {import('../handle/index.js').Context} me
38
+ * @param {string | Uint8Array} key The service's public key.
39
+ * @returns {() => void} Stops following.
40
+ */
41
+ export function follow(me, key) {
42
+ if (!me.local.pulses) {
43
+ throw CeroError.INVALID('pulse: build the spec with pulse() among its extensions')
44
+ }
45
+ const server = decode(key)
46
+ // a root that began to close before this setup ran has no network left to follow on
47
+ if (me.closing) return () => {}
48
+ const client = new Client(server, { dht: me.network.dht })
49
+ const rooms = new Map() // handle id → what this device follows of it
50
+ const byKey = new Map() // its public key on the service, hex → the same
51
+ const early = new Set() // handles written in before their topics row was read
52
+ const unsure = new Set() // handles told as a connection died
53
+ const lengths = new Map() // handle id → writer, hex → its length at its last op applied
54
+ const waits = new Map() // handle id → ends the wait of its wake
55
+ const queue = new Set()
56
+ const replays = new Set() // handles this connection brought as due, let wake
57
+ let connection = 0
58
+ let opened = 0 // when the connection opened: a time below it was kept by the service
59
+ let waking = 0
60
+ let stopped = false
61
+ let passing = null
62
+ let again = false
63
+
64
+ // the app's onerror throwing is no reason to stop
65
+ const report = (err) => {
66
+ if (stopped || me.closing) return
67
+ try {
68
+ me._onerror(err)
69
+ } catch {}
70
+ }
71
+ const live = () => !client.connecting && !client.suspended && !!client.channel?.opened
72
+
73
+ // on every handle before it opens, so a write landing as it boots is heard
74
+ const offs = Object.keys(me.spec.handles || {}).map((type) =>
75
+ me._hookType({ type }, (child) => {
76
+ const onapply = ({ writerKey, length }) => {
77
+ // a reorder applies ops again, at the length their writer wrote them at
78
+ if (!lengths.has(child.id)) lengths.set(child.id, new Map())
79
+ const writers = lengths.get(child.id)
80
+ const hex = b4a.toHex(writerKey)
81
+ if (length <= (writers.get(hex) ?? 0)) return
82
+ writers.set(hex, length)
83
+ const own = child.store.writerKey
84
+ if (own && b4a.equals(writerKey, own)) wrote(child.id)
85
+ else landed(child.id)
86
+ }
87
+ child.store.on('apply', onapply)
88
+ return () => child.store.off('apply', onapply)
89
+ })
90
+ )
91
+
92
+ client.on('connect', () => {
93
+ const on = ++connection
94
+ opened = Date.now()
95
+ replays.clear()
96
+ client.cork()
97
+ for (const room of rooms.values()) greet(room)
98
+ unsure.clear()
99
+ client.uncork()
100
+ client.connection.once('close', () => {
101
+ const since = Date.now() - UNSURE
102
+ for (const room of rooms.values()) {
103
+ if (room.on === on && room.sent > since) unsure.add(room.id)
104
+ }
105
+ })
106
+ })
107
+
108
+ client.on('announce', ({ publicKey, bumped }) => {
109
+ const room = byKey.get(b4a.toHex(publicKey))
110
+ if (!room) return
111
+ room.seen = Math.max(room.seen, bumped)
112
+ // a write owed was told before the service sent what it kept: at or past it, it was dropped
113
+ const first = room.check === connection
114
+ room.check = 0
115
+ if (first && bumped >= room.told && live()) tell(room)
116
+ // the service sends no device what it told on that connection: a time alike told before it is
117
+ // this device's own, kept; one alike told on it is another device's of the same ms, and this
118
+ // one's was dropped
119
+ if (bumped === room.prior) return
120
+ if (bumped === room.told && live()) tell(room)
121
+ // direct sync often beats the service: the write it tells of is in when told before the last
122
+ // write that landed, or the handle is open here
123
+ const direct = Date.now() - room.heard < DIRECT && (bumped <= room.heard || held(room.id))
124
+ if (room.due <= room.since && direct) {
125
+ room.since = Math.max(room.since, bumped)
126
+ return keep(room)
127
+ }
128
+ room.due = Math.max(room.due, bumped)
129
+ if (room.wokenOn === connection && room.woken >= room.due) return
130
+ if (bumped < opened && !admit(room)) return
131
+ queue.add(room)
132
+ pump()
133
+ })
134
+
135
+ const onstatus = () => {
136
+ if (me.network.suspended) client.suspend().catch(report)
137
+ else if (client.suspended) client.resume()
138
+ }
139
+ me.on('status', onstatus)
140
+
141
+ // the last landing of a window is kept as the root begins to close, while it can still write
142
+ me.own({ destroy: () => rooms.forEach(flush) })
143
+
144
+ // a cero() that fails after its setups ran never closes the root
145
+ me.network.once('close', stop)
146
+ me.ready().then(begin, () => {})
147
+ return stop
148
+
149
+ function begin() {
150
+ if (stopped) return
151
+ client.connect()
152
+ me.on('topics', pass)
153
+ pass()
154
+ }
155
+
156
+ // the topics rows, read again as one changes: a handle added, gone, or with a newer epoch
157
+ function pass() {
158
+ if (passing) {
159
+ again = true
160
+ return
161
+ }
162
+ passing = (async () => {
163
+ do {
164
+ again = false
165
+ await read()
166
+ } while (again && !stopped)
167
+ })()
168
+ .catch(report)
169
+ .finally(() => (passing = null))
170
+ }
171
+
172
+ async function read() {
173
+ const { data: rows } = await me.local.store.get('topics')
174
+ const ids = new Set(rows.map((row) => row.handle))
175
+ for (const id of [...rooms.keys()]) if (!ids.has(id)) await drop(id).catch(report)
176
+ for (const row of rows) {
177
+ const room = rooms.get(row.handle)
178
+ if (!room) await add(row).catch(report)
179
+ else if (!same(room.epochs, row.epochs)) rotated(room, row)
180
+ }
181
+ }
182
+
183
+ // `since` is the last time of the service counted as brought up to date here, `seen` the last it
184
+ // sent, `due` the last another device told, `told` the last this device told, `owed` a write
185
+ // here not told yet, `heard` when a write from another device last landed, `epoch` the newest
186
+ // this device told under. A handle followed for the first time hears of nothing before
187
+ async function add(row) {
188
+ const id = row.handle
189
+ const { data } = await get(me.local.pulses, id)
190
+ const keys = keysOf(row)
191
+ const since = data?.since ?? Date.now()
192
+ const room = {
193
+ id,
194
+ type: row.type,
195
+ ...keys,
196
+ heard: data?.heard ?? 0,
197
+ told: data?.told ?? 0,
198
+ prior: data?.told ?? 0,
199
+ since,
200
+ seen: since,
201
+ due: since,
202
+ owed: !!data?.owed,
203
+ epoch: data ? data.epoch : keys.newest,
204
+ last: 0,
205
+ on: 0,
206
+ sent: 0,
207
+ check: 0,
208
+ woken: 0,
209
+ wokenOn: 0,
210
+ timer: null,
211
+ again: false,
212
+ landing: null,
213
+ later: false,
214
+ kept: Promise.resolve(),
215
+ waking: false
216
+ }
217
+ rooms.set(id, room)
218
+ byKey.set(b4a.toHex(room.keyPair.publicKey), room)
219
+ if (!data) keep(room)
220
+ if (early.delete(id)) owe(room)
221
+ // told just before the app was stopped, maybe on a connection dead unnoticed
222
+ const age = Date.now() - room.told
223
+ if (age >= 0 && age < UNSURE) unsure.add(id)
224
+ if (live()) greet(room)
225
+ }
226
+
227
+ async function drop(id) {
228
+ const room = rooms.get(id)
229
+ rooms.delete(id)
230
+ byKey.delete(b4a.toHex(room.keyPair.publicKey))
231
+ queue.delete(room)
232
+ lengths.delete(id)
233
+ clearTimeout(room.timer)
234
+ clearTimeout(room.landing)
235
+ waits.get(id)?.()
236
+ if (live()) client.unsubscribe(room.keyPair.publicKey)
237
+ await room.kept
238
+ await del(me.local.pulses, id)
239
+ }
240
+
241
+ function rotated(room, row) {
242
+ const old = room.keyPair
243
+ Object.assign(room, keysOf(row))
244
+ if (b4a.equals(old.publicKey, room.keyPair.publicKey)) return
245
+ byKey.delete(b4a.toHex(old.publicKey))
246
+ byKey.set(b4a.toHex(room.keyPair.publicKey), room)
247
+ if (!live()) return
248
+ client.unsubscribe(old.publicKey)
249
+ greet(room)
250
+ }
251
+
252
+ // what the service kept is asked first. A write owed is told at this time; one told as a
253
+ // connection died is told again as it was, so the service drops it if it had it
254
+ function greet(room) {
255
+ client.subscribe(room.keyPair.publicKey, { since: room.since + 1 })
256
+ room.prior = room.told
257
+ if (room.epoch < room.newest) retire(room)
258
+ if (room.owed) repay(room)
259
+ else if (unsure.delete(room.id)) client.announce(room.keyPair, { bump: room.told })
260
+ }
261
+
262
+ // one last time on every older key since the one this device told under, so a device still on
263
+ // it wakes, syncs and learns the newest; a device that told before tells again on the newest
264
+ function retire(room) {
265
+ const bump = Math.max(Date.now(), room.seen + 1)
266
+ for (let epoch = room.epoch; epoch < room.newest; epoch++) {
267
+ const secret = secretOf(room, epoch)
268
+ if (secret) client.announce(keyPairOf(secret), { bump })
269
+ }
270
+ room.epoch = room.newest
271
+ if (room.told) room.owed = true
272
+ keep(room)
273
+ }
274
+
275
+ // the first write in a while is told at once, the last of those after it once the window
276
+ // closes, at the time it was made. One made with no connection is kept owed and told as the
277
+ // next one opens
278
+ function wrote(id) {
279
+ const room = rooms.get(id)
280
+ if (!room) return early.add(id)
281
+ room.last = Date.now()
282
+ if (!live()) return owe(room)
283
+ if (room.timer) {
284
+ room.again = true
285
+ return
286
+ }
287
+ tell(room)
288
+ coalesce(room)
289
+ }
290
+
291
+ function coalesce(room) {
292
+ room.timer = setTimeout(() => {
293
+ room.timer = null
294
+ if (!room.again || rooms.get(room.id) !== room) return
295
+ room.again = false
296
+ if (!live()) return owe(room)
297
+ tell(room, room.last)
298
+ coalesce(room)
299
+ }, EVERY)
300
+ }
301
+
302
+ function owe(room) {
303
+ if (room.owed) return
304
+ room.owed = true
305
+ keep(room)
306
+ }
307
+
308
+ // told as a subscription opens, before the time the service kept arrives
309
+ function repay(room) {
310
+ tell(room)
311
+ room.check = connection
312
+ }
313
+
314
+ // past what the service sent, which drops a time at or below it: never past a time of this
315
+ // device's own, so a clock that was ahead does not hold the times ahead
316
+ function tell(room, at = Date.now()) {
317
+ room.told = Math.max(at, room.seen + 1)
318
+ room.on = connection
319
+ room.sent = Date.now()
320
+ room.owed = false
321
+ client.announce(room.keyPair, { bump: room.told })
322
+ keep(room)
323
+ }
324
+
325
+ // one at a time, so the row ends as the room is, and a drop deletes it after the last
326
+ function keep(room) {
327
+ const { id, heard, told, since, owed, epoch } = room
328
+ const row = { id, heard, told, since, owed, epoch }
329
+ room.kept = room.kept.then(() => set(me.local.pulses, row)).catch(report)
330
+ }
331
+
332
+ // the one place a handle is brought up to date: a write from another device landing in it, by
333
+ // a wake or any other way. The first of a window is kept and told to the app as its batch ends,
334
+ // the last as the window closes
335
+ function landed(id) {
336
+ const room = rooms.get(id)
337
+ if (!room) return
338
+ room.heard = Date.now()
339
+ room.since = Math.max(room.since, room.due)
340
+ waits.get(id)?.()
341
+ if (room.landing) {
342
+ room.later = true
343
+ return
344
+ }
345
+ room.landing = setTimeout(() => quiet(room), HEARD)
346
+ queueMicrotask(() => heard(room))
347
+ }
348
+
349
+ function quiet(room) {
350
+ room.landing = null
351
+ if (!room.later) return
352
+ room.later = false
353
+ room.landing = setTimeout(() => quiet(room), HEARD)
354
+ heard(room)
355
+ }
356
+
357
+ function flush(room) {
358
+ clearTimeout(room.landing)
359
+ room.landing = null
360
+ if (!room.later) return
361
+ room.later = false
362
+ heard(room)
363
+ }
364
+
365
+ function heard(room) {
366
+ if (rooms.get(room.id) !== room) return
367
+ keep(room)
368
+ try {
369
+ me.emit('pulse', room.id, room.heard)
370
+ } catch (err) {
371
+ report(err)
372
+ }
373
+ }
374
+
375
+ // of the handles a connection brings as due the newest REPLAYED wake: an older one waiting its
376
+ // turn gives its notice up for a newer
377
+ function admit(room) {
378
+ if (replays.has(room)) return true
379
+ if (replays.size < REPLAYED) {
380
+ replays.add(room)
381
+ return true
382
+ }
383
+ let oldest = room
384
+ for (const r of replays) if (queue.has(r) && r.due < oldest.due) oldest = r
385
+ forgo(oldest, oldest.due)
386
+ if (oldest === room) return false
387
+ queue.delete(oldest)
388
+ replays.delete(oldest)
389
+ replays.add(room)
390
+ return true
391
+ }
392
+
393
+ // a notice nobody served is counted as brought up to date, `heard` as it was: no connection
394
+ // brings it again
395
+ function forgo(room, at) {
396
+ room.since = Math.max(room.since, at)
397
+ keep(room)
398
+ }
399
+
400
+ // the newest due first, in one pass for each wake: one whose write landed as it waited leaves
401
+ function pump() {
402
+ while (waking < WAKING && !stopped) {
403
+ let room = null
404
+ for (const r of queue) {
405
+ if (r.due <= r.since) queue.delete(r)
406
+ else if (!r.waking && (!room || r.due > room.due)) room = r
407
+ }
408
+ if (!room) return
409
+ queue.delete(room)
410
+ room.woken = room.due
411
+ room.wokenOn = connection
412
+ room.waking = true
413
+ waking++
414
+ wake(room).finally(() => {
415
+ room.waking = false
416
+ waking--
417
+ pump()
418
+ })
419
+ }
420
+ }
421
+
422
+ function held(id) {
423
+ return [...me.children].some((child) => child.id === id)
424
+ }
425
+
426
+ // open, rank first, and stay open until a write from another device lands or WAIT ms pass
427
+ async function wake(room) {
428
+ const { id } = room
429
+ let end = null
430
+ let late = false
431
+ const waited = new Promise((resolve) => {
432
+ const timer = setTimeout(() => {
433
+ late = true
434
+ end()
435
+ }, WAIT)
436
+ end = () => {
437
+ clearTimeout(timer)
438
+ if (waits.get(id) === end) waits.delete(id)
439
+ resolve()
440
+ }
441
+ waits.set(id, end)
442
+ })
443
+ try {
444
+ const h = await open(me[room.type], { id })
445
+ try {
446
+ if (rooms.get(id) !== room) return
447
+ await activate(h)
448
+ await waited
449
+ if (late && rooms.get(id) === room) forgo(room, room.woken)
450
+ } finally {
451
+ await close(h)
452
+ }
453
+ } catch (err) {
454
+ // a handle left or removed meanwhile is no longer this device's
455
+ if (rooms.get(id) === room && err.code !== 'UNKNOWN') report(err)
456
+ } finally {
457
+ end()
458
+ }
459
+ }
460
+
461
+ function stop() {
462
+ if (stopped) return
463
+ stopped = true
464
+ for (const room of rooms.values()) {
465
+ clearTimeout(room.timer)
466
+ clearTimeout(room.landing)
467
+ }
468
+ for (const end of [...waits.values()]) end()
469
+ for (const off of offs) off()
470
+ me.off('topics', pass)
471
+ me.off('status', onstatus)
472
+ me.network.off('close', stop)
473
+ client.close().catch(() => {})
474
+ }
475
+ }
476
+
477
+ // the epochs a topics row holds, the newest of them and the key pair it gives
478
+ function keysOf(row) {
479
+ const entries = row.epochs ? c.decode(epochEntries, row.epochs) : []
480
+ const room = { epochs: row.epochs ?? null, encryptionKey: row.encryptionKey, entries, newest: 0 }
481
+ for (const e of entries) room.newest = Math.max(room.newest, e.epoch)
482
+ return { ...room, keyPair: keyPairOf(secretOf(room, room.newest)) }
483
+ }
484
+
485
+ // epoch 0 is the handle before its first rotation
486
+ function secretOf({ entries, encryptionKey }, epoch) {
487
+ if (epoch === 0) return encryptionKey
488
+ return entries.find((e) => e.epoch === epoch)?.entropy ?? null
489
+ }
490
+
491
+ function keyPairOf(secret) {
492
+ return crypto.keyPair(crypto.hash([NS, secret]))
493
+ }
494
+
495
+ function same(a, b) {
496
+ return a && b ? b4a.equals(a, b) : (a ?? null) === (b ?? null)
497
+ }
498
+
499
+ function decode(key) {
500
+ try {
501
+ return hid.decode(key)
502
+ } catch {
503
+ throw CeroError.INVALID('pulse takes the public key its service prints')
504
+ }
505
+ }
package/src/lib/refs.js CHANGED
@@ -1,10 +1,10 @@
1
1
  import { CeroError } from '@cero-base/core/errors'
2
2
 
3
3
  /**
4
- * @typedef {'collection' | 'single' | 'action' | 'handle'} RefKind
4
+ * @typedef {'collection' | 'single' | 'action' | 'handle' | 'lane'} RefKind
5
5
  * @typedef {import('./spec.js').RefInfo} RefInfo
6
6
  * @typedef {import('./spec.js').Spec} Spec
7
- * @typedef {import('../handle/index.js').Context | import('../local/index.js').Local} Owner
7
+ * @typedef {import('../handle/index.js').Context | import('../local/index.js').Local | import('../extensions/calls.js').Line} Owner
8
8
  */
9
9
 
10
10
  /**
@@ -14,7 +14,7 @@ export class Ref {
14
14
  /**
15
15
  * @param {Owner} handle The root, a handle or the local store the ref lives on.
16
16
  * @param {string} name Ref name as declared in the schema.
17
- * @param {string} kind Ref kind: `'collection'`, `'single'`, `'action'`, or `'handle'`.
17
+ * @param {string} kind Ref kind: `'collection'`, `'single'`, `'action'`, `'handle'`, or a line's `'lane'`.
18
18
  * @param {string | null} [schema] Fully-qualified schema id, if any.
19
19
  * @param {string | null} [type] On a ref under a handle type (`me.room.notes`), that type.
20
20
  */