perf: reuse TLS context and avoid repeated frozen pip patch

This commit is contained in:
邹永赫
2026-02-10 10:31:01 +09:00
parent 6517069353
commit 7bac4adc54
2 changed files with 32 additions and 12 deletions
+24 -12
View File
@@ -1,5 +1,6 @@
import logging
import ssl
import threading
import aiohttp
import certifi
@@ -7,26 +8,37 @@ import certifi
logger = logging.getLogger("astrbot")
_CERTIFI_WARNING_LOGGED = False
_SHARED_TLS_CONTEXT: ssl.SSLContext | None = None
_SHARED_TLS_CONTEXT_LOCK = threading.Lock()
def build_ssl_context_with_certifi() -> ssl.SSLContext:
"""Build an SSL context from system trust store and add certifi CAs."""
global _CERTIFI_WARNING_LOGGED
global _SHARED_TLS_CONTEXT
ssl_context = ssl.create_default_context()
if _SHARED_TLS_CONTEXT is not None:
return _SHARED_TLS_CONTEXT
try:
ssl_context.load_verify_locations(cafile=certifi.where())
except Exception as exc:
if not _CERTIFI_WARNING_LOGGED:
logger.warning(
"Failed to load certifi CA bundle into SSL context; "
"falling back to system trust store only: %s",
exc,
)
_CERTIFI_WARNING_LOGGED = True
with _SHARED_TLS_CONTEXT_LOCK:
if _SHARED_TLS_CONTEXT is not None:
return _SHARED_TLS_CONTEXT
return ssl_context
ssl_context = ssl.create_default_context()
try:
ssl_context.load_verify_locations(cafile=certifi.where())
except Exception as exc:
if not _CERTIFI_WARNING_LOGGED:
logger.warning(
"Failed to load certifi CA bundle into SSL context; "
"falling back to system trust store only: %s",
exc,
)
_CERTIFI_WARNING_LOGGED = True
_SHARED_TLS_CONTEXT = ssl_context
return _SHARED_TLS_CONTEXT
def build_tls_connector() -> aiohttp.TCPConnector:
+8
View File
@@ -11,6 +11,8 @@ from astrbot.core.utils.runtime_env import is_packaged_electron_runtime
logger = logging.getLogger("astrbot")
_DISTLIB_FINDER_PATCH_ATTEMPTED = False
def _get_pip_main():
try:
@@ -48,8 +50,14 @@ def _cleanup_added_root_handlers(original_handlers: list[logging.Handler]) -> No
def _patch_distlib_finder_for_frozen_runtime() -> None:
global _DISTLIB_FINDER_PATCH_ATTEMPTED
if not getattr(sys, "frozen", False):
return
if _DISTLIB_FINDER_PATCH_ATTEMPTED:
return
_DISTLIB_FINDER_PATCH_ATTEMPTED = True
try:
from pip._vendor.distlib import resources as distlib_resources