Revert "fix(memory): bound OOM-prone accumulators (#10179)" (#10255)

Co-authored-by: Orca <help@stably.ai>
This commit is contained in:
Neil
2026-07-23 18:35:31 -07:00
committed by GitHub
co-authored by Orca
parent 6eb70d8370
commit aab112933e
1577 changed files with 15167 additions and 91655 deletions
-10
View File
@@ -55,7 +55,6 @@ import {
closeMR,
diagnoseAuth,
getRateLimit,
GITLAB_RATE_LIMIT_CACHE_HOST_MAX_BYTES,
listMergeRequests,
listWorkItems,
mergeMR,
@@ -340,15 +339,6 @@ describe('gitlab client — MR operations', () => {
expect(_getGitLabRateLimitCacheSize()).toBe(64)
})
it('does not retain an oversized host snapshot', async () => {
glabApiWithHeadersMock.mockResolvedValue({ body: '{}', headers: {} })
await getRateLimit({
host: 'h'.repeat(GITLAB_RATE_LIMIT_CACHE_HOST_MAX_BYTES + 1),
force: true
})
expect(_getGitLabRateLimitCacheSize()).toBe(0)
})
})
describe('getMergeRequestForBranch', () => {
+3 -13
View File
@@ -46,8 +46,6 @@ import {
type HostedReviewExecutionOptions
} from '../source-control/hosted-review-git-options'
import { shouldHideNonOpenReviewOnDefaultBranch } from '../source-control/repo-default-branch'
import { measureUtf8ByteLength } from '../../shared/utf8-byte-limits'
import { cacheIdentityDigest } from '../cache-identity-digest'
// Why: glab REST addresses projects by URL-encoded path; escapes slashes for nested groups.
function encodedProject(projectPath: string): string {
@@ -56,7 +54,6 @@ function encodedProject(projectPath: string): string {
const GITLAB_RATE_LIMIT_CACHE_TTL_MS = 30_000
const GITLAB_RATE_LIMIT_CACHE_MAX_ENTRIES = 64
export const GITLAB_RATE_LIMIT_CACHE_HOST_MAX_BYTES = 1024
const gitLabRateLimitCache = new Map<string, GitLabRateLimitSnapshot>()
type HostedReviewLocalGitOptions = ReturnType<typeof getHostedReviewLocalGitOptions>
@@ -213,14 +210,9 @@ export async function getRateLimit(options?: {
host?: string | null
}): Promise<GetGitLabRateLimitResult> {
const host = options?.host?.trim() || null
const retainableHost =
host === null ||
!measureUtf8ByteLength(host, {
stopAfterBytes: GITLAB_RATE_LIMIT_CACHE_HOST_MAX_BYTES
}).exceededLimit
const cacheKey = cacheIdentityDigest([host ?? 'default'])
const cacheKey = host ?? 'default'
pruneGitLabRateLimitCache()
const cached = retainableHost ? gitLabRateLimitCache.get(cacheKey) : undefined
const cached = gitLabRateLimitCache.get(cacheKey)
if (!options?.force && cached && Date.now() - cached.fetchedAt < GITLAB_RATE_LIMIT_CACHE_TTL_MS) {
return { ok: true, snapshot: cached }
}
@@ -231,9 +223,7 @@ export async function getRateLimit(options?: {
const args = host ? ['--hostname', host, 'user'] : ['user']
const { headers } = await glabApiWithHeaders(args)
const snapshot = parseGitLabRateLimitSnapshot(headers, host)
if (retainableHost) {
rememberGitLabRateLimitSnapshot(cacheKey, snapshot)
}
rememberGitLabRateLimitSnapshot(cacheKey, snapshot)
return { ok: true, snapshot }
} catch (err) {
const message = err instanceof Error ? err.message : String(err)
+16 -163
View File
@@ -7,160 +7,24 @@ export type LocalGitExecOptions = {
}
const GLAB_KNOWN_HOSTS_TIMEOUT_MS = 10_000
export const GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES = 1024 * 1024
export const GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES = 64
export const GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES = 4 * 1024
export const GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES = 128 * 1024
export const GLAB_KNOWN_HOSTS_MAX_ENTRIES = 64
export const GLAB_KNOWN_HOST_MAX_BYTES = 1024
export const GLAB_KNOWN_HOSTS_MAX_BYTES = 32 * 1024
export const GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT = 16
type KnownHostsCacheEntry = {
hosts: readonly string[]
keyBytes: number
}
type KnownHostRetention = {
hosts: string[]
retainedBytes: number
protectedEntries: number
}
const knownHostsCacheByExecutionContext = new Map<string, KnownHostsCacheEntry>()
const knownHostsCacheByExecutionContext = new Map<string, readonly string[]>()
const knownHostsInFlightByExecutionContext = new Map<string, Promise<readonly string[]>>()
let knownHostsCachedContextKeyBytes = 0
function utf8Bytes(value: string): number {
return Buffer.byteLength(value, 'utf8')
}
function knownHostsExecutionKey(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): string | null {
let key: string
): string {
if (connectionId) {
if (utf8Bytes(connectionId) > GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES) {
return null
}
// Why: reconnecting can replace the SSH/relay execution host under the same id.
key = `connection:${connectionId}:${getSshGitProviderGeneration(connectionId)}`
} else if (localGitOptions.wslDistro) {
if (utf8Bytes(localGitOptions.wslDistro) > GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES) {
return null
}
key = `wsl:${localGitOptions.wslDistro}`
} else {
key = 'native'
return `connection:${connectionId}:${getSshGitProviderGeneration(connectionId)}`
}
return utf8Bytes(key) <= GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES ? key : null
}
function deleteCachedContext(key: string): void {
const cached = knownHostsCacheByExecutionContext.get(key)
if (!cached) {
return
}
knownHostsCachedContextKeyBytes -= cached.keyBytes
knownHostsCacheByExecutionContext.delete(key)
}
function getCachedHosts(key: string): readonly string[] | undefined {
const cached = knownHostsCacheByExecutionContext.get(key)
if (!cached) {
return undefined
}
knownHostsCacheByExecutionContext.delete(key)
knownHostsCacheByExecutionContext.set(key, cached)
return cached.hosts
}
function createKnownHostRetention(includeDefaults: boolean): KnownHostRetention {
const hosts = includeDefaults ? [...DEFAULT_GITLAB_HOSTS] : []
return {
hosts,
retainedBytes: hosts.reduce((total, host) => total + utf8Bytes(host), 0),
protectedEntries: hosts.length
}
}
function retainKnownHost(retention: KnownHostRetention, host: string): void {
if (utf8Bytes(host) > GLAB_KNOWN_HOST_MAX_BYTES) {
return
}
const normalized = normalizeGitLabHost(host)
const hostBytes = utf8Bytes(normalized)
if (
hostBytes === 0 ||
hostBytes > GLAB_KNOWN_HOST_MAX_BYTES ||
retention.hosts.includes(normalized)
) {
return
}
while (
retention.hosts.length > retention.protectedEntries &&
(retention.hosts.length >= GLAB_KNOWN_HOSTS_MAX_ENTRIES ||
retention.retainedBytes + hostBytes > GLAB_KNOWN_HOSTS_MAX_BYTES)
) {
const removed = retention.hosts.splice(retention.protectedEntries, 1)[0]
retention.retainedBytes -= utf8Bytes(removed)
}
if (
retention.hosts.length >= GLAB_KNOWN_HOSTS_MAX_ENTRIES ||
retention.retainedBytes + hostBytes > GLAB_KNOWN_HOSTS_MAX_BYTES
) {
return
}
retention.hosts.push(normalized)
retention.retainedBytes += hostBytes
}
function retainKnownHosts(hosts: Iterable<string>): readonly string[] {
const retention = createKnownHostRetention(true)
for (const host of hosts) {
retainKnownHost(retention, host)
}
return retention.hosts
}
function cacheKnownHosts(key: string, hosts: Iterable<string>): readonly string[] {
const retained = retainKnownHosts(hosts)
const keyBytes = utf8Bytes(key)
deleteCachedContext(key)
while (
knownHostsCacheByExecutionContext.size >= GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES ||
knownHostsCachedContextKeyBytes + keyBytes > GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES
) {
const oldestKey = knownHostsCacheByExecutionContext.keys().next().value
if (oldestKey === undefined) {
break
}
deleteCachedContext(oldestKey)
}
knownHostsCacheByExecutionContext.set(key, { hosts: retained, keyBytes })
knownHostsCachedContextKeyBytes += keyBytes
return retained
return localGitOptions.wslDistro ? `wsl:${localGitOptions.wslDistro}` : 'native'
}
/** @internal - exposed for tests only */
export function _resetKnownHostsCache(): void {
knownHostsCacheByExecutionContext.clear()
knownHostsInFlightByExecutionContext.clear()
knownHostsCachedContextKeyBytes = 0
}
/** @internal - exposed for tests only */
export function _getKnownHostsCacheState(): {
cachedContexts: number
cachedContextKeyBytes: number
inFlightContexts: number
} {
return {
cachedContexts: knownHostsCacheByExecutionContext.size,
cachedContextKeyBytes: knownHostsCachedContextKeyBytes,
inFlightContexts: knownHostsInFlightByExecutionContext.size
}
}
export function rememberGlabKnownHost(
@@ -168,19 +32,13 @@ export function rememberGlabKnownHost(
connectionId?: string | null,
localGitOptions: LocalGitExecOptions = {}
): void {
const key = knownHostsExecutionKey(connectionId, localGitOptions)
if (!key || utf8Bytes(host) > GLAB_KNOWN_HOST_MAX_BYTES) {
return
}
const normalizedHost = normalizeGitLabHost(host)
if (utf8Bytes(normalizedHost) > GLAB_KNOWN_HOST_MAX_BYTES) {
const key = knownHostsExecutionKey(connectionId, localGitOptions)
const cached = knownHostsCacheByExecutionContext.get(key)
if (!cached || cached.map(normalizeGitLabHost).includes(normalizedHost)) {
return
}
const cached = getCachedHosts(key)
if (!cached || cached.includes(normalizedHost)) {
return
}
cacheKnownHosts(key, [...cached, normalizedHost])
knownHostsCacheByExecutionContext.set(key, [...cached, normalizedHost])
}
export async function getGlabKnownHosts(
@@ -188,10 +46,7 @@ export async function getGlabKnownHosts(
localGitOptions: LocalGitExecOptions = {}
): Promise<readonly string[]> {
const key = knownHostsExecutionKey(connectionId, localGitOptions)
if (!key) {
return [...DEFAULT_GITLAB_HOSTS]
}
const cached = getCachedHosts(key)
const cached = knownHostsCacheByExecutionContext.get(key)
if (cached) {
return cached
}
@@ -199,9 +54,6 @@ export async function getGlabKnownHosts(
if (inFlight) {
return inFlight
}
if (knownHostsInFlightByExecutionContext.size >= GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT) {
return [...DEFAULT_GITLAB_HOSTS]
}
const probe = probeGlabKnownHosts(key, connectionId, localGitOptions)
knownHostsInFlightByExecutionContext.set(key, probe)
try {
@@ -223,13 +75,14 @@ async function probeGlabKnownHosts(
// or reconnected SSH/relay results, and bound an otherwise global probe.
const { stdout, stderr } = await glabExecFileAsync(['auth', 'status'], {
timeout: GLAB_KNOWN_HOSTS_TIMEOUT_MS,
maxBuffer: GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES,
...(!connectionId && localGitOptions.wslDistro
? { wslDistro: localGitOptions.wslDistro }
: {})
})
const hosts = parseGlabAuthStatusHosts(`${stdout}\n${stderr}`)
return cacheKnownHosts(key, hosts)
const merged = Array.from(new Set([...DEFAULT_GITLAB_HOSTS, ...hosts]))
knownHostsCacheByExecutionContext.set(key, merged)
return merged
} catch {
// Keep failures uncached so auth or tunnel recovery is discovered later.
return [...DEFAULT_GITLAB_HOSTS]
@@ -237,11 +90,11 @@ async function probeGlabKnownHosts(
}
export function parseGlabAuthStatusHosts(output: string): string[] {
const retention = createKnownHostRetention(false)
const hosts = new Set<string>()
// Why: self-hosted GitLab can run on a non-default port; preserve it so
// services on the same hostname remain distinct downstream.
for (const match of output.matchAll(/logged in to ([a-zA-Z0-9.-]+(?::\d+)?)/gi)) {
retainKnownHost(retention, match[1].toLowerCase())
hosts.add(match[1].toLowerCase())
}
for (const line of output.split('\n')) {
const bareLine = line.trim()
@@ -250,8 +103,8 @@ export function parseGlabAuthStatusHosts(output: string): string[] {
line === bareLine &&
/^[a-zA-Z0-9](?:[a-zA-Z0-9.-]*[a-zA-Z0-9])?(?::\d+)?$/.test(hostLine)
) {
retainKnownHost(retention, hostLine.toLowerCase())
hosts.add(hostLine.toLowerCase())
}
}
return retention.hosts
return Array.from(hosts)
}
@@ -2,10 +2,6 @@ import { gitExecFileAsync, glabExecFileAsync } from '../git/runner'
import type { IssueSourcePreference } from '../../shared/types'
import { getSshGitProvider } from '../providers/ssh-git-dispatch'
import { clearProjectRefInFlight, runProjectRefProbeOnce } from './project-ref-inflight'
import {
buildRepositoryRefCacheKey,
RepositoryRefCache
} from '../source-control/repository-ref-cache'
import {
parseGlabAuthStatusHosts,
rememberGlabKnownHost,
@@ -22,23 +18,14 @@ import {
export { DEFAULT_GITLAB_HOSTS, parseGitLabProjectRef }
export type { ProjectRef }
export {
GLAB_KNOWN_HOST_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES,
GLAB_KNOWN_HOSTS_MAX_BYTES,
GLAB_KNOWN_HOSTS_MAX_ENTRIES,
GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT,
GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES,
_getKnownHostsCacheState,
_resetKnownHostsCache,
getGlabKnownHosts,
parseGlabAuthStatusHosts,
rememberGlabKnownHost
parseGlabAuthStatusHosts
} from './gitlab-known-host-probe'
export type { LocalGitExecOptions } from './gitlab-known-host-probe'
const projectRefCache = new RepositoryRefCache<ProjectRef>()
const PROJECT_REF_CACHE_MAX_ENTRIES = 512
const projectRefCache = new Map<string, ProjectRef | null>()
/** @internal - exposed for tests only */
export function _resetProjectRefCache(): void {
@@ -51,6 +38,17 @@ export function _getProjectRefCacheSize(): number {
return projectRefCache.size
}
function rememberProjectRefCacheEntry(cacheKey: string, value: ProjectRef | null): void {
projectRefCache.set(cacheKey, value)
while (projectRefCache.size > PROJECT_REF_CACHE_MAX_ENTRIES) {
const oldestKey = projectRefCache.keys().next().value
if (oldestKey === undefined) {
return
}
projectRefCache.delete(oldestKey)
}
}
export async function getProjectRefForRemote(
repoPath: string,
remoteName: string,
@@ -59,13 +57,12 @@ export async function getProjectRefForRemote(
localGitOptions: LocalGitExecOptions = {}
): Promise<ProjectRef | null> {
const runtimeKey = connectionId ?? `local:${localGitOptions.wslDistro ?? 'host'}`
const cacheKey = buildRepositoryRefCacheKey([runtimeKey, repoPath, remoteName, ...knownHosts])
const cached = projectRefCache.get(cacheKey)
if (cached.found) {
return cached.value
const cacheKey = `${runtimeKey}\0${repoPath}\0${remoteName}\0${knownHosts.join(',')}`
if (projectRefCache.has(cacheKey)) {
return projectRefCache.get(cacheKey)!
}
const probe = () =>
return runProjectRefProbeOnce(cacheKey, () =>
resolveProjectRefForRemote(
repoPath,
remoteName,
@@ -74,7 +71,7 @@ export async function getProjectRefForRemote(
cacheKey,
localGitOptions
)
return cacheKey === null ? probe() : runProjectRefProbeOnce(cacheKey, probe)
)
}
async function resolveProjectRefForRemote(
@@ -82,7 +79,7 @@ async function resolveProjectRefForRemote(
remoteName: string,
knownHosts: readonly string[],
connectionId: string | null | undefined,
cacheKey: string | null,
cacheKey: string,
localGitOptions: LocalGitExecOptions
): Promise<ProjectRef | null> {
try {
@@ -98,7 +95,7 @@ async function resolveProjectRefForRemote(
})
const result = parseGitLabProjectRef(stdout, knownHosts)
if (result) {
projectRefCache.remember(cacheKey, result, [result.host, result.path])
rememberProjectRefCacheEntry(cacheKey, result)
return result
}
const remoteCandidate = parseRemoteProjectRefCandidate(stdout)
@@ -112,10 +109,7 @@ async function resolveProjectRefForRemote(
))
) {
rememberGlabKnownHost(remoteCandidate.host, connectionId, localGitOptions)
projectRefCache.remember(cacheKey, remoteCandidate, [
remoteCandidate.host,
remoteCandidate.path
])
rememberProjectRefCacheEntry(cacheKey, remoteCandidate)
return remoteCandidate
}
} catch {
@@ -123,7 +117,7 @@ async function resolveProjectRefForRemote(
return null
}
}
projectRefCache.remember(cacheKey, null, [])
rememberProjectRefCacheEntry(cacheKey, null)
return null
}
+1 -156
View File
@@ -12,15 +12,6 @@ vi.mock('../git/runner', () => ({
}))
import {
GLAB_KNOWN_HOST_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES,
GLAB_KNOWN_HOSTS_MAX_BYTES,
GLAB_KNOWN_HOSTS_MAX_ENTRIES,
GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT,
GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES,
_getKnownHostsCacheState,
_getProjectRefCacheSize,
_resetKnownHostsCache,
_resetProjectRefCache,
@@ -32,7 +23,6 @@ import {
getProjectRefForRemote,
parseGlabApiResponse,
parseGlabAuthStatusHosts,
rememberGlabKnownHost,
resolveIssueSource
} from './gl-utils'
import { registerSshGitProvider, unregisterSshGitProvider } from '../providers/ssh-git-dispatch'
@@ -444,10 +434,7 @@ describe('getGlabKnownHosts', () => {
})
await expect(getGlabKnownHosts()).resolves.toEqual(['gitlab.com', 'gitlab.example.com'])
expect(glabExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], {
timeout: 10_000,
maxBuffer: GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES
})
expect(glabExecFileAsyncMock).toHaveBeenCalledWith(['auth', 'status'], { timeout: 10_000 })
})
it('falls back to default when glab auth status fails', async () => {
@@ -508,12 +495,10 @@ describe('getGlabKnownHosts', () => {
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(4)
expect(glabExecFileAsyncMock).toHaveBeenNthCalledWith(1, ['auth', 'status'], {
timeout: 10_000,
maxBuffer: GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES,
wslDistro: 'Ubuntu'
})
expect(glabExecFileAsyncMock).toHaveBeenNthCalledWith(2, ['auth', 'status'], {
timeout: 10_000,
maxBuffer: GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES,
wslDistro: 'Debian'
})
})
@@ -612,144 +597,4 @@ describe('getGlabKnownHosts', () => {
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(2)
unregisterSshGitProvider(connectionId)
})
it('keeps the most recently used execution contexts at the cache limit', async () => {
glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
for (let index = 0; index < GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES; index += 1) {
await getGlabKnownHosts(undefined, { wslDistro: `Distro-${index}` })
}
expect(_getKnownHostsCacheState().cachedContexts).toBe(GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES)
await getGlabKnownHosts(undefined, { wslDistro: 'Distro-0' })
await getGlabKnownHosts(undefined, { wslDistro: 'Distro-overflow' })
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES + 1)
await getGlabKnownHosts(undefined, { wslDistro: 'Distro-1' })
await getGlabKnownHosts(undefined, { wslDistro: 'Distro-0' })
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES + 2)
})
it('accepts an exact-limit execution key and skips an oversized context', async () => {
glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
const prefixBytes = Buffer.byteLength('wsl:', 'utf8')
const exactDistro = 'x'.repeat(GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES - prefixBytes)
await expect(getGlabKnownHosts(undefined, { wslDistro: exactDistro })).resolves.toEqual([
'gitlab.com'
])
expect(_getKnownHostsCacheState().cachedContextKeyBytes).toBe(
GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES
)
await expect(getGlabKnownHosts(undefined, { wslDistro: `${exactDistro}x` })).resolves.toEqual([
'gitlab.com'
])
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(1)
})
it('evicts old large context keys at the aggregate byte limit', async () => {
glabExecFileAsyncMock.mockResolvedValue({ stdout: '', stderr: '' })
const prefixBytes = Buffer.byteLength('wsl:', 'utf8')
const retainedContexts =
GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES / GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES
const distroAt = (index: number): string => {
const suffix = String(index).padStart(3, '0')
return `${'x'.repeat(GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES - prefixBytes - suffix.length)}${suffix}`
}
for (let index = 0; index <= retainedContexts; index += 1) {
await getGlabKnownHosts(undefined, { wslDistro: distroAt(index) })
}
expect(_getKnownHostsCacheState()).toMatchObject({
cachedContexts: retainedContexts,
cachedContextKeyBytes: GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES
})
await getGlabKnownHosts(undefined, { wslDistro: distroAt(0) })
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(retainedContexts + 2)
})
it('bounds parsed hosts while retaining the newest values', () => {
const hosts = Array.from(
{ length: GLAB_KNOWN_HOSTS_MAX_ENTRIES + 6 },
(_, index) => `gitlab-${index}.example.com`
)
expect(parseGlabAuthStatusHosts(hosts.join('\n'))).toEqual(
hosts.slice(-GLAB_KNOWN_HOSTS_MAX_ENTRIES)
)
})
it('preserves gitlab.com and the newest remembered hosts at the count limit', async () => {
glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' })
await getGlabKnownHosts()
const customHosts = Array.from(
{ length: GLAB_KNOWN_HOSTS_MAX_ENTRIES + 6 },
(_, index) => `gitlab-${index}.example.com`
)
for (const host of customHosts) {
rememberGlabKnownHost(host)
}
await expect(getGlabKnownHosts()).resolves.toEqual([
'gitlab.com',
...customHosts.slice(-(GLAB_KNOWN_HOSTS_MAX_ENTRIES - 1))
])
})
it('accepts an exact-limit host and ignores an oversized host', async () => {
glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' })
await getGlabKnownHosts()
const exactHost = `${'x'.repeat(GLAB_KNOWN_HOST_MAX_BYTES - 5)}.test`
const oversizedHost = `${exactHost}x`
rememberGlabKnownHost(exactHost)
rememberGlabKnownHost(oversizedHost)
await expect(getGlabKnownHosts()).resolves.toEqual(['gitlab.com', exactHost])
})
it('bounds aggregate retained host bytes and keeps newest values', async () => {
glabExecFileAsyncMock.mockResolvedValueOnce({ stdout: '', stderr: '' })
await getGlabKnownHosts()
const customHosts = Array.from({ length: 40 }, (_, index) => {
const prefix = String(index).padStart(2, '0')
return `${prefix}${'x'.repeat(GLAB_KNOWN_HOST_MAX_BYTES - prefix.length)}`
})
for (const host of customHosts) {
rememberGlabKnownHost(host)
}
const retained = await getGlabKnownHosts()
expect(retained).toEqual(['gitlab.com', ...customHosts.slice(-31)])
expect(
retained.reduce((total, host) => total + Buffer.byteLength(host), 0)
).toBeLessThanOrEqual(GLAB_KNOWN_HOSTS_MAX_BYTES)
})
it('caps distinct in-flight probes and recovers capacity after settlement', async () => {
const resolvers: ((value: { stdout: string; stderr: string }) => void)[] = []
glabExecFileAsyncMock.mockImplementation(
() =>
new Promise((resolve) => {
resolvers.push(resolve)
})
)
const probes = Array.from({ length: GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT }, (_, index) =>
getGlabKnownHosts(undefined, { wslDistro: `Distro-${index}` })
)
expect(_getKnownHostsCacheState().inFlightContexts).toBe(GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT)
await expect(getGlabKnownHosts(undefined, { wslDistro: 'Distro-overflow' })).resolves.toEqual([
'gitlab.com'
])
expect(glabExecFileAsyncMock).toHaveBeenCalledTimes(GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT)
for (const resolve of resolvers) {
resolve({ stdout: '', stderr: '' })
}
await Promise.all(probes)
expect(_getKnownHostsCacheState().inFlightContexts).toBe(0)
})
})
+17 -14
View File
@@ -2,7 +2,6 @@ import { execFile } from 'node:child_process'
import { promisify } from 'node:util'
import { gitExecFileAsync, glabExecFileAsync } from '../git/runner'
import { parseGlabApiResponse, type GlabApiResponse } from './glab-api-response'
import { IntegrationApiConcurrencyGate } from '../integration-api-concurrency'
// Why: legacy generic execFile wrapper - only used by callers that don't need
// WSL-aware routing. Repo-scoped callers should use the runner exports below.
@@ -11,15 +10,6 @@ export { glabExecFileAsync, gitExecFileAsync }
export { classifyGlabError, classifyListIssuesError } from './glab-error-classification'
export {
DEFAULT_GITLAB_HOSTS,
GLAB_KNOWN_HOST_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_KEYS_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_KEY_MAX_BYTES,
GLAB_KNOWN_HOSTS_CONTEXT_MAX_ENTRIES,
GLAB_KNOWN_HOSTS_MAX_BYTES,
GLAB_KNOWN_HOSTS_MAX_ENTRIES,
GLAB_KNOWN_HOSTS_MAX_IN_FLIGHT,
GLAB_KNOWN_HOSTS_OUTPUT_MAX_BYTES,
_getKnownHostsCacheState,
_getProjectRefCacheSize,
_resetKnownHostsCache,
_resetProjectRefCache,
@@ -31,7 +21,6 @@ export {
glabRepoExecOptions,
parseGlabAuthStatusHosts,
parseGitLabProjectRef,
rememberGlabKnownHost,
resolveIssueSource
} from './gitlab-project-ref-resolution'
export type {
@@ -42,14 +31,28 @@ export type {
export { parseGlabApiResponse, type GlabApiResponse } from './glab-api-response'
const MAX_CONCURRENT = 4
const concurrencyGate = new IntegrationApiConcurrencyGate(MAX_CONCURRENT)
let running = 0
const queue: (() => void)[] = []
export function acquire(): Promise<void> {
return concurrencyGate.acquire()
if (running < MAX_CONCURRENT) {
running += 1
return Promise.resolve()
}
return new Promise((resolve) =>
queue.push(() => {
running += 1
resolve()
})
)
}
export function release(): void {
concurrencyGate.release()
running -= 1
const next = queue.shift()
if (next) {
next()
}
}
export async function glabApiWithHeaders(
+38 -2
View File
@@ -1,8 +1,12 @@
import { readFile } from 'node:fs/promises'
import { join } from 'node:path'
import type { CreateHostedReviewInput, CreateHostedReviewResult } from '../../shared/hosted-review'
import {
normalizeHostedReviewBaseRef,
normalizeHostedReviewHeadRef
} from '../../shared/hosted-review-refs'
import { getSshFilesystemProvider } from '../providers/ssh-filesystem-dispatch'
import { joinWorktreeRelativePath } from '../runtime/runtime-relative-paths'
import {
getHostedReviewLocalGitOptions,
hasHostedReviewLocalGitOptions,
@@ -17,7 +21,6 @@ import {
release
} from './gl-utils'
import { findOpenMRByHeadBase, parseMergeRequestPayload } from './merge-request-creation-lookup'
import { readGitLabMergeRequestTemplate } from '../source-control/pull-request-template'
function execErrorMessage(error: unknown): string {
if (error instanceof Error) {
@@ -85,6 +88,39 @@ function hostedReviewExecutionOptionArgs(
return hasHostedReviewLocalGitOptions(options) ? [options] : []
}
async function readMergeRequestTemplate(
repoPath: string,
connectionId?: string | null
): Promise<string> {
const relativeCandidates = [
'.gitlab/merge_request_templates/Default.md',
'.gitlab/merge_request_templates/default.md',
'.gitlab/merge_request_template.md',
'.gitlab/MERGE_REQUEST_TEMPLATE.md'
]
const remoteProvider = connectionId ? getSshFilesystemProvider(connectionId) : undefined
if (connectionId && !remoteProvider) {
return ''
}
for (const relativeCandidate of relativeCandidates) {
try {
if (remoteProvider) {
const result = await remoteProvider.readFile(
joinWorktreeRelativePath(repoPath, relativeCandidate)
)
if (result.isBinary) {
continue
}
return result.content
}
return await readFile(join(repoPath, relativeCandidate), 'utf8')
} catch {
// Try the next conventional GitLab merge-request template path.
}
}
return ''
}
export async function createGitLabMergeRequest(
repoPath: string,
input: CreateHostedReviewInput,
@@ -134,7 +170,7 @@ export async function createGitLabMergeRequest(
try {
const body =
input.useTemplate && !input.body?.trim()
? await readGitLabMergeRequestTemplate(repoPath, connectionId)
? await readMergeRequestTemplate(repoPath, connectionId)
: (input.body ?? '')
const createArgs = [
'mr',
@@ -1,51 +0,0 @@
import { describe, expect, it } from 'vitest'
import {
clearProjectRefInFlight,
PROJECT_REF_MAX_IN_FLIGHT,
runProjectRefProbeOnce
} from './project-ref-inflight'
describe('GitLab project-ref in-flight probes', () => {
it('caps retained probes and recovers coalescing after settlement', async () => {
clearProjectRefInFlight()
const releases: (() => void)[] = []
const probes = Array.from({ length: PROJECT_REF_MAX_IN_FLIGHT }, (_, index) =>
runProjectRefProbeOnce(
`key-${index}`,
() =>
new Promise((resolve) => {
releases.push(() => resolve(null))
})
)
)
let overflowCalls = 0
await expect(
runProjectRefProbeOnce('overflow', async () => {
overflowCalls += 1
return null
})
).resolves.toBeNull()
await expect(
runProjectRefProbeOnce('overflow', async () => {
overflowCalls += 1
return null
})
).resolves.toBeNull()
expect(overflowCalls).toBe(2)
releases.forEach((release) => release())
await Promise.all(probes)
let retainedCalls = 0
const first = runProjectRefProbeOnce('recovered', async () => {
retainedCalls += 1
return null
})
const second = runProjectRefProbeOnce('recovered', async () => {
retainedCalls += 1
return null
})
await Promise.all([first, second])
expect(retainedCalls).toBe(1)
})
})
-4
View File
@@ -1,7 +1,6 @@
import type { ProjectRef } from './gl-utils'
const projectRefInFlight = new Map<string, Promise<ProjectRef | null>>()
export const PROJECT_REF_MAX_IN_FLIGHT = 32
export function clearProjectRefInFlight(): void {
projectRefInFlight.clear()
@@ -15,9 +14,6 @@ export async function runProjectRefProbeOnce(
if (inFlight) {
return inFlight
}
if (projectRefInFlight.size >= PROJECT_REF_MAX_IN_FLIGHT) {
return createProbe()
}
const probe = createProbe()
projectRefInFlight.set(cacheKey, probe)
try {