mirror of
https://github.com/Mak5er/Downloader-Bot
synced 2026-11-26 17:18:04 +08:00
38 lines
1.1 KiB
Python
38 lines
1.1 KiB
Python
import asyncio
|
|
from typing import Optional
|
|
|
|
import aiohttp
|
|
|
|
_session: Optional[aiohttp.ClientSession] = None
|
|
_lock = asyncio.Lock()
|
|
|
|
# Slightly higher limits to speed up bursty handler traffic while keeping sockets bounded
|
|
_CLIENT_TIMEOUT = aiohttp.ClientTimeout(total=20, connect=5, sock_read=20)
|
|
_CONNECTOR_LIMIT = 128
|
|
|
|
|
|
async def get_http_session() -> aiohttp.ClientSession:
|
|
"""Return a lazily initialised shared aiohttp session."""
|
|
global _session
|
|
if _session and not _session.closed:
|
|
return _session
|
|
|
|
async with _lock:
|
|
if _session is None or _session.closed:
|
|
connector = aiohttp.TCPConnector(
|
|
limit=_CONNECTOR_LIMIT,
|
|
limit_per_host=32,
|
|
ttl_dns_cache=300,
|
|
enable_cleanup_closed=True,
|
|
)
|
|
_session = aiohttp.ClientSession(timeout=_CLIENT_TIMEOUT, connector=connector)
|
|
return _session
|
|
|
|
|
|
async def close_http_session() -> None:
|
|
"""Close the shared session if it was created."""
|
|
global _session
|
|
if _session and not _session.closed:
|
|
await _session.close()
|
|
_session = None
|