diff --git a/.changeset/wes-run-requests.md b/.changeset/wes-run-requests.md new file mode 100644 index 00000000..fad17547 --- /dev/null +++ b/.changeset/wes-run-requests.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/wes": minor +--- + +Build WES run requests from GA4GH IO Schemas: `ecc-client-ga4gh-wes-run-create` gains a schema mode (`ioSchema`, `trsToolVersion`, `engineProfile`, `allowedSchemes`) that shows the workflow's input form and submits the request built by the profile's engine bindings; the raw mode stays. `@elixir-cloud/wes/utils` exports the builder (`toWorkflowParams`, `buildRunRequest`), TRS helpers (`trsDescriptorUrl`, `findSchemaFile`, `findPrimaryDescriptorPath`, `unsupportedBy`) and `conquestEngineProfile`. diff --git a/apps/documentation/components/packages/wes/RunCreateSchemaPreview.tsx b/apps/documentation/components/packages/wes/RunCreateSchemaPreview.tsx new file mode 100644 index 00000000..e16bda5b --- /dev/null +++ b/apps/documentation/components/packages/wes/RunCreateSchemaPreview.tsx @@ -0,0 +1,102 @@ +import React, { useMemo, useState } from 'react'; +import { ECCClientGa4ghWesRunCreate } from '@elixir-cloud/wes/react'; +import type { RunRequest, WesProvider } from '@elixir-cloud/wes/providers'; +import PreviewLayout from '@/components/common/PreviewLayout'; +import { ioFormExamples } from '@/components/packages/wes/ioFormExamples'; + +const allowedSchemes = ['drs', 'https', 's3']; + +/** A TRS tool version for each example (made up, nothing is fetched). */ +const trsToolVersion = (example: string) => ({ + trsUrl: 'https://trs.example.org/ga4gh/trs/v2', + toolId: example, + versionId: '1.0.0', + descriptorTypeVersions: ['DSL2', '8', 'v1.2', '1.1'], +}); + +/** + * A provider that runs nothing: it says that it runs every workflow type + * and shows the request that the component would submit. + */ +class DryRunProvider implements WesProvider { + private show: (request: RunRequest) => void; + + constructor(show: (request: RunRequest) => void) { + this.show = show; + } + + async getServiceInfo() { + const all = { workflow_type_version: [] as string[] }; + return { + workflow_type_versions: { NFL: all, SMK: all, WDL: all, CWL: all }, + supported_wes_versions: ['1.1.0'], + supported_filesystem_protocols: allowedSchemes, + workflow_engine_versions: {}, + default_workflow_engine_parameters: [], + system_state_counts: {}, + }; + } + + async runWorkflow(request: RunRequest) { + this.show(request); + return { run_id: 'dry-run' }; + } + + async listRuns() { + return { runs: [] }; + } + + async getRunLog(): Promise { + throw new Error('A dry run has no runs.'); + } + + async getRunStatus(): Promise { + throw new Error('A dry run has no runs.'); + } + + async cancelRun(): Promise { + throw new Error('A dry run has no runs.'); + } +} + +export default function RunCreateSchemaPreview() { + const [example, setExample] = useState('greetings-nextflow'); + const [request, setRequest] = useState(null); + const provider = useMemo(() => new DryRunProvider(setRequest), []); + + return ( + +
+ + + {request && ( +
+            {JSON.stringify(request, null, 2)}
+          
+ )} +
+
+ ); +} diff --git a/apps/documentation/pages/docs/wes/components/run-create.mdx b/apps/documentation/pages/docs/wes/components/run-create.mdx index 2b41c308..f84a9e0d 100644 --- a/apps/documentation/pages/docs/wes/components/run-create.mdx +++ b/apps/documentation/pages/docs/wes/components/run-create.mdx @@ -1,6 +1,7 @@ import { Tabs } from 'nextra/components' import ComponentName from '@/components/common/ComponentName' import RunCreatePreview from '@/components/packages/wes/RunCreatePreview' +import RunCreateSchemaPreview from '@/components/packages/wes/RunCreateSchemaPreview' # EccClientGa4ghWesRunCreate Component @@ -12,7 +13,10 @@ import RunCreatePreview from '@/components/packages/wes/RunCreatePreview' ## Overview -The `ecc-client-ga4gh-wes-run-create` component provides a form for submitting new workflow runs to a WES endpoint. +The `ecc-client-ga4gh-wes-run-create` component provides a form for submitting new workflow runs to a WES endpoint. It has two modes: + +- **Raw mode** (default): the user enters the workflow URL, type, version and `workflow_params` as JSON. +- **Schema mode** (with `ioSchema` and `trsToolVersion`): the user fills in the input form of the workflow's [I/O Schema](/docs/wes/io-schema) instead, and the component builds the run request from the schema, the values and the TRS tool version (see [Run requests](/docs/wes/io-schema#run-requests)). ## Usage @@ -71,11 +75,63 @@ This example shows the basic form for creating a new workflow run. +### Schema mode + +With an IO schema and the TRS tool version to run, the form shows the workflow's inputs ([`ecc-client-ga4gh-wes-io-form`](./io-form)) instead of the raw fields, and the workflow that will run: its type and language version (from the schema's `x-ga4gh-workflow`, else the first version of the TRS tool version that the service runs, else the first version of the TRS tool version) and the workflow URL (the plain primary descriptor in TRS). It says when the WES service doesn't run the workflow's type or version (from its `service-info`), and submits only valid values. + +On submit, the values are translated into `workflow_params` by the profile's engine binding for the descriptor type (`NFL`, `SMK`, `WDL`, `CWL`); values that the binding refuses (e.g. a file reference with a scheme that isn't allowed) are shown as `: `, and `ecc-run-create-failed` is fired with that text. The engine parameters, tags and attachments of the advanced section are added. An `engineProfile` then adapts the request to a particular WES server. + +This preview uses a provider that submits nothing and shows the request instead: + + + + + + + + ```tsx showLineNumbers copy filename="run-create-schema.tsx" + import React from 'react'; + import { ECCClientGa4ghWesRunCreate } from '@elixir-cloud/wes/react'; + import { RestWesProvider } from '@elixir-cloud/wes/providers'; + + export default function RunCreateSchema({ schema }: { schema: object }) { + const provider = new RestWesProvider( + 'https://wes.example.com/ga4gh/wes/v1' + ); + + return ( + + ); + } + ``` + + + +#### Engine profiles + +Some WES servers need more than the profile's binding gives. An engine profile (`EngineProfile` from `@elixir-cloud/wes/utils`) takes the built request and returns the request for one server; it is kept out of the generic builder. The package has one: + +- `conquestEngineProfile`: [Conquest](https://github.com/elixir-cloud-aai/conquest) runs workflows from public GitHub repositories at a full commit SHA. The profile sets `workflow_url` to the repository and adds the engine parameters `revision` and the path of the main workflow file (`main_script` for Nextflow, `snakefile` for Snakemake, `main_workflow_path` for WDL), all taken from `trsToolVersion.primaryDescriptorUrl`: the `url` of the TRS descriptor, a `raw.githubusercontent.com` or `github.com/.../blob/...` URL at a commit. It refuses CWL, branches and tags. + ## Properties -| Property | Type | Default | Description | -|------------|---------------------------|---------|--------------------------------------------------------------------------------| -| `provider` | `WesProvider` | `null` | Data provider for submitting the run (see [Providers](/docs/wes/providers)) | +| Property | Type | Default | Description | +|------------------|---------------------|--------------------|-------------| +| `provider` | `WesProvider` | `null` | Data provider for submitting the run (see [Providers](/docs/wes/providers)) | +| `ioSchema` | `object` | `undefined` | An IO schema (GA4GH IO Schema Profile 0.3.0); switches to schema mode | +| `trsToolVersion` | `TrsToolVersionRef` | `undefined` | The TRS tool version to run in schema mode: `trsUrl`, `toolId`, `versionId`, and optionally `primaryDescriptorPath` (as TRS lists it; else the schema's `primary_descriptor_path`), `descriptorTypeVersions` (of the tool version) and `primaryDescriptorUrl` (for engine profiles) | +| `engineProfile` | `EngineProfile` | `undefined` | Adapts the built request to a WES server, e.g. `conquestEngineProfile` | +| `allowedSchemes` | `string[]` | `['drs', 'https']` | URI schemes that file references may have in schema mode, in the I/O form and in the built request | ## Events diff --git a/apps/documentation/pages/docs/wes/io-schema.mdx b/apps/documentation/pages/docs/wes/io-schema.mdx index 7fe284a5..3751d89a 100644 --- a/apps/documentation/pages/docs/wes/io-schema.mdx +++ b/apps/documentation/pages/docs/wes/io-schema.mdx @@ -6,7 +6,7 @@ The WES components understand the [GA4GH IO Schema Profile](https://github.com/e ## Profile version -The package supports version **0.3.0** of the profile, pinned at commit [`2c3dc49`](https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3). Its meta-schema and vocabularies are bundled with the package; `scripts/sync-io-schema.mjs` in the package copies them, the conformance suite and the example schemas from a checkout of the profile's repository at the pinned commit. +The package supports version **0.3.0** of the profile, pinned at commit [`2c3dc49`](https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3). Its meta-schema and vocabularies are bundled with the package; `scripts/sync-io-schema.mjs` in the package copies them, the conformance suite, the test vectors and the example schemas from a checkout of the profile's repository at the pinned commit. ## Checks @@ -51,6 +51,30 @@ JSON Schema can't check the values of file references (`x-ga4gh-file`), so the c Outputs must be absolute URIs. The checks pass the profile's test vectors for file reference values (`tests/vectors/file-values`). +## Run requests + +`@elixir-cloud/wes/utils` builds WES run requests from input values by the profile's [engine bindings](https://ga4gh-io-schema.readthedocs.io/en/latest/specification/engine-bindings/), which [`ecc-client-ga4gh-wes-run-create`](./components/run-create#schema-mode) uses in schema mode: + +```typescript +import { + buildRunRequest, + findPrimaryDescriptorPath, + trsDescriptorUrl, +} from '@elixir-cloud/wes/utils'; + +const request = await buildRunRequest(schema, values, { + workflowUrl: trsDescriptorUrl(trsUrl, toolId, versionId, 'NFL', findPrimaryDescriptorPath(files)), + binding: { descriptorTypeVersion: 'DSL2' }, // only if the schema has none +}); +``` + +- `toWorkflowParams()` checks the schema, validates the values against `inputs`, checks every file reference value, and translates the values for the descriptor type: unqualified names for `NFL` and `SMK`, names qualified with the entry point for `WDL`, `File` and `Directory` objects for CWL file values. Inputs are renamed by `x-ga4gh-parameter`; defaults of the schema are never inserted. Values that Nextflow or the CWL loader would change (`${`, keys with `-` for Nextflow; `File` objects, keys with `$` or `:` for CWL) are refused. Errors are `TranslationError`s with the JSON Pointer of the value. +- `buildRunRequest()` adds `workflow_type`, `workflow_type_version` and `workflow_url` (for CWL, with the entry point as its fragment). Tags and engine parameters are left to the caller and to [engine profiles](./components/run-create#engine-profiles). +- `trsDescriptorUrl()`, `findPrimaryDescriptorPath()` and `findSchemaFile()` give the workflow URL of a TRS tool version and find its IO schema among its files. +- `unsupportedBy()` says whether a WES service runs a binding's type and version, by its `service-info`. + +The translation passes the profile's test vectors (`tests/vectors/wes-params`, `workflow-urls` and `trs-files`). It needs a validator that can check subschemas (`validateAt` of the check result), and refuses schemas that it can't follow: references that don't resolve within the document, references and branches inside embedded `$id` resources, and `$dynamicRef`. GALAXY workflows have no binding in profile 0.3.0. + ## Descriptions Titles, descriptions and `enum` values of IO schemas are always shown as text, never as markup. diff --git a/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs b/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs index 9f2bafe1..c600edfc 100644 --- a/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs +++ b/packages/ecc-client-ga4gh-wes/scripts/sync-io-schema.mjs @@ -7,8 +7,8 @@ * - `src/io-schema/profile.ts`: the meta-schema and its vocabularies, with * the commit and the version of the profile; * - `src/io-schema/tests/fixtures/*.ts`: the conformance suite, the test - * vectors of file reference values and the example schemas, for the tests - * and the demos. + * vectors (file reference values, engine bindings, workflow URLs and TRS + * files) and the example schemas, for the tests and the demos. * * Usage, from the package directory: * @@ -125,6 +125,88 @@ export const FILE_VALUE_CASES: FileValueCase[] = ${json( ` ); +/** + * The cases of `tests/vectors////`, each with + * its JSON files by name (without `.json`), sorted by type and name. + */ +const caseDirectories = (kind) => { + const directories = (...parts) => + readdirSync(path.join(checkout, "tests", "vectors", kind, ...parts), { + withFileTypes: true, + }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort(); + return directories().flatMap((descriptorType) => + directories(descriptorType).map((name) => { + const files = {}; + const at = ["tests", "vectors", kind, descriptorType, name]; + for (const file of readdirSync(path.join(checkout, ...at)) + .filter((entry) => entry.endsWith(".json")) + .sort()) { + files[file.replace(/\.json$/, "")] = readJson(...at, file); + } + return { descriptorType, name, ...files }; + }) + ); +}; + +write( + "src/io-schema/tests/fixtures/wes-params.ts", + `${header( + "Test vectors of the engine bindings (`tests/vectors/wes-params/`)." + )} +export interface WesParamsCase { + descriptorType: string; + name: string; + schema: Record; + values: unknown; + /** The expected \`workflow_params\`, or else \`error\` */ + workflow_params?: Record; + error?: { pointer: string }; + options?: { allowedSchemes?: string[]; allowAbsolutePaths?: boolean }; +} + +export const WES_PARAMS_CASES: WesParamsCase[] = ${json( + caseDirectories("wes-params") + )}; +` +); + +write( + "src/io-schema/tests/fixtures/trs.ts", + `${header( + "Test vectors of workflow URLs and TRS files (`tests/vectors/workflow-urls/`, `tests/vectors/trs-files/`)." + )} +export interface WorkflowUrlCase { + name: string; + trsUrl: string; + toolId: string; + versionId: string; + descriptorType: string; + primaryDescriptorPath?: string; + workflowUrl?: string; + error?: boolean; + imports?: { reference: string; url: string }[]; +} + +export interface TrsFilesCase { + name: string; + files: unknown; + schemaFile: { path: string; file_type: string } | null; + primaryDescriptorPath?: string | null; +} + +export const WORKFLOW_URL_CASES: WorkflowUrlCase[] = ${json( + readJson("tests", "vectors", "workflow-urls", "cases.json") + )}; + +export const TRS_FILES_CASES: TrsFilesCase[] = ${json( + readJson("tests", "vectors", "trs-files", "cases.json") + )}; +` +); + const examples = { example_tool: readJson("tests", "data", "example_tool.schema.json"), example_wdl: readJson("tests", "data", "example_wdl.schema.json"), diff --git a/packages/ecc-client-ga4gh-wes/src/components/run-create/run-create.ts b/packages/ecc-client-ga4gh-wes/src/components/run-create/run-create.ts index de33107c..931cf738 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/run-create/run-create.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/run-create/run-create.ts @@ -1,5 +1,6 @@ import { LitElement, html, css } from "lit"; import { property, state } from "lit/decorators.js"; +import { keyed } from "lit/directives/keyed.js"; import { GlobalStyles } from "../../global.js"; import { ComponentStyles as TailwindStyles } from "./tw-styles.js"; import { @@ -9,6 +10,17 @@ import { WorkflowType, } from "../../providers/wes-provider.js"; import { RestWesProvider } from "../../providers/rest-wes-provider.js"; +import { + buildRunRequest, + getBinding, + TranslationError, + unsupportedBy, +} from "../../io-schema/bindings.js"; +import type { EngineBinding } from "../../io-schema/bindings.js"; +import type { EngineProfile } from "../../io-schema/engine-profiles.js"; +import { trsDescriptorUrl } from "../../io-schema/trs.js"; +import { DEFAULT_ALLOWED_SCHEMES } from "../../io-schema/files.js"; +import type { IoFormChange } from "../io-form/io-form.js"; import "@elixir-cloud/design/components/button/index.js"; import "@elixir-cloud/design/components/input/index.js"; import "@elixir-cloud/design/components/select/index.js"; @@ -18,6 +30,33 @@ import "@elixir-cloud/design/components/separator/index.js"; import "@elixir-cloud/design/components/collapsible/index.js"; import "@elixir-cloud/design/components/code/index.js"; +/** + * The TRS tool version that a run in schema mode runs: where the workflow + * URL and, if the IO schema has none, the descriptor type version come + * from. + */ +export interface TrsToolVersionRef { + /** Base URL of the TRS API, e.g. `https://trs.example.org/ga4gh/trs/v2` */ + trsUrl: string; + /** `Tool.id` */ + toolId: string; + /** `ToolVersion.id` */ + versionId: string; + /** + * Path of the primary descriptor as TRS lists it (see + * `findPrimaryDescriptorPath`); else `primary_descriptor_path` of the + * schema's `x-ga4gh-workflow`; without either, the URL has no path + */ + primaryDescriptorPath?: string | null; + /** `descriptor_type_version` values of the tool version for the type */ + descriptorTypeVersions?: string[]; + /** + * URL of the primary descriptor at its source (the TRS descriptor's + * `url`), for engine profiles that fetch from there + */ + primaryDescriptorUrl?: string; +} + /** * @summary Component for submitting workflow runs to a WES service * @since 0.1.0 @@ -27,6 +66,16 @@ import "@elixir-cloud/design/components/code/index.js"; * @property {string} defaultWorkflowType - Default workflow type (CWL, WDL, etc.) * @property {boolean} allowFileUpload - Whether to allow file uploads for workflow attachments * @property {WesProvider} provider - Custom data provider (optional, overrides baseUrl) + * @property {object} ioSchema - An IO schema (GA4GH IO Schema Profile + * 0.3.0). With it, the run is created in schema mode: an input form from + * the schema instead of the workflow URL, type, version and parameters, + * which are built from the schema, the values and `trsToolVersion`. + * @property {TrsToolVersionRef} trsToolVersion - The TRS tool version to + * run in schema mode. + * @property {EngineProfile} engineProfile - Changes the built request for + * a particular WES server (e.g. `conquestEngineProfile`); optional. + * @property {string[]} allowedSchemes - URI schemes that file references + * may have in schema mode; default `drs https`. * * @fires ecc-run-submitted - Fired when a workflow run is successfully submitted * @fires ecc-run-create-failed - Fired when run creation fails @@ -66,6 +115,12 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { @property({ type: Boolean, reflect: true }) allowFileUpload = true; @property({ attribute: false }) provider?: WesProvider; + @property({ attribute: false }) ioSchema?: unknown; + @property({ attribute: false }) trsToolVersion?: TrsToolVersionRef; + @property({ attribute: false }) engineProfile?: EngineProfile; + @property({ attribute: false }) allowedSchemes: string[] = [ + ...DEFAULT_ALLOWED_SCHEMES, + ]; @state() private serviceInfo: ServiceInfo | null = null; @state() private loading = false; @@ -73,6 +128,8 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { @state() private error: string | null = null; @state() private success: string | null = null; @state() private attachedFiles: File[] = []; + @state() private ioChange: IoFormChange | null = null; + @state() private ioFormKey = 0; @state() private tags: { key: string; value: string }[] = [ { key: "", value: "" }, ]; @@ -113,6 +170,20 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { } protected updated(changedProperties: Map): void { + if ( + changedProperties.has("ioSchema") && + this.ioSchema && + !customElements.get("ecc-client-ga4gh-wes-io-form") + ) { + // Loaded on demand, not imported statically: a static import makes + // the docs app's server-side prerendering of the I/O form page fail + // (Lit SSR, "this._$EM is not a function") + import("../io-form/index.js").catch((err) => { + this.error = `The input form couldn't be loaded: ${ + err instanceof Error ? err.message : String(err) + }`; + }); + } if (changedProperties.has("baseUrl") && this.baseUrl && !this.provider) { this._provider = new RestWesProvider(this.baseUrl); this.loadServiceInfo(); @@ -184,6 +255,72 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { } } + /** + * In schema mode, the binding (type, version, entry point) and the + * workflow URL, or why the run can't be created. + */ + private schemaRun(): + | { binding: EngineBinding; workflowUrl: string; error: null } + | { error: string } { + const trs = this.trsToolVersion; + if (!trs) { + return { + error: + "Schema mode needs the TRS tool version to run (trsToolVersion).", + }; + } + let binding: EngineBinding; + try { + binding = getBinding(this.ioSchema); + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } + if (binding.descriptorTypeVersion === undefined) { + const offered = trs.descriptorTypeVersions ?? []; + const supported = + this.serviceInfo?.workflow_type_versions?.[binding.descriptorType] + ?.workflow_type_version ?? []; + const version = + offered.find((candidate) => supported.includes(candidate)) ?? + offered[0]; + if (version === undefined) { + return { + error: + "The workflow's language version is unknown: neither the IO schema nor the TRS tool version names one.", + }; + } + binding = { ...binding, descriptorTypeVersion: version }; + } + if (this.serviceInfo) { + const unsupported = unsupportedBy(this.serviceInfo, binding); + if (unsupported) return { error: unsupported }; + } + const block = (this.ioSchema as Record)[ + "x-ga4gh-workflow" + ] as Record; + const declaredPath = + typeof block.primary_descriptor_path === "string" + ? block.primary_descriptor_path + : undefined; + try { + const workflowUrl = trsDescriptorUrl( + trs.trsUrl, + trs.toolId, + trs.versionId, + binding.descriptorType, + trs.primaryDescriptorPath ?? declaredPath + ); + return { binding, workflowUrl, error: null }; + } catch (err) { + return { error: err instanceof Error ? err.message : String(err) }; + } + } + + private handleIoFormChange(e: CustomEvent): void { + e.stopPropagation(); + this.ioChange = e.detail; + } + public handleInputChange( field: keyof typeof this.formData, value: string @@ -343,13 +480,67 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { return null; } + /** Why the run can't be submitted in schema mode, or `null`. */ + private validateSchemaForm(): string | null { + const run = this.schemaRun(); + if (run.error !== null) return run.error; + if (!this.ioChange?.valid) { + return "Some inputs are missing or not valid."; + } + try { + const parameters = JSON.parse(this.formData.workflowEngineParams); + if ( + typeof parameters !== "object" || + parameters === null || + Array.isArray(parameters) + ) { + return "Workflow engine parameters must be a JSON object"; + } + } catch { + return "Workflow engine parameters must be valid JSON"; + } + return null; + } + + /** + * Builds the run request of schema mode: the profile's engine binding, + * then the engine profile, if any, over the user's engine parameters. + */ + private async buildSchemaRequest( + engineParameters: Record + ): Promise { + const run = this.schemaRun(); + if (run.error !== null) throw new Error(run.error); + const built = await buildRunRequest( + this.ioSchema, + this.ioChange?.values ?? {}, + { + workflowUrl: run.workflowUrl, + binding: run.binding, + allowedSchemes: this.allowedSchemes, + } + ); + const request: RunRequest = { + ...built, + workflow_engine_parameters: engineParameters, + }; + return this.engineProfile + ? this.engineProfile.apply(request, { + descriptorType: run.binding.descriptorType, + primaryDescriptorUrl: this.trsToolVersion?.primaryDescriptorUrl, + }) + : request; + } + private async handleSubmit(): Promise { if (!this._provider) { this.error = "No provider available"; return; } - const validationError = this.validateForm(); + const validationError = this.ioSchema + ? this.validateSchemaForm() + : this.validateForm(); if (validationError) { this.error = validationError; return; @@ -368,14 +559,18 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { } } + const engineParameters = JSON.parse(this.formData.workflowEngineParams); + const base: RunRequest = this.ioSchema + ? await this.buildSchemaRequest(engineParameters) + : { + workflow_url: this.formData.workflowUrl.trim(), + workflow_type: this.formData.workflowType, + workflow_type_version: this.formData.workflowTypeVersion, + workflow_params: JSON.parse(this.formData.workflowParams), + workflow_engine_parameters: engineParameters, + }; const runRequest: RunRequest = { - workflow_url: this.formData.workflowUrl.trim(), - workflow_type: this.formData.workflowType, - workflow_type_version: this.formData.workflowTypeVersion, - workflow_params: JSON.parse(this.formData.workflowParams), - workflow_engine_parameters: JSON.parse( - this.formData.workflowEngineParams - ), + ...base, tags: Object.keys(tagsObject).length > 0 ? tagsObject : undefined, workflow_attachment: this.attachedFiles.length > 0 ? this.attachedFiles : undefined, @@ -400,8 +595,12 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { // Reset form this.resetForm(); } catch (err) { - this.error = - err instanceof Error ? err.message : "Failed to submit workflow"; + if (err instanceof TranslationError) { + this.error = `${err.pointer || "/"}: ${err.message}`; + } else { + this.error = + err instanceof Error ? err.message : "Failed to submit workflow"; + } console.error("Failed to submit workflow:", err); // Emit error event @@ -434,10 +633,47 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { }; this.tags = [{ key: "", value: "" }]; this.attachedFiles = []; + this.ioChange = null; + this.ioFormKey += 1; this.error = null; this.success = null; } + private renderSchemaFields() { + const run = this.schemaRun(); + return html` +
+ ${run.error === null + ? html` +
+
+
Workflow
+
+ ${run.binding.descriptorType} + ${run.binding.descriptorTypeVersion} +
+
+
+
URL
+
+ ${run.workflowUrl} +
+
+
+ ` + : html``} + ${keyed( + this.ioFormKey, + html`` + )} +
+ `; + } + private renderBasicFields() { return html`
@@ -744,7 +980,10 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { }} >
- ${this.renderBasicFields()} ${this.renderAdvancedFields()} + ${this.ioSchema + ? this.renderSchemaFields() + : this.renderBasicFields()} + ${this.renderAdvancedFields()}
@@ -777,9 +1016,11 @@ export class ECCClientGa4ghWesRunCreate extends LitElement { @click=${this.handleSubmit} ?disabled=${this.submitting || this.loading || - !this.formData.workflowUrl || - !this.formData.workflowType || - !this.formData.workflowTypeVersion} + (this.ioSchema + ? this.schemaRun().error !== null || !this.ioChange?.valid + : !this.formData.workflowUrl || + !this.formData.workflowType || + !this.formData.workflowTypeVersion)} > ${this.submitting ? "Submitting..." : "Submit Run"} diff --git a/packages/ecc-client-ga4gh-wes/src/components/run-create/tests/run-create.test.ts b/packages/ecc-client-ga4gh-wes/src/components/run-create/tests/run-create.test.ts new file mode 100644 index 00000000..7521b0a1 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/components/run-create/tests/run-create.test.ts @@ -0,0 +1,266 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect, fixture, html, oneEvent, waitUntil } from "@open-wc/testing"; +import "../index.js"; +import type { ECCClientGa4ghWesRunCreate } from "../run-create.js"; +import type { + RunRequest, + ServiceInfo, + WesProvider, +} from "../../../providers/wes-provider.js"; +import { PROFILE_ID } from "../../../io-schema/validator.js"; +import { conquestEngineProfile } from "../../../io-schema/engine-profiles.js"; + +const SHA = "3c2cdc9823c2b4636e5e3e73e223878099ff5dc9"; + +const SCHEMA = { + $schema: PROFILE_ID, + "x-ga4gh-workflow": { descriptor_type: "NFL" }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + title: "Reads", + "x-ga4gh-file": { kind: "file" }, + }, + threads: { type: "integer", minimum: 1, default: 2 }, + }, + required: ["reads"], + }, + }, +}; + +const TRS = { + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + primaryDescriptorPath: "main.nf", + descriptorTypeVersions: ["DSL1", "DSL2"], + primaryDescriptorUrl: `https://raw.githubusercontent.com/org/repo/${SHA}/main.nf`, +}; + +/** A provider that records submitted requests. */ +class FakeProvider implements WesProvider { + submitted: RunRequest[] = []; + + private types: ServiceInfo["workflow_type_versions"]; + + constructor(types: ServiceInfo["workflow_type_versions"]) { + this.types = types; + } + + async getServiceInfo() { + return { + workflow_type_versions: this.types, + supported_wes_versions: ["1.1.0"], + supported_filesystem_protocols: ["https"], + workflow_engine_versions: {}, + default_workflow_engine_parameters: [], + system_state_counts: {}, + } as ServiceInfo; + } + + async runWorkflow(request: RunRequest) { + this.submitted.push(request); + return { run_id: "run-1" }; + } + + // eslint-disable-next-line class-methods-use-this + async listRuns() { + return { runs: [] }; + } + + // eslint-disable-next-line class-methods-use-this + async getRunLog(): Promise { + throw new Error("not used"); + } + + // eslint-disable-next-line class-methods-use-this + async getRunStatus(): Promise { + throw new Error("not used"); + } + + // eslint-disable-next-line class-methods-use-this + async cancelRun(): Promise { + throw new Error("not used"); + } +} + +const NFL_ONLY = { NFL: { workflow_type_version: ["DSL2"] } }; + +const root = (el: Element) => el.shadowRoot as ShadowRoot; + +const ioForm = (el: ECCClientGa4ghWesRunCreate) => + root(el).querySelector("ecc-client-ga4gh-wes-io-form"); + +/** Sets the values as if the user had entered them in the I/O form. */ +const enter = async ( + el: ECCClientGa4ghWesRunCreate, + values: Record, + valid = true +) => { + ioForm(el)?.dispatchEvent( + new CustomEvent("ecc-io-form-changed", { + detail: { values, valid, errors: [] }, + bubbles: true, + composed: true, + }) + ); + await el.updateComplete; +}; + +const submitButton = (el: ECCClientGa4ghWesRunCreate) => + root(el).querySelector( + 'ecc-utils-design-button[type="submit"]' + ) as HTMLElement & { disabled: boolean }; + +const render = async ( + provider: WesProvider, + extra: Partial = {} +) => { + const el = await fixture( + html`` + ); + await waitUntil(() => ioForm(el), "no I/O form", { timeout: 5000 }); + await el.updateComplete; + return el; +}; + +describe("ecc-client-ga4gh-wes-run-create", () => { + describe("raw mode", () => { + it("shows the raw fields without a schema", async () => { + const el = await fixture( + html`` + ); + await el.updateComplete; + expect(root(el).querySelector("#workflow-url")).to.not.equal(null); + expect(ioForm(el)).to.equal(null); + }); + }); + + describe("schema mode", () => { + it("shows the I/O form and the workflow instead of the raw fields", async () => { + const el = await render(new FakeProvider(NFL_ONLY)); + expect(root(el).querySelector("#workflow-url")).to.equal(null); + expect(root(el).querySelector("#workflow-params")).to.equal(null); + // The I/O form is loaded on demand + await waitUntil(() => customElements.get("ecc-client-ga4gh-wes-io-form")); + const summary = root(el).querySelector("[data-workflow]"); + expect(summary?.textContent).to.contain("NFL"); + expect(summary?.textContent).to.contain("DSL2"); + expect(summary?.textContent).to.contain( + "/tools/demo/versions/1.0.0/PLAIN_NFL/descriptor/main.nf" + ); + }); + + it("submits the request built from the values", async () => { + const provider = new FakeProvider(NFL_ONLY); + const el = await render(provider); + await enter(el, { reads: "drs://drs.example.org/1", threads: 4 }); + expect(submitButton(el).disabled).to.equal(false); + const submitted = oneEvent(el, "ecc-run-submitted"); + submitButton(el).click(); + const event = await submitted; + expect(event.detail.runId).to.equal("run-1"); + expect(provider.submitted).to.have.length(1); + const [request] = provider.submitted; + expect(request).to.include({ + workflow_type: "NFL", + workflow_type_version: "DSL2", + workflow_url: + "https://trs.example.org/ga4gh/trs/v2/tools/demo/versions/1.0.0/PLAIN_NFL/descriptor/main.nf", + }); + expect(request.workflow_params).to.deep.equal({ + reads: "drs://drs.example.org/1", + threads: 4, + }); + }); + + it("applies the engine profile", async () => { + const provider = new FakeProvider(NFL_ONLY); + const el = await render(provider, { + engineProfile: conquestEngineProfile, + }); + await enter(el, { reads: "drs://drs.example.org/1" }); + const submitted = oneEvent(el, "ecc-run-submitted"); + submitButton(el).click(); + await submitted; + const [request] = provider.submitted; + expect(request.workflow_url).to.equal("https://github.com/org/repo"); + expect(request.workflow_engine_parameters).to.deep.equal({ + revision: SHA, + main_script: "main.nf", + }); + }); + + it("keeps the submit button off while the values are invalid", async () => { + const el = await render(new FakeProvider(NFL_ONLY)); + await enter(el, {}, false); + expect(submitButton(el).disabled).to.equal(true); + }); + + it("says when the service doesn't run the workflow", async () => { + const el = await render( + new FakeProvider({ CWL: { workflow_type_version: ["v1.2"] } }) + ); + await waitUntil( + () => root(el).querySelector(".error-message"), + "no error shown" + ); + expect(root(el).querySelector(".error-message")?.textContent).to.contain( + "doesn't run NFL" + ); + await enter(el, { reads: "drs://drs.example.org/1" }); + expect(submitButton(el).disabled).to.equal(true); + }); + + it("reports values that the binding refuses", async () => { + const provider = new FakeProvider(NFL_ONLY); + const el = await render(provider); + await enter(el, { reads: "file:///etc/passwd" }); + const failed = oneEvent(el, "ecc-run-create-failed"); + submitButton(el).click(); + const event = await failed; + expect(event.detail.error).to.contain("/reads"); + expect(provider.submitted).to.have.length(0); + }); + + it("refuses engine parameters that aren't an object", async () => { + const provider = new FakeProvider(NFL_ONLY); + const el = await render(provider, { + engineProfile: conquestEngineProfile, + }); + await enter(el, { reads: "drs://drs.example.org/1" }); + el.handleInputChange("workflowEngineParams", '"abc"'); + await el.updateComplete; + submitButton(el).click(); + await waitUntil(() => root(el).querySelector(".error-message")); + expect(root(el).querySelector(".error-message")?.textContent).to.contain( + "JSON object" + ); + expect(provider.submitted).to.have.length(0); + }); + + it("needs a TRS tool version", async () => { + const el = await fixture( + html`` + ); + await waitUntil(() => root(el).querySelector(".error-message")); + expect(root(el).querySelector(".error-message")?.textContent).to.contain( + "TRS tool version" + ); + }); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/bindings.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/bindings.ts new file mode 100644 index 00000000..d289fb98 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/bindings.ts @@ -0,0 +1,761 @@ +/** + * Engine bindings of the GA4GH IO Schema Profile (profile version 0.3.0, + * `docs/specification/engine-bindings.md`): input values that are valid + * against the `inputs` of an IO schema become the `workflow_params` of a + * GA4GH WES run request, in the shape that the engine of the schema's + * descriptor type (`NFL`, `SMK`, `WDL`, `CWL`) expects; with the workflow + * URL from TRS, they become a run request. + * + * The translation follows the reference implementation of the profile + * (`ga4gh_io_schema.wes`) and passes its language-neutral test vectors + * (`tests/vectors/wes-params/`). The schemas that apply to a value are + * found as JSON Schema evaluates them: `$ref`, `allOf`, the branches of + * `anyOf` and `oneOf` that the value is valid against, `if` with `then` or + * `else`, `dependentSchemas`, and for members and items `properties`, + * `patternProperties`, `additionalProperties`, `prefixItems`, `items`, + * `contains` (if the item is valid against it) and the `unevaluated*` + * keywords. It fails closed: references that don't resolve within the + * document, references inside embedded `$id` resources and `$dynamicRef` + * are rejected rather than skipped. + */ +import type { RunRequest, ServiceInfo } from "../providers/wes-provider.js"; +import { + checkFileValue, + DEFAULT_ALLOWED_SCHEMES, + FORBIDDEN_SCHEMES, +} from "./files.js"; +import { withErrorMessages } from "./error-messages.js"; +import { + fragmentPointer, + parsePointer, + toPointer, + valueAt, +} from "./pointer.js"; +import { checkIoSchema } from "./validator.js"; +import type { SubschemaValidator } from "./validator.js"; + +/** Descriptor types with an engine binding in version 0.3.0. */ +export const DESCRIPTOR_TYPES: readonly string[] = ["CWL", "NFL", "SMK", "WDL"]; + +/** A location in the input values: keys of objects and indexes of arrays. */ +type Path = (string | number)[]; + +/** Input values that can't be translated, with their location. */ +export class TranslationError extends Error { + /** The location of the offending value in the input values */ + readonly path: Path; + + constructor(message: string, path: Path = []) { + super(message); + this.name = "TranslationError"; + this.path = [...path]; + } + + /** JSON Pointer of the offending value in the input values. */ + get pointer(): string { + return toPointer(this.path); + } +} + +/** The parts of the workflow block that the translation uses. */ +export interface EngineBinding { + /** TRS descriptor type, also the WES `workflow_type` */ + descriptorType: string; + /** Version of the workflow language, the WES `workflow_type_version` */ + descriptorTypeVersion?: string; + /** Entry point of the engine; required for `WDL` */ + entryPoint?: string; +} + +/** Options of a translation. */ +export interface TranslationOptions { + /** + * Fields that the schema's `x-ga4gh-workflow` lacks (e.g. the descriptor + * type version from TRS); fields that it has must match + */ + binding?: Partial; + /** URI schemes of the deployment's allow-list (default `drs`, `https`) */ + allowedSchemes?: readonly string[]; + /** Whether file values may be absolute paths (shared file systems only) */ + allowAbsolutePaths?: boolean; +} + +/** Options of a run request: a translation's, plus the workflow URL. */ +export interface RunRequestOptions extends TranslationOptions { + /** + * URL of the workflow, typically its plain primary descriptor in TRS (see + * `trsDescriptorUrl`); a CWL entry point becomes its fragment + */ + workflowUrl: string; +} + +const CWL_CLASSES = ["File", "Directory"]; +const CWL_DIRECTIVE = + "Keys that start with '$' or contain ':' aren't accepted in CWL input values: the CWL loader takes them for directives or namespaced fields, e.g. $include or cwltool:overrides."; +const NEXTFLOW_DASH = + "Keys with '-' aren't accepted for Nextflow: Nextflow renames them to camelCase (e.g. out-dir to outDir), so the parameter that it sets isn't the key that was checked; use the camelCase name."; +const NEXTFLOW_PLACEHOLDER = "${"; +const NEXTFLOW_VARIABLE = + // eslint-disable-next-line no-template-curly-in-string + "Strings with '${' aren't accepted for Nextflow: Nextflow replaces variables such as ${launchDir} or ${secrets} in the params file before it reads it, so the engine would get another value than the one checked."; +const NON_JSON = + "Values must be JSON: objects, arrays, strings, finite numbers, booleans or null, without cycles."; +/** Applicators whose dynamic scope the translation doesn't model */ +const UNSUPPORTED = ["$dynamicRef"]; + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +const has = (object: Record, key: string) => + Object.prototype.hasOwnProperty.call(object, key); + +/** The first key that the CWL loader takes for a directive or namespace. */ +const directive = (keys: Iterable): string | undefined => { + for (const key of keys) { + if (key.startsWith("$") || key.includes(":")) return key; + } + return undefined; +}; + +/** The first part of a value that isn't JSON, depth first, or `null`. */ +function nonJson(value: unknown): Path | null { + const ancestors = new Set(); + const visit = (item: unknown, path: Path): Path | null => { + if (item === null || ["string", "boolean"].includes(typeof item)) { + return null; + } + if (typeof item === "number") return Number.isFinite(item) ? null : path; + if (typeof item !== "object" || ancestors.has(item as object)) return path; + const prototype = Object.getPrototypeOf(item); + if ( + !Array.isArray(item) && + prototype !== Object.prototype && + prototype !== null + ) { + return path; + } + ancestors.add(item as object); + const entries: [string | number, unknown][] = Array.isArray(item) + ? item.map((child, i) => [i, child]) + : Object.entries(item as Record); + for (const [key, child] of entries) { + const found = visit(child, [...path, key]); + if (found) return found; + } + ancestors.delete(item as object); + return null; + }; + return visit(value, []); +} + +/** The first string (or key) with `${`, depth first, or `null`. */ +function placeholder(value: unknown, path: Path = []): Path | null { + if (typeof value === "string") { + return value.includes(NEXTFLOW_PLACEHOLDER) ? path : null; + } + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i += 1) { + const found = placeholder(value[i], [...path, i]); + if (found) return found; + } + } else if (isObject(value)) { + for (const key of Object.keys(value)) { + if (key.includes(NEXTFLOW_PLACEHOLDER)) return [...path, key]; + } + for (const [key, child] of Object.entries(value)) { + const found = placeholder(child, [...path, key]); + if (found) return found; + } + } + return null; +} + +/** + * Gets the engine binding of an IO schema from its `x-ga4gh-workflow`, with + * the given fields for those that it lacks. + * + * @param schema - The IO schema. + * @param given - Fields from elsewhere, e.g. the version from TRS. + * @returns The binding. + * @throws {TranslationError} If a given field differs from the schema, if + * the descriptor type is unknown or has no binding, or if `WDL` lacks the + * entry point. + */ +export function getBinding( + schema: unknown, + given: Partial = {} +): EngineBinding { + const block = + isObject(schema) && isObject(schema["x-ga4gh-workflow"]) + ? schema["x-ga4gh-workflow"] + : {}; + const field = (name: string, key: keyof EngineBinding) => { + const declared = typeof block[name] === "string" ? block[name] : undefined; + const other = given[key]; + if (declared !== undefined && other !== undefined && declared !== other) { + throw new TranslationError( + `The ${name} '${other}' differs from '${declared}' in x-ga4gh-workflow.` + ); + } + return (declared ?? other) as string | undefined; + }; + const descriptorType = field("descriptor_type", "descriptorType"); + const descriptorTypeVersion = field( + "descriptor_type_version", + "descriptorTypeVersion" + ); + const entryPoint = field("entry_point", "entryPoint"); + if (descriptorType === undefined) { + throw new TranslationError( + "The descriptor type is unknown: the schema has no x-ga4gh-workflow.descriptor_type, and none was given." + ); + } + if (!DESCRIPTOR_TYPES.includes(descriptorType)) { + throw new TranslationError( + `The descriptor type '${descriptorType}' has no engine binding; supported: ${DESCRIPTOR_TYPES.join( + ", " + )}.` + ); + } + if (descriptorType === "WDL" && !entryPoint) { + throw new TranslationError( + "WDL needs the entry point (x-ga4gh-workflow.entry_point): the name of the workflow, or of the task." + ); + } + const binding: EngineBinding = { descriptorType }; + if (descriptorTypeVersion !== undefined) { + binding.descriptorTypeVersion = descriptorTypeVersion; + } + if (entryPoint !== undefined) binding.entryPoint = entryPoint; + return binding; +} + +/** A subschema with its JSON Pointer in the document (`null` if unknown). */ +interface Scope { + schema: unknown; + pointer: string | null; +} + +/** Validates and translates the input values of one IO schema. */ +class Translator { + private readonly inPlaceCache = new Map>(); + + private readonly document: Record; + + private readonly binding: EngineBinding; + + private readonly validateAt: SubschemaValidator; + + private readonly allowedSchemes: readonly string[]; + + private readonly allowAbsolutePaths: boolean; + + constructor( + document: Record, + binding: EngineBinding, + validateAt: SubschemaValidator, + allowedSchemes: readonly string[], + allowAbsolutePaths: boolean + ) { + this.document = document; + this.binding = binding; + this.validateAt = validateAt; + this.allowedSchemes = allowedSchemes; + this.allowAbsolutePaths = allowAbsolutePaths; + } + + private get type() { + return this.binding.descriptorType; + } + + /** Translates validated values, member by member. */ + translate(values: unknown): Record { + if (!isObject(values)) { + throw new TranslationError("The input values must be a JSON object."); + } + const inputsScope = this.descend({ schema: this.document, pointer: "" }, [ + "properties", + "inputs", + ]); + const inputs = this.expand([inputsScope], values); + const params: [string, unknown][] = []; + const names = new Set(); + for (const [key, value] of Object.entries(values)) { + const scopes = this.expand( + this.children(inputs, key, value, values), + value + ); + const name = this.qualify(Translator.nameOf(scopes, key)); + if (names.has(name)) { + throw new TranslationError( + `Two inputs bind to the engine parameter '${name}'.`, + [key] + ); + } + if (this.type === "NFL" && name.includes("-")) { + throw new TranslationError(NEXTFLOW_DASH, [key]); + } + if (this.type === "NFL" && name.includes(NEXTFLOW_PLACEHOLDER)) { + throw new TranslationError(NEXTFLOW_VARIABLE, [key]); + } + if (this.type === "CWL" && directive([key, name]) !== undefined) { + throw new TranslationError(CWL_DIRECTIVE, [key]); + } + names.add(name); + params.push([name, this.value(scopes, value, [key])]); + } + // Entries, not assignments: a key `__proto__` stays a key + return Object.fromEntries(params); + } + + /** Enters a subschema by keyword (and key or index). */ + // eslint-disable-next-line class-methods-use-this + private descend(scope: Scope, segments: (string | number)[]): Scope { + let { schema } = scope; + for (const segment of segments) { + schema = (schema as Record)[segment as string]; + } + // An embedded resource has its own base URI: no pointers inside it + const embedded = isObject(schema) && typeof schema.$id === "string"; + const pointer = + scope.pointer === null || embedded + ? null + : scope.pointer + toPointer(segments); + return { schema, pointer }; + } + + /** Whether a value is valid against the subschema of a scope. */ + private valid(scope: Scope, value: unknown): boolean { + if (scope.schema === true) return true; + if (scope.schema === false) return false; + if (scope.pointer === null) { + throw new TranslationError( + "The schema applies subschemas conditionally inside an embedded $id resource, which the translation doesn't support." + ); + } + try { + return this.validateAt(scope.pointer, value); + } catch (err) { + // E.g. a subschema under a keyword that isn't a schema keyword + throw new TranslationError( + `The schema applies a subschema conditionally where the validator can't check it (${ + scope.pointer + }): ${err instanceof Error ? err.message : String(err)}` + ); + } + } + + /** The subschema that a `$ref` names, within the document. */ + private resolve(scope: Scope, ref: string): Scope { + if (scope.pointer === null) { + throw new TranslationError( + `The schema references '${ref}' inside an embedded $id resource, which the translation doesn't support.` + ); + } + const id = + typeof this.document.$id === "string" + ? this.document.$id.split("#")[0] + : undefined; + const [uri] = ref.split("#"); + const pointer = fragmentPointer(ref); + if ((uri === "" || uri === id) && ref.includes("#") && pointer !== null) { + // A target in an embedded resource (or the resource itself) resolves + // its own references against its `$id`, not the document: fail closed + const segments = parsePointer(pointer); + for (let i = 1; i <= segments.length; i += 1) { + const along = valueAt(this.document, toPointer(segments.slice(0, i))); + if (isObject(along) && typeof along.$id === "string") { + throw new TranslationError( + `The schema references '${ref}', inside an embedded $id resource, which the translation doesn't support.` + ); + } + } + const schema = valueAt(this.document, pointer); + if (schema !== undefined) return { schema, pointer }; + } + throw new TranslationError( + `The schema references '${ref}', which can't be resolved within the document; IO schemas must be bundled.` + ); + } + + /** The subschemas that apply to a value at one location. */ + private expand(scopes: Scope[], value: unknown): Scope[] { + const found: Scope[] = []; + const seen = new Set(); + const queue = [...scopes]; + while (queue.length > 0) { + const scope = queue.shift() as Scope; + const { schema } = scope; + if (isObject(schema) && !seen.has(schema)) { + seen.add(schema); + found.push(scope); + for (const keyword of UNSUPPORTED) { + if (keyword in schema) { + throw new TranslationError( + `The schema uses '${keyword}', which the translation doesn't support.` + ); + } + } + if ("if" in schema) { + const condition = this.descend(scope, ["if"]); + const valid = this.valid(condition, value); + if (valid) queue.push(condition); + const branch = valid ? "then" : "else"; + if (branch in schema) queue.push(this.descend(scope, [branch])); + } + if (isObject(schema.dependentSchemas) && isObject(value)) { + for (const name of Object.keys(schema.dependentSchemas)) { + if (has(value, name)) { + queue.push(this.descend(scope, ["dependentSchemas", name])); + } + } + } + if (typeof schema.$ref === "string") { + queue.push(this.resolve(scope, schema.$ref)); + } + if (Array.isArray(schema.allOf)) { + schema.allOf.forEach((_, i) => + queue.push(this.descend(scope, ["allOf", i])) + ); + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = schema[keyword]; + if (Array.isArray(branches)) { + branches.forEach((_, i) => { + const branch = this.descend(scope, [keyword, i]); + if (this.valid(branch, value)) queue.push(branch); + }); + } + } + } + } + return found; + } + + /** The subschemas of a member or item that a schema names directly. */ + private evaluating(scope: Scope, key: string | number, item: unknown) { + const schema = scope.schema as Record; + const children: Scope[] = []; + if (typeof key === "number") { + const prefix = schema.prefixItems; + if (Array.isArray(prefix) && key < prefix.length) { + children.push(this.descend(scope, ["prefixItems", key])); + } else if ("items" in schema) { + children.push(this.descend(scope, ["items"])); + } + if ("contains" in schema) { + const contains = this.descend(scope, ["contains"]); + if (this.valid(contains, item)) children.push(contains); + } + return children; + } + let matched = false; + if (isObject(schema.properties) && has(schema.properties, key)) { + children.push(this.descend(scope, ["properties", key])); + matched = true; + } + if (isObject(schema.patternProperties)) { + for (const pattern of Object.keys(schema.patternProperties)) { + // The values passed validation, which compiled the same patterns + if (new RegExp(pattern, "u").test(key)) { + children.push(this.descend(scope, ["patternProperties", pattern])); + matched = true; + } + } + } + if (!matched && "additionalProperties" in schema) { + children.push(this.descend(scope, ["additionalProperties"])); + } + return children; + } + + /** The subschemas that a schema applies in place to a value (cached). */ + private inPlace(scope: Scope, parent: unknown): Scope[] { + let byParent = this.inPlaceCache.get(scope.schema); + if (!byParent) { + byParent = new Map(); + this.inPlaceCache.set(scope.schema, byParent); + } + let cached = byParent.get(parent); + if (!cached) { + cached = this.expand([scope], parent); + byParent.set(parent, cached); + } + return cached; + } + + /** + * The subschemas of a member or item. `unevaluated*` applies only if + * neither the schema nor the schemas that it applies in place evaluate + * the member or item. + */ + private children( + scopes: Scope[], + key: string | number, + item: unknown, + parent: unknown + ): Scope[] { + const keyword = + typeof key === "number" ? "unevaluatedItems" : "unevaluatedProperties"; + const children: Scope[] = []; + for (const scope of scopes) { + children.push(...this.evaluating(scope, key, item)); + const schema = scope.schema as Record; + if ( + keyword in schema && + !this.inPlace(scope, parent).some( + (other) => + this.evaluating(other, key, item).length > 0 || + (other.schema !== schema && + keyword in (other.schema as Record)) + ) + ) { + children.push(this.descend(scope, [keyword])); + } + } + return children; + } + + /** Translates a value and the values nested in it. */ + private value(scopes: Scope[], value: unknown, path: Path): unknown { + const applicable = this.expand(scopes, value); + if (Array.isArray(value)) { + return value.map((item, i) => + this.value(this.children(applicable, i, item, value), item, [ + ...path, + i, + ]) + ); + } + if (isObject(value)) { + if (this.type === "CWL") { + if (CWL_CLASSES.includes(value.class as string)) { + throw new TranslationError( + "CWL File and Directory objects aren't input values: give a file reference as a string.", + path + ); + } + const found = directive(Object.keys(value)); + if (found !== undefined) { + throw new TranslationError(CWL_DIRECTIVE, [...path, found]); + } + } + return Object.fromEntries( + Object.entries(value).map(([key, item]) => [ + key, + this.value(this.children(applicable, key, item, value), item, [ + ...path, + key, + ]), + ]) + ); + } + if (typeof value !== "string") return value; + const annotations = applicable + .map((scope) => (scope.schema as Record)["x-ga4gh-file"]) + .filter(isObject); + if (annotations.length === 0) return value; + for (const annotation of annotations) { + const message = checkFileValue( + annotation, + value, + this.allowedSchemes, + this.allowAbsolutePaths + ); + if (message) throw new TranslationError(message, path); + } + const kinds = new Set(annotations.map((annotation) => annotation.kind)); + if (kinds.size > 1) { + throw new TranslationError( + "File references of different kinds apply to this value.", + path + ); + } + if (this.type === "CWL") { + const kind = kinds.has("directory") ? "Directory" : "File"; + return { class: kind, location: value }; + } + return value; + } + + /** `x-ga4gh-parameter.name` of the first schema that has one, or `key`. */ + private static nameOf(scopes: Scope[], key: string): string { + for (const { schema } of scopes) { + const parameter = (schema as Record)[ + "x-ga4gh-parameter" + ]; + if (isObject(parameter) && typeof parameter.name === "string") { + return parameter.name; + } + } + return key; + } + + /** Qualifies an engine name as the descriptor type requires. */ + private qualify(name: string): string { + return this.type === "WDL" ? `${this.binding.entryPoint}.${name}` : name; + } +} + +/** Checks the allow-list of schemes. */ +function allowList(schemes: readonly string[]): readonly string[] { + const forbidden = schemes.filter((scheme) => + FORBIDDEN_SCHEMES.includes(scheme.toLowerCase()) + ); + if (forbidden.length > 0) { + throw new Error( + `The allow-list names forbidden schemes: ${forbidden.join(", ")}.` + ); + } + return schemes; +} + +/** Checks the schema and the values, and translates them. */ +async function translate( + schema: unknown, + values: unknown, + binding: EngineBinding, + options: TranslationOptions +): Promise> { + const allowed = allowList(options.allowedSchemes ?? DEFAULT_ALLOWED_SCHEMES); + const found = nonJson(values); + if (found) throw new TranslationError(NON_JSON, found); + if (binding.descriptorType === "NFL") { + const variable = placeholder(values); + if (variable) throw new TranslationError(NEXTFLOW_VARIABLE, variable); + } + const check = await checkIoSchema(schema); + if (!check.valid) { + const [first] = check.errors; + throw new TranslationError( + `The IO schema isn't valid: ${first?.message ?? "unknown error"}` + ); + } + if (!check.validateAt) { + throw new TranslationError( + "The IO schema validator can't check subschemas (validateAt), which building run requests needs." + ); + } + const result = check.validateInputs(values); + if (!result.valid) { + const [first] = withErrorMessages(result.errors, schema, () => undefined); + const path = parsePointer(first.pointer); + const holder = valueAt(schema, first.schemaPointer); + if ( + first.keyword === "validate" && + path.length > 0 && + isObject(holder) && + (holder.additionalProperties === false || + holder.unevaluatedProperties === false) + ) { + // A member that a false schema refuses: located at its object, as the + // profile's vectors locate it (the validator reports the member) + throw new TranslationError( + `The member "${path[path.length - 1]}" isn't allowed here.`, + path.slice(0, -1) + ); + } + throw new TranslationError(first.message, path); + } + return new Translator( + schema as Record, + binding, + check.validateAt, + allowed, + options.allowAbsolutePaths ?? false + ).translate(values); +} + +/** + * Translates input values into the `workflow_params` of a WES run request. + * Checks the schema against the profile, validates the values against its + * `inputs` and checks the values of file references, then applies the + * engine binding. Defaults of the schema aren't inserted. + * + * @param schema - The IO schema. + * @param values - The input values (a JSON object). + * @param options - Binding fields, allow-list and absolute paths. + * @returns The `workflow_params`. + * @throws {TranslationError} If the values can't be translated (with the + * JSON Pointer of the offending value), or the schema can't be used. + */ +export async function toWorkflowParams( + schema: unknown, + values: unknown, + options: TranslationOptions = {} +): Promise> { + const binding = getBinding(schema, options.binding); + return translate(schema, values, binding, options); +} + +/** + * Builds a WES run request from input values: `workflow_params` (see + * `toWorkflowParams`), `workflow_type`, `workflow_type_version` and + * `workflow_url`. Tags, the engine and its parameters are left to the + * caller (and to engine profiles, see `engine-profiles.ts`). + * + * @param schema - The IO schema. + * @param values - The input values. + * @param options - The workflow URL, and the options of a translation. + * @returns The run request. + * @throws {TranslationError} If the values can't be translated, the + * version is unknown, or a CWL entry point meets a URL with a fragment. + */ +export async function buildRunRequest( + schema: unknown, + values: unknown, + options: RunRequestOptions +): Promise { + const binding = getBinding(schema, options.binding); + if (binding.descriptorTypeVersion === undefined) { + throw new TranslationError( + "The descriptor type version is unknown: set x-ga4gh-workflow.descriptor_type_version, or take it from the TRS tool version (descriptor_type_version)." + ); + } + let { workflowUrl } = options; + if (binding.descriptorType === "CWL" && binding.entryPoint) { + if (workflowUrl.includes("#")) { + throw new TranslationError( + "The workflow URL has a fragment, so the CWL entry point can't be appended to it." + ); + } + workflowUrl = `${workflowUrl}#${binding.entryPoint.replace(/^#/, "")}`; + } + const params = await translate(schema, values, binding, options); + return { + workflow_params: params, + workflow_type: binding.descriptorType, + workflow_type_version: binding.descriptorTypeVersion, + workflow_url: workflowUrl, + }; +} + +/** + * Whether a WES service runs workflows of a binding, by its `service-info` + * (`workflow_type_versions`). + * + * @param serviceInfo - The service's `service-info`. + * @param binding - The descriptor type and, if known, its version. + * @returns `null` if it does, else why not. + */ +export function unsupportedBy( + serviceInfo: Pick, + binding: Pick +): string | null { + const versions = + serviceInfo.workflow_type_versions?.[binding.descriptorType] + ?.workflow_type_version; + if (!versions) { + return `This WES service doesn't run ${binding.descriptorType} workflows.`; + } + if ( + binding.descriptorTypeVersion !== undefined && + versions.length > 0 && + !versions.includes(binding.descriptorTypeVersion) + ) { + return `This WES service doesn't run ${binding.descriptorType} ${ + binding.descriptorTypeVersion + } workflows (it runs ${versions.join(", ")}).`; + } + return null; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/engine-profiles.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/engine-profiles.ts new file mode 100644 index 00000000..4d268ee1 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/engine-profiles.ts @@ -0,0 +1,138 @@ +/** + * Engine profiles: what a WES server needs in a run request beyond the + * profile's engine bindings, kept out of the generic request builder + * (`bindings.ts`). A profile takes the generic request and returns the + * request for one server. + */ +import type { RunRequest } from "../providers/wes-provider.js"; + +/** What a profile may use besides the generic request. */ +export interface EngineProfileContext { + /** TRS descriptor type of the workflow, e.g. `NFL` */ + descriptorType: string; + /** + * URL of the primary descriptor at its source: the `url` of the TRS + * descriptor (`FileWrapper.url`), e.g. a GitHub URL at a commit + */ + primaryDescriptorUrl?: string; +} + +/** Turns a generic run request into one for a particular WES server. */ +export interface EngineProfile { + /** Name of the profile, e.g. for a choice in a portal */ + name: string; + /** + * Returns the request for the server. + * + * @throws If the server can't run the workflow (e.g. a descriptor type it + * doesn't support, or a source it can't fetch). + */ + apply(request: RunRequest, context: EngineProfileContext): RunRequest; +} + +/** A full Git commit SHA */ +const SHA = /^[0-9a-f]{40}$/; +/** A GitHub owner or repository name */ +const NAME = /^[A-Za-z0-9_.-]+$/; + +/** Where a primary descriptor is on GitHub: repository, commit and path. */ +interface GitHubFile { + repository: string; + revision: string; + path: string; +} + +/** + * Parses a GitHub URL of a file at a full commit SHA: + * `https://raw.githubusercontent.com////` or + * `https://github.com///(blob|raw)//`. The raw text + * is parsed (URL parsers would resolve `..` first); paths with empty, `.` + * or `..` segments, or with percent signs, query or fragment, are refused. + */ +function parseGitHubFile(url: string): GitHubFile { + const raw = + /^https:\/\/raw\.githubusercontent\.com\/([^/?#]+)\/([^/?#]+)\/([^/?#]+)\/([^?#]+)$/.exec( + url + ); + const web = + /^https:\/\/github\.com\/([^/?#]+)\/([^/?#]+)\/(?:blob|raw)\/([^/?#]+)\/([^?#]+)$/.exec( + url + ); + const match = raw ?? web; + if (!match) { + throw new Error( + "The primary descriptor isn't a GitHub file URL at a commit (raw.githubusercontent.com or github.com/.../blob/...)." + ); + } + const [, owner, repo, revision, path] = match; + const repository = repo.replace(/\.git$/, ""); + if ( + !NAME.test(owner) || + !NAME.test(repository) || + [owner, repository].some((name) => /^\.+$/.test(name)) + ) { + throw new Error("The GitHub owner or repository name isn't valid."); + } + if (!SHA.test(revision)) { + throw new Error( + "The primary descriptor must be at a full 40-character commit SHA, not a branch or tag." + ); + } + if ( + path.includes("%") || + // Control, format (e.g. bidi overrides) and separator characters + /[\p{Cc}\p{Cf}\p{Zl}\p{Zp}\\]/u.test(path) || + path.split("/").some((segment) => segment.trim() !== segment) || + path.split("/").some((segment) => segment.startsWith("-")) || + path.split("/").some((segment) => ["", ".", ".."].includes(segment)) + ) { + throw new Error( + "The path of the primary descriptor has empty, '.' or '..' segments, segments that start with '-' or with or end in whitespace, percent-encoding, backslashes, or control or format characters." + ); + } + return { + repository: `https://github.com/${owner}/${repository}`, + revision, + path, + }; +} + +/** Engine parameters of Conquest that name the main workflow file */ +const CONQUEST_PATH_PARAMETER: Record = { + NFL: "main_script", + SMK: "snakefile", + WDL: "main_workflow_path", +}; + +/** + * Conquest (`elixir-cloud-aai/conquest`): runs workflows from public GitHub + * repositories at a full commit SHA, not from TRS. `workflow_url` becomes + * the repository, and the engine parameters get `revision` and the path of + * the main workflow file (`main_script` for Nextflow, `snakefile` for + * Snakemake, `main_workflow_path` for WDL), all taken from the URL of the + * primary descriptor. Other engine parameters of the request are kept. + */ +export const conquestEngineProfile: EngineProfile = { + name: "conquest", + apply(request, { descriptorType, primaryDescriptorUrl }) { + const parameter = CONQUEST_PATH_PARAMETER[descriptorType]; + if (!parameter) { + throw new Error(`Conquest doesn't run ${descriptorType} workflows.`); + } + if (!primaryDescriptorUrl) { + throw new Error( + "Conquest needs the URL of the primary descriptor at its source (TRS descriptor url)." + ); + } + const file = parseGitHubFile(primaryDescriptorUrl); + return { + ...request, + workflow_url: file.repository, + workflow_engine_parameters: { + ...request.workflow_engine_parameters, + revision: file.revision, + [parameter]: file.path, + }, + }; + }, +}; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/bindings.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/bindings.test.ts new file mode 100644 index 00000000..8c6f5785 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/bindings.test.ts @@ -0,0 +1,465 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { + buildRunRequest, + getBinding, + toWorkflowParams, + TranslationError, + unsupportedBy, +} from "../bindings.js"; +import { PROFILE_SCHEMA } from "../profile.js"; +import { setIoSchemaValidator, getIoSchemaValidator } from "../validator.js"; +import { WES_PARAMS_CASES } from "./fixtures/wes-params.js"; + +const PROFILE_ID = PROFILE_SCHEMA.$id as string; + +/** An IO schema with a workflow block, inputs and `$defs`. */ +const ioSchema = ( + inputs: Record, + workflow: Record = { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + extra: Record = {} +): Record => ({ + $schema: PROFILE_ID, + "x-ga4gh-workflow": workflow, + type: "object", + properties: { inputs: { type: "object", ...inputs } }, + ...extra, +}); + +/** The error that a promise rejects with. */ +async function rejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error; + } + throw new Error("The promise was fulfilled."); +} + +describe("toWorkflowParams", () => { + describe("test vectors (wes-params)", () => { + for (const vector of WES_PARAMS_CASES) { + it(`${vector.descriptorType}/${vector.name}`, async () => { + const options = { + allowedSchemes: vector.options?.allowedSchemes, + allowAbsolutePaths: vector.options?.allowAbsolutePaths, + }; + const result = toWorkflowParams(vector.schema, vector.values, options); + if (vector.error) { + const error = await rejection(result); + expect(error).to.be.instanceOf(TranslationError); + expect((error as TranslationError).pointer).to.equal( + vector.error.pointer + ); + } else { + expect(await result).to.deep.equal(vector.workflow_params); + } + }); + } + }); + + it("doesn't change the values", async () => { + const schema = ioSchema( + { + properties: { + reads: { type: "string", "x-ga4gh-file": { kind: "file" } }, + }, + }, + { descriptor_type: "CWL", descriptor_type_version: "v1.2" } + ); + const values = { reads: "https://data.example.org/a.bam" }; + await toWorkflowParams(schema, values); + expect(values).to.deep.equal({ reads: "https://data.example.org/a.bam" }); + }); + + it("doesn't insert defaults", async () => { + const schema = ioSchema({ + properties: { threads: { type: "integer", default: 4 } }, + }); + expect(await toWorkflowParams(schema, {})).to.deep.equal({}); + }); + + it("rejects two inputs that bind to one key", async () => { + const schema = ioSchema({ + properties: { + a: { type: "integer", "x-ga4gh-parameter": { name: "x" } }, + b: { type: "integer", "x-ga4gh-parameter": { name: "x" } }, + }, + }); + const error = await rejection(toWorkflowParams(schema, { a: 1, b: 2 })); + expect((error as TranslationError).pointer).to.equal("/b"); + }); + + it("rejects values that aren't an object", async () => { + const schema = ioSchema({}, undefined); + schema.properties = { inputs: {} }; + const error = await rejection(toWorkflowParams(schema, [1])); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("rejects values that aren't JSON", async () => { + const schema = ioSchema({}); + const cyclic: Record = {}; + cyclic.self = cyclic; + for (const values of [{ a: Infinity }, { a: () => 1 }, { a: cyclic }]) { + // eslint-disable-next-line no-await-in-loop + const error = await rejection(toWorkflowParams(schema, values)); + expect(error).to.be.instanceOf(TranslationError); + expect((error as TranslationError).pointer.startsWith("/a")).to.equal( + true + ); + } + }); + + it("uses the schema's error message", async () => { + const schema = ioSchema({ + properties: { + id: { + type: "string", + pattern: "^S[0-9]+$", + "x-ga4gh-error-message": "Sample ids look like S1.", + }, + }, + }); + const error = await rejection(toWorkflowParams(schema, { id: "x" })); + expect((error as TranslationError).message).to.equal( + "Sample ids look like S1." + ); + expect((error as TranslationError).pointer).to.equal("/id"); + }); + + it("follows references to the root's own $id", async () => { + const schema = ioSchema( + { + properties: { + reads: { $ref: "https://example.org/io/1.0.0#/$defs/file" }, + }, + }, + { descriptor_type: "CWL", descriptor_type_version: "v1.2" }, + { + $id: "https://example.org/io/1.0.0", + $defs: { file: { type: "string", "x-ga4gh-file": { kind: "file" } } }, + } + ); + expect( + await toWorkflowParams(schema, { reads: "https://d.example.org/a" }) + ).to.deep.equal({ + reads: { class: "File", location: "https://d.example.org/a" }, + }); + }); + + it("names the input by the parameter of a matching union branch", async () => { + const schema = ioSchema({ + properties: { + n: { + anyOf: [ + { type: "string", "x-ga4gh-parameter": { name: "label" } }, + { type: "integer", "x-ga4gh-parameter": { name: "count" } }, + ], + }, + }, + }); + expect(await toWorkflowParams(schema, { n: 3 })).to.deep.equal({ + count: 3, + }); + expect(await toWorkflowParams(schema, { n: "a" })).to.deep.equal({ + label: "a", + }); + }); + + it("applies unevaluatedItems, prefixItems and patternProperties", async () => { + const file = { type: "string", "x-ga4gh-file": { kind: "file" } }; + const schema = ioSchema( + { + properties: { + pair: { + type: "array", + prefixItems: [{ type: "integer" }], + unevaluatedItems: file, + }, + map: { type: "object", patternProperties: { "^f_": file } }, + }, + }, + { descriptor_type: "CWL", descriptor_type_version: "v1.2" } + ); + expect( + await toWorkflowParams(schema, { + pair: [1, "drs://d.example.org/a"], + map: { f_x: "drs://d.example.org/b", other: "text" }, + }) + ).to.deep.equal({ + pair: [1, { class: "File", location: "drs://d.example.org/a" }], + map: { + f_x: { class: "File", location: "drs://d.example.org/b" }, + other: "text", + }, + }); + }); + + it("checks file references in the items of a contains match", async () => { + const schema = ioSchema({ + properties: { + list: { + type: "array", + contains: { + type: "string", + pattern: "^drs:", + "x-ga4gh-file": { kind: "file", schemes: ["drs"] }, + }, + }, + }, + }); + expect( + await toWorkflowParams(schema, { list: ["drs://a/b", "plain"] }) + ).to.deep.equal({ list: ["drs://a/b", "plain"] }); + }); + + it("rejects file references of different kinds at one value", async () => { + const schema = ioSchema( + { + properties: { + x: { + allOf: [ + { type: "string", "x-ga4gh-file": { kind: "file" } }, + { type: "string", "x-ga4gh-file": { kind: "directory" } }, + ], + }, + }, + }, + { descriptor_type: "CWL", descriptor_type_version: "v1.2" } + ); + const error = await rejection(toWorkflowParams(schema, { x: "drs://a/b" })); + expect((error as TranslationError).pointer).to.equal("/x"); + }); + + it("rejects $dynamicRef", async () => { + const schema = ioSchema( + { properties: { x: { $ref: "#/$defs/d" } } }, + undefined, + { $defs: { d: { $dynamicRef: "#/$defs/e" }, e: { type: "integer" } } } + ); + const error = await rejection(toWorkflowParams(schema, { x: 1 })); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("rejects references inside embedded resources", async () => { + const schema = ioSchema( + { + properties: { + x: { + $id: "https://example.org/inner", + $defs: { s: { type: "string" } }, + $ref: "#/$defs/s", + }, + }, + }, + undefined + ); + const error = await rejection(toWorkflowParams(schema, { x: "a" })); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("rejects references to embedded resources", async () => { + // The embedded resource's own `#/$defs/f` is a file reference; the + // root's `#/$defs/f` isn't: following the root would skip the checks + const schema = ioSchema( + { properties: { a: { $ref: "#/$defs/emb" } } }, + { descriptor_type: "CWL", descriptor_type_version: "v1.2" }, + { + $defs: { + emb: { + $id: "https://example.org/emb.json", + $ref: "#/$defs/f", + $defs: { + f: { type: "string", "x-ga4gh-file": { kind: "file" } }, + }, + }, + f: { type: "string" }, + }, + } + ); + const error = await rejection( + toWorkflowParams(schema, { a: "../../etc/passwd" }) + ); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("rejects conditional subschemas outside schema keywords", async () => { + const schema = ioSchema( + { properties: { a: { $ref: "#/x-lib/s" } } }, + undefined, + { "x-lib": { s: { anyOf: [{ type: "integer" }, { type: "string" }] } } } + ); + const error = await rejection(toWorkflowParams(schema, { a: 1 })); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("keeps a member named __proto__ as a key", async () => { + const schema = ioSchema({}); + const params = await toWorkflowParams( + schema, + JSON.parse('{"__proto__": {"x": 1}}') + ); + expect(Object.keys(params)).to.deep.equal(["__proto__"]); + expect(Object.getPrototypeOf(params)).to.equal(Object.prototype); + }); + + it("rejects a forbidden scheme on the allow-list", async () => { + const schema = ioSchema({}); + const error = await rejection( + toWorkflowParams(schema, {}, { allowedSchemes: ["https", "file"] }) + ); + expect(error).to.be.instanceOf(Error); + }); + + it("rejects schemas that aren't valid IO schemas", async () => { + const error = await rejection(toWorkflowParams({ $schema: "x" }, {})); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("rejects a validator without subschema checks", async () => { + const previous = getIoSchemaValidator(); + setIoSchemaValidator({ + async check(document) { + const result = await previous.check(document); + return result.valid + ? { + valid: true, + errors: [], + validateInputs: result.validateInputs, + } + : result; + }, + }); + try { + const error = await rejection(toWorkflowParams(ioSchema({}), {})); + expect(error).to.be.instanceOf(TranslationError); + } finally { + setIoSchemaValidator(previous); + } + }); +}); + +describe("getBinding", () => { + it("takes the workflow block", () => { + expect( + getBinding(ioSchema({}, { descriptor_type: "WDL", entry_point: "wf" }), { + descriptorTypeVersion: "1.0", + }) + ).to.deep.equal({ + descriptorType: "WDL", + descriptorTypeVersion: "1.0", + entryPoint: "wf", + }); + }); + + it("rejects given fields that differ from the schema", () => { + expect(() => + getBinding(ioSchema({}), { descriptorTypeVersion: "DSL1" }) + ).to.throw(TranslationError); + }); + + it("rejects unknown descriptor types, GALAXY and WDL without entry point", () => { + expect(() => getBinding(ioSchema({}, {}))).to.throw(TranslationError); + expect(() => + getBinding(ioSchema({}, { descriptor_type: "GALAXY" })) + ).to.throw(TranslationError); + expect(() => getBinding(ioSchema({}, { descriptor_type: "WDL" }))).to.throw( + TranslationError + ); + }); +}); + +describe("buildRunRequest", () => { + const url = + "https://trs.example.org/tools/t/versions/1/PLAIN_CWL/descriptor/main.cwl"; + + it("builds the request with the type, version and URL", async () => { + const schema = ioSchema({ properties: { n: { type: "integer" } } }); + expect( + await buildRunRequest(schema, { n: 1 }, { workflowUrl: url }) + ).to.deep.equal({ + workflow_params: { n: 1 }, + workflow_type: "NFL", + workflow_type_version: "DSL2", + workflow_url: url, + }); + }); + + it("takes the version from TRS if the schema has none", async () => { + const schema = ioSchema({}, { descriptor_type: "SMK" }); + const request = await buildRunRequest( + schema, + {}, + { workflowUrl: url, binding: { descriptorTypeVersion: "8" } } + ); + expect(request.workflow_type_version).to.equal("8"); + }); + + it("rejects an unknown version", async () => { + const schema = ioSchema({}, { descriptor_type: "SMK" }); + const error = await rejection( + buildRunRequest(schema, {}, { workflowUrl: url }) + ); + expect(error).to.be.instanceOf(TranslationError); + }); + + it("appends a CWL entry point as the fragment", async () => { + const schema = ioSchema( + {}, + { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + entry_point: "#main", + } + ); + const request = await buildRunRequest(schema, {}, { workflowUrl: url }); + expect(request.workflow_url).to.equal(`${url}#main`); + const error = await rejection( + buildRunRequest(schema, {}, { workflowUrl: `${url}#other` }) + ); + expect(error).to.be.instanceOf(TranslationError); + }); +}); + +describe("unsupportedBy", () => { + const serviceInfo = { + workflow_type_versions: { + NFL: { workflow_type_version: ["DSL2"] }, + CWL: { workflow_type_version: [] }, + }, + }; + + it("accepts listed types and versions, and any version of an empty list", () => { + expect( + unsupportedBy(serviceInfo, { + descriptorType: "NFL", + descriptorTypeVersion: "DSL2", + }) + ).to.equal(null); + expect(unsupportedBy(serviceInfo, { descriptorType: "NFL" })).to.equal( + null + ); + expect( + unsupportedBy(serviceInfo, { + descriptorType: "CWL", + descriptorTypeVersion: "v1.2", + }) + ).to.equal(null); + }); + + it("refuses other types and versions", () => { + expect(unsupportedBy(serviceInfo, { descriptorType: "WDL" })).to.match( + /doesn't run WDL/ + ); + expect( + unsupportedBy(serviceInfo, { + descriptorType: "NFL", + descriptorTypeVersion: "DSL1", + }) + ).to.match(/runs DSL2/); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/engine-profiles.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/engine-profiles.test.ts new file mode 100644 index 00000000..c6c6dbcd --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/engine-profiles.test.ts @@ -0,0 +1,91 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { conquestEngineProfile } from "../engine-profiles.js"; +import type { RunRequest } from "../../providers/wes-provider.js"; + +const SHA = "3c2cdc9823c2b4636e5e3e73e223878099ff5dc9"; + +const request = (type: string): RunRequest => ({ + workflow_params: { greeting: "hi" }, + workflow_type: type, + workflow_type_version: "DSL2", + workflow_url: + "https://trs.example.org/tools/t/versions/1/PLAIN_NFL/descriptor/main.nf", + workflow_engine_parameters: { profiles: "test" }, +}); + +describe("conquestEngineProfile", () => { + it("takes repository, commit and main script from a raw GitHub URL", () => { + expect( + conquestEngineProfile.apply(request("NFL"), { + descriptorType: "NFL", + primaryDescriptorUrl: `https://raw.githubusercontent.com/org/repo/${SHA}/flows/main.nf`, + }) + ).to.deep.equal({ + ...request("NFL"), + workflow_url: "https://github.com/org/repo", + workflow_engine_parameters: { + profiles: "test", + revision: SHA, + main_script: "flows/main.nf", + }, + }); + }); + + it("takes the blob form of GitHub URLs and the engine's own names", () => { + const smk = conquestEngineProfile.apply(request("SMK"), { + descriptorType: "SMK", + primaryDescriptorUrl: `https://github.com/org/repo/blob/${SHA}/workflow/Snakefile`, + }); + expect(smk.workflow_engine_parameters).to.deep.equal({ + profiles: "test", + revision: SHA, + snakefile: "workflow/Snakefile", + }); + const wdl = conquestEngineProfile.apply(request("WDL"), { + descriptorType: "WDL", + primaryDescriptorUrl: `https://github.com/org/repo/raw/${SHA}/main.wdl`, + }); + expect(wdl.workflow_engine_parameters).to.deep.equal({ + profiles: "test", + revision: SHA, + main_workflow_path: "main.wdl", + }); + }); + + it("refuses what Conquest can't run", () => { + const refused: [string, string | undefined][] = [ + ["CWL", `https://raw.githubusercontent.com/org/repo/${SHA}/main.cwl`], + ["NFL", undefined], + ["NFL", "https://raw.githubusercontent.com/org/repo/main/main.nf"], + ["NFL", `https://gitlab.com/org/repo/-/raw/${SHA}/main.nf`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/../main.nf`], + [ + "NFL", + `https://raw.githubusercontent.com/org/repo/${SHA}/a/%2e%2e/b.nf`, + ], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/main.nf?x=1`], + ["NFL", `http://raw.githubusercontent.com/org/repo/${SHA}/main.nf`], + ["NFL", `https://github.com/org/repo/tree/${SHA}/main.nf`], + ["NFL", `https://github.com/../../blob/${SHA}/main.nf`], + ["NFL", `https://github.com/./evil/blob/${SHA}/main.nf`], + ["NFL", `https://github.com/owner/.git/blob/${SHA}/main.nf`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/main.nf\n-x`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/a\\b.nf`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/-main.nf`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/a\u202eb.nf`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/a\u0085b.nf`], + ["NFL", `https://raw.githubusercontent.com/org/repo/${SHA}/ main.nf`], + ]; + for (const [descriptorType, primaryDescriptorUrl] of refused) { + expect( + () => + conquestEngineProfile.apply(request(descriptorType), { + descriptorType, + primaryDescriptorUrl, + }), + `${descriptorType} ${primaryDescriptorUrl}` + ).to.throw(); + } + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/trs.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/trs.ts new file mode 100644 index 00000000..55d3a770 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/trs.ts @@ -0,0 +1,688 @@ +/** + * Test vectors of workflow URLs and TRS files (`tests/vectors/workflow-urls/`, `tests/vectors/trs-files/`). + * + * Generated by `scripts/sync-io-schema.mjs` from https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3 + * (profile version 0.3.0; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ + +export interface WorkflowUrlCase { + name: string; + trsUrl: string; + toolId: string; + versionId: string; + descriptorType: string; + primaryDescriptorPath?: string; + workflowUrl?: string; + error?: boolean; + imports?: { reference: string; url: string }[]; +} + +export interface TrsFilesCase { + name: string; + files: unknown; + schemaFile: { path: string; file_type: string } | null; + primaryDescriptorPath?: string | null; +} + +export const WORKFLOW_URL_CASES: WorkflowUrlCase[] = [ + { + name: "single-file-bare", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/demo/versions/1.0.0/PLAIN_WDL/descriptor", + }, + { + name: "single-file-with-path", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "demo.wdl", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/demo/versions/1.0.0/PLAIN_WDL/descriptor/demo.wdl", + }, + { + name: "wdl-import", + trsUrl: "https://trs.example.org/ga4gh/trs/v2/", + toolId: "variant-calling", + versionId: "1.2.0", + descriptorType: "WDL", + primaryDescriptorPath: "main.wdl", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/variant-calling/versions/1.2.0/PLAIN_WDL/descriptor/main.wdl", + imports: [ + { + reference: "tasks/align.wdl", + url: "https://trs.example.org/ga4gh/trs/v2/tools/variant-calling/versions/1.2.0/PLAIN_WDL/descriptor/tasks/align.wdl", + }, + ], + }, + { + name: "wdl-import-without-path-misses", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "variant-calling", + versionId: "1.2.0", + descriptorType: "WDL", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/variant-calling/versions/1.2.0/PLAIN_WDL/descriptor", + imports: [ + { + reference: "tasks/align.wdl", + url: "https://trs.example.org/ga4gh/trs/v2/tools/variant-calling/versions/1.2.0/PLAIN_WDL/tasks/align.wdl", + }, + ], + }, + { + name: "nested-primary-descriptor", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "#workflow/example.org/variant-calling", + versionId: "1.2.0", + descriptorType: "WDL", + primaryDescriptorPath: "workflows/variant_calling.wdl", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/%23workflow%2Fexample.org%2Fvariant-calling/versions/1.2.0/PLAIN_WDL/descriptor/workflows/variant_calling.wdl", + imports: [ + { + reference: "tasks/align.wdl", + url: "https://trs.example.org/ga4gh/trs/v2/tools/%23workflow%2Fexample.org%2Fvariant-calling/versions/1.2.0/PLAIN_WDL/descriptor/workflows/tasks/align.wdl", + }, + { + reference: "../common/qc.wdl", + url: "https://trs.example.org/ga4gh/trs/v2/tools/%23workflow%2Fexample.org%2Fvariant-calling/versions/1.2.0/PLAIN_WDL/descriptor/common/qc.wdl", + }, + ], + }, + { + name: "cwl-run-reference", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "align", + versionId: "2", + descriptorType: "CWL", + primaryDescriptorPath: "Dockstore.cwl", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/align/versions/2/PLAIN_CWL/descriptor/Dockstore.cwl", + imports: [ + { + reference: "tools/bwa-mem.cwl", + url: "https://trs.example.org/ga4gh/trs/v2/tools/align/versions/2/PLAIN_CWL/descriptor/tools/bwa-mem.cwl", + }, + ], + }, + { + name: "leading-slash-bare", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "align", + versionId: "2", + descriptorType: "CWL", + primaryDescriptorPath: "/Dockstore.cwl", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/align/versions/2/PLAIN_CWL/descriptor", + }, + { + name: "path-segments-percent-encoded", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "my workflow/main#1?.wdl", + workflowUrl: + "https://trs.example.org/ga4gh/trs/v2/tools/demo/versions/1.0.0/PLAIN_WDL/descriptor/my%20workflow/main%231%3F.wdl", + imports: [ + { + reference: "sub.wdl", + url: "https://trs.example.org/ga4gh/trs/v2/tools/demo/versions/1.0.0/PLAIN_WDL/descriptor/my%20workflow/sub.wdl", + }, + ], + }, + { + name: "error-dot-dot-segment", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "../main.wdl", + error: true, + }, + { + name: "error-dot-segment", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "workflows/./main.wdl", + error: true, + }, + { + name: "error-empty-segment", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "workflows//main.wdl", + error: true, + }, + { + name: "error-directory", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "workflows/", + error: true, + }, + { + name: "error-empty", + trsUrl: "https://trs.example.org/ga4gh/trs/v2", + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + primaryDescriptorPath: "", + error: true, + }, +]; + +export const TRS_FILES_CASES: TrsFilesCase[] = [ + { + name: "other-next-to-primary", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "main.wdl", + }, + { + name: "extra-fields-ignored", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + checksum: [ + { + type: "sha-256", + checksum: + "a948904f2f0f479b8f8197694b30184b0d2ed1c1cd2a1ec0fb85d299a192a447", + }, + ], + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + checksum: [ + { + type: "sha-256", + checksum: + "ed7002b439e9ac845f22357d822bac1444730fbdb6016d3ec9432297b9ec9f73", + }, + ], + "x-registry-note": "fields that clients don't know are ignored", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + }, + { + name: "dot-slash-path", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "./ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "./ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "main.wdl", + }, + { + name: "dot-slash-primary-in-directory", + files: [ + { + path: "./wdl/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "wdl/ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "wdl/ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "wdl/main.wdl", + }, + { + name: "dot-slash-primary", + files: [ + { + path: "./main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "./ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "./ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "main.wdl", + }, + { + name: "leading-slash", + files: [ + { + path: "/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "/ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "/ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "/main.wdl", + }, + { + name: "double-slash", + files: [ + { + path: "wdl/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "wdl//ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "wdl//ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "wdl/main.wdl", + }, + { + name: "entries-without-type-or-path-ignored", + files: [ + { + path: "README.md", + }, + { + file_type: "OTHER", + }, + { + path: null, + file_type: "OTHER", + }, + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + }, + { + name: "other-in-another-directory", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "other/ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "other-above-primary", + files: [ + { + path: "wdl/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "dot-dot-segment", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "wdl/../ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "other-name-case-differs", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "GA4GH-IO.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "test-file-at-schema-path", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "TEST_FILE", + }, + ], + schemaFile: null, + }, + { + name: "no-primary-descriptor", + files: [ + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "primary-descriptors-in-two-directories", + files: [ + { + path: "a/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "b/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "a/ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "io-schema-type", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + }, + { + name: "io-schema-type-at-any-path", + files: [ + { + path: "wdl/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "schemas/inputs.json", + file_type: "IO_SCHEMA", + }, + ], + schemaFile: { + path: "schemas/inputs.json", + file_type: "IO_SCHEMA", + }, + }, + { + name: "io-schema-type-without-primary-descriptor", + files: [ + { + path: "ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + primaryDescriptorPath: null, + }, + { + name: "io-schema-type-preferred", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + { + path: "io/ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + ], + schemaFile: { + path: "io/ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + }, + { + name: "io-schema-type-twice", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + { + path: "other.schema.json", + file_type: "IO_SCHEMA", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "io-schema-type-without-path-ignored", + files: [ + { + file_type: "IO_SCHEMA", + }, + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + }, + { + name: "other-twice", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + { + path: "./ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: null, + }, + { + name: "primary-descriptors-in-one-directory", + files: [ + { + path: "wdl/main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "./wdl/alt.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "wdl/ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "wdl/ga4gh-io.schema.json", + file_type: "OTHER", + }, + primaryDescriptorPath: "wdl/main.wdl", + }, + { + name: "io-schema-type-dot-dot-ignored", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "../ga4gh-io.schema.json", + file_type: "IO_SCHEMA", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + }, + { + name: "io-schema-type-non-string-path-ignored", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: 5, + file_type: "IO_SCHEMA", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + }, + { + name: "io-schema-type-with-other-elsewhere", + files: [ + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "other/ga4gh-io.schema.json", + file_type: "OTHER", + }, + { + path: "inputs.json", + file_type: "IO_SCHEMA", + }, + ], + schemaFile: { + path: "inputs.json", + file_type: "IO_SCHEMA", + }, + }, + { + name: "entries-that-are-no-objects-ignored", + files: [ + "ga4gh-io.schema.json", + null, + ["OTHER"], + { + path: "main.wdl", + file_type: "PRIMARY_DESCRIPTOR", + }, + { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + ], + schemaFile: { + path: "ga4gh-io.schema.json", + file_type: "OTHER", + }, + }, +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/wes-params.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/wes-params.ts new file mode 100644 index 00000000..e2d6c41f --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/wes-params.ts @@ -0,0 +1,1685 @@ +/** + * Test vectors of the engine bindings (`tests/vectors/wes-params/`). + * + * Generated by `scripts/sync-io-schema.mjs` from https://github.com/elixir-cloud-aai/ga4gh-io-schema/tree/2c3dc49ad89f0a556272f160369a2a2d7a21dac3 + * (profile version 0.3.0; Apache-2.0, as this package). Don't edit. + */ +/* eslint-disable */ + +export interface WesParamsCase { + descriptorType: string; + name: string; + schema: Record; + values: unknown; + /** The expected `workflow_params`, or else `error` */ + workflow_params?: Record; + error?: { pointer: string }; + options?: { allowedSchemes?: string[]; allowAbsolutePaths?: boolean }; +} + +export const WES_PARAMS_CASES: WesParamsCase[] = [ + { + descriptorType: "CWL", + name: "all-annotations-checked", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + allOf: [ + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["drs"], + }, + }, + ], + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "https://data.example.org/r.bam", + }, + }, + { + descriptorType: "CWL", + name: "conditional-applicators", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + mode: { + type: "string", + enum: ["paired", "single"], + }, + reads: { + type: "string", + }, + mates: { + type: "string", + }, + extra: { + type: "object", + properties: { + note: { + type: "string", + }, + }, + unevaluatedProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + inputs_list: { + type: "array", + contains: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + required: ["mode", "reads"], + additionalProperties: false, + if: { + properties: { + mode: { + const: "paired", + }, + }, + }, + then: { + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + else: { + properties: { + reads: { + type: "string", + }, + }, + }, + dependentSchemas: { + mates: { + properties: { + mates: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + }, + }, + values: { + mode: "paired", + reads: "https://data.example.org/r1.fq", + mates: "https://data.example.org/r2.fq", + extra: { + note: "x", + panel: "https://data.example.org/panel.bed", + }, + inputs_list: ["https://data.example.org/a.txt"], + }, + workflow_params: { + mode: "paired", + reads: { + class: "File", + location: "https://data.example.org/r1.fq", + }, + mates: { + class: "File", + location: "https://data.example.org/r2.fq", + }, + extra: { + note: "x", + panel: { + class: "File", + location: "https://data.example.org/panel.bed", + }, + }, + inputs_list: [ + { + class: "File", + location: "https://data.example.org/a.txt", + }, + ], + }, + }, + { + descriptorType: "CWL", + name: "file-in-then-checked", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + mode: { + type: "string", + }, + reads: { + type: "string", + }, + }, + required: ["mode"], + additionalProperties: false, + if: { + properties: { + mode: { + const: "a", + }, + }, + }, + then: { + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + }, + values: { + mode: "a", + reads: "file:///etc/passwd", + }, + }, + { + descriptorType: "CWL", + name: "file-in-union-checked", + error: { + pointer: "/target", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + target: { + anyOf: [ + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + { + type: "string", + }, + ], + }, + }, + required: ["target"], + additionalProperties: false, + }, + }, + }, + values: { + target: "javascript:alert(1)", + }, + }, + { + descriptorType: "CWL", + name: "file-objects", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: ["^.bai"], + }, + }, + index: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + fastqs: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + known_sites: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + label: { + type: "string", + }, + }, + required: ["reads", "index", "fastqs"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "https://data.example.org/sample.bam", + index: "drs://drs.example.org/index", + fastqs: ["inputs/r1.fq.gz", "inputs/r2.fq.gz"], + label: "sample", + }, + workflow_params: { + reads: { + class: "File", + location: "https://data.example.org/sample.bam", + }, + index: { + class: "Directory", + location: "drs://drs.example.org/index", + }, + fastqs: [ + { + class: "File", + location: "inputs/r1.fq.gz", + }, + { + class: "File", + location: "inputs/r2.fq.gz", + }, + ], + label: "sample", + }, + }, + { + descriptorType: "CWL", + name: "loader-directive-member", + error: { + pointer: "/$include", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + additionalProperties: { + type: "string", + "x-ga4gh-parameter": { + name: "extra", + }, + }, + }, + }, + }, + values: { + reads: "https://data.example.org/sample.bam", + $include: "file:///etc/passwd", + }, + }, + { + descriptorType: "CWL", + name: "loader-directives", + error: { + pointer: "/settings/extra/0/$import", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + settings: { + type: "object", + }, + }, + required: ["reads"], + }, + }, + }, + values: { + reads: "https://data.example.org/sample.bam", + settings: { + extra: [ + { + $import: "http://169.254.169.254/latest/meta-data", + }, + ], + }, + }, + }, + { + descriptorType: "CWL", + name: "namespaced-member", + error: { + pointer: "/cwltool:overrides", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + }, + values: { + reads: "https://data.example.org/sample.bam", + "cwltool:overrides": { + "#main": { + requirements: { + DockerRequirement: { + dockerPull: "example.org/other", + }, + }, + }, + }, + }, + }, + { + descriptorType: "CWL", + name: "records-and-unions", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample: { + $ref: "#/$defs/sample", + }, + target: { + anyOf: [ + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + { + type: "string", + }, + ], + }, + threshold: { + anyOf: [ + { + type: "integer", + }, + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + ], + }, + renamed: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-parameter": { + name: "input_file", + }, + }, + }, + required: ["sample", "target"], + additionalProperties: false, + }, + }, + $defs: { + sample: { + type: "object", + properties: { + id: { + type: "string", + }, + bam: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["id", "bam"], + }, + }, + }, + values: { + sample: { + id: "a", + bam: "https://data.example.org/a.bam", + }, + target: "https://data.example.org/targets.bed", + threshold: 5, + renamed: "inputs/x.txt", + }, + workflow_params: { + sample: { + id: "a", + bam: { + class: "File", + location: "https://data.example.org/a.bam", + }, + }, + target: { + class: "File", + location: "https://data.example.org/targets.bed", + }, + threshold: 5, + input_file: { + class: "File", + location: "inputs/x.txt", + }, + }, + }, + { + descriptorType: "NFL", + name: "absolute-path", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "/shared/data/reads.fastq.gz", + }, + }, + { + descriptorType: "NFL", + name: "absolute-path-allowed", + options: { + allowAbsolutePaths: true, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "/shared/data/reads.fastq.gz", + }, + workflow_params: { + reads: "/shared/data/reads.fastq.gz", + }, + }, + { + descriptorType: "NFL", + name: "basic", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["drs", "https"], + }, + }, + genome_index: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + sample_names: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + }, + min_quality: { + type: "integer", + minimum: 0, + default: 20, + }, + skip_qc: { + type: "boolean", + }, + }, + required: ["reads", "genome_index", "sample_names"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "drs://drs.example.org/314159", + genome_index: "https://data.example.org/index/", + sample_names: ["s1", "s2"], + skip_qc: false, + }, + workflow_params: { + reads: "drs://drs.example.org/314159", + genome_index: "https://data.example.org/index/", + sample_names: ["s1", "s2"], + skip_qc: false, + }, + }, + { + descriptorType: "NFL", + name: "deployment-scheme", + options: { + allowedSchemes: ["drs", "https", "s3"], + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "s3://bucket/reads.fastq.gz", + }, + workflow_params: { + reads: "s3://bucket/reads.fastq.gz", + }, + }, + { + descriptorType: "NFL", + name: "file-branch-not-matched", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + target: { + anyOf: [ + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + pattern: "[.]bed$", + }, + { + type: "string", + enum: ["all", "exome"], + }, + ], + }, + }, + additionalProperties: false, + }, + }, + }, + values: { + target: "exome", + }, + workflow_params: { + target: "exome", + }, + }, + { + descriptorType: "NFL", + name: "file-in-array", + error: { + pointer: "/fastqs/1", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + fastqs: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + }, + }, + required: ["fastqs"], + additionalProperties: false, + }, + }, + }, + values: { + fastqs: [ + "https://data.example.org/r1.fq.gz", + "ftp://data.example.org/r2.fq.gz", + ], + }, + }, + { + descriptorType: "NFL", + name: "forbidden-scheme", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "file:///etc/passwd", + }, + }, + { + descriptorType: "NFL", + name: "grouped-parameters", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl-groups/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + }, + type: "object", + properties: { + inputs: { + title: "Parameters in groups, as converted from nf-schema", + type: "object", + allOf: [ + { + $ref: "#/$defs/input_output_options", + }, + { + $ref: "#/$defs/generic_options", + }, + ], + }, + outputs: { + type: "object", + properties: {}, + }, + }, + $defs: { + input_output_options: { + title: "Input/output options", + type: "object", + required: ["input", "outdir"], + properties: { + input: { + type: "string", + pattern: "^\\S+\\.csv$", + description: + "Path to the sample sheet.\n\nA *CSV* file with a header row.", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-error-message": "The sample sheet must be a CSV file.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + }, + outdir: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + }, + }, + generic_options: { + title: "Generic options", + type: "object", + properties: { + publish_dir_mode: { + type: "string", + enum: ["copy", "symlink"], + default: "copy", + "x-ga4gh-hidden": true, + }, + }, + }, + }, + }, + values: { + input: "https://data.example.org/samplesheet.csv", + outdir: "https://data.example.org/results/", + publish_dir_mode: "symlink", + }, + workflow_params: { + input: "https://data.example.org/samplesheet.csv", + outdir: "https://data.example.org/results/", + publish_dir_mode: "symlink", + }, + }, + { + descriptorType: "NFL", + name: "grouped-parameters-file", + error: { + pointer: "/input", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl-groups/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + }, + type: "object", + properties: { + inputs: { + title: "Parameters in groups, as converted from nf-schema", + type: "object", + allOf: [ + { + $ref: "#/$defs/input_output_options", + }, + { + $ref: "#/$defs/generic_options", + }, + ], + }, + outputs: { + type: "object", + properties: {}, + }, + }, + $defs: { + input_output_options: { + title: "Input/output options", + type: "object", + required: ["input", "outdir"], + properties: { + input: { + type: "string", + pattern: "^\\S+\\.csv$", + description: + "Path to the sample sheet.\n\nA *CSV* file with a header row.", + "x-ga4gh-description-format": "markdown", + "x-ga4gh-error-message": "The sample sheet must be a CSV file.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + }, + outdir: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + }, + }, + generic_options: { + title: "Generic options", + type: "object", + properties: { + publish_dir_mode: { + type: "string", + enum: ["copy", "symlink"], + default: "copy", + "x-ga4gh-hidden": true, + }, + }, + }, + }, + }, + values: { + input: "../samplesheet.csv", + outdir: "https://data.example.org/results/", + }, + }, + { + descriptorType: "NFL", + name: "invalid-value", + error: { + pointer: "/condition", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + condition: { + type: "string", + enum: ["control", "treatment"], + }, + }, + required: ["condition"], + additionalProperties: false, + }, + }, + }, + values: { + condition: "contrl", + }, + }, + { + descriptorType: "NFL", + name: "kebab-alias", + error: { + pointer: "/out", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + out: { + type: "string", + "x-ga4gh-parameter": { + name: "out-dir", + }, + }, + output: { + type: "string", + "x-ga4gh-parameter": { + name: "outDir", + }, + }, + }, + }, + }, + }, + values: { + out: "results", + output: "other", + }, + }, + { + descriptorType: "NFL", + name: "parameter-name", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + report_title: { + type: "string", + "x-ga4gh-parameter": { + name: "multiqc.title", + }, + }, + outdir: { + type: "string", + }, + }, + required: [], + additionalProperties: false, + }, + }, + }, + values: { + report_title: "Run 42", + outdir: "results", + }, + workflow_params: { + "multiqc.title": "Run 42", + outdir: "results", + }, + }, + { + descriptorType: "NFL", + name: "path-dot-dot", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "inputs/../../etc/passwd", + }, + }, + { + descriptorType: "NFL", + name: "path-where-schemes", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["drs", "https"], + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "reads.fastq.gz", + }, + }, + { + descriptorType: "NFL", + name: "relative-path", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + samplesheet: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + }, + }, + }, + required: ["samplesheet"], + additionalProperties: false, + }, + }, + }, + values: { + samplesheet: "inputs/samplesheet.csv", + }, + workflow_params: { + samplesheet: "inputs/samplesheet.csv", + }, + }, + { + descriptorType: "NFL", + name: "scheme-not-allowed", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "s3://bucket/reads.fastq.gz", + }, + }, + { + descriptorType: "NFL", + name: "scheme-not-in-schemes", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["drs"], + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "https://data.example.org/reads.fastq.gz", + }, + }, + { + descriptorType: "NFL", + name: "unknown-input", + error: { + pointer: "", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + outdir: { + type: "string", + }, + }, + required: [], + additionalProperties: false, + }, + }, + }, + values: { + outdir: "results", + outdri: "results", + }, + }, + { + descriptorType: "NFL", + name: "variable-in-key", + error: { + pointer: "/options/${secrets}", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + options: { + type: "object", + additionalProperties: { + type: "string", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "https://data.example.org/a.fq", + options: { + "${secrets}": "x", + }, + }, + }, + { + descriptorType: "NFL", + name: "variable-in-value", + error: { + pointer: "/reads", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reads: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + options: { + type: "object", + additionalProperties: { + type: "string", + }, + }, + }, + required: ["reads"], + additionalProperties: false, + }, + }, + }, + values: { + reads: "https://data.example.org/${launchDir}/a.fq", + }, + }, + { + descriptorType: "SMK", + name: "config", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/smk/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "SMK", + descriptor_type_version: "8", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + reference: { + type: "object", + properties: { + fasta: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + name: { + type: "string", + }, + }, + required: ["fasta"], + }, + samples: { + type: "array", + items: { + type: "object", + properties: { + id: { + type: "string", + }, + bam: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + threads: { + type: "integer", + }, + }, + required: ["reference"], + additionalProperties: false, + }, + }, + }, + values: { + reference: { + fasta: "https://data.example.org/ref.fa", + name: "GRCh38", + }, + samples: [ + { + id: "a", + bam: "drs://drs.example.org/a", + }, + ], + threads: 8, + }, + workflow_params: { + reference: { + fasta: "https://data.example.org/ref.fa", + name: "GRCh38", + }, + samples: [ + { + id: "a", + bam: "drs://drs.example.org/a", + }, + ], + threads: 8, + }, + }, + { + descriptorType: "WDL", + name: "compound-values", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/wdl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + descriptor_type_version: "1.1", + entry_point: "variant_calling", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + interval: { + type: "object", + properties: { + left: { + type: "integer", + }, + right: { + type: "string", + }, + }, + required: ["left", "right"], + additionalProperties: false, + "x-ga4gh-parameter": { + type: "Pair[Int,String]", + }, + }, + references: { + type: "object", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + "x-ga4gh-parameter": { + type: "Map[String,File]", + }, + }, + label: { + type: ["string", "null"], + "x-ga4gh-parameter": { + type: "String?", + }, + }, + }, + required: [], + additionalProperties: false, + }, + }, + }, + values: { + interval: { + left: 1, + right: "chr1", + }, + references: { + GRCh38: "drs://drs.example.org/grch38", + }, + label: null, + }, + workflow_params: { + "variant_calling.interval": { + left: 1, + right: "chr1", + }, + "variant_calling.references": { + GRCh38: "drs://drs.example.org/grch38", + }, + "variant_calling.label": null, + }, + }, + { + descriptorType: "WDL", + name: "qualified-names", + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/vectors/wdl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + descriptor_type_version: "1.1", + entry_point: "variant_calling", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + input_bam: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".bai"], + }, + "x-ga4gh-parameter": { + type: "File", + }, + }, + sample_names: { + type: "array", + items: { + type: "string", + }, + minItems: 1, + "x-ga4gh-parameter": { + type: "Array[String]+", + }, + }, + caller_threads: { + type: "integer", + minimum: 1, + default: 4, + "x-ga4gh-parameter": { + name: "call_variants.threads", + type: "Int", + }, + }, + }, + required: ["input_bam", "sample_names"], + additionalProperties: false, + }, + }, + }, + values: { + input_bam: "https://data.example.org/sample.bam", + sample_names: ["NA12878"], + caller_threads: 8, + }, + workflow_params: { + "variant_calling.input_bam": "https://data.example.org/sample.bam", + "variant_calling.sample_names": ["NA12878"], + "variant_calling.call_variants.threads": 8, + }, + }, +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/trs.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/trs.test.ts new file mode 100644 index 00000000..e2f62867 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/trs.test.ts @@ -0,0 +1,84 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { + findPrimaryDescriptorPath, + findSchemaFile, + normalisePath, + trsDescriptorUrl, +} from "../trs.js"; +import { TRS_FILES_CASES, WORKFLOW_URL_CASES } from "./fixtures/trs.js"; + +describe("trsDescriptorUrl", () => { + describe("test vectors (workflow-urls)", () => { + for (const vector of WORKFLOW_URL_CASES) { + it(vector.name, () => { + const build = () => + trsDescriptorUrl( + vector.trsUrl, + vector.toolId, + vector.versionId, + vector.descriptorType, + vector.primaryDescriptorPath + ); + if (vector.error) { + expect(build).to.throw(); + return; + } + const url = build(); + expect(url).to.equal(vector.workflowUrl); + for (const { reference, url: expected } of vector.imports ?? []) { + expect(new URL(reference, url).href).to.equal(expected); + } + }); + } + }); + + it("encodes the characters that encodeURIComponent keeps", () => { + expect( + trsDescriptorUrl("https://trs.example.org/", "a(b)", "1!", "WDL") + ).to.equal( + "https://trs.example.org/tools/a%28b%29/versions/1%21/PLAIN_WDL/descriptor" + ); + }); + + it("accepts null for no path", () => { + expect( + trsDescriptorUrl("https://trs.example.org", "a", "1", "CWL", null) + ).to.equal( + "https://trs.example.org/tools/a/versions/1/PLAIN_CWL/descriptor" + ); + }); +}); + +describe("findSchemaFile and findPrimaryDescriptorPath", () => { + describe("test vectors (trs-files)", () => { + for (const vector of TRS_FILES_CASES) { + it(vector.name, () => { + expect(findSchemaFile(vector.files)).to.deep.equal(vector.schemaFile); + if (vector.primaryDescriptorPath !== undefined) { + expect(findPrimaryDescriptorPath(vector.files)).to.equal( + vector.primaryDescriptorPath + ); + } + }); + } + }); + + it("finds nothing in an answer that isn't a list", () => { + expect(findSchemaFile({})).to.equal(null); + expect(findPrimaryDescriptorPath("main.wdl")).to.equal(null); + }); +}); + +describe("normalisePath", () => { + it("removes empty and dot segments", () => { + expect(normalisePath("./wdl//main.wdl")).to.equal("wdl/main.wdl"); + expect(normalisePath("/wdl/main.wdl")).to.equal("wdl/main.wdl"); + }); + + it("refuses paths that leave the tool version or are empty", () => { + expect(normalisePath("wdl/../main.wdl")).to.equal(null); + expect(normalisePath("./")).to.equal(null); + expect(normalisePath(3)).to.equal(null); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts index 096b4140..1c9a1304 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/validator.test.ts @@ -2,6 +2,7 @@ import { expect } from "@open-wc/testing"; import { checkIoSchema, + decidingLocations, getIoSchemaValidator, IoSchemaValidator, setIoSchemaValidator, @@ -358,6 +359,57 @@ describe("setIoSchemaValidator", () => { }); }); +describe("decidingLocations and validateAt", () => { + const DOCUMENT = ioSchema( + { + properties: { + n: { anyOf: [{ type: "integer" }, { type: "string" }] }, + list: { type: "array", contains: { const: 1 } }, + rec: { + type: "object", + if: { required: ["a"] }, + then: { oneOf: [{ required: ["b"] }, { required: ["c"] }] }, + }, + embedded: { + $id: "https://example.org/embedded", + anyOf: [{ type: "integer" }, { type: "string" }], + }, + }, + }, + { $defs: { d: { anyOf: [{ type: "null" }, { type: "boolean" }] } } } + ); + + it("lists the branches, if and contains, outside embedded resources", () => { + expect(decidingLocations(DOCUMENT)).to.have.members([ + "/properties/inputs/properties/n/anyOf/0", + "/properties/inputs/properties/n/anyOf/1", + "/properties/inputs/properties/list/contains", + "/properties/inputs/properties/rec/if", + "/properties/inputs/properties/rec/then/oneOf/0", + "/properties/inputs/properties/rec/then/oneOf/1", + "/$defs/d/anyOf/0", + "/$defs/d/anyOf/1", + ]); + }); + + it("validates at those locations and throws elsewhere", async () => { + const result = await checkIoSchema(DOCUMENT); + if (!result.valid) throw new Error(JSON.stringify(result.errors)); + const validateAt = result.validateAt!; + expect(validateAt("/properties/inputs/properties/n/anyOf/0", 3)).to.equal( + true + ); + expect(validateAt("/properties/inputs/properties/n/anyOf/0", "x")).to.equal( + false + ); + expect(validateAt("/$defs/d/anyOf/1", true)).to.equal(true); + expect(() => validateAt("/properties/inputs", {})).to.throw(); + expect(() => + validateAt("/properties/inputs/properties/embedded/anyOf/0", 1) + ).to.throw(); + }); +}); + describe("names with '#'", () => { const nullable = { anyOf: [{ type: "null" }, { type: "integer" }] }; const document = ioSchema( diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts new file mode 100644 index 00000000..76f05856 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts @@ -0,0 +1,182 @@ +/** + * What a client takes from the GA4GH Tool Registry Service (TRS) for a run + * request: the IO schema among the files of a tool version, the path of its + * primary descriptor, and the `workflow_url` of the plain primary + * descriptor (profile version 0.3.0: "Workflow URLs in TRS" of + * `docs/specification/engine-bindings.md`, and "Discovery by clients" of + * `docs/adoption/trs.md`). + */ + +/** The TRS file type of IO schemas that the profile proposes. */ +export const IO_SCHEMA_FILE_TYPE = "IO_SCHEMA"; + +/** The TRS file type of IO schemas on TRS servers without `IO_SCHEMA`. */ +export const OTHER_FILE_TYPE = "OTHER"; + +/** The TRS file type of the primary descriptor. */ +export const PRIMARY_DESCRIPTOR_FILE_TYPE = "PRIMARY_DESCRIPTOR"; + +/** The name of the IO schema file next to the primary descriptor. */ +export const SCHEMA_FILE_NAME = "ga4gh-io.schema.json"; + +/** The entry of the IO schema in the files of a TRS tool version. */ +export interface SchemaFile { + /** The path as listed (not normalised), for `.../descriptor/{path}` */ + path: string; + /** `IO_SCHEMA` or `OTHER` */ + file_type: typeof IO_SCHEMA_FILE_TYPE | typeof OTHER_FILE_TYPE; +} + +const isObject = (value: unknown): value is Record => + typeof value === "object" && value !== null && !Array.isArray(value); + +/** + * Normalises the path of a TRS file entry for comparison: empty and `.` + * segments are removed (`./wdl/main.wdl`, `/wdl/main.wdl` and + * `wdl//main.wdl` all become `wdl/main.wdl`). + * + * @param path - The `path` of a `ToolFile` entry. + * @returns The normalised path, or `null` if it isn't a string, is empty + * after normalisation, or has a `..` segment. + */ +export function normalisePath(path: unknown): string | null { + if (typeof path !== "string") return null; + const segments = path + .split("/") + .filter((segment) => segment !== "" && segment !== "."); + if (segments.length === 0 || segments.includes("..")) return null; + return segments.join("/"); +} + +/** + * Finds the path of the primary descriptor in the files of a tool version, + * for the `workflow_url` (see `trsDescriptorUrl`). + * + * @param files - The answer of `GET .../{type}/files`. + * @returns The normalised path of the first `PRIMARY_DESCRIPTOR` entry with + * a usable path; a path with a leading `/` as listed; or `null`. + */ +export function findPrimaryDescriptorPath(files: unknown): string | null { + if (!Array.isArray(files)) return null; + for (const entry of files) { + if (isObject(entry)) { + const { path } = entry; + const normalised = normalisePath(path); + if ( + entry.file_type === PRIMARY_DESCRIPTOR_FILE_TYPE && + typeof path === "string" && + normalised + ) { + return path.startsWith("/") ? path : normalised; + } + } + } + return null; +} + +/** + * Percent-encodes a path segment: every character but the unreserved ones + * of RFC 3986 (`encodeURIComponent` also keeps `!'()*`). + */ +const encodeSegment = (segment: string) => + encodeURIComponent(segment).replace( + /[!'()*]/g, + (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}` + ); + +const dirname = (path: string) => + path.includes("/") ? path.slice(0, path.lastIndexOf("/")) : ""; + +/** + * Finds the entry of the IO schema in the files of a tool version. + * + * @param files - The answer of `GET .../{type}/files`. + * @returns The one entry of type `IO_SCHEMA`; else, if there is none, the + * one entry of type `OTHER` named `ga4gh-io.schema.json` in the + * directory of the primary descriptors (which must all be in one + * directory); `null` if none or several match (a client doesn't guess). + */ +export function findSchemaFile(files: unknown): SchemaFile | null { + if (!Array.isArray(files)) return null; + const entries: { type: string; normalised: string; path: string }[] = []; + for (const entry of files) { + if (isObject(entry) && typeof entry.file_type === "string") { + const normalised = normalisePath(entry.path); + if (normalised !== null) { + entries.push({ + type: entry.file_type, + normalised, + path: entry.path as string, + }); + } + } + } + const typed = entries.filter((entry) => entry.type === IO_SCHEMA_FILE_TYPE); + if (typed.length > 0) { + return typed.length === 1 + ? { path: typed[0].path, file_type: IO_SCHEMA_FILE_TYPE } + : null; + } + const directories = new Set( + entries + .filter((entry) => entry.type === PRIMARY_DESCRIPTOR_FILE_TYPE) + .map((entry) => dirname(entry.normalised)) + ); + if (directories.size !== 1) return null; + const [directory] = [...directories]; + const expected = directory + ? `${directory}/${SCHEMA_FILE_NAME}` + : SCHEMA_FILE_NAME; + const other = entries.filter( + (entry) => entry.type === OTHER_FILE_TYPE && entry.normalised === expected + ); + return other.length === 1 + ? { path: other[0].path, file_type: OTHER_FILE_TYPE } + : null; +} + +/** + * Builds the TRS URL of the plain primary descriptor of a tool version. + * With the path of the primary descriptor, relative imports of a + * multi-file workflow resolve (RFC 3986) to files that TRS serves under + * `.../descriptor/`; without it, or with a path that starts with `/`, the + * URL has no path, which suits single-file workflows only. + * + * @param trsUrl - Base URL of the TRS API, e.g. + * `https://trs.example.org/ga4gh/trs/v2`. + * @param toolId - Id of the tool. + * @param versionId - Id of the tool version. + * @param descriptorType - TRS descriptor type, e.g. `WDL`. + * @param primaryDescriptorPath - Path of the primary descriptor as TRS + * lists it (see `findPrimaryDescriptorPath`). + * @returns The URL, with the ids, the type and each segment of the path + * percent-encoded. + * @throws If the path is empty, or has empty, `.` or `..` segments. + */ +export function trsDescriptorUrl( + trsUrl: string, + toolId: string, + versionId: string, + descriptorType: string, + primaryDescriptorPath?: string | null +): string { + const url = `${trsUrl.replace(/\/+$/, "")}/tools/${encodeSegment( + toolId + )}/versions/${encodeSegment(versionId)}/PLAIN_${encodeSegment( + descriptorType + )}/descriptor`; + if ( + primaryDescriptorPath === undefined || + primaryDescriptorPath === null || + primaryDescriptorPath.startsWith("/") + ) { + return url; + } + const segments = primaryDescriptorPath.split("/"); + if (segments.some((segment) => ["", ".", ".."].includes(segment))) { + throw new Error( + "The primary descriptor path must be a relative file path without empty, '.' or '..' segments." + ); + } + return `${url}/${segments.map(encodeSegment).join("/")}`; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts index b8482901..915ab454 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts @@ -52,9 +52,28 @@ export type InputsValidator = (values: unknown) => { errors: ValidationError[]; }; +/** + * Whether a value is valid against a subschema of a checked IO schema, + * named by its JSON Pointer in the document. It covers the subschemas whose + * validity decides which schemas apply to a value: the branches of `anyOf` + * and `oneOf`, `if` and `contains`, outside embedded `$id` resources. It + * throws for any other location. + */ +export type SubschemaValidator = (pointer: string, value: unknown) => boolean; + /** The result of checking an IO schema. */ export type IoSchemaCheck = - | { valid: true; errors: []; validateInputs: InputsValidator } + | { + valid: true; + errors: []; + validateInputs: InputsValidator; + /** + * Validity at the subschemas that decide which schemas apply, for the + * request builder (`buildRunRequest`); a validator without it can't + * be used to build run requests + */ + validateAt?: SubschemaValidator; + } | { valid: false; errors: ValidationError[] }; /** A validator of IO schemas and their input values. */ @@ -293,6 +312,49 @@ function otherLocations(document: Record): string[] { return locations; } +/** + * The subschemas whose validity decides which schemas apply to a value (the + * branches of `anyOf` and `oneOf`, `if` and `contains`), outside embedded + * `$id` resources, as JSON Pointers into the document. + */ +export function decidingLocations(document: Record): string[] { + const locations: string[] = []; + const walk = (schema: unknown, path: (string | number)[]): void => { + if (!isObject(schema)) return; + if (path.length > 0 && typeof schema.$id === "string") return; + for (const keyword of ["anyOf", "oneOf"]) { + const branches = schema[keyword]; + if (Array.isArray(branches)) { + branches.forEach((_, i) => + locations.push(toPointer([...path, keyword, i])) + ); + } + } + for (const keyword of ["if", "contains"]) { + if (keyword in schema) locations.push(toPointer([...path, keyword])); + } + for (const keyword of SCHEMA_KEYWORDS) { + if (keyword in schema) walk(schema[keyword], [...path, keyword]); + } + for (const keyword of SCHEMA_ARRAY_KEYWORDS) { + const value = schema[keyword]; + if (Array.isArray(value)) { + value.forEach((item, i) => walk(item, [...path, keyword, i])); + } + } + for (const keyword of SCHEMA_MAP_KEYWORDS) { + const value = schema[keyword]; + if (isObject(value)) { + for (const [key, item] of Object.entries(value)) { + walk(item, [...path, keyword, key]); + } + } + } + }; + walk(document, []); + return locations; +} + /** A JSON Pointer as a URI fragment. */ const fragment = (pointer: string) => `#${pointer @@ -494,7 +556,11 @@ async function checkDocument( } const uriFor = anchorLocations(copy, document, base, embedded); const others = otherLocations(document).map(uriFor); + const decidingUris = decidingLocations(document).map( + (location) => [location, uriFor(location)] as const + ); let compiled: Awaited>; + const deciding = new Map>>(); let registered = false; try { registerSchema(copy as SchemaObject, base); @@ -504,6 +570,10 @@ async function checkDocument( // eslint-disable-next-line no-await-in-loop await validate(uri); } + for (const [location, uri] of decidingUris) { + // eslint-disable-next-line no-await-in-loop + deciding.set(location, await validate(uri)); + } } finally { if (registered) { for (const uri of ids) { @@ -528,7 +598,14 @@ async function checkDocument( errors: toErrors(result.errors, values, valuesLocation), }; }; - return { valid: true, errors: [], validateInputs }; + const validateAt: SubschemaValidator = (pointer, value) => { + const validator = deciding.get(pointer); + if (!validator) { + throw new Error(`No validator for the subschema at ${pointer}.`); + } + return validator(value as never, "FLAG").valid; + }; + return { valid: true, errors: [], validateInputs, validateAt }; } /** Checks run one after the other: hyperjump's registry is global */ diff --git a/packages/ecc-client-ga4gh-wes/src/utils/index.ts b/packages/ecc-client-ga4gh-wes/src/utils/index.ts index a052388c..13ac9084 100644 --- a/packages/ecc-client-ga4gh-wes/src/utils/index.ts +++ b/packages/ecc-client-ga4gh-wes/src/utils/index.ts @@ -1,7 +1,8 @@ /** * Public helpers of the GA4GH IO Schema support (`@elixir-cloud/wes/utils`): - * schema checks and their validator, file reference checks, and how - * descriptions are rendered. + * schema checks and their validator, file reference checks, how + * descriptions are rendered, and run requests from input values (engine + * bindings, TRS workflow URLs, engine profiles). */ export { checkIoSchema, @@ -13,6 +14,7 @@ export type { InputsValidator, IoSchemaCheck, IoSchemaValidator, + SubschemaValidator, ValidationError, } from "../io-schema/validator.js"; export { @@ -26,3 +28,26 @@ export { } from "../io-schema/descriptions.js"; export type { DescriptionFormat } from "../io-schema/descriptions.js"; export { PROFILE_COMMIT, PROFILE_VERSION } from "../io-schema/profile.js"; +export { + buildRunRequest, + getBinding, + toWorkflowParams, + TranslationError, + unsupportedBy, +} from "../io-schema/bindings.js"; +export type { + EngineBinding, + RunRequestOptions, + TranslationOptions, +} from "../io-schema/bindings.js"; +export { + findPrimaryDescriptorPath, + findSchemaFile, + trsDescriptorUrl, +} from "../io-schema/trs.js"; +export type { SchemaFile } from "../io-schema/trs.js"; +export { conquestEngineProfile } from "../io-schema/engine-profiles.js"; +export type { + EngineProfile, + EngineProfileContext, +} from "../io-schema/engine-profiles.js";