Skip to content
Merged
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
54 changes: 52 additions & 2 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,13 +1,63 @@
# Changelog

## Unreleased
## 1.0.0-alpha.10

### Breaking (for a consumer with its own `Transport`)

- **`timeoutMs` is the client's rule with any transport.** It was a timer
inside the built-in fetch transport only; with a custom transport the
client timed nothing, and a transport's own timeout was resent only if
it happened to report itself as an `ApiError` coded `TIMEOUT`. Now each
attempt has `timeoutMs` (default 60000) whatever the transport: at the
deadline the request rejects with `TIMEOUT` (transient, so an
idempotent request is sent once more), whether or not the transport
lets go. The transport is handed a `signal` that fires at the deadline
and when the caller aborts; honouring `signal`, which the conformance
suite already checks, is all a transport owes. A request the client has
stopped waiting for is abandoned: what its transport answers or throws
later is discarded. A timed-out write may still have been applied, and
is not resent.
What changes for you: requests through your transport now time out at
60 seconds by default where they waited for your HTTP client alone. A
transport with a shorter timeout of its own is unaffected (it rejects
first, with its own error). A transport over an HTTP client with no
timeout configured, or with a longer one, such as an axios instance
left at its default of none, now gets one. Migration: nothing, if 60
seconds per attempt suits you; `timeoutMs: <ms>` on the client to
choose; `timeoutMs: 0` for no client timeout, leaving your transport
to decide. **Set `timeoutMs: 0` if your transport waits for a person
inside `request`** (an HTTP client that shows a sign-in prompt and
replays the request when the user is back): the deadline cannot tell
that from a slow network, and the replay would carry a signal that has
already fired. The built-in transport's `onUnauthorized` hook runs
outside the deadline. The signal your transport receives is now the attempt's own
and not the object the caller passed, so compare by `aborted`, not by
identity. Code in a transport that maps its client's timeout error to
`TIMEOUT` is no longer needed for resends. (a browser-app consumer.)

Nothing in the package changes.
### Changed

- The built-in fetch transport uses the same deadline: `timeoutMs: 0`
now means no timeout there too, and a response whose headers arrive in
time but whose body does not is a `TIMEOUT` (it surfaced as the
runtime's own abort error).

### Fixed

- `FakeAgilityClient`: a search naming a family by its abstract type
(`types: ["Workitem"]`) is expanded to the concrete types in the
request the fake records, as against a server. Without a metamodel the
fake treated the family as one concrete type. Rows and `fake.searched`
were already right.

### Repository

- `examples/11-axios-transport.ts`: a `Transport` over an axios instance
and the adapter that runs `transportConformance` against it. axios is a
dev dependency of the repository for that example alone; the package
still depends on nothing. (a browser-app consumer.)
With this release it leaves timing to the client: it no longer maps
axios's own timeout to `TIMEOUT`.

## 1.0.0-alpha.9

Expand Down
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,7 @@ Changes between alphas are in `CHANGELOG.md`, each with its migration line.
- Errors: everything thrown is an `ApiError` with a `kind` (`auth`, `forbidden`, `notFound`, `invalid`, `transient`, `aborted`, `commandFailure`, `conflict`, `protocol`, `usage`, `unknown`). A mistake caught before any request is a `UsageError`: `kind: "usage"` means nothing was sent (`status` is 0), so the fix is in the call, not on the server
- `TypeCache` - one instance's loaded type definitions, shared by many clients (`new AgilityApiClient(config, { types })`); `TypeCache.fromMetamodel(metamodel)` seeds one so nothing is loaded
- `createFetchTransport` - configurable HTTP transport: `credentials` for same-origin cookie auth, `onUnauthorized` to re-authenticate on a 401 (resends idempotent requests once), and a per-request `signal`; `client.withSignal(signal)` ties a whole client to one
- **Timeouts are the client's business with any transport**: each attempt has `timeoutMs` (default 60000; 0 for none), and at the deadline the request rejects with an `ApiError` coded `TIMEOUT`, whether or not a custom transport lets go of it (the transport is handed a `signal` that fires then; a late answer is discarded). A timed-out write may still have been applied. A custom transport that waits for a person inside `request` (a sign-in prompt before it replays the request) sets `timeoutMs: 0`: the deadline cannot tell a person from a slow network. The built-in transport's `onUnauthorized` hook runs outside the deadline
- Resends and failures are the client's business with any transport: an idempotent request (a GET, a read, a guarded batch with no creates) is sent once more after a network failure, a timeout, a 5xx or a 429 (`retries`, default 1, 0 for none; never a plain write, a 401 or a 403), and `onError(error, request)` in the config is told about each request that finally failed
- A custom `Transport` (`new AgilityApiClient(config, { transport })`) decides by itself where requests go; `config.baseUrl` is then used only for the links the client builds (`urls.*`, `embeddedImages.normalize`). `apiErrorFromResponse(status, data)` is the error the fetch transport throws for a refused response, for a custom transport to throw the same
- `@versionone/agility-sdk/services` - the services as free functions over a `Transport` (`guard`, `batch`, `resolve`, `schema`, `attachments`, `fields`), for a caller that composes one differently; the client's methods are the same things
Expand Down
10 changes: 3 additions & 7 deletions examples/11-axios-transport.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,13 +67,9 @@ export function createAxiosTransport(http: AxiosInstance): Transport {
// A refusal: the same error, word for word, as the SDK's own transport throws.
throw apiErrorFromResponse(error.response.status, readable(error.response.data, String(error.response.headers["content-type"] ?? "")));
}
// Timing is this transport's own business today: the client's `timeoutMs` binds only the SDK's built-in
// transport, so the axios instance needs its own `timeout`, and its timeout must be reported as TIMEOUT
// here for the client's resend rule to recognise it. Were the client to enforce `timeoutMs` above every
// transport (it would hand over a signal that fires when time is up), neither would be needed: honouring
// `signal`, as above, would be all a transport owes, and these two lines could go.
const timedOut = error instanceof AxiosError && (error.code === AxiosError.ECONNABORTED || error.code === AxiosError.ETIMEDOUT);
throw new ApiError(error instanceof Error ? error.message : String(error), 0, timedOut ? "TIMEOUT" : "NETWORK_ERROR", { cause: error });
// No answer at all. Timing is the client's business, not this transport's: the client's `timeoutMs` hands
// over a `signal` that fires at the deadline, and honouring it (above) is all a transport owes.
throw new ApiError(error instanceof Error ? error.message : String(error), 0, "NETWORK_ERROR", { cause: error });
}
const headers = AxiosHeaders.from(response.headers as RawAxiosHeaders);
options.onResponse?.({ status: response.status, headers: { get: (name) => { const value = headers.get(name); return value == null ? null : String(value); } } });
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@versionone/agility-sdk",
"version": "1.0.0-alpha.9",
"version": "1.0.0-alpha.10",
"description": "TypeScript SDK for the Digital.ai Agility (VersionOne) API: queries, batches, schema-translated rows, guarded writes, attachments",
"keywords": [
"agility",
Expand Down
14 changes: 14 additions & 0 deletions specs/000-layers.md
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,20 @@ custom Transport (`core/retry`), so a consumer's transport does not
re-implement it and cannot forget it. `retries: 0` turns it off for a
client. A 401 or 403 is never resent by it.

So is the timeout. Each attempt has `timeoutMs` (60 s unless told; 0 for
none), and when it has passed the request rejects with `TIMEOUT`, a
transient failure. The client enforces this above a custom transport: it
hands the transport a signal that fires at the deadline, and it stops
waiting at the deadline whether or not the transport lets go. What an
abandoned request answers later is discarded. A transport therefore owes
nothing about timing beyond honouring `signal`, which the conformance
suite checks; one with a shorter timeout of its own simply rejects first.
A timeout says the client stopped waiting, never that the server did not
act, which is one more reason a write is not resent. The deadline cannot
tell the network from a person: a custom transport that waits for someone
inside `request` turns the client's timeout off (`timeoutMs: 0`), and the
built-in transport's re-authentication hook runs outside the deadline.

Re-authentication follows the same rule. On a 401 (or a status the caller
lists) the transport calls `onUnauthorized` once per request; "retry" resends
an idempotent request one more time, outside the `retries` count. A plain
Expand Down
9 changes: 5 additions & 4 deletions src/client.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import type { ClientConfig } from "./core/clientConfig";
import { ApiError, UsageError } from "./core/errors";
import { createFetchTransport } from "./core/fetchTransport";
import { withErrorHook, withRetry } from "./core/retry";
import { withErrorHook, DEFAULT_TIMEOUT_MS, withRetry, withTimeout } from "./core/retry";
import type { Transport } from "./core/transport";
import * as attachments from "./services/attachments";
import * as batch from "./services/batch";
Expand Down Expand Up @@ -107,8 +107,8 @@ export class AgilityApiClient {
readonly schema: Schema;

constructor(config: ClientConfig, opts: ClientOptions = {}) {
// The built-in transport resends idempotent requests itself (it can read Retry-After); a custom one gets the
// same rule from the client. A transport another client of ours already dressed (withSignal) is taken as it is.
// The built-in transport times its attempts and resends idempotent requests itself (it can read Retry-After); a
// custom one gets the same two rules from the client. A transport another client of ours already dressed (withSignal) is taken as it is.
let transport = opts.transport ?? createFetchTransport({
baseUrl: config.baseUrl,
authorization: config.authorization,
Expand All @@ -121,7 +121,8 @@ export class AgilityApiClient {
unauthorizedStatuses: config.unauthorizedStatuses
});
if (!dressed.has(transport)) {
if (opts.transport) transport = withRetry(transport, config.retries ?? 1);
// A custom transport: each attempt under the client's deadline, and the resend rule around that.
if (opts.transport) transport = withRetry(withTimeout(transport, config.timeoutMs ?? DEFAULT_TIMEOUT_MS), config.retries ?? 1);
if (config.onError) transport = withErrorHook(transport, config.onError);
dressed.add(transport);
}
Expand Down
20 changes: 19 additions & 1 deletion src/core/clientConfig.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,25 @@ export interface ClientConfig extends Pick<FetchTransportConfig, "credentials" |
authorization?: string;
/** An access token, sent as "Bearer <token>". */
accessToken?: string;
/** Per-attempt timeout of the built-in fetch transport. A custom Transport does its own timing. */
/**
* How long one attempt may take, in milliseconds, whichever Transport
* the client has. Default 60000. When it has passed, the request
* rejects with an ApiError coded TIMEOUT (transient: an idempotent
* request is then sent again, see `retries`). The client stops waiting
* at the deadline whether or not a custom transport lets go of the
* request: the transport is given a `signal` that fires then, and
* whatever it answers afterwards is discarded. A timed-out write may
* still have been applied. 0 means no timeout of the client's (a custom
* transport's own timing then decides; one with a shorter timeout
* always wins anyway).
*
* The deadline cannot tell waiting on the network from waiting on a
* person. A custom transport that waits for someone inside `request` (a
* sign-in popup, a "log in again" prompt its HTTP client shows before
* replaying the request) must set `timeoutMs: 0`, or the person's time
* counts and a slow sign-in ends as TIMEOUT. The built-in transport has
* no such problem: its `onUnauthorized` hook runs outside the deadline.
*/
timeoutMs?: number;
/**
* How many times an idempotent request (a GET, a query.v1 read, a
Expand Down
21 changes: 10 additions & 11 deletions src/core/fetchTransport.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { ApiError, apiErrorFromResponse } from "./errors";
import { DEFAULT_TIMEOUT_MS, deadline } from "./retry";
import type { RequestBody, RequestOptions, ResponseType, Transport } from "./transport";

/**
Expand Down Expand Up @@ -163,7 +164,7 @@ function retryDelay(response: { status: number; headers: { get(name: string): st
const retriable = (status: number): boolean => status === 429 || status >= 500;

export function createFetchTransport(config: FetchTransportConfig): Transport {
const timeoutMs = config.timeoutMs ?? 60_000;
const timeoutMs = config.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const retries = Math.max(0, config.retries ?? 1);
const authorization = config.authorization ?? (config.accessToken ? `Bearer ${config.accessToken}` : undefined);
const unauthorizedStatuses = config.unauthorizedStatuses ?? [401];
Expand All @@ -186,17 +187,13 @@ export function createFetchTransport(config: FetchTransportConfig): Transport {
let reauthorized = false;
for (let attempt = 0; attempt < attempts; attempt += 1) {
if (callerSignal?.aborted) throw abortedError(callerSignal);
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), timeoutMs);
const onAbort = () => controller.abort();
callerSignal?.addEventListener("abort", onAbort, { once: true });
const settle = () => {
clearTimeout(timeoutId);
callerSignal?.removeEventListener("abort", onAbort);
};
// The one timeout rule (core/retry.ts): this attempt's deadline, or the caller's abort, whichever is first.
// fetch lets go when its signal fires, so nothing more is needed here than to say which of the two it was.
const limit = deadline(timeoutMs, callerSignal);
const settle = limit.clear;
let response: Response;
try {
const init: RequestInit = { method: options.method, headers, body, signal: controller.signal };
const init: RequestInit = { method: options.method, headers, body, signal: limit.signal };
if (config.credentials) init.credentials = config.credentials;
// Looked up at each request, not when the transport was made: whatever replaces the global fetch later (a test's stub, an instrumented fetch) is what gets called.
response = await (config.fetchImpl ?? globalThis.fetch)(url, init);
Expand All @@ -205,7 +202,7 @@ export function createFetchTransport(config: FetchTransportConfig): Transport {
// The caller gave up: final, whatever attempt this was.
if (callerSignal?.aborted) throw abortedError(callerSignal);
// Network failure or timeout: the only case a retry can help.
lastError = error instanceof Error && error.name === "AbortError"
lastError = limit.expired()
? new ApiError(`Timed out after ${timeoutMs} ms`, 0, "TIMEOUT", { cause: error })
: new ApiError(error instanceof Error ? error.message : String(error), 0, "NETWORK_ERROR", { cause: error });
if (attempt + 1 < attempts) await delay(150 * (attempt + 1));
Expand All @@ -229,6 +226,8 @@ export function createFetchTransport(config: FetchTransportConfig): Transport {
lastError = apiErrorFromResponse(response.status, data);
} catch (error) {
if (callerSignal?.aborted) throw abortedError(callerSignal);
// The deadline passed while the body was still arriving: a timeout like any other.
if (limit.expired()) throw new ApiError(`Timed out after ${timeoutMs} ms`, 0, "TIMEOUT", { cause: error });
throw error;
} finally {
settle();
Expand Down
Loading