Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
98 changes: 75 additions & 23 deletions apps/web/src/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,9 @@ export async function api<T>(path: string, options: { method?: string; body?: un

const trafficLimit = 300;

/** How long to wait before opening the event stream again after each failure in a row. */
const retryDelaysMs = [3_000, 5_000, 10_000, 15_000, 30_000];

/** The latest `trafficLimit` requests and as many other events, so a burst of requests cannot hide startup or a failure. */
function trimTraffic(events: TrafficEvent[]) {
let requests = 0;
Expand Down Expand Up @@ -64,40 +67,89 @@ export function useLive() {
useEffect(() => {
let cancelled = false;
let streaming = false;
// Cloudflare's quick tunnels hold event streams back, so until the stream delivers, read the same data every few seconds.
const loadTraffic = (onlyWhileWaiting: boolean) =>
void api<TrafficEvent[]>("/traffic").then((recent) => !cancelled && !(onlyWhileWaiting && streaming) && setTraffic(trimTraffic(recent)), () => {});
// Stream events that arrive while the traffic list loads, which the list may have been read before. Set only while
// a load is under way.
let arrived: TrafficEvent[] | undefined;
let loads = 0;
const loadTraffic = (onlyWhileWaiting: boolean) => {
// A poll leaves a load still under way to finish. Otherwise polls every 5 seconds would each replace a slower one,
// and none would ever count.
if (onlyWhileWaiting && arrived) return;
const load = ++loads;
arrived = [];
void api<TrafficEvent[]>("/traffic").then(
(recent) => {
// Only the latest load counts: an earlier one read an older list.
if (cancelled || load !== loads) return;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const during = arrived ?? [];
arrived = undefined;
if (onlyWhileWaiting && streaming) return;
const last = recent.at(-1)?.id ?? 0;
setTraffic(trimTraffic([...recent, ...during.filter((event) => event.id > last)]));
},
() => {
if (load === loads) arrived = undefined;
},
);
};
const loadOverview = () => void api<Overview>("/overview").then((next) => !cancelled && !streaming && setOverview(next), () => {});
loadTraffic(false);
loadOverview();
// Cloudflare's quick tunnels hold event streams back, so until the stream delivers, read the same data every few seconds.
const polling = setInterval(() => {
loadTraffic(true);
loadOverview();
}, 5_000);
const source = new EventSource("/admin/api/events");
source.onopen = () => setOnline(true);
source.onerror = () => {
setOnline(false);
// A closed stream after a failed reconnect usually means the session ended, such as after a password change elsewhere.
if (source.readyState !== EventSource.CLOSED) return;
void api<{ authenticated: boolean }>("/auth").then(
(auth) => {
if (!auth.authenticated) for (const listener of loggedOut) listener();
},
() => {},
);
};
source.onmessage = (event) => {
streaming = true;
clearInterval(polling);
const live = JSON.parse(event.data as string) as LiveMessage;
if (live.type === "overview") setOverview(live.overview);
else setTraffic((current) => trimTraffic([...current, live.event]));
let source: EventSource | undefined;
let retry: ReturnType<typeof setTimeout> | undefined;
let failures = 0;
let opens = 0;
const connect = () => {
const stream = new EventSource("/admin/api/events");
source = stream;
stream.onopen = () => {
setOnline(true);
// The stream starts with the overview. Requests made while it was down, or before a first stream that took
// several tries, come from the traffic list.
if (opens++ > 0 || failures > 0) loadTraffic(false);
failures = 0;
};
stream.onerror = () => {
setOnline(false);
// The browser retries a dropped connection by itself, but gives up for good on an error answer, such as
// the tunnel's while VM Bridge restarts. Then open a new stream, waiting longer after each failure.
if (stream.readyState !== EventSource.CLOSED) return;
const delay = retryDelaysMs[Math.min(failures++, retryDelaysMs.length - 1)];
if (!cancelled) retry = setTimeout(connect, delay);
// It can also mean the session ended, such as after a password change elsewhere. Checked beside the retry, so
// a check that never answers cannot hold the retry up.
void api<{ authenticated: boolean }>("/auth").then(
(auth) => {
if (auth.authenticated) return;
clearTimeout(retry);
for (const listener of loggedOut) listener();
},
() => {},
);
};
stream.onmessage = (event) => {
streaming = true;
clearInterval(polling);
const live = JSON.parse(event.data as string) as LiveMessage;
if (live.type === "overview") setOverview(live.overview);
else {
// Bounded like the list itself, in case the load takes a long time.
if (arrived) arrived = trimTraffic([...arrived, live.event]);
setTraffic((current) => trimTraffic([...current, live.event]));
}
};
};
connect();
return () => {
cancelled = true;
clearInterval(polling);
source.close();
clearTimeout(retry);
source?.close();
};
}, []);

Expand Down