diff --git a/CHANGELOG.md b/CHANGELOG.md index 24197ca..8d6042d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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: ` 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 diff --git a/README.md b/README.md index b75f181..312ebae 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/examples/11-axios-transport.ts b/examples/11-axios-transport.ts index 2cd27db..7922f24 100644 --- a/examples/11-axios-transport.ts +++ b/examples/11-axios-transport.ts @@ -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); } } }); diff --git a/package-lock.json b/package-lock.json index d0ce167..bb6f975 100644 --- a/package-lock.json +++ b/package-lock.json @@ -1,12 +1,12 @@ { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.9", + "version": "1.0.0-alpha.10", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "@versionone/agility-sdk", - "version": "1.0.0-alpha.9", + "version": "1.0.0-alpha.10", "license": "MIT", "devDependencies": { "@types/node": "^22.13.10", diff --git a/package.json b/package.json index df58336..85cbfc0 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/specs/000-layers.md b/specs/000-layers.md index 21ce003..872655d 100644 --- a/specs/000-layers.md +++ b/specs/000-layers.md @@ -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 diff --git a/src/client.ts b/src/client.ts index 7dd0488..eeea227 100644 --- a/src/client.ts +++ b/src/client.ts @@ -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"; @@ -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, @@ -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); } diff --git a/src/core/clientConfig.ts b/src/core/clientConfig.ts index 131ab47..6334b6c 100644 --- a/src/core/clientConfig.ts +++ b/src/core/clientConfig.ts @@ -17,7 +17,25 @@ export interface ClientConfig extends Pick". */ 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 diff --git a/src/core/fetchTransport.ts b/src/core/fetchTransport.ts index 168b461..e7cbf8d 100644 --- a/src/core/fetchTransport.ts +++ b/src/core/fetchTransport.ts @@ -1,4 +1,5 @@ import { ApiError, apiErrorFromResponse } from "./errors"; +import { DEFAULT_TIMEOUT_MS, deadline } from "./retry"; import type { RequestBody, RequestOptions, ResponseType, Transport } from "./transport"; /** @@ -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]; @@ -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); @@ -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)); @@ -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(); diff --git a/src/core/retry.ts b/src/core/retry.ts index 7ea7ca1..7562cac 100644 --- a/src/core/retry.ts +++ b/src/core/retry.ts @@ -3,6 +3,78 @@ import type { RequestOptions, Transport } from "./transport"; const delay = (ms: number): Promise => new Promise((resolve) => setTimeout(resolve, ms)); +/** How long one attempt may take when the client is not told otherwise. */ +export const DEFAULT_TIMEOUT_MS = 60_000; + +const timedOut = (ms: number): ApiError => new ApiError(`Timed out after ${ms} ms`, 0, "TIMEOUT"); +const abortedBy = (signal: AbortSignal): ApiError => new ApiError("Request aborted", 0, "ABORTED", { cause: signal.reason }); + +/** + * One attempt's deadline: a signal that fires when the caller aborts or + * when `timeoutMs` has passed, whichever is first, and which of the two + * it was. `timeoutMs` of 0 (or less) is no deadline: the signal is then + * the caller's own. Call `clear` when the attempt has settled. + */ +export function deadline(timeoutMs: number, caller?: AbortSignal): { signal: AbortSignal | undefined; expired: () => boolean; onExpire: (run: () => void) => void; clear: () => void } { + if (!(timeoutMs > 0)) return { signal: caller, expired: () => false, onExpire: () => {}, clear: () => {} }; + const controller = new AbortController(); + let expired = false; + let listener: (() => void) | undefined; + const timer = setTimeout(() => { expired = true; listener?.(); controller.abort(timedOut(timeoutMs)); }, timeoutMs); + const onAbort = () => controller.abort(caller!.reason); + if (caller?.aborted) onAbort(); else caller?.addEventListener("abort", onAbort, { once: true }); + return { + signal: controller.signal, + expired: () => expired, + onExpire: (run) => { listener = run; }, + clear: () => { clearTimeout(timer); caller?.removeEventListener("abort", onAbort); } + }; +} + +/** + * The timeout rule, for any Transport: each attempt gets `timeoutMs`, and + * when it has passed the request rejects with an ApiError coded TIMEOUT + * (a transient failure, so the resend rule sends an idempotent request + * again). `timeoutMs` of 0 means no timeout of the client's: the transport + * alone decides. + * + * The transport is handed a `signal` that fires at the deadline (and when + * the caller aborts), and honouring `signal` is all a transport owes. But + * the caller is not left to depend on that: the request rejects AT the + * deadline whether or not the transport lets go. A transport that ignores + * the signal keeps its request open on its own; whatever it answers later + * is discarded, and an error it throws later is swallowed. So TIMEOUT + * means "the client stopped waiting", never "the server did not act": a + * write that timed out may still have been applied, which is why a write + * is not resent. + * + * A transport with a shorter timeout of its own rejects first, and its + * error is the one the caller sees. A caller's abort is ABORTED, not + * TIMEOUT, and is likewise not waited on. + */ +export function withTimeout(transport: Transport, timeoutMs: number): Transport { + if (!(timeoutMs > 0)) return transport; + return { + request(options: RequestOptions): Promise { + const caller = options.signal; + if (caller?.aborted) return Promise.reject(abortedBy(caller)); + const limit = deadline(timeoutMs, caller); + return new Promise((resolve, reject) => { + const onCallerAbort = () => reject(abortedBy(caller!)); + caller?.addEventListener("abort", onCallerAbort, { once: true }); + const settle = () => { limit.clear(); caller?.removeEventListener("abort", onCallerAbort); }; + // Rejected here, at the deadline, before the signal is even seen by the transport. + limit.onExpire(() => { settle(); reject(timedOut(timeoutMs)); }); + // After a rejection above these are no-ops: a late answer is ignored and a late error does not surface. + transport.request({ ...options, signal: limit.signal }).then( + (value) => { settle(); resolve(value); }, + (error: unknown) => { settle(); reject(error); } + ); + }); + } + }; +} + /** * The resend rule, for any Transport: an idempotent request (a GET, or one * the caller marked — a query.v1 read, a guarded batch with no creates) @@ -13,10 +85,11 @@ const delay = (ms: number): Promise => new Promise((resolve) => setTimeout * resend would prompt twice); not any other 4xx, which is an answer; not a * request its caller aborted. * - * The client puts this around a custom Transport, so the rule is the - * client's and not each transport's to re-implement. The built-in fetch - * transport applies the same rule itself (it can also read Retry-After) - * and is not wrapped again. + * The client puts this around a custom Transport (outside the timeout + * rule, so each attempt has its own deadline), so the rule is the client's + * and not each transport's to re-implement. The built-in fetch transport + * applies the same rule itself (it can also read Retry-After) and is not + * wrapped again. */ export function withRetry(transport: Transport, retries: number): Transport { const extra = Math.max(0, retries); diff --git a/src/testing/index.ts b/src/testing/index.ts index 764eede..ec1a508 100644 --- a/src/testing/index.ts +++ b/src/testing/index.ts @@ -19,7 +19,7 @@ export { CONFORMANCE_BASE_URL, fetchFrom, transportConformance } from "./transpo export type { ConformanceCheck, ConformanceRequest, ConformanceResponse, ConformanceServer } from "./transportConformance"; import type { ClientConfig } from "../core/clientConfig"; import type { SearchOptions, SearchResult, SearchRow } from "../services/search"; -import { ATTRIBUTE_NAMES } from "../types/assets/subtypes"; +import { ATTRIBUTE_NAMES, CONCRETE_SUBTYPES } from "../types/assets/subtypes"; import { ApiError, UsageError, apiErrorFromResponse } from "../core/errors"; import type { RequestOptions, Transport } from "../core/transport"; import type { Asset, Oid } from "../types/asset"; @@ -183,7 +183,8 @@ function anyType(script: Script, token: string): unknown { const root = ["Name", "Description", "AssetType", "AssetState", "ChangeDateUTC", "CreateDateUTC"]; const names = token === "BaseAsset" ? root : [...new Set([...ATTRIBUTE_NAMES, ...scripted.map((key) => key.split(".")[0]!)])].filter((name) => name !== "_oid"); const Attributes = Object.fromEntries(names.map((Name) => [`${token}.${Name}`, { _type: "AttributeDefinition", Name, Token: `${token}.${Name}`, DisplayName: Name, AttributeType: "Text", IsReadOnly: false, IsRequired: false, IsMultivalue: false, IsCanned: true, IsCustom: false }])); - return { _type: "AssetType", Name: token, Token: token, DisplayName: token, Abstract: token === "BaseAsset", ...(token === "BaseAsset" ? {} : { Base: { nameref: "BaseAsset", href: "/meta.v1/BaseAsset" } }), Attributes }; + // A family the generated table knows (Workitem) is abstract here as on a server, so a search naming it expands to its subtypes. + return { _type: "AssetType", Name: token, Token: token, DisplayName: token, Abstract: token === "BaseAsset" || token in CONCRETE_SUBTYPES, ...(token === "BaseAsset" ? {} : { Base: { nameref: "BaseAsset", href: "/meta.v1/BaseAsset" } }), Attributes }; } function respond(script: Script, request: RequestOptions): unknown { diff --git a/test/unit/search.test.ts b/test/unit/search.test.ts index fbb7755..906a3b4 100644 --- a/test/unit/search.test.ts +++ b/test/unit/search.test.ts @@ -165,6 +165,13 @@ describe("FakeAgilityClient: search", () => { expect(fake.requests[0]!.query).toMatchObject({ find: "printer queue", where: "AssetType='Story','Request','Issue','Test';AssetState!='Closed'" }); }); + it("a family named by its abstract type is expanded on the fake as on a server: the request names the concrete types, and `searched` keeps what the caller wrote", async () => { + const fake = new FakeAgilityClient().onSearch(scripted); + await fake.search("printer", { types: ["Workitem", "Request"], page }); + expect(fake.requests.at(-1)!.query).toMatchObject({ where: "AssetType='Defect','Epic','Story','Task','Test','TestSet','Theme','Request'" }); + expect(fake.searched.at(-1)!.options.types).toEqual(["Workitem", "Request"]); + }); + it("an unscripted search throws, and so do the mistakes the client refuses; a function answers a page, an Error is thrown", async () => { const fake = new FakeAgilityClient(); await expect(fake.search("printer", { types: ["Story"], page })).rejects.toThrow(/no answer scripted for search\("printer"\)/); diff --git a/test/unit/timeout.test.ts b/test/unit/timeout.test.ts new file mode 100644 index 0000000..0008446 --- /dev/null +++ b/test/unit/timeout.test.ts @@ -0,0 +1,131 @@ +import { describe, expect, it } from "vitest"; +import { AgilityApiClient } from "../../src/client"; +import { ApiError } from "../../src/core/errors"; +import { createFetchTransport } from "../../src/core/fetchTransport"; +import type { RequestOptions, Transport } from "../../src/core/transport"; + +/** + * The timeout rule belongs to the client, so `timeoutMs` means the same + * with a consumer's own Transport: each attempt has that long, the caller + * gets TIMEOUT at the deadline whatever the transport does, and the resend + * rule sees it as the transient failure it is. Real (short) timers: the + * point is what happens at a deadline. + */ +const later = (ms: number, value: T): Promise => new Promise((resolve) => setTimeout(() => resolve(value), ms)); +const aborted = (signal: AbortSignal) => new ApiError("Request aborted", 0, "ABORTED", { cause: signal.reason }); + +/** A transport as a well-behaved one is: `attempt` decides how long each try takes, and its signal ends the wait. */ +function honouring(attempt: (n: number, o: RequestOptions) => Promise): Transport & { calls: RequestOptions[] } { + const calls: RequestOptions[] = []; + return { + calls, + request: ((o: RequestOptions) => { + calls.push(o); + return new Promise((resolve, reject) => { + o.signal?.addEventListener("abort", () => reject(aborted(o.signal!)), { once: true }); + attempt(calls.length, o).then(resolve as (value: unknown) => void, reject); + }); + }) as Transport["request"] + }; +} +const never = new Promise(() => {}); +const clientOn = (transport: Transport, config: { timeoutMs?: number; retries?: number } = {}) => new AgilityApiClient({ baseUrl: "https://agility.example.com/I", ...config }, { transport }).transport; +const read: RequestOptions = { method: "GET", path: "/loc-2.v1" }; +const write: RequestOptions = { method: "POST", path: "/api/asset", body: [{ from: "Story:1", update: { Name: "x" } }] }; + +describe("the timeout rule above a custom Transport", () => { + it("an attempt that takes longer than timeoutMs is a TIMEOUT, and an idempotent request is then sent once more, with a deadline of its own", async () => { + const t = honouring((n) => (n === 1 ? never : later(5, { ok: true }))); + expect(await clientOn(t, { timeoutMs: 30 }).request(read)).toEqual({ ok: true }); + expect(t.calls).toHaveLength(2); + // The first attempt was told to stop; the second got a fresh signal. + expect([t.calls[0]!.signal!.aborted, t.calls[1]!.signal!.aborted]).toEqual([true, false]); + // Every attempt slow: the caller gets the TIMEOUT, a transient failure, after the one resend. + const slow = honouring(() => never); + await expect(clientOn(slow, { timeoutMs: 20 }).request(read)).rejects.toMatchObject({ code: "TIMEOUT", status: 0, kind: "transient", message: "Timed out after 20 ms" }); + expect(slow.calls).toHaveLength(2); + }); + + it("a plain write that times out is not sent again: the client stopped waiting, which says nothing about whether the server acted", async () => { + const t = honouring(() => never); + await expect(clientOn(t, { timeoutMs: 20, retries: 3 }).request(write)).rejects.toMatchObject({ code: "TIMEOUT", kind: "transient" }); + expect(t.calls).toHaveLength(1); + }); + + it("a transport that ignores the signal still yields TIMEOUT at the deadline; what it answers or throws afterwards is discarded", async () => { + const unhandled: unknown[] = []; + const onUnhandled = (reason: unknown) => unhandled.push(reason); + process.on("unhandledRejection", onUnhandled); + try { + // Deaf to its signal: one answers late, one fails late. + for (const afterwards of [() => later(60, { late: true }), () => later(60, null).then(() => { throw new ApiError("socket hang up", 0, "NETWORK_ERROR"); })]) { + const calls: RequestOptions[] = []; + const deaf: Transport = { request: ((o: RequestOptions) => { calls.push(o); return afterwards(); }) as Transport["request"] }; + const started = Date.now(); + const error = await clientOn(deaf, { timeoutMs: 20, retries: 0 }).request(write).catch((e: unknown) => e); + expect(error).toMatchObject({ code: "TIMEOUT", status: 0 }); + expect(Date.now() - started).toBeLessThan(55); // at the deadline, not when the transport got round to it + expect(calls).toHaveLength(1); + } + await later(90, null); // let the late answer and the late error arrive + expect(unhandled).toEqual([]); + } finally { + process.off("unhandledRejection", onUnhandled); + } + }); + + it("timeoutMs: 0 is no timeout of the client's: the request waits, and the transport is handed the caller's own signal", async () => { + const t = honouring(() => later(70, { ok: true })); + expect(await clientOn(t, { timeoutMs: 0 }).request(read)).toEqual({ ok: true }); + expect(t.calls[0]!.signal).toBeUndefined(); + const controller = new AbortController(); + await clientOn(t, { timeoutMs: 0 }).request({ ...read, signal: controller.signal }); + expect(t.calls[1]!.signal).toBe(controller.signal); + // The control: the same transport under a 20 ms deadline times out. + await expect(clientOn(honouring(() => later(70, { ok: true })), { timeoutMs: 20, retries: 0 }).request(read)).rejects.toMatchObject({ code: "TIMEOUT" }); + }); + + it("a transport's own shorter timeout wins: its error is the one the caller sees", async () => { + const own = new ApiError("timeout of 10ms exceeded", 0, "TIMEOUT"); + const t = honouring(() => later(10, null).then(() => { throw own; })); + expect(await clientOn(t, { timeoutMs: 200, retries: 0 }).request(write).catch((e: unknown) => e)).toBe(own); + }); + + it("the caller's abort is ABORTED, not TIMEOUT: before sending, in flight, and even when the transport ignores the signal; it is never resent", async () => { + const before = new AbortController(); + before.abort(); + const t = honouring(() => never); + await expect(clientOn(t, { timeoutMs: 50 }).request({ ...read, signal: before.signal })).rejects.toMatchObject({ code: "ABORTED", kind: "aborted" }); + expect(t.calls).toHaveLength(0); + const during = new AbortController(); + setTimeout(() => during.abort(), 10); + await expect(clientOn(t, { timeoutMs: 200 }).request({ ...read, signal: during.signal })).rejects.toMatchObject({ code: "ABORTED" }); + expect(t.calls).toHaveLength(1); + const deaf: Transport = { request: (() => never) as Transport["request"] }; + const ignored = new AbortController(); + setTimeout(() => ignored.abort(), 10); + const started = Date.now(); + await expect(clientOn(deaf, { timeoutMs: 200 }).request({ ...read, signal: ignored.signal })).rejects.toMatchObject({ code: "ABORTED" }); + expect(Date.now() - started).toBeLessThan(150); + }); +}); + +describe("the built-in transport under the same rule", () => { + it("times out an attempt by the same deadline, covers the body as well as the headers, and timeoutMs: 0 waits", async () => { + const hanging = ((_url: string, init: RequestInit) => new Promise((_resolve, reject) => init.signal?.addEventListener("abort", () => reject(Object.assign(new Error("aborted"), { name: "AbortError" })))) as unknown) as typeof fetch; + await expect(createFetchTransport({ baseUrl: "https://x", timeoutMs: 20, retries: 0, fetchImpl: hanging }).request(read)).rejects.toMatchObject({ code: "TIMEOUT", message: "Timed out after 20 ms" }); + // Headers at once, the body never: still a TIMEOUT, not a raw stream error. + const stalled = (async (_url: string, init: RequestInit) => new Response(new ReadableStream({ start(controller) { init.signal?.addEventListener("abort", () => controller.error(Object.assign(new Error("aborted"), { name: "AbortError" }))); } }), { status: 200, headers: { "content-type": "application/json" } })) as unknown as typeof fetch; + await expect(createFetchTransport({ baseUrl: "https://x", timeoutMs: 20, retries: 0, fetchImpl: stalled }).request(read)).rejects.toMatchObject({ code: "TIMEOUT" }); + const slow = (async () => { await later(60, null); return new Response("{\"ok\":true}", { status: 200, headers: { "content-type": "application/json" } }); }) as unknown as typeof fetch; + expect(await createFetchTransport({ baseUrl: "https://x", timeoutMs: 0, retries: 0, fetchImpl: slow }).request(read)).toEqual({ ok: true }); + }); + + it("a person's time is not on the clock: the re-authentication hook runs outside the deadline, however long the sign-in takes", async () => { + const answers = [new Response("Unauthorized", { status: 401 }), new Response("{\"ok\":true}", { status: 200, headers: { "content-type": "application/json" } })]; + const fetchImpl = (async () => answers.shift()!) as unknown as typeof fetch; + // The hook takes three times the timeout, as someone typing a password would. + const transport = createFetchTransport({ baseUrl: "https://x", timeoutMs: 20, retries: 0, fetchImpl, onUnauthorized: async () => { await later(60, null); return "retry" as const; } }); + expect(await transport.request(read)).toEqual({ ok: true }); + }); +}); diff --git a/test/unit/transportAuth.test.ts b/test/unit/transportAuth.test.ts index d56cb2f..04ae618 100644 --- a/test/unit/transportAuth.test.ts +++ b/test/unit/transportAuth.test.ts @@ -94,10 +94,15 @@ describe("transport for real callers", () => { const scoped = base.withSignal(controller.signal); expect(scoped.schema.cache).toBe(base.schema.cache); await scoped.localize(["Story"]); - expect(transport.request.mock.calls[0]![0].signal).toBe(controller.signal); - // The original client is untouched. + // The transport is handed the attempt's own signal (it also fires at the client's deadline) while the request is open. + expect(transport.request.mock.calls[0]![0].signal).toBeInstanceOf(AbortSignal); + // Tied to the caller's: once that is aborted, a request through the scoped client is ABORTED and never reaches the transport. + controller.abort(); + await expect(scoped.localize(["Story"])).rejects.toMatchObject({ code: "ABORTED" }); + expect(transport.request).toHaveBeenCalledTimes(1); + // The original client is untouched: its requests are not tied to that signal. await base.localize(["Story"]); - expect(transport.request.mock.calls[1]![0].signal).toBeUndefined(); + expect(transport.request).toHaveBeenCalledTimes(2); }); it("the client passes credentials and onUnauthorized through to its fetch transport", async () => {