|
| 1 | +import { useEffect, useRef } from 'react'; |
| 2 | +import { |
| 3 | + FetchMode, |
| 4 | + Query, |
| 5 | + QueryOpts, |
| 6 | + QueryStatus, |
| 7 | + type PolycentricClient, |
| 8 | +} from '@polycentric/react-native'; |
| 9 | +import { create } from 'zustand'; |
| 10 | +import { usePolycentric } from '../../lib/polycentric-hooks'; |
| 11 | + |
| 12 | +export type QueryRef = { |
| 13 | + data: ArrayBuffer | undefined; |
| 14 | + status: QueryStatus; |
| 15 | + error: string | null; |
| 16 | +}; |
| 17 | + |
| 18 | +type QueryArgs = { |
| 19 | + client: PolycentricClient; |
| 20 | + queryKey: string[]; |
| 21 | + query: Query; |
| 22 | + opts: QueryOpts | undefined; |
| 23 | +}; |
| 24 | + |
| 25 | +type SubscriptionRef = { |
| 26 | + refCount: number; |
| 27 | + dispose: () => void; |
| 28 | + args: QueryArgs; |
| 29 | +}; |
| 30 | + |
| 31 | +type QueryStoreState = { |
| 32 | + queries: Map<string, QueryRef>; |
| 33 | + subscriptions: Map<string, SubscriptionRef>; |
| 34 | + subscribe: (key: string, args: QueryArgs) => void; |
| 35 | + unsubscribe: (key: string) => void; |
| 36 | + refresh: (key: string, args?: QueryArgs) => void; |
| 37 | + invalidate: (key: string, args?: QueryArgs) => void; |
| 38 | +}; |
| 39 | + |
| 40 | +const EMPTY_ENTRY: QueryRef = Object.freeze({ |
| 41 | + data: undefined, |
| 42 | + status: QueryStatus.Loading, |
| 43 | + error: null, |
| 44 | +}); |
| 45 | + |
| 46 | +export const useQueryStore = create<QueryStoreState>((set, get) => { |
| 47 | + const updateQueryRef = (key: string, patch: Partial<QueryRef>) => { |
| 48 | + set((state) => { |
| 49 | + const prev = state.queries.get(key) ?? EMPTY_ENTRY; |
| 50 | + const merged = { ...prev, ...patch }; |
| 51 | + if ( |
| 52 | + merged.data === prev.data && |
| 53 | + merged.status === prev.status && |
| 54 | + merged.error === prev.error |
| 55 | + ) { |
| 56 | + return {}; |
| 57 | + } |
| 58 | + const next = new Map(state.queries); |
| 59 | + next.set(key, merged); |
| 60 | + return { queries: next }; |
| 61 | + }); |
| 62 | + }; |
| 63 | + |
| 64 | + const fetch = (key: string, args: QueryArgs): (() => void) => { |
| 65 | + // Set query to loading state |
| 66 | + updateQueryRef(key, { |
| 67 | + status: QueryStatus.Loading, |
| 68 | + error: null, |
| 69 | + }); |
| 70 | + // Request from rs-core |
| 71 | + const observable = args.client.core.fetchQuery( |
| 72 | + args.queryKey, |
| 73 | + args.query, |
| 74 | + args.opts, |
| 75 | + ); |
| 76 | + // Listen for outputs from relevant servers |
| 77 | + const sub = observable.subscribe({ |
| 78 | + next(result) { |
| 79 | + updateQueryRef(key, { data: result.data, status: result.status }); |
| 80 | + }, |
| 81 | + error(message) { |
| 82 | + updateQueryRef(key, { error: message, status: QueryStatus.Error }); |
| 83 | + }, |
| 84 | + complete() { |
| 85 | + // Terminal status already arrived via the final `next`. |
| 86 | + }, |
| 87 | + }); |
| 88 | + // Dispose of the subscription if we cancel the fetch |
| 89 | + return () => sub.unsubscribe(); |
| 90 | + }; |
| 91 | + |
| 92 | + return { |
| 93 | + queries: new Map(), |
| 94 | + subscriptions: new Map(), |
| 95 | + |
| 96 | + subscribe(key, args) { |
| 97 | + const existing = get().subscriptions.get(key); |
| 98 | + if (existing) { |
| 99 | + existing.refCount += 1; |
| 100 | + existing.args = args; |
| 101 | + |
| 102 | + if (args.opts?.fetchMode === FetchMode.Default) { |
| 103 | + console.log(`Trying to refetch ${key}`); |
| 104 | + existing.dispose(); |
| 105 | + existing.dispose = fetch(key, args); |
| 106 | + } |
| 107 | + |
| 108 | + return; |
| 109 | + } |
| 110 | + get().subscriptions.set(key, { |
| 111 | + refCount: 1, |
| 112 | + dispose: fetch(key, args), |
| 113 | + args, |
| 114 | + }); |
| 115 | + }, |
| 116 | + |
| 117 | + unsubscribe(key) { |
| 118 | + const subscription = get().subscriptions.get(key); |
| 119 | + if (!subscription) return; |
| 120 | + subscription.refCount -= 1; |
| 121 | + if (subscription.refCount === 0) { |
| 122 | + subscription.dispose(); |
| 123 | + get().subscriptions.delete(key); |
| 124 | + } |
| 125 | + }, |
| 126 | + |
| 127 | + refresh(key, args) { |
| 128 | + const sub = get().subscriptions.get(key); |
| 129 | + if (!sub) return; |
| 130 | + const next = args ?? sub.args; |
| 131 | + sub.dispose(); |
| 132 | + sub.args = next; |
| 133 | + sub.dispose = fetch(key, next); |
| 134 | + }, |
| 135 | + |
| 136 | + invalidate(key, args) { |
| 137 | + const sub = get().subscriptions.get(key); |
| 138 | + const target = args ?? sub?.args; |
| 139 | + if (target) target.client.core.invalidateQuery(target.queryKey); |
| 140 | + if (sub && target) { |
| 141 | + sub.dispose(); |
| 142 | + sub.args = target; |
| 143 | + // Keep stale `data` visible — `fetch` flips status to |
| 144 | + // Loading and the new fan-out's `next` emissions will |
| 145 | + // overwrite as fresh results arrive. |
| 146 | + sub.dispose = fetch(key, target); |
| 147 | + } |
| 148 | + }, |
| 149 | + }; |
| 150 | +}); |
| 151 | + |
| 152 | +export type UseQueryResult = QueryRef & { |
| 153 | + isLoading: boolean; |
| 154 | + /** Re-run the fan-out. Cached data stays visible until the new responses arrive. */ |
| 155 | + refresh: () => void; |
| 156 | + /** |
| 157 | + * Drop the rust-side cache for this key, then re-run the fan-out. |
| 158 | + * Optional `opts` overrides the original `QueryOpts` for this run |
| 159 | + * (e.g. pass `{ fetchMode: FetchMode.Default }` to force a network |
| 160 | + * fetch when the original subscription used `OfflineOnly`). |
| 161 | + */ |
| 162 | + invalidate: (opts?: QueryOpts) => void; |
| 163 | +}; |
| 164 | + |
| 165 | +/** |
| 166 | + * Imperatively invalidate a query from outside a React component |
| 167 | + * (e.g. after a successful compose). Clears the rust-side cache and, |
| 168 | + * if a live subscription exists for this query, re-runs its fan-out |
| 169 | + * so the JS-side store gets fresh data. |
| 170 | + */ |
| 171 | +export function invalidateQuery( |
| 172 | + client: PolycentricClient, |
| 173 | + queryKey: string[], |
| 174 | +): void { |
| 175 | + client.core.invalidateQuery(queryKey); |
| 176 | + useQueryStore.getState().refresh(queryKey.join('\0')); |
| 177 | +} |
| 178 | + |
| 179 | +/** |
| 180 | + * Subscribe to a rust-core query and share its state across every |
| 181 | + * consumer using the same `queryKey`. The first consumer kicks off |
| 182 | + * the rust-side fan-out; subsequent consumers refcount onto the same |
| 183 | + * subscription. `refresh` / `invalidate` re-run the shared fan-out |
| 184 | + * for every attached consumer. Set `enabled` to `false` to skip the |
| 185 | + * subscription entirely (the hook still returns cached state if any). |
| 186 | + */ |
| 187 | +export function useQuery( |
| 188 | + queryKey: string[], |
| 189 | + query: Query, |
| 190 | + opts: QueryOpts = { fetchMode: FetchMode.Default }, |
| 191 | + enabled = true, |
| 192 | +): UseQueryResult { |
| 193 | + const client = usePolycentric(); |
| 194 | + const cacheKey = queryKey.join('\0'); |
| 195 | + |
| 196 | + const entry = useQueryStore((s) => s.queries.get(cacheKey) ?? EMPTY_ENTRY); |
| 197 | + |
| 198 | + // Keep `argsRef` pointing at the freshest call args so the |
| 199 | + // imperative handlers below always see them without needing the |
| 200 | + // effect to re-run. |
| 201 | + const argsRef = useRef<QueryArgs>({ client, queryKey, query, opts }); |
| 202 | + argsRef.current = { client, queryKey, query, opts }; |
| 203 | + |
| 204 | + useEffect(() => { |
| 205 | + if (!enabled) return; |
| 206 | + const { subscribe: attach, unsubscribe: detach } = useQueryStore.getState(); |
| 207 | + attach(cacheKey, argsRef.current); |
| 208 | + return () => detach(cacheKey); |
| 209 | + }, [cacheKey, enabled]); |
| 210 | + |
| 211 | + return { |
| 212 | + ...entry, |
| 213 | + isLoading: enabled && entry.status === QueryStatus.Loading, |
| 214 | + refresh: () => useQueryStore.getState().refresh(cacheKey, argsRef.current), |
| 215 | + invalidate: (overrideOpts?: QueryOpts) => |
| 216 | + useQueryStore |
| 217 | + .getState() |
| 218 | + .invalidate( |
| 219 | + cacheKey, |
| 220 | + overrideOpts !== undefined |
| 221 | + ? { ...argsRef.current, opts: overrideOpts } |
| 222 | + : argsRef.current, |
| 223 | + ), |
| 224 | + }; |
| 225 | +} |
0 commit comments