/** * Coming back: what was queued, which track it was on, where in that track it had got * to, and the A–B region it was repeating — kept in localStorage and put back when the * page returns. * * Three questions, answered in two places: * * - **what to store** — `PlayerSession` below, one blob rather than a key per * field: the queue, its cursor, the position on the track and the region being * looped are one moment in time, and four keys restored in four orders is four * chances to restore half of it. * - **when to write** — the store itself, at the moments that mean something (a * track chosen, the transport paused, the slider committed, a region set, the queue * replaced) and on a coarse tick while playing. Those are the places where every * value is already in hand; a subscriber watching signals for them would be * watching the * 250ms position clock to catch a four-hundredths-of-a-second event. * - **when to read back** — `startPlayerSession`, once per connection, as soon as * the index the ids resolve against has settled, through * `store.hydrateSession` — which adopts the queue without fetching or playing * anything. Nothing here starts audio: audio starts on a gesture, and a reload * is not one. * * Volume is deliberately absent. It is a fact about the room rather than about what * happens to be queued, so it has its own key and lives with the transport that * reads it (see `volume` in store.ts). * * The queue is stored as ids and re-resolved against the library on the way back, * for the same reason the queue is ids inside the store: the song objects belong to * the index, and a copy of them in storage is a second index that can only ever be * out of date. */ import * as v from "valibot"; import { createEffect, onSettled } from "solid-js"; import { connectionKey } from "../connection"; import type { ConnectionSettings } from "../connection"; import type { LibrarySong } from "../harvest/types"; import type { PlayerStore } from "./store"; /** One blob for the whole session; see the module comment. */ const SESSION_KEY = "hackermusic.player.session.v1"; /** * The largest queue that gets stored. * * A queue is a view over the index and an index is a whole collection, so the * alternative to a cap is stringifying a few hundred kilobytes every few seconds to * keep a queue that would take a week to play out. Past the cap the session keeps * the track and its position and drops the queue around it, which is the half worth * having back: the bar says what was playing and the slider says where it was, and * `n` simply runs out where the stored queue does. */ const MAX_STORED_IDS = 1000; /** * What was on the transport when the page last went away. * * `at` is an id, not an index: the row a track sits on moves under a harvest, which * is the same argument the library cursor makes (LibraryView keys its cursor rather * than numbering it). * * `server` is stamped on write and checked on read, for the reason the query's stamp * is (LibraryView): ids belong to the server that issued them, and a queue from * another host resolves to nothing there — or worse, to something else that happens * to share an id. The stamp is the same identity startPlayerSync switches on, so a * second user on one host is a second session too. */ export interface PlayerSession { server: string; ids: string[]; at: string; atOffset: number; /** * The A–B region that track was repeating, if it was — named for the track it * belongs to rather than left as two seconds beside whatever `at` happens to say. * * `atOffset` needs no such stamp because it is only ever read alongside `at`; a * region is the same kind of fact, and a loop that silently moved onto the track * next to the one the listener left is worse than no loop. The stamp is what the * read-back checks, and it is what a hand-edited or half-written blob gets caught by. */ loop?: StoredLoop; } /** A region, stamped with the track whose timeline it was measured on. */ export interface StoredLoop { at: string; start: number; end: number; } /** * The two `minLength` guards are the point of the schema: an empty `ids` or an empty * `at` parses as a value, reaches `hydrateSession`, and gets refused there — in a * code path with nothing left to say about it. Rejecting them here makes a * half-write (an older build, a poke in DevTools) read as "nothing stored", which is * what it is. */ const sessionSchema = v.object({ server: v.pipe(v.string(), v.minLength(1)), ids: v.array(v.string()), at: v.pipe(v.string(), v.minLength(1)), atOffset: v.pipe(v.number(), v.finite(), v.minValue(0)), // Optional, and junk is fatal to the whole blob rather than to itself: a stored // region is the only A–B thing the user set on purpose, so it is read under the // same rule as everything else here — a shape nobody declared reads as "nothing // stored" rather than restoring NaN as a boundary. `end > start` is checked on the // way in, because the clamp against the real length happens later, against bytes // this read has not seen. loop: v.optional( v.pipe( v.object({ at: v.pipe(v.string(), v.minLength(1)), start: v.pipe(v.number(), v.finite(), v.minValue(0)), end: v.pipe(v.number(), v.finite(), v.minValue(0)), }), v.check((region) => region.end > region.start), ), ), }); /** * The blob goes to localStorage directly rather than through a signal, which is the * one thing persist.ts does that this must not. * * Its `createPersistentSignal` reads once and keeps the value in memory as the * source of truth — right for the volume, which the page owns for its whole life. * Wrong here: the entire point is that a *reload* re-reads the session, and a * module-level signal would hand the previous page's answer to the page that came to * fetch it. The same trap catches tests: two boots in one file, one memory, and the * second restores what the first left. * * The read discipline is persist.ts's own — schema-checked at the door, junk reads * as absent rather than thrown at the caller — because the failure being designed * against is the same: a value written by an older build, or poked into DevTools, * arriving in a shape nobody declared. */ function readStored(): PlayerSession | null { try { const raw = localStorage.getItem(SESSION_KEY); if (raw === null) return null; const result = v.safeParse(sessionSchema, JSON.parse(raw)); return result.success ? result.output : null; } catch { return null; // not JSON at all, or storage refused to answer } } function writeStored(session: PlayerSession | null): void { try { if (session === null) localStorage.removeItem(SESSION_KEY); else localStorage.setItem(SESSION_KEY, JSON.stringify(session)); } catch { // private mode, or the quota. A session nobody can store is a session nobody // gets back; it is not a reason to spoil the page that tried. } } /** * The moment on the transport, on disk. Called from the store — from `playAt`, * `pause`, `seek`, the gapless handover, and the coarse tick — never from a * computation: this writes. * * The queue is windowed here rather than at the call sites, because every one of * them has the whole queue in hand and none of them should have to remember the * cap. */ export function writeSession(session: PlayerSession): void { const ids = session.ids.length > MAX_STORED_IDS ? windowedIds(session.ids, session.at) : session.ids; writeStored({ ...session, ids }); } /** Forget the session: the queue was emptied, or the user left the server. */ export function clearSession(): void { writeStored(null); } /** * What is stored, as the app sees it: `null` covers the absent key, the junk value * and the value that failed the schema alike, because to every caller those are one * answer. */ export function peekSession(): PlayerSession | null { return readStored(); } export interface SessionSyncDeps { /** * Read imperatively, never tracked: the stamp and the check that a session belongs * to this server. Reading it reactively would put this effect behind startPlayerSync * in the same flush — the connection changes, the sync effect disposes the player, * and the session effect wakes a second time for a write that has already been * dealt with. EFFECT_RELAY_TEAR names that double run, and this app asserts on it. */ connection: () => ConnectionSettings | null; /** * Tracked, and the only thing tracked here. Whether the index the ids resolve * against has settled — which is the whole question a restore asks, so it is the * only thing worth waking this effect for. * * Read in the compute rather than the effect phase, which is what the shape of * this effect is for: the harvest publishes in batches, so the reader is offered * the same decision a dozen times per crawl, and the `restored` flag below is what * makes the eleventh offer cost nothing. */ ready: () => boolean; /** Tracked, alongside `ready`: the rows the queue is re-resolved out of. */ songs: () => LibrarySong[]; /** The transport to adopt into. Read through peeks, so nothing is tracked here. */ store: PlayerStore; } /** * Call once from the app root, beside startPlayerSync: puts the stored session back. * This is the read half; the write half is in store.ts, where the values already are. * * The compute tracks the harvest — its readiness and the rows it publishes, which is * everything the decision reads and nothing it does not. The connection is read * imperatively because reacting to it is startPlayerSync's job (see * SessionSyncDeps), and the player is read through peeks because a restore is a * one-shot per connection rather than something re-attempted every time the transport * moves. * * `restored` is a plain flag, not a signal: it orders one decision per connection, * and nothing reads it reactively. */ export function startPlayerSession(deps: SessionSyncDeps): void { let restored: string | null = null; createEffect( () => (deps.ready() ? deps.songs() : null), (songs) => { // The writer's guard, in the other direction: while an index is still coming // there is nothing to resolve ids against, and "resolved to nothing" is // exactly the answer a first crawl serves up. Silence, not a decision. if (!songs) return; const store = deps.store; const server = connectionKey(deps.connection()); // With no server there is nothing to stamp a session with and nothing to // restore into — the queue on screen is about to be nothing, and emptying it // is `stop`'s job, not this effect's: it is the one place that forgets a // session, whether the queue ran out or the listener left the server. if (!server) return; if (restored === server) return; restored = server; const saved = readStored(); // Nothing stored, or a queue from another host or another user: leave it // alone rather than clear it. The user may well go back, and one key holds // one session — overwriting it is the next session's business, not this // check's. if (!saved || saved.server !== server) return; if (store.peekState() !== "idle" || store.peekCurrent()) { // Already playing: a harvest that lands after the user pressed play must // not trade the queue they chose for the one from before the reload. What // is stored stays stored — a later visit can still use it. return; } // Anything the index no longer has is dropped rather than left as a hole: a // queue with holes in it is a queue whose rows are not the rows on screen, // and `n` stepping into a hole reads as the end of the album. const list = saved.ids.flatMap((id) => { const song = songs.find((s) => s.id === id); return song ? [song] : []; }); // The region comes back only with the track it names. `atOffset` gets the same // guarantee by being read alongside `at`; a region has to ask for it by hand, // because a stored blob can hold a region for a track that is not the one the // bar is about to show — and a loop belonging to another track's timeline is a // wrong number, not a preference. const region = saved.loop && saved.loop.at === saved.at ? { start: saved.loop.start, end: saved.loop.end } : undefined; if (!store.hydrateSession(list, saved.at, saved.atOffset, region)) { // The track that carried the position is off the server, and there is no // nearest position to fall back to: a track that left the library left it. // The session goes with it, rather than coming back every reload to say // nothing. clearSession(); } }, { name: "player-session" }, ); // The exact position, on the way out. The store's own writes are a guess about // when the page might end; these are the moments it is known to be ending, or to // be about to be killed — a phone tab backgrounded into the OS's memory is a tab // that never gets a pagehide, and the difference this binding makes is whether // the track comes back to the second it was left at or to the last tick before // it. onSettled(() => { const flush = () => { const store = deps.store; const at = store.peekCurrent()?.id; if (!at) return; const server = connectionKey(deps.connection()); // Only for a session this page has already taken over: backgrounding during // the first harvest must not write the pre-restore emptiness over what is // stored. if (!server || restored !== server) return; const ids = store.queueIds(); if (!ids.length) return; const region = store.peekLoop(); writeSession({ server, ids, at, atOffset: store.peekPosition(), // stamped with the track the store says is current, which is the same track // `at` names — so the write and the read agree on one rule loop: region ? { at, start: region.start, end: region.end } : undefined, }); }; window.addEventListener("pagehide", flush); document.addEventListener("visibilitychange", flush); return () => { window.removeEventListener("pagehide", flush); document.removeEventListener("visibilitychange", flush); }; }); } /** The ids around the current track, capped, with it centred in the window. */ function windowedIds(ids: string[], at: string): string[] { const centre = ids.indexOf(at); if (centre < 0) return ids.slice(0, MAX_STORED_IDS); const half = Math.floor(MAX_STORED_IDS / 2); const start = Math.max(0, Math.min(centre - half, Math.max(0, ids.length - MAX_STORED_IDS))); return ids.slice(start, start + MAX_STORED_IDS); }