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

timeoutManager.ts

260 lines9.8 KB

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