Skip to content

Commit 088a23b

Browse files
feat: reactive getConfig() (#25)
* feat(getConfig): reactive subscribe via responseNotifier Lets a query make subscribe (or any config field) react to response state surgically. The framework exposes a Notifier on the execution context that fires after each fetch; user code wraps reads of this.response in reactiveSignal + responseNotifier.consume() to opt into per-value reactive tracking. class GetPrice extends RESTQuery { getConfig() { const ok = reactiveSignal(() => { this.responseNotifier.consume(); return this.response?.ok; }).value; return { subscribe: poll({ interval: ok ? 1000 : 5000 }) }; } } getConfig re-runs only when ok actually transitions, not on every fetch. The derived signal's default Object.is equals filters propagation; the outer resolveOptions wrapper stays clean when no deps changed; setupSubscription sees the same subscribe ref and short-circuits. Framework changes: - ctx.response stays a plain field. New ctx.responseNotifier (Notifier) is initialized in createExecutionContext. - RESTQueryAdapter.executeRequest writes both ctx.response and ctx.responseNotifier.notify() after each fetch. - this.config and this.retryConfig on QueryInstance become getters backed by a reactiveSignal wrapping resolveOptions. - setupSubscription ref-checks against lastSubscribeFn before tearing down, so identical-subscribe reads no-op. - lastSubscribeFn cleared on deactivate and on paramsDidChange so rebuilds happen in those cases regardless of ref. Three lifecycle tests in query-stream.test.ts converted from getConfig() returning inline closures to static config = ..., since their getConfig usage was incidental (the tests verify subscribe lifecycle, not dynamic config). The static form gives a stable subscribe ref so the new behavior's ref check naturally short-circuits. Two new tests in poll.test.ts cover the dynamic-interval and stop-on-error patterns end-to-end. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * style: prettier format QueryResult.ts Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * fix: rebuild _resolvedSignal when ctx is recreated Inline arrow functions inside getConfig() lexically capture `this`, so a cached config from a previous ctx will read stale params (and other ctx fields) when invoked under a new ctx. The framework was caching the resolved-options signal across ctx changes, so a query whose params changed kept seeing the old ctx through the cached subscribe closure. Replace _resolvedSignal whenever getOrCreateExecutionContext builds a new ctx. Future reads pick up the new signal and re-call getConfig with the new ctx as `this`, so inline arrows see the new params. This removes the previous test diagnostic conversion to static config: getConfig() returning an inline arrow with this.params access now works correctly across param changes. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test: drop extraneous onEvent rename in query-stream tests Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor: rename setupSubscription to reconcileSubscription Reflects the post-reactive-getConfig role of the function: not a one-shot setup but a reconcile against possibly-changed config. Also drops a vestigial cast on ctx.responseNotifier in the REST adapter and refreshes the _resolvedSignal header comment to name the reactivity contract (upstream notifier, param-change replacement). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: tighten _resolvedOptions comments Drop the redundant inline comment at the reassignment site (the field header already explains it). Refresh the field header to name the mechanism accurately (memoization, not closure capture) and use "such as" rather than "typically" since third-party use cases are open-ended. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: document reactive getConfig and responseNotifier Replace the broken dynamic-poll-interval example with the canonical reactiveSignal + responseNotifier.consume() pattern, add a Notifier row to the RESTQuery instance properties table, and note in the methods table that getConfig is reactive. Also adds a minor changeset. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs: flag reactive getConfig changeset as breaking The prior "implementations that never read reactive state continue to work" line was only true for getConfig that doesn't read mutable execution-context state at all. Direct this.response reads (the canonical pre-existing pattern) silently return stale config under the new memoization model. Spell out the failure mode and the fix. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent 2c5cb61 commit 088a23b

9 files changed

Lines changed: 144 additions & 39 deletions

File tree

‎.changeset/reactive-getconfig.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'fetchium': minor
3+
---
4+
5+
**Breaking:** `getConfig()` is now memoized via a `reactiveSignal` instead of being recomputed on every fetch; it only re-runs when a signal consumed inside notifies. Existing implementations that read mutable execution-context state directly (most commonly `this.response`) silently return stale config after first evaluation, because plain field reads track no signals. To react to new responses, wrap the read in a `reactiveSignal` thunk that consumes the newly-exposed `this.responseNotifier` (a Signalium `Notifier` on the execution context, fired by `RESTQueryAdapter` after each request): `reactiveSignal(() => { this.responseNotifier.consume(); return this.response?.ok; }).value`. `getConfig()` implementations that don't read mutable ctx state continue to work unchanged.

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

Lines changed: 16 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -65,11 +65,11 @@ Base class for all query definitions. Extend this to define custom data-fetching
6565

6666
#### Methods
6767

68-
| Method | Signature | Description |
69-
| ---------------- | ------------------------------------- | ------------------------------------------------------------------------------------------- |
70-
| `getIdentityKey` | `(): unknown` | **(abstract)** Returns a value used to compute the cache/identity key for this query class. |
71-
| `refetch` | `(): void` | Triggers a refetch of this query, bypassing staleTime. |
72-
| `getConfig` | `(): QueryConfigOptions \| undefined` | Optional. Dynamically compute config at execution time. |
68+
| Method | Signature | Description |
69+
| ---------------- | ------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------- |
70+
| `getIdentityKey` | `(): unknown` | **(abstract)** Returns a value used to compute the cache/identity key for this query class. |
71+
| `refetch` | `(): void` | Triggers a refetch of this query, bypassing staleTime. |
72+
| `getConfig` | `(): QueryConfigOptions \| undefined` | Optional. Dynamically compute config at execution time. Reactive: re-runs when any signal consumed inside notifies (e.g. `this.responseNotifier`). |
7373

7474
---
7575

@@ -79,16 +79,17 @@ Convenience base class for REST/JSON queries. Handles URL construction, search p
7979

8080
#### Instance properties
8181

82-
| Property | Type | Default | Description |
83-
| ---------------- | ------------------------------------------------- | ------- | -------------------------------------------------------------------------------------------------------------------------------- |
84-
| `method` | `'GET' \| 'POST' \| 'PUT' \| 'DELETE' \| 'PATCH'` | `'GET'` | HTTP method. |
85-
| `path` | `string \| undefined` | — | URL path. Use template literal interpolation with `this.params` references. |
86-
| `searchParams` | `Record<string, unknown> \| undefined` | — | Query string parameters. |
87-
| `body` | `Record<string, unknown> \| undefined` | — | Request body (JSON-serialized). |
88-
| `headers` | `HeadersInit \| undefined` | — | Custom HTTP headers. |
89-
| `requestOptions` | `QueryRequestOptions \| undefined` | — | Additional fetch options (credentials, mode, baseUrl, etc.). |
90-
| `fetchNext` | `FetchNextConfig \| undefined` | — | Static pagination config. Values can be FieldRefs (e.g. `this.result.nextCursor`). |
91-
| `response` | `Response \| undefined` | — | The raw HTTP `Response` from the last fetch. Set by `RESTQueryAdapter` after each request completes. Available in `getConfig()`. |
82+
| Property | Type | Default | Description |
83+
| ------------------ | ------------------------------------------------- | ------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
84+
| `method` | `'GET' \| 'POST' \| 'PUT' \| 'DELETE' \| 'PATCH'` | `'GET'` | HTTP method. |
85+
| `path` | `string \| undefined` | — | URL path. Use template literal interpolation with `this.params` references. |
86+
| `searchParams` | `Record<string, unknown> \| undefined` | — | Query string parameters. |
87+
| `body` | `Record<string, unknown> \| undefined` | — | Request body (JSON-serialized). |
88+
| `headers` | `HeadersInit \| undefined` | — | Custom HTTP headers. |
89+
| `requestOptions` | `QueryRequestOptions \| undefined` | — | Additional fetch options (credentials, mode, baseUrl, etc.). |
90+
| `fetchNext` | `FetchNextConfig \| undefined` | — | Static pagination config. Values can be FieldRefs (e.g. `this.result.nextCursor`). |
91+
| `response` | `Response \| undefined` | — | The raw HTTP `Response` from the last fetch. Set by `RESTQueryAdapter` after each request completes. Available in `getConfig()`. |
92+
| `responseNotifier` | `Notifier` | — | Notifier fired by `RESTQueryAdapter` after each fetch completes. Consume inside a `reactiveSignal` in `getConfig()` to react to new responses. |
9293

9394
#### `getIdentityKey()` default
9495

‎docs/src/app/core/queries/page.md‎

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,7 @@ The full list of options provided by `RESTQuery` is available below, but there a
9797
1. Parameters should not be connected to the _specifics_ of your Queries. You should be able to change if a parameter is passed as a search param, a path param, a header, or so on, without having to change every _usage_ of the query.
9898
2. More broadly, this distinction allows you to keep your Queries _protocol agnostic_. If you decide to switch from REST to GraphQL or gRPC in the future, none of your usage sites need to change.
9999

100-
The same distinction applies to query _results_. Internally, `RESTQuery` exposes the raw HTTP response on `this.response` after each fetch completes (which can be used in `getConfig()` for things like controlling retry or polling behavior based on whether the response was successful or errored). Externally, the result gets parsed by the `this.result` definition and exposed as the query's value.
100+
The same distinction applies to query _results_. Internally, `RESTQuery` exposes the raw HTTP response on `this.response` after each fetch completes (which can be used reactively in `getConfig()` via `this.responseNotifier` to control retry or polling behavior based on whether the response was successful or errored). Externally, the result gets parsed by the `this.result` definition and exposed as the query's value.
101101

102102
This brings us to the next topic: Using Queries.
103103

@@ -394,9 +394,11 @@ class GetUser extends RESTQuery {
394394
}
395395
```
396396
397-
But let's say we wanted to provide a _dynamic_ polling interval based on the query response. We can't use conditional logic in the _field_ version of `config`, but we can in the _method_ version:
397+
But let's say we wanted to provide a _dynamic_ polling interval based on the query response. We can't use conditional logic in the _field_ version of `config`, but we can in the _method_ version. `getConfig()` is reactive: it re-runs whenever a signal it consumed notifies. `this.responseNotifier` is fired after every fetch, so wrap response reads in a `reactiveSignal` that consumes it:
398398
399399
```ts
400+
import { reactiveSignal } from 'signalium';
401+
400402
class GetUser extends RESTQuery {
401403
params = {
402404
id: t.number,
@@ -409,7 +411,10 @@ class GetUser extends RESTQuery {
409411
};
410412

411413
getConfig() {
412-
const lastResponseOk = this.response?.ok ?? true;
414+
const lastResponseOk = reactiveSignal(() => {
415+
this.responseNotifier.consume();
416+
return this.response?.ok ?? true;
417+
}).value;
413418

414419
// If the last response was ok, poll quickly. Else, poll
415420
// slowly - the service might be having trouble.
@@ -422,6 +427,8 @@ class GetUser extends RESTQuery {
422427
}
423428
```
424429
430+
`this.response` is a plain field, not a signal, so reading it directly inside `getConfig()` would only evaluate once at activation and never re-run as new responses arrive. `responseNotifier.consume()` inside a `reactiveSignal` is what subscribes the outer `getConfig()` to fetch completions.
431+
425432
### Field reference
426433
427434
Here is a quick reference of the fields that are available for configuration on `RESTQuery`:

‎docs/src/app/reference/rest-queries/page.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ This is useful when search params or body fields affect the response but don't a
8686

8787
## Dynamic Config with getConfig()
8888

89-
For runtime-dependent configuration, override `getConfig()`. This is useful when caching, network behavior, or retry logic should vary based on the query's params or other runtime state:
89+
For runtime-dependent configuration, override `getConfig()`. This is useful when caching, network behavior, or retry logic should vary based on the query's params or other runtime state. `getConfig()` is reactive: it re-runs whenever a signal consumed inside notifies. Read `this.response` reactively via `this.responseNotifier` (see [Core: Queries](/core/queries#avoid-arrow-functions-for-dynamic-logic)).
9090

9191
```tsx
9292
class GetDashboard extends RESTQuery {

‎packages/fetchium/src/QueryResult.ts‎

Lines changed: 34 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { relay, type RelayState, ReactivePromise } from 'signalium';
1+
import { relay, reactiveSignal, type RelayState, ReactivePromise, type ReadonlySignal } from 'signalium';
22
import { NetworkMode, type QueryResult, type EntityDef } from './types.js';
33
import {
44
type QueryClient,
@@ -33,16 +33,32 @@ export class QueryInstance<T extends Query> {
3333
private params: QueryParams | undefined = undefined;
3434

3535
private unsubscribe?: () => void = undefined;
36+
private lastSubscribeFn: QueryConfigOptions['subscribe'] = undefined;
3637

3738
private _relayState: RelayState<QueryResult<T>> | undefined = undefined;
3839
private _isActive: boolean = false;
3940
private wasPaused: boolean = false;
4041
private currentParams: QueryParams | undefined = undefined;
4142
private debounceTimer: ReturnType<typeof setTimeout> | undefined = undefined;
4243

43-
/** Resolved per-instance options (depend on actual params). */
44-
config: QueryConfigOptions | undefined = undefined;
45-
retryConfig: ResolvedRetryConfig = resolveRetryConfig(undefined);
44+
// Invalidates on any signal consumed by getConfig() (such as
45+
// responseNotifier, fired by the adapter after each fetch). Param
46+
// changes are handled separately: getOrCreateExecutionContext
47+
// replaces this wholesale to force recomputation against the new ctx.
48+
private _resolvedOptions: ReadonlySignal<{
49+
config: QueryConfigOptions | undefined;
50+
retryConfig: ResolvedRetryConfig;
51+
}> = reactiveSignal(() => this.def.resolveOptions(this._executionCtx!));
52+
53+
get config(): QueryConfigOptions | undefined {
54+
if (this._executionCtx === undefined) return undefined;
55+
return this._resolvedOptions.value.config;
56+
}
57+
58+
get retryConfig(): ResolvedRetryConfig {
59+
if (this._executionCtx === undefined) return resolveRetryConfig(undefined);
60+
return this._resolvedOptions.value.retryConfig;
61+
}
4662

4763
/** Cancels in-flight fetches and retry waits. */
4864
private _abortController: AbortController | undefined = undefined;
@@ -112,6 +128,7 @@ export class QueryInstance<T extends Query> {
112128

113129
this.unsubscribe?.();
114130
this.unsubscribe = undefined;
131+
this.lastSubscribeFn = undefined;
115132

116133
const gcTime = this.config?.gcTime ?? DEFAULT_GC_TIME;
117134
this.queryClient.gcManager.schedule(this.queryKey, gcTime, GcKeyType.Query);
@@ -147,7 +164,7 @@ export class QueryInstance<T extends Query> {
147164
this.queryClient.activateQuery(this);
148165

149166
if (activating && this.updatedAt !== undefined) {
150-
this.setupSubscription();
167+
this.reconcileSubscription();
151168
}
152169

153170
// If the relay shows pending but the abort controller is gone, the
@@ -165,7 +182,9 @@ export class QueryInstance<T extends Query> {
165182
}
166183
}
167184
} else if (paramsDidChange) {
168-
this.setupSubscription();
185+
// Force rebuild: the running subscriber captured the old params.
186+
this.lastSubscribeFn = undefined;
187+
this.reconcileSubscription();
169188
this.runDebounced();
170189
}
171190
};
@@ -250,7 +269,7 @@ export class QueryInstance<T extends Query> {
250269

251270
try {
252271
if (cached !== undefined) {
253-
this.setupSubscription();
272+
this.reconcileSubscription();
254273
}
255274

256275
if (cached === undefined || this.isStale) {
@@ -263,11 +282,14 @@ export class QueryInstance<T extends Query> {
263282
}
264283
}
265284

266-
private setupSubscription(): void {
285+
private reconcileSubscription(): void {
286+
const subscribeFn = this.config?.subscribe;
287+
if (subscribeFn === this.lastSubscribeFn) return;
288+
267289
this.unsubscribe?.();
268290
this.unsubscribe = undefined;
291+
this.lastSubscribeFn = subscribeFn;
269292

270-
const subscribeFn = this.config?.subscribe;
271293
if (!subscribeFn) return;
272294

273295
const ctx = this._executionCtx;
@@ -286,19 +308,13 @@ export class QueryInstance<T extends Query> {
286308
);
287309
this._executionCtx.refetch = () => this.refetch();
288310
this._executionCtx.rawFetchNext = this.def.statics.rawFetchNext;
289-
}
290311

291-
this.resolveAndApplyOptions();
312+
this._resolvedOptions = reactiveSignal(() => this.def.resolveOptions(this._executionCtx!));
313+
}
292314

293315
return this._executionCtx;
294316
}
295317

296-
private resolveAndApplyOptions(): void {
297-
const resolved = this.def.resolveOptions(this._executionCtx!);
298-
this.config = resolved.config;
299-
this.retryConfig = resolved.retryConfig;
300-
}
301-
302318
private async runQuery(): Promise<QueryResult<T>> {
303319
const def = this.def;
304320

@@ -318,9 +334,7 @@ export class QueryInstance<T extends Query> {
318334
const result = this.applyData(freshData, true);
319335
this.saveQueryMetadata();
320336

321-
if (this.unsubscribe === undefined) {
322-
this.setupSubscription();
323-
}
337+
this.reconcileSubscription();
324338

325339
return result;
326340
},

‎packages/fetchium/src/__tests__/poll.test.ts‎

Lines changed: 73 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import { describe, it, expect } from 'vitest';
2+
import { reactiveSignal } from 'signalium';
23
import { RESTQuery } from '../rest/index.js';
34
import { fetchQuery } from '../query.js';
45
import { testWithClient, sleep, setupTestClient } from './utils.js';
@@ -137,6 +138,78 @@ describe('poll() factory', () => {
137138
expect(callCount).toBeGreaterThanOrEqual(3);
138139
});
139140
});
141+
142+
it('honors a state-dependent interval after first fetch resolves', async () => {
143+
const { client, mockFetch } = getClient();
144+
let callCount = 0;
145+
mockFetch.get('/dynamic-interval', () => ({ n: ++callCount }));
146+
147+
class GetDynamicInterval extends RESTQuery {
148+
path = '/dynamic-interval';
149+
result = { n: t.number };
150+
151+
getConfig() {
152+
const ok = reactiveSignal(() => {
153+
this.responseNotifier.consume();
154+
return this.response?.ok;
155+
}).value;
156+
157+
return {
158+
subscribe: poll({ interval: ok ? 100 : 5000 }),
159+
};
160+
}
161+
}
162+
163+
await testWithClient(client, async () => {
164+
const relay = fetchQuery(GetDynamicInterval);
165+
await relay;
166+
const callsAfterFirst = callCount;
167+
168+
// After response.ok=true, interval should be 100ms.
169+
await sleep(350);
170+
171+
expect(callCount).toBeGreaterThanOrEqual(callsAfterFirst + 2);
172+
});
173+
});
174+
175+
it('stops polling when getConfig() switches subscribe to undefined after an error', async () => {
176+
const { client, mockFetch } = getClient();
177+
let callCount = 0;
178+
// First call: 200 OK.
179+
mockFetch.get('/maybe-gone', () => ({ n: ++callCount }));
180+
// Subsequent calls: 404.
181+
mockFetch.get('/maybe-gone', () => ({ n: ++callCount }), { status: 404 });
182+
183+
class GetMaybeGone extends RESTQuery {
184+
path = '/maybe-gone';
185+
result = { n: t.number };
186+
187+
getConfig() {
188+
const is404 = reactiveSignal(() => {
189+
this.responseNotifier.consume();
190+
return this.response?.status === 404;
191+
}).value;
192+
193+
return {
194+
subscribe: is404 ? undefined : poll({ interval: 100 }),
195+
};
196+
}
197+
}
198+
199+
await testWithClient(client, async () => {
200+
const relay = fetchQuery(GetMaybeGone);
201+
await relay;
202+
203+
// Let the 100ms poll tick at least once so a 404 lands.
204+
await sleep(250);
205+
const callsAtTerminal = callCount;
206+
expect(callsAtTerminal).toBeGreaterThan(1);
207+
208+
// After the 404, subscribe becomes undefined; polling should stop.
209+
await sleep(400);
210+
expect(callCount).toBe(callsAtTerminal);
211+
});
212+
});
140213
});
141214

142215
describe('Multiple independent polls', () => {

‎packages/fetchium/src/fieldRef.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { notifier } from 'signalium';
12
import type { QueryContext } from './QueryClient.js';
23

34
// ================================
@@ -191,6 +192,7 @@ export function createExecutionContext<T>(
191192

192193
ctx.params = actualParams;
193194
ctx.context = queryContext;
195+
ctx.responseNotifier = notifier();
194196

195197
for (const [key, method] of Object.entries(methods)) {
196198
ctx[key] = method.bind(ctx);

‎packages/fetchium/src/rest/RESTQuery.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import type { Notifier } from 'signalium';
12
import { Query } from '../query.js';
23
import { RESTQueryAdapter } from './RESTQueryAdapter.js';
34
import type { FetchNextConfig } from '../query-types.js';
@@ -20,6 +21,7 @@ export abstract class RESTQuery extends Query {
2021
fetchNext?: FetchNextConfig;
2122

2223
declare response: Response | undefined;
24+
declare responseNotifier: Notifier;
2325

2426
getIdentityKey(): string {
2527
return `${this.method ?? 'GET'}:${this.path ?? ''}`;

‎packages/fetchium/src/rest/RESTQueryAdapter.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,7 @@ export class RESTQueryAdapter extends QueryAdapter {
182182
});
183183

184184
ctx.response = fetchResponse as unknown as Response;
185+
ctx.responseNotifier.notify();
185186

186187
return fetchResponse.json();
187188
}

0 commit comments

Comments
 (0)