Log bulk download progress with rate and ETA
CI / Python 3.13 (push) Successful in 44s
CI / Python 3.12 (push) Successful in 46s
CI / Build and smoke-test image (push) Successful in 17s

This commit is contained in:
omar committed 2026-11-29 07:50:04 +03:00
1 parent 710b2e068c
commit 664dcf6902
3 files changed
+67 -5

No files matched your search

+1 -1
View File
@@ -103,7 +103,7 @@ def build_server(settings: Settings) -> MCPServer:
def main() -> None:
# HTTP request loggers include query strings. Only application events belong in stdio logs.
logging.basicConfig(level=logging.WARNING, stream=sys.stderr)
logging.basicConfig(level=logging.INFO, stream=sys.stderr)
for name in ("httpx", "httpcore", "mcp"):
logging.getLogger(name).setLevel(logging.CRITICAL)
try:
+46 -4
View File
@@ -2,6 +2,7 @@ from __future__ import annotations
import asyncio
import json
import logging
import math
import re
import ssl
@@ -22,6 +23,7 @@ import anyio
import httpcore
import httpx
_LOG = logging.getLogger(__name__)
_CHUNK = 256 * 1024
_JSON_LIMIT = 32 * 1024**2
_DOWNLOAD_LIMIT = 256 * 1024**2
@@ -475,8 +477,11 @@ async def _target_file(path: Path) -> AsyncIterator[BinaryIO]:
await _finish(asyncio.to_thread(path.unlink, missing_ok=True))
async def _read_body(response: httpx.Response, limit: int, path: Path | None) -> bytes | None:
async def _read_body(
response: httpx.Response, limit: int, path: Path | None, source: str = "index",
) -> bytes | None:
length = response.headers.get("Content-Length")
size: int | None = None
if length is not None:
try:
size = int(length)
@@ -487,13 +492,20 @@ async def _read_body(response: httpx.Response, limit: int, path: Path | None) ->
if response.headers.get("Content-Encoding", "identity").lower().strip() != "identity":
raise HttpError("invalid_data")
# Only a file transfer is long enough to be worth watching.
progress = _Progress(source, size) if path is not None else None
async def chunks() -> AsyncIterator[bytes]:
total = 0
async for chunk in response.aiter_bytes(chunk_size=_CHUNK):
total += len(chunk)
if total > limit:
raise HttpError("invalid_data")
if progress is not None:
progress.advance(total)
yield chunk
if progress is not None:
progress.done(total)
if path is None:
body = bytearray()
@@ -506,6 +518,37 @@ async def _read_body(response: httpx.Response, limit: int, path: Path | None) ->
return None
class _Progress:
"""Stderr progress for a bulk transfer: bytes, rate and ETA, never a URL."""
_EVERY = 5.0
_STEP = 8 * 1024**2
def __init__(self, source: str, size: int | None) -> None:
self.source, self.size = source, size
self.started = self.last = monotonic()
self.mark = 0
def _line(self, done: int) -> str:
elapsed = max(monotonic() - self.started, 0.001)
rate = done / elapsed
total = f"{self.size / 1024**2:.1f} MiB" if self.size else "unknown size"
text = f"{self.source} download {done / 1024**2:.1f}/{total} {rate / 1024**2:.2f} MiB/s"
if self.size and rate > 0:
text += f" eta {int((self.size - done) / rate)}s ({100 * done // self.size}%)"
return text
def advance(self, done: int) -> None:
if done - self.mark < self._STEP and monotonic() - self.last < self._EVERY:
return
self.mark, self.last = done, monotonic()
_LOG.info("%s", self._line(done))
def done(self, total: int) -> None:
self.mark = total
_LOG.info("%s", self._line(total))
class _Sender:
def __init__(self, gate: _PublisherGate, max_retries: int, live_timeout: float = _LIVE_SECONDS) -> None:
self.gate = gate
@@ -627,7 +670,7 @@ class _Sender:
try:
code = response.status_code
if code in {200, 304}:
payload = None if code == 304 else await _read_body(response, limit, path)
payload = None if code == 304 else await _read_body(response, limit, path, source)
self.gate.success(source)
return _Response(code, response.headers, url, payload)
if code in _REDIRECTS:
@@ -844,8 +887,7 @@ class HttpClients:
await _finish(self._pool.replace(urls))
except (ValueError, httpx.InvalidURL):
# A malformed provider URL must not stop the server or expose credentials.
import logging
logging.getLogger(__name__).warning("proxy_list invalid; retaining existing pool")
_LOG.warning("proxy_list invalid; retaining existing pool")
async def __aenter__(self) -> HttpClients:
async with AsyncExitStack() as opening:
+20
View File
@@ -855,3 +855,23 @@ async def test_configured_timeout_bounds_the_attempt_including_the_proxy_connect
assert clients.live.budget == 5.0
await clients.live.json("siemens", SIEMENS)
assert {seen["connect"], seen["read"], seen["write"], seen["pool"]} == {4.5}
@pytest.mark.anyio
async def test_file_download_reports_bytes_rate_and_eta(monkeypatch, store, tmp_path, caplog):
caplog.set_level(logging.INFO, logger="vuln_mcp.transport")
body = b"x" * (9 * 1024**2)
async def respond(route, request):
return httpx.Response(200, content=body, headers={"Content-Length": str(len(body))})
async def sleep(delay):
return
monkeypatch.setattr(transport, "sleep", sleep)
routed_clients(monkeypatch, respond)
async with HttpClients(settings(retries=0), store) as clients:
await clients.index.download("msrc", MSRC, tmp_path / "advisory.json")
lines = [r.getMessage() for r in caplog.records if r.name == "vuln_mcp.transport"]
assert any("9.0/9.0 MiB" in line and "eta" in line and "(100%)" in line for line in lines)
assert all("http" not in line for line in lines)