From d87893435b94efdd470b8fc7b5dcfd74ebb72d9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benjam=C3=ADn=20Vicente?= Date: Sun, 22 Nov 2026 17:09:43 -0300 Subject: [PATCH] feat(query-core)!: gc at latest removal time --- .changeset/gc-removal-time.md | 5 + .../src/__tests__/mutation.test-d.tsx | 21 +-- .../src/__tests__/mutationObserver.test.tsx | 47 ++++++ .../query-core/src/__tests__/query.test-d.tsx | 8 +- .../query-core/src/__tests__/query.test.tsx | 154 ++++++++++++++---- .../src/__tests__/removable.test.tsx | 145 +++++++++++------ packages/query-core/src/mutation.ts | 20 ++- packages/query-core/src/mutationObserver.ts | 13 +- packages/query-core/src/query.ts | 28 ++-- packages/query-core/src/queryObserver.ts | 15 +- packages/query-core/src/removable.ts | 49 +++--- packages/query-core/src/types.ts | 5 +- 12 files changed, 366 insertions(+), 144 deletions(-) create mode 100644 .changeset/gc-removal-time.md diff --git a/.changeset/gc-removal-time.md b/.changeset/gc-removal-time.md new file mode 100644 index 00000000000..ab00eb85a62 --- /dev/null +++ b/.changeset/gc-removal-time.md @@ -0,0 +1,5 @@ +--- +"@tanstack/query-core": major +--- + +Garbage collect a query or mutation at the latest removal time any of its users has scheduled, instead of after the largest `gcTime` it has seen. Remove the `gcTime` property from `Query` and `Mutation`; read `options.gcTime` instead. diff --git a/packages/query-core/src/__tests__/mutation.test-d.tsx b/packages/query-core/src/__tests__/mutation.test-d.tsx index e2e692e6269..e5456cd3cb9 100644 --- a/packages/query-core/src/__tests__/mutation.test-d.tsx +++ b/packages/query-core/src/__tests__/mutation.test-d.tsx @@ -180,7 +180,6 @@ describe('mutation', () => { | 'removeObserver' | 'continue' | 'execute' - | 'gcTime' | 'destroy' >() }) @@ -339,7 +338,7 @@ describe('mutation', () => { }) describe('removeObserver', () => { - it('should take a single observer and return nothing', () => { + it('should take an observer and a gcTime and return nothing', () => { const mutation = Mutation.build< { value: string }, CustomError, @@ -352,7 +351,7 @@ describe('mutation', () => { expectTypeOf(mutation.removeObserver).returns.toEqualTypeOf() expectTypeOf(mutation.removeObserver).parameters.toEqualTypeOf< - [MutationObserver] + [MutationObserver, number | undefined] >() }) }) @@ -410,22 +409,6 @@ describe('mutation', () => { }) }) - describe('gcTime', () => { - it('should be a number inherited from Removable', () => { - const mutation = Mutation.build< - { value: string }, - CustomError, - number, - string - >(new QueryClient(), { - mutationFn: (variables: number) => - Promise.resolve({ value: String(variables) }), - }) - - expectTypeOf(mutation.gcTime).toEqualTypeOf() - }) - }) - describe('destroy', () => { it('should take no arguments and return nothing', () => { const mutation = Mutation.build< diff --git a/packages/query-core/src/__tests__/mutationObserver.test.tsx b/packages/query-core/src/__tests__/mutationObserver.test.tsx index 86037973441..2c26e18b328 100644 --- a/packages/query-core/src/__tests__/mutationObserver.test.tsx +++ b/packages/query-core/src/__tests__/mutationObserver.test.tsx @@ -68,6 +68,53 @@ describe('mutationObserver', () => { expect(queryClient.getMutationCache().findAll()).toHaveLength(0) }) + it('should record the gcTime it used for a mutation when its mutation key changes', async () => { + const observer = new MutationObserver(queryClient, { + mutationKey: createKey(), + mutationFn: (text: string) => sleep(5).then(() => text), + gcTime: 1000, + }) + const unsubscribe = observer.subscribe(vi.fn()) + + observer.mutate('input') + await vi.advanceTimersByTimeAsync(5) + expect(queryClient.getMutationCache().findAll()).toHaveLength(1) + + observer.setOptions({ + mutationKey: createKey(), + mutationFn: (text: string) => sleep(5).then(() => text), + gcTime: Infinity, + }) + + await vi.advanceTimersByTimeAsync(999) + expect(queryClient.getMutationCache().findAll()).toHaveLength(1) + + // Removed after the old key's gcTime, not kept forever with the new key's + await vi.advanceTimersByTimeAsync(1) + expect(queryClient.getMutationCache().findAll()).toHaveLength(0) + + unsubscribe() + }) + + it('should keep a pending mutation until it settles and its gcTime has passed', async () => { + const observer = new MutationObserver(queryClient, { + mutationFn: (text: string) => sleep(45).then(() => text), + gcTime: 10, + }) + const unsubscribe = observer.subscribe(vi.fn()) + + observer.mutate('input') + unsubscribe() + + // Still pending when its gc timer fires at 10, 20, 30 and 40ms, so it is + // rescheduled each time; it settles at 45ms + await vi.advanceTimersByTimeAsync(49) + expect(queryClient.getMutationCache().findAll()).toHaveLength(1) + + await vi.advanceTimersByTimeAsync(1) + expect(queryClient.getMutationCache().findAll()).toHaveLength(0) + }) + it('should reattach the observer to the in-flight mutation when resubscribing', async () => { const mutation = new MutationObserver(queryClient, { mutationFn: (text: string) => sleep(20).then(() => text), diff --git a/packages/query-core/src/__tests__/query.test-d.tsx b/packages/query-core/src/__tests__/query.test-d.tsx index c194f1cf649..d12f306adb0 100644 --- a/packages/query-core/src/__tests__/query.test-d.tsx +++ b/packages/query-core/src/__tests__/query.test-d.tsx @@ -812,7 +812,7 @@ describe('query', () => { }) describe('removeObserver', () => { - it('should take a single observer and return void', () => { + it('should take an observer and a gcTime and return void', () => { const query = queryClient .getQueryCache() .build<{ value: string }, CustomError>(queryClient, { @@ -821,7 +821,10 @@ describe('query', () => { }) expectTypeOf(query.removeObserver).parameters.toEqualTypeOf< - [observer: QueryObserver] + [ + observer: QueryObserver, + gcTime: number | undefined, + ] >() expectTypeOf(query.removeObserver).returns.toEqualTypeOf() }) @@ -952,7 +955,6 @@ describe('query', () => { | 'promise' | 'queryType' | 'resetState' - | 'gcTime' | 'setOptions' | 'setData' | 'setState' diff --git a/packages/query-core/src/__tests__/query.test.tsx b/packages/query-core/src/__tests__/query.test.tsx index 8b09bc4f470..6a134853dd4 100644 --- a/packages/query-core/src/__tests__/query.test.tsx +++ b/packages/query-core/src/__tests__/query.test.tsx @@ -89,31 +89,124 @@ describe('query', () => { } }) - it('should use the longest garbage collection time it has seen', async () => { + it('should be garbage collected at the latest removal time scheduled by its observers', async () => { const key = createKey() - await queryClient - .query({ - queryKey: key, - queryFn: () => 'data', - gcTime: 100, - }) - .catch(noop) - await queryClient - .query({ - queryKey: key, - queryFn: () => 'data', - gcTime: 200, - }) - .catch(noop) - await queryClient - .query({ - queryKey: key, - queryFn: () => 'data', - gcTime: 10, - }) - .catch(noop) + const queryFn = () => 'data' + const observerA = new QueryObserver(queryClient, { + queryKey: key, + queryFn, + gcTime: 5 * 60 * 1000, + }) + const observerB = new QueryObserver(queryClient, { + queryKey: key, + queryFn, + gcTime: 60 * 1000, + }) + const unsubscribeA = observerA.subscribe(noop) + const unsubscribeB = observerB.subscribe(noop) + await vi.advanceTimersByTimeAsync(0) + const query = queryCache.find({ queryKey: key })! + + // 0:30 A becomes inactive: removal at 5:30. Waiting first makes sure this is + // A's own removal time, not the 5:00 recorded when the query was created. + await vi.advanceTimersByTimeAsync(30 * 1000) + unsubscribeA() + + // 1:30 B becomes inactive: 2:30 is earlier, so removal stays at 5:30 + await vi.advanceTimersByTimeAsync(60 * 1000) + unsubscribeB() + + // Not removed at 2:30, as it would be if the last gcTime won + await vi.advanceTimersByTimeAsync(60 * 1000) + expect(queryCache.find({ queryKey: key })).toBe(query) + + // Not removed before 5:30 + await vi.advanceTimersByTimeAsync(3 * 60 * 1000 - 1) + expect(queryCache.find({ queryKey: key })).toBe(query) + + // Removed at 5:30, not at 6:30 as it would be if the largest gcTime won + await vi.advanceTimersByTimeAsync(1) + expect(queryCache.find({ queryKey: key })).toBeUndefined() + }) + + it('should record the gcTime an observer used for a query when it switches to another key', async () => { + const key1 = createKey() + const key2 = createKey() + const queryFn = () => 'data' + const observer = new QueryObserver(queryClient, { + queryKey: key1, + queryFn, + gcTime: 1000, + }) + const unsubscribe = observer.subscribe(noop) + await vi.advanceTimersByTimeAsync(0) + const query1 = queryCache.find({ queryKey: key1 })! + + observer.setOptions({ queryKey: key2, queryFn, gcTime: Infinity }) + + await vi.advanceTimersByTimeAsync(999) + expect(queryCache.find({ queryKey: key1 })).toBe(query1) + + // Removed after key1's gcTime, not kept forever with key2's + await vi.advanceTimersByTimeAsync(1) + expect(queryCache.find({ queryKey: key1 })).toBeUndefined() + + unsubscribe() + }) + + it('should record the gcTime a fetch was started with, even if an observer changes it meanwhile', async () => { + const key = createKey() + // An existing query with a short gcTime, so its creation can't hide the fetch's removal time + const query = queryCache.build(queryClient, { queryKey: key, gcTime: 10 }) + + // The fetch asks for 1000ms and settles at 50ms: removal at 1050ms + const fetch = queryClient.query({ + queryKey: key, + queryFn: () => sleep(50).then(() => 'data'), + gcTime: 1000, + }) + + // While it runs, an observer replaces the query's options with a gcTime of 10ms + const observer = new QueryObserver(queryClient, { + queryKey: key, + enabled: false, + gcTime: 10, + }) + const unsubscribe = observer.subscribe(noop) + + await vi.advanceTimersByTimeAsync(50) + await fetch + // 60ms is earlier, so removal stays at 1050ms + unsubscribe() + + await vi.advanceTimersByTimeAsync(999) + expect(queryCache.find({ queryKey: key })).toBe(query) + + await vi.advanceTimersByTimeAsync(1) + expect(queryCache.find({ queryKey: key })).toBeUndefined() + }) + + it('should keep a later removal time recorded at the end of an earlier fetch', async () => { + const key = createKey() + const queryFn = () => sleep(10).then(() => 'data') + + // The first fetch settles at 10ms: removal at 1010ms + const first = queryClient.query({ queryKey: key, queryFn, gcTime: 1000 }) + await vi.advanceTimersByTimeAsync(10) + await first const query = queryCache.find({ queryKey: key })! - expect(query.gcTime).toBe(200) + + // A second fetch settles at 510ms: 520ms is earlier, so removal stays at 1010ms + await vi.advanceTimersByTimeAsync(490) + const second = queryClient.query({ queryKey: key, queryFn, gcTime: 10 }) + await vi.advanceTimersByTimeAsync(10) + await second + + await vi.advanceTimersByTimeAsync(499) + expect(queryCache.find({ queryKey: key })).toBe(query) + + await vi.advanceTimersByTimeAsync(1) + expect(queryCache.find({ queryKey: key })).toBeUndefined() }) it('should continue retry after focus regain and resolve all promises', async () => { @@ -886,7 +979,9 @@ describe('query', () => { expect(query.getObserversCount()).toBe(0) const notifySpy = vi.spyOn(queryCache, 'notify') - expect(() => query.removeObserver(observer)).not.toThrow() + expect(() => + query.removeObserver(observer, observer.options.gcTime), + ).not.toThrow() expect(notifySpy).not.toHaveBeenCalled() }) @@ -1034,16 +1129,19 @@ describe('query', () => { resetIsServer() }) - it('should use an infinite garbage collection time on the server', () => { + it('should use an infinite garbage collection time on the server', async () => { const resetIsServer = setIsServer(true) try { + const key = createKey() const query = queryCache.build(queryClient, { - queryKey: createKey(), + queryKey: key, queryFn: () => 'data', }) - expect(query.gcTime).toBe(Infinity) + await vi.advanceTimersByTimeAsync(24 * 60 * 60 * 1000) + + expect(queryCache.find({ queryKey: key })).toBe(query) } finally { resetIsServer() } @@ -1497,7 +1595,7 @@ describe('query', () => { const promise1 = query.fetch() await vi.advanceTimersByTimeAsync(10) - query.removeObserver(observer1) + query.removeObserver(observer1, observer1.options.gcTime) const observer2 = new QueryObserver(queryClient, { queryKey: key, diff --git a/packages/query-core/src/__tests__/removable.test.tsx b/packages/query-core/src/__tests__/removable.test.tsx index 9b7fd04085a..021b93299f5 100644 --- a/packages/query-core/src/__tests__/removable.test.tsx +++ b/packages/query-core/src/__tests__/removable.test.tsx @@ -8,12 +8,12 @@ class RemovableTest extends Removable { optionalRemoveSpy = vi.fn<() => void>() // Expose the protected members so they can be exercised directly. - callScheduleGc(): void { - this.scheduleGc() + callScheduleGc(gcTime: number | undefined): void { + this.scheduleGc(gcTime) } - callUpdateGcTime(newGcTime: number | undefined): void { - this.updateGcTime(newGcTime) + callUpdateGcTimestamp(gcTime: number | undefined): void { + this.updateGcTimestamp(gcTime) } callClearGcTimeout(): void { @@ -42,47 +42,38 @@ describe('Removable', () => { let provider: ReturnType beforeEach(() => { + vi.useFakeTimers({ toFake: ['Date', 'performance'] }) provider = createMockProvider() timeoutManager.setTimeoutProvider(provider) }) afterEach(() => { timeoutManager.setTimeoutProvider(defaultTimeoutProvider) + vi.useRealTimers() vi.restoreAllMocks() }) - describe('updateGcTime', () => { + describe('recording removal times', () => { it('should default to 5 minutes when no gcTime is provided on the client', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(undefined) + removable.callScheduleGc(undefined) - expect(removable.gcTime).toBe(5 * 60 * 1000) - }) - - it('should use the provided gcTime when it is larger than the default', () => { - const removable = new RemovableTest() - - removable.callUpdateGcTime(10 * 60 * 1000) - - expect(removable.gcTime).toBe(10 * 60 * 1000) - }) - - it('should use an explicit gcTime even when it is smaller than the default', () => { - const removable = new RemovableTest() - - removable.callUpdateGcTime(1000) - - expect(removable.gcTime).toBe(1000) + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 5 * 60 * 1000, + ) }) - it('should never decrease an already larger gcTime', () => { + it('should use an explicit gcTime', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(10 * 60 * 1000) - removable.callUpdateGcTime(1000) + removable.callScheduleGc(1000) - expect(removable.gcTime).toBe(10 * 60 * 1000) + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 1000, + ) }) it('should default to Infinity on the server', () => { @@ -90,21 +81,49 @@ describe('Removable', () => { try { const removable = new RemovableTest() - removable.callUpdateGcTime(undefined) + removable.callScheduleGc(undefined) - expect(removable.gcTime).toBe(Infinity) + expect(provider.setTimeout).not.toHaveBeenCalled() } finally { resetIsServer() } }) + + it('should keep a later removal time from a longer gcTime recorded before', () => { + const removable = new RemovableTest() + + // 0:00 removal at 5:00 + removable.callUpdateGcTimestamp(5 * 60 * 1000) + // 1:00 removal at 2:00, earlier than 5:00 + vi.advanceTimersByTime(60 * 1000) + removable.callScheduleGc(60 * 1000) + // scheduled at 5:00, so 4 minutes + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 4 * 60 * 1000, + ) + }) + + it('should use a later removal time from a shorter gcTime recorded after', () => { + const removable = new RemovableTest() + + // 0:00 removal at 1:00 + removable.callUpdateGcTimestamp(60 * 1000) + // 2:00 removal at 2:30, later than 1:00 + vi.advanceTimersByTime(2 * 60 * 1000) + removable.callScheduleGc(30 * 1000) + // scheduled at 2:30, so 30 seconds + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 30 * 1000, + ) + }) }) describe('scheduleGc', () => { - it('should schedule optionalRemove after a valid gcTime', () => { + it('should schedule optionalRemove at the recorded removal time', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(1000) - - removable.callScheduleGc() + removable.callScheduleGc(1000) expect(provider.setTimeout).toHaveBeenCalledTimes(1) expect(provider.setTimeout).toHaveBeenCalledWith( @@ -119,33 +138,69 @@ describe('Removable', () => { expect(removable.optionalRemoveSpy).toHaveBeenCalledTimes(1) }) - it('should not schedule when gcTime is not a valid timeout', () => { + it('should not schedule when the removal time is Infinity', () => { const removable = new RemovableTest() - removable.gcTime = Infinity - - removable.callScheduleGc() + removable.callScheduleGc(Infinity) expect(provider.setTimeout).not.toHaveBeenCalled() }) it('should clear a previously scheduled timeout before scheduling a new one', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(1000) - removable.callScheduleGc() - removable.callScheduleGc() + removable.callScheduleGc(1000) + removable.callScheduleGc(1000) // The second schedule clears the first timer before setting a new one. expect(provider.clearTimeout).toHaveBeenCalledWith(123) expect(provider.setTimeout).toHaveBeenCalledTimes(2) }) + + it('should not move the removal time when the system clock changes', () => { + const removable = new RemovableTest() + + removable.callUpdateGcTimestamp(5 * 60 * 1000) + vi.advanceTimersByTime(60 * 1000) + // The system clock jumps back an hour, but only a minute has elapsed + vi.setSystemTime(Date.now() - 60 * 60 * 1000) + removable.callScheduleGc(60 * 1000) + + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 4 * 60 * 1000, + ) + }) + + it('should ignore a NaN gcTime', () => { + const removable = new RemovableTest() + + removable.callUpdateGcTimestamp(1000) + removable.callScheduleGc(NaN) + + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 1000, + ) + }) + + it('should keep an earlier removal time and recover after a NaN gcTime', () => { + const removable = new RemovableTest() + + removable.callUpdateGcTimestamp(5 * 60 * 1000) + removable.callUpdateGcTimestamp(NaN) + removable.callScheduleGc(1000) + + expect(provider.setTimeout).toHaveBeenCalledWith( + expect.any(Function), + 5 * 60 * 1000, + ) + }) }) describe('clearGcTimeout', () => { it('should clear a scheduled timeout', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(1000) - removable.callScheduleGc() + removable.callScheduleGc(1000) removable.callClearGcTimeout() @@ -162,8 +217,7 @@ describe('Removable', () => { it('should not clear the same timeout twice', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(1000) - removable.callScheduleGc() + removable.callScheduleGc(1000) removable.callClearGcTimeout() removable.callClearGcTimeout() @@ -175,8 +229,7 @@ describe('Removable', () => { describe('destroy', () => { it('should clear the scheduled gc timeout', () => { const removable = new RemovableTest() - removable.callUpdateGcTime(1000) - removable.callScheduleGc() + removable.callScheduleGc(1000) removable.destroy() diff --git a/packages/query-core/src/mutation.ts b/packages/query-core/src/mutation.ts index 94d0422be58..0129304dc82 100644 --- a/packages/query-core/src/mutation.ts +++ b/packages/query-core/src/mutation.ts @@ -189,11 +189,11 @@ export class Mutation< this.state = config.state || getDefaultState() this.setOptions(config.options) - this.scheduleGc() + this.scheduleGc(this.options.gcTime) } /** - * Replaces the mutation's options and applies their `gcTime`. + * Replaces the mutation's options. * @internal * @param options - The new mutation options. */ @@ -201,8 +201,6 @@ export class Mutation< options: MutationOptions, ): void { this.options = options - - this.updateGcTime(this.options.gcTime) } /** @@ -237,12 +235,18 @@ export class Mutation< /** * Unsubscribes an observer from the mutation. * @internal - * @param observer - The observer to remove. Garbage collection is scheduled afterwards. + * @param observer - The observer to remove. Garbage collection is scheduled afterwards, with + * `gcTime`. + * @param gcTime - The `gcTime` to record: the observer's current one, or, when it changes its + * mutation key, the one it used for this mutation. */ - removeObserver(observer: MutationObserver): void { + removeObserver( + observer: MutationObserver, + gcTime: number | undefined, + ): void { this.#observers = this.#observers.filter((x) => x !== observer) - this.scheduleGc() + this.scheduleGc(gcTime) this.#mutationCache.notify({ type: 'observerRemoved', @@ -254,7 +258,7 @@ export class Mutation< protected override optionalRemove() { if (!this.#observers.length) { if (this.state.status === 'pending') { - this.scheduleGc() + this.scheduleGc(this.options.gcTime) } else { this.#mutationCache.remove(this) } diff --git a/packages/query-core/src/mutationObserver.ts b/packages/query-core/src/mutationObserver.ts index 698416578bf..6869a61e5a4 100644 --- a/packages/query-core/src/mutationObserver.ts +++ b/packages/query-core/src/mutationObserver.ts @@ -129,7 +129,8 @@ export class MutationObserver< this.#client.getMutationCache().config.mutationKey, ) ) { - this.reset() + // Leave the current mutation with the gcTime used for it, not the new key's + this.#reset(prevOptions.gcTime) } else if (this.#currentMutation?.state.status === 'pending') { this.#currentMutation.setOptions(this.options) } @@ -145,7 +146,7 @@ export class MutationObserver< protected override onUnsubscribe(): void { if (!this.hasListeners()) { - this.#currentMutation?.removeObserver(this) + this.#currentMutation?.removeObserver(this, this.options.gcTime) } } @@ -193,9 +194,13 @@ export class MutationObserver< * ``` */ reset(): void { + this.#reset(this.options.gcTime) + } + + #reset(gcTime: number | undefined): void { // reset needs to remove the observer from the mutation because there is no way to "get it back" // another mutate call will yield a new mutation! - this.#currentMutation?.removeObserver(this) + this.#currentMutation?.removeObserver(this, gcTime) this.#currentMutation = undefined this.#updateResult() this.#notify() @@ -227,7 +232,7 @@ export class MutationObserver< ): Promise { this.#mutateOptions = options - this.#currentMutation?.removeObserver(this) + this.#currentMutation?.removeObserver(this, this.options.gcTime) this.#currentMutation = Mutation.build(this.#client, this.options) diff --git a/packages/query-core/src/query.ts b/packages/query-core/src/query.ts index 3a42b96f0be..b69eb0981d5 100644 --- a/packages/query-core/src/query.ts +++ b/packages/query-core/src/query.ts @@ -314,7 +314,7 @@ export class Query< this.queryHash = config.queryHash this.#initialState = getDefaultState(this.options) this.state = config.state ?? this.#initialState - this.scheduleGc() + this.scheduleGc(this.options.gcTime) } /** * The `meta` object passed in the query's options, if any. @@ -343,7 +343,7 @@ export class Query< } /** - * Replaces the query's options and applies their `gcTime`. If the query has no data yet, it gets + * Replaces the query's options. If the query has no data yet, it gets * the `initialData` from the new options, if any. * @internal * @param options - The new query options, merged on top of the query's default options. @@ -357,8 +357,6 @@ export class Query< this.#queryType = options._type } - this.updateGcTime(this.options.gcTime) - // oxlint-disable-next-line typescript/no-unnecessary-condition -- the constructor calls 'setOptions' before it assigns 'state' if (this.state && this.state.data === undefined) { const defaultState = getDefaultState(this.options) @@ -627,11 +625,16 @@ export class Query< /** * Unsubscribes an observer from the query. * @internal - * @param observer - The observer to remove. When the last observer is removed, the in-flight - * fetch is cancelled if its abort signal was consumed (otherwise only its retries are stopped), - * and garbage collection is scheduled. + * @param observer - The observer to remove. The `gcTime` argument is recorded as a removal time. When the + * last observer is removed, the in-flight fetch is cancelled if its abort signal was consumed + * (otherwise only its retries are stopped), and garbage collection is scheduled. + * @param gcTime - The `gcTime` to record: the observer's current one, or, when it is switching to + * another query, the one it used for this query. */ - removeObserver(observer: QueryObserver): void { + removeObserver( + observer: QueryObserver, + gcTime: number | undefined, + ): void { const index = this.observers.indexOf(observer) if (index !== -1) { this.observers.splice(index, 1) @@ -651,7 +654,9 @@ export class Query< } } - this.scheduleGc() + this.scheduleGc(gcTime) + } else { + this.updateGcTimestamp(gcTime) } this.#cache.notify({ type: 'observerRemoved', query: this, observer }) @@ -914,8 +919,9 @@ export class Query< this.#retryer = undefined this.#fetchPromise = undefined } - // Schedule query gc after fetching - this.scheduleGc() + // Schedule query gc after fetching, with the gcTime this fetch was started with: an + // observer may have replaced the query's options while it was running + this.scheduleGc(context.options.gcTime) } })() this.#fetchPromise = fetchPromise diff --git a/packages/query-core/src/queryObserver.ts b/packages/query-core/src/queryObserver.ts index a1160462f55..1b7cbe0e1ad 100644 --- a/packages/query-core/src/queryObserver.ts +++ b/packages/query-core/src/queryObserver.ts @@ -236,7 +236,7 @@ export class QueryObserver< this.listeners = new Set() this.#clearStaleTimeout() this.#clearRefetchInterval() - this.#currentQuery.removeObserver(this) + this.#currentQuery.removeObserver(this, this.options.gcTime) } /** @@ -281,7 +281,7 @@ export class QueryObserver< ) } - this.#updateQuery() + this.#updateQuery(prevOptions.gcTime) this.#currentQuery.setOptions(this.options) if ( @@ -573,7 +573,7 @@ export class QueryObserver< fetchOptions?: Omit, ): Promise { // Make sure we reference the latest query as the current one might have been removed - this.#updateQuery() + this.#updateQuery(this.options.gcTime) // Fetch let promise: Promise = this.#currentQuery.fetch( @@ -946,7 +946,12 @@ export class QueryObserver< }) } - #updateQuery(): void { + /** + * Switches to the query for the current options, if it changed. + * @param prevGcTime - The `gcTime` this observer used for the previous query, recorded when it + * leaves it. + */ + #updateQuery(prevGcTime: number | undefined): void { const query = this.#client.getQueryCache().build(this.#client, this.options) if (query === this.#currentQuery) { @@ -960,7 +965,7 @@ export class QueryObserver< this.#currentQueryInitialState = query.state if (this.hasListeners()) { - prevQuery?.removeObserver(this) + prevQuery?.removeObserver(this, prevGcTime) query.addObserver(this) } } diff --git a/packages/query-core/src/removable.ts b/packages/query-core/src/removable.ts index d6356c73845..526aea98691 100644 --- a/packages/query-core/src/removable.ts +++ b/packages/query-core/src/removable.ts @@ -5,11 +5,12 @@ import type { ManagedTimerId } from './timeoutManager' /** * The base class for cache entries that are garbage collected once nothing is using them — - * `Query` and `Mutation` both extend it. `gcTime` controls how long an unused entry is kept. + * `Query` and `Mutation` both extend it. The `gcTime` option controls how long an unused entry is + * kept. */ export abstract class Removable { - gcTime!: number #gcTimeout?: ManagedTimerId + #gcAt = 0 /** * Clears the pending garbage collection timeout, so the entry is no longer scheduled for removal. @@ -21,30 +22,40 @@ export abstract class Removable { } /** - * Schedules the entry to be removed from its cache after `gcTime`, replacing any timeout scheduled - * before. Nothing is scheduled if `gcTime` is `Infinity`. + * Records that the entry may be removed `gcTime` from now, keeping the latest removal time + * recorded so far. Without a value, `gcTime` defaults to 5 minutes on the client and `Infinity` on + * the server. A `NaN` is ignored. Removal times use the monotonic `performance.now()` clock, so + * changes to the system clock don't move them. + * @param gcTime - The `gcTime` to record, if any. */ - protected scheduleGc(): void { - this.clearGcTimeout() + protected updateGcTimestamp(gcTime: number | undefined): void { + // Default to 5 minutes (Infinity for server-side) if no gcTime is set + const resolvedGcTime = + gcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000) - if (isValidTimeout(this.gcTime)) { - this.#gcTimeout = timeoutManager.setTimeout(() => { - this.optionalRemove() - }, this.gcTime) + // A NaN would stick through every later Math.max and stop gc for good + if (!Number.isNaN(resolvedGcTime)) { + this.#gcAt = Math.max(this.#gcAt, performance.now() + resolvedGcTime) } } /** - * Updates `gcTime`, keeping the longest one seen so far. Without a value, it defaults to 5 minutes - * on the client and `Infinity` on the server. - * @param newGcTime - The `gcTime` from the latest options, if any. + * Records `gcTime` like `updateGcTimestamp`, then schedules the entry to be removed from its cache + * at the latest removal time recorded, replacing any timeout scheduled before. Nothing is + * scheduled if that time is `Infinity`. + * @param gcTime - The `gcTime` to record, if any. */ - protected updateGcTime(newGcTime: number | undefined): void { - // Default to 5 minutes (Infinity for server-side) if no gcTime is set - this.gcTime = Math.max( - this.gcTime || 0, - newGcTime ?? (isServerEnvironment() ? Infinity : 5 * 60 * 1000), - ) + protected scheduleGc(gcTime: number | undefined): void { + this.clearGcTimeout() + this.updateGcTimestamp(gcTime) + + const timeout = Math.max(0, this.#gcAt - performance.now()) + + if (isValidTimeout(timeout)) { + this.#gcTimeout = timeoutManager.setTimeout(() => { + this.optionalRemove() + }, timeout) + } } /** diff --git a/packages/query-core/src/types.ts b/packages/query-core/src/types.ts index 77f7a14fc46..bfe1d2ccfd2 100644 --- a/packages/query-core/src/types.ts +++ b/packages/query-core/src/types.ts @@ -395,7 +395,8 @@ export interface QueryOptions< /** * The time in milliseconds that unused/inactive cache data remains in memory. * When a query's cache becomes unused or inactive, that cache data will be garbage collected after this duration. - * When different garbage collection times are specified, the longest one will be used. + * When different garbage collection times are specified, the query is removed at the latest + * removal time any of them has scheduled. * Setting it to `Infinity` will disable garbage collection. * * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. @@ -1891,6 +1892,8 @@ export interface MutationOptions< /** * The time in milliseconds that an unused/inactive mutation remains in memory before it is * garbage collected. + * When different garbage collection times are specified, the mutation is removed at the latest + * removal time any of them has scheduled. * * Defaults to `5 * 60 * 1000` (5 minutes), or `Infinity` during SSR. */