Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

retryer.ts

314 lines8.7 KB

1import { focusManager } from './focusManager'
2import { onlineManager } from './onlineManager'
3import { isServer as isServerEnvironment } from './environmentManager'
4import { noop, sleep } from './utils'
5import type { CancelOptions, DefaultError, NetworkMode } from './types'
6​
7// TYPES
8​
9interface RetryerConfig<TData = unknown, TError = DefaultError> {
10 fn: () => TData | Promise<TData>
11 initialPromise?: Promise<TData>
12 onCancel?: (error: TError) => void
13 onFail?: (failureCount: number, error: TError) => void
14 onPause?: () => void
15 onContinue?: () => void
16 retry?: RetryValue<TError>
17 retryDelay?: RetryDelayValue<TError>
18 networkMode: NetworkMode | undefined
19 canRun: () => boolean
21​
22/**
23 * Runs a function with retries, and can pause, continue, or cancel it. Queries and mutations use
24 * one for each fetch or execution.
25 */
26export interface Retryer<TData = unknown> {
27 /**
28 * The promise that resolves with the data, or rejects once retries are exhausted or it is
29 * cancelled.
30 */
31 promise: Promise<TData>
32 /**
33 * Cancels the run, rejecting `promise` with a `CancelledError`.
34 */
35 cancel: (cancelOptions?: CancelOptions) => void
36 /**
37 * Resumes a paused run, and returns `promise`.
38 */
39 continue: () => Promise<unknown>
40 /**
41 * Stops further retries. The current attempt still finishes.
42 */
43 cancelRetry: () => void
44 /**
45 * Allows retries again after `cancelRetry`.
46 */
47 continueRetry: () => void
48 /**
49 * Returns whether the run can start now, based on the network mode and `canRun`.
50 */
51 canStart: () => boolean
52 /**
53 * Starts the run, or waits until it can start, and returns `promise`.
54 */
55 start: () => Promise<TData>
56 /**
57 * Returns whether `promise` is still pending, resolved, or rejected.
58 */
59 status: () => 'pending' | 'resolved' | 'rejected'
61​
62type RetryerStatus = 'pending' | 'resolved' | 'rejected'
63​
64/** @inline */
65export type RetryValue<TError> = boolean | number | ShouldRetryFunction<TError>
66​
67/** @inline */
68type ShouldRetryFunction<TError = DefaultError> = (
69 failureCount: number,
70 error: TError,
71) => boolean
72​
73/** @inline */
74export type RetryDelayValue<TError> = number | RetryDelayFunction<TError>
75​
76/** @inline */
77type RetryDelayFunction<TError = DefaultError> = (
78 failureCount: number,
79 error: TError,
80) => number
81​
82/**
83 * The default `retryDelay`: doubles with every failure, starting at 1 second, up to 30 seconds.
84 * @param failureCount - The number of failures so far.
85 * @returns The delay before the next retry, in milliseconds.
86 */
87function defaultRetryDelay(failureCount: number) {
88 return Math.min(1000 * 2 ** failureCount, 30000)
90​
91/**
92 * Checks whether a fetch can run for the given network mode.
93 * @param networkMode - The `networkMode` option. Defaults to `'online'`.
94 * @returns `true` if the network mode is not `'online'`, or if it is and the client is online.
95 */
96export function canFetch(networkMode: NetworkMode | undefined): boolean {
97 return (networkMode ?? 'online') === 'online'
98 ? onlineManager.isOnline()
99 : true
101​
102/**
103 * The error thrown by a `Retryer` (and surfaced to `query.promise`/`mutation`) when a fetch is cancelled, e.g. via
104 * `query.cancel()`. `revert`, if `true`, tells the caller to restore the state the query was in before the fetch
105 * started instead of surfacing the error. `silent`, if `true`, tells the caller to suppress this error and instead
106 * resolve with the promise of the fetch that triggered the cancellation.
107 * @example
108 * ```ts
109 * query.cancel()
110 *
111 * try {
112 * await query.promise
113 * } catch (error) {
114 * if (error instanceof CancelledError) {
115 * // the fetch was cancelled, e.g. via `query.cancel()`
116 * }
117 * }
118 * ```
119 */
120export class CancelledError extends Error {
121 revert?: boolean
122 silent?: boolean
123 constructor(options?: CancelOptions) {
124 super('CancelledError')
125 this.revert = options?.revert
126 this.silent = options?.silent
127 }
129​
130/**
131 * Checks whether a value is a `CancelledError`.
132 * @param value - The value to check.
133 * @returns `true` if `value` is a `CancelledError`.
134 * @deprecated Use instanceof `CancelledError` instead.
135 */
136export function isCancelledError(value: any): value is CancelledError {
137 return value instanceof CancelledError
139​
140/**
141 * Creates a retryer, which runs a function and retries it on failure according to the `retry` and
142 * `retryDelay` options. It pauses while the network mode doesn't allow fetching or `canRun` returns
143 * `false`, and can be cancelled. Queries and mutations use it to run their `queryFn` and
144 * `mutationFn`.
145 * @param config - The function to run, the retry options, and the callbacks for failures, pausing,
146 * continuing, and cancellation.
147 * @returns The retryer, whose `promise` settles with the result of the function.
148 */
149export function createRetryer<TData = unknown, TError = DefaultError>(
150 config: RetryerConfig<TData, TError>,
151): Retryer<TData> {
152 let isRetryCancelled = false
153 let failureCount = 0
154 let continueFn: ((value?: unknown) => void) | undefined
155 let status: RetryerStatus = 'pending'
156 let promiseResolve: (data: TData) => void
157 let promiseReject: (error: TError) => void
158​
159 const promise = new Promise<TData>((resolve, reject) => {
160 promiseResolve = resolve
161 promiseReject = reject
162 })
163 promise.catch(noop)
164​
165 const isResolved = () => status !== 'pending'
166​
167 const cancel = (cancelOptions?: CancelOptions): void => {
168 if (!isResolved()) {
169 const error = new CancelledError(cancelOptions) as TError
170 reject(error)
171​
172 config.onCancel?.(error)
173 }
174 }
175 const cancelRetry = () => {
176 isRetryCancelled = true
177 }
178​
179 const continueRetry = () => {
180 isRetryCancelled = false
181 }
182​
183 const canContinue = () =>
184 focusManager.isFocused() &&
185 (config.networkMode === 'always' || onlineManager.isOnline()) &&
186 config.canRun()
187​
188 const canStart = () => canFetch(config.networkMode) && config.canRun()
189​
190 const resolve = (value: any) => {
191 if (!isResolved()) {
192 continueFn?.()
193 status = 'resolved'
194 promiseResolve(value)
195 }
196 }
197​
198 const reject = (value: any) => {
199 if (!isResolved()) {
200 continueFn?.()
201 status = 'rejected'
202 promiseReject(value)
203 }
204 }
205​
206 const pause = (canResume: () => boolean) => {
207 return new Promise((continueResolve) => {
208 continueFn = (value) => {
209 if (isResolved() || canResume()) {
210 continueResolve(value)
211 }
212 }
213 config.onPause?.()
214 }).then(() => {
215 continueFn = undefined
216 if (!isResolved()) {
217 config.onContinue?.()
218 }
219 })
220 }
221​
222 // Create loop function
223 const run = () => {
224 // Do nothing if already resolved
225 if (isResolved()) {
226 return
227 }
228​
229 let promiseOrValue: any
230​
231 // we can re-use config.initialPromise on the first call of run()
232 const initialPromise =
233 failureCount === 0 ? config.initialPromise : undefined
234​
235 // Execute query
236 try {
237 promiseOrValue = initialPromise ?? config.fn()
238 } catch (error) {
239 promiseOrValue = Promise.reject(error)
240 }
241​
242 Promise.resolve(promiseOrValue)
243 .then(resolve)
244 .catch((error) => {
245 // Stop if the fetch is already resolved
246 if (isResolved()) {
247 return
248 }
249​
250 // Do we need to retry the request?
251 const retry = config.retry ?? (isServerEnvironment() ? 0 : 3)
252 const retryDelay = config.retryDelay ?? defaultRetryDelay
253 const delay =
254 typeof retryDelay === 'function'
255 ? retryDelay(failureCount, error)
256 : retryDelay
257 const shouldRetry =
258 retry === true ||
259 (typeof retry === 'number' && failureCount < retry) ||
260 (typeof retry === 'function' && retry(failureCount, error))
261​
262 if (isRetryCancelled || !shouldRetry) {
263 // We are done if the query does not need to be retried
264 reject(error)
265 return
266 }
267​
268 failureCount++
269​
270 // Notify on fail
271 config.onFail?.(failureCount, error)
272​
273 // Delay
274 sleep(delay)
275 // Pause if the document is not visible or when the device is offline
276 .then(() => {
277 return isResolved() || canContinue()
278 ? undefined
279 : pause(canContinue)
280 })
281 .then(() => {
282 if (isRetryCancelled) {
283 reject(error)
284 } else {
285 run()
286 }
287 })
288 })
289 }
290​
291 return {
292 promise,
293 status: () => status,
294 cancel,
295 continue: () => {
296 continueFn?.()
297 return promise
298 },
299 cancelRetry,
300 continueRetry,
301 canStart,
302 start: () => {
303 // Start loop
304 if (canStart()) {
305 run()
306 } else {
307 // Waiting to start (e.g. queued behind a scope) does not depend on focus,
308 // only on the same conditions that allow starting in the first place
309 pause(canStart).then(run)
310 }
311 return promise
312 },
313 }