fix(api): retry empty reads once and name the request in errors

A JSON GET that comes back as an empty 2xx body, or gets no response at
all, is sent once more after 300 ms. A second failure is reported with
attempts: 2. Timeouts, caller aborts, error statuses, POSTs and the SSE
streams are not retried, and GETs never enter the refusal loop.

API errors now record the method, the path and query, and the
Content-Type, Content-Length, Transfer-Encoding, Content-Encoding and
Server response headers. The copied diagnostics add an attempts line and
a headers line to each entry.
This commit is contained in:
Zakk committed 2026-10-04 04:29:05 +11:00
1 parent 8da44b0de4
commit 573ef3dfa2
8 files changed
+264 -40

No files matched your search

+4
View File
@@ -0,0 +1,4 @@
Fixed
- Reads that come back with an empty body or no response are sent once more before an error is shown.
- Error details name the failed request and the key response headers.
+17
View File
@@ -34,6 +34,23 @@ test('nodes sort by name, latency and protocol, and filter by group and protocol
await expect(list).toHaveCount(1);
});
test('a node list that comes back empty once is asked for again and shown', async ({page}) => {
const {requests} = await mockBackend(page);
let dropped = 0;
await page.route(
'**/api/v1/nodes{,?*}',
route => {
dropped++;
return route.fulfill({status: 200, contentType: 'application/json', body: ''});
},
{times: 1}
);
await page.goto('/#/nodes?provider=inline');
await expect(rows(page.locator('.rp-table').nth(1))).toHaveCount(5);
expect(dropped).toBe(1);
expect(requests.some(request => new URL(request.url()).pathname === '/api/v1/nodes')).toBe(true);
});
test('node cell content starts at its header text, including latency and action icons', async ({page}) => {
await page.setViewportSize({width: 1440, height: 900});
await page.goto('/#/nodes?provider=inline');
+140 -1
View File
@@ -6,6 +6,7 @@ import {ApiError, errorText, send} from './error';
import {createServerClock, selectServerClock} from './serverClock';
import type {ApiEvent, OperationAccepted} from './model';
import {currentRefusal} from './refusal';
import {diagnosticOf, formatDiagnostics} from './diagnostics';
import {eventSummary} from './selectors';
const acceptedBody = {operation_id: 'op-1', kind: 'reload', status: 'queued', href: '/api/v1/operations/op-1'};
@@ -283,6 +284,142 @@ describe('native transport', () => {
await vi.advanceTimersByTimeAsync(60000);
await read;
});
// What a tunnel that drops a body hands the browser: a chunked 200 with no Content-Length and nothing in it.
const emptyChunked = async () =>
new Response(new ReadableStream({start: controller => controller.close()}), {
headers: {'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', Server: 'honk'}
});
const unreachable = async () => {
throw new TypeError('Failed to fetch');
};
// The peer resets the connection once the 200 headers are out, so the body read fails.
const resetAfterHeaders = async () =>
new Response(new ReadableStream({start: controller => controller.error(new TypeError('network error'))}), {
headers: {'Content-Type': 'application/json'}
});
const badGateway = async () => json({error: {code: 'bad_gateway', message: 'Down'}}, 502);
it.each([
{name: 'an empty chunked body', first: emptyChunked},
{name: 'no response', first: unreachable},
{name: 'a reset after the headers', first: resetAfterHeaders}
])('sends a read again once after $name and returns the second answer', async ({first}) => {
vi.useFakeTimers();
const request = vi.fn(async () => json({items: [], next_cursor: null})).mockImplementationOnce(first);
vi.stubGlobal('fetch', request);
const result = createApi('https://honk.test').nodes({limit: 1000});
await vi.advanceTimersByTimeAsync(300);
await expect(result).resolves.toEqual({items: [], next_cursor: null});
expect(request).toHaveBeenCalledTimes(2);
});
// The request is named by its path alone: a query can carry a token from a redirect, or a filter.
const nodes = (api: Api) => api.nodes({limit: 1000});
const nodesRequest = {method: 'GET', path: '/api/v1/nodes'};
it.each([
{
answer: emptyChunked,
call: nodes,
expected: {
status: 200,
code: 'empty_response',
request: nodesRequest,
headers: {'Content-Type': 'application/json', 'Transfer-Encoding': 'chunked', Server: 'honk'}
}
},
{answer: unreachable, call: nodes, expected: {status: 0, code: 'network_error', request: nodesRequest, headers: null}},
{
answer: resetAfterHeaders,
call: nodes,
expected: {status: 0, code: 'network_error', request: nodesRequest, headers: {'Content-Type': 'application/json'}}
},
{
answer: emptyChunked,
call: (api: Api) => api.dnsLog({name: 'example.org', src: '10.0.0.2'}),
expected: {code: 'empty_response', request: {method: 'GET', path: '/api/v1/dns/log'}}
},
{answer: emptyChunked, again: badGateway, call: nodes, expected: {status: 502, code: 'bad_gateway'}}
])('reports a read that fails again on its retry as failed twice ($expected.code)', async ({answer, again, call, expected}) => {
vi.useFakeTimers();
const request = vi.fn(again ?? answer).mockImplementationOnce(answer);
vi.stubGlobal('fetch', request);
const result = call(createApi('https://honk.test', 'secret-token'));
const failure = expect(result).rejects.toMatchObject({...expected, attempts: 2});
await vi.advanceTimersByTimeAsync(300);
await failure;
expect(request).toHaveBeenCalledTimes(2);
});
it.each([
{name: 'timed-out read', request: () => hanging(), call: (api: Api) => api.runtime(), expected: {code: 'timeout'}},
{
name: 'read the caller aborts',
request: () => hanging(),
call: (api: Api) => {
const controller = new AbortController();
setTimeout(() => controller.abort(), 5000);
return api.runtime(controller.signal);
},
expected: {name: 'AbortError'}
},
{
name: 'read answered 404',
request: () => vi.fn(async () => json({error: {code: 'not_found', message: 'Gone'}}, 404)),
call: (api: Api) => api.runtime(),
expected: {status: 404}
},
{
name: 'read answered 502',
request: () => vi.fn(async () => json({error: {code: 'bad_gateway', message: 'Down'}}, 502)),
call: (api: Api) => api.runtime(),
expected: {status: 502}
},
{
name: 'read-only POST with no response',
request: () => vi.fn(unreachable),
call: (api: Api) => api.dnsQuery('example.org', ['A']),
expected: {code: 'network_error', attempts: 1}
},
{
name: 'operation start answered empty',
request: () => vi.fn(emptyChunked),
call: (api: Api) => api.startReload(),
expected: {code: 'empty_response', attempts: 1}
},
{
name: 'read whose body stalls',
request: () => stalling(),
call: (api: Api) => api.runtime(),
expected: {code: 'timeout', request: {method: 'GET', path: '/api/v1/runtime'}, headers: {'Content-Type': 'application/json'}}
}
])('does not send a $name again', async ({request, call, expected}) => {
vi.useFakeTimers();
const fetch = request();
vi.stubGlobal('fetch', fetch);
const failure = expect(call(createApi('https://honk.test'))).rejects.toMatchObject(expected);
await vi.advanceTimersByTimeAsync(16000);
await failure;
expect(fetch).toHaveBeenCalledTimes(1);
});
it('names the request and the response headers in the copied diagnostics, never the token', async () => {
vi.useFakeTimers();
vi.stubGlobal('fetch', vi.fn(emptyChunked));
const result = createApi('https://honk.test', 'secret-token').connections({type: 'all', detail: 'full', limit: 1000});
const failure = result.catch((error: unknown) => error);
await vi.advanceTimersByTimeAsync(300);
const text = formatDiagnostics([diagnosticOf(await failure, new Date('2026-10-04T00:00:00Z'))], {doona: '0.1.0', route: '/logs'});
expect(text).toBe(
[
'doona 0.1.0',
'page /logs',
'',
'[2026-10-04T00:00:00.000Z] GET /api/v1/connections',
'status: 200',
'code: empty_response',
'message: Response has no JSON body',
'attempts: 2',
'headers: Content-Type: application/json, Transfer-Encoding: chunked, Server: honk'
].join('\n')
);
expect(text).not.toContain('secret-token');
});
it('keeps the url of the response it rebuilds around the body', async () => {
const response = json({observed_at: new Date().toISOString()});
Object.defineProperty(response, 'url', {value: 'https://honk.test/api/v1/runtime'});
@@ -387,7 +524,9 @@ describe('native transport', () => {
throw new TypeError('Failed to fetch');
})
);
await expect(api.runtime()).rejects.toMatchObject({code: 'network_error'});
const failure = expect(api.runtime()).rejects.toMatchObject({code: 'network_error'});
await vi.advanceTimersByTimeAsync(300);
await failure;
expect(vi.getTimerCount()).toBe(0);
});
it('drops the forwarding listeners of an engine without AbortSignal.any once the request is over', async () => {
+56 -18
View File
@@ -15,10 +15,10 @@ import {
type OperationState,
type RoutingTraceResponse
} from './model';
import {ApiError, clientError, parseRetryAfter, responseError, send} from './error';
import {ApiError, clientError, describe, NO_CONTENT, parseRetryAfter, responseError, send} from './error';
import {uuid} from './hash';
import {readSse} from './sse';
import {wait} from './wait';
import {pause, wait} from './wait';
import {waitOutRefusal} from './refusal';
import {eventKinds} from './selectors';
import {normalizeCapabilities} from './capabilities';
@@ -36,6 +36,24 @@ function accepted(result: {data?: Omit<OperationAccepted, 'retryAfter'>; respons
return {...data(result), retryAfter: retryAfter(result.response)};
}
// A JSON read that succeeds with no body fails at the transport, where the request is known. Only the first non-empty
// chunk is read, from a copy, so the caller still reads the whole body.
const expectsJson = (request: Request) => request.headers.get('Accept')?.includes('application/json') ?? false;
async function filled(request: Request, response: Response): Promise<Response> {
if (!response.ok || NO_CONTENT.has(response.status)) return response;
const reader = response.clone().body?.getReader();
try {
for (let chunk = await reader?.read(); chunk && !chunk.done; chunk = await reader!.read()) if (chunk.value.byteLength) return response;
} finally {
reader?.cancel().catch(() => {});
}
throw describe(clientError(response.status, 'empty_response', 'Response has no JSON body', 'ui.errNoJson'), request.method, request.url, response);
}
// A JSON read that comes back empty or gets no response is sent once more after this pause, since a tunnel or proxy
// can drop a single body. Timeouts, caller aborts and error statuses are not retried here, and streams never come here.
// An error status on the retry becomes an ApiError in the middleware, which counts the attempt through `retried`.
const READ_RETRY_MS = 300;
// Keyed mutations and requests that write nothing retry explicit transient refusals this many times.
const MAX_REFUSALS = 3;
// The contract replays a repeated Idempotency-Key only for operation starts, the calls that can answer 202 with a
@@ -81,35 +99,55 @@ export function createApi(base: string, token?: string, clock: ServerClock = cre
};
const headers: Record<string, string> = {Accept: 'application/json'};
if (token) headers.Authorization = 'Bearer ' + token;
const retried = new WeakSet<Response>();
const options = {
baseUrl,
headers,
cache: 'no-store' as const,
fetch: async (request: Request) => {
// A mutation is replayed only under an Idempotency-Key, which only operation starts carry, so a refusal that
// already wrote something cannot repeat the write.
const {pathname} = new URL(request.url);
const readOnly = readOnlyPaths.some(path => pathname.endsWith(path));
// A read-only POST gets the read deadline and text: it cannot have changed anything.
const write = request.method !== 'GET' && !readOnly;
const retryable = request.headers.has('Idempotency-Key') || readOnly;
if (!retryable) return send(request, undefined, write);
// A refusal with Retry-After is waited out a few times; the caller sees the last refusal after that.
for (let refused = 0; ; refused++) {
const response = await send(request.clone(), undefined, write);
if ((response.status !== 503 && response.status !== 429) || refused >= MAX_REFUSALS) return response;
const error = await responseError(response.clone());
if (!error.transient) return response;
await response.body?.cancel();
await waitOutRefusal(response.status, error.retryAfter!, request.signal);
if (request.method !== 'GET' || !expectsJson(request)) return exchange(request);
try {
return await filled(request, await exchange(request.clone()));
} catch (error) {
if (!(error instanceof ApiError) || (error.code !== 'empty_response' && error.code !== 'network_error')) throw error;
await pause(READ_RETRY_MS, request.signal);
return exchange(request)
.then(response => {
retried.add(response);
return filled(request, response);
})
.catch((again: unknown) => {
if (again instanceof ApiError) again.attempts = 2;
throw again;
});
}
}
};
async function exchange(request: Request): Promise<Response> {
// A mutation is replayed only under an Idempotency-Key, which only operation starts carry, so a refusal that
// already wrote something cannot repeat the write.
const {pathname} = new URL(request.url);
const readOnly = readOnlyPaths.some(path => pathname.endsWith(path));
// A read-only POST gets the read deadline and text: it cannot have changed anything.
const write = request.method !== 'GET' && !readOnly;
const retryable = request.headers.has('Idempotency-Key') || readOnly;
if (!retryable) return send(request, undefined, write);
// A refusal with Retry-After is waited out a few times; the caller sees the last refusal after that.
for (let refused = 0; ; refused++) {
const response = await send(request.clone(), undefined, write);
if ((response.status !== 503 && response.status !== 429) || refused >= MAX_REFUSALS) return response;
const error = await responseError(response.clone());
if (!error.transient) return response;
await response.body?.cancel();
await waitOutRefusal(response.status, error.retryAfter!, request.signal);
}
}
const failures: Middleware = {
onResponse: async ({request, response, schemaPath}) => {
if (!response.ok) {
const error = await responseError(response, request.method);
error.configurationWrite = configurationWrites.has(`${request.method} ${schemaPath}`);
if (retried.has(response)) error.attempts = 2;
throw error;
}
return response;
+3 -1
View File
@@ -38,12 +38,14 @@ it.each([
expect(redact(value)).toEqual(expected);
});
it('records what an API failure carries, with the path and no query', () => {
it('records what an API failure carries, with its request and response headers', () => {
const error = new ApiError(409, 'state_conflict', 'Changed meanwhile', 'req-1', {written: false, token: 'x'});
error.request = {method: 'PUT', path: '/api/v1/config/main'};
expect(diagnosticOf(error, new Date('2026-10-02T01:02:03Z'))).toEqual({
time: '2026-10-02T01:02:03.000Z',
request: {method: 'PUT', path: '/api/v1/config/main'},
headers: null,
attempts: 1,
status: 409,
code: 'state_conflict',
message: 'Changed meanwhile',
+12 -2
View File
@@ -5,6 +5,8 @@ import {ApiError, LocalError, type OperationRef} from './error';
export type Diagnostic = {
time: string;
request: {method: string; path: string} | null;
headers: Record<string, string> | null;
attempts: number;
status: number | null;
code: string | null;
message: string;
@@ -61,11 +63,13 @@ export function redact(value: unknown, depth = 0): unknown {
export function diagnosticOf(error: unknown, now = new Date()): Diagnostic {
const cause = error instanceof Error && error.cause instanceof Error ? error.cause : null;
const source = error instanceof ApiError || error instanceof LocalError ? error : cause instanceof ApiError || cause instanceof LocalError ? cause : error;
const base = {time: now.toISOString(), request: null, status: null, code: null, details: null, requestId: null, operation: null};
const base = {time: now.toISOString(), request: null, headers: null, attempts: 1, status: null, code: null, details: null, requestId: null, operation: null};
if (source instanceof ApiError)
return {
...base,
request: source.request,
headers: source.headers,
attempts: source.attempts,
status: source.status,
code: source.code || null,
message: scrubText(source.message),
@@ -90,12 +94,18 @@ export type DiagnosticsHeader = {doona: string; engine?: string; route: string};
// Plain text for a bug report: the versions and the page first, then one block per entry.
export function formatDiagnostics(entries: Diagnostic[], {doona, engine, route}: DiagnosticsHeader): string {
const head = [`doona ${doona}`, engine && `engine ${engine}`, `page ${route}`].filter(Boolean).join('\n');
const blocks = entries.map(({time, request, status, code, message, details, requestId, operation}) =>
const blocks = entries.map(({time, request, headers, attempts, status, code, message, details, requestId, operation}) =>
[
`[${time}]${request ? ` ${request.method} ${request.path}` : ''}`,
status !== null && `status: ${status}`,
code && `code: ${code}`,
`message: ${message}`,
attempts > 1 && `attempts: ${attempts}`,
headers &&
Object.keys(headers).length > 0 &&
`headers: ${Object.entries(headers)
.map(([name, value]) => `${name}: ${value}`)
.join(', ')}`,
requestId && `request_id: ${requestId}`,
operation && `operation: ${operation.id} ${operation.kind} ${operation.status}`,
details !== null && `details: ${JSON.stringify(details)}`
+25 -10
View File
@@ -6,8 +6,12 @@ import {backendMessage, oneLine, refusalMessage, type BackendMessage} from '../i
export class ApiError extends Error {
configurationWrite = false;
// The request that failed, for a bug report: the path only, never the query.
// The request that failed and the response headers that explain it, for a bug report: the path only, never the query,
// which can carry a token from a redirect or a filter that says what someone looked up.
request: {method: string; path: string} | null = null;
headers: Record<string, string> | null = null;
// A read that failed again on its one retry says so.
attempts = 1;
constructor(
public status: number,
public code: string,
@@ -50,13 +54,21 @@ export async function responseError(response: Response, method = 'GET'): Promise
body?.error?.details ?? null,
parseRetryAfter(response)
);
if (response.url) error.request = {method: method.toUpperCase(), path: new URL(response.url).pathname};
return response.url ? describe(error, method, response.url, response) : error;
}
const REPORTED_HEADERS = ['Content-Type', 'Content-Length', 'Transfer-Encoding', 'Content-Encoding', 'Server'];
// Names the failed request on an error, and the response headers that say what came back when there was a response.
export function describe(error: ApiError, method: string, url: string, response?: Response): ApiError {
error.request = {method: method.toUpperCase(), path: new URL(url, globalThis.location?.href).pathname};
if (response) error.headers = Object.fromEntries(REPORTED_HEADERS.flatMap(name => (response.headers.has(name) ? [[name, response.headers.get(name)!]] : [])));
return error;
}
// A contract failure detected by doona: it keeps the status and code callers branch on, and a translated text.
export const clientError = (status: number, code: string, message: string, key: Key, params?: Params) =>
new ApiError(status, code, message, null, null, null, {key, params});
const networkError = (error: TypeError) => clientError(0, 'network_error', error.message, 'ui.errNetwork');
// A backend that accepts the connection and never answers would leave the request, and every consumer sharing it,
// waiting forever. A write gets longer, since the backend may be applying it. The limit runs until the headers arrive
@@ -110,11 +122,12 @@ function deadlineFor(caller: AbortSignal | null, limit: number, timeout: ApiErro
// The body is read after send has returned, and some engines error the stream with a plain AbortError rather than the
// abort reason. A read that fails once the deadline has passed fails with the timeout error; a caller abort keeps its
// own error. A body-less response has nothing to stall and passes as it is, and so does a no-content status, which
// Chromium gives an empty stream but a Response cannot be built with. A body nobody reads keeps the deadline, which
// own error, and a connection dropped mid-body fails as a network failure; the timeout and the network failure name the
// request and the headers that came. A body-less response has nothing to stall and passes as it is, and so does a
// no-content status, which Chromium gives an empty stream but a Response cannot be built with. A body nobody reads keeps the deadline, which
// then frees the connection. The rebuilt response keeps the original's url, type and redirect flag.
const NO_CONTENT = new Set([204, 205, 304]);
function bodyWithin(response: Response, caller: AbortSignal | null, deadline: Deadline, timeout: ApiError): Response {
export const NO_CONTENT = new Set([204, 205, 304]);
function bodyWithin(response: Response, caller: AbortSignal | null, deadline: Deadline, timeout: ApiError, method: string, url: string): Response {
if (!response.body || NO_CONTENT.has(response.status)) {
deadline.over();
return response;
@@ -133,7 +146,8 @@ function bodyWithin(response: Response, caller: AbortSignal | null, deadline: De
}
} catch (error) {
deadline.over();
controller.error(deadline.signal.aborted && !caller?.aborted ? timeout : error);
if (caller?.aborted || !(deadline.signal.aborted || error instanceof TypeError)) controller.error(error);
else controller.error(describe(deadline.signal.aborted ? timeout : networkError(error as TypeError), method, url, response));
}
},
cancel: reason => {
@@ -159,16 +173,17 @@ export async function send(input: RequestInfo | URL, init?: RequestInit, write?:
seconds: limit / 1000
});
const deadline = deadlineFor(signal, limit, timeout);
const url = input instanceof Request ? input.url : String(input);
try {
const response = await fetch(input, {...init, signal: deadline.signal});
// The headers are in; from here the limit runs between chunks of the body.
deadline.arm();
return bodyWithin(response, signal, deadline, timeout);
return bodyWithin(response, signal, deadline, timeout, method, url);
} catch (error) {
deadline.over();
if (signal?.aborted) throw error;
if (deadline.signal.aborted) throw timeout;
if (error instanceof TypeError) throw clientError(0, 'network_error', error.message, 'ui.errNetwork');
if (deadline.signal.aborted) throw describe(timeout, method, url);
if (error instanceof TypeError) throw describe(networkError(error), method, url);
throw error;
}
}
+7 -8
View File
@@ -1,17 +1,16 @@
export function wait(seconds: number, signal?: AbortSignal): Promise<void> {
export function pause(ms: number, signal?: AbortSignal): Promise<void> {
signal?.throwIfAborted();
return new Promise((resolve, reject) => {
const abort = () => {
clearTimeout(timer);
reject(signal?.reason);
};
const timer = setTimeout(
() => {
signal?.removeEventListener('abort', abort);
resolve();
},
Math.max(1, seconds) * 1000
);
const timer = setTimeout(() => {
signal?.removeEventListener('abort', abort);
resolve();
}, ms);
signal?.addEventListener('abort', abort, {once: true});
});
}
export const wait = (seconds: number, signal?: AbortSignal) => pause(Math.max(1, seconds) * 1000, signal);