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