Files
romm/backend/utils/context.py
Claude dd3b0a6f99 perf: stop loading the auth and web stack in background processes
Importing any handler.auth submodule ran the package __init__, which
built the auth handlers and so loaded authlib, joserfc and Socket.IO.
models.user imports handler.auth.constants, so every process that
touched the models paid for the whole auth stack. The handler
instances now live next to their classes in handler.auth.base_handler.

utils.context imported fastapi only for annotations; that import now
sits under TYPE_CHECKING.

An idle RQ worker drops from about 118 MB to 89 MB RSS. Each job's
forked work horse now imports a little more on its own, about 0.2s
on an x86 host.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gh1SRMfuK7BZmf6YxMqSyT
2026-10-01 01:02:37 +00:00

88 lines
2.6 KiB
Python

from collections.abc import AsyncGenerator, Awaitable, Callable
from contextlib import asynccontextmanager
from contextvars import ContextVar, Token
from typing import TYPE_CHECKING, TypeVar
import aiohttp
import httpx2
from config import has_proxy_env
from utils.ssrf import (
install_async_ssrf_protection,
install_sync_ssrf_protection,
validate_url_for_http_request,
)
if TYPE_CHECKING:
from fastapi import Request, Response
_T = TypeVar("_T")
ctx_aiohttp_session: ContextVar[aiohttp.ClientSession] = ContextVar("aiohttp_session")
ctx_httpx_client: ContextVar[httpx2.AsyncClient] = ContextVar("httpx_client")
def _validate_request_url_sync(request: httpx2.Request) -> None:
validate_url_for_http_request(str(request.url))
async def _validate_request_url_async(request: httpx2.Request) -> None:
validate_url_for_http_request(str(request.url))
def create_aiohttp_session() -> aiohttp.ClientSession:
return aiohttp.ClientSession(trust_env=has_proxy_env())
def create_httpx_async_client() -> httpx2.AsyncClient:
client = httpx2.AsyncClient(
trust_env=has_proxy_env(),
event_hooks={"request": [_validate_request_url_async]},
)
install_async_ssrf_protection(client)
return client
def create_httpx_client() -> httpx2.Client:
client = httpx2.Client(
trust_env=has_proxy_env(),
event_hooks={"request": [_validate_request_url_sync]},
)
install_sync_ssrf_protection(client)
return client
@asynccontextmanager
async def set_context_var(var: ContextVar[_T], value: _T) -> AsyncGenerator[Token[_T]]:
"""Temporarily set a context variables."""
token = var.set(value)
yield token
var.reset(token)
@asynccontextmanager
async def initialize_context() -> AsyncGenerator[None]:
"""Initialize context variables."""
async with (
create_aiohttp_session() as aiohttp_session,
create_httpx_async_client() as httpx_client,
set_context_var(ctx_aiohttp_session, aiohttp_session),
set_context_var(ctx_httpx_client, httpx_client),
):
yield
async def set_context_middleware(
request: Request, call_next: Callable[[Request], Awaitable[Response]]
) -> Response:
"""Initialize context variables in FastAPI request-response cycle.
This middleware is needed because the context initialized during the lifespan
process is not available in the request-response cycle.
"""
async with (
set_context_var(ctx_aiohttp_session, request.app.state.aiohttp_session),
set_context_var(ctx_httpx_client, request.app.state.httpx_client),
):
return await call_next(request)