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

VcsStatusBroadcaster.ts

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