Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/topic-subscribe-consumer-lifecycle.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'fetchium': patch
---

Fix `TopicQuery` subscribe/unsubscribe to track consumer-read lifecycle instead of the fetch path. Previously, subscribe never fired when `send()` short-circuited (pre-fulfilled topic via `fulfillTopic`, or cache within `staleTime`), but the consumer's unmount would still call unsubscribe and tear down adapter state that was never registered.
13 changes: 10 additions & 3 deletions packages/fetchium/src/QueryResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -268,9 +268,10 @@ export class QueryInstance<T extends Query> {
}

try {
if (cached !== undefined) {
this.reconcileSubscription();
}
// Wire up subscribe before the first fetch so adapters that resolve
// `send()` via stream events (TopicQuery) are on the wire by the time
// `send()` awaits.
this.reconcileSubscription();

if (cached === undefined || this.isStale) {
await sleep(0);
Expand Down Expand Up @@ -308,6 +309,12 @@ export class QueryInstance<T extends Query> {
);
this._executionCtx.refetch = () => this.refetch();
this._executionCtx.rawFetchNext = this.def.statics.rawFetchNext;
// `TopicQuery.getConfig.subscribe` reads `_topicAdapter` from the ctx;
// set it eagerly so subscribe/unsubscribe work on the cache-fresh and
// pre-fulfilled paths where `send()` never runs.
(this._executionCtx as unknown as Record<string, unknown>)._topicAdapter = this.queryClient.getAdapter(
this.def.statics.adapterClass,
);

this._resolvedOptions = reactiveSignal(() => this.def.resolveOptions(this._executionCtx!));
}
Expand Down
43 changes: 43 additions & 0 deletions packages/fetchium/src/__tests__/topic-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -93,13 +93,24 @@ class MockTopicQueryAdapter extends TopicQueryAdapter {
private _unsubscribers = new Map<string, () => void>();
private _topicMeta = new Map<string, { fetchNextUrl?: string }>();

/** Per-topic subscribe call counter, for tests. */
subscribeCalls = new Map<string, number>();
/** Per-topic unsubscribe call counter, for tests. */
unsubscribeCalls = new Map<string, number>();

constructor(stream: MockStream, fetchFn: (url: string, init?: RequestInit) => Promise<Response>) {
super();
this._stream = stream;
this._fetch = fetchFn;
}

/** Test helper: pre-fulfill a topic before any consumer mounts. */
preload(topic: string, data: unknown): void {
this.fulfillTopic(topic, data);
}

subscribe(topic: string): void {
this.subscribeCalls.set(topic, (this.subscribeCalls.get(topic) ?? 0) + 1);
const unsub = this._stream.subscribe(topic, {
onData: (data, meta) => {
if (meta) this._topicMeta.set(topic, meta);
Expand All @@ -116,6 +127,7 @@ class MockTopicQueryAdapter extends TopicQueryAdapter {
}

unsubscribe(topic: string): void {
this.unsubscribeCalls.set(topic, (this.unsubscribeCalls.get(topic) ?? 0) + 1);
this._unsubscribers.get(topic)?.();
this._unsubscribers.delete(topic);
this.clearTopic(topic);
Expand Down Expand Up @@ -546,6 +558,37 @@ describe('TopicQuery', () => {
});
});

it('should pair subscribe and unsubscribe to consumer lifecycle when topic is pre-fulfilled', async () => {
const adapter = client.getAdapter(MockTopicQueryAdapter) as MockTopicQueryAdapter;

class GetPrices extends MockTopicQuery {
topic = 'prices:preloaded';
result = {
items: t.array(t.entity(TopicPrice)),
};
}

adapter.preload('prices:preloaded', {
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
});
expect(adapter.subscribeCalls.get('prices:preloaded')).toBeUndefined();

await testWithClient(client, async () => {
const relay = fetchQuery(GetPrices);
await relay;

expect(relay.isResolved).toBe(true);
expect(relay.value!.items[0].value).toBe(50000);
expect(adapter.subscribeCalls.get('prices:preloaded')).toBe(1);
expect(adapter.unsubscribeCalls.get('prices:preloaded')).toBeUndefined();
});

await sleep(10);

expect(adapter.subscribeCalls.get('prices:preloaded')).toBe(1);
expect(adapter.unsubscribeCalls.get('prices:preloaded')).toBe(1);
});

it('should maintain entity identity across queries sharing entities', async () => {
class GetPricesA extends MockTopicQuery {
topic = 'prices:a';
Expand Down
11 changes: 7 additions & 4 deletions packages/fetchium/src/topic/TopicQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@ export abstract class TopicQuery extends Query {
return {
staleTime: 0,
subscribe: () => {
const adapter = (this as Record<string, any>)._topicAdapter as TopicQueryAdapter | undefined;
const topic = this.getTopic ? this.getTopic() : this.topic;
if (adapter && topic !== undefined) {
adapter.subscribe(topic);
}
return () => {
const adapter = (this as Record<string, any>)._topicAdapter as TopicQueryAdapter | undefined;
const topic = this.getTopic ? this.getTopic() : this.topic;
if (topic !== undefined) {
adapter?.unsubscribe(topic);
if (adapter && topic !== undefined) {
adapter.unsubscribe(topic);
}
};
},
Expand Down
5 changes: 2 additions & 3 deletions packages/fetchium/src/topic/TopicQueryAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,6 @@ export abstract class TopicQueryAdapter extends QueryAdapter {

override async send(ctx: Query, _signal: AbortSignal): Promise<unknown> {
const topicCtx = ctx as TopicCtx;
topicCtx._topicAdapter = this;
const topic = topicCtx.getTopic ? topicCtx.getTopic() : topicCtx.topic;

if (topic === undefined) {
Expand All @@ -112,7 +111,8 @@ export abstract class TopicQueryAdapter extends QueryAdapter {
}
}

// No state yet — create a deferred and subscribe
// No state yet, create a deferred. Subscribe is handled by
// `TopicQuery.getConfig.subscribe`, which runs before this path.
let resolve!: (data: unknown) => void;
let reject!: (error: unknown) => void;
const promise = new Promise<unknown>((res, rej) => {
Expand All @@ -121,7 +121,6 @@ export abstract class TopicQueryAdapter extends QueryAdapter {
});

this._topics.set(topic, { status: 'pending', promise, resolve, reject });
this.subscribe(topic);

return promise;
}
Expand Down
Loading