64 lines
1.9 KiB
TypeScript
64 lines
1.9 KiB
TypeScript
// SPDX-License-Identifier: CPAL-1.0
|
|
// Copyright (c) 2026 Marek Novák. Part of Ianitor, under the Common Public Attribution
|
|
// License 1.0: see LICENSE (its Exhibit A is this file's notice).
|
|
|
|
// Following an apply (handoff §2.2 of ui-api, §3 here): GET /applies/{id} every second while it
|
|
// runs; quiet retries while edge reloads; the id kept in sessionStorage so a reload resumes it.
|
|
|
|
import { get } from "./api";
|
|
import { app, refresh } from "./app.svelte";
|
|
import type { ApplyView } from "./types";
|
|
|
|
export const FINAL = ["kept", "reverted", "failed", "needs_attention"];
|
|
const KEY = "ianitor.activeApply";
|
|
|
|
export function remember(id: string | null): void {
|
|
try {
|
|
if (id) sessionStorage.setItem(KEY, id);
|
|
else sessionStorage.removeItem(KEY);
|
|
} catch {
|
|
/* storage may be off; the bar still shows the running apply */
|
|
}
|
|
}
|
|
|
|
export function remembered(): string | null {
|
|
try {
|
|
return sessionStorage.getItem(KEY);
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
/** Poll until the apply ends. Returns a stop function. */
|
|
export function follow(id: string, onupdate: (a: ApplyView) => void, every = 1000): () => void {
|
|
let stopped = false;
|
|
let timer: ReturnType<typeof setTimeout> | undefined;
|
|
remember(id);
|
|
const tick = async () => {
|
|
if (stopped) return;
|
|
if (app.signedOut) {
|
|
// No requests while signed out (the overview poll stops too); look again shortly.
|
|
timer = setTimeout(tick, every);
|
|
return;
|
|
}
|
|
try {
|
|
const a = await get<ApplyView>(`/applies/${encodeURIComponent(id)}`);
|
|
if (stopped) return;
|
|
onupdate(a);
|
|
if (FINAL.includes(a.state)) {
|
|
remember(null);
|
|
void refresh();
|
|
return;
|
|
}
|
|
} catch {
|
|
/* lost contact or a reload in progress: keep trying (the banner says so after 10 s) */
|
|
}
|
|
timer = setTimeout(tick, every);
|
|
};
|
|
void tick();
|
|
return () => {
|
|
stopped = true;
|
|
clearTimeout(timer);
|
|
};
|
|
}
|