From aa433275ab8028f1b74b3ec371317590232a1bb4 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 00:19:45 +0530 Subject: [PATCH 01/32] IDP-45: add the favicon --- applications/idp-arc/frontend/index.html | 1 + .../idp-arc/frontend/public/favicon.svg | 30 +++++++++++++++++++ 2 files changed, 31 insertions(+) create mode 100644 applications/idp-arc/frontend/public/favicon.svg diff --git a/applications/idp-arc/frontend/index.html b/applications/idp-arc/frontend/index.html index 3ae7837..f382c3d 100644 --- a/applications/idp-arc/frontend/index.html +++ b/applications/idp-arc/frontend/index.html @@ -3,6 +3,7 @@ + MAABCD diff --git a/applications/idp-arc/frontend/public/favicon.svg b/applications/idp-arc/frontend/public/favicon.svg new file mode 100644 index 0000000..c879088 --- /dev/null +++ b/applications/idp-arc/frontend/public/favicon.svg @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 0ed0e6701f8b4aca1b54ff079d3a9684e7b5df6d Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 00:29:54 +0530 Subject: [PATCH 02/32] IDP-45: dual login (EMBER-DANDI and OSB) from a Login dialog --- applications/idp-arc/Dockerfile | 3 + .../idp-arc/deploy/resources/default.conf | 8 + applications/idp-arc/frontend/src/App.tsx | 102 ++++-- .../idp-arc/frontend/src/app/container.ts | 19 + .../frontend/src/components/LoginDialog.tsx | 163 +++++++++ .../frontend/src/components/PageLayout.tsx | 127 ++++--- .../frontend/src/components/loginReturn.ts | 31 ++ .../frontend/src/core/ports/IEmberAuth.ts | 59 ++++ .../frontend/src/infra/emberOAuthClient.ts | 331 ++++++++++++++++++ .../idp-arc/frontend/src/infra/emberUrls.ts | 13 + .../frontend/src/locales/en/landingPage.json | 21 ++ .../frontend/src/pages/EmberCallback.tsx | 59 ++++ applications/idp-arc/frontend/vite.config.ts | 28 ++ deployment/codefresh-dev.yaml | 1 + 14 files changed, 888 insertions(+), 77 deletions(-) create mode 100644 applications/idp-arc/frontend/src/components/LoginDialog.tsx create mode 100644 applications/idp-arc/frontend/src/components/loginReturn.ts create mode 100644 applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts create mode 100644 applications/idp-arc/frontend/src/infra/emberOAuthClient.ts create mode 100644 applications/idp-arc/frontend/src/infra/emberUrls.ts create mode 100644 applications/idp-arc/frontend/src/pages/EmberCallback.tsx diff --git a/applications/idp-arc/Dockerfile b/applications/idp-arc/Dockerfile index 132d970..0adf557 100644 --- a/applications/idp-arc/Dockerfile +++ b/applications/idp-arc/Dockerfile @@ -9,6 +9,9 @@ COPY frontend/ ./ # Baked into the bundle by Vite at build time; the Codefresh pipeline passes it as a build argument. ARG VITE_UPLOAD_BUCKET_URL ENV VITE_UPLOAD_BUCKET_URL=${VITE_UPLOAD_BUCKET_URL} +# EMBER-DANDI OAuth application (public client, PKCE) registered for this IDP origin. +ARG VITE_EMBER_CLIENT_ID +ENV VITE_EMBER_CLIENT_ID=${VITE_EMBER_CLIENT_ID} RUN yarn build FROM nginxinc/nginx-unprivileged:stable-alpine diff --git a/applications/idp-arc/deploy/resources/default.conf b/applications/idp-arc/deploy/resources/default.conf index 3bc7e97..75a5cfa 100644 --- a/applications/idp-arc/deploy/resources/default.conf +++ b/applications/idp-arc/deploy/resources/default.conf @@ -8,6 +8,14 @@ server { try_files $uri $uri/ /index.html; } + # EMBER's POST /oauth/token/ reply has no CORS header, so the browser can't read the login token + # from it directly; through this same-origin proxy it can. (File bytes go straight to S3, not here.) + location /ember-proxy/ { + proxy_pass https://api-dandi.emberarchive.org/; + proxy_ssl_server_name on; + proxy_set_header Host api-dandi.emberarchive.org; + } + location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|webp|woff2?)$ { try_files $uri =404; expires 7d; diff --git a/applications/idp-arc/frontend/src/App.tsx b/applications/idp-arc/frontend/src/App.tsx index e51ca9a..7e0b847 100644 --- a/applications/idp-arc/frontend/src/App.tsx +++ b/applications/idp-arc/frontend/src/App.tsx @@ -3,21 +3,55 @@ import { useTranslation } from 'react-i18next' import { createBrowserRouter, RouterProvider } from 'react-router-dom' import { ThemeProvider } from '@mui/material/styles' import CssBaseline from '@mui/material/CssBaseline' +import Box from '@mui/material/Box' +import CircularProgress from '@mui/material/CircularProgress' +import Typography from '@mui/material/Typography' import { AppContext } from './AppContext' -import { authClient } from './app/container' +import { authClient, EMBER_CALLBACK_PATH } from './app/container' import { theme } from './theme/components' import type { AuthState } from './core/types' import Home from './pages/LandingPage' import Workspaces from './pages/Workspaces' import ProtocolsPage from './pages/ProtocolsPage' import AboutPage from './pages/AboutPage' +import EmberCallback from './pages/EmberCallback' + +/** + * This window is OSB's (Keycloak) login popup, sent back here once the user has signed in. It only + * finishes the sign-in, hands it to the main tab and closes; it never shows the app (it would + * otherwise reopen the Login dialog: a popup starts with a copy of its opener's sessionStorage). + * EMBER-DANDI's popup has no `window.opener` (COOP) and is handled on its callback route. + */ +const IN_OSB_LOGIN_POPUP = typeof window !== 'undefined' && !!window.opener + && window.location.pathname !== EMBER_CALLBACK_PATH + +/** What the OSB login popup shows while it finishes the sign-in and closes itself. */ +function OsbLoginPopupScreen({ authState }: { authState: AuthState }) { + const { t } = useTranslation('landingPage') + return ( + + + + {authState === 'loading' || authState === 'authenticated' ? ( + <> + + {t('loginDialog.finishingSignIn')} + + ) : ( + {t('loginDialog.closeWindow')} + )} + + + ) +} const router = createBrowserRouter([ { path: '/', element: }, { path: '/workspaces', element: }, { path: '/protocols', element: }, { path: '/about', element: }, + { path: EMBER_CALLBACK_PATH, element: }, ]) function App() { @@ -29,31 +63,47 @@ function App() { useEffect(() => { if (initialized.current) return - initialized.current = true - authClient - .init() - .then((authenticated: boolean) => { - // If running inside the login popup, signal the parent and close. - if (authenticated && window.opener) { - window.opener.postMessage({ type: 'keycloak-login-complete' }, window.location.origin) - window.close() - return - } - setAuthState(authenticated ? 'authenticated' : 'unauthenticated') - if (authenticated && authClient.tokenParsed) { - setTokenParsed(authClient.tokenParsed) - } - }) - .catch((err: Error) => { - // Clear stale auth fragment so a page refresh doesn't retry a failed token exchange. - if (window.location.hash) { - window.history.replaceState(null, '', window.location.pathname + window.location.search) - } - console.error('Keycloak init failed', err) - setAuthError(t('errors.authFailed')) - setAuthState('unauthenticated') - }) + // Keycloak has no business on the EMBER-DANDI callback route: its check-sso can fall back to a + // real top-level redirect, which would abort the EMBER token exchange running there. It + // starts once the callback page has navigated back (router.subscribe: App renders the + // RouterProvider, so it isn't inside it and can't useLocation). + const tryInit = () => { + if (initialized.current) return + if (router.state.location.pathname === EMBER_CALLBACK_PATH) return + initialized.current = true + unsubscribe() + startKeycloak() + } + const unsubscribe = router.subscribe(tryInit) + tryInit() + return () => unsubscribe() + + function startKeycloak() { + authClient + .init() + .then((authenticated: boolean) => { + // If running inside the login popup, signal the parent and close. + if (authenticated && window.opener) { + window.opener.postMessage({ type: 'keycloak-login-complete' }, window.location.origin) + window.close() + return + } + setAuthState(authenticated ? 'authenticated' : 'unauthenticated') + if (authenticated && authClient.tokenParsed) { + setTokenParsed(authClient.tokenParsed) + } + }) + .catch((err: Error) => { + // Clear stale auth fragment so a page refresh doesn't retry a failed token exchange. + if (window.location.hash) { + window.history.replaceState(null, '', window.location.pathname + window.location.search) + } + console.error('Keycloak init failed', err) + setAuthError(t('errors.authFailed')) + setAuthState('unauthenticated') + }) + } }, [t]) // Reload after popup login so check-sso picks up the new Keycloak session. @@ -77,6 +127,8 @@ function App() { [authState, tokenParsed, authError, username], ) + if (IN_OSB_LOGIN_POPUP) return + return ( diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index fa0db2a..c384a3d 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -20,6 +20,8 @@ import { KeycloakAuthClient } from '../infra/keycloakAuthClient' import { WorkspaceApiClient } from '../infra/workspaceApiClient' import { DandiApiClient } from '../infra/dandiApiClient' import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore' +import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient' +import { EMBER_API_ORIGIN_DEFAULT } from '../infra/emberUrls' import type { IObjectStore } from '../core/ports/IObjectStore' import { createLoadWorkspacesUseCase } from '../core/use-cases/loadWorkspaces' import { createCreateAndUploadToDandiUseCase } from '../core/use-cases/createAndUploadToDandi' @@ -37,6 +39,12 @@ const WORKSPACES_LIST_URL = `${WWW_BASE}/proxy/workspaces/api/workspace?page=1&per_page=24&q=&tags=` const FRONTEND_BASE = `${PROTOCOL}://www.${BASE_DOMAIN}` +/** EMBER-DANDI's API origin: where the OAuth login goes, and what OSB downloads assets from. */ +const EMBER_ORIGIN = (import.meta.env.VITE_EMBER_ORIGIN ?? EMBER_API_ORIGIN_DEFAULT).replace(/\/+$/, '') +/** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's + * token response carries no CORS headers. */ +const EMBER_FETCH_BASE = '/ember-proxy' + // ─── Infrastructure singletons ──────────────────────────────────────────────── export const authClient = new KeycloakAuthClient({ @@ -50,6 +58,17 @@ const workspaceApi = new WorkspaceApiClient(WORKSPACES_API, WORKSPACES_LIST_URL) // they run) — same API base as every other workspace call. const dandiApi = new DandiApiClient(WORKSPACES_API) +/** Signs the researcher in to EMBER-DANDI (OAuth in a popup, a full-page redirect if it is blocked); + * their token stays in the browser. */ +export const emberAuth = new EmberOAuthClient({ + authOrigin: EMBER_ORIGIN, + apiBase: EMBER_FETCH_BASE, + clientId: import.meta.env.VITE_EMBER_CLIENT_ID ?? '', + redirectUri: `${window.location.origin}${EMBER_CALLBACK_PATH}`, +}) +export { EMBER_CALLBACK_PATH } +export { EmberPopupBlocked, EmberSignInCancelled } from '../infra/emberOAuthClient' + /** Scenario 1: where uploads go before OSB imports them (`gs://maabcd`). Used by the upload flow. */ export const objectStore: IObjectStore = new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) diff --git a/applications/idp-arc/frontend/src/components/LoginDialog.tsx b/applications/idp-arc/frontend/src/components/LoginDialog.tsx new file mode 100644 index 0000000..dec3cf6 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/LoginDialog.tsx @@ -0,0 +1,163 @@ +import { useState } from 'react' +import { Box, Button, CircularProgress, Dialog, Divider, IconButton, Stack, Typography } from '@mui/material' +import ArrowForwardIcon from '@mui/icons-material/ArrowForward' +import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutlineOutlined' +import CloseIcon from '@mui/icons-material/Close' +import { useTranslation } from 'react-i18next' + +import { emberAuth, EmberPopupBlocked, EmberSignInCancelled } from '../app/container' +import { markLoginDialogReturn } from './loginReturn' + +export interface LoginDialogProps { + open: boolean + onClose: () => void + /** Opens OSB's (Keycloak) login popup; `onEnded` when it closes without completing (completing + * reloads the page). Resolves to how to stop waiting, or null after a full-page redirect. */ + onOsbLogin: (onEnded: () => void) => Promise<{ cancel: () => void } | null> + osbSignedIn: boolean + /** EMBER-DANDI's sign-in finished in its popup (the page didn't reload). */ + onEmberSignedIn: () => void +} + +/** + * The two logins IDP needs, each with its own flow: EMBER-DANDI, where the researcher's data is + * uploaded (a full-page OAuth redirect), and Open Source Brain, where it is analysed (the Keycloak + * popup). Both leave or reload the page, so the dialog reopens on return (loginReturn.ts). A row + * that is signed in shows a check instead of its number, and "Logged in" instead of its button. + */ +export default function LoginDialog({ open, onClose, onOsbLogin, osbSignedIn, onEmberSignedIn }: LoginDialogProps) { + const { t } = useTranslation('landingPage') + // The EMBER-DANDI popup being waited for; cancelling only stops waiting (the popup can't be + // reached from here, see emberOAuthClient.ts). + const [emberWait, setEmberWait] = useState<{ cancel: () => void } | null>(null) + const [emberError, setEmberError] = useState('') + const [osbWait, setOsbWait] = useState<{ cancel: () => void } | null>(null) + + const loginToOsb = async () => { + markLoginDialogReturn() + setOsbWait(await onOsbLogin(() => setOsbWait(null))) + } + + const loginToEmber = () => { + setEmberError('') + let attempt: ReturnType + try { + attempt = emberAuth.connectInPopup() + } catch (err) { + if (!(err instanceof EmberPopupBlocked)) throw err + // Popups blocked: the full-page redirect, back to this dialog afterwards. + markLoginDialogReturn() + void emberAuth.connect(window.location.pathname) + return + } + setEmberWait(attempt) + attempt.done.then( + () => { setEmberWait(null); onEmberSignedIn() }, + (err: unknown) => { + setEmberWait(null) + if (err instanceof EmberSignInCancelled) return + console.error('EMBER-DANDI sign-in failed', err) + setEmberError(err instanceof Error ? err.message : String(err)) + }, + ) + } + + const rows = [ + { + n: '01', title: t('loginDialog.emberTitle'), description: t('loginDialog.emberDescription'), + signedIn: emberAuth.isConnected(), + login: loginToEmber, + waiting: emberWait, + waitingText: t('loginDialog.emberWaiting'), + error: emberError, + }, + { + n: '02', title: t('loginDialog.osbTitle'), description: t('loginDialog.osbDescription'), + signedIn: osbSignedIn, + login: () => void loginToOsb(), + waiting: osbWait, + waitingText: t('loginDialog.osbWaiting'), + error: '', + }, + ] + + const text = { fontFamily: 'Inter, sans-serif', fontSize: '12px', lineHeight: '16px' } + const button = { ...text, textTransform: 'none', borderRadius: 0, px: 1.25, py: 0.5, minWidth: 0, flexShrink: 0, gap: 0.5 } + + return ( + + + + + {t('loginDialog.title')} + + {t('loginDialog.subtitle')} + + + + + + + + {t('loginDialog.notice')} + + + }> + {rows.map((row) => ( + + + {row.signedIn + ? + : {row.n}} + + + {row.title} + {row.description} + {row.waiting && ( + + + {row.waitingText} + + )} + {row.error && {row.error}} + + {row.signedIn ? ( + {t('loginDialog.loggedIn')} + ) : row.waiting ? ( + + ) : ( + + )} + + ))} + + + ) +} diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index bec254b..5dbd45b 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -5,12 +5,7 @@ import { AppBar, Box, Button, - CircularProgress, Container, - Dialog, - DialogActions, - DialogContent, - DialogTitle, Drawer, IconButton, Menu, @@ -22,14 +17,16 @@ import { useScrollTrigger, } from '@mui/material' import type { ReactNode } from 'react' -import { useEffect, useRef, useState } from 'react' +import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { useLocation, useNavigate } from 'react-router-dom' -import { authClient } from '../app/container' +import { authClient, emberAuth } from '../app/container' import { useAppContext } from '../AppContext' import { Logo } from '../Icons' import DataUploadDialog from './DataUploadDialog' import { registerUploadOpener } from './UploadContext' +import LoginDialog from './LoginDialog' +import { takeLoginDialogReturn } from './loginReturn' const ArrowIcon = () => @@ -42,6 +39,9 @@ export interface PageLayoutProps { showDivider?: boolean } +/** Read once per page load: a login started in the Login dialog left or reloaded the page. */ +let pendingLoginReturn = takeLoginDialogReturn() + export default function PageLayout({ children, title, @@ -54,11 +54,21 @@ export default function PageLayout({ const [drawerOpen, setDrawerOpen] = useState(false) const [avatarAnchor, setAvatarAnchor] = useState(null) const avatarMenuOpen = Boolean(avatarAnchor) - const [waitingForLogin, setWaitingForLogin] = useState(false) - const popupRef = useRef(null) const [uploadDialogOpen, setUploadDialogOpen] = useState(false) + // Back from a login started in the Login dialog (EMBER's redirect, or the reload after OSB's + // popup): it opens again, showing what is left, until it is closed. + const [loginDialogOpen, setLoginDialogOpen] = useState(() => pendingLoginReturn) + const closeLoginDialog = () => { + pendingLoginReturn = false + setLoginDialogOpen(false) + } - async function handleLogin() { + /** + * Opens OSB's (Keycloak) login in a popup. When it completes, the popup posts to this window and + * App.tsx reloads the page; `onEnded` is for the popup being closed without that. Returns how to + * stop waiting, or null when it fell back to a full-page redirect. + */ + async function startOsbLogin(onEnded: () => void): Promise<{ cancel: () => void } | null> { let loginUrl: string try { loginUrl = await authClient.getLoginUrl(`${window.location.origin}/`) @@ -66,36 +76,50 @@ export default function PageLayout({ // keycloak-js 26 + PKCE can throw if internal state is unset (e.g. after // token expiry). Fall back to a full-page redirect via kc.login(). authClient.login() - return + return null } const w = 480, h = 600 const left = Math.round((screen.width - w) / 2) const top = Math.round((screen.height - h) / 2) - popupRef.current = window.open(loginUrl, 'kc-login', `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`) - setWaitingForLogin(true) - + const popup = window.open(loginUrl, 'kc-login', `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`) + if (!popup) { + authClient.login() + return null + } const poll = setInterval(() => { - if (popupRef.current?.closed) { + if (popup.closed) { clearInterval(poll) - setWaitingForLogin(false) + // Closed without completing (completing reloads the page first): no dialog to reopen. + takeLoginDialogReturn() + onEnded() } }, 500) + return { cancel: () => { clearInterval(poll); popup.close(); takeLoginDialogReturn(); onEnded() } } } - function cancelLogin() { - popupRef.current?.close() - setWaitingForLogin(false) - } const navigate = useNavigate() const location = useLocation() - const { authState, username } = useAppContext() + const { authState } = useAppContext() const isAuthenticated = authState === 'authenticated' + // Uploading needs both logins: EMBER-DANDI (where the data goes) and OSB (where it is analysed). + // EMBER's popup sign-in doesn't reload the page, so it updates this state. + const [emberSignedIn, setEmberSignedIn] = useState(() => emberAuth.isConnected()) + const loginsDone = isAuthenticated && emberSignedIn && emberAuth.isConnected() + /** Every "Data upload" button: the upload dialog when signed in, else the Login dialog. */ + const openUploadOrLogin = () => (loginsDone ? setUploadDialogOpen(true) : setLoginDialogOpen(true)) + /** Logs out of both: IDP forgets its EMBER token (EMBER has no logout call), then OSB's + * Keycloak session ends, which reloads the page. */ + const logout = () => { + emberAuth.disconnect() + setEmberSignedIn(false) + if (isAuthenticated) authClient.logout() + } + const anySignedIn = isAuthenticated || emberSignedIn useEffect(() => { - registerUploadOpener(() => - isAuthenticated ? setUploadDialogOpen(true) : void handleLogin() - ) - }, [isAuthenticated]) + registerUploadOpener(openUploadOrLogin) + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [loginsDone]) const navItems = [ { label: t('nav.protocols'), path: '/protocols' }, @@ -280,18 +304,18 @@ export default function PageLayout({ ))} { - !isAuthenticated && + !loginsDone && } - {isAuthenticated && ( + {anySignedIn && ( <> - + setAvatarAnchor(e.currentTarget)} sx={styles.avatar} - aria-label={username} + aria-label={t('account.title')} /> - { setAvatarAnchor(null); authClient.logout() }}> + { setAvatarAnchor(null); logout() }}> {t('nav.logout')} @@ -365,23 +389,24 @@ export default function PageLayout({ {label} ))} - {isAuthenticated ? ( + {!loginsDone && ( - ) : ( + )} + {anySignedIn && ( )} - - ) } diff --git a/applications/idp-arc/frontend/src/components/loginReturn.ts b/applications/idp-arc/frontend/src/components/loginReturn.ts new file mode 100644 index 0000000..87cb8a2 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/loginReturn.ts @@ -0,0 +1,31 @@ +/** + * Reopens the Login dialog after a login took the user away from the page: EMBER-DANDI's sign-in + * is a full-page redirect (emberOAuthClient.ts's connect(); a popup can't work, see + * .vscode/knowledge-base/ember-oauth-popup-and-coop.md), and the OSB popup's login reloads this + * page when it completes (App.tsx). Either way the dialog is unmounted, so it is marked here and + * reopened on arrival, showing what is still left to sign in to. + * + * Lives in its own module rather than in LoginDialog because exporting non-components from a + * component file breaks React Fast Refresh. + */ + +const KEY = 'idp_login_dialog_return' + +export function markLoginDialogReturn(): void { + try { + sessionStorage.setItem(KEY, '1') + } catch { + /* blocked storage — the login still works, the dialog just won't reopen by itself */ + } +} + +/** True once after a login left the page from the Login dialog; clears the mark. */ +export function takeLoginDialogReturn(): boolean { + try { + const marked = sessionStorage.getItem(KEY) !== null + sessionStorage.removeItem(KEY) + return marked + } catch { + return false + } +} diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts new file mode 100644 index 0000000..277e57a --- /dev/null +++ b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts @@ -0,0 +1,59 @@ +/** + * IEmberAuth — per-user authentication against EMBER-DANDI. + * + * Distinct from IAuthClient: that one authenticates the user to *this app* and OSB (Keycloak). + * This one authorises the app to act against *EMBER-DANDI* as that user, so the researcher's own + * copy of an upload lands in their own account. + * + * EMBER-DANDI runs django-oauth-toolkit and issues short-lived Bearer tokens + * (24h, `read write` scope) via authorization-code + PKCE. Because it is a public client + * there is no secret, so the whole flow runs in the browser and the token never reaches + * our backend or OSB. + * + * connectInPopup() is the usual flow; connect() is a full-page redirect for when the popup is + * blocked, so callers with UI state to preserve persist it first (components/loginReturn.ts). + * Why the popup works the way it does: .vscode/knowledge-base/ember-oauth-popup-and-coop.md. + */ +export interface IEmberAuth { + /** True when a usable (non-expired) access token is held. */ + isConnected(): boolean + + /** + * Starts the authorization-code + PKCE flow by navigating to EMBER-DANDI. + * `returnTo` is the path to send the user back to once the callback completes. + * Returns a promise that never resolves — the page unloads. + */ + connect(returnTo?: string): Promise + + /** + * Signs in in a popup, without leaving the page; `done` settles once this tab holds the + * token. Throws when the browser blocks the popup: then fall back to connect(). + */ + connectInPopup(): { done: Promise; cancel: () => void } + + /** On the callback page: true when it is a popup sign-in's, whose code it has handed to the + * main tab (that page then only asks to be closed); false for the redirect flow. */ + relayPopupCallback(): boolean + + /** The path passed to connect(), read once and then cleared. */ + takeReturnTo(): string | null + + /** + * Completes the flow on the redirect back. Call this on the callback route. + * Returns the access token, or null when the URL carries no authorization code. + * Throws if EMBER returned an error or the token exchange failed. + */ + handleCallback(): Promise + + /** Identity EMBER-DANDI associates with the current token. Throws when not connected. */ + getAccount(): Promise<{ username: string; name: string | null }> + + /** Epoch ms at which the current token expires; 0 when not connected. */ + readonly expiresAt: number + + /** Current access token, or null when not connected. */ + getToken(): string | null + + /** Discards the token. Does not revoke it at EMBER. */ + disconnect(): void +} diff --git a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts new file mode 100644 index 0000000..0012c91 --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts @@ -0,0 +1,331 @@ +import type { IEmberAuth } from '../core/ports/IEmberAuth' + +/** + * EMBER-DANDI OAuth via authorization-code + PKCE, run entirely in the browser. + * + * This is the ONLY file that knows EMBER's OAuth endpoints. Verified against the live service + * 2026-09-17: /oauth/authorize/ and /oauth/token/ are django-oauth-toolkit, and tokens come back + * as `Bearer` with `read write` scope and a 24h lifetime. + * + * Caveat found the hard way: the token endpoint's OPTIONS preflight returns CORS headers, but + * the POST response does not — so a browser cannot read the exchange result cross-origin. Hence + * the split between `authOrigin` and `apiBase` below: fetches go through IDP's own same-origin + * `/ember-proxy` (Vite in dev, nginx deployed). Whether EMBER could fix this via the OAuth + * application's `allowed_origins` is an open question for EMBER. + * + * The access token is held in memory and mirrored to sessionStorage so a page reload doesn't + * force a re-login. The **refresh token is deliberately never stored** — it is the + * long-lived credential, and persisting it in browser storage would hand durable account access + * to any XSS. A 24h access token means re-connecting at most once a day. + */ + +const VERIFIER_KEY = 'ember_pkce_verifier' +const TOKEN_KEY = 'ember_access_token' +const EXPIRY_KEY = 'ember_token_expiry' +const RETURN_KEY = 'ember_return_to' +const STATE_KEY = 'ember_oauth_state' + +/** Same-origin channel the popup's callback page hands the code to the main tab on. */ +const POPUP_CHANNEL = 'idp-ember-oauth' +/** `state` values starting with this mark a popup sign-in (see connectInPopup). */ +const POPUP_STATE_PREFIX = 'popup.' +/** How long the main tab waits for the popup, including a first-time sign-up. */ +const POPUP_TIMEOUT_MS = 15 * 60_000 + +/** The popup couldn't be opened (blocked by the browser): fall back to the full-page redirect. */ +export class EmberPopupBlocked extends Error {} + +/** + * Route EMBER redirects back to, and the redirect URI registered on the OAuth application (one + * per IDP origin). Also used by App.tsx, which skips Keycloak's own init() on this route. + */ +export const EMBER_CALLBACK_PATH = '/ember-callback' + +/** + * EMBER's callback params, snapshotted at module-evaluation time and removed from the URL. + * + * This has to happen before anything else reads the URL. keycloak-js treats `?code=`/`?state=` + * as its OWN OAuth callback params: on init it tries to exchange them against Keycloak's token + * endpoint and then strips them from the URL. Since it initialises on every route, it would + * consume EMBER's authorization code before this client ever sees it — the symptom being a + * silent "not connected" with a stray Keycloak token request in the network log. + * + * Module evaluation runs during import, before React renders and before any effect fires, so + * capturing here reliably wins that race. + */ +const initialCallback: { code: string | null; error: string | null; state: string | null } | null = (() => { + if (typeof window === 'undefined') return null + if (window.location.pathname !== EMBER_CALLBACK_PATH) return null + + const params = new URLSearchParams(window.location.search) + const code = params.get('code') + const rawError = params.get('error') + if (!code && !rawError) return null + + // Authorization codes are single-use, so there is nothing to retry — strip immediately. + window.history.replaceState(null, '', window.location.pathname) + + return { + code, + error: rawError && `${rawError}: ${params.get('error_description') ?? ''}`, + state: params.get('state'), + } +})() + +/** One popup sign-in's message from its callback page to the main tab. */ +interface PopupResult { state: string; code: string | null; error: string | null } + +function base64url(bytes: ArrayBuffer): string { + return btoa(String.fromCharCode(...new Uint8Array(bytes))) + .replace(/\+/g, '-') + .replace(/\//g, '_') + .replace(/=+$/, '') +} + +async function sha256(input: string): Promise { + return crypto.subtle.digest('SHA-256', new TextEncoder().encode(input)) +} + +function read(key: string): string | null { + try { + return sessionStorage.getItem(key) + } catch { + return null + } +} + +function write(key: string, value: string | null): void { + try { + if (value === null) sessionStorage.removeItem(key) + else sessionStorage.setItem(key, value) + } catch { + /* private mode / blocked storage — the in-memory copy still works for this page load */ + } +} + +export class EmberOAuthClient implements IEmberAuth { + private token: string | null = null + private callbackConsumed = false + expiresAt = 0 + + constructor( + private readonly config: { + /** + * Real EMBER-DANDI origin. Used for the /oauth/authorize/ navigation, which must reach + * EMBER directly — its login redirects out to GitHub, which returns to EMBER's own + * domain, so this leg cannot go through a dev proxy. + */ + authOrigin: string + /** + * Base for fetch() calls (token exchange and REST API): IDP's same-origin `/ember-proxy`, + * because EMBER's token response carries no CORS headers. + */ + apiBase: string + clientId: string + redirectUri: string + }, + ) { + this.token = read(TOKEN_KEY) + this.expiresAt = Number(read(EXPIRY_KEY) ?? 0) + } + + isConnected(): boolean { + return this.getToken() !== null + } + + getToken(): string | null { + // Treat a token within 60s of expiry as gone, so a call can't start and then expire mid-flight. + if (!this.token || Date.now() > this.expiresAt - 60_000) return null + return this.token + } + + /** + * Builds the authorize URL and stashes the PKCE verifier and the `state` this tab expects back. + * `state` also tells the callback page whether it is a popup: EMBER's COOP header nulls + * `window.opener` there, so the page can't tell otherwise. + */ + private async authorizeUrl(redirectUri: string, state: string): Promise { + if (!this.config.clientId) { + throw new Error('VITE_EMBER_CLIENT_ID is not set — register a public OAuth client first.') + } + const verifier = base64url(crypto.getRandomValues(new Uint8Array(48)).buffer) + write(VERIFIER_KEY, verifier) + write(STATE_KEY, state) + + const url = new URL(`${this.config.authOrigin}/oauth/authorize/`) + url.search = new URLSearchParams({ + client_id: this.config.clientId, + response_type: 'code', + redirect_uri: redirectUri, + code_challenge: base64url(await sha256(verifier)), + code_challenge_method: 'S256', + state, + }).toString() + return url.toString() + } + + /** + * Full-page redirect to EMBER's authorize endpoint. `returnTo` is where handleCallback() + * should send the user afterwards. + * + * The fallback for connectInPopup(), when the browser blocks the popup. + * + * The PKCE verifier survives the round trip because sessionStorage persists for the tab + * across navigations, including cross-origin ones. + */ + async connect(returnTo?: string): Promise { + if (returnTo) write(RETURN_KEY, returnTo) + window.location.href = await this.authorizeUrl(this.config.redirectUri, `redirect.${nonce()}`) + return new Promise(() => {}) // page is unloading + } + + /** + * Signs in in a popup, without leaving the page. Users are expected to have an (approved) + * EMBER-DANDI account already; IDP doesn't handle EMBER's sign-up or approval. + * + * EMBER's /oauth/authorize/ sends `Cross-Origin-Opener-Policy: same-origin`, which cuts the + * popup off from this window both ways: `window.opener` is null in it, and `popup.closed` reads + * true here even while it is open. So nothing here relies on that link + * (.vscode/knowledge-base/ember-oauth-popup-and-coop.md). EMBER sends the popup back to + * EMBER_CALLBACK_PATH on this origin; that page sees the popup `state` and hands the code over a + * BroadcastChannel (relayPopupCallback). This tab, which holds the PKCE verifier, swaps it for the + * token. It can't see the popup being closed, so `cancel()` and a timeout end the wait. + * + * The popup is opened synchronously, inside the click, so browsers don't block it; EMBER's URL + * is set once the PKCE challenge is ready. Throws EmberPopupBlocked when it can't be opened. + */ + connectInPopup(): { done: Promise; cancel: () => void } { + const popup = window.open('', 'ember-login', popupFeatures(520, 720)) + if (!popup) throw new EmberPopupBlocked('The EMBER-DANDI sign-in window was blocked') + const state = `${POPUP_STATE_PREFIX}${nonce()}` + const channel = new BroadcastChannel(POPUP_CHANNEL) + let finish: (err?: Error) => void = () => {} + const done = new Promise((resolve, reject) => { + const timer = setTimeout(() => finish(new Error('Signing in with EMBER-DANDI took too long. Please try again.')), POPUP_TIMEOUT_MS) + finish = (err) => { + clearTimeout(timer) + channel.close() + if (err) reject(err); else resolve() + } + channel.onmessage = (event: MessageEvent) => { + const result = event.data + if (!result || result.state !== state) return // another tab's sign-in + if (result.error) return finish(new Error(`EMBER-DANDI refused authorization: ${result.error}`)) + if (!result.code) return finish(new Error('EMBER-DANDI returned no authorization code.')) + this.exchange(result.code, state).then(() => finish(), (err: Error) => finish(err)) + } + }) + this.authorizeUrl(this.config.redirectUri, state).then( + (url) => { popup.location.href = url }, + (err: Error) => { popup.close(); finish(err) }, + ) + return { done, cancel: () => finish(new EmberSignInCancelled('Signing in with EMBER-DANDI was cancelled')) } + } + + /** + * On the callback page: when it is a popup sign-in's, hands the code (or error) to the main tab + * and returns true; the page then just tells the user to close it. False for the redirect flow, + * which goes on to handleCallback(). + */ + relayPopupCallback(): boolean { + if (!initialCallback?.state?.startsWith(POPUP_STATE_PREFIX)) return false + const channel = new BroadcastChannel(POPUP_CHANNEL) + const result: PopupResult = { state: initialCallback.state, code: initialCallback.code, error: initialCallback.error } + channel.postMessage(result) + channel.close() + return true + } + + /** Path passed to connect(), consumed once. */ + takeReturnTo(): string | null { + const value = read(RETURN_KEY) + write(RETURN_KEY, null) + return value + } + + /** Identity EMBER-DANDI associates with the current token. */ + async getAccount(): Promise<{ username: string; name: string | null }> { + const token = this.getToken() + if (!token) throw new Error('Not connected to EMBER-DANDI.') + const res = await fetch(`${this.config.apiBase}/api/users/me/`, { + headers: { Authorization: `Bearer ${token}` }, + }) + if (!res.ok) throw new Error(`Could not read EMBER-DANDI account (HTTP ${res.status}).`) + const body = await res.json() + return { username: body.username, name: body.name ?? null } + } + + async handleCallback(): Promise { + // Reads the module-load snapshot, not the live URL — see `initialCallback` above. + // Consumed once: React invokes effects twice in dev, and the code is single-use. + if (!initialCallback || this.callbackConsumed) return null + this.callbackConsumed = true + + if (initialCallback.error) { + throw new Error(`EMBER-DANDI refused authorization: ${initialCallback.error}`) + } + if (!initialCallback.code) return null + return this.exchange(initialCallback.code, initialCallback.state) + } + + /** Swaps an authorization code for an access token, if `state` is the one this tab sent. */ + private async exchange(code: string, state: string | null): Promise { + if (!state || state !== read(STATE_KEY)) { + throw new Error('The EMBER-DANDI sign-in does not match the one started here; please try again.') + } + const verifier = read(VERIFIER_KEY) + if (!verifier) { + throw new Error('No PKCE verifier found — the login was started in a different browser session.') + } + + const res = await fetch(`${this.config.apiBase}/oauth/token/`, { + method: 'POST', + headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, + body: new URLSearchParams({ + grant_type: 'authorization_code', + code, + client_id: this.config.clientId, + redirect_uri: this.config.redirectUri, + code_verifier: verifier, + }), + }) + + const body = await res.json().catch(() => ({})) + if (!res.ok) { + // A 400 here is almost always one of: the app's redirect URI list doesn't contain + // `redirectUri` exactly (scheme included), or the code was already spent. + throw new Error(`Token exchange failed (HTTP ${res.status}): ${JSON.stringify(body)}`) + } + + write(VERIFIER_KEY, null) + write(STATE_KEY, null) + this.token = body.access_token as string + this.expiresAt = Date.now() + Number(body.expires_in ?? 0) * 1000 + write(TOKEN_KEY, this.token) + write(EXPIRY_KEY, String(this.expiresAt)) + return this.token + } + + disconnect(): void { + this.token = null + this.expiresAt = 0 + write(TOKEN_KEY, null) + write(EXPIRY_KEY, null) + write(VERIFIER_KEY, null) + write(STATE_KEY, null) + } +} + +/** The user closed the wait (Cancel); not an error to show. */ +export class EmberSignInCancelled extends Error {} + +function nonce(): string { + return base64url(crypto.getRandomValues(new Uint8Array(16)).buffer) +} + +/** A centred popup of the given size. */ +function popupFeatures(w: number, h: number): string { + const left = Math.round((window.screen.width - w) / 2) + const top = Math.round((window.screen.height - h) / 2) + return `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no` +} diff --git a/applications/idp-arc/frontend/src/infra/emberUrls.ts b/applications/idp-arc/frontend/src/infra/emberUrls.ts new file mode 100644 index 0000000..3aabb12 --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberUrls.ts @@ -0,0 +1,13 @@ +/** + * EMBER-DANDI's two public domains — the API (`api-dandi...`) and the web UI a human browses + * (`dandi...`, no `api-` prefix). Shared here so the real client's env-driven origin + * (`EMBER_ORIGIN` in container.ts) and the mock client's fake dandiset links build off the same + * values instead of each hardcoding their own copy. + */ +export const EMBER_API_ORIGIN_DEFAULT = 'https://api-dandi.emberarchive.org' +export const EMBER_WEB_ORIGIN = 'https://dandi.emberarchive.org' + +/** A dandiset's page on EMBER's own web UI — e.g. for a "view on DANDI" link. */ +export function emberDandisetUrl(dandisetId: string, version: string = 'draft'): string { + return `${EMBER_WEB_ORIGIN}/dandiset/${dandisetId}/${version}` +} diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index ee7b936..a72d37f 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -60,5 +60,26 @@ "about": "About", "contact": "Contact" } + }, + "account": { + "title": "Your accounts" + }, + "loginDialog": { + "title": "Login", + "subtitle": "Login or sign up to view or upload data.", + "notice": "Login to both is required to upload & view your data.", + "emberTitle": "EMBER-DANDI", + "emberDescription": "Upload your data in EMBER-DANDI", + "osbTitle": "Open Source Brain", + "osbDescription": "Explore and analyze your uploaded data and community data with our integration with Open Source Brain (OSB).", + "login": "Login", + "signedIn": "Signed in", + "loggedIn": "Logged in", + "emberWaiting": "Sign in in the EMBER-DANDI window…", + "osbWaiting": "Sign in in the Open Source Brain window…", + "finishingSignIn": "Finishing sign in…", + "closeWindow": "You can close this window and go back to IDP.", + "cancel": "Cancel", + "close": "Close" } } diff --git a/applications/idp-arc/frontend/src/pages/EmberCallback.tsx b/applications/idp-arc/frontend/src/pages/EmberCallback.tsx new file mode 100644 index 0000000..baeb535 --- /dev/null +++ b/applications/idp-arc/frontend/src/pages/EmberCallback.tsx @@ -0,0 +1,59 @@ +import { useEffect, useState } from 'react' +import { useNavigate } from 'react-router-dom' +import { Box, Button, CircularProgress, Typography } from '@mui/material' + +import { emberAuth } from '../app/container' + +/** + * Where EMBER-DANDI's sign-in redirects back to (EMBER_CALLBACK_PATH). + * + * In the sign-in popup (the usual case): hands the code to the main tab, which finishes the + * sign-in, and closes. EMBER's COOP header can stop a script closing the window, so it then asks + * the user to close it. + * + * After the full-page redirect (when the popup was blocked): exchanges the code for the token, + * then returns to the page the sign-in started from; PageLayout reopens the Login dialog there + * (components/loginReturn.ts). + */ +export default function EmberCallback() { + const navigate = useNavigate() + const [error, setError] = useState(null) + // Relayed once, at first render: the code is single-use. + const [inPopup] = useState(() => emberAuth.relayPopupCallback()) + + useEffect(() => { + if (inPopup) { + window.close() + return + } + emberAuth + .handleCallback() + .then(() => navigate(emberAuth.takeReturnTo() ?? '/', { replace: true })) + .catch((err: unknown) => { + console.error('EMBER-DANDI sign-in failed', err) + setError(err instanceof Error ? err.message : String(err)) + }) + }, [inPopup, navigate]) + + return ( + + {inPopup ? ( + You can close this window and go back to IDP. + ) : error ? ( + <> + + Signing in with EMBER-DANDI did not work. Please try again. + + + + ) : ( + <> + + Signing in with EMBER-DANDI… + + )} + + ) +} diff --git a/applications/idp-arc/frontend/vite.config.ts b/applications/idp-arc/frontend/vite.config.ts index 5509adb..0e45607 100644 --- a/applications/idp-arc/frontend/vite.config.ts +++ b/applications/idp-arc/frontend/vite.config.ts @@ -1,6 +1,7 @@ import { defineConfig, loadEnv } from 'vite' import react from '@vitejs/plugin-react' import path from 'path' +import fs from 'node:fs' import http from 'node:http' import https from 'node:https' @@ -11,6 +12,27 @@ const BASE_DOMAIN = env.VITE_OSB_BASE_DOMAIN || 'v2dev.opensourcebrain.org' const PROTOCOL = env.VITE_OSB_PROTOCOL || 'https' const WWW_ORIGIN = `${PROTOCOL}://www.${BASE_DOMAIN}` +/** + * Optional HTTPS for the dev server: EMBER-DANDI's OAuth application only accepts https:// + * redirect URIs, so its sign-in needs https://localhost:5173 (registered as + * https://localhost:5173/ember-callback). Opt in with DEV_HTTPS=true in .env.local and a cert: + * openssl req -x509 -newkey rsa:2048 -keyout .certs/key.pem -out .certs/cert.pem \ + * -days 365 -nodes -subj "/CN=localhost" + */ +function loadDevHttpsCerts(): { key: Buffer; cert: Buffer } | undefined { + if (env.DEV_HTTPS !== 'true') return undefined + const certDir = path.resolve(__dirname, '.certs') + if (!fs.existsSync(`${certDir}/cert.pem`)) { + console.warn('[vite] DEV_HTTPS=true but .certs/cert.pem is missing — falling back to http') + return undefined + } + return { key: fs.readFileSync(`${certDir}/key.pem`), cert: fs.readFileSync(`${certDir}/cert.pem`) } +} +const devHttps = loadDevHttpsCerts() + +// EMBER-DANDI's API: the browser's own EMBER calls go through /ember-proxy, because EMBER's +// OAuth token response carries no CORS headers. Deployed, nginx does the same (default.conf). +const EMBER_ORIGIN = env.VITE_EMBER_ORIGIN || 'https://api-dandi.emberarchive.org' // eslint-disable-next-line no-console console.log(`[vite] proxying OSB -> ${WWW_ORIGIN}`) @@ -33,6 +55,7 @@ export default defineConfig({ host: '0.0.0.0', port: 5173, strictPort: true, + ...(devHttps ? { https: devHttps } : {}), watch: { usePolling: true }, @@ -43,6 +66,11 @@ export default defineConfig({ changeOrigin: true, rewrite: (path) => path.replace(/^\/api-proxy/, ''), }, + '/ember-proxy': { + target: EMBER_ORIGIN, + changeOrigin: true, + rewrite: (path) => path.replace(/^\/ember-proxy/, ''), + }, }, }, resolve: { diff --git a/deployment/codefresh-dev.yaml b/deployment/codefresh-dev.yaml index 70bc13f..a50b035 100644 --- a/deployment/codefresh-dev.yaml +++ b/deployment/codefresh-dev.yaml @@ -143,6 +143,7 @@ steps: - NOCACHE=${{CF_BUILD_ID}} - CLOUDHARNESS_FRONTEND_BUILD=${{REGISTRY}}/cloud-harness/cloudharness-frontend-build:${{CLOUDHARNESS_FRONTEND_BUILD_TAG}} - VITE_UPLOAD_BUCKET_URL=${{VITE_UPLOAD_BUCKET_URL}} + - VITE_EMBER_CLIENT_ID=${{VITE_EMBER_CLIENT_ID}} image_name: cloud-harness/idp-arc title: Idp arc working_directory: ./applications/idp-arc From d8cf1167dec05bd047be1b7a34dd28624252b3db Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 00:36:25 +0530 Subject: [PATCH 03/32] IDP-45: My dandisets link; Protocols page's Data upload button --- .../idp-arc/frontend/src/app/container.ts | 8 +++++++- .../frontend/src/components/DataUploadDialog.tsx | 6 ++++-- .../frontend/src/components/PageLayout.tsx | 16 +++++++++++++--- .../frontend/src/components/UploadContext.ts | 8 +++++--- .../frontend/src/locales/en/landingPage.json | 1 + .../idp-arc/frontend/src/pages/LandingPage.tsx | 2 +- .../idp-arc/frontend/src/pages/ProtocolsPage.tsx | 2 ++ 7 files changed, 33 insertions(+), 10 deletions(-) diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index c384a3d..c53f993 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -21,7 +21,7 @@ import { WorkspaceApiClient } from '../infra/workspaceApiClient' import { DandiApiClient } from '../infra/dandiApiClient' import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore' import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient' -import { EMBER_API_ORIGIN_DEFAULT } from '../infra/emberUrls' +import { EMBER_API_ORIGIN_DEFAULT, EMBER_WEB_ORIGIN } from '../infra/emberUrls' import type { IObjectStore } from '../core/ports/IObjectStore' import { createLoadWorkspacesUseCase } from '../core/use-cases/loadWorkspaces' import { createCreateAndUploadToDandiUseCase } from '../core/use-cases/createAndUploadToDandi' @@ -90,6 +90,12 @@ export const createAndUploadToDandi = createCreateAndUploadToDandiUseCase(authCl // ─── Helpers ────────────────────────────────────────────────────────────────── +/** The researcher's workspaces on OSB ("My workspaces"). */ +export const OSB_WORKSPACES_URL = `${FRONTEND_BASE}/` + +/** The signed-in researcher's own dandisets on EMBER-DANDI's website. */ +export const MY_DANDISETS_URL = `${EMBER_WEB_ORIGIN}/dandiset/my` + /** * Builds the public URL for a given workspace id. * Centralised here so no component needs to know BASE_DOMAIN. diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index b3872eb..ef40e86 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -36,11 +36,13 @@ type DialogStep = 'select' | 'upload' | 'uploading' | 'success' | 'stillRunning' export interface DataUploadDialogProps { open: boolean + /** Protocol (name) to start on; ignored unless it can be run. */ + initialProtocol?: string onClose: () => void onAuthRequired?: () => void } -export default function DataUploadDialog({ open, onClose, onAuthRequired }: DataUploadDialogProps) { +export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() interface FormState { @@ -102,7 +104,7 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data if (watchRef.current) watchRef.current.current = true return } - setForm(INITIAL_FORM) + setForm({ ...INITIAL_FORM, protocol: runnableProtocols.some((p) => p.name === initialProtocol) ? initialProtocol! : '' }) // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]) diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 5dbd45b..f0c3f81 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -20,7 +20,7 @@ import type { ReactNode } from 'react' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { useLocation, useNavigate } from 'react-router-dom' -import { authClient, emberAuth } from '../app/container' +import { authClient, emberAuth, MY_DANDISETS_URL, OSB_WORKSPACES_URL } from '../app/container' import { useAppContext } from '../AppContext' import { Logo } from '../Icons' import DataUploadDialog from './DataUploadDialog' @@ -55,6 +55,8 @@ export default function PageLayout({ const [avatarAnchor, setAvatarAnchor] = useState(null) const avatarMenuOpen = Boolean(avatarAnchor) const [uploadDialogOpen, setUploadDialogOpen] = useState(false) + /** The protocol the upload dialog opens on (e.g. from a protocol's page). */ + const [uploadProtocol, setUploadProtocol] = useState() // Back from a login started in the Login dialog (EMBER's redirect, or the reload after OSB's // popup): it opens again, showing what is left, until it is closed. const [loginDialogOpen, setLoginDialogOpen] = useState(() => pendingLoginReturn) @@ -106,7 +108,11 @@ export default function PageLayout({ const [emberSignedIn, setEmberSignedIn] = useState(() => emberAuth.isConnected()) const loginsDone = isAuthenticated && emberSignedIn && emberAuth.isConnected() /** Every "Data upload" button: the upload dialog when signed in, else the Login dialog. */ - const openUploadOrLogin = () => (loginsDone ? setUploadDialogOpen(true) : setLoginDialogOpen(true)) + const openUploadOrLogin = (protocolName?: string) => { + if (!loginsDone) return setLoginDialogOpen(true) + setUploadProtocol(protocolName) + setUploadDialogOpen(true) + } /** Logs out of both: IDP forgets its EMBER token (EMBER has no logout call), then OSB's * Keycloak session ends, which reloads the page. */ const logout = () => { @@ -124,7 +130,10 @@ export default function PageLayout({ const navItems = [ { label: t('nav.protocols'), path: '/protocols' }, { label: t('nav.about'), path: '/about' }, - ...(isAuthenticated ? [{ label: t('nav.myWorkspaces'), path: 'https://www.v2dev.opensourcebrain.org/', external: true }] : []), + ...(isAuthenticated ? [ + { label: t('nav.myWorkspaces'), path: OSB_WORKSPACES_URL, external: true }, + { label: t('nav.myDandisets'), path: MY_DANDISETS_URL, external: true }, + ] : []), ] const isActive = (path: string) => location.pathname === path @@ -492,6 +501,7 @@ export default function PageLayout({ setUploadDialogOpen(false)} onAuthRequired={() => setLoginDialogOpen(true)} /> diff --git a/applications/idp-arc/frontend/src/components/UploadContext.ts b/applications/idp-arc/frontend/src/components/UploadContext.ts index e4c75a6..f941244 100644 --- a/applications/idp-arc/frontend/src/components/UploadContext.ts +++ b/applications/idp-arc/frontend/src/components/UploadContext.ts @@ -6,7 +6,9 @@ * never be *inside* a context Provider it creates — can call openUpload() to * trigger the dialog or login flow. */ -let _opener: () => void = () => {} +let _opener: (protocolName?: string) => void = () => {} -export const registerUploadOpener = (fn: () => void) => { _opener = fn } -export const openUpload = () => _opener() +export const registerUploadOpener = (fn: (protocolName?: string) => void) => { _opener = fn } +/** Opens the upload dialog (or the Login dialog when a login is missing); `protocolName` + * preselects that protocol in it. */ +export const openUpload = (protocolName?: string) => _opener(protocolName) diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index a72d37f..568198c 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -44,6 +44,7 @@ "protocols": "Protocols", "about": "About", "myWorkspaces": "My workspaces", + "myDandisets": "My dandisets", "login": "Login", "logout": "Logout", "dataUpload": "Data upload", diff --git a/applications/idp-arc/frontend/src/pages/LandingPage.tsx b/applications/idp-arc/frontend/src/pages/LandingPage.tsx index 04209db..6828caa 100644 --- a/applications/idp-arc/frontend/src/pages/LandingPage.tsx +++ b/applications/idp-arc/frontend/src/pages/LandingPage.tsx @@ -34,7 +34,7 @@ export default function LandingPage() { - diff --git a/applications/idp-arc/frontend/src/pages/ProtocolsPage.tsx b/applications/idp-arc/frontend/src/pages/ProtocolsPage.tsx index fedbe38..61b9bfc 100644 --- a/applications/idp-arc/frontend/src/pages/ProtocolsPage.tsx +++ b/applications/idp-arc/frontend/src/pages/ProtocolsPage.tsx @@ -11,6 +11,7 @@ import { } from '@mui/material' import { useState } from 'react' import PageLayout from '../components/PageLayout' +import { openUpload } from '../components/UploadContext' import protocols from '../data/protocols.json' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' @@ -126,6 +127,7 @@ export default function ProtocolsPage() { From 5b224d987c3705a3a0f772db17e36c4e97a0bad2 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 07:56:34 +0530 Subject: [PATCH 04/32] IDP-45: upload to EMBER-DANDI and import from it --- README.md | 13 +- .../idp-arc/frontend/src/app/container.ts | 29 +- .../src/components/DataUploadDialog.tsx | 112 +++++++- .../frontend/src/core/dandisetLinks.ts | 84 ++++++ .../src/core/ports/IDandiDirectApi.ts | 77 +++++ .../src/core/ports/IEmberUploadApi.ts | 46 +++ .../frontend/src/core/ports/IObjectStore.ts | 14 + .../idp-arc/frontend/src/core/ports/index.ts | 3 + .../idp-arc/frontend/src/core/protocolRepo.ts | 6 + .../idp-arc/frontend/src/core/types.ts | 2 + .../src/core/use-cases/emberObjectStore.ts | 122 ++++++++ .../src/core/use-cases/protocolDandisets.ts | 83 ++++++ .../src/core/use-cases/runProgress.ts | 5 +- .../src/core/use-cases/runProtocol.ts | 34 ++- .../idp-arc/frontend/src/core/userMessages.ts | 4 + .../idp-arc/frontend/src/data/protocols.json | 1 + .../src/infra/emberDandiDirectClient.ts | 264 ++++++++++++++++++ .../src/infra/emberUploadApiClient.ts | 62 ++++ .../tests/unit/emberObjectStore.test.ts | 116 ++++++++ .../tests/unit/protocolDandisets.test.ts | 93 ++++++ .../frontend/tests/unit/runProtocol.test.ts | 30 ++ 21 files changed, 1182 insertions(+), 18 deletions(-) create mode 100644 applications/idp-arc/frontend/src/core/dandisetLinks.ts create mode 100644 applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts create mode 100644 applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts create mode 100644 applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts create mode 100644 applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts create mode 100644 applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts create mode 100644 applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts create mode 100644 applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts create mode 100644 applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts diff --git a/README.md b/README.md index 8d94c1f..16382a7 100644 --- a/README.md +++ b/README.md @@ -70,9 +70,16 @@ Unit tests (no browser, no backend): yarn test:unit ``` -Uploads (Scenario 1 of the MAABCD–OSB integration) go from the browser straight to a public bucket -open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL` (e.g. `https://storage.googleapis.com/maabcd`), -as `uploads////`. The bucket's CORS must allow PUT from this app's origin. +Uploads go to one of two places, chosen by `UPLOAD_BACKEND` in `src/app/container.ts`. Either +way, uploading needs both logins (EMBER-DANDI and OSB), and OSB imports the file into the +researcher's workspace from there. + +- **`ember`** (default): EMBER-DANDI, into the researcher's own dandiset and the protocol's + MAABCD dandiset (`maabcdDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, + an EMBER-DANDI OAuth application (public client, PKCE) with `/ember-callback` + as a redirect URI, and OSB's `ember-api-key` secret for the MAABCD copy. +- **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL` + (e.g. `https://storage.googleapis.com/maabcd`). Its CORS must allow PUT from this app's origin. --- diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index c53f993..34f9961 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -21,8 +21,12 @@ import { WorkspaceApiClient } from '../infra/workspaceApiClient' import { DandiApiClient } from '../infra/dandiApiClient' import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore' import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient' +import { EmberDandiDirectClient } from '../infra/emberDandiDirectClient' +import { EmberUploadApiClient } from '../infra/emberUploadApiClient' import { EMBER_API_ORIGIN_DEFAULT, EMBER_WEB_ORIGIN } from '../infra/emberUrls' import type { IObjectStore } from '../core/ports/IObjectStore' +import { createEmberObjectStore } from '../core/use-cases/emberObjectStore' +import { createProtocolDandisetsUseCases, type ProtocolDandiset } from '../core/use-cases/protocolDandisets' import { createLoadWorkspacesUseCase } from '../core/use-cases/loadWorkspaces' import { createCreateAndUploadToDandiUseCase } from '../core/use-cases/createAndUploadToDandi' import { createCreateWorkspaceUseCase } from '../core/use-cases/createWorkspace' @@ -39,6 +43,9 @@ const WORKSPACES_LIST_URL = `${WWW_BASE}/proxy/workspaces/api/workspace?page=1&per_page=24&q=&tags=` const FRONTEND_BASE = `${PROTOCOL}://www.${BASE_DOMAIN}` +/** Where uploads go: `ember` (Scenario 2, EMBER-DANDI) or `bucket` (Scenario 1, the public + * bucket gs://maabcd, VITE_UPLOAD_BUCKET_URL). Change it here to switch. */ +export const UPLOAD_BACKEND = 'ember' as 'bucket' | 'ember' /** EMBER-DANDI's API origin: where the OAuth login goes, and what OSB downloads assets from. */ const EMBER_ORIGIN = (import.meta.env.VITE_EMBER_ORIGIN ?? EMBER_API_ORIGIN_DEFAULT).replace(/\/+$/, '') /** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's @@ -68,9 +75,17 @@ export const emberAuth = new EmberOAuthClient({ }) export { EMBER_CALLBACK_PATH } export { EmberPopupBlocked, EmberSignInCancelled } from '../infra/emberOAuthClient' +const emberDirect = new EmberDandiDirectClient(EMBER_FETCH_BASE) +/** The researcher's dandisets by protocol, and the workspace each runs in (dandiset metadata). */ +const protocolDandisets = createProtocolDandisetsUseCases({ + emberAuth, direct: emberDirect, osbDomain: BASE_DOMAIN, workspaceUrl: (id) => getWorkspaceUrl(id), +}) -/** Scenario 1: where uploads go before OSB imports them (`gs://maabcd`). Used by the upload flow. */ -export const objectStore: IObjectStore = new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) +/** Where uploads go before OSB imports them: the public bucket (Scenario 1), or EMBER-DANDI + * (Scenario 2: the researcher's own dandiset, plus the protocol's MAABCD dandiset through OSB). */ +export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember' + ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API), protocolDandisets, EMBER_ORIGIN) + : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) // ─── Use-cases (injected with their concrete dependencies) ──────────────────── @@ -81,13 +96,21 @@ export const loadWorkspaces = createLoadWorkspacesUseCase(authClient, workspaceA export const createWorkspace = createCreateWorkspaceUseCase(authClient, workspaceApi) /** Uploads the researcher's file, imports it and the protocol's repository into the workspace - * through OSB, and runs the notebooks in OSB's Argo task (MAABCD–OSB design, Scenario 1). */ + * through OSB, and runs the notebooks in OSB's Argo task (MAABCD–OSB design). */ export const runProtocol = createRunProtocolUseCase(authClient, workspaceApi, objectStore) /** DANDI-backed upload (Route A, see IDP-43 notes); `finalize` also runs the selected * protocol's script server-side (jupyter_kernel_client.py in OSBv2's workspaces app). */ export const createAndUploadToDandi = createCreateAndUploadToDandiUseCase(authClient, dandiApi) +/** The researcher's EMBER-DANDI dandisets for a protocol, each with the workspace it runs in when + * they still have it: what the upload dialog offers once a protocol is chosen. */ +export async function listProtocolDandisets(protocolId: string): Promise { + const ownWorkspaceIds = (await loadWorkspaces()).map((w) => Number(w.id)) + return protocolDandisets.listForProtocol(protocolId, ownWorkspaceIds) +} +export type { ProtocolDandiset } + // ─── Helpers ────────────────────────────────────────────────────────────────── /** The researcher's workspaces on OSB ("My workspaces"). */ diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index ef40e86..a925e71 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -19,7 +19,8 @@ import OpenInNewIcon from '@mui/icons-material/OpenInNewOutlined' import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' -import { getWorkspaceUrl, runProtocol } from '../app/container' +import { emberAuth, getWorkspaceUrl, listProtocolDandisets, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' +import { EMBER_SIGN_IN } from '../core/userMessages' import { useAppContext } from '../AppContext' import type { RunStep } from '../core/types' import RunChecklist from './RunChecklist' @@ -57,6 +58,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut outputsDir: string /** The run's checklist (upload, imports, run), as last reported by the use-case. */ runSteps: RunStep[] + /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ + dandisetId: string } const INITIAL_FORM: FormState = { @@ -68,10 +71,18 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut spawnedWorkspaceId: undefined, outputsDir: '', runSteps: [], + dandisetId: '', } const [form, setForm] = useState(INITIAL_FORM) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps } = form + const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId } = form + // EMBER-DANDI (Scenario 2): the upload goes to the researcher's own account (signed in to from the + // Login dialog). With the protocol, the dialog finds their dandisets for that protocol, each + // naming the workspace it runs in (its metadata): choosing one chooses both. + const usesEmber = UPLOAD_BACKEND === 'ember' + const emberSignedIn = !usesEmber || emberAuth.isConnected() + const [protocolDandisets, setProtocolDandisets] = useState(null) + const [dandisetsError, setDandisetsError] = useState('') const fileInputRef = useRef(null) // The run being watched; each run gets its own token, so stopping one never revives another. const watchRef = useRef<{ current: boolean } | null>(null) @@ -108,6 +119,36 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]) + // The chosen protocol's dandisets; the first is preselected, with its workspace. + const protocolId = runnableProtocols.find((p) => p.name === protocol)?.id + useEffect(() => { + setProtocolDandisets(null) + setDandisetsError('') + if (!open || !usesEmber || !emberSignedIn || !protocolId) return + let current = true + listProtocolDandisets(protocolId) + .then((list) => { + if (!current) return + setProtocolDandisets(list) + setForm((prev) => ({ ...prev, dandisetId: list[0]?.id ?? '', spawnedWorkspaceId: list[0]?.workspaceId })) + }) + .catch((err: unknown) => { + console.error('Could not list the EMBER-DANDI dandisets', err) + if (!current) return + setProtocolDandisets([]) + setDandisetsError('Your dandisets could not be listed; a new one will be created.') + }) + return () => { current = false } + }, [open, usesEmber, emberSignedIn, protocolId]) + + /** Messages in the dandiset section: the dialog's own 14px Inter, quieter than labels. */ + const noteText = { fontFamily: 'Inter, sans-serif', fontWeight: 400, fontSize: '14px', lineHeight: '22px', color: '#FFFFFF99' } + + const chooseDandiset = (id: string) => setForm((prev) => ({ + ...prev, dandisetId: id, spawnedWorkspaceId: protocolDandisets?.find((d) => d.id === id)?.workspaceId, + })) + + const handleDrop = useCallback((e: React.DragEvent) => { e.preventDefault() const dropped = e.dataTransfer.files[0] @@ -142,6 +183,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut // instead of creating another one. workspaceId: spawnedWorkspaceId, workspaceName: selectedProtocol.name, + dandisetId: dandisetId || undefined, }, (state) => { if (watch.current) return // the dialog was closed, or another run started: no longer this one's @@ -153,9 +195,20 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut onAuthRequired?.() return } + if (state.phase === 'failed' && state.error === EMBER_SIGN_IN) { + // The EMBER-DANDI session ended: back to the form, where the sign-in button is. + // Back to the first step, which points to the Login dialog; the dandiset and workspace stay. + setForm((prev) => ({ + ...prev, step: 'select', uploadMessage: EMBER_SIGN_IN, + spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, dandisetId: state.dandisetId ?? prev.dandisetId, + })) + return + } setForm((prev) => ({ ...prev, spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, + // A dandiset this run created is reused by a retry, not created again. + dandisetId: state.dandisetId ?? prev.dandisetId, uploadMessage: state.phase === 'failed' ? `${state.message}: ${state.error}` : state.message, outputsDir: state.outputsDir ?? prev.outputsDir, runSteps: state.steps, @@ -169,8 +222,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut } const stepIndex = step === 'select' ? 0 : 1 - const canGoNext = !!protocol - const canUpload = !!file && !fileProblem + const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null)) + const canUpload = !!file && !fileProblem && emberSignedIn return ( + {usesEmber && protocol && ( + + Your EMBER-DANDI dandiset + {uploadMessage === EMBER_SIGN_IN && ( + {EMBER_SIGN_IN} + )} + {!emberSignedIn ? ( + + + Your data is stored in your own EMBER-DANDI account. Log in to EMBER-DANDI to continue. + + + + ) : protocolDandisets === null ? ( + + + Finding your dandisets for this protocol… + + ) : protocolDandisets.length === 0 ? ( + + {dandisetsError || 'No dandiset for this protocol yet. Your upload will create a new dandiset and workspace.'} + + ) : ( + <> + + {dandisetsError && ( + {dandisetsError} + )} + + )} + + )} @@ -313,6 +411,12 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut {uploadMessage} )} + {usesEmber && ( + + {dandisetId ? `Uploading into your dandiset ${dandisetId}` : 'Uploading into a new dandiset in your EMBER-DANDI account'} + {spawnedWorkspaceId !== undefined ? `, analysed in workspace ${spawnedWorkspaceId}.` : ', analysed in a new workspace.'} + + )} + +const PROTOCOL_PREFIX = 'idp-protocol:' +const WORKSPACE_PREFIX = 'osb-workspace' + +interface Resource { + identifier?: unknown + [key: string]: unknown +} + +function resources(metadata: DandisetMetadata): Resource[] { + const r = metadata.relatedResource + return Array.isArray(r) ? (r as Resource[]) : [] +} + +/** The identifier of the first entry starting with `prefix`, without the prefix. */ +function linked(metadata: DandisetMetadata, prefix: string): string | undefined { + for (const r of resources(metadata)) { + if (typeof r.identifier === 'string' && r.identifier.startsWith(prefix)) return r.identifier.slice(prefix.length) + } + return undefined +} + +/** `metadata` with `entry` replacing any earlier entry under `prefix`; other resources untouched. */ +function withEntry(metadata: DandisetMetadata, prefix: string, entry: Resource): DandisetMetadata { + const others = resources(metadata).filter((r) => !(typeof r.identifier === 'string' && r.identifier.startsWith(prefix))) + return { ...metadata, relatedResource: [...others, entry] } +} + +function workspacePrefix(osbDomain: string): string { + return `${WORKSPACE_PREFIX}:${osbDomain}:` +} + +/** The protocol (its stable id in protocols.json) this dandiset holds data for, if recorded. */ +export function readProtocolLink(metadata: DandisetMetadata): string | undefined { + return linked(metadata, PROTOCOL_PREFIX) || undefined +} + +/** The OSB workspace (in `osbDomain`) this dandiset's data runs in, if recorded. */ +export function readWorkspaceLink(metadata: DandisetMetadata, osbDomain: string): number | undefined { + const id = Number(linked(metadata, workspacePrefix(osbDomain))) + return Number.isInteger(id) && id > 0 ? id : undefined +} + +export function withProtocolLink( + metadata: DandisetMetadata, + protocol: { id: string; name: string; url?: string }, +): DandisetMetadata { + return withEntry(metadata, PROTOCOL_PREFIX, { + schemaKey: 'Resource', + identifier: `${PROTOCOL_PREFIX}${protocol.id}`, + name: `IDP protocol: ${protocol.name}`, + ...(protocol.url ? { url: protocol.url } : {}), + relation: 'dcite:IsDescribedBy', + }) +} + +export function withWorkspaceLink( + metadata: DandisetMetadata, + osbDomain: string, + workspaceId: number, + workspaceUrl: string, +): DandisetMetadata { + const prefix = workspacePrefix(osbDomain) + return withEntry(metadata, prefix, { + schemaKey: 'Resource', + identifier: `${prefix}${workspaceId}`, + name: `Open Source Brain workspace ${workspaceId}`, + url: workspaceUrl, + relation: 'dcite:IsReferencedBy', + }) +} diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts new file mode 100644 index 0000000..f53733e --- /dev/null +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -0,0 +1,77 @@ +import type { DandisetMetadata } from '../dandisetLinks' + +/** + * IDandiDirectApi — EMBER-DANDI operations performed straight from the browser, authenticated with + * the researcher's own OAuth token (IEmberAuth). Used for the researcher's own copy of an upload; + * the MAABCD copy goes through OSB instead (IEmberUploadApi), since only OSB holds that key. + */ + +/** One part of a multipart upload, as EMBER hands it back from `initialize`. */ +export interface DirectUploadPart { + partNumber: number + size: number + url: string +} + +export interface DirectInitResult { + /** Absent when EMBER already held this content — nothing to upload. */ + uploadId?: string + /** Empty when deduplicated; the caller then skips S3 entirely. */ + parts: DirectUploadPart[] + /** Set only on the deduplicated path — the existing blob to attach an asset to. */ + blobId?: string +} + +export interface DirectUploadedPart { + partNumber: number + size: number + etag: string +} + +export interface DirectFinalizeInput { + /** Absent on the deduplicated path — no upload session to complete. */ + uploadId?: string + dandisetId: string + path: string + parts: DirectUploadedPart[] + blobId?: string +} + +/** An asset as registered in a dandiset's draft. */ +export interface RegisteredAsset { + assetPath: string + assetId: string +} + +/** A dandiset the connected EMBER account owns, as listed for the upload dialog's picker. */ +export interface OwnDandiset { + id: string + name: string +} + +export interface IDandiDirectApi { + /** `GET /dandisets/?user=me` — every dandiset this account owns, empty ones included. */ + listOwnDandisets(token: string): Promise + + /** `POST /dandisets/` — creates a public dandiset and returns its identifier. `metadata` is + * merged into the default (a description). */ + createDandiset(token: string, name: string, metadata?: DandisetMetadata): Promise + + /** `GET /dandisets/{id}/versions/draft/` — the full draft metadata. */ + getDraftMetadata(token: string, dandisetId: string): Promise + + /** `PUT /dandisets/{id}/versions/draft/` — replaces the draft metadata. Only the draft is + * writable; a published version is a frozen snapshot of it. */ + updateDraftMetadata(token: string, dandisetId: string, metadata: DandisetMetadata): Promise + + /** `POST /uploads/initialize/`. A 409 (content already present) comes back as + * `{ parts: [], blobId }` rather than an error. */ + initUpload(token: string, dandisetId: string, size: number, dandiEtag: string): Promise + + /** PUTs one part straight to S3 via its presigned URL, returning S3's ETag for that part. + * Presigned URLs carry no EMBER credential, so this also serves the uploads OSB signs. */ + putPart(url: string, blob: Blob): Promise + + /** complete → validate → register the asset, all direct to EMBER. */ + finalizeUpload(token: string, input: DirectFinalizeInput): Promise +} diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts new file mode 100644 index 0000000..49a08a3 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts @@ -0,0 +1,46 @@ +/** + * IEmberUploadApi — OSB's two EMBER-DANDI endpoints (`/ember/get_upload_urls`, + * `/ember/validate_upload`), authenticated with the OSB (Keycloak) token. OSB signs the upload + * with its own EMBER-DANDI key, which never reaches the browser; the browser still PUTs the bytes. + * + * OSB doesn't know what the dandiset is for: IDP names it (the protocol's MAABCD dandiset, from + * protocols.json). OSB builds the asset path itself, under the caller's own id. + */ + +export interface BrokeredUploadInput { + dandisetId: string + filename: string + size: number + dandiEtag: string +} + +export interface BrokeredUpload { + dandisetId: string + /** Asset path OSB chose (`//`); echoed back to validateUpload. */ + path: string + /** Absent when EMBER already held this content. */ + uploadId?: string + /** Presigned S3 part URLs; empty when deduplicated. */ + parts: { partNumber: number; url: string }[] + /** Set only when deduplicated. */ + blobId?: string +} + +export interface BrokeredValidateInput { + dandisetId: string + path: string + uploadId?: string + parts?: { partNumber: number; size: number; etag: string }[] + blobId?: string +} + +export interface BrokeredAsset { + assetId: string + assetPath: string + downloadUrl: string +} + +export interface IEmberUploadApi { + getUploadUrls(token: string, input: BrokeredUploadInput): Promise + validateUpload(token: string, input: BrokeredValidateInput): Promise +} diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index 96a8f73..d4f5a75 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -10,6 +10,16 @@ export interface ObjectUploadInput { protocolId: string /** The uploader's Keycloak id (`sub`): groups uploads by contributor. */ userSub: string + /** Scenario 2 (EMBER-DANDI) only; the bucket ignores it. */ + dandisets?: { + /** The researcher's own dandiset; created (named `newName`) when undefined. */ + user?: string + newName?: string + /** Recorded in the dandiset's metadata, with the workspace the run uses. */ + protocol?: { id: string; name: string; url?: string } + /** The protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), uploaded to through OSB. */ + maabcd?: string + } } export interface StoredObject { @@ -17,6 +27,10 @@ export interface StoredObject { url: string /** The object's name in its store, for messages and logs. */ key: string + /** Scenario 2: the researcher's dandiset it went into (created by this upload, possibly). */ + dandisetId?: string + /** Scenario 2: records the run's workspace with the upload (in the dandiset's metadata). */ + recordWorkspace?: (workspaceId: number) => Promise } export interface IObjectStore { diff --git a/applications/idp-arc/frontend/src/core/ports/index.ts b/applications/idp-arc/frontend/src/core/ports/index.ts index 1359619..28284ce 100644 --- a/applications/idp-arc/frontend/src/core/ports/index.ts +++ b/applications/idp-arc/frontend/src/core/ports/index.ts @@ -3,3 +3,6 @@ export type { IWorkspaceApi } from './IWorkspaceApi' export type { IDandiApi } from './IDandiApi' export type { IObjectStore, ObjectUploadInput, StoredObject } from './IObjectStore' export type { ImportResourceInput, StartRunInput, WorkspaceResourceState } from './IWorkspaceApi' +export type { IEmberAuth } from './IEmberAuth' +export type { IDandiDirectApi, OwnDandiset } from './IDandiDirectApi' +export type { IEmberUploadApi } from './IEmberUploadApi' diff --git a/applications/idp-arc/frontend/src/core/protocolRepo.ts b/applications/idp-arc/frontend/src/core/protocolRepo.ts index 3310702..2dd0f38 100644 --- a/applications/idp-arc/frontend/src/core/protocolRepo.ts +++ b/applications/idp-arc/frontend/src/core/protocolRepo.ts @@ -25,3 +25,9 @@ export function parseRepoZipUrl(url: string | undefined): ProtocolRepo | null { const folderRef = kind === 'tags' && /^v\d/.test(ref) ? ref.slice(1) : ref return { owner, repo, ref, folder: `${repo}-${folderRef.replace(/\//g, '-')}` } } + +/** The repository's page on GitHub, for a `repoZipUrl`; undefined if it isn't a codeload URL. */ +export function repoPage(url: string | undefined): string | undefined { + const r = parseRepoZipUrl(url) + return r ? `https://github.com/${r.owner}/${r.repo}` : undefined +} diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index 2a9e2e4..814e232 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -79,6 +79,8 @@ export interface RunState { /** Every step of the run, in order, for the checklist. */ steps: RunStep[] workspaceId?: number + /** Scenario 2: the researcher's EMBER-DANDI dandiset the upload went into (kept for a retry). */ + dandisetId?: string /** This run's results folder, relative to the workspace root. */ outputsDir?: string error?: string diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts new file mode 100644 index 0000000..75b66fb --- /dev/null +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -0,0 +1,122 @@ +import type { IAuthClient } from '../ports/IAuthClient' +import type { IDandiDirectApi } from '../ports/IDandiDirectApi' +import type { IEmberAuth } from '../ports/IEmberAuth' +import type { IEmberUploadApi } from '../ports/IEmberUploadApi' +import type { IObjectStore, ObjectUploadInput, StoredObject } from '../ports/IObjectStore' +import { computeDandiEtag, type PartPlan } from '../dandiEtag' +import { EMBER_SIGN_IN, UserFacingError } from '../userMessages' +import type { ProtocolDandisets } from './protocolDandisets' + +export { EMBER_SIGN_IN } + +/** + * Scenario 2: the upload goes to EMBER-DANDI instead of the public bucket, behind the same + * IObjectStore port, so the run (runProtocol) doesn't change. Each file is uploaded twice: + * + * 1. into the researcher's own dandiset, straight from the browser with their own EMBER token + * (picked in the dialog, or created here, recorded for the protocol). Its download URL is + * what OSB imports into their workspace, so this is the copy the run uses. Once the run has + * its workspace, `recordWorkspace` writes it into the dandiset's metadata + * (protocolDandisets.ts), so the next upload for this protocol finds both; + * 2. into the protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), through OSB's + * `/ember` endpoints, which sign with OSB's key. OSB files it under the uploader's own id, + * so the dandiset holds every contributor's uploads for the protocol, one folder each. + * Skipped when the protocol has no MAABCD dandiset configured. + * + * The browser moves the bytes both times. The second transfer is normally empty: EMBER keeps one + * blob per content, so it answers the second initialize with that blob and no parts (to be + * confirmed with EMBER for blobs that live in another account's dandiset). + * + * No wait for "valid" before returning: the blob is checked against the etag when the upload is + * validated (synchronously, before the asset exists), so its download link works at once. + * Asset *metadata* validation is a separate, asynchronous check that a plain file may never pass. + */ +export function createEmberObjectStore( + osbAuth: Pick, + emberAuth: Pick, + direct: IDandiDirectApi, + osb: IEmberUploadApi, + dandisets: Pick, + /** EMBER's public API origin (`https://api-dandi.emberarchive.org`): the download link has to + * work from OSB's cluster, so never the browser's same-origin proxy. */ + emberApiOrigin: string, +): IObjectStore { + return { + async put(input: ObjectUploadInput, onProgress?: (sentBytes: number, totalBytes: number) => void): Promise { + const { file } = input + const token = emberAuth.getToken() + if (!token) throw new UserFacingError(EMBER_SIGN_IN, 'No EMBER-DANDI token (not signed in, or it expired)') + const maabcdDandisetId = input.dandisets?.maabcd || undefined + + // Bytes counted across both transfers, so the progress bar runs once from 0 to 100%. + const transfers = maabcdDandisetId ? 2 : 1 + const total = file.size * transfers + let done = 0 + const progress = (sentInTransfer: number) => onProgress?.(Math.min(done + sentInTransfer, total), total) + const skipTransfer = () => { done += file.size; progress(0) } + + const { etag, parts: plan } = await computeDandiEtag(file) + + // 1. The researcher's own copy. + const protocol = input.dandisets?.protocol ?? { id: input.protocolId, name: input.protocolId } + const userDandisetId = input.dandisets?.user + || await dandisets.createForProtocol(input.dandisets?.newName || `IDP upload: ${protocol.name}`, protocol) + const path = `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` + const init = await direct.initUpload(token, userDandisetId, file.size, etag) + const uploaded = await putParts(init.parts, plan, file, progress) + if (!init.parts.length) skipTransfer(); else done += file.size + const asset = await direct.finalizeUpload(token, { + uploadId: init.uploadId, dandisetId: userDandisetId, path, parts: uploaded, blobId: init.blobId, + }) + + // 2. The MAABCD copy, through OSB. + if (maabcdDandisetId) { + const osbToken = await osbAuth.getToken() + const brokered = await osb.getUploadUrls(osbToken, { + dandisetId: maabcdDandisetId, filename: file.name, size: file.size, dandiEtag: etag, + }) + const brokeredParts = await putParts(brokered.parts, plan, file, progress) + if (!brokered.parts.length) skipTransfer(); else done += file.size + await osb.validateUpload(osbToken, { + dandisetId: brokered.dandisetId, + path: brokered.path, + uploadId: brokered.uploadId, + parts: brokered.blobId ? undefined : brokeredParts, + blobId: brokered.blobId, + }) + } + progress(0) + + return { + url: `${emberApiOrigin.replace(/\/+$/, '')}/api/assets/${asset.assetId}/download/`, + key: asset.assetPath, + dandisetId: userDandisetId, + recordWorkspace: (workspaceId: number) => dandisets.recordWorkspace(userDandisetId, workspaceId, protocol), + } + + async function putParts(parts: { partNumber: number; url: string }[], plan: PartPlan[], file: File, + report: (sentInTransfer: number) => void) { + // Every part or none (deduplicated): a shorter list would silently upload a truncated file. + if (parts.length && parts.length !== plan.length) { + throw new Error(`EMBER returned ${parts.length} part URLs for a file of ${plan.length} parts`) + } + const result: { partNumber: number; size: number; etag: string }[] = [] + let sent = 0 + for (const part of parts) { + const slice = plan.find((p) => p.partNumber === part.partNumber) + if (!slice) throw new Error(`EMBER asked for part ${part.partNumber}, which this file doesn't have`) + const partEtag = await direct.putPart(part.url, file.slice(slice.start, slice.end)) + result.push({ partNumber: part.partNumber, size: slice.size, etag: partEtag }) + sent += slice.size + report(sent) + } + return result + } + }, + } +} + +/** One asset path segment: DANDI rejects `@` and the like; also stops `/` adding segments. */ +function pathSafe(value: string): string { + return value.replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^[-._]+|[-._]+$/g, '') || 'unknown' +} diff --git a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts new file mode 100644 index 0000000..b4b56fd --- /dev/null +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -0,0 +1,83 @@ +import type { IDandiDirectApi } from '../ports/IDandiDirectApi' +import type { IEmberAuth } from '../ports/IEmberAuth' +import { readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink, type DandisetMetadata } from '../dandisetLinks' +import { EMBER_SIGN_IN, UserFacingError } from '../userMessages' + +/** One of the researcher's dandisets for a protocol, as the upload dialog offers it. */ +export interface ProtocolDandiset { + id: string + name: string + /** The OSB workspace recorded in its metadata, when the researcher still has it. */ + workspaceId?: number +} + +export interface ProtocolRef { + id: string + name: string + /** A page about the protocol (its repository), recorded with the link. */ + url?: string +} + +/** + * The researcher's EMBER-DANDI dandisets, organised by protocol through their metadata + * (dandisetLinks.ts): which ones hold data for a protocol, which OSB workspace each runs in, and + * the writes that record both. + */ +export function createProtocolDandisetsUseCases(deps: { + emberAuth: Pick + direct: IDandiDirectApi + /** Scopes workspace links to one OSB environment. */ + osbDomain: string + workspaceUrl: (workspaceId: number) => string +}) { + const { emberAuth, direct, osbDomain, workspaceUrl } = deps + + function token(): string { + const t = emberAuth.getToken() + if (!t) throw new UserFacingError(EMBER_SIGN_IN, 'No EMBER-DANDI token (not signed in, or it expired)') + return t + } + + /** + * The researcher's dandisets recorded for `protocolId`, each with its workspace. One metadata + * read per dandiset they own (EMBER's list carries no metadata). A workspace link is dropped + * when it isn't among `ownWorkspaceIds` (deleted, or someone else's): a new one is made then. + */ + async function listForProtocol(protocolId: string, ownWorkspaceIds: number[]): Promise { + const t = token() + const own = await direct.listOwnDandisets(t) + const read = await Promise.all(own.map(async (d) => { + try { + return { d, metadata: await direct.getDraftMetadata(t, d.id) } + } catch (err) { + console.warn(`Could not read the metadata of dandiset ${d.id}`, err) + return null + } + })) + return read + .filter((r): r is { d: (typeof own)[number]; metadata: DandisetMetadata } => !!r && readProtocolLink(r.metadata) === protocolId) + .map(({ d, metadata }) => { + const linked = readWorkspaceLink(metadata, osbDomain) + return { id: d.id, name: d.name, ...(linked && ownWorkspaceIds.includes(linked) ? { workspaceId: linked } : {}) } + }) + } + + /** A new dandiset in the researcher's account, recorded for `protocol`. */ + async function createForProtocol(name: string, protocol: ProtocolRef): Promise { + return direct.createDandiset(token(), name, withProtocolLink({}, protocol)) + } + + /** Records `workspaceId` (and `protocol`, if missing) in the dandiset's metadata; no write when + * both are already there. */ + async function recordWorkspace(dandisetId: string, workspaceId: number, protocol: ProtocolRef): Promise { + const t = token() + const metadata = await direct.getDraftMetadata(t, dandisetId) + if (readWorkspaceLink(metadata, osbDomain) === workspaceId && readProtocolLink(metadata) === protocol.id) return + const linked = withWorkspaceLink(withProtocolLink(metadata, protocol), osbDomain, workspaceId, workspaceUrl(workspaceId)) + await direct.updateDraftMetadata(t, dandisetId, linked) + } + + return { listForProtocol, createForProtocol, recordWorkspace } +} + +export type ProtocolDandisets = ReturnType diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts index 8a94eb0..b4b4939 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts @@ -25,6 +25,7 @@ export class RunProgress { /** Set once the run has failed or finished: nothing reports over the outcome after that. */ private ended = false workspaceId?: number + dandisetId?: string outputsDir?: string constructor(report: OnRunState, steps: { id: string; label: string }[], workspaceId?: number) { @@ -92,8 +93,8 @@ export class RunProgress { } emit(message: string, error?: string) { - const { phase, steps, workspaceId, outputsDir } = this - this.report({ phase, message, steps, workspaceId, outputsDir, ...(error ? { error } : {}) }) + const { phase, steps, workspaceId, dandisetId, outputsDir } = this + this.report({ phase, message, steps, workspaceId, outputsDir, ...(dandisetId ? { dandisetId } : {}), ...(error ? { error } : {}) }) } private set(id: string, state: StepState, detail?: string) { diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 2823026..9f91b31 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -3,7 +3,7 @@ import type { IObjectStore, StoredObject } from '../ports/IObjectStore' import type { IWorkspaceApi, WorkspaceResourceState } from '../ports/IWorkspaceApi' import { formatBytes } from '../formatBytes' import { inputFileProblem } from '../inputFormats' -import { parseRepoZipUrl } from '../protocolRepo' +import { parseRepoZipUrl, repoPage } from '../protocolRepo' import { RUN_SETTINGS } from '../runSettings' import { UserFacingError } from '../userMessages' import { workspaceLayout } from '../workspaceLayout' @@ -28,6 +28,9 @@ export interface RunProtocolDefinition { /** The image the notebooks run in (their environment): an OSB application's name (e.g. `netpyne`) * or an image reference from a registry OSB allows. Without it, OSB's default (JupyterLab). */ image?: string + /** Scenario 2: the protocol's MAABCD dandiset on EMBER-DANDI, which every contributor's upload + * is also copied into (through OSB). Empty or absent: no MAABCD copy. */ + maabcdDandisetId?: string } export interface RunProtocolInput { @@ -38,6 +41,9 @@ export interface RunProtocolInput { workspaceId?: number /** Name for the workspace created when `workspaceId` is undefined. */ workspaceName: string + /** Scenario 2: the researcher's own EMBER-DANDI dandiset to upload into; a new one is created + * when undefined. The bucket (Scenario 1) ignores it. */ + dandisetId?: string } /** @@ -63,10 +69,11 @@ const STEPS = [ ] /** - * Runs a protocol on the researcher's data, per the MAABCD–OSB design (Scenario 1). Before anything + * Runs a protocol on the researcher's data, per the MAABCD–OSB design. Before anything * moves, the protocol and the file are checked; then, one step per entry in STEPS: * - * 1. Upload: browser → public bucket (IObjectStore); its URL is what OSB imports. It goes first + * 1. Upload through IObjectStore: browser → public bucket (Scenario 1), or → EMBER-DANDI + * (Scenario 2, emberObjectStore.ts); the URL it returns is what OSB imports. It goes first * (the design runs it in parallel with the workspace side): nothing is created in OSB until * the file is safely in the bucket, so a failed upload leaves no empty workspace. * 2. Workspace: the selected one, or a new one tagged `maabcd:`. @@ -118,8 +125,13 @@ export function createRunProtocolUseCase( const stored = file ? await inStep('upload', () => uploadFile(file, userId)) : null if (stopped()) return - // 2. Get the workspace: the selected one, or a new one. - const workspaceId = await inStep('workspace', prepareWorkspace) + // 2. Get the workspace: the selected one, or a new one; recorded with the upload (Scenario 2: + // in the dandiset's metadata, so the next upload for this protocol finds both). + const workspaceId = await inStep('workspace', async () => { + const id = await prepareWorkspace() + await stored?.recordWorkspace?.(id) + return id + }) if (stopped()) return // 3. Import the analysis code (the protocol's repository). @@ -160,12 +172,22 @@ export function createRunProtocolUseCase( const message = `Uploading ${file.name}…` progress.start('upload', 'uploading', message, `0 B of ${formatBytes(file.size)}`) let lastReport = 0 - const stored = await objectStore.put({ file, protocolId: protocol.id, userSub: userId }, (sent, total) => { + const stored = await objectStore.put({ + file, protocolId: protocol.id, userSub: userId, + dandisets: { + user: input.dandisetId, + newName: `${protocol.name} (IDP)`, + protocol: { id: protocol.id, name: protocol.name, url: repoPage(protocol.repoZipUrl) }, + maabcd: protocol.maabcdDandisetId, + }, + }, (sent, total) => { if (Date.now() - lastReport < RUN_SETTINGS.uploadProgressMs && sent < total) return lastReport = Date.now() const pct = total ? Math.round((sent / total) * 100) : 100 progress.update('upload', `${formatBytes(sent)} of ${formatBytes(total)} (${pct}%)`, message) }) + // Kept by the dialog, so a retry uploads into the same dandiset rather than creating another. + if (stored.dandisetId) progress.dandisetId = stored.dandisetId progress.done('upload', undefined, 'Upload finished') return stored } diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index e093f31..125331d 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -21,6 +21,10 @@ const STEP_FAILED: Record = { run: 'The analysis did not finish. Open the workspace to see what happened.', } +/** Says the EMBER-DANDI session is missing or over. Deliberately not SIGN_IN_AGAIN's wording, + * which sends the user to the OSB (Keycloak) login instead. */ +export const EMBER_SIGN_IN = 'Please sign in with EMBER-DANDI and try again.' + /** Says the session has ended; the dialog sends the user to sign in when the text contains it. */ export const SIGN_IN_AGAIN = 'sign in again' diff --git a/applications/idp-arc/frontend/src/data/protocols.json b/applications/idp-arc/frontend/src/data/protocols.json index 13306ee..0488d22 100644 --- a/applications/idp-arc/frontend/src/data/protocols.json +++ b/applications/idp-arc/frontend/src/data/protocols.json @@ -4,6 +4,7 @@ "name": "Four-choice reversal digging task", "repoZipUrl": "https://codeload.github.com/maracbaylis/four-choice-example/zip/refs/heads/main", "notebooksDir": "notebooks", + "maabcdDandisetId": "000542", "inputFormats": [".xlsx", ".zip"], "templatesZipUrl": "protocols_archives/4c.zip", "description": "In the four choice reversal digging task mice must identify the single rewarded option and update their choice when a previously unrewarded option becomes rewarded. The reversal phase in this task is sensitive to orbitofrontal and dorsomedial prefrontal cortex function and the 2-day version used here provides a metric of recall on the 2nd day of testing before reversal.", diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts new file mode 100644 index 0000000..d49964f --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -0,0 +1,264 @@ +import type { DandisetMetadata } from '../core/dandisetLinks' +import type { + DirectFinalizeInput, + DirectInitResult, + IDandiDirectApi, + OwnDandiset, + RegisteredAsset, +} from '../core/ports/IDandiDirectApi' + +/** + * Whether IDP works with embargoed dandisets at all. Off for now: dandisets are created public and + * only non-embargoed ones are listed. Turning it on creates them embargoed and lists embargoed ones + * too (EMBER-DANDI leaves those out of `?user=me` unless asked, whoever owns them). + */ +export const ALLOW_EMBARGOED = false + +/** + * Talks to EMBER-DANDI's REST API directly from the browser with a per-user Bearer token. + * + * Every call here was verified against the live service (Sep 2026). Two findings are + * load-bearing and easy to get wrong: + * + * 1. OAuth tokens use `Authorization: Bearer `. The admin key uses + * `Authorization: token ` (Girder-derived). Using the wrong scheme is a silent 401. + * 2. The S3 CompleteMultipartUpload POST works from a browser — it was assumed this would + * have to stay server-side, and it doesn't. + * + * `baseUrl` is IDP's same-origin `/ember-proxy` (Vite in dev, nginx deployed); see + * EMBER_FETCH_BASE in container.ts. + */ +export class EmberDandiDirectClient implements IDandiDirectApi { + constructor(private readonly baseUrl: string) {} + + private headers(token: string, json = false): HeadersInit { + return { + Authorization: `Bearer ${token}`, + ...(json ? { 'Content-Type': 'application/json' } : {}), + } + } + + private async fail(res: Response, what: string): Promise { + const body = await res.text().catch(() => '') + throw new Error(`EMBER ${what} failed (HTTP ${res.status}): ${body.slice(0, 300)}`) + } + + async listOwnDandisets(token: string): Promise { + // `empty=true` keeps a dandiset that has no assets yet in the list; embargoed ones need + // `embargoed=true` (see ALLOW_EMBARGOED). + const embargoed = ALLOW_EMBARGOED ? '&embargoed=true' : '' + const res = await fetch( + `${this.baseUrl}/api/dandisets/?user=me${embargoed}&empty=true&page_size=100`, + { headers: this.headers(token) }, + ) + if (!res.ok) await this.fail(res, 'dandiset list') + const body = await res.json() + return (body.results ?? []).map( + (d: { identifier: string; draft_version?: { name?: string } }) => ({ + id: d.identifier, + name: d.draft_version?.name ?? d.identifier, + }), + ) + } + + async createDandiset(token: string, name: string, metadata: DandisetMetadata = {}): Promise { + const res = await fetch(`${this.baseUrl}/api/dandisets/${ALLOW_EMBARGOED ? '?embargo=true' : ''}`, { + method: 'POST', + headers: this.headers(token, true), + body: JSON.stringify({ + name, + metadata: { + description: 'Created by IDP to hold this researcher’s uploaded data.', + ...metadata, + }, + }), + }) + if (!res.ok) await this.fail(res, 'dandiset create') + return (await res.json()).identifier + } + + async getDraftMetadata(token: string, dandisetId: string): Promise { + const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/`, { + headers: this.headers(token), + }) + if (!res.ok) await this.fail(res, 'draft metadata read') + return (await res.json()) as DandisetMetadata + } + + async updateDraftMetadata(token: string, dandisetId: string, metadata: DandisetMetadata): Promise { + // The PUT replaces the whole document and wants the name alongside it, so callers pass the + // full metadata they read, with only their own change applied. + const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/`, { + method: 'PUT', + headers: this.headers(token, true), + body: JSON.stringify({ name: metadata.name, metadata }), + }) + if (!res.ok) await this.fail(res, 'draft metadata update') + } + + /** `POST /blobs/digest/`: the existing blob for this content, or null. */ + private async resolveBlobByDigest(token: string, dandiEtag: string): Promise { + const res = await fetch(`${this.baseUrl}/api/blobs/digest/`, { + method: 'POST', + headers: this.headers(token, true), + body: JSON.stringify({ algorithm: 'dandi:dandi-etag', value: dandiEtag }), + }) + // 404 is the expected "no such blob" answer, not an error. + if (res.status === 404) return null + if (!res.ok) return null // treat any refusal as "can't reuse" and fall back to uploading + const body = await res.json().catch(() => null) + return body?.blob_id ?? null + } + + private async registerAsset( + token: string, + dandisetId: string, + path: string, + blobId: string, + ): Promise { + const res = await fetch( + `${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/assets/`, + { + method: 'POST', + headers: this.headers(token, true), + body: JSON.stringify({ + // schemaKey and encodingFormat are the only fields dandi-schema requires beyond what + // DANDI backfills itself; omitting either produces "'X' is a required property". + metadata: { path, schemaKey: 'Asset', encodingFormat: guessContentType(path) }, + blob_id: blobId, + }), + }, + ) + // Already registered at this path — a re-upload of the same file. Reuse it. + if (res.status === 409) { + return { assetPath: path, assetId: await this.findDraftAssetId(token, dandisetId, path) } + } + if (!res.ok) await this.fail(res, 'register_asset') + const body = await res.json() + return { assetPath: body.path ?? path, assetId: body.asset_id } + } + + /** The 409 above carries no asset id, so look the existing asset up by path. EMBER's `path` + * filter matches by prefix, hence the exact comparison. */ + private async findDraftAssetId(token: string, dandisetId: string, path: string): Promise { + const res = await fetch( + `${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/assets/?path=${encodeURIComponent(path)}`, + { headers: this.headers(token) }, + ) + if (!res.ok) await this.fail(res, 'asset lookup') + const body = await res.json() + const asset = (body.results ?? []).find((a: { path: string }) => a.path === path) + if (!asset) throw new Error(`EMBER reported ${path} as already registered but has no such asset`) + return asset.asset_id + } + + async initUpload( + token: string, + dandisetId: string, + size: number, + dandiEtag: string, + ): Promise { + const res = await fetch(`${this.baseUrl}/api/uploads/initialize/`, { + method: 'POST', + headers: this.headers(token, true), + body: JSON.stringify({ + contentSize: size, + dandiset: dandisetId, + digest: { algorithm: 'dandi:dandi-etag', value: dandiEtag }, + }), + }) + + // 409 means EMBER already has this exact content — nothing to transfer. Mirrors the + // OSB adapter's handling of the same response. + if (res.status === 409) { + const blobId = await this.resolveBlobByDigest(token, dandiEtag) + if (!blobId) await this.fail(res, 'initialize (409 but blob not resolvable)') + return { parts: [], blobId: blobId ?? undefined } + } + if (!res.ok) await this.fail(res, 'initialize') + + const body = await res.json() + return { + uploadId: body.upload_id, + parts: (body.parts ?? []).map((p: { part_number: number; size: number; upload_url: string }) => ({ + partNumber: p.part_number, + size: p.size, + url: p.upload_url, + })), + } + } + + async putPart(url: string, blob: Blob): Promise { + const res = await fetch(url, { method: 'PUT', body: blob }) + if (!res.ok) throw new Error(`S3 part upload failed (HTTP ${res.status})`) + const etag = res.headers.get('ETag') + if (!etag) { + throw new Error( + 'S3 did not expose an ETag header on the part upload — the bucket needs ' + + 'Access-Control-Expose-Headers: ETag in its CORS config.', + ) + } + return etag.replaceAll('"', '') + } + + async finalizeUpload( + token: string, + input: DirectFinalizeInput, + ): Promise { + let blobId = input.blobId + + // Nothing was uploaded on the deduplicated path, so there is no session to complete. + if (input.uploadId) { + const complete = await fetch( + `${this.baseUrl}/api/uploads/${input.uploadId}/complete/`, + { + method: 'POST', + headers: this.headers(token, true), + body: JSON.stringify({ + parts: input.parts.map((p) => ({ + part_number: p.partNumber, + size: p.size, + etag: p.etag, + })), + }), + }, + ) + if (!complete.ok) await this.fail(complete, 'complete_upload') + const completion = await complete.json() + + // DANDI hands back a presigned S3 CompleteMultipartUpload request for us to execute — + // it can't do it itself, since only the uploader holds the part ETags. + const s3 = await fetch(completion.complete_url, { + method: 'POST', + headers: { 'Content-Type': 'text/xml' }, + body: completion.body, + }) + if (!s3.ok) await this.fail(s3, 'S3 complete-multipart') + + const validate = await fetch( + `${this.baseUrl}/api/uploads/${input.uploadId}/validate/`, + { method: 'POST', headers: this.headers(token) }, + ) + if (!validate.ok) await this.fail(validate, 'validate_upload') + blobId = (await validate.json()).blob_id + } + + if (!blobId) throw new Error('No blob to register — neither an upload nor a dedup hit.') + return this.registerAsset(token, input.dandisetId, input.path, blobId) + } +} + +/** Minimal extension→MIME mapping; DANDI requires encodingFormat on every asset. */ +function guessContentType(path: string): string { + const ext = path.slice(path.lastIndexOf('.') + 1).toLowerCase() + const map: Record = { + csv: 'text/csv', + tsv: 'text/tab-separated-values', + json: 'application/json', + nwb: 'application/x-nwb', + txt: 'text/plain', + xls: 'application/vnd.ms-excel', + xlsx: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', + } + return map[ext] ?? 'application/octet-stream' +} diff --git a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts new file mode 100644 index 0000000..95f886a --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts @@ -0,0 +1,62 @@ +import type { + BrokeredAsset, + BrokeredUpload, + BrokeredUploadInput, + BrokeredValidateInput, + IEmberUploadApi, +} from '../core/ports/IEmberUploadApi' + +/** + * EmberUploadApiClient — OSB's `/ember/get_upload_urls` and `/ember/validate_upload`, on the same + * workspaces API as every other OSB call, with the OSB (Keycloak) token. OSB answers in snake_case. + */ +export class EmberUploadApiClient implements IEmberUploadApi { + constructor(private readonly baseApiUrl: string) {} + + private async post(token: string, path: string, body: unknown, what: string): Promise { + const res = await fetch(`${this.baseApiUrl}${path}`, { + method: 'POST', + headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, + body: JSON.stringify(body), + }) + if (!res.ok) { + const text = await res.text().catch(() => '') + throw new Error(`OSB ${what} failed (HTTP ${res.status}): ${text.slice(0, 300)}`) + } + return (await res.json()) as T + } + + async getUploadUrls(token: string, input: BrokeredUploadInput): Promise { + const body = await this.post<{ + dandiset_id: string + path: string + upload_id?: string | null + parts?: { part_number: number; url: string }[] + blob_id?: string | null + }>(token, '/ember/get_upload_urls', { + dandiset_id: input.dandisetId, + filename: input.filename, + size: input.size, + dandi_etag: input.dandiEtag, + }, 'get_upload_urls') + return { + dandisetId: body.dandiset_id, + path: body.path, + uploadId: body.upload_id ?? undefined, + parts: (body.parts ?? []).map((p) => ({ partNumber: p.part_number, url: p.url })), + blobId: body.blob_id ?? undefined, + } + } + + async validateUpload(token: string, input: BrokeredValidateInput): Promise { + const body = await this.post<{ asset_id: string; asset_path: string; download_url: string }>( + token, '/ember/validate_upload', { + dandiset_id: input.dandisetId, + path: input.path, + ...(input.uploadId ? { upload_id: input.uploadId } : {}), + ...(input.parts ? { parts: input.parts.map((p) => ({ part_number: p.partNumber, size: p.size, etag: p.etag })) } : {}), + ...(input.blobId ? { blob_id: input.blobId } : {}), + }, 'validate_upload') + return { assetId: body.asset_id, assetPath: body.asset_path, downloadUrl: body.download_url } + } +} diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts new file mode 100644 index 0000000..b135499 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -0,0 +1,116 @@ +// The Scenario 2 upload (core/use-cases/emberObjectStore.ts) against in-memory ports. Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { createEmberObjectStore, EMBER_SIGN_IN } from '../../src/core/use-cases/emberObjectStore' +import type { IDandiDirectApi } from '../../src/core/ports/IDandiDirectApi' +import type { IEmberUploadApi } from '../../src/core/ports/IEmberUploadApi' +import { UserFacingError } from '../../src/core/userMessages' + +const ORIGIN = 'https://api-dandi.example.org' +const file = () => new File(['animal data'], 'animal 01.xlsx') + +function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: boolean } = {}) { + const calls: string[] = [] + const direct: IDandiDirectApi = { + async listOwnDandisets() { return [] }, + async createDandiset() { throw new Error('created through the protocol use case') }, + async getDraftMetadata() { return {} }, + async updateDraftMetadata() {}, + async initUpload(token, dandisetId) { + calls.push(`direct-init:${token}:${dandisetId}`) + return opts.dedupDirect ? { parts: [], blobId: 'blob-1' } : { uploadId: 'up-1', parts: [{ partNumber: 1, size: 11, url: 'https://s3/direct' }] } + }, + async putPart(url) { calls.push(`put:${url}`); return `etag-${url.split('/').pop()}` }, + async finalizeUpload(token, input) { + calls.push(`direct-finalize:${input.dandisetId}:${input.uploadId ?? 'dedup'}:${input.parts.map((p) => p.etag).join(',')}`) + return { assetId: 'asset-1', assetPath: input.path } + }, + } + const osb: IEmberUploadApi = { + async getUploadUrls(token, input) { + calls.push(`osb-urls:${token}:${input.dandisetId}:${input.filename}:${input.dandiEtag.endsWith('-1')}`) + if (opts.dedupOsb) return { dandisetId: input.dandisetId, path: 'u/x/f', parts: [], blobId: 'blob-1' } + const parts = opts.shortParts ? [] : [{ partNumber: 1, url: 'https://s3/osb' }] + return { dandisetId: input.dandisetId, path: 'u/x/f', uploadId: 'up-2', parts: opts.shortParts ? [...parts, { partNumber: 1, url: 'https://s3/a' }, { partNumber: 2, url: 'https://s3/b' }] : parts } + }, + async validateUpload(token, input) { + calls.push(`osb-validate:${input.dandisetId}:${input.blobId ?? input.parts?.map((p) => p.etag).join(',')}`) + return { assetId: 'asset-2', assetPath: input.path, downloadUrl: 'x' } + }, + } + const dandisets = { + async createForProtocol(name: string, protocol: { id: string }) { calls.push(`create:${name}:${protocol.id}`); return '000777' }, + async recordWorkspace(dandisetId: string, workspaceId: number, protocol: { id: string }) { calls.push(`record:${dandisetId}:${workspaceId}:${protocol.id}`) }, + } + const store = (emberToken: string | null = 'ember-token') => createEmberObjectStore( + { getToken: async () => 'osb-token' }, { getToken: () => emberToken }, direct, osb, dandisets, `${ORIGIN}/`, + ) + return { calls, store } +} + +test('uploads to the picked dandiset directly, then to the MAABCD dandiset through OSB', async () => { + const { calls, store } = fakes() + const progress: number[] = [] + const stored = await store().put({ + file: file(), protocolId: 'four-choice-reversal', userSub: 'user-1', + dandisets: { user: '000123', maabcd: '000533' }, + }, (sent, total) => progress.push(sent / total)) + + assert.deepEqual(calls, [ + 'direct-init:ember-token:000123', + 'put:https://s3/direct', + 'direct-finalize:000123:up-1:etag-direct', + 'osb-urls:osb-token:000533:animal 01.xlsx:true', + 'put:https://s3/osb', + 'osb-validate:000533:etag-osb', + ]) + // The run imports the researcher's own copy, from EMBER's public origin (not the browser's proxy). + assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) + assert.match(stored.key, /^four-choice-reversal\/[0-9a-f-]{36}\/animal-01\.xlsx$/) + assert.equal(stored.dandisetId, '000123') + assert.equal(progress.at(-1), 1) + assert.ok(progress.every((p, i) => i === 0 || p >= progress[i - 1]), 'progress never goes backwards') +}) + +test('creates the dandiset for the protocol when none was picked, and skips OSB without a MAABCD dandiset', async () => { + const { calls, store } = fakes() + const stored = await store().put({ + file: file(), protocolId: 'asst', userSub: 'user-1', + dandisets: { newName: 'ASST (IDP)', protocol: { id: 'asst', name: 'ASST' }, maabcd: '' }, + }) + + assert.equal(calls[0], 'create:ASST (IDP):asst') + assert.equal(calls[1], 'direct-init:ember-token:000777') + assert.ok(!calls.some((c) => c.startsWith('osb-'))) + // The run records its workspace in the dandiset it uploaded into. + assert.equal(stored.dandisetId, '000777') + await stored.recordWorkspace?.(42) + assert.equal(calls.at(-1), 'record:000777:42:asst') +}) + +test('deduplicated content moves no bytes and registers against the existing blob', async () => { + const { calls, store } = fakes({ dedupDirect: true, dedupOsb: true }) + await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + + assert.ok(!calls.some((c) => c.startsWith('put:'))) + assert.ok(calls.includes('direct-finalize:000123:dedup:')) + assert.ok(calls.includes('osb-validate:000533:blob-1')) +}) + +test('a part list that does not cover the file is refused before anything is uploaded', async () => { + const { calls, store } = fakes({ shortParts: true }) + await assert.rejects( + store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }), + /2 part URLs for a file of 1 parts/, + ) + assert.ok(!calls.includes('put:https://s3/a')) +}) + +test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sign in', async () => { + const { calls, store } = fakes() + await assert.rejects( + store(null).put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123' } }), + (err: unknown) => err instanceof UserFacingError && err.message === EMBER_SIGN_IN, + ) + assert.deepEqual(calls, []) +}) diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts new file mode 100644 index 0000000..3a65dcf --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -0,0 +1,93 @@ +// Protocol and workspace links in a dandiset's metadata (core/dandisetLinks.ts) and the use cases +// built on them (core/use-cases/protocolDandisets.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { + readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink, type DandisetMetadata, +} from '../../src/core/dandisetLinks' +import { createProtocolDandisetsUseCases } from '../../src/core/use-cases/protocolDandisets' +import type { IDandiDirectApi } from '../../src/core/ports/IDandiDirectApi' + +const DEV = 'v2dev.opensourcebrain.org' +const FOUR = { id: 'four-choice-reversal', name: 'Four-choice reversal digging task', url: 'https://github.com/o/r' } + +test('the protocol and the workspace are relatedResource entries, alongside any others', () => { + const start: DandisetMetadata = { name: 'Mine', relatedResource: [{ identifier: 'doi:10/x', relation: 'dcite:IsCitedBy' }] } + const linked = withWorkspaceLink(withProtocolLink(start, FOUR), DEV, 42, 'https://ws/42') + + assert.equal(readProtocolLink(linked), 'four-choice-reversal') + assert.equal(readWorkspaceLink(linked, DEV), 42) + const entries = linked.relatedResource as { identifier: string; schemaKey?: string }[] + assert.deepEqual(entries.map((r) => r.identifier), ['doi:10/x', 'idp-protocol:four-choice-reversal', `osb-workspace:${DEV}:42`]) + assert.ok(entries.slice(1).every((r) => r.schemaKey === 'Resource')) + assert.equal(linked.name, 'Mine') +}) + +test('relinking replaces the earlier link instead of adding a second one', () => { + const once = withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u') + const twice = withWorkspaceLink(withProtocolLink(once, { id: 'asst', name: 'ASST' }), DEV, 43, 'u') + + assert.equal((twice.relatedResource as unknown[]).length, 2) + assert.equal(readProtocolLink(twice), 'asst') + assert.equal(readWorkspaceLink(twice, DEV), 43) +}) + +test('a workspace link only counts in its own OSB environment', () => { + const linked = withWorkspaceLink({}, DEV, 42, 'u') + assert.equal(readWorkspaceLink(linked, 'opensourcebrain.org'), undefined) +}) + +function fakeEmber(metadata: Record) { + const writes: { id: string; metadata: DandisetMetadata }[] = [] + const created: { name: string; metadata?: DandisetMetadata }[] = [] + const direct: IDandiDirectApi = { + async listOwnDandisets() { return Object.keys(metadata).map((id) => ({ id, name: `set ${id}` })) }, + async createDandiset(_t, name, m) { created.push({ name, metadata: m }); return '000900' }, + async getDraftMetadata(_t, id) { return metadata[id] ?? {} }, + async updateDraftMetadata(_t, id, m) { writes.push({ id, metadata: m }) }, + async initUpload() { throw new Error('unused') }, + async putPart() { throw new Error('unused') }, + async finalizeUpload() { throw new Error('unused') }, + } + const uc = createProtocolDandisetsUseCases({ + emberAuth: { getToken: () => 'ember-token' }, direct, osbDomain: DEV, workspaceUrl: (id) => `https://ws/${id}`, + }) + return { uc, writes, created } +} + +test('lists only the dandisets recorded for the protocol, with the workspaces the user still has', async () => { + const { uc } = fakeEmber({ + '000001': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), + '000002': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 99, 'u'), // workspace gone + '000003': withProtocolLink({}, { id: 'asst', name: 'ASST' }), + '000004': {}, // not an IDP dandiset + }) + + const list = await uc.listForProtocol('four-choice-reversal', [42, 7]) + + assert.deepEqual(list, [ + { id: '000001', name: 'set 000001', workspaceId: 42 }, + { id: '000002', name: 'set 000002' }, + ]) +}) + +test('a new dandiset is created already recorded for its protocol', async () => { + const { uc, created } = fakeEmber({}) + assert.equal(await uc.createForProtocol('Four (IDP)', FOUR), '000900') + assert.equal(readProtocolLink(created[0].metadata ?? {}), 'four-choice-reversal') +}) + +test('recording the workspace writes once, and not at all when it is already there', async () => { + const { uc, writes } = fakeEmber({ + '000001': { name: 'set', ...withProtocolLink({}, FOUR) }, + '000002': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), + }) + + await uc.recordWorkspace('000001', 42, FOUR) + await uc.recordWorkspace('000002', 42, FOUR) + + assert.equal(writes.length, 1) + assert.equal(writes[0].id, '000001') + assert.equal(readWorkspaceLink(writes[0].metadata, DEV), 42) + assert.equal(writes[0].metadata.name, 'set') +}) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index d6179a6..985c28f 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -297,3 +297,33 @@ test('an ended session mid-run asks to sign in again', async () => { assert.equal(last.phase, 'failed') assert.match(last.error ?? '', /sign in again/) }) + +test('an EMBER-DANDI upload gets the run\'s workspace recorded in its dandiset, and the dialog the dandiset id', async () => { + const f = fakes() + const seen: { dandisets?: unknown } = {} + const store: IObjectStore = { + async put(input) { + f.calls.push('upload') + seen.dandisets = input.dandisets + return { + url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777', + recordWorkspace: async (id) => { f.calls.push(`record:${id}`) }, + } + }, + } + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)( + { protocol: { ...FOUR_CHOICE, maabcdDandisetId: '000533' }, file: file(), workspaceName: 'Four-choice', dandisetId: '000123' }, + (s) => states.push(s)) + const last = states[states.length - 1] + + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(last.dandisetId, '000777') + // Recorded once the workspace exists, before anything is imported into it. + const create = f.calls.findIndex((c) => c.startsWith('create:')) + assert.equal(f.calls[create + 1], 'record:42') + assert.deepEqual(seen.dandisets, { + user: '000123', newName: 'Four-choice reversal digging task (IDP)', maabcd: '000533', + protocol: { id: 'four-choice-reversal', name: 'Four-choice reversal digging task', url: 'https://github.com/maracbaylis/four-choice-example' }, + }) +}) From 49eb19ac40e2841bbfcbdd05a64f2c0deecfda04 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 07:58:31 +0530 Subject: [PATCH 05/32] IDP-45: clearer names for the OSB URL settings; no bucket name in docs --- README.md | 4 ++-- .../idp-arc/frontend/src/app/container.ts | 24 +++++++++---------- .../src/infra/publicBucketObjectStore.ts | 6 ++--- applications/idp-arc/frontend/vite.config.ts | 12 +++++----- 4 files changed, 23 insertions(+), 23 deletions(-) diff --git a/README.md b/README.md index 16382a7..cded89d 100644 --- a/README.md +++ b/README.md @@ -78,8 +78,8 @@ researcher's workspace from there. MAABCD dandiset (`maabcdDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, an EMBER-DANDI OAuth application (public client, PKCE) with `/ember-callback` as a redirect URI, and OSB's `ember-api-key` secret for the MAABCD copy. -- **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL` - (e.g. `https://storage.googleapis.com/maabcd`). Its CORS must allow PUT from this app's origin. +- **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL`. + Its CORS must allow PUT from this app's origin. --- diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index 34f9961..ffcf4b6 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -35,16 +35,16 @@ import { createRunProtocolUseCase } from '../core/use-cases/runProtocol' // ─── Config ─────────────────────────────────────────────────────────────────── // All environment-specific URLs live here (or read from import.meta.env in Vite). -const BASE_DOMAIN = import.meta.env.VITE_OSB_BASE_DOMAIN ?? 'v2dev.opensourcebrain.org' -const PROTOCOL = import.meta.env.VITE_OSB_PROTOCOL ?? 'https' -const WWW_BASE = import.meta.env.DEV ? '/api-proxy' : `${PROTOCOL}://www.${BASE_DOMAIN}` -const WORKSPACES_API = `${WWW_BASE}/proxy/workspaces/api` +const OSB_DOMAIN = import.meta.env.VITE_OSB_BASE_DOMAIN ?? 'v2dev.opensourcebrain.org' +const OSB_SCHEME = import.meta.env.VITE_OSB_PROTOCOL ?? 'https' +const OSB_API_BASE = import.meta.env.DEV ? '/api-proxy' : `${OSB_SCHEME}://www.${OSB_DOMAIN}` +const WORKSPACES_API = `${OSB_API_BASE}/proxy/workspaces/api` const WORKSPACES_LIST_URL = - `${WWW_BASE}/proxy/workspaces/api/workspace?page=1&per_page=24&q=&tags=` -const FRONTEND_BASE = `${PROTOCOL}://www.${BASE_DOMAIN}` + `${OSB_API_BASE}/proxy/workspaces/api/workspace?page=1&per_page=24&q=&tags=` +const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` -/** Where uploads go: `ember` (Scenario 2, EMBER-DANDI) or `bucket` (Scenario 1, the public - * bucket gs://maabcd, VITE_UPLOAD_BUCKET_URL). Change it here to switch. */ +/** Where uploads go: `ember` (EMBER-DANDI) or `bucket` (the public bucket named by + * VITE_UPLOAD_BUCKET_URL). Change it here to switch. */ export const UPLOAD_BACKEND = 'ember' as 'bucket' | 'ember' /** EMBER-DANDI's API origin: where the OAuth login goes, and what OSB downloads assets from. */ const EMBER_ORIGIN = (import.meta.env.VITE_EMBER_ORIGIN ?? EMBER_API_ORIGIN_DEFAULT).replace(/\/+$/, '') @@ -78,7 +78,7 @@ export { EmberPopupBlocked, EmberSignInCancelled } from '../infra/emberOAuthClie const emberDirect = new EmberDandiDirectClient(EMBER_FETCH_BASE) /** The researcher's dandisets by protocol, and the workspace each runs in (dandiset metadata). */ const protocolDandisets = createProtocolDandisetsUseCases({ - emberAuth, direct: emberDirect, osbDomain: BASE_DOMAIN, workspaceUrl: (id) => getWorkspaceUrl(id), + emberAuth, direct: emberDirect, osbDomain: OSB_DOMAIN, workspaceUrl: (id) => getWorkspaceUrl(id), }) /** Where uploads go before OSB imports them: the public bucket (Scenario 1), or EMBER-DANDI @@ -114,15 +114,15 @@ export type { ProtocolDandiset } // ─── Helpers ────────────────────────────────────────────────────────────────── /** The researcher's workspaces on OSB ("My workspaces"). */ -export const OSB_WORKSPACES_URL = `${FRONTEND_BASE}/` +export const OSB_WORKSPACES_URL = `${OSB_WEB_ORIGIN}/` /** The signed-in researcher's own dandisets on EMBER-DANDI's website. */ export const MY_DANDISETS_URL = `${EMBER_WEB_ORIGIN}/dandiset/my` /** * Builds the public URL for a given workspace id. - * Centralised here so no component needs to know BASE_DOMAIN. + * Centralised here so no component needs to know OSB_DOMAIN. */ export function getWorkspaceUrl(workspaceId: number): string { - return `${FRONTEND_BASE}/workspaces/open/${workspaceId}/jupyter` + return `${OSB_WEB_ORIGIN}/workspaces/open/${workspaceId}/jupyter` } diff --git a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts index b3245de..b762f49 100644 --- a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts +++ b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts @@ -1,8 +1,8 @@ import type { IObjectStore, ObjectUploadInput, StoredObject } from '../core/ports/IObjectStore' /** - * Scenario 1: PUTs straight from the browser to a bucket open for anonymous writes (`gs://maabcd`, - * `https://storage.googleapis.com/maabcd`). No Authorization header; the object is readable at the + * PUTs straight from the browser to a bucket open for anonymous writes (VITE_UPLOAD_BUCKET_URL). + * No Authorization header; the object is readable at the * same URL afterwards, which is what OSB's import fetches. The bucket's CORS must allow PUT from * MAABCD's origin. * @@ -14,7 +14,7 @@ import type { IObjectStore, ObjectUploadInput, StoredObject } from '../core/port export class PublicBucketObjectStore implements IObjectStore { private readonly baseUrl: string - /** `baseUrl`: e.g. `https://storage.googleapis.com/maabcd` (VITE_UPLOAD_BUCKET_URL). */ + /** `baseUrl`: the bucket's public URL (VITE_UPLOAD_BUCKET_URL). */ constructor(baseUrl: string | undefined) { this.baseUrl = (baseUrl ?? '').replace(/\/+$/, '') } diff --git a/applications/idp-arc/frontend/vite.config.ts b/applications/idp-arc/frontend/vite.config.ts index 0e45607..ffa4d0b 100644 --- a/applications/idp-arc/frontend/vite.config.ts +++ b/applications/idp-arc/frontend/vite.config.ts @@ -8,10 +8,10 @@ import https from 'node:https' // Must use loadEnv(), not process.env — Vite doesn't load .env into process.env for this // file, so process.env here silently falls back to the production domain. const env = loadEnv(process.env.NODE_ENV ?? 'development', process.cwd(), '') -const BASE_DOMAIN = env.VITE_OSB_BASE_DOMAIN || 'v2dev.opensourcebrain.org' -const PROTOCOL = env.VITE_OSB_PROTOCOL || 'https' +const OSB_DOMAIN = env.VITE_OSB_BASE_DOMAIN || 'v2dev.opensourcebrain.org' +const OSB_SCHEME = env.VITE_OSB_PROTOCOL || 'https' -const WWW_ORIGIN = `${PROTOCOL}://www.${BASE_DOMAIN}` +const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` /** * Optional HTTPS for the dev server: EMBER-DANDI's OAuth application only accepts https:// * redirect URIs, so its sign-in needs https://localhost:5173 (registered as @@ -35,14 +35,14 @@ const devHttps = loadDevHttpsCerts() const EMBER_ORIGIN = env.VITE_EMBER_ORIGIN || 'https://api-dandi.emberarchive.org' // eslint-disable-next-line no-console -console.log(`[vite] proxying OSB -> ${WWW_ORIGIN}`) +console.log(`[vite] proxying OSB -> ${OSB_WEB_ORIGIN}`) // IPv4 lookups and reused connections for every proxied call. macOS resolves `*.local` names // (local minikube: `osb.local`) through multicast DNS first, and the IPv6 query only falls back // to /etc/hosts after a 5 s timeout, which Node paid on each new upstream connection: every // proxied request took 5 s or more (measured 30 Sep: 5018 ms default lookup vs 6 ms for IPv4). const agentOptions = { keepAlive: true, family: 4 } -const upstreamAgent = PROTOCOL === 'https' ? new https.Agent(agentOptions) : new http.Agent(agentOptions) +const upstreamAgent = OSB_SCHEME === 'https' ? new https.Agent(agentOptions) : new http.Agent(agentOptions) export default defineConfig({ plugins: [react()], @@ -61,7 +61,7 @@ export default defineConfig({ }, proxy: { '/api-proxy': { - target: WWW_ORIGIN, + target: OSB_WEB_ORIGIN, agent: upstreamAgent, changeOrigin: true, rewrite: (path) => path.replace(/^\/api-proxy/, ''), From e67f9f4b6b0a9d13638fa5a20c20a3a26560f7bc Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 09:52:07 +0530 Subject: [PATCH 06/32] IDP-45: share a copy with MAABCD, signed with a Keycloak user's key --- README.md | 3 ++- .../idp-arc/frontend/src/app/container.ts | 5 +++- .../src/components/DataUploadDialog.tsx | 23 ++++++++++++++++++- .../src/core/ports/IEmberUploadApi.ts | 3 ++- .../src/core/use-cases/runProtocol.ts | 4 +++- .../src/infra/emberUploadApiClient.ts | 6 ++++- .../frontend/tests/unit/runProtocol.test.ts | 18 +++++++++++++++ 7 files changed, 56 insertions(+), 6 deletions(-) diff --git a/README.md b/README.md index cded89d..638cfa3 100644 --- a/README.md +++ b/README.md @@ -77,7 +77,8 @@ researcher's workspace from there. - **`ember`** (default): EMBER-DANDI, into the researcher's own dandiset and the protocol's MAABCD dandiset (`maabcdDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, an EMBER-DANDI OAuth application (public client, PKCE) with `/ember-callback` - as a redirect URI, and OSB's `ember-api-key` secret for the MAABCD copy. + as a redirect URI, and, for the MAABCD copy, the + `EMBER_API_KEY` attribute on the OSB user named by `MAABCD_EMBER_USERNAME` (`container.ts`). - **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL`. Its CORS must allow PUT from this app's origin. diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index ffcf4b6..c724a22 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -46,6 +46,9 @@ const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` /** Where uploads go: `ember` (EMBER-DANDI) or `bucket` (the public bucket named by * VITE_UPLOAD_BUCKET_URL). Change it here to switch. */ export const UPLOAD_BACKEND = 'ember' as 'bucket' | 'ember' +/** The OSB (Keycloak) user whose EMBER-DANDI key (user attribute `EMBER_API_KEY`) signs the copy + * into the protocol's MAABCD dandiset. */ +const MAABCD_EMBER_USERNAME = 'maabcd-consortium' /** EMBER-DANDI's API origin: where the OAuth login goes, and what OSB downloads assets from. */ const EMBER_ORIGIN = (import.meta.env.VITE_EMBER_ORIGIN ?? EMBER_API_ORIGIN_DEFAULT).replace(/\/+$/, '') /** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's @@ -84,7 +87,7 @@ const protocolDandisets = createProtocolDandisetsUseCases({ /** Where uploads go before OSB imports them: the public bucket (Scenario 1), or EMBER-DANDI * (Scenario 2: the researcher's own dandiset, plus the protocol's MAABCD dandiset through OSB). */ export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember' - ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API), protocolDandisets, EMBER_ORIGIN) + ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_ORIGIN) : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) // ─── Use-cases (injected with their concrete dependencies) ──────────────────── diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index a925e71..e6993c6 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -3,7 +3,9 @@ import { Box, Button, CircularProgress, + Checkbox, Dialog, + FormControlLabel, IconButton, MenuItem, Select, @@ -60,6 +62,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut runSteps: RunStep[] /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ dandisetId: string + /** Also upload into the protocol's MAABCD dandiset; on by default. */ + shareWithMaabcd: boolean } const INITIAL_FORM: FormState = { @@ -72,10 +76,11 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut outputsDir: '', runSteps: [], dandisetId: '', + shareWithMaabcd: true, } const [form, setForm] = useState(INITIAL_FORM) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId } = form + const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd } = form // EMBER-DANDI (Scenario 2): the upload goes to the researcher's own account (signed in to from the // Login dialog). With the protocol, the dialog finds their dandisets for that protocol, each // naming the workspace it runs in (its metadata): choosing one chooses both. @@ -184,6 +189,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut workspaceId: spawnedWorkspaceId, workspaceName: selectedProtocol.name, dandisetId: dandisetId || undefined, + shareWithMaabcd, }, (state) => { if (watch.current) return // the dialog was closed, or another run started: no longer this one's @@ -384,6 +390,21 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut )} )} + {usesEmber && selectedProtocol?.maabcdDandisetId && ( + setForm((prev) => ({ ...prev, shareWithMaabcd: e.target.checked }))} + /> + } + label={ + + Share a copy of this data with the MAABCD consortium + + } + /> + )} diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts index 49a08a3..4a9f2d9 100644 --- a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts @@ -1,7 +1,8 @@ /** * IEmberUploadApi — OSB's two EMBER-DANDI endpoints (`/ember/get_upload_urls`, * `/ember/validate_upload`), authenticated with the OSB (Keycloak) token. OSB signs the upload - * with its own EMBER-DANDI key, which never reaches the browser; the browser still PUTs the bytes. + * with the EMBER-DANDI key held on a Keycloak user (the adapter names it), which never reaches the + * browser; the browser still PUTs the bytes. * * OSB doesn't know what the dandiset is for: IDP names it (the protocol's MAABCD dandiset, from * protocols.json). OSB builds the asset path itself, under the caller's own id. diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 9f91b31..5c5cd48 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -44,6 +44,8 @@ export interface RunProtocolInput { /** Scenario 2: the researcher's own EMBER-DANDI dandiset to upload into; a new one is created * when undefined. The bucket (Scenario 1) ignores it. */ dandisetId?: string + /** Also upload into the protocol's MAABCD dandiset, when it has one (the default). */ + shareWithMaabcd?: boolean } /** @@ -178,7 +180,7 @@ export function createRunProtocolUseCase( user: input.dandisetId, newName: `${protocol.name} (IDP)`, protocol: { id: protocol.id, name: protocol.name, url: repoPage(protocol.repoZipUrl) }, - maabcd: protocol.maabcdDandisetId, + maabcd: input.shareWithMaabcd === false ? undefined : protocol.maabcdDandisetId, }, }, (sent, total) => { if (Date.now() - lastReport < RUN_SETTINGS.uploadProgressMs && sent < total) return diff --git a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts index 95f886a..91484b7 100644 --- a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts @@ -9,9 +9,11 @@ import type { /** * EmberUploadApiClient — OSB's `/ember/get_upload_urls` and `/ember/validate_upload`, on the same * workspaces API as every other OSB call, with the OSB (Keycloak) token. OSB answers in snake_case. + * + * `keyUsername`: the Keycloak user whose EMBER-DANDI key (attribute `EMBER_API_KEY`) OSB signs with. */ export class EmberUploadApiClient implements IEmberUploadApi { - constructor(private readonly baseApiUrl: string) {} + constructor(private readonly baseApiUrl: string, private readonly keyUsername: string) {} private async post(token: string, path: string, body: unknown, what: string): Promise { const res = await fetch(`${this.baseApiUrl}${path}`, { @@ -34,6 +36,7 @@ export class EmberUploadApiClient implements IEmberUploadApi { parts?: { part_number: number; url: string }[] blob_id?: string | null }>(token, '/ember/get_upload_urls', { + username: this.keyUsername, dandiset_id: input.dandisetId, filename: input.filename, size: input.size, @@ -51,6 +54,7 @@ export class EmberUploadApiClient implements IEmberUploadApi { async validateUpload(token: string, input: BrokeredValidateInput): Promise { const body = await this.post<{ asset_id: string; asset_path: string; download_url: string }>( token, '/ember/validate_upload', { + username: this.keyUsername, dandiset_id: input.dandisetId, path: input.path, ...(input.uploadId ? { upload_id: input.uploadId } : {}), diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index 985c28f..6602aec 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -327,3 +327,21 @@ test('an EMBER-DANDI upload gets the run\'s workspace recorded in its dandiset, protocol: { id: 'four-choice-reversal', name: 'Four-choice reversal digging task', url: 'https://github.com/maracbaylis/four-choice-example' }, }) }) + +test('with "Share with MAABCD" unticked, nothing goes to the protocol\'s MAABCD dandiset', async () => { + const f = fakes() + const seen: { dandisets?: { maabcd?: string } } = {} + const store: IObjectStore = { + async put(input) { + seen.dandisets = input.dandisets + return { url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777' } + }, + } + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)( + { protocol: { ...FOUR_CHOICE, maabcdDandisetId: '000533' }, file: file(), workspaceName: 'Four-choice', shareWithMaabcd: false }, + (s) => states.push(s)) + + assert.equal(states[states.length - 1].phase, 'succeeded') + assert.equal(seen.dandisets?.maabcd, undefined) +}) From 7316be94d2a5096b3e66ac03b10a7e9e43234061 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 09:52:42 +0530 Subject: [PATCH 07/32] IDP-45: keep the OSB login state current --- applications/idp-arc/frontend/src/App.tsx | 6 +++++ .../frontend/src/components/PageLayout.tsx | 27 ++++++++++++++----- .../frontend/src/core/ports/IAuthClient.ts | 4 +++ .../frontend/src/infra/keycloakAuthClient.ts | 21 ++++++++++++--- .../src/infra/mocks/mockAuthClient.ts | 4 +++ 5 files changed, 53 insertions(+), 9 deletions(-) diff --git a/applications/idp-arc/frontend/src/App.tsx b/applications/idp-arc/frontend/src/App.tsx index 7e0b847..bf3a061 100644 --- a/applications/idp-arc/frontend/src/App.tsx +++ b/applications/idp-arc/frontend/src/App.tsx @@ -90,6 +90,12 @@ function App() { return } setAuthState(authenticated ? 'authenticated' : 'unauthenticated') + // The OSB session can end later (its refresh refused): show it as signed out then, so + // the Login dialog offers OSB's login again instead of "Logged in". + authClient.onSessionEnded(() => { + setAuthState('unauthenticated') + setTokenParsed(null) + }) if (authenticated && authClient.tokenParsed) { setTokenParsed(authClient.tokenParsed) } diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index f0c3f81..8550a84 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -107,9 +107,24 @@ export default function PageLayout({ // EMBER's popup sign-in doesn't reload the page, so it updates this state. const [emberSignedIn, setEmberSignedIn] = useState(() => emberAuth.isConnected()) const loginsDone = isAuthenticated && emberSignedIn && emberAuth.isConnected() - /** Every "Data upload" button: the upload dialog when signed in, else the Login dialog. */ - const openUploadOrLogin = (protocolName?: string) => { - if (!loginsDone) return setLoginDialogOpen(true) + /** + * Whether each login still holds, checked now rather than as of the page load: an EMBER token + * expires, and an OSB session can end without the page knowing until a token is asked for (the + * auth client then reports it, and the app shows OSB as signed out). + */ + const checkLogins = async () => { + const ember = emberAuth.isConnected() + setEmberSignedIn(ember) + const osb = isAuthenticated && await authClient.getToken().then(() => true, () => false) + return ember && osb + } + const openLoginDialog = () => { + void checkLogins() + setLoginDialogOpen(true) + } + /** Every "Data upload" button: the upload dialog when both logins hold, else the Login dialog. */ + const openUploadOrLogin = async (protocolName?: string) => { + if (!(await checkLogins())) return setLoginDialogOpen(true) setUploadProtocol(protocolName) setUploadDialogOpen(true) } @@ -313,7 +328,7 @@ export default function PageLayout({ ))} { - !loginsDone && + !loginsDone && } @@ -503,7 +518,7 @@ export default function PageLayout({ open={uploadDialogOpen} initialProtocol={uploadProtocol} onClose={() => setUploadDialogOpen(false)} - onAuthRequired={() => setLoginDialogOpen(true)} + onAuthRequired={openLoginDialog} /> void): void + /** Parsed payload of the current token, or null when unauthenticated. */ readonly tokenParsed: Record | null } diff --git a/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts b/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts index 99a3b27..1b26be4 100644 --- a/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts @@ -9,9 +9,20 @@ import type { IAuthClient } from '../core/ports/IAuthClient' */ export class KeycloakAuthClient implements IAuthClient { private readonly kc: Keycloak + private sessionEndedListeners: (() => void)[] = [] constructor(config: { url: string; realm: string; clientId: string }) { this.kc = new Keycloak(config) + // keycloak-js clears its tokens when a refresh is refused (the Keycloak session is over). + this.kc.onAuthLogout = () => this.sessionEnded() + } + + onSessionEnded(listener: () => void): void { + this.sessionEndedListeners.push(listener) + } + + private sessionEnded() { + for (const listener of this.sessionEndedListeners) listener() } init(): Promise { @@ -31,13 +42,17 @@ export class KeycloakAuthClient implements IAuthClient { } async getToken(minValidity = 30): Promise { + let refreshed = true try { await this.kc.updateToken(minValidity) } catch { - // No refresh token available (check-sso without offline session). - // Fall through and use the current token if it still exists. + // No refresh token available (check-sso without offline session), or Keycloak unreachable. + // Fall through and use the current token if it is still valid. + refreshed = false } - if (!this.kc.token) { + // An expired token that couldn't be refreshed is as good as none: OSB would refuse it. + if (!this.kc.token || (!refreshed && this.kc.isTokenExpired())) { + this.sessionEnded() throw new Error('No access token available. Please sign in again.') } return this.kc.token diff --git a/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts b/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts index 049151f..bcd49dc 100644 --- a/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts @@ -34,6 +34,10 @@ export class MockAuthClient implements IAuthClient { console.info('[MockAuthClient] login() called — no-op in mock mode') } + onSessionEnded(): void { + // The mock session never ends. + } + logout(): void { console.info('[MockAuthClient] logout() called — no-op in mock mode') } From 20b7e4c3d1b516a6adc66f1b9c615f9f8719f223 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 10:01:43 +0530 Subject: [PATCH 08/32] IDP-45: tidy comments design-doc references --- .../idp-arc/frontend/src/app/container.ts | 9 ++++---- .../src/components/DataUploadDialog.tsx | 5 ++--- .../frontend/src/core/ports/IObjectStore.ts | 11 +++++----- .../idp-arc/frontend/src/core/protocolRepo.ts | 3 +-- .../idp-arc/frontend/src/core/types.ts | 2 +- .../src/core/use-cases/emberObjectStore.ts | 21 +++++++----------- .../src/core/use-cases/runProtocol.ts | 22 +++++++++---------- .../tests/unit/emberObjectStore.test.ts | 2 +- .../frontend/tests/unit/objectStore.test.ts | 2 +- .../frontend/tests/unit/runProtocol.test.ts | 2 +- 10 files changed, 34 insertions(+), 45 deletions(-) diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index c724a22..9f7971d 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -84,8 +84,7 @@ const protocolDandisets = createProtocolDandisetsUseCases({ emberAuth, direct: emberDirect, osbDomain: OSB_DOMAIN, workspaceUrl: (id) => getWorkspaceUrl(id), }) -/** Where uploads go before OSB imports them: the public bucket (Scenario 1), or EMBER-DANDI - * (Scenario 2: the researcher's own dandiset, plus the protocol's MAABCD dandiset through OSB). */ +/** Where uploads go before OSB imports them (UPLOAD_BACKEND): EMBER-DANDI, or the public bucket. */ export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember' ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_ORIGIN) : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) @@ -99,11 +98,11 @@ export const loadWorkspaces = createLoadWorkspacesUseCase(authClient, workspaceA export const createWorkspace = createCreateWorkspaceUseCase(authClient, workspaceApi) /** Uploads the researcher's file, imports it and the protocol's repository into the workspace - * through OSB, and runs the notebooks in OSB's Argo task (MAABCD–OSB design). */ + * through OSB, and runs the notebooks in OSB's Argo task. */ export const runProtocol = createRunProtocolUseCase(authClient, workspaceApi, objectStore) -/** DANDI-backed upload (Route A, see IDP-43 notes); `finalize` also runs the selected - * protocol's script server-side (jupyter_kernel_client.py in OSBv2's workspaces app). */ +/** The earlier DANDI-backed upload; `finalize` also runs the selected protocol's script on OSB + * (jupyter_kernel_client.py in OSBv2's workspaces app). */ export const createAndUploadToDandi = createCreateAndUploadToDandiUseCase(authClient, dandiApi) /** The researcher's EMBER-DANDI dandisets for a protocol, each with the workspace it runs in when diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index e6993c6..d3a2f84 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -81,9 +81,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const [form, setForm] = useState(INITIAL_FORM) const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd } = form - // EMBER-DANDI (Scenario 2): the upload goes to the researcher's own account (signed in to from the - // Login dialog). With the protocol, the dialog finds their dandisets for that protocol, each - // naming the workspace it runs in (its metadata): choosing one chooses both. + // EMBER-DANDI: the upload goes to the researcher's own account. Choosing a protocol lists their + // dandisets for it, each with the workspace it runs in, so choosing one chooses both. const usesEmber = UPLOAD_BACKEND === 'ember' const emberSignedIn = !usesEmber || emberAuth.isConnected() const [protocolDandisets, setProtocolDandisets] = useState(null) diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index d4f5a75..f9eed5e 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -1,7 +1,6 @@ /** - * Where a researcher's upload comes to rest before OSB imports it into the workspace (MAABCD–OSB - * Integration design, "Upload port + adapter"). Scenario 1 is a public bucket; Scenario 2 swaps - * in an EMBER-DANDI adapter behind this same port, so the upload flow doesn't change. + * Where a researcher's upload is stored before OSB imports it into the workspace: EMBER-DANDI + * (emberObjectStore.ts) or a public bucket (publicBucketObjectStore.ts). The run doesn't know which. */ export interface ObjectUploadInput { @@ -10,7 +9,7 @@ export interface ObjectUploadInput { protocolId: string /** The uploader's Keycloak id (`sub`): groups uploads by contributor. */ userSub: string - /** Scenario 2 (EMBER-DANDI) only; the bucket ignores it. */ + /** EMBER-DANDI only; the bucket ignores it. */ dandisets?: { /** The researcher's own dandiset; created (named `newName`) when undefined. */ user?: string @@ -27,9 +26,9 @@ export interface StoredObject { url: string /** The object's name in its store, for messages and logs. */ key: string - /** Scenario 2: the researcher's dandiset it went into (created by this upload, possibly). */ + /** EMBER-DANDI: the researcher's dandiset it went into (possibly created by this upload). */ dandisetId?: string - /** Scenario 2: records the run's workspace with the upload (in the dandiset's metadata). */ + /** EMBER-DANDI: records the run's workspace in the dandiset's metadata. */ recordWorkspace?: (workspaceId: number) => Promise } diff --git a/applications/idp-arc/frontend/src/core/protocolRepo.ts b/applications/idp-arc/frontend/src/core/protocolRepo.ts index 2dd0f38..49c9d89 100644 --- a/applications/idp-arc/frontend/src/core/protocolRepo.ts +++ b/applications/idp-arc/frontend/src/core/protocolRepo.ts @@ -1,6 +1,5 @@ /** - * A protocol's repository, from its `repoZipUrl` in protocols.json (GitHub's codeload archive, as - * the MAABCD–OSB design names it), e.g. + * A protocol's repository, from its `repoZipUrl` in protocols.json (GitHub's codeload archive), e.g. * `https://codeload.github.com/maracbaylis/four-choice-example/zip/refs/heads/main`. */ export interface ProtocolRepo { diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index 814e232..7081c0b 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -79,7 +79,7 @@ export interface RunState { /** Every step of the run, in order, for the checklist. */ steps: RunStep[] workspaceId?: number - /** Scenario 2: the researcher's EMBER-DANDI dandiset the upload went into (kept for a retry). */ + /** The researcher's EMBER-DANDI dandiset the upload went into; a retry reuses it. */ dandisetId?: string /** This run's results folder, relative to the workspace root. */ outputsDir?: string diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index 75b66fb..125ae01 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -10,22 +10,17 @@ import type { ProtocolDandisets } from './protocolDandisets' export { EMBER_SIGN_IN } /** - * Scenario 2: the upload goes to EMBER-DANDI instead of the public bucket, behind the same - * IObjectStore port, so the run (runProtocol) doesn't change. Each file is uploaded twice: + * The EMBER-DANDI object store. Each file is uploaded twice: * - * 1. into the researcher's own dandiset, straight from the browser with their own EMBER token - * (picked in the dialog, or created here, recorded for the protocol). Its download URL is - * what OSB imports into their workspace, so this is the copy the run uses. Once the run has - * its workspace, `recordWorkspace` writes it into the dandiset's metadata - * (protocolDandisets.ts), so the next upload for this protocol finds both; + * 1. into the researcher's own dandiset, from the browser with their EMBER token. This is the + * copy OSB imports into their workspace; `recordWorkspace` then writes that workspace into + * the dandiset's metadata, so the next upload for the protocol finds both; * 2. into the protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), through OSB's - * `/ember` endpoints, which sign with OSB's key. OSB files it under the uploader's own id, - * so the dandiset holds every contributor's uploads for the protocol, one folder each. - * Skipped when the protocol has no MAABCD dandiset configured. + * `/ember` endpoints, which sign with the MAABCD account's key. Skipped when the protocol has + * none, or the researcher chose not to share. * - * The browser moves the bytes both times. The second transfer is normally empty: EMBER keeps one - * blob per content, so it answers the second initialize with that blob and no parts (to be - * confirmed with EMBER for blobs that live in another account's dandiset). + * The browser sends the bytes both times. The second transfer is usually empty: EMBER stores each + * content once, and answers with the existing blob instead of parts. * * No wait for "valid" before returning: the blob is checked against the etag when the upload is * validated (synchronously, before the asset exists), so its download link works at once. diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 5c5cd48..a0f04df 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -28,8 +28,8 @@ export interface RunProtocolDefinition { /** The image the notebooks run in (their environment): an OSB application's name (e.g. `netpyne`) * or an image reference from a registry OSB allows. Without it, OSB's default (JupyterLab). */ image?: string - /** Scenario 2: the protocol's MAABCD dandiset on EMBER-DANDI, which every contributor's upload - * is also copied into (through OSB). Empty or absent: no MAABCD copy. */ + /** The protocol's MAABCD dandiset on EMBER-DANDI, which each upload is also copied into + * (through OSB). Empty or absent: no MAABCD copy. */ maabcdDandisetId?: string } @@ -41,8 +41,8 @@ export interface RunProtocolInput { workspaceId?: number /** Name for the workspace created when `workspaceId` is undefined. */ workspaceName: string - /** Scenario 2: the researcher's own EMBER-DANDI dandiset to upload into; a new one is created - * when undefined. The bucket (Scenario 1) ignores it. */ + /** The researcher's EMBER-DANDI dandiset to upload into; undefined creates one. The bucket + * ignores it. */ dandisetId?: string /** Also upload into the protocol's MAABCD dandiset, when it has one (the default). */ shareWithMaabcd?: boolean @@ -71,13 +71,11 @@ const STEPS = [ ] /** - * Runs a protocol on the researcher's data, per the MAABCD–OSB design. Before anything - * moves, the protocol and the file are checked; then, one step per entry in STEPS: + * Runs a protocol on the researcher's data. Before anything moves, the protocol and the file are + * checked; then, one step per entry in STEPS: * - * 1. Upload through IObjectStore: browser → public bucket (Scenario 1), or → EMBER-DANDI - * (Scenario 2, emberObjectStore.ts); the URL it returns is what OSB imports. It goes first - * (the design runs it in parallel with the workspace side): nothing is created in OSB until - * the file is safely in the bucket, so a failed upload leaves no empty workspace. + * 1. Upload through IObjectStore (EMBER-DANDI or the public bucket); OSB imports from the URL + * it returns. It goes first, so a failed upload leaves no empty workspace behind. * 2. Workspace: the selected one, or a new one tagged `maabcd:`. * 3. Import the repository and * 4. import the data, both through OSB (`POST /workspaceresource`) into this run's own folder @@ -127,8 +125,8 @@ export function createRunProtocolUseCase( const stored = file ? await inStep('upload', () => uploadFile(file, userId)) : null if (stopped()) return - // 2. Get the workspace: the selected one, or a new one; recorded with the upload (Scenario 2: - // in the dandiset's metadata, so the next upload for this protocol finds both). + // 2. Get the workspace: the selected one, or a new one, recorded in the dandiset's metadata so + // the next upload for this protocol finds both. const workspaceId = await inStep('workspace', async () => { const id = await prepareWorkspace() await stored?.recordWorkspace?.(id) diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index b135499..a53d0e3 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -1,4 +1,4 @@ -// The Scenario 2 upload (core/use-cases/emberObjectStore.ts) against in-memory ports. Run: yarn test:unit +// The EMBER-DANDI upload (core/use-cases/emberObjectStore.ts) against in-memory ports. Run: yarn test:unit import { test } from 'node:test' import assert from 'node:assert/strict' import { createEmberObjectStore, EMBER_SIGN_IN } from '../../src/core/use-cases/emberObjectStore' diff --git a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts index 8f1df99..e26ceba 100644 --- a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts @@ -1,4 +1,4 @@ -// The Scenario 1 object store (infra/publicBucketObjectStore.ts). Run: yarn test:unit +// The public-bucket object store (infra/publicBucketObjectStore.ts). Run: yarn test:unit import { test } from 'node:test' import assert from 'node:assert/strict' import { objectKey } from '../../src/infra/publicBucketObjectStore' diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index 6602aec..292861e 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -1,4 +1,4 @@ -// The Scenario 1 run (core/use-cases/runProtocol.ts) against in-memory ports. Run: yarn test:unit +// The run (core/use-cases/runProtocol.ts) against in-memory ports. Run: yarn test:unit import { test, beforeEach } from 'node:test' import assert from 'node:assert/strict' import { createRunProtocolUseCase } from '../../src/core/use-cases/runProtocol' From 9d647781a891c95849d433b06dc044a68eaf37d3 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 10:59:26 +0530 Subject: [PATCH 09/32] IDP-45: publish the researcher's dandiset for a DOI at the end of a run --- .../src/components/DataUploadDialog.tsx | 27 +++++- .../src/core/ports/IDandiDirectApi.ts | 35 ++++++++ .../frontend/src/core/ports/IObjectStore.ts | 2 + .../idp-arc/frontend/src/core/runSettings.ts | 11 +++ .../idp-arc/frontend/src/core/types.ts | 4 + .../src/core/use-cases/emberObjectStore.ts | 6 +- .../src/core/use-cases/protocolDandisets.ts | 73 +++++++++++++++- .../src/core/use-cases/runProgress.ts | 3 +- .../src/core/use-cases/runProtocol.ts | 33 +++++-- .../idp-arc/frontend/src/core/userMessages.ts | 1 + .../src/infra/emberDandiDirectClient.ts | 41 +++++++++ .../tests/unit/emberObjectStore.test.ts | 11 +++ .../tests/unit/protocolDandisets.test.ts | 85 ++++++++++++++++++- .../frontend/tests/unit/runProtocol.test.ts | 56 +++++++++++- 14 files changed, 371 insertions(+), 17 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index d3a2f84..e252989 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -18,6 +18,7 @@ import CloseIcon from '@mui/icons-material/Close' import ArrowForwardIcon from '@mui/icons-material/ArrowForward' import KeyboardArrowDownIcon from '@mui/icons-material/KeyboardArrowDown' import OpenInNewIcon from '@mui/icons-material/OpenInNewOutlined' +import ContentCopyIcon from '@mui/icons-material/ContentCopyOutlined' import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' @@ -58,6 +59,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut spawnedWorkspaceId: number | undefined /** Where the last run's results are, relative to the workspace root. */ outputsDir: string + /** The DOI the run's data was published with. */ + doi?: { doi: string; url?: string } /** The run's checklist (upload, imports, run), as last reported by the use-case. */ runSteps: RunStep[] /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ @@ -80,7 +83,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut } const [form, setForm] = useState(INITIAL_FORM) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd } = form + const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi } = form // EMBER-DANDI: the upload goes to the researcher's own account. Choosing a protocol lists their // dandisets for it, each with the workspace it runs in, so choosing one chooses both. const usesEmber = UPLOAD_BACKEND === 'ember' @@ -95,6 +98,10 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut // before that, closing would abandon the upload or the imports half way (and the user would // have to start over). Once they run in OSB's task, closing only stops watching. const [closeLocked, setCloseLocked] = useState(false) + const [doiCopied, setDoiCopied] = useState(false) + const copyDoi = (value: string) => { + navigator.clipboard?.writeText(value).then(() => setDoiCopied(true), () => setDoiCopied(false)) + } useEffect(() => { if (step !== 'uploading') setCloseLocked(false) // finished, failed, or sent back to the form }, [step]) @@ -174,7 +181,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const handleUpload = async () => { if (!file || fileProblem || !selectedProtocol) return setCloseLocked(true) - setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [] })) + setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [], doi: undefined })) + setDoiCopied(false) if (watchRef.current) watchRef.current.current = true const watch = { current: false } watchRef.current = watch @@ -216,6 +224,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut dandisetId: state.dandisetId ?? prev.dandisetId, uploadMessage: state.phase === 'failed' ? `${state.message}: ${state.error}` : state.message, outputsDir: state.outputsDir ?? prev.outputsDir, + doi: state.doi ?? prev.doi, runSteps: state.steps, ...(state.phase === 'succeeded' ? { step: 'success' } : {}), ...(state.phase === 'stillRunning' ? { step: 'stillRunning' } : {}), @@ -529,6 +538,20 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut {step === 'stillRunning' ? 'Results will be in' : 'Results are in'} {outputsDir}/ in your workspace. )} + {step === 'success' && doi && ( + + DOI + {doi.doi} + + {doi.url && ( + + )} + + )} {step !== 'uploading' && spawnedWorkspaceId !== undefined && ( - {doi.url && ( - - )} - - )} {step !== 'uploading' && spawnedWorkspaceId !== undefined && ( )} diff --git a/applications/idp-arc/frontend/src/components/DoiField.tsx b/applications/idp-arc/frontend/src/components/DoiField.tsx new file mode 100644 index 0000000..a281716 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/DoiField.tsx @@ -0,0 +1,77 @@ +import { useEffect, useRef, useState } from 'react' +import { Button, Divider, InputAdornment, TextField, Typography } from '@mui/material' +import CheckIcon from '@mui/icons-material/Check' +import ContentCopyIcon from '@mui/icons-material/ContentCopyOutlined' + +/** How long the button says "Copied" before going back to "Copy". */ +const COPIED_FOR_MS = 2000 + +/** The run's DOI in a read-only field: labelled DOI on its left, with a Copy button on its right. */ +export default function DoiField({ doi }: { doi: string }) { + const [copied, setCopied] = useState(false) + const inputRef = useRef(null) + + useEffect(() => { + if (!copied) return + const timer = setTimeout(() => setCopied(false), COPIED_FOR_MS) + return () => clearTimeout(timer) + }, [copied]) + + const copy = () => { + // Where the clipboard is refused, the DOI is selected instead, for the user to copy. + const selectIt = () => inputRef.current?.select() + if (!navigator.clipboard) return selectIt() + navigator.clipboard.writeText(doi).then(() => setCopied(true), selectIt) + } + + return ( + e.target.select()} + slotProps={{ + input: { + readOnly: true, + // Spacing: 8px before DOI, 12px after Copy (4px plus its own 8px), the 8px adornment margins + // as the only gaps beside the dividers, and the box exactly as wide as the DOI (monospace). + sx: { fontFamily: 'monospace', fontSize: 14, pl: 1, pr: 0.5, '& .MuiOutlinedInput-input': { px: 0, width: `${doi.length}ch` } }, + startAdornment: ( + + + DOI + + + + ), + endAdornment: ( + + + + + ), + }, + }} + /> + ) +} + +/** A plain text button inside the field (no border of its own); its label and icon only fade. */ +const ACTION_SX = { + whiteSpace: 'nowrap', + minWidth: 0, + px: 1, + transition: 'color 150ms ease', + '@media (prefers-reduced-motion: reduce)': { transition: 'none' }, +} as const diff --git a/applications/idp-arc/frontend/src/components/sessionStore.ts b/applications/idp-arc/frontend/src/components/sessionStore.ts new file mode 100644 index 0000000..79d1bad --- /dev/null +++ b/applications/idp-arc/frontend/src/components/sessionStore.ts @@ -0,0 +1,29 @@ +import { useSyncExternalStore } from 'react' + +type Update = T | ((previous: T) => T) + +/** + * State kept outside a component, so it outlives the component being closed or unmounted (a + * page change remounts it); useSessionStore reads and updates it like useState. + */ +export function createSessionStore(initial: T) { + let state = initial + const listeners = new Set<() => void>() + return { + get: () => state, + set(update: Update) { + state = typeof update === 'function' ? (update as (previous: T) => T)(state) : update + listeners.forEach((listener) => listener()) + }, + subscribe(listener: () => void) { + listeners.add(listener) + return () => { listeners.delete(listener) } + }, + } +} + +export type SessionStore = ReturnType> + +export function useSessionStore(store: SessionStore): [T, SessionStore['set']] { + return [useSyncExternalStore(store.subscribe, store.get), store.set] +} diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index c20a7de..2579cd0 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -3,6 +3,10 @@ * (emberObjectStore.ts) or a public bucket (publicBucketObjectStore.ts). The run doesn't know which. */ +/** Where an interrupted upload got to, in the store's own terms: reported while it uploads, and + * passed back to pick up from there. The bucket has none (one request per file). */ +export type UploadCheckpoint = Readonly> + export interface ObjectUploadInput { file: File /** The protocol's stable id (protocols.json): groups uploads by protocol. */ @@ -19,6 +23,10 @@ export interface ObjectUploadInput { /** The protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), uploaded to through OSB. */ maabcd?: string } + /** From an earlier, interrupted put of the same file: what it already did is not done again. */ + resume?: UploadCheckpoint + /** Gets the checkpoint each time a part of the upload is done. */ + onCheckpoint?: (checkpoint: UploadCheckpoint) => void } export interface StoredObject { diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index d5e2f52..40078fa 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -1,3 +1,5 @@ +import type { StoredObject, UploadCheckpoint } from './ports/IObjectStore' + /** * Core domain types — shared by ports, use-cases, and the UI layer. * @@ -65,11 +67,24 @@ export type RunPhase = | 'succeeded' | 'failed' +/** The run's steps, in order: their ids in the checklist (runProtocol's STEPS). */ +export const RUN_STEP = { + upload: 'upload', + workspace: 'workspace', + repo: 'repo', + data: 'data', + imports: 'imports', + run: 'run', + doi: 'doi', +} as const + +export type RunStepId = (typeof RUN_STEP)[keyof typeof RUN_STEP] + export type StepState = 'pending' | 'running' | 'succeeded' | 'skipped' | 'failed' /** One line of the run's checklist in the UI. */ export interface RunStep { - id: string + id: RunStepId label: string state: StepState detail?: string @@ -88,4 +103,32 @@ export interface RunState { /** The DOI of the version published at the end of the run. */ doi?: { doi: string; url?: string } error?: string + /** What the run has done so far; given back on a retry, it carries on from there. */ + checkpoint?: RunCheckpoint +} + +/** + * What a run has done so far (runProtocol), kept by the dialog for a retry. It holds only for the + * same protocol, file, dandiset choice and sharing choice (canResume); anything else starts over. + */ +export interface RunCheckpoint { + protocolId: string + /** The file it was for: name, size and last-modified time. */ + fileKey: string | null + /** The dandiset picked when it started (undefined: a new one). */ + dandisetChoice?: string + shareWithMaabcd: boolean + /** The upload, part way: the store's own checkpoint. */ + upload?: UploadCheckpoint + /** The upload, finished. */ + stored?: StoredObject + workspaceId?: number + /** The workspace is recorded with the upload (in the dandiset's metadata). */ + workspaceRecorded?: boolean + /** When this run's folder was named (workspaceLayout); reused until the notebooks are submitted. */ + runFolderAt?: string + repoImported?: boolean + dataImported?: boolean + /** The notebooks ran and passed, in this folder: a retry goes straight to the DOI. */ + ranIn?: string } diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index d60e9a0..a89b778 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -22,10 +22,23 @@ export { EMBER_SIGN_IN } * The browser sends the bytes both times. The second transfer is usually empty: EMBER stores each * content once, and answers with the existing blob instead of parts. * + * Each finished part is reported as a checkpoint (EmberUploadCheckpoint): given back on a retry, + * the dandiset is not created again and a copy already made is not made again. + * * No wait for "valid" before returning: the blob is checked against the etag when the upload is * validated (synchronously, before the asset exists), so its download link works at once. * Asset *metadata* validation is a separate, asynchronous check that a plain file may never pass. */ +/** What a put has done so far; see IObjectStore's UploadCheckpoint. */ +export interface EmberUploadCheckpoint { + /** The researcher's dandiset, once picked or created. */ + userDandisetId?: string + /** Their own copy, once registered. */ + own?: { assetId: string; assetPath: string } + /** The MAABCD copy is registered. */ + maabcdDone?: boolean +} + export function createEmberObjectStore( osbAuth: Pick, emberAuth: Pick, @@ -42,30 +55,43 @@ export function createEmberObjectStore( const token = emberAuth.getToken() if (!token) throw new UserFacingError(EMBER_SIGN_IN, 'No EMBER-DANDI token (not signed in, or it expired)') const maabcdDandisetId = input.dandisets?.maabcd || undefined + const saved: EmberUploadCheckpoint = { ...(input.resume as EmberUploadCheckpoint | undefined) } + const save = (patch: EmberUploadCheckpoint) => { + Object.assign(saved, patch) + input.onCheckpoint?.({ ...saved }) + } - // Bytes counted across both transfers, so the progress bar runs once from 0 to 100%. + // Bytes counted across both transfers, so the progress bar runs once from 0 to 100%; a copy + // made by an earlier attempt counts as sent. const transfers = maabcdDandisetId ? 2 : 1 const total = file.size * transfers - let done = 0 + let done = (saved.own ? file.size : 0) + (maabcdDandisetId && saved.maabcdDone ? file.size : 0) const progress = (sentInTransfer: number) => onProgress?.(Math.min(done + sentInTransfer, total), total) const skipTransfer = () => { done += file.size; progress(0) } + progress(0) - const { etag, parts: plan } = await computeDandiEtag(file) + const needsMaabcd = !!maabcdDandisetId && !saved.maabcdDone + const { etag, parts: plan } = !saved.own || needsMaabcd ? await computeDandiEtag(file) : { etag: '', parts: [] } // 1. The researcher's own copy. const protocol = input.dandisets?.protocol ?? { id: input.protocolId, name: input.protocolId } - const userDandisetId = input.dandisets?.user + const userDandisetId = saved.userDandisetId || input.dandisets?.user || await dandisets.createForProtocol(input.dandisets?.newName || `IDP upload: ${protocol.name}`, protocol) - const path = `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` - const init = await direct.initUpload(token, userDandisetId, file.size, etag) - const uploaded = await putParts(init.parts, plan, file, progress) - if (!init.parts.length) skipTransfer(); else done += file.size - const asset = await direct.finalizeUpload(token, { - uploadId: init.uploadId, dandisetId: userDandisetId, path, parts: uploaded, blobId: init.blobId, - }) + if (saved.userDandisetId !== userDandisetId) save({ userDandisetId }) + let asset = saved.own + if (!asset) { + const path = `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` + const init = await direct.initUpload(token, userDandisetId, file.size, etag) + const uploaded = await putParts(init.parts, plan, file, progress) + if (!init.parts.length) skipTransfer(); else done += file.size + asset = await direct.finalizeUpload(token, { + uploadId: init.uploadId, dandisetId: userDandisetId, path, parts: uploaded, blobId: init.blobId, + }) + save({ own: { assetId: asset.assetId, assetPath: asset.assetPath } }) + } // 2. The MAABCD copy, through OSB. - if (maabcdDandisetId) { + if (needsMaabcd) { const osbToken = await osbAuth.getToken() const brokered = await osb.getUploadUrls(osbToken, { dandisetId: maabcdDandisetId, filename: file.name, size: file.size, dandiEtag: etag, @@ -79,6 +105,7 @@ export function createEmberObjectStore( parts: brokered.blobId ? undefined : brokeredParts, blobId: brokered.blobId, }) + save({ maabcdDone: true }) } progress(0) diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts index c10a307..2a6e0a2 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts @@ -1,13 +1,13 @@ -import type { RunPhase, RunState, RunStep, StepState } from '../types' +import type { RunCheckpoint, RunPhase, RunState, RunStep, RunStepId, StepState } from '../types' import { UserFacingError, userMessage } from '../userMessages' export type OnRunState = (state: RunState) => void /** A failure that belongs to one step, so only that row is marked failed. */ export class StepError extends Error { - readonly step: string + readonly step: RunStepId readonly original: unknown - constructor(step: string, cause: unknown) { + constructor(step: RunStepId, cause: unknown) { super(cause instanceof Error ? cause.message : String(cause)) this.step = step this.original = cause @@ -28,15 +28,17 @@ export class RunProgress { dandisetId?: string outputsDir?: string doi?: { doi: string; url?: string } + /** Reported with every state, so the last one the dialog sees is up to date. */ + checkpoint?: RunCheckpoint - constructor(report: OnRunState, steps: { id: string; label: string }[], workspaceId?: number) { + constructor(report: OnRunState, steps: { id: RunStepId; label: string }[], workspaceId?: number) { this.report = report this.steps = steps.map((s) => ({ ...s, state: 'pending' })) this.workspaceId = workspaceId } /** A step starts; `phase` is what the whole run is doing now. */ - start(id: string, phase: RunPhase, message: string, detail?: string) { + start(id: RunStepId, phase: RunPhase, message: string, detail?: string) { if (this.ended) return this.phase = phase this.set(id, 'running', detail) @@ -44,19 +46,19 @@ export class RunProgress { } /** A running step reports progress (upload bytes, run state). */ - update(id: string, detail: string, message: string) { + update(id: RunStepId, detail: string, message: string) { if (this.ended) return this.set(id, 'running', detail) this.emit(message) } - done(id: string, detail?: string, message?: string) { + done(id: RunStepId, detail?: string, message?: string) { if (this.ended) return this.set(id, 'succeeded', detail) if (message) this.emit(message) } - skip(id: string, detail?: string) { + skip(id: RunStepId, detail?: string) { this.set(id, 'skipped', detail) } @@ -69,7 +71,7 @@ export class RunProgress { } /** Still running past the watch limit: stops following it; the run carries on in the workspace. */ - stopWatching(id: string, message: string) { + stopWatching(id: RunStepId, message: string) { if (this.ended) return this.ended = true this.phase = 'stillRunning' @@ -94,11 +96,14 @@ export class RunProgress { } emit(message: string, error?: string) { - const { phase, steps, workspaceId, dandisetId, outputsDir } = this - this.report({ phase, message, steps, workspaceId, outputsDir, ...(dandisetId ? { dandisetId } : {}), ...(this.doi ? { doi: this.doi } : {}), ...(error ? { error } : {}) }) + const { phase, steps, workspaceId, dandisetId, outputsDir, checkpoint } = this + this.report({ + phase, message, steps, workspaceId, outputsDir, + ...(dandisetId ? { dandisetId } : {}), ...(this.doi ? { doi: this.doi } : {}), ...(error ? { error } : {}), ...(checkpoint ? { checkpoint: { ...checkpoint } } : {}), + }) } - private set(id: string, state: StepState, detail?: string) { + private set(id: RunStepId, state: StepState, detail?: string) { // A running step keeps its last detail unless given a new one. this.steps = this.steps.map((s) => s.id === id ? { ...s, state, detail: detail ?? (state === 'running' ? s.detail : undefined) } : s) @@ -107,7 +112,7 @@ export class RunProgress { /** Runs one step, so a failure is attributed to that step's row (not to another one running in * parallel, like the upload). */ -export async function inStep(step: string, run: () => Promise): Promise { +export async function inStep(step: RunStepId, run: () => Promise): Promise { try { return await run() } catch (err) { diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 2632787..11443b9 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -1,5 +1,6 @@ import type { IAuthClient } from '../ports/IAuthClient' import type { IObjectStore, StoredObject } from '../ports/IObjectStore' +import { RUN_STEP, type RunCheckpoint, type RunStepId } from '../types' import type { IWorkspaceApi, WorkspaceResourceState } from '../ports/IWorkspaceApi' import { formatBytes } from '../formatBytes' import { inputFileProblem } from '../inputFormats' @@ -46,6 +47,30 @@ export interface RunProtocolInput { dandisetId?: string /** Also upload into the protocol's MAABCD dandiset, when it has one (the default). */ shareWithMaabcd?: boolean + /** From an earlier attempt that stopped: the run carries on from there when canResume allows. */ + resume?: RunCheckpoint +} + +/** Names a file well enough to tell it is the same one again: name, size, last modified. */ +export function fileKey(file?: File | null): string | null { + return file ? `${file.name}|${file.size}|${file.lastModified}` : null +} + +/** + * Whether a checkpoint applies to this attempt: same protocol, same file, same sharing choice, and + * the same dandiset and workspace (or the ones that attempt itself created). Otherwise the run + * starts over, rather than carry on with another file's upload or another dandiset. + */ +export function canResume(checkpoint: RunCheckpoint | undefined, input: RunProtocolInput): checkpoint is RunCheckpoint { + if (!checkpoint) return false + const sameDandiset = input.dandisetId === checkpoint.dandisetChoice + || (!!input.dandisetId && input.dandisetId === checkpoint.stored?.dandisetId) + const sameWorkspace = input.workspaceId === undefined || checkpoint.workspaceId === undefined + || input.workspaceId === checkpoint.workspaceId + return checkpoint.protocolId === input.protocol.id + && checkpoint.fileKey === fileKey(input.file) + && checkpoint.shareWithMaabcd === (input.shareWithMaabcd !== false) + && sameDandiset && sameWorkspace } /** @@ -61,14 +86,17 @@ const REPOSITORY_SETUP = { install: ['scripts/install.py', 'scripts/setup.py', 'scripts/pyproject.toml'], } +/** Checkpoint fields that make the next attempt import into a new run folder. */ +const NEW_RUN_FOLDER: Partial = { runFolderAt: undefined, repoImported: false, dataImported: false } + const STEPS = [ - { id: 'upload', label: 'Upload your file' }, - { id: 'workspace', label: 'Get the workspace ready' }, - { id: 'repo', label: 'Import the analysis code' }, - { id: 'data', label: 'Import your data' }, - { id: 'imports', label: 'Wait for the imports to finish' }, - { id: 'run', label: 'Run the notebooks' }, - { id: 'doi', label: 'Publish your data with a DOI' }, + { id: RUN_STEP.upload, label: 'Upload your file' }, + { id: RUN_STEP.workspace, label: 'Get the workspace ready' }, + { id: RUN_STEP.repo, label: 'Import the analysis code' }, + { id: RUN_STEP.data, label: 'Import your data' }, + { id: RUN_STEP.imports, label: 'Wait for the imports to finish' }, + { id: RUN_STEP.run, label: 'Run the notebooks' }, + { id: RUN_STEP.doi, label: 'Publish your data with a DOI' }, ] /** @@ -98,6 +126,12 @@ const STEPS = [ * * No lab server is started: the imports and the run are OSB's own Argo workflows, and their * affinity to the workspace is met by their own pods (verified 5 Oct on a never-opened workspace). + * + * Every state reports a checkpoint of what is done. Given back on a retry (`resume`), the run + * skips those steps: the upload (or the copies of it already made), the workspace, and the imports + * into the same run folder. If waiting for the imports fails, the folder's contents are in doubt, + * so the next attempt imports into a new one; and once the notebooks are submitted, a retry is a + * new run of them, in a new folder. */ export function createRunProtocolUseCase( auth: Pick, @@ -110,59 +144,110 @@ export function createRunProtocolUseCase( const { protocol, file } = input const progress = new RunProgress(report, STEPS, input.workspaceId) const stopped = () => !!abortRef?.current + const checkpoint: RunCheckpoint = canResume(input.resume, input) + ? { ...input.resume } + : { protocolId: protocol.id, fileKey: fileKey(file), dandisetChoice: input.dandisetId, shareWithMaabcd: input.shareWithMaabcd !== false } + const save = (patch: Partial) => { + Object.assign(checkpoint, patch) + progress.checkpoint = { ...checkpoint } + } + save({}) + if (checkpoint.stored?.dandisetId) progress.dandisetId = checkpoint.stored.dandisetId + if (checkpoint.workspaceId !== undefined) progress.workspaceId = checkpoint.workspaceId + const doneEarlier = (id: RunStepId) => progress.done(id, 'Done earlier') try { // Before anything moves: the protocol and the file. const { repo, userId } = checkBeforeStarting(input) - // This run's folder in the workspace, and where the repository lands in it (the zip - // unpacks to -/). - const layout = workspaceLayout(protocol.id, new Date()) - const repoDir = `${layout.run}/${repo.folder}` + // This run's folder in the workspace (the repository's zip unpacks into it as -/). + if (!checkpoint.runFolderAt) save({ runFolderAt: new Date().toISOString() }) + const layout = workspaceLayout(protocol.id, new Date(checkpoint.runFolderAt!)) if (!file) { - progress.skip('upload') - progress.skip('data') - progress.skip('doi') + progress.skip(RUN_STEP.upload) + progress.skip(RUN_STEP.data) + progress.skip(RUN_STEP.doi) } progress.emit('Starting…') // 1. Upload the file straight to the bucket. Nothing else starts until it has landed. - const stored = file ? await inStep('upload', () => uploadFile(file, userId)) : null + let stored: StoredObject | null = null + if (file && checkpoint.stored) { + stored = checkpoint.stored + doneEarlier(RUN_STEP.upload) + } else if (file) { + stored = await inStep(RUN_STEP.upload, () => uploadFile(file, userId)) + save({ stored }) + } if (stopped()) return // 2. Get the workspace: the selected one, or a new one, recorded in the dandiset's metadata so // the next upload for this protocol finds both. - const workspaceId = await inStep('workspace', async () => { + const workspaceId = await inStep(RUN_STEP.workspace, async () => { const id = await prepareWorkspace() - await stored?.recordWorkspace?.(id) + save({ workspaceId: id }) + if (!checkpoint.workspaceRecorded) { + await stored?.recordWorkspace?.(id) + save({ workspaceRecorded: true }) + } return id }) if (stopped()) return - // 3. Import the analysis code (the protocol's repository). - await inStep('repo', () => importRepo(workspaceId, repo, layout.run)) - - // 4. Import the uploaded data. - if (stored && file) await inStep('data', () => importData(workspaceId, file, stored, layout.inputs)) - - // 5. Wait for the imports, and find the notebooks to run. - if (stopped()) return - const notebooks = await inStep('imports', () => waitForImports(workspaceId, layout.run, repoDir)) - if (!notebooks) return - - // 6. Run the notebooks. - const ran = await inStep('run', () => runNotebooks(workspaceId, repoDir, notebooks, layout, !!stored)) - if (!ran) return + // 3–6 already done: the notebooks ran and passed, so only the DOI is left. + if (checkpoint.ranIn) { + for (const id of [RUN_STEP.repo, RUN_STEP.data, RUN_STEP.imports, RUN_STEP.run]) { + if (id !== RUN_STEP.data || file) doneEarlier(id) + } + progress.outputsDir = checkpoint.ranIn + } else { + const ran = await importAndRun(workspaceId, stored, repo, layout) + if (!ran) return + save({ ranIn: layout.run }) + } // 7. Publish the dandiset, for a DOI. if (stored?.publish) { const publish = stored.publish - if (!(await inStep('doi', () => publishForDoi(publish)))) return - } else progress.skip('doi') + if (!(await inStep(RUN_STEP.doi, () => publishForDoi(publish)))) return + } else progress.skip(RUN_STEP.doi) progress.finish('The analysis has finished') } catch (err) { progress.fail(err) } + /** Steps 3–6, in this run's folder. True once the notebooks have all run and passed. */ + async function importAndRun(workspaceId: number, stored: StoredObject | null, repo: { folder: string }, + layout: ReturnType): Promise { + const repoDir = `${layout.run}/${repo.folder}` + // 3. Import the analysis code (the protocol's repository). + if (checkpoint.repoImported) doneEarlier(RUN_STEP.repo) + else { + await inStep(RUN_STEP.repo, () => importRepo(workspaceId, repo, layout.run)) + save({ repoImported: true }) + } + + // 4. Import the uploaded data. + if (stored && file && checkpoint.dataImported) doneEarlier(RUN_STEP.data) + else if (stored && file) { + const upload = stored + await inStep(RUN_STEP.data, () => importData(workspaceId, file, upload, layout.inputs)) + save({ dataImported: true }) + } + + // 5. Wait for the imports, and find the notebooks to run. If this fails, the folder may hold + // a failed or half-finished import: the next attempt starts a new folder. + if (stopped()) return false + const notebooks = await inStep(RUN_STEP.imports, () => waitForImports(workspaceId, layout.run, repoDir)) + .catch((err: unknown) => { + save(NEW_RUN_FOLDER) + throw err + }) + if (!notebooks) return false + + // 6. Run the notebooks. + return inStep(RUN_STEP.run, () => runNotebooks(workspaceId, repoDir, notebooks, layout, !!stored)) + } + // ── The steps ──────────────────────────────────────────────────────────────────────── /** Before anything moves: a file the protocol can't read would only fail minutes later. */ @@ -182,10 +267,12 @@ export function createRunProtocolUseCase( /** Step 1. */ async function uploadFile(file: File, userId: string): Promise { const message = `Uploading ${file.name}…` - progress.start('upload', 'uploading', message, `0 B of ${formatBytes(file.size)}`) + progress.start(RUN_STEP.upload, 'uploading', message, `0 B of ${formatBytes(file.size)}`) let lastReport = 0 const stored = await objectStore.put({ file, protocolId: protocol.id, userSub: userId, + resume: checkpoint.upload, + onCheckpoint: (upload) => save({ upload }), dandisets: { user: input.dandisetId, newName: `${protocol.name} (IDP)`, @@ -196,43 +283,44 @@ export function createRunProtocolUseCase( if (Date.now() - lastReport < RUN_SETTINGS.uploadProgressMs && sent < total) return lastReport = Date.now() const pct = total ? Math.round((sent / total) * 100) : 100 - progress.update('upload', `${formatBytes(sent)} of ${formatBytes(total)} (${pct}%)`, message) + progress.update(RUN_STEP.upload, `${formatBytes(sent)} of ${formatBytes(total)} (${pct}%)`, message) }) // Kept by the dialog, so a retry uploads into the same dandiset rather than creating another. if (stored.dandisetId) progress.dandisetId = stored.dandisetId - progress.done('upload', undefined, 'Upload finished') + progress.done(RUN_STEP.upload, undefined, 'Upload finished') return stored } /** Step 2. */ async function prepareWorkspace(): Promise { - progress.start('workspace', 'workspace', 'Getting the workspace ready…') - if (input.workspaceId !== undefined) { - progress.done('workspace', undefined, 'Workspace ready') - return input.workspaceId + progress.start(RUN_STEP.workspace, 'workspace', 'Getting the workspace ready…') + const existing = checkpoint.workspaceId ?? input.workspaceId + if (existing !== undefined) { + progress.done(RUN_STEP.workspace, undefined, 'Workspace ready') + return existing } const id = await workspaceApi.createWorkspace(await token(), input.workspaceName, [`maabcd:${protocol.id}`]) progress.workspaceId = id - progress.done('workspace', undefined, 'Workspace ready') + progress.done(RUN_STEP.workspace, undefined, 'Workspace ready') return id } /** Step 3. */ async function importRepo(workspaceId: number, repo: { folder: string }, folder: string) { - progress.start('repo', 'importing', 'Importing the analysis code…') + progress.start(RUN_STEP.repo, 'importing', 'Importing the analysis code…') await workspaceApi.importResource(await token(), { workspaceId, name: repo.folder, url: protocol.repoZipUrl!, folder, resourceType: 'g', }) - progress.done('repo') + progress.done(RUN_STEP.repo) } /** Step 4. */ async function importData(workspaceId: number, file: File, stored: StoredObject, folder: string) { - progress.start('data', 'importing', 'Importing your data…') + progress.start(RUN_STEP.data, 'importing', 'Importing your data…') await workspaceApi.importResource(await token(), { workspaceId, name: file.name, url: stored.url, folder, resourceType: 'e', }) - progress.done('data') + progress.done(RUN_STEP.data) } /** @@ -240,7 +328,7 @@ export function createRunProtocolUseCase( * names (as the contract says: zero-padded prefixes); null if the dialog was closed meanwhile. */ async function waitForImports(workspaceId: number, runDir: string, repoDir: string): Promise { - progress.start('imports', 'importing', 'Waiting for the imports to finish…') + progress.start(RUN_STEP.imports, 'importing', 'Waiting for the imports to finish…') let resources: WorkspaceResourceState[] = [] // Only this run's imports count: a reused workspace can hold older resources that failed or // never finished, and those must not fail or stall every later run. @@ -265,7 +353,7 @@ export function createRunProtocolUseCase( .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) if (!notebooks.length) throw new UserFacingError('The analysis code has no notebooks to run. Please let the protocol\'s maintainers know.', `No notebooks in ${repoDir}/${folderInRepo} after the import`) - progress.done('imports') + progress.done(RUN_STEP.imports) return notebooks } @@ -273,7 +361,7 @@ export function createRunProtocolUseCase( /** Step 6. True once the notebooks have all run; false if it stopped watching first. */ async function runNotebooks(workspaceId: number, repoDir: string, notebooks: string[], layout: ReturnType, hasData: boolean): Promise { - progress.start('run', 'running', 'Starting the notebooks…', 'Submitting') + progress.start(RUN_STEP.run, 'running', 'Starting the notebooks…', 'Submitting') await workspaceApi.startRun(await token(), workspaceId, { // Removed once copied: every run gets the repository as it is now. repo: { dir: repoDir, discard: true }, @@ -290,6 +378,8 @@ export function createRunProtocolUseCase( results: { notebooks: layout.notebooks, log: layout.log }, ...(protocol.image ? { image: protocol.image } : {}), }) + // Submitted: the code is consumed (discard), and this folder now holds this run's results. + save(NEW_RUN_FOLDER) progress.outputsDir = layout.run // Followed through `GET /workspace/{id}`, as the imports are: while a workflow for the // workspace runs, OSB lists a placeholder resource (id -1). Seen, then gone: the run is over. @@ -297,12 +387,12 @@ export function createRunProtocolUseCase( const submitted = Date.now() const ended = await pollUntil(async () => { const running = (await workspaceApi.getWorkspaceResources(await token(), workspaceId)).some((r) => r.id === -1) - if (running && !seen) progress.update('run', 'Running the notebooks', 'Running the notebooks…') + if (running && !seen) progress.update(RUN_STEP.run, 'Running the notebooks', 'Running the notebooks…') seen ||= running // Never seen: a run that ends within seconds can finish between two polls. return seen ? !running : Date.now() - submitted > RUN_SETTINGS.runStartTimeoutMs }, { everyMs: RUN_SETTINGS.runPollMs, timeoutMs: RUN_SETTINGS.runTimeoutMs, stopped }) - if (ended === 'timeout') progress.stopWatching('run', 'Still running in the workspace; open it to follow the results') + if (ended === 'timeout') progress.stopWatching(RUN_STEP.run, 'Still running in the workspace; open it to follow the results') if (ended !== 'done') return false // Whether it succeeded. The run task leaves the executed notebooks in notebooks/ if every one @@ -322,17 +412,17 @@ export function createRunProtocolUseCase( if (failedAt) throw new Error(`${failedAt} failed; see ${layout.log}`) // Neither: it stopped before any notebook ran (e.g. installing the requirements). if (listed === 'timeout') throw new Error(`The run ended with no executed notebooks in ${layout.notebooks}/ or ${failedDir}; see ${layout.log}`) - progress.done('run', `Results in ${layout.run}/`) + progress.done(RUN_STEP.run, `Results in ${layout.run}/`) return true } /** Step 7. The published version's DOI; null if the dialog was closed meanwhile. */ async function publishForDoi(publish: NonNullable) { - progress.start('doi', 'publishing', 'Publishing your data…', 'Waiting for EMBER-DANDI to check it') + progress.start(RUN_STEP.doi, 'publishing', 'Publishing your data…', 'Waiting for EMBER-DANDI to check it') const published = await publish(stopped) if (!published) return null progress.doi = published - progress.done('doi', published.doi) + progress.done(RUN_STEP.doi) return published } } diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 0719f5e..467bf47 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -1,3 +1,5 @@ +import { RUN_STEP, type RunStepId } from './types' + /** * What the user reads when a run fails: one plain sentence per step. Technical details (HTTP * errors, OSB's messages) go to the browser console; the run's own log is in its results folder. @@ -12,14 +14,14 @@ export class UserFacingError extends Error { } } -const STEP_FAILED: Record = { - upload: 'Your file could not be uploaded. Check your connection and try again.', - workspace: 'The workspace could not be prepared. Please try again.', - repo: 'The analysis code could not be added to the workspace. Please try again.', - data: 'Your file could not be added to the workspace. Please try again.', - imports: 'The files could not be copied into the workspace. Please try again.', - run: 'The analysis did not finish. Open the workspace to see what happened.', - doi: 'Your data could not be published with a DOI. Please try again.', +const STEP_FAILED: Record = { + [RUN_STEP.upload]: 'Your file could not be uploaded. Check your connection and try again.', + [RUN_STEP.workspace]: 'The workspace could not be prepared. Please try again.', + [RUN_STEP.repo]: 'The analysis code could not be added to the workspace. Please try again.', + [RUN_STEP.data]: 'Your file could not be added to the workspace. Please try again.', + [RUN_STEP.imports]: 'The files could not be copied into the workspace. Please try again.', + [RUN_STEP.run]: 'The analysis did not finish. Open the workspace to see what happened.', + [RUN_STEP.doi]: 'Your data could not be published with a DOI. Please try again.', } /** Says the EMBER-DANDI session is missing or over. Deliberately not SIGN_IN_AGAIN's wording, @@ -30,7 +32,7 @@ export const EMBER_SIGN_IN = 'Please sign in with EMBER-DANDI and try again.' export const SIGN_IN_AGAIN = 'sign in again' /** The user's text for an error thrown during `step`. */ -export function userMessage(err: unknown, step?: string): string { +export function userMessage(err: unknown, step?: RunStepId): string { if (err instanceof UserFacingError) return err.message // The auth client's "Please sign in again." can come from any step that asks for a token: kept, // so the dialog can send the user to sign in instead of suggesting a retry that fails the same way. diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index 153d8f2..3317ba6 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -9,8 +9,10 @@ import { UserFacingError } from '../../src/core/userMessages' const ORIGIN = 'https://api-dandi.example.org' const file = () => new File(['animal data'], 'animal 01.xlsx') -function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: boolean } = {}) { +function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: boolean; failOsbOnce?: boolean; failDirectOnce?: boolean } = {}) { const calls: string[] = [] + let osbFails = opts.failOsbOnce ? 1 : 0 + let directFails = opts.failDirectOnce ? 1 : 0 const direct: IDandiDirectApi = { async listOwnDandisets() { return [] }, async createDandiset() { throw new Error('created through the protocol use case') }, @@ -21,6 +23,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b async getLatestPublished() { return null }, async initUpload(token, dandisetId) { calls.push(`direct-init:${token}:${dandisetId}`) + if (directFails > 0) { directFails -= 1; throw new Error('EMBER initialize failed') } return opts.dedupDirect ? { parts: [], blobId: 'blob-1' } : { uploadId: 'up-1', parts: [{ partNumber: 1, size: 11, url: 'https://s3/direct' }] } }, async putPart(url) { calls.push(`put:${url}`); return `etag-${url.split('/').pop()}` }, @@ -32,6 +35,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b const osb: IEmberUploadApi = { async getUploadUrls(token, input) { calls.push(`osb-urls:${token}:${input.dandisetId}:${input.filename}:${input.dandiEtag.endsWith('-1')}`) + if (osbFails > 0) { osbFails -= 1; throw new Error('OSB get_upload_urls failed (HTTP 503)') } if (opts.dedupOsb) return { dandisetId: input.dandisetId, path: 'u/x/f', parts: [], blobId: 'blob-1' } const parts = opts.shortParts ? [] : [{ partNumber: 1, url: 'https://s3/osb' }] return { dandisetId: input.dandisetId, path: 'u/x/f', uploadId: 'up-2', parts: opts.shortParts ? [...parts, { partNumber: 1, url: 'https://s3/a' }, { partNumber: 2, url: 'https://s3/b' }] : parts } @@ -119,6 +123,57 @@ test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sig assert.deepEqual(calls, []) }) +// ── Retry: carrying on from the checkpoint ─────────────────────────────────────────────────── + +test('a retry after the MAABCD copy failed makes only that copy', async () => { + const { calls, store } = fakes({ failOsbOnce: true }) + const checkpoints: unknown[] = [] + const input = { + file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, + onCheckpoint: (c: unknown) => checkpoints.push(c), + } + await assert.rejects(store().put(input), /HTTP 503/) + const resume = checkpoints.at(-1) as Record + assert.deepEqual(resume, { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: (resume.own as { assetPath: string }).assetPath } }) + calls.length = 0 + + const progress: number[] = [] + const stored = await store().put({ ...input, resume }, (sent, total) => progress.push(sent / total)) + + assert.deepEqual(calls, ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) + // Still the researcher's own copy that the run imports. + assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) + assert.equal(progress[0], 0.5, 'the copy made earlier counts as sent') + assert.equal(progress.at(-1), 1) + assert.deepEqual(checkpoints.at(-1), { ...resume, maabcdDone: true }) +}) + +test('a retry after the own copy failed reuses the dandiset it created', async () => { + const { calls, store } = fakes({ failDirectOnce: true }) + const checkpoints: unknown[] = [] + const input = { + file: file(), protocolId: 'asst', userSub: 'u', + dandisets: { newName: 'ASST (IDP)', protocol: { id: 'asst', name: 'ASST' } }, + onCheckpoint: (c: unknown) => checkpoints.push(c), + } + await assert.rejects(store().put(input), /initialize failed/) + assert.deepEqual(checkpoints.at(-1), { userDandisetId: '000777' }) + + const stored = await store().put({ ...input, resume: checkpoints.at(-1) as Record }) + + assert.equal(calls.filter((c) => c.startsWith('create:')).length, 1, 'the dandiset is created once') + assert.equal(stored.dandisetId, '000777') +}) + +test('a retry with everything done makes no copy at all', async () => { + const { calls, store } = fakes() + const resume = { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: 'p/x/f' }, maabcdDone: true } + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, resume }) + + assert.deepEqual(calls, []) + assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) +}) + test('the stored upload publishes the dandiset it went into, for its DOI', async () => { const { calls, store } = fakes() const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123' } }) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index da9dae2..d916ce0 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -1,7 +1,7 @@ // The run (core/use-cases/runProtocol.ts) against in-memory ports. Run: yarn test:unit import { test, beforeEach } from 'node:test' import assert from 'node:assert/strict' -import { createRunProtocolUseCase } from '../../src/core/use-cases/runProtocol' +import { canResume, createRunProtocolUseCase } from '../../src/core/use-cases/runProtocol' import { RUN_SETTINGS } from '../../src/core/runSettings' import type { IWorkspaceApi, ImportResourceInput, StartRunInput, WorkspaceResourceState } from '../../src/core/ports/IWorkspaceApi' import type { IObjectStore } from '../../src/core/ports/IObjectStore' @@ -347,6 +347,108 @@ test('with "Share with MAABCD" unticked, nothing goes to the protocol\'s MAABCD assert.equal(seen.dandisets?.maabcd, undefined) }) +// ── Retry: carrying on from the checkpoint ─────────────────────────────────────────────────── + +/** Makes `method` of the fake workspace API throw the first `times` times it is called. */ +function failFirst(f: ReturnType, method: K, times = 1, when: (...args: Parameters) => boolean = () => true) { + const original = f.api[method] as (...args: unknown[]) => Promise + let left = times + f.api[method] = (async (...args: Parameters) => { + if (left > 0 && when(...args)) { left -= 1; throw new Error(`${String(method)} failed`) } + return original(...args) + }) as IWorkspaceApi[K] +} +/** The researcher's file: the same File object on every attempt, as the dialog keeps it. */ +const data = new File(['x'], 'animal_01.xlsx', { lastModified: 1_700_000_000_000 }) +const count = (calls: string[], name: string) => calls.filter((c) => c === name || c.startsWith(`${name}:`)).length + +test('a retry after the data import failed imports only the data, into the same folder', async () => { + const f = fakes() + failFirst(f, 'importResource', 1, (_t, input) => input.resourceType === 'e') + const first = (await run(f, { file: data })).at(-1)! + assert.equal(first.phase, 'failed') + assert.equal(first.steps.find((s) => s.id === 'data')?.state, 'failed') + + const last = (await run(f, { file: data, workspaceId: first.workspaceId, resume: first.checkpoint })).at(-1)! + + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(count(f.calls, 'upload'), 1, 'uploaded once') + assert.equal(count(f.calls, 'create'), 1, 'one workspace') + assert.equal(count(f.calls, 'import:g'), 1, 'the code imported once') + // (the failed attempt never reached the fake, so only the retry's import is recorded) + assert.equal(count(f.calls, 'import:e'), 1, 'the data imported, on the retry') + const [repo, dataImport] = f.imports + assert.equal(dataImport.folder, `${repo.folder}/inputs`, 'into the same run folder') + assert.deepEqual(last.steps.filter((s) => s.detail === 'Done earlier').map((s) => s.id), ['upload', 'repo']) +}) + +test('when waiting for the imports fails, the retry imports into a new run folder', async () => { + const f = fakes() + failFirst(f, 'getWorkspaceResources') + const first = (await run(f, { file: data })).at(-1)! + assert.equal(first.steps.find((s) => s.id === 'imports')?.state, 'failed') + assert.equal(first.checkpoint?.runFolderAt, undefined) + + const last = (await run(f, { file: data, workspaceId: first.workspaceId, resume: first.checkpoint })).at(-1)! + + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(count(f.calls, 'upload'), 1) + assert.equal(count(f.calls, 'create'), 1) + assert.equal(count(f.calls, 'import:g'), 2, 'the code imported again') + assert.equal(count(f.calls, 'import:e'), 2, 'the data imported again') +}) + +test('once the notebooks were submitted, a retry runs them again without uploading again', async () => { + const f = fakes({ runFails: 'notebook' }) + const first = (await run(f, { file: data })).at(-1)! + assert.equal(first.steps.find((s) => s.id === 'run')?.state, 'failed') + + await run(f, { file: data, workspaceId: first.workspaceId, resume: first.checkpoint }) + + assert.equal(count(f.calls, 'upload'), 1) + assert.equal(count(f.calls, 'create'), 1) + assert.equal(count(f.calls, 'import:g'), 2, 'the code again (the first run consumed it)') + assert.equal(count(f.calls, 'run'), 2) +}) + +test('a failed upload is retried, and a later failure keeps the upload', async () => { + const f = fakes() + const put = f.store.put + let uploads = 0 + f.store.put = async (input, onProgress) => { + uploads += 1 + if (uploads === 1) throw new Error('network') + return put(input, onProgress) + } + const first = (await run(f, { file: data })).at(-1)! + assert.equal(first.steps.find((s) => s.id === 'upload')?.state, 'failed') + assert.equal(first.checkpoint?.stored, undefined) + + const last = (await run(f, { file: data, resume: first.checkpoint })).at(-1)! + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(uploads, 2) +}) + +test('another file, protocol or sharing choice starts over instead of carrying on', async () => { + const f = fakes() + failFirst(f, 'importResource', 1, (_t, input) => input.resourceType === 'e') + const first = (await run(f, { file: data })).at(-1)! + const resume = first.checkpoint! + + const changed = new File(['x'], 'animal_01.xlsx', { lastModified: data.lastModified + 1 }) + assert.equal(canResume(resume, { protocol: FOUR_CHOICE, file: changed, workspaceName: 'x', workspaceId: first.workspaceId }), false, + 'same name and size, but changed since') + const input = { protocol: FOUR_CHOICE, file: data, workspaceName: 'x', workspaceId: first.workspaceId } + assert.equal(canResume(resume, input), true) + assert.equal(canResume(resume, { ...input, protocol: { ...FOUR_CHOICE, id: 'asst' } }), false) + assert.equal(canResume(resume, { ...input, shareWithMaabcd: false }), false) + assert.equal(canResume(resume, { ...input, dandisetId: '000999' }), false) + assert.equal(canResume(resume, { ...input, workspaceId: 7 }), false) + + await run(f, { file: new File(['y'], 'animal_02.xlsx'), workspaceId: first.workspaceId, resume }) + assert.equal(count(f.calls, 'upload'), 2, 'the other file is uploaded') +}) + // ── The DOI ────────────────────────────────────────────────────────────────────────────────── test('an EMBER-DANDI upload is published once the notebooks have run, and the DOI is reported', async () => { @@ -372,7 +474,7 @@ test('an EMBER-DANDI upload is published once the notebooks have run, and the DO assert.deepEqual(last.doi, { doi: '10.60533/ember-dandi.000777/0.261010.1200', url: 'https://ember/000777/0.261010.1200' }) const doiStep = last.steps.find((s) => s.id === 'doi')! assert.equal(doiStep.state, 'succeeded') - assert.equal(doiStep.detail, '10.60533/ember-dandi.000777/0.261010.1200') + assert.equal(doiStep.detail, undefined, 'the DOI is shown in its own field, not as the row\'s detail') }) test('no DOI when the notebooks fail, and a failed publish fails only its own step', async () => { @@ -397,3 +499,34 @@ test('no DOI when the notebooks fail, and a failed publish fails only its own st assert.equal(last.phase, 'failed') assert.deepEqual(last.steps.filter((s) => s.state !== 'succeeded').map((s) => `${s.id}:${s.state}`), ['doi:failed']) }) + +test('a retry after the DOI step failed only publishes: the notebooks are not run again', async () => { + const f = fakes() + let publishes = 0 + const store: IObjectStore = { + async put() { + f.calls.push('upload') + return { + url: 'u', key: 'k', dandisetId: '000777', + publish: async () => { publishes += 1; if (publishes === 1) throw new Error('EMBER publish failed'); return { doi: 'doi/000777' } }, + } + }, + } + const attempt = async (resume?: RunState['checkpoint'], workspaceId?: number) => { + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)({ protocol: FOUR_CHOICE, file: data, workspaceName: 'x', resume, workspaceId }, (s) => states.push(s)) + return states.at(-1)! + } + const first = await attempt() + assert.equal(first.steps.find((s) => s.id === 'doi')?.state, 'failed') + + const last = await attempt(first.checkpoint, first.workspaceId) + + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(last.doi?.doi, 'doi/000777') + assert.equal(count(f.calls, 'run'), 1, 'the notebooks ran once') + assert.equal(count(f.calls, 'upload'), 1) + assert.equal(count(f.calls, 'import:g'), 1) + assert.equal(last.outputsDir, first.outputsDir, 'the results stay where the run put them') + assert.deepEqual(last.steps.filter((s) => s.detail === 'Done earlier').map((s) => s.id), ['upload', 'repo', 'data', 'imports', 'run']) +}) diff --git a/applications/idp-arc/frontend/tests/unit/sessionStore.test.ts b/applications/idp-arc/frontend/tests/unit/sessionStore.test.ts new file mode 100644 index 0000000..ac98133 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/sessionStore.test.ts @@ -0,0 +1,19 @@ +// The store that keeps the upload dialog's run across closing it (components/sessionStore.ts). +// Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { createSessionStore } from '../../src/components/sessionStore' + +test('keeps its state, applies updates like setState, and tells subscribers', () => { + const store = createSessionStore({ step: 'select', runs: 0 }) + const seen: string[] = [] + const unsubscribe = store.subscribe(() => seen.push(store.get().step)) + + store.set((prev) => ({ ...prev, step: 'uploading', runs: prev.runs + 1 })) + store.set({ step: 'failed', runs: 1 }) + unsubscribe() + store.set((prev) => ({ ...prev, step: 'select' })) + + assert.deepEqual(seen, ['uploading', 'failed'], 'no news after unsubscribing') + assert.deepEqual(store.get(), { step: 'select', runs: 1 }) +}) From 069791035887df68db109c87524120910819ddb0 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Sat, 10 Oct 2026 13:46:42 +0530 Subject: [PATCH 13/32] IDP-45: clearer comments; drop an unused helper and a lint suppression --- .../frontend/src/components/PageLayout.tsx | 6 ++--- .../frontend/src/components/loginReturn.ts | 2 +- .../src/core/ports/IDandiDirectApi.ts | 20 ++++++++--------- .../frontend/src/core/ports/IEmberAuth.ts | 4 ++-- .../src/core/ports/IEmberUploadApi.ts | 2 +- .../src/infra/emberDandiDirectClient.ts | 22 ++++++++----------- .../frontend/src/infra/emberOAuthClient.ts | 20 ++++++++--------- .../src/infra/emberUploadApiClient.ts | 2 +- .../idp-arc/frontend/src/infra/emberUrls.ts | 12 +--------- 9 files changed, 37 insertions(+), 53 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 45640f1..422b617 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -140,10 +140,8 @@ export default function PageLayout({ } const anySignedIn = isAuthenticated || emberSignedIn - useEffect(() => { - registerUploadOpener(openUploadOrLogin) - // eslint-disable-next-line react-hooks/exhaustive-deps - }, [loginsDone]) + // Re-registered on every render, so buttons outside this component never call a stale copy. + useEffect(() => { registerUploadOpener(openUploadOrLogin) }) const navItems = [ { label: t('nav.protocols'), path: '/protocols' }, diff --git a/applications/idp-arc/frontend/src/components/loginReturn.ts b/applications/idp-arc/frontend/src/components/loginReturn.ts index 87cb8a2..f332b17 100644 --- a/applications/idp-arc/frontend/src/components/loginReturn.ts +++ b/applications/idp-arc/frontend/src/components/loginReturn.ts @@ -15,7 +15,7 @@ export function markLoginDialogReturn(): void { try { sessionStorage.setItem(KEY, '1') } catch { - /* blocked storage — the login still works, the dialog just won't reopen by itself */ + /* blocked storage: the login still works, the dialog just won't reopen by itself */ } } diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts index 12e2ec5..94494c6 100644 --- a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -1,7 +1,7 @@ import type { DandisetMetadata } from '../dandisetLinks' /** - * IDandiDirectApi — EMBER-DANDI operations performed straight from the browser, authenticated with + * IDandiDirectApi: EMBER-DANDI operations performed straight from the browser, authenticated with * the researcher's own OAuth token (IEmberAuth). Used for the researcher's own copy of an upload; * the MAABCD copy goes through OSB instead (IEmberUploadApi), since only OSB holds that key. */ @@ -14,11 +14,11 @@ export interface DirectUploadPart { } export interface DirectInitResult { - /** Absent when EMBER already held this content — nothing to upload. */ + /** Absent when EMBER already holds this content: nothing to upload. */ uploadId?: string /** Empty when deduplicated; the caller then skips S3 entirely. */ parts: DirectUploadPart[] - /** Set only on the deduplicated path — the existing blob to attach an asset to. */ + /** Set only on the deduplicated path: the existing blob to attach an asset to. */ blobId?: string } @@ -29,7 +29,7 @@ export interface DirectUploadedPart { } export interface DirectFinalizeInput { - /** Absent on the deduplicated path — no upload session to complete. */ + /** Absent on the deduplicated path: there is no upload session to complete. */ uploadId?: string dandisetId: string path: string @@ -75,24 +75,24 @@ export interface PublishedVersion { } export interface IDandiDirectApi { - /** `GET /dandisets/?user=me` — every dandiset this account owns, empty ones included. */ + /** `GET /dandisets/?user=me`: every dandiset this account owns, empty ones included. */ listOwnDandisets(token: string): Promise - /** `POST /dandisets/` — creates a public dandiset and returns its identifier. `metadata` is + /** `POST /dandisets/`: creates a public dandiset and returns its identifier. `metadata` is * merged into the default (a description). */ createDandiset(token: string, name: string, metadata?: DandisetMetadata): Promise - /** `GET /dandisets/{id}/versions/draft/` — the full draft metadata. */ + /** `GET /dandisets/{id}/versions/draft/`: the full draft metadata. */ getDraftMetadata(token: string, dandisetId: string): Promise - /** `PUT /dandisets/{id}/versions/draft/` — replaces the draft metadata. Only the draft is + /** `PUT /dandisets/{id}/versions/draft/`: replaces the draft metadata. Only the draft is * writable; a published version is a frozen snapshot of it. */ updateDraftMetadata(token: string, dandisetId: string, metadata: DandisetMetadata): Promise - /** `GET /dandisets/{id}/versions/draft/info/` — whether the draft can be published. */ + /** `GET /dandisets/{id}/versions/draft/info/`: whether the draft can be published. */ getDraftStatus(token: string, dandisetId: string): Promise - /** `POST /dandisets/{id}/versions/draft/publish/` — starts publishing the draft as a new + /** `POST /dandisets/{id}/versions/draft/publish/`: starts publishing the draft as a new * version. EMBER finishes it in the background. */ publishDraft(token: string, dandisetId: string): Promise diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts index 277e57a..4058345 100644 --- a/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts +++ b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts @@ -1,5 +1,5 @@ /** - * IEmberAuth — per-user authentication against EMBER-DANDI. + * IEmberAuth: per-user authentication against EMBER-DANDI. * * Distinct from IAuthClient: that one authenticates the user to *this app* and OSB (Keycloak). * This one authorises the app to act against *EMBER-DANDI* as that user, so the researcher's own @@ -21,7 +21,7 @@ export interface IEmberAuth { /** * Starts the authorization-code + PKCE flow by navigating to EMBER-DANDI. * `returnTo` is the path to send the user back to once the callback completes. - * Returns a promise that never resolves — the page unloads. + * Returns a promise that never resolves, since the page unloads. */ connect(returnTo?: string): Promise diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts index 4a9f2d9..2982041 100644 --- a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts @@ -1,5 +1,5 @@ /** - * IEmberUploadApi — OSB's two EMBER-DANDI endpoints (`/ember/get_upload_urls`, + * IEmberUploadApi: OSB's two EMBER-DANDI endpoints (`/ember/get_upload_urls`, * `/ember/validate_upload`), authenticated with the OSB (Keycloak) token. OSB signs the upload * with the EMBER-DANDI key held on a Keycloak user (the adapter names it), which never reaches the * browser; the browser still PUTs the bytes. diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index 496abf9..9263635 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -17,15 +17,11 @@ import type { export const ALLOW_EMBARGOED = false /** - * Talks to EMBER-DANDI's REST API directly from the browser with a per-user Bearer token. + * Talks to EMBER-DANDI's REST API directly from the browser, with the researcher's OAuth token. * - * Every call here was verified against the live service (Sep 2026). Two findings are - * load-bearing and easy to get wrong: - * - * 1. OAuth tokens use `Authorization: Bearer `. The admin key uses - * `Authorization: token ` (Girder-derived). Using the wrong scheme is a silent 401. - * 2. The S3 CompleteMultipartUpload POST works from a browser — it was assumed this would - * have to stay server-side, and it doesn't. + * 1. OAuth tokens go in `Authorization: Bearer `; API keys use `token ` instead, and + * the wrong scheme fails as a plain 401. + * 2. The S3 CompleteMultipartUpload POST works from the browser, so the whole upload stays here. * * `baseUrl` is IDP's same-origin `/ember-proxy` (Vite in dev, nginx deployed); see * EMBER_FETCH_BASE in container.ts. @@ -170,7 +166,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { }), }, ) - // Already registered at this path — a re-upload of the same file. Reuse it. + // Already registered at this path: a re-upload of the same file. Reuse it. if (res.status === 409) { return { assetPath: path, assetId: await this.findDraftAssetId(token, dandisetId, path) } } @@ -209,7 +205,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { }), }) - // 409 means EMBER already has this exact content — nothing to transfer. Mirrors the + // 409 means EMBER already has this exact content, so there is nothing to transfer. Mirrors the // OSB adapter's handling of the same response. if (res.status === 409) { const blobId = await this.resolveBlobByDigest(token, dandiEtag) @@ -235,7 +231,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { const etag = res.headers.get('ETag') if (!etag) { throw new Error( - 'S3 did not expose an ETag header on the part upload — the bucket needs ' + + 'S3 did not expose an ETag header on the part upload; the bucket needs ' + 'Access-Control-Expose-Headers: ETag in its CORS config.', ) } @@ -267,7 +263,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { if (!complete.ok) await this.fail(complete, 'complete_upload') const completion = await complete.json() - // DANDI hands back a presigned S3 CompleteMultipartUpload request for us to execute — + // DANDI hands back a presigned S3 CompleteMultipartUpload request for us to execute: // it can't do it itself, since only the uploader holds the part ETags. const s3 = await fetch(completion.complete_url, { method: 'POST', @@ -284,7 +280,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { blobId = (await validate.json()).blob_id } - if (!blobId) throw new Error('No blob to register — neither an upload nor a dedup hit.') + if (!blobId) throw new Error('No blob to register: neither an upload nor a dedup hit.') return this.registerAsset(token, input.dandisetId, input.path, blobId) } } diff --git a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts index 0012c91..968dd16 100644 --- a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts @@ -8,13 +8,13 @@ import type { IEmberAuth } from '../core/ports/IEmberAuth' * as `Bearer` with `read write` scope and a 24h lifetime. * * Caveat found the hard way: the token endpoint's OPTIONS preflight returns CORS headers, but - * the POST response does not — so a browser cannot read the exchange result cross-origin. Hence + * the POST response does not, so a browser cannot read the exchange result cross-origin. Hence * the split between `authOrigin` and `apiBase` below: fetches go through IDP's own same-origin * `/ember-proxy` (Vite in dev, nginx deployed). Whether EMBER could fix this via the OAuth * application's `allowed_origins` is an open question for EMBER. * * The access token is held in memory and mirrored to sessionStorage so a page reload doesn't - * force a re-login. The **refresh token is deliberately never stored** — it is the + * force a re-login. The **refresh token is deliberately never stored**: it is the * long-lived credential, and persisting it in browser storage would hand durable account access * to any XSS. A 24h access token means re-connecting at most once a day. */ @@ -47,8 +47,8 @@ export const EMBER_CALLBACK_PATH = '/ember-callback' * This has to happen before anything else reads the URL. keycloak-js treats `?code=`/`?state=` * as its OWN OAuth callback params: on init it tries to exchange them against Keycloak's token * endpoint and then strips them from the URL. Since it initialises on every route, it would - * consume EMBER's authorization code before this client ever sees it — the symptom being a - * silent "not connected" with a stray Keycloak token request in the network log. + * consume EMBER's authorization code before this client ever sees it (the symptom being a + * silent "not connected" with a stray Keycloak token request in the network log). * * Module evaluation runs during import, before React renders and before any effect fires, so * capturing here reliably wins that race. @@ -62,7 +62,7 @@ const initialCallback: { code: string | null; error: string | null; state: strin const rawError = params.get('error') if (!code && !rawError) return null - // Authorization codes are single-use, so there is nothing to retry — strip immediately. + // Authorization codes are single-use, so there is nothing to retry: strip them at once. window.history.replaceState(null, '', window.location.pathname) return { @@ -99,7 +99,7 @@ function write(key: string, value: string | null): void { if (value === null) sessionStorage.removeItem(key) else sessionStorage.setItem(key, value) } catch { - /* private mode / blocked storage — the in-memory copy still works for this page load */ + /* private mode or blocked storage: the in-memory copy still works for this page load */ } } @@ -112,7 +112,7 @@ export class EmberOAuthClient implements IEmberAuth { private readonly config: { /** * Real EMBER-DANDI origin. Used for the /oauth/authorize/ navigation, which must reach - * EMBER directly — its login redirects out to GitHub, which returns to EMBER's own + * EMBER directly: its login redirects out to GitHub, which returns to EMBER's own * domain, so this leg cannot go through a dev proxy. */ authOrigin: string @@ -146,7 +146,7 @@ export class EmberOAuthClient implements IEmberAuth { */ private async authorizeUrl(redirectUri: string, state: string): Promise { if (!this.config.clientId) { - throw new Error('VITE_EMBER_CLIENT_ID is not set — register a public OAuth client first.') + throw new Error('VITE_EMBER_CLIENT_ID is not set; register a public OAuth client first.') } const verifier = base64url(crypto.getRandomValues(new Uint8Array(48)).buffer) write(VERIFIER_KEY, verifier) @@ -256,7 +256,7 @@ export class EmberOAuthClient implements IEmberAuth { } async handleCallback(): Promise { - // Reads the module-load snapshot, not the live URL — see `initialCallback` above. + // Reads the module-load snapshot, not the live URL (see `initialCallback` above). // Consumed once: React invokes effects twice in dev, and the code is single-use. if (!initialCallback || this.callbackConsumed) return null this.callbackConsumed = true @@ -275,7 +275,7 @@ export class EmberOAuthClient implements IEmberAuth { } const verifier = read(VERIFIER_KEY) if (!verifier) { - throw new Error('No PKCE verifier found — the login was started in a different browser session.') + throw new Error('No PKCE verifier found: the login was started in a different browser session.') } const res = await fetch(`${this.config.apiBase}/oauth/token/`, { diff --git a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts index 91484b7..876a5b2 100644 --- a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts @@ -7,7 +7,7 @@ import type { } from '../core/ports/IEmberUploadApi' /** - * EmberUploadApiClient — OSB's `/ember/get_upload_urls` and `/ember/validate_upload`, on the same + * EmberUploadApiClient: OSB's `/ember/get_upload_urls` and `/ember/validate_upload`, on the same * workspaces API as every other OSB call, with the OSB (Keycloak) token. OSB answers in snake_case. * * `keyUsername`: the Keycloak user whose EMBER-DANDI key (attribute `EMBER_API_KEY`) OSB signs with. diff --git a/applications/idp-arc/frontend/src/infra/emberUrls.ts b/applications/idp-arc/frontend/src/infra/emberUrls.ts index 3aabb12..27db919 100644 --- a/applications/idp-arc/frontend/src/infra/emberUrls.ts +++ b/applications/idp-arc/frontend/src/infra/emberUrls.ts @@ -1,13 +1,3 @@ -/** - * EMBER-DANDI's two public domains — the API (`api-dandi...`) and the web UI a human browses - * (`dandi...`, no `api-` prefix). Shared here so the real client's env-driven origin - * (`EMBER_ORIGIN` in container.ts) and the mock client's fake dandiset links build off the same - * values instead of each hardcoding their own copy. - */ +/** EMBER-DANDI's two public origins: its API (`api-dandi…`) and the web UI people browse (`dandi…`). */ export const EMBER_API_ORIGIN_DEFAULT = 'https://api-dandi.emberarchive.org' export const EMBER_WEB_ORIGIN = 'https://dandi.emberarchive.org' - -/** A dandiset's page on EMBER's own web UI — e.g. for a "view on DANDI" link. */ -export function emberDandisetUrl(dandisetId: string, version: string = 'draft'): string { - return `${EMBER_WEB_ORIGIN}/dandiset/${dandisetId}/${version}` -} From c97cb6c47af8f5b4c0956ab8cdb5e7142962108f Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Wed, 14 Oct 2026 17:03:52 +0530 Subject: [PATCH 14/32] IDP-51: call OSB's /dandi upload endpoints; remove the old DANDI upload path --- README.md | 2 +- .../idp-arc/frontend/src/app/container.ts | 14 +-- .../idp-arc/frontend/src/app/mockContainer.ts | 4 - .../frontend/src/core/ports/IDandiApi.ts | 56 ---------- .../src/core/ports/IEmberUploadApi.ts | 8 +- .../idp-arc/frontend/src/core/ports/index.ts | 1 - .../idp-arc/frontend/src/core/types.ts | 32 ------ .../core/use-cases/createAndUploadToDandi.ts | 105 ------------------ .../src/core/use-cases/emberObjectStore.ts | 4 +- .../frontend/src/infra/dandiApiClient.ts | 80 ------------- .../src/infra/emberDandiDirectClient.ts | 4 +- .../src/infra/emberUploadApiClient.ts | 17 ++- .../src/infra/mocks/mockDandiApiClient.ts | 44 -------- 13 files changed, 26 insertions(+), 345 deletions(-) delete mode 100644 applications/idp-arc/frontend/src/core/ports/IDandiApi.ts delete mode 100644 applications/idp-arc/frontend/src/core/use-cases/createAndUploadToDandi.ts delete mode 100644 applications/idp-arc/frontend/src/infra/dandiApiClient.ts delete mode 100644 applications/idp-arc/frontend/src/infra/mocks/mockDandiApiClient.ts diff --git a/README.md b/README.md index 638cfa3..cc1db84 100644 --- a/README.md +++ b/README.md @@ -78,7 +78,7 @@ researcher's workspace from there. MAABCD dandiset (`maabcdDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, an EMBER-DANDI OAuth application (public client, PKCE) with `/ember-callback` as a redirect URI, and, for the MAABCD copy, the - `EMBER_API_KEY` attribute on the OSB user named by `MAABCD_EMBER_USERNAME` (`container.ts`). + `DANDI_API_KEY` attribute on the OSB user named by `MAABCD_EMBER_USERNAME` (`container.ts`). - **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL`. Its CORS must allow PUT from this app's origin. diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index 9f7971d..55d206f 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -18,7 +18,6 @@ import { KeycloakAuthClient } from '../infra/keycloakAuthClient' import { WorkspaceApiClient } from '../infra/workspaceApiClient' -import { DandiApiClient } from '../infra/dandiApiClient' import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore' import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient' import { EmberDandiDirectClient } from '../infra/emberDandiDirectClient' @@ -28,7 +27,6 @@ import type { IObjectStore } from '../core/ports/IObjectStore' import { createEmberObjectStore } from '../core/use-cases/emberObjectStore' import { createProtocolDandisetsUseCases, type ProtocolDandiset } from '../core/use-cases/protocolDandisets' import { createLoadWorkspacesUseCase } from '../core/use-cases/loadWorkspaces' -import { createCreateAndUploadToDandiUseCase } from '../core/use-cases/createAndUploadToDandi' import { createCreateWorkspaceUseCase } from '../core/use-cases/createWorkspace' import { createRunProtocolUseCase } from '../core/use-cases/runProtocol' @@ -46,9 +44,10 @@ const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` /** Where uploads go: `ember` (EMBER-DANDI) or `bucket` (the public bucket named by * VITE_UPLOAD_BUCKET_URL). Change it here to switch. */ export const UPLOAD_BACKEND = 'ember' as 'bucket' | 'ember' -/** The OSB (Keycloak) user whose EMBER-DANDI key (user attribute `EMBER_API_KEY`) signs the copy - * into the protocol's MAABCD dandiset. */ +/** The OSB (Keycloak) user whose key (user attribute `DANDI_API_KEY`) signs the copy into the + * protocol's MAABCD dandiset, and the DANDI deployment it goes to (dandi-cli's name). */ const MAABCD_EMBER_USERNAME = 'maabcd-consortium' +const MAABCD_DANDI_INSTANCE = 'ember-dandi' /** EMBER-DANDI's API origin: where the OAuth login goes, and what OSB downloads assets from. */ const EMBER_ORIGIN = (import.meta.env.VITE_EMBER_ORIGIN ?? EMBER_API_ORIGIN_DEFAULT).replace(/\/+$/, '') /** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's @@ -66,7 +65,6 @@ export const authClient = new KeycloakAuthClient({ const workspaceApi = new WorkspaceApiClient(WORKSPACES_API, WORKSPACES_LIST_URL) // DANDI upload endpoints live in OSB's `workspaces` app (the admin key has to sit wherever // they run) — same API base as every other workspace call. -const dandiApi = new DandiApiClient(WORKSPACES_API) /** Signs the researcher in to EMBER-DANDI (OAuth in a popup, a full-page redirect if it is blocked); * their token stays in the browser. */ @@ -86,7 +84,7 @@ const protocolDandisets = createProtocolDandisetsUseCases({ /** Where uploads go before OSB imports them (UPLOAD_BACKEND): EMBER-DANDI, or the public bucket. */ export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember' - ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_ORIGIN) + ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_ORIGIN) : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) // ─── Use-cases (injected with their concrete dependencies) ──────────────────── @@ -101,10 +99,6 @@ export const createWorkspace = createCreateWorkspaceUseCase(authClient, workspac * through OSB, and runs the notebooks in OSB's Argo task. */ export const runProtocol = createRunProtocolUseCase(authClient, workspaceApi, objectStore) -/** The earlier DANDI-backed upload; `finalize` also runs the selected protocol's script on OSB - * (jupyter_kernel_client.py in OSBv2's workspaces app). */ -export const createAndUploadToDandi = createCreateAndUploadToDandiUseCase(authClient, dandiApi) - /** The researcher's EMBER-DANDI dandisets for a protocol, each with the workspace it runs in when * they still have it: what the upload dialog offers once a protocol is chosen. */ export async function listProtocolDandisets(protocolId: string): Promise { diff --git a/applications/idp-arc/frontend/src/app/mockContainer.ts b/applications/idp-arc/frontend/src/app/mockContainer.ts index 1494bef..64667fd 100644 --- a/applications/idp-arc/frontend/src/app/mockContainer.ts +++ b/applications/idp-arc/frontend/src/app/mockContainer.ts @@ -10,19 +10,16 @@ import { MockAuthClient } from '../infra/mocks/mockAuthClient' import { MockWorkspaceApiClient } from '../infra/mocks/mockWorkspaceApiClient' -import { MockDandiApiClient } from '../infra/mocks/mockDandiApiClient' import { MockObjectStore } from '../infra/mocks/mockObjectStore' import { createRunProtocolUseCase } from '../core/use-cases/runProtocol' import type { IObjectStore } from '../core/ports/IObjectStore' import { createLoadWorkspacesUseCase } from '../core/use-cases/loadWorkspaces' -import { createCreateAndUploadToDandiUseCase } from '../core/use-cases/createAndUploadToDandi' // ─── Mock infrastructure singletons ────────────────────────────────────────── export const authClient = new MockAuthClient() const workspaceApi = new MockWorkspaceApiClient() -const dandiApi = new MockDandiApiClient() export const objectStore: IObjectStore = new MockObjectStore() @@ -30,7 +27,6 @@ export const objectStore: IObjectStore = new MockObjectStore() export const loadWorkspaces = createLoadWorkspacesUseCase(authClient, workspaceApi) export const runProtocol = createRunProtocolUseCase(authClient, workspaceApi, objectStore) -export const createAndUploadToDandi = createCreateAndUploadToDandiUseCase(authClient, dandiApi) // ─── Helpers ────────────────────────────────────────────────────────────────── diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiApi.ts deleted file mode 100644 index 77ab635..0000000 --- a/applications/idp-arc/frontend/src/core/ports/IDandiApi.ts +++ /dev/null @@ -1,56 +0,0 @@ -/** Abstraction over the OSB endpoints that broker the DANDI upload. */ - -export interface UploadPart { - partNumber: number - url: string -} - -export interface UploadInitResult { - /** Absent when the content was already in DANDI — nothing was uploaded. */ - uploadId?: string - path: string - /** Empty when deduplicated; the client then skips the S3 upload entirely. */ - parts: UploadPart[] - /** Set only on the deduplicated path — the existing blob to attach a new asset to. */ - blobId?: string -} - -export interface UploadedPart { - partNumber: number - size: number - etag: string -} - -export interface UploadFinalizeResult { - assetPath: string - dandisetUrl: string - workspaceId: number - /** Everything the protocol script printed, or why it didn't run. */ - scriptOutput?: string -} - -export interface FinalizeUploadInput { - /** Absent on the deduplicated path — nothing was uploaded, so there is nothing to complete. */ - uploadId?: string - path: string - parts: UploadedPart[] - /** Existing workspace to attach to; omit to have the backend create one. */ - workspaceId?: number - workspaceName?: string - blobId?: string - /** Analysis script to run. The backend fetches it, so it must be reachable from OSB's - * cluster — not a local address. */ - scriptUrl?: string - /** Filename the script should land under in the workspace. */ - scriptName?: string -} - -export interface IDandiApi { - initUpload(token: string, taskId: string, filename: string, size: number, dandiEtag: string): Promise - - /** PUTs one part straight to S3 via its presigned URL. Returns S3's ETag for the part, - * read from the response header — requires the bucket to expose it via CORS. */ - putPart(url: string, blob: Blob): Promise - - finalizeUpload(token: string, input: FinalizeUploadInput): Promise -} diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts index 2982041..88390ce 100644 --- a/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts @@ -1,8 +1,8 @@ /** - * IEmberUploadApi: OSB's two EMBER-DANDI endpoints (`/ember/get_upload_urls`, - * `/ember/validate_upload`), authenticated with the OSB (Keycloak) token. OSB signs the upload - * with the EMBER-DANDI key held on a Keycloak user (the adapter names it), which never reaches the - * browser; the browser still PUTs the bytes. + * IEmberUploadApi: OSB's two DANDI upload endpoints (`/dandi/get_upload_urls`, + * `/dandi/validate_upload`), used here for EMBER-DANDI, authenticated with the OSB (Keycloak) + * token. OSB signs the upload with the key held on a Keycloak user (the adapter names it), which + * never reaches the browser; the browser still PUTs the bytes. * * OSB doesn't know what the dandiset is for: IDP names it (the protocol's MAABCD dandiset, from * protocols.json). OSB builds the asset path itself, under the caller's own id. diff --git a/applications/idp-arc/frontend/src/core/ports/index.ts b/applications/idp-arc/frontend/src/core/ports/index.ts index 28284ce..c402b2a 100644 --- a/applications/idp-arc/frontend/src/core/ports/index.ts +++ b/applications/idp-arc/frontend/src/core/ports/index.ts @@ -1,6 +1,5 @@ export type { IAuthClient } from './IAuthClient' export type { IWorkspaceApi } from './IWorkspaceApi' -export type { IDandiApi } from './IDandiApi' export type { IObjectStore, ObjectUploadInput, StoredObject } from './IObjectStore' export type { ImportResourceInput, StartRunInput, WorkspaceResourceState } from './IWorkspaceApi' export type { IEmberAuth } from './IEmberAuth' diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index 40078fa..8b99b31 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -21,38 +21,6 @@ export interface Workspace { thumbnail?: string } -// ─── Upload workflow ────────────────────────────────────────────────────────── - -export type UploadPhase = - | 'idle' - | 'hashing' - | 'initializing' - | 'uploading' - | 'registering' - | 'done' - | 'error' - -export interface UploadState { - phase: UploadPhase - message: string - error?: string - workspaceId?: number - scriptOutput?: string -} - -/** Human-readable labels for each upload phase, used by both the use-case and the UI. */ -export const PHASE_LABELS: Record = { - idle: '', - hashing: '1 / 4 — Computing checksum…', - initializing: '2 / 4 — Preparing upload…', - uploading: '3 / 4 — Uploading file…', - // finalize also spawns the workspace and runs the protocol script synchronously — hence "can - // take a few minutes" (see jupyter_kernel_client.py in OSBv2's workspaces app). - registering: '4 / 4 — Registering asset, creating workspace & running script (can take a few minutes)…', - done: 'Done!', - error: 'Error', -} - // ─── Protocol run (upload, OSB imports, notebooks in an Argo task) ─────────── export type RunPhase = diff --git a/applications/idp-arc/frontend/src/core/use-cases/createAndUploadToDandi.ts b/applications/idp-arc/frontend/src/core/use-cases/createAndUploadToDandi.ts deleted file mode 100644 index a4c7afb..0000000 --- a/applications/idp-arc/frontend/src/core/use-cases/createAndUploadToDandi.ts +++ /dev/null @@ -1,105 +0,0 @@ -import type { IAuthClient } from '../ports/IAuthClient' -import type { IDandiApi } from '../ports/IDandiApi' -import type { UploadState } from '../types' -import { PHASE_LABELS } from '../types' -import { computeDandiEtag } from '../dandiEtag' - -export type OnProgress = (state: UploadState) => void - -export interface CreateAndUploadToDandiInput { - taskId: string - file: File - /** Existing workspace to attach the asset to; omit to create a new one. */ - workspaceId?: number - workspaceName?: string - /** The selected protocol's analysis script, resolved from protocols.json by the caller. - * Delivered into the workspace alongside the data so it is ready to run. */ - scriptUrl?: string - scriptName?: string -} - -/** - * Uploads a file to DANDI and attaches it to an OSB workspace. - * - * 1. Hash the file in the browser into a dandi-etag — the content digest DANDI identifies a - * blob by. It has to be sent up front, before any bytes move, because DANDI answers with - * "already have this" and skips the upload entirely when the digest matches an existing blob. - * 2. POST /dandi/upload/init — the backend calls DANDI with the admin key and passes back one - * presigned S3 URL per part. Each URL carries its own signature and expiry, which is what - * lets the browser write to a bucket it has no credentials for. - * 3. PUT each part's bytes to its presigned URL — a plain unauthenticated PUT, browser straight - * to S3. The file never passes through OSB, so size costs the server nothing. - * 4. POST /dandi/upload/finalize — registers the asset, attaches the workspace, runs the script - */ -export function createCreateAndUploadToDandiUseCase( - auth: Pick, - dandiApi: IDandiApi, -) { - return async function createAndUploadToDandi( - input: CreateAndUploadToDandiInput, - onProgress: OnProgress, - abortRef: { current: boolean }, - ): Promise { - const { taskId, file, workspaceId, workspaceName, scriptUrl, scriptName } = input - - try { - // ── Step 1: hash the file into DANDI's content digest ───────────────── - onProgress({ phase: 'hashing', message: PHASE_LABELS.hashing }) - const { etag, parts: partPlan } = await computeDandiEtag(file) - if (abortRef.current) return null - - // ── Step 2: initialize ──────────────────────────────────────────────── - onProgress({ phase: 'initializing', message: PHASE_LABELS.initializing }) - const initToken = await auth.getToken(30) - const init = await dandiApi.initUpload(initToken, taskId, file.name, file.size, etag) - if (abortRef.current) return null - - // ── Step 3: PUT each part to its presigned URL ──────────────────────── - // init returns no parts when DANDI already has this exact content — just a blob_id to - // attach a new asset to, so there is nothing to upload. - const uploadedParts = [] - if (init.parts.length > 0) { - onProgress({ phase: 'uploading', message: PHASE_LABELS.uploading }) - for (const part of init.parts) { - if (abortRef.current) return null - const plan = partPlan.find((p) => p.partNumber === part.partNumber) - if (!plan) throw new Error(`No local part plan for part ${part.partNumber}`) - const blob = file.slice(plan.start, plan.end) - const s3Etag = await dandiApi.putPart(part.url, blob) - uploadedParts.push({ partNumber: part.partNumber, size: plan.size, etag: s3Etag }) - } - } else { - onProgress({ phase: 'uploading', message: 'Already in DANDI — skipping upload…' }) - } - if (abortRef.current) return null - - // finalize also spawns the workspace and runs the script, so it can block for minutes. - // The token is used at the very end of that too, so it must outlive the whole call — - // hence 600s rather than the usual short floor. - onProgress({ phase: 'registering', message: PHASE_LABELS.registering }) - const finalizeToken = await auth.getToken(600) - const result = await dandiApi.finalizeUpload(finalizeToken, { - uploadId: init.uploadId, - path: init.path, - parts: uploadedParts, - workspaceId, - workspaceName, - blobId: init.blobId, - scriptUrl, - scriptName, - }) - - onProgress({ - phase: 'done', - message: PHASE_LABELS.done, - workspaceId: result.workspaceId, - scriptOutput: result.scriptOutput, - }) - return result.workspaceId - } catch (err: unknown) { - const msg = err instanceof Error ? err.message : String(err) - onProgress({ phase: 'error', message: PHASE_LABELS.error, error: msg }) - return null - } - } -} diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index a89b778..3ea9e16 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -16,8 +16,8 @@ export { EMBER_SIGN_IN } * copy OSB imports into their workspace; `recordWorkspace` then writes that workspace into * the dandiset's metadata, so the next upload for the protocol finds both; * 2. into the protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), through OSB's - * `/ember` endpoints, which sign with the MAABCD account's key. Skipped when the protocol has - * none, or the researcher chose not to share. + * `/dandi` endpoints (instance `ember-dandi`), which sign with the MAABCD account's key. + * Skipped when the protocol has none, or the researcher chose not to share. * * The browser sends the bytes both times. The second transfer is usually empty: EMBER stores each * content once, and answers with the existing blob instead of parts. diff --git a/applications/idp-arc/frontend/src/infra/dandiApiClient.ts b/applications/idp-arc/frontend/src/infra/dandiApiClient.ts deleted file mode 100644 index ef0e4f8..0000000 --- a/applications/idp-arc/frontend/src/infra/dandiApiClient.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { FinalizeUploadInput, IDandiApi, UploadFinalizeResult, UploadInitResult } from '../core/ports/IDandiApi' - -/** - * DandiApiClient — talks to idp-arc's OWN backend (same origin, `/api/dandi/...`), which is - * what actually holds the EMBER-DANDI admin key and calls DANDI/OSB on the browser's behalf. - */ -export class DandiApiClient implements IDandiApi { - constructor(private readonly baseApiUrl: string) {} - - async initUpload(token: string, taskId: string, filename: string, size: number, dandiEtag: string): Promise { - const res = await fetch(`${this.baseApiUrl}/dandi/upload/init`, { - method: 'POST', - headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ task_id: taskId, filename, size, dandi_etag: dandiEtag }), - }) - if (!res.ok) { - throw new Error(`Upload init failed: ${res.status} ${res.statusText} — ${await res.text().catch(() => '')}`) - } - const data = await res.json() as { - upload_id?: string - path: string - parts: { part_number: number; url: string }[] - blob_id?: string - } - return { - uploadId: data.upload_id, - path: data.path, - blobId: data.blob_id, - parts: (data.parts ?? []).map((p) => ({ partNumber: p.part_number, url: p.url })), - } - } - - async putPart(url: string, blob: Blob): Promise { - const res = await fetch(url, { method: 'PUT', body: blob }) - if (!res.ok) { - throw new Error(`Part upload to S3 failed: ${res.status} ${res.statusText}`) - } - const etag = res.headers.get('ETag') - if (!etag) { - throw new Error( - 'S3 did not expose an ETag header on the part upload response — the bucket needs ' + - 'Access-Control-Expose-Headers: ETag in its CORS config.', - ) - } - return etag.replaceAll('"', '') - } - - async finalizeUpload(token: string, input: FinalizeUploadInput): Promise { - const { uploadId, path, parts, workspaceId, workspaceName, blobId, scriptUrl, scriptName } = input - const res = await fetch(`${this.baseApiUrl}/dandi/upload/finalize`, { - method: 'POST', - headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' }, - body: JSON.stringify({ - path, - ...(uploadId ? { upload_id: uploadId } : {}), - ...(blobId ? { blob_id: blobId } : {}), - parts: parts.map((p) => ({ part_number: p.partNumber, size: p.size, etag: p.etag })), - ...(workspaceId !== undefined ? { workspace_id: workspaceId } : {}), - ...(workspaceName ? { workspace_name: workspaceName } : {}), - ...(scriptUrl ? { script_url: scriptUrl } : {}), - ...(scriptName ? { script_name: scriptName } : {}), - }), - }) - if (!res.ok) { - throw new Error(`Upload finalize failed: ${res.status} ${res.statusText} — ${await res.text().catch(() => '')}`) - } - const data = await res.json() as { - asset_path: string - dandiset_url: string - workspace_id: number - script_output?: string - } - return { - assetPath: data.asset_path, - dandisetUrl: data.dandiset_url, - workspaceId: data.workspace_id, - scriptOutput: data.script_output, - } - } -} diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index 9263635..20064f8 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -111,9 +111,11 @@ export class EmberDandiDirectClient implements IDandiDirectApi { } async publishDraft(token: string, dandisetId: string): Promise { + // Newer DANDI releases require a body (it may carry release notes); EMBER ignores it. const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/publish/`, { method: 'POST', - headers: this.headers(token), + headers: this.headers(token, true), + body: '{}', }) if (!res.ok) await this.fail(res, 'publish') } diff --git a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts index 876a5b2..dc37306 100644 --- a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts @@ -7,13 +7,18 @@ import type { } from '../core/ports/IEmberUploadApi' /** - * EmberUploadApiClient: OSB's `/ember/get_upload_urls` and `/ember/validate_upload`, on the same + * EmberUploadApiClient: OSB's `/dandi/get_upload_urls` and `/dandi/validate_upload`, on the same * workspaces API as every other OSB call, with the OSB (Keycloak) token. OSB answers in snake_case. * - * `keyUsername`: the Keycloak user whose EMBER-DANDI key (attribute `EMBER_API_KEY`) OSB signs with. + * `instance`: the DANDI deployment, by its dandi-cli name (`ember-dandi`). + * `keyUsername`: the Keycloak user whose key (attribute `DANDI_API_KEY`) OSB signs with. */ export class EmberUploadApiClient implements IEmberUploadApi { - constructor(private readonly baseApiUrl: string, private readonly keyUsername: string) {} + constructor( + private readonly baseApiUrl: string, + private readonly instance: string, + private readonly keyUsername: string, + ) {} private async post(token: string, path: string, body: unknown, what: string): Promise { const res = await fetch(`${this.baseApiUrl}${path}`, { @@ -35,7 +40,8 @@ export class EmberUploadApiClient implements IEmberUploadApi { upload_id?: string | null parts?: { part_number: number; url: string }[] blob_id?: string | null - }>(token, '/ember/get_upload_urls', { + }>(token, '/dandi/get_upload_urls', { + instance: this.instance, username: this.keyUsername, dandiset_id: input.dandisetId, filename: input.filename, @@ -53,7 +59,8 @@ export class EmberUploadApiClient implements IEmberUploadApi { async validateUpload(token: string, input: BrokeredValidateInput): Promise { const body = await this.post<{ asset_id: string; asset_path: string; download_url: string }>( - token, '/ember/validate_upload', { + token, '/dandi/validate_upload', { + instance: this.instance, username: this.keyUsername, dandiset_id: input.dandisetId, path: input.path, diff --git a/applications/idp-arc/frontend/src/infra/mocks/mockDandiApiClient.ts b/applications/idp-arc/frontend/src/infra/mocks/mockDandiApiClient.ts deleted file mode 100644 index 112aaee..0000000 --- a/applications/idp-arc/frontend/src/infra/mocks/mockDandiApiClient.ts +++ /dev/null @@ -1,44 +0,0 @@ -import type { FinalizeUploadInput, IDandiApi, UploadFinalizeResult, UploadInitResult } from '../../core/ports/IDandiApi' - -let nextWorkspaceId = 900 -let nextUploadId = 1 - -/** MockDandiApiClient — in-memory stub for IDandiApi. No real DANDI/OSB calls. */ -export class MockDandiApiClient implements IDandiApi { - async initUpload(_token: string, taskId: string, filename: string, size: number, _dandiEtag: string): Promise { - await delay(400) - const uploadId = `mock-upload-${nextUploadId++}` - const path = `task-${taskId}/sub-mockuser/${filename}` - console.info(`[MockDandiApiClient] initUpload(${filename}, ${size}B) → ${uploadId} @ ${path}`) - return { uploadId, path, parts: [{ partNumber: 1, url: `blob:mock-part-url` }] } - } - - async putPart(_url: string, _blob: Blob): Promise { - await delay(500) - return 'mock-s3-etag' - } - - async finalizeUpload(_token: string, input: FinalizeUploadInput): Promise { - const { uploadId, path, workspaceId, workspaceName, scriptUrl, scriptName } = input - // The real backend blocks here for as long as spawning + running the script takes — mimic - // that shape (a longer delay) rather than resolving instantly, so this feels representative. - await delay(scriptUrl ? 1500 : 500) - const wsId = workspaceId ?? nextWorkspaceId++ - console.info( - `[MockDandiApiClient] finalizeUpload(${uploadId}) → workspace ${wsId} ` + - `(${workspaceName ?? 'existing'}), script ${scriptName ?? 'none'}`, - ) - return { - assetPath: path, - dandisetUrl: 'https://dandi.emberarchive.org/dandiset/000533/draft', - workspaceId: wsId, - scriptOutput: scriptUrl - ? 'Fetched 1818 bytes from DANDI\n\nProtocol : two-arm-bandit\nTrials : 20\nReward : 13/20 (65%)\n\nWrote ./cumulative_reward.png\n' - : undefined, - } - } -} - -function delay(ms: number): Promise { - return new Promise(resolve => setTimeout(resolve, ms)) -} From f8e68aa952a194584514a1e66712ab325600844e Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Wed, 14 Oct 2026 20:22:07 +0530 Subject: [PATCH 15/32] IDP-51: publish button to publish and get a DOI for the uploaded data --- .../idp-arc/frontend/src/app/container.ts | 6 ++ .../src/components/DataUploadDialog.tsx | 53 +++++++++--- .../frontend/src/core/ports/IObjectStore.ts | 2 - .../idp-arc/frontend/src/core/types.ts | 6 -- .../src/core/use-cases/emberObjectStore.ts | 6 +- .../src/core/use-cases/runProgress.ts | 3 +- .../src/core/use-cases/runProtocol.ts | 35 +------- .../src/infra/emberDandiDirectClient.ts | 6 +- .../src/infra/emberUploadApiClient.ts | 14 +-- .../frontend/tests/unit/emberClients.test.ts | 73 ++++++++++++++++ .../tests/unit/emberObjectStore.test.ts | 7 -- .../frontend/tests/unit/runProtocol.test.ts | 86 +------------------ 12 files changed, 140 insertions(+), 157 deletions(-) create mode 100644 applications/idp-arc/frontend/tests/unit/emberClients.test.ts diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index 55d206f..a05a492 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -107,6 +107,12 @@ export async function listProtocolDandisets(protocolId: string): Promise { + const version = await protocolDandisets.publish(dandisetId) + return version?.doi ? { doi: version.doi } : null +} + // ─── Helpers ────────────────────────────────────────────────────────────────── /** The researcher's workspaces on OSB ("My workspaces"). */ diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index 06c6fc5..1fca91c 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -21,15 +21,15 @@ import OpenInNewIcon from '@mui/icons-material/OpenInNewOutlined' import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' -import { emberAuth, getWorkspaceUrl, listProtocolDandisets, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' -import { EMBER_SIGN_IN } from '../core/userMessages' +import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' +import { EMBER_SIGN_IN, userMessage } from '../core/userMessages' import { useAppContext } from '../AppContext' -import type { RunCheckpoint, RunStep } from '../core/types' +import { RUN_STEP, type RunCheckpoint, type RunStep } from '../core/types' import RunChecklist from './RunChecklist' import { createSessionStore, useSessionStore } from './sessionStore' import DoiField from './DoiField' import { inputFileProblem, inputFormatsFor } from '../core/inputFormats' -import { canResume } from '../core/use-cases/runProtocol' +import { canResume, PUBLISH_STEP } from '../core/use-cases/runProtocol' import { formatBytes } from '../core/formatBytes' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' import { SIGN_IN_AGAIN } from '../core/userMessages' @@ -58,8 +58,10 @@ step: DialogStep spawnedWorkspaceId: number | undefined /** Where the last run's results are, relative to the workspace root. */ outputsDir: string - /** The DOI the run's data was published with. */ - doi?: { doi: string; url?: string } + /** The DOI of the version published with "Publish dandiset". */ + doi?: { doi: string } + /** That publish is under way, or failed (it can be retried). */ + publishing?: 'running' | 'failed' /** The run's checklist (upload, imports, run), as last reported by the use-case. */ runSteps: RunStep[] /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ @@ -98,7 +100,7 @@ let currentWatch: { current: boolean } | null = null export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() const [form] = useSessionStore(session) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi, checkpoint } = form + const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi, publishing, checkpoint } = form // EMBER-DANDI: the upload goes to the researcher's own account. Choosing a protocol lists their // dandisets for it, each with the workspace it runs in, so choosing one chooses both. const usesEmber = UPLOAD_BACKEND === 'ember' @@ -132,11 +134,18 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut if (!open) return const current = session.get() const unstarted = current.step === 'select' || (current.step === 'upload' && !current.checkpoint) - if (unstarted || current.resultSeen) freshForm() + if ((unstarted || current.resultSeen) && current.publishing !== 'running') freshForm() // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]) // A finished run's result counts as seen once it is on screen. const finished = step === 'success' || step === 'stillRunning' + // Publishing joins the run's checklist once the researcher starts it. + const publishStep: RunStep | null = + publishing === 'running' ? { ...PUBLISH_STEP, state: 'running' } + : publishing === 'failed' ? { ...PUBLISH_STEP, state: 'failed', detail: userMessage(undefined, RUN_STEP.doi) } + : doi ? { ...PUBLISH_STEP, state: 'succeeded' } + : null + const checklist = publishStep ? [...runSteps, publishStep] : runSteps useEffect(() => { if (open && finished) setForm((prev) => (prev.resultSeen ? prev : { ...prev, resultSeen: true })) }, [open, finished]) @@ -193,7 +202,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const handleUpload = async () => { if (!file || fileProblem || !selectedProtocol) return - setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [], doi: undefined })) + setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [], doi: undefined, publishing: undefined })) if (currentWatch) currentWatch.current = true const watch = { current: false } currentWatch = watch @@ -237,7 +246,6 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut dandisetId: state.dandisetId ?? prev.dandisetId, uploadMessage: state.phase === 'failed' ? `${state.message}: ${state.error}` : state.message, outputsDir: state.outputsDir ?? prev.outputsDir, - doi: state.doi ?? prev.doi, runSteps: state.steps, checkpoint: state.checkpoint ?? prev.checkpoint, ...(state.phase === 'succeeded' ? { step: 'success' } : {}), @@ -249,6 +257,19 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut ) } + /** "Publish dandiset": the researcher's dandiset as a new, permanent version. Optional. */ + const publish = async () => { + if (!dandisetId) return + setForm((prev) => ({ ...prev, publishing: 'running' })) + try { + const published = await publishDandiset(dandisetId) + setForm((prev) => ({ ...prev, publishing: published ? undefined : 'failed', doi: published ?? prev.doi })) + } catch (err) { + console.error('Publishing the dandiset failed', err) + setForm((prev) => ({ ...prev, publishing: 'failed' })) + } + } + // "Retry" only when an earlier attempt can be carried on (same protocol, file, dandiset and // sharing choice); choosing a dandiset that already has a workspace is still a new run. const resumable = !!selectedProtocol && canResume(checkpoint, { @@ -563,11 +584,15 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut )} - {runSteps.length > 0 && } - {/* Under the checklist, after its last row, "Publish your data with a DOI". */} - {step === 'success' && doi && ( + {checklist.length > 0 && } + {/* Optional, after the run: publishing is the researcher's choice (they can also do it on EMBER). */} + {finished && usesEmber && dandisetId && publishing !== 'running' && ( - + {doi ? : ( + + )} )} diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index 2579cd0..302fb76 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -38,8 +38,6 @@ export interface StoredObject { dandisetId?: string /** EMBER-DANDI: records the run's workspace in the dandiset's metadata. */ recordWorkspace?: (workspaceId: number) => Promise - /** EMBER-DANDI: publishes the dandiset as a new version and returns its DOI; null if `stopped`. */ - publish?: (stopped: () => boolean) => Promise<{ doi: string; url?: string } | null> } export interface IObjectStore { diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index 8b99b31..2002cd0 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -28,8 +28,6 @@ export type RunPhase = | 'workspace' | 'importing' | 'running' - /** Publishing the dandiset for its DOI. */ - | 'publishing' /** Still running in the workspace past the watch limit: no longer followed here. */ | 'stillRunning' | 'succeeded' @@ -68,8 +66,6 @@ export interface RunState { dandisetId?: string /** This run's results folder, relative to the workspace root. */ outputsDir?: string - /** The DOI of the version published at the end of the run. */ - doi?: { doi: string; url?: string } error?: string /** What the run has done so far; given back on a retry, it carries on from there. */ checkpoint?: RunCheckpoint @@ -97,6 +93,4 @@ export interface RunCheckpoint { runFolderAt?: string repoImported?: boolean dataImported?: boolean - /** The notebooks ran and passed, in this folder: a retry goes straight to the DOI. */ - ranIn?: string } diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index 3ea9e16..e33ed0e 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -44,7 +44,7 @@ export function createEmberObjectStore( emberAuth: Pick, direct: IDandiDirectApi, osb: IEmberUploadApi, - dandisets: Pick, + dandisets: Pick, /** EMBER's public API origin (`https://api-dandi.emberarchive.org`): the download link has to * work from OSB's cluster, so never the browser's same-origin proxy. */ emberApiOrigin: string, @@ -114,10 +114,6 @@ export function createEmberObjectStore( key: asset.assetPath, dandisetId: userDandisetId, recordWorkspace: (workspaceId: number) => dandisets.recordWorkspace(userDandisetId, workspaceId, protocol), - publish: async (stopped) => { - const version = await dandisets.publish(userDandisetId, stopped) - return version?.doi ? { doi: version.doi, url: version.url } : null - }, } async function putParts(parts: { partNumber: number; url: string }[], plan: PartPlan[], file: File, diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts index 2a6e0a2..7ee15f3 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts @@ -27,7 +27,6 @@ export class RunProgress { workspaceId?: number dandisetId?: string outputsDir?: string - doi?: { doi: string; url?: string } /** Reported with every state, so the last one the dialog sees is up to date. */ checkpoint?: RunCheckpoint @@ -99,7 +98,7 @@ export class RunProgress { const { phase, steps, workspaceId, dandisetId, outputsDir, checkpoint } = this this.report({ phase, message, steps, workspaceId, outputsDir, - ...(dandisetId ? { dandisetId } : {}), ...(this.doi ? { doi: this.doi } : {}), ...(error ? { error } : {}), ...(checkpoint ? { checkpoint: { ...checkpoint } } : {}), + ...(dandisetId ? { dandisetId } : {}), ...(error ? { error } : {}), ...(checkpoint ? { checkpoint: { ...checkpoint } } : {}), }) } diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 11443b9..9f274a2 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -96,9 +96,11 @@ const STEPS = [ { id: RUN_STEP.data, label: 'Import your data' }, { id: RUN_STEP.imports, label: 'Wait for the imports to finish' }, { id: RUN_STEP.run, label: 'Run the notebooks' }, - { id: RUN_STEP.doi, label: 'Publish your data with a DOI' }, ] +/** Not part of the run: the dialog adds it once the researcher publishes the dandiset. */ +export const PUBLISH_STEP = { id: RUN_STEP.doi, label: 'Publish your dandiset' } + /** * Runs a protocol on the researcher's data. Before anything moves, the protocol and the file are * checked; then, one step per entry in STEPS: @@ -121,8 +123,6 @@ const STEPS = [ * the run task removes the code once it has copied it (discard_repo). It is followed, like the * imports, through `GET /workspace/{id}`'s placeholder: that shows when it ends. Whether it * succeeded is in which folder its executed notebooks are then listed. - * 7. Publish the researcher's dandiset as a new version (EMBER-DANDI only): its DOI cites this - * data. Skipped by the bucket, and without a file. * * No lab server is started: the imports and the run are OSB's own Argo workflows, and their * affinity to the workspace is met by their own pods (verified 5 Oct on a never-opened workspace). @@ -165,7 +165,6 @@ export function createRunProtocolUseCase( if (!file) { progress.skip(RUN_STEP.upload) progress.skip(RUN_STEP.data) - progress.skip(RUN_STEP.doi) } progress.emit('Starting…') @@ -193,23 +192,7 @@ export function createRunProtocolUseCase( }) if (stopped()) return - // 3–6 already done: the notebooks ran and passed, so only the DOI is left. - if (checkpoint.ranIn) { - for (const id of [RUN_STEP.repo, RUN_STEP.data, RUN_STEP.imports, RUN_STEP.run]) { - if (id !== RUN_STEP.data || file) doneEarlier(id) - } - progress.outputsDir = checkpoint.ranIn - } else { - const ran = await importAndRun(workspaceId, stored, repo, layout) - if (!ran) return - save({ ranIn: layout.run }) - } - - // 7. Publish the dandiset, for a DOI. - if (stored?.publish) { - const publish = stored.publish - if (!(await inStep(RUN_STEP.doi, () => publishForDoi(publish)))) return - } else progress.skip(RUN_STEP.doi) + if (!(await importAndRun(workspaceId, stored, repo, layout))) return progress.finish('The analysis has finished') } catch (err) { progress.fail(err) @@ -415,15 +398,5 @@ export function createRunProtocolUseCase( progress.done(RUN_STEP.run, `Results in ${layout.run}/`) return true } - - /** Step 7. The published version's DOI; null if the dialog was closed meanwhile. */ - async function publishForDoi(publish: NonNullable) { - progress.start(RUN_STEP.doi, 'publishing', 'Publishing your data…', 'Waiting for EMBER-DANDI to check it') - const published = await publish(stopped) - if (!published) return null - progress.doi = published - progress.done(RUN_STEP.doi) - return published - } } } diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index 20064f8..32334e6 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -27,7 +27,11 @@ export const ALLOW_EMBARGOED = false * EMBER_FETCH_BASE in container.ts. */ export class EmberDandiDirectClient implements IDandiDirectApi { - constructor(private readonly baseUrl: string) {} + private readonly baseUrl: string + + constructor(baseUrl: string) { + this.baseUrl = baseUrl + } private headers(token: string, json = false): HeadersInit { return { diff --git a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts index dc37306..ba38387 100644 --- a/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts @@ -14,11 +14,15 @@ import type { * `keyUsername`: the Keycloak user whose key (attribute `DANDI_API_KEY`) OSB signs with. */ export class EmberUploadApiClient implements IEmberUploadApi { - constructor( - private readonly baseApiUrl: string, - private readonly instance: string, - private readonly keyUsername: string, - ) {} + private readonly baseApiUrl: string + private readonly instance: string + private readonly keyUsername: string + + constructor(baseApiUrl: string, instance: string, keyUsername: string) { + this.baseApiUrl = baseApiUrl + this.instance = instance + this.keyUsername = keyUsername + } private async post(token: string, path: string, body: unknown, what: string): Promise { const res = await fetch(`${this.baseApiUrl}${path}`, { diff --git a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts new file mode 100644 index 0000000..4874658 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -0,0 +1,73 @@ +// What IDP actually sends: to OSB's /dandi upload endpoints (infra/emberUploadApiClient.ts) and to +// EMBER-DANDI when publishing (infra/emberDandiDirectClient.ts). Run: yarn test:unit +import { test, afterEach } from 'node:test' +import assert from 'node:assert/strict' +import { EmberUploadApiClient } from '../../src/infra/emberUploadApiClient' +import { EmberDandiDirectClient } from '../../src/infra/emberDandiDirectClient' + +const realFetch = globalThis.fetch +afterEach(() => { globalThis.fetch = realFetch }) + +/** Replaces fetch: records each request and answers with `reply`. */ +function recordFetch(reply: (url: string) => { status?: number; json?: unknown }) { + const requests: { url: string; method?: string; headers: Record; body?: unknown }[] = [] + globalThis.fetch = (async (url: string, init: RequestInit = {}) => { + requests.push({ + url, method: init.method, headers: (init.headers ?? {}) as Record, + body: typeof init.body === 'string' ? JSON.parse(init.body) : init.body, + }) + const r = reply(url) + return new Response(JSON.stringify(r.json ?? {}), { status: r.status ?? 200 }) + }) as typeof fetch + return requests +} + +test('the MAABCD copy asks OSB for upload URLs on its /dandi endpoint, naming the deployment and key user', async () => { + const requests = recordFetch(() => ({ json: { dandiset_id: '000542', path: 'sub/u/f.xlsx', upload_id: 'up', parts: [{ part_number: 1, url: 'https://s3/p1' }] } })) + const osb = new EmberUploadApiClient('https://osb/api', 'ember-dandi', 'maabcd-consortium') + + const upload = await osb.getUploadUrls('osb-token', { dandisetId: '000542', filename: 'f.xlsx', size: 10, dandiEtag: 'e-1' }) + + assert.equal(requests[0].url, 'https://osb/api/dandi/get_upload_urls') + assert.equal(requests[0].headers.Authorization, 'Bearer osb-token') + assert.deepEqual(requests[0].body, { + instance: 'ember-dandi', username: 'maabcd-consortium', dandiset_id: '000542', filename: 'f.xlsx', size: 10, dandi_etag: 'e-1', + }) + assert.deepEqual(upload.parts, [{ partNumber: 1, url: 'https://s3/p1' }]) +}) + +test('validating sends the deployment and key user too, and only the fields that apply', async () => { + const requests = recordFetch(() => ({ json: { asset_id: 'a', asset_path: 'p', download_url: 'https://dl' } })) + const osb = new EmberUploadApiClient('https://osb/api', 'ember-dandi', 'maabcd-consortium') + + const asset = await osb.validateUpload('osb-token', { dandisetId: '000542', path: 'sub/u/f.xlsx', blobId: 'blob-1' }) + + assert.equal(requests[0].url, 'https://osb/api/dandi/validate_upload') + assert.deepEqual(requests[0].body, { + instance: 'ember-dandi', username: 'maabcd-consortium', dandiset_id: '000542', path: 'sub/u/f.xlsx', blob_id: 'blob-1', + }) + assert.deepEqual(asset, { assetId: 'a', assetPath: 'p', downloadUrl: 'https://dl' }) +}) + +test('an OSB error names the call and carries its status and message', async () => { + recordFetch(() => ({ status: 400, json: 'instance must be one of dandi, ember-dandi' })) + const osb = new EmberUploadApiClient('https://osb/api', 'nope', 'u') + + await assert.rejects( + osb.getUploadUrls('t', { dandisetId: '000542', filename: 'f', size: 1, dandiEtag: 'e' }), + /OSB get_upload_urls failed \(HTTP 400\).*instance must be one of/, + ) +}) + +test('publishing sends a JSON body, which newer DANDI releases require', async () => { + const requests = recordFetch(() => ({ status: 202 })) + const ember = new EmberDandiDirectClient('/ember-proxy') + + await ember.publishDraft('ember-token', '000777') + + assert.equal(requests[0].url, '/ember-proxy/api/dandisets/000777/versions/draft/publish/') + assert.equal(requests[0].method, 'POST') + assert.equal(requests[0].headers.Authorization, 'Bearer ember-token') + assert.equal(requests[0].headers['Content-Type'], 'application/json') + assert.deepEqual(requests[0].body, {}) +}) diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index 3317ba6..8126063 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -48,7 +48,6 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b const dandisets = { async createForProtocol(name: string, protocol: { id: string }) { calls.push(`create:${name}:${protocol.id}`); return '000777' }, async recordWorkspace(dandisetId: string, workspaceId: number, protocol: { id: string }) { calls.push(`record:${dandisetId}:${workspaceId}:${protocol.id}`) }, - async publish(dandisetId: string) { calls.push(`publish:${dandisetId}`); return { version: 'v1', doi: `doi/${dandisetId}` } }, } const store = (emberToken: string | null = 'ember-token') => createEmberObjectStore( { getToken: async () => 'osb-token' }, { getToken: () => emberToken }, direct, osb, dandisets, `${ORIGIN}/`, @@ -174,9 +173,3 @@ test('a retry with everything done makes no copy at all', async () => { assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) }) -test('the stored upload publishes the dandiset it went into, for its DOI', async () => { - const { calls, store } = fakes() - const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123' } }) - assert.deepEqual(await stored.publish?.(() => false), { doi: 'doi/000123', url: undefined }) - assert.equal(calls.at(-1), 'publish:000123') -}) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index d916ce0..269525f 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -87,8 +87,7 @@ test('uploads, imports both into the run folder, waits, runs, and reports the ru assert.equal(last.phase, 'succeeded', last.error) assert.equal(last.workspaceId, 42) - // The bucket can't publish: no DOI step. - assert.deepEqual(last.steps.map((s) => s.state), [...Array(6).fill('succeeded'), 'skipped']) + assert.deepEqual(last.steps.map((s) => s.state), Array(6).fill('succeeded')) assert.ok(f.calls.includes('create:Four-choice:maabcd:four-choice-reversal')) // /run--/: the code and the upload, imported into the run's folder. @@ -162,7 +161,7 @@ test('without a file: no upload, no data import, the notebooks run on the exampl assert.equal(last.phase, 'succeeded') assert.deepEqual(f.imports.map((i) => i.resourceType), ['g']) assert.equal(f.runInput()?.inputDir, undefined) - assert.deepEqual(last.steps.filter((s) => s.state === 'skipped').map((s) => s.id), ['upload', 'data', 'doi']) + assert.deepEqual(last.steps.filter((s) => s.state === 'skipped').map((s) => s.id), ['upload', 'data']) }) test('a failed upload marks only the upload step failed', async () => { @@ -449,84 +448,3 @@ test('another file, protocol or sharing choice starts over instead of carrying o assert.equal(count(f.calls, 'upload'), 2, 'the other file is uploaded') }) -// ── The DOI ────────────────────────────────────────────────────────────────────────────────── - -test('an EMBER-DANDI upload is published once the notebooks have run, and the DOI is reported', async () => { - const f = fakes() - const order: string[] = [] - f.api.startRun = ((startRun) => async (...args: Parameters) => { - order.push('run'); return startRun(...args) - })(f.api.startRun) - const store: IObjectStore = { - async put() { - return { - url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777', - publish: async () => { order.push('publish'); return { doi: '10.60533/ember-dandi.000777/0.261010.1200', url: 'https://ember/000777/0.261010.1200' } }, - } - }, - } - const states: RunState[] = [] - await createRunProtocolUseCase(auth, f.api, store)({ protocol: FOUR_CHOICE, file: file(), workspaceName: 'x' }, (s) => states.push(s)) - const last = states.at(-1)! - - assert.equal(last.phase, 'succeeded', last.error) - assert.deepEqual(order, ['run', 'publish']) - assert.deepEqual(last.doi, { doi: '10.60533/ember-dandi.000777/0.261010.1200', url: 'https://ember/000777/0.261010.1200' }) - const doiStep = last.steps.find((s) => s.id === 'doi')! - assert.equal(doiStep.state, 'succeeded') - assert.equal(doiStep.detail, undefined, 'the DOI is shown in its own field, not as the row\'s detail') -}) - -test('no DOI when the notebooks fail, and a failed publish fails only its own step', async () => { - const published: string[] = [] - const store = (fail: boolean): IObjectStore => ({ - async put() { - return { - url: 'u', key: 'k', dandisetId: '000777', - publish: async () => { published.push('publish'); if (fail) throw new Error('EMBER publish failed (HTTP 400)'); return { doi: 'd' } }, - } - }, - }) - const notebookFails = fakes({ runFails: 'notebook' }) - const failedRun: RunState[] = [] - await createRunProtocolUseCase(auth, notebookFails.api, store(false))({ protocol: FOUR_CHOICE, file: file(), workspaceName: 'x' }, (s) => failedRun.push(s)) - assert.equal(failedRun.at(-1)!.phase, 'failed') - assert.deepEqual(published, [], 'nothing published after a failed run') - - const states: RunState[] = [] - await createRunProtocolUseCase(auth, fakes().api, store(true))({ protocol: FOUR_CHOICE, file: file(), workspaceName: 'x' }, (s) => states.push(s)) - const last = states.at(-1)! - assert.equal(last.phase, 'failed') - assert.deepEqual(last.steps.filter((s) => s.state !== 'succeeded').map((s) => `${s.id}:${s.state}`), ['doi:failed']) -}) - -test('a retry after the DOI step failed only publishes: the notebooks are not run again', async () => { - const f = fakes() - let publishes = 0 - const store: IObjectStore = { - async put() { - f.calls.push('upload') - return { - url: 'u', key: 'k', dandisetId: '000777', - publish: async () => { publishes += 1; if (publishes === 1) throw new Error('EMBER publish failed'); return { doi: 'doi/000777' } }, - } - }, - } - const attempt = async (resume?: RunState['checkpoint'], workspaceId?: number) => { - const states: RunState[] = [] - await createRunProtocolUseCase(auth, f.api, store)({ protocol: FOUR_CHOICE, file: data, workspaceName: 'x', resume, workspaceId }, (s) => states.push(s)) - return states.at(-1)! - } - const first = await attempt() - assert.equal(first.steps.find((s) => s.id === 'doi')?.state, 'failed') - - const last = await attempt(first.checkpoint, first.workspaceId) - - assert.equal(last.phase, 'succeeded', last.error) - assert.equal(last.doi?.doi, 'doi/000777') - assert.equal(count(f.calls, 'run'), 1, 'the notebooks ran once') - assert.equal(count(f.calls, 'upload'), 1) - assert.equal(count(f.calls, 'import:g'), 1) - assert.equal(last.outputsDir, first.outputsDir, 'the results stay where the run put them') - assert.deepEqual(last.steps.filter((s) => s.detail === 'Done earlier').map((s) => s.id), ['upload', 'repo', 'data', 'imports', 'run']) -}) From a947d871e2f5fbd1e19688176f82be2c7caefc56 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Thu, 22 Oct 2026 11:40:42 +0530 Subject: [PATCH 16/32] IDP-51: rename the publish check by its role; document protocols and uploads --- README.md | 2 +- .../src/components/DataUploadDialog.tsx | 2 +- .../src/core/ports/IDandiDirectApi.ts | 29 +++++++--- .../frontend/src/core/ports/IObjectStore.ts | 2 +- .../src/core/use-cases/emberObjectStore.ts | 12 ++-- .../src/core/use-cases/protocolDandisets.ts | 12 ++-- .../src/core/use-cases/runProtocol.ts | 4 +- .../idp-arc/frontend/src/data/README.md | 56 ++++++++++++------- .../idp-arc/frontend/src/data/protocols.json | 2 +- .../src/infra/emberDandiDirectClient.ts | 6 +- .../tests/unit/emberObjectStore.test.ts | 2 +- .../tests/unit/protocolDandisets.test.ts | 2 +- .../frontend/tests/unit/runProtocol.test.ts | 4 +- 13 files changed, 81 insertions(+), 54 deletions(-) diff --git a/README.md b/README.md index cc1db84..db9ca29 100644 --- a/README.md +++ b/README.md @@ -75,7 +75,7 @@ way, uploading needs both logins (EMBER-DANDI and OSB), and OSB imports the file researcher's workspace from there. - **`ember`** (default): EMBER-DANDI, into the researcher's own dandiset and the protocol's - MAABCD dandiset (`maabcdDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, + MAABCD dandiset (`maabcdAggregateDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, an EMBER-DANDI OAuth application (public client, PKCE) with `/ember-callback` as a redirect URI, and, for the MAABCD copy, the `DANDI_API_KEY` attribute on the OSB user named by `MAABCD_EMBER_USERNAME` (`container.ts`). diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index 1fca91c..e905fb1 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -438,7 +438,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut )} )} - {usesEmber && selectedProtocol?.maabcdDandisetId && ( + {usesEmber && selectedProtocol?.maabcdAggregateDandisetId && ( - /** `GET /dandisets/{id}/versions/draft/info/`: whether the draft can be published. */ - getDraftStatus(token: string, dandisetId: string): Promise + /** `GET /dandisets/{id}/versions/draft/info/`: whether the draft can be published yet. */ + getPublishReadiness(token: string, dandisetId: string): Promise /** `POST /dandisets/{id}/versions/draft/publish/`: starts publishing the draft as a new * version. EMBER finishes it in the background. */ diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index 302fb76..8d00586 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -20,7 +20,7 @@ export interface ObjectUploadInput { newName?: string /** Recorded in the dandiset's metadata, with the workspace the run uses. */ protocol?: { id: string; name: string; url?: string } - /** The protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), uploaded to through OSB. */ + /** The protocol's MAABCD dandiset (protocols.json `maabcdAggregateDandisetId`), uploaded to through OSB. */ maabcd?: string } /** From an earlier, interrupted put of the same file: what it already did is not done again. */ diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index e33ed0e..696fd90 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -15,7 +15,7 @@ export { EMBER_SIGN_IN } * 1. into the researcher's own dandiset, from the browser with their EMBER token. This is the * copy OSB imports into their workspace; `recordWorkspace` then writes that workspace into * the dandiset's metadata, so the next upload for the protocol finds both; - * 2. into the protocol's MAABCD dandiset (protocols.json `maabcdDandisetId`), through OSB's + * 2. into the protocol's MAABCD dandiset (protocols.json `maabcdAggregateDandisetId`), through OSB's * `/dandi` endpoints (instance `ember-dandi`), which sign with the MAABCD account's key. * Skipped when the protocol has none, or the researcher chose not to share. * @@ -54,7 +54,7 @@ export function createEmberObjectStore( const { file } = input const token = emberAuth.getToken() if (!token) throw new UserFacingError(EMBER_SIGN_IN, 'No EMBER-DANDI token (not signed in, or it expired)') - const maabcdDandisetId = input.dandisets?.maabcd || undefined + const maabcdAggregateDandisetId = input.dandisets?.maabcd || undefined const saved: EmberUploadCheckpoint = { ...(input.resume as EmberUploadCheckpoint | undefined) } const save = (patch: EmberUploadCheckpoint) => { Object.assign(saved, patch) @@ -63,14 +63,14 @@ export function createEmberObjectStore( // Bytes counted across both transfers, so the progress bar runs once from 0 to 100%; a copy // made by an earlier attempt counts as sent. - const transfers = maabcdDandisetId ? 2 : 1 + const transfers = maabcdAggregateDandisetId ? 2 : 1 const total = file.size * transfers - let done = (saved.own ? file.size : 0) + (maabcdDandisetId && saved.maabcdDone ? file.size : 0) + let done = (saved.own ? file.size : 0) + (maabcdAggregateDandisetId && saved.maabcdDone ? file.size : 0) const progress = (sentInTransfer: number) => onProgress?.(Math.min(done + sentInTransfer, total), total) const skipTransfer = () => { done += file.size; progress(0) } progress(0) - const needsMaabcd = !!maabcdDandisetId && !saved.maabcdDone + const needsMaabcd = !!maabcdAggregateDandisetId && !saved.maabcdDone const { etag, parts: plan } = !saved.own || needsMaabcd ? await computeDandiEtag(file) : { etag: '', parts: [] } // 1. The researcher's own copy. @@ -94,7 +94,7 @@ export function createEmberObjectStore( if (needsMaabcd) { const osbToken = await osbAuth.getToken() const brokered = await osb.getUploadUrls(osbToken, { - dandisetId: maabcdDandisetId, filename: file.name, size: file.size, dandiEtag: etag, + dandisetId: maabcdAggregateDandisetId, filename: file.name, size: file.size, dandiEtag: etag, }) const brokeredParts = await putParts(brokered.parts, plan, file, progress) if (!brokered.parts.length) skipTransfer(); else done += file.size diff --git a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts index 2a71679..d85f06b 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -1,4 +1,4 @@ -import { DRAFT_STATUS, type IDandiDirectApi, type PublishedVersion } from '../ports/IDandiDirectApi' +import { VERSION_STATUS, type IDandiDirectApi, type PublishedVersion } from '../ports/IDandiDirectApi' import type { IEmberAuth } from '../ports/IEmberAuth' import { readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink, type DandisetMetadata } from '../dandisetLinks' import { RUN_SETTINGS } from '../runSettings' @@ -9,7 +9,7 @@ import { pollUntil } from './runProgress' export const DANDISET_LICENSE = ['spdx:CC-BY-4.0'] /** Statuses a draft can be published from (or, when Published, already was). */ -const PUBLISHABLE: string[] = [DRAFT_STATUS.valid, DRAFT_STATUS.published] +const PUBLISHABLE: string[] = [VERSION_STATUS.valid, VERSION_STATUS.published] /** Why a dandiset could not be published, for the console; the user reads the DOI step's message. */ class PublishError extends Error { @@ -102,7 +102,7 @@ export function createProtocolDandisetsUseCases(deps: { const status = await waitUntilPublishable(t, dandisetId, stopped) if (!status) return null // Unchanged since the last version: that version already holds this data. - if (status === DRAFT_STATUS.published) return latestVersion(t, dandisetId) + if (status === VERSION_STATUS.published) return latestVersion(t, dandisetId) return publishNewVersion(t, dandisetId, stopped) } @@ -116,9 +116,9 @@ export function createProtocolDandisetsUseCases(deps: { async function waitUntilPublishable(t: string, dandisetId: string, stopped: () => boolean): Promise { let status = '' const ended = await pollUntil(async () => { - const draft = await direct.getDraftStatus(t, dandisetId) - if (draft.status === DRAFT_STATUS.invalid) throw new PublishError(dandisetId, draft.errors.join('; ')) - status = draft.status + const readiness = await direct.getPublishReadiness(t, dandisetId) + if (readiness.status === VERSION_STATUS.invalid) throw new PublishError(dandisetId, readiness.errors.join('; ')) + status = readiness.status return PUBLISHABLE.includes(status) }, { everyMs: RUN_SETTINGS.publishStatusPollMs, timeoutMs: RUN_SETTINGS.publishDraftValidationTimeoutMs, stopped }) if (ended === 'timeout') throw new PublishError(dandisetId, `EMBER is still checking it (${status})`) diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 9f274a2..740fcdd 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -31,7 +31,7 @@ export interface RunProtocolDefinition { image?: string /** The protocol's MAABCD dandiset on EMBER-DANDI, which each upload is also copied into * (through OSB). Empty or absent: no MAABCD copy. */ - maabcdDandisetId?: string + maabcdAggregateDandisetId?: string } export interface RunProtocolInput { @@ -260,7 +260,7 @@ export function createRunProtocolUseCase( user: input.dandisetId, newName: `${protocol.name} (IDP)`, protocol: { id: protocol.id, name: protocol.name, url: repoPage(protocol.repoZipUrl) }, - maabcd: input.shareWithMaabcd === false ? undefined : protocol.maabcdDandisetId, + maabcd: input.shareWithMaabcd === false ? undefined : protocol.maabcdAggregateDandisetId, }, }, (sent, total) => { if (Date.now() - lastReport < RUN_SETTINGS.uploadProgressMs && sent < total) return diff --git a/applications/idp-arc/frontend/src/data/README.md b/applications/idp-arc/frontend/src/data/README.md index 700a2e7..d62a129 100644 --- a/applications/idp-arc/frontend/src/data/README.md +++ b/applications/idp-arc/frontend/src/data/README.md @@ -8,24 +8,38 @@ Field names follow the MAABCD–OSB Integration design (`id`, `repoZipUrl`, `not | Field | Used by | Meaning | |---|---|---| -| `id` | run | **Stable id, never derived from the name** (`four-choice-reversal`). Tags the workspace (`maabcd:`), prefixes the upload in the bucket and names the workspace folder its runs go in (`/run--/`). Don't change it once uploads exist. | +| `id` | run | **Stable id, chosen once** (`four-choice-reversal`). Tags the workspace (`maabcd:`), is the first folder of the upload in the researcher's dandiset and names the workspace folder its runs go in (`/run--/`). Keep it once uploads exist. | | `name` | everywhere | Display name. Free to edit. | | `description`, `imageUrl`, `videoUrl` | Protocols page | Text and media shown for the protocol. | | `repoZipUrl` | run | GitHub archive of the analysis repository, `https://codeload.github.com///zip/refs/heads/` (or `refs/tags/`, or `/zip/`). A **branch** follows the latest fixes; a **commit** freezes the code. An empty `repoZipUrl` = no analysis yet: the upload dialog doesn't offer the protocol. | | `notebooksDir` | run | Repository-relative folder of the notebooks (`notebooks`). | +| `maabcdAggregateDandisetId` | upload | The protocol's MAABCD consortium dandiset on EMBER-DANDI (`000607`): six digits, owned by the consortium account. When the researcher shares their upload, a copy goes there through OSB's `/dandi` endpoints, signed with that account's key. Leave it out and uploads for the protocol aren't shared. | | `requirements`, `pythonPath`, `install` | run | Override the repository setup below (defaults in `REPOSITORY_SETUP`, runProtocol.ts: `requirements.txt`; `["scripts"]`; `["scripts/install.py", "scripts/setup.py", "scripts/pyproject.toml"]`). OSB applies only the ones the repository has. Leave them out for a repository that follows the contract. | | `templatesZipUrl` | Protocols page, dialog | Archive of the protocol's templates (data sheets, instructions), downloaded by the **Download** buttons on the Protocols page and in the dialog's upload step. A path relative to `public/` (`protocols_archives/4c.zip`) or an absolute URL. Missing or empty = both buttons disabled. | | `inputFormats` | dialog, run | Extensions the analysis code can actually read. The dialog refuses other files before anything starts. **Without it, any file is accepted** (except an empty one, always refused). | +## Where uploads go + +Each upload goes to EMBER-DANDI, in up to two copies: + +| | Researcher's dandiset | MAABCD aggregate dandiset | +|---|---|---| +| Dandiset | picked in the dialog, or a new one | `maabcdAggregateDandisetId`, if the researcher shares | +| Path | `//` | `//` | +| Built and signed by | IDP, with the researcher's EMBER login | OSB, with the consortium's `DANDI_API_KEY` | + +`` is a random UUID, so uploads never overwrite each other. OSB builds the MAABCD path +from the caller's login, so no one can write into another's folder. + ## What happens on "Upload and run" (core/use-cases/runProtocol.ts) The button stays disabled until a file is chosen, and while that file is empty or of a format the protocol doesn't read. -1. The file goes from the browser straight to the bucket (`VITE_UPLOAD_BUCKET_URL`), as - `uploads////`. Once it has landed: the workspace (the selected one, or - a new one tagged `maabcd:`), then the repository import. No lab server is started; OSB's - import and run tasks don't need one. +1. The file goes from the browser to EMBER-DANDI: into the researcher's dandiset and, if they + share it, into the protocol's MAABCD dandiset (paths in [Where uploads go](#where-uploads-go)). + Once it has landed: the workspace (the selected one, or a new one tagged `maabcd:`), then + the repository import. 2. OSB imports both into this run's folder (`POST /workspaceresource`; names in core/workspaceLayout.ts): `/run--/-/` for the code, fresh for every run, and `…/inputs/` for the upload (a `.zip` is unpacked there). @@ -52,21 +66,21 @@ protocol doesn't read. Agreed with the protocol authors on 30 Sep 2026. These conventions live in IDP (`REPOSITORY_SETUP` and `notebooksDir`): IDP tells OSB which notebooks to run, in what order, and which setup files to -use; OSB uses the ones the repository has and assumes nothing else. +use; OSB applies the ones the repository has. 1. `requirements.txt` at the root — **optional**, installed first. Pin versions: the task image pre-installs pandas, numpy, openpyxl and matplotlib, and an unpinned requirement is satisfied by whatever version that is (four-choice broke on matplotlib 3.11, which removed `boxplot(labels=)`). 2. `scripts/` — **optional**: `scripts/install.py` is run if present, else it's pip-installed if it - is a package (`setup.py`/`pyproject.toml`); it's always on `PYTHONPATH`. A failure here doesn't - stop the run. + is a package (`setup.py`/`pyproject.toml`); it's always on `PYTHONPATH`. The run carries on if + this step fails. 3. `notebooks/` — **required**. Every visible `*.ipynb` directly in it runs, one after another, in byte order of the file name (**zero-pad the numbers**: `01_…`, `02_…`; `10_x` sorts before `2_x`), each with its own folder as working directory. The first failing notebook stops the run. 4. **Input and output: a cell tagged `parameters`** (papermill's convention) in every notebook, setting `INPUT_DIR` and `OUTPUT_DIR` to its own defaults (e.g. its example data). The notebooks read from `INPUT_DIR` and write everything they produce to `OUTPUT_DIR`; for a run, IDP passes the run's - `inputs/` and `outputs/`. A notebook without that cell isn't run. + `inputs/` and `outputs/`. A run stops at the first notebook without that cell. ## Per protocol @@ -77,26 +91,28 @@ use; OSB uses the ones the repository has and assumes nothing else. *File → Download → Microsoft Excel (.xlsx)*. - `.zip`: several such workbooks (e.g. one per animal), analysed together; files at the top level or inside one folder (what Finder/Explorer "Compress" makes). -- **Not accepted: `.csv`, `.tsv`, `.xls`, `.ods`**: the pipeline only reads `*.xlsx` with openpyxl. +- **The pipeline reads `*.xlsx` with openpyxl**, so the dialog refuses `.csv`, `.tsv`, `.xls` and `.ods`. - **Needs a `parameters` cell (not there yet):** its notebooks set `INPUT_DIR` / `OUTDIR` in their first cell without the tag, and 02/03 call `example_input_dir()` again. Until that cell is tagged and used (asked of the authors, 5 Oct 2026), runs stop with "has no cell tagged parameters". - **One workbook is one animal:** PCA and the group figures need at least two. -- **Without an upload** (not offered by the dialog) the notebooks run on the repository's own 11 - example workbooks. - Verified 2 Oct 2026 with the task image in Docker: all three notebooks in ~9 s on one workbook. ### Two arm bandit, ASST digging -No analysis repository yet (`repoZipUrl` is empty): they are shown on the site, but the upload -dialog doesn't offer them. When a repository exists, fill in `repoZipUrl` and add `notebooksDir` +Shown on the Protocols page; the upload dialog lists them once `repoZipUrl` is set (no analysis +repository yet). When a repository exists, fill in `repoZipUrl` and add `notebooksDir` and — after checking what its code reads — `inputFormats`. -## Adding or changing a protocol +## Adding a protocol -1. Check what the analysis code really reads (file types, single file vs folder, where it looks) - and set `inputFormats` to match, and check its notebooks have the `parameters` cell — don't list formats the code ignores; researchers - would only find out minutes into a run. -2. Run it once from the dialog with the sample file. +1. **Repository**: the protocol's analysis code on GitHub, in the expected standard + ([repository rules](#what-a-protocol-repository-must-look-like)). +2. **Aggregate dandiset**: on EMBER-DANDI, signed in as `maabcd` (it must own it). Name = the + protocol's name, licence CC-BY-4.0, public. Note its id (four-choice: `000607`). +3. **Files**: images in `src/assets/`, templates zip in `public/protocols_archives/`. +4. **Entry** in `protocols.json` ([Fields](#fields)). `id` is permanent: it names the workspace + tag, the dandiset folder and the run folders. +5. **This README**: a section under [Per protocol](#per-protocol). -Tunable timings of the run (time limits, polling) are in `../core/runSettings.ts`, not here. +Run timings are in `../core/runSettings.ts`. diff --git a/applications/idp-arc/frontend/src/data/protocols.json b/applications/idp-arc/frontend/src/data/protocols.json index 0488d22..5f3d3f3 100644 --- a/applications/idp-arc/frontend/src/data/protocols.json +++ b/applications/idp-arc/frontend/src/data/protocols.json @@ -4,7 +4,7 @@ "name": "Four-choice reversal digging task", "repoZipUrl": "https://codeload.github.com/maracbaylis/four-choice-example/zip/refs/heads/main", "notebooksDir": "notebooks", - "maabcdDandisetId": "000542", + "maabcdAggregateDandisetId": "000607", "inputFormats": [".xlsx", ".zip"], "templatesZipUrl": "protocols_archives/4c.zip", "description": "In the four choice reversal digging task mice must identify the single rewarded option and update their choice when a previously unrewarded option becomes rewarded. The reversal phase in this task is sensitive to orbitofrontal and dorsomedial prefrontal cortex function and the 2-day version used here provides a metric of recall on the 2nd day of testing before reversal.", diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index 32334e6..a4f4f3a 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -2,7 +2,7 @@ import type { DandisetMetadata } from '../core/dandisetLinks' import type { DirectFinalizeInput, DirectInitResult, - DraftStatus, + PublishReadiness, IDandiDirectApi, OwnDandiset, PublishedVersion, @@ -98,11 +98,11 @@ export class EmberDandiDirectClient implements IDandiDirectApi { if (!res.ok) await this.fail(res, 'draft metadata update') } - async getDraftStatus(token: string, dandisetId: string): Promise { + async getPublishReadiness(token: string, dandisetId: string): Promise { const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/info/`, { headers: this.headers(token), }) - if (!res.ok) await this.fail(res, 'draft status read') + if (!res.ok) await this.fail(res, 'publish readiness read') type Problem = { field?: string; path?: string; message: string } const body = (await res.json()) as { status: string diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index 8126063..ea56604 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -18,7 +18,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b async createDandiset() { throw new Error('created through the protocol use case') }, async getDraftMetadata() { return {} }, async updateDraftMetadata() {}, - async getDraftStatus() { return { status: 'Valid', errors: [] } }, + async getPublishReadiness() { return { status: 'Valid', errors: [] } }, async publishDraft() {}, async getLatestPublished() { return null }, async initUpload(token, dandisetId) { diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts index ff303ca..635906d 100644 --- a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -54,7 +54,7 @@ function fakeEmber(metadata: Record, publishing: { async createDandiset(_t, name, m) { created.push({ name, metadata: m }); return '000900' }, async getDraftMetadata(_t, id) { return metadata[id] ?? {} }, async updateDraftMetadata(_t, id, m) { writes.push({ id, metadata: m }) }, - async getDraftStatus() { + async getPublishReadiness() { const all = publishing.statuses ?? [{ status: 'Valid' }] const s = all[Math.min(statusReads++, all.length - 1)] calls.push(`status:${s.status}`) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index 269525f..e7a9ff7 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -313,7 +313,7 @@ test('an EMBER-DANDI upload gets the run\'s workspace recorded in its dandiset, } const states: RunState[] = [] await createRunProtocolUseCase(auth, f.api, store)( - { protocol: { ...FOUR_CHOICE, maabcdDandisetId: '000533' }, file: file(), workspaceName: 'Four-choice', dandisetId: '000123' }, + { protocol: { ...FOUR_CHOICE, maabcdAggregateDandisetId: '000533' }, file: file(), workspaceName: 'Four-choice', dandisetId: '000123' }, (s) => states.push(s)) const last = states[states.length - 1] @@ -339,7 +339,7 @@ test('with "Share with MAABCD" unticked, nothing goes to the protocol\'s MAABCD } const states: RunState[] = [] await createRunProtocolUseCase(auth, f.api, store)( - { protocol: { ...FOUR_CHOICE, maabcdDandisetId: '000533' }, file: file(), workspaceName: 'Four-choice', shareWithMaabcd: false }, + { protocol: { ...FOUR_CHOICE, maabcdAggregateDandisetId: '000533' }, file: file(), workspaceName: 'Four-choice', shareWithMaabcd: false }, (s) => states.push(s)) assert.equal(states[states.length - 1].phase, 'succeeded') From a3c923a6e9ce7d4a18f403f850df40b2413cceab Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Thu, 22 Oct 2026 12:59:14 +0530 Subject: [PATCH 17/32] IDP-52: publish once EMBER has checked every file --- .../src/components/DataUploadDialog.tsx | 18 ++++--- .../src/core/ports/IDandiDirectApi.ts | 4 +- .../src/core/use-cases/emberObjectStore.ts | 37 ++++++++------ .../src/core/use-cases/protocolDandisets.ts | 24 +++++++-- .../src/core/use-cases/runProtocol.ts | 2 + .../idp-arc/frontend/src/core/userMessages.ts | 3 ++ .../src/infra/emberDandiDirectClient.ts | 8 ++- .../frontend/tests/unit/emberClients.test.ts | 23 +++++++++ .../tests/unit/emberObjectStore.test.ts | 20 +++++--- .../tests/unit/protocolDandisets.test.ts | 50 +++++++++++++++++-- 10 files changed, 145 insertions(+), 44 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index e905fb1..ba23bb5 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -22,14 +22,14 @@ import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' -import { EMBER_SIGN_IN, userMessage } from '../core/userMessages' +import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages' import { useAppContext } from '../AppContext' import { RUN_STEP, type RunCheckpoint, type RunStep } from '../core/types' import RunChecklist from './RunChecklist' import { createSessionStore, useSessionStore } from './sessionStore' import DoiField from './DoiField' import { inputFileProblem, inputFormatsFor } from '../core/inputFormats' -import { canResume, PUBLISH_STEP } from '../core/use-cases/runProtocol' +import { canResume, PUBLISH_STEP, PUBLISHING_LABEL } from '../core/use-cases/runProtocol' import { formatBytes } from '../core/formatBytes' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' import { SIGN_IN_AGAIN } from '../core/userMessages' @@ -62,6 +62,8 @@ step: DialogStep doi?: { doi: string } /** That publish is under way, or failed (it can be retried). */ publishing?: 'running' | 'failed' + /** Why the publish failed, for the user. */ + publishError?: string /** The run's checklist (upload, imports, run), as last reported by the use-case. */ runSteps: RunStep[] /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ @@ -100,7 +102,7 @@ let currentWatch: { current: boolean } | null = null export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() const [form] = useSessionStore(session) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi, publishing, checkpoint } = form + const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps, dandisetId, shareWithMaabcd, doi, publishing, publishError, checkpoint } = form // EMBER-DANDI: the upload goes to the researcher's own account. Choosing a protocol lists their // dandisets for it, each with the workspace it runs in, so choosing one chooses both. const usesEmber = UPLOAD_BACKEND === 'ember' @@ -141,8 +143,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const finished = step === 'success' || step === 'stillRunning' // Publishing joins the run's checklist once the researcher starts it. const publishStep: RunStep | null = - publishing === 'running' ? { ...PUBLISH_STEP, state: 'running' } - : publishing === 'failed' ? { ...PUBLISH_STEP, state: 'failed', detail: userMessage(undefined, RUN_STEP.doi) } + publishing === 'running' ? { ...PUBLISH_STEP, label: PUBLISHING_LABEL, state: 'running' } + : publishing === 'failed' ? { ...PUBLISH_STEP, state: 'failed', detail: publishError ?? userMessage(undefined, RUN_STEP.doi) } : doi ? { ...PUBLISH_STEP, state: 'succeeded' } : null const checklist = publishStep ? [...runSteps, publishStep] : runSteps @@ -260,13 +262,13 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut /** "Publish dandiset": the researcher's dandiset as a new, permanent version. Optional. */ const publish = async () => { if (!dandisetId) return - setForm((prev) => ({ ...prev, publishing: 'running' })) + setForm((prev) => ({ ...prev, publishing: 'running', publishError: undefined })) try { const published = await publishDandiset(dandisetId) setForm((prev) => ({ ...prev, publishing: published ? undefined : 'failed', doi: published ?? prev.doi })) } catch (err) { - console.error('Publishing the dandiset failed', err) - setForm((prev) => ({ ...prev, publishing: 'failed' })) + console.error('Publishing the dandiset failed', err instanceof UserFacingError && err.details ? err.details : err) + setForm((prev) => ({ ...prev, publishing: 'failed', publishError: userMessage(err, RUN_STEP.doi) })) } } diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts index b0b7d97..d4c767b 100644 --- a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -72,8 +72,10 @@ export const VERSION_STATUS = { export interface PublishReadiness { /** The draft's VERSION_STATUS, or a status EMBER reports while it is still checking. */ status: string - /** Why it can't be published, one line per problem; empty unless `Invalid`. */ + /** Why it can't be published, one line per problem: the dandiset's metadata, or a file's. */ errors: string[] + /** Files EMBER hasn't checked yet. Publishing needs every file checked, even on a `Valid` draft. */ + filesBeingChecked: number } /** A published (frozen) version of a dandiset. */ diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index 696fd90..d2ce069 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -90,22 +90,29 @@ export function createEmberObjectStore( save({ own: { assetId: asset.assetId, assetPath: asset.assetPath } }) } - // 2. The MAABCD copy, through OSB. + // 2. The MAABCD copy, through OSB. It doesn't hold up the researcher's run: a failure here + // (OSB's key or configuration, EMBER) is ours to fix, so it is logged and the run goes on. if (needsMaabcd) { - const osbToken = await osbAuth.getToken() - const brokered = await osb.getUploadUrls(osbToken, { - dandisetId: maabcdAggregateDandisetId, filename: file.name, size: file.size, dandiEtag: etag, - }) - const brokeredParts = await putParts(brokered.parts, plan, file, progress) - if (!brokered.parts.length) skipTransfer(); else done += file.size - await osb.validateUpload(osbToken, { - dandisetId: brokered.dandisetId, - path: brokered.path, - uploadId: brokered.uploadId, - parts: brokered.blobId ? undefined : brokeredParts, - blobId: brokered.blobId, - }) - save({ maabcdDone: true }) + try { + const osbToken = await osbAuth.getToken() + const brokered = await osb.getUploadUrls(osbToken, { + dandisetId: maabcdAggregateDandisetId, filename: file.name, size: file.size, dandiEtag: etag, + }) + const brokeredParts = await putParts(brokered.parts, plan, file, progress) + if (!brokered.parts.length) skipTransfer(); else done += file.size + await osb.validateUpload(osbToken, { + dandisetId: brokered.dandisetId, + path: brokered.path, + uploadId: brokered.uploadId, + parts: brokered.blobId ? undefined : brokeredParts, + blobId: brokered.blobId, + }) + save({ maabcdDone: true }) + } catch (err) { + // TODO: report to Sentry once the frontend has it, so a failed copy is noticed. + console.error(`Not shared with MAABCD dandiset ${maabcdAggregateDandisetId}`, err) + skipTransfer() + } } progress(0) diff --git a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts index d85f06b..5016429 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -2,7 +2,7 @@ import { VERSION_STATUS, type IDandiDirectApi, type PublishedVersion } from '../ import type { IEmberAuth } from '../ports/IEmberAuth' import { readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink, type DandisetMetadata } from '../dandisetLinks' import { RUN_SETTINGS } from '../runSettings' -import { EMBER_SIGN_IN, UserFacingError } from '../userMessages' +import { DANDISET_NOT_PUBLISHABLE, EMBER_SIGN_IN, UserFacingError } from '../userMessages' import { pollUntil } from './runProgress' /** The license of the dandisets IDP creates. EMBER publishes no dandiset without one. */ @@ -112,19 +112,33 @@ export function createProtocolDandisetsUseCases(deps: { if (!metadata.license) await direct.updateDraftMetadata(t, dandisetId, { ...metadata, license: DANDISET_LICENSE }) } - /** Waits for EMBER to finish checking the draft; its status, or null if `stopped`. */ + /** + * Waits for EMBER to finish checking the draft and every file in it; the draft's status, or null + * if `stopped`. Stops at once, with EMBER's reasons for the user, when it can't be published. + */ async function waitUntilPublishable(t: string, dandisetId: string, stopped: () => boolean): Promise { let status = '' const ended = await pollUntil(async () => { const readiness = await direct.getPublishReadiness(t, dandisetId) - if (readiness.status === VERSION_STATUS.invalid) throw new PublishError(dandisetId, readiness.errors.join('; ')) status = readiness.status - return PUBLISHABLE.includes(status) + // Invalid, or Valid with an invalid file: EMBER would refuse the publish. + if (status === VERSION_STATUS.invalid || (status === VERSION_STATUS.valid && readiness.errors.length)) { + throw notPublishable(readiness.errors) + } + return PUBLISHABLE.includes(status) && readiness.filesBeingChecked === 0 }, { everyMs: RUN_SETTINGS.publishStatusPollMs, timeoutMs: RUN_SETTINGS.publishDraftValidationTimeoutMs, stopped }) - if (ended === 'timeout') throw new PublishError(dandisetId, `EMBER is still checking it (${status})`) + if (ended === 'timeout') { + throw new UserFacingError('EMBER-DANDI is still checking your dandiset. Please try again in a few minutes.', + `Dandiset ${dandisetId}: still ${status} after the wait`) + } return ended === 'done' ? status : null } + /** The user is told it can't be published; EMBER's reasons go to the console (its editor shows them too). */ + function notPublishable(errors: string[]): UserFacingError { + return new UserFacingError(DANDISET_NOT_PUBLISHABLE, errors.join('\n')) + } + /** Publishes the draft, then waits for the new version and its DOI. */ async function publishNewVersion(t: string, dandisetId: string, stopped: () => boolean): Promise { const previous = (await direct.getLatestPublished(t, dandisetId))?.version diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 740fcdd..41b22c1 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -100,6 +100,8 @@ const STEPS = [ /** Not part of the run: the dialog adds it once the researcher publishes the dandiset. */ export const PUBLISH_STEP = { id: RUN_STEP.doi, label: 'Publish your dandiset' } +/** PUBLISH_STEP's label while it runs. */ +export const PUBLISHING_LABEL = 'Publishing your dandiset' /** * Runs a protocol on the researcher's data. Before anything moves, the protocol and the file are diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 467bf47..1cb1ae2 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -28,6 +28,9 @@ const STEP_FAILED: Record = { * which sends the user to the OSB (Keycloak) login instead. */ export const EMBER_SIGN_IN = 'Please sign in with EMBER-DANDI and try again.' +/** EMBER refuses to publish the dandiset as it is (its metadata or a file); EMBER's editor says what to fix. */ +export const DANDISET_NOT_PUBLISHABLE = "This dandiset can't be published yet. Check on EMBER-DANDI on specific errors." + /** Says the session has ended; the dialog sends the user to sign in when the text contains it. */ export const SIGN_IN_AGAIN = 'sign in again' diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index a4f4f3a..ed6bf42 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -109,9 +109,13 @@ export class EmberDandiDirectClient implements IDandiDirectApi { version_validation_errors?: Problem[] asset_validation_errors?: Problem[] } - const errors = [...(body.version_validation_errors ?? []), ...(body.asset_validation_errors ?? [])] + // EMBER lists files it hasn't checked yet among the file errors, with this message + // (dandi-archive, Version.asset_validation_errors). + const beingChecked = (e: Problem) => /currently being validated/i.test(e.message) + const assetProblems = body.asset_validation_errors ?? [] + const errors = [...(body.version_validation_errors ?? []), ...assetProblems.filter((e) => !beingChecked(e))] .map((e) => [e.path || e.field, e.message].filter(Boolean).join(': ')) - return { status: body.status, errors } + return { status: body.status, errors, filesBeingChecked: assetProblems.filter(beingChecked).length } } async publishDraft(token: string, dandisetId: string): Promise { diff --git a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts index 4874658..a893e93 100644 --- a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -71,3 +71,26 @@ test('publishing sends a JSON body, which newer DANDI releases require', async ( assert.equal(requests[0].headers['Content-Type'], 'application/json') assert.deepEqual(requests[0].body, {}) }) + +test('publish readiness separates files EMBER is still checking from real problems', async () => { + const requests = recordFetch(() => ({ + json: { + status: 'Valid', + version_validation_errors: [{ field: 'assetsSummary', message: 'A Dandiset containing no files or zero bytes is not publishable' }], + asset_validation_errors: [ + { field: '', message: 'asset is currently being validated, please wait.', path: 'p/u/a.xlsx' }, + { field: 'contentSize', message: 'is required', path: 'p/u/b.xlsx' }, + ], + }, + })) + const ember = new EmberDandiDirectClient('/ember-proxy') + + const readiness = await ember.getPublishReadiness('ember-token', '000777') + + assert.equal(requests[0].url, '/ember-proxy/api/dandisets/000777/versions/draft/info/') + assert.deepEqual(readiness, { + status: 'Valid', + errors: ['assetsSummary: A Dandiset containing no files or zero bytes is not publishable', 'p/u/b.xlsx: is required'], + filesBeingChecked: 1, + }) +}) diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index ea56604..859eada 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -18,7 +18,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b async createDandiset() { throw new Error('created through the protocol use case') }, async getDraftMetadata() { return {} }, async updateDraftMetadata() {}, - async getPublishReadiness() { return { status: 'Valid', errors: [] } }, + async getPublishReadiness() { return { status: 'Valid', errors: [], filesBeingChecked: 0 } }, async publishDraft() {}, async getLatestPublished() { return null }, async initUpload(token, dandisetId) { @@ -104,13 +104,15 @@ test('deduplicated content moves no bytes and registers against the existing blo assert.ok(calls.includes('osb-validate:000533:blob-1')) }) -test('a part list that does not cover the file is refused before anything is uploaded', async () => { +test('a part list that does not cover the file is refused before any of it is uploaded', async () => { const { calls, store } = fakes({ shortParts: true }) - await assert.rejects( - store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }), - /2 part URLs for a file of 1 parts/, - ) + const checkpoints: Record[] = [] + await store().put({ + file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, + onCheckpoint: (c) => checkpoints.push(c as Record), + }) assert.ok(!calls.includes('put:https://s3/a')) + assert.ok(!checkpoints.at(-1)?.maabcdDone, 'the MAABCD copy is not counted as made') }) test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sign in', async () => { @@ -124,14 +126,16 @@ test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sig // ── Retry: carrying on from the checkpoint ─────────────────────────────────────────────────── -test('a retry after the MAABCD copy failed makes only that copy', async () => { +test('a failed MAABCD copy lets the run go on, and a later retry makes only that copy', async () => { const { calls, store } = fakes({ failOsbOnce: true }) const checkpoints: unknown[] = [] const input = { file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, onCheckpoint: (c: unknown) => checkpoints.push(c), } - await assert.rejects(store().put(input), /HTTP 503/) + // The failed copy doesn't stop the upload: the researcher's copy is returned for the run. + const first = await store().put(input) + assert.equal(first.url, `${ORIGIN}/api/assets/asset-1/download/`) const resume = checkpoints.at(-1) as Record assert.deepEqual(resume, { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: (resume.own as { assetPath: string }).assetPath } }) calls.length = 0 diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts index 635906d..0ee5e4f 100644 --- a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -7,6 +7,7 @@ import { } from '../../src/core/dandisetLinks' import { createProtocolDandisetsUseCases, DANDISET_LICENSE } from '../../src/core/use-cases/protocolDandisets' import { RUN_SETTINGS } from '../../src/core/runSettings' +import { DANDISET_NOT_PUBLISHABLE, UserFacingError } from '../../src/core/userMessages' import type { IDandiDirectApi } from '../../src/core/ports/IDandiDirectApi' const DEV = 'v2dev.opensourcebrain.org' @@ -41,7 +42,7 @@ test('a workspace link only counts in its own OSB environment', () => { /** `statuses`: what each draft-status read returns, in turn (the last one repeats). `versions`: * what each latest-version read returns, in turn. */ function fakeEmber(metadata: Record, publishing: { - statuses?: { status: string; errors?: string[] }[] + statuses?: { status: string; errors?: string[]; filesBeingChecked?: number }[] versions?: ({ version: string; doi?: string; url?: string } | null)[] } = {}) { const calls: string[] = [] @@ -58,7 +59,7 @@ function fakeEmber(metadata: Record, publishing: { const all = publishing.statuses ?? [{ status: 'Valid' }] const s = all[Math.min(statusReads++, all.length - 1)] calls.push(`status:${s.status}`) - return { status: s.status, errors: s.errors ?? [] } + return { status: s.status, errors: s.errors ?? [], filesBeingChecked: s.filesBeingChecked ?? 0 } }, async publishDraft(_t, id) { calls.push(`publish:${id}`) }, async getLatestPublished() { @@ -147,13 +148,52 @@ test('a dandiset without a license gets one before publishing', async () => { assert.deepEqual(writes, [{ id: '000777', metadata: { name: 'Mine', license: DANDISET_LICENSE } }]) }) -test('an invalid draft is not published, and says why', async () => { +test('an invalid draft is not published; EMBER\'s reason goes to the console', async () => { fastPolls() - const { uc, calls } = fakeEmber({ '000777': { license: ['x'] } }, { statuses: [{ status: 'Invalid', errors: ["contributor: is required"] }] }) - await assert.rejects(uc.publish('000777'), /could not be published: contributor: is required/) + const { uc, calls } = fakeEmber({ '000777': { license: ['x'] } }, { + statuses: [{ status: 'Invalid', errors: ['assetsSummary: A Dandiset containing no files or zero bytes is not publishable'] }], + }) + await assert.rejects(uc.publish('000777'), (err: Error) => { + assert.ok(err instanceof UserFacingError) + assert.equal(err.message, DANDISET_NOT_PUBLISHABLE) + assert.match((err as UserFacingError).details ?? '', /assetsSummary: A Dandiset containing no files/) + return true + }) assert.ok(!calls.some((c) => c.startsWith('publish:'))) }) +test('a valid draft waits until EMBER has checked every file', async () => { + fastPolls() + const { uc, calls } = fakeEmber({ '000777': { license: ['x'] } }, { + statuses: [{ status: 'Valid', filesBeingChecked: 2 }, { status: 'Valid', filesBeingChecked: 1 }, { status: 'Valid' }], + versions: [null, { version: '0.261010.1200', doi: 'd' }], + }) + await uc.publish('000777') + assert.deepEqual(calls, ['status:Valid', 'status:Valid', 'status:Valid', 'publish:000777']) +}) + +test('a valid draft with an invalid file is not published; the console names the file', async () => { + fastPolls() + const { uc, calls } = fakeEmber({ '000777': { license: ['x'] } }, { + statuses: [{ status: 'Valid', errors: ['protocol/u/f.xlsx: contentSize: is required'] }], + }) + await assert.rejects(uc.publish('000777'), (err: Error) => + err instanceof UserFacingError && err.message === DANDISET_NOT_PUBLISHABLE && /protocol\/u\/f\.xlsx: contentSize/.test(err.details ?? '')) + assert.ok(!calls.some((c) => c.startsWith('publish:'))) +}) + +test('a check that never finishes says so, so the user can try later', async () => { + fastPolls() + const timeout = RUN_SETTINGS.publishDraftValidationTimeoutMs + RUN_SETTINGS.publishDraftValidationTimeoutMs = 20 + try { + const { uc } = fakeEmber({ '000777': { license: ['x'] } }, { statuses: [{ status: 'Validating' }] }) + await assert.rejects(uc.publish('000777'), (err: Error) => err instanceof UserFacingError && /still checking your dandiset/.test(err.message)) + } finally { + RUN_SETTINGS.publishDraftValidationTimeoutMs = timeout + } +}) + test('a draft unchanged since its last version returns that version instead of publishing again', async () => { fastPolls() const { uc, calls } = fakeEmber({ '000777': { license: ['x'] } }, { From a42476e0dc509a9de339a930be334e8cd8aa4087 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 14:12:37 +0530 Subject: [PATCH 18/32] IDP-51: popup detection, bucket-mode login, tighter EMBER proxy paths --- applications/idp-arc/deploy/resources/default.conf | 13 +++++++++++-- applications/idp-arc/frontend/src/App.tsx | 7 ++++--- .../idp-arc/frontend/src/components/PageLayout.tsx | 14 ++++++++------ .../idp-arc/frontend/src/components/loginReturn.ts | 7 +++++++ applications/idp-arc/frontend/vite.config.ts | 3 ++- 5 files changed, 32 insertions(+), 12 deletions(-) diff --git a/applications/idp-arc/deploy/resources/default.conf b/applications/idp-arc/deploy/resources/default.conf index 75a5cfa..b4506a9 100644 --- a/applications/idp-arc/deploy/resources/default.conf +++ b/applications/idp-arc/deploy/resources/default.conf @@ -10,11 +10,20 @@ server { # EMBER's POST /oauth/token/ reply has no CORS header, so the browser can't read the login token # from it directly; through this same-origin proxy it can. (File bytes go straight to S3, not here.) - location /ember-proxy/ { - proxy_pass https://api-dandi.emberarchive.org/; + # Only what the app calls: the token exchange and the REST API. Anything else under it is refused. + location /ember-proxy/oauth/token/ { + proxy_pass https://api-dandi.emberarchive.org/oauth/token/; + proxy_ssl_server_name on; + proxy_set_header Host api-dandi.emberarchive.org; + } + location /ember-proxy/api/ { + proxy_pass https://api-dandi.emberarchive.org/api/; proxy_ssl_server_name on; proxy_set_header Host api-dandi.emberarchive.org; } + location /ember-proxy/ { + return 404; + } location ~* \.(js|css|png|jpg|jpeg|gif|svg|ico|webp|woff2?)$ { try_files $uri =404; diff --git a/applications/idp-arc/frontend/src/App.tsx b/applications/idp-arc/frontend/src/App.tsx index bf3a061..e88bb8b 100644 --- a/applications/idp-arc/frontend/src/App.tsx +++ b/applications/idp-arc/frontend/src/App.tsx @@ -16,14 +16,15 @@ import Workspaces from './pages/Workspaces' import ProtocolsPage from './pages/ProtocolsPage' import AboutPage from './pages/AboutPage' import EmberCallback from './pages/EmberCallback' +import { OSB_LOGIN_POPUP_NAME } from './components/loginReturn' /** * This window is OSB's (Keycloak) login popup, sent back here once the user has signed in. It only * finishes the sign-in, hands it to the main tab and closes; it never shows the app (it would * otherwise reopen the Login dialog: a popup starts with a copy of its opener's sessionStorage). - * EMBER-DANDI's popup has no `window.opener` (COOP) and is handled on its callback route. + * Told by its window name (OSB_LOGIN_POPUP_NAME). EMBER-DANDI's popup is handled on its callback route. */ -const IN_OSB_LOGIN_POPUP = typeof window !== 'undefined' && !!window.opener +const IN_OSB_LOGIN_POPUP = typeof window !== 'undefined' && window.name === OSB_LOGIN_POPUP_NAME && window.location.pathname !== EMBER_CALLBACK_PATH /** What the OSB login popup shows while it finishes the sign-in and closes itself. */ @@ -84,7 +85,7 @@ function App() { .init() .then((authenticated: boolean) => { // If running inside the login popup, signal the parent and close. - if (authenticated && window.opener) { + if (authenticated && IN_OSB_LOGIN_POPUP && window.opener) { window.opener.postMessage({ type: 'keycloak-login-complete' }, window.location.origin) window.close() return diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 422b617..38df3c6 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -20,13 +20,13 @@ import type { ReactNode } from 'react' import { useEffect, useState } from 'react' import { useTranslation } from 'react-i18next' import { useLocation, useNavigate } from 'react-router-dom' -import { authClient, emberAuth, MY_DANDISETS_URL, OSB_WORKSPACES_URL } from '../app/container' +import { authClient, emberAuth, MY_DANDISETS_URL, OSB_WORKSPACES_URL, UPLOAD_BACKEND } from '../app/container' import { useAppContext } from '../AppContext' import { Logo } from '../Icons' import DataUploadDialog from './DataUploadDialog' import { registerUploadOpener } from './UploadContext' import LoginDialog from './LoginDialog' -import { takeLoginDialogReturn } from './loginReturn' +import { OSB_LOGIN_POPUP_NAME, takeLoginDialogReturn } from './loginReturn' const ArrowIcon = () => @@ -83,7 +83,7 @@ export default function PageLayout({ const w = 480, h = 600 const left = Math.round((screen.width - w) / 2) const top = Math.round((screen.height - h) / 2) - const popup = window.open(loginUrl, 'kc-login', `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`) + const popup = window.open(loginUrl, OSB_LOGIN_POPUP_NAME, `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`) if (!popup) { authClient.login() return null @@ -107,9 +107,11 @@ export default function PageLayout({ // replaced, as a dev hot reload does) without authState hearing of it. const osbSignedIn = isAuthenticated && authClient.tokenParsed !== null // Uploading needs both logins: EMBER-DANDI (where the data goes) and OSB (where it is analysed). + // When uploads go to the bucket instead (UPLOAD_BACKEND), OSB's alone. // EMBER's popup sign-in doesn't reload the page, so it updates this state. + const needsEmber = UPLOAD_BACKEND === 'ember' const [emberSignedIn, setEmberSignedIn] = useState(() => emberAuth.isConnected()) - const loginsDone = osbSignedIn && emberSignedIn && emberAuth.isConnected() + const loginsDone = osbSignedIn && (!needsEmber || (emberSignedIn && emberAuth.isConnected())) /** * Whether each login still holds, checked now rather than as of the page load: an EMBER token * expires, and an OSB session can end without the page knowing until a token is asked for (the @@ -119,13 +121,13 @@ export default function PageLayout({ const ember = emberAuth.isConnected() setEmberSignedIn(ember) const osb = osbSignedIn && await authClient.getToken().then(() => true, () => false) - return ember && osb + return (!needsEmber || ember) && osb } const openLoginDialog = () => { void checkLogins() setLoginDialogOpen(true) } - /** Every "Data upload" button: the upload dialog when both logins hold, else the Login dialog. */ + /** Every "Data upload" button: the upload dialog when the logins it needs hold, else the Login dialog. */ const openUploadOrLogin = async (protocolName?: string) => { if (!(await checkLogins())) return setLoginDialogOpen(true) setUploadProtocol(protocolName) diff --git a/applications/idp-arc/frontend/src/components/loginReturn.ts b/applications/idp-arc/frontend/src/components/loginReturn.ts index f332b17..f4fd3e0 100644 --- a/applications/idp-arc/frontend/src/components/loginReturn.ts +++ b/applications/idp-arc/frontend/src/components/loginReturn.ts @@ -29,3 +29,10 @@ export function takeLoginDialogReturn(): boolean { return false } } + +/** + * The window name PageLayout opens OSB's login popup with. It stays the window's name while the + * popup goes to Keycloak and back, so App.tsx can tell it is that popup; `window.opener` can't + * tell, since any tab opened by script without `noopener` (from an OSB page, say) has one too. + */ +export const OSB_LOGIN_POPUP_NAME = 'kc-login' diff --git a/applications/idp-arc/frontend/vite.config.ts b/applications/idp-arc/frontend/vite.config.ts index ffa4d0b..f6ef672 100644 --- a/applications/idp-arc/frontend/vite.config.ts +++ b/applications/idp-arc/frontend/vite.config.ts @@ -66,7 +66,8 @@ export default defineConfig({ changeOrigin: true, rewrite: (path) => path.replace(/^\/api-proxy/, ''), }, - '/ember-proxy': { + // Only what the app calls, as in the deployed nginx (deploy/resources/default.conf). + '^/ember-proxy/(oauth/token/|api/)': { target: EMBER_ORIGIN, changeOrigin: true, rewrite: (path) => path.replace(/^\/ember-proxy/, ''), From 0fb039ad53d08d326a097e72fdd331bd8d7bbc6d Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 14:45:27 +0530 Subject: [PATCH 19/32] IDP-51: check each recorded workspace instead of listing the first page --- .../idp-arc/frontend/src/app/container.ts | 6 ++++-- .../frontend/src/components/loginReturn.ts | 7 +++---- .../frontend/src/core/ports/IEmberAuth.ts | 2 +- .../frontend/src/core/ports/IWorkspaceApi.ts | 5 +++++ .../src/core/use-cases/protocolDandisets.ts | 21 ++++++++++++------- .../frontend/src/infra/emberOAuthClient.ts | 9 ++++---- .../src/infra/mocks/mockWorkspaceApiClient.ts | 5 +++++ .../frontend/src/infra/workspaceApiClient.ts | 11 ++++++++++ .../tests/unit/protocolDandisets.test.ts | 17 ++++++++++++++- .../frontend/tests/unit/runProtocol.test.ts | 1 + 10 files changed, 63 insertions(+), 21 deletions(-) diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index a05a492..a3df222 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -102,8 +102,10 @@ export const runProtocol = createRunProtocolUseCase(authClient, workspaceApi, ob /** The researcher's EMBER-DANDI dandisets for a protocol, each with the workspace it runs in when * they still have it: what the upload dialog offers once a protocol is chosen. */ export async function listProtocolDandisets(protocolId: string): Promise { - const ownWorkspaceIds = (await loadWorkspaces()).map((w) => Number(w.id)) - return protocolDandisets.listForProtocol(protocolId, ownWorkspaceIds) + const token = await authClient.getToken() + const me = authClient.tokenParsed?.sub + return protocolDandisets.listForProtocol(protocolId, + async (workspaceId) => !!me && (await workspaceApi.getWorkspaceOwner(token, workspaceId)) === me) } export type { ProtocolDandiset } diff --git a/applications/idp-arc/frontend/src/components/loginReturn.ts b/applications/idp-arc/frontend/src/components/loginReturn.ts index f4fd3e0..dacbbf9 100644 --- a/applications/idp-arc/frontend/src/components/loginReturn.ts +++ b/applications/idp-arc/frontend/src/components/loginReturn.ts @@ -1,9 +1,8 @@ /** * Reopens the Login dialog after a login took the user away from the page: EMBER-DANDI's sign-in - * is a full-page redirect (emberOAuthClient.ts's connect(); a popup can't work, see - * .vscode/knowledge-base/ember-oauth-popup-and-coop.md), and the OSB popup's login reloads this - * page when it completes (App.tsx). Either way the dialog is unmounted, so it is marked here and - * reopened on arrival, showing what is still left to sign in to. + * redirects the whole page when its popup is blocked (emberOAuthClient.ts's connect()), and the OSB + * popup's login reloads this page when it completes (App.tsx). Either way the dialog is unmounted, + * so it is marked here and reopened on arrival, showing what is still left to sign in to. * * Lives in its own module rather than in LoginDialog because exporting non-components from a * component file breaks React Fast Refresh. diff --git a/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts index 4058345..abf7e59 100644 --- a/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts +++ b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts @@ -12,7 +12,7 @@ * * connectInPopup() is the usual flow; connect() is a full-page redirect for when the popup is * blocked, so callers with UI state to preserve persist it first (components/loginReturn.ts). - * Why the popup works the way it does: .vscode/knowledge-base/ember-oauth-popup-and-coop.md. + * Why the popup works the way it does: EmberOAuthClient.connectInPopup(). */ export interface IEmberAuth { /** True when a usable (non-expired) access token is held. */ diff --git a/applications/idp-arc/frontend/src/core/ports/IWorkspaceApi.ts b/applications/idp-arc/frontend/src/core/ports/IWorkspaceApi.ts index e7a8bed..e15d582 100644 --- a/applications/idp-arc/frontend/src/core/ports/IWorkspaceApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IWorkspaceApi.ts @@ -60,6 +60,11 @@ export interface IWorkspaceApi { */ createWorkspace(token: string, name: string, tags?: string[]): Promise + /** Who owns the workspace (their Keycloak `sub`, `GET /workspace/{id}`); null when it is gone or + * the user may not see it. OSB also shows public workspaces to anyone, so seeing one doesn't make + * it the user's. */ + getWorkspaceOwner(token: string, workspaceId: number): Promise + /** The workspace's resources (`GET /workspace/{id}`). */ getWorkspaceResources(token: string, workspaceId: number): Promise diff --git a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts index 5016429..9297849 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -55,10 +55,12 @@ export function createProtocolDandisetsUseCases(deps: { /** * The researcher's dandisets recorded for `protocolId`, each with its workspace. One metadata - * read per dandiset they own (EMBER's list carries no metadata). A workspace link is dropped - * when it isn't among `ownWorkspaceIds` (deleted, or someone else's): a new one is made then. + * read per dandiset they own (EMBER's list carries no metadata). A workspace link is kept only + * when `ownsWorkspace` says the workspace is still the researcher's (not deleted, not someone + * else's); otherwise a new one is made. It is asked once per recorded workspace, so how many + * workspaces they have doesn't matter. */ - async function listForProtocol(protocolId: string, ownWorkspaceIds: number[]): Promise { + async function listForProtocol(protocolId: string, ownsWorkspace: (workspaceId: number) => Promise): Promise { const t = token() const own = await direct.listOwnDandisets(t) const read = await Promise.all(own.map(async (d) => { @@ -69,12 +71,15 @@ export function createProtocolDandisetsUseCases(deps: { return null } })) - return read + const forProtocol = read .filter((r): r is { d: (typeof own)[number]; metadata: DandisetMetadata } => !!r && readProtocolLink(r.metadata) === protocolId) - .map(({ d, metadata }) => { - const linked = readWorkspaceLink(metadata, osbDomain) - return { id: d.id, name: d.name, ...(linked && ownWorkspaceIds.includes(linked) ? { workspaceId: linked } : {}) } - }) + .map(({ d, metadata }) => ({ d, linked: readWorkspaceLink(metadata, osbDomain) })) + // Several dandisets can record the same workspace: each is checked once. + const owned = new Map>() + for (const { linked } of forProtocol) if (linked && !owned.has(linked)) owned.set(linked, ownsWorkspace(linked)) + return Promise.all(forProtocol.map(async ({ d, linked }) => ({ + id: d.id, name: d.name, ...(linked && await owned.get(linked) ? { workspaceId: linked } : {}), + }))) } /** A new dandiset in the researcher's account, recorded for `protocol`. */ diff --git a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts index 968dd16..10a2bdb 100644 --- a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts @@ -185,11 +185,10 @@ export class EmberOAuthClient implements IEmberAuth { * * EMBER's /oauth/authorize/ sends `Cross-Origin-Opener-Policy: same-origin`, which cuts the * popup off from this window both ways: `window.opener` is null in it, and `popup.closed` reads - * true here even while it is open. So nothing here relies on that link - * (.vscode/knowledge-base/ember-oauth-popup-and-coop.md). EMBER sends the popup back to - * EMBER_CALLBACK_PATH on this origin; that page sees the popup `state` and hands the code over a - * BroadcastChannel (relayPopupCallback). This tab, which holds the PKCE verifier, swaps it for the - * token. It can't see the popup being closed, so `cancel()` and a timeout end the wait. + * true here even while it is open. So nothing here relies on that link. EMBER sends the popup + * back to EMBER_CALLBACK_PATH on this origin; that page sees the popup `state` and hands the code + * over a BroadcastChannel (relayPopupCallback). This tab, which holds the PKCE verifier, swaps it + * for the token. It can't see the popup being closed, so `cancel()` and a timeout end the wait. * * The popup is opened synchronously, inside the click, so browsers don't block it; EMBER's URL * is set once the PKCE challenge is ready. Throws EmberPopupBlocked when it can't be opened. diff --git a/applications/idp-arc/frontend/src/infra/mocks/mockWorkspaceApiClient.ts b/applications/idp-arc/frontend/src/infra/mocks/mockWorkspaceApiClient.ts index a7a1e16..2fa3a0f 100644 --- a/applications/idp-arc/frontend/src/infra/mocks/mockWorkspaceApiClient.ts +++ b/applications/idp-arc/frontend/src/infra/mocks/mockWorkspaceApiClient.ts @@ -68,6 +68,11 @@ export class MockWorkspaceApiClient implements IWorkspaceApi { private runPolls = 0 private runCount = 0 + async getWorkspaceOwner(_token: string, workspaceId: number): Promise { + await delay(100) + return MOCK_WORKSPACES.some((w) => Number(w.id) === workspaceId) ? 'mock-user-id' : null + } + async getWorkspaceResources(_token: string, _workspaceId: number): Promise { await delay(200) this.imports.forEach((i) => { i.pendingPolls -= 1 }) diff --git a/applications/idp-arc/frontend/src/infra/workspaceApiClient.ts b/applications/idp-arc/frontend/src/infra/workspaceApiClient.ts index 29e1996..9c04d70 100644 --- a/applications/idp-arc/frontend/src/infra/workspaceApiClient.ts +++ b/applications/idp-arc/frontend/src/infra/workspaceApiClient.ts @@ -81,6 +81,17 @@ export class WorkspaceApiClient implements IWorkspaceApi { throw lastError } + async getWorkspaceOwner(token: string, workspaceId: number): Promise { + const res = await fetch(`${this.baseApiUrl}/workspace/${workspaceId}`, { + headers: { Authorization: `Bearer ${token}` }, + }) + // Deleted, or private to someone else (OSB answers 403 for that). + if (res.status === 404 || res.status === 403) return null + if (!res.ok) throw new Error(`Reading workspace ${workspaceId} failed: ${res.status} ${res.statusText}`) + const ws = (await res.json()) as { user_id?: string } + return ws.user_id ?? null + } + async getWorkspaceResources(token: string, workspaceId: number): Promise { const res = await fetch(`${this.baseApiUrl}/workspace/${workspaceId}`, { headers: { Authorization: `Bearer ${token}` }, diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts index 0ee5e4f..eee2653 100644 --- a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -84,12 +84,27 @@ test('lists only the dandisets recorded for the protocol, with the workspaces th '000004': {}, // not an IDP dandiset }) - const list = await uc.listForProtocol('four-choice-reversal', [42, 7]) + const asked: number[] = [] + const list = await uc.listForProtocol('four-choice-reversal', async (id) => { asked.push(id); return id === 42 }) assert.deepEqual(list, [ { id: '000001', name: 'set 000001', workspaceId: 42 }, { id: '000002', name: 'set 000002' }, ]) + // Only the protocol's recorded workspaces are checked, not every workspace the user has. + assert.deepEqual(asked.sort(), [42, 99]) +}) + +test('a workspace recorded in several dandisets is checked once', async () => { + const { uc } = fakeEmber({ + '000001': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), + '000002': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), + }) + const asked: number[] = [] + const list = await uc.listForProtocol('four-choice-reversal', async (id) => { asked.push(id); return true }) + + assert.deepEqual(list.map((d) => d.workspaceId), [42, 42]) + assert.deepEqual(asked, [42]) }) test('a new dandiset is created already recorded for its protocol', async () => { diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index e7a9ff7..89271c0 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -39,6 +39,7 @@ function fakes(opts: { runPolls?: number; importPolls?: number; failUpload?: boo let runPollsLeft = 0 const api: IWorkspaceApi = { async listWorkspaces() { return [] }, + async getWorkspaceOwner() { return null }, async createWorkspace(_t, name, tags) { calls.push(`create:${name}:${tags?.join(',')}`); return 42 }, async getWorkspaceResources() { if (runPollsLeft > 0) { runPollsLeft -= 1; return [{ id: -1, name: 'Refreshing resources' }] } From eac97ff6205cec240dc74a6125a75f983df7d2bc Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 15:00:28 +0530 Subject: [PATCH 20/32] IDP-51: fix EMBER api link to const; read every page of the user's dandisets --- .../idp-arc/frontend/src/app/container.ts | 8 ++--- .../src/infra/emberDandiDirectClient.ts | 31 ++++++++++++------- .../idp-arc/frontend/src/infra/emberUrls.ts | 4 +-- .../frontend/tests/unit/emberClients.test.ts | 31 +++++++++++++++++++ applications/idp-arc/frontend/vite.config.ts | 9 ++---- 5 files changed, 58 insertions(+), 25 deletions(-) diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index a3df222..0cc63ad 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -22,7 +22,7 @@ import { PublicBucketObjectStore } from '../infra/publicBucketObjectStore' import { EmberOAuthClient, EMBER_CALLBACK_PATH } from '../infra/emberOAuthClient' import { EmberDandiDirectClient } from '../infra/emberDandiDirectClient' import { EmberUploadApiClient } from '../infra/emberUploadApiClient' -import { EMBER_API_ORIGIN_DEFAULT, EMBER_WEB_ORIGIN } from '../infra/emberUrls' +import { EMBER_API_ORIGIN, EMBER_WEB_ORIGIN } from '../infra/emberUrls' import type { IObjectStore } from '../core/ports/IObjectStore' import { createEmberObjectStore } from '../core/use-cases/emberObjectStore' import { createProtocolDandisetsUseCases, type ProtocolDandiset } from '../core/use-cases/protocolDandisets' @@ -48,8 +48,6 @@ export const UPLOAD_BACKEND = 'ember' as 'bucket' | 'ember' * protocol's MAABCD dandiset, and the DANDI deployment it goes to (dandi-cli's name). */ const MAABCD_EMBER_USERNAME = 'maabcd-consortium' const MAABCD_DANDI_INSTANCE = 'ember-dandi' -/** EMBER-DANDI's API origin: where the OAuth login goes, and what OSB downloads assets from. */ -const EMBER_ORIGIN = (import.meta.env.VITE_EMBER_ORIGIN ?? EMBER_API_ORIGIN_DEFAULT).replace(/\/+$/, '') /** Same-origin path for the browser's own EMBER calls (Vite proxy in dev, nginx deployed): EMBER's * token response carries no CORS headers. */ const EMBER_FETCH_BASE = '/ember-proxy' @@ -69,7 +67,7 @@ const workspaceApi = new WorkspaceApiClient(WORKSPACES_API, WORKSPACES_LIST_URL) /** Signs the researcher in to EMBER-DANDI (OAuth in a popup, a full-page redirect if it is blocked); * their token stays in the browser. */ export const emberAuth = new EmberOAuthClient({ - authOrigin: EMBER_ORIGIN, + authOrigin: EMBER_API_ORIGIN, apiBase: EMBER_FETCH_BASE, clientId: import.meta.env.VITE_EMBER_CLIENT_ID ?? '', redirectUri: `${window.location.origin}${EMBER_CALLBACK_PATH}`, @@ -84,7 +82,7 @@ const protocolDandisets = createProtocolDandisetsUseCases({ /** Where uploads go before OSB imports them (UPLOAD_BACKEND): EMBER-DANDI, or the public bucket. */ export const objectStore: IObjectStore = UPLOAD_BACKEND === 'ember' - ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_ORIGIN) + ? createEmberObjectStore(authClient, emberAuth, emberDirect, new EmberUploadApiClient(WORKSPACES_API, MAABCD_DANDI_INSTANCE, MAABCD_EMBER_USERNAME), protocolDandisets, EMBER_API_ORIGIN) : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) // ─── Use-cases (injected with their concrete dependencies) ──────────────────── diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index ed6bf42..10ccbbe 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -16,6 +16,9 @@ import type { */ export const ALLOW_EMBARGOED = false +/** Dandisets per page of the researcher's list. */ +const DANDISET_PAGE_SIZE = 100 + /** * Talks to EMBER-DANDI's REST API directly from the browser, with the researcher's OAuth token. * @@ -49,18 +52,22 @@ export class EmberDandiDirectClient implements IDandiDirectApi { // `empty=true` keeps a dandiset that has no assets yet in the list; embargoed ones need // `embargoed=true` (see ALLOW_EMBARGOED). const embargoed = ALLOW_EMBARGOED ? '&embargoed=true' : '' - const res = await fetch( - `${this.baseUrl}/api/dandisets/?user=me${embargoed}&empty=true&page_size=100`, - { headers: this.headers(token) }, - ) - if (!res.ok) await this.fail(res, 'dandiset list') - const body = await res.json() - return (body.results ?? []).map( - (d: { identifier: string; draft_version?: { name?: string } }) => ({ - id: d.identifier, - name: d.draft_version?.name ?? d.identifier, - }), - ) + const dandisets: OwnDandiset[] = [] + // Page by page until we have as many as EMBER's `count` says. + let total = Infinity + for (let page = 1; dandisets.length < total; page++) { + const res = await fetch( + `${this.baseUrl}/api/dandisets/?user=me${embargoed}&empty=true&page_size=${DANDISET_PAGE_SIZE}&page=${page}`, + { headers: this.headers(token) }, + ) + if (!res.ok) await this.fail(res, 'dandiset list') + const body = await res.json() + const results: { identifier: string; draft_version?: { name?: string } }[] = body.results ?? [] + dandisets.push(...results.map((d) => ({ id: d.identifier, name: d.draft_version?.name ?? d.identifier }))) + total = Number(body.count) || 0 + if (!results.length) break + } + return dandisets } async createDandiset(token: string, name: string, metadata: DandisetMetadata = {}): Promise { diff --git a/applications/idp-arc/frontend/src/infra/emberUrls.ts b/applications/idp-arc/frontend/src/infra/emberUrls.ts index 27db919..a5ce025 100644 --- a/applications/idp-arc/frontend/src/infra/emberUrls.ts +++ b/applications/idp-arc/frontend/src/infra/emberUrls.ts @@ -1,3 +1,3 @@ -/** EMBER-DANDI's two public origins: its API (`api-dandi…`) and the web UI people browse (`dandi…`). */ -export const EMBER_API_ORIGIN_DEFAULT = 'https://api-dandi.emberarchive.org' +/** EMBER-DANDI's API and web UI. Production only: the proxies and OSB's MAABCD copy use it too. */ +export const EMBER_API_ORIGIN = 'https://api-dandi.emberarchive.org' export const EMBER_WEB_ORIGIN = 'https://dandi.emberarchive.org' diff --git a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts index a893e93..c75abd9 100644 --- a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -94,3 +94,34 @@ test('publish readiness separates files EMBER is still checking from real proble filesBeingChecked: 1, }) }) + +test('the dandiset list reads as many pages as EMBER\'s count says, through the proxy', async () => { + const page = (from: number, n: number) => Array.from({ length: n }, (_, i) => ({ identifier: String(from + i).padStart(6, '0') })) + const requests = recordFetch((url) => (url.endsWith('&page=1') + ? { json: { count: 150, results: [{ identifier: '000000', draft_version: { name: 'First' } }, ...page(1, 99)] } } + : { json: { count: 150, results: page(100, 50) } })) + const list = await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token') + + assert.equal(list.length, 150) + assert.deepEqual(list[0], { id: '000000', name: 'First' }) + assert.deepEqual(list.at(-1), { id: '000149', name: '000149' }) + assert.equal(requests.length, 2) + assert.ok(requests.every((r) => r.url.startsWith('/ember-proxy/api/dandisets/?user=me'))) + assert.match(requests[1].url, /page_size=100&page=2$/) +}) + +test('one page when the count fits in it, none more for an empty account', async () => { + let requests = recordFetch(() => ({ json: { count: 1, results: [{ identifier: '000001' }] } })) + await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token') + assert.equal(requests.length, 1) + + requests = recordFetch(() => ({ json: { count: 0, results: [] } })) + assert.deepEqual(await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token'), []) + assert.equal(requests.length, 1) +}) + +test('an empty page ends the list early', async () => { + const requests = recordFetch(() => ({ json: { count: 5000, results: [] } })) + await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token') + assert.equal(requests.length, 1) +}) diff --git a/applications/idp-arc/frontend/vite.config.ts b/applications/idp-arc/frontend/vite.config.ts index f6ef672..29c3518 100644 --- a/applications/idp-arc/frontend/vite.config.ts +++ b/applications/idp-arc/frontend/vite.config.ts @@ -4,6 +4,7 @@ import path from 'path' import fs from 'node:fs' import http from 'node:http' import https from 'node:https' +import { EMBER_API_ORIGIN } from './src/infra/emberUrls' // Must use loadEnv(), not process.env — Vite doesn't load .env into process.env for this // file, so process.env here silently falls back to the production domain. @@ -30,10 +31,6 @@ function loadDevHttpsCerts(): { key: Buffer; cert: Buffer } | undefined { } const devHttps = loadDevHttpsCerts() -// EMBER-DANDI's API: the browser's own EMBER calls go through /ember-proxy, because EMBER's -// OAuth token response carries no CORS headers. Deployed, nginx does the same (default.conf). -const EMBER_ORIGIN = env.VITE_EMBER_ORIGIN || 'https://api-dandi.emberarchive.org' - // eslint-disable-next-line no-console console.log(`[vite] proxying OSB -> ${OSB_WEB_ORIGIN}`) @@ -66,9 +63,9 @@ export default defineConfig({ changeOrigin: true, rewrite: (path) => path.replace(/^\/api-proxy/, ''), }, - // Only what the app calls, as in the deployed nginx (deploy/resources/default.conf). + // EMBER's token reply has no CORS headers. Only what the app calls, as nginx (default.conf). '^/ember-proxy/(oauth/token/|api/)': { - target: EMBER_ORIGIN, + target: EMBER_API_ORIGIN, changeOrigin: true, rewrite: (path) => path.replace(/^\/ember-proxy/, ''), }, From c24a990b6ab7162b94757c79a01de86ff946b42f Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 16:01:19 +0530 Subject: [PATCH 21/32] IDP-51: share with MAABCD as its own step, with Retry --- .../src/components/DataUploadDialog.tsx | 32 +++++++- .../frontend/src/components/RunChecklist.tsx | 6 +- .../frontend/src/core/ports/IObjectStore.ts | 2 + .../idp-arc/frontend/src/core/types.ts | 3 + .../src/core/use-cases/emberObjectStore.ts | 68 +++++++--------- .../src/core/use-cases/runProgress.ts | 6 ++ .../src/core/use-cases/runProtocol.ts | 29 ++++++- .../idp-arc/frontend/src/core/userMessages.ts | 1 + .../tests/unit/emberObjectStore.test.ts | 60 ++++++--------- .../frontend/tests/unit/runProtocol.test.ts | 77 ++++++++++++++++++- 10 files changed, 197 insertions(+), 87 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index ba23bb5..54eab85 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -24,12 +24,12 @@ import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages' import { useAppContext } from '../AppContext' -import { RUN_STEP, type RunCheckpoint, type RunStep } from '../core/types' +import { RUN_STEP, type RunCheckpoint, type RunStep, type RunStepId } from '../core/types' import RunChecklist from './RunChecklist' import { createSessionStore, useSessionStore } from './sessionStore' import DoiField from './DoiField' import { inputFileProblem, inputFormatsFor } from '../core/inputFormats' -import { canResume, PUBLISH_STEP, PUBLISHING_LABEL } from '../core/use-cases/runProtocol' +import { canResume, PUBLISH_STEP, PUBLISHING_LABEL, retryMaabcdCopy } from '../core/use-cases/runProtocol' import { formatBytes } from '../core/formatBytes' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' import { SIGN_IN_AGAIN } from '../core/userMessages' @@ -99,6 +99,11 @@ const setForm = session.set /** The run being watched; each run gets its own token, so stopping one never revives another. */ let currentWatch: { current: boolean } | null = null +/** `steps`, with one step changed. */ +function withStep(steps: RunStep[], id: RunStepId, change: Partial): RunStep[] { + return steps.map((s) => (s.id === id ? { ...s, ...change } : s)) +} + export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() const [form] = useSessionStore(session) @@ -148,6 +153,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut : doi ? { ...PUBLISH_STEP, state: 'succeeded' } : null const checklist = publishStep ? [...runSteps, publishStep] : runSteps + // Once the run has ended, so its reports can't overwrite what the Retry shows. + const canRetryShare = step !== 'uploading' && runSteps.some((s) => s.id === RUN_STEP.maabcd && s.state === 'failed') useEffect(() => { if (open && finished) setForm((prev) => (prev.resultSeen ? prev : { ...prev, resultSeen: true })) }, [open, finished]) @@ -272,6 +279,20 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut } } + /** The MAABCD step's Retry: only the copy is tried again. */ + const retryShare = async () => { + if (!checkpoint) return + const share = (change: Partial) => (prev: FormState) => ({ ...prev, runSteps: withStep(prev.runSteps, RUN_STEP.maabcd, change) }) + setForm(share({ state: 'running', detail: undefined })) + try { + const next = await retryMaabcdCopy(checkpoint) + setForm((prev) => ({ ...share({ state: 'succeeded' })(prev), checkpoint: next })) + } catch (err) { + console.error('Not shared with the MAABCD consortium', err) + setForm(share({ state: 'failed', detail: userMessage(err, RUN_STEP.maabcd) })) + } + } + // "Retry" only when an earlier attempt can be carried on (same protocol, file, dandiset and // sharing choice); choosing a dandiset that already has a workspace is still a new run. const resumable = !!selectedProtocol && canResume(checkpoint, { @@ -586,7 +607,12 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut )} - {checklist.length > 0 && } + {checklist.length > 0 && ( + Retry } : {}} + /> + )} {/* Optional, after the run: publishing is the researcher's choice (they can also do it on EMBER). */} {finished && usesEmber && dandisetId && publishing !== 'running' && ( diff --git a/applications/idp-arc/frontend/src/components/RunChecklist.tsx b/applications/idp-arc/frontend/src/components/RunChecklist.tsx index 5bb851a..9f41ca4 100644 --- a/applications/idp-arc/frontend/src/components/RunChecklist.tsx +++ b/applications/idp-arc/frontend/src/components/RunChecklist.tsx @@ -4,7 +4,8 @@ import RadioButtonUncheckedIcon from '@mui/icons-material/RadioButtonUnchecked' import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import RemoveCircleOutlineIcon from '@mui/icons-material/RemoveCircleOutlineOutlined' -import type { RunStep, StepState } from '../core/types' +import type { ReactNode } from 'react' +import type { RunStep, RunStepId, StepState } from '../core/types' const STEP_ICON_SX = { fontSize: 20, flexShrink: 0, mt: '1px' } @@ -24,7 +25,7 @@ function StepIcon({ state }: { state: StepState }) { } /** One line per stage of the run: workspace, storage, server, then the run's own stages and notebooks. */ -export default function RunChecklist({ steps }: { steps: RunStep[] }) { +export default function RunChecklist({ steps, actions = {} }: { steps: RunStep[]; actions?: Partial> }) { return ( {steps.map((s) => ( @@ -39,6 +40,7 @@ export default function RunChecklist({ steps }: { steps: RunStep[] }) { {s.detail} )} + {actions[s.id]} ))} diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index 8d00586..d40a248 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -38,6 +38,8 @@ export interface StoredObject { dandisetId?: string /** EMBER-DANDI: records the run's workspace in the dandiset's metadata. */ recordWorkspace?: (workspaceId: number) => Promise + /** EMBER-DANDI, when a MAABCD copy was asked for: makes that copy. Safe to call again (Retry). */ + shareWithMaabcd?: () => Promise } export interface IObjectStore { diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index 2002cd0..b9cab60 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -36,6 +36,7 @@ export type RunPhase = /** The run's steps, in order: their ids in the checklist (runProtocol's STEPS). */ export const RUN_STEP = { upload: 'upload', + maabcd: 'maabcd', workspace: 'workspace', repo: 'repo', data: 'data', @@ -93,4 +94,6 @@ export interface RunCheckpoint { runFolderAt?: string repoImported?: boolean dataImported?: boolean + /** The copy for the MAABCD consortium is made. */ + maabcdShared?: boolean } diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index d2ce069..48145d4 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -10,20 +10,12 @@ import type { ProtocolDandisets } from './protocolDandisets' export { EMBER_SIGN_IN } /** - * The EMBER-DANDI object store. Each file is uploaded twice: + * The EMBER-DANDI object store. `put` uploads into the researcher's own dandiset (the copy OSB + * imports); `recordWorkspace` then records the workspace in its metadata. `shareWithMaabcd` makes a + * second copy, into the protocol's MAABCD dandiset, through OSB's `/dandi` endpoints. * - * 1. into the researcher's own dandiset, from the browser with their EMBER token. This is the - * copy OSB imports into their workspace; `recordWorkspace` then writes that workspace into - * the dandiset's metadata, so the next upload for the protocol finds both; - * 2. into the protocol's MAABCD dandiset (protocols.json `maabcdAggregateDandisetId`), through OSB's - * `/dandi` endpoints (instance `ember-dandi`), which sign with the MAABCD account's key. - * Skipped when the protocol has none, or the researcher chose not to share. - * - * The browser sends the bytes both times. The second transfer is usually empty: EMBER stores each - * content once, and answers with the existing blob instead of parts. - * - * Each finished part is reported as a checkpoint (EmberUploadCheckpoint): given back on a retry, - * the dandiset is not created again and a copy already made is not made again. + * Each finished part of `put` is reported as a checkpoint (EmberUploadCheckpoint): given back on a + * retry, the dandiset is not created again and a copy already made is not made again. * * No wait for "valid" before returning: the blob is checked against the etag when the upload is * validated (synchronously, before the asset exists), so its download link works at once. @@ -35,8 +27,6 @@ export interface EmberUploadCheckpoint { userDandisetId?: string /** Their own copy, once registered. */ own?: { assetId: string; assetPath: string } - /** The MAABCD copy is registered. */ - maabcdDone?: boolean } export function createEmberObjectStore( @@ -61,45 +51,42 @@ export function createEmberObjectStore( input.onCheckpoint?.({ ...saved }) } - // Bytes counted across both transfers, so the progress bar runs once from 0 to 100%; a copy - // made by an earlier attempt counts as sent. - const transfers = maabcdAggregateDandisetId ? 2 : 1 - const total = file.size * transfers - let done = (saved.own ? file.size : 0) + (maabcdAggregateDandisetId && saved.maabcdDone ? file.size : 0) - const progress = (sentInTransfer: number) => onProgress?.(Math.min(done + sentInTransfer, total), total) - const skipTransfer = () => { done += file.size; progress(0) } - progress(0) + const progress = (sent: number) => onProgress?.(Math.min(sent, file.size), file.size) + progress(saved.own ? file.size : 0) + // The file's DANDI etag and part plan, computed once for both copies. + let hashed: Promise<{ etag: string; parts: PartPlan[] }> | undefined + const hash = () => (hashed ??= computeDandiEtag(file)) - const needsMaabcd = !!maabcdAggregateDandisetId && !saved.maabcdDone - const { etag, parts: plan } = !saved.own || needsMaabcd ? await computeDandiEtag(file) : { etag: '', parts: [] } - - // 1. The researcher's own copy. + // The researcher's own copy. const protocol = input.dandisets?.protocol ?? { id: input.protocolId, name: input.protocolId } const userDandisetId = saved.userDandisetId || input.dandisets?.user || await dandisets.createForProtocol(input.dandisets?.newName || `IDP upload: ${protocol.name}`, protocol) if (saved.userDandisetId !== userDandisetId) save({ userDandisetId }) let asset = saved.own if (!asset) { + const { etag, parts: plan } = await hash() const path = `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` const init = await direct.initUpload(token, userDandisetId, file.size, etag) const uploaded = await putParts(init.parts, plan, file, progress) - if (!init.parts.length) skipTransfer(); else done += file.size asset = await direct.finalizeUpload(token, { uploadId: init.uploadId, dandisetId: userDandisetId, path, parts: uploaded, blobId: init.blobId, }) save({ own: { assetId: asset.assetId, assetPath: asset.assetPath } }) } + progress(file.size) - // 2. The MAABCD copy, through OSB. It doesn't hold up the researcher's run: a failure here - // (OSB's key or configuration, EMBER) is ours to fix, so it is logged and the run goes on. - if (needsMaabcd) { - try { + // The MAABCD copy, through OSB: one attempt at a time, and not again once made. + let shared = false + let sharing: Promise | undefined + const shareWithMaabcd = () => { + if (shared) return Promise.resolve() + sharing ??= (async () => { + const { etag, parts: plan } = await hash() const osbToken = await osbAuth.getToken() const brokered = await osb.getUploadUrls(osbToken, { - dandisetId: maabcdAggregateDandisetId, filename: file.name, size: file.size, dandiEtag: etag, + dandisetId: maabcdAggregateDandisetId!, filename: file.name, size: file.size, dandiEtag: etag, }) - const brokeredParts = await putParts(brokered.parts, plan, file, progress) - if (!brokered.parts.length) skipTransfer(); else done += file.size + const brokeredParts = await putParts(brokered.parts, plan, file, () => {}) await osb.validateUpload(osbToken, { dandisetId: brokered.dandisetId, path: brokered.path, @@ -107,20 +94,17 @@ export function createEmberObjectStore( parts: brokered.blobId ? undefined : brokeredParts, blobId: brokered.blobId, }) - save({ maabcdDone: true }) - } catch (err) { - // TODO: report to Sentry once the frontend has it, so a failed copy is noticed. - console.error(`Not shared with MAABCD dandiset ${maabcdAggregateDandisetId}`, err) - skipTransfer() - } + shared = true + })().finally(() => { sharing = undefined }) + return sharing } - progress(0) return { url: `${emberApiOrigin.replace(/\/+$/, '')}/api/assets/${asset.assetId}/download/`, key: asset.assetPath, dandisetId: userDandisetId, recordWorkspace: (workspaceId: number) => dandisets.recordWorkspace(userDandisetId, workspaceId, protocol), + ...(maabcdAggregateDandisetId ? { shareWithMaabcd } : {}), } async function putParts(parts: { partNumber: number; url: string }[], plan: PartPlan[], file: File, diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts index 7ee15f3..be530fc 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts @@ -61,6 +61,12 @@ export class RunProgress { this.set(id, 'skipped', detail) } + /** A step fails without stopping the run. */ + failStep(id: RunStepId, detail?: string) { + if (this.ended) return + this.set(id, 'failed', detail) + } + /** The run ends well. */ finish(message: string) { if (this.ended) return diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 41b22c1..c5adf0a 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -6,7 +6,7 @@ import { formatBytes } from '../formatBytes' import { inputFileProblem } from '../inputFormats' import { parseRepoZipUrl, repoPage } from '../protocolRepo' import { RUN_SETTINGS } from '../runSettings' -import { UserFacingError } from '../userMessages' +import { UserFacingError, userMessage } from '../userMessages' import { workspaceLayout } from '../workspaceLayout' import { inStep, pollUntil, RunProgress, type OnRunState } from './runProgress' @@ -91,6 +91,7 @@ const NEW_RUN_FOLDER: Partial = { runFolderAt: undefined, repoImp const STEPS = [ { id: RUN_STEP.upload, label: 'Upload your file' }, + { id: RUN_STEP.maabcd, label: 'Share with the MAABCD consortium' }, { id: RUN_STEP.workspace, label: 'Get the workspace ready' }, { id: RUN_STEP.repo, label: 'Import the analysis code' }, { id: RUN_STEP.data, label: 'Import your data' }, @@ -168,6 +169,8 @@ export function createRunProtocolUseCase( progress.skip(RUN_STEP.upload) progress.skip(RUN_STEP.data) } + const sharesCopy = !!file && input.shareWithMaabcd !== false && !!protocol.maabcdAggregateDandisetId + if (!sharesCopy) progress.skip(RUN_STEP.maabcd) progress.emit('Starting…') // 1. Upload the file straight to the bucket. Nothing else starts until it has landed. @@ -179,6 +182,8 @@ export function createRunProtocolUseCase( stored = await inStep(RUN_STEP.upload, () => uploadFile(file, userId)) save({ stored }) } + // The MAABCD copy: its own step, which never stops the run. + if (sharesCopy) await shareWithMaabcd(stored) if (stopped()) return // 2. Get the workspace: the selected one, or a new one, recorded in the dandiset's metadata so @@ -276,6 +281,22 @@ export function createRunProtocolUseCase( return stored } + /** The MAABCD copy's step; a failure is left for its Retry. */ + async function shareWithMaabcd(stored: StoredObject | null) { + if (!stored?.shareWithMaabcd) return + if (checkpoint.maabcdShared) return doneEarlier(RUN_STEP.maabcd) + progress.start(RUN_STEP.maabcd, 'uploading', 'Sharing with the MAABCD consortium…') + try { + await stored.shareWithMaabcd() + save({ maabcdShared: true }) + progress.done(RUN_STEP.maabcd) + } catch (err) { + // TODO: report to Sentry once the frontend has it. + console.error('Not shared with the MAABCD consortium', err) + progress.failStep(RUN_STEP.maabcd, userMessage(err, RUN_STEP.maabcd)) + } + } + /** Step 2. */ async function prepareWorkspace(): Promise { progress.start(RUN_STEP.workspace, 'workspace', 'Getting the workspace ready…') @@ -402,3 +423,9 @@ export function createRunProtocolUseCase( } } } + +/** The MAABCD step's Retry: tries only the copy again. Rejects if it fails again. */ +export async function retryMaabcdCopy(checkpoint: RunCheckpoint): Promise { + await checkpoint.stored?.shareWithMaabcd?.() + return { ...checkpoint, maabcdShared: true } +} diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 1cb1ae2..02736bc 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -16,6 +16,7 @@ export class UserFacingError extends Error { const STEP_FAILED: Record = { [RUN_STEP.upload]: 'Your file could not be uploaded. Check your connection and try again.', + [RUN_STEP.maabcd]: 'Not shared with the MAABCD consortium. Retry to try again.', [RUN_STEP.workspace]: 'The workspace could not be prepared. Please try again.', [RUN_STEP.repo]: 'The analysis code could not be added to the workspace. Please try again.', [RUN_STEP.data]: 'Your file could not be added to the workspace. Please try again.', diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index 859eada..193d3ee 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -55,7 +55,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b return { calls, store } } -test('uploads to the picked dandiset directly, then to the MAABCD dandiset through OSB', async () => { +test('uploads to the picked dandiset directly; the MAABCD copy is a separate call, through OSB', async () => { const { calls, store } = fakes() const progress: number[] = [] const stored = await store().put({ @@ -63,14 +63,9 @@ test('uploads to the picked dandiset directly, then to the MAABCD dandiset throu dandisets: { user: '000123', maabcd: '000533' }, }, (sent, total) => progress.push(sent / total)) - assert.deepEqual(calls, [ - 'direct-init:ember-token:000123', - 'put:https://s3/direct', - 'direct-finalize:000123:up-1:etag-direct', - 'osb-urls:osb-token:000533:animal 01.xlsx:true', - 'put:https://s3/osb', - 'osb-validate:000533:etag-osb', - ]) + assert.deepEqual(calls, ['direct-init:ember-token:000123', 'put:https://s3/direct', 'direct-finalize:000123:up-1:etag-direct']) + await stored.shareWithMaabcd?.() + assert.deepEqual(calls.slice(3), ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) // The run imports the researcher's own copy, from EMBER's public origin (not the browser's proxy). assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) assert.match(stored.key, /^four-choice-reversal\/[0-9a-f-]{36}\/animal-01\.xlsx$/) @@ -89,6 +84,7 @@ test('creates the dandiset for the protocol when none was picked, and skips OSB assert.equal(calls[0], 'create:ASST (IDP):asst') assert.equal(calls[1], 'direct-init:ember-token:000777') assert.ok(!calls.some((c) => c.startsWith('osb-'))) + assert.equal(stored.shareWithMaabcd, undefined, 'no MAABCD copy to make') // The run records its workspace in the dandiset it uploaded into. assert.equal(stored.dandisetId, '000777') await stored.recordWorkspace?.(42) @@ -97,7 +93,8 @@ test('creates the dandiset for the protocol when none was picked, and skips OSB test('deduplicated content moves no bytes and registers against the existing blob', async () => { const { calls, store } = fakes({ dedupDirect: true, dedupOsb: true }) - await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + await stored.shareWithMaabcd?.() assert.ok(!calls.some((c) => c.startsWith('put:'))) assert.ok(calls.includes('direct-finalize:000123:dedup:')) @@ -106,13 +103,9 @@ test('deduplicated content moves no bytes and registers against the existing blo test('a part list that does not cover the file is refused before any of it is uploaded', async () => { const { calls, store } = fakes({ shortParts: true }) - const checkpoints: Record[] = [] - await store().put({ - file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, - onCheckpoint: (c) => checkpoints.push(c as Record), - }) + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + await assert.rejects(stored.shareWithMaabcd!(), /part URLs/) assert.ok(!calls.includes('put:https://s3/a')) - assert.ok(!checkpoints.at(-1)?.maabcdDone, 'the MAABCD copy is not counted as made') }) test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sign in', async () => { @@ -126,29 +119,24 @@ test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sig // ── Retry: carrying on from the checkpoint ─────────────────────────────────────────────────── -test('a failed MAABCD copy lets the run go on, and a later retry makes only that copy', async () => { +test('a failed MAABCD copy rejects on its own; calling it again makes only that copy', async () => { const { calls, store } = fakes({ failOsbOnce: true }) - const checkpoints: unknown[] = [] - const input = { - file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, - onCheckpoint: (c: unknown) => checkpoints.push(c), - } - // The failed copy doesn't stop the upload: the researcher's copy is returned for the run. - const first = await store().put(input) - assert.equal(first.url, `${ORIGIN}/api/assets/asset-1/download/`) - const resume = checkpoints.at(-1) as Record - assert.deepEqual(resume, { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: (resume.own as { assetPath: string }).assetPath } }) + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + await assert.rejects(stored.shareWithMaabcd!(), /503/) calls.length = 0 - const progress: number[] = [] - const stored = await store().put({ ...input, resume }, (sent, total) => progress.push(sent / total)) - + await stored.shareWithMaabcd!() assert.deepEqual(calls, ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) - // Still the researcher's own copy that the run imports. - assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) - assert.equal(progress[0], 0.5, 'the copy made earlier counts as sent') - assert.equal(progress.at(-1), 1) - assert.deepEqual(checkpoints.at(-1), { ...resume, maabcdDone: true }) + calls.length = 0 + await stored.shareWithMaabcd!() + assert.deepEqual(calls, [], 'not made twice') +}) + +test('two calls at once make one copy', async () => { + const { calls, store } = fakes() + const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + await Promise.all([stored.shareWithMaabcd!(), stored.shareWithMaabcd!()]) + assert.equal(calls.filter((c) => c.startsWith('osb-validate')).length, 1) }) test('a retry after the own copy failed reuses the dandiset it created', async () => { @@ -170,7 +158,7 @@ test('a retry after the own copy failed reuses the dandiset it created', async ( test('a retry with everything done makes no copy at all', async () => { const { calls, store } = fakes() - const resume = { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: 'p/x/f' }, maabcdDone: true } + const resume = { userDandisetId: '000123', own: { assetId: 'asset-1', assetPath: 'p/x/f' } } const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' }, resume }) assert.deepEqual(calls, []) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index 89271c0..90e85a5 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -1,7 +1,7 @@ // The run (core/use-cases/runProtocol.ts) against in-memory ports. Run: yarn test:unit import { test, beforeEach } from 'node:test' import assert from 'node:assert/strict' -import { canResume, createRunProtocolUseCase } from '../../src/core/use-cases/runProtocol' +import { canResume, createRunProtocolUseCase, retryMaabcdCopy } from '../../src/core/use-cases/runProtocol' import { RUN_SETTINGS } from '../../src/core/runSettings' import type { IWorkspaceApi, ImportResourceInput, StartRunInput, WorkspaceResourceState } from '../../src/core/ports/IWorkspaceApi' import type { IObjectStore } from '../../src/core/ports/IObjectStore' @@ -88,7 +88,8 @@ test('uploads, imports both into the run folder, waits, runs, and reports the ru assert.equal(last.phase, 'succeeded', last.error) assert.equal(last.workspaceId, 42) - assert.deepEqual(last.steps.map((s) => s.state), Array(6).fill('succeeded')) + // No MAABCD dandiset for this protocol: that step is skipped. + assert.deepEqual(last.steps.map((s) => s.state), ['succeeded', 'skipped', ...Array(5).fill('succeeded')]) assert.ok(f.calls.includes('create:Four-choice:maabcd:four-choice-reversal')) // /run--/: the code and the upload, imported into the run's folder. @@ -162,7 +163,7 @@ test('without a file: no upload, no data import, the notebooks run on the exampl assert.equal(last.phase, 'succeeded') assert.deepEqual(f.imports.map((i) => i.resourceType), ['g']) assert.equal(f.runInput()?.inputDir, undefined) - assert.deepEqual(last.steps.filter((s) => s.state === 'skipped').map((s) => s.id), ['upload', 'data']) + assert.deepEqual(last.steps.filter((s) => s.state === 'skipped').map((s) => s.id), ['upload', 'maabcd', 'data']) }) test('a failed upload marks only the upload step failed', async () => { @@ -347,6 +348,76 @@ test('with "Share with MAABCD" unticked, nothing goes to the protocol\'s MAABCD assert.equal(seen.dandisets?.maabcd, undefined) }) +/** A store whose MAABCD copy fails the first `fails` times. */ +function sharingStore(fails = 0) { + let attempts = 0 + const store: IObjectStore = { + async put() { + return { + url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777', + shareWithMaabcd: async () => { + attempts += 1 + if (attempts <= fails) throw new Error('OSB get_upload_urls failed (HTTP 503)') + }, + } + }, + } + return { store, attempts: () => attempts } +} +/** A run whose upload is also copied to MAABCD; the same file each time, as the dialog keeps it. */ +const shared = () => ({ protocol: { ...FOUR_CHOICE, maabcdAggregateDandisetId: '000533' }, file: data, workspaceName: 'Four-choice' }) +const maabcdStep = (s?: RunState) => s?.steps.find((x) => x.id === 'maabcd') + +test('a failed MAABCD copy fails only its own step; its Retry makes only the copy', async () => { + const f = fakes() + const { store, attempts } = sharingStore(1) + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)(shared(), (s) => states.push(s)) + const last = states.at(-1)! + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(maabcdStep(last)?.state, 'failed') + assert.match(maabcdStep(last)?.detail ?? '', /Not shared with the MAABCD consortium/) + + const runs = count(f.calls, 'run') + const next = await retryMaabcdCopy(last.checkpoint!) + assert.equal(next.maabcdShared, true) + assert.equal(attempts(), 2) + assert.equal(count(f.calls, 'run'), runs, 'nothing else runs again') +}) + +test('the MAABCD copy is made before the workspace is prepared', async () => { + const f = fakes() + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, sharingStore().store)(shared(), (s) => states.push(s)) + const preparing = states.find((s) => s.steps.find((x) => x.id === 'workspace')?.state === 'running') + assert.equal(maabcdStep(preparing)?.state, 'succeeded') + assert.equal(states.at(-1)?.phase, 'succeeded') + assert.equal(states.at(-1)?.checkpoint?.maabcdShared, true) +}) + +test('a failure elsewhere leaves the MAABCD step alone, and a run Retry shows it done earlier', async () => { + const f = fakes({ runFails: 'notebook' }) + const { store, attempts } = sharingStore() + const states: RunState[] = [] + const runProtocol = createRunProtocolUseCase(auth, f.api, store) + await runProtocol(shared(), (s) => states.push(s)) + const first = states.at(-1)! + assert.equal(first.phase, 'failed') + assert.equal(maabcdStep(first)?.state, 'succeeded') + + await runProtocol({ ...shared(), workspaceId: first.workspaceId, resume: first.checkpoint }, (s) => states.push(s)) + assert.equal(maabcdStep(states.at(-1))?.detail, 'Done earlier') + assert.equal(attempts(), 1) +}) + +test('without a MAABCD dandiset, or with sharing unticked, the step is skipped', async () => { + for (const input of [{ ...shared(), protocol: FOUR_CHOICE }, { ...shared(), shareWithMaabcd: false }]) { + const states: RunState[] = [] + await createRunProtocolUseCase(auth, fakes().api, sharingStore().store)(input, (s) => states.push(s)) + assert.equal(maabcdStep(states.at(-1))?.state, 'skipped') + } +}) + // ── Retry: carrying on from the checkpoint ─────────────────────────────────────────────────── /** Makes `method` of the fake workspace API throw the first `times` times it is called. */ From e8555e2359377c00ec5344fc016a8948b747a7ba Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 22:37:43 +0530 Subject: [PATCH 22/32] IDP-52: keep the run across a page reload; Retry on the failed step's row --- .../src/components/DataUploadDialog.tsx | 165 ++++++++---------- .../frontend/src/components/PageLayout.tsx | 13 ++ .../frontend/src/components/runStorage.ts | 72 ++++++++ .../frontend/src/components/uploadSession.ts | 90 ++++++++++ .../frontend/src/core/ports/IObjectStore.ts | 15 +- .../idp-arc/frontend/src/core/types.ts | 2 + .../src/core/use-cases/emberObjectStore.ts | 101 +++++------ .../src/core/use-cases/runProgress.ts | 5 +- .../src/core/use-cases/runProtocol.ts | 90 +++++++--- .../idp-arc/frontend/src/core/userMessages.ts | 3 + .../src/infra/mocks/mockObjectStore.ts | 2 +- .../src/infra/publicBucketObjectStore.ts | 2 +- .../tests/unit/emberObjectStore.test.ts | 42 +++-- .../frontend/tests/unit/runProtocol.test.ts | 81 +++++++-- .../frontend/tests/unit/runStorage.test.ts | 57 ++++++ .../frontend/tests/unit/uploadSession.test.ts | 54 ++++++ 16 files changed, 583 insertions(+), 211 deletions(-) create mode 100644 applications/idp-arc/frontend/src/components/runStorage.ts create mode 100644 applications/idp-arc/frontend/src/components/uploadSession.ts create mode 100644 applications/idp-arc/frontend/tests/unit/runStorage.test.ts create mode 100644 applications/idp-arc/frontend/tests/unit/uploadSession.test.ts diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index 54eab85..992f889 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -1,4 +1,4 @@ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react' import { Box, Button, @@ -22,14 +22,16 @@ import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' -import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages' +import { EMBER_SIGN_IN, finishUploadMessage, UserFacingError, userMessage } from '../core/userMessages' +import { withRunLock } from './runStorage' +import { INITIAL_FORM, restoreSession, session } from './uploadSession' import { useAppContext } from '../AppContext' -import { RUN_STEP, type RunCheckpoint, type RunStep, type RunStepId } from '../core/types' +import { RUN_STEP, type RunStep, type RunStepId } from '../core/types' import RunChecklist from './RunChecklist' -import { createSessionStore, useSessionStore } from './sessionStore' +import { useSessionStore } from './sessionStore' import DoiField from './DoiField' import { inputFileProblem, inputFormatsFor } from '../core/inputFormats' -import { canResume, PUBLISH_STEP, PUBLISHING_LABEL, retryMaabcdCopy } from '../core/use-cases/runProtocol' +import { canResume, fileKeyName, PUBLISH_STEP, PUBLISHING_LABEL, type RunProtocolInput } from '../core/use-cases/runProtocol' import { formatBytes } from '../core/formatBytes' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' import { SIGN_IN_AGAIN } from '../core/userMessages' @@ -37,8 +39,7 @@ import protocols from '../data/protocols.json' /** Only protocols with an analysis repository can be run, so only those are offered. */ const runnableProtocols = protocols.filter((p) => 'repoZipUrl' in p && p.repoZipUrl) - -type DialogStep = 'select' | 'upload' | 'uploading' | 'success' | 'stillRunning' | 'failed' +type RunnableProtocol = (typeof runnableProtocols)[number] export interface DataUploadDialogProps { open: boolean @@ -48,61 +49,10 @@ export interface DataUploadDialogProps { onAuthRequired?: () => void } -interface FormState { -step: DialogStep - protocol: string - file: File | null - isDragging: boolean - uploadMessage: string - /** ID of the workspace spawned in the current dialog session; drives retry behaviour. */ - spawnedWorkspaceId: number | undefined - /** Where the last run's results are, relative to the workspace root. */ - outputsDir: string - /** The DOI of the version published with "Publish dandiset". */ - doi?: { doi: string } - /** That publish is under way, or failed (it can be retried). */ - publishing?: 'running' | 'failed' - /** Why the publish failed, for the user. */ - publishError?: string - /** The run's checklist (upload, imports, run), as last reported by the use-case. */ - runSteps: RunStep[] - /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ - dandisetId: string - /** Also upload into the protocol's MAABCD dandiset; on by default. */ - shareWithMaabcd: boolean - /** What the last attempt got done: a retry carries on from there (the run checks it still applies). */ - checkpoint?: RunCheckpoint - /** The finished run's result has been on screen: the next opening starts a new upload. */ - resultSeen?: boolean -} - -const INITIAL_FORM: FormState = { - step: 'select', - protocol: '', - file: null, - isDragging: false, - uploadMessage: '', - spawnedWorkspaceId: undefined, - outputsDir: '', - runSteps: [], - dandisetId: '', - shareWithMaabcd: true, -} - -/** - * The dialog's state, including a run in progress: kept outside the dialog, so closing it (or - * moving to another page, which remounts it) neither stops the run nor forgets it. Reopening shows - * it again, until a finished run's result has been seen. - */ -const session = createSessionStore(INITIAL_FORM) const setForm = session.set /** The run being watched; each run gets its own token, so stopping one never revives another. */ let currentWatch: { current: boolean } | null = null - -/** `steps`, with one step changed. */ -function withStep(steps: RunStep[], id: RunStepId, change: Partial): RunStep[] { - return steps.map((s) => (s.id === id ? { ...s, ...change } : s)) -} +const RUN_IN_OTHER_TAB = 'This run is going on in another tab.' export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() @@ -115,6 +65,10 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const [protocolDandisets, setProtocolDandisets] = useState(null) const [dandisetsError, setDandisetsError] = useState('') const fileInputRef = useRef(null) + const user = typeof tokenParsed?.sub === 'string' ? tokenParsed.sub : null + + // Once the user is known, their run saved before a reload comes back. + useEffect(() => { if (user) restoreSession(user) }, [user]) // While a run is being set up, uploaded or watched, ask before the page is reloaded or closed, // with the dialog open or not: the upload is driven by this tab and would be lost, and the @@ -136,11 +90,12 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut }) // Opening shows the current run: running, failed (for Retry), or finished and not yet seen - // (it ended while the dialog was closed). Otherwise it starts a new upload. + // (it ended while the dialog was closed). Otherwise it starts a new upload. A run sent back to + // the first step for the EMBER-DANDI sign-in keeps its checkpoint, so it counts as started. useEffect(() => { if (!open) return const current = session.get() - const unstarted = current.step === 'select' || (current.step === 'upload' && !current.checkpoint) + const unstarted = (current.step === 'select' || current.step === 'upload') && !current.checkpoint if ((unstarted || current.resultSeen) && current.publishing !== 'running') freshForm() // eslint-disable-next-line react-hooks/exhaustive-deps }, [open]) @@ -154,7 +109,6 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut : null const checklist = publishStep ? [...runSteps, publishStep] : runSteps // Once the run has ended, so its reports can't overwrite what the Retry shows. - const canRetryShare = step !== 'uploading' && runSteps.some((s) => s.id === RUN_STEP.maabcd && s.state === 'failed') useEffect(() => { if (open && finished) setForm((prev) => (prev.resultSeen ? prev : { ...prev, resultSeen: true })) }, [open, finished]) @@ -170,8 +124,9 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut .then((list) => { if (!current) return setProtocolDandisets(list) - // Only while choosing: reopening on a run must not change its dandiset or workspace. - setForm((prev) => (prev.step !== 'select' ? prev + // Only while choosing: reopening on a run (also one back here for the EMBER-DANDI sign-in) + // must not change its dandiset or workspace. + setForm((prev) => (prev.step !== 'select' || prev.checkpoint?.protocolId === protocolId ? prev : { ...prev, dandisetId: list[0]?.id ?? '', spawnedWorkspaceId: list[0]?.workspaceId })) }) .catch((err: unknown) => { @@ -210,24 +165,42 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const fileProblem = file ? inputFileProblem(file, selectedProtocol?.name ?? 'This protocol', selectedProtocol?.inputFormats) : null const handleUpload = async () => { - if (!file || fileProblem || !selectedProtocol) return + if (fileProblem || !selectedProtocol) return + // Picked up after a reload: the file is needed again unless it was already uploaded. + if (!file) { + if (checkpoint?.stored) return runLocked(selectedProtocol, null) + return setForm((prev) => ({ ...prev, step: 'upload', uploadMessage: finishUploadMessage(fileKeyName(checkpoint?.fileKey)) })) + } + return runLocked(selectedProtocol, file) + } + + /** Runs it, unless another tab is already running this user's run. */ + const runLocked = async (selectedProtocol: RunnableProtocol, file: File | null) => { + const ran = await withRunLock(user ?? '', () => startRun(selectedProtocol, file)) + if (!ran) setForm((prev) => ({ ...prev, step: 'failed', uploadMessage: RUN_IN_OTHER_TAB })) + } + + /** What every attempt is given: it carries on from `checkpoint` where that applies. */ + const inputFor = (selectedProtocol: RunnableProtocol, file: File | null): RunProtocolInput => ({ + protocol: selectedProtocol, + file, + // `spawnedWorkspaceId` is set as soon as the run has a workspace, so a retry reuses it + // instead of creating another one. + workspaceId: spawnedWorkspaceId, + workspaceName: selectedProtocol.name, + dandisetId: dandisetId || undefined, + shareWithMaabcd, + resume: checkpoint, + }) + + const startRun = async (selectedProtocol: RunnableProtocol, file: File | null) => { setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [], doi: undefined, publishing: undefined })) if (currentWatch) currentWatch.current = true const watch = { current: false } currentWatch = watch await runProtocol( - { - protocol: selectedProtocol, - file, - // `spawnedWorkspaceId` is set as soon as the run has a workspace, so a retry reuses it - // instead of creating another one. - workspaceId: spawnedWorkspaceId, - workspaceName: selectedProtocol.name, - dandisetId: dandisetId || undefined, - shareWithMaabcd, - resume: checkpoint, - }, + inputFor(selectedProtocol, file), (state) => { if (watch.current) return // another run started: no longer this one's if (state.phase === 'failed' && state.error?.toLowerCase().includes(SIGN_IN_AGAIN)) { @@ -239,8 +212,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut return } if (state.phase === 'failed' && state.error === EMBER_SIGN_IN) { - // The EMBER-DANDI session ended: back to the form, where the sign-in button is. - // Back to the first step, which points to the Login dialog; the dandiset and workspace stay. + // The EMBER-DANDI session ended: back to the first step, which points to the Login + // dialog. The checkpoint, dandiset and workspace stay, so the next attempt carries on. setForm((prev) => ({ ...prev, step: 'select', uploadMessage: EMBER_SIGN_IN, spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, dandisetId: state.dandisetId ?? prev.dandisetId, @@ -279,20 +252,21 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut } } - /** The MAABCD step's Retry: only the copy is tried again. */ - const retryShare = async () => { - if (!checkpoint) return - const share = (change: Partial) => (prev: FormState) => ({ ...prev, runSteps: withStep(prev.runSteps, RUN_STEP.maabcd, change) }) - setForm(share({ state: 'running', detail: undefined })) - try { - const next = await retryMaabcdCopy(checkpoint) - setForm((prev) => ({ ...share({ state: 'succeeded' })(prev), checkpoint: next })) - } catch (err) { - console.error('Not shared with the MAABCD consortium', err) - setForm(share({ state: 'failed', detail: userMessage(err, RUN_STEP.maabcd) })) - } + /** A finished run's Retry: only its failed non-blocking steps run again, and only their rows change. */ + const retryFinishedRun = async () => { + if (!selectedProtocol) return + await withRunLock(user ?? '', () => runProtocol( + { ...inputFor(selectedProtocol, file), finishedRun: runSteps }, + (state) => setForm((prev) => ({ ...prev, runSteps: state.steps, checkpoint: state.checkpoint ?? prev.checkpoint })), + )) } + // Every failed row has Retry while no run is going: a stopped run carries on, a finished one retries only those rows. + const failedRows = step === 'uploading' ? [] : runSteps.filter((s) => s.state === 'failed') + const rowRetry = finished ? retryFinishedRun : handleUpload + const rowActions: Partial> = Object.fromEntries( + failedRows.map((s) => [s.id, ])) + // "Retry" only when an earlier attempt can be carried on (same protocol, file, dandiset and // sharing choice); choosing a dandiset that already has a workspace is still a new run. const resumable = !!selectedProtocol && canResume(checkpoint, { @@ -610,7 +584,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut {checklist.length > 0 && ( Retry } : {}} + actions={rowActions} /> )} {/* Optional, after the run: publishing is the researcher's choice (they can also do it on EMBER). */} @@ -660,9 +634,12 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut - + {/* For a failure no row shows: before any step, or a run cut off by a reload. */} + {failedRows.length === 0 && ( + + )} )} diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 38df3c6..3c705d4 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -27,6 +27,7 @@ import DataUploadDialog from './DataUploadDialog' import { registerUploadOpener } from './UploadContext' import LoginDialog from './LoginDialog' import { OSB_LOGIN_POPUP_NAME, takeLoginDialogReturn } from './loginReturn' +import { clearAllRuns, loadRun } from './runStorage' const ArrowIcon = () => @@ -41,6 +42,8 @@ export interface PageLayoutProps { /** Read once per page load: a login started in the Login dialog left or reloaded the page. */ let pendingLoginReturn = takeLoginDialogReturn() +/** Once per page load: a run saved before the reload reopens the upload dialog. */ +let savedRunOffered = false export default function PageLayout({ children, @@ -136,6 +139,7 @@ export default function PageLayout({ /** Logs out of both: IDP forgets its EMBER token (EMBER has no logout call), then OSB's * Keycloak session ends, which reloads the page. */ const logout = () => { + clearAllRuns() emberAuth.disconnect() setEmberSignedIn(false) if (isAuthenticated) authClient.logout() @@ -145,6 +149,15 @@ export default function PageLayout({ // Re-registered on every render, so buttons outside this component never call a stale copy. useEffect(() => { registerUploadOpener(openUploadOrLogin) }) + // Back from a reload (an OSB re-login, a refresh) with a run under way: show it again. + const user = osbSignedIn ? authClient.tokenParsed?.sub : undefined + useEffect(() => { + if (savedRunOffered || typeof user !== 'string' || loginDialogOpen) return + savedRunOffered = true + if (loadRun(user)) void openUploadOrLogin() + // eslint-disable-next-line react-hooks/exhaustive-deps + }, [user, loginDialogOpen]) + const navItems = [ { label: t('nav.protocols'), path: '/protocols' }, { label: t('nav.about'), path: '/about' }, diff --git a/applications/idp-arc/frontend/src/components/runStorage.ts b/applications/idp-arc/frontend/src/components/runStorage.ts new file mode 100644 index 0000000..7f85615 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/runStorage.ts @@ -0,0 +1,72 @@ +/** + * Keeps the upload dialog's run in localStorage, so a page reload (an OSB re-login, a refresh) + * doesn't lose it. One per user; ids only, never tokens. Blocked storage just means no resume. + */ + +const PREFIX = 'idp_run:' +/** Bumped when the saved shape changes: an older one is dropped, not misread. */ +const VERSION = 1 +const MAX_AGE_MS = 7 * 24 * 60 * 60 * 1000 + +function localStore(): Storage | undefined { + try { + return globalThis.localStorage + } catch { + return undefined + } +} + +export function saveRun(user: string, run: unknown, storage = localStore()): void { + try { + storage?.setItem(PREFIX + user, JSON.stringify({ version: VERSION, savedAt: Date.now(), run })) + } catch { + /* full or blocked: the run just won't survive a reload */ + } +} + +/** The user's saved run, or null (none, too old, or saved by another version of IDP). */ +export function loadRun(user: string, storage = localStore()): T | null { + try { + const raw = storage?.getItem(PREFIX + user) + if (!raw) return null + const saved = JSON.parse(raw) as { version?: number; savedAt?: number; run?: T } + if (saved.version === VERSION && Date.now() - (saved.savedAt ?? 0) < MAX_AGE_MS && saved.run) return saved.run + storage?.removeItem(PREFIX + user) + } catch { + /* unreadable: treated as none */ + } + return null +} + +export function clearRun(user: string, storage = localStore()): void { + try { + storage?.removeItem(PREFIX + user) + } catch { + /* blocked */ + } +} + +/** On logout: nothing of anyone's run stays in this browser. */ +export function clearAllRuns(storage = localStore()): void { + try { + if (!storage) return + const keys = Array.from({ length: storage.length }, (_, i) => storage.key(i)).filter((k) => k?.startsWith(PREFIX)) + keys.forEach((k) => storage.removeItem(k!)) + } catch { + /* blocked */ + } +} + +/** Runs `fn` unless another tab is already running this user's run; false if one is. */ +export async function withRunLock(user: string, fn: () => Promise): Promise { + const locks = globalThis.navigator?.locks + if (!locks) { + await fn() + return true + } + return locks.request(PREFIX + user, { ifAvailable: true }, async (lock) => { + if (!lock) return false + await fn() + return true + }) +} diff --git a/applications/idp-arc/frontend/src/components/uploadSession.ts b/applications/idp-arc/frontend/src/components/uploadSession.ts new file mode 100644 index 0000000..39583d5 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/uploadSession.ts @@ -0,0 +1,90 @@ +import type { RunCheckpoint, RunStep } from '../core/types' +import { clearRun, loadRun, saveRun } from './runStorage' +import { createSessionStore } from './sessionStore' + +/** + * The upload dialog's state, kept outside the dialog: closing it (or moving to another page, which + * remounts it) neither stops a run nor forgets it, and its run is saved, so a page reload doesn't + * either. Its own module, as exporting non-components from a component file breaks Fast Refresh. + */ + +export type DialogStep = 'select' | 'upload' | 'uploading' | 'success' | 'stillRunning' | 'failed' + +export interface FormState { + step: DialogStep + protocol: string + file: File | null + isDragging: boolean + uploadMessage: string + /** ID of the workspace spawned in the current dialog session; drives retry behaviour. */ + spawnedWorkspaceId: number | undefined + /** Where the last run's results are, relative to the workspace root. */ + outputsDir: string + /** The DOI of the version published with "Publish dandiset". */ + doi?: { doi: string } + /** That publish is under way, or failed (it can be retried). */ + publishing?: 'running' | 'failed' + /** Why the publish failed, for the user. */ + publishError?: string + /** The run's checklist (upload, imports, run), as last reported by the use-case. */ + runSteps: RunStep[] + /** EMBER-DANDI only: the researcher's dandiset to upload into; empty creates a new one. */ + dandisetId: string + /** Also upload into the protocol's MAABCD dandiset; on by default. */ + shareWithMaabcd: boolean + /** What the last attempt got done: a retry carries on from there (the run checks it still applies). */ + checkpoint?: RunCheckpoint + /** The finished run's result has been on screen: the next opening starts a new upload. */ + resultSeen?: boolean +} + +export const INITIAL_FORM: FormState = { + step: 'select', + protocol: '', + file: null, + isDragging: false, + uploadMessage: '', + spawnedWorkspaceId: undefined, + outputsDir: '', + runSteps: [], + dandisetId: '', + shareWithMaabcd: true, +} + +export const session = createSessionStore(INITIAL_FORM) + +/** What is saved across a reload: the run, not the form around it. */ +type SavedRun = Pick + +const RUN_INTERRUPTED = 'The page was reloaded during the run. Retry to carry on from where it stopped.' + +/** The user whose run is saved, once known. */ +let savingFor: string | null = null + +session.subscribe(() => { + if (!savingFor) return + const { step, protocol, dandisetId, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage, resultSeen } = session.get() + if (!checkpoint || resultSeen) return clearRun(savingFor) + const run: SavedRun = { step, protocol, dandisetId, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage } + saveRun(savingFor, run) +}) + +/** Once the user is known: brings back their run saved before a reload, unless one is open already. */ +export function restoreSession(user: string): void { + if (savingFor === user) return + savingFor = user + const run = loadRun(user) + if (!run || session.get().checkpoint) return + // A run that was going when the page went is shown stopped, for Retry. + const interrupted = run.step === 'uploading' + session.set({ + ...INITIAL_FORM, + ...run, + ...(interrupted && { + step: 'failed', + uploadMessage: RUN_INTERRUPTED, + runSteps: run.runSteps.map((s) => (s.state === 'running' ? { ...s, state: 'pending', detail: undefined } : s)), + }), + }) +} diff --git a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts index d40a248..0f9a119 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -29,20 +29,27 @@ export interface ObjectUploadInput { onCheckpoint?: (checkpoint: UploadCheckpoint) => void } +/** An uploaded file, as plain data: kept with the run's checkpoint, which is saved across reloads. */ export interface StoredObject { /** Where OSB's workspace import fetches the file from (`workspaceresource` `origin.path`). */ url: string /** The object's name in its store, for messages and logs. */ key: string + /** The uploaded file's name and size. */ + name: string + size?: number /** EMBER-DANDI: the researcher's dandiset it went into (possibly created by this upload). */ dandisetId?: string - /** EMBER-DANDI: records the run's workspace in the dandiset's metadata. */ - recordWorkspace?: (workspaceId: number) => Promise - /** EMBER-DANDI, when a MAABCD copy was asked for: makes that copy. Safe to call again (Retry). */ - shareWithMaabcd?: () => Promise + /** EMBER-DANDI: the file's DANDI etag, so the MAABCD copy needs no file. */ + etag?: string } export interface IObjectStore { /** Stores the file. `onProgress` gets the bytes sent so far, repeatedly while it uploads. */ put(input: ObjectUploadInput, onProgress?: (sentBytes: number, totalBytes: number) => void): Promise + /** EMBER-DANDI: records the run's workspace in the upload's dandiset. */ + recordWorkspace?(stored: StoredObject, workspaceId: number, protocol: { id: string; name: string; url?: string }): Promise + /** EMBER-DANDI: copies the upload into `dandisetId` (MAABCD's), through OSB. `file` is needed only + * if EMBER doesn't already hold its bytes. */ + shareWithMaabcd?(stored: StoredObject, dandisetId: string, file?: File | null): Promise } diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index b9cab60..c6ce3cb 100644 --- a/applications/idp-arc/frontend/src/core/types.ts +++ b/applications/idp-arc/frontend/src/core/types.ts @@ -96,4 +96,6 @@ export interface RunCheckpoint { dataImported?: boolean /** The copy for the MAABCD consortium is made. */ maabcdShared?: boolean + /** The notebooks it submitted and hasn't seen end: a resumed run follows them, not resubmits. */ + submitted?: string[] } diff --git a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts index 48145d4..03bfef9 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -25,6 +25,10 @@ export { EMBER_SIGN_IN } export interface EmberUploadCheckpoint { /** The researcher's dandiset, once picked or created. */ userDandisetId?: string + /** The file's DANDI etag, once computed. */ + etag?: string + /** Where their copy goes, chosen before it is registered: a retry registers the same path. */ + path?: string /** Their own copy, once registered. */ own?: { assetId: string; assetPath: string } } @@ -44,7 +48,6 @@ export function createEmberObjectStore( const { file } = input const token = emberAuth.getToken() if (!token) throw new UserFacingError(EMBER_SIGN_IN, 'No EMBER-DANDI token (not signed in, or it expired)') - const maabcdAggregateDandisetId = input.dandisets?.maabcd || undefined const saved: EmberUploadCheckpoint = { ...(input.resume as EmberUploadCheckpoint | undefined) } const save = (patch: EmberUploadCheckpoint) => { Object.assign(saved, patch) @@ -53,9 +56,6 @@ export function createEmberObjectStore( const progress = (sent: number) => onProgress?.(Math.min(sent, file.size), file.size) progress(saved.own ? file.size : 0) - // The file's DANDI etag and part plan, computed once for both copies. - let hashed: Promise<{ etag: string; parts: PartPlan[] }> | undefined - const hash = () => (hashed ??= computeDandiEtag(file)) // The researcher's own copy. const protocol = input.dandisets?.protocol ?? { id: input.protocolId, name: input.protocolId } @@ -64,8 +64,9 @@ export function createEmberObjectStore( if (saved.userDandisetId !== userDandisetId) save({ userDandisetId }) let asset = saved.own if (!asset) { - const { etag, parts: plan } = await hash() - const path = `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` + const { etag, parts: plan } = await computeDandiEtag(file) + const path = saved.path ?? `${pathSafe(input.protocolId)}/${crypto.randomUUID()}/${pathSafe(file.name)}` + save({ etag, path }) const init = await direct.initUpload(token, userDandisetId, file.size, etag) const uploaded = await putParts(init.parts, plan, file, progress) asset = await direct.finalizeUpload(token, { @@ -75,58 +76,60 @@ export function createEmberObjectStore( } progress(file.size) - // The MAABCD copy, through OSB: one attempt at a time, and not again once made. - let shared = false - let sharing: Promise | undefined - const shareWithMaabcd = () => { - if (shared) return Promise.resolve() - sharing ??= (async () => { - const { etag, parts: plan } = await hash() - const osbToken = await osbAuth.getToken() - const brokered = await osb.getUploadUrls(osbToken, { - dandisetId: maabcdAggregateDandisetId!, filename: file.name, size: file.size, dandiEtag: etag, - }) - const brokeredParts = await putParts(brokered.parts, plan, file, () => {}) - await osb.validateUpload(osbToken, { - dandisetId: brokered.dandisetId, - path: brokered.path, - uploadId: brokered.uploadId, - parts: brokered.blobId ? undefined : brokeredParts, - blobId: brokered.blobId, - }) - shared = true - })().finally(() => { sharing = undefined }) - return sharing - } - return { url: `${emberApiOrigin.replace(/\/+$/, '')}/api/assets/${asset.assetId}/download/`, key: asset.assetPath, + name: file.name, + size: file.size, dandisetId: userDandisetId, - recordWorkspace: (workspaceId: number) => dandisets.recordWorkspace(userDandisetId, workspaceId, protocol), - ...(maabcdAggregateDandisetId ? { shareWithMaabcd } : {}), + etag: saved.etag, } + }, - async function putParts(parts: { partNumber: number; url: string }[], plan: PartPlan[], file: File, - report: (sentInTransfer: number) => void) { - // Every part or none (deduplicated): a shorter list would silently upload a truncated file. - if (parts.length && parts.length !== plan.length) { - throw new Error(`EMBER returned ${parts.length} part URLs for a file of ${plan.length} parts`) - } - const result: { partNumber: number; size: number; etag: string }[] = [] - let sent = 0 - for (const part of parts) { - const slice = plan.find((p) => p.partNumber === part.partNumber) - if (!slice) throw new Error(`EMBER asked for part ${part.partNumber}, which this file doesn't have`) - const partEtag = await direct.putPart(part.url, file.slice(slice.start, slice.end)) - result.push({ partNumber: part.partNumber, size: slice.size, etag: partEtag }) - sent += slice.size - report(sent) - } - return result + async recordWorkspace(stored, workspaceId, protocol) { + if (stored.dandisetId) await dandisets.recordWorkspace(stored.dandisetId, workspaceId, protocol) + }, + + async shareWithMaabcd(stored, dandisetId, file) { + const hashed = !stored.etag && file ? await computeDandiEtag(file) : undefined + const etag = stored.etag ?? hashed?.etag + if (!etag) throw new Error('The MAABCD copy needs the file\'s checksum, but no file is selected (the page was reloaded)') + const osbToken = await osbAuth.getToken() + const brokered = await osb.getUploadUrls(osbToken, { dandisetId, filename: stored.name, size: stored.size ?? file?.size ?? 0, dandiEtag: etag }) + // EMBER usually holds the bytes already (the researcher's copy): then there are no parts to send. + let parts: { partNumber: number; size: number; etag: string }[] = [] + if (brokered.parts.length) { + if (!file) throw new Error('EMBER needs the file for the MAABCD copy, but none is selected (the page was reloaded)') + parts = await putParts(brokered.parts, (hashed ?? await computeDandiEtag(file)).parts, file, () => {}) } + await osb.validateUpload(osbToken, { + dandisetId: brokered.dandisetId, + path: brokered.path, + uploadId: brokered.uploadId, + parts: brokered.blobId ? undefined : parts, + blobId: brokered.blobId, + }) }, } + + async function putParts(parts: { partNumber: number; url: string }[], plan: PartPlan[], file: File, + report: (sentInTransfer: number) => void) { + // Every part or none (deduplicated): a shorter list would silently upload a truncated file. + if (parts.length && parts.length !== plan.length) { + throw new Error(`EMBER returned ${parts.length} part URLs for a file of ${plan.length} parts`) + } + const result: { partNumber: number; size: number; etag: string }[] = [] + let sent = 0 + for (const part of parts) { + const slice = plan.find((p) => p.partNumber === part.partNumber) + if (!slice) throw new Error(`EMBER asked for part ${part.partNumber}, which this file doesn't have`) + const partEtag = await direct.putPart(part.url, file.slice(slice.start, slice.end)) + result.push({ partNumber: part.partNumber, size: slice.size, etag: partEtag }) + sent += slice.size + report(sent) + } + return result + } } /** One asset path segment: DANDI rejects `@` and the like; also stops `/` adding segments. */ diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts index be530fc..69ee967 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts @@ -30,9 +30,10 @@ export class RunProgress { /** Reported with every state, so the last one the dialog sees is up to date. */ checkpoint?: RunCheckpoint - constructor(report: OnRunState, steps: { id: RunStepId; label: string }[], workspaceId?: number) { + /** `steps`: the checklist it starts on. */ + constructor(report: OnRunState, steps: RunStep[], workspaceId?: number) { this.report = report - this.steps = steps.map((s) => ({ ...s, state: 'pending' })) + this.steps = steps this.workspaceId = workspaceId } diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index c5adf0a..fda6ca8 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -1,6 +1,6 @@ import type { IAuthClient } from '../ports/IAuthClient' import type { IObjectStore, StoredObject } from '../ports/IObjectStore' -import { RUN_STEP, type RunCheckpoint, type RunStepId } from '../types' +import { RUN_STEP, type RunCheckpoint, type RunStep, type RunStepId } from '../types' import type { IWorkspaceApi, WorkspaceResourceState } from '../ports/IWorkspaceApi' import { formatBytes } from '../formatBytes' import { inputFileProblem } from '../inputFormats' @@ -49,6 +49,8 @@ export interface RunProtocolInput { shareWithMaabcd?: boolean /** From an earlier attempt that stopped: the run carries on from there when canResume allows. */ resume?: RunCheckpoint + /** The checklist of a run that finished: only its failed non-blocking steps run again, on it. */ + finishedRun?: RunStep[] } /** Names a file well enough to tell it is the same one again: name, size, last modified. */ @@ -56,6 +58,11 @@ export function fileKey(file?: File | null): string | null { return file ? `${file.name}|${file.size}|${file.lastModified}` : null } +/** The file name in a fileKey. */ +export function fileKeyName(key?: string | null): string { + return key?.split('|')[0] || 'your file' +} + /** * Whether a checkpoint applies to this attempt: same protocol, same file, same sharing choice, and * the same dandiset and workspace (or the ones that attempt itself created). Otherwise the run @@ -67,8 +74,10 @@ export function canResume(checkpoint: RunCheckpoint | undefined, input: RunProto || (!!input.dandisetId && input.dandisetId === checkpoint.stored?.dandisetId) const sameWorkspace = input.workspaceId === undefined || checkpoint.workspaceId === undefined || input.workspaceId === checkpoint.workspaceId + // After a reload there is no file; the upload is all it was needed for. + const sameFile = checkpoint.fileKey === fileKey(input.file) || (!input.file && !!checkpoint.stored) return checkpoint.protocolId === input.protocol.id - && checkpoint.fileKey === fileKey(input.file) + && sameFile && checkpoint.shareWithMaabcd === (input.shareWithMaabcd !== false) && sameDandiset && sameWorkspace } @@ -87,7 +96,7 @@ const REPOSITORY_SETUP = { } /** Checkpoint fields that make the next attempt import into a new run folder. */ -const NEW_RUN_FOLDER: Partial = { runFolderAt: undefined, repoImported: false, dataImported: false } +const NEW_RUN_FOLDER: Partial = { runFolderAt: undefined, repoImported: false, dataImported: false, submitted: undefined } const STEPS = [ { id: RUN_STEP.upload, label: 'Upload your file' }, @@ -133,8 +142,8 @@ export const PUBLISHING_LABEL = 'Publishing your dandiset' * Every state reports a checkpoint of what is done. Given back on a retry (`resume`), the run * skips those steps: the upload (or the copies of it already made), the workspace, and the imports * into the same run folder. If waiting for the imports fails, the folder's contents are in doubt, - * so the next attempt imports into a new one; and once the notebooks are submitted, a retry is a - * new run of them, in a new folder. + * so the next attempt imports into a new one. Submitted notebooks are followed to their end, even + * after a reload; once that end is seen, a retry is a new run of them, in a new folder. */ export function createRunProtocolUseCase( auth: Pick, @@ -144,12 +153,13 @@ export function createRunProtocolUseCase( const token = (minValidity = 30) => auth.getToken(minValidity) return async function runProtocol(input: RunProtocolInput, report: OnRunState, abortRef?: { current: boolean }): Promise { - const { protocol, file } = input - const progress = new RunProgress(report, STEPS, input.workspaceId) + const { protocol, file, finishedRun } = input + const progress = new RunProgress(report, finishedRun ?? STEPS.map((s) => ({ ...s, state: 'pending' })), input.workspaceId) const stopped = () => !!abortRef?.current const checkpoint: RunCheckpoint = canResume(input.resume, input) ? { ...input.resume } : { protocolId: protocol.id, fileKey: fileKey(file), dandisetChoice: input.dandisetId, shareWithMaabcd: input.shareWithMaabcd !== false } + const hasData = !!file || !!checkpoint.stored const save = (patch: Partial) => { Object.assign(checkpoint, patch) progress.checkpoint = { ...checkpoint } @@ -159,23 +169,25 @@ export function createRunProtocolUseCase( if (checkpoint.workspaceId !== undefined) progress.workspaceId = checkpoint.workspaceId const doneEarlier = (id: RunStepId) => progress.done(id, 'Done earlier') + if (finishedRun) return retryNonBlocking(finishedRun) + try { // Before anything moves: the protocol and the file. const { repo, userId } = checkBeforeStarting(input) // This run's folder in the workspace (the repository's zip unpacks into it as -/). if (!checkpoint.runFolderAt) save({ runFolderAt: new Date().toISOString() }) const layout = workspaceLayout(protocol.id, new Date(checkpoint.runFolderAt!)) - if (!file) { + if (!hasData) { progress.skip(RUN_STEP.upload) progress.skip(RUN_STEP.data) } - const sharesCopy = !!file && input.shareWithMaabcd !== false && !!protocol.maabcdAggregateDandisetId + const sharesCopy = hasData && input.shareWithMaabcd !== false && !!protocol.maabcdAggregateDandisetId if (!sharesCopy) progress.skip(RUN_STEP.maabcd) progress.emit('Starting…') // 1. Upload the file straight to the bucket. Nothing else starts until it has landed. let stored: StoredObject | null = null - if (file && checkpoint.stored) { + if (checkpoint.stored) { stored = checkpoint.stored doneEarlier(RUN_STEP.upload) } else if (file) { @@ -192,7 +204,7 @@ export function createRunProtocolUseCase( const id = await prepareWorkspace() save({ workspaceId: id }) if (!checkpoint.workspaceRecorded) { - await stored?.recordWorkspace?.(id) + if (stored) await objectStore.recordWorkspace?.(stored, id, protocolRef()) save({ workspaceRecorded: true }) } return id @@ -217,13 +229,20 @@ export function createRunProtocolUseCase( } // 4. Import the uploaded data. - if (stored && file && checkpoint.dataImported) doneEarlier(RUN_STEP.data) - else if (stored && file) { + if (stored && checkpoint.dataImported) doneEarlier(RUN_STEP.data) + else if (stored) { const upload = stored - await inStep(RUN_STEP.data, () => importData(workspaceId, file, upload, layout.inputs)) + await inStep(RUN_STEP.data, () => importData(workspaceId, upload, layout.inputs)) save({ dataImported: true }) } + // Already submitted (the page was reloaded while they ran): follow them, don't resubmit. + if (checkpoint.submitted) { + doneEarlier(RUN_STEP.imports) + const submitted = checkpoint.submitted + return inStep(RUN_STEP.run, () => watchRun(workspaceId, submitted, layout)) + } + // 5. Wait for the imports, and find the notebooks to run. If this fails, the folder may hold // a failed or half-finished import: the next attempt starts a new folder. if (stopped()) return false @@ -238,6 +257,12 @@ export function createRunProtocolUseCase( return inStep(RUN_STEP.run, () => runNotebooks(workspaceId, repoDir, notebooks, layout, !!stored)) } + /** A finished run's Retry: its failed non-blocking steps (only the MAABCD copy) run again. */ + async function retryNonBlocking(steps: RunStep[]) { + if (steps.some((s) => s.id === RUN_STEP.maabcd && s.state === 'failed')) await shareWithMaabcd(checkpoint.stored ?? null) + progress.emit('Retried') // the step's own outcome is only reported with the next step's + } + // ── The steps ──────────────────────────────────────────────────────────────────────── /** Before anything moves: a file the protocol can't read would only fail minutes later. */ @@ -266,7 +291,7 @@ export function createRunProtocolUseCase( dandisets: { user: input.dandisetId, newName: `${protocol.name} (IDP)`, - protocol: { id: protocol.id, name: protocol.name, url: repoPage(protocol.repoZipUrl) }, + protocol: protocolRef(), maabcd: input.shareWithMaabcd === false ? undefined : protocol.maabcdAggregateDandisetId, }, }, (sent, total) => { @@ -281,13 +306,17 @@ export function createRunProtocolUseCase( return stored } + function protocolRef() { + return { id: protocol.id, name: protocol.name, url: repoPage(protocol.repoZipUrl) } + } + /** The MAABCD copy's step; a failure is left for its Retry. */ async function shareWithMaabcd(stored: StoredObject | null) { - if (!stored?.shareWithMaabcd) return + if (!stored || !objectStore.shareWithMaabcd) return progress.skip(RUN_STEP.maabcd) if (checkpoint.maabcdShared) return doneEarlier(RUN_STEP.maabcd) progress.start(RUN_STEP.maabcd, 'uploading', 'Sharing with the MAABCD consortium…') try { - await stored.shareWithMaabcd() + await objectStore.shareWithMaabcd(stored, protocol.maabcdAggregateDandisetId!, file) save({ maabcdShared: true }) progress.done(RUN_STEP.maabcd) } catch (err) { @@ -301,6 +330,11 @@ export function createRunProtocolUseCase( async function prepareWorkspace(): Promise { progress.start(RUN_STEP.workspace, 'workspace', 'Getting the workspace ready…') const existing = checkpoint.workspaceId ?? input.workspaceId + // A run picked up again (perhaps days later): its workspace may have been deleted since. + if (checkpoint.workspaceId !== undefined + && !(await workspaceApi.getWorkspaceOwner(await token(), checkpoint.workspaceId))) { + throw new UserFacingError('The workspace for this run no longer exists. Please start a new upload.') + } if (existing !== undefined) { progress.done(RUN_STEP.workspace, undefined, 'Workspace ready') return existing @@ -321,10 +355,10 @@ export function createRunProtocolUseCase( } /** Step 4. */ - async function importData(workspaceId: number, file: File, stored: StoredObject, folder: string) { + async function importData(workspaceId: number, stored: StoredObject, folder: string) { progress.start(RUN_STEP.data, 'importing', 'Importing your data…') await workspaceApi.importResource(await token(), { - workspaceId, name: file.name, url: stored.url, folder, resourceType: 'e', + workspaceId, name: stored.name, url: stored.url, folder, resourceType: 'e', }) progress.done(RUN_STEP.data) } @@ -363,7 +397,6 @@ export function createRunProtocolUseCase( return notebooks } - /** Step 6. */ /** Step 6. True once the notebooks have all run; false if it stopped watching first. */ async function runNotebooks(workspaceId: number, repoDir: string, notebooks: string[], layout: ReturnType, hasData: boolean): Promise { @@ -384,8 +417,14 @@ export function createRunProtocolUseCase( results: { notebooks: layout.notebooks, log: layout.log }, ...(protocol.image ? { image: protocol.image } : {}), }) - // Submitted: the code is consumed (discard), and this folder now holds this run's results. - save(NEW_RUN_FOLDER) + // Submitted: the code is consumed (discard), so from here on a retry follows this run. + save({ submitted: notebooks }) + return watchRun(workspaceId, notebooks, layout) + } + + /** Follows submitted notebooks to their end. Once it has seen the end, a retry is a new run. */ + async function watchRun(workspaceId: number, notebooks: string[], layout: ReturnType): Promise { + progress.start(RUN_STEP.run, 'running', 'Running the notebooks…', 'Running the notebooks') progress.outputsDir = layout.run // Followed through `GET /workspace/{id}`, as the imports are: while a workflow for the // workspace runs, OSB lists a placeholder resource (id -1). Seen, then gone: the run is over. @@ -414,6 +453,7 @@ export function createRunProtocolUseCase( return !!failedAt || executed.every((path) => paths.includes(path)) }, { everyMs: RUN_SETTINGS.runPollMs, timeoutMs: RUN_SETTINGS.runResultTimeoutMs, stopped }) if (listed === 'stopped') return false + save(NEW_RUN_FOLDER) // The user reads the run step's plain sentence; which notebook failed goes to the console. if (failedAt) throw new Error(`${failedAt} failed; see ${layout.log}`) // Neither: it stopped before any notebook ran (e.g. installing the requirements). @@ -423,9 +463,3 @@ export function createRunProtocolUseCase( } } } - -/** The MAABCD step's Retry: tries only the copy again. Rejects if it fails again. */ -export async function retryMaabcdCopy(checkpoint: RunCheckpoint): Promise { - await checkpoint.stored?.shareWithMaabcd?.() - return { ...checkpoint, maabcdShared: true } -} diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 02736bc..2bdd95f 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -32,6 +32,9 @@ export const EMBER_SIGN_IN = 'Please sign in with EMBER-DANDI and try again.' /** EMBER refuses to publish the dandiset as it is (its metadata or a file); EMBER's editor says what to fix. */ export const DANDISET_NOT_PUBLISHABLE = "This dandiset can't be published yet. Check on EMBER-DANDI on specific errors." +/** A run picked up after a reload whose upload hadn't finished: the browser no longer has the file. */ +export const finishUploadMessage = (fileName: string) => `Choose ${fileName} again to finish uploading it.` + /** Says the session has ended; the dialog sends the user to sign in when the text contains it. */ export const SIGN_IN_AGAIN = 'sign in again' diff --git a/applications/idp-arc/frontend/src/infra/mocks/mockObjectStore.ts b/applications/idp-arc/frontend/src/infra/mocks/mockObjectStore.ts index 441b6e6..1489f22 100644 --- a/applications/idp-arc/frontend/src/infra/mocks/mockObjectStore.ts +++ b/applications/idp-arc/frontend/src/infra/mocks/mockObjectStore.ts @@ -12,7 +12,7 @@ export class MockObjectStore implements IObjectStore { } const key = objectKey(input.protocolId, input.userSub, `mock-${Date.now()}`, file.name) console.info(`[MockObjectStore] put(${key}, ${file.size}B)`) - return { url: `https://storage.googleapis.com/mock-bucket/${key}`, key } + return { url: `https://storage.googleapis.com/mock-bucket/${key}`, key, name: input.file.name } } } diff --git a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts index b762f49..b0873e4 100644 --- a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts +++ b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts @@ -36,7 +36,7 @@ export class PublicBucketObjectStore implements IObjectStore { reject(new Error(`Upload to the bucket failed: ${xhr.status} ${xhr.statusText}`.trim())) } else { onProgress?.(file.size, file.size) - resolve({ url, key }) + resolve({ url, key, name: file.name }) } } xhr.onerror = () => reject(new Error('Upload to the bucket failed: network error (check the bucket’s CORS)')) diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index 193d3ee..2af44c6 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -8,6 +8,7 @@ import { UserFacingError } from '../../src/core/userMessages' const ORIGIN = 'https://api-dandi.example.org' const file = () => new File(['animal data'], 'animal 01.xlsx') +const finalizedPaths: string[] = [] function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: boolean; failOsbOnce?: boolean; failDirectOnce?: boolean } = {}) { const calls: string[] = [] @@ -28,6 +29,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b }, async putPart(url) { calls.push(`put:${url}`); return `etag-${url.split('/').pop()}` }, async finalizeUpload(token, input) { + finalizedPaths.push(input.path) calls.push(`direct-finalize:${input.dandisetId}:${input.uploadId ?? 'dedup'}:${input.parts.map((p) => p.etag).join(',')}`) return { assetId: 'asset-1', assetPath: input.path } }, @@ -64,7 +66,9 @@ test('uploads to the picked dandiset directly; the MAABCD copy is a separate cal }, (sent, total) => progress.push(sent / total)) assert.deepEqual(calls, ['direct-init:ember-token:000123', 'put:https://s3/direct', 'direct-finalize:000123:up-1:etag-direct']) - await stored.shareWithMaabcd?.() + // Plain data, so it can be saved across a reload: the copy needs the etag, not the file. + assert.deepEqual(JSON.parse(JSON.stringify(stored)), stored) + await store().shareWithMaabcd!(stored, '000533', file()) assert.deepEqual(calls.slice(3), ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) // The run imports the researcher's own copy, from EMBER's public origin (not the browser's proxy). assert.equal(stored.url, `${ORIGIN}/api/assets/asset-1/download/`) @@ -84,17 +88,16 @@ test('creates the dandiset for the protocol when none was picked, and skips OSB assert.equal(calls[0], 'create:ASST (IDP):asst') assert.equal(calls[1], 'direct-init:ember-token:000777') assert.ok(!calls.some((c) => c.startsWith('osb-'))) - assert.equal(stored.shareWithMaabcd, undefined, 'no MAABCD copy to make') // The run records its workspace in the dandiset it uploaded into. assert.equal(stored.dandisetId, '000777') - await stored.recordWorkspace?.(42) + await store().recordWorkspace!(stored, 42, { id: 'asst', name: 'ASST' }) assert.equal(calls.at(-1), 'record:000777:42:asst') }) test('deduplicated content moves no bytes and registers against the existing blob', async () => { const { calls, store } = fakes({ dedupDirect: true, dedupOsb: true }) const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) - await stored.shareWithMaabcd?.() + await store().shareWithMaabcd!(stored, '000533') assert.ok(!calls.some((c) => c.startsWith('put:'))) assert.ok(calls.includes('direct-finalize:000123:dedup:')) @@ -104,7 +107,7 @@ test('deduplicated content moves no bytes and registers against the existing blo test('a part list that does not cover the file is refused before any of it is uploaded', async () => { const { calls, store } = fakes({ shortParts: true }) const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) - await assert.rejects(stored.shareWithMaabcd!(), /part URLs/) + await assert.rejects(store().shareWithMaabcd!(stored, '000533', file()), /part URLs/) assert.ok(!calls.includes('put:https://s3/a')) }) @@ -122,21 +125,30 @@ test('without an EMBER-DANDI sign-in nothing starts and the user is asked to sig test('a failed MAABCD copy rejects on its own; calling it again makes only that copy', async () => { const { calls, store } = fakes({ failOsbOnce: true }) const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) - await assert.rejects(stored.shareWithMaabcd!(), /503/) + await assert.rejects(store().shareWithMaabcd!(stored, '000533', file()), /503/) calls.length = 0 - await stored.shareWithMaabcd!() + await store().shareWithMaabcd!(stored, '000533', file()) assert.deepEqual(calls, ['osb-urls:osb-token:000533:animal 01.xlsx:true', 'put:https://s3/osb', 'osb-validate:000533:etag-osb']) - calls.length = 0 - await stored.shareWithMaabcd!() - assert.deepEqual(calls, [], 'not made twice') }) -test('two calls at once make one copy', async () => { +test('without the file, the MAABCD copy works when EMBER already holds the bytes, and fails when it would need the bytes', async () => { + const dedup = fakes({ dedupOsb: true }) + const stored = await dedup.store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + await dedup.store().shareWithMaabcd!(stored, '000533', null) + assert.ok(dedup.calls.includes('osb-validate:000533:blob-1')) + + const parts = fakes() + const first = await parts.store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) + await assert.rejects(parts.store().shareWithMaabcd!(first, '000533', null), /needs the file/) +}) + +test('a resumed upload registers the same path, so it finds the asset rather than add one', async () => { const { calls, store } = fakes() - const stored = await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123', maabcd: '000533' } }) - await Promise.all([stored.shareWithMaabcd!(), stored.shareWithMaabcd!()]) - assert.equal(calls.filter((c) => c.startsWith('osb-validate')).length, 1) + const resume = { userDandisetId: '000123', etag: 'e', path: 'p/fixed-uuid/f.xlsx' } + await store().put({ file: file(), protocolId: 'p', userSub: 'u', dandisets: { user: '000123' }, resume }) + assert.ok(calls.includes('direct-finalize:000123:up-1:etag-direct')) + assert.equal(finalizedPaths.at(-1), 'p/fixed-uuid/f.xlsx') }) test('a retry after the own copy failed reuses the dandiset it created', async () => { @@ -148,7 +160,7 @@ test('a retry after the own copy failed reuses the dandiset it created', async ( onCheckpoint: (c: unknown) => checkpoints.push(c), } await assert.rejects(store().put(input), /initialize failed/) - assert.deepEqual(checkpoints.at(-1), { userDandisetId: '000777' }) + assert.equal((checkpoints.at(-1) as { userDandisetId?: string }).userDandisetId, '000777') const stored = await store().put({ ...input, resume: checkpoints.at(-1) as Record }) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index 90e85a5..b6ef4a6 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -1,7 +1,7 @@ // The run (core/use-cases/runProtocol.ts) against in-memory ports. Run: yarn test:unit import { test, beforeEach } from 'node:test' import assert from 'node:assert/strict' -import { canResume, createRunProtocolUseCase, retryMaabcdCopy } from '../../src/core/use-cases/runProtocol' +import { canResume, createRunProtocolUseCase } from '../../src/core/use-cases/runProtocol' import { RUN_SETTINGS } from '../../src/core/runSettings' import type { IWorkspaceApi, ImportResourceInput, StartRunInput, WorkspaceResourceState } from '../../src/core/ports/IWorkspaceApi' import type { IObjectStore } from '../../src/core/ports/IObjectStore' @@ -39,7 +39,7 @@ function fakes(opts: { runPolls?: number; importPolls?: number; failUpload?: boo let runPollsLeft = 0 const api: IWorkspaceApi = { async listWorkspaces() { return [] }, - async getWorkspaceOwner() { return null }, + async getWorkspaceOwner() { return 'user-1' }, async createWorkspace(_t, name, tags) { calls.push(`create:${name}:${tags?.join(',')}`); return 42 }, async getWorkspaceResources() { if (runPollsLeft > 0) { runPollsLeft -= 1; return [{ id: -1, name: 'Refreshing resources' }] } @@ -68,7 +68,7 @@ function fakes(opts: { runPolls?: number; importPolls?: number; failUpload?: boo async put(input) { calls.push('upload') if (opts.failUpload) throw new Error('403 Forbidden') - return { url: `https://storage.googleapis.com/maabcd/uploads/${input.protocolId}/${input.userSub}/u/${input.file.name}`, key: 'k' } + return { url: `https://storage.googleapis.com/maabcd/uploads/${input.protocolId}/${input.userSub}/u/${input.file.name}`, key: 'k', name: input.file.name } }, } return { api, store, calls, imports, runInput: () => runInput } @@ -307,11 +307,9 @@ test('an EMBER-DANDI upload gets the run\'s workspace recorded in its dandiset, async put(input) { f.calls.push('upload') seen.dandisets = input.dandisets - return { - url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777', - recordWorkspace: async (id) => { f.calls.push(`record:${id}`) }, - } + return { url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', name: 'animal_01.xlsx', dandisetId: '000777' } }, + async recordWorkspace(_stored, id) { f.calls.push(`record:${id}`) }, } const states: RunState[] = [] await createRunProtocolUseCase(auth, f.api, store)( @@ -336,7 +334,7 @@ test('with "Share with MAABCD" unticked, nothing goes to the protocol\'s MAABCD const store: IObjectStore = { async put(input) { seen.dandisets = input.dandisets - return { url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777' } + return { url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', name: 'animal_01.xlsx', dandisetId: '000777' } }, } const states: RunState[] = [] @@ -353,13 +351,11 @@ function sharingStore(fails = 0) { let attempts = 0 const store: IObjectStore = { async put() { - return { - url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', dandisetId: '000777', - shareWithMaabcd: async () => { - attempts += 1 - if (attempts <= fails) throw new Error('OSB get_upload_urls failed (HTTP 503)') - }, - } + return { url: 'https://api-dandi.example.org/api/assets/a/download/', key: 'k', name: 'animal_01.xlsx', dandisetId: '000777', etag: 'e' } + }, + async shareWithMaabcd() { + attempts += 1 + if (attempts <= fails) throw new Error('OSB get_upload_urls failed (HTTP 503)') }, } return { store, attempts: () => attempts } @@ -378,9 +374,15 @@ test('a failed MAABCD copy fails only its own step; its Retry makes only the cop assert.equal(maabcdStep(last)?.state, 'failed') assert.match(maabcdStep(last)?.detail ?? '', /Not shared with the MAABCD consortium/) + // Its row's Retry: the same use case, given the finished run's checklist. const runs = count(f.calls, 'run') - const next = await retryMaabcdCopy(last.checkpoint!) - assert.equal(next.maabcdShared, true) + const retried: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)( + { ...shared(), workspaceId: last.workspaceId, resume: last.checkpoint, finishedRun: last.steps }, (s) => retried.push(s)) + assert.equal(maabcdStep(retried.at(-1))?.state, 'succeeded') + assert.equal(retried.at(-1)?.checkpoint?.maabcdShared, true) + assert.deepEqual(retried.at(-1)?.steps.filter((s) => s.id !== 'maabcd'), last.steps.filter((s) => s.id !== 'maabcd'), + 'the other rows stay as they were') assert.equal(attempts(), 2) assert.equal(count(f.calls, 'run'), runs, 'nothing else runs again') }) @@ -520,3 +522,48 @@ test('another file, protocol or sharing choice starts over instead of carrying o assert.equal(count(f.calls, 'upload'), 2, 'the other file is uploaded') }) + +// ── After a page reload: the checkpoint comes back from storage, the file doesn't ───────────────── + +/** The checkpoint as it comes back from localStorage. */ +const reloaded = (s: RunState) => JSON.parse(JSON.stringify(s.checkpoint)) as RunState['checkpoint'] + +test('after a reload, a run whose upload was done carries on without the file', async () => { + const f = fakes() + failFirst(f, 'importResource', 1, (_t, input) => input.resourceType === 'e') + const first = (await run(f, { file: data })).at(-1)! + + const last = (await run(f, { file: null, workspaceId: first.workspaceId, resume: reloaded(first) })).at(-1)! + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(count(f.calls, 'upload'), 1, 'not uploaded again') + assert.equal(last.steps.find((s) => s.id === 'upload')?.detail, 'Done earlier') + assert.equal(f.runInput()?.inputDir?.endsWith('/inputs'), true, 'the run still reads the upload, not example data') +}) + +test('notebooks already submitted when the page went are followed, not submitted again', async () => { + const f = fakes() + const stop = { current: false } + const startRun = f.api.startRun.bind(f.api) + f.api.startRun = async (...args) => { const r = await startRun(...args); stop.current = true; return r } + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, f.store)( + { protocol: FOUR_CHOICE, file: data, workspaceName: 'Four-choice' }, (s) => states.push(s), stop) + const first = states.at(-1)! + assert.ok(first.checkpoint?.submitted?.length, 'saved as submitted') + + const last = (await run(f, { file: null, workspaceId: first.workspaceId, resume: reloaded(first) })).at(-1)! + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(count(f.calls, 'run'), 1, 'submitted once') + assert.equal(count(f.calls, 'import:g'), 1, 'nothing imported again') +}) + +test('a run picked up again whose workspace was deleted says so', async () => { + const f = fakes() + failFirst(f, 'importResource', 1, (_t, input) => input.resourceType === 'e') + const first = (await run(f, { file: data })).at(-1)! + f.api.getWorkspaceOwner = async () => null + + const last = (await run(f, { file: null, workspaceId: first.workspaceId, resume: reloaded(first) })).at(-1)! + assert.equal(last.phase, 'failed') + assert.match(last.error ?? '', /no longer exists/) +}) diff --git a/applications/idp-arc/frontend/tests/unit/runStorage.test.ts b/applications/idp-arc/frontend/tests/unit/runStorage.test.ts new file mode 100644 index 0000000..5668414 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/runStorage.test.ts @@ -0,0 +1,57 @@ +// Saving the upload dialog's run across reloads (components/runStorage.ts). Run: yarn test:unit +import { test } from 'node:test' +import assert from 'node:assert/strict' +import { clearAllRuns, clearRun, loadRun, saveRun, withRunLock } from '../../src/components/runStorage' + +/** An in-memory Storage. */ +function memory(): Storage { + const items = new Map() + return { + get length() { return items.size }, + key: (i) => [...items.keys()][i] ?? null, + getItem: (k) => items.get(k) ?? null, + setItem: (k, v) => { items.set(k, v) }, + removeItem: (k) => { items.delete(k) }, + clear: () => items.clear(), + } +} + +test('a saved run comes back for the same user only', () => { + const storage = memory() + saveRun('alice', { step: 'failed' }, storage) + assert.deepEqual(loadRun('alice', storage), { step: 'failed' }) + assert.equal(loadRun('bob', storage), null) + clearRun('alice', storage) + assert.equal(loadRun('alice', storage), null) +}) + +test('one saved by another version, or over a week ago, is dropped', () => { + const storage = memory() + storage.setItem('idp_run:alice', JSON.stringify({ version: 0, savedAt: Date.now(), run: { step: 'failed' } })) + assert.equal(loadRun('alice', storage), null) + storage.setItem('idp_run:alice', JSON.stringify({ version: 1, savedAt: Date.now() - 8 * 24 * 3600_000, run: { step: 'failed' } })) + assert.equal(loadRun('alice', storage), null) + assert.equal(storage.getItem('idp_run:alice'), null, 'and removed') +}) + +test('logout clears every user\'s run and nothing else', () => { + const storage = memory() + saveRun('alice', {}, storage) + saveRun('bob', {}, storage) + storage.setItem('other', 'kept') + clearAllRuns(storage) + assert.equal(storage.length, 1) + assert.equal(storage.getItem('other'), 'kept') +}) + +test('blocked storage is no storage, not an error', () => { + const blocked = { ...memory(), getItem: () => { throw new Error('denied') }, setItem: () => { throw new Error('denied') } } as Storage + assert.doesNotThrow(() => saveRun('alice', {}, blocked)) + assert.equal(loadRun('alice', blocked), null) +}) + +test('without the Web Locks API the run still runs', async () => { + let ran = false + assert.equal(await withRunLock('alice', async () => { ran = true }), true) + assert.ok(ran) +}) diff --git a/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts b/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts new file mode 100644 index 0000000..5ed834b --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts @@ -0,0 +1,54 @@ +// The upload dialog's state across reloads (components/uploadSession.ts). Run: yarn test:unit +import { test, beforeEach } from 'node:test' +import assert from 'node:assert/strict' + +/** An in-memory localStorage, installed before the module under test reads it. */ +const items = new Map() +Object.defineProperty(globalThis, 'localStorage', { + configurable: true, + value: { + get length() { return items.size }, + key: (i: number) => [...items.keys()][i] ?? null, + getItem: (k: string) => items.get(k) ?? null, + setItem: (k: string, v: string) => { items.set(k, v) }, + removeItem: (k: string) => { items.delete(k) }, + clear: () => items.clear(), + }, +}) +const { INITIAL_FORM, restoreSession, session } = await import('../../src/components/uploadSession') +const checkpoint = { protocolId: 'p', fileKey: 'animal_01.xlsx|1|1', shareWithMaabcd: true } +const saved = (user: string) => JSON.parse(items.get(`idp_run:${user}`) ?? 'null')?.run + +beforeEach(() => { session.set(INITIAL_FORM); items.clear() }) + +test('a run is saved for its user without the file, and cleared once its result is seen', () => { + restoreSession('alice') + session.set({ ...INITIAL_FORM, step: 'failed', protocol: 'Four', checkpoint, file: new File(['x'], 'animal_01.xlsx') }) + assert.equal(saved('alice').protocol, 'Four') + assert.equal('file' in saved('alice'), false) + + session.set((prev) => ({ ...prev, step: 'success', resultSeen: true })) + assert.equal(saved('alice'), undefined) +}) + +test('a run that was going when the page went comes back stopped, for Retry', () => { + items.set('idp_run:bob', JSON.stringify({ version: 1, savedAt: Date.now(), run: { + step: 'uploading', protocol: 'Four', checkpoint, dandisetId: '000123', spawnedWorkspaceId: 42, shareWithMaabcd: true, + outputsDir: '', uploadMessage: 'Running the notebooks…', + runSteps: [{ id: 'upload', label: 'Upload', state: 'succeeded' }, { id: 'run', label: 'Run', state: 'running', detail: 'Running' }], + } })) + restoreSession('bob') + const form = session.get() + assert.equal(form.step, 'failed') + assert.match(form.uploadMessage, /reloaded during the run/) + assert.deepEqual(form.runSteps.map((s) => s.state), ['succeeded', 'pending']) + assert.equal(form.spawnedWorkspaceId, 42) + assert.equal(form.file, null) +}) + +test('a run already open in the page is not replaced by a saved one', () => { + items.set('idp_run:carol', JSON.stringify({ version: 1, savedAt: Date.now(), run: { step: 'failed', protocol: 'Old', checkpoint, runSteps: [] } })) + session.set({ ...INITIAL_FORM, step: 'uploading', protocol: 'Current', checkpoint }) + restoreSession('carol') + assert.equal(session.get().protocol, 'Current') +}) From aab0205b3edfc562d2feff6c4b843a26051245da Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 23:01:38 +0530 Subject: [PATCH 23/32] IDP-52: choose the upload backend at build time; independent flow for each of the upload backend --- README.md | 10 +++++----- applications/idp-arc/Dockerfile | 5 ++++- .../idp-arc/frontend/src/app/container.ts | 8 +++++--- .../frontend/src/components/LoginDialog.tsx | 16 +++++++++------- .../frontend/src/core/use-cases/runProtocol.ts | 4 +++- .../frontend/src/locales/en/landingPage.json | 1 + .../frontend/tests/unit/runProtocol.test.ts | 7 ++++--- deployment/codefresh-dev.yaml | 1 + 8 files changed, 32 insertions(+), 20 deletions(-) diff --git a/README.md b/README.md index db9ca29..efaf1aa 100644 --- a/README.md +++ b/README.md @@ -70,17 +70,17 @@ Unit tests (no browser, no backend): yarn test:unit ``` -Uploads go to one of two places, chosen by `UPLOAD_BACKEND` in `src/app/container.ts`. Either -way, uploading needs both logins (EMBER-DANDI and OSB), and OSB imports the file into the -researcher's workspace from there. +Uploads go to one of two places, chosen at build time by `VITE_UPLOAD_BACKEND` (`ember` unless +it is `bucket`). Either way, OSB imports the file into the researcher's workspace from there. - **`ember`** (default): EMBER-DANDI, into the researcher's own dandiset and the protocol's - MAABCD dandiset (`maabcdAggregateDandisetId` in `src/data/protocols.json`). Needs `VITE_EMBER_CLIENT_ID`, + MAABCD dandiset (`maabcdAggregateDandisetId` in `src/data/protocols.json`). Needs both logins + (EMBER-DANDI and OSB), `VITE_EMBER_CLIENT_ID`, an EMBER-DANDI OAuth application (public client, PKCE) with `/ember-callback` as a redirect URI, and, for the MAABCD copy, the `DANDI_API_KEY` attribute on the OSB user named by `MAABCD_EMBER_USERNAME` (`container.ts`). - **`bucket`**: a public bucket open for anonymous writes, named by `VITE_UPLOAD_BUCKET_URL`. - Its CORS must allow PUT from this app's origin. + Its CORS must allow PUT from this app's origin. Needs only the OSB login. --- diff --git a/applications/idp-arc/Dockerfile b/applications/idp-arc/Dockerfile index 0adf557..eccee90 100644 --- a/applications/idp-arc/Dockerfile +++ b/applications/idp-arc/Dockerfile @@ -6,7 +6,10 @@ COPY frontend/package.json ./ COPY frontend/yarn.lock ./ RUN yarn install --frozen-lockfile COPY frontend/ ./ -# Baked into the bundle by Vite at build time; the Codefresh pipeline passes it as a build argument. +# Baked into the bundle by Vite at build time; the Codefresh pipeline passes them as build arguments. +# `bucket` sends uploads to VITE_UPLOAD_BUCKET_URL instead of EMBER-DANDI (the default). +ARG VITE_UPLOAD_BACKEND +ENV VITE_UPLOAD_BACKEND=${VITE_UPLOAD_BACKEND} ARG VITE_UPLOAD_BUCKET_URL ENV VITE_UPLOAD_BUCKET_URL=${VITE_UPLOAD_BUCKET_URL} # EMBER-DANDI OAuth application (public client, PKCE) registered for this IDP origin. diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index 0cc63ad..2e9df45 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -41,9 +41,11 @@ const WORKSPACES_LIST_URL = `${OSB_API_BASE}/proxy/workspaces/api/workspace?page=1&per_page=24&q=&tags=` const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` -/** Where uploads go: `ember` (EMBER-DANDI) or `bucket` (the public bucket named by - * VITE_UPLOAD_BUCKET_URL). Change it here to switch. */ -export const UPLOAD_BACKEND = 'ember' as 'bucket' | 'ember' +/** Where uploads go: EMBER-DANDI, or the public bucket at VITE_UPLOAD_BUCKET_URL. */ +export type UploadBackend = 'ember' | 'bucket' +/** VITE_UPLOAD_BACKEND; anything but `bucket` (unset included) is EMBER-DANDI. */ +const useBucket = import.meta.env.VITE_UPLOAD_BACKEND === 'bucket' +export const UPLOAD_BACKEND: UploadBackend = useBucket ? 'bucket' : 'ember' /** The OSB (Keycloak) user whose key (user attribute `DANDI_API_KEY`) signs the copy into the * protocol's MAABCD dandiset, and the DANDI deployment it goes to (dandi-cli's name). */ const MAABCD_EMBER_USERNAME = 'maabcd-consortium' diff --git a/applications/idp-arc/frontend/src/components/LoginDialog.tsx b/applications/idp-arc/frontend/src/components/LoginDialog.tsx index dec3cf6..9024d71 100644 --- a/applications/idp-arc/frontend/src/components/LoginDialog.tsx +++ b/applications/idp-arc/frontend/src/components/LoginDialog.tsx @@ -5,7 +5,7 @@ import CheckCircleOutlineIcon from '@mui/icons-material/CheckCircleOutlineOutlin import CloseIcon from '@mui/icons-material/Close' import { useTranslation } from 'react-i18next' -import { emberAuth, EmberPopupBlocked, EmberSignInCancelled } from '../app/container' +import { emberAuth, EmberPopupBlocked, EmberSignInCancelled, UPLOAD_BACKEND } from '../app/container' import { markLoginDialogReturn } from './loginReturn' export interface LoginDialogProps { @@ -62,24 +62,26 @@ export default function LoginDialog({ open, onClose, onOsbLogin, osbSignedIn, on ) } + // EMBER-DANDI only when uploads go there (UPLOAD_BACKEND); the bucket needs OSB's login alone. + const usesEmber = UPLOAD_BACKEND === 'ember' const rows = [ - { - n: '01', title: t('loginDialog.emberTitle'), description: t('loginDialog.emberDescription'), + ...(usesEmber ? [{ + title: t('loginDialog.emberTitle'), description: t('loginDialog.emberDescription'), signedIn: emberAuth.isConnected(), login: loginToEmber, waiting: emberWait, waitingText: t('loginDialog.emberWaiting'), error: emberError, - }, + }] : []), { - n: '02', title: t('loginDialog.osbTitle'), description: t('loginDialog.osbDescription'), + title: t('loginDialog.osbTitle'), description: t('loginDialog.osbDescription'), signedIn: osbSignedIn, login: () => void loginToOsb(), waiting: osbWait, waitingText: t('loginDialog.osbWaiting'), error: '', }, - ] + ].map((row, i) => ({ ...row, n: String(i + 1).padStart(2, '0') })) const text = { fontFamily: 'Inter, sans-serif', fontSize: '12px', lineHeight: '16px' } const button = { ...text, textTransform: 'none', borderRadius: 0, px: 1.25, py: 0.5, minWidth: 0, flexShrink: 0, gap: 0.5 } @@ -119,7 +121,7 @@ export default function LoginDialog({ open, onClose, onOsbLogin, osbSignedIn, on - {t('loginDialog.notice')} + {t(usesEmber ? 'loginDialog.notice' : 'loginDialog.noticeOsbOnly')} }> diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index fda6ca8..74faffd 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -151,10 +151,12 @@ export function createRunProtocolUseCase( objectStore: IObjectStore, ) { const token = (minValidity = 30) => auth.getToken(minValidity) + // The MAABCD copy is a step only where the store makes one: EMBER-DANDI, not the bucket. + const steps = STEPS.filter((s) => s.id !== RUN_STEP.maabcd || !!objectStore.shareWithMaabcd) return async function runProtocol(input: RunProtocolInput, report: OnRunState, abortRef?: { current: boolean }): Promise { const { protocol, file, finishedRun } = input - const progress = new RunProgress(report, finishedRun ?? STEPS.map((s) => ({ ...s, state: 'pending' })), input.workspaceId) + const progress = new RunProgress(report, finishedRun ?? steps.map((s) => ({ ...s, state: 'pending' })), input.workspaceId) const stopped = () => !!abortRef?.current const checkpoint: RunCheckpoint = canResume(input.resume, input) ? { ...input.resume } diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index 568198c..294aa54 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -69,6 +69,7 @@ "title": "Login", "subtitle": "Login or sign up to view or upload data.", "notice": "Login to both is required to upload & view your data.", + "noticeOsbOnly": "Login to Open Source Brain is required to upload & view your data.", "emberTitle": "EMBER-DANDI", "emberDescription": "Upload your data in EMBER-DANDI", "osbTitle": "Open Source Brain", diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index b6ef4a6..ed4318d 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -88,8 +88,9 @@ test('uploads, imports both into the run folder, waits, runs, and reports the ru assert.equal(last.phase, 'succeeded', last.error) assert.equal(last.workspaceId, 42) - // No MAABCD dandiset for this protocol: that step is skipped. - assert.deepEqual(last.steps.map((s) => s.state), ['succeeded', 'skipped', ...Array(5).fill('succeeded')]) + // A store that makes no MAABCD copy (the bucket): that step isn't in the checklist. + assert.deepEqual(last.steps.map((s) => s.id), ['upload', 'workspace', 'repo', 'data', 'imports', 'run']) + assert.deepEqual(last.steps.map((s) => s.state), Array(6).fill('succeeded')) assert.ok(f.calls.includes('create:Four-choice:maabcd:four-choice-reversal')) // /run--/: the code and the upload, imported into the run's folder. @@ -163,7 +164,7 @@ test('without a file: no upload, no data import, the notebooks run on the exampl assert.equal(last.phase, 'succeeded') assert.deepEqual(f.imports.map((i) => i.resourceType), ['g']) assert.equal(f.runInput()?.inputDir, undefined) - assert.deepEqual(last.steps.filter((s) => s.state === 'skipped').map((s) => s.id), ['upload', 'maabcd', 'data']) + assert.deepEqual(last.steps.filter((s) => s.state === 'skipped').map((s) => s.id), ['upload', 'data']) }) test('a failed upload marks only the upload step failed', async () => { diff --git a/deployment/codefresh-dev.yaml b/deployment/codefresh-dev.yaml index a50b035..c5386e7 100644 --- a/deployment/codefresh-dev.yaml +++ b/deployment/codefresh-dev.yaml @@ -142,6 +142,7 @@ steps: build_arguments: - NOCACHE=${{CF_BUILD_ID}} - CLOUDHARNESS_FRONTEND_BUILD=${{REGISTRY}}/cloud-harness/cloudharness-frontend-build:${{CLOUDHARNESS_FRONTEND_BUILD_TAG}} + - VITE_UPLOAD_BACKEND=${{VITE_UPLOAD_BACKEND}} - VITE_UPLOAD_BUCKET_URL=${{VITE_UPLOAD_BUCKET_URL}} - VITE_EMBER_CLIENT_ID=${{VITE_EMBER_CLIENT_ID}} image_name: cloud-harness/idp-arc From 19f008082f4c93ed718745e740e3176254210388 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Mon, 26 Oct 2026 23:52:15 +0530 Subject: [PATCH 24/32] IDP-52: log clearly when the chosen upload backend isn't set up --- README.md | 8 ++++++-- applications/idp-arc/frontend/src/app/container.ts | 5 ++--- .../idp-arc/frontend/src/components/LoginDialog.tsx | 5 ++++- .../idp-arc/frontend/src/core/userMessages.ts | 4 ++++ .../idp-arc/frontend/src/infra/emberOAuthClient.ts | 11 ++++++++--- .../frontend/src/infra/publicBucketObjectStore.ts | 3 ++- .../idp-arc/frontend/tests/unit/objectStore.test.ts | 9 ++++++++- 7 files changed, 34 insertions(+), 11 deletions(-) diff --git a/README.md b/README.md index efaf1aa..c780488 100644 --- a/README.md +++ b/README.md @@ -70,8 +70,12 @@ Unit tests (no browser, no backend): yarn test:unit ``` -Uploads go to one of two places, chosen at build time by `VITE_UPLOAD_BACKEND` (`ember` unless -it is `bucket`). Either way, OSB imports the file into the researcher's workspace from there. +Uploads go to one of two places, chosen at build time by `VITE_UPLOAD_BACKEND`: `bucket`, or +EMBER-DANDI for any other value, including when it isn't set (the default). If the chosen backend +lacks what it needs (`VITE_EMBER_CLIENT_ID` for EMBER-DANDI, `VITE_UPLOAD_BUCKET_URL` for the +bucket), the rest of the site works, and signing in to EMBER-DANDI or uploading says uploads aren't +set up; the console names the missing variable. Either way, OSB imports the file into the +researcher's workspace from there. - **`ember`** (default): EMBER-DANDI, into the researcher's own dandiset and the protocol's MAABCD dandiset (`maabcdAggregateDandisetId` in `src/data/protocols.json`). Needs both logins diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index 2e9df45..4afa697 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -43,9 +43,8 @@ const OSB_WEB_ORIGIN = `${OSB_SCHEME}://www.${OSB_DOMAIN}` /** Where uploads go: EMBER-DANDI, or the public bucket at VITE_UPLOAD_BUCKET_URL. */ export type UploadBackend = 'ember' | 'bucket' -/** VITE_UPLOAD_BACKEND; anything but `bucket` (unset included) is EMBER-DANDI. */ -const useBucket = import.meta.env.VITE_UPLOAD_BACKEND === 'bucket' -export const UPLOAD_BACKEND: UploadBackend = useBucket ? 'bucket' : 'ember' +/** VITE_UPLOAD_BACKEND: `bucket`, or EMBER-DANDI for anything else, unset included. */ +export const UPLOAD_BACKEND: UploadBackend = import.meta.env.VITE_UPLOAD_BACKEND === 'bucket' ? 'bucket' : 'ember' /** The OSB (Keycloak) user whose key (user attribute `DANDI_API_KEY`) signs the copy into the * protocol's MAABCD dandiset, and the DANDI deployment it goes to (dandi-cli's name). */ const MAABCD_EMBER_USERNAME = 'maabcd-consortium' diff --git a/applications/idp-arc/frontend/src/components/LoginDialog.tsx b/applications/idp-arc/frontend/src/components/LoginDialog.tsx index 9024d71..f1dd3cd 100644 --- a/applications/idp-arc/frontend/src/components/LoginDialog.tsx +++ b/applications/idp-arc/frontend/src/components/LoginDialog.tsx @@ -44,7 +44,10 @@ export default function LoginDialog({ open, onClose, onOsbLogin, osbSignedIn, on try { attempt = emberAuth.connectInPopup() } catch (err) { - if (!(err instanceof EmberPopupBlocked)) throw err + if (!(err instanceof EmberPopupBlocked)) { + console.error('EMBER-DANDI sign-in could not start', err) + return setEmberError(err instanceof Error ? err.message : String(err)) + } // Popups blocked: the full-page redirect, back to this dialog afterwards. markLoginDialogReturn() void emberAuth.connect(window.location.pathname) diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 2bdd95f..49de780 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -35,6 +35,10 @@ export const DANDISET_NOT_PUBLISHABLE = "This dandiset can't be published yet. C /** A run picked up after a reload whose upload hadn't finished: the browser no longer has the file. */ export const finishUploadMessage = (fileName: string) => `Choose ${fileName} again to finish uploading it.` +/** This site's build lacks what the upload needs (the bucket's URL, EMBER's client id): ours to fix. */ +export const UPLOADS_NOT_SET_UP = "Uploads aren't set up on this site yet. Please let the MAABCD team know." +export const EMBER_LOGIN_NOT_SET_UP = "EMBER-DANDI sign-in isn't set up on this site yet. Please let the MAABCD team know." + /** Says the session has ended; the dialog sends the user to sign in when the text contains it. */ export const SIGN_IN_AGAIN = 'sign in again' diff --git a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts index 10a2bdb..46428ad 100644 --- a/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts @@ -1,4 +1,5 @@ import type { IEmberAuth } from '../core/ports/IEmberAuth' +import { EMBER_LOGIN_NOT_SET_UP, UserFacingError } from '../core/userMessages' /** * EMBER-DANDI OAuth via authorization-code + PKCE, run entirely in the browser. @@ -139,15 +140,18 @@ export class EmberOAuthClient implements IEmberAuth { return this.token } + /** No OAuth client in this build (VITE_EMBER_CLIENT_ID): signing in can't work. */ + private checkClientId(): void { + if (!this.config.clientId) throw new UserFacingError(EMBER_LOGIN_NOT_SET_UP, 'VITE_EMBER_CLIENT_ID is not set') + } + /** * Builds the authorize URL and stashes the PKCE verifier and the `state` this tab expects back. * `state` also tells the callback page whether it is a popup: EMBER's COOP header nulls * `window.opener` there, so the page can't tell otherwise. */ private async authorizeUrl(redirectUri: string, state: string): Promise { - if (!this.config.clientId) { - throw new Error('VITE_EMBER_CLIENT_ID is not set; register a public OAuth client first.') - } + this.checkClientId() const verifier = base64url(crypto.getRandomValues(new Uint8Array(48)).buffer) write(VERIFIER_KEY, verifier) write(STATE_KEY, state) @@ -194,6 +198,7 @@ export class EmberOAuthClient implements IEmberAuth { * is set once the PKCE challenge is ready. Throws EmberPopupBlocked when it can't be opened. */ connectInPopup(): { done: Promise; cancel: () => void } { + this.checkClientId() // before opening a popup that couldn't sign in const popup = window.open('', 'ember-login', popupFeatures(520, 720)) if (!popup) throw new EmberPopupBlocked('The EMBER-DANDI sign-in window was blocked') const state = `${POPUP_STATE_PREFIX}${nonce()}` diff --git a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts index b0873e4..4d773d9 100644 --- a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts +++ b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts @@ -1,4 +1,5 @@ import type { IObjectStore, ObjectUploadInput, StoredObject } from '../core/ports/IObjectStore' +import { UPLOADS_NOT_SET_UP, UserFacingError } from '../core/userMessages' /** * PUTs straight from the browser to a bucket open for anonymous writes (VITE_UPLOAD_BUCKET_URL). @@ -20,7 +21,7 @@ export class PublicBucketObjectStore implements IObjectStore { } put(input: ObjectUploadInput, onProgress?: (sentBytes: number, totalBytes: number) => void): Promise { - if (!this.baseUrl) return Promise.reject(new Error('No upload bucket is configured (VITE_UPLOAD_BUCKET_URL)')) + if (!this.baseUrl) return Promise.reject(new UserFacingError(UPLOADS_NOT_SET_UP, 'No upload bucket is configured (VITE_UPLOAD_BUCKET_URL)')) const key = objectKey(input.protocolId, input.userSub, crypto.randomUUID(), input.file.name) const url = `${this.baseUrl}/${key.split('/').map(encodeURIComponent).join('/')}` const { file } = input diff --git a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts index e26ceba..599cf43 100644 --- a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts @@ -1,7 +1,8 @@ // The public-bucket object store (infra/publicBucketObjectStore.ts). Run: yarn test:unit import { test } from 'node:test' import assert from 'node:assert/strict' -import { objectKey } from '../../src/infra/publicBucketObjectStore' +import { objectKey, PublicBucketObjectStore } from '../../src/infra/publicBucketObjectStore' +import { UPLOADS_NOT_SET_UP, UserFacingError } from '../../src/core/userMessages' test('object key follows uploads////', () => { assert.equal( @@ -16,3 +17,9 @@ test('object key segments are path-safe: no traversal, no slashes, no spaces', ( 'uploads/four-choice/user-lab.org/u-1/my-cohort.zip', ) }) + +test('without a bucket URL the upload fails with a message for the user, before anything is sent', async () => { + const file = new File(['x'], 'animal_01.xlsx') + await assert.rejects(new PublicBucketObjectStore(undefined).put({ file, protocolId: 'p', userSub: 'u' }), + (err: unknown) => err instanceof UserFacingError && err.message === UPLOADS_NOT_SET_UP && /VITE_UPLOAD_BUCKET_URL/.test(err.details ?? '')) +}) From 404f90850b9d7ce704ddf68188bbb52509893696 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 08:47:06 +0530 Subject: [PATCH 25/32] IDP-52: 404 page for unknown URLs; fix EMBER-DANDI left in bucket mode --- applications/idp-arc/frontend/src/App.tsx | 2 ++ .../frontend/src/components/PageLayout.tsx | 4 ++-- .../idp-arc/frontend/src/core/userMessages.ts | 4 ++-- .../frontend/src/locales/en/common.json | 8 ++++++- .../frontend/src/locales/en/landingPage.json | 7 +++++- .../frontend/src/pages/LandingPage.tsx | 7 +++++- .../idp-arc/frontend/src/pages/NotFound.tsx | 24 +++++++++++++++++++ 7 files changed, 49 insertions(+), 7 deletions(-) create mode 100644 applications/idp-arc/frontend/src/pages/NotFound.tsx diff --git a/applications/idp-arc/frontend/src/App.tsx b/applications/idp-arc/frontend/src/App.tsx index e88bb8b..835e982 100644 --- a/applications/idp-arc/frontend/src/App.tsx +++ b/applications/idp-arc/frontend/src/App.tsx @@ -16,6 +16,7 @@ import Workspaces from './pages/Workspaces' import ProtocolsPage from './pages/ProtocolsPage' import AboutPage from './pages/AboutPage' import EmberCallback from './pages/EmberCallback' +import NotFound from './pages/NotFound' import { OSB_LOGIN_POPUP_NAME } from './components/loginReturn' /** @@ -53,6 +54,7 @@ const router = createBrowserRouter([ { path: '/protocols', element: }, { path: '/about', element: }, { path: EMBER_CALLBACK_PATH, element: }, + { path: '*', element: }, ]) function App() { diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 3c705d4..1524e2e 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -144,7 +144,7 @@ export default function PageLayout({ setEmberSignedIn(false) if (isAuthenticated) authClient.logout() } - const anySignedIn = isAuthenticated || emberSignedIn + const anySignedIn = isAuthenticated || (needsEmber && emberSignedIn) // Re-registered on every render, so buttons outside this component never call a stale copy. useEffect(() => { registerUploadOpener(openUploadOrLogin) }) @@ -163,7 +163,7 @@ export default function PageLayout({ { label: t('nav.about'), path: '/about' }, ...(isAuthenticated ? [ { label: t('nav.myWorkspaces'), path: OSB_WORKSPACES_URL, external: true }, - { label: t('nav.myDandisets'), path: MY_DANDISETS_URL, external: true }, + ...(needsEmber ? [{ label: t('nav.myDandisets'), path: MY_DANDISETS_URL, external: true }] : []), ] : []), ] diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 49de780..6bae33a 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -36,8 +36,8 @@ export const DANDISET_NOT_PUBLISHABLE = "This dandiset can't be published yet. C export const finishUploadMessage = (fileName: string) => `Choose ${fileName} again to finish uploading it.` /** This site's build lacks what the upload needs (the bucket's URL, EMBER's client id): ours to fix. */ -export const UPLOADS_NOT_SET_UP = "Uploads aren't set up on this site yet. Please let the MAABCD team know." -export const EMBER_LOGIN_NOT_SET_UP = "EMBER-DANDI sign-in isn't set up on this site yet. Please let the MAABCD team know." +export const UPLOADS_NOT_SET_UP = "Uploads aren't set up on this site yet." +export const EMBER_LOGIN_NOT_SET_UP = "EMBER-DANDI sign-in isn't set up on this site yet." /** Says the session has ended; the dialog sends the user to sign in when the text contains it. */ export const SIGN_IN_AGAIN = 'sign in again' diff --git a/applications/idp-arc/frontend/src/locales/en/common.json b/applications/idp-arc/frontend/src/locales/en/common.json index 5ac5c99..cf89319 100644 --- a/applications/idp-arc/frontend/src/locales/en/common.json +++ b/applications/idp-arc/frontend/src/locales/en/common.json @@ -1,5 +1,11 @@ { - "app": { + "notFound": { + "title": "404", + "heading": "Page not found", + "body": "There is no page at this address. It may have moved, or the link may be mistyped.", + "home": "Go to the home page" + }, + "app": { "title": "MAABCD" }, "auth": { diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index 294aa54..5a5400e 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -12,6 +12,7 @@ "ctaPath": "/protocols" }, { + "id": "upload", "title": "Upload data in EMBER-DANDI", "desc": "Share your experimental results with the research community. Sign in to upload dandisets to the Ember-Dandi platform.", "cta": "Data upload", @@ -39,6 +40,10 @@ "body2": "In the long term we are interested in understanding a) if there are different dimensions of adversity which have separable effects on brain and behavior and b) if there are sensitive periods for exposure. We hope to disseminate these protocols so many labs can similarly harmonize their data collection enabling comparisons of a wide variety of treatments on the same behavioral outcome metrics. Our project is supported by the BBQS R34.", "learnMore": "Learn more" }, + "uploadFeatureBucket": { + "title": "Upload your data", + "desc": "Share your experimental results with the research community. Sign in to upload your data and analyse it in Open Source Brain." + }, "nav": { "logoTitle": "MAABCD Platform", "protocols": "Protocols", @@ -69,7 +74,7 @@ "title": "Login", "subtitle": "Login or sign up to view or upload data.", "notice": "Login to both is required to upload & view your data.", - "noticeOsbOnly": "Login to Open Source Brain is required to upload & view your data.", + "noticeOsbOnly": "Login to Open Source Brain is required to upload and analyse your data.", "emberTitle": "EMBER-DANDI", "emberDescription": "Upload your data in EMBER-DANDI", "osbTitle": "Open Source Brain", diff --git a/applications/idp-arc/frontend/src/pages/LandingPage.tsx b/applications/idp-arc/frontend/src/pages/LandingPage.tsx index 6828caa..f0210e1 100644 --- a/applications/idp-arc/frontend/src/pages/LandingPage.tsx +++ b/applications/idp-arc/frontend/src/pages/LandingPage.tsx @@ -13,6 +13,7 @@ import { import { useTranslation } from 'react-i18next' import { useNavigate } from 'react-router-dom' import PageLayout from '../components/PageLayout' +import { UPLOAD_BACKEND } from '../app/container' import { openUpload } from '../components/UploadContext' const ArrowIcon = () => @@ -23,7 +24,11 @@ export default function LandingPage() { const navigate = useNavigate() - const features = t('features', { returnObjects: true }) as Array<{ title: string; desc: string; cta: string; ctaPath: string }> + type Feature = { id?: string; title: string; desc: string; cta: string; ctaPath: string } + // The upload card names where uploads go: EMBER-DANDI, or the bucket (UPLOAD_BACKEND). + const bucketUpload = t('uploadFeatureBucket', { returnObjects: true }) as Pick + const features = (t('features', { returnObjects: true }) as Feature[]) + .map((f) => (f.id === 'upload' && UPLOAD_BACKEND === 'bucket' ? { ...f, ...bucketUpload } : f)) const protocols = t('protocols.items', { returnObjects: true }) as Array<{ name: string; desc: string }> diff --git a/applications/idp-arc/frontend/src/pages/NotFound.tsx b/applications/idp-arc/frontend/src/pages/NotFound.tsx new file mode 100644 index 0000000..d9baa02 --- /dev/null +++ b/applications/idp-arc/frontend/src/pages/NotFound.tsx @@ -0,0 +1,24 @@ +import { Button, Container, Stack, Typography } from '@mui/material' +import ArrowForwardIcon from '@mui/icons-material/ArrowForward' +import { useTranslation } from 'react-i18next' +import { useNavigate } from 'react-router-dom' +import PageLayout from '../components/PageLayout' + +/** 404: any URL the app has no page for. */ +export default function NotFound() { + const { t } = useTranslation() + const navigate = useNavigate() + return ( + + + + {t('notFound.heading')} + {t('notFound.body')} + + + + + ) +} From 4e924fd50d0a8dec229b98d58efcc2bd74a31655 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 12:07:29 +0530 Subject: [PATCH 26/32] IDP-52: stopped runs name the step and why; Retry on the row; plainer copy --- .../src/components/DataUploadDialog.tsx | 97 ++++++++++++------- .../frontend/src/components/PageLayout.tsx | 3 +- .../frontend/src/components/RunChecklist.tsx | 10 +- .../frontend/src/components/uploadSession.ts | 4 +- .../src/core/use-cases/runProgress.ts | 8 +- .../src/core/use-cases/runProtocol.ts | 22 ++--- .../idp-arc/frontend/src/core/userMessages.ts | 21 +++- .../frontend/src/locales/en/landingPage.json | 8 +- .../frontend/tests/unit/runProtocol.test.ts | 12 ++- .../frontend/tests/unit/uploadSession.test.ts | 2 +- 10 files changed, 125 insertions(+), 62 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index 992f889..311e92c 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -22,16 +22,16 @@ import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' -import { EMBER_SIGN_IN, finishUploadMessage, UserFacingError, userMessage } from '../core/userMessages' +import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages' import { withRunLock } from './runStorage' import { INITIAL_FORM, restoreSession, session } from './uploadSession' import { useAppContext } from '../AppContext' -import { RUN_STEP, type RunStep, type RunStepId } from '../core/types' +import { RUN_STEP, type RunCheckpoint, type RunState, type RunStep, type RunStepId } from '../core/types' import RunChecklist from './RunChecklist' import { useSessionStore } from './sessionStore' import DoiField from './DoiField' import { inputFileProblem, inputFormatsFor } from '../core/inputFormats' -import { canResume, fileKeyName, PUBLISH_STEP, PUBLISHING_LABEL, type RunProtocolInput } from '../core/use-cases/runProtocol' +import { isNonBlocking, PUBLISH_STEP, PUBLISHING_LABEL, type RunProtocolInput } from '../core/use-cases/runProtocol' import { formatBytes } from '../core/formatBytes' import { templatesZipFileName, templatesZipHref } from '../core/protocolTemplates' import { SIGN_IN_AGAIN } from '../core/userMessages' @@ -53,6 +53,18 @@ const setForm = session.set /** The run being watched; each run gets its own token, so stopping one never revives another. */ let currentWatch: { current: boolean } | null = null const RUN_IN_OTHER_TAB = 'This run is going on in another tab.' +/** The run's steps and checkpoint, with the rows a Retry of their own settled kept over what the + * run (still going, or saved) reports; a shared MAABCD copy is then done for the run too. */ +function withRetriedRows(runSteps: RunStep[], checkpoint: RunCheckpoint | undefined, retriedRows: RunStep[] = []) { + const shared = retriedRows.some((s) => s.id === RUN_STEP.maabcd && s.state === 'succeeded') + return { + runSteps: runSteps.map((s) => retriedRows.find((r) => r.id === s.id) ?? s), + checkpoint: checkpoint && shared ? { ...checkpoint, maabcdShared: true } : checkpoint, + } +} + +/** How long a Retry shows that it is trying, even when it fails at once. */ +const MIN_ATTEMPT_MS = 300 export default function DataUploadDialog({ open, initialProtocol, onClose, onAuthRequired }: DataUploadDialogProps) { const { tokenParsed } = useAppContext() @@ -84,6 +96,9 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut return () => window.removeEventListener('beforeunload', warn) }, [step]) + /** Leaves this run (it stays on OSB and EMBER) for a fresh form on the same protocol; nothing is kept for it. */ + const startNewUpload = () => setForm({ ...INITIAL_FORM, protocol }) + /** A fresh form, on the protocol the dialog was opened for. */ const freshForm = () => setForm({ ...INITIAL_FORM, protocol: runnableProtocols.some((p) => p.name === initialProtocol) ? initialProtocol! : '', @@ -169,7 +184,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut // Picked up after a reload: the file is needed again unless it was already uploaded. if (!file) { if (checkpoint?.stored) return runLocked(selectedProtocol, null) - return setForm((prev) => ({ ...prev, step: 'upload', uploadMessage: finishUploadMessage(fileKeyName(checkpoint?.fileKey)) })) + return setForm((prev) => ({ ...prev, step: 'upload', uploadMessage: '' })) } return runLocked(selectedProtocol, file) } @@ -194,15 +209,19 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut }) const startRun = async (selectedProtocol: RunnableProtocol, file: File | null) => { - setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [], doi: undefined, publishing: undefined })) + setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [], doi: undefined, publishing: undefined, retriedRows: [] })) if (currentWatch) currentWatch.current = true const watch = { current: false } currentWatch = watch + const started = Date.now() await runProtocol( inputFor(selectedProtocol, file), - (state) => { + function report(state: RunState): void { if (watch.current) return // another run started: no longer this one's + // A run that fails at once still shows, briefly, that it tried. + const wait = state.phase === 'failed' ? MIN_ATTEMPT_MS - (Date.now() - started) : 0 + if (wait > 0) return void setTimeout(() => report(state), wait) if (state.phase === 'failed' && state.error?.toLowerCase().includes(SIGN_IN_AGAIN)) { setForm((prev) => ({ ...prev, step: 'upload', uploadMessage: '', spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, @@ -226,10 +245,10 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, // A dandiset this run created is reused by a retry, not created again. dandisetId: state.dandisetId ?? prev.dandisetId, - uploadMessage: state.phase === 'failed' ? `${state.message}: ${state.error}` : state.message, + // A failed row already says why; otherwise the headline does. + uploadMessage: state.phase === 'failed' && !state.steps.some((s) => s.state === 'failed') ? `${state.message}: ${state.error}` : state.message, outputsDir: state.outputsDir ?? prev.outputsDir, - runSteps: state.steps, - checkpoint: state.checkpoint ?? prev.checkpoint, + ...withRetriedRows(state.steps, state.checkpoint ?? prev.checkpoint, prev.retriedRows), ...(state.phase === 'succeeded' ? { step: 'success' } : {}), ...(state.phase === 'stillRunning' ? { step: 'stillRunning' } : {}), ...(state.phase === 'failed' ? { step: 'failed' } : {}), @@ -253,26 +272,30 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut } /** A finished run's Retry: only its failed non-blocking steps run again, and only their rows change. */ - const retryFinishedRun = async () => { + /** A failed non-blocking row's Retry, any time: only that step runs, on the checklist as shown. */ + const retryNonBlockingRow = async (id: RunStepId) => { if (!selectedProtocol) return - await withRunLock(user ?? '', () => runProtocol( - { ...inputFor(selectedProtocol, file), finishedRun: runSteps }, - (state) => setForm((prev) => ({ ...prev, runSteps: state.steps, checkpoint: state.checkpoint ?? prev.checkpoint })), - )) + const started = Date.now() + await runProtocol( + { ...inputFor(selectedProtocol, file), retryNonBlockingOf: runSteps }, + function report(state: RunState): void { + // Its outcome waits until the row has shown, briefly, that it is trying. + const wait = state.steps.some((s) => s.state === 'running') ? 0 : MIN_ATTEMPT_MS - (Date.now() - started) + if (wait > 0) return void setTimeout(() => report(state), wait) + const row = state.steps.find((s) => s.id === id) + setForm((prev) => { + const retriedRows = [...(prev.retriedRows ?? []).filter((s) => s.id !== id), ...(row ? [row] : [])] + return { ...prev, retriedRows, ...withRetriedRows(prev.runSteps, prev.checkpoint, retriedRows) } + }) + }, + ) } - // Every failed row has Retry while no run is going: a stopped run carries on, a finished one retries only those rows. - const failedRows = step === 'uploading' ? [] : runSteps.filter((s) => s.state === 'failed') - const rowRetry = finished ? retryFinishedRun : handleUpload - const rowActions: Partial> = Object.fromEntries( - failedRows.map((s) => [s.id, ])) - - // "Retry" only when an earlier attempt can be carried on (same protocol, file, dandiset and - // sharing choice); choosing a dandiset that already has a workspace is still a new run. - const resumable = !!selectedProtocol && canResume(checkpoint, { - protocol: selectedProtocol, file, workspaceName: selectedProtocol.name, - workspaceId: spawnedWorkspaceId, dandisetId: dandisetId || undefined, shareWithMaabcd, - }) + // Each failed row has Retry: a non-blocking one any time; a blocking one once the run has stopped. + const failedRows = runSteps.filter((s) => s.state === 'failed' && (isNonBlocking(s.id) || step === 'failed')) + const footerRetry = step === 'failed' && !failedRows.some((s) => !isNonBlocking(s.id)) + const rowActions: Partial> = Object.fromEntries(failedRows.map((s) => [s.id, + ])) const stepIndex = step === 'select' ? 0 : 1 const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null)) @@ -480,7 +503,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut {usesEmber && ( {dandisetId ? `Uploading into your dandiset ${dandisetId}` : 'Uploading into a new dandiset in your EMBER-DANDI account'} - {spawnedWorkspaceId !== undefined ? `, analysed in workspace ${spawnedWorkspaceId}.` : ', analysed in a new workspace.'} + {spawnedWorkspaceId !== undefined ? `, analyzed in workspace ${spawnedWorkspaceId}.` : ', analyzed in a new workspace.'} )} @@ -558,7 +581,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut {/* Running, finished or failed: the same checklist, with a different header */} {(step === 'uploading' || step === 'success' || step === 'stillRunning' || step === 'failed') && ( - + // One scroll: its children keep their height instead of shrinking to fit. + *': { flexShrink: 0 } }}> {step === 'uploading' && } {step === 'success' && } @@ -625,17 +649,24 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut disabled={!canUpload} onClick={handleUpload} > - {resumable ? 'Retry' : 'Upload and run'} + {/* The same file carries on its stopped run (its checklist says "Done earlier"); another starts a new one. */} + Upload and run )} - {step === 'failed' && ( + {(step === 'failed' || finished) && ( - + )} + {/* For a failure no row shows: before any step, or a run cut off by a reload. */} - {failedRows.length === 0 && ( + {footerRetry && ( diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 1524e2e..830824e 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -154,7 +154,8 @@ export default function PageLayout({ useEffect(() => { if (savedRunOffered || typeof user !== 'string' || loginDialogOpen) return savedRunOffered = true - if (loadRun(user)) void openUploadOrLogin() + // Only a run cut off while it was going; a stopped or finished one waits for Data upload. + if (loadRun<{ step?: string }>(user)?.step === 'uploading') void openUploadOrLogin() // eslint-disable-next-line react-hooks/exhaustive-deps }, [user, loginDialogOpen]) diff --git a/applications/idp-arc/frontend/src/components/RunChecklist.tsx b/applications/idp-arc/frontend/src/components/RunChecklist.tsx index 9f41ca4..1f2b667 100644 --- a/applications/idp-arc/frontend/src/components/RunChecklist.tsx +++ b/applications/idp-arc/frontend/src/components/RunChecklist.tsx @@ -6,6 +6,7 @@ import RemoveCircleOutlineIcon from '@mui/icons-material/RemoveCircleOutlineOutl import type { ReactNode } from 'react' import type { RunStep, RunStepId, StepState } from '../core/types' +import { DONE_EARLIER } from '../core/userMessages' const STEP_ICON_SX = { fontSize: 20, flexShrink: 0, mt: '1px' } @@ -31,17 +32,20 @@ export default function RunChecklist({ steps, actions = {} }: { steps: RunStep[] {steps.map((s) => ( - + {s.label} + {/* A skipped step's note stays on its line; others get one of their own. */} + {s.detail === DONE_EARLIER && · {DONE_EARLIER}} - {s.detail && ( + {s.detail && s.detail !== DONE_EARLIER && ( {s.detail} )} - {actions[s.id]} + {/* On the row's right: e.g. its own Retry. */} + {actions[s.id] && {actions[s.id]}} ))} diff --git a/applications/idp-arc/frontend/src/components/uploadSession.ts b/applications/idp-arc/frontend/src/components/uploadSession.ts index 39583d5..842d0b3 100644 --- a/applications/idp-arc/frontend/src/components/uploadSession.ts +++ b/applications/idp-arc/frontend/src/components/uploadSession.ts @@ -36,6 +36,8 @@ export interface FormState { checkpoint?: RunCheckpoint /** The finished run's result has been on screen: the next opening starts a new upload. */ resultSeen?: boolean + /** Rows a Retry of their own settled while the run went on: kept over what the run reports. */ + retriedRows?: RunStep[] } export const INITIAL_FORM: FormState = { @@ -57,7 +59,7 @@ export const session = createSessionStore(INITIAL_FORM) type SavedRun = Pick -const RUN_INTERRUPTED = 'The page was reloaded during the run. Retry to carry on from where it stopped.' +const RUN_INTERRUPTED = 'The run stopped unexpectedly. Retry to carry on from where it stopped.' /** The user whose run is saved, once known. */ let savingFor: string | null = null diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts index 69ee967..c105aec 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProgress.ts @@ -1,5 +1,5 @@ import type { RunCheckpoint, RunPhase, RunState, RunStep, RunStepId, StepState } from '../types' -import { UserFacingError, userMessage } from '../userMessages' +import { stoppedMessage, UserFacingError, userMessage } from '../userMessages' export type OnRunState = (state: RunState) => void @@ -95,10 +95,12 @@ export class RunProgress { const failed = err instanceof StepError ? err.step : this.steps.find((s) => s.state === 'running')?.id const cause = err instanceof StepError ? err.original : err console.error(cause instanceof UserFacingError && cause.details ? cause.details : cause) + const error = userMessage(cause, failed) + // The failed row says why, in place of its last progress. this.steps = this.steps.map((s) => - s.id === failed ? { ...s, state: 'failed' } : s.state === 'running' ? { ...s, state: 'pending', detail: undefined } : s) + s.id === failed ? { ...s, state: 'failed', detail: error } : s.state === 'running' ? { ...s, state: 'pending', detail: undefined } : s) this.phase = 'failed' - this.emit('The analysis did not complete', userMessage(cause, failed)) + this.emit(stoppedMessage(failed), error) } emit(message: string, error?: string) { diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 74faffd..e1a2429 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -6,7 +6,7 @@ import { formatBytes } from '../formatBytes' import { inputFileProblem } from '../inputFormats' import { parseRepoZipUrl, repoPage } from '../protocolRepo' import { RUN_SETTINGS } from '../runSettings' -import { UserFacingError, userMessage } from '../userMessages' +import { DONE_EARLIER, UserFacingError, userMessage } from '../userMessages' import { workspaceLayout } from '../workspaceLayout' import { inStep, pollUntil, RunProgress, type OnRunState } from './runProgress' @@ -49,20 +49,18 @@ export interface RunProtocolInput { shareWithMaabcd?: boolean /** From an earlier attempt that stopped: the run carries on from there when canResume allows. */ resume?: RunCheckpoint - /** The checklist of a run that finished: only its failed non-blocking steps run again, on it. */ - finishedRun?: RunStep[] + /** A checklist as last shown: only its failed non-blocking steps run again, on it (their Retry). */ + retryNonBlockingOf?: RunStep[] } +/** Steps whose failure doesn't stop the run: each has a Retry of its own, any time. */ +export const isNonBlocking = (id: RunStepId) => id === RUN_STEP.maabcd + /** Names a file well enough to tell it is the same one again: name, size, last modified. */ export function fileKey(file?: File | null): string | null { return file ? `${file.name}|${file.size}|${file.lastModified}` : null } -/** The file name in a fileKey. */ -export function fileKeyName(key?: string | null): string { - return key?.split('|')[0] || 'your file' -} - /** * Whether a checkpoint applies to this attempt: same protocol, same file, same sharing choice, and * the same dandiset and workspace (or the ones that attempt itself created). Otherwise the run @@ -155,8 +153,8 @@ export function createRunProtocolUseCase( const steps = STEPS.filter((s) => s.id !== RUN_STEP.maabcd || !!objectStore.shareWithMaabcd) return async function runProtocol(input: RunProtocolInput, report: OnRunState, abortRef?: { current: boolean }): Promise { - const { protocol, file, finishedRun } = input - const progress = new RunProgress(report, finishedRun ?? steps.map((s) => ({ ...s, state: 'pending' })), input.workspaceId) + const { protocol, file, retryNonBlockingOf } = input + const progress = new RunProgress(report, retryNonBlockingOf ?? steps.map((s) => ({ ...s, state: 'pending' })), input.workspaceId) const stopped = () => !!abortRef?.current const checkpoint: RunCheckpoint = canResume(input.resume, input) ? { ...input.resume } @@ -169,9 +167,9 @@ export function createRunProtocolUseCase( save({}) if (checkpoint.stored?.dandisetId) progress.dandisetId = checkpoint.stored.dandisetId if (checkpoint.workspaceId !== undefined) progress.workspaceId = checkpoint.workspaceId - const doneEarlier = (id: RunStepId) => progress.done(id, 'Done earlier') + const doneEarlier = (id: RunStepId) => progress.done(id, DONE_EARLIER) - if (finishedRun) return retryNonBlocking(finishedRun) + if (retryNonBlockingOf) return retryNonBlocking(retryNonBlockingOf) try { // Before anything moves: the protocol and the file. diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index 6bae33a..6695618 100644 --- a/applications/idp-arc/frontend/src/core/userMessages.ts +++ b/applications/idp-arc/frontend/src/core/userMessages.ts @@ -25,6 +25,24 @@ const STEP_FAILED: Record = { [RUN_STEP.doi]: 'Your data could not be published with a DOI. Please try again.', } +/** A step a retry skipped because an earlier attempt did it. */ +export const DONE_EARLIER = 'Done earlier' + +/** The headline when the run stops at a step; that step's row says why. */ +const STEP_STOPPED: Record = { + [RUN_STEP.upload]: "Your file wasn't uploaded", + [RUN_STEP.maabcd]: 'Not shared with the MAABCD consortium', + [RUN_STEP.workspace]: "The workspace isn't ready", + [RUN_STEP.repo]: "The analysis code wasn't added to the workspace", + [RUN_STEP.data]: "Your file wasn't added to the workspace", + [RUN_STEP.imports]: "The files weren't copied into the workspace", + [RUN_STEP.run]: 'The analysis did not complete', + [RUN_STEP.doi]: "Your dandiset wasn't published", +} + +/** The run's headline when it stops at `step`, or before any step. */ +export const stoppedMessage = (step?: RunStepId) => (step ? STEP_STOPPED[step] : 'The analysis did not complete') + /** Says the EMBER-DANDI session is missing or over. Deliberately not SIGN_IN_AGAIN's wording, * which sends the user to the OSB (Keycloak) login instead. */ export const EMBER_SIGN_IN = 'Please sign in with EMBER-DANDI and try again.' @@ -32,9 +50,6 @@ export const EMBER_SIGN_IN = 'Please sign in with EMBER-DANDI and try again.' /** EMBER refuses to publish the dandiset as it is (its metadata or a file); EMBER's editor says what to fix. */ export const DANDISET_NOT_PUBLISHABLE = "This dandiset can't be published yet. Check on EMBER-DANDI on specific errors." -/** A run picked up after a reload whose upload hadn't finished: the browser no longer has the file. */ -export const finishUploadMessage = (fileName: string) => `Choose ${fileName} again to finish uploading it.` - /** This site's build lacks what the upload needs (the bucket's URL, EMBER's client id): ours to fix. */ export const UPLOADS_NOT_SET_UP = "Uploads aren't set up on this site yet." export const EMBER_LOGIN_NOT_SET_UP = "EMBER-DANDI sign-in isn't set up on this site yet." diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index 5a5400e..4b0003e 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -20,7 +20,7 @@ }, { "title": "Use your data in Open Source Brain", - "desc": "Explore and analyze community data and your uploaded data with our integration with Open Source Brain (OSB). OSB lets you use interactive visualizations and powerful analysis tools with Jupyterlab, NetPyNE and NWB Explorer.", + "desc": "Explore and analyze your uploaded data in Open Source Brain (OSB), with interactive visualizations and analysis tools: JupyterLab, NetPyNE and NWB Explorer.", "cta": "Go to Open Source Brain", "ctaPath": "https://www.opensourcebrain.org/" } @@ -42,7 +42,7 @@ }, "uploadFeatureBucket": { "title": "Upload your data", - "desc": "Share your experimental results with the research community. Sign in to upload your data and analyse it in Open Source Brain." + "desc": "Share your experimental results with the research community. Sign in to upload your data and analyze it in Open Source Brain." }, "nav": { "logoTitle": "MAABCD Platform", @@ -74,11 +74,11 @@ "title": "Login", "subtitle": "Login or sign up to view or upload data.", "notice": "Login to both is required to upload & view your data.", - "noticeOsbOnly": "Login to Open Source Brain is required to upload and analyse your data.", + "noticeOsbOnly": "Login to Open Source Brain is required to upload and analyze your data.", "emberTitle": "EMBER-DANDI", "emberDescription": "Upload your data in EMBER-DANDI", "osbTitle": "Open Source Brain", - "osbDescription": "Explore and analyze your uploaded data and community data with our integration with Open Source Brain (OSB).", + "osbDescription": "Run the protocol's analysis on your uploaded data, in your own Open Source Brain (OSB) workspace.", "login": "Login", "signedIn": "Signed in", "loggedIn": "Logged in", diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index ed4318d..ba3f232 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -174,6 +174,16 @@ test('a failed upload marks only the upload step failed', async () => { // The user reads plain words; the 403 goes to the console. assert.equal(last.error, 'Your file could not be uploaded. Check your connection and try again.') assert.deepEqual(last.steps.filter((s) => s.state === 'failed').map((s) => s.id), ['upload']) + // The headline names the step; the row says why, not its last progress. + assert.equal(last.message, "Your file wasn't uploaded") + assert.equal(last.steps.find((s) => s.id === 'upload')?.detail, last.error) +}) + +test('a failure before any step keeps the general headline', async () => { + const last = (await run(fakes(), { file: new File([''], 'animal_01.xlsx') })).at(-1)! + assert.equal(last.phase, 'failed') + assert.equal(last.message, 'The analysis did not complete') + assert.equal(last.steps.some((s) => s.state === 'failed'), false) }) test('the run is followed through the workspace\'s placeholder: running while listed, finished once gone', async () => { @@ -379,7 +389,7 @@ test('a failed MAABCD copy fails only its own step; its Retry makes only the cop const runs = count(f.calls, 'run') const retried: RunState[] = [] await createRunProtocolUseCase(auth, f.api, store)( - { ...shared(), workspaceId: last.workspaceId, resume: last.checkpoint, finishedRun: last.steps }, (s) => retried.push(s)) + { ...shared(), workspaceId: last.workspaceId, resume: last.checkpoint, retryNonBlockingOf: last.steps }, (s) => retried.push(s)) assert.equal(maabcdStep(retried.at(-1))?.state, 'succeeded') assert.equal(retried.at(-1)?.checkpoint?.maabcdShared, true) assert.deepEqual(retried.at(-1)?.steps.filter((s) => s.id !== 'maabcd'), last.steps.filter((s) => s.id !== 'maabcd'), diff --git a/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts b/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts index 5ed834b..df17882 100644 --- a/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts +++ b/applications/idp-arc/frontend/tests/unit/uploadSession.test.ts @@ -40,7 +40,7 @@ test('a run that was going when the page went comes back stopped, for Retry', () restoreSession('bob') const form = session.get() assert.equal(form.step, 'failed') - assert.match(form.uploadMessage, /reloaded during the run/) + assert.match(form.uploadMessage, /stopped unexpectedly/) assert.deepEqual(form.runSteps.map((s) => s.state), ['succeeded', 'pending']) assert.equal(form.spawnedWorkspaceId, 42) assert.equal(form.file, null) From 8f99029ca67671bf9f0eaa4010215926694c2be4 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 12:11:53 +0530 Subject: [PATCH 27/32] IDP-52: fix the path/run folder when the imports wait fails for OSB unavailale --- .../frontend/src/components/uploadSession.ts | 9 ++++++- .../src/core/use-cases/runProtocol.ts | 24 +++++++++++------ .../frontend/tests/unit/runProtocol.test.ts | 26 +++++++++++++++++-- 3 files changed, 48 insertions(+), 11 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/uploadSession.ts b/applications/idp-arc/frontend/src/components/uploadSession.ts index 842d0b3..271b68a 100644 --- a/applications/idp-arc/frontend/src/components/uploadSession.ts +++ b/applications/idp-arc/frontend/src/components/uploadSession.ts @@ -63,9 +63,16 @@ const RUN_INTERRUPTED = 'The run stopped unexpectedly. Retry to carry on from wh /** The user whose run is saved, once known. */ let savingFor: string | null = null +/** Set when the page is reloaded or closed: the requests it cancels mid-run aren't saved as the run failing. */ +let leaving = false +if (typeof window !== 'undefined') { + window.addEventListener('pagehide', () => { leaving = true }) + // Back from the browser's back/forward cache: the page lives on. + window.addEventListener('pageshow', () => { leaving = false }) +} session.subscribe(() => { - if (!savingFor) return + if (!savingFor || leaving) return const { step, protocol, dandisetId, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage, resultSeen } = session.get() if (!checkpoint || resultSeen) return clearRun(savingFor) const run: SavedRun = { step, protocol, dandisetId, spawnedWorkspaceId, shareWithMaabcd, checkpoint, runSteps, outputsDir, uploadMessage } diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index e1a2429..59ce608 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -247,10 +247,6 @@ export function createRunProtocolUseCase( // a failed or half-finished import: the next attempt starts a new folder. if (stopped()) return false const notebooks = await inStep(RUN_STEP.imports, () => waitForImports(workspaceId, layout.run, repoDir)) - .catch((err: unknown) => { - save(NEW_RUN_FOLDER) - throw err - }) if (!notebooks) return false // 6. Run the notebooks. @@ -376,11 +372,19 @@ export function createRunProtocolUseCase( const ended = await pollUntil(async () => { resources = await workspaceApi.getWorkspaceResources(await token(), workspaceId) const failed = resources.find((r) => ours(r) && r.status === 'e') - if (failed) throw new Error(`OSB could not import ${failed.name}`) + if (failed) { + // OSB couldn't import it: the next attempt imports into a new folder. + save(NEW_RUN_FOLDER) + throw new Error(`OSB could not import ${failed.name}`) + } return !resources.some((r) => r.id === -1 || (ours(r) && r.status === 'p')) }, { everyMs: RUN_SETTINGS.importPollMs, timeoutMs: RUN_SETTINGS.importTimeoutMs, stopped }) - if (ended === 'timeout') throw new UserFacingError('Copying the files into the workspace is taking too long. Please try again later.', + if (ended === 'timeout') { + // Never finished: the next attempt imports into a new folder. + save(NEW_RUN_FOLDER) + throw new UserFacingError('Copying the files into the workspace is taking too long. Please try again later.', `The imports did not finish within ${RUN_SETTINGS.importTimeoutMs / 60_000} minutes`) + } if (ended !== 'done') return null // The visible notebooks directly in the notebooks folder, relative to the repository. const folderInRepo = `${protocol.notebooksDir}/` @@ -391,8 +395,12 @@ export function createRunProtocolUseCase( return path.startsWith(folderInRepo) && name.endsWith('.ipynb') && !name.includes('/') && !name.startsWith('.') }) .sort((a, b) => (a < b ? -1 : a > b ? 1 : 0)) - if (!notebooks.length) throw new UserFacingError('The analysis code has no notebooks to run. Please let the protocol\'s maintainers know.', - `No notebooks in ${repoDir}/${folderInRepo} after the import`) + if (!notebooks.length) { + // Imported, but not usable: the next attempt imports into a new folder. + save(NEW_RUN_FOLDER) + throw new UserFacingError('The analysis code has no notebooks to run. Please let the protocol\'s maintainers know.', + `No notebooks in ${repoDir}/${folderInRepo} after the import`) + } progress.done(RUN_STEP.imports) return notebooks } diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index ba3f232..a77985f 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -466,18 +466,40 @@ test('a retry after the data import failed imports only the data, into the same assert.deepEqual(last.steps.filter((s) => s.detail === 'Done earlier').map((s) => s.id), ['upload', 'repo']) }) -test('when waiting for the imports fails, the retry imports into a new run folder', async () => { +test('OSB unreachable while waiting for the imports: the retry waits on the same folder', async () => { const f = fakes() failFirst(f, 'getWorkspaceResources') const first = (await run(f, { file: data })).at(-1)! assert.equal(first.steps.find((s) => s.id === 'imports')?.state, 'failed') - assert.equal(first.checkpoint?.runFolderAt, undefined) + assert.ok(first.checkpoint?.runFolderAt, 'the folder is kept') const last = (await run(f, { file: data, workspaceId: first.workspaceId, resume: first.checkpoint })).at(-1)! assert.equal(last.phase, 'succeeded', last.error) assert.equal(count(f.calls, 'upload'), 1) assert.equal(count(f.calls, 'create'), 1) + assert.equal(count(f.calls, 'import:g'), 1, 'the code not imported again') + assert.equal(count(f.calls, 'import:e'), 1, 'the data not imported again') +}) + +test('an import OSB reports as failed: the retry imports into a new run folder', async () => { + const f = fakes() + const list = f.api.getWorkspaceResources.bind(f.api) + let failOnce = true + f.api.getWorkspaceResources = async (t, ws) => { + const dataImport = f.imports.find((i) => i.resourceType === 'e') + if (failOnce && dataImport) { + failOnce = false + return [{ id: 3, name: 'animal_01.xlsx', status: 'e', path: `${dataImport.folder}/animal_01.xlsx` }] + } + return list(t, ws) + } + const first = (await run(f, { file: data })).at(-1)! + assert.equal(first.checkpoint?.runFolderAt, undefined) + + const last = (await run(f, { file: data, workspaceId: first.workspaceId, resume: first.checkpoint })).at(-1)! + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(count(f.calls, 'upload'), 1) assert.equal(count(f.calls, 'import:g'), 2, 'the code imported again') assert.equal(count(f.calls, 'import:e'), 2, 'the data imported again') }) From 80a2430b6a9397bd43367d793d519b2056727248 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 12:13:27 +0530 Subject: [PATCH 28/32] IDP-52: an ended OSB session stops the run in place; it reopens after sign-in --- .../frontend/src/components/DataUploadDialog.tsx | 15 +++++---------- .../frontend/src/components/PageLayout.tsx | 8 ++++++-- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index 311e92c..cfc2603 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -222,14 +222,9 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut // A run that fails at once still shows, briefly, that it tried. const wait = state.phase === 'failed' ? MIN_ATTEMPT_MS - (Date.now() - started) : 0 if (wait > 0) return void setTimeout(() => report(state), wait) - if (state.phase === 'failed' && state.error?.toLowerCase().includes(SIGN_IN_AGAIN)) { - setForm((prev) => ({ - ...prev, step: 'upload', uploadMessage: '', spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, - checkpoint: state.checkpoint ?? prev.checkpoint, - })) - onAuthRequired?.() - return - } + // The OSB session ended: shown stopped like any failure; sign in, then Retry carries on. + const signInNeeded = state.phase === 'failed' && !!state.error?.toLowerCase().includes(SIGN_IN_AGAIN) + if (signInNeeded) onAuthRequired?.() if (state.phase === 'failed' && state.error === EMBER_SIGN_IN) { // The EMBER-DANDI session ended: back to the first step, which points to the Login // dialog. The checkpoint, dandiset and workspace stay, so the next attempt carries on. @@ -245,8 +240,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, // A dandiset this run created is reused by a retry, not created again. dandisetId: state.dandisetId ?? prev.dandisetId, - // A failed row already says why; otherwise the headline does. - uploadMessage: state.phase === 'failed' && !state.steps.some((s) => s.state === 'failed') ? `${state.message}: ${state.error}` : state.message, + // A failed row already says why; otherwise the headline does, except for a needed sign-in. + uploadMessage: state.phase === 'failed' && !signInNeeded && !state.steps.some((s) => s.state === 'failed') ? `${state.message}: ${state.error}` : state.message, outputsDir: state.outputsDir ?? prev.outputsDir, ...withRetriedRows(state.steps, state.checkpoint ?? prev.checkpoint, prev.retriedRows), ...(state.phase === 'succeeded' ? { step: 'success' } : {}), diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 830824e..1360499 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -28,6 +28,8 @@ import { registerUploadOpener } from './UploadContext' import LoginDialog from './LoginDialog' import { OSB_LOGIN_POPUP_NAME, takeLoginDialogReturn } from './loginReturn' import { clearAllRuns, loadRun } from './runStorage' +import type { RunStep } from '../core/types' +import { SIGN_IN_AGAIN } from '../core/userMessages' const ArrowIcon = () => @@ -154,8 +156,10 @@ export default function PageLayout({ useEffect(() => { if (savedRunOffered || typeof user !== 'string' || loginDialogOpen) return savedRunOffered = true - // Only a run cut off while it was going; a stopped or finished one waits for Data upload. - if (loadRun<{ step?: string }>(user)?.step === 'uploading') void openUploadOrLogin() + // Only a run cut off while it was going, or stopped for this sign-in; others wait for Data upload. + const saved = loadRun<{ step?: string; runSteps?: RunStep[] }>(user) + const stoppedForSignIn = saved?.step === 'failed' && !!saved.runSteps?.some((s) => s.detail?.toLowerCase().includes(SIGN_IN_AGAIN)) + if (saved?.step === 'uploading' || stoppedForSignIn) void openUploadOrLogin() // eslint-disable-next-line react-hooks/exhaustive-deps }, [user, loginDialogOpen]) From 5129b478f69eaf990b296d03d0852e8d6fe75df7 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 12:15:32 +0530 Subject: [PATCH 29/32] IDP-52: fix silent fail of OSB's sign-in when can't be reached --- .../frontend/src/components/LoginDialog.tsx | 18 ++++++++--- .../frontend/src/components/PageLayout.tsx | 30 +++++++++++-------- .../frontend/src/components/loginReturn.ts | 7 +++++ .../frontend/src/core/ports/IAuthClient.ts | 3 ++ .../frontend/src/infra/keycloakAuthClient.ts | 12 ++++++++ .../src/infra/mocks/mockAuthClient.ts | 4 +++ .../frontend/src/locales/en/landingPage.json | 1 + 7 files changed, 59 insertions(+), 16 deletions(-) diff --git a/applications/idp-arc/frontend/src/components/LoginDialog.tsx b/applications/idp-arc/frontend/src/components/LoginDialog.tsx index f1dd3cd..bfa900c 100644 --- a/applications/idp-arc/frontend/src/components/LoginDialog.tsx +++ b/applications/idp-arc/frontend/src/components/LoginDialog.tsx @@ -6,13 +6,14 @@ import CloseIcon from '@mui/icons-material/Close' import { useTranslation } from 'react-i18next' import { emberAuth, EmberPopupBlocked, EmberSignInCancelled, UPLOAD_BACKEND } from '../app/container' -import { markLoginDialogReturn } from './loginReturn' +import { markLoginDialogReturn, OsbUnreachable, takeLoginDialogReturn } from './loginReturn' export interface LoginDialogProps { open: boolean onClose: () => void /** Opens OSB's (Keycloak) login popup; `onEnded` when it closes without completing (completing - * reloads the page). Resolves to how to stop waiting, or null after a full-page redirect. */ + * reloads the page). Resolves to how to stop waiting, or null after a full-page redirect; + * rejects with OsbUnreachable when Keycloak doesn't answer. */ onOsbLogin: (onEnded: () => void) => Promise<{ cancel: () => void } | null> osbSignedIn: boolean /** EMBER-DANDI's sign-in finished in its popup (the page didn't reload). */ @@ -32,10 +33,19 @@ export default function LoginDialog({ open, onClose, onOsbLogin, osbSignedIn, on const [emberWait, setEmberWait] = useState<{ cancel: () => void } | null>(null) const [emberError, setEmberError] = useState('') const [osbWait, setOsbWait] = useState<{ cancel: () => void } | null>(null) + const [osbError, setOsbError] = useState('') const loginToOsb = async () => { + setOsbError('') markLoginDialogReturn() - setOsbWait(await onOsbLogin(() => setOsbWait(null))) + try { + setOsbWait(await onOsbLogin(() => setOsbWait(null))) + } catch (err) { + // The page stays, so there is no dialog to reopen. + takeLoginDialogReturn() + console.error('OSB sign-in could not start', err) + setOsbError(err instanceof OsbUnreachable ? t('loginDialog.osbUnreachable') : err instanceof Error ? err.message : String(err)) + } } const loginToEmber = () => { @@ -82,7 +92,7 @@ export default function LoginDialog({ open, onClose, onOsbLogin, osbSignedIn, on login: () => void loginToOsb(), waiting: osbWait, waitingText: t('loginDialog.osbWaiting'), - error: '', + error: osbError, }, ].map((row, i) => ({ ...row, n: String(i + 1).padStart(2, '0') })) diff --git a/applications/idp-arc/frontend/src/components/PageLayout.tsx b/applications/idp-arc/frontend/src/components/PageLayout.tsx index 1360499..2829a6d 100644 --- a/applications/idp-arc/frontend/src/components/PageLayout.tsx +++ b/applications/idp-arc/frontend/src/components/PageLayout.tsx @@ -26,7 +26,7 @@ import { Logo } from '../Icons' import DataUploadDialog from './DataUploadDialog' import { registerUploadOpener } from './UploadContext' import LoginDialog from './LoginDialog' -import { OSB_LOGIN_POPUP_NAME, takeLoginDialogReturn } from './loginReturn' +import { OSB_LOGIN_POPUP_NAME, OsbUnreachable, takeLoginDialogReturn } from './loginReturn' import { clearAllRuns, loadRun } from './runStorage' import type { RunStep } from '../core/types' import { SIGN_IN_AGAIN } from '../core/userMessages' @@ -73,26 +73,32 @@ export default function PageLayout({ /** * Opens OSB's (Keycloak) login in a popup. When it completes, the popup posts to this window and * App.tsx reloads the page; `onEnded` is for the popup being closed without that. Returns how to - * stop waiting, or null when it fell back to a full-page redirect. + * stop waiting, or null when it fell back to a full-page redirect. Throws OsbUnreachable when + * Keycloak doesn't answer. */ async function startOsbLogin(onEnded: () => void): Promise<{ cancel: () => void } | null> { - let loginUrl: string - try { - loginUrl = await authClient.getLoginUrl(`${window.location.origin}/`) - } catch { - // keycloak-js 26 + PKCE can throw if internal state is unset (e.g. after - // token expiry). Fall back to a full-page redirect via kc.login(). - authClient.login() - return null - } + // Opened blank before any wait, while the click still counts (popup blockers), then pointed at Keycloak. const w = 480, h = 600 const left = Math.round((screen.width - w) / 2) const top = Math.round((screen.height - h) / 2) - const popup = window.open(loginUrl, OSB_LOGIN_POPUP_NAME, `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`) + const popup = window.open('', OSB_LOGIN_POPUP_NAME, `width=${w},height=${h},left=${left},top=${top},toolbar=no,menubar=no`) + if (!(await authClient.isReachable())) { + popup?.close() + throw new OsbUnreachable() + } if (!popup) { authClient.login() return null } + try { + popup.location.href = await authClient.getLoginUrl(`${window.location.origin}/`) + } catch { + // keycloak-js 26 + PKCE can throw if internal state is unset (e.g. after + // token expiry). Fall back to a full-page redirect via kc.login(). + popup.close() + authClient.login() + return null + } const poll = setInterval(() => { if (popup.closed) { clearInterval(poll) diff --git a/applications/idp-arc/frontend/src/components/loginReturn.ts b/applications/idp-arc/frontend/src/components/loginReturn.ts index dacbbf9..72726b8 100644 --- a/applications/idp-arc/frontend/src/components/loginReturn.ts +++ b/applications/idp-arc/frontend/src/components/loginReturn.ts @@ -35,3 +35,10 @@ export function takeLoginDialogReturn(): boolean { * tell, since any tab opened by script without `noopener` (from an OSB page, say) has one too. */ export const OSB_LOGIN_POPUP_NAME = 'kc-login' + +/** OSB's login couldn't start: Keycloak didn't answer. */ +export class OsbUnreachable extends Error { + constructor() { + super("Open Source Brain's sign-in (Keycloak) could not be reached") + } +} diff --git a/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts b/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts index 3f03300..3dc9a6d 100644 --- a/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts +++ b/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts @@ -15,6 +15,9 @@ export interface IAuthClient { /** Returns the IdP login URL so callers can open it in a popup rather than redirecting. */ getLoginUrl(redirectUri: string): Promise + /** Whether the IdP answers at all, so a login isn't sent to a server that is down. */ + isReachable(): Promise + /** Redirects the user to the IdP login page. */ login(): void diff --git a/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts b/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts index 1b26be4..2228265 100644 --- a/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts @@ -9,10 +9,12 @@ import type { IAuthClient } from '../core/ports/IAuthClient' */ export class KeycloakAuthClient implements IAuthClient { private readonly kc: Keycloak + private readonly realmUrl: string private sessionEndedListeners: (() => void)[] = [] constructor(config: { url: string; realm: string; clientId: string }) { this.kc = new Keycloak(config) + this.realmUrl = `${config.url}/realms/${config.realm}` // keycloak-js clears its tokens when a refresh is refused (the Keycloak session is over). this.kc.onAuthLogout = () => this.sessionEnded() } @@ -62,6 +64,16 @@ export class KeycloakAuthClient implements IAuthClient { return this.kc.createLoginUrl({ redirectUri }) } + async isReachable(timeoutMs = 5000): Promise { + try { + // Any response counts (no-cors makes it opaque); only a network failure or the timeout doesn't. + await fetch(this.realmUrl, { mode: 'no-cors', cache: 'no-store', signal: AbortSignal.timeout(timeoutMs) }) + return true + } catch { + return false + } + } + login(): void { void this.kc.login() } diff --git a/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts b/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts index bcd49dc..3b04767 100644 --- a/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/mocks/mockAuthClient.ts @@ -21,6 +21,10 @@ export class MockAuthClient implements IAuthClient { return '/' } + async isReachable(): Promise { + return true + } + async init(): Promise { console.info('[MockAuthClient] init() → authenticated') return true diff --git a/applications/idp-arc/frontend/src/locales/en/landingPage.json b/applications/idp-arc/frontend/src/locales/en/landingPage.json index 4b0003e..e1fc2ec 100644 --- a/applications/idp-arc/frontend/src/locales/en/landingPage.json +++ b/applications/idp-arc/frontend/src/locales/en/landingPage.json @@ -84,6 +84,7 @@ "loggedIn": "Logged in", "emberWaiting": "Sign in in the EMBER-DANDI window…", "osbWaiting": "Sign in in the Open Source Brain window…", + "osbUnreachable": "Can't reach Open Source Brain's sign-in. Check your connection and try again.", "finishingSignIn": "Finishing sign in…", "closeWindow": "You can close this window and go back to IDP.", "cancel": "Cancel", From a64007544413d3af5b61007f3c95f1dfaf3e10a4 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 12:57:56 +0530 Subject: [PATCH 30/32] IDP-52: fix the dandiset picker making a call per dandiset and per workspace --- .../idp-arc/frontend/src/app/container.ts | 15 +++--- .../src/components/DataUploadDialog.tsx | 32 +++++++++---- .../frontend/src/core/dandisetLinks.ts | 5 +- .../src/core/ports/IDandiDirectApi.ts | 5 +- .../src/core/use-cases/protocolDandisets.ts | 45 +++++++----------- .../src/core/use-cases/runProtocol.ts | 16 ++++--- .../src/infra/emberDandiDirectClient.ts | 5 +- .../frontend/tests/unit/emberClients.test.ts | 6 +++ .../tests/unit/protocolDandisets.test.ts | 47 +++++++++---------- .../frontend/tests/unit/runProtocol.test.ts | 17 +++++++ 10 files changed, 110 insertions(+), 83 deletions(-) diff --git a/applications/idp-arc/frontend/src/app/container.ts b/applications/idp-arc/frontend/src/app/container.ts index 4afa697..f7edb18 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -98,14 +98,13 @@ export const createWorkspace = createCreateWorkspaceUseCase(authClient, workspac * through OSB, and runs the notebooks in OSB's Argo task. */ export const runProtocol = createRunProtocolUseCase(authClient, workspaceApi, objectStore) -/** The researcher's EMBER-DANDI dandisets for a protocol, each with the workspace it runs in when - * they still have it: what the upload dialog offers once a protocol is chosen. */ -export async function listProtocolDandisets(protocolId: string): Promise { - const token = await authClient.getToken() - const me = authClient.tokenParsed?.sub - return protocolDandisets.listForProtocol(protocolId, - async (workspaceId) => !!me && (await workspaceApi.getWorkspaceOwner(token, workspaceId)) === me) -} +/** The researcher's EMBER-DANDI dandisets for a protocol: what the upload dialog offers once a + * protocol is chosen. */ +export const listProtocolDandisets = (protocolId: string): Promise => protocolDandisets.listForProtocol(protocolId) + +/** The OSB workspace recorded in the selected dandiset, read once it is selected. */ +export const recordedWorkspace = (dandisetId: string, protocolId: string): Promise => + protocolDandisets.recordedWorkspace(dandisetId, protocolId) export type { ProtocolDandiset } /** Publishes the researcher's dandiset as a new version, for its DOI; only when they ask for it. */ diff --git a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index cfc2603..0593cee 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -21,7 +21,7 @@ import OpenInNewIcon from '@mui/icons-material/OpenInNewOutlined' import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined' import HourglassEmptyIcon from '@mui/icons-material/HourglassEmpty' -import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' +import { emberAuth, getWorkspaceUrl, listProtocolDandisets, publishDandiset, recordedWorkspace, runProtocol, UPLOAD_BACKEND, type ProtocolDandiset } from '../app/container' import { EMBER_SIGN_IN, UserFacingError, userMessage } from '../core/userMessages' import { withRunLock } from './runStorage' import { INITIAL_FORM, restoreSession, session } from './uploadSession' @@ -76,6 +76,9 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut const emberSignedIn = !usesEmber || emberAuth.isConnected() const [protocolDandisets, setProtocolDandisets] = useState(null) const [dandisetsError, setDandisetsError] = useState('') + // The selected dandiset's workspace is being read: Next waits for it. + const [findingWorkspace, setFindingWorkspace] = useState(false) + const workspaceLookup = useRef(0) const fileInputRef = useRef(null) const user = typeof tokenParsed?.sub === 'string' ? tokenParsed.sub : null @@ -130,6 +133,19 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut // The chosen protocol's dandisets; the first is preselected, with its workspace. const protocolId = runnableProtocols.find((p) => p.name === protocol)?.id + + /** Selects a dandiset and reads its recorded workspace (this one only); none: a new one is made. */ + const selectDandiset = (id: string) => { + setForm((prev) => ({ ...prev, dandisetId: id, spawnedWorkspaceId: undefined })) + const lookup = ++workspaceLookup.current + if (!id || !protocolId) return setFindingWorkspace(false) + setFindingWorkspace(true) + recordedWorkspace(id, protocolId) + .then((workspaceId) => setForm((prev) => (prev.dandisetId === id ? { ...prev, spawnedWorkspaceId: workspaceId } : prev))) + .catch((err: unknown) => console.warn(`Could not read dandiset ${id}'s workspace; the run will make a new one`, err)) + .finally(() => { if (workspaceLookup.current === lookup) setFindingWorkspace(false) }) + } + useEffect(() => { setProtocolDandisets(null) setDandisetsError('') @@ -141,8 +157,8 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut setProtocolDandisets(list) // Only while choosing: reopening on a run (also one back here for the EMBER-DANDI sign-in) // must not change its dandiset or workspace. - setForm((prev) => (prev.step !== 'select' || prev.checkpoint?.protocolId === protocolId ? prev - : { ...prev, dandisetId: list[0]?.id ?? '', spawnedWorkspaceId: list[0]?.workspaceId })) + const prev = session.get() + if (prev.step === 'select' && prev.checkpoint?.protocolId !== protocolId) selectDandiset(list[0]?.id ?? '') }) .catch((err: unknown) => { console.error('Could not list the EMBER-DANDI dandisets', err) @@ -151,14 +167,12 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut setDandisetsError('Your dandisets could not be listed; a new one will be created.') }) return () => { current = false } + // eslint-disable-next-line react-hooks/exhaustive-deps }, [open, usesEmber, emberSignedIn, protocolId]) /** Messages in the dandiset section: the dialog's own 14px Inter, quieter than labels. */ const noteText = { fontFamily: 'Inter, sans-serif', fontWeight: 400, fontSize: '14px', lineHeight: '22px', color: '#FFFFFF99' } - const chooseDandiset = (id: string) => setForm((prev) => ({ - ...prev, dandisetId: id, spawnedWorkspaceId: protocolDandisets?.find((d) => d.id === id)?.workspaceId, - })) const handleDrop = useCallback((e: React.DragEvent) => { @@ -293,7 +307,7 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut ])) const stepIndex = step === 'select' ? 0 : 1 - const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null)) + const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null && !findingWorkspace)) const canUpload = !!file && !fileProblem && emberSignedIn return ( @@ -436,12 +450,12 @@ export default function DataUploadDialog({ open, initialProtocol, onClose, onAut fullWidth displayEmpty value={dandisetId} - onChange={(e) => chooseDandiset(e.target.value)} + onChange={(e) => selectDandiset(e.target.value)} sx={{ fontFamily: 'Inter, sans-serif', fontWeight: 400, fontSize: '14px', lineHeight: '22px' }} > {protocolDandisets.map((d) => ( - {d.name} ({d.id}){d.workspaceId !== undefined ? ` · workspace ${d.workspaceId}` : ' · new workspace'} + {d.name} ({d.id}) ))} Create a new dandiset and workspace diff --git a/applications/idp-arc/frontend/src/core/dandisetLinks.ts b/applications/idp-arc/frontend/src/core/dandisetLinks.ts index b223be8..b715e88 100644 --- a/applications/idp-arc/frontend/src/core/dandisetLinks.ts +++ b/applications/idp-arc/frontend/src/core/dandisetLinks.ts @@ -15,6 +15,9 @@ export type DandisetMetadata = Record const PROTOCOL_PREFIX = 'idp-protocol:' const WORKSPACE_PREFIX = 'osb-workspace' +/** The identifier of a protocol's link, as recorded in the metadata (and found by EMBER's search). */ +export const protocolLinkId = (protocolId: string) => `${PROTOCOL_PREFIX}${protocolId}` + interface Resource { identifier?: unknown [key: string]: unknown @@ -60,7 +63,7 @@ export function withProtocolLink( ): DandisetMetadata { return withEntry(metadata, PROTOCOL_PREFIX, { schemaKey: 'Resource', - identifier: `${PROTOCOL_PREFIX}${protocol.id}`, + identifier: protocolLinkId(protocol.id), name: `IDP protocol: ${protocol.name}`, ...(protocol.url ? { url: protocol.url } : {}), relation: 'dcite:IsDescribedBy', diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts index d4c767b..63050bc 100644 --- a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -88,8 +88,9 @@ export interface PublishedVersion { } export interface IDandiDirectApi { - /** `GET /dandisets/?user=me`: every dandiset this account owns, empty ones included. */ - listOwnDandisets(token: string): Promise + /** `GET /dandisets/?user=me`: every dandiset this account owns, empty ones included; with + * `search`, only those EMBER's search matches (it also looks in the metadata). */ + listOwnDandisets(token: string, search?: string): Promise /** `POST /dandisets/`: creates a public dandiset and returns its identifier. `metadata` is * merged into the default (a description). */ diff --git a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts index 9297849..5e249af 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -1,6 +1,6 @@ import { VERSION_STATUS, type IDandiDirectApi, type PublishedVersion } from '../ports/IDandiDirectApi' import type { IEmberAuth } from '../ports/IEmberAuth' -import { readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink, type DandisetMetadata } from '../dandisetLinks' +import { protocolLinkId, readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink } from '../dandisetLinks' import { RUN_SETTINGS } from '../runSettings' import { DANDISET_NOT_PUBLISHABLE, EMBER_SIGN_IN, UserFacingError } from '../userMessages' import { pollUntil } from './runProgress' @@ -22,8 +22,6 @@ class PublishError extends Error { export interface ProtocolDandiset { id: string name: string - /** The OSB workspace recorded in its metadata, when the researcher still has it. */ - workspaceId?: number } export interface ProtocolRef { @@ -54,32 +52,21 @@ export function createProtocolDandisetsUseCases(deps: { } /** - * The researcher's dandisets recorded for `protocolId`, each with its workspace. One metadata - * read per dandiset they own (EMBER's list carries no metadata). A workspace link is kept only - * when `ownsWorkspace` says the workspace is still the researcher's (not deleted, not someone - * else's); otherwise a new one is made. It is asked once per recorded workspace, so how many - * workspaces they have doesn't matter. + * The researcher's dandisets recorded for `protocolId`, in one list call: EMBER's search also + * matches the metadata, where the protocol link is. No metadata is read here; the selected + * dandiset's workspace is (recordedWorkspace). */ - async function listForProtocol(protocolId: string, ownsWorkspace: (workspaceId: number) => Promise): Promise { - const t = token() - const own = await direct.listOwnDandisets(t) - const read = await Promise.all(own.map(async (d) => { - try { - return { d, metadata: await direct.getDraftMetadata(t, d.id) } - } catch (err) { - console.warn(`Could not read the metadata of dandiset ${d.id}`, err) - return null - } - })) - const forProtocol = read - .filter((r): r is { d: (typeof own)[number]; metadata: DandisetMetadata } => !!r && readProtocolLink(r.metadata) === protocolId) - .map(({ d, metadata }) => ({ d, linked: readWorkspaceLink(metadata, osbDomain) })) - // Several dandisets can record the same workspace: each is checked once. - const owned = new Map>() - for (const { linked } of forProtocol) if (linked && !owned.has(linked)) owned.set(linked, ownsWorkspace(linked)) - return Promise.all(forProtocol.map(async ({ d, linked }) => ({ - id: d.id, name: d.name, ...(linked && await owned.get(linked) ? { workspaceId: linked } : {}), - }))) + async function listForProtocol(protocolId: string): Promise { + return direct.listOwnDandisets(token(), protocolLinkId(protocolId)) + } + + /** + * The workspace recorded in the dandiset, when it is really `protocolId`'s (the search also + * matches a longer protocol id). Whether the researcher still has it, the run checks. + */ + async function recordedWorkspace(dandisetId: string, protocolId: string): Promise { + const metadata = await direct.getDraftMetadata(token(), dandisetId) + return readProtocolLink(metadata) === protocolId ? readWorkspaceLink(metadata, osbDomain) : undefined } /** A new dandiset in the researcher's account, recorded for `protocol`. */ @@ -163,7 +150,7 @@ export function createProtocolDandisetsUseCases(deps: { return latest } - return { listForProtocol, createForProtocol, recordWorkspace, publish } + return { listForProtocol, recordedWorkspace, createForProtocol, recordWorkspace, publish } } export type ProtocolDandisets = ReturnType diff --git a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts index 59ce608..55eec41 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -325,15 +325,19 @@ export function createRunProtocolUseCase( /** Step 2. */ async function prepareWorkspace(): Promise { progress.start(RUN_STEP.workspace, 'workspace', 'Getting the workspace ready…') - const existing = checkpoint.workspaceId ?? input.workspaceId // A run picked up again (perhaps days later): its workspace may have been deleted since. - if (checkpoint.workspaceId !== undefined - && !(await workspaceApi.getWorkspaceOwner(await token(), checkpoint.workspaceId))) { - throw new UserFacingError('The workspace for this run no longer exists. Please start a new upload.') + if (checkpoint.workspaceId !== undefined) { + if (!(await workspaceApi.getWorkspaceOwner(await token(), checkpoint.workspaceId))) { + throw new UserFacingError('The workspace for this run no longer exists. Please start a new upload.') + } + progress.done(RUN_STEP.workspace, undefined, 'Workspace ready') + return checkpoint.workspaceId } - if (existing !== undefined) { + // The dandiset's recorded workspace, while it is still the researcher's; else a new one. + if (input.workspaceId !== undefined + && (await workspaceApi.getWorkspaceOwner(await token(), input.workspaceId)) === auth.tokenParsed?.sub) { progress.done(RUN_STEP.workspace, undefined, 'Workspace ready') - return existing + return input.workspaceId } const id = await workspaceApi.createWorkspace(await token(), input.workspaceName, [`maabcd:${protocol.id}`]) progress.workspaceId = id diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index 10ccbbe..3ce03a7 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -48,16 +48,17 @@ export class EmberDandiDirectClient implements IDandiDirectApi { throw new Error(`EMBER ${what} failed (HTTP ${res.status}): ${body.slice(0, 300)}`) } - async listOwnDandisets(token: string): Promise { + async listOwnDandisets(token: string, search?: string): Promise { // `empty=true` keeps a dandiset that has no assets yet in the list; embargoed ones need // `embargoed=true` (see ALLOW_EMBARGOED). const embargoed = ALLOW_EMBARGOED ? '&embargoed=true' : '' + const searched = search ? `&search=${encodeURIComponent(search)}` : '' const dandisets: OwnDandiset[] = [] // Page by page until we have as many as EMBER's `count` says. let total = Infinity for (let page = 1; dandisets.length < total; page++) { const res = await fetch( - `${this.baseUrl}/api/dandisets/?user=me${embargoed}&empty=true&page_size=${DANDISET_PAGE_SIZE}&page=${page}`, + `${this.baseUrl}/api/dandisets/?user=me${embargoed}${searched}&empty=true&page_size=${DANDISET_PAGE_SIZE}&page=${page}`, { headers: this.headers(token) }, ) if (!res.ok) await this.fail(res, 'dandiset list') diff --git a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts index c75abd9..fc743e2 100644 --- a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -110,6 +110,12 @@ test('the dandiset list reads as many pages as EMBER\'s count says, through the assert.match(requests[1].url, /page_size=100&page=2$/) }) +test('a search is passed to EMBER, encoded, on every page', async () => { + const requests = recordFetch(() => ({ json: { count: 1, results: [{ identifier: '000001' }] } })) + await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token', 'idp-protocol:four-choice-reversal') + assert.match(requests[0].url, /&search=idp-protocol%3Afour-choice-reversal&/) +}) + test('one page when the count fits in it, none more for an empty account', async () => { let requests = recordFetch(() => ({ json: { count: 1, results: [{ identifier: '000001' }] } })) await new EmberDandiDirectClient('/ember-proxy').listOwnDandisets('ember-token') diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts index eee2653..4e01d2f 100644 --- a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -46,14 +46,18 @@ function fakeEmber(metadata: Record, publishing: { versions?: ({ version: string; doi?: string; url?: string } | null)[] } = {}) { const calls: string[] = [] + const drafts: string[] = [] let statusReads = 0 let versionReads = 0 const writes: { id: string; metadata: DandisetMetadata }[] = [] const created: { name: string; metadata?: DandisetMetadata }[] = [] const direct: IDandiDirectApi = { - async listOwnDandisets() { return Object.keys(metadata).map((id) => ({ id, name: `set ${id}` })) }, + async listOwnDandisets(_t, search) { + calls.push(`list:${search ?? ''}`) + return Object.keys(metadata).map((id) => ({ id, name: `set ${id}` })) + }, async createDandiset(_t, name, m) { created.push({ name, metadata: m }); return '000900' }, - async getDraftMetadata(_t, id) { return metadata[id] ?? {} }, + async getDraftMetadata(_t, id) { drafts.push(id); return metadata[id] ?? {} }, async updateDraftMetadata(_t, id, m) { writes.push({ id, metadata: m }) }, async getPublishReadiness() { const all = publishing.statuses ?? [{ status: 'Valid' }] @@ -73,38 +77,29 @@ function fakeEmber(metadata: Record, publishing: { const uc = createProtocolDandisetsUseCases({ emberAuth: { getToken: () => 'ember-token' }, direct, osbDomain: DEV, workspaceUrl: (id) => `https://ws/${id}`, }) - return { uc, writes, created, calls } + return { uc, writes, created, calls, drafts } } -test('lists only the dandisets recorded for the protocol, with the workspaces the user still has', async () => { - const { uc } = fakeEmber({ - '000001': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), - '000002': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 99, 'u'), // workspace gone - '000003': withProtocolLink({}, { id: 'asst', name: 'ASST' }), - '000004': {}, // not an IDP dandiset - }) +test('the protocol\'s dandisets come from one search for its link, with no metadata read', async () => { + const { uc, calls, drafts } = fakeEmber({ '000001': withProtocolLink({}, FOUR) }) - const asked: number[] = [] - const list = await uc.listForProtocol('four-choice-reversal', async (id) => { asked.push(id); return id === 42 }) - - assert.deepEqual(list, [ - { id: '000001', name: 'set 000001', workspaceId: 42 }, - { id: '000002', name: 'set 000002' }, - ]) - // Only the protocol's recorded workspaces are checked, not every workspace the user has. - assert.deepEqual(asked.sort(), [42, 99]) + assert.deepEqual(await uc.listForProtocol('four-choice-reversal'), [{ id: '000001', name: 'set 000001' }]) + assert.deepEqual(calls, ['list:idp-protocol:four-choice-reversal']) + assert.deepEqual(drafts, []) }) -test('a workspace recorded in several dandisets is checked once', async () => { - const { uc } = fakeEmber({ +test('the selected dandiset\'s workspace is read from its own metadata, only for its protocol', async () => { + const { uc, drafts } = fakeEmber({ '000001': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), - '000002': withWorkspaceLink(withProtocolLink({}, FOUR), DEV, 42, 'u'), + '000002': withProtocolLink({}, FOUR), // no workspace yet + '000003': withWorkspaceLink(withProtocolLink({}, { id: 'four-choice-reversal-v2', name: 'v2' }), DEV, 7, 'u'), }) - const asked: number[] = [] - const list = await uc.listForProtocol('four-choice-reversal', async (id) => { asked.push(id); return true }) - assert.deepEqual(list.map((d) => d.workspaceId), [42, 42]) - assert.deepEqual(asked, [42]) + assert.equal(await uc.recordedWorkspace('000001', 'four-choice-reversal'), 42) + assert.equal(await uc.recordedWorkspace('000002', 'four-choice-reversal'), undefined) + // The search also matches a longer protocol id: its workspace is not this protocol's. + assert.equal(await uc.recordedWorkspace('000003', 'four-choice-reversal'), undefined) + assert.deepEqual(drafts, ['000001', '000002', '000003']) }) test('a new dandiset is created already recorded for its protocol', async () => { diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index a77985f..2402017 100644 --- a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts +++ b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts @@ -590,6 +590,23 @@ test('notebooks already submitted when the page went are followed, not submitted assert.equal(count(f.calls, 'import:g'), 1, 'nothing imported again') }) +test('the dandiset\'s recorded workspace is used while it is still the user\'s, else a new one is made', async () => { + const kept = fakes() + const reused = (await run(kept, { file: data, workspaceId: 7 })).at(-1)! + assert.equal(reused.phase, 'succeeded', reused.error) + assert.equal(reused.workspaceId, 7) + assert.equal(count(kept.calls, 'create'), 0) + + for (const owner of [null, 'someone-else']) { + const f = fakes() + f.api.getWorkspaceOwner = async () => owner + const last = (await run(f, { file: data, workspaceId: 7 })).at(-1)! + assert.equal(last.phase, 'succeeded', last.error) + assert.equal(last.workspaceId, 42, `owner ${owner}: a new workspace`) + assert.equal(count(f.calls, 'create'), 1) + } +}) + test('a run picked up again whose workspace was deleted says so', async () => { const f = fakes() failFirst(f, 'importResource', 1, (_t, input) => input.resourceType === 'e') From fac9c49131fddf8c2557bc6e3b6a8b67e99709b4 Mon Sep 17 00:00:00 2001 From: "D. Gopal Krishna" Date: Tue, 27 Oct 2026 13:18:49 +0530 Subject: [PATCH 31/32] IDP-52: read a version's status, not just the draft's --- .../src/core/ports/IDandiDirectApi.ts | 40 +++++++++++-------- .../src/core/use-cases/protocolDandisets.ts | 20 +++++----- .../src/infra/emberDandiDirectClient.ts | 14 ++++--- .../frontend/tests/unit/emberClients.test.ts | 7 ++-- .../tests/unit/emberObjectStore.test.ts | 2 +- .../tests/unit/protocolDandisets.test.ts | 6 +-- 6 files changed, 49 insertions(+), 40 deletions(-) diff --git a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts index 63050bc..b506e64 100644 --- a/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -50,28 +50,33 @@ export interface OwnDandiset { } /** - * DANDI's status of a dandiset version (its `status` field), as read for the draft before - * publishing. Only the values IDP acts on; while EMBER is still checking the draft it reports - * others (`Pending`, `Validating`), and `Publishing` while a publish is under way. - * A version status, not a draft status: in DANDI the draft is itself a version (`"draft"`), and - * its status can be `Published` (identical to the last published version). + * DANDI's status of a dandiset version (its `status` field), exactly as EMBER's API defines it. + * The draft is a version (`draft`), as is each published one (`0.YYMMDD.HHMM`). The draft: + * - starts `Pending`, and goes back to `Pending` after every change (an upload, a metadata edit); + * - is checked by EMBER in the background: `Pending` → `Validating` → `Valid` or `Invalid`; + * - can be published only when `Valid` and every file in it has been checked: `Publishing`, then + * `Published` (identical to the version that publish created, until the next change). */ export const VERSION_STATUS = { - /** EMBER has checked the draft and it can be published. */ + pending: 'Pending', + validating: 'Validating', valid: 'Valid', - /** It can't be published; `errors` says why. */ + /** Can't be published as it is; `errors` says why. */ invalid: 'Invalid', - /** Nothing changed since the last published version: nothing new to publish. */ + publishing: 'Publishing', + /** For the draft: unchanged since the last published version, so nothing new to publish. */ published: 'Published', } as const -/** - * Whether the draft can be published yet. EMBER re-checks the draft in the background after every - * change (an upload, a metadata edit) and accepts a publish only once it is `Valid`. - */ -export interface PublishReadiness { - /** The draft's VERSION_STATUS, or a status EMBER reports while it is still checking. */ - status: string +/** A version's state: one of VERSION_STATUS. */ +export type VersionStatus = (typeof VERSION_STATUS)[keyof typeof VERSION_STATUS] + +/** A version of a dandiset, as EMBER reports it: which one, its state, and what stops it from + * being published. */ +export interface DandisetVersion { + /** `draft`, or a published version (`0.YYMMDD.HHMM`). */ + version: string + status: VersionStatus /** Why it can't be published, one line per problem: the dandiset's metadata, or a file's. */ errors: string[] /** Files EMBER hasn't checked yet. Publishing needs every file checked, even on a `Valid` draft. */ @@ -103,8 +108,9 @@ export interface IDandiDirectApi { * writable; a published version is a frozen snapshot of it. */ updateDraftMetadata(token: string, dandisetId: string, metadata: DandisetMetadata): Promise - /** `GET /dandisets/{id}/versions/draft/info/`: whether the draft can be published yet. */ - getPublishReadiness(token: string, dandisetId: string): Promise + /** `GET /dandisets/{id}/versions/{version}/info/`: the version (`draft`, or a published one) and + * its state. */ + getVersionInfo(token: string, dandisetId: string, version: string): Promise /** `POST /dandisets/{id}/versions/draft/publish/`: starts publishing the draft as a new * version. EMBER finishes it in the background. */ diff --git a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts index 5e249af..772836b 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -1,4 +1,4 @@ -import { VERSION_STATUS, type IDandiDirectApi, type PublishedVersion } from '../ports/IDandiDirectApi' +import { VERSION_STATUS, type IDandiDirectApi, type PublishedVersion, type VersionStatus } from '../ports/IDandiDirectApi' import type { IEmberAuth } from '../ports/IEmberAuth' import { protocolLinkId, readProtocolLink, readWorkspaceLink, withProtocolLink, withWorkspaceLink } from '../dandisetLinks' import { RUN_SETTINGS } from '../runSettings' @@ -8,8 +8,8 @@ import { pollUntil } from './runProgress' /** The license of the dandisets IDP creates. EMBER publishes no dandiset without one. */ export const DANDISET_LICENSE = ['spdx:CC-BY-4.0'] -/** Statuses a draft can be published from (or, when Published, already was). */ -const PUBLISHABLE: string[] = [VERSION_STATUS.valid, VERSION_STATUS.published] +/** Draft statuses that end the wait: publish it (Valid), or it already was (Published). */ +const PUBLISHABLE: VersionStatus[] = [VERSION_STATUS.valid, VERSION_STATUS.published] /** Why a dandiset could not be published, for the console; the user reads the DOI step's message. */ class PublishError extends Error { @@ -108,16 +108,16 @@ export function createProtocolDandisetsUseCases(deps: { * Waits for EMBER to finish checking the draft and every file in it; the draft's status, or null * if `stopped`. Stops at once, with EMBER's reasons for the user, when it can't be published. */ - async function waitUntilPublishable(t: string, dandisetId: string, stopped: () => boolean): Promise { - let status = '' + async function waitUntilPublishable(t: string, dandisetId: string, stopped: () => boolean): Promise { + let status: VersionStatus = VERSION_STATUS.pending const ended = await pollUntil(async () => { - const readiness = await direct.getPublishReadiness(t, dandisetId) - status = readiness.status + const draft = await direct.getVersionInfo(t, dandisetId, 'draft') + status = draft.status // Invalid, or Valid with an invalid file: EMBER would refuse the publish. - if (status === VERSION_STATUS.invalid || (status === VERSION_STATUS.valid && readiness.errors.length)) { - throw notPublishable(readiness.errors) + if (status === VERSION_STATUS.invalid || (status === VERSION_STATUS.valid && draft.errors.length)) { + throw notPublishable(draft.errors) } - return PUBLISHABLE.includes(status) && readiness.filesBeingChecked === 0 + return PUBLISHABLE.includes(status) && draft.filesBeingChecked === 0 }, { everyMs: RUN_SETTINGS.publishStatusPollMs, timeoutMs: RUN_SETTINGS.publishDraftValidationTimeoutMs, stopped }) if (ended === 'timeout') { throw new UserFacingError('EMBER-DANDI is still checking your dandiset. Please try again in a few minutes.', diff --git a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts index 3ce03a7..d2dc359 100644 --- a/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -2,7 +2,8 @@ import type { DandisetMetadata } from '../core/dandisetLinks' import type { DirectFinalizeInput, DirectInitResult, - PublishReadiness, + DandisetVersion, + VersionStatus, IDandiDirectApi, OwnDandiset, PublishedVersion, @@ -106,14 +107,15 @@ export class EmberDandiDirectClient implements IDandiDirectApi { if (!res.ok) await this.fail(res, 'draft metadata update') } - async getPublishReadiness(token: string, dandisetId: string): Promise { - const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/draft/info/`, { + async getVersionInfo(token: string, dandisetId: string, version: string): Promise { + const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/${encodeURIComponent(version)}/info/`, { headers: this.headers(token), }) - if (!res.ok) await this.fail(res, 'publish readiness read') + if (!res.ok) await this.fail(res, 'version info read') type Problem = { field?: string; path?: string; message: string } const body = (await res.json()) as { - status: string + version?: string + status: VersionStatus version_validation_errors?: Problem[] asset_validation_errors?: Problem[] } @@ -123,7 +125,7 @@ export class EmberDandiDirectClient implements IDandiDirectApi { const assetProblems = body.asset_validation_errors ?? [] const errors = [...(body.version_validation_errors ?? []), ...assetProblems.filter((e) => !beingChecked(e))] .map((e) => [e.path || e.field, e.message].filter(Boolean).join(': ')) - return { status: body.status, errors, filesBeingChecked: assetProblems.filter(beingChecked).length } + return { version: body.version ?? version, status: body.status, errors, filesBeingChecked: assetProblems.filter(beingChecked).length } } async publishDraft(token: string, dandisetId: string): Promise { diff --git a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts index fc743e2..ae5b4e8 100644 --- a/applications/idp-arc/frontend/tests/unit/emberClients.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -72,7 +72,7 @@ test('publishing sends a JSON body, which newer DANDI releases require', async ( assert.deepEqual(requests[0].body, {}) }) -test('publish readiness separates files EMBER is still checking from real problems', async () => { +test('a version\'s status separates files EMBER is still checking from real problems', async () => { const requests = recordFetch(() => ({ json: { status: 'Valid', @@ -85,10 +85,11 @@ test('publish readiness separates files EMBER is still checking from real proble })) const ember = new EmberDandiDirectClient('/ember-proxy') - const readiness = await ember.getPublishReadiness('ember-token', '000777') + const draft = await ember.getVersionInfo('ember-token', '000777', 'draft') assert.equal(requests[0].url, '/ember-proxy/api/dandisets/000777/versions/draft/info/') - assert.deepEqual(readiness, { + assert.deepEqual(draft, { + version: 'draft', status: 'Valid', errors: ['assetsSummary: A Dandiset containing no files or zero bytes is not publishable', 'p/u/b.xlsx: is required'], filesBeingChecked: 1, diff --git a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts index 2af44c6..b27cdf1 100644 --- a/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -19,7 +19,7 @@ function fakes(opts: { dedupDirect?: boolean; dedupOsb?: boolean; shortParts?: b async createDandiset() { throw new Error('created through the protocol use case') }, async getDraftMetadata() { return {} }, async updateDraftMetadata() {}, - async getPublishReadiness() { return { status: 'Valid', errors: [], filesBeingChecked: 0 } }, + async getVersionInfo() { return { version: 'draft', status: 'Valid', errors: [], filesBeingChecked: 0 } }, async publishDraft() {}, async getLatestPublished() { return null }, async initUpload(token, dandisetId) { diff --git a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts index 4e01d2f..921bf83 100644 --- a/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -8,7 +8,7 @@ import { import { createProtocolDandisetsUseCases, DANDISET_LICENSE } from '../../src/core/use-cases/protocolDandisets' import { RUN_SETTINGS } from '../../src/core/runSettings' import { DANDISET_NOT_PUBLISHABLE, UserFacingError } from '../../src/core/userMessages' -import type { IDandiDirectApi } from '../../src/core/ports/IDandiDirectApi' +import type { IDandiDirectApi, VersionStatus } from '../../src/core/ports/IDandiDirectApi' const DEV = 'v2dev.opensourcebrain.org' const FOUR = { id: 'four-choice-reversal', name: 'Four-choice reversal digging task', url: 'https://github.com/o/r' } @@ -59,11 +59,11 @@ function fakeEmber(metadata: Record, publishing: { async createDandiset(_t, name, m) { created.push({ name, metadata: m }); return '000900' }, async getDraftMetadata(_t, id) { drafts.push(id); return metadata[id] ?? {} }, async updateDraftMetadata(_t, id, m) { writes.push({ id, metadata: m }) }, - async getPublishReadiness() { + async getVersionInfo(_t, _id, version) { const all = publishing.statuses ?? [{ status: 'Valid' }] const s = all[Math.min(statusReads++, all.length - 1)] calls.push(`status:${s.status}`) - return { status: s.status, errors: s.errors ?? [], filesBeingChecked: s.filesBeingChecked ?? 0 } + return { version, status: s.status as VersionStatus, errors: s.errors ?? [], filesBeingChecked: s.filesBeingChecked ?? 0 } }, async publishDraft(_t, id) { calls.push(`publish:${id}`) }, async getLatestPublished() { From f3e6a251f59cdaed067c40b21c5a81f022456301 Mon Sep 17 00:00:00 2001 From: Dario Del Piano Date: Tue, 27 Oct 2026 12:33:32 +0100 Subject: [PATCH 32/32] fixing conditional destination for ember --- applications/idp-arc/Dockerfile | 5 ++++- .../idp-arc/deploy/resources/default.conf | 15 +++++++++++++-- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/applications/idp-arc/Dockerfile b/applications/idp-arc/Dockerfile index eccee90..09bde31 100644 --- a/applications/idp-arc/Dockerfile +++ b/applications/idp-arc/Dockerfile @@ -22,7 +22,10 @@ FROM nginxinc/nginx-unprivileged:stable-alpine USER root RUN rm -rf /usr/share/nginx/html/* COPY --from=build --chown=101:101 /app/dist/ /usr/share/nginx/html/ -COPY --chown=101:101 deploy/resources/default.conf /etc/nginx/conf.d/default.conf +# The image's entrypoint renders templates into conf.d at start; the local-resolvers flag gives the +# template the pod's DNS servers so the EMBER proxy can resolve at request time (see default.conf). +COPY --chown=101:101 deploy/resources/default.conf /etc/nginx/templates/default.conf.template +ENV NGINX_ENTRYPOINT_LOCAL_RESOLVERS=1 USER 101 EXPOSE 8080 \ No newline at end of file diff --git a/applications/idp-arc/deploy/resources/default.conf b/applications/idp-arc/deploy/resources/default.conf index b4506a9..504613f 100644 --- a/applications/idp-arc/deploy/resources/default.conf +++ b/applications/idp-arc/deploy/resources/default.conf @@ -1,3 +1,5 @@ +# Installed as an envsubst template (Dockerfile): ${NGINX_LOCAL_RESOLVERS} becomes the pod's +# nameservers from /etc/resolv.conf at container start. Other $names are nginx variables. server { listen 8080; @@ -11,13 +13,22 @@ server { # EMBER's POST /oauth/token/ reply has no CORS header, so the browser can't read the login token # from it directly; through this same-origin proxy it can. (File bytes go straight to S3, not here.) # Only what the app calls: the token exchange and the REST API. Anything else under it is refused. + # The upstream is a variable so nginx resolves EMBER per request (honouring the DNS TTL) instead of + # once at startup: a failed lookup then only breaks EMBER calls, not nginx starting, and EMBER's IPs + # can change under us. A variable proxy_pass doesn't strip the location prefix, hence the rewrite. + resolver ${NGINX_LOCAL_RESOLVERS} ipv6=off; + resolver_timeout 5s; + set $ember https://api-dandi.emberarchive.org; + location /ember-proxy/oauth/token/ { - proxy_pass https://api-dandi.emberarchive.org/oauth/token/; + rewrite ^/ember-proxy(/.*)$ $1 break; + proxy_pass $ember; proxy_ssl_server_name on; proxy_set_header Host api-dandi.emberarchive.org; } location /ember-proxy/api/ { - proxy_pass https://api-dandi.emberarchive.org/api/; + rewrite ^/ember-proxy(/.*)$ $1 break; + proxy_pass $ember; proxy_ssl_server_name on; proxy_set_header Host api-dandi.emberarchive.org; }