Line data Source code
1 : import type { RetryPolicy } from './retryPolicy'
2 : import {
3 : canRetryMethod,
4 : canRetrySignInRefusal,
5 : nextRetry,
6 : signInRefusalDelayMs,
7 : sleep as sleepFor
8 : } from './retryPolicy'
9 : import type { StatusRetryEnd } from './statusRetryTelemetry'
10 : import { abortEnd, endForStop, trackStatusRetry } from './statusRetryTelemetry'
11 :
12 : type FetchLike = (
13 : input: RequestInfo | URL,
14 : init?: RequestInit
15 : ) => Promise<Response>
16 :
17 : export interface RetryingFetchOptions {
18 : readonly policy?: RetryPolicy
19 : readonly fetchImpl?: FetchLike
20 : readonly sleep?: (ms: number, signal?: AbortSignal) => Promise<void>
21 : readonly random?: () => number
22 : }
23 :
24 1 : function requestMethod(input: RequestInfo | URL, init: RequestInit): string {
25 1 : return init.method ?? (input instanceof Request ? input.method : 'GET')
26 : }
27 :
28 0 : function requestSignal(
29 : input: RequestInfo | URL,
30 : init: RequestInit
31 : ): AbortSignal | undefined {
32 0 : return init.signal ?? (input instanceof Request ? input.signal : undefined)
33 : }
34 :
35 0 : function isReplayable(input: RequestInfo | URL, init: RequestInit): boolean {
36 0 : return (
37 : !(init.body instanceof ReadableStream) &&
38 : !(input instanceof Request && input.bodyUsed)
39 : )
40 : }
41 :
42 0 : async function fetchWriteAfterRefusal(
43 : input: RequestInfo | URL,
44 : init: RequestInit,
45 : method: string,
46 : options: RetryingFetchOptions
47 : ): Promise<Response> {
48 0 : const { policy, fetchImpl = fetch, sleep = sleepFor, random } = options
49 0 : const replay =
50 : input instanceof Request && input.body !== null ? input.clone() : input
51 0 : const first = await fetchImpl(input, init)
52 0 : const delayMs = await signInRefusalDelayMs({
53 : method,
54 : status: first.status,
55 : readRetryAfter: () => first.headers.get('Retry-After'),
56 : readBody: (signal) =>
57 : new Response(
58 : first.clone().body?.pipeThrough(new TransformStream(), { signal })
59 : ).json(),
60 : policy,
61 : random
62 : })
63 0 : if (delayMs === undefined) return first
64 :
65 0 : const signal = requestSignal(input, init)
66 0 : await first.body?.cancel().catch(() => undefined)
67 0 : const settle = (
68 : end: StatusRetryEnd,
69 : attempts: number,
70 : finalStatus = first.status
71 : ) =>
72 : trackStatusRetry({
73 : transport: 'fetch',
74 : method,
75 : url: () => (input instanceof Request ? input.url : String(input)),
76 : end,
77 : attempts,
78 : finalStatus,
79 : retryScheduled: true
80 : })
81 0 : try {
82 0 : await sleep(delayMs, signal)
83 : } catch (error) {
84 0 : settle(abortEnd(signal), 1)
85 0 : throw error
86 : }
87 0 : let second: Response
88 0 : try {
89 0 : second = await fetchImpl(replay, init)
90 : } catch (error) {
91 0 : settle(abortEnd(signal), 2)
92 0 : throw error
93 : }
94 0 : settle('answered', 2, second.status)
95 0 : return second
96 : }
97 :
98 : /**
99 : * `fetch` that retries retryable statuses on idempotent methods, honoring
100 : * `Retry-After`; a policy may opt in a write the sign-in check refused.
101 : */
102 1 : export async function fetchWithRetry(
103 : input: RequestInfo | URL,
104 : init: RequestInit = {},
105 : options: RetryingFetchOptions = {}
106 : ): Promise<Response> {
107 1 : const { policy, fetchImpl = fetch, sleep = sleepFor, random } = options
108 1 : const method = requestMethod(input, init)
109 1 : if (canRetrySignInRefusal(method, policy) && isReplayable(input, init)) {
110 0 : return fetchWriteAfterRefusal(input, init, method, options)
111 : }
112 1 : if (!canRetryMethod(method, policy) || !isReplayable(input, init)) {
113 1 : return fetchImpl(input, init)
114 : }
115 :
116 0 : const signal = requestSignal(input, init)
117 1 : const template =
118 : input instanceof Request && input.body !== null ? input.clone() : undefined
119 :
120 1 : let lastRetryStatus: number | undefined
121 1 : const settle = (end: StatusRetryEnd, attempts: number, status?: number) =>
122 : trackStatusRetry({
123 : transport: 'fetch',
124 : method,
125 : url: () => (input instanceof Request ? input.url : String(input)),
126 : end,
127 : attempts,
128 : finalStatus: status ?? lastRetryStatus,
129 : retryScheduled: lastRetryStatus !== undefined
130 : })
131 :
132 1 : for (let attempt = 1; ; attempt++) {
133 0 : let response: Response
134 0 : try {
135 0 : response = await fetchImpl(template?.clone() ?? input, init)
136 : } catch (error) {
137 0 : settle(abortEnd(signal), attempt)
138 0 : throw error
139 : }
140 0 : const decision = nextRetry({
141 : method,
142 : status: response.status,
143 : readRetryAfter: () => response.headers.get('Retry-After'),
144 : attempt,
145 : policy,
146 : random
147 : })
148 0 : if (!decision.retry) {
149 0 : settle(endForStop(decision.reason), attempt, response.status)
150 0 : return response
151 : }
152 0 : lastRetryStatus = response.status
153 0 : await response.body?.cancel().catch(() => undefined)
154 0 : try {
155 0 : await sleep(decision.delayMs, signal)
156 : } catch (error) {
157 0 : settle(abortEnd(signal), attempt)
158 0 : throw error
159 : }
160 : }
161 : }
162 :
163 : /** Wraps a url-based send so it retries like {@link fetchWithRetry}. */
164 0 : export function retryingSend(
165 : send: (url: string, init: RequestInit) => Promise<Response>,
166 : policy?: RetryPolicy
167 : ): (url: string, init: RequestInit) => Promise<Response> {
168 0 : return (url, init) =>
169 : fetchWithRetry(url, init, {
170 : policy,
171 : fetchImpl: (input, attemptInit) => send(String(input), attemptInit ?? {})
172 : })
173 : }
|