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