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

VcsStatusBroadcaster.ts

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