diff --git a/.changeset/wes-run-tasks.md b/.changeset/wes-run-tasks.md new file mode 100644 index 00000000..2edc7df7 --- /dev/null +++ b/.changeset/wes-run-tasks.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/wes": minor +--- + +`ecc-client-ga4gh-wes-run` lists the tasks of WES 1.1 runs that give only `task_logs_url`, by page, through the provider's new optional `listRunTasks()`, and fetches log URLs through the new optional `getLog()` (`RestWesProvider` implements both). New types `TaskLog` and `TaskListResponse`; `RunLog.task_logs` may now be absent or `null`, so code that reads it needs a fallback. Providers without `getLog()` now fetch logs without credentials: implement `getLog()` to send them. diff --git a/apps/documentation/pages/docs/wes/components/run.mdx b/apps/documentation/pages/docs/wes/components/run.mdx index 05fd178b..c25e585c 100644 --- a/apps/documentation/pages/docs/wes/components/run.mdx +++ b/apps/documentation/pages/docs/wes/components/run.mdx @@ -78,6 +78,15 @@ This example shows the details for a specific workflow run ID. +### Tasks + +The Task Logs tab shows the run's tasks: + +- the inline `task_logs` of the run log, or, for WES 1.1 servers that give only `task_logs_url` (e.g. Conquest), the tasks listed by the provider's `listRunTasks()` (`GET /runs/{run_id}/tasks`), a page at a time, with a button for the next page (also after an empty page) and one to try again if a listing fails; +- for each task its name, ID, start and end time, exit code, system logs, its TES task (`tes_uri`, a link only if it is an HTTP(S) URL) and its logs, which are fetched when the task is opened. + +Log URLs are fetched with the provider's `getLog()` (with `RestWesProvider`: the service's authorization for its own origin, no credentials elsewhere). Providers without `getLog()` fetch them without credentials, also on the page's own origin: implement `getLog()` if your logs need cookies or a token. Log values that aren't URLs are shown as given, with a hint. + ### 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`. diff --git a/apps/documentation/pages/docs/wes/providers.mdx b/apps/documentation/pages/docs/wes/providers.mdx index 07cbad27..be7c8399 100644 --- a/apps/documentation/pages/docs/wes/providers.mdx +++ b/apps/documentation/pages/docs/wes/providers.mdx @@ -23,6 +23,14 @@ export interface WesProvider { getRunLog(runId: string): Promise; getRunStatus(runId: string): Promise; cancelRun(runId: string): Promise; + + // Optional (WES 1.1 task listing, log fetching) + listRunTasks?( + runId: string, + pageSize?: number, + pageToken?: string + ): Promise; + getLog?(url: string): Promise; } ``` @@ -153,6 +161,22 @@ Cancels a running workflow. cancelRun(runId: string): Promise ``` +### listRunTasks() + +Lists a page of a run's tasks (`GET /runs/{run_id}/tasks`, WES 1.1). Optional in the interface; `ecc-client-ga4gh-wes-run` uses it for runs that give `task_logs_url` instead of `task_logs`. `RestWesProvider` calls the endpoint under its base URL; it doesn't follow `task_logs_url` itself, so the provider's authorization never goes to another address. + +```typescript +listRunTasks(runId: string, pageSize?: number, pageToken?: string): Promise +``` + +### getLog() + +Fetches the text of a log URL (`stdout`, `stderr`). Optional in the interface; without it, components fetch logs without credentials. `RestWesProvider` fetches URLs on its base URL's origin through its `fetch` (so a subclass's `Authorization` header goes along), other origins without credentials, and refuses URLs that aren't HTTP(S). A relative base URL is resolved against the page. Redirects are followed: browsers drop `Authorization` and cookies when a redirect leaves the origin, but not other headers, so a subclass that adds its own header (e.g. `X-Api-Key`) should send it only where it belongs, or override `getLog()`. + +```typescript +getLog(url: string): Promise +``` + ## Type Definitions @@ -218,6 +242,16 @@ interface Log { } ``` +### TaskLog + +```typescript +interface TaskLog extends Log { + id?: string; + system_logs?: string[]; + tes_uri?: string; +} +``` + ### RunLog ```typescript @@ -226,11 +260,21 @@ interface RunLog { request: RunRequest; state: State; run_log: Log; - task_logs: Log[]; + task_logs?: TaskLog[] | null; // deprecated in WES 1.1 + task_logs_url?: string | null; // WES 1.1 outputs: object; } ``` +### TaskListResponse + +```typescript +interface TaskListResponse { + task_logs: TaskLog[]; + next_page_token?: string; +} +``` + ### RunListResponse ```typescript 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 4a858e9c..785e7a18 100644 --- a/packages/ecc-client-ga4gh-wes/src/components/run/run.ts +++ b/packages/ecc-client-ga4gh-wes/src/components/run/run.ts @@ -7,6 +7,7 @@ import { RunLog, State, Log, + TaskLog, } from "../../providers/wes-provider.js"; import type { EccRunLogChangedEvent } from "../../events/ecc-run-log-changed.js"; import { RestWesProvider } from "../../providers/rest-wes-provider.js"; @@ -27,6 +28,9 @@ import "@elixir-cloud/design/components/separator/index.js"; import "@elixir-cloud/design/components/code/index.js"; import "@elixir-cloud/design/components/collapsible/index.js"; +/** Tasks per page when listing them from `task_logs_url` */ +const TASK_PAGE_SIZE = 50; + /** * @summary Displays details of a single workflow run. * @since 0.1.0 @@ -92,6 +96,21 @@ export class ECCClientGa4ghWesRun extends LitElement { @state() private loading = false; @state() private error: string | null = null; @state() private logContents: Record = {}; + // The run's tasks: inline `task_logs`, or the pages listed so far from + // `task_logs_url` (WES 1.1) + @state() private tasks: TaskLog[] = []; + @state() private tasksNextPage?: string; + @state() private tasksLoading = false; + @state() private tasksNotice?: string; + // The page token of a listing that failed, to offer a retry (`null`: + // the first page) + @state() private tasksRetry?: string | null; + // Positions of the tasks whose details are open: logs are fetched only + // for open tasks, not for every task of a page + @state() private openTasks: ReadonlySet = new Set(); + + // Number of the latest task listing, to drop pages of an earlier run + private taskListings = 0; private _provider: WesProvider | null = null; @@ -223,6 +242,8 @@ export class ECCClientGa4ghWesRun extends LitElement { this.runLogRequests += 1; this.run = null; this.loading = false; + this.logContents = {}; + this.resetTasks(); } private initializeProvider(): void { @@ -248,12 +269,22 @@ export class ECCClientGa4ghWesRun extends LitElement { this.error = null; this.run = null; this.logContents = {}; + this.resetTasks(); try { const runLog = await this._provider.getRunLog(this.runId); // A newer request (another run ID or provider) supersedes this one if (!current()) return; this.run = runLog; + if (runLog.task_logs && runLog.task_logs.length > 0) { + this.tasks = runLog.task_logs; + } else if (runLog.task_logs_url) { + // Not awaited: the run shows while its tasks load. Pages of an + // earlier run are dropped by `taskListings`, which resetTasks() + // bumps, as `runLogRequests` drops run logs of earlier requests + // eslint-disable-next-line no-void + void this.loadTasks(); + } this.dispatchEvent( new CustomEvent( "ecc-run-log-changed", @@ -278,6 +309,51 @@ export class ECCClientGa4ghWesRun extends LitElement { } } + private resetTasks(): void { + this.taskListings += 1; + this.tasks = []; + this.tasksNextPage = undefined; + this.tasksLoading = false; + this.tasksNotice = undefined; + this.tasksRetry = undefined; + this.openTasks = new Set(); + } + + /** Lists the next page of the run's tasks (WES 1.1 `task_logs_url`). */ + private async loadTasks(pageToken?: string): Promise { + const provider = this._provider; + // One page at a time: a second click before the button is disabled + // would list the same page again + if (!provider || !this.run || this.tasksLoading) return; + if (!provider.listRunTasks) { + this.tasksNotice = + "The run lists its tasks at task_logs_url, but this provider can't list them (listRunTasks)."; + return; + } + const listing = this.taskListings; + this.tasksLoading = true; + this.tasksNotice = undefined; + this.tasksRetry = undefined; + try { + const page = await provider.listRunTasks( + this.run.run_id, + TASK_PAGE_SIZE, + pageToken + ); + if (listing !== this.taskListings) return; + this.tasks = [...this.tasks, ...(page.task_logs ?? [])]; + this.tasksNextPage = page.next_page_token || undefined; + } catch (err) { + if (listing !== this.taskListings) return; + this.tasksNotice = `The run's tasks couldn't be listed: ${ + err instanceof Error ? err.message : String(err) + }`; + this.tasksRetry = pageToken ?? null; + } finally { + if (listing === this.taskListings) this.tasksLoading = false; + } + } + private static getStateInfo(runState: State): { variant: "default" | "secondary" | "destructive" | "outline"; label: string; @@ -640,14 +716,28 @@ export class ECCClientGa4ghWesRun extends LitElement { } private async fetchLogUrlToCache(url: string, key: string): Promise { + // Keys are positions (e.g. `task_logs-0-stdout`): a log of an earlier + // run or task listing must not fill the same key of the current one + const { runLogRequests, taskListings } = this; + const current = () => + runLogRequests === this.runLogRequests && + taskListings === this.taskListings; try { - const response = await fetch(url); - if (!response.ok) { - throw new Error(response.statusText || "Failed to fetch log"); + let text: string; + if (this._provider?.getLog) { + // E.g. with the service's authorization for its own log URLs + text = await this._provider.getLog(url); + } else { + const response = await fetch(url, { credentials: "omit" }); + if (!response.ok) { + throw new Error(response.statusText || "Failed to fetch log"); + } + text = await response.text(); } - const text = await response.text(); + if (!current()) return; this.logContents = { ...this.logContents, [key]: text }; } catch (err) { + if (!current()) return; this.logContents = { ...this.logContents, [key]: `Error loading log: ${ @@ -657,6 +747,59 @@ export class ECCClientGa4ghWesRun extends LitElement { } } + /** A hint for a log value that isn't a URL (WES gives URLs). */ + private static renderLogHint(value: string | undefined) { + return value && !ECCClientGa4ghWesRun.isProbablyUrl(value) + ? html`

+ The service gave this log as text, not as a URL; it is shown as given. +

` + : nothing; + } + + /** Task details beyond those of a log: ID, TES task, system logs. */ + private static renderTaskDetails(task: TaskLog) { + const tesUri = task.tes_uri; + return html` +
+ ${task.id + ? html`
+
Task ID
+
${task.id}
+
` + : nothing} + ${tesUri + ? html`
+
TES task
+
+ ${ECCClientGa4ghWesRun.isProbablyUrl(tesUri) + ? html`${tesUri}` + : tesUri} +
+
` + : nothing} +
+ ${task.system_logs && task.system_logs.length > 0 + ? html`
+
System Logs
+ +
` + : nothing} + `; + } + private renderLog(log: Log, keyPrefix: string) { const stdoutKey = `${keyPrefix}-stdout`; const stderrKey = `${keyPrefix}-stderr`; @@ -729,9 +872,11 @@ export class ECCClientGa4ghWesRun extends LitElement {
Output Logs
+ ${ECCClientGa4ghWesRun.renderLogHint(log.stdout)}

Standard Output

+ ${ECCClientGa4ghWesRun.renderLogHint(log.stderr)}

Standard Error

- - -

No task logs available.

-
-
-
- `; - } return html`
- ${this.run.task_logs.map( - (taskLog, index) => html` - + ${this.tasks.length === 0 && !this.tasksNotice + ? html` + + ${this.tasksLoading + ? html`

+ Loading the tasks... +

` + : html`

+ No task logs available. +

`} +
+
` + : nothing} + ${this.tasks.map((task, index) => { + const label = task.name || task.id || `Task ${index + 1}`; + const open = this.openTasks.has(index); + // Keys by position: pages are appended, so positions stay + return html` + + ) => this.toggleTask(index, event.detail.open)} + >
- ${taskLog.name || `Task ${index + 1}`} + ${label} Click to expand @@ -800,16 +959,50 @@ export class ECCClientGa4ghWesRun extends LitElement {
- ${this.renderLog(taskLog, `task_logs-${index}`)} + ${ECCClientGa4ghWesRun.renderTaskDetails(task)} + ${open ? this.renderLog(task, `task_logs-${index}`) : nothing}
- ` - )} + `; + })} + ${this.tasksNotice + ? html`

+ ${this.tasksNotice} +

` + : nothing} + ${this.tasksRetry !== undefined + ? html` this.loadTasks(this.tasksRetry ?? undefined)} + >Try again` + : nothing} + ${this.tasksNextPage + ? html` this.loadTasks(this.tasksNextPage)} + >${this.tasksLoading + ? "Loading..." + : "Load more tasks"}` + : nothing}
`; } + /** Records whether a task's details are open (its logs load then). */ + private toggleTask(index: number, open: boolean): void { + const openTasks = new Set(this.openTasks); + if (open) openTasks.add(index); + else openTasks.delete(index); + this.openTasks = openTasks; + } + private renderRawOutputs() { return html` 0); + return ( + this.tasks.length > 0 || + !!(this.run && this.run.task_logs_url && !this.run.task_logs?.length) + ); } render() { 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 index 4fc18d00..d824ecbb 100644 --- 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 @@ -1,8 +1,13 @@ /* eslint-disable import/no-extraneous-dependencies */ +/* eslint-disable no-script-url -- tests that script URLs aren't links */ 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 { + RunLog, + TaskListResponse, + WesProvider, +} from "../../../providers/wes-provider.js"; import type { ECCClientGa4ghWesRunOutput } from "../../run-output/run-output.js"; import { PROFILE_ID } from "../../../io-schema/validator.js"; @@ -440,3 +445,321 @@ describe("ecc-client-ga4gh-wes-run attributes", () => { }); } }); + +/** A provider that lists tasks by page and serves logs. */ +class TaskProvider extends FakeProvider { + pages: Record; + + calls: (string | undefined)[] = []; + + logs: string[] = []; + + constructor(log: RunLog, pages: Record) { + super(log); + this.pages = pages; + } + + async listRunTasks(_runId: string, _pageSize?: number, pageToken?: string) { + this.calls.push(pageToken); + const page = this.pages[pageToken ?? ""]; + if (!page) throw new Error("no such page"); + return page; + } + + async getLog(url: string) { + this.logs.push(url); + return `log of ${url}`; + } +} + +/** A run that lists its tasks only by URL (WES 1.1). */ +const byUrl = (): RunLog => + ({ + ...runLog("COMPLETE", {}), + task_logs: null, + task_logs_url: "https://wes.example.org/ga4gh/wes/v1/runs/run-7/tasks", + } as unknown as RunLog); + +async function renderTasks( + provider: WesProvider +): Promise { + const el = await fixture( + html`` + ); + await waitUntil( + () => + el.shadowRoot?.querySelector( + "[data-task], [data-tasks-notice], [data-tasks-empty]" + ) && !el.shadowRoot?.querySelector("[data-tasks-loading]"), + "the tasks weren't shown", + { timeout: 5000 } + ); + return el; +} + +const tasks = (el: ECCClientGa4ghWesRun) => [ + ...(el.shadowRoot?.querySelectorAll("[data-task]") ?? []), +]; + +describe("ecc-client-ga4gh-wes-run tasks", () => { + it("shows inline task logs", async () => { + const log = { + ...runLog("COMPLETE", {}), + task_logs: [{ name: "align", exit_code: 0 }], + } as unknown as RunLog; + const el = await renderTasks(new FakeProvider(log)); + expect(tasks(el).map((task) => task.dataset.task)).to.deep.equal(["align"]); + }); + + it("drops the tasks of a run ID that was cleared", async () => { + const log = { + ...runLog("COMPLETE", {}), + task_logs: [{ name: "align", exit_code: 0 }], + } as unknown as RunLog; + const el = await renderTasks(new FakeProvider(log)); + el.runId = ""; + await el.updateComplete; + const state = el as unknown as { tasks: unknown[] }; + expect(state.tasks).to.deep.equal([]); + }); + + it("drops a task page of an earlier run ID", async () => { + let releaseOld: ((page: TaskListResponse) => void) | undefined; + const provider = new TaskProvider(byUrl(), { + "": { task_logs: [{ id: "new", name: "new" }] }, + }); + const listPage = provider.listRunTasks.bind(provider); + provider.listRunTasks = (runId: string, size?: number, token?: string) => + releaseOld === undefined + ? new Promise((resolve) => { + releaseOld = resolve; + }) + : listPage(runId, size, token); + const el = await fixture( + html`` + ); + await waitUntil(() => releaseOld !== undefined, "no task listing"); + el.runId = "run-8"; + await waitUntil( + () => tasks(el).length === 1, + "run-8's tasks weren't shown" + ); + releaseOld?.({ task_logs: [{ id: "old", name: "old" }] }); + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + expect(tasks(el).map((task) => task.dataset.task)).to.deep.equal(["new"]); + }); + + it("asks for the next task page once while it loads", async () => { + const provider = new TaskProvider(byUrl(), { + "": { task_logs: [{ id: "t1", name: "align" }], next_page_token: "p2" }, + p2: { task_logs: [{ id: "t2", name: "count" }] }, + }); + const el = await renderTasks(provider); + const more = el.shadowRoot?.querySelector("[data-load-more]"); + more?.click(); + more?.click(); + await waitUntil(() => tasks(el).length === 2, "no second page"); + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + expect(provider.calls).to.deep.equal([undefined, "p2"]); + expect(tasks(el)).to.have.length(2); + }); + + it("drops a log of an earlier run ID", async () => { + const log = (id: string) => + ({ + ...runLog("COMPLETE", {}), + run_id: id, + run_log: { stdout: `https://wes.example.org/logs/${id}` }, + } as unknown as RunLog); + const provider = new TaskProvider(log("run-7"), {}); + provider.getRunLog = async (id: string) => log(id); + let releaseOld: ((text: string) => void) | undefined; + provider.getLog = (url: string) => + url.endsWith("run-7") + ? new Promise((resolve) => { + releaseOld = resolve; + }) + : Promise.resolve("log of run-8"); + const el = await fixture( + html`` + ); + const contents = () => + Object.values( + (el as unknown as { logContents: Record }).logContents + ); + await waitUntil( + () => releaseOld !== undefined, + "run-7's log wasn't fetched" + ); + el.runId = "run-8"; + await waitUntil( + () => contents().includes("log of run-8"), + "run-8's log wasn't fetched" + ); + releaseOld?.("log of run-7"); + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + expect(contents()).to.include("log of run-8"); + expect(contents()).to.not.include("log of run-7"); + }); + + it("lists the tasks from task_logs_url by page", async () => { + const provider = new TaskProvider(byUrl(), { + "": { + task_logs: [ + { + id: "t1", + name: "align", + exit_code: 0, + system_logs: ["pulled image"], + tes_uri: "https://tes.example.org/ga4gh/tes/v1/tasks/abc", + }, + ], + next_page_token: "p2", + }, + p2: { task_logs: [{ id: "t2", name: "count", exit_code: 1 }] }, + }); + const el = await renderTasks(provider); + expect(tasks(el)).to.have.length(1); + const [first] = tasks(el); + expect( + first.querySelector("[data-system-logs]") + ?.value + ).to.equal("pulled image"); + const link = first.querySelector("a[data-tes-uri]"); + expect(link?.href).to.equal( + "https://tes.example.org/ga4gh/tes/v1/tasks/abc" + ); + const more = el.shadowRoot?.querySelector("[data-load-more]"); + expect(more).to.not.equal(null); + more?.click(); + await waitUntil(() => tasks(el).length === 2, "no second page"); + expect(tasks(el).map((task) => task.dataset.task)).to.deep.equal([ + "align", + "count", + ]); + expect(provider.calls).to.deep.equal([undefined, "p2"]); + expect(el.shadowRoot?.querySelector("[data-load-more]")).to.equal(null); + }); + + it("shows a TES URI that isn't a web address as text", async () => { + const provider = new TaskProvider(byUrl(), { + "": { + task_logs: [ + { id: "t1", name: "align", tes_uri: "javascript:alert(1)" }, + ], + }, + }); + const el = await renderTasks(provider); + const [first] = tasks(el); + expect(first.querySelector("a[data-tes-uri]")).to.equal(null); + expect(first.textContent).to.contain("javascript:alert(1)"); + }); + + it("says when the provider can't list tasks", async () => { + const el = await renderTasks(new FakeProvider(byUrl())); + expect( + el.shadowRoot?.querySelector("[data-tasks-notice]")?.textContent + ).to.contain("can't list"); + }); + + it("reports tasks that can't be listed", async () => { + const el = await renderTasks(new TaskProvider(byUrl(), {})); + expect( + el.shadowRoot?.querySelector("[data-tasks-notice]")?.textContent + ).to.contain("no such page"); + }); + + it("fetches log URLs through the provider", async () => { + const provider = new TaskProvider( + { + ...runLog("COMPLETE", {}), + run_log: { stdout: "https://wes.example.org/logs/run-7/stdout" }, + } as unknown as RunLog, + {} + ); + const el = await fixture( + html`` + ); + await waitUntil(() => provider.logs.length > 0, "no log fetched"); + expect(provider.logs).to.deep.equal([ + "https://wes.example.org/logs/run-7/stdout", + ]); + await el.updateComplete; + }); + + it("shows log values that aren't URLs as text, with a hint", async () => { + const el = await fixture( + html`` + ); + await waitUntil( + () => el.shadowRoot?.querySelector("[data-log-hint]"), + "no hint" + ); + expect( + el.shadowRoot?.querySelector( + "[data-stdout]" + )?.value + ).to.equal("plain text"); + }); + + it("offers a retry when the task listing fails", async () => { + const provider = new TaskProvider(byUrl(), {}); + const el = await renderTasks(provider); + provider.pages[""] = { task_logs: [{ id: "t1", name: "align" }] }; + el.shadowRoot?.querySelector("[data-tasks-retry]")?.click(); + await waitUntil(() => tasks(el).length === 1, "the retry listed nothing"); + expect(el.shadowRoot?.querySelector("[data-tasks-notice]")).to.equal(null); + }); + + it("offers the next page after an empty page", async () => { + const provider = new TaskProvider(byUrl(), { + "": { task_logs: [], next_page_token: "p2" }, + p2: { task_logs: [{ id: "t2", name: "count" }] }, + }); + const el = await renderTasks(provider); + el.shadowRoot?.querySelector("[data-load-more]")?.click(); + await waitUntil(() => tasks(el).length === 1, "no second page"); + }); + + it("fetches a task's logs only when it is opened", async () => { + const provider = new TaskProvider(byUrl(), { + "": { + task_logs: [ + { id: "t1", name: "align", stdout: "https://wes.example.org/l/1" }, + ], + }, + }); + const el = await renderTasks(provider); + await new Promise((resolve) => { + setTimeout(resolve, 50); + }); + expect(provider.logs).to.deep.equal([]); + (tasks(el)[0] as HTMLElement & { toggleOpen(): void }).toggleOpen(); + await waitUntil(() => provider.logs.length > 0, "no log fetched"); + expect(provider.logs).to.deep.equal(["https://wes.example.org/l/1"]); + }); +}); diff --git a/packages/ecc-client-ga4gh-wes/src/providers/rest-wes-provider.ts b/packages/ecc-client-ga4gh-wes/src/providers/rest-wes-provider.ts index f0b5340a..e6a3f136 100644 --- a/packages/ecc-client-ga4gh-wes/src/providers/rest-wes-provider.ts +++ b/packages/ecc-client-ga4gh-wes/src/providers/rest-wes-provider.ts @@ -7,6 +7,7 @@ import { RunLog, RunStatus, ErrorResponse, + TaskListResponse, } from "./wes-provider.js"; /** @@ -124,6 +125,52 @@ export class RestWesProvider implements WesProvider { return RestWesProvider.handleResponse(response); } + async listRunTasks( + runId: string, + pageSize?: number, + pageToken?: string + ): Promise { + const params = new URLSearchParams(); + if (pageSize !== undefined) { + params.append("page_size", pageSize.toString()); + } + if (pageToken) params.append("page_token", pageToken); + const query = params.toString(); + const response = await this.fetch( + `${this.baseUrl}/runs/${encodeURIComponent(runId)}/tasks${ + query ? `?${query}` : "" + }` + ); + return RestWesProvider.handleResponse(response); + } + + /** + * Fetches the text of a log. URLs on the service's origin go through + * `fetch` (and so get what a subclass adds, e.g. `Authorization`); other + * origins are fetched without credentials. Only http(s) URLs are fetched. + */ + async getLog(url: string): Promise { + // A relative base URL (e.g. behind a same-origin proxy) is relative to + // the page + const base = new URL(`${this.baseUrl}/`, globalThis.location?.href); + const target = new URL(url, base); + if (target.protocol !== "https:" && target.protocol !== "http:") { + throw new Error(`Logs are fetched only over HTTP(S): ${url}`); + } + const sameOrigin = target.origin === base.origin; + const response = sameOrigin + ? await this.fetch(target.href) + : await fetch(target.href, { credentials: "omit" }); + if (!response.ok) { + throw new Error( + `HTTP ${response.status}${ + response.statusText ? `: ${response.statusText}` : "" + }` + ); + } + return response.text(); + } + async cancelRun(runId: string): Promise { const response = await this.fetch( `${this.baseUrl}/runs/${encodeURIComponent(runId)}/cancel`, diff --git a/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider.test.ts b/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider.test.ts index 19f30f72..fed91cbf 100644 --- a/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider.test.ts +++ b/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider.test.ts @@ -30,6 +30,8 @@ const callAllMethods = async (provider: RestWesProvider) => { await provider.getRunLog("run-1"); await provider.getRunStatus("run-1"); await provider.cancelRun("run-1"); + await provider.listRunTasks("run-1", 10, "next"); + await provider.getLog(`${BASE_URL}/runs/run-1/logs/stdout`); }; describe("RestWesProvider", () => { @@ -48,7 +50,7 @@ describe("RestWesProvider", () => { it("sends requests without headers by default", async () => { await callAllMethods(new RestWesProvider(BASE_URL)); - expect(fetchStub.callCount).to.equal(6); + expect(fetchStub.callCount).to.equal(8); fetchStub.getCalls().forEach((call) => { expect(call.args[1]?.headers).to.equal(undefined); }); @@ -57,7 +59,7 @@ describe("RestWesProvider", () => { it("sends every request through an overridden fetch", async () => { await callAllMethods(new TokenWesProvider(BASE_URL)); - expect(fetchStub.callCount).to.equal(6); + expect(fetchStub.callCount).to.equal(8); fetchStub.getCalls().forEach((call) => { const headers = new Headers(call.args[1]?.headers); expect(headers.get("Authorization")).to.equal("Bearer test-token"); @@ -73,4 +75,112 @@ describe("RestWesProvider", () => { // The browser sets the multipart boundary only if Content-Type is unset expect(new Headers(init.headers).has("Content-Type")).to.equal(false); }); + + it("lists a run's tasks by page", async () => { + fetchStub.callsFake( + async () => + new Response( + JSON.stringify({ + task_logs: [{ id: "t1", name: "align" }], + next_page_token: "p2", + }), + { status: 200 } + ) + ); + const page = await new RestWesProvider(BASE_URL).listRunTasks( + "run/1", + 50, + "p1" + ); + expect(fetchStub.firstCall.args[0]).to.equal( + `${BASE_URL}/runs/run%2F1/tasks?page_size=50&page_token=p1` + ); + expect(page.task_logs[0].id).to.equal("t1"); + expect(page.next_page_token).to.equal("p2"); + }); + + it("lists tasks without a query when no page is given", async () => { + fetchStub.callsFake( + async () => + new Response(JSON.stringify({ task_logs: [] }), { status: 200 }) + ); + await new RestWesProvider(BASE_URL).listRunTasks("run-1"); + expect(fetchStub.firstCall.args[0]).to.equal( + `${BASE_URL}/runs/run-1/tasks` + ); + }); + + it("reports a task listing that fails", async () => { + fetchStub.callsFake( + async () => new Response("{}", { status: 500, statusText: "Oops" }) + ); + let error: unknown; + try { + await new RestWesProvider(BASE_URL).listRunTasks("run-1"); + } catch (err) { + error = err; + } + expect(error).to.be.instanceOf(Error); + }); + + it("fetches logs with a base URL relative to the page", async () => { + fetchStub.callsFake(async () => new Response("hello", { status: 200 })); + const text = await new TokenWesProvider("/ga4gh/wes/v1").getLog( + "logs/run-1/stdout" + ); + expect(text).to.equal("hello"); + expect(fetchStub.firstCall.args[0]).to.equal( + new URL("/ga4gh/wes/v1/logs/run-1/stdout", window.location.href).href + ); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("fetches logs on the service's origin with its fetch", async () => { + fetchStub.callsFake(async () => new Response("hello", { status: 200 })); + const text = await new TokenWesProvider(BASE_URL).getLog( + "https://wes.example.org/logs/run-1/stdout" + ); + expect(text).to.equal("hello"); + expect(fetchStub.firstCall.args[0]).to.equal( + "https://wes.example.org/logs/run-1/stdout" + ); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("fetches logs on other origins without credentials", async () => { + fetchStub.callsFake(async () => new Response("hello", { status: 200 })); + await new TokenWesProvider(BASE_URL).getLog( + "https://storage.example.com/run-1/stdout" + ); + const [url, init] = fetchStub.firstCall.args; + expect(url).to.equal("https://storage.example.com/run-1/stdout"); + expect(new Headers(init?.headers).has("Authorization")).to.equal(false); + expect(init?.credentials).to.equal("omit"); + }); + + it("refuses log URLs that aren't http(s)", async () => { + let error: unknown; + try { + await new RestWesProvider(BASE_URL).getLog("file:///etc/passwd"); + } catch (err) { + error = err; + } + expect(error).to.be.instanceOf(Error); + expect(fetchStub.callCount).to.equal(0); + }); + + it("reports a log that can't be fetched", async () => { + fetchStub.callsFake( + async () => new Response("", { status: 404, statusText: "Not Found" }) + ); + let error: unknown; + try { + await new RestWesProvider(BASE_URL).getLog(`${BASE_URL}/logs/x`); + } catch (err) { + error = err; + } + expect((error as Error).message).to.contain("404"); + }); }); diff --git a/packages/ecc-client-ga4gh-wes/src/providers/wes-provider.ts b/packages/ecc-client-ga4gh-wes/src/providers/wes-provider.ts index a65ff164..17005aa5 100644 --- a/packages/ecc-client-ga4gh-wes/src/providers/wes-provider.ts +++ b/packages/ecc-client-ga4gh-wes/src/providers/wes-provider.ts @@ -36,6 +36,22 @@ export interface Log { exit_code?: number; } +/** A task of a run (WES 1.1 `TaskLog`) */ +export interface TaskLog extends Log { + /** The task's ID, unique within the run */ + id?: string; + /** System logs of the task, e.g. why it failed */ + system_logs?: string[]; + /** The task's URI at a TES service, if it ran there */ + tes_uri?: string; +} + +/** A page of a run's tasks (`GET /runs/{run_id}/tasks`, WES 1.1) */ +export interface TaskListResponse { + task_logs: TaskLog[]; + next_page_token?: string; +} + // Workflow type version export interface WorkflowTypeVersion { workflow_type_version: string[]; @@ -82,7 +98,10 @@ export interface RunLog { request: RunRequest; state: State; run_log: Log; - task_logs: Log[]; + /** Deprecated in WES 1.1 in favour of `task_logs_url` */ + task_logs?: TaskLog[] | null; + /** Where the run's tasks are listed, by page (WES 1.1) */ + task_logs_url?: string | null; outputs: object; } @@ -112,4 +131,20 @@ export interface WesProvider { getRunLog(runId: string): Promise; getRunStatus(runId: string): Promise; cancelRun(runId: string): Promise; + + /** + * Lists a page of a run's tasks (WES 1.1 `GET /runs/{run_id}/tasks`); + * optional, for runs that give `task_logs_url` instead of `task_logs`. + */ + listRunTasks?( + runId: string, + pageSize?: number, + pageToken?: string + ): Promise; + + /** + * Fetches the text of a log (`stdout`, `stderr` URLs); optional. Without + * it, logs are fetched without credentials. + */ + getLog?(url: string): Promise; }