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

sourceControlDiscoveryState.ts

401 lines11.9 KB

1import type { SourceControlDiscoveryResult } from "@t3tools/contracts";
2import * as Effect from "effect/Effect";
3import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
4​
5/* --- Types ---------------------------------------------------------- */
6​
7export interface SourceControlDiscoveryState {
8 readonly data: SourceControlDiscoveryResult | null;
9 readonly error: string | null;
10 readonly isPending: boolean;
12​
13export interface SourceControlDiscoveryTarget<TKey extends string = string> {
14 readonly key: TKey | null;
16​
17export interface SourceControlDiscoveryClient {
18 readonly discoverSourceControl: () => Promise<SourceControlDiscoveryResult>;
20​
21interface WatchedEntry {
22 refCount: number;
23 teardown: () => void;
25​
26/* --- Constants ------------------------------------------------------ */
27​
28export const EMPTY_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
29 data: null,
30 error: null,
31 isPending: false,
32});
33​
34const INITIAL_SOURCE_CONTROL_DISCOVERY_STATE = Object.freeze<SourceControlDiscoveryState>({
35 data: null,
36 error: null,
37 isPending: true,
38});
39​
40/* --- Atoms ---------------------------------------------------------- */
41​
42const knownSourceControlDiscoveryKeys = new Set<string>();
43​
44export const sourceControlDiscoveryStateAtom = Atom.family((key: string) => {
45 knownSourceControlDiscoveryKeys.add(key);
46 return Atom.make(INITIAL_SOURCE_CONTROL_DISCOVERY_STATE).pipe(
47 Atom.keepAlive,
48 Atom.withLabel(`source-control-discovery:${key}`),
49 );
50});
51​
52export const EMPTY_SOURCE_CONTROL_DISCOVERY_ATOM = Atom.make(
53 EMPTY_SOURCE_CONTROL_DISCOVERY_STATE,
54).pipe(Atom.keepAlive, Atom.withLabel("source-control-discovery:null"));
55​
56/* --- Helpers -------------------------------------------------------- */
57​
58export function getSourceControlDiscoveryTargetKey<TKey extends string>(
59 target: SourceControlDiscoveryTarget<TKey>,
60): TKey | null {
61 const key = target.key;
62 return key && key.length > 0 ? key : null;
64​
65/* --- Refresh manager ------------------------------------------------ */
66​
67export interface SourceControlDiscoveryManagerConfig<TKey extends string = string> {
68 /**
69 * Get the atom registry used to read/write source-control discovery snapshots.
70 */
71 readonly getRegistry: () => AtomRegistry.AtomRegistry;
72 /**
73 * Resolve the runtime client for a discovery target key.
74 *
75 * Web currently uses a single `"primary"` target, but keeping this keyed
76 * lets mobile or future multi-environment clients provide separate discovery
77 * clients without changing the state primitive.
78 */
79 readonly getClient: (key: TKey) => SourceControlDiscoveryClient | null;
80 /**
81 * Optional: subscribe to environment/client availability changes.
82 *
83 * When provided, `watch` refreshes as clients appear or are replaced
84 * instead of relying on React hooks to manually kick discovery.
85 */
86 readonly subscribeClientChanges?: (listener: () => void) => () => void;
87 readonly staleTimeMs?: number;
88 readonly idleTtlMs?: number;
90​
91const NOOP: () => void = () => undefined;
92const DEFAULT_STALE_TIME_MS = 30_000;
93const DEFAULT_IDLE_TTL_MS = 5 * 60_000;
94​
95export function createSourceControlDiscoveryManager<TKey extends string = string>(
96 config: SourceControlDiscoveryManagerConfig<TKey>,
97) {
98 const refreshInFlight = new Map<
99 string,
100 {
101 readonly client: SourceControlDiscoveryClient;
102 readonly promise: Promise<SourceControlDiscoveryResult | null>;
103 }
104 >();
105 const refreshVersions = new Map<string, number>();
106 const watched = new Map<string, WatchedEntry>();
107 const refreshTargets = new Map<string, SourceControlDiscoveryTarget<TKey>>();
108 const staleTimeMs = config.staleTimeMs ?? DEFAULT_STALE_TIME_MS;
109 const idleTtlMs = config.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;
110​
111 const watchedRefreshAtom = Atom.family((targetKey: string) =>
112 Atom.make(() =>
113 Effect.promise(() => {
114 const target = refreshTargets.get(targetKey);
115 return target ? refresh(target) : Promise.resolve(null);
116 }),
117 ).pipe(
118 Atom.swr({
119 staleTime: staleTimeMs,
120 revalidateOnMount: true,
121 }),
122 Atom.setIdleTTL(idleTtlMs),
123 Atom.withLabel(`source-control-discovery:watched-refresh:${targetKey}`),
124 ),
125 );
126​
127 function getRefreshVersion(targetKey: string): number {
128 return refreshVersions.get(targetKey) ?? 0;
129 }
130​
131 function bumpRefreshVersion(targetKey: string): void {
132 refreshVersions.set(targetKey, getRefreshVersion(targetKey) + 1);
133 }
134​
135 /* -- Atom helpers -------------------------------------------------- */
136​
137 function setState(targetKey: string, nextState: SourceControlDiscoveryState): void {
138 config.getRegistry().set(sourceControlDiscoveryStateAtom(targetKey), nextState);
139 }
140​
141 function markPending(targetKey: string): void {
142 const current = config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
143 const next: SourceControlDiscoveryState =
144 current.data === null
145 ? INITIAL_SOURCE_CONTROL_DISCOVERY_STATE
146 : {
147 data: current.data,
148 error: null,
149 isPending: true,
150 };
151​
152 if (
153 current.data === next.data &&
154 current.error === next.error &&
155 current.isPending === next.isPending
156 ) {
157 return;
158 }
159​
160 setState(targetKey, next);
161 }
162​
163 function setData(targetKey: string, data: SourceControlDiscoveryResult): void {
164 setState(targetKey, {
165 data,
166 error: null,
167 isPending: false,
168 });
169 }
170​
171 function setError(targetKey: string, error: unknown): void {
172 const current = config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
173 setState(targetKey, {
174 data: current.data,
175 error: error instanceof Error ? error.message : "Failed to discover source control tools.",
176 isPending: false,
177 });
178 }
179​
180 /* -- Public API ---------------------------------------------------- */
181​
182 /**
183 * Trigger a one-shot source-control discovery RPC for a target.
184 *
185 * Calls are deduplicated while a refresh for the same target key is in
186 * flight. On failure, the previous successful snapshot is kept in `data`
187 * and the error message is stored separately so UI can keep rendering stale
188 * discovery results while showing the failure.
189 *
190 * @param target The logical runtime target to refresh.
191 * @param client Optional pre-resolved client, useful in tests.
192 */
193 function refresh(
194 target: SourceControlDiscoveryTarget<TKey>,
195 client?: SourceControlDiscoveryClient,
196 ): Promise<SourceControlDiscoveryResult | null> {
197 const targetKey = getSourceControlDiscoveryTargetKey(target);
198 if (targetKey === null) {
199 return Promise.resolve(null);
200 }
201 refreshTargets.set(targetKey, target);
202​
203 const resolvedClient = client ?? config.getClient(targetKey);
204 if (!resolvedClient) {
205 const error = new Error("Source control discovery client is unavailable.");
206 setError(targetKey, error);
207 return Promise.resolve(getSnapshot(target).data);
208 }
209​
210 const existing = refreshInFlight.get(targetKey);
211 if (existing) {
212 if (!client || existing.client === resolvedClient) {
213 return existing.promise;
214 }
215​
216 return existing.promise.then(() => refresh(target, resolvedClient));
217 }
218​
219 markPending(targetKey);
220 const refreshVersion = getRefreshVersion(targetKey);
221 const promise = resolvedClient.discoverSourceControl().then(
222 (result) => {
223 if (getRefreshVersion(targetKey) === refreshVersion) {
224 setData(targetKey, result);
225 }
226 return result;
227 },
228 (error: unknown) => {
229 if (getRefreshVersion(targetKey) === refreshVersion) {
230 setError(targetKey, error);
231 }
232 return getSnapshot(target).data;
233 },
234 );
235 let tracked: Promise<SourceControlDiscoveryResult | null>;
236 tracked = promise.finally(() => {
237 if (refreshInFlight.get(targetKey)?.promise === tracked) {
238 refreshInFlight.delete(targetKey);
239 }
240 });
241 refreshInFlight.set(targetKey, {
242 client: resolvedClient,
243 promise: tracked,
244 });
245 return tracked;
246 }
247​
248 /**
249 * Reset discovery state for one target and ignore any currently in-flight
250 * refresh for that target. If no target is provided, every known target is
251 * invalidated.
252 */
253 function invalidate(target?: SourceControlDiscoveryTarget<TKey>): void {
254 if (!target) {
255 reset();
256 return;
257 }
258​
259 const targetKey = getSourceControlDiscoveryTargetKey(target);
260 if (targetKey === null) {
261 return;
262 }
263​
264 bumpRefreshVersion(targetKey);
265 refreshInFlight.delete(targetKey);
266 setState(targetKey, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE);
267 }
268​
269 /**
270 * Read the current atom snapshot for `target`.
271 *
272 * Invalid targets return the inert empty state rather than creating a new
273 * family atom entry.
274 */
275 function getSnapshot(target: SourceControlDiscoveryTarget<TKey>): SourceControlDiscoveryState {
276 const targetKey = getSourceControlDiscoveryTargetKey(target);
277 if (targetKey === null) {
278 return EMPTY_SOURCE_CONTROL_DISCOVERY_STATE;
279 }
280​
281 return config.getRegistry().get(sourceControlDiscoveryStateAtom(targetKey));
282 }
283​
284 /**
285 * Keep discovery warm for `target`.
286 *
287 * Multiple callers sharing a target key are ref-counted. With
288 * `subscribeClientChanges`, the manager refreshes whenever a client first
289 * appears or is replaced after reconnect.
290 */
291 function watch(
292 target: SourceControlDiscoveryTarget<TKey>,
293 client?: SourceControlDiscoveryClient,
294 ): () => void {
295 const targetKey = getSourceControlDiscoveryTargetKey(target);
296 if (targetKey === null) {
297 return NOOP;
298 }
299 refreshTargets.set(targetKey, target);
300​
301 const existing = watched.get(targetKey);
302 if (existing) {
303 existing.refCount += 1;
304 return () => unwatch(targetKey);
305 }
306​
307 let teardown: () => void;
308​
309 if (client) {
310 void refresh(target, client);
311 teardown = NOOP;
312 } else if (config.subscribeClientChanges) {
313 let currentClient: SourceControlDiscoveryClient | null = null;
314​
315 const sync = () => {
316 const resolved = config.getClient(targetKey);
317 if (!resolved) {
318 currentClient = null;
319 markPending(targetKey);
320 return;
321 }
322​
323 if (currentClient === resolved) {
324 return;
325 }
326​
327 const isClientReplacement = currentClient !== null;
328 currentClient = resolved;
329 refreshWatchedTarget(targetKey, target, isClientReplacement ? resolved : undefined);
330 };
331​
332 const unsubChanges = config.subscribeClientChanges(sync);
333 sync();
334 teardown = unsubChanges;
335 } else {
336 if (!config.getClient(targetKey)) {
337 return NOOP;
338 }
339 refreshWatchedTarget(targetKey, target);
340 teardown = NOOP;
341 }
342​
343 watched.set(targetKey, { refCount: 1, teardown });
344 return () => unwatch(targetKey);
345 }
346​
347 function unwatch(targetKey: string): void {
348 const entry = watched.get(targetKey);
349 if (!entry) {
350 return;
351 }
352​
353 entry.refCount -= 1;
354 if (entry.refCount > 0) {
355 return;
356 }
357​
358 entry.teardown();
359 watched.delete(targetKey);
360 }
361​
362 function refreshWatchedTarget(
363 targetKey: string,
364 target: SourceControlDiscoveryTarget<TKey>,
365 client?: SourceControlDiscoveryClient,
366 ): void {
367 refreshTargets.set(targetKey, target);
368 if (client) {
369 void refresh(target, client);
370 return;
371 }
372​
373 config.getRegistry().get(watchedRefreshAtom(targetKey));
374 }
375​
376 /**
377 * Clear in-flight refresh tracking and reset every known discovery atom.
378 * Primarily used by tests and runtime teardown.
379 */
380 function reset(): void {
381 const keys = new Set([...knownSourceControlDiscoveryKeys, ...refreshInFlight.keys()]);
382 for (const entry of watched.values()) {
383 entry.teardown();
384 }
385 watched.clear();
386 refreshTargets.clear();
387 refreshInFlight.clear();
388 for (const key of keys) {
389 bumpRefreshVersion(key);
390 setState(key, INITIAL_SOURCE_CONTROL_DISCOVERY_STATE);
391 }
392 }
393​
394 return {
395 watch,
396 refresh,
397 getSnapshot,
398 invalidate,
399 reset,
400 };