Skip to content

Commit 1cc0908

Browse files
perf(fetchium): hydrate synchronously from a sync store and start the first fetch on a microtask
A query activated against SyncQueryStore (MMKV on mobile) resolved with its cached value a microtask after activation, so the first React render showed a loading state and a second, sync-lane render showed the data. The first fetch then waited on setTimeout(0). Apply the cached value in the activating read when the store returns synchronously, and run the subscription and first fetch on a microtask, still outside the relay's computation. AsyncQueryStore keeps its async path. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent ae82eb2 commit 1cc0908

5 files changed

Lines changed: 453 additions & 44 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'fetchium': patch
3+
---
4+
5+
A query whose cached value lives in a synchronous store (`SyncQueryStore`) now resolves with that value in the same read that activates it, instead of a microtask later. A component that mounts such a query renders the cached data on its first render, not a loading state followed by a re-render. The first fetch, and the subscription before it, now start on a microtask instead of after a `setTimeout(0)`, which on device waits a frame or more. Neither runs inside the activating read. `AsyncQueryStore` hydrates on the tick its load resolves, as before.
6+
7+
A cached entry that fails to apply is now treated as a cache miss, so the query fetches. Previously it kept the entry's timestamp, and a fresh-looking timestamp could leave the query pending without fetching.

‎packages/fetchium/src/QueryResult.ts‎

Lines changed: 71 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -15,12 +15,17 @@ import {
1515
queryKeyFor,
1616
CachedQuery,
1717
} from './QueryClient.js';
18+
import type { MaybePromise } from './query-types.js';
1819
import { DEFAULT_GC_TIME } from './stores/shared.js';
1920
import { GcKeyType } from './GcManager.js';
2021
import { Query, QueryDefinition, type ResolvedRetryConfig, resolveRetryConfig } from './query.js';
2122
import { EntityInstance } from './EntityInstance.js';
2223
import { hashValue } from 'signalium/utils';
23-
import { sleep, withRetry } from './retry.js';
24+
import { withRetry } from './retry.js';
25+
26+
function isThenable<T>(value: MaybePromise<T>): value is Promise<T> {
27+
return typeof (value as { then?: unknown } | null | undefined)?.then === 'function';
28+
}
2429

2530
/**
2631
* Thin fetch/relay orchestrator. Data management (proxy, notifier, child refs,
@@ -252,27 +257,75 @@ export class QueryInstance<T extends Query> {
252257
);
253258
}
254259

255-
private async initialize(): Promise<void> {
256-
const qc = this.queryClient;
257-
const state = this.relayState;
258-
260+
/**
261+
* Runs once, from the relay's first activation. That activation happens
262+
* inside the read that watched the relay (for React, during render).
263+
*
264+
* When the store answers synchronously (SyncQueryStore), the cached value is
265+
* applied right here, so the activating read, and the first render, already
266+
* see it. Subscribing and fetching wait for the next microtask: both call
267+
* into adapter and app code that may read or write signals, which must not
268+
* run while the relay's computation is the current consumer. A microtask
269+
* rather than a timer keeps the first fetch off the macrotask queue.
270+
*
271+
* With an asynchronous store (AsyncQueryStore), the cache resolves on a later
272+
* tick, outside the activating read, and everything runs from there.
273+
*/
274+
private initialize(): void {
259275
this.initialized = true;
260276

261-
let cached: CachedQuery | undefined;
277+
let loaded: MaybePromise<CachedQuery | undefined>;
262278

263279
try {
264-
cached = await qc.loadCachedQuery(this.def, this.storageKey);
280+
loaded = this.queryClient.loadCachedQuery(this.def, this.storageKey);
281+
} catch (error) {
282+
this.discardCorruptCache(error);
283+
loaded = undefined;
284+
}
265285

266-
if (cached !== undefined) {
267-
this.updatedAt = cached.updatedAt;
268-
state.value = this.applyData(cached.value, false, false, cached.preloadedEntities);
269-
}
286+
if (isThenable(loaded)) {
287+
loaded.then(
288+
cached => {
289+
this.hydrate(cached);
290+
this.startSubscriptionAndFetch();
291+
},
292+
error => {
293+
this.discardCorruptCache(error);
294+
this.startSubscriptionAndFetch();
295+
},
296+
);
297+
} else {
298+
this.hydrate(loaded);
299+
queueMicrotask(() => this.startSubscriptionAndFetch());
300+
}
301+
}
302+
303+
private discardCorruptCache(error: unknown): void {
304+
const qc = this.queryClient;
305+
qc.store.deleteQuery(this.storageKey);
306+
qc.getContext().log?.warn?.('Failed to initialize query, the query cache may be corrupted or invalid', error);
307+
}
308+
309+
/** Resolves the relay with a cached value. */
310+
private hydrate(cached: CachedQuery | undefined): void {
311+
if (cached === undefined) return;
312+
313+
try {
314+
this.updatedAt = cached.updatedAt;
315+
this.relayState.value = this.applyData(cached.value, false, false, cached.preloadedEntities);
270316
} catch (error) {
271-
qc.store.deleteQuery(this.storageKey);
272-
qc.getContext().log?.warn?.('Failed to initialize query, the query cache may be corrupted or invalid', error);
317+
// Unusable entry: treat it as a miss so the query still fetches, instead
318+
// of trusting a timestamp whose data was never applied.
319+
this.updatedAt = undefined;
320+
this.discardCorruptCache(error);
273321
}
322+
}
274323

275-
if (this.isPaused) {
324+
/** Starts the subscription, then the first fetch if there is no fresh cached value. */
325+
private startSubscriptionAndFetch(): void {
326+
// Deactivated in the meantime: update() fetches on reactivation, since the
327+
// relay is still pending (or stale) with no fetch in flight.
328+
if (!this._isActive || this.isPaused) {
276329
return;
277330
}
278331

@@ -282,13 +335,13 @@ export class QueryInstance<T extends Query> {
282335
// `send()` awaits.
283336
this.reconcileSubscription();
284337

285-
if (cached === undefined || this.isStale) {
286-
await sleep(0);
287-
if (this.isPaused) return;
338+
// Skip if something already started a fetch since activation (refetch()).
339+
const fetchInFlight = this.relayState.isPending && this._abortController !== undefined;
340+
if (this.isStale && !fetchInFlight) {
288341
this.runQueryImmediately();
289342
}
290343
} catch (error) {
291-
state.setError(error as Error);
344+
this.relayState.setError(error as Error);
292345
}
293346
}
294347

‎packages/fetchium/src/__tests__/caching-persistence.test.ts‎

Lines changed: 24 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -230,19 +230,18 @@ describe('Caching and Persistence', () => {
230230

231231
await testWithClient(client, async () => {
232232
const relay = fetchQuery(GetItem, { id: '1' });
233-
// Force a pull
233+
// A synchronous store resolves the relay with the cached value in the
234+
// read that activates it, so awaiting it yields the cached value.
234235
relay.value;
235-
await sleep();
236-
236+
expect(relay.isPending).toBe(false);
237237
expect(relay.value!).toMatchObject({ id: 1, name: 'Cached Data' });
238+
expect(await relay).toMatchObject({ id: 1, name: 'Cached Data' });
238239

239-
const result = await relay;
240-
241-
// Immediate value should be the same as the cached value because we're
242-
// background refetching but have a value that is still valid.
243-
expect(result).toMatchObject({ id: 1, name: 'Cached Data' });
240+
// The background refetch starts a microtask later; the cached value
241+
// stays visible while it is in flight.
242+
await sleep();
243+
expect(relay.isPending).toBe(true);
244244
expect(relay.value!).toMatchObject({ id: 1, name: 'Cached Data' });
245-
expect(relay.isPending).toBe(false);
246245

247246
await sleep(20);
248247

@@ -277,19 +276,18 @@ describe('Caching and Persistence', () => {
277276

278277
await testWithClient(client2, async () => {
279278
const relay = fetchQuery(GetItem);
280-
// Force a pull
279+
// A synchronous store resolves the relay with the cached value in the
280+
// read that activates it, so awaiting it yields the cached value.
281281
relay.value;
282-
await sleep();
283-
282+
expect(relay.isPending).toBe(false);
284283
expect(relay.value!).toMatchObject({ id: 1, value: 'Persistent' });
284+
expect(await relay).toMatchObject({ id: 1, value: 'Persistent' });
285285

286-
const result = await relay;
287-
288-
// Immediate value should be the same as the cached value because we're
289-
// background refetching but have a value that is still valid.
290-
expect(result).toMatchObject({ id: 1, value: 'Persistent' });
286+
// The background refetch starts a microtask later; the cached value
287+
// stays visible while it is in flight.
288+
await sleep();
289+
expect(relay.isPending).toBe(true);
291290
expect(relay.value!).toMatchObject({ id: 1, value: 'Persistent' });
292-
expect(relay.isPending).toBe(false);
293291

294292
await sleep(30);
295293

@@ -380,19 +378,19 @@ describe('Caching and Persistence', () => {
380378

381379
await testWithClient(client, async () => {
382380
const relay = fetchQuery(GetDocument);
383-
// Force a pull
381+
// A synchronous store resolves the relay with the cached value in the
382+
// read that activates it, so awaiting it yields the cached value.
384383
relay.value;
385-
await sleep();
386-
384+
expect(relay.isPending).toBe(false);
387385
expect(relay.value!).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
388-
389386
const result = await relay;
390-
391-
// Immediate value should be the same as the cached value because we're
392-
// background refetching but have a value that is still valid.
393387
expect(result).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
388+
389+
// The background refetch starts a microtask later; the cached value
390+
// stays visible while it is in flight.
391+
await sleep();
392+
expect(relay.isPending).toBe(true);
394393
expect(relay.value!).toMatchObject({ user: { __typename: 'User', id: 1, name: 'Persisted User' } });
395-
expect(relay.isPending).toBe(false);
396394

397395
await sleep(20);
398396

0 commit comments

Comments
 (0)