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

GitStatusBroadcaster.ts

307 lines9.6 KB

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;
35​
36interface CachedValue<T> {
37 readonly fingerprint: string;
38 readonly value: T;
40​
41interface CachedGitStatus {
42 readonly local: CachedValue<GitStatusLocalResult> | null;
43 readonly remote: CachedValue<GitStatusRemoteResult | null> | null;
45​
46interface ActiveRemotePoller {
47 readonly fiber: Fiber.Fiber<void, never>;
48 readonly subscriberCount: number;
50​
51function normalizeCwd(cwd: string): string {
52 try {
53 return realpathSync.native(cwd);
54 } catch {
55 return cwd;
56 }
58​
59function fingerprintStatusPart(status: unknown): string {
60 return JSON.stringify(status);
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 = Effect.fn("refreshLocalStatus")(function* (cwd: string) {
183 yield* gitManager.invalidateLocalStatus(cwd);
184 const local = yield* gitManager.localStatus({ cwd });
185 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
186 });
187​
188 const refreshRemoteStatus = Effect.fn("refreshRemoteStatus")(function* (cwd: string) {
189 yield* gitManager.invalidateRemoteStatus(cwd);
190 const remote = yield* gitManager.remoteStatus({ cwd });
191 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
192 });
193​
194 const refreshStatus: GitStatusBroadcasterShape["refreshStatus"] = Effect.fn("refreshStatus")(
195 function* (cwd) {
196 const normalizedCwd = normalizeCwd(cwd);
197 const [local, remote] = yield* Effect.all([
198 refreshLocalStatus(normalizedCwd),
199 refreshRemoteStatus(normalizedCwd),
200 ]);
201 return mergeGitStatusParts(local, remote);
202 },
203 );
204​
205 const makeRemoteRefreshLoop = (cwd: string) => {
206 const logRefreshFailure = (error: Error) =>
207 Effect.logWarning("git remote status refresh failed", {
208 cwd,
209 detail: error.message,
210 });
211​
212 return refreshRemoteStatus(cwd).pipe(
213 Effect.catch(logRefreshFailure),
214 Effect.andThen(
215 Effect.forever(
216 Effect.sleep(GIT_STATUS_REFRESH_INTERVAL).pipe(
217 Effect.andThen(refreshRemoteStatus(cwd).pipe(Effect.catch(logRefreshFailure))),
218 ),
219 ),
220 ),
221 );
222 };
223​
224 const retainRemotePoller = Effect.fn("retainRemotePoller")(function* (cwd: string) {
225 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
226 const existing = activePollers.get(cwd);
227 if (existing) {
228 const nextPollers = new Map(activePollers);
229 nextPollers.set(cwd, {
230 ...existing,
231 subscriberCount: existing.subscriberCount + 1,
232 });
233 return Effect.succeed([undefined, nextPollers] as const);
234 }
235​
236 return makeRemoteRefreshLoop(cwd).pipe(
237 Effect.forkIn(broadcasterScope),
238 Effect.map((fiber) => {
239 const nextPollers = new Map(activePollers);
240 nextPollers.set(cwd, {
241 fiber,
242 subscriberCount: 1,
243 });
244 return [undefined, nextPollers] as const;
245 }),
246 );
247 });
248 });
249​
250 const releaseRemotePoller = Effect.fn("releaseRemotePoller")(function* (cwd: string) {
251 const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
252 const existing = activePollers.get(cwd);
253 if (!existing) {
254 return [null, activePollers] as const;
255 }
256​
257 if (existing.subscriberCount > 1) {
258 const nextPollers = new Map(activePollers);
259 nextPollers.set(cwd, {
260 ...existing,
261 subscriberCount: existing.subscriberCount - 1,
262 });
263 return [null, nextPollers] as const;
264 }
265​
266 const nextPollers = new Map(activePollers);
267 nextPollers.delete(cwd);
268 return [existing.fiber, nextPollers] as const;
269 });
270​
271 if (pollerToInterrupt) {
272 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
273 }
274 });
275​
276 const streamStatus: GitStatusBroadcasterShape["streamStatus"] = (input) =>
277 Stream.unwrap(
278 Effect.gen(function* () {
279 const normalizedCwd = normalizeCwd(input.cwd);
280 const subscription = yield* PubSub.subscribe(changesPubSub);
281 const initialLocal = yield* getOrLoadLocalStatus(normalizedCwd);
282 const initialRemote = (yield* getCachedStatus(normalizedCwd))?.remote?.value ?? null;
283 yield* retainRemotePoller(normalizedCwd);
284​
285 const release = releaseRemotePoller(normalizedCwd).pipe(Effect.ignore, Effect.asVoid);
286​
287 return Stream.concat(
288 Stream.make({
289 _tag: "snapshot" as const,
290 local: initialLocal,
291 remote: initialRemote,
292 }),
293 Stream.fromSubscription(subscription).pipe(
294 Stream.filter((event) => event.cwd === normalizedCwd),
295 Stream.map((event) => event.event),
296 ),
297 ).pipe(Stream.ensuring(release));
298 }),
299 );
300​
301 return {
302 getStatus,
303 refreshStatus,
304 streamStatus,
305 } satisfies GitStatusBroadcasterShape;
306 }),
307);