Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

SlowRpcRequestToastCoordinator.tsx

75 lines2.2 KB

1import { useEffect, useRef } from "react";
2​
3import { type SlowRpcAckRequest, useSlowRpcAckRequests } from "../rpc/requestLatencyState";
4import { toastManager } from "./ui/toast";
5​
6function describeSlowRequests(requests: ReadonlyArray<SlowRpcAckRequest>): string {
7 const count = requests.length;
8 const thresholdSeconds = Math.round(
9 Math.min(...requests.map((request) => request.thresholdMs)) / 1000,
10 );
11​
12 return `${count} request${count === 1 ? "" : "s"} waiting longer than ${thresholdSeconds}s.`;
14​
15function SlowRequestDetails({ requests }: { requests: ReadonlyArray<SlowRpcAckRequest> }) {
16 return (
17 <ul className="space-y-2.5 text-xs text-muted-foreground">
18 {requests.map((request) => (
19 <li
20 className="min-w-0 border-border/50 border-b pb-2 last:border-b-0 last:pb-0"
21 key={request.requestId}
22 >
23 <div className="wrap-break-word font-medium text-foreground">{request.tag}</div>
24 <div className="mt-0.5 text-3xs opacity-75">
25 Started {new Date(request.startedAt).toLocaleTimeString()}
26 </div>
27 </li>
28 ))}
29 </ul>
30 );
32​
33export function SlowRpcRequestToastCoordinator() {
34 const slowRequests = useSlowRpcAckRequests();
35 const toastIdRef = useRef<ReturnType<typeof toastManager.add> | null>(null);
36​
37 useEffect(() => {
38 if (slowRequests.length === 0) {
39 if (toastIdRef.current !== null) {
40 toastManager.close(toastIdRef.current);
41 toastIdRef.current = null;
42 }
43 return;
44 }
45​
46 const nextToast = {
47 data: {
48 expandableContent: <SlowRequestDetails requests={slowRequests} />,
49 expandableDescriptionTrigger: true,
50 expandableLabels: { collapse: "Hide requests", expand: "Show requests" },
51 },
52 description: describeSlowRequests(slowRequests),
53 timeout: 0,
54 title: "Some requests are slow",
55 type: "warning" as const,
56 };
57​
58 if (toastIdRef.current === null) {
59 toastIdRef.current = toastManager.add(nextToast);
60 } else {
61 toastManager.update(toastIdRef.current, nextToast);
62 }
63 }, [slowRequests]);
64​
65 useEffect(
66 () => () => {
67 if (toastIdRef.current !== null) {
68 toastManager.close(toastIdRef.current);
69 }
70 },
71 [],
72 );
73​
74 return null;