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

VcsStatusBroadcaster.ts

864 lines31.4 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 VcsBranchStatus,
19 VcsStatusLocalResult,
20 VcsStatusRemoteResult,
21 VcsStatusResult,
22 VcsStatusStreamEvent,
23 VcsStatusSubscriptionInput,
24} from "@t3tools/contracts";
25import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts";
26import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
27import { mergeGitStatusParts } from "@t3tools/shared/git";
28import * as KeyedLock from "@t3tools/shared/KeyedLock";
29import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
30​
31import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
32import * as GitWorkflowService from "../git/GitWorkflowService.ts";
33import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
34import * as ServerSettings from "../serverSettings.ts";
35​
36const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
37const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
38const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
39const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
40​
41function boundedDiagnosticValue(value: string): string {
42 return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
44​
45function diagnosticValueTag(value: unknown): string {
46 try {
47 if (
48 typeof value === "object" &&
49 value !== null &&
50 "_tag" in value &&
51 typeof value._tag === "string"
52 ) {
53 return boundedDiagnosticValue(value._tag);
54 }
55 if (value instanceof Error) {
56 return boundedDiagnosticValue(value.name);
57 }
58 return typeof value;
59 } catch {
60 return "Uninspectable";
61 }
63​
64function diagnosticFailureOperation(value: unknown): string | undefined {
65 try {
66 if (
67 typeof value === "object" &&
68 value !== null &&
69 "operation" in value &&
70 typeof value.operation === "string"
71 ) {
72 return boundedDiagnosticValue(value.operation);
73 }
74 } catch {
75 return undefined;
76 }
77 return undefined;
79​
80function addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {
81 if (
82 value !== undefined &&
83 values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&
84 !values.includes(value)
85 ) {
86 values.push(value);
87 }
89​
90function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
91 const failureTags: Array<string> = [];
92 const failureOperations: Array<string> = [];
93 const defectTags: Array<string> = [];
94 let failureCount = 0;
95 let defectCount = 0;
96 let interruptionCount = 0;
97​
98 for (const reason of cause.reasons) {
99 if (Cause.isFailReason(reason)) {
100 failureCount += 1;
101 addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));
102 addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));
103 continue;
104 }
105 if (Cause.isDieReason(reason)) {
106 defectCount += 1;
107 addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));
108 continue;
109 }
110 interruptionCount += 1;
111 }
112​
113 return {
114 reasonCount: cause.reasons.length,
115 failureCount,
116 failureTags,
117 failureOperations,
118 defectCount,
119 defectTags,
120 interruptionCount,
121 };
123​
124interface VcsStatusChange {
125 readonly cwd: string;
126 readonly event: VcsStatusStreamEvent;
128​
129interface CachedValue<T> {
130 readonly fingerprint: string;
131 readonly value: T;
133​
134interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {
135 readonly branch: string | null;
137​
138interface CachedVcsStatus {
139 readonly local: CachedValue<VcsStatusLocalResult> | null;
140 readonly remote: CachedRemoteStatus | null;
142​
143interface ActiveRemotePoller {
144 readonly fiber: Fiber.Fiber<void, never>;
145 readonly subscriberCount: number;
146 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
148​
149export class VcsAutomaticFetchInterval extends Context.Reference<Effect.Effect<Duration.Duration>>(
150 "t3/vcs/VcsAutomaticFetchInterval",
151 { defaultValue: () => Effect.succeed(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) },
152) {}
153​
154export const layerAutomaticFetchInterval = Layer.effect(
155 VcsAutomaticFetchInterval,
156 Effect.gen(function* () {
157 const serverSettings = yield* ServerSettings.ServerSettingsService;
158 return serverSettings.getSettings.pipe(
159 Effect.map(
160 (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
161 ),
162 Effect.orElseSucceed(() => DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL),
163 );
164 }),
165);
166​
167export class VcsAutoPullPolicy extends Context.Reference<{
168 readonly isEnabled: (cwd: string) => Effect.Effect<boolean, never>;
169}>("t3/vcs/VcsAutoPullPolicy", {
170 defaultValue: () => ({ isEnabled: () => Effect.succeed(false) }),
171}) {}
172​
173export const layerAutoPullPolicy = Layer.effect(
174 VcsAutoPullPolicy,
175 Effect.gen(function* () {
176 const projects = yield* ProjectStore.ProjectStoreV2;
177 const serverSettings = yield* ServerSettings.ServerSettingsService;
178 return {
179 isEnabled: Effect.fn("VcsAutoPullPolicy.isEnabled")(
180 function* (cwd: string) {
181 const project = yield* projects.findActiveByWorkspaceRoot(cwd);
182 if (project._tag === "None") return false;
183 const settings = yield* serverSettings.getSettings;
184 return resolveProjectSettings(settings, project.value.projectId).settings.defaultAutoPull;
185 },
186 Effect.orElseSucceed(() => false),
187 ),
188 };
189 }),
190);
191​
192function remoteRefreshFailureDelay(
193 consecutiveFailures: number,
194 configuredInterval: Duration.Duration,
195) {
196 const exponent = Math.max(0, consecutiveFailures - 1);
197 const backoffMs =
198 Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
199 const cappedBackoff = Duration.min(
200 Duration.millis(backoffMs),
201 VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
202 );
203 return Duration.max(configuredInterval, cappedBackoff);
205​
206export class VcsStatusBroadcaster extends Context.Service<
207 VcsStatusBroadcaster,
208 {
209 readonly streamBranchStatus: (
210 input: VcsStatusInput,
211 ) => Stream.Stream<VcsBranchStatus, GitManagerServiceError>;
212 readonly refreshBranchStatus: (
213 input: VcsStatusInput,
214 ) => Effect.Effect<VcsBranchStatus, GitManagerServiceError>;
215 readonly streamBranchChanges: Stream.Stream<{
216 readonly cwd: string;
217 readonly refName: string | null;
218 }>;
219 readonly getStatus: (
220 input: VcsStatusInput,
221 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
222 readonly refreshLocalStatus: (
223 cwd: string,
224 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
225 readonly refreshStatus: (
226 cwd: string,
227 options?: { readonly localOnly?: boolean },
228 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
229 readonly refreshPullRequestStatus: (
230 cwd: string,
231 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
232 readonly streamStatus: (
233 input: VcsStatusSubscriptionInput,
234 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
235 }
236>()("t3/vcs/VcsStatusBroadcaster") {}
237​
238function fingerprintStatusPart(status: unknown): string {
239 return JSON.stringify(status);
241​
242const normalizeCwd = (cwd: string) =>
243 Effect.service(FileSystem.FileSystem).pipe(
244 Effect.flatMap((fs) => fs.realPath(cwd)),
245 Effect.orElseSucceed(() => cwd),
246 );
247​
248/** @public */
249export const make = Effect.gen(function* () {
250 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
251 const autoPullPolicy = yield* VcsAutoPullPolicy;
252 const workflow = yield* GitWorkflowService.GitWorkflowService;
253 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
254 const fs = yield* FileSystem.FileSystem;
255 const changesPubSub = yield* Effect.acquireRelease(
256 PubSub.unbounded<VcsStatusChange>(),
257 (pubsub) => PubSub.shutdown(pubsub),
258 );
259 const branchChangesPubSub = yield* Effect.acquireRelease(
260 PubSub.unbounded<{
261 readonly cwd: string;
262 readonly refName: string | null;
263 readonly revision: number;
264 }>(),
265 (pubsub) => PubSub.shutdown(pubsub),
266 );
267 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
268 Scope.close(scope, Exit.void),
269 );
270 const detailedSubscribers = new Map<string, number>();
271 const branches = new Map<
272 string,
273 { readonly refName: string | null; readonly revision: number }
274 >();
275 let branchRevision = 0;
276 const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* (
277 cwd: string,
278 refName: string | null,
279 ) {
280 if (branches.get(cwd)?.refName === refName) return;
281 const revision = ++branchRevision;
282 branches.set(cwd, { refName, revision });
283 yield* PubSub.publish(branchChangesPubSub, { cwd, refName, revision });
284 });
285 const localRefreshLocks = yield* KeyedLock.make<string>();
286 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
287 // One permit per cwd for remote reads that write the cache. Without it a
288 // periodic poll that started before an agent creates a PR can finish after the
289 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
290 const remoteWriteLocks = yield* KeyedLock.make<string>();
291 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
292 remoteWriteLocks.withLock(cwd, effect);
293 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
294​
295 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
296 cwd: string,
297 ) {
298 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
299 });
300​
301 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
302 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
303 const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
304 const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
305 const previous = cache.get(cwd) ?? { local: null, remote: null };
306 const remote = previous.remote?.branch === local.refName ? previous.remote : null;
307 return [
308 [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
309 new Map(cache).set(cwd, { local: nextLocal, remote }),
310 ] as const;
311 });
312 yield* publishBranch(cwd, local.refName);
313 if (options?.publish && remoteCleared) {
314 yield* PubSub.publish(changesPubSub, {
315 cwd,
316 event: { _tag: "remoteUpdated", remote: null },
317 });
318 }
319 if (options?.publish && localChanged) {
320 yield* PubSub.publish(changesPubSub, {
321 cwd,
322 event: { _tag: "localUpdated", local },
323 });
324 }
325 return local;
326 },
327 );
328​
329 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
330 function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
331 const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
332 const previous = cache.get(cwd) ?? { local: null, remote: null };
333 const next = remote?.branch === previous.local?.value.refName ? remote : null;
334 return [
335 [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
336 new Map(cache).set(cwd, { ...previous, remote: next }),
337 ] as const;
338 });
339 if (options?.publish && changed) {
340 yield* PubSub.publish(changesPubSub, {
341 cwd,
342 event: { _tag: "remoteUpdated", remote: value },
343 });
344 }
345 return value;
346 },
347 );
348​
349 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
350 cwd: string,
351 ) {
352 const local = yield* workflow.localStatus({ cwd });
353 return yield* updateCachedLocalStatus(cwd, local);
354 });
355​
356 const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
357 function* (cwd: string) {
358 const cached = yield* getCachedStatus(cwd);
359 if (cached?.local) {
360 const branch = yield* workflow.currentBranch(cwd);
361 if (branch === cached.local.value.refName) return cached.local.value;
362 yield* workflow.invalidateLocalStatus(cwd);
363 return yield* updateCachedLocalStatus(cwd, yield* workflow.localStatus({ cwd }), {
364 publish: true,
365 });
366 }
367 return yield* loadLocalStatus(cwd);
368 },
369 );
370​
371 const getOrLoadLocalStatus = (cwd: string) =>
372 localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
373​
374 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
375 const cached = yield* getCachedStatus(cwd);
376 if (cached?.local) {
377 return { local: cached.local.value, remote: cached.remote?.value ?? null };
378 }
379 return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
380 });
381​
382 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
383​
384 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
385 "VcsStatusBroadcaster.getStatus",
386 )(function* (input) {
387 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
388 yield* getOrLoadLocalStatus(cwd);
389 const cached = yield* getCachedStatus(cwd);
390 if (cached?.local && cached.remote) {
391 return mergeGitStatusParts(cached.local.value, cached.remote.value);
392 }
393 return yield* withRemoteWriteLock(
394 cwd,
395 Effect.gen(function* () {
396 const latest = yield* getCachedStatus(cwd);
397 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
398 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
399 yield* updateCachedRemoteStatus(cwd, remote);
400 const parts = yield* getStatusParts(cwd);
401 return mergeGitStatusParts(parts.local, parts.remote);
402 }),
403 );
404 });
405​
406 // A refresh that started after a request saw every change that request could mean, so queued
407 // callers share it instead of each running git status again.
408 const localRefreshRequests = new Map<string, number>();
409 const localRefreshResults = new Map<
410 string,
411 { readonly startedAt: number; readonly local: VcsStatusLocalResult }
412 >();
413 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
414 function* (cwd: string) {
415 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
416 localRefreshRequests.set(cwd, requestedAt);
417 return yield* localRefreshLocks.withLock(
418 cwd,
419 Effect.gen(function* () {
420 const shared = localRefreshResults.get(cwd);
421 if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local;
422 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
423 yield* workflow.invalidateLocalStatus(cwd);
424 const local = yield* workflow.localStatus({ cwd });
425 localRefreshResults.set(cwd, { startedAt, local });
426 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
427 }),
428 );
429 },
430 );
431​
432 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
433 "VcsStatusBroadcaster.refreshLocalStatus",
434 )(function* (rawCwd) {
435 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
436 return yield* refreshLocalStatusCore(cwd);
437 });
438​
439 const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
440 cwd: string,
441 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
442 ) {
443 const branch = yield* workflow.currentBranch(cwd);
444 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
445 yield* workflow.invalidateRemoteStatus(cwd);
446 const value = yield* workflow.remoteStatus({ cwd }, options);
447 const currentBranch = yield* workflow.currentBranch(cwd);
448 const cached = yield* getCachedStatus(cwd);
449 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
450 yield* refreshLocalStatusCore(cwd);
451 }
452 return branch === currentBranch
453 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
454 : null;
455 });
456​
457 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
458 cwd: string,
459 remoteRead: CachedRemoteStatus | null,
460 policyCwds: ReadonlyArray<string>,
461 ) {
462 const remote = remoteRead?.value ?? null;
463 let pullAttempted = false;
464 return yield* Effect.gen(function* () {
465 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
466 concurrency: "unbounded",
467 })).some(Boolean);
468 if (
469 remote === null ||
470 !remote.hasUpstream ||
471 remote.aheadCount > 0 ||
472 remote.behindCount <= 0 ||
473 !autoPullEnabled
474 ) {
475 return null;
476 }
477​
478 yield* workflow.invalidateLocalStatus(cwd);
479 const local = yield* workflow.localStatus({ cwd });
480 if (
481 !local.isRepo ||
482 !local.isDefaultRef ||
483 local.hasWorkingTreeChanges ||
484 local.refName !== remoteRead?.branch
485 )
486 return null;
487​
488 pullAttempted = true;
489 yield* workflow.pullCurrentBranch(cwd);
490 yield* workflow.invalidateStatus(cwd);
491 yield* refreshLocalStatusCore(cwd);
492 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
493 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
494 return yield* getStatusParts(cwd);
495 }).pipe(
496 Effect.catch((error) =>
497 Effect.gen(function* () {
498 yield* Effect.logWarning("Automatic project pull failed", {
499 cwdLength: cwd.length,
500 errorTag: error._tag,
501 });
502 if (!pullAttempted) return null;
503 // A pull or its follow-up reads can fail after local state has changed.
504 // Let a failed reconciliation reach the caller instead of publishing old status.
505 yield* refreshLocalStatusCore(cwd);
506 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
507 return yield* getStatusParts(cwd);
508 }),
509 ),
510 );
511 });
512​
513 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
514 cwd: string,
515 options?: {
516 readonly refreshUpstream?: boolean;
517 readonly policyCwds?: ReadonlyArray<string>;
518 },
519 ) {
520 return yield* withRemoteWriteLock(
521 cwd,
522 Effect.gen(function* () {
523 const remoteRead = yield* readRemoteStatus(cwd, options);
524 const pulled =
525 options?.refreshUpstream === false
526 ? null
527 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
528 if (pulled !== null) return pulled.remote;
529 // Base refs and merge bases can move without changing divergence counts.
530 yield* refreshLocalStatusCore(cwd);
531 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
532 }),
533 );
534 });
535​
536 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
537 "VcsStatusBroadcaster.refreshStatus",
538 )(function* (rawCwd, options) {
539 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
540 yield* refreshLocalStatusCore(cwd);
541 if (options?.localOnly) {
542 // Never cache a remote here: readers take `value: null` as "read and found no PR".
543 const parts = yield* getStatusParts(cwd);
544 return mergeGitStatusParts(parts.local, parts.remote);
545 }
546 return yield* withRemoteWriteLock(
547 cwd,
548 Effect.gen(function* () {
549 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
550 // Bump the PR lookup epoch after earlier remote writers have finished.
551 yield* workflow.invalidateStatus(cwd);
552 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
553 // Fetch can move the base used for local Changes totals.
554 yield* refreshLocalStatusCore(cwd);
555 // Without a fetch, the cached behind count cannot justify an automatic pull.
556 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
557 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
558 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
559 const parts = yield* getStatusParts(cwd);
560 return mergeGitStatusParts(parts.local, parts.remote);
561 }),
562 );
563 });
564​
565 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
566 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
567 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
568 return yield* withRemoteWriteLock(
569 cwd,
570 Effect.gen(function* () {
571 const cached = yield* getCachedStatus(cwd);
572 if (!cached || cached.remote?.value === null) return null;
573 // Turn completion must update divergence even when background polling is paused.
574 const remoteRead = yield* readRemoteStatus(cwd, {
575 refreshUpstream: false,
576 refreshMissingPullRequest: true,
577 });
578 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
579 }),
580 );
581 });
582​
583 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
584 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
585 cwd: string,
586 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
587 refreshImmediately: boolean,
588 ) {
589 const consecutiveFailuresRef = yield* Ref.make(0);
590 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
591 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
592 const configuredInterval = yield* automaticFetchInterval;
593 const activeInterval = Duration.isZero(configuredInterval)
594 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
595 : configuredInterval;
596 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
597 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
598 return activeInterval;
599 }
600​
601 const demandCwds = yield* Ref.get(demandCwdsRef);
602 const shouldRun =
603 needsInitialRefresh ||
604 (yield* Effect.forEach(
605 [...demandCwds.keys()],
606 (demandCwd) =>
607 backgroundPolicy.shouldRunScopeWork({
608 type: "vcs-status",
609 cwd: demandCwd,
610 }),
611 { concurrency: "unbounded" },
612 )).some(Boolean);
613 if (!shouldRun) {
614 return activeInterval;
615 }
616​
617 const exit = yield* refreshRemoteStatus(cwd, {
618 refreshUpstream: !Duration.isZero(configuredInterval),
619 policyCwds: [...demandCwds.keys()],
620 }).pipe(Effect.exit);
621 if (Exit.isSuccess(exit)) {
622 yield* Ref.set(needsInitialRefreshRef, false);
623 yield* Ref.set(consecutiveFailuresRef, 0);
624 return activeInterval;
625 }
626​
627 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
628 if (interruptionReasons.length > 0) {
629 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
630 }
631​
632 const consecutiveFailures = yield* Ref.updateAndGet(
633 consecutiveFailuresRef,
634 (count) => count + 1,
635 );
636 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
637 yield* Effect.logWarning("VCS remote status refresh failed", {
638 cwdLength: cwd.length,
639 ...remoteRefreshFailureDiagnostics(exit.cause),
640 consecutiveFailures,
641 nextDelayMs: Duration.toMillis(nextDelay),
642 });
643 return nextDelay;
644 });
645​
646 if (!refreshImmediately) {
647 const configuredInterval = yield* automaticFetchInterval;
648 yield* Effect.sleep(
649 Duration.isZero(configuredInterval)
650 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
651 : configuredInterval,
652 );
653 }
654​
655 return yield* refreshRemoteStatusIfEnabled.pipe(
656 Effect.repeat(
657 Schedule.identity<Duration.Duration>().pipe(
658 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
659 ),
660 ),
661 Effect.asVoid,
662 );
663 });
664​
665 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
666 cwd: string,
667 demandCwd: string,
668 refreshImmediately: boolean,
669 ) {
670 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
671 const existing = activePollers.get(cwd);
672 if (existing) {
673 return Ref.update(existing.demandCwds, (demandCwds) => {
674 const next = new Map(demandCwds);
675 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
676 return next;
677 }).pipe(
678 Effect.map(() => {
679 const nextPollers = new Map(activePollers);
680 nextPollers.set(cwd, {
681 ...existing,
682 subscriberCount: existing.subscriberCount + 1,
683 });
684 return [undefined, nextPollers] as const;
685 }),
686 );
687 }
688​
689 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
690 Effect.flatMap((demandCwds) =>
691 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
692 Effect.forkIn(broadcasterScope),
693 Effect.map((fiber) => {
694 const nextPollers = new Map(activePollers);
695 nextPollers.set(cwd, {
696 fiber,
697 subscriberCount: 1,
698 demandCwds,
699 });
700 return [undefined, nextPollers] as const;
701 }),
702 ),
703 ),
704 );
705 });
706 });
707​
708 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
709 cwd: string,
710 demandCwd: string,
711 ) {
712 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
713 const existing = activePollers.get(cwd);
714 if (!existing) {
715 return Effect.succeed([null, activePollers] as const);
716 }
717​
718 if (existing.subscriberCount > 1) {
719 return Ref.update(existing.demandCwds, (demandCwds) => {
720 const nextDemandCwds = new Map(demandCwds);
721 const count = nextDemandCwds.get(demandCwd) ?? 0;
722 if (count <= 1) {
723 nextDemandCwds.delete(demandCwd);
724 } else {
725 nextDemandCwds.set(demandCwd, count - 1);
726 }
727 return nextDemandCwds;
728 }).pipe(
729 Effect.as([
730 null,
731 new Map(activePollers).set(cwd, {
732 ...existing,
733 subscriberCount: existing.subscriberCount - 1,
734 }),
735 ] as const),
736 );
737 }
738​
739 return Effect.succeed([
740 existing.fiber,
741 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
742 ] as const);
743 });
744​
745 if (pollerToInterrupt) {
746 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
747 }
748 });
749​
750 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
751 Stream.unwrap(
752 Effect.gen(function* () {
753 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
754 yield* Effect.acquireRelease(
755 Effect.sync(() => {
756 const previous = detailedSubscribers.get(cwd) ?? 0;
757 detailedSubscribers.set(cwd, previous + 1);
758 }),
759 () =>
760 Effect.sync(() => {
761 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
762 if (remaining === 0) detailedSubscribers.delete(cwd);
763 else detailedSubscribers.set(cwd, remaining);
764 }),
765 );
766 const subscription = yield* PubSub.subscribe(changesPubSub);
767 const initialLocal = yield* getOrLoadLocalStatus(cwd);
768 const cachedStatus = yield* getCachedStatus(cwd);
769 const initialRemote = cachedStatus?.remote?.value ?? null;
770 if (input.includeRemote !== false) {
771 yield* retainRemotePoller(
772 cwd,
773 input.cwd,
774 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
775 );
776 }
777 const release =
778 input.includeRemote === false
779 ? Effect.void
780 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
781​
782 return Stream.concat(
783 Stream.make({
784 _tag: "snapshot" as const,
785 local: initialLocal,
786 remote: initialRemote,
787 }),
788 Stream.fromSubscription(subscription).pipe(
789 Stream.filter((event) => event.cwd === cwd),
790 Stream.map((event) => event.event),
791 ),
792 ).pipe(Stream.ensuring(release));
793 }),
794 );
795​
796 // Serialize branch publication and cache invalidation with detailed reads and refreshes.
797 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
798 (cwd: string) =>
799 localRefreshLocks.withLock(
800 cwd,
801 Effect.gen(function* () {
802 if (detailedSubscribers.has(cwd)) {
803 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
804 return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
805 }
806 const refName = yield* workflow.currentBranch(cwd);
807 // HEAD cannot certify working-tree totals, even when it has not moved.
808 localRefreshResults.delete(cwd);
809 yield* workflow.invalidateLocalStatus(cwd);
810 yield* Ref.update(cacheRef, (cache) => {
811 const previous = cache.get(cwd);
812 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
813 });
814 if (detailedSubscribers.has(cwd)) {
815 const local = yield* workflow.localStatus({ cwd });
816 yield* updateCachedLocalStatus(cwd, local, { publish: true });
817 return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
818 }
819 yield* publishBranch(cwd, refName);
820 return { refName, revision: branches.get(cwd)?.revision ?? 0 };
821 }),
822 ),
823 );
824​
825 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
826 "VcsStatusBroadcaster.refreshBranchStatus",
827 )(function* (input) {
828 const { refName } = yield* refreshBranchStatusCore(
829 yield* withFileSystem(normalizeCwd(input.cwd)),
830 );
831 return { refName };
832 });
833​
834 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
835 Stream.unwrap(
836 Effect.gen(function* () {
837 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
838 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
839 const branch = yield* refreshBranchStatusCore(cwd);
840 return Stream.concat(
841 Stream.make({ refName: branch.refName }),
842 Stream.fromSubscription(subscription).pipe(
843 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
844 Stream.map(({ refName }) => ({ refName })),
845 ),
846 ).pipe(Stream.changesWith((left, right) => left.refName === right.refName));
847 }),
848 );
849​
850 return VcsStatusBroadcaster.of({
851 streamBranchStatus,
852 refreshBranchStatus,
853 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
854 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
855 ),
856 getStatus,
857 refreshLocalStatus,
858 refreshStatus,
859 refreshPullRequestStatus,
860 streamStatus,
861 });
862});
863​
864export const layer = Layer.effect(VcsStatusBroadcaster, make);