// Every move on either server, kept up to date for the whole app: live // events for moves running here, and polling for moves running on the peer // (fast while something is moving, slow otherwise). import { api, type Job } from './api'; export const moves = $state({ jobs: {} as Record, error: null as string | null, peerError: null as string | null, loaded: false, }); type DoneListener = (job: Job) => void; const listeners = new Set(); /** Call `fn` whenever a move (not a dry run) finishes. Returns an unsubscribe. */ export function onMoveDone(fn: DoneListener): () => void { listeners.add(fn); return () => listeners.delete(fn); } const isActive = (j: Job) => j.status.kind === 'Queued' || j.status.kind === 'Running'; /** Record a job snapshot and tell listeners if it has just finished. */ function put(job: Job) { const before = moves.jobs[job.id]; moves.jobs[job.id] = job; const finished = job.status.kind === 'Done' && !job.dry_run && before && before.status.kind !== 'Done'; // A move we only learn about once it's done (e.g. it finished between // polls) still counts, as long as the list had loaded before. const unseen = job.status.kind === 'Done' && !job.dry_run && !before && moves.loaded; if (finished || unseen) for (const fn of listeners) fn(job); } export async function refreshMoves() { try { const view = await api.jobs(); const all = [...view.local, ...view.peer]; for (const j of all) put(j); // Forget jobs that no longer exist anywhere. const ids = new Set(all.map((j) => j.id)); for (const id of Object.keys(moves.jobs)) if (!ids.has(id)) delete moves.jobs[id]; moves.peerError = view.peer_error; moves.error = null; moves.loaded = true; } catch (e) { moves.error = (e as Error).message; } } let timer: ReturnType | undefined; let running = false; async function tick() { clearTimeout(timer); await refreshMoves(); if (!running) return; const busy = Object.values(moves.jobs).some(isActive); timer = setTimeout(tick, busy ? 2000 : 10_000); } /** Note a move just started here, and check on it soon. */ export function trackMove(job: Job) { put(job); if (running) { clearTimeout(timer); timer = setTimeout(tick, 1000); } } /** Start watching for the lifetime of the app. Returns a stop function. */ export function watchMoves(): () => void { if (running) return () => {}; running = true; const es = new EventSource('/api/events'); es.addEventListener('job', (ev) => put(JSON.parse((ev as MessageEvent).data) as Job)); tick(); return () => { running = false; clearTimeout(timer); es.close(); }; }