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

VcsStatusBroadcaster.ts

877 lines31.8 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 const previous = options?.localOnly ? yield* getCachedStatus(cwd) : null;
541 const local = yield* refreshLocalStatusCore(cwd);
542 if (options?.localOnly) {
543 return yield* withRemoteWriteLock(
544 cwd,
545 Effect.gen(function* () {
546 if (previous?.local?.value.refName !== local.refName || !previous?.remote) {
547 yield* workflow.invalidateRemoteStatus(cwd);
548 yield* updateCachedRemoteStatus(
549 cwd,
550 { branch: local.refName, fingerprint: fingerprintStatusPart(null), value: null },
551 { publish: true },
552 );
553 }
554 const parts = yield* getStatusParts(cwd);
555 return mergeGitStatusParts(parts.local, parts.remote);
556 }),
557 );
558 }
559 return yield* withRemoteWriteLock(
560 cwd,
561 Effect.gen(function* () {
562 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
563 // Bump the PR lookup epoch after earlier remote writers have finished.
564 yield* workflow.invalidateStatus(cwd);
565 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
566 // Fetch can move the base used for local Changes totals.
567 yield* refreshLocalStatusCore(cwd);
568 // Without a fetch, the cached behind count cannot justify an automatic pull.
569 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
570 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
571 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
572 const parts = yield* getStatusParts(cwd);
573 return mergeGitStatusParts(parts.local, parts.remote);
574 }),
575 );
576 });
577​
578 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
579 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
580 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
581 return yield* withRemoteWriteLock(
582 cwd,
583 Effect.gen(function* () {
584 const cached = yield* getCachedStatus(cwd);
585 if (!cached || cached.remote?.value === null) return null;
586 // Turn completion must update divergence even when background polling is paused.
587 const remoteRead = yield* readRemoteStatus(cwd, {
588 refreshUpstream: false,
589 refreshMissingPullRequest: true,
590 });
591 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
592 }),
593 );
594 });
595​
596 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
597 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
598 cwd: string,
599 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
600 refreshImmediately: boolean,
601 ) {
602 const consecutiveFailuresRef = yield* Ref.make(0);
603 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
604 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
605 const configuredInterval = yield* automaticFetchInterval;
606 const activeInterval = Duration.isZero(configuredInterval)
607 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
608 : configuredInterval;
609 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
610 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
611 return activeInterval;
612 }
613​
614 const demandCwds = yield* Ref.get(demandCwdsRef);
615 const shouldRun =
616 needsInitialRefresh ||
617 (yield* Effect.forEach(
618 [...demandCwds.keys()],
619 (demandCwd) =>
620 backgroundPolicy.shouldRunScopeWork({
621 type: "vcs-status",
622 cwd: demandCwd,
623 }),
624 { concurrency: "unbounded" },
625 )).some(Boolean);
626 if (!shouldRun) {
627 return activeInterval;
628 }
629​
630 const exit = yield* refreshRemoteStatus(cwd, {
631 refreshUpstream: !Duration.isZero(configuredInterval),
632 policyCwds: [...demandCwds.keys()],
633 }).pipe(Effect.exit);
634 if (Exit.isSuccess(exit)) {
635 yield* Ref.set(needsInitialRefreshRef, false);
636 yield* Ref.set(consecutiveFailuresRef, 0);
637 return activeInterval;
638 }
639​
640 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
641 if (interruptionReasons.length > 0) {
642 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
643 }
644​
645 const consecutiveFailures = yield* Ref.updateAndGet(
646 consecutiveFailuresRef,
647 (count) => count + 1,
648 );
649 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
650 yield* Effect.logWarning("VCS remote status refresh failed", {
651 cwdLength: cwd.length,
652 ...remoteRefreshFailureDiagnostics(exit.cause),
653 consecutiveFailures,
654 nextDelayMs: Duration.toMillis(nextDelay),
655 });
656 return nextDelay;
657 });
658​
659 if (!refreshImmediately) {
660 const configuredInterval = yield* automaticFetchInterval;
661 yield* Effect.sleep(
662 Duration.isZero(configuredInterval)
663 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
664 : configuredInterval,
665 );
666 }
667​
668 return yield* refreshRemoteStatusIfEnabled.pipe(
669 Effect.repeat(
670 Schedule.identity<Duration.Duration>().pipe(
671 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
672 ),
673 ),
674 Effect.asVoid,
675 );
676 });
677​
678 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
679 cwd: string,
680 demandCwd: string,
681 refreshImmediately: boolean,
682 ) {
683 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
684 const existing = activePollers.get(cwd);
685 if (existing) {
686 return Ref.update(existing.demandCwds, (demandCwds) => {
687 const next = new Map(demandCwds);
688 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
689 return next;
690 }).pipe(
691 Effect.map(() => {
692 const nextPollers = new Map(activePollers);
693 nextPollers.set(cwd, {
694 ...existing,
695 subscriberCount: existing.subscriberCount + 1,
696 });
697 return [undefined, nextPollers] as const;
698 }),
699 );
700 }
701​
702 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
703 Effect.flatMap((demandCwds) =>
704 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
705 Effect.forkIn(broadcasterScope),
706 Effect.map((fiber) => {
707 const nextPollers = new Map(activePollers);
708 nextPollers.set(cwd, {
709 fiber,
710 subscriberCount: 1,
711 demandCwds,
712 });
713 return [undefined, nextPollers] as const;
714 }),
715 ),
716 ),
717 );
718 });
719 });
720​
721 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
722 cwd: string,
723 demandCwd: string,
724 ) {
725 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
726 const existing = activePollers.get(cwd);
727 if (!existing) {
728 return Effect.succeed([null, activePollers] as const);
729 }
730​
731 if (existing.subscriberCount > 1) {
732 return Ref.update(existing.demandCwds, (demandCwds) => {
733 const nextDemandCwds = new Map(demandCwds);
734 const count = nextDemandCwds.get(demandCwd) ?? 0;
735 if (count <= 1) {
736 nextDemandCwds.delete(demandCwd);
737 } else {
738 nextDemandCwds.set(demandCwd, count - 1);
739 }
740 return nextDemandCwds;
741 }).pipe(
742 Effect.as([
743 null,
744 new Map(activePollers).set(cwd, {
745 ...existing,
746 subscriberCount: existing.subscriberCount - 1,
747 }),
748 ] as const),
749 );
750 }
751​
752 return Effect.succeed([
753 existing.fiber,
754 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
755 ] as const);
756 });
757​
758 if (pollerToInterrupt) {
759 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
760 }
761 });
762​
763 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
764 Stream.unwrap(
765 Effect.gen(function* () {
766 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
767 yield* Effect.acquireRelease(
768 Effect.sync(() => {
769 const previous = detailedSubscribers.get(cwd) ?? 0;
770 detailedSubscribers.set(cwd, previous + 1);
771 }),
772 () =>
773 Effect.sync(() => {
774 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
775 if (remaining === 0) detailedSubscribers.delete(cwd);
776 else detailedSubscribers.set(cwd, remaining);
777 }),
778 );
779 const subscription = yield* PubSub.subscribe(changesPubSub);
780 const initialLocal = yield* getOrLoadLocalStatus(cwd);
781 const cachedStatus = yield* getCachedStatus(cwd);
782 const initialRemote = cachedStatus?.remote?.value ?? null;
783 if (input.includeRemote !== false) {
784 yield* retainRemotePoller(
785 cwd,
786 input.cwd,
787 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
788 );
789 }
790 const release =
791 input.includeRemote === false
792 ? Effect.void
793 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
794​
795 return Stream.concat(
796 Stream.make({
797 _tag: "snapshot" as const,
798 local: initialLocal,
799 remote: initialRemote,
800 }),
801 Stream.fromSubscription(subscription).pipe(
802 Stream.filter((event) => event.cwd === cwd),
803 Stream.map((event) => event.event),
804 ),
805 ).pipe(Stream.ensuring(release));
806 }),
807 );
808​
809 // Serialize branch publication and cache invalidation with detailed reads and refreshes.
810 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
811 (cwd: string) =>
812 localRefreshLocks.withLock(
813 cwd,
814 Effect.gen(function* () {
815 if (detailedSubscribers.has(cwd)) {
816 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
817 return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
818 }
819 const refName = yield* workflow.currentBranch(cwd);
820 // HEAD cannot certify working-tree totals, even when it has not moved.
821 localRefreshResults.delete(cwd);
822 yield* workflow.invalidateLocalStatus(cwd);
823 yield* Ref.update(cacheRef, (cache) => {
824 const previous = cache.get(cwd);
825 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
826 });
827 if (detailedSubscribers.has(cwd)) {
828 const local = yield* workflow.localStatus({ cwd });
829 yield* updateCachedLocalStatus(cwd, local, { publish: true });
830 return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
831 }
832 yield* publishBranch(cwd, refName);
833 return { refName, revision: branches.get(cwd)?.revision ?? 0 };
834 }),
835 ),
836 );
837​
838 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
839 "VcsStatusBroadcaster.refreshBranchStatus",
840 )(function* (input) {
841 const { refName } = yield* refreshBranchStatusCore(
842 yield* withFileSystem(normalizeCwd(input.cwd)),
843 );
844 return { refName };
845 });
846​
847 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
848 Stream.unwrap(
849 Effect.gen(function* () {
850 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
851 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
852 const branch = yield* refreshBranchStatusCore(cwd);
853 return Stream.concat(
854 Stream.make({ refName: branch.refName }),
855 Stream.fromSubscription(subscription).pipe(
856 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
857 Stream.map(({ refName }) => ({ refName })),
858 ),
859 ).pipe(Stream.changesWith((left, right) => left.refName === right.refName));
860 }),
861 );
862​
863 return VcsStatusBroadcaster.of({
864 streamBranchStatus,
865 refreshBranchStatus,
866 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
867 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
868 ),
869 getStatus,
870 refreshLocalStatus,
871 refreshStatus,
872 refreshPullRequestStatus,
873 streamStatus,
874 });
875});
876​
877export const layer = Layer.effect(VcsStatusBroadcaster, make);