/** * One task's run: the reads, the caches and the view state the run page and its * panels share. * * The page provides it and the panels inject it, rather than the page threading * a dozen props through a host component: the attempt a panel reads and the * attempt the selector shows come from the same place, so they cannot disagree. * * Every keyed fetch goes through keyedLoad: the key is what the response * belongs to, so a late response for an attempt the operator has already left * lands under its own key and is never shown against another attempt. */ import { computed, inject, onMounted, provide, reactive, ref, watch, type ComputedRef, type InjectionKey, type Ref, } from "vue"; import { useRoute, useRouter } from "vue-router"; import { api } from "@/lib/api"; import { keepValue } from "@/lib/keep-unchanged"; import { useLiveResource } from "@/stores/session"; import { attemptKey, EMPTY_LOG_FILTERS, initialAttempt, initialTab, logCacheKey, runQuery, type AttemptsState, type ChangesState, type DebugState, type LogFilters, type LogState, type TaskEvent, type TaskRecord, } from "./task-run"; /** A keyed read has three states: pending, failed, or the response. */ type Cache = Map; export interface TaskRun { tab: string; attempts: AttemptsState | null | undefined; taskList: TaskRecord[] | null | undefined; events: TaskEvent[] | null | undefined; missing: boolean; filters: LogFilters; task: TaskRecord | null; attemptNumber: number | null; currentAttempt: number | null; stageNames: string[]; logState: LogState | null | undefined; changesState: ChangesState | null | undefined; debugState: DebugState | null | undefined; /** A tab id, as the Tabs root reports it (its model value is string|number). */ setTab(id: string | number): void; selectAttempt(attempt: number): void; setFilters(next: LogFilters): void; refreshAll(): void; loadAttempts(): void; loadEvents(): void; loadTaskList(): void; loadLogs(attempt: number, opts?: { force?: boolean }): void; loadChanges(attempt: number, opts?: { force?: boolean }): void; loadDebug(attempt: number, opts?: { force?: boolean }): void; } const TASK_RUN: InjectionKey = Symbol("task-run"); /** * Creates the run state for one task and provides it to the page's subtree. * `id` is the parsed task id, or null when the route's id is not a task id -- * in which case nothing is ever fetched. */ export function provideTaskRun(id: ComputedRef): TaskRun { const route = useRoute(); const router = useRouter(); const tab = ref(initialTab(route.query)); const requestedAttempt = ref(initialAttempt(route.query)); const taskList = ref(undefined); const attempts = ref(undefined); const missing = ref(false); const events = ref(undefined); const filters = ref({ ...EMPTY_LOG_FILTERS }); const logs = ref>(new Map()); const changes = ref>(new Map()); const debug = ref>(new Map()); const refreshToken = ref(0); const task = computed(() => Array.isArray(taskList.value) ? taskList.value.find((t) => String(t.id) === String(id.value)) || null : null, ); const currentAttempt = computed(() => Number(attempts.value?.current_attempt) > 0 ? Number(attempts.value?.current_attempt) : null, ); // The wire spells "the task's current attempt" as 0, which is not an attempt // number: a task with no run at all must not address attempt 0. const attemptNumber = computed( () => requestedAttempt.value ?? currentAttempt.value, ); const selectedAttempt = computed(() => (attempts.value?.attempts || []).find( (a) => Number(a.attempt) === Number(attemptNumber.value), ), ); const stageNames = computed(() => [ ...new Set( (selectedAttempt.value?.stages || []) .map((stage) => stage.name) .filter(Boolean) as string[], ), ]); const logKey = computed(() => id.value == null || attemptNumber.value == null ? null : logCacheKey(id.value, attemptNumber.value, filters.value), ); const changeKey = computed(() => id.value == null ? null : attemptKey(id.value, attemptNumber.value), ); const debugKey = changeKey; const logState = computed(() => logKey.value == null ? undefined : logs.value.get(logKey.value), ); const changesState = computed(() => changeKey.value == null ? undefined : changes.value.get(changeKey.value), ); const debugState = computed(() => debugKey.value == null ? undefined : debug.value.get(debugKey.value), ); // Each keyed read gets a generation number; a response or timeout that // settles after a newer read for the same key started is dropped, so a late // null never overwrites a newer successful response. dropCaches bumps the // global counter, which stales every in-flight read at once. let cacheGeneration = 0; const loadGenerations = new Map(); function keyedLoad( cacheKey: string, fetcher: () => Promise, cache: Ref>, { force = false, keep = false }: { force?: boolean; keep?: boolean } = {}, ): void { if (cache.value.has(cacheKey) && cache.value.get(cacheKey) !== null && !force) return; const current = ++cacheGeneration; loadGenerations.set(cacheKey, current); // keep leaves a loaded payload on screen while it is re-read, so a live // refresh replaces it in place instead of flashing the loading state. if (!keep || cache.value.get(cacheKey) == null) cache.value = new Map(cache.value).set(cacheKey, undefined); // A read that never settles would pin the panel's loading line forever: // after a quiet minute the read is declared broken so the retry button // can appear. A late response after the timeout is discarded by the race. const timeout = new Promise((_, reject) => { setTimeout(() => { reject(new Error("read timed out")); }, 30_000); }); Promise.race([fetcher(), timeout]) .then((res) => { if (loadGenerations.get(cacheKey) !== current) return; cache.value = new Map(cache.value).set(cacheKey, keepValue(cache.value.get(cacheKey), res)); }) .catch(() => { if (loadGenerations.get(cacheKey) !== current) return; cache.value = new Map(cache.value).set(cacheKey, null); }); } function loadTaskList(): void { if (id.value == null) return; // Keep the current gate mounted so a refresh preserves its selection. api .tasks() .then((res) => { taskList.value = keepValue(taskList.value, res); }) .catch(() => { // Keep the last known list: a failed refresh must not flash the // panels to their loading state. }); } function loadAttempts(keep = false): void { if (id.value == null) return; if (!keep || !attempts.value) attempts.value = undefined; missing.value = false; api .taskAttempts(String(id.value)) .then((res) => { attempts.value = keepValue(attempts.value, res); }) .catch((err) => { if ((err as { status?: number })?.status === 404) missing.value = true; attempts.value = null; }); } function loadEvents(keep = false): void { if (id.value == null) return; if (!keep || !events.value) events.value = undefined; api .task(String(id.value)) .then((res) => { events.value = keepValue(events.value, res || []); }) .catch(() => { events.value = null; }); } function loadLogs(attempt: number, opts?: { force?: boolean; keep?: boolean }): void { if (id.value == null) return; const current = filters.value; keyedLoad( logCacheKey(id.value, attempt, current), () => api.taskLogs(String(id.value), { attempt: attempt || undefined, level: current.level, stage: current.stage, limit: 500, }), logs, opts, ); } function loadChanges(attempt: number, opts?: { force?: boolean; keep?: boolean }): void { if (id.value == null) return; keyedLoad( attemptKey(id.value, attempt), () => api.taskChanges(String(id.value), { attempt }), changes, opts, ); } function loadDebug(attempt: number, opts?: { force?: boolean; keep?: boolean }): void { if (id.value == null) return; keyedLoad( attemptKey(id.value, attempt), () => api.taskDebug(String(id.value), { attempt }), debug, opts, ); } /** Drop every cache so a manual refresh cannot show a stale capture or log * beside fresh attempt history. */ function dropCaches(): void { // Invalidate in-flight reads too: a response that lands after the drop // would otherwise write its stale payload into the fresh caches. cacheGeneration++; loadGenerations.clear(); logs.value = new Map(); changes.value = new Map(); debug.value = new Map(); } function refreshAll(): void { dropCaches(); requestedAttempt.value = null; loadTaskList(); loadAttempts(true); loadEvents(true); refreshToken.value += 1; } /** Re-read what is on screen after a live event, keeping it visible until * the new response lands. Cached payloads for other tabs and attempts are * dropped so they are re-read when shown. */ function refreshLive(): void { const attempt = attemptNumber.value; const visible = attempt == null ? null : tab.value; const keepOnly = (cache: Ref>, key: string | null) => { const value = key == null ? undefined : cache.value.get(key); cache.value = value == null || key == null ? new Map() : new Map([[key, value]]); }; keepOnly(logs, visible === "log" ? logKey.value : null); keepOnly(changes, visible === "changes" ? changeKey.value : null); keepOnly(debug, visible === "debug" ? debugKey.value : null); loadTaskList(); loadAttempts(true); loadEvents(true); if (attempt == null) return; const opts = { force: true, keep: true }; if (visible === "log") loadLogs(attempt, opts); else if (visible === "changes") loadChanges(attempt, opts); else if (visible === "debug") loadDebug(attempt, opts); } useLiveResource("tasks", refreshLive, 500); onMounted(() => { // The page loads once for the task it was opened for; the route remounts it // when that changes (App.vue keys the outlet on the path). if (id.value == null) return; loadTaskList(); loadAttempts(); loadEvents(); }); // A stage filter is a command scoped to the attempt it was made on: the rail // set it against that attempt's stage list. A different attempt presents a // different list, so the stage filter resets on an attempt switch and the // rail can never highlight a stage the operator did not select here. The // level filter is attempt-agnostic and survives. watch(attemptNumber, () => { if (filters.value.stage) filters.value = { ...filters.value, stage: "" }; }); watch([tab, attemptNumber, filters, refreshToken], () => { const attempt = attemptNumber.value; if (attempt == null) return; // Only the visible tab's lazy payload is fetched: the debug envelope // repeats the whole event list, so fetching it on every page load would // duplicate a large body for nothing. if (tab.value === "log") loadLogs(attempt); else if (tab.value === "changes") loadChanges(attempt); else if (tab.value === "debug") loadDebug(attempt); }, { immediate: true }); watch([tab, attemptNumber], () => { if (id.value == null) return; // The open tab and the pinned attempt are written back with router.replace // rather than a hash assignment or a push: replace adds no history entry, // so a tab click does not remount and refetch the page, while the address // bar still holds the full state for a copy, a bookmark or a reload. void router.replace({ query: runQuery(tab.value, attemptNumber.value) }); }); const run = reactive({ tab, attempts, taskList, events, missing, filters, task, attemptNumber, currentAttempt, stageNames, logState, changesState, debugState, setTab(next: string | number) { tab.value = String(next); }, selectAttempt(attempt: number) { requestedAttempt.value = attempt; }, setFilters(next: LogFilters) { filters.value = { ...next }; }, refreshAll, loadAttempts, loadEvents, loadTaskList, loadLogs, loadChanges, loadDebug, }); provide(TASK_RUN, run as TaskRun); return run as TaskRun; } /** The run state provided by the nearest TaskDetailPage. */ export function useTaskRun(): TaskRun { const run = inject(TASK_RUN); if (!run) throw new Error("useTaskRun() must be called under a TaskDetailPage"); return run; }