|
| 1 | +import { onScopeDispose, ref } from "vue"; |
| 2 | + |
| 3 | +import { withPrefix } from "@/utils/redirect"; |
| 4 | + |
| 5 | +/** |
| 6 | + * All SSE event types the server may emit. |
| 7 | + */ |
| 8 | +export const SSE_EVENT_TYPES = [ |
| 9 | + "notification_update", |
| 10 | + "broadcast_update", |
| 11 | + "notification_status", |
| 12 | + "history_update", |
| 13 | + "entry_point_update", |
| 14 | +] as const; |
| 15 | + |
| 16 | +export type SSEEventType = (typeof SSE_EVENT_TYPES)[number]; |
| 17 | + |
| 18 | +interface SSEDebugGlobals { |
| 19 | + __galaxy_sse_connected?: boolean; |
| 20 | + __galaxy_sse_last_event_ts?: number; |
| 21 | +} |
| 22 | + |
| 23 | +function sseGlobals(): SSEDebugGlobals { |
| 24 | + return window as unknown as SSEDebugGlobals; |
| 25 | +} |
| 26 | + |
| 27 | +// --------------------------------------------------------------------------- |
| 28 | +// Module-level shared EventSource. |
| 29 | +// |
| 30 | +// Every call to ``useSSE`` registers its handler against this one socket so |
| 31 | +// the tab opens a single ``/api/events/stream`` connection no matter how many |
| 32 | +// stores listen. HTTP/1.1 caps simultaneous connections per origin at six; |
| 33 | +// before this consolidation we burned three slots on SSE alone (history, |
| 34 | +// notifications, entry points), which is what starved the scratchbook iframe |
| 35 | +// flow — see the fix in ``client/src/entry/analysis/App.vue``. |
| 36 | +// --------------------------------------------------------------------------- |
| 37 | + |
| 38 | +type Handler = (event: MessageEvent) => void; |
| 39 | + |
| 40 | +let sharedSource: EventSource | null = null; |
| 41 | +const sharedConnected = ref(false); |
| 42 | +const subscribers: Map<SSEEventType, Set<Handler>> = new Map(); |
| 43 | +// Track the per-type dispatchers we registered so ``closeSource`` removes the |
| 44 | +// exact same listeners (``addEventListener`` matches by reference). |
| 45 | +const dispatchers: Map<SSEEventType, Handler> = new Map(); |
| 46 | + |
| 47 | +function openSourceIfNeeded() { |
| 48 | + if (sharedSource) { |
| 49 | + return; |
| 50 | + } |
| 51 | + sharedSource = new EventSource(withPrefix("/api/events/stream")); |
| 52 | + |
| 53 | + for (const eventType of SSE_EVENT_TYPES) { |
| 54 | + const dispatcher: Handler = (event) => { |
| 55 | + // Selenium tests watch ``__galaxy_sse_last_event_ts`` to prove that |
| 56 | + // an observable state change came from an SSE push and not the |
| 57 | + // polling fallback (where the global would never advance). |
| 58 | + sseGlobals().__galaxy_sse_last_event_ts = Date.now(); |
| 59 | + const subs = subscribers.get(eventType); |
| 60 | + if (!subs) { |
| 61 | + return; |
| 62 | + } |
| 63 | + for (const handler of subs) { |
| 64 | + handler(event); |
| 65 | + } |
| 66 | + }; |
| 67 | + dispatchers.set(eventType, dispatcher); |
| 68 | + sharedSource.addEventListener(eventType, dispatcher); |
| 69 | + } |
| 70 | + |
| 71 | + sharedSource.onopen = () => { |
| 72 | + sharedConnected.value = true; |
| 73 | + // Global readiness flag so Selenium tests can distinguish a working |
| 74 | + // SSE pipeline from the polling fallback. |
| 75 | + sseGlobals().__galaxy_sse_connected = true; |
| 76 | + }; |
| 77 | + |
| 78 | + sharedSource.onerror = () => { |
| 79 | + // EventSource auto-reconnects natively; SSE-vs-polling is a |
| 80 | + // config-level decision (see historyStore / notificationsStore), so |
| 81 | + // we must not give up on transient errors here — doing so would leave |
| 82 | + // the client with no updates at all. |
| 83 | + sharedConnected.value = false; |
| 84 | + sseGlobals().__galaxy_sse_connected = false; |
| 85 | + }; |
| 86 | + |
| 87 | + // Browser EventSource teardown during a full-page navigation |
| 88 | + // (``window.location.href = …``) is not guaranteed to happen before the |
| 89 | + // browser issues requests for the new page — we've seen Chrome keep the |
| 90 | + // stream alive long enough that a login/register POST reload races the |
| 91 | + // close, and the new page then loads with a stale auth view. Force a |
| 92 | + // synchronous ``close()`` during ``pagehide`` (fires for both reloads and |
| 93 | + // tab-close, unlike ``beforeunload``) to close that window. |
| 94 | + if (typeof window !== "undefined") { |
| 95 | + window.addEventListener("pagehide", closeSource); |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +function closeSource() { |
| 100 | + if (!sharedSource) { |
| 101 | + return; |
| 102 | + } |
| 103 | + for (const [eventType, dispatcher] of dispatchers) { |
| 104 | + sharedSource.removeEventListener(eventType, dispatcher); |
| 105 | + } |
| 106 | + dispatchers.clear(); |
| 107 | + sharedSource.close(); |
| 108 | + sharedSource = null; |
| 109 | + sharedConnected.value = false; |
| 110 | + sseGlobals().__galaxy_sse_connected = false; |
| 111 | + if (typeof window !== "undefined") { |
| 112 | + window.removeEventListener("pagehide", closeSource); |
| 113 | + } |
| 114 | +} |
| 115 | + |
| 116 | +function addSubscriber(onEvent: Handler, eventTypes: readonly SSEEventType[]) { |
| 117 | + for (const eventType of eventTypes) { |
| 118 | + let subs = subscribers.get(eventType); |
| 119 | + if (!subs) { |
| 120 | + subs = new Set(); |
| 121 | + subscribers.set(eventType, subs); |
| 122 | + } |
| 123 | + subs.add(onEvent); |
| 124 | + } |
| 125 | +} |
| 126 | + |
| 127 | +function removeSubscriber(onEvent: Handler, eventTypes: readonly SSEEventType[]): boolean { |
| 128 | + let anyRemaining = false; |
| 129 | + for (const eventType of eventTypes) { |
| 130 | + const subs = subscribers.get(eventType); |
| 131 | + if (subs) { |
| 132 | + subs.delete(onEvent); |
| 133 | + if (subs.size === 0) { |
| 134 | + subscribers.delete(eventType); |
| 135 | + } |
| 136 | + } |
| 137 | + } |
| 138 | + for (const subs of subscribers.values()) { |
| 139 | + if (subs.size > 0) { |
| 140 | + anyRemaining = true; |
| 141 | + break; |
| 142 | + } |
| 143 | + } |
| 144 | + return anyRemaining; |
| 145 | +} |
| 146 | + |
| 147 | +/** |
| 148 | + * Composable for subscribing to events on the shared SSE stream. |
| 149 | + * |
| 150 | + * The browser's EventSource handles reconnection automatically and sends the |
| 151 | + * ``Last-Event-ID`` header so the server can catch up on missed events. Only |
| 152 | + * one EventSource is opened per tab regardless of how many callers invoke |
| 153 | + * this composable; the composable multiplexes dispatch per event type. |
| 154 | + * |
| 155 | + * @param onEvent - callback invoked for every matching SSE event |
| 156 | + * @param eventTypes - subset of event types to listen to (defaults to all) |
| 157 | + */ |
| 158 | +export function useSSE(onEvent: Handler, eventTypes: readonly SSEEventType[] = SSE_EVENT_TYPES) { |
| 159 | + let connected_: boolean = false; |
| 160 | + |
| 161 | + function connect() { |
| 162 | + if (connected_) { |
| 163 | + return; |
| 164 | + } |
| 165 | + connected_ = true; |
| 166 | + addSubscriber(onEvent, eventTypes); |
| 167 | + openSourceIfNeeded(); |
| 168 | + } |
| 169 | + |
| 170 | + function disconnect() { |
| 171 | + if (!connected_) { |
| 172 | + return; |
| 173 | + } |
| 174 | + connected_ = false; |
| 175 | + const anyRemaining = removeSubscriber(onEvent, eventTypes); |
| 176 | + if (!anyRemaining) { |
| 177 | + closeSource(); |
| 178 | + } |
| 179 | + } |
| 180 | + |
| 181 | + onScopeDispose(() => { |
| 182 | + disconnect(); |
| 183 | + }); |
| 184 | + |
| 185 | + return { connect, disconnect, connected: sharedConnected }; |
| 186 | +} |
| 187 | + |
| 188 | +/** |
| 189 | + * @deprecated Use `useSSE` instead. This alias exists for backward compatibility. |
| 190 | + */ |
| 191 | +export const useNotificationSSE = useSSE; |
0 commit comments