@cero-base/cero 3.5.0 → 3.6.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.
@@ -0,0 +1,929 @@
1
+ import AbortController from 'bare-abort-controller'
2
+ import hid from 'hypercore-id-encoding'
3
+ import b4a from 'b4a'
4
+ import safetyCatch from 'safety-catch'
5
+
6
+ import { CeroError } from '@cero-base/core/errors'
7
+ import { can, inTurn, WRITE } from '@cero-base/core/utils'
8
+ import { Call } from '@cero-base/core/call'
9
+
10
+ import { t } from '../lib/spec.js'
11
+ import { Ref } from '../lib/refs.js'
12
+ import { LANES, muted, wire } from '../lib/line.js'
13
+ import { Media, bindings } from '../lib/media.js'
14
+ import { after, before, call, close, del, get, open, put, supports } from '../lib/operators.js'
15
+
16
+ /**
17
+ * How often a device on a call beats, how long one stays silent before it is a ghost, how long a
18
+ * call rings once a device sees it, and how old a ring may be when a device first sees it. A test
19
+ * shortens them.
20
+ */
21
+ export const durations = {
22
+ beat: 5 * 60 * 1000,
23
+ ghost: 11 * 60 * 1000,
24
+ ring: 45 * 1000,
25
+ fresh: 120 * 1000
26
+ }
27
+
28
+ // how long a quitting app waits for its leaves to reach a peer
29
+ const QUIT = 1500
30
+ // a negotiation is a handful of signals: the newest this many of each device wait for the UI
31
+ // what a device's row says of it: its microphone, its camera, its screen
32
+ const FLAGS = [...LANES, 'screen']
33
+ let dials = 0
34
+
35
+ const refs = {
36
+ calls: t.collection({
37
+ by: t.string,
38
+ rung: t.json,
39
+ denied: t.json,
40
+ ended: t.int,
41
+ endedBy: t.string,
42
+ answered: t.bool
43
+ }),
44
+ participants: t.collection({
45
+ call: t.string,
46
+ member: t.string,
47
+ audio: t.bool,
48
+ video: t.bool,
49
+ at: t.int,
50
+ key: t.string,
51
+ screen: t.bool
52
+ }),
53
+ callStart: t.action({ to: t.json, over: t.string, key: t.string, off: t.json }),
54
+ callJoin: t.action({ call: t.string, to: t.json, key: t.string, off: t.json }),
55
+ callLeave: t.action({}),
56
+ callEnd: t.action({ call: t.string }),
57
+ callDeny: t.action({ call: t.string, reason: t.string }),
58
+ callBeat: t.action({}),
59
+ callLane: t.action({ lane: t.string, on: t.bool })
60
+ }
61
+
62
+ const rings = t.collection({
63
+ type: t.string,
64
+ name: t.string,
65
+ by: t.string,
66
+ at: t.int,
67
+ until: t.int
68
+ })
69
+
70
+ // a room this device holds a seat in on its call, as last seen here: a crash leaves it listed
71
+ const lines = t.collection({
72
+ type: t.string,
73
+ name: t.string
74
+ })
75
+
76
+ /**
77
+ * Calls in the app's handles: who is on one, ringing the members it names, the media between them,
78
+ * and the verbs `dial`, `end`, `mute`, `unmute`, `share`, `unshare`, and `deny` on a ring. Every handle type has them, or the `types` named.
79
+ * The rows change only through the actions it declares, under rules every device runs at apply.
80
+ *
81
+ * @param {{ types?: string[] }} [opts]
82
+ * @returns {import('./index.js').Extension}
83
+ */
84
+ export function calls({ types } = {}) {
85
+ return {
86
+ name: 'calls',
87
+ schema(names) {
88
+ const unknown = types?.find((type) => !names.includes(type))
89
+ if (unknown) throw CeroError.INVALID(`calls: '${unknown}' is not a handle type`)
90
+ const typed = Object.fromEntries((types ?? names).map((type) => [type, refs]))
91
+ return { ...typed, local: { rings, lines } }
92
+ },
93
+ setup(me) {
94
+ const handles = me.spec.handles ?? {}
95
+ const typed = Object.keys(handles).filter((type) => handles[type].meta.refs.callStart)
96
+ for (const type of typed) rules(me[type])
97
+ const service = (me._calls = new Calls(me, typed))
98
+ return () => service.close()
99
+ }
100
+ }
101
+ }
102
+
103
+ function rules(room) {
104
+ const refuse = () => {
105
+ throw CeroError.INVALID('a call is written by cero.dial, cero.mute, cero.end and cero.close')
106
+ }
107
+ before(room.calls, refuse)
108
+ before(room.participants, refuse)
109
+ // before the change lands, while the member who leaves may still write
110
+ before(room.members, gone)
111
+ before(room.devices, gone)
112
+ after(room.callStart, start)
113
+ after(room.callJoin, join)
114
+ after(room.callLeave, leave)
115
+ after(room.callEnd, end)
116
+ after(room.callDeny, deny)
117
+ after(room.callBeat, beat)
118
+ after(room.callLane, lane)
119
+ }
120
+
121
+ // the device is the op's writer, never its data; one rule alone decides on the op's time
122
+ async function start(ctx) {
123
+ const { row, memberId, device, ts, get, put, set, del } = ctx
124
+ const to = ids(row.to)
125
+ keyed(row.key)
126
+ const { data: rows } = await get('participants')
127
+ let open = rows[0]?.call ?? null
128
+ // the dialing device judged it dead on its clock: it ends where its op's time agrees for every row
129
+ if (open && row.over === open && rows.every((r) => ts - r.at >= durations.ghost)) {
130
+ for (const r of rows) await del('participants', r.id)
131
+ await set('calls', { id: open, ended: Math.max(...rows.map((r) => r.at)), endedBy: null })
132
+ open = null
133
+ }
134
+ // two that start at once end on one call, and so does a start over a call that is going
135
+ if (open) return enter(ctx, open, to)
136
+ const named = to ?? (await get('members')).data.filter((m) => can(m.role, WRITE)).map((m) => m.id)
137
+ const rung = ringing({}, named, memberId, ts)
138
+ const fresh = { by: memberId, rung, denied: {}, ended: 0, endedBy: null, answered: false }
139
+ const { data: started } = await put('calls', fresh)
140
+ await put('participants', seat(device, started.id, memberId, ts, row.key, down(row.off)))
141
+ }
142
+
143
+ async function join(ctx) {
144
+ const { row, get } = ctx
145
+ const to = ids(row.to)
146
+ keyed(row.key)
147
+ const { id } = await meant(get, row.call)
148
+ // an answer that lands after the call ended starts nothing
149
+ if (!id) throw CeroError.INVALID('the call ended')
150
+ await enter(ctx, id, to)
151
+ }
152
+
153
+ // the call a write means: the one going, when it names it or one that never was. A call with no
154
+ // row never was one: its start folded into another made at once, and that one is the call
155
+ async function meant(get, named) {
156
+ const { data: rows } = await get('participants')
157
+ const id = rows[0]?.call
158
+ if (!id || (id !== named && (await get('calls', named)).data)) return { rows }
159
+ return { id, rows }
160
+ }
161
+
162
+ async function enter({ row, memberId, device, ts, get, put, set }, id, to) {
163
+ const { data: going } = await get('calls', id)
164
+ const { data: mine } = await get('participants', device)
165
+ const denied = { ...going.denied }
166
+ for (const member of to ?? []) delete denied[member]
167
+ const rung = ringing(going.rung, to ?? [], memberId, ts)
168
+ const answered = going.answered || memberId !== going.by
169
+ if (to?.length || answered !== going.answered) {
170
+ await set('calls', { id, rung, denied, answered })
171
+ }
172
+ const off = down(row.off)
173
+ // back on the call it is on, a device keeps its flags: a lane its stream has off goes off, none on
174
+ const dark = Object.fromEntries(off.map((lane) => [lane, false]))
175
+ if (mine?.call === id) await set('participants', { id: device, at: ts, ...dark })
176
+ else await put('participants', seat(device, id, memberId, ts, row.key, off))
177
+ }
178
+
179
+ // the lanes a device starts with off
180
+ function down(off) {
181
+ if (off == null) return []
182
+ if (!Array.isArray(off) || !off.every((lane) => LANES.includes(lane))) {
183
+ throw CeroError.INVALID(`off takes ${LANES.join(' or ')}`)
184
+ }
185
+ return off
186
+ }
187
+
188
+ async function leave({ memberId, device, ts, get, set, del }) {
189
+ const { data: rows } = await get('participants')
190
+ const mine = rows.find((r) => r.id === device)
191
+ if (!mine) return
192
+ await del('participants', device)
193
+ if (rows.length === 1) await set('calls', { id: mine.call, ended: ts, endedBy: memberId })
194
+ }
195
+
196
+ // the call its device is on, whichever its view named: two that started at once are one call
197
+ async function end({ row, memberId, device, ts, get, set, del }) {
198
+ const { data: rows } = await get('participants')
199
+ const mine = rows.find((r) => r.id === device)
200
+ if (!mine) {
201
+ if (rows[0]?.call === row.call) throw CeroError.INVALID('a call is ended from a device on it')
202
+ return
203
+ }
204
+ for (const r of rows) await del('participants', r.id)
205
+ await set('calls', { id: mine.call, ended: ts, endedBy: memberId })
206
+ }
207
+
208
+ async function deny({ row, memberId, ts, get, set, del }) {
209
+ const { id, rows } = await meant(get, row.call)
210
+ if (!id) return
211
+ const { data: going } = await get('calls', id)
212
+ if (!going.rung?.[memberId]) {
213
+ // a ring that folded into a call that never rang this member turns nothing down
214
+ if (id !== row.call) return
215
+ throw CeroError.INVALID('the call does not ring this member')
216
+ }
217
+ const denied = { ...going.denied, [memberId]: row.reason ?? '' }
218
+ // turned down by every member it rang before anyone answered, it is over
219
+ const over = !going.answered && Object.keys(going.rung).every((member) => member in denied)
220
+ if (over) for (const r of rows) await del('participants', r.id)
221
+ await set('calls', { id, denied, ...(over && { ended: ts, endedBy: memberId }) })
222
+ }
223
+
224
+ async function beat({ device, ts, get, set }) {
225
+ const { data: mine } = await get('participants', device)
226
+ if (mine) await set('participants', { id: device, at: ts })
227
+ }
228
+
229
+ // a device's microphone, camera or screen, on or off: its row says it to every device
230
+ async function lane({ row, device, ts, get, set }) {
231
+ if (!FLAGS.includes(row.lane)) throw CeroError.INVALID(`a lane is ${FLAGS.join(', ')}`)
232
+ const { data: mine } = await get('participants', device)
233
+ if (mine) await set('participants', { id: device, [row.lane]: row.on, at: ts })
234
+ }
235
+
236
+ // a member out of the room or made a reader, or a device out of it, is off the call
237
+ async function gone({ op, name, id, row, memberId, ts, get, set, del }) {
238
+ const out = op === 'del' || (name === 'members' && op === 'set' && !can(row.role, WRITE))
239
+ if (!out) return
240
+ const { data: rows } = await get('participants')
241
+ const off = rows.filter((r) => r.member === id || r.id === id)
242
+ for (const r of off) await del('participants', r.id)
243
+ if (off.length && off.length === rows.length) {
244
+ await set('calls', { id: rows[0].call, ended: ts, endedBy: memberId })
245
+ }
246
+ }
247
+
248
+ function ids(to) {
249
+ if (to == null) return null
250
+ if (!Array.isArray(to) || !to.every((id) => typeof id === 'string')) {
251
+ throw CeroError.INVALID('to takes member ids')
252
+ }
253
+ return to
254
+ }
255
+
256
+ // the other devices dial a seat's key: one that is no key would stop each of them
257
+ function keyed(key) {
258
+ if (!key) return
259
+ try {
260
+ hid.decode(key)
261
+ } catch {
262
+ throw CeroError.INVALID('a call key is a 32-byte key')
263
+ }
264
+ }
265
+
266
+ function ringing(rung, members, by, at) {
267
+ const out = { ...rung }
268
+ for (const member of members) if (member !== by) out[member] = { by, at }
269
+ return out
270
+ }
271
+
272
+ function seat(device, call, member, ts, key, off) {
273
+ const lanes = { audio: !off.includes('audio'), video: !off.includes('video'), screen: false }
274
+ return { id: device, call, member, ...lanes, at: ts, key: key || null }
275
+ }
276
+
277
+ function ghost(row, now) {
278
+ return now - row.at >= durations.ghost
279
+ }
280
+
281
+ /**
282
+ * This device's calls: one line per room, and the rings of the rooms open here.
283
+ */
284
+ export class Calls {
285
+ /**
286
+ * @param {import('../handle/index.js').Context} me
287
+ * @param {string[]} types The handle types with calls.
288
+ */
289
+ constructor(me, types) {
290
+ this.me = me
291
+ this.types = new Set(types)
292
+ // this device's clock, which every local judgement reads
293
+ this.now = () => Date.now()
294
+ /** @type {Map<string, Promise<Line>>} */
295
+ this.lines = new Map()
296
+ /** @private */
297
+ this._closed = false
298
+ /** @private */
299
+ this._timer = null
300
+ /** @private */
301
+ this._rings = null
302
+ // by room: the ring this device saw and when it stops ringing, on this device's clock
303
+ /** @private @type {Map<string, { key: string, until: number }>} */
304
+ this._seen = new Map()
305
+ // by room: the transport of a line that closed, still letting its key pair go
306
+ /** @private @type {Map<string, Promise<void>>} */
307
+ this._hangups = new Map()
308
+ // by room: one held open here because a crash left it listed, until its seat goes
309
+ /** @private @type {Map<string, import('../handle/index.js').Context>} */
310
+ this._kept = new Map()
311
+ /** @private */
312
+ this._onhandle = (room) => this.types.has(room.type) && this._follow(room)
313
+ me.on('handle', this._onhandle)
314
+ this._expire()
315
+ this._queue(() => this._resume())
316
+ }
317
+
318
+ // a room a crash left listed is opened here, so the list follows its call with no room opened by the app
319
+ /** @private */
320
+ async _resume() {
321
+ await this.me.ready()
322
+ const { data } = await get(this.me.local.lines)
323
+ for (const { id, type } of data) {
324
+ if (this._closed) return
325
+ try {
326
+ this._kept.set(id, await open(this.me[type], { id }))
327
+ } catch (err) {
328
+ if (err.code !== 'UNKNOWN') throw err
329
+ // left for good while away
330
+ await del(this.me.local.lines, id)
331
+ }
332
+ }
333
+ }
334
+
335
+ // the room is listed while this device holds a seat on its call
336
+ /** @private */
337
+ async _mark(room) {
338
+ const key = room.store.writerKey
339
+ const seat = key && (await get(room.participants, hid.encode(key))).data
340
+ const { data: was } = await get(this.me.local.lines, room.id)
341
+ if (seat) {
342
+ const { data: entry } = await get(this.me.handles, room.id)
343
+ const name = entry?.name ?? null
344
+ if (was?.name !== name || !was) {
345
+ await put(this.me.local.lines, { id: room.id, type: room.type, name })
346
+ }
347
+ return
348
+ }
349
+ if (was) await del(this.me.local.lines, room.id)
350
+ const kept = this._kept.get(room.id)
351
+ if (kept && this._kept.delete(room.id)) await close(kept)
352
+ }
353
+
354
+ /** @private */
355
+ async _unlist(id) {
356
+ const { data: was } = await get(this.me.local.lines, id)
357
+ if (was) await del(this.me.local.lines, id)
358
+ }
359
+
360
+ /**
361
+ * @param {import('../handle/index.js').Context} room
362
+ * @param {{ to?: string[] | null, stream?: MediaStream | null }} [opts]
363
+ * @returns {Promise<Line>}
364
+ */
365
+ async dial(room, { to = null, stream = null, off = muted(stream) } = {}) {
366
+ if (!room.parent || !this.types.has(room.type)) {
367
+ throw CeroError.INVALID('dial takes a handle of a type with calls')
368
+ }
369
+ if (to !== null) {
370
+ if (!Array.isArray(to) || !to.every((id) => typeof id === 'string')) {
371
+ throw CeroError.INVALID('to takes member ids')
372
+ }
373
+ for (const id of to) {
374
+ if (!(await get(room.members, id)).data) throw CeroError.UNKNOWN('member', id)
375
+ }
376
+ }
377
+ const was = this.lines.get(room.id)
378
+ const line = was && (await was.catch(() => null))
379
+ if (line && !line.closed) {
380
+ if (to) await line._add(to)
381
+ return line
382
+ }
383
+ if (this.lines.get(room.id) !== was) return this.dial(room, { to, stream, off })
384
+ const opening = this._open(room, to, stream, line, off)
385
+ this.lines.set(room.id, opening)
386
+ opening.catch(() => this.lines.get(room.id) === opening && this.lines.delete(room.id))
387
+ return opening
388
+ }
389
+
390
+ // the ring a member turns down: her devices stop ringing, the call goes on for the others
391
+ /** @param {import('../handle/index.js').Context} room @param {string} reason */
392
+ async deny(room, reason) {
393
+ const { data: rows } = await get(room.participants)
394
+ if (rows.length) await call(room.callDeny, { call: rows[0].call, reason })
395
+ }
396
+
397
+ // the room's line, or every line on the root, leaves before it closes
398
+ /** @param {import('../handle/index.js').Context} ctx */
399
+ async hangup(ctx) {
400
+ const rooms = []
401
+ for (const id of ctx.parent ? [ctx.id] : [...this.lines.keys()]) {
402
+ const line = await this.lines.get(id)?.catch(() => null)
403
+ if (!line || line.closed) continue
404
+ rooms.push(line._room)
405
+ await line.close().catch((err) => this.me._onerror(err))
406
+ }
407
+ if (ctx.parent || !rooms.length) return
408
+ // the app quits: without its leaves, the others see it until it is a ghost
409
+ const held = rooms.map((room) => room.store.held())
410
+ await within(held, QUIT)
411
+ }
412
+
413
+ close() {
414
+ this._closed = true
415
+ clearTimeout(this._timer)
416
+ this.me.off('handle', this._onhandle)
417
+ }
418
+
419
+ /** @private */
420
+ _gone(line, hangup) {
421
+ const id = line._room.id
422
+ this.lines.get(id)?.then(
423
+ (open) => open === line && this.lines.delete(id),
424
+ () => {}
425
+ )
426
+ const done = hangup.then(() => this._hangups.get(id) === done && this._hangups.delete(id))
427
+ this._hangups.set(id, done)
428
+ }
429
+
430
+ // decided on this device's clock: a call someone is heard on is joined, any other is started anew
431
+ /** @private */
432
+ async _open(room, to, stream, last, off) {
433
+ await last?._closing?.catch(() => {})
434
+ // a key pair holds one transport at a time
435
+ await this._hangups.get(room.id)
436
+ const device = hid.encode(room.store.writerKey)
437
+ // the same on every dial of this room on this device, a crash and rejoin too
438
+ const keyPair = await room.store.store.createKeyPair(`cero/call/${room.id}`)
439
+ const key = hid.encode(keyPair.publicKey)
440
+ const read = async () => {
441
+ const { data: rows } = await get(room.participants)
442
+ const now = this.now()
443
+ const live = rows.filter((r) => r.id !== device && !ghost(r, now))
444
+ return { rows, live, mine: rows.find((r) => r.id === device) }
445
+ }
446
+ let { rows, live, mine } = await read()
447
+ if (mine && !live.length) {
448
+ // back from a crash with nobody heard on its call, it leaves that call first
449
+ await call(room.callLeave)
450
+ ;({ rows, live, mine } = await read())
451
+ }
452
+ // what starts off rides with the start or the join where the room has that field, and follows
453
+ // it where it does not yet
454
+ const rides = off.length > 0 && (await supports(room.callStart, 'off'))
455
+ const dark = rides ? { off } : {}
456
+ if (!live.length) await call(room.callStart, { to, over: rows[0]?.call ?? null, key, ...dark })
457
+ else await call(room.callJoin, { call: live[0].call, to, key, ...dark })
458
+ if (!rides) for (const lane of off) await call(room.callLane, { lane, on: false })
459
+ // back on its seat with a new line, which shares no screen: one its row still shows is taken down
460
+ if (mine?.screen) await call(room.callLane, { lane: 'screen', on: false })
461
+ return new Line(this, room, device, stream, keyPair)
462
+ }
463
+
464
+ /** @private */
465
+ _follow(room) {
466
+ const step = async () => {
467
+ await this._ring(room)
468
+ await this._mark(room)
469
+ }
470
+ const ring = () => this._queue(step)
471
+ room._onclose(room.store.onUpdate('participants', ring))
472
+ ring()
473
+ }
474
+
475
+ /** @private */
476
+ _queue(fn) {
477
+ // a step under way as the app closes finds its stores closed: that is no error to report
478
+ this._rings = inTurn(this._rings, fn).catch((err) => {
479
+ if (err.code !== 'CLOSED' && !this._closed) this.me._onerror(err)
480
+ })
481
+ }
482
+
483
+ // a call rings this member's devices while its ringer is on it and none of them answered or
484
+ // turned it down, for the ring time from when this device first saw it
485
+ /** @private */
486
+ async _ring(room) {
487
+ const me = this.me.identity.id
488
+ const now = this.now()
489
+ const { data: rows } = await get(room.participants)
490
+ const { data: going } = rows.length ? await get(room.calls, rows[0].call) : { data: null }
491
+ const rang = going?.rung?.[me]
492
+ let until = 0
493
+ if (
494
+ rang &&
495
+ !(me in (going.denied ?? {})) &&
496
+ !rows.some((r) => r.member === me) &&
497
+ rows.some((r) => r.member === rang.by)
498
+ ) {
499
+ const key = `${going.id}/${rang.at}`
500
+ if (this._seen.get(room.id)?.key !== key) {
501
+ const fresh = now - rang.at < durations.fresh
502
+ this._seen.set(room.id, { key, until: fresh ? now + durations.ring : 0 })
503
+ }
504
+ until = this._seen.get(room.id).until
505
+ }
506
+ const { data: was } = await get(this.me.local.rings, room.id)
507
+ if (until <= now) {
508
+ if (was) await del(this.me.local.rings, room.id)
509
+ return
510
+ }
511
+ const { data: entry } = await get(this.me.handles, room.id)
512
+ const name = entry?.name ?? null
513
+ const ring = { id: room.id, type: room.type, name, by: rang.by, at: rang.at, until }
514
+ if (was && Object.keys(ring).every((k) => was[k] === ring[k])) return
515
+ await put(this.me.local.rings, ring)
516
+ this._expire()
517
+ }
518
+
519
+ // a ring goes at its end, whichever room it is of and whether it is open here
520
+ /** @private */
521
+ _expire() {
522
+ this._queue(async () => {
523
+ clearTimeout(this._timer)
524
+ const { data } = await get(this.me.local.rings)
525
+ const now = this.now()
526
+ let next = Infinity
527
+ for (const ring of data) {
528
+ if (ring.until <= now) await del(this.me.local.rings, ring.id)
529
+ else next = Math.min(next, ring.until)
530
+ }
531
+ if (next !== Infinity && !this._closed) {
532
+ this._timer = setTimeout(() => this._expire(), next - now)
533
+ }
534
+ })
535
+ }
536
+ }
537
+
538
+ /**
539
+ * This device on a room's call. Its state is the room's rows; it closes when its own row goes. It
540
+ * holds a connection to each other device on the call, and with WebRTC here, the media over them.
541
+ */
542
+ export class Line {
543
+ /**
544
+ * @param {Calls} calls
545
+ * @param {import('../handle/index.js').Context} room
546
+ * @param {string} device This device's id in the room, its `participants` row.
547
+ * @param {MediaStream | null} stream
548
+ * @param {{ publicKey: Uint8Array, secretKey: Uint8Array }} keyPair This device's key pair on the room's calls.
549
+ */
550
+ constructor(calls, room, device, stream, keyPair) {
551
+ // one per dial: what is left of a line that closed never reaches the next one in its room
552
+ this.id = `${room.id}/${device}/${++dials}`
553
+ this.audio = new Ref(this, 'audio', 'lane')
554
+ this.video = new Ref(this, 'video', 'lane')
555
+ this.screen = new Ref(this, 'screen', 'lane')
556
+ this.spec = wire(room.spec)
557
+ const { refs } = this.spec.meta
558
+ this.peers = new Ref(this, 'peers', 'collection', refs.peers.schema)
559
+ this.closed = false
560
+ /** @private */
561
+ this._calls = calls
562
+ /** @private */
563
+ this._room = room
564
+ /** @private */
565
+ this._device = device
566
+ /** @private */
567
+ this._stream = stream
568
+ /** @private */
569
+ this._ac = new AbortController()
570
+ /** @private */
571
+ this._owned = new Set()
572
+ /** @private */
573
+ this._fns = new Set()
574
+ /** @private */
575
+ this._feeds = new Set()
576
+ // what a UI reads beside the peers: this device's lanes, and for its WebRTC each device's port
577
+ /** @private */
578
+ this._lanes = new Ref(this, '_lanes', 'single', refs._lanes.schema)
579
+ /** @private */
580
+ this._ports = new Ref(this, '_ports', 'collection', refs._ports.schema)
581
+ // a lane reads as on or off, as this device's row shows it
582
+ const lane = (name) => ({
583
+ get: async () => ({ data: (await this._rows()).mine?.[name] ?? null }),
584
+ watch: (fn) => this._onPeers(fn)
585
+ })
586
+ /** @private */
587
+ this._live = {
588
+ peers: { get: () => this._peers(), watch: (fn) => this._onPeers(fn) },
589
+ audio: lane('audio'),
590
+ video: lane('video'),
591
+ screen: lane('screen'),
592
+ _lanes: { get: () => this._own(), watch: (fn) => this._onPeers(fn) },
593
+ _ports: { get: () => ({ data: this._feed() }), watch: (fn) => this._onFeed(fn) }
594
+ }
595
+ /** @private */
596
+ this._key = hid.encode(keyPair.publicKey)
597
+ // the other devices, call key in hex to device id
598
+ /** @private @type {Map<string, string>} */
599
+ this._keys = new Map()
600
+ // the devices this one has reached since they came on the call
601
+ /** @private @type {Set<string>} */
602
+ this._met = new Set()
603
+ // the description each device sent last, and the port it came on
604
+ /** @private @type {Map<string, { port: number, sent: { seq: number } & import('../lib/media.js').Signal }>} */
605
+ this._signals = new Map()
606
+ /** @private */
607
+ this._seq = 0
608
+ // this device's lanes as its row shows them, which a UI that starts over takes its mutes from
609
+ /** @private @type {import('../lib/media.js').Bridge['self']} */
610
+ this._mine = null
611
+ const { dht, relayThrough } = room.network
612
+ /** @private */
613
+ this._call = new Call({ dht, keyPair, id: room.id, relayThrough })
614
+ this._call.on('peer', (key) => this._moved(key))
615
+ this._call.on('peer-close', (key) => this._moved(key))
616
+ this._call.on('signal', (key, data) => this._heard(key, data))
617
+ this._call.ready().catch((err) => this._report(err))
618
+ const webrtc = bindings(calls.me._opts.webrtc)
619
+ /** @private */
620
+ this._media = webrtc
621
+ ? new Media(webrtc, {
622
+ send: (id, port, data) => this._signal(id, port, data),
623
+ onchange: () => this._changed(),
624
+ onerror: (err) => this._report(err)
625
+ })
626
+ : null
627
+ this._media?.share(stream)
628
+ /** @private */
629
+ this._sleeping = null
630
+ /** @private @type {Promise<void> | null} */
631
+ this._closing = null
632
+ /** @private */
633
+ this._updating = null
634
+ /** @private */
635
+ this._beat = null
636
+ /** @private */
637
+ this._beating = false
638
+ /** @private */
639
+ this._ghost = null
640
+ const me = calls.me
641
+ // each status is the app going to the background or back
642
+ const status = () => {
643
+ const asleep = me._sus.suspended
644
+ const step = () => (asleep ? this._call.suspend() : this._call.resume())
645
+ this._sleeping = inTurn(this._sleeping, step).catch((err) => this._report(err))
646
+ if (!asleep) this._update()
647
+ }
648
+ me.on('status', status)
649
+ /** @private */
650
+ this._offs = [
651
+ room.store.onUpdate('participants', () => this._update()),
652
+ () => me.off('status', status)
653
+ ]
654
+ // the room stays open while the call goes
655
+ room._hold()
656
+ this._schedule()
657
+ this._update()
658
+ }
659
+
660
+ /** @returns {AbortSignal} fires when the line closes */
661
+ get signal() {
662
+ return this._ac.signal
663
+ }
664
+
665
+ /**
666
+ * Tie a watch to the line: it ends when the line closes.
667
+ *
668
+ * @template {import('streamx').Readable} T
669
+ * @param {T} stream
670
+ * @returns {T}
671
+ */
672
+ own(stream) {
673
+ if (this.closed) {
674
+ stream.push(null)
675
+ return stream
676
+ }
677
+ this._owned.add(stream)
678
+ stream.once('close', () => this._owned.delete(stream))
679
+ return stream
680
+ }
681
+
682
+ /** Leave the call: it goes on for the others, and ends with the last device on it. */
683
+ close() {
684
+ return (this._closing ??= this._shut(true))
685
+ }
686
+
687
+ /** @private */
688
+ async _finish() {
689
+ const { mine } = await this._rows()
690
+ if (!mine) throw CeroError.CLOSED('Line')
691
+ await call(this._room.callEnd, { call: mine.call })
692
+ }
693
+
694
+ // a dial with `to` on a line open already rings them too
695
+ /** @private */
696
+ async _add(to) {
697
+ const { mine } = await this._rows()
698
+ if (!mine) throw CeroError.CLOSED('Line')
699
+ await call(this._room.callJoin, { call: mine.call, to, key: this._key })
700
+ }
701
+
702
+ // the local tracks at once, then the flag every device sees
703
+ /** @private */
704
+ async _lane(lane, on) {
705
+ if (this.closed) throw CeroError.CLOSED('Line')
706
+ this._media?.lane(lane, on)
707
+ await call(this._room.callLane, { lane, on })
708
+ }
709
+
710
+ /** @private */
711
+ async _share(kind, stream) {
712
+ if (this.closed) throw CeroError.CLOSED('Line')
713
+ if (kind !== 'screen') return this._media?.share(stream)
714
+ // with no WebRTC here there is no screen to show; taking one down is for any side to say
715
+ if (!this._media && stream) return
716
+ this._media?.present(stream)
717
+ await call(this._room.callLane, { lane: 'screen', on: !!stream })
718
+ }
719
+
720
+ // from the UI's WebRTC, for the device on that port: one that moved on since drops it
721
+ /** @private */
722
+ _signal(id, port, data) {
723
+ const key = this._at(id, port)
724
+ if (key) this._call.signal(key, data)
725
+ }
726
+
727
+ /** @private */
728
+ _at(id, port) {
729
+ for (const [key, peer] of this._keys) {
730
+ if (peer === id && this._call.peers.get(key) === port) return key
731
+ }
732
+ return null
733
+ }
734
+
735
+ /** @private */
736
+ _drop() {
737
+ return (this._closing ??= this._shut(false))
738
+ }
739
+
740
+ /** @private */
741
+ async _shut(leave) {
742
+ this.closed = true
743
+ clearTimeout(this._beat)
744
+ clearTimeout(this._ghost)
745
+ for (const off of this._offs) off()
746
+ this._media?.close()
747
+ try {
748
+ if (leave) {
749
+ await call(this._room.callLeave)
750
+ // unlisted with the leave: an app that quits may close before the room's rows are followed
751
+ await this._calls._unlist(this._room.id)
752
+ }
753
+ } finally {
754
+ this._fns.clear()
755
+ this._feeds.clear()
756
+ for (const stream of [...this._owned]) stream.push(null)
757
+ this._ac.abort()
758
+ // not awaited: offline it can take long, and only the next line on this key pair needs it done
759
+ this._calls._gone(this, this._call.close().catch(safetyCatch))
760
+ if (!this._room.closing) this._room.close().catch((err) => this._calls.me._onerror(err))
761
+ }
762
+ }
763
+
764
+ /** @private */
765
+ async _rows() {
766
+ if (this.closed) return { mine: null, others: [] }
767
+ const { data: rows } = await get(this._room.participants)
768
+ const mine = rows.find((r) => r.id === this._device) ?? null
769
+ const others = mine ? rows.filter((r) => r.id !== this._device && r.call === mine.call) : []
770
+ return { mine, others }
771
+ }
772
+
773
+ /** @private */
774
+ async _peers() {
775
+ const now = this._calls.now()
776
+ const { others } = await this._rows()
777
+ const data = others.filter((r) => !ghost(r, now)).map((r) => this._entry(r))
778
+ return { data, total: data.length, size: data.length }
779
+ }
780
+
781
+ /** @private */
782
+ async _own() {
783
+ const { mine } = await this._rows()
784
+ return { data: mine && lanes(mine) }
785
+ }
786
+
787
+ // with no WebRTC here, connected is the connection to it
788
+ /** @private */
789
+ _entry({ id, member, audio, video, screen, key }) {
790
+ const connected = !!key && this._call.peers.has(hex(key))
791
+ const media = this._media?.entry(id, screen) ?? { stream: null, screen: null, connected }
792
+ // reached before and not now: it is coming back, not arriving
793
+ const reconnecting = !connected && this._met.has(id)
794
+ return { id, member, audio, video, sharing: screen, reconnecting, ...media }
795
+ }
796
+
797
+ /** @private */
798
+ _onPeers(fn) {
799
+ this._fns.add(fn)
800
+ return () => this._fns.delete(fn)
801
+ }
802
+
803
+ /** @private */
804
+ _onFeed(fn) {
805
+ this._feeds.add(fn)
806
+ return () => this._feeds.delete(fn)
807
+ }
808
+
809
+ /** @private */
810
+ _changed() {
811
+ for (const fn of this._fns) fn()
812
+ }
813
+
814
+ // the port of each device reached, with the description it sent last on it
815
+ /** @private */
816
+ _feed() {
817
+ const rows = []
818
+ for (const [key, port] of this._call.peers) {
819
+ const id = this._keys.get(key)
820
+ if (id) rows.push({ id, port, ...this._signals.get(id)?.sent })
821
+ }
822
+ return rows
823
+ }
824
+
825
+ /** @private */
826
+ _tell() {
827
+ this._media?.update({ self: this._mine, peers: this._feed() })
828
+ for (const fn of this._feeds) fn()
829
+ this._changed()
830
+ }
831
+
832
+ // a device's port opened, moved or closed: what it sent on the one before is moot
833
+ /** @private */
834
+ _moved(key) {
835
+ const id = this._keys.get(key)
836
+ const port = this._call.peers.get(key)
837
+ if (id && port) this._met.add(id)
838
+ if (this._signals.get(id)?.port !== port) this._signals.delete(id)
839
+ this._tell()
840
+ }
841
+
842
+ /** @private */
843
+ _heard(key, data) {
844
+ const id = this._keys.get(key)
845
+ if (!id) return
846
+ const port = this._call.peers.get(key)
847
+ // a newer offer starts that connection over, and a connection takes one answer: the last is enough
848
+ this._signals.set(id, { port, sent: { seq: ++this._seq, ...data } })
849
+ this._tell()
850
+ }
851
+
852
+ // the rows moved, the app came back, or a peer turned ghost on this device's clock
853
+ /** @private */
854
+ _update() {
855
+ const run = async () => {
856
+ if (this.closed) return
857
+ const { mine, others } = await this._rows()
858
+ // closed while its rows were read: no timer is armed past its close
859
+ if (this.closed) return
860
+ if (!mine) return this._drop()
861
+ const now = this._calls.now()
862
+ // a key two seats claim, or this device's own, is held for neither: whose it is cannot be told
863
+ const claims = new Map([[hex(this._key), 1]])
864
+ const seats = others.filter((r) => !ghost(r, now) && r.key)
865
+ for (const r of seats) claims.set(hex(r.key), (claims.get(hex(r.key)) ?? 0) + 1)
866
+ const live = seats.filter((r) => claims.get(hex(r.key)) === 1)
867
+ this._keys = new Map(live.map((r) => [hex(r.key), r.id]))
868
+ const held = new Set(this._keys.values())
869
+ for (const id of this._met) if (!held.has(id)) this._met.delete(id)
870
+ // what a device sent goes with it: back on the same port, it starts from nothing
871
+ for (const id of this._signals.keys()) if (!held.has(id)) this._signals.delete(id)
872
+ this._mine = lanes(mine)
873
+ this._call.set(live.map((r) => r.key))
874
+ this._tell()
875
+ // a row a sleep or a crash left stale is beaten at once
876
+ if (now - mine.at >= durations.beat) this._pulse()
877
+ clearTimeout(this._ghost)
878
+ const due = others.filter((r) => !ghost(r, now)).map((r) => r.at + durations.ghost - now)
879
+ if (due.length) this._ghost = setTimeout(() => this._update(), Math.min(...due))
880
+ }
881
+ this._updating = inTurn(this._updating, run).catch((err) => this._report(err))
882
+ }
883
+
884
+ /** @private */
885
+ _schedule() {
886
+ clearTimeout(this._beat)
887
+ this._beat = setTimeout(() => this._pulse(), durations.beat)
888
+ }
889
+
890
+ // one beat at a time, none while the app is in the background
891
+ /** @private */
892
+ async _pulse() {
893
+ if (this._beating || this.closed) return
894
+ if (!this._calls.me._sus.suspended) {
895
+ this._beating = true
896
+ try {
897
+ await call(this._room.callBeat)
898
+ } catch (err) {
899
+ this._report(err)
900
+ } finally {
901
+ this._beating = false
902
+ }
903
+ }
904
+ if (!this.closed) this._schedule()
905
+ }
906
+
907
+ /** @private */
908
+ _report(err) {
909
+ if (!this.closed) this._calls.me._onerror(err)
910
+ }
911
+ }
912
+
913
+ function hex(key) {
914
+ return b4a.toString(hid.decode(key), 'hex')
915
+ }
916
+
917
+ function lanes({ id, audio, video, screen }) {
918
+ return { id, audio, video, screen }
919
+ }
920
+
921
+ function within(promises, ms) {
922
+ return new Promise((resolve) => {
923
+ const timer = setTimeout(resolve, ms)
924
+ Promise.allSettled(promises).then(() => {
925
+ clearTimeout(timer)
926
+ resolve()
927
+ })
928
+ })
929
+ }