|
| 1 | +import asyncio |
| 2 | +from collections.abc import Callable, Generator |
| 3 | +from contextlib import AbstractAsyncContextManager |
| 4 | +from types import TracebackType |
| 5 | +from typing import ( |
| 6 | + TYPE_CHECKING, |
| 7 | + Any, |
| 8 | + Generic, |
| 9 | + Protocol, |
| 10 | + TypeVar, |
| 11 | +) |
| 12 | + |
| 13 | +from .exceptions import NoAvailablePoolError |
| 14 | +from .metrics import CalculateMetrics |
| 15 | + |
| 16 | +if TYPE_CHECKING: |
| 17 | + from .balancer_policy.base import AbstractBalancerPolicy |
| 18 | + from .pool_state import PoolState |
| 19 | + |
| 20 | +PoolT = TypeVar("PoolT") |
| 21 | +ConnT = TypeVar("ConnT") |
| 22 | +ConnT_co = TypeVar("ConnT_co", covariant=True) |
| 23 | + |
| 24 | + |
| 25 | +class AcquireContext(Protocol[ConnT_co]): |
| 26 | + async def __aenter__(self) -> ConnT_co: ... |
| 27 | + async def __aexit__( |
| 28 | + self, |
| 29 | + exc_type: type[BaseException] | None, |
| 30 | + exc_val: BaseException | None, |
| 31 | + exc_tb: TracebackType | None, |
| 32 | + ) -> bool | None: ... |
| 33 | + def __await__(self) -> Generator[Any, None, ConnT_co]: ... |
| 34 | + |
| 35 | + |
| 36 | +class TimeoutAcquireContext(Generic[ConnT]): |
| 37 | + __slots__ = ("_context", "_timeout") |
| 38 | + |
| 39 | + def __init__(self, context: AcquireContext[ConnT], timeout: float): |
| 40 | + self._context = context |
| 41 | + self._timeout = timeout |
| 42 | + |
| 43 | + async def __aenter__(self) -> ConnT: |
| 44 | + return await asyncio.wait_for( |
| 45 | + self._context.__aenter__(), |
| 46 | + timeout=self._timeout, |
| 47 | + ) |
| 48 | + |
| 49 | + async def __aexit__(self, *exc): |
| 50 | + # TODO: consider adding a bounded timeout here. Currently if the |
| 51 | + # underlying driver hangs during connection release this will block |
| 52 | + # indefinitely. A timeout risks leaking the connection (not returned |
| 53 | + # to pool), so this needs careful design. |
| 54 | + return await self._context.__aexit__(*exc) |
| 55 | + |
| 56 | + def __await__(self) -> Generator[Any, None, ConnT]: |
| 57 | + return asyncio.wait_for( |
| 58 | + self._context.__aenter__(), |
| 59 | + timeout=self._timeout, |
| 60 | + ).__await__() |
| 61 | + |
| 62 | + |
| 63 | +class PoolAcquireContext( |
| 64 | + AbstractAsyncContextManager[ConnT], |
| 65 | + Generic[PoolT, ConnT], |
| 66 | +): |
| 67 | + def __init__( |
| 68 | + self, |
| 69 | + pool_state: "PoolState[PoolT, ConnT]", |
| 70 | + balancer: "AbstractBalancerPolicy[PoolT]", |
| 71 | + register_connection: Callable[[ConnT, PoolT], None], |
| 72 | + unregister_connection: Callable[[ConnT], None], |
| 73 | + read_only: bool, |
| 74 | + master_as_replica_weight: float | None, |
| 75 | + timeout: float, |
| 76 | + metrics: CalculateMetrics, |
| 77 | + fallback_master: bool = False, |
| 78 | + **kwargs, |
| 79 | + ): |
| 80 | + self._pool_state = pool_state |
| 81 | + self._balancer = balancer |
| 82 | + self._register_connection = register_connection |
| 83 | + self._unregister_connection = unregister_connection |
| 84 | + self._read_only = read_only |
| 85 | + self._fallback_master = fallback_master |
| 86 | + self._master_as_replica_weight = master_as_replica_weight |
| 87 | + self._timeout = timeout |
| 88 | + self._kwargs = kwargs |
| 89 | + self._metrics = metrics |
| 90 | + self._pool: PoolT | None = None |
| 91 | + self._conn: ConnT | None = None |
| 92 | + self._context: AcquireContext[ConnT] | None = None |
| 93 | + |
| 94 | + def _deadline(self) -> float: |
| 95 | + return asyncio.get_running_loop().time() + self._timeout |
| 96 | + |
| 97 | + def _remaining_timeout(self, deadline: float) -> float: |
| 98 | + remaining_timeout = deadline - asyncio.get_running_loop().time() |
| 99 | + if remaining_timeout <= 0: |
| 100 | + raise asyncio.TimeoutError |
| 101 | + return remaining_timeout |
| 102 | + |
| 103 | + async def _get_pool(self, deadline: float) -> PoolT: |
| 104 | + async def get_pool() -> PoolT: |
| 105 | + with self._metrics.with_get_pool(): |
| 106 | + pool = await self._balancer.get_pool( |
| 107 | + read_only=self._read_only, |
| 108 | + fallback_master=self._fallback_master, |
| 109 | + master_as_replica_weight=self._master_as_replica_weight, |
| 110 | + ) |
| 111 | + if pool is None: |
| 112 | + raise NoAvailablePoolError("No available pool") |
| 113 | + return pool |
| 114 | + |
| 115 | + return await asyncio.wait_for( |
| 116 | + get_pool(), |
| 117 | + timeout=self._remaining_timeout(deadline), |
| 118 | + ) |
| 119 | + |
| 120 | + async def _resolve_pool_and_acquire_context( |
| 121 | + self, |
| 122 | + ) -> tuple[PoolT, AcquireContext[ConnT]]: |
| 123 | + deadline = self._deadline() |
| 124 | + pool = await self._get_pool(deadline) |
| 125 | + remaining = self._remaining_timeout(deadline) |
| 126 | + driver_ctx = self._pool_state.acquire_from_pool( |
| 127 | + pool, |
| 128 | + timeout=remaining, |
| 129 | + **self._kwargs, |
| 130 | + ) |
| 131 | + return pool, driver_ctx |
| 132 | + |
| 133 | + async def _acquire_connection(self) -> ConnT: |
| 134 | + pool, driver_ctx = await self._resolve_pool_and_acquire_context() |
| 135 | + |
| 136 | + host = self._pool_state.host(pool) |
| 137 | + with self._metrics.with_acquire(host): |
| 138 | + conn: ConnT = await driver_ctx |
| 139 | + |
| 140 | + try: |
| 141 | + self._metrics.add_connection(host) |
| 142 | + self._register_connection(conn, pool) |
| 143 | + except BaseException: |
| 144 | + await self._pool_state.release_to_pool(conn, pool) |
| 145 | + raise |
| 146 | + return conn |
| 147 | + |
| 148 | + async def __aenter__(self) -> ConnT: |
| 149 | + pool, driver_ctx = await self._resolve_pool_and_acquire_context() |
| 150 | + |
| 151 | + host = self._pool_state.host(pool) |
| 152 | + with self._metrics.with_acquire(host): |
| 153 | + conn: ConnT = await driver_ctx.__aenter__() |
| 154 | + |
| 155 | + try: |
| 156 | + self._metrics.add_connection(host) |
| 157 | + self._register_connection(conn, pool) |
| 158 | + except BaseException: |
| 159 | + await driver_ctx.__aexit__(None, None, None) |
| 160 | + raise |
| 161 | + |
| 162 | + self._pool = pool |
| 163 | + self._conn = conn |
| 164 | + self._context = driver_ctx |
| 165 | + return conn |
| 166 | + |
| 167 | + async def __aexit__(self, *exc): |
| 168 | + if self._conn is None or self._pool is None or self._context is None: |
| 169 | + return |
| 170 | + self._unregister_connection(self._conn) |
| 171 | + self._metrics.remove_connection( |
| 172 | + self._pool_state.host(self._pool), |
| 173 | + ) |
| 174 | + await self._context.__aexit__(*exc) |
| 175 | + |
| 176 | + def __await__(self): |
| 177 | + return self._acquire_connection().__await__() |
| 178 | + |
| 179 | + |
| 180 | +__all__ = ( |
| 181 | + "AcquireContext", |
| 182 | + "TimeoutAcquireContext", |
| 183 | + "PoolAcquireContext", |
| 184 | +) |
0 commit comments