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 yield* Effect.all([workflow.invalidateLocalStatus(cwd), workflow.invalidateRemoteStatus(cwd)], {
370 concurrency: "unbounded",
371 discard: true,
372 });
373 const [local, remote] = yield* Effect.all(
374 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd })],
375 { concurrency: "unbounded" },
376 );
377 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
378 });
379
380 const makeRemoteRefreshLoop = (
381 cwd: string,
382 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
383 refreshImmediately: boolean,
384 ) => {
385 return Effect.gen(function* () {
386 const consecutiveFailuresRef = yield* Ref.make(0);
387 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
388 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
389 const configuredInterval = yield* automaticRemoteRefreshInterval;
390 const activeInterval = Duration.isZero(configuredInterval)
391 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
392 : configuredInterval;
393 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
394 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
395 return activeInterval;
396 }
397
398 const exit = yield* refreshRemoteStatus(cwd, {
399 refreshUpstream: !Duration.isZero(configuredInterval),
400 }).pipe(Effect.exit);
401 if (Exit.isSuccess(exit)) {
402 yield* Ref.set(needsInitialRefreshRef, false);
403 yield* Ref.set(consecutiveFailuresRef, 0);
404 return activeInterval;
405 }
406
407 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
408 if (interruptionReasons.length > 0) {
409 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
410 }
411
412 const consecutiveFailures = yield* Ref.updateAndGet(
413 consecutiveFailuresRef,
414 (count) => count + 1,
415 );
416 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
417 yield* Effect.logWarning("VCS remote status refresh failed", {
418 cwdLength: cwd.length,
419 ...remoteRefreshFailureDiagnostics(exit.cause),
420 consecutiveFailures,
421 nextDelayMs: Duration.toMillis(nextDelay),
422 });
423 return nextDelay;
424 });
425
426 if (!refreshImmediately) {
427 const configuredInterval = yield* automaticRemoteRefreshInterval;
428 yield* Effect.sleep(
429 Duration.isZero(configuredInterval)
430 ? DEFAULT_VCS_STATUS_REFRESH_INTERVAL
431 : configuredInterval,
432 );
433 }
434
435 return yield* refreshRemoteStatusIfEnabled.pipe(
436 Effect.repeat(
437 Schedule.identity<Duration.Duration>().pipe(
438 Schedule.addDelay((delay) => Effect.succeed(delay)),
439 ),
440 ),
441 Effect.asVoid,
442 );
443 });
444 };
445
446 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
447 cwd: string,
448 automaticRemoteRefreshInterval: Effect.Effect<Duration.Duration, never>,
449 refreshImmediately: boolean,
450 ) {
451 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
452 const existing = activePollers.get(cwd);
453 if (existing) {
454 const nextPollers = new Map(activePollers);
455 nextPollers.set(cwd, {
456 ...existing,
457 subscriberCount: existing.subscriberCount + 1,
458 });
459 return Effect.succeed([undefined, nextPollers] as const);
460 }
461
462 return makeRemoteRefreshLoop(cwd, automaticRemoteRefreshInterval, refreshImmediately).pipe(
463 Effect.forkIn(broadcasterScope),
464 Effect.map((fiber) => {
465 const nextPollers = new Map(activePollers);
466 nextPollers.set(cwd, {
467 fiber,
468 subscriberCount: 1,
469 });
470 return [undefined, nextPollers] as const;
471 }),
472 );
473 });
474 });
475
476 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
477 cwd: string,
478 ) {
479 const pollerToInterrupt = yield* SynchronizedRef.modify(pollersRef, (activePollers) => {
480 const existing = activePollers.get(cwd);
481 if (!existing) {
482 return [null, activePollers] as const;
483 }
484
485 if (existing.subscriberCount > 1) {
486 const nextPollers = new Map(activePollers);
487 nextPollers.set(cwd, {
488 ...existing,
489 subscriberCount: existing.subscriberCount - 1,
490 });
491 return [null, nextPollers] as const;
492 }
493
494 const nextPollers = new Map(activePollers);
495 nextPollers.delete(cwd);
496 return [existing.fiber, nextPollers] as const;
497 });
498
499 if (pollerToInterrupt) {
500 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
501 }
502 });
503
504 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input, options) =>
505 Stream.unwrap(
506 Effect.gen(function* () {
507 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
508 const subscription = yield* PubSub.subscribe(changesPubSub);
509 const initialLocal = yield* getOrLoadLocalStatus(cwd);
510 const cachedStatus = yield* getCachedStatus(cwd);
511 const initialRemote = cachedStatus?.remote?.value ?? null;
512 yield* retainRemotePoller(
513 cwd,
514 options?.automaticRemoteRefreshInterval ??
515 Effect.succeed(DEFAULT_VCS_STATUS_REFRESH_INTERVAL),
516 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
517 );
518
519 const release = releaseRemotePoller(cwd).pipe(Effect.ignore, Effect.asVoid);
520
521 return Stream.concat(
522 Stream.make({
523 _tag: "snapshot" as const,
524 local: initialLocal,
525 remote: initialRemote,
526 }),
527 Stream.fromSubscription(subscription).pipe(
528 Stream.filter((event) => event.cwd === cwd),
529 Stream.map((event) => event.event),
530 ),
531 ).pipe(Stream.ensuring(release));
532 }),
533 );
534
535 return VcsStatusBroadcaster.of({
536 getStatus,
537 refreshLocalStatus,
538 refreshStatus,
539 streamStatus,
540 });
541});
542
543export const layer = Layer.effect(VcsStatusBroadcaster, make);