diff --git a/.changeset/cloud-registry-request-timeout.md b/.changeset/cloud-registry-request-timeout.md new file mode 100644 index 00000000..bc8c7a39 --- /dev/null +++ b/.changeset/cloud-registry-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/cloud-registry": minor +--- + +`RestCloudRegistryProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/design-request-timeout.md b/.changeset/design-request-timeout.md new file mode 100644 index 00000000..8d49bec9 --- /dev/null +++ b/.changeset/design-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/design": minor +--- + +Add `fetchWithTimeout()`, `RequestTimeoutError` and the other request timeout utilities to `@elixir-cloud/design/utils`. diff --git a/.changeset/drs-filer-request-timeout.md b/.changeset/drs-filer-request-timeout.md new file mode 100644 index 00000000..5cb6ddad --- /dev/null +++ b/.changeset/drs-filer-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/drs-filer": minor +--- + +`RestDrsFilerProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/drs-request-timeout.md b/.changeset/drs-request-timeout.md new file mode 100644 index 00000000..2a6d433e --- /dev/null +++ b/.changeset/drs-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/drs": minor +--- + +`RestDrsProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/service-registry-request-timeout.md b/.changeset/service-registry-request-timeout.md new file mode 100644 index 00000000..e3ab1a6c --- /dev/null +++ b/.changeset/service-registry-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/service-registry": minor +--- + +`RestServiceRegistryProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/tes-request-timeout.md b/.changeset/tes-request-timeout.md new file mode 100644 index 00000000..4b3f7e66 --- /dev/null +++ b/.changeset/tes-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/tes": minor +--- + +`RestTesProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/trs-filer-request-timeout.md b/.changeset/trs-filer-request-timeout.md new file mode 100644 index 00000000..36e5bf55 --- /dev/null +++ b/.changeset/trs-filer-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/trs-filer": minor +--- + +`RestTrsFilerProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/trs-request-timeout.md b/.changeset/trs-request-timeout.md new file mode 100644 index 00000000..74c9f27c --- /dev/null +++ b/.changeset/trs-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/trs": minor +--- + +`RestTrsProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/.changeset/wes-request-timeout.md b/.changeset/wes-request-timeout.md new file mode 100644 index 00000000..2add92d4 --- /dev/null +++ b/.changeset/wes-request-timeout.md @@ -0,0 +1,5 @@ +--- +"@elixir-cloud/wes": minor +--- + +`RestWesProvider` times out requests after 30 s by default. Set another deadline with the new `timeout` option (milliseconds, `0` for none). diff --git a/apps/documentation/pages/docs/cloud-registry/providers.mdx b/apps/documentation/pages/docs/cloud-registry/providers.mdx index 83e45c31..fb0cca48 100644 --- a/apps/documentation/pages/docs/cloud-registry/providers.mdx +++ b/apps/documentation/pages/docs/cloud-registry/providers.mdx @@ -49,11 +49,12 @@ The `RestCloudRegistryProvider` is the main implementation that communicates wit ### Constructor ```typescript -constructor(baseUrl: string) +constructor(baseUrl: string, options?: { timeout?: number }) ``` **Parameters:** - `baseUrl`: The base URL of the Cloud Registry API endpoint (e.g., `https://cloud-registry.example.com/ga4gh/registry/v1`) +- `options.timeout`: request deadline in milliseconds (default 30 s, `0` for none). See [Request timeouts](/docs/design/request-timeouts). ### Basic Usage diff --git a/apps/documentation/pages/docs/design/_meta.json b/apps/documentation/pages/docs/design/_meta.json index bc577822..7bc00c68 100644 --- a/apps/documentation/pages/docs/design/_meta.json +++ b/apps/documentation/pages/docs/design/_meta.json @@ -2,5 +2,6 @@ "introduction": "Introduction", "architecture": "Architecture", "components": "Components", - "field-errors": "Field errors" + "field-errors": "Field errors", + "request-timeouts": "Request timeouts" } diff --git a/apps/documentation/pages/docs/design/request-timeouts.mdx b/apps/documentation/pages/docs/design/request-timeouts.mdx new file mode 100644 index 00000000..29709f43 --- /dev/null +++ b/apps/documentation/pages/docs/design/request-timeouts.mdx @@ -0,0 +1,58 @@ +import { Callout } from 'nextra/components'; + +# Request timeouts + +Every request of a REST provider has a deadline, so that a server that never +answers makes the component show an error instead of loading forever. When +the deadline expires, the request rejects with a `RequestTimeoutError`. + +The deadline is **30 seconds** by default and covers the whole request, +including reading the response. Set it per provider with the `timeout` option +(milliseconds, `0` for none): + +```ts +import { RestTrsProvider } from '@elixir-cloud/trs/providers'; + +const provider = new RestTrsProvider('https://trs.example.org/ga4gh/trs/v2', { + timeout: 10_000, +}); +``` + +All REST providers take this option, including `RestDrsProvider` and +`RestDrsFilerProvider`. Components created with `baseUrl` use the default; to +set another deadline, pass them a provider. + +A provider that overrides `fetch()` and calls `super.fetch()` keeps the +deadline. A custom provider that doesn't extend a REST provider must set its +own: its methods should reject, not stay pending. + + + A timed-out request that creates something (e.g. `createTask()` of TES, + `runWorkflow()` of WES) may still have succeeded on the server. Don't retry + it automatically. + + +## Utilities + +`@elixir-cloud/design/utils` exports what the REST providers use: + +| Export | Description | +| ------------------------------------------ | ------------------------------------------------------------------------------------ | +| `fetchWithTimeout(input, init?, timeout?)` | `fetch` with a deadline in milliseconds (default 30 s, `0` for none). | +| `RequestTimeoutError` | The error of an expired request, with the deadline as `timeout`. | +| `resolveRequestTimeout(options?)` | The deadline of provider options; throws a `RangeError` for an invalid value. | +| `DEFAULT_REQUEST_TIMEOUT` | `30000` (30 s). | +| `MAX_REQUEST_TIMEOUT` | `2147483647`, the longest deadline that timers support. | +| `RestProviderOptions` | Type of the options (`{ timeout?: number }`). | + +```ts +import { RequestTimeoutError } from '@elixir-cloud/design/utils'; + +try { + await provider.getServiceInfo(); +} catch (error) { + if (error instanceof RequestTimeoutError) { + // the server didn't answer within error.timeout ms + } +} +``` diff --git a/apps/documentation/pages/docs/providers.mdx b/apps/documentation/pages/docs/providers.mdx index 3a059ce7..4621d81e 100644 --- a/apps/documentation/pages/docs/providers.mdx +++ b/apps/documentation/pages/docs/providers.mdx @@ -280,6 +280,8 @@ function handleProviderError(error, method, args) { #### Retry Logic ```tsx copy +import { RequestTimeoutError } from '@elixir-cloud/design/utils'; + // Retry wrapper for transient failures function withRetry(Provider, maxRetries = 3, delay = 1000) { return class extends Provider { @@ -296,6 +298,16 @@ function withRetry(Provider, maxRetries = 3, delay = 1000) { if (error.status >= 400 && error.status < 500) { throw error; } + + // Don't repeat a timed-out request that may have changed + // something: the server may have done it already + const method = (options.method ?? 'GET').toUpperCase(); + if ( + error instanceof RequestTimeoutError && + !['GET', 'HEAD'].includes(method) + ) { + throw error; + } if (i < maxRetries) { await new Promise(resolve => setTimeout(resolve, delay * (i + 1))); @@ -313,6 +325,20 @@ const RetryableProvider = withRetry(RestWesProvider, 3, 1000); const provider = new RetryableProvider('https://api.example.com'); ``` +Each attempt has its own [deadline](#timeouts). Don't retry a timed-out request that creates something: the server may already have done it. + +#### Timeouts + +Requests of the REST providers time out after 30 seconds with a `RequestTimeoutError`. Set another deadline with the `timeout` option (milliseconds, `0` for none): + +```tsx copy +const provider = new RestWesProvider('https://api.example.com', { + timeout: 10_000, +}); +``` + +See [Request timeouts](/docs/design/request-timeouts). + ### Caching and Performance #### Request Caching diff --git a/apps/documentation/pages/docs/service-registry/providers.mdx b/apps/documentation/pages/docs/service-registry/providers.mdx index 6d01ca98..66d934ea 100644 --- a/apps/documentation/pages/docs/service-registry/providers.mdx +++ b/apps/documentation/pages/docs/service-registry/providers.mdx @@ -35,11 +35,12 @@ The `RestServiceRegistryProvider` is the main implementation that communicates w ### Constructor ```typescript -constructor(baseUrl: string) +constructor(baseUrl: string, options?: { timeout?: number }) ``` **Parameters:** - `baseUrl`: The base URL of the Service Registry API endpoint (e.g., `https://registry.example.com/ga4gh/registry/v1`) +- `options.timeout`: request deadline in milliseconds (default 30 s, `0` for none). See [Request timeouts](/docs/design/request-timeouts). ### Basic Usage diff --git a/apps/documentation/pages/docs/tes/providers.mdx b/apps/documentation/pages/docs/tes/providers.mdx index 95de9ac8..986ff4f4 100644 --- a/apps/documentation/pages/docs/tes/providers.mdx +++ b/apps/documentation/pages/docs/tes/providers.mdx @@ -34,12 +34,13 @@ The `RestTesProvider` is the main implementation that communicates with TES APIs ### Constructor ```typescript -constructor(baseUrl: string) +constructor(baseUrl: string, options?: { timeout?: number }) ``` **Parameters:** - `baseUrl`: The base URL of the TES API endpoint (e.g., `https://protes.rahtiapp.fi/ga4gh/tes/v1`) +- `options.timeout`: request deadline in milliseconds (default 30 s, `0` for none). See [Request timeouts](/docs/design/request-timeouts). ### Basic Usage diff --git a/apps/documentation/pages/docs/trs-filer/providers.mdx b/apps/documentation/pages/docs/trs-filer/providers.mdx index 25bfe64b..c717adc6 100644 --- a/apps/documentation/pages/docs/trs-filer/providers.mdx +++ b/apps/documentation/pages/docs/trs-filer/providers.mdx @@ -79,11 +79,12 @@ The `RestTrsFilerProvider` is the main implementation that communicates with TRS ### Constructor ```typescript -constructor(baseUrl: string) +constructor(baseUrl: string, options?: { timeout?: number }) ``` **Parameters:** - `baseUrl`: The base URL of the TRS Filer API endpoint (e.g., `https://trs-filer.example.com/ga4gh/trs/v2`) +- `options.timeout`: request deadline in milliseconds (default 30 s, `0` for none). See [Request timeouts](/docs/design/request-timeouts). ### Basic Usage diff --git a/apps/documentation/pages/docs/trs/providers.mdx b/apps/documentation/pages/docs/trs/providers.mdx index 6fad01c3..130138b7 100644 --- a/apps/documentation/pages/docs/trs/providers.mdx +++ b/apps/documentation/pages/docs/trs/providers.mdx @@ -64,11 +64,12 @@ The `RestTrsProvider` is the main implementation that communicates with TRS APIs ### Constructor ```typescript -constructor(baseUrl: string) +constructor(baseUrl: string, options?: { timeout?: number }) ``` **Parameters:** - `baseUrl`: The base URL of the TRS API endpoint (e.g., `https://dockstore.org/api/ga4gh/trs/v2`) +- `options.timeout`: request deadline in milliseconds (default 30 s, `0` for none). See [Request timeouts](/docs/design/request-timeouts). ### Basic Usage diff --git a/apps/documentation/pages/docs/wes/providers.mdx b/apps/documentation/pages/docs/wes/providers.mdx index 0cec1627..ea465329 100644 --- a/apps/documentation/pages/docs/wes/providers.mdx +++ b/apps/documentation/pages/docs/wes/providers.mdx @@ -33,11 +33,12 @@ The `RestWesProvider` is the main implementation that communicates with WES APIs ### Constructor ```typescript -constructor(baseUrl: string) +constructor(baseUrl: string, options?: { timeout?: number }) ``` **Parameters:** - `baseUrl`: The base URL of the WES API endpoint (e.g., `https://weskit.example.com/ga4gh/wes/v1`) +- `options.timeout`: request deadline in milliseconds (default 30 s, `0` for none). See [Request timeouts](/docs/design/request-timeouts). ### Basic Usage diff --git a/packages/ecc-client-elixir-cloud-registry/src/providers/rest-cr-provider.ts b/packages/ecc-client-elixir-cloud-registry/src/providers/rest-cr-provider.ts index 8c6e7857..c0eadb08 100644 --- a/packages/ecc-client-elixir-cloud-registry/src/providers/rest-cr-provider.ts +++ b/packages/ecc-client-elixir-cloud-registry/src/providers/rest-cr-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { CloudRegistryProvider, ExternalService, @@ -19,16 +24,28 @@ import { CloudRegistryError } from "./errors.js"; * with an error status; it carries the status and the problem details. */ export class RestCloudRegistryProvider implements CloudRegistryProvider { - // eslint-disable-next-line no-useless-constructor - constructor(public readonly baseUrl: string) {} + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the Cloud Registry API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor( + public readonly baseUrl: string, + options: RestProviderOptions = {} + ) { + this.timeout = resolveRequestTimeout(options); + } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } /** diff --git a/packages/ecc-client-elixir-cloud-registry/src/providers/tests/rest-cr-provider-timeout.test.ts b/packages/ecc-client-elixir-cloud-registry/src/providers/tests/rest-cr-provider-timeout.test.ts new file mode 100644 index 00000000..fe5d0ba0 --- /dev/null +++ b/packages/ecc-client-elixir-cloud-registry/src/providers/tests/rest-cr-provider-timeout.test.ts @@ -0,0 +1,96 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; +import { RestCloudRegistryProvider } from "../rest-cr-provider.js"; + +const BASE_URL = "https://registry.example.org/ga4gh/registry/v1"; + +/** Provider that adds a bearer token to every request, as in the docs. */ +class TokenProvider extends RestCloudRegistryProvider { + protected fetch(input: RequestInfo | URL, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("Authorization", "Bearer test-token"); + return super.fetch(input, { ...init, headers }); + } +} + +/** Provider methods, one of each kind of request. */ +const CALLS: [string, (p: RestCloudRegistryProvider) => Promise][] = [ + ["getServices", (p) => p.getServices()], + ["deleteService", (p) => p.deleteService("service-1")], +]; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + +/** The error that a call rejects with. */ +const rejection = async (call: () => Promise): Promise => { + try { + await call(); + } catch (err) { + return err; + } + throw new Error("Expected the call to reject"); +}; + +describe("RestCloudRegistryProvider request timeout", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("defaults to 30 s", () => { + expect(new RestCloudRegistryProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect( + () => new RestCloudRegistryProvider(BASE_URL, { timeout: -1 }) + ).to.throw(RangeError); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + const provider = new RestCloudRegistryProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => call(provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as Error).message).to.equal( + "Request timed out after 20 ms" + ); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + const provider = new TokenProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => CALLS[0][1](provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("{}", { status: 200 })); + + await CALLS[0][1](new RestCloudRegistryProvider(BASE_URL, { timeout: 0 })); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); +}); diff --git a/packages/ecc-client-elixir-drs-filer/src/providers/rest-drs-filer-provider.ts b/packages/ecc-client-elixir-drs-filer/src/providers/rest-drs-filer-provider.ts index 49cf3461..c6652467 100644 --- a/packages/ecc-client-elixir-drs-filer/src/providers/rest-drs-filer-provider.ts +++ b/packages/ecc-client-elixir-drs-filer/src/providers/rest-drs-filer-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { DrsFilerProvider, DrsObject, @@ -12,16 +17,28 @@ import { * This class provides DRS-Filer specific functionality for object management */ export class RestDrsFilerProvider implements DrsFilerProvider { - // eslint-disable-next-line no-useless-constructor - constructor(public readonly baseUrl: string) {} + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the DRS-Filer API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor( + public readonly baseUrl: string, + options: RestProviderOptions = {} + ) { + this.timeout = resolveRequestTimeout(options); + } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } // Base DRS operations (inherited from DrsProvider) diff --git a/packages/ecc-client-elixir-trs-filer/src/providers/rest-trs-filer-provider.ts b/packages/ecc-client-elixir-trs-filer/src/providers/rest-trs-filer-provider.ts index 60f1f212..dbdd0c72 100644 --- a/packages/ecc-client-elixir-trs-filer/src/providers/rest-trs-filer-provider.ts +++ b/packages/ecc-client-elixir-trs-filer/src/providers/rest-trs-filer-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { TrsFilerProvider, DescriptorType, @@ -16,16 +21,28 @@ import { * This class combines the functionality of TrsAPI and RestTrsProvider for TRS-Filer */ export class RestTrsFilerProvider implements TrsFilerProvider { - // eslint-disable-next-line no-useless-constructor - constructor(public readonly baseUrl: string) {} + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the TRS-Filer API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor( + public readonly baseUrl: string, + options: RestProviderOptions = {} + ) { + this.timeout = resolveRequestTimeout(options); + } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } async getToolClasses(): Promise { diff --git a/packages/ecc-client-elixir-trs-filer/src/providers/tests/rest-trs-filer-provider-timeout.test.ts b/packages/ecc-client-elixir-trs-filer/src/providers/tests/rest-trs-filer-provider-timeout.test.ts new file mode 100644 index 00000000..8ce395c6 --- /dev/null +++ b/packages/ecc-client-elixir-trs-filer/src/providers/tests/rest-trs-filer-provider-timeout.test.ts @@ -0,0 +1,99 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; +import { RestTrsFilerProvider } from "../rest-trs-filer-provider.js"; + +const BASE_URL = "https://trs.example.org/ga4gh/trs/v2"; + +/** Provider that adds a bearer token to every request, as in the docs. */ +class TokenProvider extends RestTrsFilerProvider { + protected fetch(input: RequestInfo | URL, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("Authorization", "Bearer test-token"); + return super.fetch(input, { ...init, headers }); + } +} + +/** Provider methods, one of each kind of request. */ +const CALLS: [string, (p: RestTrsFilerProvider) => Promise][] = [ + ["getToolClasses", (p) => p.getToolClasses()], + [ + "createToolClass", + (p) => p.createToolClass({ name: "Workflow", description: "" }), + ], +]; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + +/** The error that a call rejects with. */ +const rejection = async (call: () => Promise): Promise => { + try { + await call(); + } catch (err) { + return err; + } + throw new Error("Expected the call to reject"); +}; + +describe("RestTrsFilerProvider request timeout", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("defaults to 30 s", () => { + expect(new RestTrsFilerProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect(() => new RestTrsFilerProvider(BASE_URL, { timeout: -1 })).to.throw( + RangeError + ); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + const provider = new RestTrsFilerProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => call(provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as Error).message).to.equal( + "Request timed out after 20 ms" + ); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + const provider = new TokenProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => CALLS[0][1](provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("{}", { status: 200 })); + + await CALLS[0][1](new RestTrsFilerProvider(BASE_URL, { timeout: 0 })); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); +}); diff --git a/packages/ecc-client-ga4gh-drs/src/components/objects-list/tests/objects.test.ts b/packages/ecc-client-ga4gh-drs/src/components/objects-list/tests/objects.test.ts index cd654566..411a9755 100644 --- a/packages/ecc-client-ga4gh-drs/src/components/objects-list/tests/objects.test.ts +++ b/packages/ecc-client-ga4gh-drs/src/components/objects-list/tests/objects.test.ts @@ -3,11 +3,18 @@ import { expect, fixture, html, waitUntil } from "@open-wc/testing"; import sinon from "sinon"; import "../index.js"; import type { ECCClientGa4ghDrsObjects } from "../objects.js"; +import { RestDrsProvider } from "../../../providers/rest-drs-provider.js"; import type { DrsObject, DrsProvider, } from "../../../providers/drs-provider.js"; +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + const BASE_URL = "https://drs.example.org/ga4gh/drs/v1"; const OTHER_URL = "https://other.example.org/ga4gh/drs/v1"; const MISSING = "Please provide either a base URL"; @@ -224,4 +231,22 @@ describe("ecc-client-ga4gh-drs-objects provider", () => { expect(el.shadowRoot?.textContent).not.to.contain("Unavailable"); expect(reported).to.deep.equal([]); }); + + it("shows the error of an expired request and reports no objects", async () => { + fetchStub.callsFake(neverAnswer); + const reported: DrsObject[][] = []; + const el = await fixture( + html` + reported.push(e.detail.objects)} + >` + ); + + await waitUntil(() => + el.shadowRoot?.textContent?.includes("Request timed out after 20 ms") + ); + expect(internals(el).objects).to.deep.equal([]); + expect(reported).to.deep.equal([[]]); + }); }); diff --git a/packages/ecc-client-ga4gh-drs/src/providers/rest-drs-provider.ts b/packages/ecc-client-ga4gh-drs/src/providers/rest-drs-provider.ts index 975eb18a..20715202 100644 --- a/packages/ecc-client-ga4gh-drs/src/providers/rest-drs-provider.ts +++ b/packages/ecc-client-ga4gh-drs/src/providers/rest-drs-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { DrsProvider, DrsObject, AccessURL, Service } from "./drs-provider.js"; /** @@ -5,16 +10,28 @@ import { DrsProvider, DrsObject, AccessURL, Service } from "./drs-provider.js"; * This class provides standard GA4GH DRS API functionality */ export class RestDrsProvider implements DrsProvider { - // eslint-disable-next-line no-useless-constructor - constructor(public readonly baseUrl: string) {} + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * @param baseUrl Base URL of the DRS API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor( + public readonly baseUrl: string, + options: RestProviderOptions = {} + ) { + this.timeout = resolveRequestTimeout(options); + } + + /** + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } async getObjects( diff --git a/packages/ecc-client-ga4gh-drs/src/providers/tests/rest-drs-provider-timeout.test.ts b/packages/ecc-client-ga4gh-drs/src/providers/tests/rest-drs-provider-timeout.test.ts new file mode 100644 index 00000000..229e1d82 --- /dev/null +++ b/packages/ecc-client-ga4gh-drs/src/providers/tests/rest-drs-provider-timeout.test.ts @@ -0,0 +1,96 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; +import { RestDrsProvider } from "../rest-drs-provider.js"; + +const BASE_URL = "https://drs.example.org/ga4gh/drs/v1"; + +/** Provider that adds a bearer token to every request, as in the docs. */ +class TokenProvider extends RestDrsProvider { + protected fetch(input: RequestInfo | URL, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("Authorization", "Bearer test-token"); + return super.fetch(input, { ...init, headers }); + } +} + +/** Provider methods, one of each kind of request. */ +const CALLS: [string, (p: RestDrsProvider) => Promise][] = [ + ["getServiceInfo", (p) => p.getServiceInfo()], + ["getObject", (p) => p.getObject("object-1")], +]; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + +/** The error that a call rejects with. */ +const rejection = async (call: () => Promise): Promise => { + try { + await call(); + } catch (err) { + return err; + } + throw new Error("Expected the call to reject"); +}; + +describe("RestDrsProvider request timeout", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("defaults to 30 s", () => { + expect(new RestDrsProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect(() => new RestDrsProvider(BASE_URL, { timeout: -1 })).to.throw( + RangeError + ); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + const provider = new RestDrsProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => call(provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as Error).message).to.equal( + "Request timed out after 20 ms" + ); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + const provider = new TokenProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => CALLS[0][1](provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("{}", { status: 200 })); + + await CALLS[0][1](new RestDrsProvider(BASE_URL, { timeout: 0 })); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); +}); diff --git a/packages/ecc-client-ga4gh-service-registry/src/components/services/tests/services-provider.test.ts b/packages/ecc-client-ga4gh-service-registry/src/components/services/tests/services-provider.test.ts index 1fb39aeb..e2cb692b 100644 --- a/packages/ecc-client-ga4gh-service-registry/src/components/services/tests/services-provider.test.ts +++ b/packages/ecc-client-ga4gh-service-registry/src/components/services/tests/services-provider.test.ts @@ -42,6 +42,12 @@ const deferred = () => { return { promise, resolve: settleWith }; }; +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + /** The services the component shows. */ const shown = (el: ECCClientGa4ghServiceRegistryServices) => (el as unknown as { services: ExternalService[] }).services; @@ -252,6 +258,25 @@ describe("ecc-client-ga4gh-service-registry-services provider", () => { expect(reported).to.deep.equal([[]]); }); + it("shows the error of an expired request and reports no services", async () => { + fetchStub.callsFake(neverAnswer); + const provider = new RestServiceRegistryProvider(BASE_URL, { + timeout: 20, + }); + const el = await fixture( + html`` + ); + const changed = oneEvent(el, "ecc-services-changed"); + + expect((await changed).detail.services).to.deep.equal([]); + await waitUntil(() => + el.shadowRoot?.textContent?.includes("Request timed out after 20 ms") + ); + expect(shown(el)).to.deep.equal([]); + }); + it("starts on the first page with a provider that replaces the first one", async () => { const first = stubProvider(); const second = stubProvider([service("b")]); diff --git a/packages/ecc-client-ga4gh-service-registry/src/providers/rest-sr-provider.ts b/packages/ecc-client-ga4gh-service-registry/src/providers/rest-sr-provider.ts index 293b6491..a930989d 100644 --- a/packages/ecc-client-ga4gh-service-registry/src/providers/rest-sr-provider.ts +++ b/packages/ecc-client-ga4gh-service-registry/src/providers/rest-sr-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { ServiceRegistryProvider, ExternalService, @@ -10,16 +15,28 @@ import { * This class combines the functionality of ServiceRegistryAPI and RestServiceRegistryProvider */ export class RestServiceRegistryProvider implements ServiceRegistryProvider { - // eslint-disable-next-line no-useless-constructor - constructor(public readonly baseUrl: string) {} + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the Service Registry API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor( + public readonly baseUrl: string, + options: RestProviderOptions = {} + ) { + this.timeout = resolveRequestTimeout(options); + } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } /** diff --git a/packages/ecc-client-ga4gh-service-registry/src/providers/tests/rest-sr-provider.test.ts b/packages/ecc-client-ga4gh-service-registry/src/providers/tests/rest-sr-provider.test.ts index 03dfeb81..1338a58d 100644 --- a/packages/ecc-client-ga4gh-service-registry/src/providers/tests/rest-sr-provider.test.ts +++ b/packages/ecc-client-ga4gh-service-registry/src/providers/tests/rest-sr-provider.test.ts @@ -1,6 +1,10 @@ /* eslint-disable import/no-extraneous-dependencies */ import { expect } from "@open-wc/testing"; import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; import { RestServiceRegistryProvider } from "../rest-sr-provider.js"; const BASE_URL = "https://registry.example.org/ga4gh/registry/v1"; @@ -32,6 +36,13 @@ const CALLS: Call[] = [ ["getServiceInfo", (p) => p.getServiceInfo(), `${BASE_URL}/service-info`], ]; +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +function neverAnswer(_input: RequestInfo | URL, init: RequestInit = {}) { + return new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); +} + describe("RestServiceRegistryProvider", () => { let fetchStub: sinon.SinonStub; @@ -80,4 +91,54 @@ describe("RestServiceRegistryProvider", () => { expect(headers.get("Authorization")).to.equal("Bearer test-token"); }); }); + + it("times out requests after 30 s by default", () => { + expect(new RestServiceRegistryProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect( + () => new RestServiceRegistryProvider(BASE_URL, { timeout: -1 }) + ).to.throw(RangeError); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + fetchStub.callsFake(neverAnswer); + + let error: unknown; + try { + await call(new RestServiceRegistryProvider(BASE_URL, { timeout: 20 })); + } catch (e) { + error = e; + } + + expect(error).to.be.instanceOf(RequestTimeoutError); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + fetchStub.callsFake(neverAnswer); + + let error: unknown; + try { + await new TokenServiceRegistryProvider(BASE_URL, { + timeout: 20, + }).getServices(); + } catch (e) { + error = e; + } + + expect(error).to.be.instanceOf(RequestTimeoutError); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + await new RestServiceRegistryProvider(BASE_URL, { + timeout: 0, + }).getServices(); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); }); diff --git a/packages/ecc-client-ga4gh-tes/src/components/runs/runs.test.ts b/packages/ecc-client-ga4gh-tes/src/components/runs/runs.test.ts index d44325e7..44613ecc 100644 --- a/packages/ecc-client-ga4gh-tes/src/components/runs/runs.test.ts +++ b/packages/ecc-client-ga4gh-tes/src/components/runs/runs.test.ts @@ -7,6 +7,13 @@ import type { Task, ServiceInfo, } from "../../providers/tes-provider.js"; +import { RestTesProvider } from "../../providers/rest-tes-provider.js"; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); const tasks: Task[] = [ { id: "task-1", name: "first", state: "RUNNING" }, @@ -345,4 +352,23 @@ describe("ecc-client-ga4gh-tes-runs", () => { ) ).to.equal(null); }); + + it("shows the error of an expired request", async () => { + const originalFetch = window.fetch; + window.fetch = neverAnswer as typeof fetch; + try { + const el = await fixture( + html`` + ); + await waitUntil(() => + el.shadowRoot!.textContent!.includes("Request timed out after 20 ms") + ); + } finally { + window.fetch = originalFetch; + } + }); }); diff --git a/packages/ecc-client-ga4gh-tes/src/providers/rest-tes-provider.ts b/packages/ecc-client-ga4gh-tes/src/providers/rest-tes-provider.ts index b9c276e8..9ffd7061 100644 --- a/packages/ecc-client-ga4gh-tes/src/providers/rest-tes-provider.ts +++ b/packages/ecc-client-ga4gh-tes/src/providers/rest-tes-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { TesProvider, ServiceInfo, @@ -17,17 +22,26 @@ import { export class RestTesProvider implements TesProvider { private baseUrl: string; - constructor(baseUrl: string) { + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the TES API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor(baseUrl: string, options: RestProviderOptions = {}) { this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl; + this.timeout = resolveRequestTimeout(options); } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } private static async handleResponse(response: Response): Promise { diff --git a/packages/ecc-client-ga4gh-tes/src/providers/tests/rest-tes-provider-timeout.test.ts b/packages/ecc-client-ga4gh-tes/src/providers/tests/rest-tes-provider-timeout.test.ts new file mode 100644 index 00000000..304e4351 --- /dev/null +++ b/packages/ecc-client-ga4gh-tes/src/providers/tests/rest-tes-provider-timeout.test.ts @@ -0,0 +1,96 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; +import { RestTesProvider } from "../rest-tes-provider.js"; + +const BASE_URL = "https://tes.example.org/ga4gh/tes/v1"; + +/** Provider that adds a bearer token to every request, as in the docs. */ +class TokenProvider extends RestTesProvider { + protected fetch(input: RequestInfo | URL, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("Authorization", "Bearer test-token"); + return super.fetch(input, { ...init, headers }); + } +} + +/** Provider methods, one of each kind of request. */ +const CALLS: [string, (p: RestTesProvider) => Promise][] = [ + ["listTasks", (p) => p.listTasks()], + ["cancelTask", (p) => p.cancelTask("task-1")], +]; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + +/** The error that a call rejects with. */ +const rejection = async (call: () => Promise): Promise => { + try { + await call(); + } catch (err) { + return err; + } + throw new Error("Expected the call to reject"); +}; + +describe("RestTesProvider request timeout", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("defaults to 30 s", () => { + expect(new RestTesProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect(() => new RestTesProvider(BASE_URL, { timeout: -1 })).to.throw( + RangeError + ); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + const provider = new RestTesProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => call(provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as Error).message).to.equal( + "Request timed out after 20 ms" + ); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + const provider = new TokenProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => CALLS[0][1](provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("{}", { status: 200 })); + + await CALLS[0][1](new RestTesProvider(BASE_URL, { timeout: 0 })); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); +}); diff --git a/packages/ecc-client-ga4gh-trs/src/components/tools/tests/tools.test.ts b/packages/ecc-client-ga4gh-trs/src/components/tools/tests/tools.test.ts index df6874a8..0998c0af 100644 --- a/packages/ecc-client-ga4gh-trs/src/components/tools/tests/tools.test.ts +++ b/packages/ecc-client-ga4gh-trs/src/components/tools/tests/tools.test.ts @@ -4,6 +4,13 @@ import sinon from "sinon"; import "../index.js"; import type { ECCClientGa4ghTrsTools } from "../tools.js"; import type { Tool, ToolClass, TrsProvider } from "../../../providers/index.js"; +import { RestTrsProvider } from "../../../providers/rest-trs-provider.js"; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); const BASE_URL = "https://trs.example.org/ga4gh/trs/v2"; const OTHER_URL = "https://other.example.org/ga4gh/trs/v2"; @@ -270,6 +277,23 @@ describe("ecc-client-ga4gh-trs-tools provider", () => { expect(reported).to.deep.equal([]); }); + it("shows the error of an expired request and reports no tools", async () => { + fetchStub.callsFake(neverAnswer); + const reported: Tool[][] = []; + const el = await fixture( + html` reported.push(e.detail.tools)} + >` + ); + + await waitUntil(() => + el.shadowRoot?.textContent?.includes("Request timed out after 20 ms") + ); + expect(internals(el).tools).to.deep.equal([]); + expect(reported).to.deep.equal([[]]); + }); + it("drops the tool class filter of a replaced provider", async () => { const first = stubProvider(); first.stubs.getToolClasses.resolves([{ id: "notebook", name: "Notebook" }]); diff --git a/packages/ecc-client-ga4gh-trs/src/providers/rest-trs-provider.ts b/packages/ecc-client-ga4gh-trs/src/providers/rest-trs-provider.ts index 9352b205..16ee3219 100644 --- a/packages/ecc-client-ga4gh-trs/src/providers/rest-trs-provider.ts +++ b/packages/ecc-client-ga4gh-trs/src/providers/rest-trs-provider.ts @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { TrsProvider, DescriptorType, @@ -13,16 +18,28 @@ import { * This class combines the functionality of TrsAPI and RestTrsProvider */ export class RestTrsProvider implements TrsProvider { - // eslint-disable-next-line no-useless-constructor - constructor(public readonly baseUrl: string) {} + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the TRS API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor( + public readonly baseUrl: string, + options: RestProviderOptions = {} + ) { + this.timeout = resolveRequestTimeout(options); + } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } async getToolClasses(): Promise { diff --git a/packages/ecc-client-ga4gh-trs/src/providers/tests/rest-trs-provider-timeout.test.ts b/packages/ecc-client-ga4gh-trs/src/providers/tests/rest-trs-provider-timeout.test.ts new file mode 100644 index 00000000..3e1879d6 --- /dev/null +++ b/packages/ecc-client-ga4gh-trs/src/providers/tests/rest-trs-provider-timeout.test.ts @@ -0,0 +1,95 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; +import { RestTrsProvider } from "../rest-trs-provider.js"; + +const BASE_URL = "https://trs.example.org/ga4gh/trs/v2"; + +/** Provider that adds a bearer token to every request, as in the docs. */ +class TokenProvider extends RestTrsProvider { + protected fetch(input: RequestInfo | URL, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("Authorization", "Bearer test-token"); + return super.fetch(input, { ...init, headers }); + } +} + +/** Provider methods, one of each kind of request. */ +const CALLS: [string, (p: RestTrsProvider) => Promise][] = [ + ["getToolClasses", (p) => p.getToolClasses()], +]; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + +/** The error that a call rejects with. */ +const rejection = async (call: () => Promise): Promise => { + try { + await call(); + } catch (err) { + return err; + } + throw new Error("Expected the call to reject"); +}; + +describe("RestTrsProvider request timeout", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("defaults to 30 s", () => { + expect(new RestTrsProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect(() => new RestTrsProvider(BASE_URL, { timeout: -1 })).to.throw( + RangeError + ); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + const provider = new RestTrsProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => call(provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as Error).message).to.equal( + "Request timed out after 20 ms" + ); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + const provider = new TokenProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => CALLS[0][1](provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("{}", { status: 200 })); + + await CALLS[0][1](new RestTrsProvider(BASE_URL, { timeout: 0 })); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); +}); 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..a3fc3614 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 @@ -1,3 +1,8 @@ +import { + fetchWithTimeout, + resolveRequestTimeout, +} from "@elixir-cloud/design/utils"; +import type { RestProviderOptions } from "@elixir-cloud/design/utils"; import { WesProvider, ServiceInfo, @@ -16,17 +21,26 @@ import { export class RestWesProvider implements WesProvider { protected baseUrl: string; - constructor(baseUrl: string) { + /** Deadline of each request in milliseconds, `0` for none. */ + public readonly timeout: number; + + /** + * @param baseUrl Base URL of the WES API + * @param options `timeout`: deadline of each request in milliseconds + * (default 30 s, `0` for none) + */ + constructor(baseUrl: string, options: RestProviderOptions = {}) { this.baseUrl = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl; + this.timeout = resolveRequestTimeout(options); } /** - * Sends every request of this provider. Override it in a subclass to add - * headers (e.g. `Authorization`) or otherwise change requests. + * Sends every request of this provider, with the provider's deadline. + * Override it in a subclass to add headers (e.g. `Authorization`) or + * otherwise change requests; call `super.fetch()` to keep the deadline. */ - // eslint-disable-next-line class-methods-use-this protected fetch(input: RequestInfo | URL, init?: RequestInit) { - return fetch(input, init); + return fetchWithTimeout(input, init, this.timeout); } private static async handleResponse(response: Response): Promise { diff --git a/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider-timeout.test.ts b/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider-timeout.test.ts new file mode 100644 index 00000000..32412174 --- /dev/null +++ b/packages/ecc-client-ga4gh-wes/src/providers/tests/rest-wes-provider-timeout.test.ts @@ -0,0 +1,96 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + RequestTimeoutError, +} from "@elixir-cloud/design/utils"; +import { RestWesProvider } from "../rest-wes-provider.js"; + +const BASE_URL = "https://wes.example.org/ga4gh/wes/v1"; + +/** Provider that adds a bearer token to every request, as in the docs. */ +class TokenProvider extends RestWesProvider { + protected fetch(input: RequestInfo | URL, init: RequestInit = {}) { + const headers = new Headers(init.headers); + headers.set("Authorization", "Bearer test-token"); + return super.fetch(input, { ...init, headers }); + } +} + +/** Provider methods, one of each kind of request. */ +const CALLS: [string, (p: RestWesProvider) => Promise][] = [ + ["getServiceInfo", (p) => p.getServiceInfo()], + ["getRunLog", (p) => p.getRunLog("run-1")], +]; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +const neverAnswer = (_input: RequestInfo | URL, init: RequestInit = {}) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); + +/** The error that a call rejects with. */ +const rejection = async (call: () => Promise): Promise => { + try { + await call(); + } catch (err) { + return err; + } + throw new Error("Expected the call to reject"); +}; + +describe("RestWesProvider request timeout", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("defaults to 30 s", () => { + expect(new RestWesProvider(BASE_URL).timeout).to.equal( + DEFAULT_REQUEST_TIMEOUT + ); + }); + + it("rejects an invalid timeout", () => { + expect(() => new RestWesProvider(BASE_URL, { timeout: -1 })).to.throw( + RangeError + ); + }); + + CALLS.forEach(([name, call]) => { + it(`${name} rejects when the server doesn't answer in time`, async () => { + const provider = new RestWesProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => call(provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as Error).message).to.equal( + "Request timed out after 20 ms" + ); + }); + }); + + it("keeps the timeout with an overridden fetch", async () => { + const provider = new TokenProvider(BASE_URL, { timeout: 20 }); + + const error = await rejection(() => CALLS[0][1](provider)); + + expect(error).to.be.instanceOf(RequestTimeoutError); + const headers = new Headers(fetchStub.firstCall.args[1]?.headers); + expect(headers.get("Authorization")).to.equal("Bearer test-token"); + }); + + it("sends requests without a deadline with a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("{}", { status: 200 })); + + await CALLS[0][1](new RestWesProvider(BASE_URL, { timeout: 0 })); + + expect(fetchStub.firstCall.args[1]?.signal).to.equal(undefined); + }); +}); diff --git a/packages/ecc-utils-design/src/utils/index.test.ts b/packages/ecc-utils-design/src/utils/index.test.ts index 5e3a85bf..7a2f32b3 100644 --- a/packages/ecc-utils-design/src/utils/index.test.ts +++ b/packages/ecc-utils-design/src/utils/index.test.ts @@ -12,6 +12,13 @@ describe("utils entry point", () => { expect(utils.normalizePointer).to.be.a("function"); }); + it("exports the request timeout utilities", () => { + expect(utils.fetchWithTimeout).to.be.a("function"); + expect(utils.resolveRequestTimeout).to.be.a("function"); + expect(utils.RequestTimeoutError).to.be.a("function"); + expect(utils.DEFAULT_REQUEST_TIMEOUT).to.equal(30_000); + }); + it("registers no components", () => { ["input", "checkbox", "code", "select"].forEach((name) => { expect(customElements.get(`ecc-utils-design-${name}`)).to.equal( diff --git a/packages/ecc-utils-design/src/utils/index.ts b/packages/ecc-utils-design/src/utils/index.ts index d508a2cc..372cf0a4 100644 --- a/packages/ecc-utils-design/src/utils/index.ts +++ b/packages/ecc-utils-design/src/utils/index.ts @@ -1 +1,2 @@ export * from "./problem-details.js"; +export * from "./request-timeout.js"; diff --git a/packages/ecc-utils-design/src/utils/request-timeout.test.ts b/packages/ecc-utils-design/src/utils/request-timeout.test.ts new file mode 100644 index 00000000..08d39a3c --- /dev/null +++ b/packages/ecc-utils-design/src/utils/request-timeout.test.ts @@ -0,0 +1,302 @@ +/* eslint-disable import/no-extraneous-dependencies */ +import { expect } from "@open-wc/testing"; +import sinon from "sinon"; +import { + DEFAULT_REQUEST_TIMEOUT, + MAX_REQUEST_TIMEOUT, + RequestTimeoutError, + fetchWithTimeout, + resolveRequestTimeout, +} from "./index.js"; + +/** A `fetch` that settles only when its signal aborts, like a silent server. */ +function neverAnswer(_input: RequestInfo | URL, init: RequestInit = {}) { + return new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => reject(init.signal?.reason)); + }); +} + +/** Resolves with the rejection reason of a promise, fails if it fulfils. */ +async function rejectionOf(promise: Promise): Promise { + try { + await promise; + } catch (error) { + return error; + } + throw new Error("Expected the promise to reject"); +} + +describe("resolveRequestTimeout()", () => { + it("defaults to 30 s", () => { + expect(DEFAULT_REQUEST_TIMEOUT).to.equal(30_000); + expect(resolveRequestTimeout()).to.equal(DEFAULT_REQUEST_TIMEOUT); + expect(resolveRequestTimeout({})).to.equal(DEFAULT_REQUEST_TIMEOUT); + }); + + it("returns a valid timeout as given", () => { + expect(resolveRequestTimeout({ timeout: 0 })).to.equal(0); + expect(resolveRequestTimeout({ timeout: 5000 })).to.equal(5000); + expect(resolveRequestTimeout({ timeout: MAX_REQUEST_TIMEOUT })).to.equal( + MAX_REQUEST_TIMEOUT + ); + }); + + [-1, 1.5, Number.NaN, Infinity, MAX_REQUEST_TIMEOUT + 1].forEach( + (timeout) => { + it(`rejects ${timeout}`, () => { + expect(() => resolveRequestTimeout({ timeout })).to.throw(RangeError); + }); + } + ); +}); + +describe("fetchWithTimeout()", () => { + let fetchStub: sinon.SinonStub; + + beforeEach(() => { + fetchStub = sinon.stub(window, "fetch").callsFake(neverAnswer); + }); + + afterEach(() => { + sinon.restore(); + }); + + it("passes the request and its options on", async () => { + fetchStub.callsFake(async () => new Response("ok")); + + const response = await fetchWithTimeout( + "https://api.example.org/things", + { method: "POST", headers: { "X-Test": "1" } }, + 1000 + ); + + expect(await response.text()).to.equal("ok"); + const [input, init] = fetchStub.firstCall.args; + expect(input).to.equal("https://api.example.org/things"); + expect(init.method).to.equal("POST"); + expect(init.headers).to.deep.equal({ "X-Test": "1" }); + expect(init.signal).to.be.instanceOf(AbortSignal); + }); + + it("rejects with a RequestTimeoutError once the deadline expires", async () => { + const error = await rejectionOf( + fetchWithTimeout("https://api.example.org/things", {}, 20) + ); + + expect(error).to.be.instanceOf(RequestTimeoutError); + expect((error as RequestTimeoutError).name).to.equal("RequestTimeoutError"); + expect((error as RequestTimeoutError).timeout).to.equal(20); + expect((error as Error).message).to.equal("Request timed out after 20 ms"); + }); + + it("keeps the deadline after the response arrived", async () => { + // `fetch` aborts reading the body with the reason of its signal + fetchStub.callsFake(async () => new Response("ok")); + + await fetchWithTimeout("https://api.example.org/things", {}, 20); + const { signal } = fetchStub.firstCall.args[1] as RequestInit; + expect(signal?.aborted).to.equal(false); + await new Promise((resolve) => { + signal?.addEventListener("abort", resolve); + }); + + expect(signal?.reason).to.be.instanceOf(RequestTimeoutError); + }); + + it("sets no deadline for a timeout of 0", async () => { + fetchStub.callsFake(async () => new Response("ok")); + + await fetchWithTimeout("https://api.example.org/things", {}, 0); + + expect(fetchStub.firstCall.args[1].signal).to.equal(undefined); + }); + + it("defaults to 30 s", async () => { + const clock = sinon.useFakeTimers({ toFake: ["setTimeout"] }); + const request = rejectionOf( + fetchWithTimeout("https://api.example.org/things") + ); + + clock.tick(DEFAULT_REQUEST_TIMEOUT - 1); + let settled = false; + request.then(() => { + settled = true; + }); + await Promise.resolve(); + expect(settled).to.equal(false); + + clock.tick(1); + expect(await request).to.be.instanceOf(RequestTimeoutError); + }); + + it("aborts with the reason of the caller's signal", async () => { + const caller = new AbortController(); + const request = rejectionOf( + fetchWithTimeout( + "https://api.example.org/things", + { signal: caller.signal }, + 1000 + ) + ); + + caller.abort(new Error("cancelled")); + + expect(((await request) as Error).message).to.equal("cancelled"); + }); + + it("aborts at once with a signal that is already aborted", async () => { + const caller = new AbortController(); + caller.abort(new Error("cancelled")); + fetchStub.callsFake(async (_input, init: RequestInit) => { + if (init.signal?.aborted) { + throw init.signal.reason; + } + return new Response("ok"); + }); + + const error = await rejectionOf( + fetchWithTimeout( + "https://api.example.org/things", + { signal: caller.signal }, + 1000 + ) + ); + + expect((error as Error).message).to.equal("cancelled"); + }); + + it("follows the signal of a Request", async () => { + const caller = new AbortController(); + const request = rejectionOf( + fetchWithTimeout( + new Request("https://api.example.org/things", { + signal: caller.signal, + }), + {}, + 1000 + ) + ); + + caller.abort(new Error("cancelled")); + + expect(((await request) as Error).message).to.equal("cancelled"); + }); + + it("rejects with the timeout error for a plain AbortError", async () => { + // Like fetch implementations that ignore the abort reason + fetchStub.callsFake( + (_input, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => + reject(new DOMException("Aborted", "AbortError")) + ); + }) + ); + + const error = await rejectionOf( + fetchWithTimeout("https://api.example.org/things", {}, 20) + ); + + expect(error).to.be.instanceOf(RequestTimeoutError); + }); + + it("rejects with the timeout error where signals drop the abort reason", async () => { + // Like browsers without abort reasons: `abort()` ignores its argument + const { abort } = AbortController.prototype; + sinon + .stub(AbortController.prototype, "abort") + .callsFake(function abortWithoutReason(this: AbortController) { + abort.call(this); + }); + fetchStub.callsFake( + (_input, init: RequestInit) => + new Promise((_resolve, reject) => { + init.signal?.addEventListener("abort", () => + reject(new DOMException("Aborted", "AbortError")) + ); + }) + ); + + const error = await rejectionOf( + fetchWithTimeout("https://api.example.org/things", {}, 20) + ); + + expect(error).to.be.instanceOf(RequestTimeoutError); + }); + + it("follows the signal of a Request-like input of another realm", async () => { + const caller = new AbortController(); + // Not an instance of this realm's Request, as from an iframe + const input = { + url: "https://api.example.org/things", + signal: caller.signal, + } as unknown as Request; + const request = rejectionOf(fetchWithTimeout(input, {}, 1000)); + + caller.abort(new Error("cancelled")); + + expect(((await request) as Error).message).to.equal("cancelled"); + }); + + it("ignores the signal of a Request for a signal of null", async () => { + const caller = new AbortController(); + caller.abort(new Error("cancelled")); + fetchStub.callsFake(async (_input, init: RequestInit) => { + if (init.signal?.aborted) { + throw init.signal.reason; + } + return new Response("ok"); + }); + + const response = await fetchWithTimeout( + new Request("https://api.example.org/things", { signal: caller.signal }), + { signal: null }, + 1000 + ); + + expect(await response.text()).to.equal("ok"); + }); + + it("releases the timer and the caller's signal when fetch fails", async () => { + const caller = new AbortController(); + const removed = sinon.spy(caller.signal, "removeEventListener"); + const cleared = sinon.spy(window, "clearTimeout"); + fetchStub.rejects(new TypeError("Failed to fetch")); + + await rejectionOf( + fetchWithTimeout( + "https://api.example.org/things", + { signal: caller.signal }, + 1000 + ) + ); + + expect(removed.calledWith("abort")).to.equal(true); + expect(cleared.called).to.equal(true); + }); + + it("passes other errors on", async () => { + fetchStub.rejects(new TypeError("Failed to fetch")); + + const error = await rejectionOf( + fetchWithTimeout("https://api.example.org/things", {}, 1000) + ); + + expect(error).to.be.instanceOf(TypeError); + }); + + it("stops following the caller's signal once the deadline expires", async () => { + const caller = new AbortController(); + const removed = sinon.spy(caller.signal, "removeEventListener"); + + await rejectionOf( + fetchWithTimeout( + "https://api.example.org/things", + { signal: caller.signal }, + 20 + ) + ); + + expect(removed.calledWith("abort")).to.equal(true); + }); +}); diff --git a/packages/ecc-utils-design/src/utils/request-timeout.ts b/packages/ecc-utils-design/src/utils/request-timeout.ts new file mode 100644 index 00000000..e7d0cc83 --- /dev/null +++ b/packages/ecc-utils-design/src/utils/request-timeout.ts @@ -0,0 +1,139 @@ +/** + * Request deadlines for the REST providers of the client packages, so that a + * request that never settles (e.g. to a server that accepts the connection + * but never answers) rejects, and components show their usual error instead + * of loading forever. + * + * The deadline covers the whole request: from sending it until its response + * body has been read (`response.json()` and the like reject too once it has + * expired, with the `RequestTimeoutError` in browsers that support abort + * reasons, else with an `AbortError`). + */ + +/** `AbortSignal` with its abort reason (newer than TypeScript 4.3's DOM). */ +interface AbortSignalWithReason extends AbortSignal { + readonly reason: unknown; +} + +/** `AbortController` that aborts with a reason. */ +interface AbortControllerWithReason extends AbortController { + readonly signal: AbortSignalWithReason; + abort(reason?: unknown): void; +} + +/** Default deadline of a request of the REST providers: 30 s. */ +export const DEFAULT_REQUEST_TIMEOUT = 30_000; + +/** + * Longest deadline that timers support (2^31 - 1 ms, about 24.8 days); + * longer ones would expire at once. + */ +export const MAX_REQUEST_TIMEOUT = 2_147_483_647; + +/** Options of the REST providers of the client packages. */ +export interface RestProviderOptions { + /** + * Deadline of each request in milliseconds, until its response body has + * been read; `0` for none. Defaults to `DEFAULT_REQUEST_TIMEOUT` (30 s). + */ + timeout?: number; +} + +/** Reason of a request that was aborted because its deadline expired. */ +export class RequestTimeoutError extends Error { + /** The deadline that expired, in milliseconds. */ + readonly timeout: number; + + constructor(timeout: number) { + super(`Request timed out after ${timeout} ms`); + this.name = "RequestTimeoutError"; + this.timeout = timeout; + } +} + +/** + * Returns the request deadline of the given provider options: the default if + * none is set, else the value. + * @param options Options of a REST provider + * @returns Deadline in milliseconds, `0` for none + * @throws {RangeError} If the timeout is not an integer from `0` to + * `MAX_REQUEST_TIMEOUT` + */ +export function resolveRequestTimeout( + options: RestProviderOptions = {} +): number { + const { timeout = DEFAULT_REQUEST_TIMEOUT } = options; + if ( + !Number.isInteger(timeout) || + timeout < 0 || + timeout > MAX_REQUEST_TIMEOUT + ) { + throw new RangeError( + `timeout must be an integer from 0 to ${MAX_REQUEST_TIMEOUT} (ms), got ${timeout}` + ); + } + return timeout; +} + +/** + * Sends a request with `fetch` that is aborted with a `RequestTimeoutError` + * once the deadline expires. A `signal` of the request still aborts it, with + * its own reason. + * @param input Resource to fetch + * @param init Options of the request + * @param timeout Deadline in milliseconds (as by `resolveRequestTimeout()`), + * `0` for none + * @returns The response, as from `fetch` + */ +export function fetchWithTimeout( + input: RequestInfo | URL, + init: RequestInit = {}, + timeout: number = DEFAULT_REQUEST_TIMEOUT +): Promise { + // Typed for the DOM library of TypeScript 4.3, which the packages build + // with: it lacks `URL` inputs, `abort(reason)` and `signal.reason` + const request = input as RequestInfo; + if (timeout === 0) { + return fetch(request, init); + } + const controller = new AbortController() as AbortControllerWithReason; + // As in `fetch`, a `signal` in `init` (even `null`) replaces the one of a + // `Request`; read without `instanceof`, which misses other realms' requests + const requestSignal = + typeof input === "object" && "signal" in input ? input.signal : undefined; + const signal = ("signal" in init ? init.signal : requestSignal) as + | AbortSignalWithReason + | null + | undefined; + // Kept here too, as browsers without abort reasons drop it from the signal + let timeoutError: RequestTimeoutError | undefined; + // Deliberately not cleared when the response arrives, so that the + // deadline also covers reading the body; aborting afterwards is a no-op + const timer = setTimeout(() => { + signal?.removeEventListener("abort", followSignal); + timeoutError = new RequestTimeoutError(timeout); + controller.abort(timeoutError); + }, timeout); + // Don't keep Node processes (SSR, tests) alive for the deadline; the cast + // is for Node's timer object (in browsers, timers are numbers) + (timer as { unref?: () => void }).unref?.(); + function followSignal() { + clearTimeout(timer); + controller.abort(signal?.reason); + } + if (signal?.aborted) { + followSignal(); + } else { + signal?.addEventListener("abort", followSignal, { once: true }); + } + return fetch(request, { ...init, signal: controller.signal }).catch( + (error: unknown) => { + // The request is over: release the timer and the caller's signal + clearTimeout(timer); + signal?.removeEventListener("abort", followSignal); + // Fetch implementations that reject with a plain `AbortError` + // instead of the abort reason still reject with the timeout error + throw timeoutError ?? error; + } + ); +} diff --git a/scripts/check-design-utils.mjs b/scripts/check-design-utils.mjs index c4d276b1..72ca9378 100644 --- a/scripts/check-design-utils.mjs +++ b/scripts/check-design-utils.mjs @@ -6,10 +6,13 @@ const utils = await import("@elixir-cloud/design/utils"); const expected = [ + "RequestTimeoutError", + "fetchWithTimeout", "mapFieldErrors", "normalizePointer", "parseProblemDetails", "readProblemDetails", + "resolveRequestTimeout", ]; const missing = expected.filter((name) => typeof utils[name] !== "function"); if (missing.length > 0) {