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 */
22export type TimeoutProvider<TTimerId extends ManagedTimerId = ManagedTimerId> =
23 {
24 readonly setTimeout: (callback: TimeoutCallback, delay: number) => TTimerId
25 readonly clearTimeout: (timeoutId: TTimerId | undefined) => void
26β
27 readonly setInterval: (callback: TimeoutCallback, delay: number) => TTimerId
28 readonly clearInterval: (intervalId: TTimerId | undefined) => void
29 }
30β
31export const defaultTimeoutProvider: TimeoutProvider<
32 ReturnType<typeof setTimeout>
33> = {
34 // We need the wrapper function syntax below instead of direct references to
35 // global setTimeout etc.
36 //
37 // BAD: `setTimeout: setTimeout`
38 // GOOD: `setTimeout: (cb, delay) => setTimeout(cb, delay)`
39 //
40 // If we use direct references here, then anything that wants to spy on or
41 // replace the global setTimeout (like tests) won't work since we'll already
42 // have a hard reference to the original implementation at the time when this
43 // file was imported.
44 setTimeout: (callback, delay) => setTimeout(callback, delay),
45 clearTimeout: (timeoutId) => clearTimeout(timeoutId),
46β
47 setInterval: (callback, delay) => setInterval(callback, delay),
48 clearInterval: (intervalId) => clearInterval(intervalId),
49}
50β
51/**
52 * Allows customization of how timeouts are created.
53 *
54 * @tanstack/query-core makes liberal use of timeouts to implement `staleTime`
55 * and `gcTime`. The default TimeoutManager provider uses the platform's global
56 * `setTimeout` implementation, which is known to have scalability issues with
57 * thousands of timeouts on the event loop.
58 *
59 * If you hit this limitation, consider providing a custom TimeoutProvider that
60 * coalesces timeouts.
61 */
62export class TimeoutManager implements Omit<TimeoutProvider, 'name'> {
63 // We cannot have TimeoutManager<T> as we must instantiate it with a concrete
64 // type at app boot; and if we leave that type, then any new timer provider
65 // would need to support ReturnType<typeof setTimeout>, which is infeasible.
66 //
67 // We settle for type safety for the TimeoutProvider type, and accept that
68 // this class is unsafe internally to allow for extension.
69 #provider: TimeoutProvider<any> = defaultTimeoutProvider
70 #providerCalled = false
71β
72 setTimeoutProvider<TTimerId extends ManagedTimerId>(
73 provider: TimeoutProvider<TTimerId>,
74 ): void {
75 if (process.env.NODE_ENV !== 'production') {
76 if (this.#providerCalled && provider !== this.#provider) {
77 // After changing providers, `clearTimeout` will not work as expected for
78 // timeouts from the previous provider.
79 //
80 // Since they may allocate the same timeout ID, clearTimeout may cancel an
81 // arbitrary different timeout, or unexpected no-op.
82 //
83 // We could protect against this by mixing the timeout ID bits
84 // deterministically with some per-provider bits.
85 //
86 // We could internally queue `setTimeout` calls to `TimeoutManager` until
87 // some API call to set the initial provider.
88 console.error(
89 `[timeoutManager]: Switching provider after calls to previous provider might result in unexpected behavior.`,
90 { previous: this.#provider, provider },
91 )
92 }
93 }
94β
95 this.#provider = provider
96 if (process.env.NODE_ENV !== 'production') {
97 this.#providerCalled = false
98 }
99 }
100β
101 setTimeout(callback: TimeoutCallback, delay: number): ManagedTimerId {
102 if (process.env.NODE_ENV !== 'production') {
103 this.#providerCalled = true
104 }
105 return this.#provider.setTimeout(callback, delay)
106 }
107β
108 clearTimeout(timeoutId: ManagedTimerId | undefined): void {
109 this.#provider.clearTimeout(timeoutId)
110 }
111β
112 setInterval(callback: TimeoutCallback, delay: number): ManagedTimerId {
113 if (process.env.NODE_ENV !== 'production') {
114 this.#providerCalled = true
115 }
116 return this.#provider.setInterval(callback, delay)
117 }
118β
119 clearInterval(intervalId: ManagedTimerId | undefined): void {
120 this.#provider.clearInterval(intervalId)
121 }
122}
123β
124export const timeoutManager = new TimeoutManager()
125β
126/**
127 * In many cases code wants to delay to the next event loop tick; this is not
128 * mediated by {@link timeoutManager}.
129 *
130 * This function is provided to make auditing the `tanstack/query-core` for
131 * incorrect use of system `setTimeout` easier.
132 */
133export function systemSetTimeoutZero(callback: TimeoutCallback): void {
134 setTimeout(callback, 0)
135}