Files
archie/ui/src/stores/session.ts
T

145 lines
4.7 KiB
TypeScript

import { defineStore } from "pinia";
import {
onUnmounted,
reactive,
ref,
watch,
} from "vue";
import { api, setAuthenticationStateHandler, subscribeEvents, type StreamFrame } from "../lib/api.ts";
import type { CapabilitySections } from "../lib/capabilities.ts";
import { reconnectDelay, type StreamState } from "../lib/stream-state.ts";
import {
resourcesForEvent,
type LiveEvent,
type LiveResource,
} from "./live-events.ts";
/** The browser's session with the server: the live event stream, and which
* sections this composition can back. */
export const useSessionStore = defineStore("session", () => {
/**
* The server's capability map. Null means nothing has been reported (an
* older server, a failed read), and every surface stays visible: a page that
* says "unavailable" is recoverable, one that silently vanished is not.
*/
const sections = ref<CapabilitySections | null>(null);
/** Asked once, after the shell is up: the nav paints immediately and loses
* what this process cannot back a moment later. A failed read hides nothing. */
async function loadCapabilities(): Promise<void> {
try {
sections.value = (await api.capabilities<{ sections?: CapabilitySections } | null>())?.sections ?? null;
} catch {
// Offline or an older server: every section stays visible.
}
}
const streamState = ref<StreamState | "connecting">("connecting");
const connectionRevision = ref(0);
const activity = ref<LiveEvent[]>([]);
const revisions = reactive<Record<LiveResource, number>>({
tasks: 0,
captures: 0,
curators: 0,
skills: 0,
updates: 0,
chat: 0,
});
let unsubscribe: (() => void) | undefined;
let cursor = "";
let logsReaders = 0;
const listeners = new Map<string, Set<(data: unknown) => void>>();
function receive(raw: unknown): void {
const event = raw as LiveEvent;
activity.value = [event, ...activity.value].slice(0, 50);
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);
}
// The browser retries a dropped stream itself, but a non-200 answer (the
// backend restarting behind a proxy) closes it for good; reopen it then, or
// the page reads "Disconnected" until a reload.
let retryTimer: ReturnType<typeof setTimeout> | undefined;
let retryAttempt = 0;
function connect(): void {
clearTimeout(retryTimer);
unsubscribe?.();
streamState.value = "connecting";
unsubscribe = subscribeEvents(handleFrame, (state) => {
streamState.value = state;
if (state === "live") {
retryAttempt = 0;
connectionRevision.value += 1;
} else if (state === "unavailable") {
retryTimer = setTimeout(connect, reconnectDelay(retryAttempt++));
}
}, cursor, logsReaders > 0);
}
function initialize(): void {
if (unsubscribe) return;
// An expired session reloads the document: the server answers a page
// request without a session by sending the browser to sign in.
setAuthenticationStateHandler((required) => {
if (required) window.location.reload();
});
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 {
sections,
loadCapabilities,
activity,
connectionRevision,
revisions,
streamState,
initialize,
receive,
subscribe,
};
});
/** Re-read one mounted projection when SSE says its backend resource changed. */
export function useLiveResource(
resource: LiveResource | null,
load: () => void,
debounceMs = 100,
): void {
const live = useSessionStore();
let timer: ReturnType<typeof setTimeout> | undefined;
const revision = () =>
resource === null
? live.connectionRevision
: [live.revisions[resource], live.connectionRevision];
const stop = watch(revision, () => {
clearTimeout(timer);
timer = setTimeout(load, debounceMs);
});
onUnmounted(() => {
clearTimeout(timer);
stop();
});
}