Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/cloud-registry-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/design-request-timeout.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@elixir-cloud/design": minor
---

Add `fetchWithTimeout()`, `RequestTimeoutError` and the other request timeout utilities to `@elixir-cloud/design/utils`.
5 changes: 5 additions & 0 deletions .changeset/drs-filer-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/drs-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/service-registry-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/tes-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/trs-filer-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/trs-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
5 changes: 5 additions & 0 deletions .changeset/wes-request-timeout.md
Original file line number Diff line number Diff line change
@@ -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).
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion apps/documentation/pages/docs/design/_meta.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,5 +2,6 @@
"introduction": "Introduction",
"architecture": "Architecture",
"components": "Components",
"field-errors": "Field errors"
"field-errors": "Field errors",
"request-timeouts": "Request timeouts"
}
58 changes: 58 additions & 0 deletions apps/documentation/pages/docs/design/request-timeouts.mdx
Original file line number Diff line number Diff line change
@@ -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.

<Callout type='warning'>
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.
</Callout>

## 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
}
}
```
26 changes: 26 additions & 0 deletions apps/documentation/pages/docs/providers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -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)));
Expand All @@ -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
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion apps/documentation/pages/docs/tes/providers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion apps/documentation/pages/docs/trs-filer/providers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion apps/documentation/pages/docs/trs/providers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
3 changes: 2 additions & 1 deletion apps/documentation/pages/docs/wes/providers.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Original file line number Diff line number Diff line change
@@ -1,3 +1,8 @@
import {
fetchWithTimeout,
resolveRequestTimeout,
} from "@elixir-cloud/design/utils";
import type { RestProviderOptions } from "@elixir-cloud/design/utils";
import {
CloudRegistryProvider,
ExternalService,
Expand All @@ -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);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -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<unknown>][] = [
["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<Response>((_resolve, reject) => {
init.signal?.addEventListener("abort", () => reject(init.signal?.reason));
});

/** The error that a call rejects with. */
const rejection = async (call: () => Promise<unknown>): Promise<unknown> => {
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);
});
});
Loading
Loading