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

VcsStatusBroadcaster.ts

1,131 lines42.6 KB

1import * as Cause from "effect/Cause";
2import * as Context from "effect/Context";
3import * as Deferred from "effect/Deferred";
4import * as Duration from "effect/Duration";
5import * as Effect from "effect/Effect";
6import * as Exit from "effect/Exit";
7import * as Fiber from "effect/Fiber";
8import * as FileSystem from "effect/FileSystem";
9import * as Layer from "effect/Layer";
10import * as Path from "effect/Path";
11import * as PubSub from "effect/PubSub";
12import * as Ref from "effect/Ref";
13import * as Schedule from "effect/Schedule";
14import * as Scope from "effect/Scope";
15import * as Stream from "effect/Stream";
16import * as SynchronizedRef from "effect/SynchronizedRef";
17import type {
18 GitManagerServiceError,
19 VcsStatusInput,
20 VcsBranchStatus,
21 VcsStatusLocalResult,
22 VcsStatusRemoteResult,
23 VcsStatusResult,
24 VcsStatusStreamEvent,
25 VcsStatusSubscriptionInput,
26} from "@t3tools/contracts";
27import { DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL } from "@t3tools/contracts";
28import { resolveServerBackgroundActivitySettings } from "@t3tools/shared/backgroundActivitySettings";
29import { mergeGitStatusParts } from "@t3tools/shared/git";
30import * as KeyedLock from "@t3tools/shared/KeyedLock";
31import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
32​
33import * as BackgroundPolicy from "../background/BackgroundPolicy.ts";
34import * as GitWorkflowService from "../git/GitWorkflowService.ts";
35import * as ProjectStore from "../orchestration-v2/ProjectStore.ts";
36import * as ServerSettings from "../serverSettings.ts";
37​
38const VCS_STATUS_REFRESH_FAILURE_BASE_DELAY = Duration.seconds(30);
39const VCS_STATUS_REFRESH_FAILURE_MAX_DELAY = Duration.minutes(15);
40const MAX_FAILURE_DIAGNOSTIC_VALUES = 8;
41// A held index.lock fails the read, and its removal moves no HEAD to trigger another.
42const CHECKOUT_REFRESH_RETRY = Schedule.exponential(Duration.seconds(1)).pipe(
43 Schedule.modifyDelay(({ duration }) =>
44 Effect.succeed(Duration.min(duration, Duration.seconds(30))),
45 ),
46);
47const MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH = 128;
48​
49function boundedDiagnosticValue(value: string): string {
50 return value.slice(0, MAX_FAILURE_DIAGNOSTIC_VALUE_LENGTH);
52​
53function diagnosticValueTag(value: unknown): string {
54 try {
55 if (
56 typeof value === "object" &&
57 value !== null &&
58 "_tag" in value &&
59 typeof value._tag === "string"
60 ) {
61 return boundedDiagnosticValue(value._tag);
62 }
63 if (value instanceof Error) {
64 return boundedDiagnosticValue(value.name);
65 }
66 return typeof value;
67 } catch {
68 return "Uninspectable";
69 }
71​
72function diagnosticFailureOperation(value: unknown): string | undefined {
73 try {
74 if (
75 typeof value === "object" &&
76 value !== null &&
77 "operation" in value &&
78 typeof value.operation === "string"
79 ) {
80 return boundedDiagnosticValue(value.operation);
81 }
82 } catch {
83 return undefined;
84 }
85 return undefined;
87​
88function addUniqueDiagnosticValue(values: Array<string>, value: string | undefined): void {
89 if (
90 value !== undefined &&
91 values.length < MAX_FAILURE_DIAGNOSTIC_VALUES &&
92 !values.includes(value)
93 ) {
94 values.push(value);
95 }
97​
98function remoteRefreshFailureDiagnostics(cause: Cause.Cause<unknown>) {
99 const failureTags: Array<string> = [];
100 const failureOperations: Array<string> = [];
101 const defectTags: Array<string> = [];
102 let failureCount = 0;
103 let defectCount = 0;
104 let interruptionCount = 0;
105​
106 for (const reason of cause.reasons) {
107 if (Cause.isFailReason(reason)) {
108 failureCount += 1;
109 addUniqueDiagnosticValue(failureTags, diagnosticValueTag(reason.error));
110 addUniqueDiagnosticValue(failureOperations, diagnosticFailureOperation(reason.error));
111 continue;
112 }
113 if (Cause.isDieReason(reason)) {
114 defectCount += 1;
115 addUniqueDiagnosticValue(defectTags, diagnosticValueTag(reason.defect));
116 continue;
117 }
118 interruptionCount += 1;
119 }
120​
121 return {
122 reasonCount: cause.reasons.length,
123 failureCount,
124 failureTags,
125 failureOperations,
126 defectCount,
127 defectTags,
128 interruptionCount,
129 };
131​
132interface VcsStatusChange {
133 readonly cwd: string;
134 readonly event: VcsStatusStreamEvent;
136​
137interface CachedValue<T> {
138 readonly fingerprint: string;
139 readonly value: T;
141​
142interface CachedRemoteStatus extends CachedValue<VcsStatusRemoteResult | null> {
143 readonly branch: string | null;
145​
146interface CachedVcsStatus {
147 readonly local: CachedValue<VcsStatusLocalResult> | null;
148 readonly remote: CachedRemoteStatus | null;
150​
151interface ActiveHeadWatcher {
152 readonly fiber: Fiber.Fiber<void, never>;
153 readonly ready: Deferred.Deferred<void>;
154 readonly subscriberCount: number;
156​
157interface ActiveRemotePoller {
158 readonly fiber: Fiber.Fiber<void, never>;
159 readonly subscriberCount: number;
160 readonly demandCwds: Ref.Ref<ReadonlyMap<string, number>>;
162​
163export class VcsAutomaticFetchInterval extends Context.Reference<Effect.Effect<Duration.Duration>>(
164 "t3/vcs/VcsAutomaticFetchInterval",
165 { defaultValue: () => Effect.succeed(DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL) },
166) {}
167​
168export const layerAutomaticFetchInterval = Layer.effect(
169 VcsAutomaticFetchInterval,
170 Effect.gen(function* () {
171 const serverSettings = yield* ServerSettings.ServerSettingsService;
172 return serverSettings.getSettings.pipe(
173 Effect.map(
174 (settings) => resolveServerBackgroundActivitySettings(settings).automaticGitFetchInterval,
175 ),
176 Effect.orElseSucceed(() => DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL),
177 );
178 }),
179);
180​
181export class VcsAutoPullPolicy extends Context.Reference<{
182 readonly isEnabled: (cwd: string) => Effect.Effect<boolean, never>;
183}>("t3/vcs/VcsAutoPullPolicy", {
184 defaultValue: () => ({ isEnabled: () => Effect.succeed(false) }),
185}) {}
186​
187export const layerAutoPullPolicy = Layer.effect(
188 VcsAutoPullPolicy,
189 Effect.gen(function* () {
190 const projects = yield* ProjectStore.ProjectStoreV2;
191 const serverSettings = yield* ServerSettings.ServerSettingsService;
192 return {
193 isEnabled: Effect.fn("VcsAutoPullPolicy.isEnabled")(
194 function* (cwd: string) {
195 const project = yield* projects.findActiveByWorkspaceRoot(cwd);
196 if (project._tag === "None") return false;
197 const settings = yield* serverSettings.getSettings;
198 return resolveProjectSettings(settings, project.value.projectId).settings.defaultAutoPull;
199 },
200 Effect.orElseSucceed(() => false),
201 ),
202 };
203 }),
204);
205​
206function remoteRefreshFailureDelay(
207 consecutiveFailures: number,
208 configuredInterval: Duration.Duration,
209) {
210 const exponent = Math.max(0, consecutiveFailures - 1);
211 const backoffMs =
212 Duration.toMillis(VCS_STATUS_REFRESH_FAILURE_BASE_DELAY) * Math.pow(2, exponent);
213 const cappedBackoff = Duration.min(
214 Duration.millis(backoffMs),
215 VCS_STATUS_REFRESH_FAILURE_MAX_DELAY,
216 );
217 return Duration.max(configuredInterval, cappedBackoff);
219​
220export class VcsStatusBroadcaster extends Context.Service<
221 VcsStatusBroadcaster,
222 {
223 readonly streamBranchStatus: (
224 input: VcsStatusInput,
225 ) => Stream.Stream<VcsBranchStatus, GitManagerServiceError>;
226 readonly refreshBranchStatus: (
227 input: VcsStatusInput,
228 ) => Effect.Effect<VcsBranchStatus, GitManagerServiceError>;
229 readonly streamBranchChanges: Stream.Stream<{
230 readonly cwd: string;
231 readonly refName: string | null;
232 }>;
233 readonly getStatus: (
234 input: VcsStatusInput,
235 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
236 readonly refreshLocalStatus: (
237 cwd: string,
238 ) => Effect.Effect<VcsStatusLocalResult, GitManagerServiceError>;
239 readonly refreshStatus: (
240 cwd: string,
241 options?: { readonly localOnly?: boolean },
242 ) => Effect.Effect<VcsStatusResult, GitManagerServiceError>;
243 readonly refreshPullRequestStatus: (
244 cwd: string,
245 ) => Effect.Effect<VcsStatusRemoteResult | null, GitManagerServiceError>;
246 readonly streamStatus: (
247 input: VcsStatusSubscriptionInput,
248 ) => Stream.Stream<VcsStatusStreamEvent, GitManagerServiceError>;
249 }
250>()("t3/vcs/VcsStatusBroadcaster") {}
251​
252function fingerprintStatusPart(status: unknown): string {
253 return JSON.stringify(status);
255​
256const normalizeCwd = (cwd: string) =>
257 Effect.service(FileSystem.FileSystem).pipe(
258 Effect.flatMap((fs) => fs.realPath(cwd)),
259 Effect.orElseSucceed(() => cwd),
260 );
261​
262/** @public */
263export const make = Effect.gen(function* () {
264 const automaticFetchInterval = yield* VcsAutomaticFetchInterval;
265 const autoPullPolicy = yield* VcsAutoPullPolicy;
266 const workflow = yield* GitWorkflowService.GitWorkflowService;
267 const backgroundPolicy = yield* BackgroundPolicy.BackgroundPolicy;
268 const fs = yield* FileSystem.FileSystem;
269 const path = yield* Path.Path;
270 const changesPubSub = yield* Effect.acquireRelease(
271 PubSub.unbounded<VcsStatusChange>(),
272 (pubsub) => PubSub.shutdown(pubsub),
273 );
274 const branchChangesPubSub = yield* Effect.acquireRelease(
275 PubSub.unbounded<{
276 readonly cwd: string;
277 readonly refName: string | null;
278 readonly isRepo: boolean;
279 readonly revision: number;
280 }>(),
281 (pubsub) => PubSub.shutdown(pubsub),
282 );
283 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
284 Scope.close(scope, Exit.void),
285 );
286 const detailedSubscribers = new Map<string, number>();
287 const branches = new Map<
288 string,
289 {
290 readonly refName: string | null;
291 readonly isRepo: boolean;
292 readonly revision: number;
293 readonly observation: number;
294 }
295 >();
296 let branchRevision = 0;
297 // A slow detailed read must not replace a newer HEAD-only observation.
298 let branchObservation = 0;
299 const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* (
300 cwd: string,
301 { refName, isRepo }: { readonly refName: string | null; readonly isRepo: boolean },
302 observation: number,
303 ) {
304 const previous = branches.get(cwd);
305 if (previous && previous.observation > observation) return;
306 if (previous?.refName === refName && previous.isRepo === isRepo) {
307 branches.set(cwd, { ...previous, observation });
308 return;
309 }
310 const revision = ++branchRevision;
311 branches.set(cwd, { refName, isRepo, revision, observation });
312 yield* PubSub.publish(branchChangesPubSub, { cwd, refName, isRepo, revision });
313 });
314 const localRefreshLocks = yield* KeyedLock.make<string>();
315 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
316 // One permit per cwd for remote reads that write the cache. Without it a
317 // periodic poll that started before an agent creates a PR can finish after the
318 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
319 const remoteWriteLocks = yield* KeyedLock.make<string>();
320 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
321 remoteWriteLocks.withLock(cwd, effect);
322 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
323 const headWatchersRef = yield* SynchronizedRef.make(new Map<string, ActiveHeadWatcher>());
324​
325 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
326 cwd: string,
327 ) {
328 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
329 });
330​
331 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
332 function* (
333 cwd: string,
334 local: VcsStatusLocalResult,
335 observation: number,
336 options?: { publish?: boolean },
337 ) {
338 const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
339 const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
340 const previous = cache.get(cwd) ?? { local: null, remote: null };
341 const remote = previous.remote?.branch === local.refName ? previous.remote : null;
342 return [
343 [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
344 new Map(cache).set(cwd, { local: nextLocal, remote }),
345 ] as const;
346 });
347 yield* publishBranch(cwd, local, observation);
348 if (options?.publish && remoteCleared) {
349 yield* PubSub.publish(changesPubSub, {
350 cwd,
351 event: { _tag: "remoteUpdated", remote: null },
352 });
353 }
354 if (options?.publish && localChanged) {
355 yield* PubSub.publish(changesPubSub, {
356 cwd,
357 event: { _tag: "localUpdated", local },
358 });
359 }
360 return local;
361 },
362 );
363​
364 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
365 function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
366 const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
367 const previous = cache.get(cwd) ?? { local: null, remote: null };
368 const next = remote?.branch === previous.local?.value.refName ? remote : null;
369 return [
370 [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
371 new Map(cache).set(cwd, { ...previous, remote: next }),
372 ] as const;
373 });
374 if (options?.publish && changed) {
375 yield* PubSub.publish(changesPubSub, {
376 cwd,
377 event: { _tag: "remoteUpdated", remote: value },
378 });
379 }
380 return value;
381 },
382 );
383​
384 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
385 cwd: string,
386 options?: { publish?: boolean },
387 ) {
388 const observation = ++branchObservation;
389 const local = yield* workflow.localStatus({ cwd });
390 return yield* updateCachedLocalStatus(cwd, local, observation, options);
391 });
392​
393 const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
394 function* (cwd: string) {
395 const cached = yield* getCachedStatus(cwd);
396 if (cached?.local) {
397 const branch = yield* workflow.currentBranch(cwd);
398 if (branch === cached.local.value.refName) return cached.local.value;
399 yield* workflow.invalidateLocalStatus(cwd);
400 return yield* loadLocalStatus(cwd, { publish: true });
401 }
402 return yield* loadLocalStatus(cwd);
403 },
404 );
405​
406 const getOrLoadLocalStatus = (cwd: string) =>
407 localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
408​
409 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
410 const cached = yield* getCachedStatus(cwd);
411 if (cached?.local) {
412 return { local: cached.local.value, remote: cached.remote?.value ?? null };
413 }
414 return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
415 });
416​
417 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
418​
419 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
420 "VcsStatusBroadcaster.getStatus",
421 )(function* (input) {
422 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
423 yield* getOrLoadLocalStatus(cwd);
424 const cached = yield* getCachedStatus(cwd);
425 if (cached?.local && cached.remote) {
426 return mergeGitStatusParts(cached.local.value, cached.remote.value);
427 }
428 return yield* withRemoteWriteLock(
429 cwd,
430 Effect.gen(function* () {
431 const latest = yield* getCachedStatus(cwd);
432 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
433 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
434 yield* updateCachedRemoteStatus(cwd, remote);
435 const parts = yield* getStatusParts(cwd);
436 return mergeGitStatusParts(parts.local, parts.remote);
437 }),
438 );
439 });
440​
441 // A refresh that started after a request saw every change that request could mean, so queued
442 // callers share it instead of each running git status again.
443 const localRefreshRequests = new Map<string, number>();
444 const localRefreshResults = new Map<
445 string,
446 { readonly startedAt: number; readonly local: VcsStatusLocalResult }
447 >();
448 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
449 function* (cwd: string) {
450 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
451 localRefreshRequests.set(cwd, requestedAt);
452 return yield* localRefreshLocks.withLock(
453 cwd,
454 Effect.gen(function* () {
455 const shared = localRefreshResults.get(cwd);
456 if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local;
457 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
458 yield* workflow.invalidateLocalStatus(cwd);
459 const observation = ++branchObservation;
460 const local = yield* workflow.localStatus({ cwd });
461 localRefreshResults.set(cwd, { startedAt, local });
462 return yield* updateCachedLocalStatus(cwd, local, observation, { publish: true });
463 }),
464 );
465 },
466 );
467​
468 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
469 "VcsStatusBroadcaster.refreshLocalStatus",
470 )(function* (rawCwd) {
471 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
472 const local = yield* refreshLocalStatusCore(cwd);
473 const cached = yield* getCachedStatus(cwd);
474 // Divergence is local Git data; a slow forge lookup must not delay turn-end updates.
475 if (cached?.remote?.value?.hasUpstream) {
476 const divergence = yield* workflow.upstreamDivergence(cwd);
477 const latest = yield* getCachedStatus(cwd);
478 if (divergence && latest?.remote?.value && latest.remote.branch === divergence.refName) {
479 const value = {
480 ...latest.remote.value,
481 aheadCount: divergence.aheadCount,
482 behindCount: divergence.behindCount,
483 };
484 yield* updateCachedRemoteStatus(
485 cwd,
486 {
487 branch: divergence.refName,
488 value,
489 fingerprint: fingerprintStatusPart(value),
490 },
491 { publish: true },
492 );
493 }
494 }
495 return local;
496 });
497​
498 const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
499 cwd: string,
500 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
501 ) {
502 const branch = yield* workflow.currentBranch(cwd);
503 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
504 yield* workflow.invalidateRemoteStatus(cwd);
505 const previousRemote = (yield* getCachedStatus(cwd))?.remote;
506 const remote = yield* workflow.remoteStatus({ cwd }, options);
507 const latest = yield* getCachedStatus(cwd);
508 // An overlapping turn refresh and fetch can both move divergence during the forge lookup.
509 const refreshed =
510 remote?.hasUpstream && latest?.remote !== previousRemote && latest?.remote?.branch === branch
511 ? yield* workflow.upstreamDivergence(cwd)
512 : null;
513 const value =
514 remote && refreshed?.refName === branch
515 ? { ...remote, aheadCount: refreshed.aheadCount, behindCount: refreshed.behindCount }
516 : remote;
517 const currentBranch = yield* workflow.currentBranch(cwd);
518 const cached = yield* getCachedStatus(cwd);
519 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
520 yield* refreshLocalStatusCore(cwd);
521 }
522 return branch === currentBranch
523 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
524 : null;
525 });
526​
527 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
528 cwd: string,
529 remoteRead: CachedRemoteStatus | null,
530 policyCwds: ReadonlyArray<string>,
531 ) {
532 const remote = remoteRead?.value ?? null;
533 let pullAttempted = false;
534 return yield* Effect.gen(function* () {
535 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
536 concurrency: "unbounded",
537 })).some(Boolean);
538 if (
539 remote === null ||
540 !remote.hasUpstream ||
541 remote.aheadCount > 0 ||
542 remote.behindCount <= 0 ||
543 !autoPullEnabled
544 ) {
545 return null;
546 }
547​
548 yield* workflow.invalidateLocalStatus(cwd);
549 const local = yield* workflow.localStatus({ cwd });
550 if (
551 !local.isRepo ||
552 !local.isDefaultRef ||
553 local.hasWorkingTreeChanges ||
554 local.refName !== remoteRead?.branch
555 )
556 return null;
557​
558 pullAttempted = true;
559 yield* workflow.pullCurrentBranch(cwd);
560 yield* workflow.invalidateStatus(cwd);
561 yield* refreshLocalStatusCore(cwd);
562 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
563 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
564 return yield* getStatusParts(cwd);
565 }).pipe(
566 Effect.catch((error) =>
567 Effect.gen(function* () {
568 yield* Effect.logWarning("Automatic project pull failed", {
569 cwdLength: cwd.length,
570 errorTag: error._tag,
571 });
572 if (!pullAttempted) return null;
573 // A pull or its follow-up reads can fail after local state has changed.
574 // Let a failed reconciliation reach the caller instead of publishing old status.
575 yield* refreshLocalStatusCore(cwd);
576 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
577 return yield* getStatusParts(cwd);
578 }),
579 ),
580 );
581 });
582​
583 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
584 cwd: string,
585 options?: {
586 readonly refreshUpstream?: boolean;
587 readonly policyCwds?: ReadonlyArray<string>;
588 },
589 ) {
590 return yield* withRemoteWriteLock(
591 cwd,
592 Effect.gen(function* () {
593 const remoteRead = yield* readRemoteStatus(cwd, options);
594 const pulled =
595 options?.refreshUpstream === false
596 ? null
597 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
598 if (pulled !== null) return pulled.remote;
599 // Base refs and merge bases can move without changing divergence counts.
600 yield* refreshLocalStatusCore(cwd);
601 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
602 }),
603 );
604 });
605​
606 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
607 "VcsStatusBroadcaster.refreshStatus",
608 )(function* (rawCwd, options) {
609 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
610 yield* refreshLocalStatusCore(cwd);
611 if (options?.localOnly) {
612 // Never cache a remote here: readers take `value: null` as "read and found no PR".
613 const parts = yield* getStatusParts(cwd);
614 return mergeGitStatusParts(parts.local, parts.remote);
615 }
616 return yield* withRemoteWriteLock(
617 cwd,
618 Effect.gen(function* () {
619 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
620 // Bump the PR lookup epoch after earlier remote writers have finished.
621 yield* workflow.invalidateStatus(cwd);
622 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
623 // Fetch can move the base used for local Changes totals.
624 yield* refreshLocalStatusCore(cwd);
625 // Without a fetch, the cached behind count cannot justify an automatic pull.
626 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
627 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
628 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
629 const parts = yield* getStatusParts(cwd);
630 return mergeGitStatusParts(parts.local, parts.remote);
631 }),
632 );
633 });
634​
635 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
636 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
637 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
638 return yield* withRemoteWriteLock(
639 cwd,
640 Effect.gen(function* () {
641 const cached = yield* getCachedStatus(cwd);
642 if (!cached || cached.remote?.value === null) return null;
643 // Turn completion must update divergence even when background polling is paused.
644 const remoteRead = yield* readRemoteStatus(cwd, {
645 refreshUpstream: false,
646 refreshMissingPullRequest: true,
647 });
648 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
649 }),
650 );
651 });
652​
653 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
654 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
655 cwd: string,
656 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
657 refreshImmediately: boolean,
658 ) {
659 const consecutiveFailuresRef = yield* Ref.make(0);
660 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
661 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
662 const configuredInterval = yield* automaticFetchInterval;
663 const activeInterval = Duration.isZero(configuredInterval)
664 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
665 : configuredInterval;
666 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
667 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
668 return activeInterval;
669 }
670​
671 const demandCwds = yield* Ref.get(demandCwdsRef);
672 const shouldRun =
673 needsInitialRefresh ||
674 (yield* Effect.forEach(
675 [...demandCwds.keys()],
676 (demandCwd) =>
677 backgroundPolicy.shouldRunScopeWork({
678 type: "vcs-status",
679 cwd: demandCwd,
680 }),
681 { concurrency: "unbounded" },
682 )).some(Boolean);
683 if (!shouldRun) {
684 return activeInterval;
685 }
686​
687 const exit = yield* refreshRemoteStatus(cwd, {
688 refreshUpstream: !Duration.isZero(configuredInterval),
689 policyCwds: [...demandCwds.keys()],
690 }).pipe(Effect.exit);
691 if (Exit.isSuccess(exit)) {
692 yield* Ref.set(needsInitialRefreshRef, false);
693 yield* Ref.set(consecutiveFailuresRef, 0);
694 return activeInterval;
695 }
696​
697 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
698 if (interruptionReasons.length > 0) {
699 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
700 }
701​
702 const consecutiveFailures = yield* Ref.updateAndGet(
703 consecutiveFailuresRef,
704 (count) => count + 1,
705 );
706 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
707 yield* Effect.logWarning("VCS remote status refresh failed", {
708 cwdLength: cwd.length,
709 ...remoteRefreshFailureDiagnostics(exit.cause),
710 consecutiveFailures,
711 nextDelayMs: Duration.toMillis(nextDelay),
712 });
713 return nextDelay;
714 });
715​
716 if (!refreshImmediately) {
717 const configuredInterval = yield* automaticFetchInterval;
718 yield* Effect.sleep(
719 Duration.isZero(configuredInterval)
720 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
721 : configuredInterval,
722 );
723 }
724​
725 return yield* refreshRemoteStatusIfEnabled.pipe(
726 Effect.repeat(
727 Schedule.identity<Duration.Duration>().pipe(
728 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
729 ),
730 ),
731 Effect.asVoid,
732 );
733 });
734​
735 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
736 cwd: string,
737 demandCwd: string,
738 refreshImmediately: boolean,
739 ) {
740 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
741 const existing = activePollers.get(cwd);
742 if (existing) {
743 return Ref.update(existing.demandCwds, (demandCwds) => {
744 const next = new Map(demandCwds);
745 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
746 return next;
747 }).pipe(
748 Effect.map(() => {
749 const nextPollers = new Map(activePollers);
750 nextPollers.set(cwd, {
751 ...existing,
752 subscriberCount: existing.subscriberCount + 1,
753 });
754 return [undefined, nextPollers] as const;
755 }),
756 );
757 }
758​
759 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
760 Effect.flatMap((demandCwds) =>
761 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
762 Effect.forkIn(broadcasterScope),
763 Effect.map((fiber) => {
764 const nextPollers = new Map(activePollers);
765 nextPollers.set(cwd, {
766 fiber,
767 subscriberCount: 1,
768 demandCwds,
769 });
770 return [undefined, nextPollers] as const;
771 }),
772 ),
773 ),
774 );
775 });
776 });
777​
778 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
779 cwd: string,
780 demandCwd: string,
781 ) {
782 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
783 const existing = activePollers.get(cwd);
784 if (!existing) {
785 return Effect.succeed([null, activePollers] as const);
786 }
787​
788 if (existing.subscriberCount > 1) {
789 return Ref.update(existing.demandCwds, (demandCwds) => {
790 const nextDemandCwds = new Map(demandCwds);
791 const count = nextDemandCwds.get(demandCwd) ?? 0;
792 if (count <= 1) {
793 nextDemandCwds.delete(demandCwd);
794 } else {
795 nextDemandCwds.set(demandCwd, count - 1);
796 }
797 return nextDemandCwds;
798 }).pipe(
799 Effect.as([
800 null,
801 new Map(activePollers).set(cwd, {
802 ...existing,
803 subscriberCount: existing.subscriberCount - 1,
804 }),
805 ] as const),
806 );
807 }
808​
809 return Effect.succeed([
810 existing.fiber,
811 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
812 ] as const);
813 });
814​
815 if (pollerToInterrupt) {
816 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
817 }
818 });
819​
820 // A request made during a refresh needs a read that starts after it, so overlapping requests
821 // share one follow-up. Keyed by raw cwd because auto-pull policy depends on it.
822 // Missing means idle; null means running with no follow-up queued.
823 type SharedRefresh = Deferred.Deferred<VcsStatusResult, GitManagerServiceError>;
824 const queuedRefreshesRef = yield* Ref.make(new Map<string, SharedRefresh | null>());
825​
826 const runQueuedRefreshes = Effect.fn("VcsStatusBroadcaster.runQueuedRefreshes")(function* (
827 rawCwd: string,
828 first: SharedRefresh,
829 ) {
830 let next: SharedRefresh | null = first;
831 while (next !== null) {
832 yield* Deferred.into(refreshStatus(rawCwd), next);
833 next = yield* Ref.modify(queuedRefreshesRef, (queued) => {
834 const followUp = queued.get(rawCwd) ?? null;
835 const nextQueued = new Map(queued);
836 if (followUp === null) {
837 nextQueued.delete(rawCwd);
838 } else {
839 nextQueued.set(rawCwd, null);
840 }
841 return [followUp, nextQueued] as const;
842 });
843 }
844 });
845​
846 const shareQueuedRefreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
847 "VcsStatusBroadcaster.shareQueuedRefreshStatus",
848 )(function* (rawCwd, options) {
849 if (options?.localOnly) return yield* refreshStatus(rawCwd, options);
850 const requested = yield* Deferred.make<VcsStatusResult, GitManagerServiceError>();
851 // Registering and forking together keeps an interrupt from leaving an entry with no worker.
852 const shared = yield* Effect.uninterruptible(
853 Effect.gen(function* () {
854 const followUp = yield* Ref.modify(
855 queuedRefreshesRef,
856 (queued): readonly [SharedRefresh | undefined, Map<string, SharedRefresh | null>] => {
857 if (!queued.has(rawCwd)) return [undefined, new Map(queued).set(rawCwd, null)];
858 const followUp = queued.get(rawCwd) ?? requested;
859 return [followUp, new Map(queued).set(rawCwd, followUp)];
860 },
861 );
862 if (followUp !== undefined) return followUp;
863 // The broadcaster scope owns the work, so one caller's interrupt does not cancel it for the rest.
864 yield* runQueuedRefreshes(rawCwd, requested).pipe(Effect.forkIn(broadcasterScope));
865 return requested;
866 }),
867 );
868 return yield* Deferred.await(shared);
869 });
870​
871 const readHeadBranch = Effect.fn("VcsStatusBroadcaster.readHeadBranch")(function* (cwd: string) {
872 const observation = ++branchObservation;
873 const refName = yield* workflow.currentBranch(cwd);
874 // A null branch is a detached HEAD or a checkout that is gone, such as a removed worktree.
875 const isRepo = refName !== null || (yield* workflow.repositoryRoot(cwd)) !== null;
876 return { observation, refName, isRepo };
877 });
878​
879 // Keep cache invalidation serialized with detailed reads and refreshes.
880 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
881 (cwd: string) =>
882 localRefreshLocks.withLock(
883 cwd,
884 Effect.gen(function* () {
885 if (detailedSubscribers.has(cwd)) {
886 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
887 return (
888 branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 }
889 );
890 }
891 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
892 // HEAD cannot certify working-tree totals, even when it has not moved.
893 localRefreshResults.delete(cwd);
894 yield* workflow.invalidateLocalStatus(cwd);
895 yield* Ref.update(cacheRef, (cache) => {
896 const previous = cache.get(cwd);
897 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
898 });
899 if (detailedSubscribers.has(cwd)) {
900 const local = yield* loadLocalStatus(cwd, { publish: true });
901 return (
902 branches.get(cwd) ?? { refName: local.refName, isRepo: local.isRepo, revision: 0 }
903 );
904 }
905 yield* publishBranch(cwd, { refName, isRepo }, observation);
906 return branches.get(cwd) ?? { refName, isRepo, revision: 0 };
907 }),
908 ),
909 );
910​
911 // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC.
912 // Rereading remote too, without a fetch, sends the new branch with its own PR and counts.
913 const publishCheckedOutRef = Effect.fn("VcsStatusBroadcaster.publishCheckedOutRef")(function* (
914 cwd: string,
915 ) {
916 if (!detailedSubscribers.has(cwd)) return yield* refreshBranchStatusCore(cwd);
917 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
918 yield* publishBranch(cwd, { refName, isRepo }, observation);
919 });
920​
921 const reconcileCheckedOutRef = Effect.fn("VcsStatusBroadcaster.reconcileCheckedOutRef")(
922 function* (cwd: string) {
923 if (!detailedSubscribers.has(cwd)) return;
924 if ((yield* getCachedStatus(cwd))?.remote) {
925 yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
926 } else {
927 yield* refreshLocalStatusCore(cwd);
928 }
929 },
930 );
931​
932 const retryCheckedOutRef = <E>(cwd: string, refresh: Effect.Effect<unknown, E>) =>
933 refresh.pipe(
934 Effect.retry(CHECKOUT_REFRESH_RETRY),
935 Effect.catchCause((cause) =>
936 Effect.logWarning("VCS checked-out ref refresh failed", {
937 cwdLength: cwd.length,
938 ...remoteRefreshFailureDiagnostics(cause),
939 }),
940 ),
941 );
942​
943 // Runs for the subscription lifetime, so tracing would leave a span open indefinitely.
944 const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred<void>) {
945 const headPath = yield* workflow.headPath(cwd);
946 if (headPath === null) return;
947 const headDirectory = path.dirname(headPath);
948 // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose.
949 yield* fs
950 .watch(headDirectory, {
951 onReady: () => Deferred.doneUnsafe(ready, Exit.void),
952 })
953 .pipe(
954 // On Windows a watch outlives its deleted directory and reports it ~150k times a second.
955 Stream.takeUntilEffect((event) =>
956 event._tag === "Remove"
957 ? fs.exists(headDirectory).pipe(Effect.map((exists) => !exists))
958 : Effect.succeed(false),
959 ),
960 Stream.filter((event) => path.basename(event.path) === "HEAD"),
961 // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
962 Stream.buffer({ capacity: 1, strategy: "sliding" }),
963 Stream.mapEffect(() => retryCheckedOutRef(cwd, publishCheckedOutRef(cwd))),
964 // Detailed status waits behind its own reads; the branch keeps up on the stage above.
965 Stream.buffer({ capacity: 1, strategy: "sliding" }),
966 Stream.runForEach(() => retryCheckedOutRef(cwd, reconcileCheckedOutRef(cwd))),
967 );
968 });
969​
970 const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* (
971 cwd: string,
972 ) {
973 const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => {
974 const existing = activeWatchers.get(cwd);
975 if (existing && existing.fiber.pollUnsafe() === undefined) {
976 const nextWatchers = new Map(activeWatchers).set(cwd, {
977 ...existing,
978 subscriberCount: existing.subscriberCount + 1,
979 });
980 return Effect.succeed([existing.ready, nextWatchers] as const);
981 }
982 // A watch that ended, say before the repository existed, restarts for everyone holding it.
983 return Effect.gen(function* () {
984 const ready = yield* Deferred.make<void>();
985 const fiber = yield* watchHead(cwd, ready).pipe(
986 Effect.catchCause((cause) =>
987 Effect.logWarning("VCS HEAD watch failed", {
988 cwdLength: cwd.length,
989 ...remoteRefreshFailureDiagnostics(cause),
990 }),
991 ),
992 // Subscribers wait for the watch, so one that cannot start must not hold them.
993 Effect.ensuring(Deferred.succeed(ready, undefined)),
994 Effect.forkIn(broadcasterScope),
995 );
996 const nextWatchers = new Map(activeWatchers).set(cwd, {
997 fiber,
998 ready,
999 subscriberCount: (existing?.subscriberCount ?? 0) + 1,
1000 });
1001 return [ready, nextWatchers] as const;
1002 });
1003 });
1004 yield* Deferred.await(ready);
1005 });
1006​
1007 const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* (
1008 cwd: string,
1009 ) {
1010 const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => {
1011 const existing = activeWatchers.get(cwd);
1012 if (!existing) return [null, activeWatchers] as const;
1013 const nextWatchers = new Map(activeWatchers);
1014 if (existing.subscriberCount > 1) {
1015 nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 });
1016 return [null, nextWatchers] as const;
1018 nextWatchers.delete(cwd);
1019 return [existing.fiber, nextWatchers] as const;
1020 });
1021 if (watcherToInterrupt) {
1022 yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore);
1024 });
1025​
1026 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
1027 Stream.unwrap(
1028 Effect.gen(function* () {
1029 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1030 yield* Effect.acquireRelease(
1031 Effect.sync(() => {
1032 const previous = detailedSubscribers.get(cwd) ?? 0;
1033 detailedSubscribers.set(cwd, previous + 1);
1034 }),
1035 () =>
1036 Effect.sync(() => {
1037 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
1038 if (remaining === 0) detailedSubscribers.delete(cwd);
1039 else detailedSubscribers.set(cwd, remaining);
1040 }),
1041 );
1042 const subscription = yield* PubSub.subscribe(changesPubSub);
1043 // Watch before reading so a checkout in between still publishes.
1044 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
1045 const initialLocal = yield* getOrLoadLocalStatus(cwd);
1046 const cachedStatus = yield* getCachedStatus(cwd);
1047 const initialRemote = cachedStatus?.remote?.value ?? null;
1048 if (input.includeRemote !== false) {
1049 yield* retainRemotePoller(
1050 cwd,
1051 input.cwd,
1052 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
1053 );
1055 const release =
1056 input.includeRemote === false
1057 ? Effect.void
1058 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
1059​
1060 return Stream.concat(
1061 Stream.make({
1062 _tag: "snapshot" as const,
1063 local: initialLocal,
1064 remote: initialRemote,
1065 }),
1066 Stream.fromSubscription(subscription).pipe(
1067 Stream.filter((event) => event.cwd === cwd),
1068 Stream.map((event) => event.event),
1069 ),
1070 ).pipe(Stream.ensuring(release));
1071 }),
1072 );
1073​
1074 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
1075 "VcsStatusBroadcaster.refreshBranchStatus",
1076 )(function* (input) {
1077 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1078 if (!detailedSubscribers.has(cwd)) {
1079 const { refName, isRepo } = yield* refreshBranchStatusCore(cwd);
1080 return { refName, isRepo };
1082 const { observation, refName, isRepo } = yield* readHeadBranch(cwd);
1083 yield* publishBranch(cwd, { refName, isRepo }, observation);
1084 yield* refreshBranchStatusCore(cwd).pipe(
1085 Effect.catchCause((cause) =>
1086 Effect.logWarning("VCS branch refresh failed", {
1087 cwdLength: cwd.length,
1088 ...remoteRefreshFailureDiagnostics(cause),
1089 }),
1090 ),
1091 Effect.forkIn(broadcasterScope),
1092 );
1093 return { refName, isRepo };
1094 });
1095​
1096 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
1097 Stream.unwrap(
1098 Effect.gen(function* () {
1099 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
1100 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
1101 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
1102 const branch = yield* refreshBranchStatusCore(cwd);
1103 return Stream.concat(
1104 Stream.make({ refName: branch.refName, isRepo: branch.isRepo }),
1105 Stream.fromSubscription(subscription).pipe(
1106 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
1107 Stream.map(({ refName, isRepo }) => ({ refName, isRepo })),
1108 ),
1109 ).pipe(
1110 Stream.changesWith(
1111 (left, right) => left.refName === right.refName && left.isRepo === right.isRepo,
1112 ),
1113 );
1114 }),
1115 );
1116​
1117 return VcsStatusBroadcaster.of({
1118 streamBranchStatus,
1119 refreshBranchStatus,
1120 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
1121 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
1122 ),
1123 getStatus,
1124 refreshLocalStatus,
1125 refreshStatus: shareQueuedRefreshStatus,
1126 refreshPullRequestStatus,
1127 streamStatus,
1128 });
1129});
1130​
1131export const layer = Layer.effect(VcsStatusBroadcaster, make);