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

cacheAggregate.ts

89 lines3.2 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 */
45export function createCacheAggregate<T>(
46 subscribe: (onEvent: () => void) => () => void,
47 read: (prev: T) => T,
48 empty: T,
49): Accessor<T> {
50 const hydratedMount = isHydrating()
51​
52 // Cast: createSignal's value overload excludes functions (a function
53 // argument means a compute); aggregate values are counts and arrays.
54 const [durable, setDurable] = createSignal<T>(
55 (hydratedMount || isServer ? empty : untrack(() => read(empty))) as Exclude<
56 T,
57 Function
58 >,
59 { ownedWrite: true },
60 )
61 const [value, setValue] = createOptimistic(() => durable(), {
62 ownedWrite: true,
63 })
64​
65 const sync = () => {
66 const next = untrack(() => read(untrack(durable)))
67 setDurable(() => next)
68 setValue(() => next)
69 }
70 let unsubscribe: (() => void) | null = null
71 const attach = () => {
72 unsubscribe ??= untrack(() => subscribe(sync))
73 }
74 onCleanup(() => unsubscribe?.())
75​
76 createEffect(
77 () => undefined,
78 () => {
79 if (hydratedMount) {
80 attach()
81 sync()
82 }
83 },
84 )
85​
86 if (isServer) return () => empty
87 if (!hydratedMount) attach()
88 return value