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

sourceControlDiscoveryState.ts

206 lines6.5 KB

1import type { SourceControlDiscoveryResult } from "@t3tools/contracts";
2import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
3​
4/* --- Types ---------------------------------------------------------- */
5​
6export interface SourceControlDiscoveryState {
7 readonly data: SourceControlDiscoveryResult | null;
8 readonly error: string | null;
9 readonly isPending: boolean;
11​
12export interface SourceControlDiscoveryTarget {
13 readonly key: string | null;
15​
16export interface SourceControlDiscoveryClient {
17 readonly discoverSourceControl: () => Promise<SourceControlDiscoveryResult>;
19​
20/* --- Constants ------------------------------------------------------ */
21​
22export const EMPTY_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
23 data: null,
24 error: null,
25 isPending: false,
26});
27​
28const INITIAL_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
29 data: null,
30 error: null,
31 isPending: true,
32});
33​
34/* --- Atoms ---------------------------------------------------------- */
35​
36const knownSourceControlDiscoveryKeys = new Set<string>();
37​
38export const sourceControlDiscoveryStateAtom = Atom.family((key: string) => {
39 knownSourceControlDiscoveryKeys.add(key);
40 return Atom.make(INITIAL_SOURCE_CONTROL_DISCOVERY_STATE).pipe(
41 Atom.keepAlive,
42 Atom.withLabel(`source-control-discovery:${key}`),
43 );
44});
45​
46export const EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM = Atom.make(
47 EMPTY_SOURCE_CONTROL_DISCOVERY_STATE,
48).pipe(Atom.keepAlive, Atom.withLabel("source-control-discovery:null"));
49​
50/* --- Helpers -------------------------------------------------------- */
51​
52export function getSourceControlDiscoveryTargetKey(
53 target: SourceControlDiscoveryTarget,
54): string | null {
55 const key = target.key?.trim();
56 return key && key.length > 0 ? key : null;
58​
59/* --- Refresh manager ------------------------------------------------ */
60​
61export interface SourceControlDiscoveryManagerConfig {
62 /**
63 * Get the atom registry used to read/write source-control discovery snapshots.
64 */
65 readonly getRegistry: () => AtomRegistry.AtomRegistry;
66 /**
67 * Resolve the runtime client for a discovery target key.
68 *
69 * Web currently uses a single `"primary"` target, but keeping this keyed
70 * lets mobile or future multi-environment clients provide separate discovery
71 * clients without changing the state primitive.
72 */
73 readonly getClient: (key: string) => SourceControlDiscoveryClient | null;
75​
76export function createSourceControlDiscoveryManager(config: SourceControlDiscoveryManagerConfig) {
77 const refreshInFlight = new Map<string, Promise<SourceControlDiscoveryResult | null>>();
78​
79 /* -- Atom helpers -------------------------------------------------- */
80​
81 function setState(targetKey: string, nextState: SourceControlDiscoveryState): void {
82 config.getRegistry().set(sourceControlDiscoveryStateAtom(targetKey), nextState);
83 }
84​
85 function markPending(targetKey: string): void {
86 const current = config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
87 const next: SourceControlDiscoveryState =
88 current.data === null
89 ? INITIAL_SOURCE_CONTROL_DISCOVERY_STATE
90 : {
91 data: current.data,
92 error: null,
93 isPending: true,
94 };
95​
96 if (
97 current.data === next.data &&
98 current.error === next.error &&
99 current.isPending === next.isPending
100 ) {
101 return;
102 }
103​
104 setState(targetKey, next);
105 }
106​
107 function setData(targetKey: string, data: SourceControlDiscoveryResult): void {
108 setState(targetKey, {
109 data,
110 error: null,
111 isPending: false,
112 });
113 }
114​
115 function setError(targetKey: string, error: unknown): void {
116 const current = config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
117 setState(targetKey, {
118 data: current.data,
119 error: error instanceof Error ? error.message : "Failed to discover source control tools.",
120 isPending: false,
121 });
122 }
123​
124 /* -- Public API ---------------------------------------------------- */
125​
126 /**
127 * Trigger a one-shot source-control discovery RPC for a target.
128 *
129 * Calls are deduplicated while a refresh for the same target key is in
130 * flight. On failure, the previous successful snapshot is kept in `data`
131 * and the error message is stored separately so UI can keep rendering stale
132 * discovery results while showing the failure.
133 *
134 * @param target The logical runtime target to refresh.
135 * @param client Optional pre-resolved client, useful in tests.
136 */
137 function refresh(
138 target: SourceControlDiscoveryTarget,
139 client?: SourceControlDiscoveryClient,
140 ): Promise<SourceControlDiscoveryResult | null> {
141 const targetKey = getSourceControlDiscoveryTargetKey(target);
142 if (targetKey === null) {
143 return Promise.resolve(null);
144 }
145​
146 const existing = refreshInFlight.get(targetKey);
147 if (existing) {
148 return existing;
149 }
150​
151 const resolvedClient = client ?? config.getClient(targetKey);
152 if (!resolvedClient) {
153 const error = new Error("Source control discovery client is unavailable.");
154 setError(targetKey, error);
155 return Promise.resolve(getSnapshot(target).data);
156 }
157​
158 markPending(targetKey);
159 const promise = resolvedClient.discoverSourceControl().then(
160 (result) => {
161 setData(targetKey, result);
162 return result;
163 },
164 (error: unknown) => {
165 setError(targetKey, error);
166 return getSnapshot(target).data;
167 },
168 );
169 const tracked = promise.finally(() => refreshInFlight.delete(targetKey));
170 refreshInFlight.set(targetKey, tracked);
171 return tracked;
172 }
173​
174 /**
175 * Read the current atom snapshot for `target`.
176 *
177 * Invalid targets return the inert empty state rather than creating a new
178 * family atom entry.
179 */
180 function getSnapshot(target: SourceControlDiscoveryTarget): SourceControlDiscoveryState {
181 const targetKey = getSourceControlDiscoveryTargetKey(target);
182 if (targetKey === null) {
183 return EMPTY_SOURCE_CONTROL_DISCOVERY_STATE;
184 }
185​
186 return config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
187 }
188​
189 /**
190 * Clear in-flight refresh tracking and reset every known discovery atom.
191 * Primarily used by tests and runtime teardown.
192 */
193 function reset(): void {
194 refreshInFlight.clear();
195 for (const key of knownSourceControlDiscoveryKeys) {
196 setState(key, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE);
197 }
198 knownSourceControlDiscoveryKeys.clear();
199 }
200​
201 return {
202 refresh,
203 getSnapshot,
204 reset,
205 };