Watch
0
0
Fork
You've already forked hyperhive
0

swarm-ui: one polled-resource hook for the refreshing pages

Each polling page repeated its own fetch-and-set code on a fixed timer,
so a slow answer could be overtaken by the next tick, an older response
could overwrite a newer one, and nothing aborted a request when the page
went away.

usePolled skips a tick while a request is in flight, aborts on unmount
or refresh, ignores answers from dropped requests, and keeps the last
good data under an error. The alerts, hives, agents, schedules, builds,
review runs and broadcast pages and the subagent list use it.
This commit is contained in:
iris 2026-10-21 22:03:59 +02:00 • committed by mara
commit 8917ba27b6

View file

@ -0,0 +1,53 @@
// The request discipline behind a polled page, kept free of Preact so it can
// be tested on its own. `tick` fetches unless a request is already in flight,
// so a slow answer is not overtaken by the next tick. `refetch` drops the
// request in flight and asks again, for a refresh that follows a change.
// `stop` drops the request in flight. An answer from a dropped request never
// reaches `onData` or `onError`, so an older response cannot overwrite a
// newer one or land on a page that is gone.
export interface Poller {
tick(): void;
refetch(): void;
stop(): void;
}
export function createPoller<T>(opts: {
fetch: (signal: AbortSignal) => Promise<T>;
onData: (data: T) => void;
onError: (error: unknown) => void;
}): Poller {
let current: { controller: AbortController } | null = null;
function start() {
const run = { controller: new AbortController() };
current = run;
opts.fetch(run.controller.signal).then(
(data) => {
if (current !== run) return;
current = null;
opts.onData(data);
},
(error: unknown) => {
if (current !== run) return;
current = null;
opts.onError(error);
},
);
}
function stop() {
current?.controller.abort();
current = null;
}
return {
tick() {
if (current === null) start();
},
refetch() {
stop();
start();
},
stop,
};
}