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

VcsStatusBroadcaster.ts

784 lines27.1 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​
89function 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​
187function 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: (
211 cwd: string,
212 options?: { readonly localOnly?: boolean },
213 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
214 readonly refreshPullRequestStatus: (
215 cwd: string,
216 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
217 readonly streamStatus: (
218 input: VcsStatusSubscriptionInput,
219 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
220 }
221>()("t3/vcs/VcsStatusBroadcaster") {}
222​
223function fingerprintStatusPart(status: unknown): string {
224 return JSON.stringify(status);
226​
227const normalizeCwd = (cwd: string) =>
228 Effect.service(FileSystem.FileSystem).pipe(
229 Effect.flatMap((fs) => fs.realPath(cwd)),
230 Effect.orElseSucceed(() => cwd),
231 );
232​
233/** @public */
234export const make = Effect.gen(function* () {
235 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
236 const autoPullPolicy = yield* VcsAutoPullPolicy;
237 const workflow = yield* GitWorkflowService.GitWorkflowService;
238 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
239 const fs = yield* FileSystem.FileSystem;
240 const changesPubSub = yield* Effect.acquireRelease(
241 PubSub.unbounded<VcsStatusChange>(),
242 (pubsub) => PubSub.shutdown(pubsub),
243 );
244 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
245 Scope.close(scope, Exit.void),
246 );
247 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
248 // One permit per cwd for remote reads that write the cache. Without it a
249 // periodic poll that started before an agent creates a PR can finish after the
250 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
251 const remoteWriteLocks = yield* KeyedLock.make<string>();
252 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
253 remoteWriteLocks.withLock(cwd, effect);
254 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
255​
256 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
257 cwd: string,
258 ) {
259 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
260 });
261​
262 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
263 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
264 const nextLocal = {
265 fingerprint: fingerprintStatusPart(local),
266 value: local,
267 } satisfies CachedValue<VcsStatusLocalResult>;
268 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
269 const previous = cache.get(cwd) ?? { local: null, remote: null };
270 const nextCache = new Map(cache);
271 nextCache.set(cwd, {
272 ...previous,
273 local: nextLocal,
274 });
275 return [previous.local?.fingerprint !== nextLocal.fingerprint, nextCache] as const;
276 });
277​
278 if (options?.publish && shouldPublish) {
279 yield* PubSub.publish(changesPubSub, {
280 cwd,
281 event: {
282 _tag: "localUpdated",
283 local,
284 },
285 });
286 }
287​
288 return local;
289 },
290 );
291​
292 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
293 function* (cwd: string, remote: VcsStatusRemoteResult | null, options?: { publish?: boolean }) {
294 const nextRemote = {
295 fingerprint: fingerprintStatusPart(remote),
296 value: remote,
297 } satisfies CachedValue<VcsStatusRemoteResult | null>;
298 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
299 const previous = cache.get(cwd) ?? { local: null, remote: null };
300 const nextCache = new Map(cache);
301 nextCache.set(cwd, {
302 ...previous,
303 remote: nextRemote,
304 });
305 return [previous.remote?.fingerprint !== nextRemote.fingerprint, nextCache] as const;
306 });
307​
308 if (options?.publish && shouldPublish) {
309 yield* PubSub.publish(changesPubSub, {
310 cwd,
311 event: {
312 _tag: "remoteUpdated",
313 remote,
314 },
315 });
316 }
317​
318 return remote;
319 },
320 );
321​
322 const updateCachedStatus = Effect.fn("VcsStatusBroadcaster.updateCachedStatus")(function* (
323 cwd: string,
324 local: VcsStatusLocalResult,
325 remote: VcsStatusRemoteResult | null,
326 options?: { publish?: boolean },
327 ) {
328 const nextLocal = {
329 fingerprint: fingerprintStatusPart(local),
330 value: local,
331 } satisfies CachedValue<VcsStatusLocalResult>;
332 const nextRemote = {
333 fingerprint: fingerprintStatusPart(remote),
334 value: remote,
335 } satisfies CachedValue<VcsStatusRemoteResult | null>;
336 const shouldPublish = yield* Ref.modify(cacheRef, (cache) => {
337 const previous = cache.get(cwd) ?? { local: null, remote: null };
338 const nextCache = new Map(cache);
339 nextCache.set(cwd, {
340 local: nextLocal,
341 remote: nextRemote,
342 });
343 return [
344 previous.local?.fingerprint !== nextLocal.fingerprint ||
345 previous.remote?.fingerprint !== nextRemote.fingerprint,
346 nextCache,
347 ] as const;
348 });
349​
350 if (options?.publish && shouldPublish) {
351 yield* PubSub.publish(changesPubSub, {
352 cwd,
353 event: {
354 _tag: "snapshot",
355 local,
356 remote,
357 },
358 });
359 }
360​
361 return mergeGitStatusParts(local, remote);
362 });
363​
364 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
365 cwd: string,
366 ) {
367 const local = yield* workflow.localStatus({ cwd });
368 return yield* updateCachedLocalStatus(cwd, local);
369 });
370​
371 const getOrLoadLocalStatus = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(function* (
372 cwd: string,
373 ) {
374 const cached = yield* getCachedStatus(cwd);
375 if (cached?.local) {
376 return cached.local.value;
377 }
378 return yield* loadLocalStatus(cwd);
379 });
380​
381 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
382​
383 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
384 "VcsStatusBroadcaster.getStatus",
385 )(function* (input) {
386 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
387 const cached = yield* getCachedStatus(cwd);
388 if (cached?.local && cached.remote) {
389 return mergeGitStatusParts(cached.local.value, cached.remote.value);
390 }
391 return yield* withRemoteWriteLock(
392 cwd,
393 Effect.gen(function* () {
394 const latest = yield* getCachedStatus(cwd);
395 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
396 const [local, remote] = yield* Effect.all(
397 [
398 latest?.local ? Effect.succeed(latest.local.value) : workflow.localStatus({ cwd }),
399 latest?.remote
400 ? Effect.succeed(latest.remote.value)
401 : workflow.remoteStatus({ cwd }, { refreshUpstream }),
402 ],
403 { concurrency: "unbounded" },
404 );
405 return yield* updateCachedStatus(cwd, local, remote);
406 }),
407 );
408 });
409​
410 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
411 function* (cwd: string) {
412 yield* workflow.invalidateLocalStatus(cwd);
413 const local = yield* workflow.localStatus({ cwd });
414 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
415 },
416 );
417​
418 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
419 "VcsStatusBroadcaster.refreshLocalStatus",
420 )(function* (rawCwd) {
421 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
422 return yield* refreshLocalStatusCore(cwd);
423 });
424​
425 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
426 cwd: string,
427 remote: VcsStatusRemoteResult | null,
428 policyCwds: ReadonlyArray<string>,
429 ) {
430 let pullAttempted = false;
431 return yield* Effect.gen(function* () {
432 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
433 concurrency: "unbounded",
434 })).some(Boolean);
435 if (
436 remote === null ||
437 !remote.hasUpstream ||
438 remote.aheadCount > 0 ||
439 remote.behindCount <= 0 ||
440 !autoPullEnabled
441 ) {
442 return null;
443 }
444​
445 yield* workflow.invalidateLocalStatus(cwd);
446 const local = yield* workflow.localStatus({ cwd });
447 if (!local.isRepo || !local.isDefaultRef || local.hasWorkingTreeChanges) return null;
448​
449 pullAttempted = true;
450 yield* workflow.pullCurrentBranch(cwd);
451 yield* workflow.invalidateStatus(cwd);
452 const [refreshedLocal, refreshedRemote] = yield* Effect.all(
453 [workflow.localStatus({ cwd }), workflow.remoteStatus({ cwd }, { refreshUpstream: false })],
454 { concurrency: "unbounded" },
455 );
456 yield* updateCachedStatus(cwd, refreshedLocal, refreshedRemote, { publish: true });
457 return { local: refreshedLocal, remote: refreshedRemote };
458 }).pipe(
459 Effect.catch((error) =>
460 Effect.gen(function* () {
461 yield* Effect.logWarning("Automatic project pull failed", {
462 cwdLength: cwd.length,
463 errorTag: error._tag,
464 });
465 if (!pullAttempted) return null;
466 // Pull can change local state before failing; propagate reconciliation failures instead of publishing stale status.
467 yield* workflow.invalidateLocalStatus(cwd);
468 const local = yield* workflow.localStatus({ cwd });
469 yield* updateCachedStatus(cwd, local, remote, { publish: true });
470 return { local, remote };
471 }),
472 ),
473 );
474 });
475​
476 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
477 cwd: string,
478 options?: {
479 readonly refreshUpstream?: boolean;
480 readonly policyCwds?: ReadonlyArray<string>;
481 },
482 ) {
483 return yield* withRemoteWriteLock(
484 cwd,
485 Effect.gen(function* () {
486 if (options?.refreshUpstream !== false) {
487 yield* workflow.invalidateRemoteStatus(cwd);
488 }
489 const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value;
490 const remote = yield* workflow.remoteStatus({ cwd }, options);
491 const pulled =
492 options?.refreshUpstream === false
493 ? null
494 : yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
495 if (pulled !== null) return pulled.remote;
496 if (
497 remote &&
498 (!previousRemote ||
499 previousRemote.aheadCount !== remote.aheadCount ||
500 previousRemote.behindCount !== remote.behindCount ||
501 previousRemote.aheadOfDefaultCount !== remote.aheadOfDefaultCount)
502 ) {
503 yield* refreshLocalStatusCore(cwd);
504 }
505 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
506 }),
507 );
508 });
509​
510 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
511 "VcsStatusBroadcaster.refreshStatus",
512 )(function* (rawCwd, options) {
513 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
514 if (options?.localOnly) {
515 return yield* withRemoteWriteLock(
516 cwd,
517 Effect.gen(function* () {
518 yield* workflow.invalidateLocalStatus(cwd);
519 const local = yield* workflow.localStatus({ cwd });
520 const previous = yield* getCachedStatus(cwd);
521 if (previous?.local?.value.refName !== local.refName) {
522 yield* workflow.invalidateRemoteStatus(cwd);
523 return yield* updateCachedStatus(cwd, local, null, { publish: true });
524 }
525 yield* updateCachedLocalStatus(cwd, local, { publish: true });
526 return mergeGitStatusParts(local, previous?.remote?.value ?? null);
527 }),
528 );
529 }
530 // Full invalidation also bypasses GitManager's slow PR cache.
531 return yield* withRemoteWriteLock(
532 cwd,
533 Effect.gen(function* () {
534 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
535 yield* workflow.invalidateStatus(cwd);
536 // Local after remote: the fetch can move the base that the Changes totals compare with.
537 const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream });
538 const local = yield* workflow.localStatus({ cwd });
539 // Without a fetch, the cached behind count cannot justify an automatic pull.
540 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remote, [rawCwd]) : null;
541 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
542 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
543 }),
544 );
545 });
546​
547 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
548 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
549 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
550 return yield* withRemoteWriteLock(
551 cwd,
552 Effect.gen(function* () {
553 const cached = yield* getCachedStatus(cwd);
554 if (cached?.remote?.value == null) return null;
555 const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);
556 const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];
557 const shouldRefresh = (yield* Effect.forEach(
558 demandCwds,
559 (demandCwd) =>
560 backgroundPolicy.shouldRunScopeWork({ type: "vcs-status", cwd: demandCwd }),
561 { concurrency: "unbounded" },
562 )).some(Boolean);
563 if (!shouldRefresh) return null;
564 // Re-resolve the branch; cached PRs may belong to a checkout's previous branch.
565 const remote = yield* workflow.remoteStatus(
566 { cwd },
567 { refreshUpstream: false, refreshMissingPullRequest: true },
568 );
569 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
570 }),
571 );
572 });
573​
574 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
575 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
576 cwd: string,
577 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
578 refreshImmediately: boolean,
579 ) {
580 const consecutiveFailuresRef = yield* Ref.make(0);
581 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
582 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
583 const configuredInterval = yield* automaticFetchInterval;
584 const activeInterval = Duration.isZero(configuredInterval)
585 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
586 : configuredInterval;
587 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
588 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
589 return activeInterval;
590 }
591​
592 const demandCwds = yield* Ref.get(demandCwdsRef);
593 const shouldRun =
594 needsInitialRefresh ||
595 (yield* Effect.forEach(
596 [...demandCwds.keys()],
597 (demandCwd) =>
598 backgroundPolicy.shouldRunScopeWork({
599 type: "vcs-status",
600 cwd: demandCwd,
601 }),
602 { concurrency: "unbounded" },
603 )).some(Boolean);
604 if (!shouldRun) {
605 return activeInterval;
606 }
607​
608 const exit = yield* refreshRemoteStatus(cwd, {
609 refreshUpstream: !Duration.isZero(configuredInterval),
610 policyCwds: [...demandCwds.keys()],
611 }).pipe(Effect.exit);
612 if (Exit.isSuccess(exit)) {
613 yield* Ref.set(needsInitialRefreshRef, false);
614 yield* Ref.set(consecutiveFailuresRef, 0);
615 return activeInterval;
616 }
617​
618 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
619 if (interruptionReasons.length > 0) {
620 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
621 }
622​
623 const consecutiveFailures = yield* Ref.updateAndGet(
624 consecutiveFailuresRef,
625 (count) => count + 1,
626 );
627 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
628 yield* Effect.logWarning("VCS remote status refresh failed", {
629 cwdLength: cwd.length,
630 ...remoteRefreshFailureDiagnostics(exit.cause),
631 consecutiveFailures,
632 nextDelayMs: Duration.toMillis(nextDelay),
633 });
634 return nextDelay;
635 });
636​
637 if (!refreshImmediately) {
638 const configuredInterval = yield* automaticFetchInterval;
639 yield* Effect.sleep(
640 Duration.isZero(configuredInterval)
641 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
642 : configuredInterval,
643 );
644 }
645​
646 return yield* refreshRemoteStatusIfEnabled.pipe(
647 Effect.repeat(
648 Schedule.identity<Duration.Duration>().pipe(
649 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
650 ),
651 ),
652 Effect.asVoid,
653 );
654 });
655​
656 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
657 cwd: string,
658 demandCwd: string,
659 refreshImmediately: boolean,
660 ) {
661 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
662 const existing = activePollers.get(cwd);
663 if (existing) {
664 return Ref.update(existing.demandCwds, (demandCwds) => {
665 const next = new Map(demandCwds);
666 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
667 return next;
668 }).pipe(
669 Effect.map(() => {
670 const nextPollers = new Map(activePollers);
671 nextPollers.set(cwd, {
672 ...existing,
673 subscriberCount: existing.subscriberCount + 1,
674 });
675 return [undefined, nextPollers] as const;
676 }),
677 );
678 }
679​
680 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
681 Effect.flatMap((demandCwds) =>
682 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
683 Effect.forkIn(broadcasterScope),
684 Effect.map((fiber) => {
685 const nextPollers = new Map(activePollers);
686 nextPollers.set(cwd, {
687 fiber,
688 subscriberCount: 1,
689 demandCwds,
690 });
691 return [undefined, nextPollers] as const;
692 }),
693 ),
694 ),
695 );
696 });
697 });
698​
699 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
700 cwd: string,
701 demandCwd: string,
702 ) {
703 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
704 const existing = activePollers.get(cwd);
705 if (!existing) {
706 return Effect.succeed([null, activePollers] as const);
707 }
708​
709 if (existing.subscriberCount > 1) {
710 return Ref.update(existing.demandCwds, (demandCwds) => {
711 const nextDemandCwds = new Map(demandCwds);
712 const count = nextDemandCwds.get(demandCwd) ?? 0;
713 if (count <= 1) {
714 nextDemandCwds.delete(demandCwd);
715 } else {
716 nextDemandCwds.set(demandCwd, count - 1);
717 }
718 return nextDemandCwds;
719 }).pipe(
720 Effect.as([
721 null,
722 new Map(activePollers).set(cwd, {
723 ...existing,
724 subscriberCount: existing.subscriberCount - 1,
725 }),
726 ] as const),
727 );
728 }
729​
730 return Effect.succeed([
731 existing.fiber,
732 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
733 ] as const);
734 });
735​
736 if (pollerToInterrupt) {
737 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
738 }
739 });
740​
741 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
742 Stream.unwrap(
743 Effect.gen(function* () {
744 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
745 const subscription = yield* PubSub.subscribe(changesPubSub);
746 const initialLocal = yield* getOrLoadLocalStatus(cwd);
747 const cachedStatus = yield* getCachedStatus(cwd);
748 const initialRemote = cachedStatus?.remote?.value ?? null;
749 if (input.includeRemote !== false) {
750 yield* retainRemotePoller(
751 cwd,
752 input.cwd,
753 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
754 );
755 }
756 const release =
757 input.includeRemote === false
758 ? Effect.void
759 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
760​
761 return Stream.concat(
762 Stream.make({
763 _tag: "snapshot" as const,
764 local: initialLocal,
765 remote: initialRemote,
766 }),
767 Stream.fromSubscription(subscription).pipe(
768 Stream.filter((event) => event.cwd === cwd),
769 Stream.map((event) => event.event),
770 ),
771 ).pipe(Stream.ensuring(release));
772 }),
773 );
774​
775 return VcsStatusBroadcaster.of({
776 getStatus,
777 refreshLocalStatus,
778 refreshStatus,
779 refreshPullRequestStatus,
780 streamStatus,
781 });
782});
783​
784export const layer = Layer.effect(VcsStatusBroadcaster, make);