// talk-link.mjs — a window's link to the server while it presents // (spec §6, "Moving through the talk"). Shared by the presenter window // and the slide window. // // The window moves at once, from what it holds, and then tells the // link. The link tells the server, and decides which of the server's // positions the window should take: // // - Presses go to the server one at a time, in order, each with its own // id, so a press sent twice counts once (presenting_position.go). // - While a press is unanswered, the server's positions (its answers // and the stream's events) are recorded but not applied. When the // queue empties, the newest is applied if its seq is higher than the // last applied and it differs from where the window stands. // - A send that fails or takes over 3 seconds marks the link offline. // Unanswered presses are dropped: the position they reached is kept, // and the server is told it on reconnecting. // - On reconnecting, a window that pressed while offline (or lost a // press) sends resume with where it stands, black screen included; // one that did not takes the server's position. // - The talk's timer comes with every position (timerAt, Unix ms, or // null while it waits for a press), and is taken from the newest one // at the same moment, whether or not the window moves: another // window's first press starts it here, and a reset there resets it. // - Every command carries the link's id and its number, rising. The // server applies a link's command only if its number is above every // one it has applied, so a press given up on cannot reach the talk // after the resume that replaced it (presenting_position.go). // // post(fields) sends one press and resolves with the server's answer, // {slide, step, mode, black, seq, deckSeq, timerAt}. stream({open, error, // position}) starts hearing the server's positions in the same shape // and returns a function that stops. now() is the time in ms, and // after(ms, fn) a timer that returns its cancel: both are injected so // a test can run on a fake clock. // How long a press may wait for its answer before the link is offline. export const ANSWER_TIMEOUT_MS = 3000 // How often an offline link that owes the server a resume tries again, // when the stream has not already said the network is back. export const RETRY_MS = 2000 // How long the stream may be gone before the link is offline. The // server ends every stream after five minutes and the browser opens it // again three seconds later; that is not a split, and a room should not // see the slide window say it is waiting each time. export const STREAM_GRACE_MS = 5000 const ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' /** A press id: 22 characters from the alphabet the server accepts, from crypto.getRandomValues. */ export function pressID () { const bytes = new Uint8Array(22) globalThis.crypto.getRandomValues(bytes) let out = '' // 64 letters divide 256 evenly, so each is equally likely. for (const b of bytes) out += ALPHABET[b & 63] return out } // The ops moves.mjs names, as the command form names them. const WIRE = { back: 'prev', black: 'blackout' } /** The form fields for a move: {op, slide} in moves.mjs's words. */ export function pressFields (move) { const fields = { op: WIRE[move.op] || move.op } if (move.slide) fields.slide = String(move.slide) return fields } /** Whether two positions differ in anything the window draws. */ export function differs (a, b) { if (!a || !b) return a !== b return a.slide !== b.slide || (a.step || 0) !== (b.step || 0) || a.mode !== b.mode || !!a.black !== !!b.black } const defaultAfter = (ms, fn) => { const id = setTimeout(fn, ms) return () => clearTimeout(id) } export function createLink ({ post, stream, now = () => Date.now(), after = defaultAfter, onPosition = () => {}, onStatus = () => {}, onDeckSeq = () => {}, onTimer = () => {}, makeID = pressID }) { let online = true let queue = [] // presses not yet answered: [{fields}] let sending = null // the press on the wire, while it is let owed = false // the server has not heard where this window went let standing = null // where the window stands let newest = null // the newest position the server has said let applied = 0 // the seq of the last position taken or matched let retry = null let gap = null // the stream's grace, while it is gone const linkID = makeID() // this window's link, for as long as it is loaded let count = 0 // the number of the newest command made const command = fields => ({ id: makeID(), n: ++count, fields }) function status () { return online ? 'online' : 'offline' } function say (s) { const was = online online = s === 'online' if (was !== online) onStatus(status()) } // hear is every position the server says, from any source. function hear (pos) { if (!pos || typeof pos.seq !== 'number') return if (typeof pos.deckSeq === 'number') onDeckSeq(pos.deckSeq) if (!newest || pos.seq > newest.seq) newest = pos } // take applies the newest position once nothing is waiting: its // timer always, the position where it differs. function take () { if (!online || sending || queue.length || !newest || newest.seq <= applied) return applied = newest.seq if ('timerAt' in newest) onTimer(newest.timerAt === null ? null : Number(newest.timerAt)) if (!differs(newest, standing)) return standing = { slide: newest.slide, step: newest.step || 0, mode: newest.mode, black: !!newest.black } onPosition({ ...standing, seq: newest.seq }) } function pump () { if (!online || sending || !queue.length) return const item = queue[0] const sentAt = now() // mine is this send; once the link has given up on it (lost), what // comes back for it is nobody's. const mine = { item } sending = mine const cancel = after(ANSWER_TIMEOUT_MS, () => { if (sending === mine) lost() }) Promise.resolve() .then(() => post({ ...item.fields, press: item.id, link: linkID, n: String(item.n) })) .then(answer => { if (sending !== mine) return cancel() // An answer that took too long is as good as lost: the window // may have been throttled and the timer late. if (now() - sentAt > ANSWER_TIMEOUT_MS) { lost(); return } sending = null queue.shift() hear(answer) if (queue.length) pump() else take() }, () => { if (sending !== mine) return cancel() lost() }) } // lost is the network gone: every unanswered press is dropped, and // the window's position is owed to the server instead. function lost () { if (sending || queue.length) owed = true sending = null queue = [] say('offline') schedule() } // schedule tries the resume again while offline and owing one. function schedule () { if (retry || online || !owed) return retry = after(RETRY_MS, () => { retry = null if (online || !owed) return reconnect() }) } // reconnect is the network back: the resume if one is owed, which // is a press like any other (it may fail, and the link is offline // again); otherwise the server's newest position is taken. function reconnect () { if (retry) { retry(); retry = null } say('online') if (owed && standing) { owed = false queue = [command({ op: 'resume', at_slide: standing.slide, at_step: String(standing.step || 0), at_mode: standing.mode, at_black: standing.black ? 'true' : 'false' })] pump() return } take() } function heardFrom () { if (gap) { gap(); gap = null } } stream({ open () { heardFrom() if (!online) reconnect() }, error () { // The stream opens again by itself. Gone for longer than its // grace, nothing is reaching this window: offline. if (!online || gap) return gap = after(STREAM_GRACE_MS, () => { gap = null; if (online) lost() }) }, position (pos) { heardFrom() hear(pos) // Hearing anything means the network is back. if (!online) reconnect() else take() } }) return { /** The window has moved by move to landedAt; tell the server. */ press (move, landedAt) { if (landedAt) standing = { ...landedAt } if (!online) { owed = true; schedule(); return } queue.push(command(pressFields(move))) pump() }, /** The window stands at position without a press (it started there, or a newer deck settled it). */ resume (position) { standing = position ? { ...position } : null }, status } }