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

VcsStatusBroadcaster.ts

765 lines26.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 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: (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 */
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 an agent creates a PR 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 // Pull can change local state before failing; propagate reconciliation failures instead of publishing stale status.
464 yield* workflow.invalidateLocalStatus(cwd);
465 const local = yield* workflow.localStatus({ cwd });
466 yield* updateCachedStatus(cwd, local, remote, { publish: true });
467 return { local, remote };
468 }),
469 ),
470 );
471 });
472​
473 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
474 cwd: string,
475 options?: {
476 readonly refreshUpstream?: boolean;
477 readonly policyCwds?: ReadonlyArray<string>;
478 },
479 ) {
480 return yield* withRemoteWriteLock(
481 cwd,
482 Effect.gen(function* () {
483 if (options?.refreshUpstream !== false) {
484 yield* workflow.invalidateRemoteStatus(cwd);
485 }
486 const previousRemote = (yield* getCachedStatus(cwd))?.remote?.value;
487 const remote = yield* workflow.remoteStatus({ cwd }, options);
488 const pulled =
489 options?.refreshUpstream === false
490 ? null
491 : yield* maybeAutoPull(cwd, remote, options?.policyCwds ?? [cwd]);
492 if (pulled !== null) return pulled.remote;
493 if (
494 remote &&
495 (!previousRemote ||
496 previousRemote.aheadCount !== remote.aheadCount ||
497 previousRemote.behindCount !== remote.behindCount ||
498 previousRemote.aheadOfDefaultCount !== remote.aheadOfDefaultCount)
499 ) {
500 yield* refreshLocalStatusCore(cwd);
501 }
502 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
503 }),
504 );
505 });
506​
507 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
508 "VcsStatusBroadcaster.refreshStatus",
509 )(function* (rawCwd) {
510 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
511 // Full invalidation also bypasses GitManager's slow PR cache.
512 return yield* withRemoteWriteLock(
513 cwd,
514 Effect.gen(function* () {
515 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
516 yield* workflow.invalidateStatus(cwd);
517 // Local after remote: the fetch can move the base that the Changes totals compare with.
518 const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream });
519 const local = yield* workflow.localStatus({ cwd });
520 // Without a fetch, the cached behind count cannot justify an automatic pull.
521 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remote, [rawCwd]) : null;
522 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
523 return yield* updateCachedStatus(cwd, local, remote, { publish: true });
524 }),
525 );
526 });
527​
528 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
529 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
530 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
531 return yield* withRemoteWriteLock(
532 cwd,
533 Effect.gen(function* () {
534 const cached = yield* getCachedStatus(cwd);
535 if (cached?.remote?.value == null) return null;
536 const poller = (yield* SynchronizedRef.get(pollersRef)).get(cwd);
537 const demandCwds = poller ? [...(yield* Ref.get(poller.demandCwds)).keys()] : [rawCwd];
538 const shouldRefresh = (yield* Effect.forEach(
539 demandCwds,
540 (demandCwd) =>
541 backgroundPolicy.shouldRunScopeWork({ type: "vcs-status", cwd: demandCwd }),
542 { concurrency: "unbounded" },
543 )).some(Boolean);
544 if (!shouldRefresh) return null;
545 // Re-resolve the branch; cached PRs may belong to a checkout's previous branch.
546 const remote = yield* workflow.remoteStatus(
547 { cwd },
548 { refreshUpstream: false, refreshMissingPullRequest: true },
549 );
550 return yield* updateCachedRemoteStatus(cwd, remote, { publish: true });
551 }),
552 );
553 });
554​
555 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
556 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
557 cwd: string,
558 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
559 refreshImmediately: boolean,
560 ) {
561 const consecutiveFailuresRef = yield* Ref.make(0);
562 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
563 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
564 const configuredInterval = yield* automaticFetchInterval;
565 const activeInterval = Duration.isZero(configuredInterval)
566 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
567 : configuredInterval;
568 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
569 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
570 return activeInterval;
571 }
572​
573 const demandCwds = yield* Ref.get(demandCwdsRef);
574 const shouldRun =
575 needsInitialRefresh ||
576 (yield* Effect.forEach(
577 [...demandCwds.keys()],
578 (demandCwd) =>
579 backgroundPolicy.shouldRunScopeWork({
580 type: "vcs-status",
581 cwd: demandCwd,
582 }),
583 { concurrency: "unbounded" },
584 )).some(Boolean);
585 if (!shouldRun) {
586 return activeInterval;
587 }
588​
589 const exit = yield* refreshRemoteStatus(cwd, {
590 refreshUpstream: !Duration.isZero(configuredInterval),
591 policyCwds: [...demandCwds.keys()],
592 }).pipe(Effect.exit);
593 if (Exit.isSuccess(exit)) {
594 yield* Ref.set(needsInitialRefreshRef, false);
595 yield* Ref.set(consecutiveFailuresRef, 0);
596 return activeInterval;
597 }
598​
599 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
600 if (interruptionReasons.length > 0) {
601 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
602 }
603​
604 const consecutiveFailures = yield* Ref.updateAndGet(
605 consecutiveFailuresRef,
606 (count) => count + 1,
607 );
608 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
609 yield* Effect.logWarning("VCS remote status refresh failed", {
610 cwdLength: cwd.length,
611 ...remoteRefreshFailureDiagnostics(exit.cause),
612 consecutiveFailures,
613 nextDelayMs: Duration.toMillis(nextDelay),
614 });
615 return nextDelay;
616 });
617​
618 if (!refreshImmediately) {
619 const configuredInterval = yield* automaticFetchInterval;
620 yield* Effect.sleep(
621 Duration.isZero(configuredInterval)
622 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
623 : configuredInterval,
624 );
625 }
626​
627 return yield* refreshRemoteStatusIfEnabled.pipe(
628 Effect.repeat(
629 Schedule.identity<Duration.Duration>().pipe(
630 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
631 ),
632 ),
633 Effect.asVoid,
634 );
635 });
636​
637 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
638 cwd: string,
639 demandCwd: string,
640 refreshImmediately: boolean,
641 ) {
642 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
643 const existing = activePollers.get(cwd);
644 if (existing) {
645 return Ref.update(existing.demandCwds, (demandCwds) => {
646 const next = new Map(demandCwds);
647 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
648 return next;
649 }).pipe(
650 Effect.map(() => {
651 const nextPollers = new Map(activePollers);
652 nextPollers.set(cwd, {
653 ...existing,
654 subscriberCount: existing.subscriberCount + 1,
655 });
656 return [undefined, nextPollers] as const;
657 }),
658 );
659 }
660​
661 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
662 Effect.flatMap((demandCwds) =>
663 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
664 Effect.forkIn(broadcasterScope),
665 Effect.map((fiber) => {
666 const nextPollers = new Map(activePollers);
667 nextPollers.set(cwd, {
668 fiber,
669 subscriberCount: 1,
670 demandCwds,
671 });
672 return [undefined, nextPollers] as const;
673 }),
674 ),
675 ),
676 );
677 });
678 });
679​
680 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
681 cwd: string,
682 demandCwd: string,
683 ) {
684 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
685 const existing = activePollers.get(cwd);
686 if (!existing) {
687 return Effect.succeed([null, activePollers] as const);
688 }
689​
690 if (existing.subscriberCount > 1) {
691 return Ref.update(existing.demandCwds, (demandCwds) => {
692 const nextDemandCwds = new Map(demandCwds);
693 const count = nextDemandCwds.get(demandCwd) ?? 0;
694 if (count <= 1) {
695 nextDemandCwds.delete(demandCwd);
696 } else {
697 nextDemandCwds.set(demandCwd, count - 1);
698 }
699 return nextDemandCwds;
700 }).pipe(
701 Effect.as([
702 null,
703 new Map(activePollers).set(cwd, {
704 ...existing,
705 subscriberCount: existing.subscriberCount - 1,
706 }),
707 ] as const),
708 );
709 }
710​
711 return Effect.succeed([
712 existing.fiber,
713 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
714 ] as const);
715 });
716​
717 if (pollerToInterrupt) {
718 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
719 }
720 });
721​
722 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
723 Stream.unwrap(
724 Effect.gen(function* () {
725 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
726 const subscription = yield* PubSub.subscribe(changesPubSub);
727 const initialLocal = yield* getOrLoadLocalStatus(cwd);
728 const cachedStatus = yield* getCachedStatus(cwd);
729 const initialRemote = cachedStatus?.remote?.value ?? null;
730 if (input.includeRemote !== false) {
731 yield* retainRemotePoller(
732 cwd,
733 input.cwd,
734 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
735 );
736 }
737 const release =
738 input.includeRemote === false
739 ? Effect.void
740 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
741​
742 return Stream.concat(
743 Stream.make({
744 _tag: "snapshot" as const,
745 local: initialLocal,
746 remote: initialRemote,
747 }),
748 Stream.fromSubscription(subscription).pipe(
749 Stream.filter((event) => event.cwd === cwd),
750 Stream.map((event) => event.event),
751 ),
752 ).pipe(Stream.ensuring(release));
753 }),
754 );
755​
756 return VcsStatusBroadcaster.of({
757 getStatus,
758 refreshLocalStatus,
759 refreshStatus,
760 refreshPullRequestStatus,
761 streamStatus,
762 });
763});
764​
765export const layer = Layer.effect(VcsStatusBroadcaster, make);