Skip to content

Commit 9063e3d

Browse files
jimmy-phantomclaude
andcommitted
fix(fetchium): re-subscribe TopicQuery on refetch and invalidate
Adds an optional `QueryAdapter.invalidate(ctx)` lifecycle method that drops adapter-internal cached state for a query so the next send() delivers fresh data. TopicQueryAdapter implements it as unsubscribe(topic); stateless adapters like REST don't need to. QueryInstance now calls adapter.invalidate?.(ctx) before each send() on the refetch path, and markStale() kicks a debounced refetch when the relay is currently active so invalidateQueries actually refreshes mounted consumers without requiring a deactivate/reactivate cycle. The TopicQueryAdapter.unsubscribe contract is strengthened to make the "must call clearTopic" obligation explicit, since the base class can't enforce it and any subclass that doesn't clear state will return stale data on resubscribe. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 5b44a7d commit 9063e3d

5 files changed

Lines changed: 167 additions & 2 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"fetchium": patch
3+
---
4+
5+
Fix `TopicQuery` refetch and `invalidateQueries` returning stale data on still-mounted consumers. Adds an optional `QueryAdapter.invalidate(ctx)` lifecycle method (`TopicQueryAdapter` implements it as `unsubscribe(topic)`; stateless adapters like REST don't need it). `QueryInstance` now calls `adapter.invalidate?.(ctx)` before each `send()` on the refetch path, and `markStale()` kicks a debounced refetch when the relay is currently active so `invalidateQueries` actually refreshes mounted consumers without requiring a deactivate/reactivate cycle.

‎packages/fetchium/src/QueryAdapter.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -81,4 +81,11 @@ export abstract class QueryAdapter {
8181
* @param signal AbortSignal to cancel the in-flight request.
8282
*/
8383
sendMutation?(ctx: Mutation, signal: AbortSignal): Promise<unknown>;
84+
85+
/**
86+
* Drop any adapter-internal cached state for this query so the next `send()`
87+
* delivers fresh data. Called by `QueryInstance` on refetch / invalidate.
88+
* Optional — stateless adapters (e.g. REST) don't need to implement this.
89+
*/
90+
invalidate?(ctx: Query): void;
8491
}

‎packages/fetchium/src/QueryResult.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -330,6 +330,11 @@ export class QueryInstance<T extends Query> {
330330
this._fetchNextAbort?.abort();
331331
this._fetchNextAbort = undefined;
332332
this._fetchNextPromise = undefined;
333+
// Drop any adapter-internal cached state for this query so the upcoming
334+
// send() delivers fresh data. No-op for stateless adapters (REST).
335+
const ctx = this.getOrCreateExecutionContext();
336+
const adapter = this.queryClient.getAdapter(this.def.statics.adapterClass);
337+
adapter.invalidate?.(ctx);
333338
this.relayState.setPromise(this.runQuery());
334339
}
335340

@@ -358,6 +363,12 @@ export class QueryInstance<T extends Query> {
358363

359364
markStale(): void {
360365
this.updatedAt = 0;
366+
// If a consumer is currently mounted, kick a refetch so they see fresh
367+
// data without having to deactivate/reactivate. runDebounced bails when a
368+
// fetch is already in flight, so duplicate invalidations dedupe.
369+
if (this._relayState !== undefined && !this.isPaused) {
370+
this.runDebounced();
371+
}
361372
}
362373

363374
get resolvedParams(): QueryParams | undefined {

‎packages/fetchium/src/__tests__/topic-query.test.ts‎

Lines changed: 135 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2140,4 +2140,139 @@ describe('TopicQuery', () => {
21402140
}
21412141
});
21422142
});
2143+
2144+
// ============================================================
2145+
// Section: Refetch
2146+
// ============================================================
2147+
2148+
describe('Refetch', () => {
2149+
it('should re-subscribe and deliver fresh data when __refetch is called on a fulfilled topic', async () => {
2150+
class GetPrices extends MockTopicQuery {
2151+
topic = 'prices:live';
2152+
result = {
2153+
items: t.array(t.entity(TopicPrice)),
2154+
};
2155+
}
2156+
2157+
mockStream.pushTopicData('prices:live', {
2158+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
2159+
});
2160+
2161+
await testWithClient(client, async () => {
2162+
const relay = fetchQuery(GetPrices);
2163+
await relay;
2164+
expect(relay.value!.items[0].value).toBe(50000);
2165+
2166+
const refetchPromise = (relay.value as any).__refetch();
2167+
// Adapter has now torn down the previous subscription and re-subscribed
2168+
// synchronously. Push fresh data to the new subscription.
2169+
mockStream.pushTopicData('prices:live', {
2170+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 60000, change24h: 5.0 }],
2171+
});
2172+
await refetchPromise;
2173+
2174+
expect(relay.value!.items[0].value).toBe(60000);
2175+
expect(relay.value!.items[0].change24h).toBe(5.0);
2176+
});
2177+
});
2178+
2179+
it('should dedupe a __refetch call while a previous fetch is still pending', async () => {
2180+
class GetPrices extends MockTopicQuery {
2181+
topic = 'prices:live';
2182+
result = {
2183+
items: t.array(t.entity(TopicPrice)),
2184+
};
2185+
}
2186+
2187+
mockStream.pushTopicData('prices:live', {
2188+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
2189+
});
2190+
2191+
await testWithClient(client, async () => {
2192+
const relay = fetchQuery(GetPrices);
2193+
await relay;
2194+
2195+
// First refetch suspends until the next push.
2196+
const first = (relay.value as any).__refetch();
2197+
// Second refetch while first is in flight — should resolve with the
2198+
// same data, not trigger a duplicate teardown/resubscribe race.
2199+
const second = (relay.value as any).__refetch();
2200+
2201+
mockStream.pushTopicData('prices:live', {
2202+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 75000, change24h: 1.0 }],
2203+
});
2204+
2205+
const [r1, r2] = await Promise.all([first, second]);
2206+
expect(r1).toBe(r2);
2207+
expect(relay.value!.items[0].value).toBe(75000);
2208+
});
2209+
});
2210+
2211+
it('should keep ongoing mutation events flowing after refetch', async () => {
2212+
class GetPrices extends MockTopicQuery {
2213+
topic = 'prices:live';
2214+
result = {
2215+
items: t.array(t.entity(TopicPrice)),
2216+
};
2217+
}
2218+
2219+
mockStream.pushTopicData('prices:live', {
2220+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
2221+
});
2222+
2223+
await testWithClient(client, async () => {
2224+
const relay = fetchQuery(GetPrices);
2225+
await relay;
2226+
2227+
const refetchPromise = (relay.value as any).__refetch();
2228+
mockStream.pushTopicData('prices:live', {
2229+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 60000, change24h: 3.0 }],
2230+
});
2231+
await refetchPromise;
2232+
2233+
// The new subscription should still receive entity updates.
2234+
await pushUpdateOutsideReactiveContext(mockStream, 'prices:live', {
2235+
type: 'update',
2236+
typename: 'TopicPrice',
2237+
data: { id: '1', value: 65000 },
2238+
});
2239+
2240+
expect(relay.value!.items[0].value).toBe(65000);
2241+
});
2242+
});
2243+
2244+
it('should refetch a still-mounted consumer when invalidateQueries is called', async () => {
2245+
class GetPrices extends MockTopicQuery {
2246+
topic = 'prices:live';
2247+
result = {
2248+
items: t.array(t.entity(TopicPrice)),
2249+
};
2250+
}
2251+
2252+
mockStream.pushTopicData('prices:live', {
2253+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
2254+
});
2255+
2256+
await testWithClient(client, async () => {
2257+
const relay = fetchQuery(GetPrices);
2258+
await relay;
2259+
expect(relay.value!.items[0].value).toBe(50000);
2260+
2261+
// Mounted consumer; no remount, just invalidate.
2262+
client.invalidateQueries([GetPrices]);
2263+
2264+
// markStale schedules the refetch via setTimeout (runDebounced); wait
2265+
// for that to fire so the adapter has torn down the old subscription
2266+
// and re-subscribed before the stream pushes new data.
2267+
await sleep(1);
2268+
2269+
mockStream.pushTopicData('prices:live', {
2270+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 80000, change24h: 4.0 }],
2271+
});
2272+
2273+
await sleep(20);
2274+
expect(relay.value!.items[0].value).toBe(80000);
2275+
});
2276+
});
2277+
});
21432278
});

‎packages/fetchium/src/topic/TopicQueryAdapter.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -32,8 +32,10 @@ export abstract class TopicQueryAdapter extends QueryAdapter {
3232
abstract subscribe(topic: string): void;
3333

3434
/**
35-
* Called when the query deactivates. Implementations should
36-
* tear down any resources for this topic.
35+
* Called when the query deactivates or is invalidated. Implementations
36+
* must tear down resources for this topic AND call `clearTopic(topic)`
37+
* to drop the cached subscription state — otherwise subsequent `send()`
38+
* calls will return stale data instead of re-subscribing.
3739
*/
3840
abstract unsubscribe(topic: string): void;
3941

@@ -89,6 +91,11 @@ export abstract class TopicQueryAdapter extends QueryAdapter {
8991
this._topics.clear();
9092
}
9193

94+
override invalidate(ctx: Query): void {
95+
const topic = (ctx as TopicCtx).topic;
96+
this.unsubscribe(topic);
97+
}
98+
9299
override async send(ctx: Query, _signal: AbortSignal): Promise<unknown> {
93100
const topicCtx = ctx as TopicCtx;
94101
topicCtx._topicAdapter = this;

0 commit comments

Comments
 (0)