diff --git a/.changeset/wes-run-outputs.md b/.changeset/wes-run-outputs.md new file mode 100644 index 00000000..ed6ae4aa --- /dev/null +++ b/.changeset/wes-run-outputs.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/wes": minor +--- + +Show run outputs with GA4GH IO Schema hints: `ecc-client-ga4gh-wes-run` gains `ioSchema`, `outputOptions`, `outputProvider` and `allowedSchemes`; with a schema, its Outputs tab shows the normalised outputs of a run that has ended through `ecc-client-ga4gh-wes-run-output` (titles, descriptions, viewers, downloads), with warnings for partial and non-conformant outputs and the normaliser's reports; without one, the raw outputs stay. `@elixir-cloud/wes/utils` exports the output normaliser (`normaliseOutputs`, `NormalisationError`, `FINAL_STATES`). `IoSchemaCheck` gains an optional `validateOutputs` (`OutputsValidator`): a validator set with `setIoSchemaValidator()` needs it for the normaliser. diff --git a/apps/documentation/components/packages/wes/RunSchemaOutputsPreview.tsx b/apps/documentation/components/packages/wes/RunSchemaOutputsPreview.tsx new file mode 100644 index 00000000..ddc87202 --- /dev/null +++ b/apps/documentation/components/packages/wes/RunSchemaOutputsPreview.tsx @@ -0,0 +1,122 @@ +import React, { useMemo, useState } from 'react'; +import { ECCClientGa4ghWesRun } from '@elixir-cloud/wes/react'; +import type { RunLog, WesProvider } from '@elixir-cloud/wes/providers'; +import PreviewLayout from '@/components/common/PreviewLayout'; +import { ioFormExamples } from '@/components/packages/wes/ioFormExamples'; +import { + DEMO_RUN, + exampleOutputProvider, +} from '@/components/packages/wes/runOutputExample'; + +const allowedSchemes = ['drs', 'https', 's3']; + +/** The output directory of the demo run, as miniwdl sees it (made up). */ +const LOCAL_DIR = '/data/miniwdl-runs/20261113_021212_io_schema_demo/out'; + +/** Outputs of the demo workflow as miniwdl reports them: local paths. */ +const reported: Record = { + 'io_schema_demo.report': `${LOCAL_DIR}/report/report.html`, + 'io_schema_demo.read_counts': `${LOCAL_DIR}/read_counts/read_counts.tsv`, + 'io_schema_demo.filtered_bam': `${LOCAL_DIR}/filtered_bam/filtered.bam`, + 'io_schema_demo.filtered_bam_index': `${LOCAL_DIR}/filtered_bam_index/filtered.bam.bai`, +}; + +const runs: Record = { + complete: { + label: 'Completed run', + log: { + run_id: 'demo-complete', + state: 'COMPLETE', + outputs: reported, + } as unknown as RunLog, + }, + failed: { + label: 'Failed run (partial outputs)', + log: { + run_id: 'demo-failed', + state: 'EXECUTOR_ERROR', + outputs: { + 'io_schema_demo.report': reported['io_schema_demo.report'], + 'io_schema_demo.read_counts': reported['io_schema_demo.read_counts'], + }, + } as unknown as RunLog, + }, +}; + +/** A provider that returns one made-up run of the demo workflow. */ +class DemoRunProvider implements WesProvider { + private log: RunLog; + + constructor(log: RunLog) { + this.log = { + ...log, + request: { + workflow_type: 'WDL', + workflow_type_version: '1.1', + workflow_url: 'https://example.org/demo.wdl', + workflow_params: {}, + }, + run_log: {}, + task_logs: [], + } as unknown as RunLog; + } + + async getRunLog() { + return this.log; + } + + async getServiceInfo(): Promise { + throw new Error('Not available in the demo.'); + } + + async runWorkflow(): Promise { + throw new Error('Not available in the demo.'); + } + + async listRuns() { + return { runs: [] }; + } + + async getRunStatus(): Promise { + throw new Error('Not available in the demo.'); + } + + async cancelRun(): Promise { + throw new Error('Not available in the demo.'); + } +} + +export default function RunSchemaOutputsPreview() { + const [run, setRun] = useState('complete'); + const provider = useMemo(() => new DemoRunProvider(runs[run].log), [run]); + + return ( + +
+ + +
+
+ ); +} diff --git a/apps/documentation/components/packages/wes/runOutputExample.ts b/apps/documentation/components/packages/wes/runOutputExample.ts index e547393a..931a8e3d 100644 --- a/apps/documentation/components/packages/wes/runOutputExample.ts +++ b/apps/documentation/components/packages/wes/runOutputExample.ts @@ -11,7 +11,7 @@ import { withBasePath } from '@/utils/basePath'; export const PROFILE_COMMIT = '2c3dc49ad89f0a556272f160369a2a2d7a21dac3'; -const DEMO_RUN = +export const DEMO_RUN = 's3://conquest/v1/workflow-runs/9f1c2e4a-5b6d-4e7f-8a9b-0c1d2e3f4a5b/outputs/files/miniwdl-runs/20261113_021212_io_schema_demo/out'; /** Schemas of the outputs (the `properties` of `outputs`). */ diff --git a/apps/documentation/pages/docs/wes/components/run.mdx b/apps/documentation/pages/docs/wes/components/run.mdx index 0196f772..367fbf1c 100644 --- a/apps/documentation/pages/docs/wes/components/run.mdx +++ b/apps/documentation/pages/docs/wes/components/run.mdx @@ -1,6 +1,7 @@ import { Callout, Tabs } from 'nextra/components' import ComponentName from '@/components/common/ComponentName' import RunPreview from '@/components/packages/wes/RunPreview' +import RunSchemaOutputsPreview from '@/components/packages/wes/RunSchemaOutputsPreview' # EccClientGa4ghWesRun Component @@ -77,12 +78,74 @@ This example shows the details for a specific workflow run ID. +### Outputs with an IO schema + +Without an IO schema, the Outputs tab shows `RunLog.outputs` as the server reports it. With the workflow's [IO schema](../io-schema) (`ioSchema`), it shows the [normalised outputs](../io-schema#run-outputs) of a run that has ended: each output by its title and description, with its viewer hint (a table, an HTML report in a sandboxed frame) and download, as [`ecc-client-ga4gh-wes-run-output`](./run-output) shows it. Only URIs with a scheme from `allowedSchemes` are fetched or offered for download, through `outputProvider`. + +- While the run hasn't ended, the tab says that outputs are shown when it has (without the raw outputs). +- Outputs of a run that didn't complete are shown with a warning that they may be incomplete; invalid ones are left out and named. +- Outputs that don't match the schema are kept, with a warning and the errors. +- Outputs that the engine reports but the schema doesn't declare, and listed files that no output found ("Other files"), are shown without a description; outputs that weren't produced are named. +- Outputs that can't be converted (e.g. files that can't be located, or values nested too deeply), globs that match several files, and listed files with unsafe paths are named in notices. +- If the outputs can't be normalised (e.g. an unsupported shape, or a schema that doesn't conform to the profile), the tab says why and shows them as reported. + +Where the server keeps the run's files is deployment knowledge: `outputOptions` gives it (`outputDir`, `localDir`, `files`), or a function of the run log that returns it, also as a promise (e.g. to fetch a listing). The outputs are normalised again whenever `ioSchema` or `outputOptions` changes, so pass the same object or function between renders (in React, define it outside the component or memoise it). The normaliser and the output element are loaded when they are first needed. + +This preview uses a provider that returns a run of the profile's demo workflow (WDL), as miniwdl reports it (local paths), from a completed or a failed run: + + + + + + + + ```tsx showLineNumbers copy filename="run-outputs.tsx" + import React from 'react'; + import { ECCClientGa4ghWesRun } from '@elixir-cloud/wes/react'; + import { RestWesProvider } from '@elixir-cloud/wes/providers'; + import type { RunLog, WesOutputProvider } from '@elixir-cloud/wes/providers'; + + // Defined once, so that the outputs aren't normalised on every render + const outputOptions = (runLog: RunLog) => ({ + outputDir: `s3://bucket/runs/${runLog.run_id}`, + }); + + export default function RunOutputs({ + schema, + outputProvider, + }: { + schema: object; + outputProvider: WesOutputProvider; + }) { + const provider = new RestWesProvider( + 'https://wes.example.com/ga4gh/wes/v1' + ); + + return ( + + ); + } + ``` + + + ## Properties -| Property | Type | Default | Description | -|------------|---------------------------|---------|--------------------------------------------------------------------------------| -| `runId` | `string` | `""` | ID of the workflow run to display details for. | -| `provider` | `WesProvider` | `null` | Data provider for fetching run data (see [Providers](/docs/wes/providers)) | +| Property | Type | Default | Description | +|------------------|---------------------------|-------------|--------------------------------------------------------------------------------| +| `runId` | `string` | `""` | ID of the workflow run to display details for. | +| `provider` | `WesProvider` | `null` | Data provider for fetching run data (see [Providers](/docs/wes/providers)) | +| `ioSchema` | `object` | `undefined` | The workflow's IO schema (GA4GH IO Schema Profile 0.3.0); shows the normalised outputs | +| `outputOptions` | `OutputOptions \| (runLog) => OutputOptions \| Promise` | `undefined` | Where the run keeps its files: `outputDir` (URI), `localDir` (path as the engine sees it), `files` (a listing) | +| `outputProvider` | `WesOutputProvider` | `undefined` | Fetches output files for viewers and returns download URLs (see [Run Output](./run-output)) | +| `allowedSchemes` | `string[]` | `['drs', 'https']` | URI schemes of outputs that may be fetched or downloaded | ## Events diff --git a/apps/documentation/pages/docs/wes/io-schema.mdx b/apps/documentation/pages/docs/wes/io-schema.mdx index 5d097214..63b799b5 100644 --- a/apps/documentation/pages/docs/wes/io-schema.mdx +++ b/apps/documentation/pages/docs/wes/io-schema.mdx @@ -75,6 +75,29 @@ const request = await buildRunRequest(schema, values, { 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. +## Run outputs + +`normaliseOutputs()` from `@elixir-cloud/wes/utils` builds the [normalised outputs object](https://ga4gh-io-schema.readthedocs.io/en/latest/specification/outputs/#the-normalised-outputs-object) of a WES run from what the server reports, keyed by the outputs of an IO schema, which [`ecc-client-ga4gh-wes-run`](./components/run#outputs-with-an-io-schema) shows: + +```typescript +import { normaliseOutputs } from '@elixir-cloud/wes/utils'; + +const result = await normaliseOutputs(schema, runLog, { + outputDir: 's3://bucket/runs/7', // where the server keeps the run's files + localDir: '/data/runs/7/out', // the same directory as the engine sees it +}); +// result.conformance: 'conformant' | 'non-conformant' | 'partial' +// result.outputs: { report: 's3://bucket/runs/7/report/report.html', ... } +``` + +- Outputs are found **by name** (the property name, or `name` of `x-ga4gh-parameter`, qualified with the entry point for WDL), else **by `x-ga4gh-output-glob`** among the files that the server lists: Sapporo's list of files, WESkit's `filesystem`, or `files` of the options. CWL `File` and `Directory` objects give their `location`; paths under `localDir`, and relative paths, become URIs under `outputDir` (each segment percent-encoded); other paths are reported as `unconverted`. +- Listed entries are checked before globs are matched: absolute paths, `.`, `..` and empty segments, backslashes, control characters, a colon in the first segment, URIs outside `outputDir`, with a query or fragment, or with an encoded `/` are skipped and reported (`skippedFiles`, without user information, query and fragment, which may carry credentials). WESkit's presigned URLs (`S3`) are dropped. +- The object is validated against `outputs` for a run that completed (`non-conformant` outputs are kept as they are, with `errors`); for a run that ended otherwise, output by output, and invalid outputs are left out (`removed`). File references must be absolute URIs with one of their `schemes`. +- Outputs that the schema doesn't declare (`undeclared`), files that no output found (`unmatchedFiles`) and globs of one file with several matches (`ambiguous`) are reported, never dropped silently. +- A run that hasn't ended, a run log of an unsupported shape and inconsistent options raise a `NormalisationError` (with `schemaErrors` for a schema that doesn't conform to the profile). + +The normaliser never fetches anything, and it doesn't check output URIs against the deployment's allow-list: [`ecc-client-ga4gh-wes-run-output`](./components/run-output) does that before it shows or fetches a file. It passes the profile's test vectors (`tests/vectors/wes-outputs`) and needs a validator that validates outputs (`validateOutputs` of the check result). Unlike the reference implementation, it checks the `schemes` of file references only in the shapes that values are converted by (files, lists, records, files keyed by name, a single branch besides `null`, `allOf`), not inside other unions. It doesn't follow references into embedded `$id` resources (the value is then kept as reported, for validation to report), and refuses values nested more than 64 levels deep (`unconverted`). + ## 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 c600edfc..15bf5a93 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,9 @@ * - `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 (file reference values, engine bindings, workflow URLs and TRS - * files) and the example schemas, for the tests and the demos. + * vectors (file reference values, engine bindings, workflow URLs, TRS + * files and outputs of runs) and the example schemas, for the tests and + * the demos. * * Usage, from the package directory: * @@ -173,6 +174,59 @@ export const WES_PARAMS_CASES: WesParamsCase[] = ${json( ` ); +/** + * The cases of `tests/vectors///`, each with its JSON files by + * name (without `.json`), sorted by name. + */ +const flatCaseDirectories = (kind) => + readdirSync(path.join(checkout, "tests", "vectors", kind), { + withFileTypes: true, + }) + .filter((entry) => entry.isDirectory()) + .map((entry) => entry.name) + .sort() + .map((name) => { + const files = {}; + const at = ["tests", "vectors", kind, name]; + for (const file of readdirSync(path.join(checkout, ...at)) + .filter((entry) => entry.endsWith(".json")) + .sort()) { + files[file.replace(/\.json$/, "")] = readJson(...at, file); + } + return { name, ...files }; + }); + +write( + "src/io-schema/tests/fixtures/wes-outputs.ts", + `${header( + "Test vectors of the output normaliser (`tests/vectors/wes-outputs/`)." + )} +export interface WesOutputsCase { + name: string; + schema: Record; + run_log: Record; + options?: { outputDir?: string; localDir?: string; files?: unknown[] }; + /** The expected result, or else \`error\` */ + expected?: { + description: string; + conformance: string; + outputs: Record; + removed?: string[]; + ambiguous?: Record; + unconverted?: string[]; + undeclared?: string[]; + unmatchedFiles?: string[]; + skippedFiles?: unknown[]; + }; + error?: Record; +} + +export const WES_OUTPUTS_CASES: WesOutputsCase[] = ${json( + flatCaseDirectories("wes-outputs") + )}; +` +); + write( "src/io-schema/tests/fixtures/trs.ts", `${header( diff --git a/packages/ecc-client-ga4gh-wes/src/components/run/run.ts b/packages/ecc-client-ga4gh-wes/src/components/run/run.ts index 27daa6ec..0ca3c84c 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/run/run.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/run/run.ts @@ -1,4 +1,4 @@ -import { LitElement, html, css } from "lit"; +import { LitElement, html, css, nothing, PropertyValues } from "lit"; import { property, state } from "lit/decorators.js"; import { ComponentStyles as TailwindStyles } from "./tw-styles.js"; import { GlobalStyles } from "../../global.js"; @@ -10,6 +10,13 @@ import { } from "../../providers/wes-provider.js"; import type { EccRunLogChangedEvent } from "../../events/ecc-run-log-changed.js"; import { RestWesProvider } from "../../providers/rest-wes-provider.js"; +import type { WesOutputProvider } from "../../providers/wes-output-provider.js"; +import type { + NormalisedOutputs, + OutputOptions, +} from "../../io-schema/outputs.js"; +import { FINAL_STATES } from "../../io-schema/states.js"; +import { DEFAULT_ALLOWED_SCHEMES } from "../../io-schema/files.js"; import "@elixir-cloud/design/components/table/index.js"; import "@elixir-cloud/design/components/button/index.js"; import "@elixir-cloud/design/components/badge/index.js"; @@ -27,6 +34,21 @@ import "@elixir-cloud/design/components/collapsible/index.js"; * @property {string} baseUrl - Base URL of the WES instance. * @property {string} runId - The ID of the workflow run to display. * @property {WesProvider} provider - Custom data provider (optional, overrides baseUrl). + * @property {unknown} ioSchema - The workflow's GA4GH IO Schema (optional). + * With it, the Outputs tab shows the normalised outputs of a run that has + * ended, each by its title, description and viewer hint; without it, the + * raw `RunLog.outputs`. + * @property {OutputOptions | Function} outputOptions - What the deployment + * knows about where the run keeps its files (`outputDir`, `localDir`, + * `files`), or a function of the run log that returns it (also as a + * promise), for the output normaliser (optional). Outputs are + * normalised again when it changes: pass the same object or function + * between renders (e.g. memoised in React). + * @property {WesOutputProvider} outputProvider - Fetches output files for + * viewers and returns download URLs (optional; without it, URIs only). + * @property {string[]} allowedSchemes - URI schemes of outputs that may be + * fetched or downloaded (optional; the default of + * `ecc-client-ga4gh-wes-run-output` otherwise). * * @fires ecc-run-log-changed - Fired when run-log data loads; detail.runLog contains the RunLog. */ @@ -45,6 +67,23 @@ export class ECCClientGa4ghWesRun extends LitElement { @property({ type: String, reflect: true }) baseUrl = ""; @property({ type: String, reflect: true }) runId = ""; @property({ attribute: false }) provider?: WesProvider; + @property({ attribute: false }) ioSchema?: unknown; + @property({ attribute: false }) outputOptions?: + | OutputOptions + | ((runLog: RunLog) => OutputOptions | Promise); + + @property({ attribute: false }) outputProvider?: WesOutputProvider; + @property({ attribute: false }) allowedSchemes?: string[]; + + /** The normalised outputs of the run, with the schema */ + @state() private normalised?: NormalisedOutputs; + /** The output schemas of `ioSchema`, by name, as the normaliser read them */ + private declaredOutputs: Record = {}; + @state() private normalising = false; + @state() private outputsError?: string; + + /** Number of the latest normalisation, to drop results of older ones */ + private normalisations = 0; @state() private run: RunLog | null = null; @state() private loading = false; @@ -71,6 +110,60 @@ export class ECCClientGa4ghWesRun extends LitElement { } } + protected willUpdate(changed: PropertyValues): void { + if ( + changed.has("run" as keyof ECCClientGa4ghWesRun) || + changed.has("ioSchema") || + changed.has("outputOptions") + ) { + this.updateOutputs(); + } + } + + /** + * Normalises the outputs of the run with the IO schema, if both are set + * and the run has ended. The normaliser and the output element are + * loaded on demand, so pages without a schema don't load the validator. + */ + private async updateOutputs(): Promise { + this.normalisations += 1; + const request = this.normalisations; + const { run, ioSchema, outputOptions } = this; + this.normalised = undefined; + this.outputsError = undefined; + this.normalising = false; + if (!run || !ioSchema || !FINAL_STATES.includes(run.state)) return; + this.normalising = true; + const current = () => request === this.normalisations; + try { + const [{ displaySchema, normaliseOutputs, outputProperties }] = + await Promise.all([ + import("../../io-schema/outputs.js"), + import("../run-output/index.js"), + ]); + const options = + typeof outputOptions === "function" + ? await outputOptions(run) + : outputOptions ?? {}; + const result = await normaliseOutputs(ioSchema, run, options); + if (current()) { + this.declaredOutputs = Object.fromEntries( + Object.entries(outputProperties(ioSchema)).map(([name, schema]) => [ + name, + displaySchema(ioSchema, schema), + ]) + ); + this.normalised = result; + } + } catch (err) { + if (current()) { + this.outputsError = err instanceof Error ? err.message : String(err); + } + } finally { + if (current()) this.normalising = false; + } + } + protected updated(changedProperties: Map): void { // Handle provider changes if (changedProperties.has("provider")) { @@ -689,7 +782,202 @@ export class ECCClientGa4ghWesRun extends LitElement { `; } + private renderRawOutputs() { + return html` + + `; + } + + private static renderNotice( + kind: string, + text: unknown, + destructive = false + ) { + return html`
+ ${text} +
`; + } + + /** One output, as `ecc-client-ga4gh-wes-run-output` shows it. */ + private renderOutput(name: string, schema: unknown, value: unknown) { + return html`} + .value=${value} + .provider=${this.outputProvider} + .allowedSchemes=${this.allowedSchemes ?? [...DEFAULT_ALLOWED_SCHEMES]} + >`; + } + + /** The reports of the normaliser that the user should know about. */ + private static renderReports(result: NormalisedOutputs) { + const notices: unknown[] = []; + const list = (items: string[]) => items.join(", "); + if (result.conformance === "partial") { + notices.push( + ECCClientGa4ghWesRun.renderNotice( + "partial", + `The run didn't complete (${result.state}): these outputs were produced, and may be incomplete.`, + true + ) + ); + } + if (result.conformance === "non-conformant") { + notices.push( + ECCClientGa4ghWesRun.renderNotice( + "non-conformant", + html`The outputs don't match the workflow's schema: +
    + ${result.errors.map( + (error) => + html`
  • + ${error.pointer || "/"}: ${error.message} +
  • ` + )} +
`, + true + ) + ); + } + const removed = Object.keys(result.removed); + if (removed.length) { + notices.push( + ECCClientGa4ghWesRun.renderNotice( + "removed", + `Left out, as their values are invalid: ${list(removed)}.` + ) + ); + } + const ambiguous = Object.entries(result.ambiguous); + if (ambiguous.length) { + notices.push( + ECCClientGa4ghWesRun.renderNotice( + "ambiguous", + `Not shown, as several files match: ${list( + ambiguous.map(([name, uris]) => `${name} (${uris.length} files)`) + )}.` + ) + ); + } + if (result.unconverted.length) { + notices.push( + ECCClientGa4ghWesRun.renderNotice( + "unconverted", + `Not shown, as they can't be converted: ${list( + result.unconverted.map( + ({ output, reason }) => `${output} (${reason})` + ) + )}.` + ) + ); + } + if (result.skippedFiles.length) { + const count = result.skippedFiles.length; + notices.push( + ECCClientGa4ghWesRun.renderNotice( + "skipped", + `${count} listed ${ + count === 1 ? "file was" : "files were" + } skipped, as their paths aren't safe.` + ) + ); + } + return notices; + } + + /** The Outputs tab with the IO schema. */ + private renderSchemaOutputs() { + if (!this.run) return nothing; + if (!FINAL_STATES.includes(this.run.state)) { + return ECCClientGa4ghWesRun.renderNotice( + "running", + "Outputs are shown when the run has ended." + ); + } + if (this.outputsError !== undefined) { + return html`
+ ${ECCClientGa4ghWesRun.renderNotice( + "error", + `The outputs can't be shown by the workflow's schema: ${this.outputsError} They are shown as reported.`, + true + )} + ${this.renderRawOutputs()} +
`; + } + const result = this.normalised; + if (this.normalising || !result) { + return html``; + } + const declared = this.declaredOutputs; + const present = Object.keys(declared).filter((name) => + Object.prototype.hasOwnProperty.call(result.outputs, name) + ); + const absent = Object.keys(declared).filter( + (name) => + !present.includes(name) && + !Object.prototype.hasOwnProperty.call(result.removed, name) && + !Object.prototype.hasOwnProperty.call(result.ambiguous, name) && + !result.unconverted.some(({ output }) => output === name) + ); + const undeclared = Object.entries(result.undeclared); + const empty = + present.length === 0 && + undeclared.length === 0 && + result.unmatchedFiles.length === 0; + return html`
+ ${ECCClientGa4ghWesRun.renderReports(result)} +
+ ${present.map((name) => + this.renderOutput(name, declared[name], result.outputs[name]) + )} + ${undeclared.map(([name, value]) => + // Without a description, and never as links: engine values + this.renderOutput(name, { title: name }, value) + )} + ${result.unmatchedFiles.length + ? this.renderOutput( + "other-files", + { + type: "array", + title: "Other files", + description: "Files of the run that no output describes.", + items: { type: "string", "x-ga4gh-file": { kind: "file" } }, + }, + result.unmatchedFiles + ) + : nothing} +
+ ${empty + ? html`

+ No outputs. +

` + : nothing} + ${absent.length + ? html`

+ Not produced: ${absent.join(", ")}. +

` + : nothing} +
`; + } + private renderOutputsTab() { + if (this.ioSchema && this.run) { + return html`
${this.renderSchemaOutputs()}
`; + } if (!this.run || !this.run.outputs) { return html`
@@ -701,16 +989,7 @@ export class ECCClientGa4ghWesRun extends LitElement {
`; } - return html` -
- -
- `; + return html`
${this.renderRawOutputs()}
`; } private hasTaskLogs(): boolean { diff --git a/packages/ecc-client-ga4gh-wes/src/components/run/tests/run.test.ts b/packages/ecc-client-ga4gh-wes/src/components/run/tests/run.test.ts new file mode 100644 index 00000000..3845cbc5 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/components/run/tests/run.test.ts @@ -0,0 +1,362 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect, fixture, html, waitUntil } from "@open-wc/testing"; +import "../index.js"; +import type { ECCClientGa4ghWesRun } from "../run.js"; +import type { RunLog, WesProvider } from "../../../providers/wes-provider.js"; +import type { ECCClientGa4ghWesRunOutput } from "../../run-output/run-output.js"; +import { PROFILE_ID } from "../../../io-schema/validator.js"; + +const FILE = { type: "string", "x-ga4gh-file": { kind: "file" } }; + +const SCHEMA = { + $schema: PROFILE_ID, + "x-ga4gh-workflow": { descriptor_type: "WDL", entry_point: "demo" }, + type: "object", + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { + report: { + ...FILE, + title: "Report", + "x-ga4gh-ui-widget": "html-viewer", + }, + counts: { type: "integer", title: "Counts" }, + bam: { ...FILE, title: "Reads" }, + }, + required: ["report"], + }, + }, +}; + +const OUTPUT_DIR = "s3://bucket/runs/7"; + +/** A run log with the given state and outputs. */ +const runLog = (state: string, outputs: unknown): RunLog => + ({ + run_id: "run-7", + state, + outputs, + request: { + workflow_type: "WDL", + workflow_type_version: "1.1", + workflow_url: "https://example.org/demo.wdl", + workflow_params: {}, + }, + run_log: {}, + task_logs: [], + } as unknown as RunLog); + +/** A provider that returns one run log. */ +class FakeProvider implements WesProvider { + private readonly log: RunLog; + + constructor(log: RunLog) { + this.log = log; + } + + async getRunLog() { + return this.log; + } + + // eslint-disable-next-line class-methods-use-this + async getServiceInfo(): Promise { + throw new Error("not used"); + } + + // eslint-disable-next-line class-methods-use-this + async runWorkflow(): Promise { + throw new Error("not used"); + } + + // eslint-disable-next-line class-methods-use-this + async listRuns() { + return { runs: [] }; + } + + // 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"); + } +} + +async function render( + log: RunLog, + properties: Partial = {} +): Promise { + const el = await fixture( + html`` + ); + await waitUntil( + () => + el.shadowRoot?.querySelector( + "[data-outputs], [data-notice], [data-raw-outputs], [data-loading]" + ), + "the outputs weren't shown", + { timeout: 5000 } + ); + return el; +} + +const shown = (el: ECCClientGa4ghWesRun) => + [ + ...(el.shadowRoot?.querySelectorAll( + "ecc-client-ga4gh-wes-run-output" + ) ?? []), + ].map((output) => ({ name: output.name, value: output.value })); + +const notice = (el: ECCClientGa4ghWesRun, kind: string) => + el.shadowRoot?.querySelector(`[data-notice="${kind}"]`); + +describe("ecc-client-ga4gh-wes-run outputs", () => { + it("shows the raw outputs without a schema", async () => { + const el = await render( + runLog("COMPLETE", { "demo.report": "/work/out/r.html" }) + ); + const raw = el.shadowRoot?.querySelector("[data-raw-outputs]"); + expect(raw?.getAttribute("value")).to.contain("demo.report"); + expect(shown(el)).to.deep.equal([]); + }); + + it("shows the normalised outputs in the schema's order", async () => { + let given: RunLog | undefined; + const el = await render( + runLog("COMPLETE", { + "demo.counts": 3, + "demo.report": "/work/out/report/r.html", + "demo.bam": null, + }), + { + ioSchema: SCHEMA, + outputOptions: async (log: RunLog) => { + given = log; + return { outputDir: OUTPUT_DIR, localDir: "/work/out" }; + }, + } + ); + await waitUntil(() => shown(el).length > 0); + expect(given?.run_id).to.equal("run-7"); + expect(shown(el)).to.deep.equal([ + { name: "report", value: `${OUTPUT_DIR}/report/r.html` }, + { name: "counts", value: 3 }, + ]); + expect( + el.shadowRoot?.querySelector("[data-absent]")?.textContent + ).to.contain("bam"); + expect(notice(el, "partial")).to.equal(null); + expect(notice(el, "non-conformant")).to.equal(null); + }); + + it("passes the schema and the allowed schemes to each output", async () => { + const el = await render( + runLog("COMPLETE", { "demo.report": `${OUTPUT_DIR}/r.html` }), + { ioSchema: SCHEMA, allowedSchemes: ["s3"] } + ); + await waitUntil(() => shown(el).length > 0); + const output = el.shadowRoot?.querySelector( + "ecc-client-ga4gh-wes-run-output" + ); + expect(output?.schema?.title).to.equal("Report"); + expect(output?.allowedSchemes).to.deep.equal(["s3"]); + }); + + it("shows outputs declared by reference as files", async () => { + const el = await render( + runLog("COMPLETE", { + "demo.chunks": [`${OUTPUT_DIR}/c1.txt`, `${OUTPUT_DIR}/c2.txt`], + }), + { + ioSchema: { + ...SCHEMA, + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { chunks: { $ref: "#/$defs/list" } }, + }, + }, + $defs: { + list: { + type: "array", + title: "Chunks", + items: { $ref: "#/$defs/f" }, + }, + f: FILE, + }, + }, + } + ); + await waitUntil(() => shown(el).length > 0); + const output = el.shadowRoot?.querySelector( + "ecc-client-ga4gh-wes-run-output" + ); + expect(output?.schema).to.deep.equal({ + type: "array", + title: "Chunks", + items: FILE, + }); + await waitUntil( + () => output?.shadowRoot?.querySelectorAll("[data-entry]").length === 2 + ); + }); + + it("passes the default allowed schemes when none are set", async () => { + const el = await render( + runLog("COMPLETE", { "demo.report": `${OUTPUT_DIR}/r.html` }), + { ioSchema: SCHEMA } + ); + await waitUntil(() => shown(el).length > 0); + const output = el.shadowRoot?.querySelector( + "ecc-client-ga4gh-wes-run-output" + ); + expect(output?.allowedSchemes).to.deep.equal(["drs", "https"]); + }); + + it("warns about the outputs of a run that didn't complete", async () => { + const el = await render( + runLog("EXECUTOR_ERROR", { "demo.report": 42, "demo.counts": 1 }), + { ioSchema: SCHEMA } + ); + await waitUntil(() => notice(el, "partial")); + expect(notice(el, "partial")?.textContent).to.contain("EXECUTOR_ERROR"); + expect(notice(el, "removed")?.textContent).to.contain("report"); + expect(shown(el)).to.deep.equal([{ name: "counts", value: 1 }]); + }); + + it("lists the errors of non-conformant outputs and keeps them", async () => { + const el = await render(runLog("COMPLETE", { "demo.counts": "many" }), { + ioSchema: SCHEMA, + }); + await waitUntil(() => notice(el, "non-conformant")); + const errors = el.shadowRoot?.querySelectorAll("[data-errors] li"); + expect(errors?.length).to.be.at.least(2); + expect(shown(el)).to.deep.equal([{ name: "counts", value: "many" }]); + }); + + it("shows undeclared outputs and unmatched files without descriptions", async () => { + const el = await render( + runLog("COMPLETE", ["report/r.html", "logs/x.log"]), + { + ioSchema: { + ...SCHEMA, + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { + report: { ...FILE, "x-ga4gh-output-glob": "report/*.html" }, + }, + }, + }, + }, + outputOptions: { outputDir: OUTPUT_DIR }, + } + ); + await waitUntil(() => shown(el).length > 1); + expect(shown(el)).to.deep.equal([ + { name: "report", value: `${OUTPUT_DIR}/report/r.html` }, + { name: "other-files", value: [`${OUTPUT_DIR}/logs/x.log`] }, + ]); + }); + + it("reports ambiguous, unconverted and skipped outputs", async () => { + const el = await render( + runLog("COMPLETE", ["a/1.bam", "a/2.bam", "../x.bam"]), + { + ioSchema: { + ...SCHEMA, + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { + bam: { ...FILE, "x-ga4gh-output-glob": "a/*.bam" }, + }, + }, + }, + }, + outputOptions: { outputDir: OUTPUT_DIR }, + } + ); + await waitUntil(() => notice(el, "ambiguous")); + expect(notice(el, "ambiguous")?.textContent).to.contain("bam (2 files)"); + expect(notice(el, "skipped")?.textContent).to.contain("1 listed file was"); + + const other = await render( + runLog("COMPLETE", { "demo.report": "/elsewhere/r.html", x: 1 }), + { ioSchema: SCHEMA, outputOptions: { outputDir: OUTPUT_DIR } } + ); + await waitUntil(() => notice(other, "unconverted")); + expect(notice(other, "unconverted")?.textContent).to.contain("report"); + expect(shown(other)).to.deep.equal([{ name: "x", value: 1 }]); + }); + + it("waits for the run to end", async () => { + const el = await render(runLog("RUNNING", {}), { ioSchema: SCHEMA }); + expect(notice(el, "running")).to.not.equal(null); + expect(shown(el)).to.deep.equal([]); + }); + + it("falls back to the raw outputs if they can't be normalised", async () => { + const el = await render(runLog("COMPLETE", "not outputs"), { + ioSchema: SCHEMA, + }); + await waitUntil(() => notice(el, "error")); + expect(el.shadowRoot?.querySelector("[data-raw-outputs]")).to.not.equal( + null + ); + + const invalid = await render(runLog("COMPLETE", {}), { + ioSchema: { $schema: PROFILE_ID, type: "array" }, + }); + await waitUntil(() => notice(invalid, "error")); + expect(notice(invalid, "error")?.textContent).to.contain("profile"); + }); + + it("says when a run has no outputs", async () => { + const el = await render(runLog("COMPLETE", null), { + ioSchema: { + ...SCHEMA, + properties: { + inputs: { type: "object" }, + outputs: { type: "object", properties: {} }, + }, + }, + }); + await waitUntil(() => el.shadowRoot?.querySelector("[data-empty]")); + }); + + it("drops the result of an older normalisation", async () => { + let release: ((options: Record) => void) | undefined; + const el = await render(runLog("COMPLETE", { "demo.counts": 1 }), { + ioSchema: SCHEMA, + outputOptions: () => + new Promise((resolve) => { + release = resolve; + }), + }); + const slow = release as + | ((options: Record) => void) + | undefined; + el.outputOptions = {}; + await waitUntil(() => shown(el).length > 0); + slow?.({ outputDir: "nonsense" }); + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + expect(notice(el, "error")).to.equal(null); + expect(shown(el)).to.deep.equal([{ name: "counts", value: 1 }]); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/outputs.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/outputs.ts new file mode 100644 index 00000000..672f1797 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/outputs.ts @@ -0,0 +1,1039 @@ +/** + * The output normaliser of the GA4GH IO Schema Profile (profile version + * 0.3.0, `docs/specification/outputs.md`): what a WES server reports for a + * run (`RunLog.outputs`, and the files of the run if it lists them) becomes + * the *normalised outputs object* of the run, keyed by the outputs of an IO + * schema. Outputs are found by name first and otherwise by + * `x-ga4gh-output-glob` among the listed files; the object is validated + * against `outputs` (for a run that completed) or output by output (for a + * run that didn't); everything that doesn't fit is reported, never dropped + * silently. + * + * It follows the reference implementation of the profile + * (`ga4gh_io_schema.outputs`) and passes its language-neutral test vectors + * (`tests/vectors/wes-outputs/`). It never fetches anything: not the files + * of the run, not the URIs of outputs, and not references of the schema. + */ +import { + fragmentPointer, + parsePointer, + toPointer, + valueAt, +} from "./pointer.js"; +import { FINAL_STATES } from "./states.js"; +import { encodeSegment } from "./trs.js"; +import { checkIoSchema } from "./validator.js"; +import type { OutputsValidator, ValidationError } from "./validator.js"; + +/** Conformance of the outputs of a run (see `NormalisedOutputs`). */ +export type Conformance = "conformant" | "non-conformant" | "partial"; + +/** What the deployment gives the normaliser about a run. */ +export interface OutputOptions { + /** + * URI of the output directory of the run: the URI prefix under which the + * server keeps its files (a trailing `/` is removed). Needed to match + * globs against a listing, and to turn paths into URIs. + */ + outputDir?: string; + /** + * Absolute local path of the output directory, as the engine sees it; + * absolute paths and `file:` URIs that the engine reports under it + * become URIs under `outputDir`. Needs `outputDir`. + */ + localDir?: string; + /** + * The files of the run, as paths relative to the output directory or as + * URIs under it; replaces the listing of the run log, if any. + */ + files?: unknown[]; +} + +/** A value of the normalised outputs object that fails validation. */ +export interface OutputError { + /** Name of the output, or `null` for the whole object (e.g. `required`) */ + output: string | null; + /** JSON Pointer of the value in the normalised outputs object */ + pointer: string; + message: string; +} + +/** An output reported by name whose value can't be given as URIs. */ +export interface UnconvertedOutput { + output: string; + /** The value that the engine reported */ + value: unknown; + reason: string; +} + +/** An entry of the listing that failed the checks. */ +export interface SkippedFile { + /** + * The entry as it can be reported: URIs without user information, query + * and fragment (they may carry credentials), objects and arrays as + * `{type: "object"}` or `{type: "array"}` + */ + entry: unknown; + reason: string; +} + +/** The normalised outputs object of a run, with the report on it. */ +export interface NormalisedOutputs { + /** The WES state of the run */ + state: string; + /** + * `conformant` or `non-conformant` for a run that completed, `partial` + * for a run that ended in another final state + */ + conformance: Conformance; + /** The normalised outputs object; outputs not produced are absent */ + outputs: Record; + /** + * Validation errors: of the object, which is kept as it is, for a run + * that completed; of the outputs that were left out, for one that didn't + */ + errors: OutputError[]; + /** Outputs of a partial run left out because they are invalid, by name */ + removed: Record; + /** Outputs of one file whose glob matches several files: the matches */ + ambiguous: Record; + /** Outputs reported by name whose values can't be given as URIs */ + unconverted: UnconvertedOutput[]; + /** Outputs reported by name that the schema doesn't declare, by name */ + undeclared: Record; + /** URIs of listed files that no output found, sorted by code point */ + unmatchedFiles: string[]; + /** Entries of the listing that failed the checks, in listed order */ + skippedFiles: SkippedFile[]; +} + +/** + * The outputs of a run can't be normalised as a whole: the schema doesn't + * conform to the profile, the run hasn't ended, `RunLog.outputs` has no + * supported shape, or the options are inconsistent. + */ +export class NormalisationError extends Error { + /** Errors of the schema, if it doesn't conform to the profile */ + readonly schemaErrors: ValidationError[]; + + constructor(message: string, schemaErrors: ValidationError[] = []) { + super(message); + this.name = "NormalisationError"; + this.schemaErrors = schemaErrors; + } +} + +/** A reported value or listed entry that can't be given as a URI. */ +class Unconvertible extends Error {} + +type Schema = Record; +type Segments = string[]; + +const SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:/; +// C0 and C1 control characters and DEL, which listed paths must not contain +// eslint-disable-next-line no-control-regex +const CONTROL = /[\u0000-\u001F\u007F-\u009F]/; +/** A UTF-16 surrogate without its pair, which has no UTF-8 encoding */ +const LONE_SURROGATE = + /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(? => + typeof value === "object" && value !== null && !Array.isArray(value); + +const own = (object: Record, key: string): boolean => + Object.prototype.hasOwnProperty.call(object, key); + +/** Sets a member, also one named `__proto__`. */ +function put(object: Record, key: string, value: unknown) { + Object.defineProperty(object, key, { + value, + enumerable: true, + writable: true, + configurable: true, + }); +} + +/** Compares strings by Unicode code points (as the profile sorts). */ +function byCodePoint(a: string, b: string): number { + const x = Array.from(a); + const y = Array.from(b); + for (let i = 0; i < Math.min(x.length, y.length); i += 1) { + const d = (x[i].codePointAt(0) ?? 0) - (y[i].codePointAt(0) ?? 0); + if (d !== 0) return d; + } + return x.length - y.length; +} + +/** Decodes percent-encoding strictly (valid escapes, UTF-8). */ +function decodeStrict(text: string): string { + if (BAD_ESCAPE.test(text)) + throw new Unconvertible("invalid percent-encoding"); + try { + return decodeURIComponent(text); + } catch { + throw new Unconvertible("percent-encoding that isn't UTF-8"); + } +} + +/** + * Resolves the references of an IO schema within the document. Unlike + * `resolve()` of `fields.ts` (which merges a missing target into `{}` for + * the form) and the fail-closed walk of `bindings.ts` (which throws), the + * normaliser follows the reference implementation: a reference that + * doesn't resolve, or whose target lies in an embedded `$id` resource, + * keeps the value as it is, for validation to report. + */ +class Resolver { + private readonly base?: string; + + constructor(private readonly document: Schema) { + const id = document.$id; + this.base = + typeof id === "string" && SCHEME.test(id) ? id.split("#")[0] : undefined; + } + + /** + * The schema at a reference, or `undefined` if it doesn't resolve within + * the document or lies in an embedded `$id` resource (whose own relative + * references would resolve elsewhere). + */ + lookup(ref: string): unknown { + let pointer: string | null = null; + if (ref.startsWith("#")) pointer = fragmentPointer(ref); + else if (this.base) { + try { + const url = new URL(ref, this.base).href; + if (url.split("#")[0] === this.base) pointer = fragmentPointer(url); + } catch { + return undefined; + } + } + if (pointer === null) return undefined; + let segments: string[]; + try { + segments = parsePointer(pointer); + } catch { + return undefined; + } + for (let i = 1; i <= segments.length; i += 1) { + const step = valueAt(this.document, toPointer(segments.slice(0, i))); + if (step === undefined || (isObject(step) && "$id" in step)) { + return undefined; + } + } + return valueAt(this.document, pointer); + } + + /** + * Follows the `$ref` of a schema without a shape of its own; `true` if a + * reference doesn't resolve (the value is then kept as it is). + */ + follow(schema: unknown): unknown { + let current = schema; + for (let depth = 0; ; depth += 1) { + // eslint-disable-next-line no-use-before-define + if ( + !isObject(current) || + typeof current.$ref !== "string" || + hasShape(current) + ) { + return current; + } + if (depth >= MAX_REFS) return true; + const target = this.lookup(current.$ref); + if (target === undefined) return true; + current = target; + } + } +} + +/** + * The schema of an output as a viewer needs it: local references followed + * (the referencing schema's own keywords, e.g. `title`, override the + * target's), a single branch besides `null` unwrapped, and the same for + * `items` and `additionalProperties`, so that file references are seen + * where the normaliser found them. + */ +export function displaySchema(document: unknown, schema: unknown): unknown { + if (!isObject(document)) return schema; + const resolver = new Resolver(document); + const flatten = (value: unknown, depth: number): unknown => { + let current = value; + for (let step = 0; step < MAX_REFS && isObject(current); step += 1) { + const { $ref, ...ownKeywords } = current; + if (typeof $ref === "string" && !hasShape(current)) { + const target = resolver.lookup($ref); + if (!isObject(target)) break; + current = { ...target, ...ownKeywords }; + } else { + // eslint-disable-next-line no-use-before-define + const branch = singleBranch(current); + if (!isObject(branch)) break; + const rest = Object.fromEntries( + Object.entries(current).filter( + ([keyword]) => keyword !== "anyOf" && keyword !== "oneOf" + ) + ); + current = { ...branch, ...rest }; + } + } + if (!isObject(current) || depth >= 2) return current; + const result: Record = { ...current }; + for (const keyword of ["items", "additionalProperties"]) { + if (isObject(result[keyword])) { + result[keyword] = flatten(result[keyword], depth + 1); + } + } + return result; + }; + return flatten(schema, 0); +} + +/** Whether a schema has a shape of its own (see `SHAPE`). */ +function hasShape(schema: Schema): boolean { + return SHAPE.some((keyword) => keyword in schema); +} + +/** The only branch of `anyOf` or `oneOf` that isn't `{"type": "null"}`. */ +function singleBranch(schema: Schema): unknown { + if (hasShape(schema)) return undefined; + for (const keyword of ["anyOf", "oneOf"]) { + const branches = schema[keyword]; + if (Array.isArray(branches)) { + const others = branches.filter( + (b) => + !(isObject(b) && Object.keys(b).length === 1 && b.type === "null") + ); + if (others.length === 1) return others[0]; + } + } + return undefined; +} + +/** The output schemas of an IO schema (`outputs.properties`), by name. */ +export function outputProperties(schema: unknown): Record { + if (!isObject(schema)) return {}; + const properties = isObject(schema.properties) ? schema.properties : {}; + const outputs = own(properties, "outputs") ? properties.outputs : undefined; + return isObject(outputs) && isObject(outputs.properties) + ? outputs.properties + : {}; +} + +/** The name of each output in the engine, qualified for WDL. */ +function engineNames( + schema: Schema, + properties: Record +): Map { + const workflow = isObject(schema["x-ga4gh-workflow"]) + ? schema["x-ga4gh-workflow"] + : {}; + const prefix = + workflow.descriptor_type === "WDL" && + typeof workflow.entry_point === "string" && + workflow.entry_point + ? `${workflow.entry_point}.` + : ""; + const names = new Map(); + const taken = new Set(); + for (const [name, prop] of Object.entries(properties)) { + const binding = isObject(prop) ? prop["x-ga4gh-parameter"] : undefined; + const engineName = + prefix + + (isObject(binding) && typeof binding.name === "string" + ? binding.name + : name); + if (taken.has(engineName)) { + throw new NormalisationError( + `Several outputs have the name "${engineName}" in the engine.` + ); + } + taken.add(engineName); + names.set(name, engineName); + } + return names; +} + +/** The state of a run that has ended. */ +function finalState(runLog: unknown): string { + if (!isObject(runLog)) { + throw new NormalisationError("The run log must be a JSON object."); + } + const { state } = runLog; + if (typeof state !== "string" || !FINAL_STATES.includes(state)) { + throw new NormalisationError( + `The run is in the state ${JSON.stringify( + state ?? null + )}, not in a final state (${FINAL_STATES.join( + ", " + )}): outputs are normalised only for runs that have ended.` + ); + } + return state; +} + +function checkOutputDir(outputDir: unknown): string | undefined { + if (outputDir === undefined || outputDir === null) return undefined; + if ( + typeof outputDir !== "string" || + !SCHEME.test(outputDir) || + /[?#]/.test(outputDir) + ) { + throw new NormalisationError( + "The output directory must be an absolute URI without query or fragment." + ); + } + return outputDir.endsWith("/") ? outputDir.slice(0, -1) : outputDir; +} + +function checkLocalDir( + localDir: unknown, + base: string | undefined +): string | undefined { + if (localDir === undefined || localDir === null) return undefined; + if (typeof localDir !== "string" || !localDir.startsWith("/")) { + throw new NormalisationError("The local directory must be absolute."); + } + if (base === undefined) { + throw new NormalisationError( + "A local directory needs the URI of the output directory." + ); + } + return localDir.replace(/\/+$/, ""); +} + +/** Splits `RunLog.outputs` into outputs by name and a listing of files. */ +function splitRunLog( + outputs: unknown, + names: Set +): { named: Map; listing: unknown[] } { + if (outputs === undefined || outputs === null) { + return { named: new Map(), listing: [] }; + } + if (Array.isArray(outputs)) { + // Sapporo: objects with file_name (and file_url), or plain entries + const listing = outputs.map((entry) => + isObject(entry) && typeof entry.file_name === "string" + ? entry.file_name + : entry + ); + return { named: new Map(), listing }; + } + if (!isObject(outputs)) { + throw new NormalisationError( + "RunLog.outputs must be an object, an array or null." + ); + } + const named = new Map(Object.entries(outputs)); + // WESkit's presigned URLs: credentials, never copied into a report + if (!names.has("S3")) named.delete("S3"); + const filesystem = named.get("filesystem"); + if ( + !names.has("filesystem") && + Array.isArray(filesystem) && + named.size === 1 + ) { + return { named: new Map(), listing: [...filesystem] }; + } + return { named, listing: [] }; +} + +/** Checks the segments of a relative path from a run. */ +function checkSegments(segments: Segments): void { + for (const segment of segments) { + if (!segment) throw new Unconvertible("an empty segment"); + if (segment === "." || segment === "..") { + throw new Unconvertible(`a '${segment}' segment`); + } + if (segment.includes("\\")) throw new Unconvertible("a backslash"); + if (CONTROL.test(segment)) throw new Unconvertible("a control character"); + if (LONE_SURROGATE.test(segment)) { + throw new Unconvertible("a character that isn't valid Unicode"); + } + } + if (segments[0].includes(":")) { + throw new Unconvertible("a colon in the first segment"); + } +} + +/** The decoded segments of a listed URI under the output directory. */ +function uriSegments(uri: string, base: string): Segments { + const prefix = `${base}/`; + if (!uri.startsWith(prefix)) { + throw new Unconvertible("not under the output directory"); + } + const rest = uri.slice(prefix.length); + if (/[?#]/.test(rest)) + throw new Unconvertible("a URI with a query or fragment"); + const segments = rest.split("/").map(decodeStrict); + if (segments.some((segment) => segment.includes("/"))) { + // A %2F would hide several segments in one (e.g. x%2F..%2F..%2Fy) + throw new Unconvertible("an encoded '/'"); + } + return segments; +} + +/** A listed entry as it can be reported (see `SkippedFile.entry`). */ +function redact(entry: unknown): unknown { + if (Array.isArray(entry)) return { type: "array" }; + if (isObject(entry)) return { type: "object" }; + if (typeof entry === "string" && SCHEME.test(entry)) { + return entry.split(/[?#]/)[0].replace(USERINFO, "$1"); + } + return entry; +} + +/** Checks the listed files; returns the safe ones, without duplicates. */ +function checkListing( + listing: unknown[], + base: string | undefined, + skipped: SkippedFile[] +): Map { + const checked = new Map(); + for (const entry of listing) { + try { + if (typeof entry !== "string") { + throw new Unconvertible("not a path or URI"); + } + let segments: Segments; + if (SCHEME.test(entry)) segments = uriSegments(entry, base ?? ""); + else if (entry.startsWith("/")) { + throw new Unconvertible("an absolute path"); + } else segments = entry.split("/"); + checkSegments(segments); + // Checked segments contain no '/', so the joined path is a key + checked.set(segments.join("/"), segments); + } catch (error) { + if (!(error instanceof Unconvertible)) throw error; + skipped.push({ entry: redact(entry), reason: error.message }); + } + } + return checked; +} + +/** The URI of a file of the run from its relative path. */ +const buildUri = (base: string, segments: Segments): string => + [base, ...segments.map(encodeSegment)].join("/"); + +/** The local path of a `file:` URI. */ +function fileUriPath(uri: string): string { + let rest = uri.slice("file:".length); + if (/[?#]/.test(rest)) { + throw new Unconvertible("a file URI of another host, or with a query"); + } + if (rest.startsWith("//")) { + const end = rest.indexOf("/", 2); + const host = end === -1 ? rest.slice(2) : rest.slice(2, end); + if (host !== "" && host !== "localhost") { + throw new Unconvertible("a file URI of another host, or with a query"); + } + rest = end === -1 ? "" : rest.slice(end); + } + return decodeStrict(rest); +} + +interface Context { + base?: string; + local?: string; +} + +/** Turns a reported file reference into a URI. */ +function convertFile(reported: unknown, context: Context): unknown { + let value = reported; + if ( + isObject(value) && + (value.class === "File" || value.class === "Directory") + ) { + value = value.location || value.path; + if (typeof value !== "string") { + throw new Unconvertible("a File or Directory object without location"); + } + } + if (typeof value !== "string") return value; + if (WINDOWS_PATH.test(value)) throw new Unconvertible("a Windows path"); + if (SCHEME.test(value)) { + if (!value.toLowerCase().startsWith("file:")) return value; + value = fileUriPath(value); + } + let path = value as string; + if (path.startsWith("/")) { + if (context.local === undefined || !path.startsWith(`${context.local}/`)) { + throw new Unconvertible("a local path outside the output directory"); + } + path = path.slice(context.local.length + 1); + } + if (context.base === undefined) { + throw new Unconvertible("a relative path, and no output directory given"); + } + const segments = path.split("/"); + checkSegments(segments); + return buildUri(context.base, segments); +} + +/** + * Converts a reported value into the shape of its schema: file references + * become URIs; arrays, records, files keyed by name and single branches + * besides `null` are converted item by item. `null` items of arrays are + * left out, `null` members of objects kept. Other values are kept as they + * are, for validation to report. + */ +function convert( + value: unknown, + schemaIn: unknown, + resolver: Resolver, + context: Context, + depth = 0 +): unknown { + if (depth > MAX_DEPTH) throw new Unconvertible("nested too deeply"); + const schema = resolver.follow(schemaIn); + if (!isObject(schema)) return value; + if ("x-ga4gh-file" in schema) return convertFile(value, context); + const branch = singleBranch(schema); + if (branch !== undefined) { + return convert(value, branch, resolver, context, depth + 1); + } + if (Array.isArray(value) && !("prefixItems" in schema)) { + const items = "items" in schema ? schema.items : true; + return value + .filter((item) => item !== null) + .map((item) => convert(item, items, resolver, context, depth + 1)); + } + if (isObject(value)) { + const properties = isObject(schema.properties) ? schema.properties : {}; + const additional = + "additionalProperties" in schema ? schema.additionalProperties : true; + const result: Record = {}; + for (const [key, item] of Object.entries(value)) { + put( + result, + key, + item === null + ? null + : convert( + item, + own(properties, key) ? properties[key] : additional, + resolver, + context, + depth + 1 + ) + ); + } + return result; + } + return value; +} + +/** + * Matches a glob against a relative path, segment by segment: `**` matches + * any number of segments. Time polynomial in the lengths (globs come from + * untrusted schemas). + */ +export function matchGlob(glob: Segments, path: Segments): boolean { + let ends = [true, ...path.map(() => false)]; + for (const segment of glob) { + if (segment === "**") { + for (let j = 1; j <= path.length; j += 1) { + ends[j] = ends[j] || ends[j - 1]; + } + } else { + const previous = ends; + ends = [ + false, + // eslint-disable-next-line no-use-before-define + ...path.map((name, j) => previous[j] && matchSegment(segment, name)), + ]; + } + } + return ends[path.length]; +} + +/** + * Matches a segment of a glob against a segment of a path: `*` matches + * any characters (also none), `?` exactly one (code point); others match + * themselves. Greedy, with backtracking to the last `*` only. + */ +function matchSegment(globText: string, nameText: string): boolean { + const glob = Array.from(globText); + const name = Array.from(nameText); + let g = 0; + let n = 0; + let star = -1; + let mark = 0; + while (n < name.length) { + if (g < glob.length && glob[g] === "*") { + star = g; + mark = n; + g += 1; + } else if (g < glob.length && (glob[g] === "?" || glob[g] === name[n])) { + g += 1; + n += 1; + } else if (star >= 0) { + g = star + 1; + mark += 1; + n = mark; + } else return false; + } + return glob.slice(g).every((c) => c === "*"); +} + +/** + * The name of a secondary file: the pattern's suffix appended, after one + * extension is removed for each leading `^`. + */ +export function secondaryName(name: string, pattern: string): string { + const suffix = pattern.replace(/^\^+/, ""); + let base = name; + for (let i = 0; i < pattern.length - suffix.length; i += 1) { + if (base.includes(".")) base = base.slice(0, base.lastIndexOf(".")); + } + return base + suffix; +} + +/** Adds an output found by its `x-ga4gh-output-glob`. */ +function takeGlob( + name: string, + prop: Schema, + checked: Map, + base: string, + result: NormalisedOutputs, + covered: Set +): void { + const globText = prop["x-ga4gh-output-glob"]; + if (typeof globText !== "string") return; + const isArray = prop.type === "array"; + const reference = isArray ? prop.items : prop; + const annotation = + isObject(reference) && isObject(reference["x-ga4gh-file"]) + ? reference["x-ga4gh-file"] + : {}; + const glob = globText.split("/"); + const files = [...checked.values()]; + let matches: Segments[]; + if (annotation.kind === "directory") { + const candidates = new Map(); + for (const segments of files) { + for (let i = 1; i < segments.length; i += 1) { + const prefix = segments.slice(0, i); + candidates.set(prefix.join("/"), prefix); + } + } + matches = [...candidates.values()].filter((c) => matchGlob(glob, c)); + for (const [key, segments] of checked) { + if ( + matches.some((m) => m.every((segment, i) => segments[i] === segment)) + ) { + covered.add(key); + } + } + } else { + matches = files.filter((segments) => matchGlob(glob, segments)); + const patterns = Array.isArray(annotation.secondaryFiles) + ? annotation.secondaryFiles.filter( + (p): p is string => typeof p === "string" + ) + : []; + const secondary = new Set(); + for (const m of matches) { + for (const pattern of patterns) { + secondary.add( + [...m.slice(0, -1), secondaryName(m[m.length - 1], pattern)].join("/") + ); + } + } + for (const m of matches) covered.add(m.join("/")); + for (const key of secondary) if (checked.has(key)) covered.add(key); + matches = matches.filter((m) => !secondary.has(m.join("/"))); + } + const uris = matches + .sort((a, b) => byCodePoint(a.join("/"), b.join("/"))) + .map((m) => buildUri(base, m)); + if (uris.length === 0) return; + if (isArray) put(result.outputs, name, uris); + else if (uris.length === 1) put(result.outputs, name, uris[0]); + else put(result.ambiguous, name, uris); +} + +/** Whether a JSON value is nested more than `MAX_DEPTH` levels deep. */ +function tooDeep(value: unknown): boolean { + const stack: [unknown, number][] = [[value, 0]]; + while (stack.length > 0) { + const [item, depth] = stack.pop() as [unknown, number]; + if (Array.isArray(item) || isObject(item)) { + if (depth >= MAX_DEPTH) return true; + for (const child of Object.values(item)) stack.push([child, depth + 1]); + } + } + return false; +} + +/** The strings in a JSON value, up to `MAX_DEPTH` levels deep. */ +function strings(value: unknown): Set { + // Iterative and bounded: values that the normaliser keeps as they are + // can be nested deeper than the stack allows + const found = new Set(); + const stack: [unknown, number][] = [[value, 0]]; + while (stack.length > 0) { + const [item, depth] = stack.pop() as [unknown, number]; + if (typeof item === "string") found.add(item); + else if (depth < MAX_DEPTH && (Array.isArray(item) || isObject(item))) { + for (const child of Object.values(item)) stack.push([child, depth + 1]); + } + } + return found; +} + +/** + * Checks output values of file references: absolute URIs, with one of the + * annotation's `schemes` if it has any. It walks the shapes that values are + * converted by (file references, `allOf`, single branches besides `null`, + * `prefixItems`, `items`, `properties`, `additionalProperties`) through + * local references; file references in other applicators (e.g. unions of + * several types) aren't checked here. Clients check every output URI + * against their allow-list before they show it either way. + */ +function fileErrors( + schemaIn: unknown, + value: unknown, + path: (string | number)[], + resolver: Resolver, + errors: { path: (string | number)[]; message: string }[], + depth = 0 +): void { + if (depth > MAX_DEPTH) return; + const schema = resolver.follow(schemaIn); + if (!isObject(schema)) return; + const next = (sub: unknown, item: unknown, at: (string | number)[]) => + fileErrors(sub, item, at, resolver, errors, depth + 1); + if (isObject(schema["x-ga4gh-file"]) && typeof value === "string") { + const match = SCHEME.exec(value); + const { schemes } = schema["x-ga4gh-file"]; + if (!match) { + errors.push({ path, message: "The value is not an absolute URI." }); + } else if (Array.isArray(schemes)) { + const scheme = match[0].slice(0, -1).toLowerCase(); + if (!schemes.includes(scheme)) { + errors.push({ + path, + message: `The scheme "${scheme}" is not one of ${schemes.join( + ", " + )}.`, + }); + } + } + } + if ("$ref" in schema && typeof schema.$ref === "string") { + const target = resolver.lookup(schema.$ref); + if (target !== undefined) next(target, value, path); + } + if (Array.isArray(schema.allOf)) { + for (const branch of schema.allOf) next(branch, value, path); + } + for (const keyword of ["anyOf", "oneOf"]) { + const branches = schema[keyword]; + if (Array.isArray(branches)) { + const others = branches.filter( + (b) => + !(isObject(b) && Object.keys(b).length === 1 && b.type === "null") + ); + if (others.length === 1) next(others[0], value, path); + } + } + if (Array.isArray(value)) { + const prefix = Array.isArray(schema.prefixItems) ? schema.prefixItems : []; + value.forEach((item, i) => { + if (i < prefix.length) next(prefix[i], item, [...path, i]); + else if ("items" in schema) next(schema.items, item, [...path, i]); + }); + } else if (isObject(value)) { + const properties = isObject(schema.properties) ? schema.properties : {}; + for (const [key, item] of Object.entries(value)) { + if (own(properties, key)) next(properties[key], item, [...path, key]); + else if ("additionalProperties" in schema) { + next(schema.additionalProperties, item, [...path, key]); + } + } + } +} + +/** + * The validation errors of the normalised outputs object: of the whole + * object for a run that completed, of each output for one that didn't. + */ +function validationErrors( + schema: Schema, + complete: boolean, + outputs: Record, + validateOutputs: OutputsValidator, + resolver: Resolver +): OutputError[] { + const properties = outputProperties(schema); + const found: OutputError[] = []; + const collect = (value: unknown, name?: string) => { + for (const error of validateOutputs(value, name).errors) { + const [first] = parsePointer(error.pointer); + found.push({ + output: first ?? null, + pointer: error.pointer, + message: error.message, + }); + } + const files: { path: (string | number)[]; message: string }[] = []; + if (name === undefined) { + const schemaProperties = isObject(schema.properties) + ? schema.properties + : {}; + fileErrors(schemaProperties.outputs, value, [], resolver, files); + } else fileErrors(properties[name], value, [name], resolver, files); + for (const { path, message } of files) { + found.push({ + output: String(path[0]), + pointer: toPointer(path), + message, + }); + } + }; + if (complete) collect(outputs); + else { + for (const [name, value] of Object.entries(outputs)) collect(value, name); + } + return found.sort((a, b) => byCodePoint(a.pointer, b.pointer)); +} + +/** + * Builds the normalised outputs object of a WES run. The shape of + * `RunLog.outputs` is detected: an object keyed by output name (cwltool, + * Toil; Cromwell, miniwdl and Conquest with names qualified by the WDL + * workflow); an array of files (Sapporo); an object with only + * `filesystem` (and `S3`; WESkit, whose presigned URLs are dropped); or + * nothing. + * + * @param schema - The IO schema; it must conform to the profile. + * @param runLog - The WES `RunLog` of the run, with `state` and `outputs`. + * @param options - What the deployment gives (see `OutputOptions`). + * @returns The normalised outputs object and the report on it. + * @throws NormalisationError - If the outputs can't be normalised as a + * whole. + */ +export async function normaliseOutputs( + schema: unknown, + runLog: unknown, + options: OutputOptions = {} +): Promise { + const check = await checkIoSchema(schema); + if (!check.valid) { + throw new NormalisationError( + "The IO schema doesn't conform to the profile.", + check.errors + ); + } + if (!check.validateOutputs) { + throw new NormalisationError( + "The IO schema validator can't validate outputs." + ); + } + const document = schema as Schema; + const state = finalState(runLog); + const base = checkOutputDir(options.outputDir); + const local = checkLocalDir(options.localDir, base); + const properties = outputProperties(document); + const names = engineNames(document, properties); + const split = splitRunLog( + (runLog as Record).outputs, + new Set(names.values()) + ); + const { named } = split; + let { listing } = split; + if (options.files !== undefined) { + if (!Array.isArray(options.files)) { + throw new NormalisationError("The listing of files must be an array."); + } + listing = [...options.files]; + } + if (listing.length > 0 && base === undefined) { + throw new NormalisationError( + "The run lists files: give the URI of its output directory." + ); + } + + const resolver = new Resolver(document); + const context: Context = { base, local }; + const result: NormalisedOutputs = { + state, + conformance: "conformant", + outputs: {}, + errors: [], + removed: {}, + ambiguous: {}, + unconverted: [], + undeclared: {}, + unmatchedFiles: [], + skippedFiles: [], + }; + + const checked = checkListing(listing, base, result.skippedFiles); + const covered = new Set(); + for (const [name, engineName] of names) { + const prop = properties[name]; + if (named.has(engineName)) { + const value = named.get(engineName); + if (value !== null && value !== undefined) { + try { + // The validator recurses into values: refuse what's too deep + if (tooDeep(value)) throw new Unconvertible("nested too deeply"); + put(result.outputs, name, convert(value, prop, resolver, context)); + } catch (error) { + if (!(error instanceof Unconvertible)) throw error; + result.unconverted.push({ + output: name, + value, + reason: error.message, + }); + } + } + } else if (isObject(prop) && "x-ga4gh-output-glob" in prop) { + takeGlob(name, prop, checked, base as string, result, covered); + } + } + + const engineNameSet = new Set(names.values()); + for (const [engineName, value] of named) { + if (!engineNameSet.has(engineName)) + put(result.undeclared, engineName, value); + } + const found = strings(result.outputs); + result.unmatchedFiles = [...checked] + .filter(([key]) => !covered.has(key)) + .map(([, segments]) => buildUri(base as string, segments)) + .filter((uri) => !found.has(uri)) + .sort(byCodePoint); + + const complete = state === "COMPLETE"; + result.errors = validationErrors( + document, + complete, + result.outputs, + check.validateOutputs, + resolver + ); + if (!complete) { + result.conformance = "partial"; + for (const { output } of result.errors) { + if (output !== null && own(result.outputs, output)) { + put(result.removed, output, result.outputs[output]); + delete result.outputs[output]; + } + } + } else if (result.errors.length > 0) { + result.conformance = "non-conformant"; + } + return result; +} diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/states.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/states.ts new file mode 100644 index 00000000..80a42f13 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/states.ts @@ -0,0 +1,13 @@ +/** + * Final states of a WES 1.1 run: outputs are normalised only for runs in + * one of them (`docs/specification/outputs.md`, profile version 0.3.0). + * A module of its own, so that elements can tell whether to normalise + * before they load the normaliser. + */ +export const FINAL_STATES: readonly string[] = [ + "CANCELED", + "COMPLETE", + "EXECUTOR_ERROR", + "PREEMPTED", + "SYSTEM_ERROR", +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/wes-outputs.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/wes-outputs.ts new file mode 100644 index 00000000..fe2d1f38 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/fixtures/wes-outputs.ts @@ -0,0 +1,2388 @@ +/** + * Test vectors of the output normaliser (`tests/vectors/wes-outputs/`). + * + * 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 WesOutputsCase { + name: string; + schema: Record; + run_log: Record; + options?: { outputDir?: string; localDir?: string; files?: unknown[] }; + /** The expected result, or else `error` */ + expected?: { + description: string; + conformance: string; + outputs: Record; + removed?: string[]; + ambiguous?: Record; + unconverted?: string[]; + undeclared?: string[]; + unmatchedFiles?: string[]; + skippedFiles?: unknown[]; + }; + error?: Record; +} + +export const WES_OUTPUTS_CASES: WesOutputsCase[] = [ + { + name: "by-name-ignores-glob", + expected: { + description: + "An output reported by name is taken from the name, also if the value is null (it is then absent), and its glob is ignored: the listed file that the glob would match is reported as unmatched.", + conformance: "partial", + outputs: { + alignments: ["s3://example-bucket/runs/run-12/alignments/s1.bam"], + }, + unmatchedFiles: [ + "s3://example-bucket/runs/run-12/multiqc/multiqc_report.html", + ], + }, + options: { + outputDir: "s3://example-bucket/runs/run-12", + files: ["multiqc/multiqc_report.html", "alignments/s1.bam"], + }, + run_log: { + run_id: "run-12", + state: "CANCELED", + outputs: { + qc_report: null, + alignments: ["s3://example-bucket/runs/run-12/alignments/s1.bam"], + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + }, + { + name: "cromwell-wdl-local-paths", + expected: { + description: + "Cromwell (92) WES API, local backend: WDL outputs keyed by names qualified with the workflow name, files as absolute local paths under the root of the run, turned into URIs of the output directory; null for an optional output that wasn't produced, Map[String, File] as files keyed by name, and an output that the schema doesn't declare. Captured from a real run; paths and run ID anonymised.", + conformance: "conformant", + outputs: { + qc_report: + "https://wes.example.org/cromwell/runs/run-18/call-qc/execution/multiqc_report.html", + alignments: [ + "https://wes.example.org/cromwell/runs/run-18/call-align/shard-0/execution/s1.bam", + "https://wes.example.org/cromwell/runs/run-18/call-align/shard-1/execution/s2.bam", + ], + gene_counts: { + s1: "https://wes.example.org/cromwell/runs/run-18/call-qc/execution/s1.tsv", + }, + samples_passed_qc: 2, + }, + undeclared: ["rnaseq.debug_log"], + }, + options: { + outputDir: "https://wes.example.org/cromwell/runs/run-18", + localDir: "/data/cromwell/cromwell-executions/rnaseq/run-18", + }, + run_log: { + run_id: "run-18", + state: "COMPLETE", + outputs: { + "rnaseq.alignments": [ + "/data/cromwell/cromwell-executions/rnaseq/run-18/call-align/shard-0/execution/s1.bam", + "/data/cromwell/cromwell-executions/rnaseq/run-18/call-align/shard-1/execution/s2.bam", + ], + "rnaseq.debug_log": + "/data/cromwell/cromwell-executions/rnaseq/run-18/call-qc/execution/debug.log", + "rnaseq.gene_counts": { + s1: "/data/cromwell/cromwell-executions/rnaseq/run-18/call-qc/execution/s1.tsv", + }, + "rnaseq.optional_plot": null, + "rnaseq.qc_report": + "/data/cromwell/cromwell-executions/rnaseq/run-18/call-qc/execution/multiqc_report.html", + "rnaseq.samples_passed_qc": 2, + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/wdl/1.1.0", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + descriptor_type_version: "1.0", + entry_point: "rnaseq", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + gene_counts: { + type: "object", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + optional_plot: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + samples_passed_qc: { + type: "integer", + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "cwl-remote-objects", + expected: { + description: + "CWL output object with remote locations (as Toil reports them when it writes outputs to object storage): File and Directory objects, a record with a File, a null field (kept: only null outputs and null items of lists are absent) and an optional File (anyOf with null), and an array of files through $ref.", + conformance: "conformant", + outputs: { + qc_report: "s3://example-bucket/toil/run-2/qc.html", + index_dir: "s3://example-bucket/toil/run-2/index", + summary: { + report: "s3://example-bucket/toil/run-2/summary.txt", + contigs: 42, + plot: null, + coverage: "s3://example-bucket/toil/run-2/coverage.tsv", + }, + chunks: [ + "s3://example-bucket/toil/run-2/chunk_1.fa", + "s3://example-bucket/toil/run-2/chunk_2.fa", + ], + }, + }, + run_log: { + run_id: "run-2", + state: "COMPLETE", + outputs: { + qc_report: { + class: "File", + location: "s3://example-bucket/toil/run-2/qc.html", + basename: "qc.html", + size: 120, + }, + index_dir: { + class: "Directory", + location: "s3://example-bucket/toil/run-2/index", + basename: "index", + listing: [ + { + class: "File", + location: "s3://example-bucket/toil/run-2/index/a.idx", + }, + ], + }, + summary: { + report: { + class: "File", + location: "s3://example-bucket/toil/run-2/summary.txt", + }, + contigs: 42, + plot: null, + coverage: { + class: "File", + location: "s3://example-bucket/toil/run-2/coverage.tsv", + }, + }, + chunks: [ + { + class: "File", + location: "s3://example-bucket/toil/run-2/chunk_1.fa", + }, + null, + { + class: "File", + location: "s3://example-bucket/toil/run-2/chunk_2.fa", + }, + ], + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/assembly/cwl/2.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + index_dir: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + summary: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + contigs: { + type: "integer", + }, + plot: { + anyOf: [ + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + { + type: "null", + }, + ], + }, + coverage: { + anyOf: [ + { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + { + type: "null", + }, + ], + }, + }, + required: ["report"], + }, + chunks: { + $ref: "#/$defs/fileList", + }, + }, + additionalProperties: false, + required: ["qc_report", "index_dir", "summary"], + }, + }, + $defs: { + fileList: { + type: "array", + items: { + $ref: "#/$defs/file", + }, + }, + file: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + }, + }, + { + name: "cwltool-file-objects", + expected: { + description: + "cwltool (3.3): the CWL output object, files as File objects with file: locations and secondary files, null for an optional output that wasn't produced. Captured from a real run; paths anonymised.", + conformance: "conformant", + outputs: { + qc_report: "s3://example-bucket/runs/run-1/outputs/report.html", + alignments: [ + "s3://example-bucket/runs/run-1/outputs/s1.bam", + "s3://example-bucket/runs/run-1/outputs/s2.bam", + ], + samples_passed_qc: 2, + }, + }, + options: { + outputDir: "s3://example-bucket/runs/run-1/outputs", + localDir: "/data/wes/runs/run-1/outputs", + }, + run_log: { + run_id: "run-1", + state: "COMPLETE", + outputs: { + alignments: [ + { + location: "file:///data/wes/runs/run-1/outputs/s1.bam", + basename: "s1.bam", + class: "File", + checksum: "sha1$d0257f733e5e1c54fcf496857e2b4f0e4148c017", + size: 3, + secondaryFiles: [ + { + basename: "s1.bam.bai", + location: "file:///data/wes/runs/run-1/outputs/s1.bam.bai", + class: "File", + size: 2, + checksum: "sha1$397d543883c5cb5019a0ed08acba13fcb26261c2", + path: "/data/wes/runs/run-1/outputs/s1.bam.bai", + }, + ], + path: "/data/wes/runs/run-1/outputs/s1.bam", + }, + { + location: "file:///data/wes/runs/run-1/outputs/s2.bam", + basename: "s2.bam", + class: "File", + checksum: "sha1$630081a5992e722541bc1fc6f3dee804a22b6233", + size: 3, + secondaryFiles: [ + { + basename: "s2.bam.bai", + location: "file:///data/wes/runs/run-1/outputs/s2.bam.bai", + class: "File", + size: 2, + checksum: "sha1$397d543883c5cb5019a0ed08acba13fcb26261c2", + path: "/data/wes/runs/run-1/outputs/s2.bam.bai", + }, + ], + path: "/data/wes/runs/run-1/outputs/s2.bam", + }, + ], + missing_optional: null, + qc_report: { + location: "file:///data/wes/runs/run-1/outputs/report.html", + basename: "report.html", + class: "File", + checksum: "sha1$ec2daf6a782747ad7d983aefafd954cc7e661cf7", + size: 14, + path: "/data/wes/runs/run-1/outputs/report.html", + }, + samples_passed_qc: 2, + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".bai"], + }, + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + }, + missing_optional: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "error-listing-without-output-dir", + error: { + description: + "A run that lists files, without the URI of its output directory: the URIs of the files can't be built.", + }, + run_log: { + run_id: "run-15", + state: "COMPLETE", + outputs: [ + { + file_name: "multiqc/multiqc_report.html", + file_url: + "https://wes.example.org/runs/run-15/outputs/multiqc/multiqc_report.html", + }, + ], + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + }, + { + name: "error-run-not-final", + error: { + description: + "A run that hasn't ended (RUNNING): its outputs are not normalised.", + }, + run_log: { + run_id: "run-14", + state: "RUNNING", + outputs: {}, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + }, + { + name: "glob-matching", + expected: { + description: + "Glob syntax and results: '*' and '?' within a segment (also matching a leading dot), '**' for any number of segments, case-sensitive; caret patterns of secondary files; directories that contain listed files; an ambiguous one-file output (several matches) is absent and reported, so the required output is missing.", + conformance: "non-conformant", + outputs: { + bams: ["s3://example-bucket/runs/run-9/s1.bam"], + crams: ["s3://example-bucket/runs/run-9/crams/s1.cram"], + vcfs: [ + "s3://example-bucket/runs/run-9/a.vcf.gz", + "s3://example-bucket/runs/run-9/x/y/b.vcf.gz", + ], + single_char: ["s3://example-bucket/runs/run-9/a.txt"], + configs: [ + "s3://example-bucket/runs/run-9/.hidden.cfg", + "s3://example-bucket/runs/run-9/run.cfg", + ], + indexes: [ + "s3://example-bucket/runs/run-9/index/salmon", + "s3://example-bucket/runs/run-9/index/star", + ], + multiqc_data: "s3://example-bucket/runs/run-9/multiqc/multiqc_data", + }, + ambiguous: { + report: [ + "s3://example-bucket/runs/run-9/reports/a.html", + "s3://example-bucket/runs/run-9/reports/b.html", + ], + everything_dir: [ + "s3://example-bucket/runs/run-9/crams", + "s3://example-bucket/runs/run-9/index", + "s3://example-bucket/runs/run-9/index/salmon", + "s3://example-bucket/runs/run-9/index/star", + "s3://example-bucket/runs/run-9/multiqc", + "s3://example-bucket/runs/run-9/multiqc/multiqc_data", + "s3://example-bucket/runs/run-9/reports", + "s3://example-bucket/runs/run-9/x", + "s3://example-bucket/runs/run-9/x/y", + ], + }, + unmatchedFiles: [ + "s3://example-bucket/runs/run-9/A.TXT", + "s3://example-bucket/runs/run-9/ab.txt", + ], + }, + options: { + outputDir: "s3://example-bucket/runs/run-9", + files: [ + "reports/a.html", + "reports/b.html", + "s1.bam", + "s1.bai", + "crams/s1.cram", + "crams/s1.cram.crai", + "a.vcf.gz", + "a.vcf.gz.tbi", + "a.idx", + "x/y/b.vcf.gz", + "a.txt", + "ab.txt", + "A.TXT", + ".hidden.cfg", + "run.cfg", + "index/star/SA", + "index/star/Genome", + "index/salmon/info.json", + "multiqc/multiqc_data/multiqc.log", + ], + }, + run_log: { + run_id: "run-9", + state: "COMPLETE", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/globs/nfl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-output-glob": "reports/*.html", + }, + bams: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: ["^.bai"], + }, + }, + "x-ga4gh-output-glob": "*.bam", + }, + crams: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".crai"], + }, + }, + "x-ga4gh-output-glob": "crams/*", + }, + vcfs: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".tbi", "^^.idx"], + }, + }, + "x-ga4gh-output-glob": "**/*.vcf.gz", + }, + single_char: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + "x-ga4gh-output-glob": "?.txt", + }, + configs: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + "x-ga4gh-output-glob": "*.cfg", + }, + indexes: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + "x-ga4gh-output-glob": "index/*", + }, + multiqc_data: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + "x-ga4gh-output-glob": "multiqc/multiqc_data", + }, + everything_dir: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + "x-ga4gh-output-glob": "**", + }, + }, + additionalProperties: false, + required: ["report"], + }, + }, + }, + }, + { + name: "listing-checks", + expected: { + description: + "Checks of a listing given with the files option, as paths and as URIs: entries that are absolute, have empty, '.' or '..' segments (also percent-encoded), backslashes, control characters, a colon in the first segment, a query or fragment, an encoded '/', invalid percent-encoding, or lie outside the output directory are skipped and reported; the queries and fragments of skipped URIs are removed from the report.", + conformance: "conformant", + outputs: { + qc_report: + "https://storage.example.org/runs/run-8/outputs/multiqc/multiqc_report.html", + alignments: [ + "https://storage.example.org/runs/run-8/outputs/alignments/s%201.bam", + ], + }, + skippedFiles: [ + "/etc/passwd", + "alignments/../s0.bam", + "alignments/./s0.bam", + "alignments//s0.bam", + "alignments/", + "alignments\\s0.bam", + "alignments/s0\u0007.bam", + "c:/alignments/s0.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/%2E%2E/%2E%2E/run-9/outputs/alignments/s9.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/s0.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/s0.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/sub%2Fs0.bam", + "https://storage.example.org/runs/run-8/outputs/x%2F..%2F..%2Frun-9", + "https://storage.example.org/runs/run-8/outputs/alignments/s0%zz.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/s0%FF.bam", + "https://storage.example.org/runs/run-8/outputs-other/alignments/s0.bam", + "https://other.example.org/alignments/s0.bam", + 42, + ], + }, + options: { + outputDir: "https://storage.example.org/runs/run-8/outputs", + files: [ + "https://storage.example.org/runs/run-8/outputs/multiqc/multiqc_report.html", + "https://storage.example.org/runs/run-8/outputs/alignments/s%201.bam", + "alignments/s 1.bam", + "/etc/passwd", + "alignments/../s0.bam", + "alignments/./s0.bam", + "alignments//s0.bam", + "alignments/", + "alignments\\s0.bam", + "alignments/s0\u0007.bam", + "c:/alignments/s0.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/%2E%2E/%2E%2E/run-9/outputs/alignments/s9.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/s0.bam?download=1", + "https://storage.example.org/runs/run-8/outputs/alignments/s0.bam#x", + "https://storage.example.org/runs/run-8/outputs/alignments/sub%2Fs0.bam", + "https://storage.example.org/runs/run-8/outputs/x%2F..%2F..%2Frun-9", + "https://storage.example.org/runs/run-8/outputs/alignments/s0%zz.bam", + "https://storage.example.org/runs/run-8/outputs/alignments/s0%FF.bam", + "https://storage.example.org/runs/run-8/outputs-other/alignments/s0.bam", + "https://other.example.org/alignments/s0.bam", + 42, + ], + }, + run_log: { + run_id: "run-8", + state: "COMPLETE", + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + }, + { + name: "nextflow-no-outputs", + expected: { + description: + "Nextflow on a server that reports no outputs (RunLog.outputs is {}): without a listing, globs find nothing; the required outputs are missing, so the outputs of the completed run are non-conformant.", + conformance: "non-conformant", + outputs: {}, + }, + run_log: { + run_id: "run-7", + state: "COMPLETE", + outputs: {}, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + }, + { + name: "non-conformant-kept", + expected: { + description: + "A completed run whose outputs don't conform (fewer files than minItems, a scheme outside schemes): the outputs are kept as they are, and the run is reported as non-conformant.", + conformance: "non-conformant", + outputs: { + qc_report: "https://storage.example.org/run-11/report.html", + alignments: ["s3://example-bucket/run-11/s1.bam"], + }, + }, + run_log: { + run_id: "run-11", + state: "COMPLETE", + outputs: { + qc_report: "https://storage.example.org/run-11/report.html", + alignments: ["s3://example-bucket/run-11/s1.bam"], + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/cwl/1.1.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + schemes: ["s3"], + }, + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + minItems: 2, + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "partial-run", + expected: { + description: + "A run that ended in EXECUTOR_ERROR: its outputs are checked one by one, required doesn't apply, and outputs with invalid values are left out and reported.", + conformance: "partial", + outputs: { + qc_report: "s3://example-bucket/runs/run-10/report.html", + }, + removed: ["alignments", "samples_passed_qc"], + }, + run_log: { + run_id: "run-10", + state: "EXECUTOR_ERROR", + outputs: { + qc_report: { + class: "File", + location: "s3://example-bucket/runs/run-10/report.html", + }, + alignments: { + class: "File", + location: "s3://example-bucket/runs/run-10/s1.bam", + }, + samples_passed_qc: "two", + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".bai"], + }, + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + }, + missing_optional: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "sapporo-cwltool-listing", + expected: { + description: + "Sapporo (2.4) with cwltool: RunLog.outputs lists the files of the output directory, not the CWL output object. cwltool puts files directly in the output directory (Directory outputs keep their name), so globs match base names; samples_passed_qc, an integer, isn't in the listing and is absent. Captured from a real run; run ID anonymised.", + conformance: "conformant", + outputs: { + qc_report: + "https://wes.example.org/runs/run-16/outputs/multiqc_report.html", + alignments: [ + "https://wes.example.org/runs/run-16/outputs/s1.bam", + "https://wes.example.org/runs/run-16/outputs/s2.bam", + ], + gene_counts: "https://wes.example.org/runs/run-16/outputs/counts", + }, + unmatchedFiles: [ + "https://wes.example.org/runs/run-16/outputs/report%20%231.html", + ], + }, + options: { + outputDir: "https://wes.example.org/runs/run-16/outputs", + }, + run_log: { + run_id: "run-16", + state: "COMPLETE", + outputs: [ + { + file_name: "counts/s1.tsv", + file_url: "https://wes.example.org/runs/run-16/outputs/counts/s1.tsv", + }, + { + file_name: "multiqc_report.html", + file_url: + "https://wes.example.org/runs/run-16/outputs/multiqc_report.html", + }, + { + file_name: "report #1.html", + file_url: + "https://wes.example.org/runs/run-16/outputs/report%20%231.html", + }, + { + file_name: "s1.bam", + file_url: "https://wes.example.org/runs/run-16/outputs/s1.bam", + }, + { + file_name: "s1.bam.bai", + file_url: "https://wes.example.org/runs/run-16/outputs/s1.bam.bai", + }, + { + file_name: "s2.bam", + file_url: "https://wes.example.org/runs/run-16/outputs/s2.bam", + }, + { + file_name: "s2.bam.bai", + file_url: "https://wes.example.org/runs/run-16/outputs/s2.bam.bai", + }, + ], + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq-qc/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-output-glob": "multiqc_report.html", + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "*.bam", + }, + gene_counts: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + "x-ga4gh-output-glob": "counts", + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "sapporo-listing", + expected: { + description: + "Sapporo (2.x): RunLog.outputs is a list of files, each with file_name (relative to the output directory of the run) and file_url. Outputs are found by glob; secondary files are not values of their own; files that no output finds are reported.", + conformance: "conformant", + outputs: { + qc_report: + "https://wes.example.org/runs/run-5/outputs/multiqc/multiqc_report.html", + alignments: [ + "https://wes.example.org/runs/run-5/outputs/alignments/s1.bam", + "https://wes.example.org/runs/run-5/outputs/alignments/s2.bam", + ], + }, + unmatchedFiles: [ + "https://wes.example.org/runs/run-5/outputs/counts/s1.tsv", + "https://wes.example.org/runs/run-5/outputs/pipeline_info/report%20%231.html", + ], + }, + options: { + outputDir: "https://wes.example.org/runs/run-5/outputs", + }, + run_log: { + run_id: "run-5", + state: "COMPLETE", + outputs: [ + { + file_name: "alignments/s1.bam", + file_url: + "https://wes.example.org/runs/run-5/outputs/alignments/s1.bam", + }, + { + file_name: "alignments/s1.bam.bai", + file_url: + "https://wes.example.org/runs/run-5/outputs/alignments/s1.bam.bai", + }, + { + file_name: "alignments/s2.bam", + file_url: + "https://wes.example.org/runs/run-5/outputs/alignments/s2.bam", + }, + { + file_name: "alignments/s2.bam.bai", + file_url: + "https://wes.example.org/runs/run-5/outputs/alignments/s2.bam.bai", + }, + { + file_name: "counts/s1.tsv", + file_url: "https://wes.example.org/runs/run-5/outputs/counts/s1.tsv", + }, + { + file_name: "multiqc/multiqc_report.html", + file_url: + "https://wes.example.org/runs/run-5/outputs/multiqc/multiqc_report.html", + }, + { + file_name: "pipeline_info/report #1.html", + file_url: + "https://wes.example.org/runs/run-5/outputs/pipeline_info/report%20%231.html", + }, + ], + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/nfl/1.0.0", + title: "RNA-Seq Pipeline", + description: "Bulk RNA-Seq alignment and QC workflow.", + "x-ga4gh-workflow": { + trs_tool_id: "#workflow/example.org/rna-seq", + trs_version_id: "1.0.0", + descriptor_type: "NFL", + descriptor_type_version: "DSL2", + primary_descriptor_path: "main.nf", + checksum: [ + { + type: "sha-256", + checksum: + "3f7a2c9e1b4d6f8a0c2e4b6d8f1a3c5e7b9d0f2a4c6e8b1d3f5a7c9e0b2d4f6a", + }, + ], + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: { + sample_manifest: { + type: "string", + title: "Sample Manifest", + description: + "CSV sample sheet containing biological replicate information.", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/csv", + schemes: ["drs", "https"], + }, + "x-ga4gh-tabular-schema": { + type: "array", + description: + "Experimental hint: the expected columns of the CSV sample sheet (not a validation rule).", + items: { + type: "object", + properties: { + sample_id: { + type: "string", + title: "Sample ID", + pattern: "^[a-zA-Z0-9_]+$", + }, + fastq_1: { + type: "string", + title: "Read 1 FASTQ", + "x-ga4gh-file": { + kind: "file", + compression: "gzip", + }, + }, + condition: { + type: "string", + title: "Condition", + enum: ["control", "treatment"], + }, + }, + required: ["sample_id", "fastq_1", "condition"], + }, + }, + }, + genome_index: { + type: "string", + title: "Genome Index", + description: + "Directory with the index of the reference genome for the aligner.", + "x-ga4gh-file": { + kind: "directory", + }, + }, + known_variants: { + type: "string", + title: "Known Variants", + description: + "Variants to mask during QC, as a VCF file indexed with tabix.", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_3016", + compression: "bgzip", + secondaryFiles: [".tbi"], + }, + }, + }, + required: ["sample_manifest", "genome_index"], + additionalProperties: false, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + title: "QC HTML Report", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-ui-widget": "html-viewer", + "x-ga4gh-output-glob": "multiqc/multiqc_report.html", + }, + alignments: { + type: "array", + title: "Aligned Reads", + description: + "One BAM file per sample, each with its index next to it.", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + ontology: "http://edamontology.org/format_2572", + secondaryFiles: [".bai"], + }, + }, + "x-ga4gh-output-glob": "alignments/*.bam", + }, + gene_counts: { + type: "object", + title: "Gene Counts", + description: "Gene counts per sample, keyed by sample ID.", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/tab-separated-values", + }, + "x-ga4gh-ui-widget": "table-viewer", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + title: "Samples Passing QC", + }, + }, + required: ["qc_report", "alignments"], + additionalProperties: false, + }, + }, + }, + }, + { + name: "schema-without-outputs", + expected: { + description: + "A schema without outputs: the normalised outputs object is empty, and everything that the engine reports is undeclared.", + conformance: "conformant", + outputs: {}, + undeclared: ["report"], + }, + run_log: { + run_id: "run-13", + state: "COMPLETE", + outputs: { + report: "s3://example-bucket/r.html", + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/no-outputs/cwl/1.0.0", + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + }, + }, + }, + { + name: "toil-cwl-local-files", + expected: { + description: + "Toil (9.5) WES server with toil-cwl-runner, local job store: the CWL output object, files and a Directory as objects with percent-encoded file: locations (a name with a space and #) and raw paths, secondary files, null for an optional output that wasn't produced, and an integer. Captured from a real run; paths and run ID anonymised.", + conformance: "conformant", + outputs: { + qc_report: + "https://wes.example.org/toil/runs/run-17/outputs/multiqc_report.html", + alignments: [ + "https://wes.example.org/toil/runs/run-17/outputs/s1.bam", + "https://wes.example.org/toil/runs/run-17/outputs/s2.bam", + ], + gene_counts: "https://wes.example.org/toil/runs/run-17/outputs/counts", + pipeline_report: + "https://wes.example.org/toil/runs/run-17/outputs/report%20%231.html", + samples_passed_qc: 2, + }, + }, + options: { + outputDir: "https://wes.example.org/toil/runs/run-17/outputs", + localDir: "/data/toil/workflows/run-17/outputs", + }, + run_log: { + run_id: "run-17", + state: "COMPLETE", + outputs: { + alignments: [ + { + basename: "s1.bam", + checksum: "sha1$7af258594b50ff874a047b54a92442e81f458cfb", + class: "File", + location: "file:///data/toil/workflows/run-17/outputs/s1.bam", + nameext: ".bam", + nameroot: "s1", + path: "/data/toil/workflows/run-17/outputs/s1.bam", + secondaryFiles: [ + { + basename: "s1.bam.bai", + checksum: "sha1$d4f506d11f53beffb8d67eda0740af3a887a992e", + class: "File", + location: + "file:///data/toil/workflows/run-17/outputs/s1.bam.bai", + nameext: ".bai", + nameroot: "s1.bam", + path: "/data/toil/workflows/run-17/outputs/s1.bam.bai", + size: 2, + }, + ], + size: 3, + }, + { + basename: "s2.bam", + checksum: "sha1$7af258594b50ff874a047b54a92442e81f458cfb", + class: "File", + location: "file:///data/toil/workflows/run-17/outputs/s2.bam", + nameext: ".bam", + nameroot: "s2", + path: "/data/toil/workflows/run-17/outputs/s2.bam", + secondaryFiles: [ + { + basename: "s2.bam.bai", + checksum: "sha1$d4f506d11f53beffb8d67eda0740af3a887a992e", + class: "File", + location: + "file:///data/toil/workflows/run-17/outputs/s2.bam.bai", + nameext: ".bai", + nameroot: "s2.bam", + path: "/data/toil/workflows/run-17/outputs/s2.bam.bai", + size: 2, + }, + ], + size: 3, + }, + ], + gene_counts: { + basename: "counts", + class: "Directory", + listing: [ + { + basename: "s1.tsv", + checksum: "sha1$165505b60a863826442272a60e78fc160ca309c8", + class: "File", + location: + "file:///data/toil/workflows/run-17/outputs/counts/s1.tsv", + nameext: ".tsv", + nameroot: "s1", + path: "/data/toil/workflows/run-17/outputs/counts/s1.tsv", + size: 4, + }, + ], + location: "file:///data/toil/workflows/run-17/outputs/counts", + nameext: "", + nameroot: "counts", + path: "/data/toil/workflows/run-17/outputs/counts", + }, + missing_optional: null, + pipeline_report: { + basename: "report #1.html", + checksum: "sha1$941efb7368e46b27b937d34b07fc4d41da01b002", + class: "File", + location: + "file:///data/toil/workflows/run-17/outputs/report%20%231.html", + nameext: ".html", + nameroot: "report #1", + path: "/data/toil/workflows/run-17/outputs/report #1.html", + size: 13, + }, + qc_report: { + basename: "multiqc_report.html", + checksum: "sha1$941efb7368e46b27b937d34b07fc4d41da01b002", + class: "File", + location: + "file:///data/toil/workflows/run-17/outputs/multiqc_report.html", + nameext: ".html", + nameroot: "multiqc_report", + path: "/data/toil/workflows/run-17/outputs/multiqc_report.html", + size: 13, + }, + samples_passed_qc: 2, + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq-qc/cwl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "CWL", + descriptor_type_version: "v1.2", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".bai"], + }, + }, + }, + gene_counts: { + type: "string", + "x-ga4gh-file": { + kind: "directory", + }, + }, + pipeline_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + }, + samples_passed_qc: { + type: "integer", + minimum: 0, + }, + missing_optional: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "wdl-local-paths", + expected: { + description: + "WDL outputs as absolute local paths (as miniwdl reports them), turned into URIs of the output directory; x-ga4gh-parameter names the output in the engine; a path outside the output directory is reported, not converted.", + conformance: "conformant", + outputs: { + variants_vcf: + "https://wes.example.org/runs/run-4/files/out/vcf/calls%201.vcf.gz", + stats: "https://wes.example.org/runs/run-4/files/out/stats/calls.stats", + }, + unconverted: ["log"], + }, + options: { + outputDir: "https://wes.example.org/runs/run-4/files/", + localDir: "/data/wes/runs/run-4/", + }, + run_log: { + run_id: "run-4", + state: "COMPLETE", + outputs: { + "variant_calling.vcf": "/data/wes/runs/run-4/out/vcf/calls 1.vcf.gz", + "variant_calling.stats": + "file:///data/wes/runs/run-4/out/stats/calls.stats", + "variant_calling.log": "/scratch/tmp/run-4.log", + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/variant-calling/wdl/1.2.0", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + descriptor_type_version: "1.1", + entry_point: "variant_calling", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + variants_vcf: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + "x-ga4gh-parameter": { + name: "vcf", + type: "File", + }, + }, + stats: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + log: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + additionalProperties: false, + required: ["variants_vcf"], + }, + }, + }, + }, + { + name: "wdl-qualified-names", + expected: { + description: + "WDL outputs keyed by names qualified with the workflow name, as Cromwell, miniwdl and Conquest report them: null for an optional output and for an item of Array[File?], Map[String, File] as files keyed by name, and an output that the schema doesn't declare.", + conformance: "conformant", + outputs: { + qc_report: + "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-multiqc/multiqc_report.html", + alignments: [ + "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-align/shard-0/s1.bam", + "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-align/shard-2/s3.bam", + ], + gene_counts: { + s1: "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-count/shard-0/s1.tsv", + s3: "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-count/shard-2/s3.tsv", + }, + samples_passed_qc: 2, + }, + undeclared: ["rnaseq.debug_log"], + }, + run_log: { + run_id: "run-3", + state: "COMPLETE", + outputs: { + "rnaseq.qc_report": + "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-multiqc/multiqc_report.html", + "rnaseq.alignments": [ + "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-align/shard-0/s1.bam", + null, + "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-align/shard-2/s3.bam", + ], + "rnaseq.gene_counts": { + s1: "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-count/shard-0/s1.tsv", + s3: "gs://example-bucket/cromwell-executions/rnaseq/run-3/call-count/shard-2/s3.tsv", + }, + "rnaseq.optional_plot": null, + "rnaseq.samples_passed_qc": 2, + "rnaseq.debug_log": + "gs://example-bucket/cromwell-executions/rnaseq/run-3/debug.log", + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/rna-seq/wdl/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "WDL", + descriptor_type_version: "1.0", + entry_point: "rnaseq", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + qc_report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + alignments: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + gene_counts: { + type: "object", + additionalProperties: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + }, + optional_plot: { + type: "string", + "x-ga4gh-file": { + kind: "file", + }, + }, + samples_passed_qc: { + type: "integer", + }, + }, + additionalProperties: false, + required: ["qc_report", "alignments"], + }, + }, + }, + }, + { + name: "weskit-listing", + expected: { + description: + 'WESkit (master of 2026-07, Snakemake 9.16.3): RunLog.outputs is {"filesystem": [...]}, the files of the working directory of the run, relative to it, in the order of the file system, and, with S3, presigned URLs of the same files (bucket: the first four characters of the run ID), which carry credentials and are ignored. Matches are sorted by code point (B before a). Captured from a real run; run ID anonymised, signatures redacted.', + conformance: "conformant", + outputs: { + calls: [ + "s3://wesk/weskit-run-6/results/calls/B.vcf.gz", + "s3://wesk/weskit-run-6/results/calls/a.vcf.gz", + ], + report: "s3://wesk/weskit-run-6/results/report.html", + }, + unmatchedFiles: [ + "s3://wesk/weskit-run-6/.snakemake/log/2026-11-13T020908.258601.snakemake.log", + "s3://wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9CLnZjZi5neg%3D%3D", + "s3://wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9CLnZjZi5nei50Ymk%3D", + "s3://wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9hLnZjZi5neg%3D%3D", + "s3://wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9hLnZjZi5nei50Ymk%3D", + "s3://wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9yZXBvcnQuaHRtbA%3D%3D", + "s3://wesk/weskit-run-6/config.yaml", + ], + }, + options: { + outputDir: "s3://wesk/weskit-run-6", + }, + run_log: { + run_id: "weskit-run-6", + state: "COMPLETE", + outputs: { + S3: [ + "https://s3.example.org/wesk/weskit-run-6/config.yaml?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/results/report.html?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/results/calls/a.vcf.gz?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/results/calls/B.vcf.gz.tbi?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/results/calls/B.vcf.gz?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/results/calls/a.vcf.gz.tbi?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/.snakemake/log/2026-11-13T020908.258601.snakemake.log?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9CLnZjZi5neg%3D%3D?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9yZXBvcnQuaHRtbA%3D%3D?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9CLnZjZi5nei50Ymk%3D?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9hLnZjZi5nei50Ymk%3D?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + "https://s3.example.org/wesk/weskit-run-6/.snakemake/metadata/cmVzdWx0cy9jYWxscy9hLnZjZi5neg%3D%3D?AWSAccessKeyId=EXAMPLEKEYID&Signature=REDACTED&Expires=1794539353", + ], + filesystem: [ + "config.yaml", + "results/report.html", + "results/calls/a.vcf.gz", + "results/calls/B.vcf.gz.tbi", + "results/calls/B.vcf.gz", + "results/calls/a.vcf.gz.tbi", + ".snakemake/log/2026-11-13T020908.258601.snakemake.log", + ".snakemake/metadata/cmVzdWx0cy9jYWxscy9CLnZjZi5neg==", + ".snakemake/metadata/cmVzdWx0cy9yZXBvcnQuaHRtbA==", + ".snakemake/metadata/cmVzdWx0cy9jYWxscy9CLnZjZi5nei50Ymk=", + ".snakemake/metadata/cmVzdWx0cy9jYWxscy9hLnZjZi5nei50Ymk=", + ".snakemake/metadata/cmVzdWx0cy9jYWxscy9hLnZjZi5neg==", + ], + }, + }, + schema: { + $schema: + "https://raw.githubusercontent.com/elixir-cloud-aai/ga4gh-io-schema/main/schemas/ga4gh-io-profile.schema.json", + $id: "https://example.org/schemas/variant-calling/smk/1.0.0", + "x-ga4gh-workflow": { + descriptor_type: "SMK", + }, + type: "object", + properties: { + inputs: { + type: "object", + properties: {}, + }, + outputs: { + type: "object", + properties: { + calls: { + type: "array", + items: { + type: "string", + "x-ga4gh-file": { + kind: "file", + secondaryFiles: [".tbi"], + }, + }, + "x-ga4gh-output-glob": "results/calls/*.vcf.gz", + }, + report: { + type: "string", + "x-ga4gh-file": { + kind: "file", + mediaType: "text/html", + }, + "x-ga4gh-output-glob": "results/report.html", + }, + }, + additionalProperties: false, + required: ["calls", "report"], + }, + }, + }, + }, +]; diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/tests/outputs.test.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/outputs.test.ts new file mode 100644 index 00000000..d2368472 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/tests/outputs.test.ts @@ -0,0 +1,535 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import { + displaySchema, + matchGlob, + NormalisationError, + normaliseOutputs, + secondaryName, +} from "../outputs.js"; +import { PROFILE_SCHEMA } from "../profile.js"; +import { getIoSchemaValidator, setIoSchemaValidator } from "../validator.js"; +import { WES_OUTPUTS_CASES } from "./fixtures/wes-outputs.js"; + +const PROFILE_ID = PROFILE_SCHEMA.$id as string; + +/** An IO schema with the given outputs. */ +const ioSchema = ( + outputs: Record | undefined, + extra: Record = {} +): Record => ({ + $schema: PROFILE_ID, + type: "object", + properties: { + inputs: { type: "object" }, + ...(outputs ? { outputs: { type: "object", ...outputs } } : {}), + }, + ...extra, +}); + +const FILE = { type: "string", "x-ga4gh-file": { kind: "file" } }; + +/** 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."); +} + +const sortedKeys = (value: Record) => + Object.keys(value).sort(); + +describe("normaliseOutputs", () => { + describe("test vectors (wes-outputs)", () => { + for (const vector of WES_OUTPUTS_CASES) { + it(vector.name, async () => { + const result = normaliseOutputs( + vector.schema, + vector.run_log, + vector.options ?? {} + ); + if (vector.error) { + expect(await rejection(result)).to.be.instanceOf(NormalisationError); + return; + } + const { expected } = vector; + if (!expected) throw new Error("The vector has no expected result."); + const actual = await result; + expect(actual.conformance).to.equal(expected.conformance); + expect(actual.outputs).to.deep.equal(expected.outputs); + expect(sortedKeys(actual.removed)).to.deep.equal( + expected.removed ?? [] + ); + expect(actual.ambiguous).to.deep.equal(expected.ambiguous ?? {}); + expect( + actual.unconverted.map(({ output }) => output).sort() + ).to.deep.equal(expected.unconverted ?? []); + expect(sortedKeys(actual.undeclared)).to.deep.equal( + expected.undeclared ?? [] + ); + expect(actual.unmatchedFiles).to.deep.equal( + expected.unmatchedFiles ?? [] + ); + expect(actual.skippedFiles.map(({ entry }) => entry)).to.deep.equal( + expected.skippedFiles ?? [] + ); + }); + } + }); + + it("rejects a schema that doesn't conform to the profile", async () => { + const error = await rejection( + normaliseOutputs( + { $schema: PROFILE_ID, type: "array" }, + { + state: "COMPLETE", + } + ) + ); + expect(error).to.be.instanceOf(NormalisationError); + expect((error as NormalisationError).schemaErrors.length).to.be.above(0); + }); + + it("rejects a run that hasn't ended, and a run log that isn't an object", async () => { + const schema = ioSchema({ properties: { r: FILE } }); + for (const runLog of [{ state: "RUNNING" }, {}, null, []]) { + // eslint-disable-next-line no-await-in-loop + const error = await rejection(normaliseOutputs(schema, runLog)); + expect(error).to.be.instanceOf(NormalisationError); + } + }); + + it("rejects outputs of an unsupported shape and inconsistent options", async () => { + const schema = ioSchema({ properties: { r: FILE } }); + const cases: [unknown, Record][] = [ + [{ state: "COMPLETE", outputs: "out.txt" }, {}], + [{ state: "COMPLETE" }, { outputDir: "out" }], + [{ state: "COMPLETE" }, { outputDir: "s3://b/out?x=1" }], + [{ state: "COMPLETE" }, { localDir: "/data" }], + [{ state: "COMPLETE" }, { outputDir: "s3://b/o", localDir: "data" }], + [{ state: "COMPLETE" }, { files: "a.txt" }], + [{ state: "COMPLETE" }, { files: ["a.txt"] }], + ]; + for (const [runLog, options] of cases) { + // eslint-disable-next-line no-await-in-loop + const error = await rejection(normaliseOutputs(schema, runLog, options)); + expect(error, JSON.stringify(options)).to.be.instanceOf( + NormalisationError + ); + } + }); + + it("rejects outputs with the same name in the engine", async () => { + const schema = ioSchema({ + properties: { + a: { ...FILE, "x-ga4gh-parameter": { name: "x" } }, + x: FILE, + }, + }); + const error = await rejection( + normaliseOutputs(schema, { state: "COMPLETE", outputs: {} }) + ); + expect(error).to.be.instanceOf(NormalisationError); + }); + + it("validates file references: absolute URIs with one of the schemes", async () => { + const schema = ioSchema( + { + properties: { + r: { + type: "string", + "x-ga4gh-file": { kind: "file", schemes: ["s3"] }, + }, + list: { type: "array", items: { $ref: "#/$defs/file" } }, + }, + }, + { $defs: { file: FILE } } + ); + const result = await normaliseOutputs(schema, { + state: "COMPLETE", + outputs: { r: "https://data.example.org/r.txt", list: [{ a: 1 }] }, + }); + expect(result.conformance).to.equal("non-conformant"); + expect(result.outputs.r).to.equal("https://data.example.org/r.txt"); + expect(result.errors.map(({ pointer }) => pointer)).to.deep.equal([ + "/list/0", + "/r", + ]); + expect(result.errors.map(({ output }) => output)).to.deep.equal([ + "list", + "r", + ]); + }); + + it("reports an error of the whole object without an output", async () => { + const schema = ioSchema({ properties: { r: FILE }, required: ["r"] }); + const result = await normaliseOutputs(schema, { + state: "COMPLETE", + outputs: {}, + }); + expect(result.conformance).to.equal("non-conformant"); + expect(result.errors[0].output).to.equal(null); + expect(result.errors[0].pointer).to.equal(""); + }); + + it("takes everything as undeclared from a schema without outputs", async () => { + const result = await normaliseOutputs(ioSchema(undefined), { + state: "COMPLETE", + outputs: { report: "s3://b/r.html" }, + }); + expect(result.conformance).to.equal("conformant"); + expect(result.outputs).to.deep.equal({}); + expect(result.undeclared).to.deep.equal({ report: "s3://b/r.html" }); + }); + + it("converts paths in records, files keyed by name and single branches", async () => { + const schema = ioSchema( + { + properties: { + rec: { + type: "object", + properties: { f: { anyOf: [{ type: "null" }, FILE] }, n: {} }, + }, + keyed: { type: "object", additionalProperties: FILE }, + ref: { $ref: "https://example.org/s#/$defs/file" }, + }, + }, + { + $id: "https://example.org/s", + $defs: { file: FILE }, + } + ); + const result = await normaliseOutputs( + schema, + { + state: "COMPLETE", + outputs: { + rec: { f: "/work/out/a b.txt", n: null }, + keyed: { s1: "file:///work/out/s1.tsv", s2: null }, + ref: { class: "File", path: "x/y.txt" }, + }, + }, + { outputDir: "s3://bucket/run/", localDir: "/work/out/" } + ); + expect(result.outputs.rec).to.deep.equal({ + f: "s3://bucket/run/a%20b.txt", + n: null, + }); + expect(result.outputs.keyed).to.deep.equal({ + s1: "s3://bucket/run/s1.tsv", + s2: null, + }); + expect(result.outputs.ref).to.equal("s3://bucket/run/x/y.txt"); + // null in an object is kept, for validation to report + expect(result.conformance).to.equal("non-conformant"); + }); + + it("reports values that can't be given as URIs", async () => { + const schema = ioSchema({ + properties: { + a: FILE, + b: FILE, + c: FILE, + d: FILE, + e: FILE, + f: FILE, + g: FILE, + }, + }); + const result = await normaliseOutputs( + schema, + { + state: "COMPLETE", + outputs: { + a: "C:\\data\\r.html", + b: "/other/r.html", + c: "file://host/work/r.html", + d: { class: "File" }, + e: "file:///work/%E0%A4%A.txt", + f: "file:///work/%C3%28.txt", + g: "../r.html", + }, + }, + { outputDir: "s3://bucket/run", localDir: "/work" } + ); + expect(result.unconverted.map(({ output }) => output)).to.deep.equal([ + "a", + "b", + "c", + "d", + "e", + "f", + "g", + ]); + expect(result.outputs).to.deep.equal({}); + }); + + it("reports a relative path without an output directory", async () => { + const result = await normaliseOutputs( + ioSchema({ properties: { a: FILE } }), + { state: "COMPLETE", outputs: { a: "r.html" } } + ); + expect(result.unconverted[0].reason).to.match(/no output directory/); + }); + + it("drops WESkit's presigned URLs unless the schema declares S3", async () => { + const outputs = { + filesystem: ["r.html"], + S3: ["https://b.example.org/r.html?Signature=secret"], + }; + const withoutS3 = await normaliseOutputs( + ioSchema({ + properties: { r: { ...FILE, "x-ga4gh-output-glob": "*.html" } }, + }), + { state: "COMPLETE", outputs }, + { outputDir: "s3://bucket/run" } + ); + expect(withoutS3.outputs).to.deep.equal({ r: "s3://bucket/run/r.html" }); + expect(JSON.stringify(withoutS3)).not.to.contain("secret"); + + const withS3 = await normaliseOutputs( + ioSchema({ properties: { S3: { type: "array" } } }), + { state: "COMPLETE", outputs } + ); + expect(withS3.outputs.S3).to.deep.equal(outputs.S3); + expect(withS3.undeclared).to.have.property("filesystem"); + }); + + it("checks listed paths and URIs", async () => { + const schema = ioSchema({ + properties: { + all: { + type: "array", + items: FILE, + "x-ga4gh-output-glob": "**", + }, + }, + }); + const files = [ + "ok/a.txt", + "/abs.txt", + "a//b.txt", + "./a.txt", + "a/../b.txt", + "a\\b.txt", + "a\u0007.txt", + "c:d/e.txt", + "\uD800.txt", + 42, + { name: "x" }, + "s3://bucket/run/ok/b%20c.txt", + "s3://bucket/run/x%2F..%2Fy.txt", + "s3://bucket/run/q.txt?x=1", + "s3://user:pw@bucket/run/elsewhere.txt#f", + "s3://other/run/a.txt", + "s3://bucket/run/bad%zz.txt", + "s3://bucket/run/bad%C3%28.txt", + ]; + const result = await normaliseOutputs( + schema, + { state: "COMPLETE" }, + { outputDir: "s3://bucket/run", files } + ); + expect(result.outputs.all).to.deep.equal([ + "s3://bucket/run/ok/a.txt", + "s3://bucket/run/ok/b%20c.txt", + ]); + expect(result.skippedFiles.map(({ entry }) => entry)).to.deep.equal([ + "/abs.txt", + "a//b.txt", + "./a.txt", + "a/../b.txt", + "a\\b.txt", + "a\u0007.txt", + "c:d/e.txt", + "\uD800.txt", + 42, + { type: "object" }, + "s3://bucket/run/x%2F..%2Fy.txt", + "s3://bucket/run/q.txt", + "s3://bucket/run/elsewhere.txt", + "s3://other/run/a.txt", + "s3://bucket/run/bad%zz.txt", + "s3://bucket/run/bad%C3%28.txt", + ]); + }); + + it("encodes every character but the unreserved ones", async () => { + const schema = ioSchema({ + properties: { r: { ...FILE, "x-ga4gh-output-glob": "*" } }, + }); + const result = await normaliseOutputs( + schema, + { state: "COMPLETE" }, + { outputDir: "s3://bucket/run", files: ["s 1#!'()*~é.tsv"] } + ); + expect(result.outputs.r).to.equal( + "s3://bucket/run/s%201%23%21%27%28%29%2A~%C3%A9.tsv" + ); + }); + + it("finds directories that contain listed files", async () => { + const schema = ioSchema({ + properties: { + dirs: { + type: "array", + items: { type: "string", "x-ga4gh-file": { kind: "directory" } }, + "x-ga4gh-output-glob": "results/*", + }, + }, + }); + const result = await normaliseOutputs( + schema, + { state: "COMPLETE" }, + { + outputDir: "s3://bucket/run", + files: ["results/b/x.txt", "results/a/y/z.txt", "other.txt"], + } + ); + expect(result.outputs.dirs).to.deep.equal([ + "s3://bucket/run/results/a", + "s3://bucket/run/results/b", + ]); + expect(result.unmatchedFiles).to.deep.equal(["s3://bucket/run/other.txt"]); + }); + + it("sorts by code points, not by UTF-16 code units", async () => { + const schema = ioSchema({ + properties: { + all: { type: "array", items: FILE, "x-ga4gh-output-glob": "*" }, + }, + }); + const result = await normaliseOutputs( + schema, + { state: "COMPLETE" }, + { outputDir: "s3://b/r", files: ["\uFF5E.txt", "\u{1F600}.txt"] } + ); + expect(result.outputs.all).to.deep.equal([ + "s3://b/r/%EF%BD%9E.txt", + "s3://b/r/%F0%9F%98%80.txt", + ]); + }); + + it("doesn't change the schema or the run log", async () => { + const schema = ioSchema({ properties: { r: FILE } }); + const runLog = { state: "COMPLETE", outputs: { r: "x.txt", S3: [] } }; + const copies = JSON.stringify([schema, runLog]); + await normaliseOutputs(schema, runLog, { outputDir: "s3://b/r" }); + expect(JSON.stringify([schema, runLog])).to.equal(copies); + }); + + it("keeps members named __proto__", async () => { + const schema = ioSchema({ + properties: { rec: { type: "object", additionalProperties: FILE } }, + }); + const outputs = JSON.parse('{"rec": {"__proto__": "s3://b/r/a.txt"}}'); + const result = await normaliseOutputs(schema, { + state: "COMPLETE", + outputs, + }); + expect( + Object.prototype.hasOwnProperty.call(result.outputs.rec, "__proto__") + ).to.equal(true); + }); + + it("needs a validator that validates outputs", async () => { + const original = getIoSchemaValidator(); + setIoSchemaValidator({ + check: async () => ({ + valid: true, + errors: [], + validateInputs: () => ({ valid: true, errors: [] }), + }), + }); + try { + const error = await rejection( + normaliseOutputs(ioSchema({ properties: {} }), { state: "COMPLETE" }) + ); + expect(error).to.be.instanceOf(NormalisationError); + } finally { + setIoSchemaValidator(original); + } + }); +}); + +describe("normaliseOutputs limits", () => { + it("reports deeply nested values without exhausting the stack", async () => { + let deep: unknown = ["x"]; + for (let i = 0; i < 6000; i += 1) deep = [deep]; + const result = await normaliseOutputs( + ioSchema({ properties: { r: { type: "array", items: FILE } } }), + { state: "COMPLETE", outputs: { r: deep } } + ); + expect(result.unconverted.map(({ output }) => output)).to.deep.equal(["r"]); + }); +}); + +describe("displaySchema", () => { + it("follows references and single branches, also of items", () => { + const document = { + $defs: { + file: { ...FILE, title: "A file" }, + list: { type: "array", items: { $ref: "#/$defs/file" } }, + }, + }; + expect( + displaySchema(document, { $ref: "#/$defs/list", title: "Chunks" }) + ).to.deep.equal({ + type: "array", + title: "Chunks", + items: { ...FILE, title: "A file" }, + }); + expect( + displaySchema(document, { + anyOf: [{ $ref: "#/$defs/file" }, { type: "null" }], + title: "Optional", + }) + ).to.deep.equal({ ...FILE, title: "Optional" }); + expect(displaySchema(document, { $ref: "#/nowhere" })).to.deep.equal({ + $ref: "#/nowhere", + }); + }); +}); + +describe("matchGlob", () => { + const cases: [string, string, boolean][] = [ + ["*.bam", "a.bam", true], + ["*.bam", "dir/a.bam", false], + ["**/*.bam", "a.bam", true], + ["**/*.bam", "x/y/a.bam", true], + ["a/**", "a", true], + ["a/**", "b", false], + ["a/**", "a/b/c", true], + ["**", "a", true], + ["?.txt", "a.txt", true], + ["?.txt", "ab.txt", false], + ["*", ".hidden", true], + ["a*b*c", "aXbYc", true], + ["a*b*c", "aXbY", false], + ["A.txt", "a.txt", false], + ]; + for (const [glob, path, expected] of cases) { + it(`${glob} ${expected ? "matches" : "doesn't match"} ${path}`, () => { + expect(matchGlob(glob.split("/"), path.split("/"))).to.equal(expected); + }); + } + + it("takes time polynomial in the lengths", () => { + const glob = `${"*a".repeat(30)}b`; + const start = Date.now(); + expect(matchGlob([glob], ["a".repeat(5000)])).to.equal(false); + expect(Date.now() - start).to.be.below(2000); + }); +}); + +describe("secondaryName", () => { + it("appends a suffix, or replaces extensions with carets", () => { + expect(secondaryName("s1.bam", ".bai")).to.equal("s1.bam.bai"); + expect(secondaryName("s1.bam", "^.bai")).to.equal("s1.bai"); + expect(secondaryName("s1.vcf.gz", "^^.idx")).to.equal("s1.idx"); + expect(secondaryName("noext", "^.idx")).to.equal("noext.idx"); + }); +}); 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 6b4ca0a1..cc619b22 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 @@ -409,3 +409,69 @@ describe("decidingLocations and validateAt", () => { ).to.throw(); }); }); + +describe("validateOutputs", () => { + const PROFILE = PROFILE_SCHEMA.$id as string; + const withOutputs = { + $schema: PROFILE, + type: "object", + properties: { + inputs: { type: "object" }, + outputs: { + type: "object", + properties: { + "a/b": { type: "integer" }, + "x#y%z~": { type: "integer" }, + count: { $ref: "#/$defs/count" }, + }, + required: ["count"], + }, + }, + $defs: { count: { type: "integer", minimum: 0 } }, + }; + + const validatorOf = async (document: unknown) => { + const result = await checkIoSchema(document); + if (!result.valid || !result.validateOutputs) { + throw new Error("The schema wasn't accepted."); + } + return result.validateOutputs; + }; + + it("validates the outputs object against outputs", async () => { + const validateOutputs = await validatorOf(withOutputs); + expect(validateOutputs({ count: 2 })).to.deep.equal({ + valid: true, + errors: [], + }); + const { valid, errors } = validateOutputs({ count: -1, "a/b": "x" }); + expect(valid).to.equal(false); + expect(errors.map(({ pointer }) => pointer).sort()).to.deep.equal([ + "/a~1b", + "/count", + ]); + expect(validateOutputs({}).errors[0].pointer).to.equal(""); + }); + + it("validates one output, with pointers into the outputs object", async () => { + const validateOutputs = await validatorOf(withOutputs); + expect(validateOutputs(-1, "count").errors[0].pointer).to.equal("/count"); + expect(validateOutputs("x", "a/b").errors[0].pointer).to.equal("/a~1b"); + expect(validateOutputs(3, "count").valid).to.equal(true); + expect(validateOutputs("x", "x#y%z~").errors[0].pointer).to.equal( + "/x#y%z~0" + ); + }); + + it("accepts outputs that the schema doesn't declare, and schemas without outputs", async () => { + const validateOutputs = await validatorOf(withOutputs); + expect(validateOutputs("anything", "other").valid).to.equal(true); + const without = await validatorOf({ + $schema: PROFILE, + type: "object", + properties: { inputs: { type: "object" } }, + }); + expect(without({ x: 1 }).valid).to.equal(true); + expect(without(1, "x").valid).to.equal(true); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts b/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts index 76f05856..e39b9e67 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/trs.ts @@ -78,7 +78,7 @@ export function findPrimaryDescriptorPath(files: unknown): string | null { * Percent-encodes a path segment: every character but the unreserved ones * of RFC 3986 (`encodeURIComponent` also keeps `!'()*`). */ -const encodeSegment = (segment: string) => +export const encodeSegment = (segment: string) => encodeURIComponent(segment).replace( /[!'()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}` 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 3e9f3343..e561b9e9 100644 --- a/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts +++ b/packages/ecc-client-ga4gh-wes/src/io-schema/validator.ts @@ -61,6 +61,19 @@ export type InputsValidator = (values: unknown) => { */ export type SubschemaValidator = (pointer: string, value: unknown) => boolean; +/** + * Validates output values against `outputs` of a checked IO schema: the + * normalised outputs object against `outputs`, or, with `output`, one + * value against the schema of that output (for runs that didn't complete). + * Errors point into the outputs object. File references are not checked + * here (`x-ga4gh-file` is an annotation for JSON Schema). A schema without + * `outputs`, or an output it doesn't declare, accepts everything. + */ +export type OutputsValidator = ( + value: unknown, + output?: string +) => { valid: boolean; errors: ValidationError[] }; + /** The result of checking an IO schema. */ export type IoSchemaCheck = | { @@ -73,6 +86,12 @@ export type IoSchemaCheck = * be used to build run requests */ validateAt?: SubschemaValidator; + /** + * Validates output values, for the output normaliser + * (`normaliseOutputs`); a validator without it can't be used to + * normalise outputs + */ + validateOutputs?: OutputsValidator; } | { valid: false; errors: ValidationError[] }; @@ -277,11 +296,12 @@ const unusable = (error: unknown): IoSchemaCheck => ({ ], }); -/** Locations to compile besides `inputs`, so that all their refs resolve */ +/** + * Locations to compile besides `inputs` and `outputs`, so that all their + * refs resolve + */ function otherLocations(document: Record): string[] { const locations: string[] = []; - const properties = isObject(document.properties) ? document.properties : {}; - if ("outputs" in properties) locations.push("/properties/outputs"); for (const keyword of ["$defs", "definitions"]) { const value = document[keyword]; if (isObject(value)) { @@ -293,6 +313,13 @@ function otherLocations(document: Record): string[] { return locations; } +/** The names of the outputs of a document (`outputs.properties`). */ +function outputNames(document: Record): string[] { + const properties = isObject(document.properties) ? document.properties : {}; + const outputs = isObject(properties.outputs) ? properties.outputs : {}; + return isObject(outputs.properties) ? Object.keys(outputs.properties) : []; +} + /** * The subschemas whose validity decides which schemas apply to a value (the * branches of `anyOf` and `oneOf`, `if` and `contains`), outside embedded @@ -372,6 +399,7 @@ async function checkDocument( throw new Error(`The $id ${taken} is the $id of a schema in use.`); } let compiled: Awaited>; + let compiledOutputs: Awaited> | undefined; const deciding = new Map>>(); let registered = false; try { @@ -382,6 +410,9 @@ async function checkDocument( // eslint-disable-next-line no-await-in-loop await validate(`${base}${fragment(location)}`); } + if (isObject(document.properties) && "outputs" in document.properties) { + compiledOutputs = await validate(`${base}#/properties/outputs`); + } for (const location of decidingLocations(document)) { // eslint-disable-next-line no-await-in-loop deciding.set(location, await validate(`${base}${fragment(location)}`)); @@ -417,7 +448,43 @@ async function checkDocument( } return validator(value as never, "FLAG").valid; }; - return { valid: true, errors: [], validateInputs, validateAt }; + const declared = new Set(outputNames(document)); + const validateOutputs: OutputsValidator = (value, name) => { + if (!compiledOutputs) return { valid: true, errors: [] }; + if (name !== undefined && !declared.has(name)) { + return { valid: true, errors: [] }; + } + // One output is validated as the only member of the outputs object, + // keeping only the errors at or below it (no `required`): no subschema + // is compiled by a name that would have to survive a URI fragment + const instance: Record = {}; + if (name !== undefined) { + Object.defineProperty(instance, name, { + value, + enumerable: true, + writable: true, + configurable: true, + }); + } + const target = name === undefined ? value : instance; + const result = compiledOutputs(target as never, "BASIC"); + if (result.valid) return { valid: true, errors: [] }; + const prefix = name === undefined ? "" : toPointer([name]); + const errors = toErrors(result.errors, target, valuesLocation).filter( + (error) => + name === undefined || + error.pointer === prefix || + error.pointer.startsWith(`${prefix}/`) + ); + return { valid: errors.length === 0, errors }; + }; + return { + valid: true, + errors: [], + validateInputs, + validateAt, + validateOutputs, + }; } /** 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 13ac9084..0ed3bce6 100644 --- a/packages/ecc-client-ga4gh-wes/src/utils/index.ts +++ b/packages/ecc-client-ga4gh-wes/src/utils/index.ts @@ -2,7 +2,8 @@ * Public helpers of the GA4GH IO Schema support (`@elixir-cloud/wes/utils`): * 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). + * bindings, TRS workflow URLs, engine profiles), and the normalised + * outputs of runs. */ export { checkIoSchema, @@ -13,6 +14,7 @@ export { export type { InputsValidator, IoSchemaCheck, + OutputsValidator, IoSchemaValidator, SubschemaValidator, ValidationError, @@ -51,3 +53,13 @@ export type { EngineProfile, EngineProfileContext, } from "../io-schema/engine-profiles.js"; +export { NormalisationError, normaliseOutputs } from "../io-schema/outputs.js"; +export { FINAL_STATES } from "../io-schema/states.js"; +export type { + Conformance, + NormalisedOutputs, + OutputError, + OutputOptions, + SkippedFile, + UnconvertedOutput, +} from "../io-schema/outputs.js";