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

revisionedQuery.ts

140 lines6.2 KB

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