Open History to see the last commit
1import type { EnvironmentId, GitManagerServiceError, VcsStatusResult } from "@t3tools/contracts";
2import type * as Cause from "effect/Cause";
3import * as DateTime from "effect/DateTime";
4import { Atom, type AtomRegistry } from "effect/unstable/reactivity";
5import type { WsRpcClient } from "./wsRpcClient.ts";
6
7/* ─── Types ─────────────────────────────────────────────────────────── */
8
9export interface VcsStatusState {
10 readonly data: VcsStatusResult | null;
11 readonly error: GitManagerServiceError | null;
12 readonly cause: Cause.Cause<GitManagerServiceError> | null;
13 readonly isPending: boolean;
14}
15
16export interface VcsStatusTarget {
17 readonly environmentId: EnvironmentId | null;
18 readonly cwd: string | null;
19}
20
21export type VcsStatusClient = Pick<WsRpcClient["vcs"], "onStatus" | "refreshStatus">;
22
23interface WatchedEntry {
24 refCount: number;
25 teardown: () => void;
26}
27
28/* ─── Constants ─────────────────────────────────────────────────────── */
29
30const NOOP: () => void = () => undefined;
31
32export const EMPTY_VCS_STATUS_STATE = Object.freeze<VcsStatusState>({
33 data: null,
34 error: null,
35 cause: null,
36 isPending: false,
37});
38
39const INITIAL_VCS_STATUS_STATE = Object.freeze<VcsStatusState>({
40 data: null,
41 error: null,
42 cause: null,
43 isPending: true,
44});
45
46/* ─── Atoms ─────────────────────────────────────────────────────────── */
47
48const knownVcsStatusKeys = new Set<string>();
49
50export const vcsStatusStateAtom = Atom.family((key: string) => {
51 knownVcsStatusKeys.add(key);
52 return Atom.make(INITIAL_VCS_STATUS_STATE).pipe(
53 Atom.keepAlive,
54 Atom.withLabel(`vcs-status:${key}`),
55 );
56});
57
58export const EMPTY_VCS_STATUS_ATOM = Atom.make(EMPTY_VCS_STATUS_STATE).pipe(
59 Atom.keepAlive,
60 Atom.withLabel("vcs-status:null"),
61);
62
63/* ─── Helpers ───────────────────────────────────────────────────────── */
64
65export function getVcsStatusTargetKey(target: VcsStatusTarget): string | null {
66 if (target.environmentId === null || target.cwd === null) {
67 return null;
68 }
69 return `${target.environmentId}:${target.cwd}`;
70}
71
72/* ─── Subscription manager ──────────────────────────────────────────── */
73
74export interface VcsStatusManagerConfig {
75 /**
76 * Get the atom registry to read/write VCS status atoms.
77 */
78 readonly getRegistry: () => AtomRegistry.AtomRegistry;
79 /** Resolve a VCS client for an environment. */
80 readonly getClient: (environmentId: EnvironmentId) => VcsStatusClient | null;
81 /**
82 * Optional: get a stable identity for the current client.
83 * Used to detect reconnections — when the identity changes the
84 * manager tears down the old `onStatus` stream and subscribes anew.
85 */
86 readonly getClientIdentity?: (environmentId: EnvironmentId) => string | null;
87 /**
88 * Optional: subscribe to environment-connection changes.
89 * When provided the manager reacts to client appear / disappear /
90 * reconnect events instead of doing a one-shot resolution.
91 */
92 readonly subscribeClientChanges?: (listener: () => void) => () => void;
93}
94
95const VCS_STATUS_REFRESH_DEBOUNCE_MS = 1_000;
96const nowMs = () => DateTime.toEpochMillis(DateTime.nowUnsafe());
97
98export function createVcsStatusManager(config: VcsStatusManagerConfig) {
99 const watched = new Map<string, WatchedEntry>();
100 const refreshInFlight = new Map<string, Promise<VcsStatusResult>>();
101 const lastRefreshAt = new Map<string, number>();
102
103 /* ── Atom helpers ───────────────────────────────────────────────── */
104
105 function markPending(targetKey: string): void {
106 const atom = vcsStatusStateAtom(targetKey);
107 const current = config.getRegistry().get(atom);
108 const next: VcsStatusState =
109 current.data === null
110 ? INITIAL_VCS_STATUS_STATE
111 : { ...current, error: null, cause: null, isPending: true };
112 if (
113 current.data === next.data &&
114 current.error === next.error &&
115 current.cause === next.cause &&
116 current.isPending === next.isPending
117 ) {
118 return;
119 }
120 config.getRegistry().set(atom, next);
121 }
122
123 function setData(targetKey: string, status: VcsStatusResult): void {
124 config.getRegistry().set(vcsStatusStateAtom(targetKey), {
125 data: status,
126 error: null,
127 cause: null,
128 isPending: false,
129 });
130 }
131
132 /* ── Core subscription ──────────────────────────────────────────── */
133
134 function subscribeStream(targetKey: string, cwd: string, client: VcsStatusClient): () => void {
135 markPending(targetKey);
136 return client.onStatus({ cwd }, (status) => setData(targetKey, status), {
137 onResubscribe: () => markPending(targetKey),
138 });
139 }
140
141 /* ── Dynamic subscription (handles reconnection) ────────────────── */
142
143 function createDynamicSubscription(targetKey: string, target: VcsStatusTarget): () => void {
144 const environmentId = target.environmentId!;
145 const cwd = target.cwd!;
146 let currentIdentity: string | null = null;
147 let currentUnsub = NOOP;
148
149 const sync = () => {
150 const client = config.getClient(environmentId);
151 const identity = client ? (config.getClientIdentity?.(environmentId) ?? environmentId) : null;
152
153 if (!client || identity === null) {
154 if (currentIdentity !== null) {
155 currentUnsub();
156 currentUnsub = NOOP;
157 currentIdentity = null;
158 }
159 markPending(targetKey);
160 return;
161 }
162
163 if (currentIdentity === identity) return;
164
165 currentUnsub();
166 currentIdentity = identity;
167 currentUnsub = subscribeStream(targetKey, cwd, client);
168 };
169
170 const unsubChanges = config.subscribeClientChanges!(sync);
171 sync();
172
173 return () => {
174 unsubChanges();
175 currentUnsub();
176 };
177 }
178
179 /* ── Public API ─────────────────────────────────────────────────── */
180
181 /**
182 * Begin watching VCS status for `target`.
183 *
184 * Multiple watchers sharing the same `environmentId:cwd` key share
185 * one `onStatus` WS subscription (ref-counted).
186 *
187 * @param target The environment + cwd to watch.
188 * @param client Optional pre-resolved client — skips `getClient`
189 * lookup and reconnection handling. Useful in tests.
190 * @returns An unwatch function.
191 */
192 function watch(target: VcsStatusTarget, client?: VcsStatusClient): () => void {
193 const targetKey = getVcsStatusTargetKey(target);
194 if (targetKey === null || target.environmentId === null || target.cwd === null) {
195 return NOOP;
196 }
197
198 const existing = watched.get(targetKey);
199 if (existing) {
200 existing.refCount += 1;
201 return () => unwatch(targetKey);
202 }
203
204 let teardown: () => void;
205
206 if (client) {
207 // Explicit client — direct subscription, no reconnection handling.
208 teardown = subscribeStream(targetKey, target.cwd, client);
209 } else if (config.subscribeClientChanges) {
210 // Dynamic client — subscribe to connection changes for reconnection.
211 teardown = createDynamicSubscription(targetKey, target);
212 } else {
213 // One-shot client resolution.
214 const resolved = config.getClient(target.environmentId);
215 if (!resolved) return NOOP;
216 teardown = subscribeStream(targetKey, target.cwd, resolved);
217 }
218
219 watched.set(targetKey, { refCount: 1, teardown });
220 return () => unwatch(targetKey);
221 }
222
223 function unwatch(targetKey: string): void {
224 const entry = watched.get(targetKey);
225 if (!entry) return;
226
227 entry.refCount -= 1;
228 if (entry.refCount > 0) return;
229
230 entry.teardown();
231 watched.delete(targetKey);
232 }
233
234 /**
235 * Trigger a one-shot `refreshStatus` RPC for a target.
236 * Debounced (1 s) and deduplicated (in-flight).
237 * The server-side refresh pushes a new event on the existing
238 * `onStatus` stream, so the subscription picks it up automatically.
239 */
240 function refresh(
241 target: VcsStatusTarget,
242 client?: VcsStatusClient,
243 ): Promise<VcsStatusResult | null> {
244 const targetKey = getVcsStatusTargetKey(target);
245 if (targetKey === null || target.cwd === null) {
246 return Promise.resolve(null);
247 }
248
249 const resolved =
250 client ?? (target.environmentId ? config.getClient(target.environmentId) : null);
251 if (!resolved) {
252 return Promise.resolve(getSnapshot(target).data);
253 }
254
255 const existing = refreshInFlight.get(targetKey);
256 if (existing) return existing;
257
258 const requestedAt = nowMs();
259 const last = lastRefreshAt.get(targetKey) ?? 0;
260 if (requestedAt - last < VCS_STATUS_REFRESH_DEBOUNCE_MS) {
261 return Promise.resolve(getSnapshot(target).data);
262 }
263
264 lastRefreshAt.set(targetKey, requestedAt);
265 const promise = resolved
266 .refreshStatus({ cwd: target.cwd })
267 .finally(() => refreshInFlight.delete(targetKey));
268 refreshInFlight.set(targetKey, promise);
269 return promise;
270 }
271
272 function getSnapshot(target: VcsStatusTarget): VcsStatusState {
273 const targetKey = getVcsStatusTargetKey(target);
274 if (targetKey === null) return EMPTY_VCS_STATUS_STATE;
275 return config.getRegistry().get(vcsStatusStateAtom(targetKey));
276 }
277
278 function reset(): void {
279 for (const entry of watched.values()) {
280 entry.teardown();
281 }
282 watched.clear();
283 refreshInFlight.clear();
284 lastRefreshAt.clear();
285 for (const key of knownVcsStatusKeys) {
286 config.getRegistry().set(vcsStatusStateAtom(key), INITIAL_VCS_STATUS_STATE);
287 }
288 knownVcsStatusKeys.clear();
289 }
290
291 return { watch, refresh, getSnapshot, reset };
292}