ratelimit
Cross-process rate limiter and resilient HTTP getter with tenacity retry.
- class arxiv_query_mcp.ratelimit.RateLimiter(cfg, dc, *, namespace='', period=None)[source]
Bases:
objectCross-process rate limiter backed by diskcache with in-process concurrency cap.
The last-request timestamp is stored in a shared
diskcache.Cache, and adiskcache.Lockguards the read-modify-write so that multiple processes coordinate without collisions. The synchronous lock section runs in a thread viaasyncio.to_thread()so the event loop is never blocked.An
asyncio.Semaphoreadditionally caps the number of simultaneous in-process outgoing HTTP connections.When
rate_limit_enabledisFalse(e.g. in tests) the spacing sleep is skipped entirely; only the semaphore still applies.- Parameters:
cfg (Config) – Server configuration providing rate-limit and concurrency settings.
dc (diskcache.Cache) – Open
diskcache.Cacheused to store the shared timestamp and the distributed lock. The caller is responsible for closing it.namespace (str) – Separates the spacing of different upstream services that share one disk cache. The default (empty) namespace is arXiv.
period (float | None) – Minimum seconds between requests in this namespace. Defaults to
rate_limit_period.
- async arxiv_query_mcp.ratelimit.resilient_get(client, url, *, params=None, headers=None, cfg, limiter)[source]
Perform a rate-limited, retrying HTTP GET request.
The limiter slot is acquired before every attempt (including retries) and released as soon as the attempt finishes, so retries obey the same request spacing as first attempts and no slot is held during back-off. On retryable failures (see
_is_retryable()) tenacity waits with exponential back-off + jitter and tries again up tomax_retriestimes. When the failed response carries aRetry-Afterheader the wait is the larger of that value and the back-off interval, capped atbackoff_max.The final exception (after all retries are exhausted) is re-raised so the caller’s error handler (e.g.
_handle_error()) can classify it.- Parameters:
client (httpx.AsyncClient) – Shared async HTTP client (managed by the server lifespan).
url (str) – Target URL.
params (dict[str, Any] | None) – Optional query-string parameters forwarded to
client.get.headers (dict[str, str] | None) – Optional extra request headers (e.g. an API key).
cfg (Config) – Server configuration providing
max_retries,backoff_base, andbackoff_max.limiter (RateLimiter) –
RateLimiterwhoseacquire()is called before each HTTP attempt.
- Returns:
The successful
httpx.Response.- Raises:
httpx.HTTPStatusError – When the final attempt returns a non-2xx status.
httpx.TimeoutException – When the final attempt times out.
httpx.TransportError – When the final attempt encounters a transport error.
- Return type:
httpx.Response