diff --git a/.github/workflows/integration_selenium.yaml b/.github/workflows/integration_selenium.yaml index c6ca7e437397..88212edd124e 100644 --- a/.github/workflows/integration_selenium.yaml +++ b/.github/workflows/integration_selenium.yaml @@ -19,6 +19,10 @@ env: YARN_INSTALL_OPTS: --frozen-lockfile GALAXY_CONFIG_SQLALCHEMY_WARN_20: '1' GALAXY_DEPENDENCIES_INSTALL_WEASYPRINT: '1' + # TEMP: shake down SSE/notification system across full UI surface — revert before merge + GALAXY_CONFIG_OVERRIDE_ENABLE_NOTIFICATION_SYSTEM: '1' + GALAXY_CONFIG_OVERRIDE_ENABLE_SSE_HISTORY_UPDATES: '1' + GALAXY_CONFIG_OVERRIDE_ENABLE_SSE_ENTRY_POINT_UPDATES: '1' concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true diff --git a/.github/workflows/playwright.yaml b/.github/workflows/playwright.yaml index 163c83b38fd3..44fddab54988 100644 --- a/.github/workflows/playwright.yaml +++ b/.github/workflows/playwright.yaml @@ -20,6 +20,10 @@ env: GALAXY_TEST_SELENIUM_HEADLESS: 1 YARN_INSTALL_OPTS: --frozen-lockfile GALAXY_CONFIG_SQLALCHEMY_WARN_20: '1' + # TEMP: shake down SSE/notification system across full UI surface — revert before merge + GALAXY_CONFIG_OVERRIDE_ENABLE_NOTIFICATION_SYSTEM: '1' + GALAXY_CONFIG_OVERRIDE_ENABLE_SSE_HISTORY_UPDATES: '1' + GALAXY_CONFIG_OVERRIDE_ENABLE_SSE_ENTRY_POINT_UPDATES: '1' concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true diff --git a/.github/workflows/selenium.yaml b/.github/workflows/selenium.yaml index 60003fdf51ea..7f5c8490872d 100644 --- a/.github/workflows/selenium.yaml +++ b/.github/workflows/selenium.yaml @@ -19,6 +19,10 @@ env: GALAXY_TEST_SKIP_FLAKEY_TESTS_ON_ERROR: 1 YARN_INSTALL_OPTS: --frozen-lockfile GALAXY_CONFIG_SQLALCHEMY_WARN_20: '1' + # TEMP: shake down SSE/notification system across full UI surface — revert before merge + GALAXY_CONFIG_OVERRIDE_ENABLE_NOTIFICATION_SYSTEM: '1' + GALAXY_CONFIG_OVERRIDE_ENABLE_SSE_HISTORY_UPDATES: '1' + GALAXY_CONFIG_OVERRIDE_ENABLE_SSE_ENTRY_POINT_UPDATES: '1' concurrency: group: ${{ github.workflow }}-${{ github.ref }} cancel-in-progress: true diff --git a/client/src/api/client/index.ts b/client/src/api/client/index.ts index 5e1d4d09c854..98a359387778 100644 --- a/client/src/api/client/index.ts +++ b/client/src/api/client/index.ts @@ -1,5 +1,6 @@ import createClient from "openapi-fetch"; +import { pendingRequestsMiddleware } from "@/api/client/pendingRequestsMiddleware"; import { createRateLimiterMiddleware } from "@/api/client/rateLimiter"; import type { GalaxyApiPaths } from "@/api/schema"; import { getAppRoot } from "@/onload/loadConfig"; @@ -12,6 +13,9 @@ function getBaseUrl() { function apiClientFactory() { const client = createClient({ baseUrl: getBaseUrl() }); + // Registered first so aborted requests bypass the rate-limiter queue. + client.use(pendingRequestsMiddleware); + // TODO: Adjust based on server limits (maybe this goes in Galaxy config?) client.use( createRateLimiterMiddleware({ diff --git a/client/src/api/client/pendingRequestsMiddleware.ts b/client/src/api/client/pendingRequestsMiddleware.ts new file mode 100644 index 000000000000..5c1dec00f8fb --- /dev/null +++ b/client/src/api/client/pendingRequestsMiddleware.ts @@ -0,0 +1,26 @@ +import type { Middleware } from "openapi-fetch"; + +import { getPendingAbortSignal, SKIP_PENDING_REQUESTS_HEADER } from "@/api/pendingRequests"; + +/** + * Attaches the shared pending-requests signal to every ``GalaxyApi`` request. + * The ``openapi-fetch`` client uses native ``fetch()`` so the axios + * interceptor does not apply; without this middleware, login/register + * navigations cannot cancel in-flight ``/api/...`` calls and a late + * anonymous-cookie response can clobber the authenticated ``galaxysession`` + * cookie. See ``client/src/api/pendingRequests.ts`` for the race. + */ +export const pendingRequestsMiddleware: Middleware = { + async onRequest({ request }) { + if (request.headers.has(SKIP_PENDING_REQUESTS_HEADER)) { + const headers = new Headers(request.headers); + headers.delete(SKIP_PENDING_REQUESTS_HEADER); + return new Request(request, { headers }); + } + const shared = getPendingAbortSignal(); + // Combine with any signal the caller may have set so we don't silently + // drop their cancellation semantics. + const signal = typeof AbortSignal.any === "function" ? AbortSignal.any([request.signal, shared]) : shared; + return new Request(request, { signal }); + }, +}; diff --git a/client/src/api/pendingRequests.ts b/client/src/api/pendingRequests.ts new file mode 100644 index 000000000000..cbae404bd408 --- /dev/null +++ b/client/src/api/pendingRequests.ts @@ -0,0 +1,58 @@ +/** + * Shared ``AbortController`` used by both the axios interceptor and the + * ``openapi-fetch`` middleware so we can cancel every in-flight request in + * one shot right before a login/register navigation. + * + * Why this exists: when the server processes a request that carries the old + * anonymous ``galaxysession`` cookie *after* ``handle_user_login`` has marked + * that session ``is_valid=False``, it creates a fresh anonymous session and + * responds with ``Set-Cookie: galaxysession=``. Delivered into the cookie + * jar after the login response but before the new page loads, it overwrites + * the just-issued authenticated cookie — so the new page loads anonymous and + * ``wait_for_logged_in`` times out in selenium. Aborting the TCP connection + * before the response headers are parsed prevents that ``Set-Cookie`` from + * ever applying. + */ +import axios, { type InternalAxiosRequestConfig } from "axios"; + +let activeController = new AbortController(); + +/** Explicit opt-out header that the login/register POST itself sets. */ +export const SKIP_PENDING_REQUESTS_HEADER = "x-galaxy-skip-pending-abort"; + +/** + * The signal every request should ride on by default. Read lazily so the + * ``openapi-fetch`` middleware picks up the fresh signal after each + * ``cancelPendingRequests()`` rotation. + */ +export function getPendingAbortSignal(): AbortSignal { + return activeController.signal; +} + +/** + * Install a request interceptor that attaches the shared signal to every + * outgoing axios request that didn't set one itself. Call once at app boot. + */ +export function installPendingRequestsInterceptor() { + axios.interceptors.request.use((config: InternalAxiosRequestConfig) => { + if (config.signal !== undefined) { + return config; + } + if (config.headers?.[SKIP_PENDING_REQUESTS_HEADER]) { + delete config.headers[SKIP_PENDING_REQUESTS_HEADER]; + return config; + } + config.signal = activeController.signal; + return config; + }); +} + +/** + * Abort every request that is using the shared signal (both axios via the + * interceptor and ``openapi-fetch`` via its middleware) and install a fresh + * controller so subsequent requests can still go out. + */ +export function cancelPendingRequests() { + activeController.abort(); + activeController = new AbortController(); +} diff --git a/client/src/api/schema/schema.ts b/client/src/api/schema/schema.ts index 943dabe0561d..4ba15c5a5d83 100644 --- a/client/src/api/schema/schema.ts +++ b/client/src/api/schema/schema.ts @@ -1292,6 +1292,33 @@ export interface paths { patch?: never; trace?: never; }; + "/api/events/stream": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Server-Sent Events stream for real-time updates. + * @description Opens a Server-Sent Events (SSE) connection that pushes real-time + * updates for notifications, history changes, and other events. + * + * On reconnect, the browser sends the ``Last-Event-ID`` header automatically. + * If the notification system is enabled, any notifications created since that + * timestamp are delivered as a catch-up ``notification_status`` event. + * + * Anonymous users receive only broadcast events. + */ + get: operations["stream_events_api_events_stream_get"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/exports": { parameters: { query?: never; @@ -33194,6 +33221,46 @@ export interface operations { }; }; }; + stream_events_api_events_stream_get: { + parameters: { + query?: never; + header?: { + "Last-Event-ID"?: string | null; + /** @description The user ID that will be used to effectively make this API call. Only admins and designated users can make API calls on behalf of other users. */ + "run-as"?: string | null; + }; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content?: never; + }; + /** @description Request Error */ + "4XX": { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MessageExceptionModel"]; + }; + }; + /** @description Server Error */ + "5XX": { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["MessageExceptionModel"]; + }; + }; + }; + }; index_api_exports_get: { parameters: { query?: { diff --git a/client/src/components/Login/LoginForm.vue b/client/src/components/Login/LoginForm.vue index 7ec8b232cd11..d9f6af213224 100644 --- a/client/src/components/Login/LoginForm.vue +++ b/client/src/components/Login/LoginForm.vue @@ -15,6 +15,8 @@ import { import { computed, ref } from "vue"; import { useRouter } from "vue-router/composables"; +import { SKIP_PENDING_REQUESTS_HEADER } from "@/api/pendingRequests"; +import { discardActiveConnectionsBeforeAuthNavigation } from "@/composables/useAuthNavigation"; import localize from "@/utils/localization"; import { withPrefix } from "@/utils/redirect"; import { errorMessageAsString } from "@/utils/simple-error"; @@ -86,13 +88,22 @@ async function submitLogin() { redirect = props.redirect ?? null; } + // Close SSE, stop polling, and abort in-flight axios before sending the + // login POST — otherwise a late anonymous-cookie response can overwrite + // the authenticated cookie we're about to receive. + discardActiveConnectionsBeforeAuthNavigation(); + try { - const response = await axios.post(withPrefix("/user/login"), { - login: login.value, - password: password.value, - redirect: redirect, - session_csrf_token: props.sessionCsrfToken, - }); + const response = await axios.post( + withPrefix("/user/login"), + { + login: login.value, + password: password.value, + redirect: redirect, + session_csrf_token: props.sessionCsrfToken, + }, + { headers: { [SKIP_PENDING_REQUESTS_HEADER]: "1" } }, + ); if (response.data.message && response.data.status) { alert(response.data.message); diff --git a/client/src/components/Register/RegisterForm.vue b/client/src/components/Register/RegisterForm.vue index c3598d14a965..0ba0449d7a62 100644 --- a/client/src/components/Register/RegisterForm.vue +++ b/client/src/components/Register/RegisterForm.vue @@ -14,8 +14,10 @@ import { } from "bootstrap-vue"; import { computed, type Ref, ref } from "vue"; +import { SKIP_PENDING_REQUESTS_HEADER } from "@/api/pendingRequests"; import { getOIDCIdpsWithRegistration, type OIDCConfig } from "@/components/User/ExternalIdentities/ExternalIDHelper"; import { Toast } from "@/composables/toast"; +import { discardActiveConnectionsBeforeAuthNavigation } from "@/composables/useAuthNavigation"; import localize from "@/utils/localization"; import { withPrefix } from "@/utils/redirect"; import { errorMessageAsString } from "@/utils/simple-error"; @@ -72,15 +74,24 @@ const registerColumnDisplay = computed(() => Boolean(props.termsUrl)); async function submit() { disableCreate.value = true; + // Close SSE, stop polling, and abort in-flight axios before sending the + // register POST — otherwise a late anonymous-cookie response can overwrite + // the authenticated cookie we're about to receive. + discardActiveConnectionsBeforeAuthNavigation(); + try { - const response = await axios.post(withPrefix("/user/create"), { - email: email.value, - username: username.value, - password: password.value, - confirm: confirm.value, - subscribe: subscribe.value, - session_csrf_token: props.sessionCsrfToken, - }); + const response = await axios.post( + withPrefix("/user/create"), + { + email: email.value, + username: username.value, + password: password.value, + confirm: confirm.value, + subscribe: subscribe.value, + session_csrf_token: props.sessionCsrfToken, + }, + { headers: { [SKIP_PENDING_REQUESTS_HEADER]: "1" } }, + ); if (response.data.message && response.data.status) { Toast.info(response.data.message); diff --git a/client/src/composables/useAuthNavigation.ts b/client/src/composables/useAuthNavigation.ts new file mode 100644 index 000000000000..69d7f88a00da --- /dev/null +++ b/client/src/composables/useAuthNavigation.ts @@ -0,0 +1,26 @@ +import { cancelPendingRequests } from "@/api/pendingRequests"; +import { useEntryPointStore } from "@/stores/entryPointStore"; +import { useHistoryStore } from "@/stores/historyStore"; +import { useNotificationsStore } from "@/stores/notificationsStore"; + +/** + * Tear down every long-lived connection and cancel every in-flight request + * (both axios and ``openapi-fetch``/GalaxyApi) so that nothing issued under + * the old anonymous ``galaxysession`` cookie can land on the server after + * ``handle_user_login`` has invalidated it. See + * ``client/src/api/pendingRequests.ts`` for the race this guards against. + * + * Call this synchronously as the first step of a login or registration + * submit, before the authenticating POST goes out. The shared abort + * controller is rotated, so the login/register POST (issued right after) + * will use a fresh signal and is not affected. + */ +export function discardActiveConnectionsBeforeAuthNavigation() { + // Order: close SSE streams first (synchronous TCP close), then stop the + // polling watchers so they can't kick off new fetches, then abort any + // requests still in flight via the shared AbortController. + useHistoryStore().stopWatchingHistory(); + useEntryPointStore().stopWatchingEntryPoints(); + useNotificationsStore().stopWatchingNotifications(); + cancelPendingRequests(); +} diff --git a/client/src/composables/useNotificationSSE.ts b/client/src/composables/useNotificationSSE.ts new file mode 100644 index 000000000000..8bdae964f2e7 --- /dev/null +++ b/client/src/composables/useNotificationSSE.ts @@ -0,0 +1,191 @@ +import { onScopeDispose, ref } from "vue"; + +import { withPrefix } from "@/utils/redirect"; + +/** + * All SSE event types the server may emit. + */ +export const SSE_EVENT_TYPES = [ + "notification_update", + "broadcast_update", + "notification_status", + "history_update", + "entry_point_update", +] as const; + +export type SSEEventType = (typeof SSE_EVENT_TYPES)[number]; + +interface SSEDebugGlobals { + __galaxy_sse_connected?: boolean; + __galaxy_sse_last_event_ts?: number; +} + +function sseGlobals(): SSEDebugGlobals { + return window as unknown as SSEDebugGlobals; +} + +// --------------------------------------------------------------------------- +// Module-level shared EventSource. +// +// Every call to ``useSSE`` registers its handler against this one socket so +// the tab opens a single ``/api/events/stream`` connection no matter how many +// stores listen. HTTP/1.1 caps simultaneous connections per origin at six; +// before this consolidation we burned three slots on SSE alone (history, +// notifications, entry points), which is what starved the scratchbook iframe +// flow — see the fix in ``client/src/entry/analysis/App.vue``. +// --------------------------------------------------------------------------- + +type Handler = (event: MessageEvent) => void; + +let sharedSource: EventSource | null = null; +const sharedConnected = ref(false); +const subscribers: Map> = new Map(); +// Track the per-type dispatchers we registered so ``closeSource`` removes the +// exact same listeners (``addEventListener`` matches by reference). +const dispatchers: Map = new Map(); + +function openSourceIfNeeded() { + if (sharedSource) { + return; + } + sharedSource = new EventSource(withPrefix("/api/events/stream")); + + for (const eventType of SSE_EVENT_TYPES) { + const dispatcher: Handler = (event) => { + // Selenium tests watch ``__galaxy_sse_last_event_ts`` to prove that + // an observable state change came from an SSE push and not the + // polling fallback (where the global would never advance). + sseGlobals().__galaxy_sse_last_event_ts = Date.now(); + const subs = subscribers.get(eventType); + if (!subs) { + return; + } + for (const handler of subs) { + handler(event); + } + }; + dispatchers.set(eventType, dispatcher); + sharedSource.addEventListener(eventType, dispatcher); + } + + sharedSource.onopen = () => { + sharedConnected.value = true; + // Global readiness flag so Selenium tests can distinguish a working + // SSE pipeline from the polling fallback. + sseGlobals().__galaxy_sse_connected = true; + }; + + sharedSource.onerror = () => { + // EventSource auto-reconnects natively; SSE-vs-polling is a + // config-level decision (see historyStore / notificationsStore), so + // we must not give up on transient errors here — doing so would leave + // the client with no updates at all. + sharedConnected.value = false; + sseGlobals().__galaxy_sse_connected = false; + }; + + // Browser EventSource teardown during a full-page navigation + // (``window.location.href = …``) is not guaranteed to happen before the + // browser issues requests for the new page — we've seen Chrome keep the + // stream alive long enough that a login/register POST reload races the + // close, and the new page then loads with a stale auth view. Force a + // synchronous ``close()`` during ``pagehide`` (fires for both reloads and + // tab-close, unlike ``beforeunload``) to close that window. + if (typeof window !== "undefined") { + window.addEventListener("pagehide", closeSource); + } +} + +function closeSource() { + if (!sharedSource) { + return; + } + for (const [eventType, dispatcher] of dispatchers) { + sharedSource.removeEventListener(eventType, dispatcher); + } + dispatchers.clear(); + sharedSource.close(); + sharedSource = null; + sharedConnected.value = false; + sseGlobals().__galaxy_sse_connected = false; + if (typeof window !== "undefined") { + window.removeEventListener("pagehide", closeSource); + } +} + +function addSubscriber(onEvent: Handler, eventTypes: readonly SSEEventType[]) { + for (const eventType of eventTypes) { + let subs = subscribers.get(eventType); + if (!subs) { + subs = new Set(); + subscribers.set(eventType, subs); + } + subs.add(onEvent); + } +} + +function removeSubscriber(onEvent: Handler, eventTypes: readonly SSEEventType[]): boolean { + let anyRemaining = false; + for (const eventType of eventTypes) { + const subs = subscribers.get(eventType); + if (subs) { + subs.delete(onEvent); + if (subs.size === 0) { + subscribers.delete(eventType); + } + } + } + for (const subs of subscribers.values()) { + if (subs.size > 0) { + anyRemaining = true; + break; + } + } + return anyRemaining; +} + +/** + * Composable for subscribing to events on the shared SSE stream. + * + * The browser's EventSource handles reconnection automatically and sends the + * ``Last-Event-ID`` header so the server can catch up on missed events. Only + * one EventSource is opened per tab regardless of how many callers invoke + * this composable; the composable multiplexes dispatch per event type. + * + * @param onEvent - callback invoked for every matching SSE event + * @param eventTypes - subset of event types to listen to (defaults to all) + */ +export function useSSE(onEvent: Handler, eventTypes: readonly SSEEventType[] = SSE_EVENT_TYPES) { + let connected_: boolean = false; + + function connect() { + if (connected_) { + return; + } + connected_ = true; + addSubscriber(onEvent, eventTypes); + openSourceIfNeeded(); + } + + function disconnect() { + if (!connected_) { + return; + } + connected_ = false; + const anyRemaining = removeSubscriber(onEvent, eventTypes); + if (!anyRemaining) { + closeSource(); + } + } + + onScopeDispose(() => { + disconnect(); + }); + + return { connect, disconnect, connected: sharedConnected }; +} + +/** + * @deprecated Use `useSSE` instead. This alias exists for backward compatibility. + */ +export const useNotificationSSE = useSSE; diff --git a/client/src/entry/analysis/App.vue b/client/src/entry/analysis/App.vue index cbc80f181cde..64bd2a784a02 100644 --- a/client/src/entry/analysis/App.vue +++ b/client/src/entry/analysis/App.vue @@ -48,7 +48,7 @@