diff --git a/README.md b/README.md index 8d94c1f..c780488 100644 --- a/README.md +++ b/README.md @@ -70,9 +70,21 @@ 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 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 + (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. Needs only the OSB login. --- diff --git a/applications/idp-arc/Dockerfile b/applications/idp-arc/Dockerfile index 132d970..09bde31 100644 --- a/applications/idp-arc/Dockerfile +++ b/applications/idp-arc/Dockerfile @@ -6,9 +6,15 @@ 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. +ARG VITE_EMBER_CLIENT_ID +ENV VITE_EMBER_CLIENT_ID=${VITE_EMBER_CLIENT_ID} RUN yarn build FROM nginxinc/nginx-unprivileged:stable-alpine @@ -16,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 3bc7e97..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; @@ -8,6 +10,32 @@ 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.) + # 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/ { + 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/ { + rewrite ^/ember-proxy(/.*)$ $1 break; + proxy_pass $ember; + 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; expires 7d; 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 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/applications/idp-arc/frontend/src/App.tsx b/applications/idp-arc/frontend/src/App.tsx index e51ca9a..835e982 100644 --- a/applications/idp-arc/frontend/src/App.tsx +++ b/applications/idp-arc/frontend/src/App.tsx @@ -3,21 +3,58 @@ 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' +import NotFound from './pages/NotFound' +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). + * 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.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. */ +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: }, + { path: '*', element: }, ]) function App() { @@ -29,31 +66,53 @@ 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 && IN_OSB_LOGIN_POPUP && window.opener) { + window.opener.postMessage({ type: 'keycloak-login-complete' }, window.location.origin) + window.close() + 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) + } + }) + .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 +136,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..f7edb18 100644 --- a/applications/idp-arc/frontend/src/app/container.ts +++ b/applications/idp-arc/frontend/src/app/container.ts @@ -18,24 +18,40 @@ 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' +import { EmberUploadApiClient } from '../infra/emberUploadApiClient' +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' 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' // ─── 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-DANDI, or the public bucket at VITE_UPLOAD_BUCKET_URL. */ +export type UploadBackend = 'ember' | 'bucket' +/** 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' +const MAABCD_DANDI_INSTANCE = 'ember-dandi' +/** 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 ──────────────────────────────────────────────── @@ -48,10 +64,27 @@ 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) -/** 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) +/** 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_API_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' +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: OSB_DOMAIN, workspaceUrl: (id) => getWorkspaceUrl(id), +}) + +/** 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_API_ORIGIN) + : new PublicBucketObjectStore(import.meta.env.VITE_UPLOAD_BUCKET_URL) // ─── Use-cases (injected with their concrete dependencies) ──────────────────── @@ -62,19 +95,36 @@ 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. */ 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: 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. */ +export async function publishDandiset(dandisetId: string): Promise<{ doi: string } | null> { + const version = await protocolDandisets.publish(dandisetId) + return version?.doi ? { doi: version.doi } : null +} // ─── Helpers ────────────────────────────────────────────────────────────────── +/** The researcher's workspaces on OSB ("My workspaces"). */ +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/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/components/DataUploadDialog.tsx b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx index b3872eb..0593cee 100644 --- a/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx +++ b/applications/idp-arc/frontend/src/components/DataUploadDialog.tsx @@ -1,9 +1,11 @@ -import { useCallback, useEffect, useRef, useState } from 'react' +import { useCallback, useEffect, useRef, useState, type ReactNode } from 'react' import { Box, Button, CircularProgress, + Checkbox, Dialog, + FormControlLabel, IconButton, MenuItem, Select, @@ -19,11 +21,17 @@ 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, 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' import { useAppContext } from '../AppContext' -import type { RunStep } 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 { 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' @@ -31,80 +39,141 @@ 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 + /** 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) { - const { tokenParsed } = useAppContext() - - 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 run's checklist (upload, imports, run), as last reported by the use-case. */ - runSteps: RunStep[] +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, } +} - const INITIAL_FORM: FormState = { - step: 'select', - protocol: '', - file: null, - isDragging: false, - uploadMessage: '', - spawnedWorkspaceId: undefined, - outputsDir: '', - runSteps: [], - } +/** How long a Retry shows that it is trying, even when it fails at once. */ +const MIN_ATTEMPT_MS = 300 - const [form, setForm] = useState(INITIAL_FORM) - const { step, protocol, file, isDragging, uploadMessage, spawnedWorkspaceId, outputsDir, runSteps } = form +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, 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' + 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) - // The run being watched; each run gets its own token, so stopping one never revives another. - const watchRef = useRef<{ current: boolean } | null>(null) + const user = typeof tokenParsed?.sub === 'string' ? tokenParsed.sub : null - // The dialog can't be closed from clicking Upload until the notebooks have started in OSB: - // 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) - useEffect(() => { - if (step !== 'uploading') setCloseLocked(false) // finished, failed, or sent back to the form - }, [step]) + // 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: - // the upload is driven by this tab and would be lost, and the progress view would lose track - // of the run (which itself carries on in the workspace). Browsers show their own generic - // "Leave site?" text. This can't stop sleep, a crash, or the browser discarding the tab. + // 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 + // progress view would lose track of the run (which itself carries on in the workspace). Browsers + // show their own generic "Leave site?" text. This can't stop sleep, a crash, or a discarded tab. useEffect(() => { - if (!open || step !== 'uploading') return + if (step !== 'uploading') return const warn = (e: BeforeUnloadEvent) => { e.preventDefault() e.returnValue = '' // still needed by some browsers to show the prompt } window.addEventListener('beforeunload', warn) return () => window.removeEventListener('beforeunload', warn) - }, [open, step]) + }, [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! : '', + }) + + // 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. 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) { - // Stops watching only: the run itself carries on in the workspace. - if (watchRef.current) watchRef.current.current = true - return - } - setForm(INITIAL_FORM) + if (!open) return + const current = session.get() + 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]) + // 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, 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 + // Once the run has ended, so its reports can't overwrite what the Retry shows. + useEffect(() => { + if (open && finished) setForm((prev) => (prev.resultSeen ? prev : { ...prev, resultSeen: true })) + }, [open, finished]) + + // 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('') + if (!open || !usesEmber || !emberSignedIn || !protocolId) return + let current = true + listProtocolDandisets(protocolId) + .then((list) => { + if (!current) return + 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. + 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) + if (!current) return + setProtocolDandisets([]) + 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 handleDrop = useCallback((e: React.DragEvent) => { e.preventDefault() @@ -125,38 +194,70 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data const fileProblem = file ? inputFileProblem(file, selectedProtocol?.name ?? 'This protocol', selectedProtocol?.inputFormats) : null const handleUpload = async () => { - if (!file || fileProblem || !selectedProtocol) return - setCloseLocked(true) - setForm((prev) => ({ ...prev, step: 'uploading', uploadMessage: '', outputsDir: '', runSteps: [] })) - if (watchRef.current) watchRef.current.current = true + 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: '' })) + } + 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, retriedRows: [] })) + if (currentWatch) currentWatch.current = true const watch = { current: false } - watchRef.current = watch + currentWatch = watch + const started = Date.now() 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, - }, - (state) => { - if (watch.current) return // the dialog was closed, or another run started: no longer this one's - if (state.phase === 'running') setCloseLocked(false) // in OSB's task now: closing only stops watching - if (state.phase === 'failed' && state.error?.toLowerCase().includes(SIGN_IN_AGAIN)) { + inputFor(selectedProtocol, file), + 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) + // 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. setForm((prev) => ({ - ...prev, step: 'upload', uploadMessage: '', spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, + ...prev, step: 'select', uploadMessage: EMBER_SIGN_IN, + spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, dandisetId: state.dandisetId ?? prev.dandisetId, + checkpoint: state.checkpoint ?? prev.checkpoint, })) - onAuthRequired?.() return } setForm((prev) => ({ ...prev, spawnedWorkspaceId: state.workspaceId ?? prev.spawnedWorkspaceId, - uploadMessage: state.phase === 'failed' ? `${state.message}: ${state.error}` : state.message, + // 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, 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, - runSteps: state.steps, + ...withRetriedRows(state.steps, state.checkpoint ?? prev.checkpoint, prev.retriedRows), ...(state.phase === 'succeeded' ? { step: 'success' } : {}), ...(state.phase === 'stillRunning' ? { step: 'stillRunning' } : {}), ...(state.phase === 'failed' ? { step: 'failed' } : {}), @@ -166,14 +267,53 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data ) } + /** "Publish dandiset": the researcher's dandiset as a new, permanent version. Optional. */ + const publish = async () => { + if (!dandisetId) return + 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 instanceof UserFacingError && err.details ? err.details : err) + setForm((prev) => ({ ...prev, publishing: 'failed', publishError: userMessage(err, RUN_STEP.doi) })) + } + } + + /** A finished run's Retry: only its failed non-blocking steps run again, and only their rows change. */ + /** 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 + 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) } + }) + }, + ) + } + + // 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 - const canUpload = !!file && !fileProblem + const canGoNext = !!protocol && (!usesEmber || (emberSignedIn && protocolDandisets !== null && !findingWorkspace)) + const canUpload = !!file && !fileProblem && emberSignedIn return ( @@ -284,6 +422,66 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data ))} + {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} + )} + + )} + + )} + {usesEmber && selectedProtocol?.maabcdAggregateDandisetId && ( + setForm((prev) => ({ ...prev, shareWithMaabcd: e.target.checked }))} + /> + } + label={ + + Share a copy of this data with the MAABCD consortium + + } + /> + )} @@ -311,6 +509,12 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data {uploadMessage} )} + {usesEmber && ( + + {dandisetId ? `Uploading into your dandiset ${dandisetId}` : 'Uploading into a new dandiset in your EMBER-DANDI account'} + {spawnedWorkspaceId !== undefined ? `, analyzed in workspace ${spawnedWorkspaceId}.` : ', analyzed in a new workspace.'} + + )} + // One scroll: its children keep their height instead of shrinking to fit. + *': { flexShrink: 0 } }}> {step === 'uploading' && } {step === 'success' && } @@ -409,7 +614,22 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data )} - {runSteps.length > 0 && } + {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 ? : ( + + )} + + )} )} @@ -438,18 +658,28 @@ export default function DataUploadDialog({ open, onClose, onAuthRequired }: Data disabled={!canUpload} onClick={handleUpload} > - {spawnedWorkspaceId !== undefined ? '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. */} + {footerRetry && ( + + )} )} 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/LoginDialog.tsx b/applications/idp-arc/frontend/src/components/LoginDialog.tsx new file mode 100644 index 0000000..bfa900c --- /dev/null +++ b/applications/idp-arc/frontend/src/components/LoginDialog.tsx @@ -0,0 +1,178 @@ +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, UPLOAD_BACKEND } from '../app/container' +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; + * 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). */ + 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 [osbError, setOsbError] = useState('') + + const loginToOsb = async () => { + setOsbError('') + markLoginDialogReturn() + 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 = () => { + setEmberError('') + let attempt: ReturnType + try { + attempt = emberAuth.connectInPopup() + } catch (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) + 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)) + }, + ) + } + + // EMBER-DANDI only when uploads go there (UPLOAD_BACKEND); the bucket needs OSB's login alone. + const usesEmber = UPLOAD_BACKEND === 'ember' + const rows = [ + ...(usesEmber ? [{ + title: t('loginDialog.emberTitle'), description: t('loginDialog.emberDescription'), + signedIn: emberAuth.isConnected(), + login: loginToEmber, + waiting: emberWait, + waitingText: t('loginDialog.emberWaiting'), + error: emberError, + }] : []), + { + title: t('loginDialog.osbTitle'), description: t('loginDialog.osbDescription'), + signedIn: osbSignedIn, + login: () => void loginToOsb(), + waiting: osbWait, + waitingText: t('loginDialog.osbWaiting'), + error: osbError, + }, + ].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 } + + return ( + + + + + {t('loginDialog.title')} + + {t('loginDialog.subtitle')} + + + + + + + + {t(usesEmber ? 'loginDialog.notice' : 'loginDialog.noticeOsbOnly')} + + + }> + {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..2829a6d 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,19 @@ 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, 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 { 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' const ArrowIcon = () => @@ -42,6 +42,11 @@ 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() +/** Once per page load: a run saved before the reload reopens the upload dialog. */ +let savedRunOffered = false + export default function PageLayout({ children, title, @@ -54,53 +59,123 @@ 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) + /** 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) + const closeLoginDialog = () => { + pendingLoginReturn = false + setLoginDialogOpen(false) + } - async function handleLogin() { - let loginUrl: string + /** + * 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. Throws OsbUnreachable when + * Keycloak doesn't answer. + */ + async function startOsbLogin(onEnded: () => void): Promise<{ cancel: () => void } | 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('', 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 { - loginUrl = await authClient.getLoginUrl(`${window.location.origin}/`) + 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 + 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 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' + // Signed in to OSB only while there is a token: the session can end (or the auth client be + // 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 && (!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 + * auth client then reports it, and the app shows OSB as signed out). + */ + const checkLogins = async () => { + const ember = emberAuth.isConnected() + setEmberSignedIn(ember) + const osb = osbSignedIn && await authClient.getToken().then(() => true, () => false) + return (!needsEmber || ember) && osb + } + const openLoginDialog = () => { + void checkLogins() + setLoginDialogOpen(true) + } + /** 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) + 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 = () => { + clearAllRuns() + emberAuth.disconnect() + setEmberSignedIn(false) + if (isAuthenticated) authClient.logout() + } + const anySignedIn = isAuthenticated || (needsEmber && emberSignedIn) + + // 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(() => { - registerUploadOpener(() => - isAuthenticated ? setUploadDialogOpen(true) : void handleLogin() - ) - }, [isAuthenticated]) + if (savedRunOffered || typeof user !== 'string' || loginDialogOpen) return + savedRunOffered = true + // 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]) 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 }, + ...(needsEmber ? [{ label: t('nav.myDandisets'), path: MY_DANDISETS_URL, external: true }] : []), + ] : []), ] const isActive = (path: string) => location.pathname === path @@ -280,18 +355,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 +440,24 @@ export default function PageLayout({ {label} ))} - {isAuthenticated ? ( + {!loginsDone && ( - ) : ( + )} + {anySignedIn && ( )} - - ) } diff --git a/applications/idp-arc/frontend/src/components/RunChecklist.tsx b/applications/idp-arc/frontend/src/components/RunChecklist.tsx index 5bb851a..1f2b667 100644 --- a/applications/idp-arc/frontend/src/components/RunChecklist.tsx +++ b/applications/idp-arc/frontend/src/components/RunChecklist.tsx @@ -4,7 +4,9 @@ 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' +import { DONE_EARLIER } from '../core/userMessages' const STEP_ICON_SX = { fontSize: 20, flexShrink: 0, mt: '1px' } @@ -24,22 +26,26 @@ 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) => ( - + {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} )} + {/* 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/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/components/loginReturn.ts b/applications/idp-arc/frontend/src/components/loginReturn.ts new file mode 100644 index 0000000..72726b8 --- /dev/null +++ b/applications/idp-arc/frontend/src/components/loginReturn.ts @@ -0,0 +1,44 @@ +/** + * Reopens the Login dialog after a login took the user away from the page: EMBER-DANDI's sign-in + * 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. + */ + +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 + } +} + +/** + * 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' + +/** 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/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/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/components/uploadSession.ts b/applications/idp-arc/frontend/src/components/uploadSession.ts new file mode 100644 index 0000000..271b68a --- /dev/null +++ b/applications/idp-arc/frontend/src/components/uploadSession.ts @@ -0,0 +1,99 @@ +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 + /** 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 = { + 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 run stopped unexpectedly. Retry to carry on from where it stopped.' + +/** 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 || 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 } + 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/dandisetLinks.ts b/applications/idp-arc/frontend/src/core/dandisetLinks.ts new file mode 100644 index 0000000..b715e88 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/dandisetLinks.ts @@ -0,0 +1,87 @@ +/** + * What an IDP dandiset is for, recorded in its own EMBER-DANDI metadata: the protocol it holds + * data for, and the OSB workspace that data runs in. Choosing a protocol in the upload dialog lists + * the researcher's dandisets for that protocol, and picking one picks its workspace too. + * + * Both are `relatedResource` entries rather than custom top-level fields: DANDI's schema already + * defines that field, so the draft stays valid and publishable. An entry is ours when its + * `identifier` starts with one of the prefixes below. The workspace's carries the OSB domain, + * because workspace ids don't carry across OSB environments: a dev link must never match on prod. + */ + +/** A dandiset's draft metadata document, exactly as EMBER returns it. Written back whole. */ +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 +} + +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: protocolLinkId(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/IAuthClient.ts b/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts index 9024cbd..3dc9a6d 100644 --- a/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts +++ b/applications/idp-arc/frontend/src/core/ports/IAuthClient.ts @@ -15,12 +15,19 @@ 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 /** Logs the user out and clears the session. */ logout(): void + /** Calls `listener` when the session turns out to be over (its token can no longer be had), so + * the app stops showing the user as signed in. */ + onSessionEnded(listener: () => void): void + /** Parsed payload of the current token, or null when unauthenticated. */ readonly tokenParsed: Record | null } 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/IDandiDirectApi.ts b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts new file mode 100644 index 0000000..b506e64 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/ports/IDandiDirectApi.ts @@ -0,0 +1,132 @@ +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 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. */ + blobId?: string +} + +export interface DirectUploadedPart { + partNumber: number + size: number + etag: string +} + +export interface DirectFinalizeInput { + /** Absent on the deduplicated path: there is 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 +} + +/** + * 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 = { + pending: 'Pending', + validating: 'Validating', + valid: 'Valid', + /** Can't be published as it is; `errors` says why. */ + invalid: 'Invalid', + publishing: 'Publishing', + /** For the draft: unchanged since the last published version, so nothing new to publish. */ + published: 'Published', +} as const + +/** 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. */ + filesBeingChecked: number +} + +/** A published (frozen) version of a dandiset. */ +export interface PublishedVersion { + version: string + /** Its DOI, e.g. `10.60533/ember-dandi.000542/0.260924.1156`. */ + doi?: string + /** Its page on EMBER-DANDI. */ + url?: string +} + +export interface IDandiDirectApi { + /** `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). */ + 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 + + /** `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. */ + publishDraft(token: string, dandisetId: string): Promise + + /** The most recent published version, with its DOI; null when there is none yet. */ + getLatestPublished(token: string, dandisetId: string): 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/IEmberAuth.ts b/applications/idp-arc/frontend/src/core/ports/IEmberAuth.ts new file mode 100644 index 0000000..abf7e59 --- /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: EmberOAuthClient.connectInPopup(). + */ +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, since 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/core/ports/IEmberUploadApi.ts b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts new file mode 100644 index 0000000..88390ce --- /dev/null +++ b/applications/idp-arc/frontend/src/core/ports/IEmberUploadApi.ts @@ -0,0 +1,47 @@ +/** + * 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. + */ + +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..0f9a119 100644 --- a/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts +++ b/applications/idp-arc/frontend/src/core/ports/IObjectStore.ts @@ -1,25 +1,55 @@ /** - * 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. */ +/** 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. */ protocolId: string /** The uploader's Keycloak id (`sub`): groups uploads by contributor. */ userSub: string + /** 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 `maabcdAggregateDandisetId`), 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 } +/** 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: 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/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/ports/index.ts b/applications/idp-arc/frontend/src/core/ports/index.ts index 1359619..c402b2a 100644 --- a/applications/idp-arc/frontend/src/core/ports/index.ts +++ b/applications/idp-arc/frontend/src/core/ports/index.ts @@ -1,5 +1,7 @@ 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' +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..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 { @@ -25,3 +24,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/runSettings.ts b/applications/idp-arc/frontend/src/core/runSettings.ts index 14a64b3..16b1907 100644 --- a/applications/idp-arc/frontend/src/core/runSettings.ts +++ b/applications/idp-arc/frontend/src/core/runSettings.ts @@ -32,4 +32,15 @@ export const RUN_SETTINGS = { * run stopped before any notebook ran. */ runResultTimeoutMs: 15_000, + + // ─── The DOI ───────────────────────────────────────────────────────────────── + + /** How often EMBER-DANDI is asked whether the draft is valid, and whether the version is out. */ + publishStatusPollMs: 5_000, + + /** How long EMBER may take to validate the draft (it checks every new file). */ + publishDraftValidationTimeoutMs: 15 * 60_000, + + /** How long EMBER may take to publish the version once asked. */ + publishVersionTimeoutMs: 10 * 60_000, } diff --git a/applications/idp-arc/frontend/src/core/types.ts b/applications/idp-arc/frontend/src/core/types.ts index 2a9e2e4..c6ce3cb 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. * @@ -19,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 = @@ -63,11 +33,25 @@ 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', + maabcd: 'maabcd', + 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 @@ -79,7 +63,39 @@ export interface RunState { /** Every step of the run, in order, for the checklist. */ steps: RunStep[] workspaceId?: number + /** 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 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 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/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 new file mode 100644 index 0000000..03bfef9 --- /dev/null +++ b/applications/idp-arc/frontend/src/core/use-cases/emberObjectStore.ts @@ -0,0 +1,138 @@ +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 } + +/** + * 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. + * + * 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. + * 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 + /** 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 } +} + +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 saved: EmberUploadCheckpoint = { ...(input.resume as EmberUploadCheckpoint | undefined) } + const save = (patch: EmberUploadCheckpoint) => { + Object.assign(saved, patch) + input.onCheckpoint?.({ ...saved }) + } + + const progress = (sent: number) => onProgress?.(Math.min(sent, file.size), file.size) + progress(saved.own ? file.size : 0) + + // 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 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, { + uploadId: init.uploadId, dandisetId: userDandisetId, path, parts: uploaded, blobId: init.blobId, + }) + save({ own: { assetId: asset.assetId, assetPath: asset.assetPath } }) + } + progress(file.size) + + return { + url: `${emberApiOrigin.replace(/\/+$/, '')}/api/assets/${asset.assetId}/download/`, + key: asset.assetPath, + name: file.name, + size: file.size, + dandisetId: userDandisetId, + etag: saved.etag, + } + }, + + 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. */ +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..772836b --- /dev/null +++ b/applications/idp-arc/frontend/src/core/use-cases/protocolDandisets.ts @@ -0,0 +1,156 @@ +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' +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. */ +export const DANDISET_LICENSE = ['spdx:CC-BY-4.0'] + +/** 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 { + constructor(dandisetId: string, reason: string) { + super(`Dandiset ${dandisetId} could not be published: ${reason}`) + } +} + +/** One of the researcher's dandisets for a protocol, as the upload dialog offers it. */ +export interface ProtocolDandiset { + id: string + name: string +} + +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`, 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): 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`. */ + async function createForProtocol(name: string, protocol: ProtocolRef): Promise { + return direct.createDandiset(token(), name, withProtocolLink({ license: DANDISET_LICENSE }, 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) + } + + /** + * Publishes the dandiset's draft as a new version and returns it, with its DOI; null if + * `stopped` first. EMBER publishes only a valid draft, and validates it again after every change. + */ + async function publish(dandisetId: string, stopped: () => boolean = () => false): Promise { + const t = token() + await addLicenseIfMissing(t, dandisetId) + const status = await waitUntilPublishable(t, dandisetId, stopped) + if (!status) return null + // Unchanged since the last version: that version already holds this data. + if (status === VERSION_STATUS.published) return latestVersion(t, dandisetId) + return publishNewVersion(t, dandisetId, stopped) + } + + /** Older IDP dandisets have no license. */ + async function addLicenseIfMissing(t: string, dandisetId: string) { + const metadata = await direct.getDraftMetadata(t, dandisetId) + if (!metadata.license) await direct.updateDraftMetadata(t, dandisetId, { ...metadata, license: DANDISET_LICENSE }) + } + + /** + * 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: VersionStatus = VERSION_STATUS.pending + const ended = await pollUntil(async () => { + 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 && draft.errors.length)) { + throw notPublishable(draft.errors) + } + 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.', + `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 + await direct.publishDraft(t, dandisetId) + let latest: PublishedVersion | null = null + const ended = await pollUntil(async () => { + latest = await direct.getLatestPublished(t, dandisetId) + return !!latest?.doi && latest.version !== previous + }, { everyMs: RUN_SETTINGS.publishStatusPollMs, timeoutMs: RUN_SETTINGS.publishVersionTimeoutMs, stopped }) + if (ended === 'timeout') throw new PublishError(dandisetId, 'the new version did not appear in time') + return ended === 'done' ? latest : null + } + + async function latestVersion(t: string, dandisetId: string): Promise { + const latest = await direct.getLatestPublished(t, dandisetId) + if (!latest?.doi) throw new PublishError(dandisetId, 'its latest version has no DOI') + return latest + } + + return { listForProtocol, recordedWorkspace, createForProtocol, recordWorkspace, publish } +} + +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..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,13 +1,13 @@ -import type { RunPhase, RunState, RunStep, StepState } from '../types' -import { UserFacingError, userMessage } from '../userMessages' +import type { RunCheckpoint, RunPhase, RunState, RunStep, RunStepId, StepState } from '../types' +import { stoppedMessage, 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 @@ -25,16 +25,20 @@ 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 + /** 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) { + /** `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 } /** 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) @@ -42,22 +46,28 @@ 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) } + /** 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 @@ -67,7 +77,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' @@ -85,18 +95,23 @@ 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) { - const { phase, steps, workspaceId, outputsDir } = this - this.report({ phase, message, steps, workspaceId, outputsDir, ...(error ? { error } : {}) }) + const { phase, steps, workspaceId, dandisetId, outputsDir, checkpoint } = this + this.report({ + phase, message, steps, workspaceId, outputsDir, + ...(dandisetId ? { dandisetId } : {}), ...(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) @@ -105,7 +120,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 2823026..55eec41 100644 --- a/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts +++ b/applications/idp-arc/frontend/src/core/use-cases/runProtocol.ts @@ -1,11 +1,12 @@ import type { IAuthClient } from '../ports/IAuthClient' import type { IObjectStore, StoredObject } from '../ports/IObjectStore' +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' -import { parseRepoZipUrl } from '../protocolRepo' +import { parseRepoZipUrl, repoPage } from '../protocolRepo' import { RUN_SETTINGS } from '../runSettings' -import { UserFacingError } from '../userMessages' +import { DONE_EARLIER, UserFacingError, userMessage } from '../userMessages' import { workspaceLayout } from '../workspaceLayout' import { inStep, pollUntil, RunProgress, type OnRunState } from './runProgress' @@ -28,6 +29,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 + /** The protocol's MAABCD dandiset on EMBER-DANDI, which each upload is also copied into + * (through OSB). Empty or absent: no MAABCD copy. */ + maabcdAggregateDandisetId?: string } export interface RunProtocolInput { @@ -38,6 +42,42 @@ export interface RunProtocolInput { workspaceId?: number /** Name for the workspace created when `workspaceId` is undefined. */ workspaceName: string + /** 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 + /** From an earlier attempt that stopped: the run carries on from there when canResume allows. */ + resume?: RunCheckpoint + /** 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 +} + +/** + * 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 + // 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 + && sameFile + && checkpoint.shareWithMaabcd === (input.shareWithMaabcd !== false) + && sameDandiset && sameWorkspace } /** @@ -53,22 +93,30 @@ 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, submitted: undefined } + 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: 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' }, + { id: RUN_STEP.imports, label: 'Wait for the imports to finish' }, + { id: RUN_STEP.run, label: 'Run the notebooks' }, ] +/** 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, per the MAABCD–OSB design (Scenario 1). 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: browser → public bucket (IObjectStore); its URL 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 @@ -88,6 +136,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. 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, @@ -95,48 +149,114 @@ 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 } = input - const progress = new RunProgress(report, STEPS, 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 } + : { 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 } + } + 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) + + if (retryNonBlockingOf) return retryNonBlocking(retryNonBlockingOf) 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}` - if (!file) { - progress.skip('upload') - progress.skip('data') + // 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 (!hasData) { + progress.skip(RUN_STEP.upload) + progress.skip(RUN_STEP.data) } + 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. - const stored = file ? await inStep('upload', () => uploadFile(file, userId)) : null + let stored: StoredObject | null = null + if (checkpoint.stored) { + stored = checkpoint.stored + doneEarlier(RUN_STEP.upload) + } else if (file) { + 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. - const workspaceId = await inStep('workspace', prepareWorkspace) + // 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(RUN_STEP.workspace, async () => { + const id = await prepareWorkspace() + save({ workspaceId: id }) + if (!checkpoint.workspaceRecorded) { + if (stored) await objectStore.recordWorkspace?.(stored, id, protocolRef()) + save({ workspaceRecorded: true }) + } + return id + }) if (stopped()) return + if (!(await importAndRun(workspaceId, stored, repo, layout))) return + 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). - await inStep('repo', () => importRepo(workspaceId, repo, layout.run)) + 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) await inStep('data', () => importData(workspaceId, file, stored, layout.inputs)) + if (stored && checkpoint.dataImported) doneEarlier(RUN_STEP.data) + else if (stored) { + const upload = stored + await inStep(RUN_STEP.data, () => importData(workspaceId, upload, layout.inputs)) + save({ dataImported: true }) + } - // 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 + // 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 + const notebooks = await inStep(RUN_STEP.imports, () => waitForImports(workspaceId, layout.run, repoDir)) + if (!notebooks) return false // 6. Run the notebooks. - await inStep('run', () => runNotebooks(workspaceId, repoDir, notebooks, layout, !!stored)) - } catch (err) { - progress.fail(err) + 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 ──────────────────────────────────────────────────────────────────────── @@ -158,47 +278,89 @@ 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 }, (sent, total) => { + 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)`, + protocol: protocolRef(), + maabcd: input.shareWithMaabcd === false ? undefined : protocol.maabcdAggregateDandisetId, + }, + }, (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) + progress.update(RUN_STEP.upload, `${formatBytes(sent)} of ${formatBytes(total)} (${pct}%)`, message) }) - progress.done('upload', undefined, 'Upload finished') + // 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(RUN_STEP.upload, undefined, 'Upload finished') 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 || !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 objectStore.shareWithMaabcd(stored, protocol.maabcdAggregateDandisetId!, file) + 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('workspace', 'workspace', 'Getting the workspace ready…') - if (input.workspaceId !== undefined) { - progress.done('workspace', undefined, 'Workspace ready') + progress.start(RUN_STEP.workspace, 'workspace', 'Getting the workspace ready…') + // A run picked up again (perhaps days later): its workspace may have been deleted since. + 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 + } + // 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 input.workspaceId } 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…') + 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('data') + progress.done(RUN_STEP.data) } /** @@ -206,7 +368,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. @@ -214,11 +376,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}/` @@ -229,16 +399,20 @@ 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`) - progress.done('imports') + 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 } - /** 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) { - progress.start('run', 'running', 'Starting the notebooks…', 'Submitting') + layout: ReturnType, hasData: boolean): Promise { + 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 }, @@ -255,6 +429,14 @@ export function createRunProtocolUseCase( results: { notebooks: layout.notebooks, log: layout.log }, ...(protocol.image ? { image: protocol.image } : {}), }) + // 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. @@ -262,13 +444,13 @@ 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 !== 'done') return + 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 // passed, else in notebooks.failed/ (the failed one last), and its workflow ends with a scan @@ -282,13 +464,14 @@ export function createRunProtocolUseCase( failedAt = paths.filter((path) => path.startsWith(failedDir)).sort().pop() return !!failedAt || executed.every((path) => paths.includes(path)) }, { everyMs: RUN_SETTINGS.runPollMs, timeoutMs: RUN_SETTINGS.runResultTimeoutMs, stopped }) - if (listed === 'stopped') return + 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). 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.finish('The analysis has finished') + progress.done(RUN_STEP.run, `Results in ${layout.run}/`) + return true } } } diff --git a/applications/idp-arc/frontend/src/core/userMessages.ts b/applications/idp-arc/frontend/src/core/userMessages.ts index e093f31..6695618 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,20 +14,51 @@ 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.', +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.', + [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.', +} + +/** 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.' + +/** 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." + +/** 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." + /** 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' /** 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/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 13306ee..5f3d3f3 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", + "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/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 new file mode 100644 index 0000000..d2dc359 --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberDandiDirectClient.ts @@ -0,0 +1,321 @@ +import type { DandisetMetadata } from '../core/dandisetLinks' +import type { + DirectFinalizeInput, + DirectInitResult, + DandisetVersion, + VersionStatus, + IDandiDirectApi, + OwnDandiset, + PublishedVersion, + 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 + +/** 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. + * + * 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. + */ +export class EmberDandiDirectClient implements IDandiDirectApi { + private readonly baseUrl: string + + constructor(baseUrl: string) { + this.baseUrl = baseUrl + } + + 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, 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}${searched}&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 { + 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') + } + + 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, 'version info read') + type Problem = { field?: string; path?: string; message: string } + const body = (await res.json()) as { + version?: string + status: VersionStatus + version_validation_errors?: Problem[] + asset_validation_errors?: Problem[] + } + // 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 { version: body.version ?? version, status: body.status, errors, filesBeingChecked: assetProblems.filter(beingChecked).length } + } + + 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, true), + body: '{}', + }) + if (!res.ok) await this.fail(res, 'publish') + } + + async getLatestPublished(token: string, dandisetId: string): Promise { + const res = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/`, { headers: this.headers(token) }) + if (!res.ok) await this.fail(res, 'dandiset read') + const latest = (await res.json()) as { most_recent_published_version?: { version?: string } | null } + const version = latest.most_recent_published_version?.version + if (!version) return null + // The DOI is in the version's own metadata. + const info = await fetch(`${this.baseUrl}/api/dandisets/${dandisetId}/versions/${version}/info/`, { + headers: this.headers(token), + }) + if (!info.ok) await this.fail(info, 'published version read') + const metadata = ((await info.json()) as { metadata?: { doi?: string; url?: string } }).metadata ?? {} + return { version, doi: metadata.doi, url: metadata.url } + } + + /** `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, 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) + 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/emberOAuthClient.ts b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts new file mode 100644 index 0000000..46428ad --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberOAuthClient.ts @@ -0,0 +1,335 @@ +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. + * + * 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 them at once. + 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 or 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 + } + + /** 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 { + this.checkClientId() + 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. 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 } { + 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()}` + 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/emberUploadApiClient.ts b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts new file mode 100644 index 0000000..ba38387 --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberUploadApiClient.ts @@ -0,0 +1,77 @@ +import type { + BrokeredAsset, + BrokeredUpload, + BrokeredUploadInput, + BrokeredValidateInput, + IEmberUploadApi, +} from '../core/ports/IEmberUploadApi' + +/** + * 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. + * + * `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 { + 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}`, { + 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, '/dandi/get_upload_urls', { + instance: this.instance, + username: this.keyUsername, + 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, '/dandi/validate_upload', { + instance: this.instance, + username: this.keyUsername, + 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/src/infra/emberUrls.ts b/applications/idp-arc/frontend/src/infra/emberUrls.ts new file mode 100644 index 0000000..a5ce025 --- /dev/null +++ b/applications/idp-arc/frontend/src/infra/emberUrls.ts @@ -0,0 +1,3 @@ +/** 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/src/infra/keycloakAuthClient.ts b/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts index 99a3b27..2228265 100644 --- a/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts +++ b/applications/idp-arc/frontend/src/infra/keycloakAuthClient.ts @@ -9,9 +9,22 @@ 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() + } + + onSessionEnded(listener: () => void): void { + this.sessionEndedListeners.push(listener) + } + + private sessionEnded() { + for (const listener of this.sessionEndedListeners) listener() } init(): Promise { @@ -31,13 +44,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 @@ -47,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 049151f..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 @@ -34,6 +38,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') } 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)) -} 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/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/publicBucketObjectStore.ts b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts index b3245de..4d773d9 100644 --- a/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts +++ b/applications/idp-arc/frontend/src/infra/publicBucketObjectStore.ts @@ -1,8 +1,9 @@ import type { IObjectStore, ObjectUploadInput, StoredObject } from '../core/ports/IObjectStore' +import { UPLOADS_NOT_SET_UP, UserFacingError } from '../core/userMessages' /** - * 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,13 +15,13 @@ 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(/\/+$/, '') } 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 @@ -36,7 +37,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/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/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 ee7b936..e1fc2ec 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", @@ -19,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/" } @@ -39,11 +40,16 @@ "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 analyze it in Open Source Brain." + }, "nav": { "logoTitle": "MAABCD Platform", "protocols": "Protocols", "about": "About", "myWorkspaces": "My workspaces", + "myDandisets": "My dandisets", "login": "Login", "logout": "Logout", "dataUpload": "Data upload", @@ -60,5 +66,28 @@ "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.", + "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": "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", + "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", + "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/src/pages/LandingPage.tsx b/applications/idp-arc/frontend/src/pages/LandingPage.tsx index 04209db..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 }> @@ -34,7 +39,7 @@ export default function LandingPage() { - 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')} + + + + + ) +} 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() { diff --git a/applications/idp-arc/frontend/src/theme/components.ts b/applications/idp-arc/frontend/src/theme/components.ts index 90f053e..7be6e32 100644 --- a/applications/idp-arc/frontend/src/theme/components.ts +++ b/applications/idp-arc/frontend/src/theme/components.ts @@ -178,6 +178,12 @@ export const theme = createTheme({ '&:hover': { backgroundColor: 'var(--mui-palette-text-secondary)', }, + // Keeps its own colours when disabled (the root's opacity dims it): MUI's disabled + // colours are near-transparent here, so the button vanished against the dialog. + '&.Mui-disabled': { + backgroundColor: 'var(--mui-palette-text-primary)', + color: 'var(--mui-palette-background-default)', + }, }, outlined: { color: 'var(--mui-palette-text-primary)', 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..ae5b4e8 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/emberClients.test.ts @@ -0,0 +1,134 @@ +// 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, {}) +}) + +test('a version\'s status 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 draft = await ember.getVersionInfo('ember-token', '000777', 'draft') + + assert.equal(requests[0].url, '/ember-proxy/api/dandisets/000777/versions/draft/info/') + 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, + }) +}) + +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('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') + 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/tests/unit/emberObjectStore.test.ts b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts new file mode 100644 index 0000000..b27cdf1 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/emberObjectStore.test.ts @@ -0,0 +1,179 @@ +// 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' +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') +const finalizedPaths: string[] = [] + +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') }, + async getDraftMetadata() { return {} }, + async updateDraftMetadata() {}, + async getVersionInfo() { return { version: 'draft', status: 'Valid', errors: [], filesBeingChecked: 0 } }, + async publishDraft() {}, + 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()}` }, + 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 } + }, + } + 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 } + }, + 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; the MAABCD copy is a separate call, 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']) + // 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/`) + 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 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 store().shareWithMaabcd!(stored, '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 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(store().shareWithMaabcd!(stored, '000533', file()), /part URLs/) + 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, []) +}) + +// ── Retry: carrying on from the checkpoint ─────────────────────────────────────────────────── + +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(store().shareWithMaabcd!(stored, '000533', file()), /503/) + calls.length = 0 + + 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']) +}) + +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 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 () => { + 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.equal((checkpoints.at(-1) as { userDandisetId?: string }).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' } } + 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/`) +}) + diff --git a/applications/idp-arc/frontend/tests/unit/objectStore.test.ts b/applications/idp-arc/frontend/tests/unit/objectStore.test.ts index 8f1df99..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 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' +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 ?? '')) +}) 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..921bf83 --- /dev/null +++ b/applications/idp-arc/frontend/tests/unit/protocolDandisets.test.ts @@ -0,0 +1,222 @@ +// 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, 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, 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' } + +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) +}) + +/** `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[]; filesBeingChecked?: number }[] + 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(_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) { drafts.push(id); return metadata[id] ?? {} }, + async updateDraftMetadata(_t, id, m) { writes.push({ id, metadata: m }) }, + 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 { version, status: s.status as VersionStatus, errors: s.errors ?? [], filesBeingChecked: s.filesBeingChecked ?? 0 } + }, + async publishDraft(_t, id) { calls.push(`publish:${id}`) }, + async getLatestPublished() { + const all = publishing.versions ?? [null] + return all[Math.min(versionReads++, all.length - 1)] + }, + 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, calls, drafts } +} + +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) }) + + 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('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': withProtocolLink({}, FOUR), // no workspace yet + '000003': withWorkspaceLink(withProtocolLink({}, { id: 'four-choice-reversal-v2', name: 'v2' }), DEV, 7, 'u'), + }) + + 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 () => { + 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') +}) + +// ── Publishing for a DOI ───────────────────────────────────────────────────────────────────── + +const fastPolls = () => { RUN_SETTINGS.publishStatusPollMs = 1 } + +test('new dandisets get a license, since EMBER publishes none without one', async () => { + const { uc, created } = fakeEmber({}) + await uc.createForProtocol('Four (IDP)', FOUR) + assert.deepEqual(created[0].metadata?.license, DANDISET_LICENSE) +}) + +test('publishing waits for a valid draft, publishes, and returns the new version with its DOI', async () => { + fastPolls() + const { uc, calls, writes } = fakeEmber({ '000777': { name: 'Mine', license: ['spdx:CC0-1.0'] } }, { + statuses: [{ status: 'Pending' }, { status: 'Validating' }, { status: 'Valid' }], + versions: [ + { version: '0.260924.1156', doi: '10.60533/ember-dandi.000777/0.260924.1156' }, // before + { version: '0.260924.1156', doi: '10.60533/ember-dandi.000777/0.260924.1156' }, // not out yet + { version: '0.261010.1200', doi: '10.60533/ember-dandi.000777/0.261010.1200', url: 'https://ember/000777/0.261010.1200' }, + ], + }) + + const published = await uc.publish('000777') + + assert.deepEqual(calls, ['status:Pending', 'status:Validating', 'status:Valid', 'publish:000777']) + assert.equal(published?.doi, '10.60533/ember-dandi.000777/0.261010.1200') + assert.equal(writes.length, 0, 'its own license is kept') +}) + +test('a dandiset without a license gets one before publishing', async () => { + fastPolls() + const { uc, writes } = fakeEmber({ '000777': { name: 'Mine' } }, { versions: [null, { version: '0.261010.1200', doi: 'd' }] }) + await uc.publish('000777') + assert.deepEqual(writes, [{ id: '000777', metadata: { name: 'Mine', license: DANDISET_LICENSE } }]) +}) + +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: ['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'] } }, { + statuses: [{ status: 'Published' }], versions: [{ version: '0.261010.1200', doi: '10.60533/ember-dandi.000777/0.261010.1200' }], + }) + assert.equal((await uc.publish('000777'))?.version, '0.261010.1200') + assert.ok(!calls.some((c) => c.startsWith('publish:'))) +}) + +test('stopping while EMBER validates publishes nothing', async () => { + fastPolls() + const { uc, calls } = fakeEmber({ '000777': { license: ['x'] } }, { statuses: [{ status: 'Pending' }] }) + let reads = 0 + assert.equal(await uc.publish('000777', () => reads++ > 2), null) + assert.ok(!calls.some((c) => c.startsWith('publish:'))) +}) diff --git a/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts b/applications/idp-arc/frontend/tests/unit/runProtocol.test.ts index d6179a6..2402017 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 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' +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,6 +39,7 @@ function fakes(opts: { runPolls?: number; importPolls?: number; failUpload?: boo let runPollsLeft = 0 const api: IWorkspaceApi = { async listWorkspaces() { return [] }, + 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' }] } @@ -67,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 } @@ -87,6 +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) + // 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')) @@ -171,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 () => { @@ -297,3 +310,310 @@ 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', name: 'animal_01.xlsx', dandisetId: '000777' } + }, + async recordWorkspace(_stored, id) { f.calls.push(`record:${id}`) }, + } + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)( + { protocol: { ...FOUR_CHOICE, maabcdAggregateDandisetId: '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' }, + }) +}) + +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', name: 'animal_01.xlsx', dandisetId: '000777' } + }, + } + const states: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)( + { protocol: { ...FOUR_CHOICE, maabcdAggregateDandisetId: '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) +}) + +/** 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', 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 } +} +/** 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/) + + // Its row's Retry: the same use case, given the finished run's checklist. + const runs = count(f.calls, 'run') + const retried: RunState[] = [] + await createRunProtocolUseCase(auth, f.api, store)( + { ...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'), + 'the other rows stay as they were') + 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. */ +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('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.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') +}) + +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') +}) + + +// ── 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('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') + 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/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 }) +}) 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..df17882 --- /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, /stopped unexpectedly/) + 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') +}) diff --git a/applications/idp-arc/frontend/vite.config.ts b/applications/idp-arc/frontend/vite.config.ts index 5509adb..29c3518 100644 --- a/applications/idp-arc/frontend/vite.config.ts +++ b/applications/idp-arc/frontend/vite.config.ts @@ -1,26 +1,45 @@ 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' +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. 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 + * 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() // 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()], @@ -33,16 +52,23 @@ export default defineConfig({ host: '0.0.0.0', port: 5173, strictPort: true, + ...(devHttps ? { https: devHttps } : {}), watch: { usePolling: true }, proxy: { '/api-proxy': { - target: WWW_ORIGIN, + target: OSB_WEB_ORIGIN, agent: upstreamAgent, changeOrigin: true, rewrite: (path) => path.replace(/^\/api-proxy/, ''), }, + // EMBER's token reply has no CORS headers. Only what the app calls, as nginx (default.conf). + '^/ember-proxy/(oauth/token/|api/)': { + target: EMBER_API_ORIGIN, + changeOrigin: true, + rewrite: (path) => path.replace(/^\/ember-proxy/, ''), + }, }, }, resolve: { diff --git a/deployment/codefresh-dev.yaml b/deployment/codefresh-dev.yaml index 70bc13f..c5386e7 100644 --- a/deployment/codefresh-dev.yaml +++ b/deployment/codefresh-dev.yaml @@ -142,7 +142,9 @@ 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 title: Idp arc working_directory: ./applications/idp-arc