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

timeoutManager.ts

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