Skip to content

Commit 82d67fc

Browse files
perf(fetchium): microtask refetches, prefetch/retain, sync lease starts, shouldRetry hook (#71)
* perf(fetchium): microtask refetches, prefetch/retain leases, useSuspenseQuery Read-path latency: - A refetch with no debounce (stale reactivation, Signal param change) now starts on a microtask instead of setTimeout(0). On React Native a zero timer goes through the native timing module and can wait a frame. Stale reactivation goes from 1 macrotask turn to 0, a param change from 2 to 1 (the remaining one is Signalium's flush), a staggered reactivation from 2 to 1. Zero-delay refetches requested in one task still coalesce. - Invalidation keeps the timer, so a query whose last reader left in the same task is deactivated by Signalium's flush instead of refetched and aborted. New API: - QueryClient.prefetch(QueryClass, params, { ttl }) starts a query and keeps it active for ttl (default 10 s). A reader that mounts inside the window joins it: no second request, data on the first render if it has arrived. - QueryClient.retain(fn, { ttl }) keeps the queries fn reads or returns active until release() or ttl. Built on public Signalium 3.0.3 APIs (watcher + addListener), mirroring the unreleased signalium retain() but bound to the client's QueryClientContext. destroy() releases leases. - useSuspenseQuery (fetchium/react) suspends only on a cold miss, never on a refetch; it decides before subscribing and has the client hold the query while suspended, so a discarded render leaks no watch. A failed cold fetch is thrown to the error boundary; a boundary reset retries. Docs: useQuery's .value never suspended and a rejected .value never threw; the agent doc's `{ suspended }` option never existed. Fixed, and documented the new API. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(fetchium): skip live value notify when a reducer returns the current value A stream reconnect re-delivers every entity as an update event. Entities, writes and live-array membership were already quiet for identical data, but every update event still ran the live value's onUpdate reducer and notified unconditionally, even when the reducer returned the value it was given. Only notify when the reduced value changed, as LiveValueInstance.reset already does. Adds tests pinning identical re-delivery as a no-op across query results, mutation events, topic events and nested entities (no entity notify, no version bump, no write, no live collection notify, no React re-render), and that a real change still notifies exactly once. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * perf(fetchium): start prefetch/retain fetches synchronously A query activated by a read leaves its subscription and first fetch for a microtask, since that work runs adapter and app code that must not run while the relay's computation is the current consumer. Leases paid the same hop: a tap handler that called prefetch() and then navigated had React's sync render microtask (queued by the press) run before the request went out. retain() and prefetch() now collect the queries their first run left a start for (a cold start from initialize(), or a zero-delay runDebounced() refetch on reactivation), and run those starts once the watcher's read has returned, outside any computation. The queued microtask then does nothing. Reader activation is unchanged, as are the stagger queue and debounce timers, the reactivation grace, and sync-store hydration (fresh cached data still issues no request). useSuspenseQuery's internal hold keeps the deferred start, since it leases from inside a render. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): do not retry 4xx client errors; add shouldRetry A failed attempt whose HTTP status is 4xx (except 408 and 429) now fails at once instead of retrying three times. The status comes from the adapter's error response (ctx.response set during the attempt) or from status, statusCode or response.status on the error. QueryClientConfig.shouldRetry and RetryConfig.shouldRetry override the default. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): notify a live value after every reducer run again Skipping the notify when a reducer returned the value it was given broke reducers that mutate in place: one that pushes onto its array and returns it changed the value without notifying, so readers kept the old length. A reference check can't tell that from a no-op, so every routed event that runs a reducer notifies again. Entities, writes and live arrays stay quiet on identical re-delivery. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): suspend on the current fetch when a suspense hold's fetch already settled When the fetch a useSuspenseQuery hold waited for settled and another fetch started before the reader rendered (a refetch from elsewhere, a reconnect), the hold kept handing out its already-resolved promise. React re-rendered at once on each throw, spinning tens of thousands of renders until the new fetch landed. A hold whose fetch settled now starts over on the fetch in flight, with a fresh promise. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): give a remount a new attempt after an abandoned suspense hold failed A hold's failed fetch was kept for SUSPENSE_HOLD_TTL (10 s) whether or not a render ever claimed the error. When the suspended tree was abandoned (the user navigated away) and the fetch then failed, mounting the screen again within that window threw the stale error with no new attempt, though a later mount is promised a fresh one. React retries a suspended render within a task or two of its promise settling, so a failure no render claims within 50 ms now drops the hold. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): resubscribe a never-loaded query before refetching it A TopicQuery whose first fetch was aborted (a prefetch or retain released before the snapshot arrived, now routine) never loaded. Reactivation skipped reconcileSubscription() for a query with no data and restarted the fetch from inside the activating read; TopicQueryAdapter.send() then waited on a deferred that only the torn-down subscription could fulfil. A topic whose snapshot was rejected hung the same way on its next activation. runQuery() now puts the subscription back before sending, and the restart of an aborted fetch takes the relay's promise at once (so the doomed one can't settle it) but runs the subscription and the request on a microtask, or when a lease starts them, outside the read. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * 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> * fix(fetchium): retry every failed attempt by default; keep shouldRetry opt-in Restores the previous retry default: every failed attempt is retried with the existing backoff, whatever its status, including all 4xx responses. The shouldRetry hook stays (QueryClientConfig.shouldRetry and per-query or per-mutation RetryConfig.shouldRetry, with getErrorStatus for reading a status), so an app can opt out per query where it knows a 4xx is permanent. Not retrying 4xx by default removed several seconds of retries that apps were relying on to recover queries that failed before their first load and had no other retry path. The burst of 400s that motivated the change was fixed at its source, so the default no longer needs to guard against it. defaultShouldRetry is removed (it was new in this branch); without a hook, withRetry no longer computes a status at all. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): rewrite this change's changesets for React developers Lead with what changes for an app using useQuery or fetchQuery, keep migration notes to a line or two, and drop internal detail. No source change. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): tighten comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): release a retain() lease when starting one of its queries throws Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * chore(fetchium): cut and shorten comments Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): keep a throwing getConfig() from stalling Signalium's scheduler Options resolution now catches a getConfig() throw and returns default options plus the error, so it never throws inside a Signalium flush. The relay rejects with that error instead, and the start path skips fetching while it is set. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): recover a query once its getConfig() stops throwing A config error now stops the query's running subscription before rejecting. When the error clears, the query refetches and resubscribes on its own. Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): cancel any queued debounced run when starting a fetch immediately Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> * fix(fetchium): pass a mutation response's status to shouldRetry Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
1 parent 46e004f commit 82d67fc

27 files changed

Lines changed: 3063 additions & 93 deletions
Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
---
2+
'fetchium': minor
3+
---
4+
5+
New `queryClient.prefetch(Query, params, { ttl })` and `queryClient.retain(fn, { ttl })` start queries before any component reads them. A component that mounts while one is held reuses its request and renders the data on its first render if it has arrived. Both return a `release` function; `prefetch` lasts 10 seconds by default and `retain` until released.
6+
7+
New `useSuspenseQuery` in `fetchium/react`. It suspends only while the query has no data yet, and sends a failed first fetch to the error boundary.
8+
9+
- A refetch without `debounce` starts on a microtask instead of after `setTimeout(0)`.
10+
- Reading `.value` on a pending or failed query doesn't suspend or throw. The docs said it did.

‎.changeset/should-retry-hook.md‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'fetchium': minor
3+
---
4+
5+
New optional `shouldRetry(error, attempt, status)` on `QueryClientConfig` and on a query's or mutation's `retry` config. Return `false` to stop retrying an error you know is permanent, such as a 404.
6+
7+
`status` is the HTTP status when it is known, and `getErrorStatus` is exported. Without the hook, retries work as before. `retry.retries` is now optional.

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

Lines changed: 45 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ description: API reference for the fetchium React integration.
88
React hooks for using Fetchium queries in React components. Built on top of Signalium's `useReactive` hook.
99

1010
```ts
11-
import { useQuery } from 'fetchium/react';
11+
import { useQuery, useSuspenseQuery } from 'fetchium/react';
1212
```
1313

1414
---
@@ -39,14 +39,14 @@ React hook for fetching a query. Subscribes the component to the query's reactiv
3939

4040
The returned promise object has the following properties:
4141

42-
| Property | Type | Description |
43-
| ------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------- |
44-
| `value` | `QueryResult<T>` | The resolved query result. Reading this while pending triggers React Suspense. Returns a deep clone to avoid accidental mutation of cached entities. |
45-
| `isReady` | `boolean` | `true` once the query has loaded a value at least once. Use for type narrowing on `value`. |
46-
| `isPending` | `boolean` | `true` while the query is loading. Also true during refetches, even if a value already exists. |
47-
| `isResolved` | `boolean` | `true` when the most recent execution resolved successfully. |
48-
| `isRejected` | `boolean` | `true` when the most recent execution failed. |
49-
| `error` | `unknown` | The error if `isRejected` is `true`. |
42+
| Property | Type | Description |
43+
| ------------ | ---------------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
44+
| `value` | `QueryResult<T>` | The resolved query result, or `undefined` until the first value arrives. Returns a deep clone to avoid accidental mutation of cached entities. |
45+
| `isReady` | `boolean` | `true` once the query has loaded a value at least once. Use for type narrowing on `value`. |
46+
| `isPending` | `boolean` | `true` while the query is loading. Also true during refetches, even if a value already exists. |
47+
| `isResolved` | `boolean` | `true` when the most recent execution resolved successfully. |
48+
| `isRejected` | `boolean` | `true` when the most recent execution failed. |
49+
| `error` | `unknown` | The error if `isRejected` is `true`. |
5050

5151
The resolved `QueryResult<T>` includes pagination helpers:
5252

@@ -133,4 +133,39 @@ const SearchResults = component(() => {
133133
- `useQuery` is a thin wrapper around Signalium v3's `useReactive`, which is deep-by-default. It returns a **structurally-shared snapshot** of the query result, so memoized children that receive subtrees as props keep stable references when the underlying data is unchanged.
134134
- Fetchium registers a custom snapshot for entity proxies so the snapshot walks into entities (instead of returning them by reference), giving you correct re-rendering on entity field changes.
135135
- The snapshot is a plain-object copy of the query result to prevent accidental mutation of the entity cache. Use `draft()` from `fetchium` if you need a mutable copy for mutations.
136-
- When used with React Suspense, reading `.value` on a pending query will suspend the component.
136+
- `useQuery` never suspends. Reading `.value` while pending returns `undefined`. Use [`useSuspenseQuery`](#usesuspensequery) to suspend on a cold miss.
137+
138+
---
139+
140+
### `useSuspenseQuery`
141+
142+
```ts
143+
function useSuspenseQuery<T extends Query>(
144+
QueryClass: new () => T,
145+
params?: ExtractQueryParams<T>,
146+
): ReadyReactivePromise<QueryResult<T>>;
147+
```
148+
149+
`useQuery` for components under a React `<Suspense>` boundary. It suspends only on a **cold miss**: the query has never produced a value, neither in memory nor, with a synchronous store, in the persisted cache. Anything else renders at once, including a stale value whose refetch is in flight. Refetches never suspend. Because the hook only returns once a value exists, `value` is always defined.
150+
151+
A cold fetch that fails is thrown to the nearest error boundary. Resetting the boundary (remounting the component) tries the fetch again.
152+
153+
Changing params to ones with no value yet is a cold miss, so the component suspends. Wrap the change in `startTransition` to keep showing the previous result.
154+
155+
Call it from a plain function component. Like `useQuery`, it cannot run inside a Signalium `component()`, which is a reactive context.
156+
157+
```tsx
158+
import { Suspense } from 'react';
159+
import { useSuspenseQuery } from 'fetchium/react';
160+
161+
function UserName({ id }: { id: number }) {
162+
const user = useSuspenseQuery(GetUser, { id });
163+
return <span>{user.value.name}</span>;
164+
}
165+
166+
<Suspense fallback={<Spinner />}>
167+
<UserName id={42} />
168+
</Suspense>;
169+
```
170+
171+
While suspended, the client keeps the query active, since React discards a suspended render without subscribing to anything. The component's commit takes over.

0 commit comments

Comments
 (0)