diff --git a/backend/app/services/scanner.py b/backend/app/services/scanner.py index 9409add..c9f84b9 100644 --- a/backend/app/services/scanner.py +++ b/backend/app/services/scanner.py @@ -61,12 +61,30 @@ async def _request_with_retry( headers: Dict[str, str], max_retries: int = 3, ) -> httpx.Response: - """带自动重试的 HTTP GET 请求,针对连接超时进行重试""" + """带自动重试的 HTTP GET 请求,针对连接超时进行重试 + + 首次尝试使用较短的超时时间(2秒)快速判断连接是否成功, + 后续重试使用默认超时时间,避免长时间阻塞用户。 + """ last_exc: Optional[Exception] = None + + # 首次尝试使用短超时(2秒),快速探测连接 + first_attempt_timeout = httpx.Timeout( + connect=2.0, # 首次连接超时 2 秒 + read=10.0, # 首次读取超时 10 秒 + write=10.0, + pool=2.0, + ) + for attempt in range(max_retries): try: - return await client.get(url, headers=headers) - except (httpx.ConnectTimeout, httpx.ConnectError) as e: + if attempt == 0: + # 首次尝试:使用短超时快速探测 + return await client.get(url, headers=headers, timeout=first_attempt_timeout) + else: + # 后续重试:使用默认超时(client 配置的 _GIT_API_TIMEOUT) + return await client.get(url, headers=headers) + except (httpx.ConnectTimeout, httpx.ConnectError, httpx.ReadTimeout) as e: last_exc = e if attempt < max_retries - 1: wait = (attempt + 1) * 2