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