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

VcsStatusBroadcaster.ts

980 lines36.2 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 revision: number;
279 }>(),
280 (pubsub) => PubSub.shutdown(pubsub),
281 );
282 const broadcasterScope = yield* Effect.acquireRelease(Scope.make(), (scope) =>
283 Scope.close(scope, Exit.void),
284 );
285 const detailedSubscribers = new Map<string, number>();
286 const branches = new Map<
287 string,
288 { readonly refName: string | null; readonly revision: number }
289 >();
290 let branchRevision = 0;
291 const publishBranch = Effect.fn("VcsStatusBroadcaster.publishBranch")(function* (
292 cwd: string,
293 refName: string | null,
294 ) {
295 if (branches.get(cwd)?.refName === refName) return;
296 const revision = ++branchRevision;
297 branches.set(cwd, { refName, revision });
298 yield* PubSub.publish(branchChangesPubSub, { cwd, refName, revision });
299 });
300 const localRefreshLocks = yield* KeyedLock.make<string>();
301 const cacheRef = yield* Ref.make(new Map<string, CachedVcsStatus>());
302 // One permit per cwd for remote reads that write the cache. Without it a
303 // periodic poll that started before an agent creates a PR can finish after the
304 // turn-end refresh and overwrite the fresh PR with its stale `pr: null`.
305 const remoteWriteLocks = yield* KeyedLock.make<string>();
306 const withRemoteWriteLock = <A, E, R>(cwd: string, effect: Effect.Effect<A, E, R>) =>
307 remoteWriteLocks.withLock(cwd, effect);
308 const pollersRef = yield* SynchronizedRef.make(new Map<string, ActiveRemotePoller>());
309 const headWatchersRef = yield* SynchronizedRef.make(new Map<string, ActiveHeadWatcher>());
310​
311 const getCachedStatus = Effect.fn("VcsStatusBroadcaster.getCachedStatus")(function* (
312 cwd: string,
313 ) {
314 return yield* Ref.get(cacheRef).pipe(Effect.map((cache) => cache.get(cwd) ?? null));
315 });
316​
317 const updateCachedLocalStatus = Effect.fn("VcsStatusBroadcaster.updateCachedLocalStatus")(
318 function* (cwd: string, local: VcsStatusLocalResult, options?: { publish?: boolean }) {
319 const nextLocal = { fingerprint: fingerprintStatusPart(local), value: local };
320 const [localChanged, remoteCleared] = yield* Ref.modify(cacheRef, (cache) => {
321 const previous = cache.get(cwd) ?? { local: null, remote: null };
322 const remote = previous.remote?.branch === local.refName ? previous.remote : null;
323 return [
324 [previous.local?.fingerprint !== nextLocal.fingerprint, previous.remote !== remote],
325 new Map(cache).set(cwd, { local: nextLocal, remote }),
326 ] as const;
327 });
328 yield* publishBranch(cwd, local.refName);
329 if (options?.publish && remoteCleared) {
330 yield* PubSub.publish(changesPubSub, {
331 cwd,
332 event: { _tag: "remoteUpdated", remote: null },
333 });
334 }
335 if (options?.publish && localChanged) {
336 yield* PubSub.publish(changesPubSub, {
337 cwd,
338 event: { _tag: "localUpdated", local },
339 });
340 }
341 return local;
342 },
343 );
344​
345 const updateCachedRemoteStatus = Effect.fn("VcsStatusBroadcaster.updateCachedRemoteStatus")(
346 function* (cwd: string, remote: CachedRemoteStatus | null, options?: { publish?: boolean }) {
347 const [changed, value] = yield* Ref.modify(cacheRef, (cache) => {
348 const previous = cache.get(cwd) ?? { local: null, remote: null };
349 const next = remote?.branch === previous.local?.value.refName ? remote : null;
350 return [
351 [previous.remote?.fingerprint !== next?.fingerprint, next?.value ?? null],
352 new Map(cache).set(cwd, { ...previous, remote: next }),
353 ] as const;
354 });
355 if (options?.publish && changed) {
356 yield* PubSub.publish(changesPubSub, {
357 cwd,
358 event: { _tag: "remoteUpdated", remote: value },
359 });
360 }
361 return value;
362 },
363 );
364​
365 const loadLocalStatus = Effect.fn("VcsStatusBroadcaster.loadLocalStatus")(function* (
366 cwd: string,
367 ) {
368 const local = yield* workflow.localStatus({ cwd });
369 return yield* updateCachedLocalStatus(cwd, local);
370 });
371​
372 const getOrLoadLocalStatusUnlocked = Effect.fn("VcsStatusBroadcaster.getOrLoadLocalStatus")(
373 function* (cwd: string) {
374 const cached = yield* getCachedStatus(cwd);
375 if (cached?.local) {
376 const branch = yield* workflow.currentBranch(cwd);
377 if (branch === cached.local.value.refName) return cached.local.value;
378 yield* workflow.invalidateLocalStatus(cwd);
379 return yield* updateCachedLocalStatus(cwd, yield* workflow.localStatus({ cwd }), {
380 publish: true,
381 });
382 }
383 return yield* loadLocalStatus(cwd);
384 },
385 );
386​
387 const getOrLoadLocalStatus = (cwd: string) =>
388 localRefreshLocks.withLock(cwd, getOrLoadLocalStatusUnlocked(cwd));
389​
390 const getStatusParts = Effect.fn("VcsStatusBroadcaster.getStatusParts")(function* (cwd: string) {
391 const cached = yield* getCachedStatus(cwd);
392 if (cached?.local) {
393 return { local: cached.local.value, remote: cached.remote?.value ?? null };
394 }
395 return { local: yield* getOrLoadLocalStatus(cwd), remote: null };
396 });
397​
398 const withFileSystem = Effect.provideService(FileSystem.FileSystem, fs);
399​
400 const getStatus: VcsStatusBroadcaster["Service"]["getStatus"] = Effect.fn(
401 "VcsStatusBroadcaster.getStatus",
402 )(function* (input) {
403 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
404 yield* getOrLoadLocalStatus(cwd);
405 const cached = yield* getCachedStatus(cwd);
406 if (cached?.local && cached.remote) {
407 return mergeGitStatusParts(cached.local.value, cached.remote.value);
408 }
409 return yield* withRemoteWriteLock(
410 cwd,
411 Effect.gen(function* () {
412 const latest = yield* getCachedStatus(cwd);
413 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
414 const remote = latest?.remote ?? (yield* readRemoteStatus(cwd, { refreshUpstream }));
415 yield* updateCachedRemoteStatus(cwd, remote);
416 const parts = yield* getStatusParts(cwd);
417 return mergeGitStatusParts(parts.local, parts.remote);
418 }),
419 );
420 });
421​
422 // A refresh that started after a request saw every change that request could mean, so queued
423 // callers share it instead of each running git status again.
424 const localRefreshRequests = new Map<string, number>();
425 const localRefreshResults = new Map<
426 string,
427 { readonly startedAt: number; readonly local: VcsStatusLocalResult }
428 >();
429 const refreshLocalStatusCore = Effect.fn("VcsStatusBroadcaster.refreshLocalStatusCore")(
430 function* (cwd: string) {
431 const requestedAt = (localRefreshRequests.get(cwd) ?? 0) + 1;
432 localRefreshRequests.set(cwd, requestedAt);
433 return yield* localRefreshLocks.withLock(
434 cwd,
435 Effect.gen(function* () {
436 const shared = localRefreshResults.get(cwd);
437 if (shared !== undefined && shared.startedAt >= requestedAt) return shared.local;
438 const startedAt = localRefreshRequests.get(cwd) ?? requestedAt;
439 yield* workflow.invalidateLocalStatus(cwd);
440 const local = yield* workflow.localStatus({ cwd });
441 localRefreshResults.set(cwd, { startedAt, local });
442 return yield* updateCachedLocalStatus(cwd, local, { publish: true });
443 }),
444 );
445 },
446 );
447​
448 const refreshLocalStatus: VcsStatusBroadcaster["Service"]["refreshLocalStatus"] = Effect.fn(
449 "VcsStatusBroadcaster.refreshLocalStatus",
450 )(function* (rawCwd) {
451 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
452 return yield* refreshLocalStatusCore(cwd);
453 });
454​
455 const readRemoteStatus = Effect.fn("VcsStatusBroadcaster.readRemoteStatus")(function* (
456 cwd: string,
457 options?: Parameters<GitWorkflowService.GitWorkflowService["Service"]["remoteStatus"]>[1],
458 ) {
459 const branch = yield* workflow.currentBranch(cwd);
460 // GitManager's remote TTL cache is keyed by cwd, not the checked-out branch.
461 yield* workflow.invalidateRemoteStatus(cwd);
462 const value = yield* workflow.remoteStatus({ cwd }, options);
463 const currentBranch = yield* workflow.currentBranch(cwd);
464 const cached = yield* getCachedStatus(cwd);
465 if (branch !== currentBranch || cached?.local?.value.refName !== currentBranch) {
466 yield* refreshLocalStatusCore(cwd);
467 }
468 return branch === currentBranch
469 ? { branch, value, fingerprint: fingerprintStatusPart(value) }
470 : null;
471 });
472​
473 const maybeAutoPull = Effect.fn("VcsStatusBroadcaster.maybeAutoPull")(function* (
474 cwd: string,
475 remoteRead: CachedRemoteStatus | null,
476 policyCwds: ReadonlyArray<string>,
477 ) {
478 const remote = remoteRead?.value ?? null;
479 let pullAttempted = false;
480 return yield* Effect.gen(function* () {
481 const autoPullEnabled = (yield* Effect.forEach(policyCwds, autoPullPolicy.isEnabled, {
482 concurrency: "unbounded",
483 })).some(Boolean);
484 if (
485 remote === null ||
486 !remote.hasUpstream ||
487 remote.aheadCount > 0 ||
488 remote.behindCount <= 0 ||
489 !autoPullEnabled
490 ) {
491 return null;
492 }
493​
494 yield* workflow.invalidateLocalStatus(cwd);
495 const local = yield* workflow.localStatus({ cwd });
496 if (
497 !local.isRepo ||
498 !local.isDefaultRef ||
499 local.hasWorkingTreeChanges ||
500 local.refName !== remoteRead?.branch
501 )
502 return null;
503​
504 pullAttempted = true;
505 yield* workflow.pullCurrentBranch(cwd);
506 yield* workflow.invalidateStatus(cwd);
507 yield* refreshLocalStatusCore(cwd);
508 const refreshedRemote = yield* readRemoteStatus(cwd, { refreshUpstream: false });
509 yield* updateCachedRemoteStatus(cwd, refreshedRemote, { publish: true });
510 return yield* getStatusParts(cwd);
511 }).pipe(
512 Effect.catch((error) =>
513 Effect.gen(function* () {
514 yield* Effect.logWarning("Automatic project pull failed", {
515 cwdLength: cwd.length,
516 errorTag: error._tag,
517 });
518 if (!pullAttempted) return null;
519 // A pull or its follow-up reads can fail after local state has changed.
520 // Let a failed reconciliation reach the caller instead of publishing old status.
521 yield* refreshLocalStatusCore(cwd);
522 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
523 return yield* getStatusParts(cwd);
524 }),
525 ),
526 );
527 });
528​
529 const refreshRemoteStatus = Effect.fn("VcsStatusBroadcaster.refreshRemoteStatus")(function* (
530 cwd: string,
531 options?: {
532 readonly refreshUpstream?: boolean;
533 readonly policyCwds?: ReadonlyArray<string>;
534 },
535 ) {
536 return yield* withRemoteWriteLock(
537 cwd,
538 Effect.gen(function* () {
539 const remoteRead = yield* readRemoteStatus(cwd, options);
540 const pulled =
541 options?.refreshUpstream === false
542 ? null
543 : yield* maybeAutoPull(cwd, remoteRead, options?.policyCwds ?? [cwd]);
544 if (pulled !== null) return pulled.remote;
545 // Base refs and merge bases can move without changing divergence counts.
546 yield* refreshLocalStatusCore(cwd);
547 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
548 }),
549 );
550 });
551​
552 const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(
553 "VcsStatusBroadcaster.refreshStatus",
554 )(function* (rawCwd, options) {
555 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
556 yield* refreshLocalStatusCore(cwd);
557 if (options?.localOnly) {
558 // Never cache a remote here: readers take `value: null` as "read and found no PR".
559 const parts = yield* getStatusParts(cwd);
560 return mergeGitStatusParts(parts.local, parts.remote);
561 }
562 return yield* withRemoteWriteLock(
563 cwd,
564 Effect.gen(function* () {
565 const refreshUpstream = !Duration.isZero(yield* automaticFetchInterval);
566 // Bump the PR lookup epoch after earlier remote writers have finished.
567 yield* workflow.invalidateStatus(cwd);
568 const remoteRead = yield* readRemoteStatus(cwd, { refreshUpstream });
569 // Fetch can move the base used for local Changes totals.
570 yield* refreshLocalStatusCore(cwd);
571 // Without a fetch, the cached behind count cannot justify an automatic pull.
572 const pulled = refreshUpstream ? yield* maybeAutoPull(cwd, remoteRead, [rawCwd]) : null;
573 if (pulled !== null) return mergeGitStatusParts(pulled.local, pulled.remote);
574 yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
575 const parts = yield* getStatusParts(cwd);
576 return mergeGitStatusParts(parts.local, parts.remote);
577 }),
578 );
579 });
580​
581 const refreshPullRequestStatus: VcsStatusBroadcaster["Service"]["refreshPullRequestStatus"] =
582 Effect.fn("VcsStatusBroadcaster.refreshPullRequestStatus")(function* (rawCwd) {
583 const cwd = yield* withFileSystem(normalizeCwd(rawCwd));
584 return yield* withRemoteWriteLock(
585 cwd,
586 Effect.gen(function* () {
587 const cached = yield* getCachedStatus(cwd);
588 if (!cached || cached.remote?.value === null) return null;
589 // Turn completion must update divergence even when background polling is paused.
590 const remoteRead = yield* readRemoteStatus(cwd, {
591 refreshUpstream: false,
592 refreshMissingPullRequest: true,
593 });
594 return yield* updateCachedRemoteStatus(cwd, remoteRead, { publish: true });
595 }),
596 );
597 });
598​
599 // A subscription owns this loop; keep each poll's spans out of a never-ending parent span.
600 const makeRemoteRefreshLoop = Effect.fnUntraced(function* (
601 cwd: string,
602 demandCwdsRef: Ref.Ref<ReadonlyMap<string, number>>,
603 refreshImmediately: boolean,
604 ) {
605 const consecutiveFailuresRef = yield* Ref.make(0);
606 const needsInitialRefreshRef = yield* Ref.make(refreshImmediately);
607 const refreshRemoteStatusIfEnabled = Effect.gen(function* () {
608 const configuredInterval = yield* automaticFetchInterval;
609 const activeInterval = Duration.isZero(configuredInterval)
610 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
611 : configuredInterval;
612 const needsInitialRefresh = yield* Ref.get(needsInitialRefreshRef);
613 if (Duration.isZero(configuredInterval) && !needsInitialRefresh) {
614 return activeInterval;
615 }
616​
617 const demandCwds = yield* Ref.get(demandCwdsRef);
618 const shouldRun =
619 needsInitialRefresh ||
620 (yield* Effect.forEach(
621 [...demandCwds.keys()],
622 (demandCwd) =>
623 backgroundPolicy.shouldRunScopeWork({
624 type: "vcs-status",
625 cwd: demandCwd,
626 }),
627 { concurrency: "unbounded" },
628 )).some(Boolean);
629 if (!shouldRun) {
630 return activeInterval;
631 }
632​
633 const exit = yield* refreshRemoteStatus(cwd, {
634 refreshUpstream: !Duration.isZero(configuredInterval),
635 policyCwds: [...demandCwds.keys()],
636 }).pipe(Effect.exit);
637 if (Exit.isSuccess(exit)) {
638 yield* Ref.set(needsInitialRefreshRef, false);
639 yield* Ref.set(consecutiveFailuresRef, 0);
640 return activeInterval;
641 }
642​
643 const interruptionReasons = exit.cause.reasons.filter(Cause.isInterruptReason);
644 if (interruptionReasons.length > 0) {
645 return yield* Effect.failCause(Cause.fromReasons<never>(interruptionReasons));
646 }
647​
648 const consecutiveFailures = yield* Ref.updateAndGet(
649 consecutiveFailuresRef,
650 (count) => count + 1,
651 );
652 const nextDelay = remoteRefreshFailureDelay(consecutiveFailures, activeInterval);
653 yield* Effect.logWarning("VCS remote status refresh failed", {
654 cwdLength: cwd.length,
655 ...remoteRefreshFailureDiagnostics(exit.cause),
656 consecutiveFailures,
657 nextDelayMs: Duration.toMillis(nextDelay),
658 });
659 return nextDelay;
660 });
661​
662 if (!refreshImmediately) {
663 const configuredInterval = yield* automaticFetchInterval;
664 yield* Effect.sleep(
665 Duration.isZero(configuredInterval)
666 ? DEFAULT_AUTOMATIC_GIT_FETCH_INTERVAL
667 : configuredInterval,
668 );
669 }
670​
671 return yield* refreshRemoteStatusIfEnabled.pipe(
672 Effect.repeat(
673 Schedule.identity<Duration.Duration>().pipe(
674 Schedule.addDelay(({ output: delay }) => Effect.succeed(delay)),
675 ),
676 ),
677 Effect.asVoid,
678 );
679 });
680​
681 const retainRemotePoller = Effect.fn("VcsStatusBroadcaster.retainRemotePoller")(function* (
682 cwd: string,
683 demandCwd: string,
684 refreshImmediately: boolean,
685 ) {
686 yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
687 const existing = activePollers.get(cwd);
688 if (existing) {
689 return Ref.update(existing.demandCwds, (demandCwds) => {
690 const next = new Map(demandCwds);
691 next.set(demandCwd, (next.get(demandCwd) ?? 0) + 1);
692 return next;
693 }).pipe(
694 Effect.map(() => {
695 const nextPollers = new Map(activePollers);
696 nextPollers.set(cwd, {
697 ...existing,
698 subscriberCount: existing.subscriberCount + 1,
699 });
700 return [undefined, nextPollers] as const;
701 }),
702 );
703 }
704​
705 return Ref.make<ReadonlyMap<string, number>>(new Map([[demandCwd, 1]])).pipe(
706 Effect.flatMap((demandCwds) =>
707 makeRemoteRefreshLoop(cwd, demandCwds, refreshImmediately).pipe(
708 Effect.forkIn(broadcasterScope),
709 Effect.map((fiber) => {
710 const nextPollers = new Map(activePollers);
711 nextPollers.set(cwd, {
712 fiber,
713 subscriberCount: 1,
714 demandCwds,
715 });
716 return [undefined, nextPollers] as const;
717 }),
718 ),
719 ),
720 );
721 });
722 });
723​
724 const releaseRemotePoller = Effect.fn("VcsStatusBroadcaster.releaseRemotePoller")(function* (
725 cwd: string,
726 demandCwd: string,
727 ) {
728 const pollerToInterrupt = yield* SynchronizedRef.modifyEffect(pollersRef, (activePollers) => {
729 const existing = activePollers.get(cwd);
730 if (!existing) {
731 return Effect.succeed([null, activePollers] as const);
732 }
733​
734 if (existing.subscriberCount > 1) {
735 return Ref.update(existing.demandCwds, (demandCwds) => {
736 const nextDemandCwds = new Map(demandCwds);
737 const count = nextDemandCwds.get(demandCwd) ?? 0;
738 if (count <= 1) {
739 nextDemandCwds.delete(demandCwd);
740 } else {
741 nextDemandCwds.set(demandCwd, count - 1);
742 }
743 return nextDemandCwds;
744 }).pipe(
745 Effect.as([
746 null,
747 new Map(activePollers).set(cwd, {
748 ...existing,
749 subscriberCount: existing.subscriberCount - 1,
750 }),
751 ] as const),
752 );
753 }
754​
755 return Effect.succeed([
756 existing.fiber,
757 new Map([...activePollers].filter(([activeCwd]) => activeCwd !== cwd)),
758 ] as const);
759 });
760​
761 if (pollerToInterrupt) {
762 yield* Fiber.interrupt(pollerToInterrupt).pipe(Effect.ignore);
763 }
764 });
765​
766 // Serialize branch publication and cache invalidation with detailed reads and refreshes.
767 const refreshBranchStatusCore = Effect.fn("VcsStatusBroadcaster.refreshBranchStatusCore")(
768 (cwd: string) =>
769 localRefreshLocks.withLock(
770 cwd,
771 Effect.gen(function* () {
772 if (detailedSubscribers.has(cwd)) {
773 const local = yield* getOrLoadLocalStatusUnlocked(cwd);
774 return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
775 }
776 const refName = yield* workflow.currentBranch(cwd);
777 // HEAD cannot certify working-tree totals, even when it has not moved.
778 localRefreshResults.delete(cwd);
779 yield* workflow.invalidateLocalStatus(cwd);
780 yield* Ref.update(cacheRef, (cache) => {
781 const previous = cache.get(cwd);
782 return previous ? new Map(cache).set(cwd, { ...previous, local: null }) : cache;
783 });
784 if (detailedSubscribers.has(cwd)) {
785 const local = yield* workflow.localStatus({ cwd });
786 yield* updateCachedLocalStatus(cwd, local, { publish: true });
787 return { refName: local.refName, revision: branches.get(cwd)?.revision ?? 0 };
788 }
789 yield* publishBranch(cwd, refName);
790 return { refName, revision: branches.get(cwd)?.revision ?? 0 };
791 }),
792 ),
793 );
794​
795 // A checkout outside T3 Code, such as `git switch` in the terminal, calls no refresh RPC.
796 // Rereading remote too, without a fetch, sends the new branch with its own PR and counts.
797 const refreshCheckedOutRef = Effect.fn("VcsStatusBroadcaster.refreshCheckedOutRef")(function* (
798 cwd: string,
799 ) {
800 if (!detailedSubscribers.has(cwd)) {
801 yield* refreshBranchStatusCore(cwd);
802 } else if ((yield* getCachedStatus(cwd))?.remote) {
803 yield* refreshRemoteStatus(cwd, { refreshUpstream: false });
804 } else {
805 yield* refreshLocalStatusCore(cwd);
806 }
807 });
808​
809 // Runs for the subscription lifetime, so tracing would leave a span open indefinitely.
810 const watchHead = Effect.fnUntraced(function* (cwd: string, ready: Deferred.Deferred<void>) {
811 const headPath = yield* workflow.headPath(cwd);
812 if (headPath === null) return;
813 // Git replaces HEAD by renaming HEAD.lock, which a watch on the file itself would lose.
814 yield* fs
815 .watch(path.dirname(headPath), {
816 onReady: () => Deferred.doneUnsafe(ready, Exit.void),
817 })
818 .pipe(
819 Stream.filter((event) => path.basename(event.path) === "HEAD"),
820 // A rebase moves HEAD many times; refresh once for whatever arrived during a refresh.
821 Stream.buffer({ capacity: 1, strategy: "sliding" }),
822 Stream.runForEach(() =>
823 refreshCheckedOutRef(cwd).pipe(
824 Effect.retry(CHECKOUT_REFRESH_RETRY),
825 Effect.catchCause((cause) =>
826 Effect.logWarning("VCS checked-out ref refresh failed", {
827 cwdLength: cwd.length,
828 ...remoteRefreshFailureDiagnostics(cause),
829 }),
830 ),
831 ),
832 ),
833 );
834 });
835​
836 const retainHeadWatcher = Effect.fn("VcsStatusBroadcaster.retainHeadWatcher")(function* (
837 cwd: string,
838 ) {
839 const ready = yield* SynchronizedRef.modifyEffect(headWatchersRef, (activeWatchers) => {
840 const existing = activeWatchers.get(cwd);
841 if (existing && existing.fiber.pollUnsafe() === undefined) {
842 const nextWatchers = new Map(activeWatchers).set(cwd, {
843 ...existing,
844 subscriberCount: existing.subscriberCount + 1,
845 });
846 return Effect.succeed([existing.ready, nextWatchers] as const);
847 }
848 // A watch that ended, say before the repository existed, restarts for everyone holding it.
849 return Effect.gen(function* () {
850 const ready = yield* Deferred.make<void>();
851 const fiber = yield* watchHead(cwd, ready).pipe(
852 Effect.catchCause((cause) =>
853 Effect.logWarning("VCS HEAD watch failed", {
854 cwdLength: cwd.length,
855 ...remoteRefreshFailureDiagnostics(cause),
856 }),
857 ),
858 // Subscribers wait for the watch, so one that cannot start must not hold them.
859 Effect.ensuring(Deferred.succeed(ready, undefined)),
860 Effect.forkIn(broadcasterScope),
861 );
862 const nextWatchers = new Map(activeWatchers).set(cwd, {
863 fiber,
864 ready,
865 subscriberCount: (existing?.subscriberCount ?? 0) + 1,
866 });
867 return [ready, nextWatchers] as const;
868 });
869 });
870 yield* Deferred.await(ready);
871 });
872​
873 const releaseHeadWatcher = Effect.fn("VcsStatusBroadcaster.releaseHeadWatcher")(function* (
874 cwd: string,
875 ) {
876 const watcherToInterrupt = yield* SynchronizedRef.modify(headWatchersRef, (activeWatchers) => {
877 const existing = activeWatchers.get(cwd);
878 if (!existing) return [null, activeWatchers] as const;
879 const nextWatchers = new Map(activeWatchers);
880 if (existing.subscriberCount > 1) {
881 nextWatchers.set(cwd, { ...existing, subscriberCount: existing.subscriberCount - 1 });
882 return [null, nextWatchers] as const;
883 }
884 nextWatchers.delete(cwd);
885 return [existing.fiber, nextWatchers] as const;
886 });
887 if (watcherToInterrupt) {
888 yield* Fiber.interrupt(watcherToInterrupt).pipe(Effect.ignore);
889 }
890 });
891​
892 const streamStatus: VcsStatusBroadcaster["Service"]["streamStatus"] = (input) =>
893 Stream.unwrap(
894 Effect.gen(function* () {
895 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
896 yield* Effect.acquireRelease(
897 Effect.sync(() => {
898 const previous = detailedSubscribers.get(cwd) ?? 0;
899 detailedSubscribers.set(cwd, previous + 1);
900 }),
901 () =>
902 Effect.sync(() => {
903 const remaining = (detailedSubscribers.get(cwd) ?? 1) - 1;
904 if (remaining === 0) detailedSubscribers.delete(cwd);
905 else detailedSubscribers.set(cwd, remaining);
906 }),
907 );
908 const subscription = yield* PubSub.subscribe(changesPubSub);
909 // Watch before reading so a checkout in between still publishes.
910 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
911 const initialLocal = yield* getOrLoadLocalStatus(cwd);
912 const cachedStatus = yield* getCachedStatus(cwd);
913 const initialRemote = cachedStatus?.remote?.value ?? null;
914 if (input.includeRemote !== false) {
915 yield* retainRemotePoller(
916 cwd,
917 input.cwd,
918 cachedStatus?.remote === null || cachedStatus?.remote === undefined,
919 );
920 }
921 const release =
922 input.includeRemote === false
923 ? Effect.void
924 : releaseRemotePoller(cwd, input.cwd).pipe(Effect.ignore, Effect.asVoid);
925​
926 return Stream.concat(
927 Stream.make({
928 _tag: "snapshot" as const,
929 local: initialLocal,
930 remote: initialRemote,
931 }),
932 Stream.fromSubscription(subscription).pipe(
933 Stream.filter((event) => event.cwd === cwd),
934 Stream.map((event) => event.event),
935 ),
936 ).pipe(Stream.ensuring(release));
937 }),
938 );
939​
940 const refreshBranchStatus: VcsStatusBroadcaster["Service"]["refreshBranchStatus"] = Effect.fn(
941 "VcsStatusBroadcaster.refreshBranchStatus",
942 )(function* (input) {
943 const { refName } = yield* refreshBranchStatusCore(
944 yield* withFileSystem(normalizeCwd(input.cwd)),
945 );
946 return { refName };
947 });
948​
949 const streamBranchStatus: VcsStatusBroadcaster["Service"]["streamBranchStatus"] = (input) =>
950 Stream.unwrap(
951 Effect.gen(function* () {
952 const cwd = yield* withFileSystem(normalizeCwd(input.cwd));
953 const subscription = yield* PubSub.subscribe(branchChangesPubSub);
954 yield* Effect.acquireRelease(retainHeadWatcher(cwd), () => releaseHeadWatcher(cwd));
955 const branch = yield* refreshBranchStatusCore(cwd);
956 return Stream.concat(
957 Stream.make({ refName: branch.refName }),
958 Stream.fromSubscription(subscription).pipe(
959 Stream.filter((event) => event.cwd === cwd && event.revision > branch.revision),
960 Stream.map(({ refName }) => ({ refName })),
961 ),
962 ).pipe(Stream.changesWith((left, right) => left.refName === right.refName));
963 }),
964 );
965​
966 return VcsStatusBroadcaster.of({
967 streamBranchStatus,
968 refreshBranchStatus,
969 streamBranchChanges: Stream.fromPubSub(branchChangesPubSub).pipe(
970 Stream.map(({ cwd, refName }) => ({ cwd, refName })),
971 ),
972 getStatus,
973 refreshLocalStatus,
974 refreshStatus,
975 refreshPullRequestStatus,
976 streamStatus,
977 });
978});
979​
980export const layer = Layer.effect(VcsStatusBroadcaster, make);