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

VcsStatusBroadcaster.ts

344 lines10.6 KB

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