mirror of
https://github.com/getpaseo/paseo.git
synced 2026-11-26 10:15:46 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b169d30fe4 | ||
|
|
3f142f6846 | ||
|
|
5ca7880864 |
@@ -5,25 +5,146 @@ import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import {
|
||||
buildBackgroundFetchEnvOverlay,
|
||||
diffWorkspaceGitRefs,
|
||||
diffWorkspaceGitRemoteRefs,
|
||||
fetchWorkspaceGitRemote,
|
||||
isGitFetchAuthError,
|
||||
parseWorkspaceGitRefs,
|
||||
} from "./workspace-git-fetch.js";
|
||||
import { runGitCommand, type RunGitCommand } from "../utils/run-git-command.js";
|
||||
|
||||
describe("buildBackgroundFetchEnvOverlay", () => {
|
||||
test("disables terminal and GUI prompts while guarding Linux headless D-Bus autolaunch", async () => {
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform: "linux",
|
||||
env: {},
|
||||
uid: 0,
|
||||
socketExists: () => false,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/dev/null",
|
||||
});
|
||||
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform: "linux",
|
||||
env: { DBUS_SESSION_BUS_ADDRESS: "autolaunch:" },
|
||||
uid: 1000,
|
||||
socketExists: () => false,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/dev/null",
|
||||
});
|
||||
});
|
||||
|
||||
test("preserves explicit DBUS_SESSION_BUS_ADDRESS and resolves existing runtime bus sockets", async () => {
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform: "linux",
|
||||
env: { DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus" },
|
||||
uid: 1000,
|
||||
socketExists: () => false,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
});
|
||||
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform: "linux",
|
||||
env: { XDG_RUNTIME_DIR: "/run/user/1000" },
|
||||
uid: 1000,
|
||||
socketExists: (socketPath) => socketPath === "/run/user/1000/bus",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
});
|
||||
|
||||
// Systemd service with unset XDG_RUNTIME_DIR and DBUS_SESSION_BUS_ADDRESS,
|
||||
// but an active logind runtime socket at /run/user/<uid>/bus.
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform: "linux",
|
||||
env: {},
|
||||
uid: 1000,
|
||||
socketExists: (socketPath) => socketPath === "/run/user/1000/bus",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
});
|
||||
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform: "linux",
|
||||
env: { DBUS_SESSION_BUS_ADDRESS: "autolaunch:" },
|
||||
uid: 1000,
|
||||
socketExists: (socketPath) => socketPath === "/run/user/1000/bus",
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
DBUS_SESSION_BUS_ADDRESS: "unix:path=/run/user/1000/bus",
|
||||
});
|
||||
});
|
||||
|
||||
test("omits DBUS_SESSION_BUS_ADDRESS on non-Linux platforms", async () => {
|
||||
for (const platform of ["darwin", "win32"] as const) {
|
||||
await expect(
|
||||
buildBackgroundFetchEnvOverlay({
|
||||
platform,
|
||||
env: {},
|
||||
uid: null,
|
||||
socketExists: () => false,
|
||||
}),
|
||||
).resolves.toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("workspace Git remote refs", () => {
|
||||
test("runs the complete fetch through the supplied Git runner", async () => {
|
||||
const commands: string[][] = [];
|
||||
let refRead = 0;
|
||||
const expectedOverlay = await buildBackgroundFetchEnvOverlay();
|
||||
const run: RunGitCommand = async (args, options) => {
|
||||
commands.push(args);
|
||||
if (args[0] === "fetch") {
|
||||
expect(options.envOverlay).toEqual({
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
});
|
||||
expect(options.envOverlay).toEqual(expectedOverlay);
|
||||
}
|
||||
const stdout =
|
||||
args[0] === "for-each-ref"
|
||||
@@ -247,3 +368,113 @@ test.skipIf(process.platform === "win32")(
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
test.skipIf(process.platform === "win32")(
|
||||
"background fetches pass DBUS_SESSION_BUS_ADDRESS=unix:path=/dev/null to credential helpers on headless Linux",
|
||||
async () => {
|
||||
for (const initialDbus of [undefined, "autolaunch:", "unix:path=/tmp/live-session-bus"]) {
|
||||
await withAuthenticatedRemote(async ({ cwd, run, root }) => {
|
||||
const captureFile = join(root, "helper-env.txt");
|
||||
const helperScript = join(root, "credential-helper.sh");
|
||||
await writeFile(
|
||||
helperScript,
|
||||
[
|
||||
"#!/bin/sh",
|
||||
`printf 'DBUS=%s\\nSSH_ASKPASS=%s\\nSSH_ASKPASS_REQUIRE=%s\\nGIT_TERMINAL_PROMPT=%s\\nGIT_ASKPASS=%s\\nGCM_INTERACTIVE=%s\\n' \\`,
|
||||
' "${DBUS_SESSION_BUS_ADDRESS-<unset>}" \\',
|
||||
' "${SSH_ASKPASS-<unset>}" \\',
|
||||
' "${SSH_ASKPASS_REQUIRE-<unset>}" \\',
|
||||
' "${GIT_TERMINAL_PROMPT-<unset>}" \\',
|
||||
' "${GIT_ASKPASS-<unset>}" \\',
|
||||
' "${GCM_INTERACTIVE-<unset>}" \\',
|
||||
` > '${captureFile.replaceAll("'", "'\\''")}'`,
|
||||
"exit 1",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
await chmod(helperScript, 0o755);
|
||||
await run(["config", "credential.helper", helperScript], { cwd });
|
||||
|
||||
const headlessEnv =
|
||||
initialDbus === undefined ? {} : { DBUS_SESSION_BUS_ADDRESS: initialDbus };
|
||||
const headlessRun: RunGitCommand = (args, options) =>
|
||||
run(args, {
|
||||
...options,
|
||||
env: {
|
||||
...options.env,
|
||||
...headlessEnv,
|
||||
},
|
||||
});
|
||||
|
||||
const result = await fetchWorkspaceGitRemote(cwd, { onRefSnapshot() {} }, headlessRun, {
|
||||
platform: "linux",
|
||||
env: headlessEnv,
|
||||
uid: 999_999,
|
||||
socketExists: () => false,
|
||||
});
|
||||
|
||||
expect(String(result.error)).toContain("terminal prompts disabled");
|
||||
const captured = await readFile(captureFile, "utf8");
|
||||
const expectedDbus =
|
||||
initialDbus === undefined || initialDbus === "autolaunch:"
|
||||
? "unix:path=/dev/null"
|
||||
: initialDbus;
|
||||
expect(captured).toBe(
|
||||
[
|
||||
`DBUS=${expectedDbus}`,
|
||||
"SSH_ASKPASS=",
|
||||
"SSH_ASKPASS_REQUIRE=never",
|
||||
"GIT_TERMINAL_PROMPT=0",
|
||||
"GIT_ASKPASS=",
|
||||
"GCM_INTERACTIVE=0",
|
||||
"",
|
||||
].join("\n"),
|
||||
);
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
describe("isGitFetchAuthError", () => {
|
||||
test.each([
|
||||
new Error("fatal: could not read Username for 'https://github.com': terminal prompts disabled"),
|
||||
new Error(
|
||||
"fatal: could not read Password for 'https://example.com': terminal prompts disabled",
|
||||
),
|
||||
new Error("fatal: Authentication failed for 'https://github.com/org/repo.git/'"),
|
||||
new Error("remote: Invalid username or token. Password authentication is not supported"),
|
||||
new Error(
|
||||
"fatal: unable to access 'https://example.com/repo.git/': The requested URL returned error: 401",
|
||||
),
|
||||
new Error(
|
||||
"fatal: unable to access 'https://example.com/repo.git/': The requested URL returned error: 403",
|
||||
),
|
||||
new Error("Logon failed, use ctrl+c to cancel basic credential prompt."),
|
||||
new Error(
|
||||
"git@github.com: Permission denied (publickey).\nfatal: Could not read from remote repository.",
|
||||
),
|
||||
new Error("Host key verification failed.\nfatal: Could not read from remote repository."),
|
||||
new Error("Received disconnect from 1.2.3.4 port 22:2: Too many authentication failures"),
|
||||
])("classifies auth/credential failure as auth error: %s", (error) => {
|
||||
expect(isGitFetchAuthError(error)).toBe(true);
|
||||
});
|
||||
|
||||
test.each([
|
||||
new Error("Git command timed out after 120000ms: git fetch origin --prune"),
|
||||
new Error(
|
||||
"ssh: Could not resolve hostname github.com: Temporary failure in name resolution\nfatal: Could not read from remote repository.",
|
||||
),
|
||||
new Error(
|
||||
"fatal: unable to access 'https://github.com/org/repo.git/': Failed to connect to github.com port 443: Connection timed out",
|
||||
),
|
||||
new Error(
|
||||
"fatal: unable to access 'https://github.com/org/repo.git/': The requested URL returned error: 503",
|
||||
),
|
||||
new Error(
|
||||
"fatal: unable to access 'https://github.com/org/repo.git/': The requested URL returned error: 429",
|
||||
),
|
||||
new Error("error: RPC failed; curl 56 Recv failure: Connection reset by peer"),
|
||||
])("classifies network/timeout/server failure as transient: %s", (error) => {
|
||||
expect(isGitFetchAuthError(error)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -1,5 +1,113 @@
|
||||
import { access } from "node:fs/promises";
|
||||
import { join } from "node:path";
|
||||
import type { ProcessEnvRecord } from "./paseo-env.js";
|
||||
import { runGitCommand, type RunGitCommand } from "../utils/run-git-command.js";
|
||||
|
||||
const HEADLESS_DBUS_SESSION_BUS_ADDRESS = "unix:path=/dev/null";
|
||||
const GIT_FETCH_AUTH_ERROR_PATTERN =
|
||||
/\b(terminal prompts disabled|could not read (?:username|password)|authentication failed|invalid username or (?:password|token)|invalid credentials|bad credentials|logon failed|access denied|permission denied|host key verification failed|too many authentication failures|agent refused operation|returned error: (?:401|403)|http (?:401|403)|401 unauthorized|403 forbidden)\b/i;
|
||||
|
||||
function extractGitFetchErrorText(error: unknown): string {
|
||||
if (typeof error === "string") {
|
||||
return error;
|
||||
}
|
||||
if (error instanceof Error) {
|
||||
const stderr =
|
||||
"stderr" in error && typeof (error as { stderr?: unknown }).stderr === "string"
|
||||
? (error as { stderr: string }).stderr
|
||||
: "";
|
||||
return stderr ? `${error.message}\n${stderr}` : error.message;
|
||||
}
|
||||
if (error && typeof error === "object" && "stderr" in error && typeof error.stderr === "string") {
|
||||
return error.stderr;
|
||||
}
|
||||
return String(error);
|
||||
}
|
||||
|
||||
/**
|
||||
* Classifies git fetch errors that will keep failing without user intervention
|
||||
* (missing credentials, disabled prompts, bad tokens, SSH key/host rejections).
|
||||
*/
|
||||
export function isGitFetchAuthError(error: unknown): boolean {
|
||||
if (error === null || error === undefined) {
|
||||
return false;
|
||||
}
|
||||
return GIT_FETCH_AUTH_ERROR_PATTERN.test(extractGitFetchErrorText(error));
|
||||
}
|
||||
|
||||
export interface BackgroundFetchEnvOptions {
|
||||
platform?: NodeJS.Platform;
|
||||
env?: ProcessEnvRecord;
|
||||
uid?: number | null;
|
||||
socketExists?: (socketPath: string) => boolean | Promise<boolean>;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds the non-interactive subprocess environment overlay for background `git fetch`.
|
||||
* Keeps `credential.helper` active so stored credentials work, while blocking terminal,
|
||||
* SSH, and GUI prompts as well as Linux D-Bus autolaunch when no session bus exists.
|
||||
*/
|
||||
export async function buildBackgroundFetchEnvOverlay(
|
||||
options: BackgroundFetchEnvOptions = {},
|
||||
): Promise<ProcessEnvRecord> {
|
||||
const platform = options.platform ?? process.platform;
|
||||
const env = options.env ?? process.env;
|
||||
const overlay: ProcessEnvRecord = {
|
||||
GIT_TERMINAL_PROMPT: "0",
|
||||
GIT_ASKPASS: "",
|
||||
GCM_INTERACTIVE: "0",
|
||||
SSH_ASKPASS: "",
|
||||
SSH_ASKPASS_REQUIRE: "never",
|
||||
};
|
||||
if (platform !== "linux") {
|
||||
return overlay;
|
||||
}
|
||||
|
||||
const dbusAddress = env.DBUS_SESSION_BUS_ADDRESS?.trim() ?? "";
|
||||
const needsDbusFallback = dbusAddress === "" || dbusAddress.startsWith("autolaunch:");
|
||||
if (!needsDbusFallback) {
|
||||
return overlay;
|
||||
}
|
||||
|
||||
const uid = options.uid === undefined ? (process.getuid?.() ?? null) : options.uid;
|
||||
const socketExists = options.socketExists ?? pathExists;
|
||||
const runtimeBusSocket = await findLinuxSessionBusSocket(env, uid, socketExists);
|
||||
overlay.DBUS_SESSION_BUS_ADDRESS = runtimeBusSocket
|
||||
? `unix:path=${runtimeBusSocket}`
|
||||
: HEADLESS_DBUS_SESSION_BUS_ADDRESS;
|
||||
return overlay;
|
||||
}
|
||||
|
||||
async function pathExists(socketPath: string): Promise<boolean> {
|
||||
try {
|
||||
await access(socketPath);
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async function findLinuxSessionBusSocket(
|
||||
env: ProcessEnvRecord,
|
||||
uid: number | null,
|
||||
socketExists: (socketPath: string) => boolean | Promise<boolean>,
|
||||
): Promise<string | null> {
|
||||
const candidates = new Set<string>();
|
||||
const xdgRuntimeDir = env.XDG_RUNTIME_DIR?.trim();
|
||||
if (xdgRuntimeDir) {
|
||||
candidates.add(join(xdgRuntimeDir, "bus"));
|
||||
}
|
||||
if (uid !== null && uid >= 0) {
|
||||
candidates.add(`/run/user/${uid}/bus`);
|
||||
}
|
||||
for (const candidate of candidates) {
|
||||
if (await socketExists(candidate)) {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export interface WorkspaceGitFetchResult {
|
||||
changes: WorkspaceGitRemoteRefChange[] | null;
|
||||
nonRemoteRefsChanged?: boolean;
|
||||
@@ -20,6 +128,7 @@ export async function fetchWorkspaceGitRemote(
|
||||
cwd: string,
|
||||
observer: WorkspaceGitFetchObserver,
|
||||
run: RunGitCommand = runGitCommand,
|
||||
envOptions?: BackgroundFetchEnvOptions,
|
||||
): Promise<WorkspaceGitFetchResult> {
|
||||
let before: Map<string, string> | null = null;
|
||||
let after: Map<string, string> | null = null;
|
||||
@@ -34,8 +143,8 @@ export async function fetchWorkspaceGitRemote(
|
||||
await run(["fetch", "origin", "--prune"], {
|
||||
cwd,
|
||||
// Terminal prompting and graphical credential prompting have separate controls.
|
||||
// Keep cached credentials available, but never start a login from a passive fetch.
|
||||
envOverlay: { GIT_TERMINAL_PROMPT: "0", GIT_ASKPASS: "", GCM_INTERACTIVE: "0" },
|
||||
// Keep cached credentials available, but never start a login or D-Bus autolaunch from a passive fetch.
|
||||
envOverlay: await buildBackgroundFetchEnvOverlay(envOptions),
|
||||
timeout: 120_000,
|
||||
});
|
||||
} catch (caught) {
|
||||
|
||||
@@ -15,11 +15,13 @@ import type {
|
||||
} from "../utils/checkout-git.js";
|
||||
import {
|
||||
BACKGROUND_GIT_FETCH_INTERVAL_MS,
|
||||
BACKGROUND_GIT_FETCH_MAX_BACKOFF_MS,
|
||||
WORKSPACE_GIT_OBSERVATION_REENSURE_INTERVAL_MS,
|
||||
WORKSPACE_GIT_OBSERVATION_SETUP_CONCURRENCY,
|
||||
WORKSPACE_GIT_REFRESH_CONCURRENCY,
|
||||
WORKSPACE_GIT_WATCHER_SUBSCRIBE_TIMEOUT_MS,
|
||||
WorkspaceGitServiceImpl,
|
||||
computeBackgroundGitFetchDelayMs,
|
||||
type WorkspaceGitRuntimeSnapshot,
|
||||
workspaceFolderExists,
|
||||
} from "./workspace-git-service.js";
|
||||
@@ -261,6 +263,7 @@ function createGitHubServiceStub(): ForgeService {
|
||||
}
|
||||
|
||||
interface CreateServiceTestOptions {
|
||||
logger?: ReturnType<typeof createLogger>;
|
||||
subscribe?: ReturnType<typeof vi.fn>;
|
||||
getCheckoutStatus?: ReturnType<typeof vi.fn>;
|
||||
getCheckoutSnapshotFacts?: (cwd: string) => Promise<CheckoutSnapshotFacts>;
|
||||
@@ -334,7 +337,7 @@ function createService(options?: CreateServiceTestOptions) {
|
||||
};
|
||||
});
|
||||
return new WorkspaceGitServiceImpl({
|
||||
logger: createLogger() as unknown as pino.Logger,
|
||||
logger: (options?.logger ?? createLogger()) as unknown as pino.Logger,
|
||||
paseoHome: "/tmp/paseo-test",
|
||||
deps,
|
||||
});
|
||||
@@ -2759,3 +2762,382 @@ describe("WorkspaceGitServiceImpl with workspace folders that no longer exist",
|
||||
expect(await workspaceFolderExists(join(file, "nested"))).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("WorkspaceGitServiceImpl background fetch backoff", () => {
|
||||
const temporaryFolders: string[] = [];
|
||||
|
||||
async function createTemporaryFolder(): Promise<string> {
|
||||
const folder = await mkdtemp(join(os.tmpdir(), "paseo-git-fetch-backoff-"));
|
||||
temporaryFolders.push(folder);
|
||||
return folder;
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers();
|
||||
});
|
||||
|
||||
afterEach(async () => {
|
||||
vi.useRealTimers();
|
||||
await Promise.all(
|
||||
temporaryFolders.splice(0).map((folder) => rm(folder, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
test("pauses periodic background fetches on auth failure and resumes on forced refresh, state change, or remoteUrl change", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const logger = createLogger();
|
||||
const git = createFolderBackedGit();
|
||||
let currentRemoteUrl = "https://github.com/acme/repo.git";
|
||||
git.deps.getCheckoutSnapshotFacts.mockImplementation(async (cwd: string) => ({
|
||||
...createCheckoutSnapshotFacts(cwd),
|
||||
remoteUrl: currentRemoteUrl,
|
||||
}));
|
||||
git.deps.getCheckoutStatus.mockImplementation(async (cwd: string) =>
|
||||
createCheckoutStatus(cwd, { remoteUrl: currentRemoteUrl }),
|
||||
);
|
||||
git.deps.runGitFetch.mockResolvedValue({
|
||||
changes: [],
|
||||
error: new Error(
|
||||
"fatal: could not read Username for 'https://github.com': terminal prompts disabled",
|
||||
),
|
||||
});
|
||||
|
||||
const service = createService({ ...git.deps, logger });
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await waitForObservationToSettle(service, 1);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(1);
|
||||
});
|
||||
|
||||
// Advancing through many intervals must not repeat failing auth fetches.
|
||||
await vi.advanceTimersByTimeAsync(10 * BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
await settle(() => {
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
expect(git.fetchesIn(workspace)).toBe(1);
|
||||
expect(
|
||||
logger.warn.mock.calls.filter(([, message]) =>
|
||||
String(message).includes("paused due to authentication failure"),
|
||||
),
|
||||
).toHaveLength(1);
|
||||
|
||||
// 1. Forced getSnapshot resumes fetching.
|
||||
await service.getSnapshot(workspace, { force: true, reason: "user-refresh" });
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(5 * BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
|
||||
// 2. onWorkspaceStateMayHaveChanged resumes fetching.
|
||||
service.onWorkspaceStateMayHaveChanged(workspace);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(3);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(5 * BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
expect(git.fetchesIn(workspace)).toBe(3);
|
||||
|
||||
// 3. Changing remoteUrl and refreshing resumes fetching and restores periodic cadence on success.
|
||||
git.deps.runGitFetch.mockResolvedValue({ changes: [], error: null });
|
||||
currentRemoteUrl = "git@github.com:acme/repo.git";
|
||||
await service.refresh(workspace);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(4);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
|
||||
await vi.advanceTimersByTimeAsync(BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(5);
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("pauses when runGitFetch rejects with an auth error and honors resume signals received in flight", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
const firstFetchStarted = createDeferred<void>();
|
||||
const releaseFirstFetch = createDeferred<void>();
|
||||
let attempt = 0;
|
||||
git.deps.runGitFetch.mockImplementation(async () => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) {
|
||||
firstFetchStarted.resolve();
|
||||
await releaseFirstFetch.promise;
|
||||
throw new Error("git@github.com: Permission denied (publickey).");
|
||||
}
|
||||
return { changes: [], error: null };
|
||||
});
|
||||
|
||||
const service = createService(git.deps);
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await firstFetchStarted.promise;
|
||||
|
||||
// A resume signal during the in-flight failing attempt must schedule a follow-up fetch
|
||||
// rather than letting the stale error leave background fetch paused.
|
||||
service.onWorkspaceStateMayHaveChanged(workspace);
|
||||
releaseFirstFetch.resolve();
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
|
||||
// After the retry succeeds, normal periodic cadence is active.
|
||||
await vi.advanceTimersByTimeAsync(BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(3);
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("backs off transient background fetch failures exponentially and resets on success", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
git.deps.runGitFetch.mockResolvedValue({
|
||||
changes: [],
|
||||
error: new Error(
|
||||
"fatal: unable to access 'https://github.com/acme/repo.git/': The requested URL returned error: 503",
|
||||
),
|
||||
});
|
||||
|
||||
const service = createService(git.deps);
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await waitForObservationToSettle(service, 1);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(1);
|
||||
});
|
||||
|
||||
const expectedDelays = [
|
||||
computeBackgroundGitFetchDelayMs(1),
|
||||
computeBackgroundGitFetchDelayMs(2),
|
||||
computeBackgroundGitFetchDelayMs(3),
|
||||
computeBackgroundGitFetchDelayMs(4),
|
||||
computeBackgroundGitFetchDelayMs(5),
|
||||
computeBackgroundGitFetchDelayMs(6),
|
||||
];
|
||||
expect(expectedDelays).toEqual([
|
||||
360_000,
|
||||
720_000,
|
||||
1_440_000,
|
||||
2_880_000,
|
||||
BACKGROUND_GIT_FETCH_MAX_BACKOFF_MS,
|
||||
BACKGROUND_GIT_FETCH_MAX_BACKOFF_MS,
|
||||
]);
|
||||
|
||||
for (let index = 0; index < expectedDelays.length; index += 1) {
|
||||
const delayMs = expectedDelays[index]!;
|
||||
const countBefore = git.fetchesIn(workspace);
|
||||
await vi.advanceTimersByTimeAsync(delayMs - 1);
|
||||
expect(git.fetchesIn(workspace)).toBe(countBefore);
|
||||
|
||||
if (index === expectedDelays.length - 1) {
|
||||
git.deps.runGitFetch.mockResolvedValue({ changes: [], error: null });
|
||||
}
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(countBefore + 1);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
}
|
||||
|
||||
// Success resets the next fetch delay back to BACKGROUND_GIT_FETCH_INTERVAL_MS.
|
||||
const countAfterSuccess = git.fetchesIn(workspace);
|
||||
await vi.advanceTimersByTimeAsync(BACKGROUND_GIT_FETCH_INTERVAL_MS - 1);
|
||||
expect(git.fetchesIn(workspace)).toBe(countAfterSuccess);
|
||||
await vi.advanceTimersByTimeAsync(1);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(countAfterSuccess + 1);
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("does not trigger a redundant follow-up fetch when force refresh or state change overlaps a healthy in-flight fetch", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
const firstFetchStarted = createDeferred<void>();
|
||||
const releaseFirstFetch = createDeferred<void>();
|
||||
let attempt = 0;
|
||||
git.deps.runGitFetch.mockImplementation(async () => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) {
|
||||
firstFetchStarted.resolve();
|
||||
await releaseFirstFetch.promise;
|
||||
}
|
||||
return { changes: [], error: null };
|
||||
});
|
||||
|
||||
const service = createService(git.deps);
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await firstFetchStarted.promise;
|
||||
|
||||
await service.getSnapshot(workspace, { force: true, reason: "open-project" });
|
||||
service.onWorkspaceStateMayHaveChanged(workspace);
|
||||
releaseFirstFetch.resolve();
|
||||
|
||||
await settle(() => {
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(1_000);
|
||||
await waitForRefreshesToSettle(service);
|
||||
expect(git.fetchesIn(workspace)).toBe(1);
|
||||
|
||||
// Normal 3-minute schedule remains active.
|
||||
await vi.advanceTimersByTimeAsync(BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("triggers a follow-up fetch when remoteUrl changes during a healthy in-flight fetch", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
let currentRemoteUrl = "https://github.com/acme/repo.git";
|
||||
git.deps.getCheckoutSnapshotFacts.mockImplementation(async (cwd: string) => ({
|
||||
...createCheckoutSnapshotFacts(cwd),
|
||||
remoteUrl: currentRemoteUrl,
|
||||
}));
|
||||
git.deps.getCheckoutStatus.mockImplementation(async (cwd: string) =>
|
||||
createCheckoutStatus(cwd, { remoteUrl: currentRemoteUrl }),
|
||||
);
|
||||
const firstFetchStarted = createDeferred<void>();
|
||||
const releaseFirstFetch = createDeferred<void>();
|
||||
let attempt = 0;
|
||||
git.deps.runGitFetch.mockImplementation(async () => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) {
|
||||
firstFetchStarted.resolve();
|
||||
await releaseFirstFetch.promise;
|
||||
}
|
||||
return { changes: [], error: null };
|
||||
});
|
||||
|
||||
const service = createService(git.deps);
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await firstFetchStarted.promise;
|
||||
|
||||
currentRemoteUrl = "git@github.com:acme/repo.git";
|
||||
await service.getSnapshot(workspace, { force: true, reason: "remote-changed" });
|
||||
releaseFirstFetch.resolve();
|
||||
|
||||
await settle(() => {
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("preserves in-flight state when origin is removed mid-fetch and avoids concurrent fetch if re-added", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const git = createFolderBackedGit();
|
||||
let currentRemoteUrl: string | null = "https://github.com/acme/repo.git";
|
||||
git.deps.getCheckoutSnapshotFacts.mockImplementation(async (cwd: string) => ({
|
||||
...createCheckoutSnapshotFacts(cwd),
|
||||
remoteUrl: currentRemoteUrl,
|
||||
}));
|
||||
git.deps.getCheckoutStatus.mockImplementation(async (cwd: string) =>
|
||||
createCheckoutStatus(cwd, { remoteUrl: currentRemoteUrl }),
|
||||
);
|
||||
const firstFetchStarted = createDeferred<void>();
|
||||
const releaseFirstFetch = createDeferred<void>();
|
||||
const secondFetchStarted = createDeferred<void>();
|
||||
const releaseSecondFetch = createDeferred<void>();
|
||||
let attempt = 0;
|
||||
git.deps.runGitFetch.mockImplementation(async () => {
|
||||
attempt += 1;
|
||||
if (attempt === 1) {
|
||||
firstFetchStarted.resolve();
|
||||
await releaseFirstFetch.promise;
|
||||
} else if (attempt === 2) {
|
||||
secondFetchStarted.resolve();
|
||||
await releaseSecondFetch.promise;
|
||||
}
|
||||
return { changes: [], error: null };
|
||||
});
|
||||
|
||||
const service = createService(git.deps);
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await firstFetchStarted.promise;
|
||||
await waitForRefreshesToSettle(service);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(1);
|
||||
|
||||
// Removing origin while fetch 1 is in flight must keep fetchInFlightCount at 1.
|
||||
currentRemoteUrl = null;
|
||||
await service.refresh(workspace);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(1);
|
||||
|
||||
// Re-adding origin while fetch 1 is still in flight must NOT launch a concurrent fetch 2.
|
||||
currentRemoteUrl = "https://github.com/acme/other.git";
|
||||
await service.getSnapshot(workspace, { force: true, reason: "re-added-origin" });
|
||||
expect(git.fetchesIn(workspace)).toBe(1);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(1);
|
||||
|
||||
// Releasing fetch 1 starts fetch 2 sequentially.
|
||||
releaseFirstFetch.resolve();
|
||||
await secondFetchStarted.promise;
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(1);
|
||||
|
||||
// Removing origin while fetch 2 is in flight and letting it settle leaves fetchInFlightCount at 0
|
||||
// with no follow-up fetch scheduled.
|
||||
currentRemoteUrl = null;
|
||||
await service.getSnapshot(workspace, { force: true, reason: "removed-origin-again" });
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(1);
|
||||
releaseSecondFetch.resolve();
|
||||
await settle(() => {
|
||||
expect(service.getMetrics().fetchInFlightCount).toBe(0);
|
||||
});
|
||||
await vi.advanceTimersByTimeAsync(2 * BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
expect(git.fetchesIn(workspace)).toBe(2);
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
|
||||
test("ensureRepoTarget preserves fetchState resolved during async observation setup", async () => {
|
||||
const workspace = await createTemporaryFolder();
|
||||
const gitDir = join(workspace, ".git");
|
||||
await mkdir(gitDir);
|
||||
const metadataWatchRelease = createDeferred<void>();
|
||||
let currentRemoteUrl: string | null = "https://github.com/acme/repo.git";
|
||||
const git = createFolderBackedGit({
|
||||
heldWatch: { directory: gitDir, release: metadataWatchRelease.promise },
|
||||
});
|
||||
git.deps.getCheckoutSnapshotFacts.mockImplementation(async (cwd: string) => ({
|
||||
...createCheckoutSnapshotFacts(cwd),
|
||||
remoteUrl: currentRemoteUrl,
|
||||
}));
|
||||
git.deps.getCheckoutStatus.mockImplementation(async (cwd: string) =>
|
||||
createCheckoutStatus(cwd, { remoteUrl: currentRemoteUrl }),
|
||||
);
|
||||
|
||||
const service = createService(git.deps);
|
||||
const subscription = service.registerWorkspace({ cwd: workspace }, vi.fn());
|
||||
await settle(() => {
|
||||
expect(git.watchAttemptsFor(gitDir)).toBe(1);
|
||||
});
|
||||
|
||||
// While ensureRepoTarget is awaiting startRepoMetadataObservation, remove origin and refresh.
|
||||
currentRemoteUrl = null;
|
||||
await service.getSnapshot(workspace, { force: true, reason: "origin-removed-during-setup" });
|
||||
|
||||
metadataWatchRelease.resolve();
|
||||
await waitForObservationToSettle(service, 1);
|
||||
expect(git.fetchesIn(workspace)).toBe(0);
|
||||
|
||||
subscription.unsubscribe();
|
||||
await service.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -64,6 +64,7 @@ import { READ_ONLY_GIT_ENV } from "./checkout-git-utils.js";
|
||||
import { classifyGitMetadataPath, getPrunedGitMetadataPaths } from "./git-metadata-event-rules.js";
|
||||
import {
|
||||
fetchWorkspaceGitRemote,
|
||||
isGitFetchAuthError,
|
||||
type WorkspaceGitFetchResult,
|
||||
type WorkspaceGitFetchObserver,
|
||||
type WorkspaceGitRemoteRefChange,
|
||||
@@ -93,6 +94,7 @@ const WORKSPACE_GIT_WATCH_DEBOUNCE_MS = 1_000;
|
||||
// and watchers instead of re-reading every checkout.
|
||||
const WORKSPACE_GIT_RELEASE_GRACE_MS = 90_000;
|
||||
export const BACKGROUND_GIT_FETCH_INTERVAL_MS = 180_000;
|
||||
export const BACKGROUND_GIT_FETCH_MAX_BACKOFF_MS = 3_600_000;
|
||||
const FETCH_METADATA_ECHO_TTL_MS = 5_000;
|
||||
export const WORKSPACE_GIT_OBSERVATION_REENSURE_INTERVAL_MS = 60_000;
|
||||
const FORGE_PR_STATUS_POLL_FAST_INTERVAL_MS = 20_000;
|
||||
@@ -146,6 +148,16 @@ const WORKSPACE_GIT_INTERNAL_MIN_GAP_MS = 2_000;
|
||||
// Small values (booleans, short strings, small arrays); generous cap.
|
||||
const WORKSPACE_GIT_AUXILIARY_CACHE_MAX = 256;
|
||||
|
||||
export function computeBackgroundGitFetchDelayMs(consecutiveErrors: number): number {
|
||||
if (consecutiveErrors <= 0) {
|
||||
return BACKGROUND_GIT_FETCH_INTERVAL_MS;
|
||||
}
|
||||
return Math.min(
|
||||
BACKGROUND_GIT_FETCH_INTERVAL_MS * 2 ** Math.min(consecutiveErrors, 5),
|
||||
BACKGROUND_GIT_FETCH_MAX_BACKOFF_MS,
|
||||
);
|
||||
}
|
||||
|
||||
function mergeSets<T>(
|
||||
left: ReadonlySet<T>,
|
||||
right: ReadonlySet<T>,
|
||||
@@ -516,6 +528,22 @@ interface WorkspaceGitTarget {
|
||||
closed: boolean;
|
||||
}
|
||||
|
||||
type RepoFetchState =
|
||||
| { kind: "idle"; remoteUrl: string | null | undefined }
|
||||
| {
|
||||
kind: "scheduled";
|
||||
remoteUrl: string | undefined;
|
||||
timer: NodeJS.Timeout;
|
||||
consecutiveErrors: number;
|
||||
}
|
||||
| {
|
||||
kind: "in-flight";
|
||||
remoteUrl: string | null | undefined;
|
||||
consecutiveErrors: number;
|
||||
pendingRetry: "none" | "on-error" | "always";
|
||||
}
|
||||
| { kind: "paused-auth"; remoteUrl: string | undefined };
|
||||
|
||||
interface RepoGitTarget {
|
||||
paths: GitObservationPaths;
|
||||
repoGitRoot: string;
|
||||
@@ -526,8 +554,7 @@ interface RepoGitTarget {
|
||||
fallbackPollTimer: NodeJS.Timeout | null;
|
||||
fallbackPollQuietTickCount: number;
|
||||
recovery: WatchRecoveryState;
|
||||
intervalId: NodeJS.Timeout | null;
|
||||
fetchInFlight: boolean;
|
||||
fetchState: RepoFetchState;
|
||||
bufferedFetchMetadataEvents: FileChange[];
|
||||
recentFetchRemoteRefChanges: Map<
|
||||
string,
|
||||
@@ -821,7 +848,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
for (const target of this.repoTargets.values()) {
|
||||
repositoryWorkspaceLinkCount += target.workspaceKeys.size;
|
||||
if (target.fetchInFlight) {
|
||||
if (target.fetchState.kind === "in-flight") {
|
||||
fetchInFlightCount += 1;
|
||||
}
|
||||
}
|
||||
@@ -867,6 +894,9 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
} else if (target.folderMissing) {
|
||||
await this.resumeWorkspaceIfFolderRestored(target);
|
||||
}
|
||||
if (request.force) {
|
||||
this.resumeRepoFetchIfPausedOrErrored(target);
|
||||
}
|
||||
if (!request.force && target.latestSnapshot) {
|
||||
return target.latestSnapshot;
|
||||
}
|
||||
@@ -1163,6 +1193,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
void this.resumeWorkspaceIfFolderRestored(target);
|
||||
return;
|
||||
}
|
||||
this.resumeRepoFetchIfPausedOrErrored(target);
|
||||
this.scheduleWorkspaceRefresh(target, {
|
||||
origin: "demand",
|
||||
force: true,
|
||||
@@ -2548,8 +2579,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
establishedAt: null,
|
||||
setupKey: `repository-metadata:${paths.identity}`,
|
||||
},
|
||||
intervalId: null,
|
||||
fetchInFlight: false,
|
||||
fetchState: { kind: "idle", remoteUrl: undefined },
|
||||
bufferedFetchMetadataEvents: [],
|
||||
recentFetchRemoteRefChanges: new Map(),
|
||||
knownRemoteRefs: null,
|
||||
@@ -2577,21 +2607,42 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
return;
|
||||
}
|
||||
repoTarget.cwd = fetchWorkspaceTarget.cwd;
|
||||
await this.initializeRepoTargetFetch(repoTarget, fetchWorkspaceTarget);
|
||||
}
|
||||
|
||||
private async initializeRepoTargetFetch(
|
||||
repoTarget: RepoGitTarget,
|
||||
fetchWorkspaceTarget: WorkspaceGitTarget,
|
||||
): Promise<void> {
|
||||
const facts = fetchWorkspaceTarget.latestFacts;
|
||||
const hasOrigin =
|
||||
facts?.isGit === true
|
||||
? facts.remoteUrl !== null
|
||||
: await this.deps.hasOriginRemote(fetchWorkspaceTarget.cwd);
|
||||
if (repoTarget.closed || this.repoTargets.get(repoGitRoot) !== repoTarget) {
|
||||
if (repoTarget.closed || this.repoTargets.get(repoTarget.repoGitRoot) !== repoTarget) {
|
||||
return;
|
||||
}
|
||||
if (!hasOrigin) {
|
||||
if (repoTarget.fetchState.kind !== "idle") {
|
||||
return;
|
||||
}
|
||||
repoTarget.intervalId = setInterval(() => {
|
||||
if (repoTarget.fetchState.remoteUrl !== undefined) {
|
||||
if (repoTarget.fetchState.remoteUrl !== null) {
|
||||
void this.runRepoFetch(repoTarget);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let initialRemoteUrl: string | null | undefined;
|
||||
if (facts?.isGit === true) {
|
||||
initialRemoteUrl = facts.remoteUrl;
|
||||
} else if (hasOrigin) {
|
||||
initialRemoteUrl = fetchWorkspaceTarget.latestGit?.remoteUrl ?? undefined;
|
||||
} else {
|
||||
initialRemoteUrl = null;
|
||||
}
|
||||
repoTarget.fetchState = { kind: "idle", remoteUrl: initialRemoteUrl };
|
||||
if (hasOrigin) {
|
||||
void this.runRepoFetch(repoTarget);
|
||||
}, BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
void this.runRepoFetch(repoTarget);
|
||||
}
|
||||
}
|
||||
|
||||
private async startRepoMetadataObservation(
|
||||
@@ -2657,15 +2708,16 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
ignore.every((ignoredPath) => !isPathInsideRoot(ignoredPath, event.path)),
|
||||
);
|
||||
if (relevantEvents.length > 0) {
|
||||
const immediateEvents = target.fetchInFlight
|
||||
? relevantEvents.filter((event) => {
|
||||
if (this.isFetchRemoteMetadataEvent(target, event)) {
|
||||
target.bufferedFetchMetadataEvents.push(event);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
: relevantEvents;
|
||||
const immediateEvents =
|
||||
target.fetchState.kind === "in-flight"
|
||||
? relevantEvents.filter((event) => {
|
||||
if (this.isFetchRemoteMetadataEvent(target, event)) {
|
||||
target.bufferedFetchMetadataEvents.push(event);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
})
|
||||
: relevantEvents;
|
||||
if (immediateEvents.length > 0) {
|
||||
this.refreshWorkingTreeIgnoresFromRepoMetadataEvents(target, immediateEvents);
|
||||
const routedRefreshes = this.routeRepoMetadataEvents(target, immediateEvents);
|
||||
@@ -3800,6 +3852,8 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
target.lastShellOutAtMs = now.getTime();
|
||||
|
||||
const cwd = target.cwd;
|
||||
const hadPreviousGit = target.latestGit !== null;
|
||||
const previousRemoteUrl = target.latestGit?.isGit ? target.latestGit.remoteUrl : null;
|
||||
const previousForgePrStatusPollKey = this.getForgePrStatusPollKey(target);
|
||||
const previousBaseRef = target.latestFacts?.isGit ? target.latestFacts.resolvedBaseRef : null;
|
||||
const baseContext: CheckoutContext = {
|
||||
@@ -3822,6 +3876,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
target.latestForge = buildForgeUnavailableSnapshot();
|
||||
target.latestForgeWeb = null;
|
||||
target.latestForgeLoadedAtMs = target.latestGitLoadedAtMs;
|
||||
this.syncRepoFetchRemoteUrl(target, hadPreviousGit, previousRemoteUrl, null);
|
||||
return facts;
|
||||
}
|
||||
|
||||
@@ -3861,6 +3916,12 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
};
|
||||
const loadedAtMs = this.deps.now().getTime();
|
||||
target.latestGitLoadedAtMs = loadedAtMs;
|
||||
this.syncRepoFetchRemoteUrl(
|
||||
target,
|
||||
hadPreviousGit,
|
||||
previousRemoteUrl,
|
||||
checkoutStatus.remoteUrl,
|
||||
);
|
||||
|
||||
if (previousForgePrStatusPollKey !== this.getForgePrStatusPollKey(target)) {
|
||||
target.latestForge = buildForgeUnavailableSnapshot();
|
||||
@@ -4078,18 +4139,186 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
}
|
||||
}
|
||||
|
||||
private async runRepoFetch(target: RepoGitTarget): Promise<void> {
|
||||
if (target.fetchInFlight) {
|
||||
private stopRepoFetchSchedule(target: RepoGitTarget): void {
|
||||
if (target.fetchState.kind === "scheduled") {
|
||||
clearTimeout(target.fetchState.timer);
|
||||
}
|
||||
if (!target.closed && target.fetchState.kind === "in-flight") {
|
||||
target.fetchState = {
|
||||
kind: "in-flight",
|
||||
remoteUrl: null,
|
||||
consecutiveErrors: 0,
|
||||
pendingRetry: "none",
|
||||
};
|
||||
return;
|
||||
}
|
||||
target.fetchState = { kind: "idle", remoteUrl: null };
|
||||
}
|
||||
|
||||
private resumeRepoFetch(target: RepoGitTarget, remoteUrlOverride?: string): void {
|
||||
if (target.closed || this.repoTargets.get(target.repoGitRoot) !== target) {
|
||||
return;
|
||||
}
|
||||
const remoteUrl =
|
||||
remoteUrlOverride !== undefined ? remoteUrlOverride : target.fetchState.remoteUrl;
|
||||
if (remoteUrl === null) {
|
||||
return;
|
||||
}
|
||||
if (target.fetchState.kind === "in-flight") {
|
||||
const pendingRetry =
|
||||
remoteUrlOverride !== undefined || target.fetchState.pendingRetry === "always"
|
||||
? "always"
|
||||
: "on-error";
|
||||
target.fetchState = {
|
||||
kind: "in-flight",
|
||||
remoteUrl,
|
||||
consecutiveErrors: 0,
|
||||
pendingRetry,
|
||||
};
|
||||
return;
|
||||
}
|
||||
if (target.fetchState.kind === "scheduled") {
|
||||
clearTimeout(target.fetchState.timer);
|
||||
}
|
||||
target.fetchState = { kind: "idle", remoteUrl };
|
||||
void this.runRepoFetch(target);
|
||||
}
|
||||
|
||||
private resumeRepoFetchIfPausedOrErrored(workspaceTarget: WorkspaceGitTarget): void {
|
||||
if (!workspaceTarget.repoGitRoot) {
|
||||
return;
|
||||
}
|
||||
const repoTarget = this.repoTargets.get(workspaceTarget.repoGitRoot);
|
||||
if (!repoTarget || repoTarget.closed) {
|
||||
return;
|
||||
}
|
||||
const state = repoTarget.fetchState;
|
||||
if (
|
||||
state.kind === "in-flight" ||
|
||||
state.kind === "paused-auth" ||
|
||||
(state.kind === "scheduled" && state.consecutiveErrors > 0)
|
||||
) {
|
||||
this.resumeRepoFetch(repoTarget);
|
||||
}
|
||||
}
|
||||
|
||||
private syncRepoFetchRemoteUrl(
|
||||
workspaceTarget: WorkspaceGitTarget,
|
||||
hadPreviousGit: boolean,
|
||||
previousRemoteUrl: string | null,
|
||||
nextRemoteUrl: string | null,
|
||||
): void {
|
||||
if (!workspaceTarget.repoGitRoot) {
|
||||
return;
|
||||
}
|
||||
const repoTarget = this.repoTargets.get(workspaceTarget.repoGitRoot);
|
||||
if (!repoTarget || repoTarget.closed) {
|
||||
return;
|
||||
}
|
||||
if (repoTarget.fetchState.remoteUrl === undefined) {
|
||||
if (nextRemoteUrl === null) {
|
||||
this.stopRepoFetchSchedule(repoTarget);
|
||||
} else {
|
||||
repoTarget.fetchState = { ...repoTarget.fetchState, remoteUrl: nextRemoteUrl };
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (!hadPreviousGit || previousRemoteUrl === nextRemoteUrl) {
|
||||
return;
|
||||
}
|
||||
if (repoTarget.fetchState.remoteUrl === nextRemoteUrl) {
|
||||
return;
|
||||
}
|
||||
if (nextRemoteUrl === null) {
|
||||
this.stopRepoFetchSchedule(repoTarget);
|
||||
return;
|
||||
}
|
||||
this.resumeRepoFetch(repoTarget, nextRemoteUrl);
|
||||
}
|
||||
|
||||
private armRepoFetchTimer(
|
||||
target: RepoGitTarget,
|
||||
remoteUrl: string | undefined,
|
||||
consecutiveErrors: number,
|
||||
delayMs: number,
|
||||
): void {
|
||||
if (target.fetchState.kind === "scheduled") {
|
||||
clearTimeout(target.fetchState.timer);
|
||||
}
|
||||
const timer = setTimeout(() => {
|
||||
void this.runRepoFetch(target);
|
||||
}, delayMs);
|
||||
target.fetchState = { kind: "scheduled", remoteUrl, timer, consecutiveErrors };
|
||||
}
|
||||
|
||||
private scheduleNextRepoFetch(
|
||||
target: RepoGitTarget,
|
||||
remoteUrl: string | undefined,
|
||||
previousErrors: number,
|
||||
fetchError: unknown | null,
|
||||
): void {
|
||||
if (target.closed || this.disposed || this.repoTargets.get(target.repoGitRoot) !== target) {
|
||||
target.fetchState = { kind: "idle", remoteUrl: null };
|
||||
return;
|
||||
}
|
||||
|
||||
target.fetchInFlight = true;
|
||||
if (fetchError !== null && isGitFetchAuthError(fetchError)) {
|
||||
target.fetchState = { kind: "paused-auth", remoteUrl };
|
||||
this.logger.warn(
|
||||
{ err: fetchError, repoGitRoot: target.repoGitRoot, cwd: target.cwd },
|
||||
"Background git fetch paused due to authentication failure",
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
if (fetchError !== null) {
|
||||
const consecutiveErrors = previousErrors + 1;
|
||||
const delayMs = computeBackgroundGitFetchDelayMs(consecutiveErrors);
|
||||
this.logger.warn(
|
||||
{
|
||||
err: fetchError,
|
||||
repoGitRoot: target.repoGitRoot,
|
||||
cwd: target.cwd,
|
||||
attempt: consecutiveErrors,
|
||||
retryInMs: delayMs,
|
||||
},
|
||||
"Background git fetch failed; retrying with backoff",
|
||||
);
|
||||
this.armRepoFetchTimer(target, remoteUrl, consecutiveErrors, delayMs);
|
||||
return;
|
||||
}
|
||||
|
||||
this.armRepoFetchTimer(target, remoteUrl, 0, BACKGROUND_GIT_FETCH_INTERVAL_MS);
|
||||
}
|
||||
|
||||
private async runRepoFetch(target: RepoGitTarget): Promise<void> {
|
||||
if (
|
||||
target.closed ||
|
||||
target.fetchState.kind === "in-flight" ||
|
||||
target.fetchState.remoteUrl === null ||
|
||||
this.repoTargets.get(target.repoGitRoot) !== target
|
||||
) {
|
||||
return;
|
||||
}
|
||||
const previousErrors =
|
||||
target.fetchState.kind === "scheduled" ? target.fetchState.consecutiveErrors : 0;
|
||||
if (target.fetchState.kind === "scheduled") {
|
||||
clearTimeout(target.fetchState.timer);
|
||||
}
|
||||
|
||||
target.fetchState = {
|
||||
kind: "in-flight",
|
||||
remoteUrl: target.fetchState.remoteUrl,
|
||||
consecutiveErrors: previousErrors,
|
||||
pendingRetry: "none",
|
||||
};
|
||||
this.logger.debug(
|
||||
{ repoGitRoot: target.repoGitRoot, cwd: target.cwd },
|
||||
"Running background git fetch",
|
||||
);
|
||||
|
||||
let result: WorkspaceGitFetchResult | null = null;
|
||||
let thrownError: unknown = null;
|
||||
const eventsBeforeFetchSnapshot: FileChange[] = [];
|
||||
try {
|
||||
try {
|
||||
@@ -4106,14 +4335,49 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
createRunGitCommand("background-fetch", { priority: "background" }),
|
||||
);
|
||||
} catch (error) {
|
||||
this.logger.warn(
|
||||
{ err: error, repoGitRoot: target.repoGitRoot, cwd: target.cwd },
|
||||
"Background git fetch failed",
|
||||
);
|
||||
thrownError = error;
|
||||
}
|
||||
if (target.closed || this.repoTargets.get(target.repoGitRoot) !== target) {
|
||||
return;
|
||||
}
|
||||
const fetchError = thrownError ?? result?.error ?? null;
|
||||
this.applyRepoFetchResult(target, result, eventsBeforeFetchSnapshot);
|
||||
this.completeInFlightRepoFetch(target, fetchError);
|
||||
} finally {
|
||||
target.fetchInFlight = false;
|
||||
this.finalizeInFlightRepoFetch(target);
|
||||
}
|
||||
}
|
||||
|
||||
private completeInFlightRepoFetch(target: RepoGitTarget, fetchError: unknown | null): void {
|
||||
const state = target.fetchState;
|
||||
if (state.kind !== "in-flight") {
|
||||
return;
|
||||
}
|
||||
if (state.remoteUrl === null) {
|
||||
target.fetchState = { kind: "idle", remoteUrl: null };
|
||||
return;
|
||||
}
|
||||
const shouldRetryImmediately =
|
||||
state.pendingRetry === "always" || (state.pendingRetry === "on-error" && fetchError !== null);
|
||||
if (shouldRetryImmediately) {
|
||||
return;
|
||||
}
|
||||
this.scheduleNextRepoFetch(target, state.remoteUrl, state.consecutiveErrors, fetchError);
|
||||
}
|
||||
|
||||
private finalizeInFlightRepoFetch(target: RepoGitTarget): void {
|
||||
if (target.fetchState.kind !== "in-flight") {
|
||||
return;
|
||||
}
|
||||
const { remoteUrl, pendingRetry } = target.fetchState;
|
||||
target.fetchState = { kind: "idle", remoteUrl };
|
||||
if (
|
||||
remoteUrl !== null &&
|
||||
pendingRetry !== "none" &&
|
||||
!target.closed &&
|
||||
this.repoTargets.get(target.repoGitRoot) === target
|
||||
) {
|
||||
void this.runRepoFetch(target);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4127,16 +4391,16 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
target.recentFetchRemoteRefChanges.clear();
|
||||
target.knownRemoteRefs = null;
|
||||
this.flushBufferedFetchMetadataEvents(target);
|
||||
if (result) {
|
||||
if (result && !result.error) {
|
||||
this.logger.warn(
|
||||
{ err: result.error, repoGitRoot: target.repoGitRoot, cwd: target.cwd },
|
||||
{ repoGitRoot: target.repoGitRoot, cwd: target.cwd },
|
||||
"Background git fetch ref classification failed; using structural refresh",
|
||||
);
|
||||
}
|
||||
this.scheduleRepoMetadataRefresh(target, "repo-fetch-unclassified", false);
|
||||
return;
|
||||
}
|
||||
if (result.error) {
|
||||
if (result.error && (result.changes.length > 0 || result.nonRemoteRefsChanged === true)) {
|
||||
this.logger.warn(
|
||||
{ err: result.error, repoGitRoot: target.repoGitRoot, cwd: target.cwd },
|
||||
"Background git fetch completed with errors after changing refs",
|
||||
@@ -4372,10 +4636,7 @@ export class WorkspaceGitServiceImpl implements WorkspaceGitService {
|
||||
|
||||
private closeRepoTarget(target: RepoGitTarget): void {
|
||||
target.closed = true;
|
||||
if (target.intervalId) {
|
||||
clearInterval(target.intervalId);
|
||||
target.intervalId = null;
|
||||
}
|
||||
this.stopRepoFetchSchedule(target);
|
||||
if (target.fallbackPollTimer) {
|
||||
clearTimeout(target.fallbackPollTimer);
|
||||
target.fallbackPollTimer = null;
|
||||
|
||||
Reference in New Issue
Block a user