Skip to content
Open
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
26 changes: 9 additions & 17 deletions src/components/map-projects/MultiAlgoSelector.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import AddRoundedIcon from "@mui/icons-material/AddRounded";
import MatchingIcon from '@mui/icons-material/DeviceHub';
import countBy from 'lodash/countBy'
import omit from 'lodash/omit'
import filter from 'lodash/filter'
import find from 'lodash/find'
import isString from 'lodash/isString'
import orderBy from 'lodash/orderBy'
Expand All @@ -35,6 +34,7 @@ import orderBy from 'lodash/orderBy'
import ConceptIcon from '../concepts/ConceptIcon'
import { OperationsContext } from '../app/LayoutContext'
import { isLikelyCanonicalUrl } from './algorithms'
import { metadataFields, fetchAlgorithmMetadata, conflictingFields } from './customAlgoMetadata.js'
import RepoVersionSearchAutocomplete from '../repos/RepoVersionSearchAutocomplete'
import APIService from '../../services/APIService';
import { needsSessionToken, getTokenFlag, tokenInputValue, removeSavedToken } from '../../services/tokenScope';
Expand Down Expand Up @@ -201,14 +201,9 @@ export default function MultiAlgoSelector({
const updateSelected = (key, patch) => {
const next = normalizedValue.map(v => (v.__key === key ? { ...v, ...patch } : v));
onChange(next);
if((patch.id || patch.name)) {
if(filter(value, patch).length > 0)
setErrors(prev => ({...prev, [key]: {...prev[key], ...patch}}))
else if (patch.id)
setErrors(prev => ({...prev, [key]: {...omit(prev[key], 'id')}}))
else if (patch.name)
setErrors(prev => ({...prev, [key]: {...omit(prev[key], 'name')}}))
}
const conflicts = conflictingFields(normalizedValue, key, patch);
if(Object.keys(conflicts).length > 0)
setErrors(prev => ({...prev, [key]: {...prev[key], ...conflicts}}))
};

// For each selected bridge algo, fetch the source repo's canonical_url from
Expand Down Expand Up @@ -353,9 +348,10 @@ export default function MultiAlgoSelector({
setCustomAlgoState(key, {isLoading: true, requestError: '', requestSuccess: '', tokenRequired: false});

const service = APIService.new();
service.URL = selected.url;

const response = await service.get(token || false, {}, undefined, true);
const response = await fetchAlgorithmMetadata(selected.url, url => {
service.URL = url;
return service.get(token || false, {}, undefined, true);
});
const status = response?.response?.status || response?.status;

if([401, 403].includes(status)) {
Expand Down Expand Up @@ -389,11 +385,7 @@ export default function MultiAlgoSelector({
return;
}

updateSelected(key, {
id: data.ID || data.id || '',
name: data.name || '',
description: data.description || '',
});
updateSelected(key, metadataFields(data, selected));
setCustomAlgoState(key, {
isLoading: false,
tokenRequired: false,
Expand Down
148 changes: 148 additions & 0 deletions src/components/map-projects/__tests__/customAlgoMetadata.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,148 @@
import test from 'node:test'
import assert from 'node:assert/strict'
import { createServer } from 'node:http'
import { metadataFields, fetchAlgorithmMetadata, conflictingFields } from '../customAlgoMetadata.js'

test('an algorithm never conflicts with itself when its own id and name are re-applied', () => {
const items = [{__key: 'a', id: 'icd-agent', name: 'ICD Agent'}]
assert.deepEqual(conflictingFields(items, 'a', {id: 'icd-agent', name: 'ICD Agent', description: ''}), {id: false, name: false})
})

test('id and name conflicts are reported independently against the other algorithms only', () => {
const items = [{__key: 'a', id: 'icd-agent', name: 'ICD Agent'}, {__key: 'b', id: 'other', name: 'ICD Agent'}]
assert.deepEqual(conflictingFields(items, 'a', {id: 'other', name: 'Fresh'}), {id: true, name: false})
assert.deepEqual(conflictingFields(items, 'a', {id: 'fresh', name: 'ICD Agent'}), {id: false, name: true})
})

test('fields absent from the patch are not evaluated', () => {
const items = [{__key: 'a', id: 'x', name: 'X'}, {__key: 'b', id: 'y', name: 'Y'}]
assert.deepEqual(conflictingFields(items, 'a', {description: 'd'}), {})
assert.deepEqual(conflictingFields(items, 'a', {id: 'y'}), {id: true})
})

test('metadata does not replace a canonical URL the user already filled in', () => {
const data = { id: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' }
assert.equal('canonical_url' in metadataFields(data, { canonical_url: 'http://typed.test' }), false)
for (const canonical_url of [undefined, '', ' ']) {
assert.equal(metadataFields(data, { canonical_url }).canonical_url, 'http://example.test/system')
}
})

test('metadata supplies the canonical URL alongside the other form fields', () => {
assert.deepEqual(metadataFields({ ID: 'agent', name: 'Agent', canonical_url: 'http://example.test/system' }), {
id: 'agent', name: 'Agent', description: '', canonical_url: 'http://example.test/system'
})
})

test('missing or invalid canonical URL leaves the existing field untouched', () => {
for (const canonical_url of [undefined, '', 'invalid', null]) {
assert.deepEqual(metadataFields({ id: 'agent', name: 'Agent', canonical_url }), {
id: 'agent', name: 'Agent', description: ''
})
}
})

test('metadata GET tries the configured URL first, then the operation without dollar on failure', async () => {
const urls = []
const result = await fetchAlgorithmMetadata('https://example.test/api/$match?x=$keep', async url => {
urls.push(url)
return urls.length === 1 ? {response: {status: 404}} : {data: {ID: 'x', name: 'X'}}
})
assert.deepEqual(urls, ['https://example.test/api/$match?x=$keep', 'https://example.test/api/match?x=$keep'])
assert.equal(result.data.ID, 'x')
})

test('metadata GET never reaches another document when the configured URL already returns metadata', async () => {
for (const url of ['https://example.test/api/$match/', 'https://example.test/fhir/ConceptMap/$translate']) {
const calls = []
const result = await fetchAlgorithmMetadata(url, async candidate => (
calls.push(candidate) && candidate === url ? {data: {id: 'configured', name: 'Configured'}} : {data: {id: 'translate', name: 'Wrong document'}}
))
assert.deepEqual(calls, [url])
assert.equal(result.data.id, 'configured')
}
})

test('metadata GET requests a URL without an operation marker only once', async () => {
const calls = []
await fetchAlgorithmMetadata('https://example.test/api/match', async candidate => { calls.push(candidate); return {response: {status: 404}} })
assert.deepEqual(calls, ['https://example.test/api/match'])
})

test('metadata GET moves on when the configured URL does not return usable metadata', async () => {
const calls = []
const result = await fetchAlgorithmMetadata('https://example.test/$match', async url => {
calls.push(url)
return calls.length === 1 ? {data: {message: 'not metadata'}} : {data: {id: 'x', name: 'X'}}
})
assert.deepEqual(calls, ['https://example.test/$match', 'https://example.test/match'])
assert.equal(result.data.id, 'x')
})

test('metadata GET falls back to the parent endpoint after both operation URLs fail', async () => {
const calls = []
const result = await fetchAlgorithmMetadata('https://example.test/api/ciel-bridge-rxnorm/$match?lang=en', async url => {
calls.push(url)
return calls.length < 3 ? {response: {status: 404}} : {data: {ID: 'x', name: 'X'}}
})
assert.deepEqual(calls, [
'https://example.test/api/ciel-bridge-rxnorm/$match?lang=en',
'https://example.test/api/ciel-bridge-rxnorm/match?lang=en',
'https://example.test/api/ciel-bridge-rxnorm?lang=en',
])
assert.equal(result.data.ID, 'x')
})

test('metadata GET retains an authentication failure if the alternate is missing', async () => {
const result = await fetchAlgorithmMetadata('https://example.test/$match', async url => (
{response: {status: url.includes('$') ? 404 : 401}}
))
assert.equal(result.response.status, 401)
})

test('parent fallback keeps the first authentication error if all three attempts fail', async () => {
const calls = []
const result = await fetchAlgorithmMetadata('https://example.test/api/$match/', async url => {
calls.push(url)
return {response: {status: calls.length === 2 ? 403 : 404}}
})
assert.deepEqual(calls, ['https://example.test/api/$match/', 'https://example.test/api/match/', 'https://example.test/api'])
assert.equal(result.response.status, 403)
})

test('metadata fallback performs real GET requests against a local server', async t => {
const requests = []
const server = createServer((req, res) => {
requests.push([req.method, req.url, req.headers.authorization])
res.setHeader('Content-Type', 'application/json')
if(req.url === '/$match') res.end(JSON.stringify({ID: 'x', name: 'X', canonical_url: 'https://example.test/system'}))
else { res.statusCode = 404; res.end('{}') }
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
t.after(() => new Promise(resolve => server.close(resolve)))
const url = `http://127.0.0.1:${server.address().port}/$match`
const response = await fetchAlgorithmMetadata(url, async candidate => {
const result = await fetch(candidate, {headers: {Authorization: 'Token test'}})
return result.ok ? {data: await result.json()} : {response: {status: result.status}}
})
assert.deepEqual(requests, [['GET', '/$match', 'Token test']])
assert.equal(metadataFields(response.data).canonical_url, 'https://example.test/system')
})

test('parent fallback obtains metadata through real HTTP after two 404 responses', async t => {
const requests = []
const server = createServer((req, res) => {
requests.push(req.url)
res.setHeader('Content-Type', 'application/json')
if(req.url === '/api/algorithm') res.end(JSON.stringify({ID: 'x', name: 'X'}))
else { res.statusCode = 404; res.end('{}') }
})
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
t.after(() => new Promise(resolve => server.close(resolve)))
const result = await fetchAlgorithmMetadata(`http://127.0.0.1:${server.address().port}/api/algorithm/$match`, async url => {
const response = await fetch(url)
return response.ok ? {data: await response.json()} : {response: {status: response.status}}
})
assert.deepEqual(requests, ['/api/algorithm/$match', '/api/algorithm/match', '/api/algorithm'])
assert.equal(result.data.ID, 'x')
})
9 changes: 2 additions & 7 deletions src/components/map-projects/algorithms.jsx
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import React from 'react'
import MatchingIcon from '@mui/icons-material/DeviceHub';
import { isLikelyCanonicalUrl } from './customAlgoMetadata.js'

// Canonical concept-identity config per algorithm type
// (plans/unified-mapper-model.md). Single source of truth shared between
Expand Down Expand Up @@ -47,13 +48,7 @@ export const CONCEPT_IDENTITY_BY_TYPE = {
}
}

// Cheap structural validator for canonical URLs. The unified mapper model
// requires every algorithm's concept_identity.canonical_url to be a URL —
// custom algos rely on user input for this, so the form validates here.
export const isLikelyCanonicalUrl = (value) => {
if(!value || typeof value !== 'string') return false
return /^https?:\/\/[^\s]+$/i.test(value.trim())
}
export { isLikelyCanonicalUrl }

// Walk algosSelected and return the subset that fails project-config
// validation. Currently: custom algos must have a valid canonical_url.
Expand Down
48 changes: 48 additions & 0 deletions src/components/map-projects/customAlgoMetadata.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
// Cheap structural validator for canonical URLs. The unified mapper model requires every
// algorithm's concept_identity.canonical_url to be a URL, and custom algorithms rely on user
// input or on the metadata below for it, so the form validates here.
export const isLikelyCanonicalUrl = value => {
if(!value || typeof value !== 'string') return false
return /^https?:\/\/[^\s]+$/i.test(value.trim())
}

// Omit an absent or invalid canonical, and never replace one the user already filled in.
export const metadataFields = (data, current = {}) => ({
id: data.ID || data.id || '',
name: data.name || '',
description: data.description || '',
...(isLikelyCanonicalUrl(data.canonical_url) && !current.canonical_url?.trim() ? { canonical_url: data.canonical_url.trim() } : {}),
})

const isMetadata = response => {
const data = response?.data || response
return !response?.response && Boolean(data?.name && (data?.ID || data?.id))
}

// The configured URL is authoritative: request it first, then the operation without $
// (`/$match` -> `/match`), then the parent path. Candidates that collapse to the same URL
// (no `$` marker) are requested once.
export const fetchAlgorithmMetadata = async (url, get) => {
const [path] = url.split(/[?#]/, 1)
const suffix = url.slice(path.length)
const candidates = [...new Set([
url,
path.replace(/\/\$([^/]+)(\/?)$/, '/$1$2') + suffix,
path.replace(/\/\$[^/]+\/?$/, '') + suffix,
])]
const responses = []
for(const candidate of candidates) {
const response = await get(candidate)
if(isMetadata(response)) return response
responses.push(response)
}
return responses.find(response => [401, 403].includes(response?.response?.status || response?.status)) || responses[responses.length - 1]
}

// Whether the patched id/name collide with ANOTHER algorithm (the one being edited is excluded by key).
export const conflictingFields = (items, key, patch) => {
const others = (items || []).filter(item => item.__key !== key)
return Object.fromEntries(['id', 'name']
.filter(field => patch[field])
.map(field => [field, others.some(item => item[field] === patch[field])]))
}
Loading