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

VcsStatusBroadcaster.ts

596 lines19.3 KB

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