fix: abort old loads, stale sync state, warn before unsaved edits are lost

This commit is contained in:
lobo committed 2026-09-30 07:51:09 +02:00
1 parent cbafa3d540
commit 9ddc50f819
28 files changed
+753 -121

No files matched your search

+40 -22
View File
@@ -1,4 +1,4 @@
import {useEffect, useRef, useState} from 'react';
import {useCallback, useEffect, useRef, useState} from 'react';
import {apiFetch} from '../utils/api.js';
import {hasSession} from '../utils/auth.js';
@@ -7,28 +7,42 @@ 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 transitions to OK / FAILED.
* 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 transition to OK/FAILED
* @returns {{status: string|null, lastSyncedAt: string|null, isRunning: boolean, error: string|null}}
* @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});
const previousRunningRef = useRef(null);
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;
@@ -51,22 +65,24 @@ export default function useLibrarySync({enabled, expectInitialSync = false, onCo
const status = json.lastSyncStatus;
const lastSyncedAt = json.lastSyncedAt;
setState({status, lastSyncedAt, error: null});
lastSyncedAtRef.current = lastSyncedAt;
const isRunning = status === 'RUNNING';
const wasRunning = previousRunningRef.current;
if (wasRunning === true && !isRunning) {
onCompleteRef.current?.();
}
previousRunningRef.current = isRunning;
const elapsed = Date.now() - startedAt;
const waitingForInitial =
expectInitialSync && status == null && elapsed < INITIAL_SYNC_GRACE_MS;
const stillWaiting = isRunning || waitingForInitial;
const stale = isRunning && elapsed >= MAX_POLL_DURATION_MS;
setState({status, lastSyncedAt, error: null, stale});
if (stillWaiting && elapsed < MAX_POLL_DURATION_MS) {
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) {
@@ -82,12 +98,14 @@ export default function useLibrarySync({enabled, expectInitialSync = false, onCo
cancelled = true;
if (timer) clearTimeout(timer);
};
}, [enabled, expectInitialSync]);
}, [enabled, expectInitialSync, watched]);
return {
status: state.status,
lastSyncedAt: state.lastSyncedAt,
isRunning: state.status === 'RUNNING',
isRunning: state.status === 'RUNNING' && !state.stale,
stale: state.stale,
error: state.error,
watch,
};
}