Open History to see the last commit
1import { realpathSync } from "node:fs";
2
3import {
4 Duration,
5 Effect,
6 Exit,
7 Fiber,
8 Layer,
9 PubSub,
10 Ref,
11 Scope,
12 Stream,
13 SynchronizedRef,
14} from "effect";
15import type {
16 GitStatusInput,
17 GitStatusLocalResult,
18 GitStatusRemoteResult,
19 GitStatusStreamEvent,
20} from "@t3tools/contracts";
21import { mergeGitStatusParts } from "@t3tools/shared/git";
22
23import {
24 GitStatusBroadcaster,
25 type GitStatusBroadcasterShape,
26} from "../Services/GitStatusBroadcaster.ts";
27import { GitManager } from "../Services/GitManager.ts";
28
29const GIT_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
30
31interface GitStatusChange {
32 readonly cwd: string;
33 readonly event: GitStatusStreamEvent;
34}
35
36interface CachedValue<T> {
37 readonly fingerprint: string;
38 readonly value: T;
39}
40
41interface CachedGitStatus {
42 readonly local: CachedValue<GitStatusLocalResult> | null;
43 readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
44}
45
46interface ActiveRemotePoller {
47 readonly fiber: Fiber.Fiber<void, never>;
48 readonly subscriberCount: number;
49}
50
51function normalizeCwd(cwd: string): string {
52 try {
53 return realpathSync.native(cwd);
54 } catch {
55 return cwd;
56 }
57}
58
59function fingerprintStatusPart(status: unknown): string {
60 return JSON.stringify(status);
61}
62
63export const GitStatusBroadcasterLive = Layer.effect(
64 GitStatusBroadcaster,
65 Effect.gen(function* () {
66 const gitManager = yield* GitManager;
67 const changesPubSub = yield* Effect.acquireRelease(
68 PubSub.unbounded<GitStatusChange>(),
69 (pubsub) => PubSub.shutdown(pubsub),
70 );
71 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
72 Scope.close(scope, Exit.void),
73 );
74 const cacheRef = yield* Ref.make(new Map<string, CachedGitStatus>());
75 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
76
77 const getCachedStatus = Effect.fn("getCachedStatus")(function* (cwd: string) {
78 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
79 });
80
81 const updateCachedLocalStatus = Effect.fn("updateCachedLocalStatus")(function* (
82 cwd: string,
83 local: GitStatusLocalResult,
84 options?: { publish?: boolean },
85 ) {
86 const nextLocal = {
87 fingerprint: fingerprintStatusPart(local),
88 value: local,
89 } satisfies CachedValue<GitStatusLocalResult>;
90 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
91 const previous = cache.get(cwd) ?? { local: null, remote: null };
92 const nextCache = new Map(cache);
93 nextCache.set(cwd, {
94 ...previous,
95 local: nextLocal,
96 });
97 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
98 });
99
100 if (options?.publish && shouldPublish) {
101 yield* PubSub.publish(changesPubSub, {
102 cwd,
103 event: {
104 _tag: "localUpdated",
105 local,
106 },
107 });
108 }
109
110 return local;
111 });
112
113 const updateCachedRemoteStatus = Effect.fn("updateCachedRemoteStatus")(function* (
114 cwd: string,
115 remote: GitStatusRemoteResult | null,
116 options?: { publish?: boolean },
117 ) {
118 const nextRemote = {
119 fingerprint: fingerprintStatusPart(remote),
120 value: remote,
121 } satisfies CachedValue<GitStatusRemoteResult | null>;
122 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
123 const previous = cache.get(cwd) ?? { local: null, remote: null };
124 const nextCache = new Map(cache);
125 nextCache.set(cwd, {
126 ...previous,
127 remote: nextRemote,
128 });
129 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
130 });
131
132 if (options?.publish && shouldPublish) {
133 yield* PubSub.publish(changesPubSub, {
134 cwd,
135 event: {
136 _tag: "remoteUpdated",
137 remote,
138 },
139 });
140 }
141
142 return remote;
143 });
144
145 const loadLocalStatus = Effect.fn("loadLocalStatus")(function* (cwd: string) {
146 const local = yield* gitManager.localStatus({ cwd });
147 return yield* updateCachedLocalStatus(cwd, local);
148 });
149
150 const loadRemoteStatus = Effect.fn("loadRemoteStatus")(function* (cwd: string) {
151 const remote = yield* gitManager.remoteStatus({ cwd });
152 return yield* updateCachedRemoteStatus(cwd, remote);
153 });
154
155 const getOrLoadLocalStatus = Effect.fn("getOrLoadLocalStatus")(function* (cwd: string) {
156 const cached = yield* getCachedStatus(cwd);
157 if (cached?.local) {
158 return cached.local.value;
159 }
160 return yield* loadLocalStatus(cwd);
161 });
162
163 const getOrLoadRemoteStatus = Effect.fn("getOrLoadRemoteStatus")(function* (cwd: string) {
164 const cached = yield* getCachedStatus(cwd);
165 if (cached?.remote) {
166 return cached.remote.value;
167 }
168 return yield* loadRemoteStatus(cwd);
169 });
170
171 const getStatus: GitStatusBroadcasterShape["getStatus"] = Effect.fn("getStatus")(function* (
172 input: GitStatusInput,
173 ) {
174 const normalizedCwd = normalizeCwd(input.cwd);
175 const [local, remote] = yield* Effect.all([
176 getOrLoadLocalStatus(normalizedCwd),
177 getOrLoadRemoteStatus(normalizedCwd),
178 ]);
179 return mergeGitStatusParts(local, remote);
180 });
181
182 const refreshLocalStatus: GitStatusBroadcasterShape["refreshLocalStatus"] = Effect.fn(
183 "refreshLocalStatus",
184 )(function* (cwd) {
185 const normalizedCwd = normalizeCwd(cwd);
186 yield* gitManager.invalidateLocalStatus(normalizedCwd);
187 const local = yield* gitManager.localStatus({ cwd: normalizedCwd });
188 return yield* updateCachedLocalStatus(normalizedCwd, local, { publish: true });
189 });
190
191 const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
192 yield* gitManager.invalidateRemoteStatus(cwd);
193 const remote = yield* gitManager.remoteStatus({ cwd });
194 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
195 });
196
197 const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
198 function* (cwd) {
199 const normalizedCwd = normalizeCwd(cwd);
200 const [local, remote] = yield* Effect.all([
201 refreshLocalStatus(normalizedCwd),
202 refreshRemoteStatus(normalizedCwd),
203 ]);
204 return mergeGitStatusParts(local, remote);
205 },
206 );
207
208 const makeRemoteRefreshLoop = (cwd: string) => {
209 const logRefreshFailure = (error: Error) =>
210 Effect.logWarning("git remote status refresh failed", {
211 cwd,
212 detail: error.message,
213 });
214
215 return refreshRemoteStatus(cwd).pipe(
216 Effect.catch(logRefreshFailure),
217 Effect.andThen(
218 Effect.forever(
219 Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
220 Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
221 ),
222 ),
223 ),
224 );
225 };
226
227 const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
228 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
229 const existing = activePollers.get(cwd);
230 if (existing) {
231 const nextPollers = new Map(activePollers);
232 nextPollers.set(cwd, {
233 ...existing,
234 subscriberCount: existing.subscriberCount + 1,
235 });
236 return Effect.succeed([undefined, nextPollers] as const);
237 }
238
239 return makeRemoteRefreshLoop(cwd).pipe(
240 Effect.forkIn(broadcasterScope),
241 Effect.map((fiber) => {
242 const nextPollers = new Map(activePollers);
243 nextPollers.set(cwd, {
244 fiber,
245 subscriberCount: 1,
246 });
247 return [undefined, nextPollers] as const;
248 }),
249 );
250 });
251 });
252
253 const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
254 const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
255 const existing = activePollers.get(cwd);
256 if (!existing) {
257 return [null, activePollers] as const;
258 }
259
260 if (existing.subscriberCount > 1) {
261 const nextPollers = new Map(activePollers);
262 nextPollers.set(cwd, {
263 ...existing,
264 subscriberCount: existing.subscriberCount - 1,
265 });
266 return [null, nextPollers] as const;
267 }
268
269 const nextPollers = new Map(activePollers);
270 nextPollers.delete(cwd);
271 return [existing.fiber, nextPollers] as const;
272 });
273
274 if (pollerToInterrupt) {
275 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
276 }
277 });
278
279 const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
280 Stream.unwrap(
281 Effect.gen(function* () {
282 const normalizedCwd = normalizeCwd(input.cwd);
283 const subscription = yield* PubSub.subscribe(changesPubSub);
284 const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
285 const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
286 yield* retainRemotePoller(normalizedCwd);
287
288 const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
289
290 return Stream.concat(
291 Stream.make({
292 _tag: "snapshot" as const,
293 local: initialLocal,
294 remote: initialRemote,
295 }),
296 Stream.fromSubscription(subscription).pipe(
297 Stream.filter((event) => event.cwd === normalizedCwd),
298 Stream.map((event) => event.event),
299 ),
300 ).pipe(Stream.ensuring(release));
301 }),
302 );
303
304 return {
305 getStatus,
306 refreshLocalStatus,
307 refreshStatus,
308 streamStatus,
309 } satisfies GitStatusBroadcasterShape;
310 }),
311);