mirror of
https://github.com/Zakkaus/doona.git
synced 2026-12-06 00:00:57 +00:00
refactor(api): share Retry-After parsing and the snapshot refusal check
parseRetryAfter replaces the two header readers, and isSnapshotRefusal the three inline 503 snapshot_unavailable tests. Each caller keeps its default and condition.
This commit is contained in:
1 parent
09a3ea3e46
commit
951cdb21cd
7 files changed
+60
-14
No files matched your search
@@ -0,0 +1,3 @@
|
||||
Internal
|
||||
|
||||
- The API client shares one Retry-After parser and one snapshot refusal check instead of repeating them per call site.
|
||||
@@ -580,6 +580,18 @@ describe('native transport', () => {
|
||||
expect(String(request.mock.calls[1][0])).toBe('https://honk.test/doona' + acceptedBody.href);
|
||||
await expect(result).resolves.toMatchObject({status: 'succeeded'});
|
||||
});
|
||||
it.each([
|
||||
['absent', undefined, 1],
|
||||
['not a number', 'soon', 1],
|
||||
['below one second', '0.5', 1],
|
||||
['given', '7', 7]
|
||||
])('polls an accepted operation after %s Retry-After by %s seconds', async (_label, header, seconds) => {
|
||||
vi.stubGlobal(
|
||||
'fetch',
|
||||
vi.fn(async () => json(acceptedBody, 202, {Location: acceptedBody.href, ...(header ? {'Retry-After': header} : {})}))
|
||||
);
|
||||
await expect(createApi('https://honk.test').startReload()).resolves.toMatchObject({retryAfter: seconds});
|
||||
});
|
||||
it('enforces the one-second floor and aborts without another GET', async () => {
|
||||
vi.useFakeTimers();
|
||||
const request = vi.fn();
|
||||
|
||||
+3
-2
@@ -15,7 +15,7 @@ import {
|
||||
type OperationState,
|
||||
type RoutingTraceResponse
|
||||
} from './model';
|
||||
import {ApiError, clientError, responseError, send} from './error';
|
||||
import {ApiError, clientError, parseRetryAfter, responseError, send} from './error';
|
||||
import {uuid} from './hash';
|
||||
import {readSse} from './sse';
|
||||
import {wait} from './wait';
|
||||
@@ -24,7 +24,8 @@ import {eventKinds} from './selectors';
|
||||
import {normalizeCapabilities} from './capabilities';
|
||||
import {createServerClock, type ServerClock} from './serverClock';
|
||||
|
||||
const retryAfter = (response: Response) => Math.max(1, Number(response.headers.get('Retry-After')) || 1);
|
||||
// An operation's poll delay: Retry-After, or one second when it is absent, and never less than one.
|
||||
const retryAfter = (response: Response) => Math.max(1, parseRetryAfter(response) ?? 1);
|
||||
|
||||
function data<T>(result: {data?: T; response: Response}): T {
|
||||
if (result.data === undefined) throw clientError(result.response.status, 'empty_response', 'Response has no JSON body', 'ui.errNoJson');
|
||||
|
||||
+22
-1
@@ -1,6 +1,6 @@
|
||||
import {expect, it} from 'vitest';
|
||||
import {LANGS, translate} from '../i18n';
|
||||
import {ApiError, LocalError, errorLines, errorText, failureNotice, noticeText, requestIdOf, responseError} from './error';
|
||||
import {ApiError, LocalError, errorLines, errorText, failureNotice, isSnapshotRefusal, noticeText, parseRetryAfter, requestIdOf, responseError} from './error';
|
||||
|
||||
it('joins a local error and its detail with the colon of the active language', () => {
|
||||
const error = new LocalError('ui.operationFailed', 'member refused');
|
||||
@@ -153,3 +153,24 @@ it('shows refusal recovery directly for a failed operation', () => {
|
||||
const error = new LocalError('ui.operationFailed', 'Refused', 'permission_denied', {reason: 'credential_sources_changed'});
|
||||
expect(errorText(error, t)).toBe('The sources declaring API secrets have changed. Reload honk and retry.');
|
||||
});
|
||||
|
||||
it('reads Retry-After as a positive number of seconds and as null otherwise', () => {
|
||||
const answer = (headers?: HeadersInit) => new Response(null, {status: 503, headers});
|
||||
expect(parseRetryAfter(answer({'Retry-After': '3'}))).toBe(3);
|
||||
expect(parseRetryAfter(answer({'Retry-After': '0.5'}))).toBe(0.5);
|
||||
for (const header of [undefined, {'Retry-After': '0'}, {'Retry-After': '-2'}, {'Retry-After': 'soon'}]) expect(parseRetryAfter(answer(header))).toBeNull();
|
||||
});
|
||||
|
||||
it('carries Retry-After onto the error, null when the backend gave none', async () => {
|
||||
const refused = (headers?: HeadersInit) => responseError(new Response('{}', {status: 503, headers}));
|
||||
expect((await refused({'Retry-After': '4'})).retryAfter).toBe(4);
|
||||
expect((await refused()).retryAfter).toBeNull();
|
||||
});
|
||||
|
||||
it('takes only a 503 snapshot_unavailable that carries a Retry-After as a refusal to wait out', () => {
|
||||
expect(isSnapshotRefusal(new ApiError(503, 'snapshot_unavailable', 'busy', null, null, 2))).toBe(true);
|
||||
expect(isSnapshotRefusal(new ApiError(503, 'snapshot_unavailable', 'busy'))).toBe(false);
|
||||
expect(isSnapshotRefusal(new ApiError(503, 'temporarily_unavailable', 'busy', null, null, 2))).toBe(false);
|
||||
expect(isSnapshotRefusal(new ApiError(429, 'snapshot_unavailable', 'busy', null, null, 2))).toBe(false);
|
||||
expect(isSnapshotRefusal(new Error('snapshot_unavailable'))).toBe(false);
|
||||
});
|
||||
+12
-2
@@ -29,16 +29,26 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
// The seconds a response's Retry-After asks for, or null when it is absent or not a positive number.
|
||||
export const parseRetryAfter = (response: Response): number | null => {
|
||||
const seconds = Number(response.headers.get('Retry-After'));
|
||||
return seconds > 0 ? seconds : null;
|
||||
};
|
||||
|
||||
// A 503 snapshot_unavailable with a Retry-After: the backend cannot hold the listing snapshot now, and asks for a wait
|
||||
// before the listing is asked for again. The same refusal without a Retry-After is not retried.
|
||||
export const isSnapshotRefusal = (error: unknown): error is ApiError & {retryAfter: number} =>
|
||||
error instanceof ApiError && error.status === 503 && error.code === 'snapshot_unavailable' && error.retryAfter !== null;
|
||||
|
||||
export async function responseError(response: Response, method = 'GET'): Promise<ApiError> {
|
||||
const body: Partial<ErrorResponse> | null = await response.json().catch(() => null);
|
||||
const retryAfter = Number(response.headers.get('Retry-After'));
|
||||
const error = new ApiError(
|
||||
response.status,
|
||||
body?.error?.code ?? '',
|
||||
body?.error?.message ?? (response.statusText || `HTTP ${response.status}`),
|
||||
body?.request_id ?? null,
|
||||
body?.error?.details ?? null,
|
||||
retryAfter > 0 ? retryAfter : null
|
||||
parseRetryAfter(response)
|
||||
);
|
||||
if (response.url) error.request = {method: method.toUpperCase(), path: new URL(response.url).pathname};
|
||||
return error;
|
||||
|
||||
@@ -11,7 +11,7 @@ import {downloadFile, exportName, panelQuery, toast, toastErrorDetail, useDeboun
|
||||
import type {PageProps} from '../../shell/routes';
|
||||
import {appendDnsLog, dnsCacheView, dnsLogDetail, dnsLogsExport, dnsLogView, dnsLogWindow, dnsQueryUpstreams, dnsQueryView} from './view';
|
||||
import {href, pickTab, within, tabQuery} from '../../shell/route';
|
||||
import {ApiError, errorText} from '../../api/error';
|
||||
import {ApiError, errorText, isSnapshotRefusal} from '../../api/error';
|
||||
import {wait} from '../../api/wait';
|
||||
import {cacheCard, cacheCardState} from './cache';
|
||||
import {dnsPattern, matchKinds, matchListMax, type MatchKind} from './match';
|
||||
@@ -325,10 +325,10 @@ export function useDnsLogTab(enabled: boolean | undefined, initialName: string,
|
||||
// the cursor refused for filters that changed since; asking again would fail the same way, so the log starts
|
||||
// over from the newest page. A 503 snapshot_unavailable does the same once the wait it asks for has passed.
|
||||
if (!(error instanceof ApiError) || signal.aborted) throw error;
|
||||
const unavailable = error.status === 503 && error.code === 'snapshot_unavailable' && error.retryAfter !== null;
|
||||
const unavailable = isSnapshotRefusal(error);
|
||||
const expired = (error.status === 410 && error.code === 'snapshot_expired') || (error.status === 400 && error.code === 'invalid_request');
|
||||
if (!expired && !unavailable) throw error;
|
||||
if (unavailable) await wait(error.retryAfter!, signal);
|
||||
if (unavailable) await wait(error.retryAfter, signal);
|
||||
setHeld(null);
|
||||
void log.refetch();
|
||||
toast('info', t('dns.olderExpired'));
|
||||
|
||||
+5
-6
@@ -2,7 +2,7 @@ import {useCallback} from 'react';
|
||||
import {MAX_PAGE, poll} from './cadence';
|
||||
import {getApi} from '../api/index';
|
||||
import type {Api} from '../api/api';
|
||||
import {ApiError} from '../api/error';
|
||||
import {ApiError, isSnapshotRefusal} from '../api/error';
|
||||
import type {Capabilities, DnsCacheList, DnsQueryResponse} from '../api/model';
|
||||
import {wait} from '../api/wait';
|
||||
import {pageSize, useResource, walk} from './resource';
|
||||
@@ -28,9 +28,8 @@ export async function smallerOnRefusal<Q extends {limit?: number}, P>(
|
||||
return {page: await fetch(query), limit: query.limit};
|
||||
} catch (error) {
|
||||
const {limit} = query;
|
||||
const refused = error instanceof ApiError && error.status === 503 && error.code === 'snapshot_unavailable' && error.retryAfter !== null;
|
||||
if (!refused || limit === undefined || limit < 2) throw error;
|
||||
await wait(error.retryAfter!, signal);
|
||||
if (!isSnapshotRefusal(error) || limit === undefined || limit < 2) throw error;
|
||||
await wait(error.retryAfter, signal);
|
||||
const smaller = Math.ceil(limit / 4);
|
||||
return {page: await fetch({...query, limit: smaller}), limit: smaller};
|
||||
}
|
||||
@@ -51,8 +50,8 @@ export async function dnsCacheListing(api: Api, signal?: AbortSignal) {
|
||||
try {
|
||||
return await listing();
|
||||
} catch (error) {
|
||||
if (!(error instanceof ApiError && error.status === 503 && error.code === 'snapshot_unavailable' && error.transient)) throw error;
|
||||
await wait(error.retryAfter!, signal);
|
||||
if (!isSnapshotRefusal(error)) throw error;
|
||||
await wait(error.retryAfter, signal);
|
||||
return listing();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user