|
| 1 | +import logging |
| 2 | +import random |
| 3 | +import typing |
| 4 | +from operator import itemgetter |
| 5 | + |
| 6 | +import asyncpg |
| 7 | +import sqlalchemy |
| 8 | +from asyncpg.connect_utils import SessionAttribute |
| 9 | +from sqlalchemy.dialects.postgresql.asyncpg import PGDialect_asyncpg |
| 10 | + |
| 11 | + |
| 12 | +if typing.TYPE_CHECKING: |
| 13 | + ConnectionType = asyncpg.Connection[typing.Any] |
| 14 | + |
| 15 | + |
| 16 | +logger = logging.getLogger(__name__) |
| 17 | + |
| 18 | + |
| 19 | +def build_connection_factory( |
| 20 | + url: sqlalchemy.URL, |
| 21 | + timeout: float, |
| 22 | +) -> typing.Callable[[], typing.Awaitable["ConnectionType"]]: |
| 23 | + connect_args: typing.Final[dict[str, typing.Any]] = PGDialect_asyncpg().create_connect_args(url)[1] # type: ignore[no-untyped-call] |
| 24 | + raw_target_session_attrs: typing.Final[str | None] = connect_args.pop("target_session_attrs", None) |
| 25 | + target_session_attrs: typing.Final[SessionAttribute | None] = ( |
| 26 | + SessionAttribute(raw_target_session_attrs) if raw_target_session_attrs else None |
| 27 | + ) |
| 28 | + |
| 29 | + raw_hosts: typing.Final[str | list[str]] = connect_args.pop("host") |
| 30 | + raw_ports: typing.Final[int | list[int] | None] = connect_args.pop("port", None) |
| 31 | + hosts_and_ports: list[tuple[str, int]] |
| 32 | + hosts: str | list[str] |
| 33 | + ports: int | list[int] | None |
| 34 | + if isinstance(raw_hosts, list) and isinstance(raw_ports, list): |
| 35 | + hosts_and_ports = list(zip(raw_hosts, raw_ports, strict=True)) |
| 36 | + random.shuffle(hosts_and_ports) |
| 37 | + hosts = list(map(itemgetter(0), hosts_and_ports)) |
| 38 | + ports = list(map(itemgetter(1), hosts_and_ports)) |
| 39 | + else: |
| 40 | + hosts_and_ports = [] |
| 41 | + hosts = raw_hosts |
| 42 | + ports = raw_ports |
| 43 | + |
| 44 | + async def _connection_factory() -> "ConnectionType": |
| 45 | + connection: ConnectionType |
| 46 | + nonlocal hosts_and_ports |
| 47 | + try: |
| 48 | + connection = await asyncpg.connect( |
| 49 | + **connect_args, |
| 50 | + host=hosts, |
| 51 | + port=ports, |
| 52 | + timeout=timeout, |
| 53 | + target_session_attrs=target_session_attrs, |
| 54 | + ) |
| 55 | + return connection # noqa: TRY300 |
| 56 | + except TimeoutError: |
| 57 | + if not hosts_and_ports: |
| 58 | + raise |
| 59 | + |
| 60 | + logger.warning("Failed to fetch asyncpg connection. Trying host by host.") |
| 61 | + |
| 62 | + hosts_and_ports_copy: typing.Final = hosts_and_ports.copy() |
| 63 | + random.shuffle(hosts_and_ports_copy) |
| 64 | + for one_host, one_port in hosts_and_ports_copy: |
| 65 | + try: |
| 66 | + connection = await asyncpg.connect( |
| 67 | + **connect_args, |
| 68 | + host=one_host, |
| 69 | + port=one_port, |
| 70 | + timeout=timeout, |
| 71 | + target_session_attrs=target_session_attrs, |
| 72 | + ) |
| 73 | + return connection # noqa: TRY300 |
| 74 | + except (TimeoutError, OSError, asyncpg.TargetServerAttributeNotMatched) as exc: # noqa: PERF203 |
| 75 | + logger.warning("Failed to fetch asyncpg connection from %s, %s", one_host, exc) |
| 76 | + msg: typing.Final = f"None of the hosts match the target attribute requirement {target_session_attrs}" |
| 77 | + raise asyncpg.TargetServerAttributeNotMatched(msg) |
| 78 | + |
| 79 | + return _connection_factory |
0 commit comments