189 build - уменьшинно количество запросов для одновременной работы на 2х матчах

This commit is contained in:
2026-10-02 18:39:15 +03:00
parent 74249d7fa2
commit e4bedb1264
10 changed files with 556 additions and 128 deletions

View File

@@ -5,12 +5,13 @@ job; passing an existing atomic Session to another thread is rejected.
"""
from __future__ import annotations
import asyncio
import inspect
import os
from functools import partial, wraps
from typing import Any, Callable
from anyio import CapacityLimiter, to_thread
from anyio import CancelScope, CapacityLimiter, to_thread
from anyio.lowlevel import RunVar
from .database import _atomic_session
@@ -35,9 +36,27 @@ async def run_db(function: Callable[..., Any], *args: Any, **kwargs: Any) -> Any
except LookupError:
limiter = CapacityLimiter(worker_limit())
_limiter.set(limiter)
# Do not abandon a worker on cancellation: its transaction must finish or
# roll back before the caller can release the concurrency budget.
return await to_thread.run_sync(partial(function, *args, **kwargs), limiter=limiter)
# asyncio.Task.cancel() bypasses AnyIO's cancel-scope protection. Keep the
# worker's await alive so its transaction and limiter token finish together.
worker = asyncio.create_task(
to_thread.run_sync(partial(function, *args, **kwargs), limiter=limiter)
)
try:
return await asyncio.shield(worker)
except asyncio.CancelledError:
# AnyIO scopes repeat cancellation at every await. Shield that scope
# too, otherwise cleanup would spin while the SQL thread is running.
with CancelScope(shield=True):
while not worker.done():
try:
await asyncio.shield(worker)
except asyncio.CancelledError:
continue
except Exception:
break
if not worker.cancelled():
worker.exception() # Consume errors while preserving cancellation.
raise
def db_endpoint(function: Callable[..., Any]) -> Callable[..., Any]: