Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

cacheAggregate.ts

93 lines3.5 KB

1import {
2 createEffect,
3 createOptimistic,
4 createSignal,
5 isHydrating,
6 onCleanup,
7 untrack,
8} from 'solid-js'
9import type { Accessor } from 'solid-js'
10​
11const isServer = typeof window === 'undefined'
12​
13/**
14 * Shared reactive core for the cross-cache aggregate hooks β€” `useIsFetching`,
15 * `useIsMutating`, `useMutationState` β€” which all reduce to "a value derived
16 * from a whole cache, refreshed on its events". Two invariants live here so
17 * each hook doesn't restate them:
18 *
19 * Dual write. Cache events can fire inside an action transaction
20 * (`useMutation` rides core `action`; an onSuccess invalidation dispatches
21 * refetches mid-action), where a plain signal write is held until settle β€”
22 * the in-flight value would be invisible. An optimistic override alone fails
23 * the other way: outside a transaction, overrides drop at batch end. So a
24 * durable signal carries committed state and an optimistic node tracks it as
25 * its base; in-transaction values surface through the override, and the held
26 * durable write becomes the base when the settle lands.
27 *
28 * Hydration. A cross-cache aggregate is not tied to a single async source,
29 * so it cannot ride the boundary contract per-query meta uses (suspend until
30 * settled). Its contract is fixed by construction instead: a hydrating
31 * client can only ever observe the empty value at claim time β€” its own
32 * fetches are held inside the hydration window, channel-primed entries are
33 * settled, and mutations do not transfer across SSR. So the server
34 * serializes the empty value, and a hydrated mount latches there until its
35 * window closes: the subscription and first sync run from an effect half,
36 * deferred past hydration β€” the earliest globally-safe moment for a
37 * cross-cache read to go live (on a streamed page, an already-hydrated
38 * region's refetch can be in flight while this region is still claiming).
39 *
40 * Every node here is created on the server too, where it is never read or
41 * written: hydration id assignment is positional, so both sides must create
42 * the same reactive nodes or every id downstream shifts and the subtree
43 * key-misses.
44 * @param subscribe - Subscribes to the cache's events and returns the unsubscribe function.
45 * @param read - Computes the aggregate from the cache, given the previously committed value.
46 * @param empty - The value served on the server and while a hydrated mount is still hydrating.
47 * @returns An accessor for the current aggregate.
48 */
49export function createCacheAggregate<T>(
50 subscribe: (onEvent: () => void) => () => void,
51 read: (prev: T) => T,
52 empty: T,
53): Accessor<T> {
54 const hydratedMount = isHydrating()
55​
56 // Cast: createSignal's value overload excludes functions (a function
57 // argument means a compute); aggregate values are counts and arrays.
58 const [durable, setDurable] = createSignal<T>(
59 (hydratedMount || isServer ? empty : untrack(() => read(empty))) as Exclude<
60 T,
61 Function
62 >,
63 { ownedWrite: true },
64 )
65 const [value, setValue] = createOptimistic(() => durable(), {
66 ownedWrite: true,
67 })
68​
69 const sync = () => {
70 const next = untrack(() => read(untrack(durable)))
71 setDurable(() => next)
72 setValue(() => next)
73 }
74 let unsubscribe: (() => void) | null = null
75 const attach = () => {
76 unsubscribe ??= untrack(() => subscribe(sync))
77 }
78 onCleanup(() => unsubscribe?.())
79​
80 createEffect(
81 () => undefined,
82 () => {
83 if (hydratedMount) {
84 attach()
85 sync()
86 }
87 },
88 )
89​
90 if (isServer) return () => empty
91 if (!hydratedMount) attach()
92 return value