From 6c0533a23b0fc294149860d3b8ef87d79ea51282 Mon Sep 17 00:00:00 2001 From: Ben Davis Date: Fri, 26 Jun 2026 11:14:27 -0700 Subject: [PATCH] fix(server): harden background Git status refresh --- apps/server/src/git/GitWorkflowService.ts | 7 + apps/server/src/vcs/GitVcsDriver.ts | 1 + apps/server/src/vcs/GitVcsDriverCore.test.ts | 211 +++++++++++++++++- apps/server/src/vcs/GitVcsDriverCore.ts | 162 ++++++++++---- .../src/vcs/VcsStatusBroadcaster.test.ts | 96 ++++++++ apps/server/src/vcs/VcsStatusBroadcaster.ts | 12 +- 6 files changed, 448 insertions(+), 41 deletions(-) diff --git a/apps/server/src/git/GitWorkflowService.ts b/apps/server/src/git/GitWorkflowService.ts index 100b9beadb..d0adff88b3 100644 --- a/apps/server/src/git/GitWorkflowService.ts +++ b/apps/server/src/git/GitWorkflowService.ts @@ -45,6 +45,7 @@ export class GitWorkflowService extends Context.Service< input: VcsStatusInput, options?: GitVcsDriver.GitRemoteStatusOptions, ) => Effect.Effect; + readonly refreshStatusUpstream: (cwd: string) => Effect.Effect; readonly invalidateLocalStatus: (cwd: string) => Effect.Effect; readonly invalidateRemoteStatus: (cwd: string) => Effect.Effect; readonly invalidateStatus: (cwd: string) => Effect.Effect; @@ -270,6 +271,12 @@ export const make = Effect.gen(function* () { isGitRepository ? gitManager.remoteStatus(input, options) : Effect.succeed(null), ), ), + refreshStatusUpstream: (cwd) => + detectGitRepositoryForStatus("GitWorkflowService.refreshStatusUpstream", cwd).pipe( + Effect.flatMap((isGitRepository) => + isGitRepository ? git.refreshStatusUpstream(cwd) : Effect.void, + ), + ), invalidateLocalStatus: gitManager.invalidateLocalStatus, invalidateRemoteStatus: gitManager.invalidateRemoteStatus, invalidateStatus: gitManager.invalidateStatus, diff --git a/apps/server/src/vcs/GitVcsDriver.ts b/apps/server/src/vcs/GitVcsDriver.ts index 55aa8f3883..5281775b51 100644 --- a/apps/server/src/vcs/GitVcsDriver.ts +++ b/apps/server/src/vcs/GitVcsDriver.ts @@ -199,6 +199,7 @@ export class GitVcsDriver extends Context.Service< cwd: string, options?: GitRemoteStatusOptions, ) => Effect.Effect; + readonly refreshStatusUpstream: (cwd: string) => Effect.Effect; readonly prepareCommitContext: ( cwd: string, filePaths?: readonly string[], diff --git a/apps/server/src/vcs/GitVcsDriverCore.test.ts b/apps/server/src/vcs/GitVcsDriverCore.test.ts index dc58fc2543..4ed52be86d 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.test.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.test.ts @@ -8,6 +8,7 @@ import * as PlatformError from "effect/PlatformError"; import * as Scope from "effect/Scope"; import { GitCommandError } from "@t3tools/contracts"; +import { HostProcessPlatform } from "@t3tools/shared/hostProcess"; import { ServerConfig } from "../config.ts"; import { splitNullSeparatedGitStdoutPaths } from "./GitVcsDriverCore.ts"; import * as GitVcsDriver from "./GitVcsDriver.ts"; @@ -58,6 +59,20 @@ const git = ( return result.stdout.trim(); }); +const findGitExecutable = Effect.fn("GitVcsDriver.test.findGitExecutable")(function* () { + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const pathDelimiter = (yield* HostProcessPlatform) === "win32" ? ";" : ":"; + for (const entry of (process.env.PATH ?? "").split(pathDelimiter)) { + if (entry.length === 0) continue; + const candidate = pathService.join(entry, "git"); + if (yield* fileSystem.exists(candidate)) { + return yield* fileSystem.realPath(candidate); + } + } + return yield* Effect.die(new Error("Could not find the Git executable in PATH.")); +}); + const initRepoWithCommit = ( cwd: string, ): Effect.Effect< @@ -148,6 +163,7 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { const cwd = pathService.join(parent, "missing"); const driver = yield* GitVcsDriver.GitVcsDriver; + yield* driver.refreshStatusUpstream(cwd); const [localStatus, remoteStatus, refs] = yield* Effect.all([ driver.statusDetails(cwd), driver.statusDetailsRemote(cwd, { refreshUpstream: false }), @@ -435,8 +451,16 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { process.env.SSH_ASKPASS_REQUIRE = "force"; process.env.T3_TEST_SSH_ASKPASS_LOG = sshLogPath; - yield* (yield* GitVcsDriver.GitVcsDriver).statusDetails(cwd); + const refreshError = yield* (yield* GitVcsDriver.GitVcsDriver) + .refreshStatusUpstream(cwd) + .pipe(Effect.flip); + assert.deepInclude(refreshError, { + _tag: "GitCommandError", + operation: "GitVcsDriver.fetchRemoteForStatus", + cwd, + detail: "Background Git fetch failed.", + }); assert.deepEqual((yield* fileSystem.readFileString(sshLogPath)).trim().split(/\r?\n/), [ "GCM_INTERACTIVE=never", "GIT_ASKPASS=", @@ -461,6 +485,191 @@ it.layer(TestLayer)("GitVcsDriver core integration", (it) => { }), ); + it.effect("fetches status remotes from the worktree with hardened background flags", () => + Effect.gen(function* () { + const platform = yield* HostProcessPlatform; + if (platform === "win32") return; + + const cwd = yield* makeTmpDir(); + const remote = yield* makeTmpDir("git-vcs-driver-remote-"); + const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const realGit = yield* findGitExecutable(); + const wrapperPath = pathService.join(wrapperDir, "git"); + const invocationLogPath = pathService.join(wrapperDir, "fetch-invocation.txt"); + const fetchHeadPath = pathService.join(cwd, ".git", "FETCH_HEAD"); + const previousPath = process.env.PATH; + const previousRealGit = process.env.T3_TEST_REAL_GIT; + const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG; + + yield* git(remote, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", remote]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + yield* fileSystem.writeFileString(fetchHeadPath, "sentinel-fetch-head\n"); + yield* fileSystem.writeFileString( + wrapperPath, + [ + "#!/bin/sh", + "is_fetch=0", + 'for arg in "$@"; do', + ' if [ "$arg" = "fetch" ]; then is_fetch=1; fi', + "done", + 'if [ "$is_fetch" = "1" ]; then', + ' printf "cwd=%s\\n" "$PWD" > "$T3_TEST_FETCH_INVOCATION_LOG"', + ' for arg in "$@"; do', + ' printf "arg=%s\\n" "$arg" >> "$T3_TEST_FETCH_INVOCATION_LOG"', + " done", + "fi", + 'exec "$T3_TEST_REAL_GIT" "$@"', + "", + ].join("\n"), + ); + yield* fileSystem.chmod(wrapperPath, 0o755); + + yield* Effect.gen(function* () { + process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`; + process.env.T3_TEST_REAL_GIT = realGit; + process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath; + + yield* (yield* GitVcsDriver.GitVcsDriver).refreshStatusUpstream(cwd); + + assert.deepStrictEqual( + (yield* fileSystem.readFileString(invocationLogPath)).trim().split(/\r?\n/), + [ + `cwd=${cwd}`, + "arg=fetch", + "arg=--quiet", + "arg=--no-tags", + "arg=--no-write-fetch-head", + "arg=--no-auto-maintenance", + "arg=--no-recurse-submodules", + "arg=--", + "arg=origin", + ], + ); + assert.equal(yield* fileSystem.readFileString(fetchHeadPath), "sentinel-fetch-head\n"); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (previousPath === undefined) delete process.env.PATH; + else process.env.PATH = previousPath; + if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT; + else process.env.T3_TEST_REAL_GIT = previousRealGit; + if (previousInvocationLog === undefined) { + delete process.env.T3_TEST_FETCH_INVOCATION_LOG; + } else { + process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog; + } + }), + ), + ); + }), + ); + + it.effect("coalesces matching refreshes and serializes different remotes sharing objects", () => + Effect.gen(function* () { + const platform = yield* HostProcessPlatform; + if (platform === "win32") return; + + const cwd = yield* makeTmpDir(); + const origin = yield* makeTmpDir("git-vcs-driver-origin-"); + const backup = yield* makeTmpDir("git-vcs-driver-backup-"); + const worktreeParent = yield* makeTmpDir("git-vcs-driver-worktrees-"); + const wrapperDir = yield* makeTmpDir("git-vcs-driver-wrapper-"); + const { initialBranch } = yield* initRepoWithCommit(cwd); + const fileSystem = yield* FileSystem.FileSystem; + const pathService = yield* Path.Path; + const worktreeCwd = pathService.join(worktreeParent, "feature"); + const realGit = yield* findGitExecutable(); + const wrapperPath = pathService.join(wrapperDir, "git"); + const invocationLogPath = pathService.join(wrapperDir, "fetches.txt"); + const activeLockPath = pathService.join(wrapperDir, "active-fetch"); + const overlapLogPath = pathService.join(wrapperDir, "overlap.txt"); + const previousPath = process.env.PATH; + const previousRealGit = process.env.T3_TEST_REAL_GIT; + const previousInvocationLog = process.env.T3_TEST_FETCH_INVOCATION_LOG; + const previousActiveLock = process.env.T3_TEST_FETCH_ACTIVE_LOCK; + const previousOverlapLog = process.env.T3_TEST_FETCH_OVERLAP_LOG; + + yield* git(origin, ["init", "--bare"]); + yield* git(backup, ["init", "--bare"]); + yield* git(cwd, ["remote", "add", "origin", origin]); + yield* git(cwd, ["remote", "add", "backup", backup]); + yield* git(cwd, ["push", "-u", "origin", initialBranch]); + yield* git(cwd, ["worktree", "add", "-b", "feature/serialized", worktreeCwd]); + yield* git(worktreeCwd, ["push", "-u", "backup", "feature/serialized"]); + yield* fileSystem.writeFileString( + wrapperPath, + [ + "#!/bin/sh", + "is_fetch=0", + 'for arg in "$@"; do', + ' if [ "$arg" = "fetch" ]; then is_fetch=1; fi', + "done", + 'if [ "$is_fetch" = "1" ]; then', + ' printf "start\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"', + ' if ! mkdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null; then', + ' printf "overlap\\n" >> "$T3_TEST_FETCH_OVERLAP_LOG"', + " fi", + " sleep 0.2", + ' "$T3_TEST_REAL_GIT" "$@"', + " status=$?", + ' rmdir "$T3_TEST_FETCH_ACTIVE_LOCK" 2>/dev/null || true', + ' printf "end\\n" >> "$T3_TEST_FETCH_INVOCATION_LOG"', + " exit $status", + "fi", + 'exec "$T3_TEST_REAL_GIT" "$@"', + "", + ].join("\n"), + ); + yield* fileSystem.chmod(wrapperPath, 0o755); + + yield* Effect.gen(function* () { + process.env.PATH = `${wrapperDir}:${previousPath ?? ""}`; + process.env.T3_TEST_REAL_GIT = realGit; + process.env.T3_TEST_FETCH_INVOCATION_LOG = invocationLogPath; + process.env.T3_TEST_FETCH_ACTIVE_LOCK = activeLockPath; + process.env.T3_TEST_FETCH_OVERLAP_LOG = overlapLogPath; + + const driver = yield* GitVcsDriver.GitVcsDriver; + yield* Effect.all( + [ + driver.refreshStatusUpstream(cwd), + driver.refreshStatusUpstream(cwd), + driver.refreshStatusUpstream(worktreeCwd), + ], + { concurrency: "unbounded", discard: true }, + ); + + const invocationLines = (yield* fileSystem.readFileString(invocationLogPath)) + .trim() + .split(/\r?\n/); + assert.deepStrictEqual(invocationLines, ["start", "end", "start", "end"]); + assert.equal(yield* fileSystem.exists(overlapLogPath), false); + }).pipe( + Effect.ensuring( + Effect.sync(() => { + if (previousPath === undefined) delete process.env.PATH; + else process.env.PATH = previousPath; + if (previousRealGit === undefined) delete process.env.T3_TEST_REAL_GIT; + else process.env.T3_TEST_REAL_GIT = previousRealGit; + if (previousInvocationLog === undefined) { + delete process.env.T3_TEST_FETCH_INVOCATION_LOG; + } else { + process.env.T3_TEST_FETCH_INVOCATION_LOG = previousInvocationLog; + } + if (previousActiveLock === undefined) delete process.env.T3_TEST_FETCH_ACTIVE_LOCK; + else process.env.T3_TEST_FETCH_ACTIVE_LOCK = previousActiveLock; + if (previousOverlapLog === undefined) delete process.env.T3_TEST_FETCH_OVERLAP_LOG; + else process.env.T3_TEST_FETCH_OVERLAP_LOG = previousOverlapLog; + }), + ), + ); + }), + ); + it.effect("reuses the no-upstream fallback ahead count for default-branch delta", () => Effect.gen(function* () { const cwd = yield* makeTmpDir(); diff --git a/apps/server/src/vcs/GitVcsDriverCore.ts b/apps/server/src/vcs/GitVcsDriverCore.ts index a406cbce54..cc8f17066b 100644 --- a/apps/server/src/vcs/GitVcsDriverCore.ts +++ b/apps/server/src/vcs/GitVcsDriverCore.ts @@ -1,13 +1,14 @@ import * as Arr from "effect/Array"; import * as Cache from "effect/Cache"; -import * as Data from "effect/Data"; import * as Crypto from "effect/Crypto"; import * as DateTime from "effect/DateTime"; import * as Duration from "effect/Duration"; import * as Effect from "effect/Effect"; +import * as Equal from "effect/Equal"; import * as Encoding from "effect/Encoding"; import * as Exit from "effect/Exit"; import * as FileSystem from "effect/FileSystem"; +import * as Hash from "effect/Hash"; import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as PlatformError from "effect/PlatformError"; @@ -48,9 +49,9 @@ const REVIEW_DIFF_PATCH_MAX_OUTPUT_BYTES = 120_000; const REVIEW_UNTRACKED_DIFF_MAX_OUTPUT_BYTES = 80_000; const WORKSPACE_FILES_MAX_OUTPUT_BYTES = 120_000; const STATUS_UPSTREAM_REFRESH_INTERVAL = Duration.seconds(15); -const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.seconds(5); +const STATUS_UPSTREAM_REFRESH_TIMEOUT = Duration.minutes(1); -const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(5); +const STATUS_UPSTREAM_REFRESH_FAILURE_COOLDOWN = Duration.seconds(30); const STATUS_UPSTREAM_REFRESH_CACHE_CAPACITY = 2_048; const STATUS_UPSTREAM_REFRESH_ENV = Object.freeze({ GCM_INTERACTIVE: "never", @@ -90,10 +91,34 @@ type TraceTailState = { remainder: string; }; -class StatusRemoteRefreshCacheKey extends Data.Class<{ - gitCommonDir: string; - remoteName: string; -}> {} +class StatusRemoteRefreshCacheKey { + readonly objectDir: string; + readonly remoteName: string; + readonly cwd: string; + + constructor(objectDir: string, remoteName: string, cwd: string) { + this.objectDir = objectDir; + this.remoteName = remoteName; + this.cwd = cwd; + } + + [Equal.symbol](that: unknown) { + return ( + that instanceof StatusRemoteRefreshCacheKey && + this.objectDir === that.objectDir && + this.remoteName === that.remoteName + ); + } + + [Hash.symbol]() { + return Hash.string(`${this.objectDir}\0${this.remoteName}`); + } +} + +interface StatusRefreshLock { + readonly semaphore: Semaphore.Semaphore; + readonly users: number; +} interface ExecuteGitOptions { stdin?: string | undefined; @@ -920,23 +945,26 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ); }); - const fetchRemoteForStatus = ( - gitCommonDir: string, - remoteName: string, - ): Effect.Effect => { - const fetchCwd = - path.basename(gitCommonDir) === ".git" ? path.dirname(gitCommonDir) : gitCommonDir; - return executeGit( + const fetchRemoteForStatus = (cwd: string, remoteName: string) => + executeGit( "GitVcsDriver.fetchRemoteForStatus", - fetchCwd, - ["--git-dir", gitCommonDir, "fetch", "--quiet", "--no-tags", remoteName], + cwd, + [ + "fetch", + "--quiet", + "--no-tags", + "--no-write-fetch-head", + "--no-auto-maintenance", + "--no-recurse-submodules", + "--", + remoteName, + ], { - allowNonZeroExit: true, env: STATUS_UPSTREAM_REFRESH_ENV, + fallbackErrorDetail: "Background Git fetch failed.", timeoutMs: Duration.toMillis(STATUS_UPSTREAM_REFRESH_TIMEOUT), }, ).pipe(Effect.asVoid); - }; const resolveGitCommonDir = Effect.fn("resolveGitCommonDir")(function* (cwd: string) { const gitCommonDir = yield* runGitStdout("GitVcsDriver.resolveGitCommonDir", cwd, [ @@ -946,10 +974,72 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* return path.isAbsolute(gitCommonDir) ? gitCommonDir : path.resolve(cwd, gitCommonDir); }); + const resolveCanonicalGitObjectDir = Effect.fn("resolveCanonicalGitObjectDir")(function* ( + cwd: string, + ) { + const gitCommonDir = yield* resolveGitCommonDir(cwd); + const objectDir = path.join(gitCommonDir, "objects"); + return yield* fileSystem.realPath(objectDir).pipe(Effect.orElseSucceed(() => objectDir)); + }); + + const statusRefreshLocks = yield* Ref.make>(new Map()); + const statusRefreshLocksGuard = yield* Semaphore.make(1); + + const withStatusRefreshLock = (objectDir: string, effect: Effect.Effect) => + Effect.acquireUseRelease( + statusRefreshLocksGuard.withPermits(1)( + Effect.gen(function* () { + const current = yield* Ref.get(statusRefreshLocks); + const existing = current.get(objectDir); + if (existing) { + yield* Ref.set( + statusRefreshLocks, + new Map(current).set(objectDir, { + semaphore: existing.semaphore, + users: existing.users + 1, + }), + ); + return existing.semaphore; + } + + const semaphore = yield* Semaphore.make(1); + yield* Ref.set( + statusRefreshLocks, + new Map(current).set(objectDir, { semaphore, users: 1 }), + ); + return semaphore; + }), + ), + (semaphore) => semaphore.withPermits(1)(effect), + (semaphore) => + statusRefreshLocksGuard.withPermits(1)( + Ref.update(statusRefreshLocks, (current) => { + const existing = current.get(objectDir); + if (!existing || existing.semaphore !== semaphore) { + return current; + } + + const next = new Map(current); + if (existing.users === 1) { + next.delete(objectDir); + } else { + next.set(objectDir, { + semaphore, + users: existing.users - 1, + }); + } + return next; + }), + ), + ); + const refreshStatusRemoteCacheEntry = Effect.fn("refreshStatusRemoteCacheEntry")(function* ( cacheKey: StatusRemoteRefreshCacheKey, ) { - yield* fetchRemoteForStatus(cacheKey.gitCommonDir, cacheKey.remoteName); + yield* withStatusRefreshLock( + cacheKey.objectDir, + fetchRemoteForStatus(cacheKey.cwd, cacheKey.remoteName), + ); return true as const; }); @@ -967,16 +1057,23 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* ) { const upstream = yield* resolveCurrentUpstream(cwd); if (!upstream) return; - const gitCommonDir = yield* resolveGitCommonDir(cwd); + const objectDir = yield* resolveCanonicalGitObjectDir(cwd); yield* Cache.get( statusRemoteRefreshCache, - new StatusRemoteRefreshCacheKey({ - gitCommonDir, - remoteName: upstream.remoteName, - }), + new StatusRemoteRefreshCacheKey(objectDir, upstream.remoteName, cwd), ); }); + const refreshStatusUpstream: GitVcsDriver.GitVcsDriver["Service"]["refreshStatusUpstream"] = + Effect.fn("refreshStatusUpstream")(function* (cwd) { + yield* refreshStatusUpstreamIfStale(cwd).pipe( + Effect.catchTags({ + GitCommandError: (error) => + isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), + }), + ); + }); + const resolveDefaultBranchName = ( cwd: string, remoteName: string, @@ -1474,26 +1571,14 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* const statusDetails: GitVcsDriver.GitVcsDriver["Service"]["statusDetails"] = Effect.fn( "statusDetails", )(function* (cwd) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( - Effect.catchTags({ - GitCommandError: (error) => - isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), - }), - Effect.ignoreCause({ log: true }), - ); + yield* refreshStatusUpstream(cwd).pipe(Effect.ignore); return yield* readStatusDetailsLocal(cwd); }); const statusDetailsRemote: GitVcsDriver.GitVcsDriver["Service"]["statusDetailsRemote"] = Effect.fn("statusDetailsRemote")(function* (cwd, options) { if (options?.refreshUpstream !== false) { - yield* refreshStatusUpstreamIfStale(cwd).pipe( - Effect.catchTags({ - GitCommandError: (error) => - isMissingGitCwdError(error) ? Effect.void : Effect.fail(error), - }), - Effect.ignoreCause({ log: true }), - ); + yield* refreshStatusUpstream(cwd).pipe(Effect.ignore); } return yield* readStatusDetailsRemote(cwd); }); @@ -2535,6 +2620,7 @@ export const makeGitVcsDriverCore = Effect.fn("makeGitVcsDriverCore")(function* statusDetails, statusDetailsLocal, statusDetailsRemote, + refreshStatusUpstream, prepareCommitContext, commit, pushCurrentBranch, diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts index 032e48e461..26a0e99b05 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.test.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.test.ts @@ -69,6 +69,7 @@ function makeTestLayer(state: { remoteStatusCalls: number; localInvalidationCalls: number; remoteInvalidationCalls: number; + remoteRefreshCalls?: number; remoteStatusRefreshUpstreamValues?: Array; }) { return VcsStatusBroadcaster.layer.pipe( @@ -86,6 +87,10 @@ function makeTestLayer(state: { state.remoteStatusRefreshUpstreamValues?.push(options?.refreshUpstream); return state.currentRemoteStatus; }), + refreshStatusUpstream: () => + Effect.sync(() => { + state.remoteRefreshCalls = (state.remoteRefreshCalls ?? 0) + 1; + }), invalidateLocalStatus: () => Effect.sync(() => { state.localInvalidationCalls += 1; @@ -545,6 +550,96 @@ describe("VcsStatusBroadcaster", () => { ); }); + it.effect("publishes stale remote status and backs off when upstream refresh fails", () => { + const state = { + refreshCalls: 0, + remoteStatusCalls: 0, + remoteInvalidationCalls: 0, + remoteStatusRefreshUpstreamValues: [] as Array, + }; + let firstRefreshDeferred: Deferred.Deferred | null = null; + const testLayer = VcsStatusBroadcaster.layer.pipe( + Layer.provideMerge(NodeServices.layer), + Layer.provide( + Layer.mock(GitWorkflowService.GitWorkflowService)({ + localStatus: () => Effect.succeed(baseLocalStatus), + refreshStatusUpstream: () => + Effect.suspend(() => { + state.refreshCalls += 1; + if (state.refreshCalls !== 1) { + return Effect.void; + } + return Effect.fail( + new GitManagerError({ + operation: "GitWorkflowService.refreshStatusUpstream", + cwd: "/repo", + detail: "background fetch failed", + }), + ).pipe( + Effect.ensuring( + firstRefreshDeferred + ? Deferred.succeed(firstRefreshDeferred, undefined).pipe(Effect.ignore) + : Effect.void, + ), + ); + }), + remoteStatus: (_input, options) => + Effect.sync(() => { + state.remoteStatusCalls += 1; + state.remoteStatusRefreshUpstreamValues.push(options?.refreshUpstream); + return baseRemoteStatus; + }), + invalidateRemoteStatus: () => + Effect.sync(() => { + state.remoteInvalidationCalls += 1; + }), + } satisfies Partial), + ), + ); + + return Effect.gen(function* () { + const broadcaster = yield* VcsStatusBroadcaster.VcsStatusBroadcaster; + const scope = yield* Scope.make(); + firstRefreshDeferred = yield* Deferred.make(); + const remoteUpdatedDeferred = yield* Deferred.make(); + yield* Stream.runForEach( + broadcaster.streamStatus( + { cwd: "/repo" }, + { automaticRemoteRefreshInterval: Effect.succeed(Duration.seconds(1)) }, + ), + (event) => + event._tag === "remoteUpdated" + ? Deferred.succeed(remoteUpdatedDeferred, event).pipe(Effect.ignore) + : Effect.void, + ).pipe(Effect.forkIn(scope)); + + yield* Deferred.await(firstRefreshDeferred); + const remoteUpdated = yield* Deferred.await(remoteUpdatedDeferred); + yield* Effect.yieldNow; + + assert.deepStrictEqual(remoteUpdated, { + _tag: "remoteUpdated", + remote: baseRemoteStatus, + } satisfies VcsStatusStreamEvent); + assert.equal(state.refreshCalls, 1); + assert.equal(state.remoteStatusCalls, 1); + assert.equal(state.remoteInvalidationCalls, 1); + assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false]); + + yield* TestClock.adjust(Duration.seconds(29)); + assert.equal(state.refreshCalls, 1); + + yield* TestClock.adjust(Duration.seconds(1)); + yield* Effect.yieldNow; + assert.equal(state.refreshCalls, 2); + assert.equal(state.remoteStatusCalls, 2); + assert.equal(state.remoteInvalidationCalls, 2); + assert.deepStrictEqual(state.remoteStatusRefreshUpstreamValues, [false, false]); + + yield* Scope.close(scope, Exit.void); + }).pipe(Effect.provide(Layer.merge(testLayer, TestClock.layer()))); + }); + it.effect("delays automatic refresh when a cached remote snapshot is available", () => { const state = { currentLocalStatus: baseLocalStatus, @@ -667,6 +762,7 @@ describe("VcsStatusBroadcaster", () => { : Effect.void, ), ), + refreshStatusUpstream: () => Effect.void, invalidateLocalStatus: () => Effect.sync(() => { state.localInvalidationCalls += 1; diff --git a/apps/server/src/vcs/VcsStatusBroadcaster.ts b/apps/server/src/vcs/VcsStatusBroadcaster.ts index c238154f58..b74c40caff 100644 --- a/apps/server/src/vcs/VcsStatusBroadcaster.ts +++ b/apps/server/src/vcs/VcsStatusBroadcaster.ts @@ -355,11 +355,19 @@ export const make = Effect.gen(function* () { cwd: string, options?: { readonly refreshUpstream?: boolean }, ) { + const refreshExit = + options?.refreshUpstream === false + ? Exit.void + : yield* workflow.refreshStatusUpstream(cwd).pipe(Effect.exit); if (options?.refreshUpstream !== false) { yield* workflow.invalidateRemoteStatus(cwd); } - const remote = yield* workflow.remoteStatus({ cwd }, options); - return yield* updateCachedRemoteStatus(cwd, remote, { publish: true }); + const remote = yield* workflow.remoteStatus({ cwd }, { refreshUpstream: false }); + const updated = yield* updateCachedRemoteStatus(cwd, remote, { publish: true }); + if (Exit.isFailure(refreshExit)) { + return yield* Effect.failCause(refreshExit.cause); + } + return updated; }); const refreshStatus: VcsStatusBroadcaster["Service"]["refreshStatus"] = Effect.fn(