diff --git a/bun.lock b/bun.lock index 55b7a23..ead04a8 100644 --- a/bun.lock +++ b/bun.lock @@ -7,7 +7,7 @@ "dependencies": { "@base-ui/react": "^1.9.0", "@elixir-cloud/tes": "^2.0.0-alpha.51", - "@elixir-cloud/wes": "file:./vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz", + "@elixir-cloud/wes": "file:./vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz", "axios": "^1.20.0", "class-variance-authority": "^0.7.1", "cn": "^0.5.0", @@ -41,7 +41,7 @@ "sharp", ], "overrides": { - "@elixir-cloud/design": "file:./vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz", + "@elixir-cloud/design": "file:./vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz", "body-parser": "^2.4.0", "systeminformation": "^5.33.16", }, @@ -134,11 +134,11 @@ "@dotenvx/primitives": ["@dotenvx/primitives@0.8.0", "", {}, "sha512-VYJy0uhFm9zTJ1TxBaW/pA8bjbOM/OttaNMwZ1RHG4JKyRG7DhSdiqD1ipQoAyoD22olUtxbP78W9xY3Wd11bg=="], - "@elixir-cloud/design": ["@elixir-cloud/design@./vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz", { "dependencies": { "@lit/react": "^1.0.2", "ace-builds": "^1.35.0", "dom-accessibility-api": "^0.7.1", "lit": "^2.8.0" } }, "sha512-f91k3OllkRiTLMiT1qlvdD3cbz4fcrkotXr5Hjgoy66t9MlMO5BjQwNLq1ObpQkCEpjXWeIOEmuWzUdTKA+O/w=="], + "@elixir-cloud/design": ["@elixir-cloud/design@./vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz", { "dependencies": { "@lit/react": "^1.0.2", "ace-builds": "^1.35.0", "dom-accessibility-api": "^0.7.1", "lit": "^2.8.0" } }, "sha512-0z38nBxE05YjfP9154vWXlRassltxewr0bUyN/Aw58kfx028YX6j7DZwb26xMBN+/CoBx4l6EFSnswJwz2O5kQ=="], "@elixir-cloud/tes": ["@elixir-cloud/tes@2.0.0-alpha.51", "", { "dependencies": { "@elixir-cloud/design": "2.0.0-alpha.51", "@lit/react": "^1.0.2", "lit": "^2.8.0" } }, "sha512-ysheVxGyjJ43JGKdSJ9rFyzn1Ps6x+SS/lfyc/NiicZgZMkng+zmPlVkYHo9X5pIOj2Pasnbed5OqxWDCk5OnQ=="], - "@elixir-cloud/wes": ["@elixir-cloud/wes@./vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz", { "dependencies": { "@elixir-cloud/design": "2.0.0-alpha.51-io.f28c15c", "@hyperjump/browser": "^1.6.0", "@hyperjump/json-schema": "^1.18.1", "@lit/react": "^1.0.2", "lit": "^2.8.0", "markdown-it": "^15.0.3" } }, "sha512-zRA68yrADBQMX7FBL9k9IFZdKulTGkoXJbKEwJiBqdxQabKO8aFPD3LEEh4NRbihcVZirJ/Vp0uzbEg69/LApw=="], + "@elixir-cloud/wes": ["@elixir-cloud/wes@./vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz", { "dependencies": { "@elixir-cloud/design": "2.0.0-alpha.51-io.c24a517", "@hyperjump/browser": "^1.6.0", "@hyperjump/json-schema": "^1.18.1", "@lit/react": "^1.0.2", "lit": "^2.8.0", "markdown-it": "^15.0.3" } }, "sha512-BDvb021jcLQHYM0koZnyfJ8qYITy9JmHf19xdcfNUL5lc+bp6YPUxrcfbMcfy2MDnGbdK2j+me2ddlUy/v1SXw=="], "@emnapi/core": ["@emnapi/core@2.0.0-beta.2", "", { "dependencies": { "@emnapi/wasi-threads": "2.2.0", "tslib": "^2.4.0" } }, "sha512-MzCVoWtcg4Pm2B3je5mMvYMvj3MmBKw+fU7vbsJc9/iT8ip6/eYIHo/Dsm/mr+wsHB6SEyJDuxB09Yy6r/8+4A=="], diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 5f9ba70..58dbc11 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -100,6 +100,33 @@ info (`supported_filesystem_protocols`). **Use the plain form** goes back to the form without a schema; without a schema, Krini always uses that form. +### Outputs of runs from I/O Schemas + +A run that Krini starts from an I/O Schema records where the schema came +from in the run's tags: `io_schema.source` (`trs`, `url` or `upload`), +`io_schema.trs_url`, `io_schema.tool_id`, `io_schema.version_id`, +`io_schema.descriptor_type` and, for a schema by URL, `io_schema.url`. +When you open the run's details, Krini finds the schema again from these +tags, from the tool registry or the URL, and the **Outputs** tab shows +each output by its title and description, in the schema's order. Outputs +of runs that didn't complete are marked as partial. + +- An **uploaded schema** can't be found again: the run's outputs are + shown as the WES service reports them, and the page says why. +- If the schema **can't be loaded** (e.g. the tool registry is + unreachable), the page says so and shows the outputs as reported. +- Runs **without these tags**, such as runs from the plain form, show + their outputs as before. + +The tags only help Krini find the schema; they aren't checked, and you +can change them on runs you start yourself. + +Viewing and downloading output files (tables, reports) needs a way for +your browser to fetch them from the WES service. Conquest reports its +outputs as `s3://` URIs in the run's bucket and offers no route for users +to fetch them yet, so on Conquest the outputs are shown with their titles, +descriptions and URIs only. + ## Privacy The privacy notice at `/privacy`, linked from the login page and the diff --git a/e2e/fixtures.ts b/e2e/fixtures.ts index f48fa44..dba5bee 100644 --- a/e2e/fixtures.ts +++ b/e2e/fixtures.ts @@ -56,6 +56,23 @@ async function wesRequests(): Promise { return response.json(); } +/** + * Add a run to the mock WES service, as the service would report it + * @param run The run: ID, state, run request and outputs + */ +async function addWesRun(run: { + run_id: string; + state: string; + request?: Record; + outputs?: unknown; +}): Promise { + const response = await fetch(`${mock}/mock/runs`, { + method: "POST", + body: JSON.stringify(run), + }); + if (!response.ok) throw new Error(`mock run: HTTP ${response.status}`); +} + /** * Get all requests that the mock TES service received * @returns The requests, oldest first @@ -160,6 +177,7 @@ const test = base.extend({ export { accessToken, + addWesRun, expect, expireAccessToken, forgiveProblems, diff --git a/e2e/io-schema-outputs.spec.ts b/e2e/io-schema-outputs.spec.ts new file mode 100644 index 0000000..5bce1b4 --- /dev/null +++ b/e2e/io-schema-outputs.spec.ts @@ -0,0 +1,76 @@ +/** + * @description Run outputs with I/O Schema hints (krini#132): Krini records + * where a run's I/O Schema came from in the run's tags, finds the schema + * again from them, and the run view shows the outputs by the schema's + * titles and descriptions. Runs from uploaded schemas show their outputs + * as the service reports them, and say why + */ +import { addWesRun, expect, login, test } from "./fixtures"; +import { mockHttpsPort } from "./settings"; + +const trsUrl = `https://127.0.0.1:${mockHttpsPort}/ga4gh/trs/v2`; +const tags = { + "io_schema.source": "trs", + "io_schema.trs_url": trsUrl, + "io_schema.tool_id": "io-schema-word-count", + "io_schema.version_id": "1.0.0", + "io_schema.descriptor_type": "CWL", +}; +const request = { + workflow_url: `${trsUrl}/tools/io-schema-word-count/versions/1.0.0/PLAIN_CWL/descriptor/wc.cwl`, + workflow_type: "CWL", + workflow_type_version: "v1.2", +}; +const count = "https://example.org/runs/run-io/count.txt"; + +test.describe("members", () => { + test.beforeEach(async ({ page }) => { + await login(page); + }); + + test("see the outputs of a run by its I/O Schema", async ({ page }) => { + await addWesRun({ + run_id: "run-io", + state: "COMPLETE", + request: { ...request, tags }, + outputs: { count }, + }); + await page.goto( + "/dashboard/workflows/details?id=run-io&service=mock-wes", + ); + await page.getByRole("tab", { name: /Outputs/ }).click(); + // the output's title and description come from the schema + await expect(page.getByText("Count", { exact: true })).toBeVisible(); + await expect( + page.getByText( + "The count and the name of the file, as wc prints them.", + ), + ).toBeVisible(); + }); + + test("see why the outputs of a run from an uploaded schema have no hints", async ({ + page, + }) => { + await addWesRun({ + run_id: "run-upload", + state: "COMPLETE", + request: { + ...request, + tags: { ...tags, "io_schema.source": "upload" }, + }, + outputs: { count }, + }); + await page.goto( + "/dashboard/workflows/details?id=run-upload&service=mock-wes", + ); + await expect(page.getByRole("status")).toContainText( + "uploaded I/O Schema", + ); + await page.getByRole("tab", { name: /Outputs/ }).click(); + await expect( + page.getByText( + "The count and the name of the file, as wc prints them.", + ), + ).toHaveCount(0); + }); +}); diff --git a/e2e/io-schema.spec.ts b/e2e/io-schema.spec.ts index 78e8a76..1fba852 100644 --- a/e2e/io-schema.spec.ts +++ b/e2e/io-schema.spec.ts @@ -67,6 +67,14 @@ test.describe("members", () => { text: { class: "File", location: text }, unit: "words", }); + // where the schema came from, for the run view (#132) + expect(JSON.parse(submission.fields?.tags ?? "")).toEqual({ + "io_schema.source": "trs", + "io_schema.trs_url": trsUrl, + "io_schema.tool_id": "io-schema-word-count", + "io_schema.version_id": "1.0.0", + "io_schema.descriptor_type": "CWL", + }); // back to the plain form await page.getByRole("button", { name: "Use the plain form" }).click(); diff --git a/e2e/mock/server.ts b/e2e/mock/server.ts index e621e89..9728feb 100644 --- a/e2e/mock/server.ts +++ b/e2e/mock/server.ts @@ -177,7 +177,14 @@ const revokedRefreshTokens = new Set(); /** How the provider answers refresh token grants (`/mock/refresh`) */ let refreshMode: RefreshMode = {}; /** Runs that the WES service accepted */ -const runs: { run_id: string; state: string }[] = []; +/** Runs of the mock WES service: what `GET /runs/{id}` answers */ +type MockRun = { + run_id: string; + state: string; + request?: Record; + outputs?: unknown; +}; +const runs: MockRun[] = []; /** Requests that the WES service received, for the tests */ const requests: WesRequest[] = []; /** Tasks that the TES service accepted */ @@ -368,6 +375,13 @@ async function handleHttp(req: IncomingMessage, res: ServerResponse) { if (req.method === "GET" && url.pathname === "/mock/tes-requests") return send(res, 200, tesRequests); + // a run as the WES service would report it, e.g. a finished one + if (req.method === "POST" && url.pathname === "/mock/runs") { + const run = JSON.parse(await bodyOf(req)) as MockRun; + runs.push(run); + return send(res, 201, run); + } + if (req.method === "POST" && url.pathname === "/mock/reset") { requests.length = 0; runs.length = 0; @@ -555,6 +569,7 @@ async function handleHttps(req: IncomingMessage, res: ServerResponse) { "workflow_type", "workflow_type_version", "workflow_params", + "tags", ].map((name) => [name, String(form?.get(name) ?? "")]), ); requests[requests.length - 1].fields = fields; @@ -575,7 +590,27 @@ async function handleHttps(req: IncomingMessage, res: ServerResponse) { { msg: "invalid run request", status_code: 400 }, cors, ); - const run = { run_id: `run-${runs.length + 1}`, state: "QUEUED" }; + let tags: unknown = {}; + try { + tags = fields.tags ? JSON.parse(fields.tags) : {}; + } catch { + return send( + res, + 400, + { msg: "invalid run request", status_code: 400 }, + cors, + ); + } + const run: MockRun = { + run_id: `run-${runs.length + 1}`, + state: "QUEUED", + request: { + workflow_url: fields.workflow_url, + workflow_type: fields.workflow_type, + workflow_type_version: fields.workflow_type_version, + tags, + }, + }; runs.push(run); return send(res, 200, { run_id: run.run_id }, cors); } @@ -585,7 +620,12 @@ async function handleHttps(req: IncomingMessage, res: ServerResponse) { return send( res, 200, - { run_id: run.run_id, state: run.state, request: {} }, + { + run_id: run.run_id, + state: run.state, + request: run.request ?? {}, + ...(run.outputs === undefined ? {} : { outputs: run.outputs }), + }, cors, ); diff --git a/package.json b/package.json index cdde1cb..78b9df9 100644 --- a/package.json +++ b/package.json @@ -15,7 +15,7 @@ "dependencies": { "@base-ui/react": "^1.9.0", "@elixir-cloud/tes": "^2.0.0-alpha.51", - "@elixir-cloud/wes": "file:./vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz", + "@elixir-cloud/wes": "file:./vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz", "axios": "^1.20.0", "class-variance-authority": "^0.7.1", "cn": "^0.5.0", @@ -55,6 +55,6 @@ "overrides": { "body-parser": "^2.4.0", "systeminformation": "^5.33.16", - "@elixir-cloud/design": "file:./vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz" + "@elixir-cloud/design": "file:./vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz" } } diff --git a/src/app/dashboard/workflows/_components/ecc-wes-create-run-wrapper.tsx b/src/app/dashboard/workflows/_components/ecc-wes-create-run-wrapper.tsx index e8a3799..3a23fcb 100644 --- a/src/app/dashboard/workflows/_components/ecc-wes-create-run-wrapper.tsx +++ b/src/app/dashboard/workflows/_components/ecc-wes-create-run-wrapper.tsx @@ -1,6 +1,6 @@ "use client"; import dynamic from "next/dynamic"; -import { useRef, useState } from "react"; +import { useMemo, useRef, useState } from "react"; import { ExampleButtons } from "@/components/shared/example-buttons"; import { useWESProvider } from "@/hooks"; import { withSelfHostedAce } from "@/lib/ace-workers"; @@ -11,6 +11,7 @@ import { engineProfileFor, type IoSchemaDemo, } from "@/lib/io-schema"; +import { provenanceTags, withRunTags } from "@/lib/run-schema"; import type { SchemaRun } from "@/lib/schema-run"; import { useWESStore } from "@/stores/wes"; import { IoSchemaSource } from "./io-schema-source"; @@ -48,6 +49,18 @@ export function ECCClientGa4ghWesCreateRunsClient({ // schema mode: the I/O Schema and the TRS tool version to run (#47) const [schemaRun, setSchemaRun] = useState(null); const [schemaKey, setSchemaKey] = useState(0); + // runs from a schema record where it came from, so that the run view + // can find it again (#132) + const schemaProvider = useMemo( + () => + wesProvider === null || schemaRun === null + ? null + : withRunTags( + wesProvider, + provenanceTags(schemaRun.provenance), + ), + [wesProvider, schemaRun], + ); if ( selectedServer === null || @@ -105,7 +118,7 @@ export function ECCClientGa4ghWesCreateRunsClient({ ) : ( } + | { state: "uploaded" } + | { state: "failed"; message: string }; + +/** + * Find the I/O Schema of the run shown, from the tags of its run request + * @returns The schema state and the handler of `ecc-run-log-changed` + */ +function useRunSchema() { + const [runSchema, setRunSchema] = useState({ state: "none" }); + // the run log is reported again on every refresh: load once per source + const loaded = useRef(null); + + const onRunLog = useCallback((event: Event) => { + const { runLog } = (event as CustomEvent<{ runLog?: unknown }>).detail; + const request = (runLog as { request?: { tags?: unknown } } | null) + ?.request; + const provenance = provenanceFromTags(request?.tags); + const key = JSON.stringify(provenance); + if (key === loaded.current) return; + loaded.current = key; + if (provenance === null) { + setRunSchema({ state: "none" }); + return; + } + load(provenance).then((next) => { + // a newer run log may have named another source meanwhile + if (loaded.current === key) setRunSchema(next); + }); + }, []); + + return { runSchema, onRunLog }; +} + +async function load(provenance: SchemaProvenance): Promise { + try { + const schema = await loadRunSchema(provenance); + if (schema !== null) return { state: "loaded", schema }; + return provenance.source === "upload" + ? { state: "uploaded" } + : { state: "none" }; + } catch (error) { + return { + state: "failed", + message: error instanceof Error ? error.message : String(error), + }; + } +} + +/** + * Says why the outputs are shown without the hints of the run's schema + * @param props.runSchema The schema state + */ +function RunSchemaNotice({ runSchema }: { runSchema: RunSchema }) { + const text = + runSchema.state === "uploaded" + ? "This run was started from an uploaded I/O Schema, which Krini can't find again: its outputs are shown as the service reports them." + : runSchema.state === "failed" + ? `The I/O Schema of this run can't be loaded (${runSchema.message}): its outputs are shown as the service reports them.` + : null; + if (text === null) return null; + return ( + {text} + ); +} + /** * Details of a workflow run: its state, logs and outputs * @@ -29,19 +104,26 @@ const ECCClientGa4ghWesRun = dynamic( * link, the current selection is used, with a selector to change it. * @param props.runId ID of the workflow run * @param props.serviceId Registry ID of the run's service, if known + * @param props.outputProvider Fetches output files for the viewers and + * downloads of outputs shown by the run's I/O Schema. None yet: no WES + * that Krini knows offers a route for its users to fetch output files, so + * outputs are shown by title and description, with their URIs */ export function ECCClientGa4ghWesRunClient({ runId, serviceId, + outputProvider, }: { runId: string; serviceId?: string; + outputProvider?: WesOutputProvider; }) { const servers = useWESStore((state) => state.servers); const serversLoaded = useWESStore((state) => state.serversLoaded); const selectedServer = useWESStore((state) => state.selectedServer); const setSelectedServer = useWESStore((state) => state.setSelectedServer); const { wesProvider } = useWESProvider(); + const { runSchema, onRunLog } = useRunSchema(); // only services of the (https-only) registry list can be selected const linked = serviceId @@ -87,10 +169,16 @@ export function ECCClientGa4ghWesRunClient({ WES instance: {name}

) : null} + ); diff --git a/src/lib/run-schema.test.ts b/src/lib/run-schema.test.ts new file mode 100644 index 0000000..b1ec7e6 --- /dev/null +++ b/src/lib/run-schema.test.ts @@ -0,0 +1,207 @@ +import { describe, expect, it, vi } from "vitest"; +import { + loadRunSchema, + provenanceFromTags, + provenanceTags, + type SchemaProvenance, + withRunTags, +} from "./run-schema"; + +const trsUrl = "https://trs.example.org/ga4gh/trs/v2"; +const schema = { title: "Word count" }; +const fromTrs: SchemaProvenance = { + source: "trs", + trsUrl, + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", +}; +const fromUrl: SchemaProvenance = { + ...fromTrs, + source: "url", + url: "https://schemas.example.org/demo.json", +}; +const json = (body: unknown, status = 200) => + new Response(JSON.stringify(body), { status }); + +/** + * A fetch with one answer + * @param reply Answer (an error: a network error) + */ +function fetcher(reply: Response | Error) { + return vi.fn(async () => { + if (reply instanceof Error) throw reply; + return reply; + }) as unknown as typeof fetch & ReturnType; +} + +describe("provenanceTags", () => { + it("names the tool version of a schema from the tool registry", () => { + expect(provenanceTags(fromTrs)).toEqual({ + "io_schema.source": "trs", + "io_schema.trs_url": trsUrl, + "io_schema.tool_id": "demo", + "io_schema.version_id": "1.0.0", + "io_schema.descriptor_type": "WDL", + }); + }); + + it("adds the URL of a schema given by URL", () => { + expect(provenanceTags(fromUrl)).toMatchObject({ + "io_schema.source": "url", + "io_schema.url": "https://schemas.example.org/demo.json", + }); + }); +}); + +describe("provenanceFromTags", () => { + it.each([ + ["a schema from the tool registry", fromTrs], + ["a schema by URL", fromUrl], + ["an uploaded schema", { ...fromTrs, source: "upload" }], + ])("reads back %s", (_, provenance) => { + expect( + provenanceFromTags(provenanceTags(provenance as SchemaProvenance)), + ).toEqual(provenance); + }); + + it("ignores other tags", () => { + expect( + provenanceFromTags({ ...provenanceTags(fromTrs), project: "x" }), + ).toEqual(fromTrs); + }); + + it.each([ + ["no tags", undefined], + ["tags that aren't an object", "io_schema.source=trs"], + ["tags of a run without a schema", { project: "x" }], + [ + "an unknown source", + { ...provenanceTags(fromTrs), "io_schema.source": "drs" }, + ], + [ + "a missing tool ID", + { ...provenanceTags(fromTrs), "io_schema.tool_id": "" }, + ], + [ + "a value that isn't a string", + { ...provenanceTags(fromTrs), "io_schema.version_id": 1 }, + ], + [ + "a schema URL source without a URL", + { ...provenanceTags(fromTrs), "io_schema.source": "url" }, + ], + ])("finds nothing in %s", (_, tags) => { + expect(provenanceFromTags(tags)).toBeNull(); + }); +}); + +describe("loadRunSchema", () => { + it("has no schema for an uploaded one", async () => { + const fetch = fetcher(json({})); + await expect( + loadRunSchema({ ...fromTrs, source: "upload" }, fetch), + ).resolves.toBeNull(); + expect(fetch).not.toHaveBeenCalled(); + }); + + it("reads the schema of the tool version through Krini's server", async () => { + const fetch = fetcher(json({ schema })); + await expect(loadRunSchema(fromTrs, fetch)).resolves.toEqual(schema); + expect(fetch).toHaveBeenCalledWith( + `/api/workflows/trs-tool-version?${new URLSearchParams({ + trs: trsUrl, + tool: "demo", + version: "1.0.0", + type: "WDL", + })}`, + ); + }); + + it("has no schema when the tool version has none", async () => { + await expect( + loadRunSchema(fromTrs, fetcher(json({ schema: null }))), + ).resolves.toBeNull(); + }); + + it("reads a schema by URL without credentials", async () => { + const fetch = fetcher(json(schema)); + await expect(loadRunSchema(fromUrl, fetch)).resolves.toEqual(schema); + expect(fetch).toHaveBeenCalledWith( + "https://schemas.example.org/demo.json", + expect.objectContaining({ credentials: "omit" }), + ); + }); + + it.each([ + ["the server is unreachable", fetcher(new TypeError("offline"))], + ["the server refuses", fetcher(json({ error: "Not listed." }, 400))], + ["the answer isn't JSON", fetcher(new Response(""))], + ])("fails when %s", async (_, fetch) => { + await expect(loadRunSchema(fromTrs, fetch)).rejects.toThrow(); + }); + + it("says why the tool registry can't be read", async () => { + await expect( + loadRunSchema( + fromTrs, + fetcher(json({ error: "Not listed." }, 400)), + ), + ).rejects.toThrow("Not listed."); + await expect( + loadRunSchema(fromTrs, fetcher(json({}, 502))), + ).rejects.toThrow("HTTP 502"); + }); + + it("refuses a schema URL that isn't https", async () => { + const fetch = fetcher(json(schema)); + await expect( + loadRunSchema({ ...fromUrl, url: "http://x.example.org/s" }, fetch), + ).rejects.toThrow("HTTPS"); + expect(fetch).not.toHaveBeenCalled(); + }); +}); + +describe("withRunTags", () => { + it("adds the tags to every run request and keeps the user's", async () => { + const provider = { + runs: 0, + async runWorkflow(request: { tags?: Record }) { + this.runs += 1; + return { run_id: "r1", tags: request.tags }; + }, + async getServiceInfo() { + return this.runs; + }, + }; + const tagged = withRunTags(provider, { "io_schema.source": "trs" }); + await expect( + tagged.runWorkflow({ tags: { project: "x" } }), + ).resolves.toEqual({ + run_id: "r1", + tags: { project: "x", "io_schema.source": "trs" }, + }); + // the provider's own methods keep their `this` + await expect(tagged.getServiceInfo()).resolves.toBe(1); + // and its other properties stay as they are + expect(tagged.runs).toBe(1); + }); + + it("overrides user tags with the same names", async () => { + const provider = { + async runWorkflow(request: { tags?: Record }) { + return request.tags; + }, + }; + await expect( + withRunTags(provider, { "io_schema.source": "trs" }).runWorkflow({ + tags: { "io_schema.source": "upload" }, + }), + ).resolves.toEqual({ "io_schema.source": "trs" }); + await expect( + withRunTags(provider, { "io_schema.source": "trs" }).runWorkflow( + {}, + ), + ).resolves.toEqual({ "io_schema.source": "trs" }); + }); +}); diff --git a/src/lib/run-schema.ts b/src/lib/run-schema.ts new file mode 100644 index 0000000..6167829 --- /dev/null +++ b/src/lib/run-schema.ts @@ -0,0 +1,177 @@ +/** + * The I/O Schema of a workflow run (krini#132) + * + * When Krini starts a run from an I/O Schema, it records where the schema + * came from in the run's WES tags (`io_schema.*`): the tool registry, tool, + * version and workflow type, and the schema's URL if the user gave one. + * The run view reads them back to find the schema again and show the + * run's outputs by it. An uploaded schema can't be found again, so its + * runs (and runs without these tags) show their outputs without hints. + * + * The tags are hints, not proof: the run's owner can set them. Schemas are + * read the same way as for the form: from tool registries that the + * service registry lists (through Krini's server), or by an HTTPS URL from + * the browser without credentials. + */ +import { parseSchemaText, SchemaSourceError } from "@/lib/io-schema"; +import { fetchSchemaText } from "@/lib/schema-run"; + +/** Where the schema of a run came from */ +export type SchemaProvenance = { + /** From the tool registry, by URL, or uploaded */ + source: "trs" | "url" | "upload"; + /** The TRS tool version that the run request names */ + trsUrl: string; + toolId: string; + versionId: string; + descriptorType: string; + /** URL of the schema, for `source: "url"` */ + url?: string; +}; + +/** Names of the run tags, by field of `SchemaProvenance` */ +const TAGS = { + source: "io_schema.source", + trsUrl: "io_schema.trs_url", + toolId: "io_schema.tool_id", + versionId: "io_schema.version_id", + descriptorType: "io_schema.descriptor_type", + url: "io_schema.url", +} as const; + +const SOURCES: readonly string[] = ["trs", "url", "upload"]; + +/** + * Tags that record where a run's schema came from + * @param provenance Where the schema came from + * @returns WES run tags + */ +export function provenanceTags( + provenance: SchemaProvenance, +): Record { + const tags: Record = { + [TAGS.source]: provenance.source, + [TAGS.trsUrl]: provenance.trsUrl, + [TAGS.toolId]: provenance.toolId, + [TAGS.versionId]: provenance.versionId, + [TAGS.descriptorType]: provenance.descriptorType, + }; + if (provenance.url !== undefined) tags[TAGS.url] = provenance.url; + return tags; +} + +/** + * Read back where a run's schema came from + * @param tags The tags of the run request + * @returns Where the schema came from, or `null` if the tags don't say + */ +export function provenanceFromTags(tags: unknown): SchemaProvenance | null { + if (typeof tags !== "object" || tags === null) return null; + const read = (name: string) => { + const value = (tags as Record)[name]; + return typeof value === "string" && value !== "" ? value : null; + }; + const source = read(TAGS.source); + const trsUrl = read(TAGS.trsUrl); + const toolId = read(TAGS.toolId); + const versionId = read(TAGS.versionId); + const descriptorType = read(TAGS.descriptorType); + const url = read(TAGS.url); + if ( + source === null || + !SOURCES.includes(source) || + trsUrl === null || + toolId === null || + versionId === null || + descriptorType === null || + (source === "url" && url === null) + ) + return null; + return { + source: source as SchemaProvenance["source"], + trsUrl, + toolId, + versionId, + descriptorType, + ...(source === "url" ? { url: url as string } : {}), + }; +} + +/** + * Find a run's schema again + * @param provenance Where the schema came from + * @param fetcher `fetch`, replaceable in tests + * @returns The schema, or `null` if it can't be found again (uploaded, or + * the tool version has none) + * @throws SchemaSourceError With a message for the user + */ +export async function loadRunSchema( + provenance: SchemaProvenance, + fetcher: typeof fetch = fetch, +): Promise | null> { + if (provenance.source === "upload") return null; + if (provenance.source === "url") + return parseSchemaText( + await fetchSchemaText(provenance.url as string, fetcher), + ); + + const params = new URLSearchParams({ + trs: provenance.trsUrl, + tool: provenance.toolId, + version: provenance.versionId, + type: provenance.descriptorType, + }); + let response: Response; + try { + response = await fetcher(`/api/workflows/trs-tool-version?${params}`); + } catch { + throw new SchemaSourceError("Unable to reach Krini's server."); + } + const body: unknown = await response.json().catch(() => null); + const record = + typeof body === "object" && body !== null + ? (body as { error?: unknown; schema?: unknown }) + : null; + if (!response.ok || record === null) { + throw new SchemaSourceError( + typeof record?.error === "string" + ? record.error + : `Unable to load the I/O Schema (HTTP ${response.status}).`, + ); + } + const { schema } = record; + return typeof schema === "object" && schema !== null + ? (schema as Record) + : null; +} + +/** + * A WES provider that adds tags to every run request + * + * The tags override user tags of the same names, so that the recorded + * provenance is the one Krini used. + * @param provider The provider + * @param tags The tags to add + * @returns The provider with `runWorkflow` wrapped + */ +export function withRunTags< + P extends { + runWorkflow(request: R): Promise; + }, + R extends { tags?: Record } = Parameters< + P["runWorkflow"] + >[0], +>(provider: P, tags: Record): P { + return new Proxy(provider, { + get(target, property, receiver) { + if (property === "runWorkflow") + return (request: R) => + target.runWorkflow({ + ...request, + tags: { ...request.tags, ...tags }, + }); + const value = Reflect.get(target, property, receiver); + return typeof value === "function" ? value.bind(target) : value; + }, + }); +} diff --git a/src/lib/schema-run.test.ts b/src/lib/schema-run.test.ts index 5f193a2..0a8b457 100644 --- a/src/lib/schema-run.test.ts +++ b/src/lib/schema-run.test.ts @@ -14,6 +14,15 @@ const result = (schema: unknown = trsSchema) => ({ descriptorTypeVersions: ["1.1"], }, }); +/** Where the schema of `result()` came from */ +const provenance = (source: string, extra: Record = {}) => ({ + source, + trsUrl, + toolId: "demo", + versionId: "1.0.0", + descriptorType: "WDL", + ...extra, +}); const json = (body: unknown, status = 200) => new Response(JSON.stringify(body), { status }); @@ -42,7 +51,7 @@ describe("loadSchemaRun", () => { const fetch = fetcher(json(result())); await expect( loadSchemaRun(request({ kind: "trs" }), fetch), - ).resolves.toEqual(result()); + ).resolves.toEqual({ ...result(), provenance: provenance("trs") }); expect(fetch).toHaveBeenCalledWith( `/api/workflows/trs-tool-version?${new URLSearchParams({ trs: trsUrl, @@ -72,6 +81,8 @@ describe("loadSchemaRun", () => { fetch, ); expect(run.schema).toEqual(uploaded); + // the tool version comes from the tool registry's answer + expect(run.provenance).toEqual(provenance("upload")); expect(fetch).toHaveBeenCalledWith( `/api/workflows/trs-tool-version?${new URLSearchParams({ trs: trsUrl, @@ -90,6 +101,9 @@ describe("loadSchemaRun", () => { fetch, ); expect(run.schema).toEqual({ title: "by URL" }); + expect(run.provenance).toEqual( + provenance("url", { url: "https://example.org/s.json" }), + ); expect(fetch).toHaveBeenCalledWith("https://example.org/s.json", { credentials: "omit", headers: { Accept: "application/json" }, @@ -170,9 +184,10 @@ describe("loadSchemaRun", () => { it("uses the global fetch by default", async () => { const stub = vi.fn(async () => json(result())); vi.stubGlobal("fetch", stub); - await expect(loadSchemaRun(request({ kind: "trs" }))).resolves.toEqual( - result(), - ); + await expect(loadSchemaRun(request({ kind: "trs" }))).resolves.toEqual({ + ...result(), + provenance: provenance("trs"), + }); expect(stub).toHaveBeenCalledOnce(); }); }); diff --git a/src/lib/schema-run.ts b/src/lib/schema-run.ts index 09dc24a..d2954b4 100644 --- a/src/lib/schema-run.ts +++ b/src/lib/schema-run.ts @@ -15,6 +15,7 @@ import { schemaUrl, schemaWorkflow, } from "@/lib/io-schema"; +import type { SchemaProvenance } from "@/lib/run-schema"; import type { TrsToolVersionResult } from "@/lib/trs"; /** Where the schema comes from */ @@ -35,14 +36,25 @@ export type SchemaRunRequest = { /** The schema and the tool version, for `ecc-client-ga4gh-wes-run-create` */ export type SchemaRun = TrsToolVersionResult & { schema: Record; + /** Where the schema came from, recorded in the run's tags */ + provenance: SchemaProvenance; }; type Fetch = typeof fetch; -async function schemaText(source: SchemaSource, fetcher: Fetch) { - if (source.kind === "upload") return source.text; - if (source.kind === "trs") return null; - const url = schemaUrl(source.url); +/** + * Fetch a schema by its URL, from the browser and without credentials + * @param value URL of the schema + * @param fetcher `fetch`, replaceable in tests + * @returns The text of the schema + * @throws SchemaSourceError If the URL isn't an HTTPS URL or the schema + * can't be fetched + */ +export async function fetchSchemaText( + value: string, + fetcher: Fetch = fetch, +): Promise { + const url = schemaUrl(value); if (url === null) throw new SchemaSourceError("The schema URL must be an HTTPS URL."); let response: Response; @@ -63,6 +75,12 @@ async function schemaText(source: SchemaSource, fetcher: Fetch) { return response.text(); } +async function schemaText(source: SchemaSource, fetcher: Fetch) { + if (source.kind === "upload") return source.text; + if (source.kind === "trs") return null; + return fetchSchemaText(source.url, fetcher); +} + /** * Get the schema and the tool version for schema mode * @param request The user's choice @@ -112,5 +130,14 @@ export async function loadSchemaRun( throw new SchemaSourceError( "The tool version has no I/O Schema: upload it, give its URL or use the plain form.", ); - return { ...result, schema }; + const { source } = request; + const provenance: SchemaProvenance = { + source: source.kind, + trsUrl: result.trsToolVersion.trsUrl, + toolId: result.trsToolVersion.toolId, + versionId: result.trsToolVersion.versionId, + descriptorType: result.descriptorType, + ...(source.kind === "url" ? { url: source.url.trim() } : {}), + }; + return { ...result, schema, provenance }; } diff --git a/vendor/cloud-components/README.md b/vendor/cloud-components/README.md index 2bdb4d7..79055b5 100644 --- a/vendor/cloud-components/README.md +++ b/vendor/cloud-components/README.md @@ -8,15 +8,15 @@ needs before they are released: | Tarball | Package | Source | | --- | --- | --- | -| `elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz` | `@elixir-cloud/wes` | `packages/ecc-client-ga4gh-wes` | -| `elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz` | `@elixir-cloud/design` | `packages/ecc-utils-design` | +| `elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz` | `@elixir-cloud/wes` | `packages/ecc-client-ga4gh-wes` | +| `elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz` | `@elixir-cloud/design` | `packages/ecc-utils-design` | Both are built from [elixir-cloud-aai/cloud-components](https://github.com/elixir-cloud-aai/cloud-components) -at commit `f28c15c` (branch `feat/io-run-request-proposal`, PR #614, -stacked on `feat/io-form-proposal`, PR #613), with `npm run build` and +at commit `c24a517` (branch `feat/io-run-output-proposal`, PR #615, stacked on PR #614 +and PR #613), with `npm run build` and `npm pack` in each package. The version in their `package.json` is set to -`2.0.0-alpha.51-io.f28c15c` (and the WES package's dependency on the +`2.0.0-alpha.51-io.c24a517` (and the WES package's dependency on the design package to the same), so that they can't be mistaken for the published `2.0.0-alpha.51`. Nothing was published. diff --git a/vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz b/vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz new file mode 100644 index 0000000..d96612e Binary files /dev/null and b/vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.c24a517.tgz differ diff --git a/vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz b/vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz deleted file mode 100644 index 1c20844..0000000 Binary files a/vendor/cloud-components/elixir-cloud-design-2.0.0-alpha.51-io.f28c15c.tgz and /dev/null differ diff --git a/vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz b/vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz new file mode 100644 index 0000000..0b82329 Binary files /dev/null and b/vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.c24a517.tgz differ diff --git a/vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz b/vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz deleted file mode 100644 index 3c5e6b1..0000000 Binary files a/vendor/cloud-components/elixir-cloud-wes-2.0.0-alpha.51-io.f28c15c.tgz and /dev/null differ