import { type DataError, toDataError } from './errors'; import { createKeyedFlight } from './keyed-flight'; import { dataNow, getDataLogger } from './runtime'; /** Options every refetch helper accepts. `bypassCache` is what realtime pings and pull-to-refresh pass. */ export interface FetchOptions { bypassCache?: boolean; } /** * Per-slice request state (Dispatch baseline: one loading flag and one error per resource). Only * `fetchedAt` is persisted (sync metadata); loading flags and errors never are. */ export interface SliceMeta { loading: Partial>; errors: Partial>; fetchedAt: Partial>; } export const emptySliceMeta = (): SliceMeta => ({ loading: {}, errors: {}, fetchedAt: {} }); export type SliceResult = { ok: true; value: T } | { ok: false; error?: DataError; stale?: boolean }; type SetState = (partial: Partial | ((state: S) => Partial)) => void; export interface RunOptions { /** De-duplication key when one slice is fetched per id (e.g. `feeds:`); defaults to the slice key. */ flightKey?: string; /** Queue a trailing refetch instead of sharing the in-flight one (realtime pings). */ trailing?: boolean; /** Do not flip the loading flag (poll rounds, background prefetch). */ silent?: boolean; /** * Race-guard lane; defaults to the slice key. The newest request in a lane wins and older answers in it are dropped. * A page merged into a list (older history) takes its own lane, so a refresh of the same slice does not drop it. */ raceKey?: string; } export interface SliceRunner { run(key: K, fetcher: () => Promise, apply: (value: T, state: S) => Partial, options?: RunOptions): Promise>; /** Drop every in-flight answer (sign-out, store reset): late responses must not repopulate the store. */ invalidate(): void; generation(): number; } const metaPatch = >(state: S, key: K, patch: { loading?: boolean; error?: DataError | null; fetchedAt?: number }): Partial => { const next: Partial> = {}; if (patch.loading !== undefined) next.loading = { ...state.loading, [key]: patch.loading }; if (patch.error !== undefined) next.errors = { ...state.errors, [key]: patch.error }; if (patch.fetchedAt !== undefined) next.fetchedAt = { ...state.fetchedAt, [key]: patch.fetchedAt }; return next as Partial; }; /** * Runs fetches for a store's slices with loading/error bookkeeping, de-duplication, a per-slice race guard * (the newest request for a slice wins — Dispatch video-feed guard, Unit records guards; `raceKey` splits a slice into * lanes) and a generation * guard so a response that lands after sign-out is dropped. */ export function createSliceRunner>(storeName: string, set: SetState): SliceRunner { let generation = 0; const sequences = new Map(); const flights = createKeyedFlight(); return { run(key: K, fetcher: () => Promise, apply: (value: T, state: S) => Partial, options: RunOptions = {}): Promise> { // The generation of the call, not of the moment the read starts: a trailing read queued before sign-out (or a reset) // starts after it, and must settle as stale without reading anything for the next session. const startedIn = generation; return flights.run>( options.flightKey ?? key, async () => { if (startedIn !== generation) return { ok: false, stale: true }; const lane = options.raceKey ?? key; const sequence = (sequences.get(lane) ?? 0) + 1; sequences.set(lane, sequence); const isCurrent = (): boolean => startedIn === generation && sequences.get(lane) === sequence; if (!options.silent) set((state) => metaPatch(state, key, { loading: true, error: null })); try { const value = await fetcher(); if (!isCurrent()) return { ok: false, stale: true }; set((state) => ({ ...apply(value, state), ...metaPatch(state, key, { loading: false, error: null, fetchedAt: dataNow() }) })); return { ok: true, value }; } catch (error) { const dataError = toDataError(error); if (!isCurrent()) return { ok: false, stale: true, error: dataError }; getDataLogger().warn({ message: 'Data fetch failed', context: { store: storeName, slice: key, code: dataError.code, status: dataError.status } }); set((state) => metaPatch(state, key, { loading: false, error: dataError })); return { ok: false, error: dataError }; } }, { trailing: options.trailing } ); }, invalidate() { generation++; sequences.clear(); flights.clear(); }, generation: () => generation, }; } /** True when the slice was fetched within `maxAgeMs` (hydration `isCurrent`, skip-if-fresh guards). */ export function isSliceFresh(meta: SliceMeta, key: K, maxAgeMs: number): boolean { const at = meta.fetchedAt[key] ?? 0; return at > 0 && dataNow() - at <= maxAgeMs; } /** Cached-endpoint options for a refetch: `bypassCache` maps to the API's `forceRefresh`. */ export const cacheOptions = (options?: FetchOptions): { forceRefresh: boolean } => ({ forceRefresh: options?.bypassCache === true });