fix(webui): multiplex dashboard live updates over one stream
This commit is contained in:
1 parent
c1143ea3db
commit
29004db774
25 files changed
+835
-322
No files matched your search
+19
-28
@@ -2,8 +2,9 @@
|
||||
// through api.* below, and every api.* method goes through send(), so the CSRF
|
||||
// header, the Content-Type, the request timeout, and the error shape live in
|
||||
// this one file.
|
||||
import { streamStateFor, type StreamState } from "./stream-state";
|
||||
import { randomUUID } from "./uuid";
|
||||
import { streamStateFor, type StreamState } from "./stream-state.ts";
|
||||
import { streamURL } from "./stream-url.ts";
|
||||
import { randomUUID } from "./uuid.ts";
|
||||
|
||||
// DEFAULT_TIMEOUT_MS bounds a request so a daemon that accepts the connection
|
||||
// but never answers cannot leave the UI in a loading state with no way back.
|
||||
@@ -318,38 +319,28 @@ export const api = {
|
||||
* Reconnection is the browser's job via EventSource, but a closed stream is
|
||||
* surfaced to the caller so the UI can show it rather than silently freezing.
|
||||
*/
|
||||
export interface StreamFrame {
|
||||
topic: string;
|
||||
data: unknown;
|
||||
}
|
||||
|
||||
/** One EventSource per tab. Re-creating it on Logs entry/exit carries the
|
||||
* last multi-topic cursor in ?since; native reconnects use Last-Event-ID. */
|
||||
export function subscribeEvents(
|
||||
onEvent: (event: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
onFrame: (frame: StreamFrame, cursor: string) => void,
|
||||
onStateChange: (state: StreamState) => void,
|
||||
cursor = "",
|
||||
logs = false,
|
||||
): () => void {
|
||||
const src = new EventSource("/api/stream");
|
||||
src.onopen = () => onStateChange?.("live");
|
||||
src.onerror = () => onStateChange?.("reconnecting");
|
||||
src.onmessage = (e) => {
|
||||
const src = new EventSource(streamURL(cursor, logs));
|
||||
src.onopen = () => onStateChange("live");
|
||||
src.onerror = () => onStateChange(streamStateFor(src.readyState));
|
||||
src.onmessage = (event) => {
|
||||
try {
|
||||
onEvent(JSON.parse(e.data));
|
||||
onFrame(JSON.parse(event.data) as StreamFrame, event.lastEventId);
|
||||
} catch {
|
||||
/* a malformed frame should not kill the stream */
|
||||
}
|
||||
};
|
||||
return () => src.close();
|
||||
}
|
||||
|
||||
export function subscribeLogs(
|
||||
onEntry: (entry: unknown) => void,
|
||||
onStateChange?: (state: StreamState) => void,
|
||||
): () => void {
|
||||
const src = new EventSource("/api/logs/stream");
|
||||
src.onopen = () => onStateChange?.("live");
|
||||
// onerror fires both for a drop the browser will retry and for one it has
|
||||
// given up on; readyState is what tells them apart.
|
||||
src.onerror = () => onStateChange?.(streamStateFor(src.readyState));
|
||||
src.onmessage = (event) => {
|
||||
try {
|
||||
onEntry(JSON.parse(event.data));
|
||||
} catch {
|
||||
/* malformed log frame */
|
||||
}
|
||||
};
|
||||
return () => src.close();
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
// A deliberate EventSource replacement does not inherit Last-Event-ID from
|
||||
// its predecessor. Carry the last multi-topic token in the new URL instead.
|
||||
export function streamURL(cursor: string, logs: boolean): string {
|
||||
const params = new URLSearchParams();
|
||||
if (cursor) params.set("since", cursor);
|
||||
if (logs) params.set("topics", "logs");
|
||||
return `/api/stream${params.size ? `?${params}` : ""}`;
|
||||
}
|
||||
@@ -26,7 +26,7 @@ export function logsEmptyDetail(
|
||||
streamState: string,
|
||||
): string {
|
||||
if (streamState === "unavailable") {
|
||||
return "The log stream will reconnect automatically.";
|
||||
return "This process is not delivering live daemon logs.";
|
||||
}
|
||||
if (durableUnavailable) {
|
||||
return "This deployment keeps no durable history. Live daemon logs appear here while the page is open.";
|
||||
|
||||
+17
-5
@@ -1,6 +1,7 @@
|
||||
import { computed, onMounted, onUnmounted, reactive, ref, watch } from "vue";
|
||||
|
||||
import { api, subscribeLogs } from "@/lib/api";
|
||||
import { api } from "@/lib/api";
|
||||
import { useLiveUpdatesStore } from "@/stores/live-updates";
|
||||
import type { LogEntry } from "@/lib/log";
|
||||
import type { StatusKind } from "@/lib/status";
|
||||
import type { StreamState } from "@/lib/stream-state";
|
||||
@@ -138,6 +139,7 @@ let unsubscribe: (() => void) | undefined;
|
||||
/** Owns the initial read, the re-reads a filter change causes, and the live
|
||||
* stream, for the page's lifetime. */
|
||||
export function useLogs(): void {
|
||||
const live = useLiveUpdatesStore();
|
||||
onMounted(() => {
|
||||
// A mount opens a new stream against a fresh read, so the tail starts
|
||||
// unpaused, connecting, and without the lines the previous visit's stream
|
||||
@@ -149,11 +151,21 @@ export function useLogs(): void {
|
||||
liveTick.value += 1;
|
||||
|
||||
void loadLogs();
|
||||
unsubscribe = subscribeLogs(handleEntry, (state) => {
|
||||
streamState.value = state;
|
||||
});
|
||||
unsubscribe = live.subscribe("logs", handleEntry);
|
||||
streamState.value = live.streamState;
|
||||
});
|
||||
onUnmounted(() => unsubscribe?.());
|
||||
onUnmounted(() => {
|
||||
unsubscribe?.();
|
||||
unsubscribe = undefined;
|
||||
});
|
||||
watch(() => live.streamState, (state) => {
|
||||
streamState.value = state;
|
||||
});
|
||||
// A process without a LogFeed cannot deliver live entries.
|
||||
const stopStatus = live.subscribe("logs-status", (data) => {
|
||||
if (!(data as { available: boolean }).available) streamState.value = "unavailable";
|
||||
});
|
||||
onUnmounted(stopStatus);
|
||||
|
||||
// Every filter is a server-side one -- the request carries it -- so a change
|
||||
// to any of them is a new read, not a re-filter of what is already here.
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { computed, reactive, ref } from "vue";
|
||||
import { computed, onScopeDispose, reactive, ref, watch } from "vue";
|
||||
import { useLiveUpdatesStore } from "./live-updates.ts";
|
||||
|
||||
export interface ResourceDescriptor {
|
||||
kind: string;
|
||||
@@ -229,7 +230,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
const catalog = ref<ResourceDescriptor[]>([]);
|
||||
const catalogError = ref("");
|
||||
const states = reactive<Record<string, ResourceState>>({});
|
||||
const streams = new Map<string, EventSource>();
|
||||
const live = useLiveUpdatesStore();
|
||||
const applyStatus = ref<ApplyStatusResponse>({ records: [], processes: [] });
|
||||
|
||||
const genericResources = computed(() =>
|
||||
@@ -247,7 +248,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
loading: false,
|
||||
saving: false,
|
||||
conflict: false,
|
||||
stream: "connecting",
|
||||
stream: live.streamState === "live" ? "live" : "connecting",
|
||||
};
|
||||
return states[kind];
|
||||
}
|
||||
@@ -278,28 +279,22 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
}
|
||||
}
|
||||
|
||||
function watchResource(kind: string): void {
|
||||
if (streams.has(kind)) return;
|
||||
const state = stateFor(kind);
|
||||
const after = state.resource?.version ?? 0;
|
||||
const stream = new EventSource(
|
||||
`/api/control-plane/watch/${encodeURIComponent(kind)}?after=${after}`,
|
||||
);
|
||||
stream.onopen = () => {
|
||||
state.stream = "live";
|
||||
};
|
||||
stream.onerror = () => {
|
||||
state.stream = "reconnecting";
|
||||
};
|
||||
stream.onmessage = (event) => {
|
||||
try {
|
||||
apply((JSON.parse(event.data) as ResourceResponse).resource);
|
||||
} catch {
|
||||
state.error = "Invalid live update";
|
||||
}
|
||||
};
|
||||
streams.set(kind, stream);
|
||||
}
|
||||
const stopResource = live.subscribe("control-plane", (data) => {
|
||||
const resource = (data as ResourceResponse).resource;
|
||||
if (resource?.kind) apply(resource);
|
||||
});
|
||||
const stopStatus = live.subscribe("apply-status", (data) => {
|
||||
applyStatus.value = data as ApplyStatusResponse;
|
||||
});
|
||||
const stopConnection = watch(() => live.streamState, (state) => {
|
||||
for (const resource of Object.values(states))
|
||||
resource.stream = state === "live" ? "live" : "reconnecting";
|
||||
});
|
||||
onScopeDispose(() => {
|
||||
stopResource();
|
||||
stopStatus();
|
||||
stopConnection();
|
||||
});
|
||||
|
||||
/** Re-read on every load and after each save, so the page reflects what the
|
||||
* processes did with the edit rather than what was stored. A failure leaves
|
||||
@@ -333,12 +328,7 @@ export const useControlPlaneStore = defineStore("control-plane", () => {
|
||||
catalog.value = response.resources ?? [];
|
||||
catalogError.value = "";
|
||||
await loadApplyStatus();
|
||||
await Promise.all(
|
||||
genericResources.value.map(async ({ kind }) => {
|
||||
await loadResource(kind);
|
||||
watchResource(kind);
|
||||
}),
|
||||
);
|
||||
await Promise.all(genericResources.value.map(({ kind }) => loadResource(kind)));
|
||||
} catch (error) {
|
||||
catalogError.value = String((error as Error).message || error);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { defineStore } from "pinia";
|
||||
import { onScopeDispose, ref } from "vue";
|
||||
import { useLiveUpdatesStore } from "./live-updates";
|
||||
|
||||
export interface Identity {
|
||||
id: string;
|
||||
@@ -27,7 +28,8 @@ export const useIdentitiesStore = defineStore("identities", () => {
|
||||
const identities = ref<Identity[]>([]);
|
||||
const error = ref("");
|
||||
const busy = ref("");
|
||||
let stream: EventSource | undefined;
|
||||
const live = useLiveUpdatesStore();
|
||||
let stop: (() => void) | undefined;
|
||||
|
||||
async function load(): Promise<void> {
|
||||
try {
|
||||
@@ -40,25 +42,11 @@ export const useIdentitiesStore = defineStore("identities", () => {
|
||||
}
|
||||
}
|
||||
function watch(): void {
|
||||
if (stream) return;
|
||||
if (stop) return;
|
||||
void load();
|
||||
stream = new EventSource("/api/identities/watch");
|
||||
stream.onmessage = (event) => {
|
||||
try {
|
||||
identities.value = (
|
||||
JSON.parse(event.data) as { identities: Identity[] }
|
||||
).identities;
|
||||
error.value = "";
|
||||
} catch {
|
||||
error.value = "Invalid live update";
|
||||
}
|
||||
};
|
||||
stream.onerror = () => {
|
||||
error.value = "Identity updates disconnected";
|
||||
};
|
||||
onScopeDispose(() => {
|
||||
stream?.close();
|
||||
stream = undefined;
|
||||
stop = live.subscribe("identities", (data) => {
|
||||
identities.value = (data as { identities: Identity[] }).identities;
|
||||
error.value = "";
|
||||
});
|
||||
}
|
||||
async function create(
|
||||
@@ -100,5 +88,6 @@ export const useIdentitiesStore = defineStore("identities", () => {
|
||||
busy.value = "";
|
||||
}
|
||||
}
|
||||
onScopeDispose(() => stop?.());
|
||||
return { identities, error, busy, watch, create, command };
|
||||
});
|
||||
@@ -8,14 +8,14 @@ import {
|
||||
type ComputedRef,
|
||||
} from "vue";
|
||||
|
||||
import { setAuthenticationStateHandler, subscribeEvents } from "@/lib/api";
|
||||
import { setAuthenticationStateHandler, subscribeEvents, type StreamFrame } from "../lib/api.ts";
|
||||
import type { StatusKind } from "@/lib/status";
|
||||
import type { StreamState } from "@/lib/stream-state";
|
||||
import {
|
||||
resourcesForEvent,
|
||||
type LiveEvent,
|
||||
type LiveResource,
|
||||
} from "./live-events";
|
||||
} from "./live-events.ts";
|
||||
|
||||
export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
const streamState = ref<StreamState | "connecting">("connecting");
|
||||
@@ -30,6 +30,9 @@ export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
updates: 0,
|
||||
});
|
||||
let unsubscribe: (() => void) | undefined;
|
||||
let cursor = "";
|
||||
let logsReaders = 0;
|
||||
const listeners = new Map<string, Set<(data: unknown) => void>>();
|
||||
|
||||
const streamKind: ComputedRef<StatusKind> = computed(() => {
|
||||
if (streamState.value === "live") return "ok";
|
||||
@@ -42,15 +45,41 @@ export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
for (const resource of resourcesForEvent(event)) revisions[resource] += 1;
|
||||
}
|
||||
|
||||
function handleFrame(frame: StreamFrame, lastEventId: string): void {
|
||||
if (lastEventId) cursor = lastEventId;
|
||||
if (frame.topic === "tasks") receive(frame.data);
|
||||
for (const listener of listeners.get(frame.topic) ?? []) listener(frame.data);
|
||||
}
|
||||
|
||||
function connect(): void {
|
||||
unsubscribe?.();
|
||||
streamState.value = "connecting";
|
||||
unsubscribe = subscribeEvents(handleFrame, (state) => {
|
||||
streamState.value = state;
|
||||
if (state === "live") connectionRevision.value += 1;
|
||||
}, cursor, logsReaders > 0);
|
||||
}
|
||||
|
||||
function initialize(): void {
|
||||
if (unsubscribe) return;
|
||||
setAuthenticationStateHandler((required) => {
|
||||
authenticationRequired.value = required;
|
||||
});
|
||||
unsubscribe = subscribeEvents(receive, (state) => {
|
||||
streamState.value = state;
|
||||
if (state === "live") connectionRevision.value += 1;
|
||||
});
|
||||
connect();
|
||||
}
|
||||
|
||||
/** Subscriptions are local callbacks, not browser connections. Only Logs
|
||||
* changes the upstream topic set and intentionally reconnects the stream. */
|
||||
function subscribe(topic: string, listener: (data: unknown) => void): () => void {
|
||||
const callbacks = listeners.get(topic) ?? new Set<(data: unknown) => void>();
|
||||
callbacks.add(listener);
|
||||
listeners.set(topic, callbacks);
|
||||
if (topic === "logs" && ++logsReaders === 1) connect();
|
||||
return () => {
|
||||
callbacks.delete(listener);
|
||||
if (callbacks.size === 0) listeners.delete(topic);
|
||||
if (topic === "logs" && --logsReaders === 0) connect();
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
@@ -62,6 +91,7 @@ export const useLiveUpdatesStore = defineStore("live-updates", () => {
|
||||
streamState,
|
||||
initialize,
|
||||
receive,
|
||||
subscribe,
|
||||
};
|
||||
});
|
||||
|
||||
|
||||
Reference in new issue
Block a user