Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

revisionedQuery.ts

109 lines5.0 KB

1import * as Option from "effect/Option";
2import { AsyncResult, Atom, type AtomRegistry } from "effect/reactivity";
3​
4// Outside the nodes: a node is dropped once unmounted, and the next read must
5// still compare against the revision the query was last read under.
6type LastRead = WeakMap<AtomRegistry.AtomRegistry, WeakMap<object, string | null>>;
7const readRevisions: LastRead = new WeakMap();
8const readDetails: LastRead = new WeakMap();
9const lastReadOf = (lastRead: LastRead, registry: AtomRegistry.AtomRegistry) => {
10 let byQuery = lastRead.get(registry);
11 if (byQuery === undefined) {
12 byQuery = new WeakMap();
13 lastRead.set(registry, byQuery);
14 }
15 return byQuery;
16};
17​
18// The registry keys serializable atoms' nodes by their key, not the atom.
19const hasNode = (registry: AtomRegistry.AtomRegistry, atom: Atom.Atom<unknown>) =>
20 registry.getNodes().has(Atom.isSerializable(atom) ? atom[Atom.SerializableTypeId].key : atom);
21​
22// A query's own node can go with its last reader while the atom it takes its value from
23// (an environment query's cache, on an idle TTL) still holds the value.
24const isCached = (registry: AtomRegistry.AtomRegistry, query: Atom.Atom<unknown>) =>
25 hasNode(registry, query) ||
26 (query.initialValueTarget !== undefined && hasNode(registry, query.initialValueTarget));
27​
28const isWaiting = (value: unknown) => AsyncResult.isAsyncResult(value) && value.waiting;
29​
30const makeRevisionedFamily = (query: Atom.Atom<unknown>) =>
31 Atom.family((key: string) => {
32 const { revision, startedUnder, detail } = JSON.parse(key) as {
33 readonly revision?: string | null;
34 readonly startedUnder?: string;
35 readonly detail?: string;
36 };
37 return Atom.readable(
38 (get) => {
39 // Only a node's first build compares: a node still mounted under the old
40 // revision rebuilds when the query refetches, and must not refetch it again.
41 if (Option.isNone(get.self())) {
42 const revisions = lastReadOf(readRevisions, get.registry);
43 // Nothing cached: the read below fetches fresh, which a refresh would only restart.
44 const cached = isCached(get.registry, query);
45 if (revision === undefined) {
46 if (!cached && startedUnder !== undefined) revisions.set(query, startedUnder);
47 return get(query);
48 }
49 const details = lastReadOf(readDetails, get.registry);
50 const stale = revisions.has(query)
51 ? revisions.get(query) !== revision ||
52 (detail !== undefined && details.has(query) && details.get(query) !== detail)
53 : // A reader without a revision may have cached it before the latest
54 // workspace change.
55 revision !== null || detail !== undefined;
56 revisions.set(query, revision);
57 if (detail !== undefined) details.set(query, detail);
58 const value = get(query);
59 // Deferred: this builds while React renders, and a refresh would synchronously
60 // re-render the query's other readers, which React rejects.
61 if (stale && cached) {
62 const registry = get.registry;
63 const wasWaiting = isWaiting(value);
64 queueMicrotask(() => {
65 // No node, as after the registry is disposed: nothing cached to refetch.
66 if (!isCached(registry, query)) return;
67 // A fetch that began since, as another reader's refresh, reads the same workspace.
68 if (!wasWaiting && isWaiting(registry.get(query))) return;
69 registry.refresh(query);
70 });
71 }
72 return value;
73 }
74 return get(query);
75 },
76 // Refreshing the reader refetches the query it reads.
77 (refresh) => refresh(query),
78 );
79 });
80​
81// Held as long as the query lives, so one (query, revision) pair keeps one atom; an
82// `Atom.family` would hold the inner family only weakly and could swap the atom under a reader.
83const revisionedFamilies = new WeakMap<
84 Atom.Atom<unknown>,
85 ReturnType<typeof makeRevisionedFamily>
86>();
87const revisionedFamily = (query: Atom.Atom<unknown>) => {
88 let family = revisionedFamilies.get(query);
89 if (family === undefined) {
90 family = makeRevisionedFamily(query);
91 revisionedFamilies.set(query, family);
92 }
93 return family;
94};
95​
96/**
97 * Reads `query` under a workspace revision (latest mutation id), which its readers share; a
98 * revision other than the last one read refetches a cached query. `undefined` reads without
99 * taking part. `startedUnder` records a fetch such a read starts as read under that revision;
100 * `detail` is one reader's own second revision, which the other readers neither see nor reset.
101 */
102export function revisionedQuery<A>(
103 query: Atom.Atom<A>,
104 revision: string | null | undefined,
105 options: { readonly startedUnder?: string | undefined; readonly detail?: string } = {},
106): Atom.Atom<A> {
107 if (revision === undefined && options.startedUnder === undefined) return query;
108 return revisionedFamily(query)(JSON.stringify({ revision, ...options })) as Atom.Atom<A>;