"use client"; import { useEffect, useRef } from "react"; import type { WikiBuildStatus } from "@/types/wiki"; const TERMINAL_BUILD_STATUSES = new Set([ "ready", "failed", "conflict", ]); export function wikiPollDelay(attempt: number): number { return Math.min(2_000 * 2 ** Math.max(0, attempt), 10_000); } interface WikiBuildPollingOptions { getVisibility: () => "hidden" | "visible"; subscribeVisibility: (listener: () => void) => () => void; refetch: () => Promise; } export interface WikiBuildPollingController { update: (status: WikiBuildStatus | undefined, enabled: boolean) => void; cleanup: () => void; } export function createWikiBuildPollingController({ getVisibility, subscribeVisibility, refetch, }: WikiBuildPollingOptions): WikiBuildPollingController { let attempt = 0; let status: WikiBuildStatus | undefined; let enabled = false; let timer: ReturnType | undefined; let epoch = 0; let inFlightEpoch: number | undefined; let disposed = false; const isRunning = () => Boolean(enabled && status && !TERMINAL_BUILD_STATUSES.has(status)); const clearTimer = () => { if (timer !== undefined) clearTimeout(timer); timer = undefined; }; const schedule = () => { if ( disposed || timer !== undefined || inFlightEpoch === epoch || getVisibility() === "hidden" || !isRunning() ) { return; } const scheduledEpoch = epoch; timer = setTimeout(() => { timer = undefined; if (scheduledEpoch !== epoch) return; void performRefetch(); }, wikiPollDelay(attempt)); }; const performRefetch = async () => { if (disposed || getVisibility() === "hidden" || !isRunning()) return; const requestEpoch = epoch; if (inFlightEpoch === requestEpoch) return; inFlightEpoch = requestEpoch; attempt += 1; try { await refetch(); } catch { // A transient request failure must not stop observation of a live build. } finally { if (inFlightEpoch === requestEpoch) inFlightEpoch = undefined; if (requestEpoch === epoch) schedule(); } }; const unsubscribe = subscribeVisibility(() => { clearTimer(); if (getVisibility() === "visible" && isRunning()) { void performRefetch(); } }); return { update(nextStatus, nextEnabled) { if (disposed) return; const wasRunning = isRunning(); status = nextStatus; enabled = nextEnabled; const startsRunningCycle = !wasRunning && isRunning(); if (startsRunningCycle) { epoch += 1; attempt = 0; clearTimer(); } if (!isRunning() || getVisibility() === "hidden") { clearTimer(); return; } schedule(); }, cleanup() { disposed = true; epoch += 1; clearTimer(); unsubscribe(); }, }; } export function useWikiBuildPolling( status: WikiBuildStatus | undefined, refetch: () => Promise, enabled = true, ): void { const refetchRef = useRef(refetch); const controllerRef = useRef(null); refetchRef.current = refetch; useEffect(() => { const controller = createWikiBuildPollingController({ getVisibility: () => typeof document === "undefined" ? "visible" : document.visibilityState, subscribeVisibility: (listener) => { if (typeof document === "undefined") return () => {}; document.addEventListener("visibilitychange", listener); return () => document.removeEventListener("visibilitychange", listener); }, refetch: () => refetchRef.current(), }); controllerRef.current = controller; controller.update(status, enabled); return () => { controller.cleanup(); controllerRef.current = null; }; // The controller owns changing build state through update(), and the latest // refetch callback is read from refetchRef to avoid timer churn. // eslint-disable-next-line react-hooks/exhaustive-deps }, []); useEffect(() => { controllerRef.current?.update(status, enabled); }, [enabled, status]); }