-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathshared_http.py
More file actions
144 lines (122 loc) · 3.89 KB
/
Copy pathshared_http.py
File metadata and controls
144 lines (122 loc) · 3.89 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
"""Shared HTTP clients for long-lived runtime workloads."""
from __future__ import annotations
import asyncio
import os
import threading
from typing import Dict
import httpx
from curl_cffi import requests as curl_requests
_LOCKS_BY_LOOP: Dict[int, asyncio.Lock] = {}
_LOCK_THREAD_GUARD = threading.Lock()
_CLIENTS: Dict[str, httpx.AsyncClient | curl_requests.AsyncSession] = {}
def _get_async_lock() -> asyncio.Lock:
loop = asyncio.get_running_loop()
loop_id = id(loop)
with _LOCK_THREAD_GUARD:
lock = _LOCKS_BY_LOOP.get(loop_id)
if lock is None:
lock = asyncio.Lock()
_LOCKS_BY_LOOP[loop_id] = lock
return lock
def _default_limits() -> httpx.Limits:
"""Return sensible connection pool limits from env or defaults."""
try:
max_connections = int(os.getenv("HTTP_MAX_CONNECTIONS", "50"))
except Exception:
max_connections = 50
try:
max_keepalive = int(os.getenv("HTTP_MAX_KEEPALIVE", "10"))
except Exception:
max_keepalive = 10
return httpx.Limits(
max_connections=max_connections,
max_keepalive_connections=max_keepalive,
)
async def _get_or_create(
name: str,
*,
timeout: httpx.Timeout | float | int,
follow_redirects: bool = False,
) -> httpx.AsyncClient:
lock = _get_async_lock()
async with lock:
client = _CLIENTS.get(name)
if client is not None:
return client
created = httpx.AsyncClient(
timeout=timeout,
follow_redirects=follow_redirects,
limits=_default_limits(),
trust_env=False,
)
_CLIENTS[name] = created
return created
async def get_codex_http_client() -> curl_requests.AsyncSession:
try:
total_timeout = float(os.getenv("CODEX_HTTP_TIMEOUT", "90.0"))
except Exception:
total_timeout = 90.0
lock = _get_async_lock()
async with lock:
client = _CLIENTS.get("codex")
if client is not None:
return client
created = curl_requests.AsyncSession(
timeout=total_timeout,
impersonate="chrome",
)
_CLIENTS["codex"] = created
return created
async def get_auth_http_client() -> httpx.AsyncClient:
try:
timeout = float(os.getenv("AUTH_HTTP_TIMEOUT", "30.0"))
except Exception:
timeout = 30.0
return await _get_or_create(
"auth",
timeout=httpx.Timeout(timeout),
)
async def get_bot_http_client(timeout: httpx.Timeout | float | int) -> httpx.AsyncClient:
# Reuse a single client for all bot API traffic. The first caller determines
# the concrete timeout profile; later calls reuse the same pool.
return await _get_or_create(
"bot_api",
timeout=timeout,
)
async def get_web_http_client() -> httpx.AsyncClient:
try:
timeout = float(os.getenv("WEB_HTTP_TIMEOUT", "20.0"))
except Exception:
timeout = 20.0
return await _get_or_create(
"web_search",
timeout=httpx.Timeout(timeout),
follow_redirects=True,
)
async def reset_shared_http_client(name: str) -> None:
lock = _get_async_lock()
async with lock:
client = _CLIENTS.pop(name, None)
if client is not None:
try:
if isinstance(client, httpx.AsyncClient):
await client.aclose()
else:
await client.close()
except Exception:
pass
async def close_shared_http_clients() -> None:
lock = _get_async_lock()
async with lock:
clients = list(_CLIENTS.values())
_CLIENTS.clear()
with _LOCK_THREAD_GUARD:
_LOCKS_BY_LOOP.clear()
for client in clients:
try:
if isinstance(client, httpx.AsyncClient):
await client.aclose()
else:
await client.close()
except Exception:
pass