Skip to content

Commit 7c9c521

Browse files
fix(ui): show when the Substrate lists were read, not a running age (#3545)
--- *Written by 🤖 (start)* The Substrate page's actor and worker lists now show `Read at 4:41:02 PM` instead of `read 12.3s ago`, which re-rendered twice a second and pulled the eye off the rows. While polling, a list that goes 3 intervals (at least 5s) without a new read adds its age in the warning colour, e.g. `Read at 4:41:02 PM, 12s ago`. # Testing 1. Open Substrate. Each list shows `Read at <time>`, which changes only when the list refreshes. 2. Turn polling on, then make the API hang. After about 5s, each list reads `Read at <time>, <n>s ago` in amber. --- *Written by 🤖 (end)* --------- Signed-off-by: Nicholas Bucher <[email protected]>
1 parent 2e2acf5 commit 7c9c521

2 files changed

Lines changed: 108 additions & 14 deletions

File tree

‎ui/src/pages/SubstratePage.tsx‎

Lines changed: 63 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -692,25 +692,74 @@ function SectionSearch({
692692

693693
const PAGE_SIZE = 25;
694694

695-
function PageAge({ computedAt }: { computedAt?: string }) {
695+
/**
696+
* When the list was read, as a clock time rather than a running age: an age that ticks
697+
* twice a second pulls the eye off the rows while saying nothing new.
698+
*
699+
* While polling, a list with no new read for `STALLED_AFTER_TICKS` intervals adds how
700+
* long it has gone without one, in the warning colour. That is the stall the old age
701+
* showed, now shown only when it is happening.
702+
*/
703+
function PageAge({ computedAt, pollMs }: { computedAt?: string; pollMs?: number }) {
696704
const theme = useTheme();
697-
const age = useDataAge(computedAt);
698-
return <Text css={{ color: theme.color.textMuted, fontSize: 12 }}>{age}</Text>;
705+
const stalledMs = useStalledFor(computedAt, pollMs);
706+
const at = readAt(computedAt);
707+
if (stalledMs === undefined) {
708+
return <Text css={{ color: theme.color.textMuted, fontSize: 12 }}>{at}</Text>;
709+
}
710+
return (
711+
<Text css={{ color: theme.color.warning, fontSize: 12 }}>
712+
{`${at}, ${elapsed(stalledMs)} ago`}
713+
</Text>
714+
);
699715
}
700716

701-
function useDataAge(computedAt: string | undefined): string {
702-
const [now, setNow] = useState(() => Date.now());
717+
const STALLED_AFTER_TICKS = 3;
718+
// A floor, so a half-second interval does not call one slow read a stall.
719+
const STALLED_FLOOR_MS = 5_000;
720+
721+
/**
722+
* How long a polled list has gone without a new read, once that is a stall.
723+
*
724+
* Measured on the browser's clock from when `computedAt` last changed, not from
725+
* `computedAt` itself, so a skewed server clock cannot raise it.
726+
*/
727+
function useStalledFor(computedAt: string | undefined, pollMs: number | undefined) {
728+
const [stall, setStall] = useState<{ key?: string; ms: number }>();
729+
703730
useEffect(() => {
704-
const timer = window.setInterval(() => setNow(Date.now()), 500);
731+
if (pollMs === undefined) return;
732+
const sinceMs = Date.now();
733+
const limitMs = Math.max(STALLED_AFTER_TICKS * pollMs, STALLED_FLOOR_MS);
734+
const timer = window.setInterval(() => {
735+
const ms = Date.now() - sinceMs;
736+
setStall(ms >= limitMs ? { key: computedAt, ms } : undefined);
737+
}, 1_000);
705738
return () => window.clearInterval(timer);
706-
}, []);
739+
}, [computedAt, pollMs]);
707740

741+
// A stall belongs to the read it was measured against; a new read clears it at once.
742+
return pollMs !== undefined && stall !== undefined && stall.key === computedAt
743+
? stall.ms
744+
: undefined;
745+
}
746+
747+
function readAt(computedAt: string | undefined): string {
708748
if (!computedAt) return "";
709-
const at = new Date(computedAt).getTime();
710-
if (Number.isNaN(at)) return "";
711-
const seconds = Math.max(0, (now - at) / 1000);
712-
if (seconds < 1) return "read just now";
713-
return `read ${seconds.toFixed(1)}s ago`;
749+
const at = new Date(computedAt);
750+
if (Number.isNaN(at.getTime())) return "";
751+
return `Read at ${at.toLocaleTimeString([], {
752+
hour: "numeric",
753+
minute: "2-digit",
754+
second: "2-digit",
755+
})}`;
756+
}
757+
758+
/** `12s`, `3m 05s`. */
759+
function elapsed(ms: number): string {
760+
const whole = Math.floor(ms / 1_000);
761+
if (whole < 60) return `${whole}s`;
762+
return `${Math.floor(whole / 60)}m ${String(whole % 60).padStart(2, "0")}s`;
714763
}
715764

716765
function PageWarning({ message, testId }: { message: string; testId: string }) {
@@ -1484,7 +1533,7 @@ export function SubstratePage() {
14841533
"& > [data-testid$='-pages']": { marginTop: 0 },
14851534
}}
14861535
>
1487-
<PageAge computedAt={actors.data?.computedAt} />
1536+
<PageAge computedAt={actors.data?.computedAt} pollMs={isTicking ? pollMs : undefined} />
14881537

14891538
<PageControls
14901539
testId="substrate-actors-pages"
@@ -1562,7 +1611,7 @@ export function SubstratePage() {
15621611
"& > [data-testid$='-pages']": { marginTop: 0 },
15631612
}}
15641613
>
1565-
<PageAge computedAt={workers.data?.computedAt} />
1614+
<PageAge computedAt={workers.data?.computedAt} pollMs={isTicking ? pollMs : undefined} />
15661615

15671616
<PageControls
15681617
testId="substrate-workers-pages"
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
import { act, fireEvent, render, screen } from "@testing-library/react";
2+
import { ThemeProvider } from "@emotion/react";
3+
import { MemoryRouter } from "react-router-dom";
4+
import { SWRConfig } from "swr";
5+
import { afterEach, expect, it, vi } from "vitest";
6+
import { createRouterTransport } from "@connectrpc/connect";
7+
import { timestampFromDate } from "@bufbuild/protobuf/wkt";
8+
import { SystemService } from "@/generated/kagent/api/v1/system_pb";
9+
import { setApiTransport } from "@/api/transport";
10+
import { themeFor } from "@/theme/theme";
11+
import { SubstratePage } from "./SubstratePage";
12+
13+
afterEach(() => {
14+
setApiTransport(undefined);
15+
vi.useRealTimers();
16+
});
17+
18+
// The lists answer once, then hang: polling keeps asking and no new read lands.
19+
it("shows how long a polled list has gone without a new read", async () => {
20+
vi.useFakeTimers({ toFake: ["setInterval", "clearInterval", "Date"] });
21+
const hang = () => new Promise<never>(() => {});
22+
let actorReads = 0;
23+
setApiTransport(createRouterTransport(({ service }) => service(SystemService, {
24+
listNamespaces: () => ({}),
25+
getSubstrateSummary: () => ({}),
26+
listSubstrateActors: () =>
27+
actorReads++ === 0 ? { computedAt: timestampFromDate(new Date()) } : hang(),
28+
listSubstrateWorkers: () => ({ computedAt: timestampFromDate(new Date()) }),
29+
})));
30+
render(<ThemeProvider theme={themeFor("dark")}>
31+
<SWRConfig value={{ provider: () => new Map(), shouldRetryOnError: false }}>
32+
<MemoryRouter><SubstratePage /></MemoryRouter>
33+
</SWRConfig>
34+
</ThemeProvider>);
35+
36+
const [actorsAge] = await screen.findAllByText(/^Read at /);
37+
expect(actorsAge).not.toHaveTextContent(/ago$/);
38+
39+
fireEvent.click(screen.getByTestId("substrate-poll-toggle"));
40+
await act(async () => {
41+
vi.advanceTimersByTime(8_000);
42+
});
43+
44+
expect(actorsAge).toHaveTextContent(/^Read at .+, \d+s ago$/);
45+
});

0 commit comments

Comments
 (0)