Open History to see the last commit
1import { timeoutManager } from './timeoutManager'
2import { isServer as isServerEnvironment } from './environmentManager'
3import { isValidTimeout } from './utils'
4import type { ManagedTimerId } from './timeoutManager'
5β
6/**
7 * The base class for cache entries that are garbage collected once nothing is
8 * using them β `Query` and `Mutation` both extend it. `gcTime` controls how
9 * long an unused entry is kept.
10 */
11export abstract class Removable {
12 gcTime!: number
13 #gcTimeout?: ManagedTimerId
14β
15 /**
16 * Clears the pending garbage collection timeout, so the entry is no longer
17 * scheduled for removal. A subclass may override this to release what it
18 * holds on to as well β `Query` also cancels any in-flight fetch.
19 */
20 destroy(): void {
21 this.clearGcTimeout()
22 }
23β
24 /**
25 * Schedules the entry to be removed from its cache after `gcTime`, replacing
26 * any timeout scheduled before. Nothing is scheduled if `gcTime` is
27 * `Infinity`.
28 */
29 protected scheduleGc(): void {
30 this.clearGcTimeout()
31β
32 if (isValidTimeout(this.gcTime)) {
33 this.#gcTimeout = timeoutManager.setTimeout(() => {
34 this.optionalRemove()
35 }, this.gcTime)
36 }
37 }
38β
39 /**
40 * Updates `gcTime`, keeping the longest one seen so far. Without a value, it
41 * defaults to 5 minutes on the client and `Infinity` on the server.
42 *
43 * @param newGcTime - The `gcTime` from the latest options, if any.
44 */
45 protected updateGcTime(newGcTime: number | undefined): void {
46 // Default to 5 minutes (Infinity for server-side) if no gcTime is set
47 this.gcTime = Math.max(
48 this.gcTime || 0,
49 newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000),
50 )
51 }
52β
53 /** Cancels the scheduled removal, if there is one. */
54 protected clearGcTimeout() {
55 if (this.#gcTimeout !== undefined) {
56 timeoutManager.clearTimeout(this.#gcTimeout)
57 this.#gcTimeout = undefined
58 }
59 }
60β
61 /**
62 * Called when the garbage collection timeout fires. Subclasses remove the
63 * entry from its cache unless it is still in use, e.g. because it has
64 * observers.
65 */
66 protected abstract optionalRemove(): void
67}