Skip to content

Commit eabd16d

Browse files
fix(fetchium): bound lease lifetimes and clean them up on destroy
- prefetch()'s ttl is now an upper bound. A lease whose fetch was in flight at expiry waited for it to settle, so a fetch that never settles (offline, a topic nobody fulfils) kept the query active forever. It now releases at the ttl, which aborts the fetch only when no reader has joined it. - destroy() cleared leases but not prefetch's separate ttl timer; prefetch now uses retain()'s ttl, which release() clears. - Releasing leases in destroy() deactivates their queries on Signalium's next flush, after gcManager.destroy(), and that deactivation created a fresh GC bucket interval nothing would clear. GcManager.schedule() is a no-op once destroyed. - retain() called inside a reactive computation took a new lease on every rerun. It now warns once in development, starts its fetches on their usual microtask instead of inside the computation, and releases the leases the computation's previous run took. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent efac971 commit eabd16d

5 files changed

Lines changed: 201 additions & 39 deletions

File tree

‎.changeset/fast-delivery-prefetch-retain.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
'fetchium': minor
33
---
44

5-
Adds `queryClient.prefetch(QueryClass, params, { ttl })` and `queryClient.retain(fn, { ttl })`. Both keep queries active without a reader and return a `release` function. A reader that mounts while the lease is held joins the running query: no second request, and the data on its first render if it has arrived. `prefetch` defaults to a 10 s lease (`DEFAULT_PREFETCH_TTL`) and lets a fetch in flight at expiry finish; `retain` lasts until released.
5+
Adds `queryClient.prefetch(QueryClass, params, { ttl })` and `queryClient.retain(fn, { ttl })`. Both keep queries active without a reader and return a `release` function. A reader that mounts while the lease is held joins the running query: no second request, and the data on its first render if it has arrived. `prefetch` defaults to a 10 s lease (`DEFAULT_PREFETCH_TTL`), an upper bound even with a fetch in flight; `retain` lasts until released.
66

77
Adds `useSuspenseQuery` to `fetchium/react`. It suspends only when the query has never produced a value (in memory or in a synchronous store), never for a refetch, and throws a failed cold fetch to the error boundary.
88

‎docs/src/app/api/fetchium/page.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -252,7 +252,7 @@ new QueryClient(config: QueryClientConfig)
252252

253253
#### `prefetch` and `retain`
254254

255-
Both take a lease: the queries stay active (fetched, subscribed, exempt from GC) without a component reading them. A reader that mounts while the lease is held joins the active query, so it starts no request of its own and renders the data on its first render if it has arrived. Both return an idempotent `release` function. Releasing never interrupts other readers; once the last one goes, the query deactivates and its `gcTime` starts as usual. Calling `release` while a fetch is in flight, with no reader, aborts that fetch. A `prefetch` whose `ttl` runs out mid-fetch instead waits for the fetch to settle before letting go.
255+
Both take a lease: the queries stay active (fetched, subscribed, exempt from GC) without a component reading them. A reader that mounts while the lease is held joins the active query, so it starts no request of its own and renders the data on its first render if it has arrived. Both return an idempotent `release` function. Releasing never interrupts other readers; once the last one goes, the query deactivates and its `gcTime` starts as usual. Calling `release` while a fetch is in flight, with no reader, aborts that fetch. A `ttl` is an upper bound: the lease goes when it runs out even if the fetch is still in flight (offline, or a topic never fulfilled), which aborts the fetch unless a reader has joined it. Call `retain` and `prefetch` from event handlers or effects, not from inside a reactive computation; called from one, they warn in development and keep only the leases from the computation's latest run.
256256

257257
`prefetch` is for the moment a user commits to a navigation, such as a tap. Call it in the handler, before navigating:
258258

‎packages/fetchium/src/GcManager.ts‎

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -62,14 +62,16 @@ export class GcManager {
6262
private _nextTickScheduled = false;
6363
private _onEvict: (key: number, type: GcKeyType) => void;
6464
private _multiplier: number;
65+
/** Set by destroy(). Queries that deactivate afterwards schedule nothing. */
66+
private _destroyed = false;
6567

6668
constructor(onEvict: (key: number, type: GcKeyType) => void, multiplier: number = 1) {
6769
this._onEvict = onEvict;
6870
this._multiplier = multiplier;
6971
}
7072

7173
schedule(key: number, gcTime: number, type: GcKeyType): void {
72-
if (gcTime === Infinity) return;
74+
if (gcTime === Infinity || this._destroyed) return;
7375

7476
if (gcTime === 0) {
7577
const { _nextTickEntries } = this;
@@ -111,6 +113,7 @@ export class GcManager {
111113
};
112114

113115
destroy(): void {
116+
this._destroyed = true;
114117
const { _buckets, _nextTickEntries } = this;
115118
for (const bucket of _buckets.values()) {
116119
bucket.destroy();

‎packages/fetchium/src/QueryClient.ts‎

Lines changed: 57 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { context, watcher, withContexts, ReactivePromise, ReactiveTask, type Context } from 'signalium';
1+
import { context, signal, watcher, withContexts, ReactivePromise, ReactiveTask, type Context } from 'signalium';
22
import { hashValue } from 'signalium/utils';
33
import {
44
EntityDef,
@@ -188,6 +188,12 @@ export class QueryClient {
188188
* starts them before returning. See `retain()`.
189189
*/
190190
private leaseStarts: Set<QueryInstance<any>> | undefined = undefined;
191+
/**
192+
* Leases taken by `retain()` calls inside a reactive computation, by the
193+
* computation, with the run that took them. See `retain()`.
194+
*/
195+
private reactiveLeases = new WeakMap<object, { run: number; releases: Array<() => void> }>();
196+
private warnedReactiveRetain = false;
191197
/** Leases taken by `useSuspenseQuery` for cold misses, by query instance key. */
192198
private suspenseHolds = new Map<number, SuspenseHold>();
193199

@@ -436,10 +442,32 @@ export class QueryClient {
436442
* query that depends on another's result (`fn` reads an id, then fetches by
437443
* it) starts once that result arrives, as with any reader. Call `retain`
438444
* from an event handler or effect, not from inside a reactive computation:
439-
* starting a fetch runs adapter code.
445+
* starting a fetch runs adapter code, and a computation that reruns would
446+
* take a new lease on every run. Called from one anyway, it warns in
447+
* development, starts its fetches on their usual microtask, and releases the
448+
* leases the computation's previous run took.
440449
*/
441450
retain(fn: () => unknown, options?: RetainOptions): () => void {
442-
return this.lease(fn, options, true);
451+
const owner = currentReactiveOwner();
452+
if (owner === undefined) return this.lease(fn, options, true);
453+
454+
if (IS_DEV && !this.warnedReactiveRetain) {
455+
this.warnedReactiveRetain = true;
456+
this.context.log?.warn?.(
457+
'QueryClient.retain() (or prefetch()) was called inside a reactive computation. Call it from an event handler or effect instead.',
458+
);
459+
}
460+
461+
const release = this.lease(fn, options, false);
462+
const previous = this.reactiveLeases.get(owner.ref);
463+
if (previous === undefined || previous.run !== owner.run) {
464+
this.reactiveLeases.set(owner.ref, { run: owner.run, releases: [release] });
465+
// After taking the new lease, so queries both runs read stay active.
466+
if (previous !== undefined) for (const prior of previous.releases) prior();
467+
} else {
468+
previous.releases.push(release);
469+
}
470+
return release;
443471
}
444472

445473
/**
@@ -494,8 +522,10 @@ export class QueryClient {
494522
/**
495523
* Starts `QueryClass` with `params` now and keeps it active for `ttl`
496524
* milliseconds (default {@link DEFAULT_PREFETCH_TTL}), or until the returned
497-
* `release` is called. A fetch still in flight when `ttl` runs out is let
498-
* finish before the lease goes; `release()` lets go at once. Meant for the moment a user commits to a navigation
525+
* `release` is called. The `ttl` is an upper bound: the lease goes when it
526+
* runs out even if the fetch is still in flight (offline, or a topic that is
527+
* never fulfilled), which aborts that fetch unless a reader has joined it.
528+
* Meant for the moment a user commits to a navigation
499529
* (a tap): the destination's reader, mounting within the window, reuses the
500530
* in-flight or finished fetch instead of starting its own, and renders the
501531
* data on its first render if it has arrived.
@@ -510,27 +540,9 @@ export class QueryClient {
510540
options?: PrefetchOptions,
511541
): () => void {
512542
const def = QueryDefinition.for(QueryClass);
513-
let relay: QueryPromise<T> | undefined;
514-
const release = this.retain(() => (relay = this.getQuery(def, params as QueryParams | undefined)));
515-
516-
const ttl = options?.ttl ?? DEFAULT_PREFETCH_TTL;
517-
if (Number.isFinite(ttl)) {
518-
const timer = setTimeout(
519-
() => {
520-
// Expiring mid-fetch would abort a request that is about to land:
521-
// hold until it settles. An explicit release() still lets go at once.
522-
if (relay?.isPending) relay.then(release, release);
523-
else release();
524-
},
525-
Math.max(0, ttl),
526-
);
527-
return () => {
528-
clearTimeout(timer);
529-
release();
530-
};
531-
}
532-
533-
return release;
543+
return this.retain(() => this.getQuery(def, params as QueryParams | undefined), {
544+
ttl: options?.ttl ?? DEFAULT_PREFETCH_TTL,
545+
});
534546
}
535547

536548
/**
@@ -955,6 +967,25 @@ export const QueryClientContext: Context<QueryClient | undefined> = context<Quer
955967

956968
const noop = (): void => {};
957969

970+
/**
971+
* The reactive computation (and its run) currently executing, if any. Signalium
972+
* has no public API for this: a signal read records its consumer, so read a
973+
* throwaway signal and look at what it recorded. Undefined when the shape
974+
* isn't the expected one.
975+
*/
976+
function currentReactiveOwner(): { ref: object; run: number } | undefined {
977+
try {
978+
const probe = signal(0);
979+
void probe.value;
980+
const subs = (probe as unknown as { _subs?: Map<object, number> })._subs;
981+
if (!(subs instanceof Map) || subs.size === 0) return undefined;
982+
const [ref, run] = subs.entries().next().value!;
983+
return typeof ref === 'object' && ref !== null && typeof run === 'number' ? { ref, run } : undefined;
984+
} catch {
985+
return undefined;
986+
}
987+
}
988+
958989
/**
959990
* Reads the query promises `retain`'s callback returned, so the lease's
960991
* watcher depends on them and keeps them active. `isReady` changes once per

‎packages/fetchium/src/__tests__/retain-prefetch.test.ts‎

Lines changed: 138 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,14 @@
11
/* eslint-disable @typescript-eslint/no-unused-expressions */
2-
import { describe, it, expect, afterEach } from 'vitest';
3-
import { signal, watcher, withContexts } from 'signalium';
2+
import { describe, it, expect, afterEach, vi } from 'vitest';
3+
import { reactive, signal, watcher, withContexts } from 'signalium';
44
import { MemoryPersistentStore, SyncQueryStore } from '../stores/sync.js';
55
import { QueryClient, QueryClientContext, DEFAULT_PREFETCH_TTL } from '../QueryClient.js';
66
import { RESTQuery, RESTQueryAdapter } from '../rest/index.js';
77
import { t } from '../typeDefs.js';
88
import { fetchQuery, QueryDefinition } from '../query.js';
99
import type { MutationEvent } from '../types.js';
10+
import { GcManager, type GcKeyType } from '../GcManager.js';
11+
import { NetworkManager } from '../NetworkManager.js';
1012
import { createMockFetch, sleep } from './utils.js';
1113

1214
/**
@@ -266,21 +268,69 @@ describe('client.prefetch()', () => {
266268
unsub();
267269
});
268270

269-
it('a ttl that runs out mid-fetch waits for the fetch instead of aborting it', async () => {
271+
it('a ttl that runs out mid-fetch releases the lease, aborting the fetch with no reader', async () => {
270272
const { client, mockFetch } = setup();
271273
mockFetch.reset();
272274
mockFetch.get('/streamed', { n: 9 }, { delay: 40 });
273275
client.prefetch(GetStreamed, undefined, { ttl: 10 });
274276
await sleep(25);
275-
// Past the ttl, before the response (40 ms): still held, request not cancelled.
276-
expect(unsubscribed).toBe(0);
277-
expect(mockFetch.calls[0].options.signal?.aborted).toBe(false);
277+
// The ttl is an upper bound: past it, before the response, the lease is gone.
278+
expect(unsubscribed).toBe(1);
279+
expect(mockFetch.calls[0].options.signal?.aborted).toBe(true);
280+
await sleep(40);
281+
});
282+
283+
it('a ttl that runs out mid-fetch leaves a reader that joined the fetch running', async () => {
284+
const { client, mockFetch } = setup();
285+
mockFetch.reset();
286+
mockFetch.get('/streamed', { n: 9 }, { delay: 40 });
287+
client.prefetch(GetStreamed, undefined, { ttl: 10 });
288+
await sleep(5);
289+
const { w, unsub } = mountReader(client, () => fetchQuery(GetStreamed).value);
278290
await sleep(60);
279291
expect(mockFetch.calls).toHaveLength(1);
280-
// The fetch landed (an aborted one applies nothing), then the lease went.
281-
const relay = client.getQuery(QueryDefinition.for(GetStreamed), undefined);
282-
expect(relay.value).toMatchObject({ n: 9 });
283-
expect(unsubscribed).toBe(1);
292+
expect(mockFetch.calls[0].options.signal?.aborted).toBe(false);
293+
expect(w.value).toMatchObject({ n: 9 });
294+
unsub();
295+
});
296+
297+
it('a ttl caps a lease whose fetch never settles', async () => {
298+
vi.useFakeTimers();
299+
try {
300+
const networkManager = new NetworkManager(false);
301+
const client = new QueryClient({
302+
store: new SyncQueryStore(new MemoryPersistentStore()),
303+
adapters: [new RESTQueryAdapter({ fetch: createMockFetch() as any, baseUrl: 'http://localhost' })],
304+
networkManager,
305+
});
306+
clients.push(client);
307+
// Offline: the relay stays pending.
308+
client.prefetch(GetStreamed, undefined, { ttl: 1_000 });
309+
await vi.advanceTimersByTimeAsync(10);
310+
expect(client.getQuery(QueryDefinition.for(GetStreamed), undefined).isPending).toBe(true);
311+
await vi.advanceTimersByTimeAsync(2_000);
312+
expect((client as unknown as { leases: Set<unknown> }).leases.size).toBe(0);
313+
client.destroy();
314+
clients = [];
315+
await vi.advanceTimersByTimeAsync(1_000);
316+
} finally {
317+
vi.useRealTimers();
318+
}
319+
});
320+
321+
it('destroy() clears the ttl timer', async () => {
322+
vi.useFakeTimers();
323+
try {
324+
const { client } = setup();
325+
client.prefetch(GetItem, undefined, { ttl: 60_000 });
326+
await vi.advanceTimersByTimeAsync(20);
327+
client.destroy();
328+
clients = [];
329+
await vi.advanceTimersByTimeAsync(50);
330+
expect(vi.getTimerCount()).toBe(0);
331+
} finally {
332+
vi.useRealTimers();
333+
}
284334
});
285335

286336
it('defaults ttl to DEFAULT_PREFETCH_TTL', () => {
@@ -441,6 +491,84 @@ describe('client.retain()', () => {
441491
expect(unsubscribed).toBe(1);
442492
});
443493

494+
it('destroy() leaves no GC timer behind for the queries it releases', async () => {
495+
const created: unknown[] = [];
496+
const cleared = new Set<unknown>();
497+
const realSetInterval = globalThis.setInterval;
498+
const realClearInterval = globalThis.clearInterval;
499+
vi.spyOn(globalThis, 'setInterval').mockImplementation(((fn: () => void, ms?: number) => {
500+
const id = realSetInterval(fn, ms);
501+
created.push(id);
502+
return id;
503+
}) as typeof setInterval);
504+
vi.spyOn(globalThis, 'clearInterval').mockImplementation(((id: ReturnType<typeof setInterval>) => {
505+
cleared.add(id);
506+
realClearInterval(id);
507+
}) as typeof clearInterval);
508+
509+
try {
510+
const { client } = setup();
511+
// A real GcManager: the tests' window-less environment gets the no-op one.
512+
(client as unknown as { gcManager: GcManager }).gcManager = new GcManager(
513+
(client as unknown as { handleEviction: (key: number, type: GcKeyType) => void }).handleEviction,
514+
1,
515+
);
516+
client.retain(() => fetchQuery(GetItem));
517+
await sleep(20);
518+
client.destroy();
519+
clients = [];
520+
// The released query deactivates on Signalium's next flush, after destroy().
521+
await sleep(50);
522+
const leaked = created.filter(id => !cleared.has(id));
523+
for (const id of leaked) realClearInterval(id as ReturnType<typeof setInterval>);
524+
expect(leaked).toHaveLength(0);
525+
} finally {
526+
vi.restoreAllMocks();
527+
}
528+
});
529+
530+
it('warns, and keeps one lease, when called from a reactive computation that reruns', async () => {
531+
const warn = vi.fn();
532+
const mockFetch = createMockFetch();
533+
mockFetch.get('/item', () => ({ n: 1 }));
534+
const client = new QueryClient({
535+
store: new SyncQueryStore(new MemoryPersistentStore()),
536+
adapters: [new RESTQueryAdapter({ fetch: mockFetch as any, baseUrl: 'http://localhost' })],
537+
log: { warn },
538+
});
539+
clients.push(client);
540+
const leases = (client as unknown as { leases: Set<unknown> }).leases;
541+
542+
const tick = signal(0);
543+
const computation = reactive(() => {
544+
const value = tick.value;
545+
client.retain(() => fetchQuery(GetItem));
546+
return value;
547+
});
548+
const { w, unsub } = mountReader(client, () => computation());
549+
expect(warn).toHaveBeenCalledTimes(1);
550+
for (let i = 1; i <= 5; i++) {
551+
tick.value = i;
552+
w.value;
553+
await sleep(10);
554+
}
555+
expect(leases.size).toBe(1);
556+
expect(mockFetch.calls).toHaveLength(1);
557+
unsub();
558+
});
559+
560+
it('does not warn when called outside a reactive computation', () => {
561+
const warn = vi.fn();
562+
const client = new QueryClient({
563+
store: new SyncQueryStore(new MemoryPersistentStore()),
564+
adapters: [new RESTQueryAdapter({ fetch: createMockFetch() as any, baseUrl: 'http://localhost' })],
565+
log: { warn },
566+
});
567+
clients.push(client);
568+
client.retain(() => fetchQuery(GetItem))();
569+
expect(warn).not.toHaveBeenCalled();
570+
});
571+
444572
it('releases and rethrows when the callback throws', () => {
445573
const { client } = setup();
446574
expect(() =>

0 commit comments

Comments
 (0)