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

VcsStatusBroadcaster.ts

768 lines26.6 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 VcsStatusSubscriptionInput,
23} from "@t3tools/contracts";
24import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts";
25import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
26import { mergeGitStatusParts } from "@t3tools/shared/git";
27import * as KeyedLock from "@t3tools/shared/KeyedLock";
28import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
29​
30import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
31import * as GitWorkflowService from "../git/GitWorkflowService.ts";
32import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
33import * as ServerSettings from "../serverSettings.ts";
34​
35const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
36const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
37const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
38const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
39​
40function boundedDiagnosticValue(value: string): string {
41 return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
43​
44function diagnosticValueTag(value: unknown): string {
45 try {
46 if (
47 typeof value === "object" &&
48 value !== null &&
49 "_tag" in value &&
50 typeof value._tag === "string"
51 ) {
52 return boundedDiagnosticValue(value._tag);
53 }
54 if (value instanceof Error) {
55 return boundedDiagnosticValue(value.name);
56 }
57 return typeof value;
58 } catch {
59 return "Uninspectable";
60 }
62​
63function diagnosticFailureOperation(value: unknown): string | undefined {
64 try {
65 if (
66 typeof value === "object" &&
67 value !== null &&
68 "operation" in value &&
69 typeof value.operation === "string"
70 ) {
71 return boundedDiagnosticValue(value.operation);
72 }
73 } catch {
74 return undefined;
75 }
76 return undefined;
78​
79function addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {
80 if (
81 value !== undefined &&
82 values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&
83 !values.includes(value)
84 ) {
85 values.push(value);
86 }
88​
89export function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
90 const failureTags: Array<string> = [];
91 const failureOperations: Array<string> = [];
92 const defectTags: Array<string> = [];
93 let failureCount = 0;
94 let defectCount = 0;
95 let interruptionCount = 0;
96​
97 for (const reason of cause.reasons) {
98 if (Cause.isFailReason(reason)) {
99 failureCount += 1;
100 addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));
101 addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));
102 continue;
103 }
104 if (Cause.isDieReason(reason)) {
105 defectCount += 1;
106 addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));
107 continue;
108 }
109 interruptionCount += 1;
110 }
111​
112 return {
113 reasonCount: cause.reasons.length,
114 failureCount,
115 failureTags,
116 failureOperations,
117 defectCount,
118 defectTags,
119 interruptionCount,
120 };
122​
123interface VcsStatusChange {
124 readonly cwd: string;
125 readonly event: VcsStatusStreamEvent;
127​
128interface CachedValue<T> {
129 readonly fingerprint: string;
130 readonly value: T;
132​
133interface CachedVcsStatus {
134 readonly local: CachedValue<VcsStatusLocalResult> | null;
135 readonly remote: CachedValue<VcsStatusRemoteResult | null> | null;
137​
138interface ActiveRemotePoller {
139 readonly fiber: Fiber.Fiber<void, never>;
140 readonly subscriberCount: number;
141 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
143​
144export class VcsAutomaticFetchInterval extends Context.Reference<Effect.Effect<Duration.Duration>>(
145 "t3/vcs/VcsAutomaticFetchInterval",
146 { defaultValue: () => Effect.succeed(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) },
147) {}
148​
149export const layerAutomaticFetchInterval = Layer.effect(
150 VcsAutomaticFetchInterval,
151 Effect.gen(function* () {
152 const serverSettings = yield* ServerSettings.ServerSettingsService;
153 return serverSettings.getSettings.pipe(
154 Effect.map(
155 (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
156 ),
157 Effect.orElseSucceed(() => DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL),
158 );
159 }),
160);
161​
162export class VcsAutoPullPolicy extends Context.Reference<{
163 readonly isEnabled: (cwd: string) => Effect.Effect<boolean, never>;
164}>("t3/vcs/VcsAutoPullPolicy", {
165 defaultValue: () => ({ isEnabled: () => Effect.succeed(false) }),
166}) {}
167​
168export const layerAutoPullPolicy = Layer.effect(
169 VcsAutoPullPolicy,
170 Effect.gen(function* () {
171 const projects = yield* ProjectStore.ProjectStoreV2;
172 const serverSettings = yield* ServerSettings.ServerSettingsService;
173 return {
174 isEnabled: Effect.fn("VcsAutoPullPolicy.isEnabled")(
175 function* (cwd: string) {
176 const project = yield* projects.findActiveByWorkspaceRoot(cwd);
177 if (project._tag === "None") return false;
178 const settings = yield* serverSettings.getSettings;
179 return resolveProjectSettings(settings, project.value.projectId).settings.defaultAutoPull;
180 },
181 Effect.orElseSucceed(() => false),
182 ),
183 };
184 }),
185);
186​
187export function remoteRefreshFailureDelay(
188 consecutiveFailures: number,
189 configuredInterval: Duration.Duration,
190) {
191 const exponent = Math.max(0, consecutiveFailures - 1);
192 const backoffMs =
193 Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
194 const cappedBackoff = Duration.min(
195 Duration.millis(backoffMs),
196 VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
197 );
198 return Duration.max(configuredInterval, cappedBackoff);
200​
201export class VcsStatusBroadcaster extends Context.Service<
202 VcsStatusBroadcaster,
203 {
204 readonly getStatus: (
205 input: VcsStatusInput,
206 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
207 readonly refreshLocalStatus: (
208 cwd: string,
209 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
210 readonly refreshStatus: (cwd: string) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
211 readonly refreshPullRequestStatus: (
212 cwd: string,
213 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
214 readonly streamStatus: (
215 input: VcsStatusSubscriptionInput,
216 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
217 }
218>()("t3/vcs/VcsStatusBroadcaster") {}
219​
220function fingerprintStatusPart(status: unknown): string {
221 return JSON.stringify(status);
223​
224const normalizeCwd = (cwd: string) =>
225 Effect.service(FileSystem.FileSystem).pipe(
226 Effect.flatMap((fs) => fs.realPath(cwd)),
227 Effect.orElseSucceed(() => cwd),
228 );
229​
230/** @public Service construction is part of the canonical Effect module API. */
231export const make = Effect.gen(function* () {
232 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
233 const autoPullPolicy = yield* VcsAutoPullPolicy;
234 const workflow = yield* GitWorkflowService.GitWorkflowService;
235 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
236 const fs = yield* FileSystem.FileSystem;
237 const changesPubSub = yield* Effect.acquireRelease(
238 PubSub.unbounded<VcsStatusChange>(),
239 (pubsub) => PubSub.shutdown(pubsub),
240 );
241 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
242 Scope.close(scope, Exit.void),
243 );
244 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
245 // One permit per cwd for remote reads that write the cache. Without it a
246 // periodic poll that started before `gh pr create` can finish after the
247 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
248 const remoteWriteLocks = yield* KeyedLock.make<string>();
249 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
250 remoteWriteLocks.withLock(cwd, effect);
251 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
252​
253 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
254 cwd: string,
255 ) {
256 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
257 });
258​
259 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
260 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
261 const nextLocal = {
262 fingerprint: fingerprintStatusPart(local),
263 value: local,
264 } satisfies CachedValue<VcsStatusLocalResult>;
265 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
266 const previous = cache.get(cwd) ?? { local: null, remote: null };
267 const nextCache = new Map(cache);
268 nextCache.set(cwd, {
269 ...previous,
270 local: nextLocal,
271 });
272 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
273 });
274​
275 if (options?.publish && shouldPublish) {
276 yield* PubSub.publish(changesPubSub, {
277 cwd,
278 event: {
279 _tag: "localUpdated",
280 local,
281 },
282 });
283 }
284​
285 return local;
286 },
287 );
288​
289 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
290 function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
291 const nextRemote = {
292 fingerprint: fingerprintStatusPart(remote),
293 value: remote,
294 } satisfies CachedValue<VcsStatusRemoteResult | null>;
295 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
296 const previous = cache.get(cwd) ?? { local: null, remote: null };
297 const nextCache = new Map(cache);
298 nextCache.set(cwd, {
299 ...previous,
300 remote: nextRemote,
301 });
302 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
303 });
304​
305 if (options?.publish && shouldPublish) {
306 yield* PubSub.publish(changesPubSub, {
307 cwd,
308 event: {
309 _tag: "remoteUpdated",
310 remote,
311 },
312 });
313 }
314​
315 return remote;
316 },
317 );
318​
319 const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
320 cwd: string,
321 local: VcsStatusLocalResult,
322 remote: VcsStatusRemoteResult | null,
323 options?: { publish?: boolean },
324 ) {
325 const nextLocal = {
326 fingerprint: fingerprintStatusPart(local),
327 value: local,
328 } satisfies CachedValue<VcsStatusLocalResult>;
329 const nextRemote = {
330 fingerprint: fingerprintStatusPart(remote),
331 value: remote,
332 } satisfies CachedValue<VcsStatusRemoteResult | null>;
333 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
334 const previous = cache.get(cwd) ?? { local: null, remote: null };
335 const nextCache = new Map(cache);
336 nextCache.set(cwd, {
337 local: nextLocal,
338 remote: nextRemote,
339 });
340 return [
341 previous.local?.fingerprint !== nextLocal.fingerprint ||
342 previous.remote?.fingerprint !== nextRemote.fingerprint,
343 nextCache,
344 ] as const;
345 });
346​
347 if (options?.publish && shouldPublish) {
348 yield* PubSub.publish(changesPubSub, {
349 cwd,
350 event: {
351 _tag: "snapshot",
352 local,
353 remote,
354 },
355 });
356 }
357​
358 return mergeGitStatusParts(local, remote);
359 });
360​
361 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
362 cwd: string,
363 ) {
364 const local = yield* workflow.localStatus({ cwd });
365 return yield* updateCachedLocalStatus(cwd, local);
366 });
367​
368 const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
369 cwd: string,
370 ) {
371 const cached = yield* getCachedStatus(cwd);
372 if (cached?.local) {
373 return cached.local.value;
374 }
375 return yield* loadLocalStatus(cwd);
376 });
377​
378 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
379​
380 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
381 "VcsStatusBroadcaster.getStatus",
382 )(function* (input) {
383 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
384 const cached = yield* getCachedStatus(cwd);
385 if (cached?.local && cached.remote) {
386 return mergeGitStatusParts(cached.local.value, cached.remote.value);
387 }
388 return yield* withRemoteWriteLock(
389 cwd,
390 Effect.gen(function* () {
391 const latest = yield* getCachedStatus(cwd);
392 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
393 const [local, remote] = yield* Effect.all(
394 [
395 latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),
396 latest?.remote
397 ? Effect.succeed(latest.remote.value)
398 : workflow.remoteStatus({ cwd }, { refreshUpstream }),
399 ],
400 { concurrency: "unbounded" },
401 );
402 return yield* updateCachedStatus(cwd, local, remote);
403 }),
404 );
405 });
406​
407 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
408 function* (cwd: string) {
409 yield* workflow.invalidateLocalStatus(cwd);
410 const local = yield* workflow.localStatus({ cwd });
411 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
412 },
413 );
414​
415 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
416 "VcsStatusBroadcaster.refreshLocalStatus",
417 )(function* (rawCwd) {
418 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
419 return yield* refreshLocalStatusCore(cwd);
420 });
421​
422 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
423 cwd: string,
424 remote: VcsStatusRemoteResult | null,
425 policyCwds: ReadonlyArray<string>,
426 ) {
427 let pullAttempted = false;
428 return yield* Effect.gen(function* () {
429 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
430 concurrency: "unbounded",
431 })).some(Boolean);
432 if (
433 remote === null ||
434 !remote.hasUpstream ||
435 remote.aheadCount > 0 ||
436 remote.behindCount <= 0 ||
437 !autoPullEnabled
438 ) {
439 return null;
440 }
441​
442 yield* workflow.invalidateLocalStatus(cwd);
443 const local = yield* workflow.localStatus({ cwd });
444 if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;
445​
446 pullAttempted = true;
447 yield* workflow.pullCurrentBranch(cwd);
448 yield* workflow.invalidateStatus(cwd);
449 const [refreshedLocal, refreshedRemote] = yield* Effect.all(
450 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],
451 { concurrency: "unbounded" },
452 );
453 yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });
454 return { local: refreshedLocal, remote: refreshedRemote };
455 }).pipe(
456 Effect.catch((error) =>
457 Effect.gen(function* () {
458 yield* Effect.logWarning("Automatic project pull failed", {
459 cwdLength: cwd.length,
460 errorTag: error._tag,
461 });
462 if (!pullAttempted) return null;
463 // A pull or its follow-up reads can fail after local state has changed.
464 // Let a failed reconciliation reach the caller instead of publishing old status.
465 yield* workflow.invalidateLocalStatus(cwd);
466 const local = yield* workflow.localStatus({ cwd });
467 yield* updateCachedStatus(cwd, local, remote, { publish: true });
468 return { local, remote };
469 }),
470 ),
471 );
472 });
473​
474 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
475 cwd: string,
476 options?: {
477 readonly refreshUpstream?: boolean;
478 readonly policyCwds?: ReadonlyArray<string>;
479 },
480 ) {
481 return yield* withRemoteWriteLock(
482 cwd,
483 Effect.gen(function* () {
484 if (options?.refreshUpstream !== false) {
485 yield* workflow.invalidateRemoteStatus(cwd);
486 }
487 const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value;
488 const remote = yield* workflow.remoteStatus({ cwd }, options);
489 const pulled =
490 options?.refreshUpstream === false
491 ? null
492 : yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
493 if (pulled !== null) return pulled.remote;
494 if (
495 remote &&
496 (!previousRemote ||
497 previousRemote.aheadCount !== remote.aheadCount ||
498 previousRemote.behindCount !== remote.behindCount ||
499 previousRemote.aheadOfDefaultCount !== remote.aheadOfDefaultCount)
500 ) {
501 yield* refreshLocalStatusCore(cwd);
502 }
503 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
504 }),
505 );
506 });
507​
508 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
509 "VcsStatusBroadcaster.refreshStatus",
510 )(function* (rawCwd) {
511 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
512 // invalidateStatus (not the two partial invalidations) so an explicit
513 // refresh also bypasses GitManager's slow PR-lookup cache.
514 return yield* withRemoteWriteLock(
515 cwd,
516 Effect.gen(function* () {
517 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
518 yield* workflow.invalidateStatus(cwd);
519 // Local after remote: the fetch can move the base that the Changes totals compare with.
520 const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream });
521 const local = yield* workflow.localStatus({ cwd });
522 // Without a fetch, the cached behind count cannot justify an automatic pull.
523 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remote, [rawCwd]) : null;
524 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
525 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
526 }),
527 );
528 });
529​
530 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
531 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
532 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
533 return yield* withRemoteWriteLock(
534 cwd,
535 Effect.gen(function* () {
536 const cached = yield* getCachedStatus(cwd);
537 if (cached?.remote?.value == null) return null;
538 const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);
539 const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];
540 const shouldRefresh = (yield* Effect.forEach(
541 demandCwds,
542 (demandCwd) =>
543 backgroundPolicy.shouldRunScopeWork({ type: "vcs-status", cwd: demandCwd }),
544 { concurrency: "unbounded" },
545 )).some(Boolean);
546 if (!shouldRefresh) return null;
547 // Resolve the checked-out branch again. A cached PR can belong to
548 // the previous branch after an agent checks out another branch.
549 const remote = yield* workflow.remoteStatus(
550 { cwd },
551 { refreshUpstream: false, refreshMissingPullRequest: true },
552 );
553 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
554 }),
555 );
556 });
557​
558 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
559 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
560 cwd: string,
561 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
562 refreshImmediately: boolean,
563 ) {
564 const consecutiveFailuresRef = yield* Ref.make(0);
565 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
566 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
567 const configuredInterval = yield* automaticFetchInterval;
568 const activeInterval = Duration.isZero(configuredInterval)
569 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
570 : configuredInterval;
571 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
572 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
573 return activeInterval;
574 }
575​
576 const demandCwds = yield* Ref.get(demandCwdsRef);
577 const shouldRun =
578 needsInitialRefresh ||
579 (yield* Effect.forEach(
580 [...demandCwds.keys()],
581 (demandCwd) =>
582 backgroundPolicy.shouldRunScopeWork({
583 type: "vcs-status",
584 cwd: demandCwd,
585 }),
586 { concurrency: "unbounded" },
587 )).some(Boolean);
588 if (!shouldRun) {
589 return activeInterval;
590 }
591​
592 const exit = yield* refreshRemoteStatus(cwd, {
593 refreshUpstream: !Duration.isZero(configuredInterval),
594 policyCwds: [...demandCwds.keys()],
595 }).pipe(Effect.exit);
596 if (Exit.isSuccess(exit)) {
597 yield* Ref.set(needsInitialRefreshRef, false);
598 yield* Ref.set(consecutiveFailuresRef, 0);
599 return activeInterval;
600 }
601​
602 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
603 if (interruptionReasons.length > 0) {
604 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
605 }
606​
607 const consecutiveFailures = yield* Ref.updateAndGet(
608 consecutiveFailuresRef,
609 (count) => count + 1,
610 );
611 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
612 yield* Effect.logWarning("VCS remote status refresh failed", {
613 cwdLength: cwd.length,
614 ...remoteRefreshFailureDiagnostics(exit.cause),
615 consecutiveFailures,
616 nextDelayMs: Duration.toMillis(nextDelay),
617 });
618 return nextDelay;
619 });
620​
621 if (!refreshImmediately) {
622 const configuredInterval = yield* automaticFetchInterval;
623 yield* Effect.sleep(
624 Duration.isZero(configuredInterval)
625 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
626 : configuredInterval,
627 );
628 }
629​
630 return yield* refreshRemoteStatusIfEnabled.pipe(
631 Effect.repeat(
632 Schedule.identity<Duration.Duration>().pipe(
633 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
634 ),
635 ),
636 Effect.asVoid,
637 );
638 });
639​
640 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
641 cwd: string,
642 demandCwd: string,
643 refreshImmediately: boolean,
644 ) {
645 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
646 const existing = activePollers.get(cwd);
647 if (existing) {
648 return Ref.update(existing.demandCwds, (demandCwds) => {
649 const next = new Map(demandCwds);
650 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
651 return next;
652 }).pipe(
653 Effect.map(() => {
654 const nextPollers = new Map(activePollers);
655 nextPollers.set(cwd, {
656 ...existing,
657 subscriberCount: existing.subscriberCount + 1,
658 });
659 return [undefined, nextPollers] as const;
660 }),
661 );
662 }
663​
664 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
665 Effect.flatMap((demandCwds) =>
666 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
667 Effect.forkIn(broadcasterScope),
668 Effect.map((fiber) => {
669 const nextPollers = new Map(activePollers);
670 nextPollers.set(cwd, {
671 fiber,
672 subscriberCount: 1,
673 demandCwds,
674 });
675 return [undefined, nextPollers] as const;
676 }),
677 ),
678 ),
679 );
680 });
681 });
682​
683 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
684 cwd: string,
685 demandCwd: string,
686 ) {
687 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
688 const existing = activePollers.get(cwd);
689 if (!existing) {
690 return Effect.succeed([null, activePollers] as const);
691 }
692​
693 if (existing.subscriberCount > 1) {
694 return Ref.update(existing.demandCwds, (demandCwds) => {
695 const nextDemandCwds = new Map(demandCwds);
696 const count = nextDemandCwds.get(demandCwd) ?? 0;
697 if (count <= 1) {
698 nextDemandCwds.delete(demandCwd);
699 } else {
700 nextDemandCwds.set(demandCwd, count - 1);
701 }
702 return nextDemandCwds;
703 }).pipe(
704 Effect.as([
705 null,
706 new Map(activePollers).set(cwd, {
707 ...existing,
708 subscriberCount: existing.subscriberCount - 1,
709 }),
710 ] as const),
711 );
712 }
713​
714 return Effect.succeed([
715 existing.fiber,
716 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
717 ] as const);
718 });
719​
720 if (pollerToInterrupt) {
721 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
722 }
723 });
724​
725 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
726 Stream.unwrap(
727 Effect.gen(function* () {
728 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
729 const subscription = yield* PubSub.subscribe(changesPubSub);
730 const initialLocal = yield* getOrLoadLocalStatus(cwd);
731 const cachedStatus = yield* getCachedStatus(cwd);
732 const initialRemote = cachedStatus?.remote?.value ?? null;
733 if (input.includeRemote !== false) {
734 yield* retainRemotePoller(
735 cwd,
736 input.cwd,
737 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
738 );
739 }
740 const release =
741 input.includeRemote === false
742 ? Effect.void
743 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
744​
745 return Stream.concat(
746 Stream.make({
747 _tag: "snapshot" as const,
748 local: initialLocal,
749 remote: initialRemote,
750 }),
751 Stream.fromSubscription(subscription).pipe(
752 Stream.filter((event) => event.cwd === cwd),
753 Stream.map((event) => event.event),
754 ),
755 ).pipe(Stream.ensuring(release));
756 }),
757 );
758​
759 return VcsStatusBroadcaster.of({
760 getStatus,
761 refreshLocalStatus,
762 refreshStatus,
763 refreshPullRequestStatus,
764 streamStatus,
765 });
766});
767​
768export const layer = Layer.effect(VcsStatusBroadcaster, make);