Skip to content
Merged
Show file tree
Hide file tree
Changes from 10 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
10 changes: 10 additions & 0 deletions .changeset/quiet-reactivation.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
---
'fetchium': minor
---

New `QueryClient` options that make coming back to a screen, or to the app, quieter. All are off by default.

- `reactivationGraceMs` (also per query): a query that mounts again with data younger than this doesn't refetch. Data a live subscription kept current counts as fresh.
- `reactivationStaggerMs`: refetches from queries that mount together are spread across this window instead of all starting at once.
- `activity: { isActive(), subscribe(listener) }`: `poll()` stops while the app is inactive and resumes when it's active again. On React Native, wrap `AppState`. `pollResumeJitterMs` spreads out polls that were overdue on resume.
- Pass the topic to `TopicQueryAdapter.sendMutationEvent(event, topic)` so that topic's query counts the push as fresh data.
49 changes: 30 additions & 19 deletions docs/src/app/api/fetchium/page.md

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions docs/src/app/core/streaming/page.md
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ class MyStreamAdapter extends TopicQueryAdapter {
this.rejectTopic(msg.topic, new Error(msg.error));
} else if (msg.type === 'event') {
// Ongoing mutation event
this.sendMutationEvent(msg.event);
this.sendMutationEvent(msg.event, msg.topic);
}
};
}
Expand All @@ -207,13 +207,13 @@ class MyStreamAdapter extends TopicQueryAdapter {

The adapter has several protected helper methods:

| Method | Description |
| --------------------------- | ------------------------------------------------------------------------------------------------------ |
| `fulfillTopic(topic, data)` | Resolve the query with initial data. Can be called before or after the query activates. |
| `rejectTopic(topic, error)` | Reject the query with an error. Can be called before or after the query activates. |
| `sendMutationEvent(event)` | Push a `MutationEvent` through Fetchium's entity event system. |
| `clearTopic(topic)` | Clear buffered state for a topic. Call this in `unsubscribe` to reset for the next subscription cycle. |
| `clearAll()` | Clear all buffered topic state. Useful when resetting the connection. |
| Method | Description |
| ---------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `fulfillTopic(topic, data)` | Resolve the query with initial data. Can be called before or after the query activates. |
| `rejectTopic(topic, error)` | Reject the query with an error. Can be called before or after the query activates. |
| `sendMutationEvent(event, topic?)` | Push a `MutationEvent` through Fetchium's entity event system. Pass the `topic` it arrived on so that topic's query counts as current (see `reactivationGraceMs`). |
| `clearTopic(topic)` | Clear buffered state for a topic. Call this in `unsubscribe` to reset for the next subscription cycle. |
| `clearAll()` | Clear all buffered topic state. Useful when resetting the connection. |

### Registering the adapter

Expand Down
20 changes: 16 additions & 4 deletions packages/fetchium/src/NetworkManager.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ export class NetworkManager {
// Initialize with manual status if provided, otherwise detect from environment
const initialOnlineStatus = initialStatus ?? this.detectOnlineStatus();
this.onlineSignal = signal(initialOnlineStatus);
this.lastOnline = initialOnlineStatus;

// Automatically attach event listeners if in browser/React Native environment
if (this.canAttachListeners()) {
Expand All @@ -38,20 +39,30 @@ export class NetworkManager {
return this.onlineSignal.value;
}

reconnects = 0;
/** Untracked copy of the signal's value, so writes don't consume it. */
private lastOnline: boolean;

private setOnline(online: boolean): void {
if (online && !this.lastOnline) this.reconnects++;
this.lastOnline = online;
this.onlineSignal.value = online;
}

/**
* Manually set the network status (useful for testing)
*/
setNetworkStatus(online: boolean): void {
this.manualOverride = online;
this.onlineSignal.value = online;
this.setOnline(online);
}

/**
* Clear manual override and return to automatic detection
*/
clearManualOverride(): void {
this.manualOverride = undefined;
this.onlineSignal.value = this.detectOnlineStatus();
this.setOnline(this.detectOnlineStatus());
}

/**
Expand Down Expand Up @@ -106,13 +117,13 @@ export class NetworkManager {

this.handleOnline = () => {
if (this.manualOverride === undefined) {
this.onlineSignal.value = true;
this.setOnline(true);
}
};

this.handleOffline = () => {
if (this.manualOverride === undefined) {
this.onlineSignal.value = false;
this.setOnline(false);
}
};

Expand All @@ -126,6 +137,7 @@ export class NetworkManager {
// No-op implementation for SSR environments where network status tracking is not needed
export class NoOpNetworkManager {
private static readonly onlineSignal: Signal<boolean> = signal(true);
readonly reconnects = 0;

get isOnline(): boolean {
return true;
Expand Down
3 changes: 3 additions & 0 deletions packages/fetchium/src/QueryAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,9 @@ export type QueryAdapterClass<T extends QueryAdapter = QueryAdapter> = abstract
export abstract class QueryAdapter {
protected queryClient: IQueryClientForAdapter | undefined;

/** Set if the adapter merges nearby requests into one. Its reactivation refetches are then not staggered. */
declare readonly coalescesRequests?: boolean;

/**
* Called once by QueryClient when this adapter is registered.
* Subclasses can override to do setup (e.g. open a WebSocket connection).
Expand Down
59 changes: 59 additions & 0 deletions packages/fetchium/src/QueryClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
type QueryStore,
type QueryParams,
type PreloadedEntityMap,
type ActivitySource,
queryKeyFor,
} from './query-types.js';
import { SyncQueryStore, MemoryPersistentStore } from './stores/sync.js';
Expand All @@ -47,10 +48,23 @@ export interface QueryClientConfig {
debug?: (message: string) => void;
};
evictionMultiplier?: number;
/**
* Ms. A reactivating query with data younger than this skips its stale refetch.
* Subscription pushes count as fresh data, `poll()` only through its fetches.
* Reconnects, `refetch()`, invalidation and a failed last fetch still refetch. Default: 0.
*/
reactivationGraceMs?: number;
/** Ms. Reactivation refetches started in the same task are spread evenly across this window. Default: 0. */
reactivationStaggerMs?: number;
/** Foreground/background source. `poll()` stops its timers while the app is inactive. */
activity?: ActivitySource;
/** Ms. Overdue `poll()` ticks on resume fire at a random point in this window, not all at once. Default: 0. */
pollResumeJitterMs?: number;
}

export {
type QueryContext,
type ActivitySource,
type QueryCacheOptions,
type QueryConfigOptions,
type FetchNextConfig,
Expand All @@ -77,6 +91,12 @@ export class QueryClient {
/** Without `store.onDelete`, `_persisted` cannot be trusted. */
storeReportsDeletes: boolean = false;

readonly reactivationGraceMs: number;
readonly reactivationStaggerMs: number;

private staggerQueue = new Set<QueryInstance<any>>();
private staggerTimer: ReturnType<typeof setTimeout> | undefined = undefined;

private context!: QueryContext;
private typenameRegistry = new Map<string, ValidatorDef<any>[]>();
private constraintRegistry = new Map<string, ConstraintMatcher>();
Expand All @@ -90,13 +110,18 @@ export class QueryClient {
store = new SyncQueryStore(new MemoryPersistentStore()),
log,
evictionMultiplier,
reactivationGraceMs,
reactivationStaggerMs,
adapters: _c,
networkManager: _n,
gcManager: _g,
...rest
} = config as QueryClientConfig & Record<string, unknown>;
this.isServer = typeof window === 'undefined';
this.store = store;
this.reactivationGraceMs = nonNegative(reactivationGraceMs);
this.reactivationStaggerMs = nonNegative(reactivationStaggerMs);
// poll() reads `activity` and `pollResumeJitterMs` from the context, via `rest`.
this.context = { ...rest, log: log ?? console, evictionMultiplier };
this.gcManager =
config.gcManager ??
Expand Down Expand Up @@ -436,6 +461,33 @@ export class QueryClient {
}
}

// ======================================================
// Reactivation stagger
// ======================================================

/** Queues a reactivation refetch. Each task's queue is spread across `reactivationStaggerMs`. */
scheduleReactivationRefetch(instance: QueryInstance<any>): void {
this.staggerQueue.add(instance);
this.staggerTimer ??= setTimeout(this.flushStaggerQueue, 0);
}

private flushStaggerQueue = (): void => {
this.staggerTimer = undefined;
const spread: QueryInstance<any>[] = [];
for (const instance of this.staggerQueue) {
if (this.getAdapter(instance.def.statics.adapterClass).coalescesRequests === true) {
instance.runReactivationRefetch(0);
} else {
spread.push(instance);
}
}
this.staggerQueue.clear();
const step = spread.length > 1 ? this.reactivationStaggerMs / spread.length : 0;
for (let i = 0; i < spread.length; i++) {
spread[i].runReactivationRefetch(Math.round(i * step));
}
};

// ======================================================
// Query Invalidation
// ======================================================
Expand Down Expand Up @@ -524,6 +576,9 @@ export class QueryClient {
}

destroy(): void {
clearTimeout(this.staggerTimer);
this.staggerTimer = undefined;
this.staggerQueue.clear();
this.networkUnsubscribe?.();
this.gcManager.destroy();
this.networkManager.destroy();
Expand All @@ -542,6 +597,10 @@ export class QueryClient {

export const QueryClientContext: Context<QueryClient | undefined> = context<QueryClient | undefined>(undefined);

function nonNegative(value: unknown): number {
return typeof value === 'number' && value > 0 ? value : 0;
}

function paramsMatch(instanceParams: Record<string, unknown> | undefined, subset: Record<string, unknown>): boolean {
if (instanceParams === undefined) return false;
for (const key in subset) {
Expand Down
Loading
Loading