mirror of
https://github.com/AstrBotDevs/AstrBot.git
synced 2026-09-24 16:39:52 +08:00
perf: reuse TLS context and avoid repeated frozen pip patch
This commit is contained in:
@@ -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:
|
||||
|
||||
@@ -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
|
||||
|
||||
Reference in New Issue
Block a user