Skip to content
Merged
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
200 changes: 200 additions & 0 deletions src/main/git/remote-name-listing.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,200 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'

const {
gitExecFileAsyncMock,
getSshGitProviderMock,
getSshGitProviderGenerationMock,
readLocalGitConfigSignatureMock
} = vi.hoisted(() => ({
gitExecFileAsyncMock: vi.fn(),
getSshGitProviderMock: vi.fn(),
getSshGitProviderGenerationMock: vi.fn(() => 0),
readLocalGitConfigSignatureMock: vi.fn<() => Promise<string | undefined>>(async () => 'sig-1')
}))

vi.mock('./runner', () => ({ gitExecFileAsync: gitExecFileAsyncMock }))
vi.mock('../providers/ssh-git-dispatch', () => ({
getSshGitProvider: getSshGitProviderMock,
getSshGitProviderGeneration: getSshGitProviderGenerationMock
}))
vi.mock('../github/local-git-config-signature', () => ({
readLocalGitConfigSignature: readLocalGitConfigSignatureMock
}))

import { REMOTE_URL_PROBE_TIMEOUT_MS } from './remote-url-probe'
import {
_resetRemoteNameListingCache,
listCachedRemoteNames,
shouldProbeGitRemote
} from './remote-name-listing'

function remoteListCalls(): unknown[][] {
return gitExecFileAsyncMock.mock.calls.filter(
([args]) => Array.isArray(args) && args[0] === 'remote' && args[1] !== 'get-url'
)
}

describe('cached git remote name listing', () => {
beforeEach(() => {
_resetRemoteNameListingCache()
gitExecFileAsyncMock.mockReset()
getSshGitProviderMock.mockReset()
getSshGitProviderGenerationMock.mockReset()
getSshGitProviderGenerationMock.mockReturnValue(0)
readLocalGitConfigSignatureMock.mockReset()
readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-1')
})

it('skips probing upstream when listing only has origin', async () => {
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'origin\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await expect(listCachedRemoteNames('/repo')).resolves.toEqual(['origin'])
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
expect(gitExecFileAsyncMock).toHaveBeenCalledWith(['remote'], {
cwd: '/repo',
timeout: REMOTE_URL_PROBE_TIMEOUT_MS
})
})

it('still probes upstream when listing includes that remote', async () => {
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'origin\nupstream\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(true)
expect(gitExecFileAsyncMock).toHaveBeenCalledTimes(1)
})

it('reuses a signed listing instead of spawning git remote again', async () => {
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'origin\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await expect(shouldProbeGitRemote('/repo', 'origin')).resolves.toBe(true)

expect(remoteListCalls()).toHaveLength(1)
})

it('re-lists as soon as the git config signature changes', async () => {
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'origin\n' })
.mockResolvedValueOnce({ stdout: 'origin\nupstream\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
readLocalGitConfigSignatureMock.mockImplementation(async () => 'sig-2')
await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(true)
expect(remoteListCalls()).toHaveLength(2)
})

it('uses the short TTL when config changes during remote listing', async () => {
vi.useFakeTimers()
try {
readLocalGitConfigSignatureMock
.mockResolvedValueOnce('sig-1')
.mockResolvedValueOnce('sig-2')
.mockResolvedValue('sig-2')
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'origin\n' })
.mockResolvedValueOnce({ stdout: 'origin\nupstream\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await vi.advanceTimersByTimeAsync(30_001)
await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(true)
expect(remoteListCalls()).toHaveLength(2)
} finally {
vi.useRealTimers()
}
})

it('expires an unsigned listing after the short TTL', async () => {
vi.useFakeTimers()
try {
readLocalGitConfigSignatureMock.mockImplementation(async () => undefined)
gitExecFileAsyncMock
.mockResolvedValueOnce({ stdout: 'origin\n' })
.mockResolvedValueOnce({ stdout: 'origin\nupstream\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await vi.advanceTimersByTimeAsync(30_001)
await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(true)
expect(remoteListCalls()).toHaveLength(2)
} finally {
vi.useRealTimers()
}
})

it('holds a signed listing past the unsigned TTL', async () => {
vi.useFakeTimers()
try {
gitExecFileAsyncMock.mockResolvedValue({ stdout: 'origin\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await vi.advanceTimersByTimeAsync(4 * 60_000)
await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
expect(remoteListCalls()).toHaveLength(1)
} finally {
vi.useRealTimers()
}
})

it('fails open and does not cache when listing throws', async () => {
gitExecFileAsyncMock
.mockRejectedValueOnce(new Error('git timed out.'))
.mockResolvedValueOnce({ stdout: 'origin\n' })

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(true)
await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
expect(remoteListCalls()).toHaveLength(2)
})

it('coalesces concurrent listings onto one spawn', async () => {
gitExecFileAsyncMock.mockImplementation(async () => {
await Promise.resolve()
return { stdout: 'origin\n' }
})

await expect(
Promise.all([
shouldProbeGitRemote('/repo', 'upstream'),
shouldProbeGitRemote('/repo', 'upstream'),
listCachedRemoteNames('/repo')
])
).resolves.toEqual([false, false, ['origin']])
expect(remoteListCalls()).toHaveLength(1)
})

it('keeps host and WSL listings separate', async () => {
gitExecFileAsyncMock.mockImplementation(
async (_args: string[], options: { wslDistro?: string } = {}) => ({
stdout: options.wslDistro ? 'origin\nupstream\n' : 'origin\n'
})
)

await expect(shouldProbeGitRemote('/repo', 'upstream')).resolves.toBe(false)
await expect(
shouldProbeGitRemote('/repo', 'upstream', null, { wslDistro: 'Ubuntu' })
).resolves.toBe(true)
expect(gitExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['remote'], {
cwd: '/repo',
timeout: REMOTE_URL_PROBE_TIMEOUT_MS,
wslDistro: 'Ubuntu'
})
})

it('lists remotes through the SSH git provider', async () => {
const exec = vi.fn(async () => ({ stdout: 'origin\n', stderr: '' }))
getSshGitProviderMock.mockReturnValue({ exec })

await expect(shouldProbeGitRemote('/remote/repo', 'upstream', 'ssh-1')).resolves.toBe(false)
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
expect(exec).toHaveBeenCalledWith(['remote'], '/remote/repo', {
signal: expect.any(AbortSignal)
})
})

it('fails open when the SSH git provider is missing instead of listing locally', async () => {
getSshGitProviderMock.mockReturnValue(undefined)

await expect(shouldProbeGitRemote('/remote/repo', 'upstream', 'ssh-1')).resolves.toBe(true)
expect(gitExecFileAsyncMock).not.toHaveBeenCalled()
})
})
174 changes: 174 additions & 0 deletions src/main/git/remote-name-listing.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,174 @@
import { readLocalGitConfigSignature } from '../github/local-git-config-signature'
import { getSshGitProvider, getSshGitProviderGeneration } from '../providers/ssh-git-dispatch'
import { runCoalescedProbe, type CoalescedProbes } from './coalesced-probe'
import type { GitAdmissionTier } from './command-runner/git-exec-options'
import { REMOTE_URL_PROBE_TIMEOUT_MS } from './remote-url-probe'
import { gitExecFileAsync } from './runner'

export type RemoteNameListingGitOptions = {
wslDistro?: string
admissionTier?: GitAdmissionTier
}

const SIGNED_REMOTE_NAME_LISTING_TTL_MS = 5 * 60_000
const UNSIGNED_REMOTE_NAME_LISTING_TTL_MS = 30_000
const REMOTE_NAME_LISTING_CACHE_MAX_ENTRIES = 512

type CachedRemoteNames = {
remotes: string[]
expiresAt: number
configSignature?: string
}

const remoteNameListingCache = new Map<string, CachedRemoteNames>()
const remoteNameListingInFlight: CoalescedProbes<string[] | null> = new Map()

/** @internal - exposed for tests only */
export function _resetRemoteNameListingCache(): void {
remoteNameListingCache.clear()
remoteNameListingInFlight.clear()
}

function parseRemoteNames(stdout: string): string[] {
return stdout
.split(/\r?\n/)
.map((line) => line.trim())
.filter(Boolean)
}

function remoteNameListingCacheKey(
repoPath: string,
connectionId?: string | null,
localGitOptions: RemoteNameListingGitOptions = {}
): string {
const runtimeKey = connectionId
? `ssh:${connectionId}:${getSshGitProviderGeneration(connectionId)}`
: `local:${localGitOptions.wslDistro ?? 'host'}`
return `${runtimeKey}\0${repoPath}`
}

function pruneRemoteNameListingCache(now: number): void {
for (const [key, entry] of remoteNameListingCache) {
if (entry.expiresAt <= now) {
remoteNameListingCache.delete(key)
}
}
while (remoteNameListingCache.size > REMOTE_NAME_LISTING_CACHE_MAX_ENTRIES) {
const oldestKey = remoteNameListingCache.keys().next().value
if (oldestKey === undefined) {
return
}
remoteNameListingCache.delete(oldestKey)
}
}

function listingGitConfigContext(
repoPath: string,
connectionId?: string | null,
localGitOptions: RemoteNameListingGitOptions = {}
): { repoPath: string; connectionId: string | null; wslDistro?: string } {
return {
repoPath,
connectionId: connectionId ?? null,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {})
}
}

/**
* `git remote` names for one repo/runtime. Failed listings are not cached: a
* missed `upstream` would otherwise send issue/PR resolvers to origin on a
* contributor clone (#7331).
*/
export async function listCachedRemoteNames(
repoPath: string,
connectionId?: string | null,
localGitOptions: RemoteNameListingGitOptions = {}
): Promise<string[] | null> {
const cacheKey = remoteNameListingCacheKey(repoPath, connectionId, localGitOptions)
const now = Date.now()
pruneRemoteNameListingCache(now)
const cached = remoteNameListingCache.get(cacheKey)
if (cached && cached.expiresAt > now) {
if (cached.configSignature !== undefined) {
const currentSignature = await readLocalGitConfigSignature(
listingGitConfigContext(repoPath, connectionId, localGitOptions)
)
if (currentSignature === cached.configSignature) {
return cached.remotes
}
remoteNameListingCache.delete(cacheKey)
} else {
return cached.remotes
}
}

return runCoalescedProbe(remoteNameListingInFlight, cacheKey, async (ownsKey) => {
const configContext = listingGitConfigContext(repoPath, connectionId, localGitOptions)
const configSignatureBefore = await readLocalGitConfigSignature(configContext)
const remotes = await listUncachedRemoteNames(repoPath, connectionId, localGitOptions)
if (remotes === null) {
return null
}
if (ownsKey()) {
const configSignatureAfter = await readLocalGitConfigSignature(configContext)
const configSignature =
configSignatureBefore !== undefined && configSignatureBefore === configSignatureAfter
? configSignatureAfter
: undefined
remoteNameListingCache.set(cacheKey, {
remotes,
expiresAt:
Date.now() +
(configSignature
? SIGNED_REMOTE_NAME_LISTING_TTL_MS
: UNSIGNED_REMOTE_NAME_LISTING_TTL_MS),
...(configSignature ? { configSignature } : {})
})
pruneRemoteNameListingCache(Date.now())
}
return remotes
})
}

async function listUncachedRemoteNames(
repoPath: string,
connectionId?: string | null,
localGitOptions: RemoteNameListingGitOptions = {}
): Promise<string[] | null> {
if (connectionId) {
const provider = getSshGitProvider(connectionId)
if (!provider) {
return null
}
try {
const { stdout } = await provider.exec(['remote'], repoPath, {
signal: AbortSignal.timeout(REMOTE_URL_PROBE_TIMEOUT_MS)
})
return parseRemoteNames(stdout)
} catch {
return null
}
}
try {
const { stdout } = await gitExecFileAsync(['remote'], {
cwd: repoPath,
timeout: REMOTE_URL_PROBE_TIMEOUT_MS,
...(localGitOptions.wslDistro ? { wslDistro: localGitOptions.wslDistro } : {}),
...(localGitOptions.admissionTier ? { admissionTier: localGitOptions.admissionTier } : {})
})
return parseRemoteNames(stdout)
} catch {
return null
}
}

/** Probe a named remote only when listing says it exists, or listing failed. */
export async function shouldProbeGitRemote(
repoPath: string,
remoteName: string,
connectionId?: string | null,
localGitOptions: RemoteNameListingGitOptions = {}
): Promise<boolean> {
const remotes = await listCachedRemoteNames(repoPath, connectionId, localGitOptions)
return remotes === null || remotes.includes(remoteName)
}
Loading