Open History to see the last commit
1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Duration from "effect/Duration";
4import * as Effect from "effect/Effect";
5import * as Exit from "effect/Exit";
6import * as Fiber from "effect/Fiber";
7import * as FileSystem from "effect/FileSystem";
8import * as Layer from "effect/Layer";
9import * as PubSub from "effect/PubSub";
10import * as Ref from "effect/Ref";
11import * as Schedule from "effect/Schedule";
12import * as Scope from "effect/Scope";
13import * as Stream from "effect/Stream";
14import * as SynchronizedRef from "effect/SynchronizedRef";
15import type {
16 GitManagerServiceError,
17 VcsStatusInput,
18 VcsStatusLocalResult,
19 VcsStatusRemoteResult,
20 VcsStatusResult,
21 VcsStatusStreamEvent,
22} from "@t3tools/contracts";
23import { mergeGitStatusParts } from "@t3tools/shared/git";
24
25import * as GitWorkflowService from "../git/GitWorkflowService.ts";
26
27const DEFAULT_VCS_STATUS_REFRESH_INTERVAL = Duration.seconds(30);
28const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
29const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
30const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
31const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
32
33function boundedDiagnosticValue(value: string): string {
34 return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
35}
36
37function diagnosticValueTag(value: unknown): string {
38 try {
39 if (
40 typeof value === "object" &&
41 value !== null &&
42 "_tag" in value &&
43 typeof value._tag === "string"
44 ) {
45 return boundedDiagnosticValue(value._tag);
46 }
47 if (value instanceof Error) {
48 return boundedDiagnosticValue(value.name);
49 }
50 return typeof value;
51 } catch {
52 return "Uninspectable";
53 }
54}
55
56function diagnosticFailureOperation(value: unknown): string | undefined {
57 try {
58 if (
59 typeof value === "object" &&
60 value !== null &&
61 "operation" in value &&
62 typeof value.operation === "string"
63 ) {
64 return boundedDiagnosticValue(value.operation);
65 }
66 } catch {
67 return undefined;
68 }
69 return undefined;
70}
71
72function addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {
73 if (
74 value !== undefined &&
75 values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&
76 !values.includes(value)
77 ) {
78 values.push(value);
79 }
80}
81
82export function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
83 const failureTags: Array<string> = [];
84 const failureOperations: Array<string> = [];
85 const defectTags: Array<string> = [];
86 let failureCount = 0;
87 let defectCount = 0;
88 let interruptionCount = 0;
89
90 for (const reason of cause.reasons) {
91 if (Cause.isFailReason(reason)) {
92 failureCount += 1;
93 addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));
94 addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));
95 continue;
96 }
97 if (Cause.isDieReason(reason)) {
98 defectCount += 1;
99 addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));
100 continue;
101 }
102 interruptionCount += 1;
103 }
104
105 return {
106 reasonCount: cause.reasons.length,
107 failureCount,
108 failureTags,
109 failureOperations,
110 defectCount,
111 defectTags,
112 interruptionCount,
113 };
114}
115
116interface VcsStatusChange {
117 readonly cwd: string;
118 readonly event: VcsStatusStreamEvent;
119}
120
121interface CachedValue<T> {
122 readonly fingerprint: string;
123 readonly value: T;
124}
125
126interface CachedVcsStatus {
127 readonly local: CachedValue<VcsStatusLocalResult> | null;
128 readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
129}
130
131interface ActiveRemotePoller {
132 readonly fiber: Fiber.Fiber<void, never>;
133 readonly subscriberCount: number;
134}
135
136interface StreamStatusOptions {
137 readonly automaticRemoteRefreshInterval?: Effect.Effect<Duration.Duration, never>;
138}
139
140export function remoteRefreshFailureDelay(
141 consecutiveFailures: number,
142 configuredInterval: Duration.Duration,
143) {
144 const exponent = Math.max(0, consecutiveFailures - 1);
145 const backoffMs =
146 Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
147 const cappedBackoff = Duration.min(
148 Duration.millis(backoffMs),
149 VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
150 );
151 return Duration.max(configuredInterval, cappedBackoff);
152}
153
154export class VcsStatusBroadcaster extends Context.Service<
155 VcsStatusBroadcaster,
156 {
157 readonly getStatus: (
158 input: VcsStatusInput,
159 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
160 readonly refreshLocalStatus: (
161 cwd: string,
162 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
163 readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
164 readonly streamStatus: (
165 input: VcsStatusInput,
166 options?: StreamStatusOptions,
167 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
168 }
169>()("t3/vcs/VcsStatusBroadcaster") {}
170
171function fingerprintStatusPart(status: unknown): string {
172 return JSON.stringify(status);
173}
174
175const normalizeCwd = (cwd: string) =>
176 Effect.service(FileSystem.FileSystem).pipe(
177 Effect.flatMap((fs) => fs.realPath(cwd)),
178 Effect.orElseSucceed(() => cwd),
179 );
180
181export const make = Effect.gen(function* () {
182 const workflow = yield* GitWorkflowService.GitWorkflowService;
183 const fs = yield* FileSystem.FileSystem;
184 const changesPubSub = yield* Effect.acquireRelease(
185 PubSub.unbounded<VcsStatusChange>(),
186 (pubsub) => PubSub.shutdown(pubsub),
187 );
188 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
189 Scope.close(scope, Exit.void),
190 );
191 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
192 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
193
194 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
195 cwd: string,
196 ) {
197 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
198 });
199
200 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
201 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
202 const nextLocal = {
203 fingerprint: fingerprintStatusPart(local),
204 value: local,
205 } satisfies CachedValue<VcsStatusLocalResult>;
206 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
207 const previous = cache.get(cwd) ?? { local: null, remote: null };
208 const nextCache = new Map(cache);
209 nextCache.set(cwd, {
210 ...previous,
211 local: nextLocal,
212 });
213 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
214 });
215
216 if (options?.publish && shouldPublish) {
217 yield* PubSub.publish(changesPubSub, {
218 cwd,
219 event: {
220 _tag: "localUpdated",
221 local,
222 },
223 });
224 }
225
226 return local;
227 },
228 );
229
230 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
231 function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
232 const nextRemote = {
233 fingerprint: fingerprintStatusPart(remote),
234 value: remote,
235 } satisfies CachedValue<VcsStatusRemoteResult | null>;
236 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
237 const previous = cache.get(cwd) ?? { local: null, remote: null };
238 const nextCache = new Map(cache);
239 nextCache.set(cwd, {
240 ...previous,
241 remote: nextRemote,
242 });
243 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
244 });
245
246 if (options?.publish && shouldPublish) {
247 yield* PubSub.publish(changesPubSub, {
248 cwd,
249 event: {
250 _tag: "remoteUpdated",
251 remote,
252 },
253 });
254 }
255
256 return remote;
257 },
258 );
259
260 const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
261 cwd: string,
262 local: VcsStatusLocalResult,
263 remote: VcsStatusRemoteResult | null,
264 options?: { publish?: boolean },
265 ) {
266 const nextLocal = {
267 fingerprint: fingerprintStatusPart(local),
268 value: local,
269 } satisfies CachedValue<VcsStatusLocalResult>;
270 const nextRemote = {
271 fingerprint: fingerprintStatusPart(remote),
272 value: remote,
273 } satisfies CachedValue<VcsStatusRemoteResult | null>;
274 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
275 const previous = cache.get(cwd) ?? { local: null, remote: null };
276 const nextCache = new Map(cache);
277 nextCache.set(cwd, {
278 local: nextLocal,
279 remote: nextRemote,
280 });
281 return [
282 previous.local?.fingerprint !== nextLocal.fingerprint ||
283 previous.remote?.fingerprint !== nextRemote.fingerprint,
284 nextCache,
285 ] as const;
286 });
287
288 if (options?.publish && shouldPublish) {
289 yield* PubSub.publish(changesPubSub, {
290 cwd,
291 event: {
292 _tag: "snapshot",
293 local,
294 remote,
295 },
296 });
297 }
298
299 return mergeGitStatusParts(local, remote);
300 });
301
302 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
303 cwd: string,
304 ) {
305 const local = yield* workflow.localStatus({ cwd });
306 return yield* updateCachedLocalStatus(cwd, local);
307 });
308
309 const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
310 cwd: string,
311 ) {
312 const cached = yield* getCachedStatus(cwd);
313 if (cached?.local) {
314 return cached.local.value;
315 }
316 return yield* loadLocalStatus(cwd);
317 });
318
319 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
320
321 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
322 "VcsStatusBroadcaster.getStatus",
323 )(function* (input) {
324 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
325 const cached = yield* getCachedStatus(cwd);
326 if (cached?.local && cached.remote) {
327 return mergeGitStatusParts(cached.local.value, cached.remote.value);
328 }
329 const [local, remote] = yield* Effect.all(
330 [
331 cached?.local ? Effect.succeed(cached.local.value) : workflow.localStatus({ cwd }),
332 cached?.remote ? Effect.succeed(cached.remote.value) : workflow.remoteStatus({ cwd }),
333 ],
334 { concurrency: "unbounded" },
335 );
336 return yield* updateCachedStatus(cwd, local, remote);
337 });
338
339 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
340 function* (cwd: string) {
341 yield* workflow.invalidateLocalStatus(cwd);
342 const local = yield* workflow.localStatus({ cwd });
343 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
344 },
345 );
346
347 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
348 "VcsStatusBroadcaster.refreshLocalStatus",
349 )(function* (rawCwd) {
350 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
351 return yield* refreshLocalStatusCore(cwd);
352 });
353
354 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
355 cwd: string,
356 options?: { readonly refreshUpstream?: boolean },
357 ) {
358 if (options?.refreshUpstream !== false) {
359 yield* workflow.invalidateRemoteStatus(cwd);
360 }
361 const remote = yield* workflow.remoteStatus({ cwd }, options);
362 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
363 });
364
365 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
366 "VcsStatusBroadcaster.refreshStatus",
367 )(function* (rawCwd) {
368 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
369 // invalidateStatus (not the two partial invalidations) so an explicit
370 // refresh also bypasses GitManager's slow PR-lookup cache.
371 yield* workflow.invalidateStatus(cwd);
372 const [local, remote] = yield* Effect.all(
373 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
374 { concurrency: "unbounded" },
375 );
376 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
377 });
378
379 const makeRemoteRefreshLoop = (
380 cwd: string,
381 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
382 refreshImmediately: boolean,
383 ) => {
384 return Effect.gen(function* () {
385 const consecutiveFailuresRef = yield* Ref.make(0);
386 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
387 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
388 const configuredInterval = yield* automaticRemoteRefreshInterval;
389 const activeInterval = Duration.isZero(configuredInterval)
390 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
391 : configuredInterval;
392 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
393 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
394 return activeInterval;
395 }
396
397 const exit = yield* refreshRemoteStatus(cwd, {
398 refreshUpstream: !Duration.isZero(configuredInterval),
399 }).pipe(Effect.exit);
400 if (Exit.isSuccess(exit)) {
401 yield* Ref.set(needsInitialRefreshRef, false);
402 yield* Ref.set(consecutiveFailuresRef, 0);
403 return activeInterval;
404 }
405
406 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
407 if (interruptionReasons.length > 0) {
408 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
409 }
410
411 const consecutiveFailures = yield* Ref.updateAndGet(
412 consecutiveFailuresRef,
413 (count) => count + 1,
414 );
415 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
416 yield* Effect.logWarning("VCS remote status refresh failed", {
417 cwdLength: cwd.length,
418 ...remoteRefreshFailureDiagnostics(exit.cause),
419 consecutiveFailures,
420 nextDelayMs: Duration.toMillis(nextDelay),
421 });
422 return nextDelay;
423 });
424
425 if (!refreshImmediately) {
426 const configuredInterval = yield* automaticRemoteRefreshInterval;
427 yield* Effect.sleep(
428 Duration.isZero(configuredInterval)
429 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
430 : configuredInterval,
431 );
432 }
433
434 return yield* refreshRemoteStatusIfEnabled.pipe(
435 Effect.repeat(
436 Schedule.identity<Duration.Duration>().pipe(
437 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
438 ),
439 ),
440 Effect.asVoid,
441 );
442 });
443 };
444
445 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
446 cwd: string,
447 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
448 refreshImmediately: boolean,
449 ) {
450 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
451 const existing = activePollers.get(cwd);
452 if (existing) {
453 const nextPollers = new Map(activePollers);
454 nextPollers.set(cwd, {
455 ...existing,
456 subscriberCount: existing.subscriberCount + 1,
457 });
458 return Effect.succeed([undefined, nextPollers] as const);
459 }
460
461 return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
462 Effect.forkIn(broadcasterScope),
463 Effect.map((fiber) => {
464 const nextPollers = new Map(activePollers);
465 nextPollers.set(cwd, {
466 fiber,
467 subscriberCount: 1,
468 });
469 return [undefined, nextPollers] as const;
470 }),
471 );
472 });
473 });
474
475 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
476 cwd: string,
477 ) {
478 const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
479 const existing = activePollers.get(cwd);
480 if (!existing) {
481 return [null, activePollers] as const;
482 }
483
484 if (existing.subscriberCount > 1) {
485 const nextPollers = new Map(activePollers);
486 nextPollers.set(cwd, {
487 ...existing,
488 subscriberCount: existing.subscriberCount - 1,
489 });
490 return [null, nextPollers] as const;
491 }
492
493 const nextPollers = new Map(activePollers);
494 nextPollers.delete(cwd);
495 return [existing.fiber, nextPollers] as const;
496 });
497
498 if (pollerToInterrupt) {
499 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
500 }
501 });
502
503 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input, options) =>
504 Stream.unwrap(
505 Effect.gen(function* () {
506 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
507 const subscription = yield* PubSub.subscribe(changesPubSub);
508 const initialLocal = yield* getOrLoadLocalStatus(cwd);
509 const cachedStatus = yield* getCachedStatus(cwd);
510 const initialRemote = cachedStatus?.remote?.value ?? null;
511 yield* retainRemotePoller(
512 cwd,
513 options?.automaticRemoteRefreshInterval ??
514 Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
515 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
516 );
517
518 const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
519
520 return Stream.concat(
521 Stream.make({
522 _tag: "snapshot" as const,
523 local: initialLocal,
524 remote: initialRemote,
525 }),
526 Stream.fromSubscription(subscription).pipe(
527 Stream.filter((event) => event.cwd === cwd),
528 Stream.map((event) => event.event),
529 ),
530 ).pipe(Stream.ensuring(release));
531 }),
532 );
533
534 return VcsStatusBroadcaster.of({
535 getStatus,
536 refreshLocalStatus,
537 refreshStatus,
538 streamStatus,
539 });
540});
541
542export const layer = Layer.effect(VcsStatusBroadcaster, make);