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