/** * The playback trace: a paper trail from "the listener chose a track" to "the audio thread * has a source armed", and every place in between where a load can stop answering. * * Why this exists as a module rather than as `console.log`s left in by whoever debugged it * last: the failure it is for — a track that sits in `loading` forever — is a failure *of * silence*. Every stage of the load is a promise that has not settled, so there is nothing * thrown, nothing to catch, and nothing in the console. The only way to see it is to have * said something at each stage beforehand, so the absence of the next line is the answer. * A trace that is switched on after the fact cannot do that; one that is already running can. * * Three rules keep it usable: * * - **Dev only, and silent under the tests.** `console.debug` in a test run is a wall of * text over the failure someone is trying to read. The gate is `DEV` minus the test mode; * the toggle below overrides it in the console. * - **One line per event, prefixed and timed.** Every line carries the track id and the * milliseconds since the load began — the number that matters is not when the decode * finished but how long after the request it finished, and whether the gap moved at all. * - **The watchdog says what it is waiting for, in the present tense.** "Still waiting: the * decoder has had the bytes for 12.3s" is a sentence that ends the investigation, whereas * "loading…" is the state the bar already shows. * * Nothing here is read by the app: the trace observes and does not participate. If a line * ever changes what playback does, it has stopped being a trace. */ /** What a load is blocked on right now, in the words the stall line will print. */ export type LoadWait = string; const STORE_KEY = "hackermusic.player.trace.v1"; /** * The detector's own channel, gated apart from the playback one because the two are read for * different reasons and at different rates: playback says a handful of lines per track and is * worth having on all day, the detector says a dozen lines of numbers per track and is wanted * only in the situation it was built for — a `c` press that came back *not sure* on music * that plainly repeats. It follows the playback switch unless it has been set on its own, so * turning the trace on for a hung load also explains the loop chip, and turning the numbers * on does not put a wall of them under ordinary listening. */ const DETECT_KEY = "hackermusic.detect.trace.v1"; /** * The first stall line comes four seconds in — long enough that it is not printed for an * ordinary slow response on a phone connection, short enough that a watch is worth sitting * through. After that, every eight seconds: a load that has been stuck for a minute has to * keep saying so, because the interesting part is whether the wait is *moving*. */ const FIRST_STALL_MS = 4000; const STALL_EVERY_MS = 8000; /** * The waveform's own channel, gated apart for the same reason the detector's is: the fold says ten * lines per track and the playback trace says five, and the interesting one is the burst. * * It is where the question "why does the row fill in choppy?" gets answered, which is a question about * *spacing* — how big each slice was, how long between publishes, how long a slice got to animate * before the next one replaced it. None of those are visible from outside, because all three are * numbers the code chose and then forgot. The lines carry them. * * `off` prints nothing; `on` prints the two lines per fold that a diagnosis needs (what the pass * reported to the row, and what the row drew from it); `"slices"` adds one line per slice of the pass, * which is the wall of text that shows where the time inside the fold actually went. */ const WAVE_KEY = "hackermusic.wave.trace.v1"; export type WaveTraceLevel = false | true | "slices"; /** * `null` = nobody has said, so the defaults below decide; `true`/`false` = said explicitly, * from the console or from a test, and the defaults do not get a vote. */ let forced: boolean | null = null; let detectForced: boolean | null = null; let waveForced: WaveTraceLevel | null = null; function stored(): boolean | null { try { const raw = globalThis.localStorage?.getItem(STORE_KEY); return raw === null ? null : raw === "1"; } catch { return null; // private mode, or no storage at all: the default stands } } function persist(on: boolean): void { try { globalThis.localStorage?.setItem(STORE_KEY, on ? "1" : "0"); } catch { // The setting lives for the page either way; a page that will not store it just does not // remember it across a reload, which is what a trace is for. } } /** * Whether the trace is printing. * * The default is dev-only, because that is where it is useful: a hung load in production is * something the user reports, and by then the console is empty. Under the test runner it is * off even though `DEV` is true there — the same reasoning that keeps `perf.ts` from * patching anything in a test: a probe that changes what the test is looking at is worse * than no probe, and console noise over a real failure is that, only louder. */ export function playbackTrace(): boolean { if (forced !== null) return forced; if (!import.meta.env.DEV || import.meta.env.MODE === "test") return false; const saved = stored(); return saved === null ? true : saved; } /** Turn it on or off, and remember which across a reload: the question is usually asked * again after a reload, from a phone, where retyping the console line is the whole cost. */ /** * Turn it on or off — or back to "nobody has said" with `null`, which is what a test does * when it is finished being explicit and does not want to leave the page in its setting. */ export function setPlaybackTrace(on: boolean | null): void { forced = on; if (on !== null) persist(on); } /** * Whether the detector is printing, which is a separate channel from the playback trace * because the two are read for different reasons and at different rates: playback says a * handful of lines per track and is worth having on all day, the detector says a dozen lines * of numbers per track and is wanted only in the one situation where a `c` press came back * *not sure*. It follows the playback switch unless it has been set on its own, so turning * the trace on for a hung load also explains the loop chip, without the numbers sitting * under an ordinary listening session. */ export function detectTrace(): boolean { if (detectForced !== null) return detectForced; const saved = storedDetect(); return saved === null ? playbackTrace() : saved; } /** * The worker's lines, assembled on the thread that measured and printed from the page. * * A worker is a separate instance of every module it imports, and this one is no exception: the * console's switch sets a variable in the *page's* copy, the worker's copy never hears about it, * and its `console.debug` goes to a place the page's filters, grouping and test spies do not * reach. A trace nobody can see is worse than no trace, because it reads as "the detector had * nothing to say" — which is precisely the misreading this whole feature exists to prevent. * * So the worker builds its lines into a buffer instead of printing them, sends them back with * the answer, and the page prints them under its own switch. The work of deciding what to say * stays beside the measurement; the work of deciding whether to say it stays with the reader. */ let capture: string[] | null = null; /** Start assembling lines instead of printing them. Worker-side, inside one synchronous run. */ export function beginDetectCapture(): void { capture = []; } /** The lines assembled since `beginDetectCapture*, and the capture switched back off. */ export function takeDetectCapture(): string[] { const lines = capture ?? []; capture = null; return lines; } /** Print lines handed back from another thread, under this thread's switch. */ export function printDetectLines(lines: string[]): void { if (!detectTrace()) return; for (const line of lines) console.debug(line); } export function setDetectTrace(on: boolean | null): void { detectForced = on; if (on === null) return; try { globalThis.localStorage?.setItem(DETECT_KEY, on ? "1" : "0"); } catch { // The setting lives for the page either way. } } function storedDetect(): boolean | null { try { const raw = globalThis.localStorage?.getItem(DETECT_KEY); return raw === null ? null : raw === "1"; } catch { return null; } } /** * One line about one track's detection. Same shape as `tracePlayback` — id, elapsed on the * load's clock, details assembled only if somebody is listening — with one difference that * matters when the lines are read across a thread boundary: the same call works from inside * the worker and outside it, so a measurement and the decision taken on it are printed by * the code that made them and not by a caller relaying what it was told. */ export function traceDetect( what: string, id?: string, since?: number, detail?: () => Record, ): void { // Capturing is not the same question as printing: the worker assembles its lines whatever the // page's switch says, because the page asked for them by asking for the measurement. if (capture === null && !detectTrace()) return; const pairs = detail ? Object.entries(detail()) .filter(([, v]) => v !== undefined) // Three decimals, where the playback trace uses two: these are correlations, and the // whole argument is about the second decimal place of one. .map(([k, v]) => `${k}=${typeof v === "number" ? Math.round(v * 1000) / 1000 : String(v)}`) .join(" ") : ""; const text = `${line("detect", id, since)} ${what}${pairs ? ` (${pairs})` : ""}`; if (capture) capture.push(text); else console.debug(text); } const clock = (): number => typeof performance === "undefined" || !performance.now ? Date.now() : performance.now(); /** Milliseconds since a load's own clock started — the number every line about it carries. */ export function elapsed(since: number): number { return clock() - since; } const seconds = (ms: number): string => `${(ms / 1000).toFixed(1)}s`; /** The prefix, in one place: `12:04:33.512 [player] 4.2s s1 ·`. */ function line(tag: string, id: string | undefined, since: number | undefined): string { const at = new Date().toISOString().slice(11, 23); const who = id ? ` ${id}` : ""; const t = since === undefined ? "" : ` +${seconds(since)}`; return `${at} [${tag}]${who}${t} ·`; } /** `k=v` for the ones that are there, assembled only when somebody is going to read them. */ function pairs(detail?: () => Record): string { if (!detail) return ""; return Object.entries(detail()) .filter(([, v]) => v !== undefined) .map(([k, v]) => `${k}=${typeof v === "number" ? Math.round(v * 100) / 100 : String(v)}`) .join(" "); } function emit( tag: string, what: string, id: string | undefined, since: number | undefined, detail?: () => Record, ): void { const rest = pairs(detail); console.debug(`${line(tag, id, since)} ${what}${rest ? ` (${rest})` : ""}`); } /** * One line about one track. `since` is the load's own clock — pass the value `startLoad` * returned — because a load's stages are meaningful to each other and to nothing else. */ export function tracePlayback( what: string, id?: string, since?: number, // A function, and deliberately: a caller that hands over an object has built it — and // building it often means reading something that only exists to be logged, like // `res.headers.get(...)` on a response whose shape is not guaranteed. Off, the trace has to // cost the program nothing but the call, so the object is assembled on the way out of here // or not at all. detail?: () => Record, ): void { if (!playbackTrace()) return; emit("player", what, id, since, detail); } /** * Whether the fold and the row are printing, which follows the playback switch unless somebody has * set it on its own — the same arrangement the detector has, for the same reason: nobody wants a burst * of measurement lines permanently under an ordinary listening session, and nobody wants to have to * remember a second command when they are already looking at a trace. */ export function waveTrace(): WaveTraceLevel { if (waveForced !== null) return waveForced; const saved = storedWave(); return saved === null ? playbackTrace() : saved; } /** `true` for the diagnosis, `"slices"` to also see the pass itself, `false` for quiet, `null` for "follow playback". */ export function setWaveTrace(on: WaveTraceLevel | null): void { waveForced = on; if (on === null) return; try { globalThis.localStorage?.setItem(WAVE_KEY, on === true ? "1" : on === false ? "0" : "s"); } catch { // The setting lives for the page either way. } } function storedWave(): WaveTraceLevel | null { try { const raw = globalThis.localStorage?.getItem(WAVE_KEY); return raw === null ? null : raw === "1" ? true : raw === "0" ? false : "slices"; } catch { return null; } } /** One line about the row: what the pass reported, or what the row drew. */ export function traceWave( what: string, id?: string, since?: number, detail?: () => Record, ): void { if (waveTrace() === false) return; emit("wave", what, id, since, detail); } /** * One line per slice of the pass — the wall of text, behind `hackermusic.waveTrace("slices")`, for the * question the publish lines cannot answer: whether the fold itself is running in even steps or in * ones that get bigger as the buffers start paging. */ export function traceWaveSlice( what: string, id?: string, since?: number, detail?: () => Record, ): void { if (waveTrace() !== "slices") return; emit("wave", what, id, since, detail); } /** * Watch a load that has not settled, and say so while it lasts. * * The caller owns what the wait *is* — "the response has not arrived", "the decoder has had * the bytes" — which is the whole value of the arrangement: only the code sitting in front * of the promise knows which promise it is sitting in front of, and only the reader knows * they want to hear it in the present tense. A stall line that names a stage is a verdict; * one that says "still loading" is the bar's own label back at you. * * Returns the disarm function, and it must be called — from a `finally`, usually. A watch * left running is one that prints "still waiting" about a track that started playing two * tracks ago, which is how a trace gets itself ignored. */ export function watchLoad( id: string, since: number, waiting: () => LoadWait, detail?: () => Record, ): () => void { if (!playbackTrace()) return () => undefined; let fired = 0; let timer: ReturnType | null = null; const tick = () => { const waited = elapsed(since); // The sentence is the payload; the elapsed belongs to the prefix, which every line in the // trace already carries. Saying the number twice, in two bracketed clauses, is what made // the first version of this line unreadable. tracePlayback(`still waiting: ${waiting()}`, id, waited, detail); fired += 1; timer = setTimeout(tick, STALL_EVERY_MS); }; timer = setTimeout(tick, FIRST_STALL_MS); return () => { if (timer !== null) clearTimeout(timer); timer = null; }; } /** * Start a clock for one load. Everything the trace prints about that load is measured from * here, which is what makes "the decode is the slow part" readable off the screen instead of * something to be computed from four timestamps in four different lines. */ export function beginLoadClock(): number { return clock(); } /** * The console handle, installed the way `perf.ts` installs its probes: dev-only, at module * evaluation, and doing nothing to anything the app reads. * * hackermusic.playbackTrace() // is it on? * hackermusic.playbackTrace(true) // on, and remembered * hackermusic.playbackTrace(false) // off, and remembered * * It has to be reachable from the console because the question it answers — "what was this * track waiting on?" — is asked while the track is still waiting, from a phone over tailscale * where rebuilding the page to add a log is not an option. It is also the reason the gate and * the setting live in this module rather than inlined at the call sites: an on switch that * cannot reach the code that prints is how a debug flag ends up being a rebuild. */ export interface PlaybackTraceHandle { (): boolean; (on: boolean): boolean; } export const playbackTraceHandle: PlaybackTraceHandle = ((on?: boolean) => { if (on !== undefined) setPlaybackTrace(on); return playbackTrace(); }) as PlaybackTraceHandle; if (import.meta.env.DEV && typeof globalThis !== "undefined") { const g = globalThis as unknown as { hackermusic?: Record }; g.hackermusic = { ...g.hackermusic, playbackTrace: playbackTraceHandle }; }