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

VcsStatusBroadcaster.ts

1,360 lines52.4 KB

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