77 lines
1.8 KiB
Python
Raw Normal View History

2026-07-23 01:15:04 +02:00
# retoor <retoor@molodetz.nl>
from __future__ import annotations
import contextvars
import os
from typing import Any
import httpx
from devplacepy import stealth
INTERNAL_CALLS: contextvars.ContextVar[int] = contextvars.ContextVar(
"internal_calls", default=0
)
REQUEST_ID: contextvars.ContextVar[str] = contextvars.ContextVar("request_id", default="")
_POOL: httpx.AsyncClient | None = None
def bump_internal_calls() -> None:
INTERNAL_CALLS.set(INTERNAL_CALLS.get() + 1)
def current_internal_calls() -> int:
return INTERNAL_CALLS.get()
def current_request_id() -> str:
return REQUEST_ID.get()
async def startup_pool() -> None:
global _POOL
if _POOL is None:
_POOL = httpx.AsyncClient(
limits=httpx.Limits(max_connections=32, max_keepalive_connections=32),
timeout=httpx.Timeout(30.0),
http2=False,
)
async def shutdown_pool() -> None:
global _POOL
if _POOL is not None:
await _POOL.aclose()
_POOL = None
def stealth_async_client(**kwargs: Any) -> httpx.AsyncClient:
return stealth.stealth_async_client(**kwargs)
async def internal_request(
method: str,
url: str,
*,
json: dict | None = None,
params: dict | None = None,
headers: dict[str, str] | None = None,
timeout: float = 30.0,
) -> httpx.Response:
await startup_pool()
assert _POOL is not None
bump_internal_calls()
merged: dict[str, str] = {}
request_id = current_request_id()
if request_id:
merged["X-Request-Id"] = request_id
internal_key = os.environ.get("DEVPLACE_GATEWAY_INTERNAL_KEY", "").strip()
if internal_key:
merged["X-Internal-Key"] = internal_key
if headers:
merged.update(headers)
return await _POOL.request(
method, url, json=json, params=params, headers=merged, timeout=timeout
)