Open History to see the last commit
1/**
2 * {@link TimeoutManager} does not support passing arguments to the callback.
3 *
4 * `(_: void)` is the argument type inferred by TypeScript's default typings for
5 * `setTimeout(cb, number)`. If we don't accept a single void argument, then
6 * `new Promise(resolve => timeoutManager.setTimeout(resolve, N))` is a type
7 * error.
8 */
9export type TimeoutCallback = (_: void) => void
10β
11/**
12 * Wrapping `setTimeout` is awkward from a typing perspective because platform
13 * typings may extend the return type of `setTimeout`. For example, NodeJS
14 * typings add `NodeJS.Timeout`; but a non-default `timeoutManager` may not be
15 * able to return such a type.
16 */
17export type ManagedTimerId = number | { [Symbol.toPrimitive]: () => number }
18β
19/**
20 * Backend for timer functions.
21 *
22 * Timers are performance-sensitive: short-lived timers (delays under a few
23 * seconds) tend to be latency-sensitive, while long-lived ones may benefit more
24 * from coalescing β batching timers with similar deadlines together β which the
25 * default provider (backed by the platform's global `setTimeout`/`setInterval`)
26 * does not do. A custom provider can implement coalescing, and can also support
27 * delays longer than the ~24-day maximum of the global `setTimeout`.
28 */
29export type TimeoutProvider<TTimerId extends ManagedTimerId = ManagedTimerId> =
30 {
31 /**
32 * Schedules `callback` to run once after `delay` milliseconds, like the
33 * global `setTimeout`.
34 */
35 readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId
36 /** Cancels a timeout scheduled with `setTimeout`. */
37 readonly clearTimeout: (timeoutId: TTimerId | undefined) => void
38β
39 /**
40 * Schedules `callback` to run every `delay` milliseconds, like the global
41 * `setInterval`.
42 */
43 readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId
44 /** Cancels an interval scheduled with `setInterval`. */
45 readonly clearInterval: (intervalId: TTimerId | undefined) => void
46 }
47β
48type SystemTimerId = ReturnType<typeof setTimeout>
49β
50export const defaultTimeoutProvider: TimeoutProvider = {
51 // We need the wrapper function syntax below instead of direct references to
52 // global setTimeout etc.
53 //
54 // BAD: `setTimeout: setTimeout`
55 // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
56 //
57 // If we use direct references here, then anything that wants to spy on or
58 // replace the global setTimeout (like tests) won't work since we'll already
59 // have a hard reference to the original implementation at the time when this
60 // file was imported.
61 setTimeout: (callback, delay) => setTimeout(callback, delay),
62 clearTimeout: (timeoutId) =>
63 clearTimeout(timeoutId as SystemTimerId | undefined),
64β
65 setInterval: (callback, delay) => setInterval(callback, delay),
66 clearInterval: (intervalId) =>
67 clearInterval(intervalId as SystemTimerId | undefined),
68}
69β
70/**
71 * Allows customization of how timeouts are created.
72 *
73 * `@tanstack/query-core` makes liberal use of timeouts to implement `staleTime`
74 * and `gcTime`. The default TimeoutManager provider uses the platform's global
75 * `setTimeout` implementation, which is known to have scalability issues with
76 * thousands of timeouts on the event loop.
77 *
78 * If you hit this limitation, consider providing a custom TimeoutProvider that
79 * coalesces timeouts.
80 */
81export class TimeoutManager implements Omit<TimeoutProvider, 'name'> {
82 // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
83 // type at app boot; and if we leave that type, then any new timer provider
84 // would need to support the default provider's concrete timer ID, which is
85 // infeasible across environments.
86 //
87 // We settle for type safety for the TimeoutProvider type, and accept that
88 // this class is unsafe internally to allow for extension.
89 #provider: TimeoutProvider<any> = defaultTimeoutProvider
90 #providerCalled = false
91β
92 /**
93 * `setTimeoutProvider` can be used to set a custom implementation of the
94 * `setTimeout`, `clearTimeout`, `setInterval`, `clearInterval` functions,
95 * called a `TimeoutProvider`.
96 *
97 * This may be useful if you notice event loop performance issues with
98 * thousands of queries. A custom TimeoutProvider could also support timer
99 * delays longer than the global `setTimeout` maximum delay value of about 24
100 * days.
101 *
102 * It is important to call `setTimeoutProvider` before creating a QueryClient
103 * or queries, so that the same provider is used consistently for all timers
104 * in the application, since different TimeoutProviders cannot cancel each
105 * others' timers.
106 *
107 * @example
108 * ;```ts
109 * import { timeoutManager, QueryClient } from '@tanstack/query-core'
110 * import { CustomTimeoutProvider } from './CustomTimeoutProvider'
111 *
112 * timeoutManager.setTimeoutProvider(new CustomTimeoutProvider())
113 *
114 * export const queryClient = new QueryClient()
115 * ```
116 *
117 * @param provider - The `TimeoutProvider` to use for all timers from now on.
118 */
119 setTimeoutProvider<TTimerId extends ManagedTimerId>(
120 provider: TimeoutProvider<TTimerId>,
121 ): void {
122 if (process.env.NODE_ENV !== 'production') {
123 if (this.#providerCalled && provider !== this.#provider) {
124 // After changing providers, `clearTimeout` will not work as expected for
125 // timeouts from the previous provider.
126 //
127 // Since they may allocate the same timeout ID, clearTimeout may cancel an
128 // arbitrary different timeout, or unexpected no-op.
129 //
130 // We could protect against this by mixing the timeout ID bits
131 // deterministically with some per-provider bits.
132 //
133 // We could internally queue `setTimeout` calls to `TimeoutManager` until
134 // some API call to set the initial provider.
135 console.error(
136 `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
137 { previous: this.#provider, provider },
138 )
139 }
140 }
141β
142 this.#provider = provider
143 if (process.env.NODE_ENV !== 'production') {
144 this.#providerCalled = false
145 }
146 }
147β
148 /**
149 * `setTimeout` schedules a callback to run after approximately `delay`
150 * milliseconds, like the global `setTimeout` function. The callback can be
151 * canceled with `clearTimeout`.
152 *
153 * It returns a timer ID, which may be a number or an object that can be
154 * coerced to a number via `Symbol.toPrimitive`.
155 *
156 * @example
157 * ;```ts
158 * import { timeoutManager } from '@tanstack/query-core'
159 *
160 * const timeoutId = timeoutManager.setTimeout(
161 * () => console.log('ran at:', new Date()),
162 * 1000,
163 * )
164 *
165 * const timeoutIdNumber: number = Number(timeoutId)
166 * ```
167 *
168 * @param callback - The function to call when the timeout elapses.
169 * @param delay - The time to wait before calling `callback`, in milliseconds.
170 * @returns The timer ID, to pass to {@link TimeoutManager#clearTimeout}.
171 */
172 setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId {
173 if (process.env.NODE_ENV !== 'production') {
174 this.#providerCalled = true
175 }
176 return this.#provider.setTimeout(callback, delay)
177 }
178β
179 /**
180 * `clearTimeout` cancels a timeout callback scheduled with `setTimeout`, like
181 * the global `clearTimeout` function. It should be called with a timer ID
182 * returned by `setTimeout`.
183 *
184 * @example
185 * ;```ts
186 * import { timeoutManager } from '@tanstack/query-core'
187 *
188 * const timeoutId = timeoutManager.setTimeout(
189 * () => console.log('ran at:', new Date()),
190 * 1000,
191 * )
192 *
193 * timeoutManager.clearTimeout(timeoutId)
194 * ```
195 *
196 * @param timeoutId - The timer ID returned by `setTimeout`, or `undefined`.
197 */
198 clearTimeout(timeoutId: ManagedTimerId | undefined): void {
199 this.#provider.clearTimeout(timeoutId)
200 }
201β
202 /**
203 * `setInterval` schedules a callback to be called approximately every `delay`
204 * milliseconds, like the global `setInterval` function.
205 *
206 * Like `setTimeout`, it returns a timer ID, which may be a number or an
207 * object that can be coerced to a number via `Symbol.toPrimitive`.
208 *
209 * @example
210 * ;```ts
211 * import { timeoutManager } from '@tanstack/query-core'
212 *
213 * const intervalId = timeoutManager.setInterval(
214 * () => console.log('ran at:', new Date()),
215 * 1000,
216 * )
217 * ```
218 *
219 * @param callback - The function to call on every interval.
220 * @param delay - The time between calls, in milliseconds.
221 * @returns The timer ID, to pass to {@link TimeoutManager#clearInterval}.
222 */
223 setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId {
224 if (process.env.NODE_ENV !== 'production') {
225 this.#providerCalled = true
226 }
227 return this.#provider.setInterval(callback, delay)
228 }
229β
230 /**
231 * `clearInterval` can be used to cancel an interval, like the global
232 * `clearInterval` function. It should be called with an interval ID returned
233 * by `setInterval`.
234 *
235 * @example
236 * ;```ts
237 * import { timeoutManager } from '@tanstack/query-core'
238 *
239 * const intervalId = timeoutManager.setInterval(
240 * () => console.log('ran at:', new Date()),
241 * 1000,
242 * )
243 *
244 * timeoutManager.clearInterval(intervalId)
245 * ```
246 *
247 * @param intervalId - The timer ID returned by `setInterval`, or `undefined`.
248 */
249 clearInterval(intervalId: ManagedTimerId | undefined): void {
250 this.#provider.clearInterval(intervalId)
251 }
252}
253β
254/**
255 * Singleton instance of {@link TimeoutManager}, used throughout TanStack Query
256 * to schedule and cancel timers.
257 */
258export const timeoutManager = new TimeoutManager()
259β
260/**
261 * In many cases code wants to delay to the next event loop tick; this is not
262 * mediated by {@link timeoutManager}.
263 *
264 * This function is provided to make auditing the `tanstack/query-core` for
265 * incorrect use of system `setTimeout` easier.
266 *
267 * @param callback - The function to call on the next event loop tick.
268 */
269export function systemSetTimeoutZero(callback: TimeoutCallback): void {
270 setTimeout(callback, 0)
271}