Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
71 changes: 58 additions & 13 deletions src/components/map-projects/AutoMatchDialog.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,9 +15,13 @@ import FormLabel from '@mui/material/FormLabel';
import Chip from '@mui/material/Chip'
import Alert from '@mui/material/Alert';
import Box from '@mui/material/Box';
import { visuallyHidden } from '@mui/utils';
import Tooltip from '@mui/material/Tooltip';
import CircularProgress from '@mui/material/CircularProgress';
import Typography from '@mui/material/Typography';

import DoubleArrowIcon from '@mui/icons-material/DoubleArrow';
import ErrorOutlineIcon from '@mui/icons-material/ErrorOutlineOutlined';

import map from 'lodash/map'

Expand All @@ -32,6 +36,10 @@ import useAutoMatchCheck from '@openconceptlab/oclmap-extensions'
// Lines an option's sub-text up with its checkbox label.
const SUBTEXT_SX = {margin: '-6px 0 0 32px'}

// Describes the disabled Submit while the target repository loads or after it
// failed to load.
const TARGET_REPO_STATUS_ID = 'automatch-target-repo-status'

const AutoMatchDialog = ({
open,
onClose,
Expand All @@ -48,6 +56,9 @@ const AutoMatchDialog = ({
promptTemplate,
setPromptTemplate,
repoVersion,
targetRepoState,
onRetryTargetReads,
retryTargetReadsWaiting,
onSubmit,
inAIAssistantGroup,
algosSelected,
Expand Down Expand Up @@ -167,8 +178,11 @@ const AutoMatchDialog = ({

notices.push(...(check.notices || []))

const targetRepoSettling = ['loading', 'failed'].includes(targetRepoState)
const targetRepoStatusId = targetRepoSettling ? TARGET_REPO_STATUS_ID : undefined

const isDisabled =
!repoVersion?.version_url ||
targetRepoState !== 'loaded' ||
Boolean(blocker) ||
notices.some(notice => notice.blocks || (notice.confirm && !confirmed[notice.key]))

Expand All @@ -193,10 +207,31 @@ const AutoMatchDialog = ({
<CloseIconButton onClick={onClose} />
</DialogTitle>
<DialogContent sx={{paddingBottom: '12px'}}>
<div className='col-xs-12 padding-0' style={{display: 'flex', alignItems: 'center', fontSize: '1rem'}}>
{/* As tall as the chip, so the chip arriving moves nothing. */}
<div className='col-xs-12 padding-0' style={{display: 'flex', alignItems: 'center', fontSize: '1rem', minHeight: '36px'}}>
{t('map_project.auto_match_target_repository')}
{
repoVersion?.id &&
targetRepoState === 'loading' &&
// The footer's status line says it's loading; hidden here so it's read once.
<CircularProgress size={20} sx={{marginLeft: '12px'}} aria-hidden='true' />
}
{
targetRepoState === 'failed' &&
<>
<Typography id={TARGET_REPO_STATUS_ID} role='alert' variant='body2' sx={{display: 'flex', alignItems: 'center', gap: '6px', marginLeft: '12px', color: 'error.main'}}>
<ErrorOutlineIcon fontSize='small' />
{/* Read out, and as Submit's description, it says what didn't load. */}
<Box component='span' sx={visuallyHidden}>{`${t('map_project.auto_match_target_repository')} `}</Box>
{t('map_project.auto_match_target_repository_failed')}
</Typography>
{/* Waits out a rate-limited read's countdown. */}
<Button size='small' sx={{textTransform: 'none', marginLeft: '8px'}} disabled={Boolean(retryTargetReadsWaiting)} onClick={onRetryTargetReads}>
{t('common.try_again')}
</Button>
</>
}
{
!targetRepoSettling && repoVersion?.id &&
<RepoChip repo={repoVersion} hideType sx={{marginLeft: '12px'}} />
}
</div>
Expand Down Expand Up @@ -335,16 +370,26 @@ const AutoMatchDialog = ({
}
<Box sx={{display: 'flex', alignItems: 'flex-end', flexWrap: 'wrap', gap: '12px'}}>
{check.summary && <Box sx={{flex: '1 1 300px', minWidth: 0}}>{check.summary}</Box>}
<Button
variant='contained'
size='small'
sx={{textTransform: 'none', marginLeft: 'auto'}}
endIcon={<DoubleArrowIcon />}
disabled={isDisabled}
onClick={event => onSubmit(event, retrieveCandidates ? map(runnableAlgos, val => val?.id) : [])}
>
{t('common.submit')}
</Button>
<Box sx={{display: 'flex', alignItems: 'center', gap: '12px', marginLeft: 'auto', minWidth: 0}}>
{/* One line, so the footer keeps its height when it goes. */}
{
targetRepoState === 'loading' &&
<Typography id={TARGET_REPO_STATUS_ID} role='status' variant='body2' noWrap sx={{fontSize: '13px', color: 'text.secondary'}}>
{t('map_project.auto_match_target_repository_loading')}
</Typography>
}
<Button
variant='contained'
size='small'
sx={{textTransform: 'none'}}
endIcon={<DoubleArrowIcon />}
disabled={isDisabled}
aria-describedby={targetRepoStatusId}
onClick={event => onSubmit(event, retrieveCandidates ? map(runnableAlgos, val => val?.id) : [])}
>
{t('common.submit')}
</Button>
</Box>
</Box>
</Box>
</Dialog>
Expand Down
91 changes: 79 additions & 12 deletions src/components/map-projects/MapProject.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ import pick from 'lodash/pick'

import { OperationsContext } from '../app/LayoutContext';

import APIService, { isTransientNetworkError, retryWithBackoff } from '../../services/APIService';
import APIService, { getThrottlingDetails, isTransientNetworkError, retryWithBackoff } from '../../services/APIService';
import { matchToken, lookupTokenFor, needsSessionToken, needsSessionLookupToken, withoutTokens, withSavedTokenURL, withoutLocalKeys, isAbsoluteURL } from '../../services/tokenScope'
import { buildAttributionHeaders, buildConfigSnapshot, summarizeRunCompletion, matchesOnOCL } from '../../services/attribution'
import { CAPACITY_LIMIT, RATE_LIMIT, CAPACITY_WAIT_CAP_MS, HEAVY_REQUEST_TIMEOUT_MS, LIGHT_REQUEST_TIMEOUT_MS, createCapacityGate, createLimiter, isRetryableError, requestWithCapacityRetry, sleepUnlessCancelled, untilCancelled } from '../../services/capacity'
Expand Down Expand Up @@ -122,9 +122,10 @@ import { normalizeAlgorithmInvocation, hasSuccessfulAlgorithmResponse, getAlgori
import { createLookupSession, LOOKUP_NOT_FOUND } from './lookupSession'
import { parseConceptKey } from './conceptKey'
import { normalizeLookupConfig } from './lookupConfigFields'
import { getDeclaredLocales, getDefaultTargetRepoVersion, getProjectTargetRepoVersion, getSavedTargetRepoVersion, getTargetRepoVersionFromUrl, getTargetRepoVersionId } from './projectTargetRepo'
import { getDeclaredLocales, getDefaultTargetRepoVersion, getProjectTargetRepoVersion, getSavedTargetRepoVersion, getTargetRepoState, getTargetRepoVersionFromUrl, getTargetRepoVersionId, getVersionsFromResponse } from './projectTargetRepo'
import { buildBridgeTargetDownloadEntries, buildQualityRowViews, conceptBelongsToTargetRepo, conceptForMapping, findTargetRowView, formatBridgeTargetDownloadEntry, resolveAICandidateID, getScoreDetails, getAIAnalysisCandidateIDs, getAIIndicatorTooltip, withCachedConcept, withCandidateNames, buildMatchEntries, restoredNote, withOwnNames, withSavedMatch } from './viewBuilders.js'
import { formatClockTime, getCapacityWaitLabel, mergeCapacityWaits } from './rowProgress.js'
import { createLatestRead, getRetryAt, isSameTargetRepo, settleRepoRead } from './targetReads'
import { createProjectLogsLoader, mergeSavedLogs, savedLogsFromResult } from './projectLogSync'
import { createMappedSourcesReader, MAPPED_SOURCES_PAGE_SIZE, probeBridgeMappedSources } from './mappedSources'

Expand Down Expand Up @@ -517,6 +518,10 @@ const MapProject = () => {
React.useEffect(() => () => stopTargetMappedSourcesRef.current(), [])
const [locales, setLocales] = React.useState([])
const [versions, setVersions] = React.useState([])
// 'loading' while the target repository, or its versions, are read,
// 'failed' if that read failed, else null (OpenConceptLab/ocl_issues#3067).
const [repoStatus, setRepoStatus] = React.useState(null)
const [versionsStatus, setVersionsStatus] = React.useState(null)
const [conceptCache, setConceptCache] = React.useState({})
const [allMapTypes, setAllMapTypes] = React.useState([])
// PR3-H: OCL Locales source provides the canonical language picker for
Expand Down Expand Up @@ -1558,6 +1563,8 @@ const MapProject = () => {
let _mapTypes = {}
let _proposed = {}
let _repo = null
// The URL of the repository _repo came from, read from its own row.
let _repoRowURL = ''
let _states = {...rowStatuses}
const savedMatches = keyBy(compact(projectData?.matches), 'rowIndex')
const repoVersionURL = data['__Repo URL__'] || data['__map_repo_url__']
Expand Down Expand Up @@ -1586,6 +1593,7 @@ const MapProject = () => {
if(concept?.id) {
_mapSelected[index] = withSavedMatch(concept, savedMatches[index])
_repo = repo
_repoRowURL = data['__Repo URL__'] || data['__map_repo_url__'] || ''
}
let rowStateLabel = data['__State__'] || data['__row_status__'] || data['__row_map_status__']
let state = keys(pickBy(VIEWS, info => info.label === rowStateLabel))[0]
Expand All @@ -1610,7 +1618,9 @@ const MapProject = () => {
let repoURL = projectData?.target_repo_url || _repo?.url
let repoVersion = getProjectTargetRepoVersion(projectData) || _repo?.version || ''
if(repoURL) {
fetchRepo(repoURL, _repo)
// The saved rows' repository stands in for a failed read only if it's
// this project's target.
fetchRepo(repoURL, isSameTargetRepo(_repo, _repoRowURL, repoURL) ? _repo : null)
fetchVersions(repoURL, repoVersion)
}
}
Expand Down Expand Up @@ -2184,7 +2194,23 @@ const MapProject = () => {
)
}

const fetchRepo = (url, _repo) => APIService.new().overrideURL(url).get().then(response => setRepo(response.data?.id ? response.data : _repo))
// Only the latest read may set the repository. A failed read falls back to
// fallbackRepo, if given. Raw, so a rate-limited read settles too.
const repoReadRef = React.useRef(null)
if(!repoReadRef.current)
repoReadRef.current = createLatestRead()
const fetchRepo = (url, fallbackRepo) => {
const isLatest = repoReadRef.current.begin(url, fallbackRepo)
setRepoStatus('loading')
APIService.new().overrideURL(url).get(undefined, undefined, undefined, true).then(response => {
if(!isLatest() || !isMountedRef.current)
return
const settled = settleRepoRead(response, fallbackRepo)
setRepo(settled.repo)
setRepoStatus(settled.status)
noteTargetReadThrottle(response)
})
}

const onRepoVersionChange = version => {
setRepoVersion(version || false)
Expand Down Expand Up @@ -3047,29 +3073,61 @@ const MapProject = () => {

// Only the latest request may set the version: a slower response is for a
// repository no longer chosen.
const versionsRequestRef = React.useRef(0)
const versionsReadRef = React.useRef(null)
if(!versionsReadRef.current)
versionsReadRef.current = createLatestRead()

// A rate-limited target read can be tried again once the app's countdown
// ends; until then the dialog's Try again waits.
const [targetReadsRetryAt, setTargetReadsRetryAt] = React.useState(0)
const noteTargetReadThrottle = response => {
if(response?.response?.status === 429)
setTargetReadsRetryAt(getRetryAt(getThrottlingDetails(response.response).retryAfter, Date.now()))
}
React.useEffect(() => {
if(!targetReadsRetryAt)
return
const timer = setTimeout(() => setTargetReadsRetryAt(0), Math.max(targetReadsRetryAt - Date.now(), 0))
return () => clearTimeout(timer)
}, [targetReadsRetryAt])

// The AutoMatch dialog's Try again repeats whichever read failed.
const retryTargetReads = () => {
if(repoStatus === 'failed')
fetchRepo(...repoReadRef.current.lastArgs())
if(versionsStatus === 'failed')
fetchVersions(...versionsReadRef.current.lastArgs())
}

// A newly chosen repository gets the default version. A saved project
// passes its own version and keeps it (OpenConceptLab/ocl_issues#2906).
const fetchVersions = (url, savedVersion) => {
const request = ++versionsRequestRef.current
APIService.new().overrideURL(dropVersion(url)).appendToUrl('versions/?verbose=true').get().then(response => {
if(request !== versionsRequestRef.current || !isMountedRef.current)
const isLatest = versionsReadRef.current.begin(url, savedVersion)
setVersionsStatus('loading')
// Raw, so a rate-limited read settles as failed instead of loading
// forever; the app shows its countdown.
APIService.new().overrideURL(dropVersion(url)).appendToUrl('versions/?verbose=true').get(undefined, undefined, undefined, true).then(response => {
if(!isLatest() || !isMountedRef.current)
return
let _versions = response.data
setVersions(_versions)
onRepoVersionChange(savedVersion === undefined ? getDefaultTargetRepoVersion(_versions) : getSavedTargetRepoVersion(_versions, savedVersion))
const fetchedVersions = getVersionsFromResponse(response)
setVersions(fetchedVersions || [])
setVersionsStatus(fetchedVersions ? null : 'failed')
noteTargetReadThrottle(response)
onRepoVersionChange(savedVersion === undefined ? getDefaultTargetRepoVersion(fetchedVersions) : getSavedTargetRepoVersion(fetchedVersions, savedVersion))
})
}

const onRepoChange = (newRepo) => {
repoReadRef.current.invalidate()
setRepo(newRepo)
setRepoStatus(null)
onRepoVersionChange(false)
if(newRepo?.url) {
fetchVersions(newRepo.url)
} else {
versionsRequestRef.current += 1
versionsReadRef.current.invalidate()
setVersions([])
setVersionsStatus(null)
}
}

Expand Down Expand Up @@ -4197,6 +4255,12 @@ const MapProject = () => {
const fetchAllCandidatesForRow = (algoId, _row, offset=0, _retired, scrollToBottom, _filters, forceReload=false, keepAlert=false) => {
if(loadingMatches)
return
// Matching needs the target repository, which may still be loading or
// may have failed to load (OpenConceptLab/ocl_issues#3067).
if(!repo?.id) {
setAlert({message: t('map_project.target_repository_not_loaded'), severity: 'error'})
return
}
if(!keepAlert)
setAlert(false)
if(isAnyValidColumn()) {
Expand Down Expand Up @@ -6808,6 +6872,9 @@ const MapProject = () => {
promptTemplate,
setPromptTemplate: onPromptTemplateChange,
repoVersion,
targetRepoState: getTargetRepoState(repoVersion, repoStatus, versionsStatus),
onRetryTargetReads: retryTargetReads,
retryTargetReadsWaiting: targetReadsRetryAt > 0,
inAIAssistantGroup,
algosSelected,
runnableAlgos,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -311,7 +311,7 @@ test('the target version and the bridge probe read through the one shared reader
assert.match(source, /readMappedSources,\n/)
// Leaving the project stops the target's read, and a versions answer that
// lands after it starts none.
assert.match(source, /if\(request !== versionsRequestRef\.current \|\| !isMountedRef\.current\)\n\s*return\n\s*let _versions/)
assert.match(source, /appendToUrl\('versions\/\?verbose=true'\)[^\n]*\.then\(response => \{\n\s*if\(!isLatest\(\) \|\| !isMountedRef\.current\)\n\s*return\n/)
assert.match(source, /React\.useEffect\(\(\) => \(\) => stopTargetMappedSourcesRef\.current\(\), \[\]\)/)
// Nothing reads the list around the reader, and a throttled read settles.
assert.equal(source.match(/appendToUrl\('mapped-sources\/'\)/g).length, 1)
Expand Down
42 changes: 42 additions & 0 deletions src/components/map-projects/__tests__/projectTargetRepo.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import {
getTargetRepoVersionBadges,
getTargetRepoVersionFromUrl,
getTargetRepoVersionId,
getTargetRepoState,
getTargetRepoVersionReleaseDate,
getVersionsFromResponse,
hasSelectedTargetRepoVersion,
needsSemanticSearchWarning
} from '../projectTargetRepo.js'
Expand Down Expand Up @@ -253,3 +255,43 @@ test('needsSemanticSearchWarning stays quiet on a version that runs Semantic Sea
test('needsSemanticSearchWarning waits for a version to be chosen', () => {
assert.equal(needsSemanticSearchWarning(false, [SEMANTIC_ALGO]), false)
})

// OpenConceptLab/ocl_issues#3067: the AutoMatch dialog shows the target
// repository loading, loaded or failed.
test('getVersionsFromResponse reads the list from a reply', () => {
assert.deepEqual(getVersionsFromResponse({ data: LOINC_VERSIONS }), LOINC_VERSIONS)
assert.deepEqual(getVersionsFromResponse({ data: [] }), [])
})

test('getVersionsFromResponse gives null for a failed read', () => {
// A 401 resolves with undefined while the session renews.
assert.equal(getVersionsFromResponse(undefined), null)
// A raw read resolves with the error itself, a 429 among them.
assert.equal(getVersionsFromResponse({ message: 'Request failed with status code 429', response: { status: 429, data: {} } }), null)
})

const LOINC_281_URL = { ...LOINC_VERSIONS[0], version_url: '/orgs/Regenstrief/sources/LOINC/2.81/' }

// getTargetRepoState(repoVersion, repoStatus, versionsStatus)
test('getTargetRepoState: loading while either read runs', () => {
assert.equal(getTargetRepoState(false, null, 'loading'), 'loading')
assert.equal(getTargetRepoState(false, 'loading', null), 'loading')
assert.equal(getTargetRepoState(false, 'failed', 'loading'), 'loading')
// A version still set from before the read waits for the new one.
assert.equal(getTargetRepoState(LOINC_281_URL, null, 'loading'), 'loading')
})

test('getTargetRepoState: loaded once both reads are in and a version is chosen', () => {
assert.equal(getTargetRepoState(LOINC_281_URL, null, null), 'loaded')
})

test('getTargetRepoState: failed when either read failed', () => {
assert.equal(getTargetRepoState(false, null, 'failed'), 'failed')
// The repository's read failed, its versions' didn't: Submit still waits.
assert.equal(getTargetRepoState(LOINC_281_URL, 'failed', null), 'failed')
})

test('getTargetRepoState: none chosen and nothing loading', () => {
assert.equal(getTargetRepoState(false, null, null), null)
assert.equal(getTargetRepoState({ id: '2.81' }, null, null), null)
})
Loading
Loading