import {useCallback, useEffect, useRef, useState} from 'react'; import {apiFetch} from '../utils/api.js'; import {hasSession} from '../utils/auth.js'; const POLL_INTERVAL_MS = 3000; const MAX_POLL_DURATION_MS = 120_000; const INITIAL_SYNC_GRACE_MS = 15_000; /** * Polls /api/library/sync-status while a sync is running (or expected), and fires onComplete once when the run ends. * A run that still runs after 2 minutes is shown as `stale` and polling stops. `watch()` polls again after the * user started a sync: that run counts as ended when `lastSyncedAt` changes, also when no poll saw it running. * * @param {Object} opts * @param {boolean} opts.enabled - skip work entirely when false (e.g. user has no steamId) * @param {boolean} opts.expectInitialSync - if true and no row yet, keep polling (covers the * gap between async sync dispatch and first DB write) * @param {() => void} opts.onComplete - called once per run that ends * @returns {{status: string|null, lastSyncedAt: string|null, isRunning: boolean, stale: boolean, error: string|null, * watch: () => void}} */ export default function useLibrarySync({enabled, expectInitialSync = false, onComplete}) { const [state, setState] = useState({status: null, lastSyncedAt: null, error: null, stale: false}); // count starts polling again; since is the last known end, so a new one shows that the started run is over const [watched, setWatched] = useState({count: 0, since: undefined}); const lastSyncedAtRef = useRef(undefined); // The count of the last watch whose run ended; a later restart of the polling must not report that run again. const endedWatch = useRef(0); const onCompleteRef = useRef(onComplete); onCompleteRef.current = onComplete; const watch = useCallback(() => { setWatched((current) => ({count: current.count + 1, since: lastSyncedAtRef.current})); }, []); useEffect(() => { if (!enabled) return undefined; let cancelled = false; let timer = null; let wasRunning = false; const startedAt = Date.now(); const watching = watched.count > endedWatch.current; // Before the first answer the last end is unknown; then the first answer is the one to compare with. let since = watched.since; const fetchOnce = async () => { if (!hasSession()) return; try { const response = await apiFetch( `${import.meta.env.VITE_CORE_API_URL}/api/library/sync-status` ); if (cancelled) return; // The session is over; polling stops. if (response.status === 401) return; if (!response.ok) { setState((s) => ({...s, error: 'sync-status fetch failed'})); return; } const json = await response.json(); if (cancelled) return; const status = json.lastSyncStatus; const lastSyncedAt = json.lastSyncedAt; lastSyncedAtRef.current = lastSyncedAt; const isRunning = status === 'RUNNING'; const elapsed = Date.now() - startedAt; const stale = isRunning && elapsed >= MAX_POLL_DURATION_MS; setState({status, lastSyncedAt, error: null, stale}); if (since === undefined) since = lastSyncedAt; const ended = !isRunning && (wasRunning || (watching && lastSyncedAt !== since)); if (ended) { endedWatch.current = watched.count; onCompleteRef.current?.(); return; } wasRunning = isRunning; const waitingForInitial = expectInitialSync && status == null; const waitingForStart = (watching || waitingForInitial) && elapsed < INITIAL_SYNC_GRACE_MS; if ((isRunning && !stale) || waitingForStart) { timer = setTimeout(fetchOnce, POLL_INTERVAL_MS); } } catch (err) { if (cancelled) return; console.error('sync-status poll error:', err); setState((s) => ({...s, error: 'network'})); } }; fetchOnce(); return () => { cancelled = true; if (timer) clearTimeout(timer); }; }, [enabled, expectInitialSync, watched]); return { status: state.status, lastSyncedAt: state.lastSyncedAt, isRunning: state.status === 'RUNNING' && !state.stale, stale: state.stale, error: state.error, watch, }; }