Repository Public
1"use client";2import { useQueryClient, type QueryClient } from "@tanstack/react-query";3import { createContext, useContext, useEffect, useMemo, useRef, useSyncExternalStore, type ReactNode } from "react";4import type { Schemas } from "@/api/client";5import { invalidatePaths } from "@/api/query";6import { SseClient, type SseMessage, type SseStatus } from "@/lib/sse";7import { ME_KEY, useSession } from "./session";89type Payloads = {10 "node.state": Schemas["NodeStateEvent"];11 "node.updated": Schemas["NodeUpdatedEvent"];12 "alert.changed": Schemas["AlertChangedEvent"];13 "incident.changed": Schemas["IncidentChangedEvent"];14 "action.changed": Schemas["ActionChangedEvent"];15 "action.output": Schemas["ActionOutputEvent"];16 "service.changed": Schemas["ServiceChangedEvent"];17 "job.changed": Schemas["JobChangedEvent"];18 "maintenance.changed": Schemas["MaintenanceChangedEvent"];19 "audit.appended": Schemas["AuditAppendedEvent"];20 resync: Schemas["ResyncEvent"];21};22export type Topic = keyof Payloads;23type Handler<T extends Topic> = (payload: Payloads[T]) => void;2425/** Topic → API path prefixes whose cached queries are refreshed. */26const INVALIDATES: Record<string, string[]> = {27 "node.updated": ["/nodes", "/cluster/overview", "/network", "/storage/volumes", "/agents"],28 "alert.changed": ["/alerts", "/incidents", "/cluster/overview", "/activity"],29 "incident.changed": ["/incidents", "/cluster/overview", "/activity"],30 "action.changed": ["/actions", "/activity", "/cluster/overview"],31 "service.changed": ["/services", "/nodes/{id}/services", "/cluster/overview"],32 "job.changed": ["/jobs", "/cluster/overview"],33 "maintenance.changed": ["/maintenance", "/nodes", "/activity", "/silences"],34 "audit.appended": ["/audit"],35 "model.changed": ["/models", "/cluster/overview"],36};3738export interface LastEvent {39 id: string | undefined;40 topic: string;41 at: number;42}43interface Realtime {44 subscribeStatus: (fn: () => void) => () => void;45 getStatus: () => SseStatus;46 subscribeLast: (fn: () => void) => () => void;47 getLast: () => LastEvent | null;48 on: <T extends Topic>(topic: T, handler: Handler<T>) => () => void;49}50const IDLE: SseStatus = { state: "closed", since: 0, attempt: 0 };51const Ctx = createContext<Realtime | null>(null);5253function patchNodeState(qc: QueryClient, ev: Schemas["NodeStateEvent"]) {54 const apply = (n: Schemas["Node"]): Schemas["Node"] =>55 n.id !== ev.node_id ? n : { ...n, ...(ev.freshness ? { freshness: ev.freshness } : {}), ...(typeof ev.maintenance === "boolean" ? { maintenance: ev.maintenance } : {}), ...(ev.headline ? { headline: ev.headline } : {}), ...(ev.observed_at ? { observed_at: ev.observed_at, last_seen_at: ev.observed_at } : {}) };56 qc.setQueriesData<unknown>({ predicate: (q) => q.queryKey[0] === "/nodes" }, (old: unknown) => {57 if (!old || typeof old !== "object") return old;58 if ("pages" in old) {59 const o = old as { pages: Schemas["NodeList"][]; pageParams: unknown[] };60 return { ...o, pages: o.pages.map((p) => ({ ...p, items: p.items.map(apply) })) };61 }62 if ("items" in old) {63 const o = old as Schemas["NodeList"];64 return { ...o, items: o.items.map(apply) };65 }66 return old;67 });68 qc.setQueriesData<Schemas["NodeDetail"]>({ predicate: (q) => q.queryKey[0] === "/nodes/{id}" }, (old) => (old && old.node.id === ev.node_id ? { ...old, node: apply(old.node) } : old));69}7071export function RealtimeProvider({ children }: { children: ReactNode }) {72 const qc = useQueryClient();73 const { status } = useSession();74 const statusRef = useRef<SseStatus>(IDLE);75 const listeners = useRef(new Set<() => void>());76 const lastRef = useRef<LastEvent | null>(null);77 const lastListeners = useRef(new Set<() => void>());78 const handlers = useRef(new Map<string, Set<(p: never) => void>>());79 const pending = useRef(new Set<string>());80 const flushTimer = useRef<number | null>(null);8182 useEffect(() => {83 if (status !== "authenticated") return;84 // coalesce invalidations: a burst of events refetches each affected path once per second at most85 const schedule = (paths: string[]) => {86 paths.forEach((p) => pending.current.add(p));87 if (flushTimer.current !== null) return;88 flushTimer.current = window.setTimeout(() => {89 flushTimer.current = null;90 const batch = [...pending.current];91 pending.current.clear();92 void invalidatePaths(qc, ...batch);93 }, 1000);94 };95 let lastOverview = 0;96 const onMessage = (m: SseMessage) => {97 if (m.event === "hello") return;98 lastRef.current = { id: m.id, topic: m.event, at: Date.now() };99 lastListeners.current.forEach((fn) => fn());100 let payload: unknown;101 try {102 payload = JSON.parse(m.data || "{}");103 } catch {104 return;105 }106 if (m.event === "resync") {107 void qc.invalidateQueries({ predicate: (q) => q.queryKey[0] !== ME_KEY[0] });108 } else if (m.event === "node.state") {109 patchNodeState(qc, payload as Schemas["NodeStateEvent"]);110 const now = Date.now();111 if (now - lastOverview > 5000) {112 lastOverview = now;113 schedule(["/cluster/overview"]);114 }115 } else {116 const paths = INVALIDATES[m.event];117 if (paths) schedule(paths);118 }119 handlers.current.get(m.event)?.forEach((h) => (h as (p: unknown) => void)(payload));120 };121 const client = new SseClient({122 url: "/api/v1/events",123 onMessage,124 onStatus: (s) => {125 const was = statusRef.current.state;126 statusRef.current = s;127 listeners.current.forEach((fn) => fn());128 // back online after an interruption: whatever happened meanwhile is covered by Last-Event-ID replay, and a129 // refetch of active queries makes the screen consistent even if the server answered `resync`130 if (s.state === "live" && (was === "reconnecting" || was === "offline")) void qc.invalidateQueries({ predicate: (q) => q.queryKey[0] !== ME_KEY[0], refetchType: "active" });131 },132 onUnauthorized: () => qc.setQueryData(ME_KEY, null),133 });134 client.start();135 const wake = () => client.wake();136 window.addEventListener("online", wake);137 document.addEventListener("visibilitychange", wake);138 return () => {139 window.removeEventListener("online", wake);140 document.removeEventListener("visibilitychange", wake);141 client.stop();142 if (flushTimer.current !== null) window.clearTimeout(flushTimer.current);143 flushTimer.current = null;144 };145 }, [qc, status]);146147 const value = useMemo<Realtime>(148 () => ({149 subscribeStatus: (fn) => {150 listeners.current.add(fn);151 return () => listeners.current.delete(fn);152 },153 getStatus: () => statusRef.current,154 subscribeLast: (fn) => {155 lastListeners.current.add(fn);156 return () => lastListeners.current.delete(fn);157 },158 getLast: () => lastRef.current,159 on: (topic, handler) => {160 let set = handlers.current.get(topic);161 if (!set) handlers.current.set(topic, (set = new Set()));162 set.add(handler as (p: never) => void);163 return () => set.delete(handler as (p: never) => void);164 },165 }),166 [],167 );168 return <Ctx.Provider value={value}>{children}</Ctx.Provider>;169}170171export function useRealtimeStatus(): SseStatus {172 const rt = useContext(Ctx);173 if (!rt) throw new Error("useRealtimeStatus outside RealtimeProvider");174 return useSyncExternalStore(rt.subscribeStatus, rt.getStatus, () => IDLE);175}176177/** Last event received on the stream (diagnostics: shown by the connection indicator). */178export function useLastEvent(): LastEvent | null {179 const rt = useContext(Ctx);180 if (!rt) throw new Error("useLastEvent outside RealtimeProvider");181 return useSyncExternalStore(rt.subscribeLast, rt.getLast, () => null);182}183184/** Subscribe a component to one event topic (payload typed from the contract). */185export function useEvent<T extends Topic>(topic: T, handler: Handler<T>): void {186 const rt = useContext(Ctx);187 const ref = useRef(handler);188 useEffect(() => {189 ref.current = handler;190 });191 useEffect(() => {192 if (!rt) return;193 return rt.on(topic, ((p: Payloads[T]) => ref.current(p)) as Handler<T>);194 }, [rt, topic]);195}196