From a01ad3267e44a6ebd98d69034acd9c4e59ae9091 Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Tue, 13 Oct 2026 21:30:04 -0700 Subject: [PATCH 1/4] fix: stop the topology monitor from extending its own expiration A storage-service read publishes a data access, and the monitor service turns that into an expiration extension for the monitor that produces the type. The cluster topology monitor reads the topology it produces on every tick, so it renewed its own 15-minute expiration indefinitely and could never be reaped as idle. StorageService.get gains a keyword-only register_data_access flag, default True so every consumer is unaffected, and the monitor's own read passes False. Keyword-only so a positional argument cannot silently become this flag. The expiration is still not reachable on its own: ClusterTopologyMonitorImpl reports can_dispose only once it has already stopped, so remove_expired_if never fires for a live monitor. That is tracked separately; the two defects mask each other, and fixing either alone changes nothing observable. --- .../cluster_topology_monitor.py | 6 ++++- .../utils/storage/storage_service.py | 11 +++++++-- tests/unit/test_cluster_topology_monitor.py | 22 ++++++++++++++++++ tests/unit/test_storage_service.py | 23 +++++++++++++++++++ 4 files changed, 59 insertions(+), 3 deletions(-) diff --git a/aws_advanced_python_wrapper/cluster_topology_monitor.py b/aws_advanced_python_wrapper/cluster_topology_monitor.py index b125a0664..26b466a47 100644 --- a/aws_advanced_python_wrapper/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/cluster_topology_monitor.py @@ -217,7 +217,11 @@ def _wait_till_topology_gets_updated(self, timeout_sec: float) -> Topology: self._cluster_id, timeout_sec * 1000)) def _get_stored_hosts(self) -> Topology: - hosts = services_container.get_storage_service().get(Topology, self._cluster_id) + # Not a data access: this monitor produces the topology it is reading, + # and a data access extends the producing monitor's expiration, so + # registering one here would make the monitor keep itself alive. + hosts = services_container.get_storage_service().get( + Topology, self._cluster_id, register_data_access=False) if hosts is None: return () return hosts diff --git a/aws_advanced_python_wrapper/utils/storage/storage_service.py b/aws_advanced_python_wrapper/utils/storage/storage_service.py index 2df472442..19f42b573 100644 --- a/aws_advanced_python_wrapper/utils/storage/storage_service.py +++ b/aws_advanced_python_wrapper/utils/storage/storage_service.py @@ -52,12 +52,19 @@ def register( should_dispose_func=should_dispose, item_disposal_func=on_dispose)) - def get(self, item_type: Type[V], key: Any) -> Optional[V]: + def get(self, item_type: Type[V], key: Any, *, register_data_access: bool = True) -> Optional[V]: + """Read a stored item, publishing a data-access event by default. + + Pass ``register_data_access=False`` when the reader is the monitor that + produces this type. A data access extends the producing monitor's + expiration, so a monitor reading its own output would keep itself alive + for as long as the process runs. + """ cache = self._caches.get(item_type) if cache is None: return None value = cache.get(key) - if value is not None: + if value is not None and register_data_access: self._event_publisher.publish(DataAccessEvent(data_type=item_type, key=key)) return value diff --git a/tests/unit/test_cluster_topology_monitor.py b/tests/unit/test_cluster_topology_monitor.py index a740c831d..66f39f73f 100644 --- a/tests/unit/test_cluster_topology_monitor.py +++ b/tests/unit/test_cluster_topology_monitor.py @@ -357,3 +357,25 @@ def test_reader_thread_fetch_topology_exception(self, monitor_impl_mock): monitor._reader_thread_fetch_topology(connection_mock) monitor_impl_mock._host_threads_latest_topology.set.assert_not_called() + + +def test_monitor_reading_its_own_topology_does_not_extend_its_expiration( + cluster_monitor): + """The monitor produces Topology, so reading it must not count as an access. + + A data access extends the producing monitor's expiration, so a monitor + that registered one here would renew itself on every tick and never be + reaped as idle -- the whole point of the expiration. + """ + from aws_advanced_python_wrapper.host_list_provider import Topology + + storage = MagicMock() + storage.get.return_value = (HostInfo("writer.com", 5432, HostRole.WRITER),) + + with patch('aws_advanced_python_wrapper.cluster_topology_monitor' + '.services_container.get_storage_service', + return_value=storage): + cluster_monitor._get_stored_hosts() + + storage.get.assert_called_once_with( + Topology, cluster_monitor._cluster_id, register_data_access=False) diff --git a/tests/unit/test_storage_service.py b/tests/unit/test_storage_service.py index 69d44c0b5..893979df4 100644 --- a/tests/unit/test_storage_service.py +++ b/tests/unit/test_storage_service.py @@ -147,6 +147,29 @@ def test_get_miss_does_not_publish_event(storage, publisher): publisher.publish.assert_not_called() +def test_get_can_opt_out_of_publishing_a_data_access_event(storage, publisher): + """A monitor reading the type it produces must not register an access. + + The event extends the producing monitor's expiration, so a monitor that + reads its own output would renew itself on every read and never expire. + """ + storage.register(TypeA, item_expiration_time=timedelta(minutes=5)) + storage.put(TypeA, "key1", "value1") + + publisher.reset_mock() + assert storage.get(TypeA, "key1", register_data_access=False) == "value1" + + publisher.publish.assert_not_called() + + +def test_register_data_access_is_keyword_only(storage): + """So a positional third argument cannot silently become this flag.""" + import inspect + + param = inspect.signature(StorageService.get).parameters["register_data_access"] + assert param.kind is inspect.Parameter.KEYWORD_ONLY + + def test_register_is_idempotent(storage): storage.register(TypeA, item_expiration_time=timedelta(minutes=5)) storage.put(TypeA, "key1", "value1") From 35dfcce72998ef662abd5aec4a89bf696dc22556 Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Wed, 14 Oct 2026 01:15:57 -0700 Subject: [PATCH 2/4] refactor: move async topology into the storage service and monitor service --- aws_advanced_python_wrapper/aio/cleanup.py | 12 + .../aio/cluster_topology_monitor.py | 283 +++++-- .../aio/host_list_provider.py | 768 +++++------------- .../aio/topology_store.py | 128 +++ .../aio/topology_utils.py | 441 ++++++++++ .../cluster_topology_monitor.py | 5 +- ...dvanced_python_wrapper_messages.properties | 5 + .../utils/monitor_service.py | 13 + .../storage/expiration_tracking_cache.py | 3 +- tests/unit/conftest.py | 4 + ...st_aio_global_aurora_host_list_provider.py | 28 +- tests/unit/test_aio_host_list_provider.py | 452 ++++++----- ...t_aio_host_list_provider_monitor_wiring.py | 210 ++--- .../test_aio_monitor_service_integration.py | 218 +++++ .../test_aio_multi_az_host_list_provider.py | 6 +- tests/unit/test_aio_topology_storage.py | 300 +++++++ 16 files changed, 1913 insertions(+), 963 deletions(-) create mode 100644 aws_advanced_python_wrapper/aio/topology_store.py create mode 100644 aws_advanced_python_wrapper/aio/topology_utils.py create mode 100644 tests/unit/test_aio_monitor_service_integration.py create mode 100644 tests/unit/test_aio_topology_storage.py diff --git a/aws_advanced_python_wrapper/aio/cleanup.py b/aws_advanced_python_wrapper/aio/cleanup.py index 12d092ee2..77134b678 100644 --- a/aws_advanced_python_wrapper/aio/cleanup.py +++ b/aws_advanced_python_wrapper/aio/cleanup.py @@ -71,6 +71,18 @@ def register_shutdown_hook(hook: Callable[[], Awaitable[None]]) -> None: _registered_shutdown_hooks.append(hook) +def unregister_shutdown_hook(hook: Callable[[], Awaitable[None]]) -> None: + """Drop a hook once the object that registered it has torn itself down. + + The registry is process-global and otherwise only emptied on release, so + a caller that registers one hook per instance has to remove it. + """ + try: + _registered_shutdown_hooks.remove(hook) + except ValueError: + pass + + def clear_shutdown_hooks() -> None: """Testing helper: drop all registered hooks without awaiting them.""" _registered_shutdown_hooks.clear() diff --git a/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py b/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py index 265f8aa8b..0ef7a6f2d 100644 --- a/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py @@ -1,4 +1,4 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"). # You may not use this file except in compliance with the License. @@ -45,18 +45,22 @@ import asyncio import copy import time +import weakref +from time import perf_counter_ns from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Set, Tuple) +from aws_advanced_python_wrapper.aio import topology_store from aws_advanced_python_wrapper.hostinfo import HostRole from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages if TYPE_CHECKING: - from aws_advanced_python_wrapper.aio.host_list_provider import ( - AsyncAuroraHostListProvider, Topology) from aws_advanced_python_wrapper.aio.plugin_service import \ AsyncPluginService + from aws_advanced_python_wrapper.aio.topology_store import TopologyKey + from aws_advanced_python_wrapper.aio.topology_utils import ( + AsyncTopologyUtils, Topology) from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.utils.properties import Properties @@ -71,7 +75,9 @@ class AsyncClusterTopologyMonitor: def __init__( self, - provider: AsyncAuroraHostListProvider, + topology_utils: AsyncTopologyUtils, + cluster_id: str, + key: TopologyKey, connection_getter: Any, refresh_interval_sec: float = 30.0, high_refresh_rate_sec: float = 1.0, @@ -80,8 +86,13 @@ def __init__( connection_factory: Optional[Callable[[], Awaitable[Any]]] = None, ) -> None: """ - :param provider: the host list provider whose ``force_refresh`` to - call each tick. + :param topology_utils: owns this dialect's topology query and the + parsing of its rows. The monitor holds no host list provider, so + one monitor can serve every provider on the cluster. + :param cluster_id: the cluster this monitor watches, matched against + ``MonitorResetEvent.cluster_id``. + :param key: the compound ``(cluster_id, loop_token)`` key this monitor + is registered under and stores its topology at. :param connection_getter: a zero-arg callable returning the current async driver connection (or ``None``). Using a getter lets the monitor track connection replacement on failover. @@ -105,7 +116,9 @@ def __init__( ``plugin_service.force_connect(initial_host, monitoring_props)``. When ``None``, falls back to ``connection_getter`` (test/back-compat). """ - self._provider = provider + self._topology_utils = topology_utils + self._cluster_id = cluster_id + self._key = key self._connection_getter = connection_getter self._connection_factory = connection_factory self._owned_conn: Optional[Any] = None @@ -123,6 +136,10 @@ def __init__( # force_monitoring_refresh (sync parity: _request_to_update_topology / # _wait_till_topology_gets_updated, cluster_topology_monitor.py:157-178). self._topology_updated: asyncio.Event = asyncio.Event() + # How many times this monitor has been reset, so a publication whose + # fetch began before a reset can be told apart and dropped. Counts + # resets only, never topology changes. + self._reset_count: int = 0 # Wakes the run loop immediately (skip the tick sleep) when a # blocking refresh is requested. self._request_tick: asyncio.Event = asyncio.Event() @@ -135,6 +152,20 @@ def __init__( self._probe_tasks: Dict[str, asyncio.Task] = {} self._writer_found_event: asyncio.Event = asyncio.Event() + # Monitor protocol state (utils/monitor_service.py). perf_counter_ns + # to match MonitorService._run_cleanup, which compares against it. + self._last_activity_ns: int = perf_counter_ns() + self._in_flight_refreshes: int = 0 + self._closed: bool = False + # Weak: a shutdown hook holds this monitor for the life of the + # process, so a strong reference would pin the loop and everything it + # retains. + self._loop_ref: Optional[weakref.ref] = None + self._loop_strong: Optional[asyncio.AbstractEventLoop] = None + # Set by whoever registered a shutdown hook for this monitor, so the + # hook can drop itself once the monitor is gone. + self.on_closed: Optional[Callable[[], Any]] = None + @property def high_refresh_rate_sec(self) -> float: """Seconds between refreshes while in high-freq mode (read-only).""" @@ -178,17 +209,21 @@ async def force_monitoring_refresh( await self._drop_owned_connection() self._topology_updated.clear() self._request_tick.set() + self._in_flight_refreshes += 1 try: await asyncio.wait_for(self._topology_updated.wait(), timeout_sec) except asyncio.TimeoutError: return () + finally: + self._in_flight_refreshes -= 1 return self._last_topology def start(self) -> None: """Spawn the background refresh task. No-op if already running.""" - if self.is_running(): + if self.is_running() or self._closed: return self._stop_event.clear() + self._set_loop(asyncio.get_running_loop()) self._task = asyncio.create_task(self._run()) async def _get_monitoring_connection(self) -> Any: @@ -224,6 +259,8 @@ async def _drop_owned_connection(self) -> None: async def _run(self) -> None: try: while not self._stop_event.is_set(): + self._last_activity_ns = perf_counter_ns() + reset_count = self._reset_count conn = await self._get_monitoring_connection() if conn is not None: topology = None @@ -231,7 +268,7 @@ async def _run(self) -> None: # Use the provider's direct-DB path to avoid # recursion; the public force_refresh now # routes through this monitor (N.1b). - topology = await self._fetch_via_provider(conn) + topology = await self._topology_utils.query_for_topology(conn) except Exception as ex: # Monitor failures shouldn't crash the task; the cached # topology remains usable. A failure may mean the owned @@ -243,7 +280,7 @@ async def _run(self) -> None: # on the next tick. logger.debug( "ClusterTopologyMonitor.ErrorFetchingTopology", - self._provider.get_cluster_id(), ex) + self._cluster_id, ex) await self._drop_owned_connection() if topology: # Adopt only a NON-EMPTY result. A query through a dead / @@ -253,7 +290,7 @@ async def _run(self) -> None: # on _last_topology being non-empty). Mirrors sync # RdsHostListProvider._get_topology ("use live only if # len > 0"). - self._publish_topology(topology) + self._publish_topology(topology, reset_count) else: # Empty/failed refresh: drop the (likely dead) connection # so the next tick reopens to a live host; KEEP the cached @@ -358,23 +395,27 @@ def _role_corrected(self, topology: Topology) -> Topology: f"publishing a role-corrected view (replica_status lag)") return tuple(corrected) - def _publish_topology(self, topology: Topology) -> None: - """Adopt a NON-EMPTY topology: update the monitor state, push it into - the provider cache, and wake any blocked force_monitoring_refresh - callers. Sync parity: HostMonitor/_reader_thread publications land in - the shared storage-service cache and unblock - _wait_till_topology_gets_updated (:491-495, :157-178).""" + def _publish_topology( + self, + topology: Topology, + reset_count: Optional[int] = None) -> None: + """Adopt a NON-EMPTY topology: update the monitor state, store it, and + wake any blocked force_monitoring_refresh callers. + + ``reset_count`` is this monitor's reset count when the caller started + fetching. A caller that read it passes it back so a topology fetched + before a reset is dropped rather than published after it. + """ if not topology: return + if reset_count is not None and reset_count != self._reset_count: + # A reset landed while this topology was being fetched, so it + # describes the pre-switchover cluster. + return topology = self._role_corrected(topology) self._last_topology = topology self._check_for_writer_change(topology) - adopt = getattr(self._provider, "adopt_topology", None) - if adopt is not None: - try: - adopt(topology) - except Exception: # noqa: BLE001 - cache publication is best-effort - pass + topology_store.put_topology(self._key, topology) self._topology_updated.set() async def _wait_for_tick(self, interval: float) -> None: @@ -470,6 +511,7 @@ def _spawn_panic_probes(self) -> None: async def _probe_and_report(self, host_info: HostInfo) -> None: """Run one probe; stash the conn + host on winner, close on loser.""" assert self._probe_host is not None # _should_panic gates this + reset_count = self._reset_count conn: Optional[Any] = None role: Optional[HostRole] = None for attempt in range(self._MAX_TRANSIENT_PROBE_ATTEMPTS + 1): @@ -515,10 +557,10 @@ async def _probe_and_report(self, host_info: HostInfo) -> None: # writer -- sync parity with HostMonitor's winner path # (_fetch_topology_and_update_cache, cluster_topology_monitor.py:561). try: - topology = await self._fetch_via_provider(conn) + topology = await self._topology_utils.query_for_topology(conn) except Exception: # noqa: BLE001 - publication is best-effort topology = () - self._publish_topology(topology) + self._publish_topology(topology, reset_count) self._writer_found_event.set() return @@ -531,7 +573,7 @@ async def _probe_and_report(self, host_info: HostInfo) -> None: and role == HostRole.READER and not self._writer_found_event.is_set()): try: - topology = await self._fetch_via_provider(conn) + topology = await self._topology_utils.query_for_topology(conn) except Exception: # noqa: BLE001 - publication is best-effort topology = () if topology: @@ -540,7 +582,7 @@ async def _probe_and_report(self, host_info: HostInfo) -> None: if h.role == HostRole.WRITER), None) if (new_writer is not None and new_writer != self._last_known_writer): - self._publish_topology(topology) + self._publish_topology(topology, reset_count) # Lost the race OR role is reader: close the conn. if conn is not None: @@ -626,54 +668,185 @@ async def force_refresh_with_connection( """ if not bypass_ignore_window and self.should_ignore_refresh_request(): return self._last_topology + reset_count = self._reset_count try: topology = await asyncio.wait_for( - self._fetch_via_provider(conn), + self._topology_utils.query_for_topology(conn), timeout=timeout_sec, ) except asyncio.TimeoutError as e: raise TimeoutError(Messages.get_formatted( "ClusterTopologyMonitor.TopologyNotUpdated", - self._provider.get_cluster_id(), timeout_sec * 1000)) from e + self._cluster_id, timeout_sec * 1000)) from e # Never overwrite the cached topology with an empty result (a refresh # through a dead/failed-over connection returns nothing); keep the last # good topology so failover/panic can use it. Mirrors sync # RdsHostListProvider._get_topology ("use live only if len > 0"). # _publish_topology also wakes any blocked force_monitoring_refresh. - self._publish_topology(topology) + self._publish_topology(topology, reset_count) return topology - async def _fetch_via_provider(self, conn: Any) -> Topology: - """Call the provider's direct-DB query path, preferring - :meth:`_fetch_from_db` when available. Falls back to - ``force_refresh`` for providers (or bare mocks) that don't have - the split -- preserves pre-N.1b behavior. + def stop(self) -> None: + """Signal the monitor to stop and schedule teardown on its own loop. + + Non-blocking: MonitorStopEvent is delivered on the publisher's thread + and async blue/green publishes from a coroutine, so blocking here + would wedge that loop. Await :meth:`aclose` to wait for teardown. + + Nothing here touches ``_stop_event``; aclose() sets it on the + monitor's own loop. Setting an asyncio.Event from the cleanup thread + raises once the loop is closed with a tick waiter parked on it. + """ + if not self._schedule(self.aclose()): + logger.debug( + "AsyncClusterTopologyMonitor.StopWithoutLoop", self._cluster_id) + + def close(self) -> None: + """Release resources. Same work as stop() for this monitor.""" + self.stop() + + async def aclose(self) -> None: + """Await full teardown: cancel the task, release the connections. + + Idempotent. ``release_resources_async`` must drain this before the + synchronous release clears the monitor cache, which drops the last + reference to the monitor. """ - import inspect - - # Check the class first (normal case), then the instance (tests - # may monkey-patch an async override). Must be a coroutine - # function so bare MagicMock attrs don't trigger the path. - cls_direct = getattr(type(self._provider), "_fetch_from_db", None) - if cls_direct is not None and inspect.iscoroutinefunction(cls_direct): - inst_direct = getattr(self._provider, "_fetch_from_db", None) - if inspect.iscoroutinefunction(inst_direct): - return await inst_direct(conn) - return await cls_direct(self._provider, conn) - return await self._provider.force_refresh(conn) - - async def stop(self) -> None: - """Signal the task to exit and await its termination.""" self._stop_event.set() - if self._task is None: + if self._closed: return - if not self._task.done(): - self._task.cancel() + self._closed = True + task = self._task + self._task = None + if task is not None and not task.done(): + task.cancel() try: - await self._task + await task except (asyncio.CancelledError, Exception): pass - self._task = None + # _run's finally closes these when its task is cancelled, but a + # monitor that never started, or whose task has already exited, still + # owns a connection. + await self._drop_owned_connection() + if self._verified_writer_conn is not None: + await self._close_best_effort(self._verified_writer_conn) + self._verified_writer_conn = None + self._verified_writer_host_info = None + self._writer_found_event.clear() + self._release_loop() + if self.on_closed is not None: + on_closed, self.on_closed = self.on_closed, None + try: + on_closed() + except Exception: # noqa: BLE001 - deregistration is best-effort + pass + + def _release_loop(self) -> None: + """Drop everything that ties this monitor to its event loop. + + An asyncio.Event caches the loop it was first awaited on, so holding + the loop weakly is not enough on its own. + + Anyone parked on one of these is woken first. A caller inside + force_monitoring_refresh awaits the event object it read, so + replacing the attribute without setting it would leave that caller + waiting on an orphan until its own timeout expired. + """ + self._topology_updated.set() + self._writer_found_event.set() + self._request_tick.set() + self._loop_ref = None + self._loop_strong = None + self._stop_event = asyncio.Event() + self._request_tick = asyncio.Event() + self._topology_updated = asyncio.Event() + self._writer_found_event = asyncio.Event() + + @property + def can_dispose(self) -> bool: + """Whether the monitor may be disposed when its entry expires. + + Only the expiry path consults this. The stuck-monitor path removes + unconditionally, so a blocked caller is not protected by it. + """ + return self._in_flight_refreshes == 0 + + @property + def last_activity_ns(self) -> int: + return self._last_activity_ns + + def process_event(self, event: Any) -> None: + """Handle a blue/green MonitorResetEvent for this cluster. + + Events are delivered on the publisher's thread, so this hands the work + to the monitor's own loop and returns. + """ + from aws_advanced_python_wrapper.utils.events import MonitorResetEvent + if not isinstance(event, MonitorResetEvent): + return + if event.cluster_id != self._cluster_id: + return + self._reset_count += 1 + self._schedule(self._reset()) + + def _set_loop(self, loop: asyncio.AbstractEventLoop) -> None: + try: + self._loop_ref = weakref.ref(loop) + except TypeError: + self._loop_strong = loop + + def _get_loop(self) -> Optional[asyncio.AbstractEventLoop]: + if self._loop_strong is not None: + return self._loop_strong + return self._loop_ref() if self._loop_ref is not None else None + + def _schedule(self, coro: Awaitable[None]) -> bool: + """Run ``coro`` on the monitor's loop. False if there is no live loop.""" + loop = self._get_loop() + if loop is None or loop.is_closed(): + coro.close() # type: ignore[attr-defined] + return False + try: + if loop is asyncio.get_running_loop(): + loop.create_task(coro) # type: ignore[arg-type] + return True + except RuntimeError: + pass + try: + asyncio.run_coroutine_threadsafe(coro, loop) # type: ignore[arg-type] + return True + except RuntimeError: + coro.close() # type: ignore[attr-defined] + return False + + async def _reset(self) -> None: + """Drop everything tied to the pre-switchover cluster. + + Removes the stored topology too, so a switchover does not keep serving + the old host list. + """ + logger.debug( + "ClusterTopologyMonitor.ResetEventReceived", self._cluster_id) + pending = [t for t in self._probe_tasks.values() if not t.done()] + for task in pending: + task.cancel() + if pending: + await asyncio.gather(*pending, return_exceptions=True) + self._probe_tasks.clear() + self._submitted_host_aliases.clear() + await self._drop_owned_connection() + if self._verified_writer_conn is not None: + await self._close_best_effort(self._verified_writer_conn) + self._verified_writer_conn = None + self._verified_writer_host_info = None + self._writer_found_event.clear() + self._last_known_writer = None + self._last_topology = () + self._high_refresh_until_ns = 0 + topology_store.remove_topology(self._key) + # Wake the loop so it re-queries now rather than serving nothing for a + # full tick. + self._request_tick.set() def build_probe_host( diff --git a/aws_advanced_python_wrapper/aio/host_list_provider.py b/aws_advanced_python_wrapper/aio/host_list_provider.py index 38345699c..948473081 100644 --- a/aws_advanced_python_wrapper/aio/host_list_provider.py +++ b/aws_advanced_python_wrapper/aio/host_list_provider.py @@ -37,14 +37,19 @@ from __future__ import annotations import asyncio -from datetime import datetime -from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, - Optional, Protocol, Tuple, runtime_checkable) - -from aws_advanced_python_wrapper.errors import AwsWrapperError +from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, + Protocol, Tuple, runtime_checkable) + +from aws_advanced_python_wrapper.aio import topology_store +from aws_advanced_python_wrapper.aio.cleanup import (register_shutdown_hook, + unregister_shutdown_hook) +from aws_advanced_python_wrapper.aio.topology_utils import ( + AsyncAuroraTopologyUtils, AsyncGlobalAuroraTopologyUtils, + AsyncMultiAzTopologyUtils, AsyncTopologyUtils) from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.events import MonitorStopEvent from aws_advanced_python_wrapper.utils.log import Logger -from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.properties import WrapperProperties logger = Logger(__name__) @@ -52,6 +57,7 @@ if TYPE_CHECKING: from aws_advanced_python_wrapper.aio.driver_dialect.base import \ AsyncDriverDialect + from aws_advanced_python_wrapper.aio.topology_store import TopologyKey from aws_advanced_python_wrapper.database_dialect import DatabaseDialect from aws_advanced_python_wrapper.utils.properties import Properties @@ -59,23 +65,6 @@ Topology = Tuple[HostInfo, ...] -def _is_programming_error(ex: BaseException) -> bool: - """True when ``ex`` is a PEP-249 ``ProgrammingError`` (bad SQL / not an - Aurora cluster), regardless of which driver raised it. - - The async topology query runs on the raw driver connection, so the - exception is the driver's own ``ProgrammingError`` (psycopg / aiomysql) or - the wrapper's :class:`aws_advanced_python_wrapper.pep249.ProgrammingError`. - Match by class name across the MRO so all of them are recognized -- sync - catches ``pep249.ProgrammingError`` directly (host_list_provider.py:593). - """ - from aws_advanced_python_wrapper.pep249 import \ - ProgrammingError as WrapperProgrammingError - if isinstance(ex, WrapperProgrammingError): - return True - return any(cls.__name__ == "ProgrammingError" for cls in type(ex).__mro__) - - @runtime_checkable class AsyncHostListProvider(Protocol): """Async host list provider contract.""" @@ -172,29 +161,22 @@ async def stop(self) -> None: class AsyncAuroraHostListProvider: """Aurora topology discovery over an async driver connection. - Runs an Aurora-topology query (e.g., ``SELECT server_id, session_id - OPERATOR(pg_catalog.=) 'MASTER_SESSION_ID' AS is_writer, ... FROM - pg_catalog.aurora_replica_status()``) and returns a tuple of - :class:`HostInfo` objects. The exact SQL and parsing live on the shared sync - :class:`TopologyAwareDatabaseDialect` classes (reused rather than - duplicated). Note the schema qualification: every function and operator in a - PostgreSQL query the driver issues internally is pinned to ``pg_catalog`` so - the session's ``search_path`` cannot redirect it. - - Refresh flow (N.1b, matches sync RdsHostListProvider -> ClusterTopologyMonitor): - - * :meth:`refresh` / :meth:`force_refresh` delegate to a per-provider - :class:`AsyncClusterTopologyMonitor` so panic-mode probing - engages automatically on initial connect when writer discovery - stalls. The monitor also keeps a cached ``last_topology`` so - cache-hit refreshes don't hit the DB. - * The monitor itself calls :meth:`_fetch_from_db` (private, no - recursion) to run the actual SQL probe. - - Thread-safety: the cache is protected by an :class:`asyncio.Lock`. + The query and its row parsing live on an :class:`AsyncTopologyUtils`, so + the topology monitor can query the cluster without holding a provider. + Every function and operator in a PostgreSQL query the driver issues is + pinned to ``pg_catalog`` so the session's ``search_path`` cannot redirect + it. + + :meth:`refresh` returns the stored topology when there is one; + :meth:`force_refresh` goes through the cluster's topology monitor, so + panic-mode probing engages when writer discovery stalls on initial + connect. The monitor is shared per cluster and event loop, and the + topology it publishes lives in the storage service. """ _DEFAULT_REFRESH_RATE_NS = 30 * 1_000_000_000 # 30 seconds + _MONITOR_EXPIRATION_NS = 15 * 60 * 1_000_000_000 # 15 minutes + _MONITOR_INACTIVE_TIMEOUT_NS = 3 * 60 * 1_000_000_000 # 3 minutes def __init__( self, @@ -221,25 +203,42 @@ def __init__( cluster_id: Optional[str] = None, default_port: int = 5432, monitor_connection_factory: Optional[ - Callable[[], Awaitable[Any]]] = None) -> None: + Callable[[], Awaitable[Any]]] = None, + topology_utils: Optional[AsyncTopologyUtils] = None) -> None: self._props = props self._driver_dialect = driver_dialect - self._topology_query = topology_query self._default_port = default_port self._monitor_connection_factory = monitor_connection_factory self._cluster_id = cluster_id or self._derive_cluster_id(props) - self._topology_cache: Optional[Topology] = None - self._last_refresh_ns: int = 0 self._refresh_lock = asyncio.Lock() refresh_ms = WrapperProperties.TOPOLOGY_REFRESH_MS.get(props) self._refresh_ns: int = ( int(refresh_ms) * 1_000_000 if refresh_ms is not None else self._DEFAULT_REFRESH_RATE_NS ) - # Monitor wiring (N.1b). Lazy-created on first refresh so - # provider construction stays cheap and test-friendly. - self._monitor: Optional[Any] = None # AsyncClusterTopologyMonitor + # Owns this dialect's topology query and row parsing. Subclasses pass + # their own; the monitor is handed the same object so it can query the + # cluster without a provider. + self._topology_utils: AsyncTopologyUtils = ( + topology_utils if topology_utils is not None + else AsyncAuroraTopologyUtils(props, topology_query, default_port)) self._last_conn: Optional[Any] = None + + # produced_data_type is what links a topology read to this monitor: + # the monitor service turns a read of the stored topology into an + # expiration extension for the monitor that produces it. + from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor + self._monitor_service = services_container.get_monitor_service() + # The monitor stamps its activity once per tick, so the inactive + # timeout has to outlast a tick, and topology_refresh_ms is + # user-settable and can exceed the default on its own. + self._monitor_service.register_monitor_type( + AsyncClusterTopologyMonitor, + expiration_timeout_ns=self._MONITOR_EXPIRATION_NS, + inactive_timeout_ns=max(self._MONITOR_INACTIVE_TIMEOUT_NS, + 2 * self._refresh_ns), + produced_data_type=topology_store.StoredTopology) # Panic-mode probe: opens a pipeline connection to a host and # classifies its role, used by the monitor to discover the new # writer when the monitoring connection dies (mirrors sync @@ -260,52 +259,64 @@ def set_probe_host(self, probe_host: Callable[..., Any]) -> None: def reconfigure_topology_query( self, topology_query: str, default_port: Optional[int] = None) -> None: - """Re-point the provider at a (post-connect) resolved dialect's query. - - The provider is built BEFORE the connection exists, so an - instance-endpoint MySQL connection starts with the PostgreSQL-default - topology query + port (the ctor default). Once the database dialect is - resolved/upgraded to the Aurora MySQL dialect we swap in its topology - query and the MySQL port so discovery actually works. Clears the cache - so the next refresh re-probes with the new query (any cached PG-query - result is stale/empty). + """Re-point the provider at a resolved dialect's query. + + The provider is built before the connection exists, so an + instance-endpoint MySQL connection starts with the PostgreSQL default + query and port. Once the dialect is upgraded to Aurora MySQL the real + query and port are swapped in, and the stored topology is dropped + because anything the old query produced is stale or empty. """ - if topology_query: - self._topology_query = topology_query + self._topology_utils.reconfigure(topology_query, default_port) if default_port: self._default_port = default_port - self._topology_cache = None - self._last_refresh_ns = 0 + self._discard_stored_topology() @staticmethod def _derive_cluster_id(props: Properties) -> str: - # Only treat `cluster_id` as explicit when present in the props dict; - # WrapperProperties.CLUSTER_ID.get() returns the default '1' even - # when unset. - if WrapperProperties.CLUSTER_ID.name in props: - return str(props[WrapperProperties.CLUSTER_ID.name]) - host = props.get("host", "") - port = props.get("port", "") - return f"aurora:{host}:{port}" + """Identify the cluster this provider is talking to. + + The ``cluster_id`` property, which defaults to ``"1"``, as the + synchronous provider and the reference implementation both do. + Deriving one from the endpoint was tried and abandoned upstream. + + Connections sharing an id share a topology entry and a topology + monitor, so an application connecting to more than one cluster has to + set it per cluster. Without that, the second cluster reuses the + first's monitor -- and therefore the first's topology query and + monitoring credentials -- and a blue/green reset for either resets + both. + """ + return str(WrapperProperties.CLUSTER_ID.get(props) or "1") def get_cluster_id(self) -> str: return self._cluster_id + def _storage_key(self) -> Optional[TopologyKey]: + return topology_store.topology_key(self._cluster_id) + + def _get_stored_topology(self) -> Optional[Topology]: + return topology_store.get_topology(self._storage_key()) + + def _store_topology(self, topology: Topology) -> None: + topology_store.put_topology(self._storage_key(), topology) + + def _discard_stored_topology(self) -> None: + topology_store.remove_topology(self._storage_key()) + async def refresh(self, connection: Optional[Any] = None) -> Topology: - """Return cached topology if still fresh, else force a refresh. + """Return the stored topology if there is one, else force a refresh. - Matches sync :meth:`RdsHostListProvider.refresh` semantics: if the - cache is within the refresh window, short-circuit; otherwise - delegate to :meth:`force_refresh` which goes through the - cluster topology monitor (panic mode engages automatically on - initial connect when writer discovery stalls). + Matches sync :meth:`RdsHostListProvider.refresh`: a present entry is + returned and the topology monitor is what keeps it fresh. No second + freshness window here, on purpose -- the store already expires + entries. """ if connection is not None: self._last_conn = connection - now_ns = asyncio.get_running_loop().time() * 1_000_000_000 - if (self._topology_cache is not None - and now_ns - self._last_refresh_ns < self._refresh_ns): - return self._topology_cache + stored = self._get_stored_topology() + if stored: + return stored return await self.force_refresh(connection) async def force_refresh(self, connection: Optional[Any] = None) -> Topology: @@ -321,9 +332,7 @@ async def force_refresh(self, connection: Optional[Any] = None) -> Topology: self._last_conn = connection if connection is None: - if self._topology_cache is not None: - return self._topology_cache - return () + return self._get_stored_topology() or () async with self._refresh_lock: monitor = self._get_or_create_monitor() @@ -335,25 +344,8 @@ async def force_refresh(self, connection: Optional[Any] = None) -> Topology: connection, bypass_ignore_window=True) except Exception: # noqa: BLE001 - monitor failure return await self._fetch_and_cache(connection) - if topology: - self._topology_cache = topology - self._last_refresh_ns = int( - asyncio.get_running_loop().time() * 1_000_000_000 - ) - return topology or (self._topology_cache or ()) - - def adopt_topology(self, topology: Topology) -> None: - """Adopt a monitor-published NON-EMPTY topology into the cache. - - Called by ``AsyncClusterTopologyMonitor._publish_topology`` when a - background tick or a panic probe discovers fresh topology -- the async - analogue of sync's monitor publishing to the shared storage-service - cache (_update_topology_cache, cluster_topology_monitor.py:491-495).""" - if not topology: - return - self._topology_cache = topology - self._last_refresh_ns = int( - asyncio.get_running_loop().time() * 1_000_000_000) + self._store_topology(topology) + return topology or (self._get_stored_topology() or ()) async def force_monitoring_refresh( self, @@ -375,40 +367,63 @@ async def force_monitoring_refresh( return topology or () def _get_or_create_monitor(self) -> Optional[Any]: - """Lazy-construct the per-provider topology monitor. + """Get the cluster's topology monitor from the monitor service. + + One monitor serves every provider on the cluster and loop, so a + dialect upgrade or a second connection reuses it rather than starting + a second background task. - Returns ``None`` if monitor construction fails or if the - topology_query is absent (e.g., static/unsupported dialects). - Mirrors sync :meth:`RdsHostListProvider._get_or_create_monitor`. + No ``await`` between acquiring the monitor and re-checking it, on + purpose: ``run_if_absent``, ``is_running`` and the removal are all + synchronous, so nothing can interleave. Making this method async + would reopen that gap. """ - if self._monitor is not None and self._monitor.is_running(): - return self._monitor - if not self._topology_query: + key = self._storage_key() + if key is None or not self._topology_utils.topology_query: return None - try: - from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ - AsyncClusterTopologyMonitor - except Exception: # noqa: BLE001 - defensive import guard + from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor + + monitor_service = services_container.get_monitor_service() + monitor = monitor_service.run_if_absent( + AsyncClusterTopologyMonitor, key, + lambda: self._create_monitor(key)) + if monitor is None: return None + # The monitor service has no liveness check of its own, and + # compute_if_absent extends expiration on every hit, so a monitor + # whose loop has closed would be handed out until the stuck-monitor + # sweep removed it, while every blocking refresh waits for an update + # that can never arrive. + if not monitor.is_running(): + monitor_service.stop_and_remove_value( + AsyncClusterTopologyMonitor, monitor) + monitor = monitor_service.run_if_absent( + AsyncClusterTopologyMonitor, key, + lambda: self._create_monitor(key)) + return monitor + + def _create_monitor(self, key: TopologyKey) -> Any: + from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor high_refresh_ms = WrapperProperties.CLUSTER_TOPOLOGY_HIGH_REFRESH_RATE_MS.get_int( self._props) - # The background monitor must never query the shared app connection - # concurrently with the app -- driver connections can't service - # concurrent queries, so a background refresh there corrupts the app's - # in-flight query. When a dedicated monitoring connection factory is - # wired the monitor opens its own connection; when it isn't, hand it a - # getter that yields None so the background loop skips rather than - # falling back to the shared app connection. The foreground - # force_refresh path still refreshes on demand via the connection - # passed to it. + # The background loop must never query the shared application + # connection: driver connections cannot service concurrent queries, so + # a background refresh there corrupts the application's in-flight + # query. Without a dedicated monitoring connection the getter yields + # None and the loop skips, rather than falling back to the shared + # connection. Foreground force_refresh still refreshes on demand + # through the connection passed to it. if self._monitor_connection_factory is None: logger.warning( - "[AsyncAuroraHostListProvider] no dedicated monitoring " - "connection factory wired; background topology refresh disabled " - "to avoid racing the shared application connection.") + "AsyncAuroraHostListProvider.NoMonitoringConnectionFactory", + self._cluster_id) monitor = AsyncClusterTopologyMonitor( - provider=self, + topology_utils=self._topology_utils, + cluster_id=self._cluster_id, + key=key, connection_getter=( (lambda: self._last_conn) if self._monitor_connection_factory is not None @@ -420,250 +435,41 @@ def _get_or_create_monitor(self) -> Optional[Any]: connection_factory=self._monitor_connection_factory, ) monitor.start() - self._monitor = monitor - # Register monitor teardown with the global cleanup hook so - # release_resources_async() tears it down. - try: - from aws_advanced_python_wrapper.aio.cleanup import \ - register_shutdown_hook - register_shutdown_hook(monitor.stop) - except Exception: # noqa: BLE001 - pass - return monitor - async def _fetch_and_cache(self, connection: Any) -> Topology: - """Direct DB query + cache update, used as a monitor fallback.""" - rows = await self._run_topology_query(connection) - topology = self._rows_to_topology(rows) - if topology: - self._topology_cache = topology - self._last_refresh_ns = int( - asyncio.get_running_loop().time() * 1_000_000_000 - ) - return topology or (self._topology_cache or ()) - - async def _fetch_from_db(self, connection: Any) -> Topology: - """Raw DB-query path used BY the cluster topology monitor. - - Does NOT re-enter the monitor (which would recurse). The - monitor's ``_run`` / ``force_refresh_with_connection`` both - call this; all other callers should go through the public - :meth:`refresh` / :meth:`force_refresh`. - """ - rows = await self._run_topology_query(connection) - return self._rows_to_topology(rows) + # A shutdown hook as well as the monitor-service entry: + # release_resources() clears the cache, dropping the last reference + # before the teardown stop() scheduled could run, and + # release_resources_async only awaits registered hooks. + async def _close_and_unregister() -> None: + try: + await monitor.aclose() + finally: + unregister_shutdown_hook(_close_and_unregister) - async def _run_topology_query(self, connection: Any) -> List[tuple]: - """Execute the topology query and return its rows. + monitor.on_closed = _close_and_unregister + register_shutdown_hook(_close_and_unregister) + return monitor - Uses the driver's raw async cursor -- we bypass the plugin pipeline - here on purpose. Topology queries run in a tight loop; running them - through the full pipeline would double-count timing, trigger - failover-retry on every refresh, and prevent the topology monitor - from operating independently of app-level plugins. - """ - # The underlying connection is a raw async driver connection - # (psycopg.AsyncConnection at 3.0.0). It exposes a sync ``cursor()`` - # method that returns an async cursor. - try: - # ``connection.cursor()`` MUST stay inside the try. On a fully - # closed connection psycopg raises OperationalError('the connection - # is closed') from cursor() itself -- not just from execute(). If - # that escapes, force_refresh / _fetch_and_cache propagate it to the - # caller instead of falling back to the cached topology, which - # strands failover on the single seed host and yields a spurious - # FailoverFailedError (test_fail_from_reader_to_writer): the failover - # refreshes through the dead current connection, the probe raises - # rather than returning [], and the cached [writer, reader,...] - # topology is never consulted. - # Bind the ENTERED cursor: psycopg's ``cursor()`` returns the - # cursor directly, but aiomysql's returns a ``_ContextManager`` - # whose ``__aenter__`` yields the real cursor -- ``async with X - # as cur`` gets the right object for both. Using the bare - # ``_ContextManager`` (no ``as``) would call ``.execute`` on the - # manager and raise AttributeError on aiomysql, so every MySQL - # topology probe returned [] (failover then stranded on the seed). - async with connection.cursor() as cur: - await cur.execute(self._topology_query) - return list(await cur.fetchall()) - except Exception as ex: - # A ProgrammingError means the query itself is invalid (wrong SQL - # after a dialect mismatch, or not an Aurora cluster) -- surface it - # rather than silently degrading, matching sync - # AuroraTopologyUtils._query_for_topology (:593-594). - if _is_programming_error(ex): - raise AwsWrapperError( - Messages.get("RdsHostListProvider.InvalidQuery")) from ex - # Any OTHER failure (closed connection, timeout) should not raise - # into the caller; it sees an empty topology and falls back to the - # cache. Log so a transient probe failure stays distinguishable - # from a genuinely empty cluster. - logger.debug( - f"[AsyncAuroraHostListProvider] topology query failed; " - f"returning empty topology (caller falls back to cache): {ex}") - return [] - - def _rows_to_topology(self, rows: List[tuple]) -> Topology: - # The instance host pattern may carry an explicit ``:port`` (proxied - # test endpoints do); use it for every topology host. See - # :meth:`_resolve_instance_pattern`. - _, pattern_port = self._resolve_instance_pattern() - port = pattern_port if pattern_port is not None else self._default_port - # Dedup by resolved host (a row may repeat), matching sync - # AuroraTopologyUtils._process_query_results (:603-606). - host_map: Dict[str, HostInfo] = {} - for row in rows: - if not row: - continue - server_id = row[0] - is_writer = bool(row[1]) if len(row) > 1 else False - # The topology query may include LAST_UPDATE_TIMESTAMP as a 5th - # column (sync _create_host:527-528); it disambiguates multiple - # writer rows during a failover window. - last_update = row[4] if len(row) > 4 and isinstance(row[4], datetime) else None - host = self._host_from_server_id(server_id) - host_info = HostInfo( - host=host, - port=port, - role=HostRole.WRITER if is_writer else HostRole.READER, - last_update_time=last_update, - # Sync parity (create_host, host_list_provider.py:548-556): - # host_id is how identify_connection correlates a live - # connection back to its topology row. Without it, EVERY - # cluster-endpoint identification fails (EFM's - # _get_monitoring_host_info raises UnableToIdentifyConnection). - # The MultiAz and GlobalAurora async providers already set it. - host_id=str(server_id), - ) - host_info.add_alias(str(server_id)) - host_map[host] = host_info - - readers = [h for h in host_map.values() if h.role != HostRole.WRITER] - writers = [h for h in host_map.values() if h.role == HostRole.WRITER] - - if not host_map: - return () - # No writer => invalid topology. Return empty so callers fall back to - # the cached topology instead of acting on a readers-only host list - # (matches sync AuroraTopologyUtils._process_query_results and the - # async MultiAz/GlobalAurora providers). - if not writers: - # Caller falls back to the cached topology on the empty result. - logger.debug("RdsHostListProvider.InvalidTopology") - return () - if len(writers) == 1: - chosen_writer = writers[0] - else: - # More than one writer row: take the most-recently-updated writer as - # the current writer and ignore the rest -- sync parity - # (_process_query_results:621-625). Writers without a timestamp are - # only considered if none carry one. - timestamped = [w for w in writers if w.last_update_time is not None] - if timestamped: - timestamped.sort(reverse=True, key=lambda h: h.last_update_time or datetime.min) - chosen_writer = timestamped[0] - else: - chosen_writer = writers[0] - logger.debug( - "[AsyncAuroraHostListProvider] topology query returned multiple " - "writers; using the latest-updated one") - # Writer first, readers after (async convention). - return (chosen_writer, *readers) - - def _resolve_instance_pattern(self) -> Tuple[Optional[str], Optional[int]]: - """Resolve the instance host pattern and its explicit port (if any). - - Returns ``(host_pattern_with_'?', port)``; ``port`` is ``None`` when the - pattern carries no explicit ``:port`` suffix. - - Prefers the ``cluster_instance_host_pattern`` connection property; when - unset, auto-derives the pattern from the connection endpoint via - ``RdsUtils.get_rds_instance_host_pattern`` -- exactly what the sync - ``AuroraHostListProvider`` does (host_list_provider.py:459). - - The pattern may include a port -- proxied test endpoints use - ``?.:8666``. That port MUST be split out (mirroring sync - ``AuroraHostListProvider.__init__`` at host_list_provider.py:445-449): - otherwise it stays baked into the hostname (``.:8666``, - which doesn't resolve) while the connection uses the wrong default - port, so every failover/reader connect to a topology host fails and - writer failover is stranded (test_fail_from_reader_to_writer). - """ - user_pattern = WrapperProperties.CLUSTER_INSTANCE_HOST_PATTERN.get( - self._props - ) - pattern = user_pattern - if user_pattern and "?" not in user_pattern: - # The user explicitly set a pattern with no '?' placeholder -- - # reject it (sync _validate_host_pattern:470-473). - self._validate_host_pattern(user_pattern.split(":", 1)[0]) - if not (pattern and "?" in pattern): - from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils - derived = RdsUtils().get_rds_instance_host_pattern( - self._props.get("host", "") or "") - if derived and "?" in derived: - pattern = derived - if not (pattern and "?" in pattern): - return None, None - port: Optional[int] = None - if ":" in pattern: - pattern, _, port_str = pattern.rpartition(":") - try: - port = int(port_str) - except ValueError: - port = None - # Reject RDS Proxy / RDS Custom endpoints as instance host patterns - # (sync _validate_host_pattern:475-484). - self._validate_host_pattern(pattern) - return pattern, port - - def _validate_host_pattern(self, host: str) -> None: - """Reject invalid instance host patterns -- sync parity - (host_list_provider.py:469-484). An invalid pattern is a configuration - error and should fail loudly rather than silently yield no topology.""" - from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType - from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils - rds_utils = RdsUtils() - if not rds_utils.is_dns_pattern_valid(host): - logger.error("RdsHostListProvider.InvalidPattern") - raise AwsWrapperError(Messages.get("RdsHostListProvider.InvalidPattern")) - url_type = rds_utils.identify_rds_type(host) - if url_type == RdsUrlType.RDS_PROXY: - logger.error("RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSProxy") - raise AwsWrapperError( - Messages.get("RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSProxy")) - if url_type == RdsUrlType.RDS_CUSTOM_CLUSTER: - logger.error("RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSCustom") - raise AwsWrapperError( - Messages.get("RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSCustom")) - - def _host_from_server_id(self, server_id: str) -> str: - """Translate an Aurora server ID into a reachable host name. - - Builds ``.`` from the resolved instance host pattern - (see :meth:`_resolve_instance_pattern`). Falling back to the bare server - ID yields a non-resolvable name, so every reader/failover connect to a - topology host fails with "failed to resolve host ''". - """ - host_pattern, _ = self._resolve_instance_pattern() - if host_pattern: - return host_pattern.replace("?", server_id) - return server_id + async def _fetch_and_cache(self, connection: Any) -> Topology: + """Direct topology query plus a store update, used as a fallback.""" + topology = await self._topology_utils.query_for_topology(connection) + self._store_topology(topology) + return topology or (self._get_stored_topology() or ()) async def stop(self) -> None: - """Tear down the provider's background topology monitor. + """Stop the cluster's topology monitor. - Sync parity: sync ``RdsHostListProvider`` stops its monitor on release. - The async provider previously no-op'd here, leaking the monitor task - (it only stopped via the global cleanup hook). + Publishes MonitorStopEvent as sync ``stop_monitor`` does, so the + monitor service owns the disposal. The monitor is shared, so this + stops it for every provider on the cluster and loop. """ - monitor = self._monitor - self._monitor = None - if monitor is not None: - try: - await monitor.stop() - except Exception: # noqa: BLE001 - best-effort teardown - pass + from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor + key = self._storage_key() + if key is None: + return + services_container.get_event_publisher().publish( + MonitorStopEvent(monitor_type=AsyncClusterTopologyMonitor, key=key)) class AsyncMultiAzHostListProvider(AsyncAuroraHostListProvider): @@ -716,136 +522,27 @@ def __init__( cluster_id=cluster_id, default_port=default_port, monitor_connection_factory=monitor_connection_factory, + topology_utils=AsyncMultiAzTopologyUtils( + props=props, + topology_query=topology_query, + default_port=default_port, + writer_host_query=writer_host_query, + host_id_query=host_id_query, + writer_host_column_index=writer_host_column_index, + instance_template_host=instance_template_host), ) - self._writer_host_query = writer_host_query - self._host_id_query = host_id_query - # Column of ``writer_host_query``'s result row holding the writer's - # ID. PG's query returns a single column (index 0); MySQL's - # ``SHOW REPLICA STATUS`` carries the source host at column 39 -- - # matching sync ``MultiAzTopologyUtils`` / - # ``MultiAzClusterMysqlDialect._WRITER_HOST_COLUMN_INDEX``. - self._writer_host_column_index = writer_host_column_index - self._instance_template_host = instance_template_host - # Import locally to avoid widening the module's top-level import set. - from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils - self._rds_utils = RdsUtils() - self._writer_id: Optional[str] = None - - async def _run_topology_query(self, connection: Any) -> List[tuple]: - """Two-step MultiAz topology query. - - Step 1: ``writer_host_query``. Empty row => fall through to - ``host_id_query`` (we are the writer, MySQL-style). - Step 2: ``topology_query`` for the full host list. - - We stash the identified writer ID on ``self._writer_id`` so - :meth:`_rows_to_topology` can assign roles. A failure at any step - returns ``[]`` so callers fall back to cache, matching - :meth:`AsyncAuroraHostListProvider._run_topology_query`. - """ - try: - # Bind the ENTERED cursor (``as cur``) -- aiomysql's cursor() is a - # _ContextManager whose __aenter__ yields the real cursor; the bare - # manager has no ``.execute``. See AsyncAuroraHostListProvider. - async with connection.cursor() as cur: - # Step 1: writer host query. Empty row => we're the writer - # (MySQL), fall back to host_id_query. - await cur.execute(self._writer_host_query) - writer_row = await cur.fetchone() - if writer_row is not None: - writer_id = str(writer_row[self._writer_host_column_index]) - else: - await cur.execute(self._host_id_query) - self_row = await cur.fetchone() - if self_row is None: - return [] - writer_id = str(self_row[0]) - - # Step 2: topology query. - await cur.execute(self._topology_query) - rows = list(await cur.fetchall()) - - self._writer_id = writer_id - return rows - except Exception as ex: - # A ProgrammingError means the query itself is invalid -- surface it - # (sync MultiAzTopologyUtils._query_for_topology:659-660). Any other - # failure yields an empty topology so callers fall back to cache. - if _is_programming_error(ex): - raise AwsWrapperError( - Messages.get("RdsHostListProvider.InvalidQuery")) from ex - logger.debug( - f"[AsyncMultiAzHostListProvider] topology query failed; " - f"returning empty topology (caller falls back to cache): {ex}") - return [] - - def _rows_to_topology(self, rows: List[tuple]) -> Topology: - writer_id = self._writer_id - hosts: List[HostInfo] = [] - for row in rows: - if len(row) < 3: - continue - row_id = str(row[0]) - host = str(row[1]) - try: - port = int(row[2]) - except (TypeError, ValueError): - port = self._default_port - - role = HostRole.WRITER if row_id == writer_id else HostRole.READER - - # Optional instance-template substitution. Matches sync - # MultiAzTopologyUtils._create_multi_az_host. - if self._instance_template_host: - instance_name = self._rds_utils.get_instance_id(host) - if instance_name: - substituted = self._instance_template_host.replace( - "?", instance_name - ) - if ":" in substituted: - host_part, _, port_part = substituted.partition(":") - host = host_part - if port_part.isdigit(): - port = int(port_part) - else: - host = substituted - - host_info = HostInfo( - host=host, - port=port, - role=role, - host_id=row_id, - ) - host_info.add_alias(host) - hosts.append(host_info) - - # Validate: must have exactly one writer (sync MultiAz clears - # everything if no writer is found). - writers = [h for h in hosts if h.role == HostRole.WRITER] - if not writers: - return () - # Writer first, readers after -- matches AsyncAuroraHostListProvider. - hosts.sort(key=lambda h: 0 if h.role == HostRole.WRITER else 1) - return tuple(hosts) class AsyncGlobalAuroraHostListProvider(AsyncAuroraHostListProvider): - """Async Global Aurora topology provider. - - Subclasses :class:`AsyncAuroraHostListProvider` and overrides row - parsing to handle Global Aurora's cross-region topology. Row shape: - ``(server_id, region, is_writer)``. Each host is built from the - region-specific template configured via the ``instance_templates_by_region`` - ctor argument or the ``GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS`` property - (comma-separated ``region=pattern`` pairs, where ``pattern`` may include - a ``:port`` suffix). - - Minimal port -- sync's :class:`GlobalAuroraTopologyMonitor` thread - machinery is not mirrored; topology is fetched on-demand via the base - class's standard refresh path. Full auto-detection via ``DatabaseDialect`` - is a future enhancement (sync reads the topology query from - ``GlobalAuroraTopologyDialect`` -- that path does not yet flow through - the async ``PluginService`` dialect resolution chain). + """Async Aurora Global Database topology provider. + + An Aurora global database spans regions, so each host is built from the + template configured for its own region rather than this connection's DNS + suffix. Templates come from the ``instance_templates_by_region`` argument + or the ``global_cluster_instance_host_patterns`` property. + + A partial port: sync's GlobalAuroraTopologyMonitor thread machinery is not + mirrored, so topology is fetched through the normal refresh path. """ def __init__( @@ -867,90 +564,9 @@ def __init__( cluster_id=cluster_id, default_port=default_port, monitor_connection_factory=monitor_connection_factory, + topology_utils=AsyncGlobalAuroraTopologyUtils( + props=props, + topology_query=topology_query, + default_port=default_port, + instance_templates_by_region=instance_templates_by_region), ) - if instance_templates_by_region is None: - raw = WrapperProperties.GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.get( - props - ) - if raw: - instance_templates_by_region = self._parse_templates(raw) - else: - instance_templates_by_region = {} - self._templates_by_region: Dict[str, str] = instance_templates_by_region - - @staticmethod - def _parse_templates(raw: str) -> Dict[str, str]: - """Parse ``'region:host:port,region:host,...'`` into a dict. - - Same format as the sync ``GlobalAuroraTopologyUtils.parse_instance_templates`` - (``region:host:port`` or ``region:host``, comma-separated) so one - ``global_cluster_instance_host_patterns`` value works for both the - sync and async wrappers. A pair without a host raises, matching sync. - """ - result: Dict[str, str] = {} - for pair in raw.split(","): - pair = pair.strip() - if not pair: - continue - parts = pair.split(":", 2) - if len(parts) < 2 or not parts[0].strip() or not parts[1].strip(): - raise AwsWrapperError(Messages.get_formatted( - "GlobalAuroraTopologyUtils.invalidInstanceTemplate", pair)) - region = parts[0].strip() - pattern = parts[1].strip() - if len(parts) > 2 and parts[2].strip(): - pattern = f"{pattern}:{parts[2].strip()}" - result[region] = pattern - return result - - def _rows_to_topology(self, rows: List[tuple]) -> Topology: - """Override. Rows are ``(server_id, is_writer, lag, aws_region)`` — - the sync Global Aurora topology-query shape (``SERVER_ID``, - ``SESSION_ID``-derived writer flag, ``VISIBILITY_LAG_IN_MSEC``, - ``AWS_REGION``); the lag column is unused, matching sync. - - Each row's host is built from the region-specific template. Rows - referencing a region without a configured template are skipped. - Returns an empty tuple if no writer is present (matches - :class:`AsyncMultiAzHostListProvider`). - """ - hosts: List[HostInfo] = [] - for row in rows: - if len(row) < 4: - continue - server_id = str(row[0]) - is_writer = bool(row[1]) - region = str(row[3]) - template = self._templates_by_region.get(region) - if template is None: - # No template for this region -- skip the host. - continue - host_str = template.replace("?", server_id) - host = host_str - port = self._default_port - if ":" in host_str: - host_part, port_part = host_str.rsplit(":", 1) - try: - port = int(port_part) - host = host_part - except ValueError: - # Non-numeric port -- treat whole string as host. - pass - role = HostRole.WRITER if is_writer else HostRole.READER - host_info = HostInfo( - host=host, - port=port, - role=role, - host_id=server_id, - ) - host_info.add_alias(host) - hosts.append(host_info) - - # Validate: at least one writer. Match the MultiAz/sync convention - # of returning an empty topology when no writer is found so callers - # fall back to the cache. - if not any(h.role == HostRole.WRITER for h in hosts): - return () - # Writer first, readers after -- matches the other async providers. - hosts.sort(key=lambda h: 0 if h.role == HostRole.WRITER else 1) - return tuple(hosts) diff --git a/aws_advanced_python_wrapper/aio/topology_store.py b/aws_advanced_python_wrapper/aio/topology_store.py new file mode 100644 index 000000000..d323f7d17 --- /dev/null +++ b/aws_advanced_python_wrapper/aio/topology_store.py @@ -0,0 +1,128 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Shared access to the stored async topology. + +The host list provider and the topology monitor both read and write the +cluster's topology, and they key the storage service and the monitor service +the same way, so the key and the accessors live here rather than on either of +them. +""" + +from __future__ import annotations + +import asyncio +import copy +import threading +import weakref +from typing import Optional, Tuple +from uuid import uuid4 + +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.hostinfo import Topology as StoredTopology +from aws_advanced_python_wrapper.utils import services_container + +# The storage service is keyed by type, and the sync Topology alias is a +# forward reference, so an async-side alias is a different object. Only the +# sync alias is registered, so keying on anything else writes to an +# unregistered cache. + +TopologyKey = Tuple[str, str] + +_loop_tokens: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, str] = \ + weakref.WeakKeyDictionary() +# setdefault on a WeakKeyDictionary is not documented atomic, and two threads +# minting competing tokens for one loop would split its topology entries. +_loop_tokens_lock = threading.Lock() + + +def loop_token(loop: asyncio.AbstractEventLoop) -> str: + """A stable identity for ``loop``, for use in a storage or monitor key. + + Deliberately not ``id(loop)``: addresses are reused, so a fresh loop could + be handed a dead loop's entry, including HostInfo objects a previous run + marked unavailable. + """ + with _loop_tokens_lock: + try: + token = _loop_tokens.get(loop) + if token is None: + token = uuid4().hex + _loop_tokens[loop] = token + return token + except TypeError: + # Some accelerated loops (Cython extension types) are not + # weak-referenceable, and the lookup raises as readily as the + # assignment. Falling back to the address is only safe because + # every consumer re-checks liveness and replaces a dead entry, so + # a recycled address is detected rather than silently reused. + return f"id:{id(loop)}" + + +def topology_key(cluster_id: str) -> Optional[TopologyKey]: + """The key for this cluster's topology on the running event loop. + + Compound because the store is process-global and shared with the sync + provider, which keys by bare cluster id. ``None`` off-loop: the key names + a loop, so there is no entry to read or invalidate. + """ + try: + loop = asyncio.get_running_loop() + except RuntimeError: + return None + return (cluster_id, loop_token(loop)) + + +def get_topology( + key: Optional[TopologyKey]) -> Optional[StoredTopology]: + """Read the stored topology as fresh HostInfo objects. + + The entry is shared by every provider on this cluster and loop, and + availability is written into a HostInfo in place, so handing out the + stored objects would let one connection's availability marking rewrite + the hosts another connection is holding. + """ + if key is None: + return None + stored = services_container.get_storage_service().get(StoredTopology, key) + if stored is None: + return None + return tuple(_copy_host(host) for host in stored) + + +def _copy_host(host: HostInfo) -> HostInfo: + """Copy a host, restoring what ``HostInfo.__copy__`` drops. + + It carries neither the aliases, which match a live connection back to its + topology row, nor the availability strategy, which decides when a host + marked unavailable becomes usable again. + """ + clone = copy.copy(host) + clone.host_availability_strategy = host.host_availability_strategy + aliases = host.aliases + if aliases: + clone.add_alias(*aliases) + return clone + + +def put_topology(key: Optional[TopologyKey], topology: StoredTopology) -> None: + if key is None or not topology: + return + services_container.get_storage_service().put(StoredTopology, key, topology) + + +def remove_topology(key: Optional[TopologyKey]) -> None: + if key is None: + return + services_container.get_storage_service().remove(StoredTopology, key) diff --git a/aws_advanced_python_wrapper/aio/topology_utils.py b/aws_advanced_python_wrapper/aio/topology_utils.py new file mode 100644 index 000000000..94c7d11a8 --- /dev/null +++ b/aws_advanced_python_wrapper/aio/topology_utils.py @@ -0,0 +1,441 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Async topology queries and row parsing. + +The async counterparts of the synchronous ``TopologyUtils`` family. A +topology-utils object owns one dialect's topology SQL and the parsing of its +rows, so the topology monitor can query a cluster without holding a host list +provider. +""" + +from __future__ import annotations + +from abc import ABC, abstractmethod +from datetime import datetime +from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple + +from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole, Topology +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import WrapperProperties +from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType +from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.utils.properties import Properties + +logger = Logger(__name__) + + +def _is_programming_error(ex: BaseException) -> bool: + """True when ``ex`` is a PEP-249 ``ProgrammingError``. + + The topology query runs on the raw driver connection, so the exception is + the driver's own ``ProgrammingError`` (psycopg or aiomysql) rather than the + wrapper's. Match on the class name across the MRO so all of them are + recognised; sync catches ``pep249.ProgrammingError`` directly. + """ + from aws_advanced_python_wrapper.pep249 import \ + ProgrammingError as WrapperProgrammingError + if isinstance(ex, WrapperProgrammingError): + return True + return any(cls.__name__ == "ProgrammingError" for cls in type(ex).__mro__) + + +class AsyncTopologyUtils(ABC): + """Query a cluster's topology and turn the rows into hosts.""" + + def __init__( + self, + props: Properties, + topology_query: str, + default_port: int) -> None: + self._props = props + self._topology_query = topology_query + self._default_port = default_port + self._rds_utils = RdsUtils() + + self.initial_host_info: HostInfo = HostInfo( + host=str(props.get("host", "")), port=self._port_from_props(default_port)) + self.instance_template: Optional[HostInfo] = self._build_instance_template() + + def _port_from_props(self, default_port: int) -> int: + try: + return int(self._props["port"]) + except (KeyError, TypeError, ValueError): + return default_port + + @property + def topology_query(self) -> str: + return self._topology_query + + def reconfigure( + self, topology_query: str, default_port: Optional[int] = None) -> None: + """Swap in a resolved dialect's query after the connection exists. + + The utils are built from the dialect guessed off the endpoint, which + for a MySQL instance endpoint is PostgreSQL's query and port. + """ + if topology_query: + self._topology_query = topology_query + if default_port: + self._default_port = default_port + + async def query_for_topology(self, conn: Any) -> Topology: + """Query ``conn`` for the cluster topology. + + Returns an empty topology when the query fails for a reason that a + later attempt could recover from, so callers fall back to whatever is + already stored. An invalid query raises instead: that is a + configuration or dialect mismatch, not a transient failure. + """ + # cursor() is inside the try on purpose: on a closed connection + # psycopg raises from cursor() itself, not only from execute(). + try: + return await self._query_for_topology(conn) + except AwsWrapperError: + raise + except Exception as ex: + if _is_programming_error(ex): + raise AwsWrapperError( + Messages.get("RdsHostListProvider.InvalidQuery")) from ex + logger.debug( + "AsyncTopologyUtils.TopologyQueryFailed", type(self).__name__, ex) + return () + + @abstractmethod + async def _query_for_topology(self, conn: Any) -> Topology: + ... + + def create_host( + self, + host_id: str, + is_writer: bool, + last_update: Optional[datetime] = None, + port: Optional[int] = None) -> HostInfo: + host_info = HostInfo( + host=self._host_from_host_id(host_id), + port=port if port is not None else self._resolved_port(), + role=HostRole.WRITER if is_writer else HostRole.READER, + last_update_time=last_update, + # host_id is how identify_connection correlates a live connection + # back to its topology row; without it every cluster-endpoint + # identification fails. + host_id=str(host_id)) + host_info.add_alias(str(host_id)) + return host_info + + def _resolved_port(self) -> int: + """The port topology hosts should use. + + An instance template may carry an explicit ``:port`` -- proxied test + endpoints use ``?.:8666`` -- and that port applies to every + host in the topology. Otherwise the connection's own port, which is + what sync uses: a cluster reached on a non-default port has hosts on + that port, not on the dialect default. + """ + template = self.instance_template + if template is not None and template.is_port_specified(): + return template.port + if self.initial_host_info.is_port_specified(): + return self.initial_host_info.port + return self._default_port + + def _host_from_host_id(self, host_id: str) -> str: + """Turn an instance id into a reachable host name. + + Falling back to the bare id would yield a name that does not resolve, + so every reader and failover connect to a topology host would fail. + """ + template = self.instance_template + if template is not None and "?" in template.host: + return template.host.replace("?", str(host_id)) + return str(host_id) + + def _build_instance_template(self) -> Optional[HostInfo]: + """Resolve the instance host pattern once, as sync does on init. + + Prefers ``cluster_instance_host_pattern``; otherwise derives the + pattern from the connection endpoint. + """ + pattern = WrapperProperties.CLUSTER_INSTANCE_HOST_PATTERN.get(self._props) + if pattern and "?" not in pattern: + # An explicit pattern with no '?' placeholder is a configuration + # error; report it rather than quietly deriving a different one. + self._validate_host_pattern(pattern.split(":", 1)[0]) + if not (pattern and "?" in pattern): + derived = self._rds_utils.get_rds_instance_host_pattern( + str(self._props.get("host", ""))) + pattern = derived if derived and "?" in derived else None + if not pattern: + return None + + port = HostInfo.NO_PORT + if ":" in pattern: + pattern, _, port_str = pattern.rpartition(":") + try: + port = int(port_str) + except ValueError: + port = HostInfo.NO_PORT + self._validate_host_pattern(pattern) + return HostInfo(host=pattern, port=port) + + def _validate_host_pattern(self, host: str) -> None: + if not self._rds_utils.is_dns_pattern_valid(host): + logger.error("RdsHostListProvider.InvalidPattern") + raise AwsWrapperError(Messages.get("RdsHostListProvider.InvalidPattern")) + url_type = self._rds_utils.identify_rds_type(host) + if url_type == RdsUrlType.RDS_PROXY: + logger.error("RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSProxy") + raise AwsWrapperError(Messages.get( + "RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSProxy")) + if url_type == RdsUrlType.RDS_CUSTOM_CLUSTER: + logger.error("RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSCustom") + raise AwsWrapperError(Messages.get( + "RdsHostListProvider.ClusterInstanceHostPatternNotSupportedForRDSCustom")) + + @staticmethod + async def _fetch_all(conn: Any, query: str) -> List[tuple]: + """Run ``query`` on the raw driver connection and return its rows. + + The plugin pipeline is bypassed on purpose: topology queries run in a + tight loop, and routing them through it would trigger failover retry + on every refresh. + """ + async with conn.cursor() as cur: + await cur.execute(query) + return list(await cur.fetchall()) + + +class AsyncAuroraTopologyUtils(AsyncTopologyUtils): + """Aurora topology from ``aurora_replica_status``.""" + + async def _query_for_topology(self, conn: Any) -> Topology: + rows = await self._fetch_all(conn, self._topology_query) + return self._process_query_results(rows) + + def _process_query_results(self, rows: List[tuple]) -> Topology: + hosts_by_host: Dict[str, HostInfo] = {} + for row in rows: + if not row: + continue + host_id = row[0] + is_writer = bool(row[1]) if len(row) > 1 else False + # LAST_UPDATE_TIMESTAMP may arrive as a fifth column; it + # disambiguates multiple writer rows during a failover window. + last_update = (row[4] if len(row) > 4 and isinstance(row[4], datetime) + else None) + host_info = self.create_host(host_id, is_writer, last_update) + hosts_by_host[host_info.host] = host_info + + if not hosts_by_host: + return () + writers = [h for h in hosts_by_host.values() if h.role == HostRole.WRITER] + readers = [h for h in hosts_by_host.values() if h.role != HostRole.WRITER] + if not writers: + # A readers-only list is an invalid topology. Return empty so the + # caller keeps using what is already stored. + logger.debug("RdsHostListProvider.InvalidTopology") + return () + return (self._verify_writer(writers), *readers) + + @staticmethod + def _verify_writer(writers: List[HostInfo]) -> HostInfo: + """Pick the current writer when the query reports more than one. + + During a failover window several rows can claim the writer role; the + most recently updated one wins. Rows without a timestamp are only + considered when none carry one. + """ + if len(writers) == 1: + return writers[0] + timestamped = [w for w in writers if w.last_update_time is not None] + logger.debug("AsyncTopologyUtils.MultipleWriters", len(writers)) + if timestamped: + timestamped.sort(reverse=True, + key=lambda h: h.last_update_time or datetime.min) + return timestamped[0] + return writers[0] + + +class AsyncMultiAzTopologyUtils(AsyncTopologyUtils): + """RDS Multi-AZ DB cluster topology. + + Two steps, matching sync: the writer host query names the writer, then the + topology query returns ``(id, host, port)`` rows. An empty writer row means + this connection is the writer (MySQL), so its own id is queried instead. + """ + + def __init__( + self, + props: Properties, + topology_query: str, + default_port: int, + writer_host_query: str, + host_id_query: str, + writer_host_column_index: int = 0, + instance_template_host: Optional[str] = None) -> None: + super().__init__(props, topology_query, default_port) + self._writer_host_query = writer_host_query + self._host_id_query = host_id_query + # The PG writer query returns a single column; MySQL's SHOW REPLICA + # STATUS carries the source host at column 39. + self._writer_host_column_index = writer_host_column_index + self._instance_template_host = instance_template_host + + async def _query_for_topology(self, conn: Any) -> Topology: + async with conn.cursor() as cur: + await cur.execute(self._writer_host_query) + writer_row = await cur.fetchone() + if writer_row is not None: + writer_id = str(writer_row[self._writer_host_column_index]) + else: + await cur.execute(self._host_id_query) + self_row = await cur.fetchone() + if self_row is None: + return () + writer_id = str(self_row[0]) + + await cur.execute(self._topology_query) + rows = list(await cur.fetchall()) + return self._process_multi_az_query_results(rows, writer_id) + + def _process_multi_az_query_results( + self, rows: List[tuple], writer_id: str) -> Topology: + hosts: List[HostInfo] = [] + for row in rows: + if len(row) < 3: + continue + row_id = str(row[0]) + host = str(row[1]) + try: + port = int(row[2]) + except (TypeError, ValueError): + port = self._default_port + + if self._instance_template_host: + host, port = self._apply_instance_template(host, port) + + host_info = HostInfo( + host=host, + port=port, + role=HostRole.WRITER if row_id == writer_id else HostRole.READER, + host_id=row_id) + host_info.add_alias(host) + hosts.append(host_info) + + if not any(h.role == HostRole.WRITER for h in hosts): + return () + hosts.sort(key=lambda h: 0 if h.role == HostRole.WRITER else 1) + return tuple(hosts) + + def _apply_instance_template(self, host: str, port: int) -> Tuple[str, int]: + instance_id = self._rds_utils.get_instance_id(host) + if not instance_id or not self._instance_template_host: + return host, port + substituted = self._instance_template_host.replace("?", instance_id) + if ":" in substituted: + host_part, _, port_part = substituted.partition(":") + return host_part, int(port_part) if port_part.isdigit() else port + return substituted, port + + +class AsyncGlobalAuroraTopologyUtils(AsyncTopologyUtils): + """Aurora Global Database topology, which spans regions. + + Rows are ``(server_id, is_writer, lag, aws_region)``. Each host is built + from the template configured for its region, because an instance in another + region does not share this connection's DNS suffix. + """ + + def __init__( + self, + props: Properties, + topology_query: str, + default_port: int, + instance_templates_by_region: Optional[Dict[str, str]] = None) -> None: + super().__init__(props, topology_query, default_port) + if instance_templates_by_region is None: + raw = WrapperProperties.GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.get(props) + instance_templates_by_region = ( + self.parse_instance_templates(raw) if raw else {}) + self._templates_by_region: Dict[str, str] = instance_templates_by_region + + @staticmethod + def parse_instance_templates(raw: str) -> Dict[str, str]: + """Parse ``region:host[:port],…`` into a mapping. + + Same format the sync provider accepts, so one + ``global_cluster_instance_host_patterns`` value works for both. A pair + without a host raises, as sync does. + """ + result: Dict[str, str] = {} + for pair in raw.split(","): + pair = pair.strip() + if not pair: + continue + parts = pair.split(":", 2) + if len(parts) < 2 or not parts[0].strip() or not parts[1].strip(): + raise AwsWrapperError(Messages.get_formatted( + "GlobalAuroraTopologyUtils.invalidInstanceTemplate", pair)) + template = parts[1].strip() + if len(parts) > 2 and parts[2].strip(): + template = f"{template}:{parts[2].strip()}" + result[parts[0].strip()] = template + return result + + async def _query_for_topology(self, conn: Any) -> Topology: + rows = await self._fetch_all(conn, self._topology_query) + return self._process_global_query_results(rows) + + def _process_global_query_results(self, rows: List[tuple]) -> Topology: + hosts: List[HostInfo] = [] + for row in rows: + if len(row) < 4: + continue + server_id = str(row[0]) + is_writer = bool(row[1]) + region = str(row[3]) + template = self._templates_by_region.get(region) + if not template: + logger.debug( + "AsyncTopologyUtils.NoTemplateForRegion", server_id, region) + continue + host, port = self._host_from_template(template, server_id) + host_info = HostInfo( + host=host, + port=port, + role=HostRole.WRITER if is_writer else HostRole.READER, + host_id=server_id) + host_info.add_alias(host) + hosts.append(host_info) + + writers = [h for h in hosts if h.role == HostRole.WRITER] + if not writers: + return () + readers = [h for h in hosts if h.role != HostRole.WRITER] + return (AsyncAuroraTopologyUtils._verify_writer(writers), *readers) + + def _host_from_template(self, template: str, server_id: str) -> Tuple[str, int]: + host = template.replace("?", server_id) + if ":" in host: + host_part, _, port_part = host.rpartition(":") + try: + return host_part, int(port_part) + except ValueError: + # A non-numeric suffix is not a port; keep the whole string. + return host, self._default_port + return host, self._default_port diff --git a/aws_advanced_python_wrapper/cluster_topology_monitor.py b/aws_advanced_python_wrapper/cluster_topology_monitor.py index 26b466a47..ae3df67ab 100644 --- a/aws_advanced_python_wrapper/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/cluster_topology_monitor.py @@ -217,9 +217,8 @@ def _wait_till_topology_gets_updated(self, timeout_sec: float) -> Topology: self._cluster_id, timeout_sec * 1000)) def _get_stored_hosts(self) -> Topology: - # Not a data access: this monitor produces the topology it is reading, - # and a data access extends the producing monitor's expiration, so - # registering one here would make the monitor keep itself alive. + # This monitor produces the topology it is reading, so registering an + # access would make it renew its own expiration. hosts = services_container.get_storage_service().get( Topology, self._cluster_id, register_data_access=False) if hosts is None: diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 911056ccf..b64adb514 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -34,7 +34,12 @@ AdfsCredentialsProviderFactory.SignOnPagePostActionUrl=[AdfsCredentialsProviderF AdfsCredentialsProviderFactory.SignOnPagePostActionRequestFailed=[AdfsCredentialsProviderFactory] ADFS SignOn Page POST action failed with HTTP status '{}', reason phrase '{}', and response '{}' AdfsCredentialsProviderFactory.SignOnPageUrl=[AdfsCredentialsProviderFactory] ADFS SignOn URL: '{}' +AsyncAuroraHostListProvider.NoMonitoringConnectionFactory=[AsyncAuroraHostListProvider, clusterId: '{}'] No monitoring connection is available, so background topology refresh is disabled. Topology is still refreshed on demand. +AsyncClusterTopologyMonitor.StopWithoutLoop=[AsyncClusterTopologyMonitor, clusterId: '{}'] The monitor was asked to stop after its event loop closed; its monitoring connection could not be closed. AsyncPluginService.HostListProviderNotSet=[AsyncPluginService] Host list provider is not set. Ensure AsyncAwsWrapperConnection.connect has populated it before calling refresh. +AsyncTopologyUtils.MultipleWriters=[AsyncTopologyUtils] The topology query returned {} writers; using the most recently updated one. +AsyncTopologyUtils.NoTemplateForRegion=[AsyncTopologyUtils] Skipping instance '{}': no instance template is configured for region '{}'. Set 'global_cluster_instance_host_patterns' to include this region. +AsyncTopologyUtils.TopologyQueryFailed=[{}] The topology query failed; the previously stored topology will be used: {} AwsSdk.UnsupportedRegion=[AwsSdk] Unsupported AWS region {}. Please check AWS documentation for supported AWS regions. diff --git a/aws_advanced_python_wrapper/utils/monitor_service.py b/aws_advanced_python_wrapper/utils/monitor_service.py index 2a7006dfa..33a0db5de 100644 --- a/aws_advanced_python_wrapper/utils/monitor_service.py +++ b/aws_advanced_python_wrapper/utils/monitor_service.py @@ -141,6 +141,19 @@ def stop_and_remove(self, monitor_type: type, key: Any) -> None: if monitor is not None: _CacheContainer._dispose(monitor) + def stop_and_remove_value(self, monitor_type: type, monitor: Any) -> None: + """Remove and dispose this exact monitor, whatever key it sits under. + + Use this instead of stop_and_remove when the caller holds the monitor + it means: removing by key would dispose whatever is at the key now, + which may be a replacement another caller is already using. + """ + container = self._monitor_caches.get(monitor_type) + if container is None: + return + if container.cache.detach_value(monitor): + _CacheContainer._dispose(monitor) + def stop_and_remove_all(self, monitor_type: type) -> None: container = self._monitor_caches.get(monitor_type) if container is not None: diff --git a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py index 304140639..6c89aeea6 100644 --- a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py +++ b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py @@ -89,8 +89,7 @@ def remove_expired_if(self, key: K, predicate: Callable[[V], bool]) -> Optional[ def detach_value(self, value: V) -> bool: for key, entry in self._cache.items(): if entry.item is value: - self._cache.remove(key) - return True + return self._cache.remove(key) is not None return False def items(self) -> List[Tuple[K, V]]: diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 80cdb2dbc..95a1ae254 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -29,6 +29,10 @@ def pytest_runtest_setup(item): services_container.get_storage_service().clear_all() + # Monitors are keyed partly by event loop, and each test gets a new + # loop whose identity can be recycled, so a monitor from the previous + # test would otherwise be handed to this one. + services_container.get_monitor_service().stop_all() PluginServiceImpl._host_availability_expiring_cache.clear() AsyncPluginServiceImpl._host_availability_expiring_cache.clear() DatabaseDialectManager._known_endpoint_dialects.clear() diff --git a/tests/unit/test_aio_global_aurora_host_list_provider.py b/tests/unit/test_aio_global_aurora_host_list_provider.py index 867d5e3f7..2bb693856 100644 --- a/tests/unit/test_aio_global_aurora_host_list_provider.py +++ b/tests/unit/test_aio_global_aurora_host_list_provider.py @@ -31,6 +31,8 @@ from aws_advanced_python_wrapper.aio.host_list_provider import \ AsyncGlobalAuroraHostListProvider +from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncGlobalAuroraTopologyUtils from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.hostinfo import HostRole from aws_advanced_python_wrapper.utils.properties import Properties @@ -59,7 +61,7 @@ def _make_provider(**overrides: Any) -> AsyncGlobalAuroraHostListProvider: return AsyncGlobalAuroraHostListProvider(**kwargs) -# ---- _parse_templates ---------------------------------------------------- +# ---- parse_instance_templates ---------------------------------------------------- def test_parse_templates_colon_format_pairs(): @@ -70,7 +72,7 @@ def test_parse_templates_colon_format_pairs(): "us-east-1:?.xyz.us-east-1.rds.amazonaws.com:5432," " us-west-2 : ?.abc.us-west-2.rds.amazonaws.com , " ) - parsed = AsyncGlobalAuroraHostListProvider._parse_templates(raw) + parsed = AsyncGlobalAuroraTopologyUtils.parse_instance_templates(raw) assert parsed == { "us-east-1": "?.xyz.us-east-1.rds.amazonaws.com:5432", "us-west-2": "?.abc.us-west-2.rds.amazonaws.com", @@ -81,11 +83,11 @@ def test_parse_templates_malformed_entry_raises(): """An entry without a host part raises, matching sync ``GlobalAuroraTopologyUtils.parse_instance_templates``.""" with pytest.raises(AwsWrapperError): - AsyncGlobalAuroraHostListProvider._parse_templates( + AsyncGlobalAuroraTopologyUtils.parse_instance_templates( "us-east-1:?.xyz.us-east-1.rds.amazonaws.com:5432,bad-entry-no-colon") -# ---- _rows_to_topology --------------------------------------------------- +# ---- _process_global_query_results --------------------------------------------------- def test_empty_templates_returns_empty_topology(): @@ -95,7 +97,7 @@ def test_empty_templates_returns_empty_topology(): ("instance-1", True, 0.0, "us-east-1"), ("instance-2", False, 12.5, "us-west-2"), ] - assert prov._rows_to_topology(rows) == () + assert prov._topology_utils._process_global_query_results(rows) == () def test_region_without_matching_template_skipped(): @@ -113,7 +115,7 @@ def test_region_without_matching_template_skipped(): ("instance-1", True, 0.0, "us-east-1"), ("instance-2", False, 12.5, "us-west-2"), # skipped ] - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_global_query_results(rows) assert len(topo) == 1 assert topo[0].host == "instance-1.xyz.us-east-1.rds.amazonaws.com" assert topo[0].port == 5432 @@ -128,7 +130,7 @@ def test_template_substitution_with_port(): }, ) rows = [("my-instance", True, 0.0, "us-east-1")] - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_global_query_results(rows) assert len(topo) == 1 assert topo[0].host == "my-instance.xyz.us-east-1.rds.amazonaws.com" assert topo[0].port == 6000 @@ -144,7 +146,7 @@ def test_template_substitution_without_port_uses_default_port(): }, ) rows = [("my-instance", True, 0.0, "us-east-1")] - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_global_query_results(rows) assert len(topo) == 1 assert topo[0].host == "my-instance.xyz.us-east-1.rds.amazonaws.com" assert topo[0].port == 5433 @@ -164,7 +166,7 @@ def test_writer_and_reader_roles_assigned_from_is_writer_column(): ("writer-a", True, 0.0, "us-east-1"), ("reader-b", False, 31.0, "us-west-2"), ] - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_global_query_results(rows) assert len(topo) == 3 # Writer first. assert topo[0].role == HostRole.WRITER @@ -186,7 +188,7 @@ def test_short_rows_are_skipped(): ("legacy-row", "us-east-1", True), # old 3-col shape: skipped ("writer-a", True, 0.0, "us-east-1"), ] - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_global_query_results(rows) assert [h.host_id for h in topo] == ["writer-a"] @@ -202,7 +204,7 @@ def test_rows_without_writer_return_empty_tuple(): ("reader-a", False, 10.0, "us-east-1"), ("reader-b", False, 20.0, "us-east-1"), ] - assert prov._rows_to_topology(rows) == () + assert prov._topology_utils._process_global_query_results(rows) == () # ---- Property-based construction ---------------------------------------- @@ -212,7 +214,7 @@ def test_construction_from_property_parses_patterns(): """When ``instance_templates_by_region`` is omitted, the provider reads ``GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS`` from props (sync ``region:host:port`` format) and parses it. Subsequent - ``_rows_to_topology`` calls use that map.""" + row parsing uses that map.""" patterns = ( "us-east-1:?.xyz.us-east-1.rds.amazonaws.com:5432," "us-west-2:?.abc.us-west-2.rds.amazonaws.com:5432" @@ -224,7 +226,7 @@ def test_construction_from_property_parses_patterns(): ("instance-1", True, 0.0, "us-east-1"), ("instance-2", False, 15.0, "us-west-2"), ] - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_global_query_results(rows) assert len(topo) == 2 assert topo[0].role == HostRole.WRITER assert topo[0].host == "instance-1.xyz.us-east-1.rds.amazonaws.com" diff --git a/tests/unit/test_aio_host_list_provider.py b/tests/unit/test_aio_host_list_provider.py index 8cf91b0b2..23c6451e7 100644 --- a/tests/unit/test_aio_host_list_provider.py +++ b/tests/unit/test_aio_host_list_provider.py @@ -24,16 +24,33 @@ import pytest +from aws_advanced_python_wrapper.aio import topology_store from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ AsyncClusterTopologyMonitor from aws_advanced_python_wrapper.aio.host_list_provider import ( AsyncAuroraHostListProvider, AsyncHostListProvider, AsyncStaticHostListProvider) +from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncAuroraTopologyUtils from aws_advanced_python_wrapper.errors import AwsWrapperError -from aws_advanced_python_wrapper.hostinfo import HostRole +from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.properties import Properties +def _stub_utils() -> AsyncAuroraTopologyUtils: + """Topology utils for monitor tests. + + The monitor's only collaborator is query_for_topology, so a real utils + object with that one method stubbed is all it needs. + """ + utils = AsyncAuroraTopologyUtils( + Properties({"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"}), + "SELECT 1", 5432) + utils.query_for_topology = AsyncMock(return_value=()) # type: ignore[method-assign] + return utils + + def _build_error_cursor(exc: BaseException) -> MagicMock: cur = MagicMock() cur.execute = AsyncMock(side_effect=exc) @@ -125,11 +142,17 @@ def test_static_provider_implements_protocol(): # ---- Aurora provider tests --------------------------------------------- -def test_aurora_provider_cluster_id_uses_host_port_when_no_explicit_id(): - prov = AsyncAuroraHostListProvider(_props(), driver_dialect=MagicMock()) - cid = prov.get_cluster_id() - assert "aurora:" in cid - assert "cluster-xyz" in cid +def test_cluster_id_defaults_to_one_whatever_the_endpoint(): + """The property value, defaulting to "1", as sync does. Nothing is + derived from the endpoint, so every endpoint form gives the same id and an + application on more than one cluster must set cluster_id per cluster.""" + for host in ("mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "mydb.cluster-ro-abc123.us-east-2.rds.amazonaws.com", + "mydb-instance-1.abc123.us-east-2.rds.amazonaws.com", + "10.0.0.5"): + prov = AsyncAuroraHostListProvider( + _props(host=host), driver_dialect=MagicMock()) + assert prov.get_cluster_id() == "1", host def test_aurora_provider_cluster_id_uses_explicit_cluster_id_prop(): @@ -148,7 +171,7 @@ def test_host_from_server_id_auto_derives_instance_fqdn_from_cluster_endpoint(): prov = AsyncAuroraHostListProvider( _props(host="mydb.cluster-abc123.us-east-2.rds.amazonaws.com"), driver_dialect=MagicMock()) - assert (prov._host_from_server_id("test-pg-x-2") + assert (prov._topology_utils._host_from_host_id("test-pg-x-2") == "test-pg-x-2.abc123.us-east-2.rds.amazonaws.com") @@ -156,7 +179,7 @@ def test_host_from_server_id_uses_explicit_pattern_when_set(): prov = AsyncAuroraHostListProvider( _props(cluster_instance_host_pattern="?.custom.example.com"), driver_dialect=MagicMock()) - assert prov._host_from_server_id("inst-1") == "inst-1.custom.example.com" + assert prov._topology_utils._host_from_host_id("inst-1") == "inst-1.custom.example.com" def test_host_from_server_id_strips_port_suffix_from_pattern(): @@ -168,11 +191,12 @@ def test_host_from_server_id_strips_port_suffix_from_pattern(): prov = AsyncAuroraHostListProvider( _props(cluster_instance_host_pattern="?.cvqiy8.us-east-2.rds.amazonaws.com.proxied:8666"), driver_dialect=MagicMock()) - assert (prov._host_from_server_id("inst-1") + assert (prov._topology_utils._host_from_host_id("inst-1") == "inst-1.cvqiy8.us-east-2.rds.amazonaws.com.proxied") - host_pattern, port = prov._resolve_instance_pattern() - assert host_pattern == "?.cvqiy8.us-east-2.rds.amazonaws.com.proxied" - assert port == 8666 + template = prov._topology_utils.instance_template + assert template is not None + assert template.host == "?.cvqiy8.us-east-2.rds.amazonaws.com.proxied" + assert template.port == 8666 def test_topology_hosts_use_pattern_port_and_clean_host(): @@ -260,7 +284,7 @@ def test_topology_multiple_writers_picks_latest_updated_writer(): ("r-1", False, 0, 0, newer), ] prov = _aurora() - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_query_results(rows) writers = [h for h in topo if h.role == HostRole.WRITER] readers = [h for h in topo if h.role == HostRole.READER] @@ -274,7 +298,7 @@ def test_topology_multiple_writers_picks_latest_updated_writer(): def test_topology_multiple_writers_without_timestamps_keeps_one(): rows = [("w-a", True), ("w-b", True), ("r-1", False)] prov = _aurora() - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_query_results(rows) writers = [h for h in topo if h.role == HostRole.WRITER] assert len(writers) == 1 @@ -290,7 +314,7 @@ def test_topology_rows_carry_host_id_and_instance_alias(): already did both.""" rows = [("w-1", True), ("r-1", False)] prov = _aurora() - topo = prov._rows_to_topology(rows) + topo = prov._topology_utils._process_query_results(rows) assert {h.host_id for h in topo} == {"w-1", "r-1"} for h in topo: assert h.host_id in h.as_aliases() @@ -301,7 +325,7 @@ async def _body() -> None: prov = _aurora() conn = _build_error_conn(ProgrammingError("bad topology sql")) with pytest.raises(AwsWrapperError, match="Aurora"): - await prov._run_topology_query(conn) + await prov._topology_utils.query_for_topology(conn) asyncio.run(_body()) @@ -311,57 +335,61 @@ async def _body() -> None: prov = _aurora() conn = _build_error_conn(RuntimeError("connection closed")) # Non-ProgrammingError failures fall back to an empty topology (cache). - assert await prov._run_topology_query(conn) == [] + assert await prov._topology_utils.query_for_topology(conn) == () asyncio.run(_body()) -# ---- _validate_host_pattern (sync parity) ----------------------------- +# ---- host pattern validation, at construction as sync does ----------------------------- def test_validate_rejects_pattern_without_placeholder(): - prov = AsyncAuroraHostListProvider( - _props(cluster_instance_host_pattern="no-placeholder.example.com"), - driver_dialect=MagicMock()) with pytest.raises(AwsWrapperError, match="must contain"): - prov._resolve_instance_pattern() + AsyncAuroraHostListProvider( + _props(cluster_instance_host_pattern="no-placeholder.example.com"), + driver_dialect=MagicMock()) def test_validate_rejects_rds_proxy_pattern(): - prov = AsyncAuroraHostListProvider( - _props(cluster_instance_host_pattern="?.proxy-abc123.us-east-1.rds.amazonaws.com"), - driver_dialect=MagicMock()) with pytest.raises(AwsWrapperError, match="RDS Proxy"): - prov._resolve_instance_pattern() + AsyncAuroraHostListProvider( + _props(cluster_instance_host_pattern="?.proxy-abc123.us-east-1.rds.amazonaws.com"), + driver_dialect=MagicMock()) def test_validate_rejects_rds_custom_pattern(): - prov = AsyncAuroraHostListProvider( - _props(cluster_instance_host_pattern="?.cluster-custom-abc123.us-east-1.rds.amazonaws.com"), - driver_dialect=MagicMock()) with pytest.raises(AwsWrapperError, match="RDS Custom"): - prov._resolve_instance_pattern() + AsyncAuroraHostListProvider( + _props(cluster_instance_host_pattern="?.cluster-custom-abc123.us-east-1.rds.amazonaws.com"), + driver_dialect=MagicMock()) def test_validate_accepts_normal_cluster_pattern(): prov = _aurora() - host_pattern, port = prov._resolve_instance_pattern() - assert host_pattern == "?.cluster-xyz.us-east-1.rds.amazonaws.com" - assert port is None + template = prov._topology_utils.instance_template + assert template is not None + assert template.host == "?.cluster-xyz.us-east-1.rds.amazonaws.com" + assert template.port == HostInfo.NO_PORT # ---- provider.stop() tears down the monitor --------------------------- -def test_provider_stop_stops_monitor(): +def test_provider_stop_disposes_the_shared_monitor(): + """stop() publishes MonitorStopEvent, as sync stop_monitor does, so the + monitor service owns disposal. The monitor is shared, so this stops it for + every provider on the cluster and loop.""" async def _body() -> None: prov = _aurora() - mock_monitor = MagicMock() - mock_monitor.stop = AsyncMock() - prov._monitor = mock_monitor + monitor = prov._get_or_create_monitor() + assert monitor is not None + monitor_service = services_container.get_monitor_service() + assert monitor_service.count(AsyncClusterTopologyMonitor) == 1 + await prov.stop() - mock_monitor.stop.assert_awaited_once() - assert prov._monitor is None + + assert monitor_service.count(AsyncClusterTopologyMonitor) == 0 + await monitor.aclose() asyncio.run(_body()) @@ -391,7 +419,7 @@ async def _body() -> None: def test_aurora_provider_cursor_raises_falls_back_to_cache_without_raising(): # Regression for test_fail_from_reader_to_writer: on a FULLY CLOSED # connection psycopg raises OperationalError('the connection is closed') - # from connection.cursor() itself -- not from execute(). _run_topology_query + # from connection.cursor() itself -- not from execute(). query_for_topology # must still swallow it (cursor() lives inside its try), so a failover # refresh through the dead current connection returns the CACHED topology # instead of raising. If it raises, _do_failover discards the cached @@ -422,42 +450,46 @@ async def _body() -> None: def test_topology_monitor_starts_and_stops_cleanly(): async def _body() -> None: prov = MagicMock() - prov.force_refresh = AsyncMock(return_value=()) + prov._topology_utils.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=prov, + topology_utils=prov._topology_utils, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.5, ) assert monitor.is_running() is False monitor.start() assert monitor.is_running() is True - await monitor.stop() + await monitor.aclose() assert monitor.is_running() is False asyncio.run(_body()) -def test_topology_monitor_calls_force_refresh_at_least_once(): +def test_topology_monitor_queries_topology_at_least_once(): async def _body() -> None: prov = MagicMock() - refresh_calls: List[int] = [] + query_calls: List[int] = [] async def _refresh(conn: Any = None) -> tuple: - refresh_calls.append(1) + query_calls.append(1) return () - prov.force_refresh = _refresh + prov._topology_utils.query_for_topology = _refresh conn = MagicMock() monitor = AsyncClusterTopologyMonitor( - provider=prov, + topology_utils=prov._topology_utils, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: conn, refresh_interval_sec=0.5, ) monitor.start() # Give the task a moment to run one iteration. await asyncio.sleep(0.05) - await monitor.stop() - assert len(refresh_calls) >= 1 + await monitor.aclose() + assert len(query_calls) >= 1 asyncio.run(_body()) @@ -465,16 +497,18 @@ async def _refresh(conn: Any = None) -> tuple: def test_topology_monitor_skips_refresh_when_getter_returns_none(): async def _body() -> None: prov = MagicMock() - prov.force_refresh = AsyncMock(return_value=()) + prov._topology_utils.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=prov, + topology_utils=prov._topology_utils, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=0.5, ) monitor.start() await asyncio.sleep(0.05) - await monitor.stop() - prov.force_refresh.assert_not_called() + await monitor.aclose() + prov._topology_utils.query_for_topology.assert_not_called() asyncio.run(_body()) @@ -482,9 +516,11 @@ async def _body() -> None: def test_topology_monitor_survives_provider_exception(): async def _body() -> None: prov = MagicMock() - prov.force_refresh = AsyncMock(side_effect=RuntimeError("topology failure")) + prov._topology_utils.query_for_topology = AsyncMock(side_effect=RuntimeError("topology failure")) monitor = AsyncClusterTopologyMonitor( - provider=prov, + topology_utils=prov._topology_utils, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.5, ) @@ -492,7 +528,7 @@ async def _body() -> None: await asyncio.sleep(0.05) # Must still be running; exceptions are swallowed. assert monitor.is_running() is True - await monitor.stop() + await monitor.aclose() asyncio.run(_body()) @@ -500,9 +536,11 @@ async def _body() -> None: def test_topology_monitor_start_is_idempotent(): async def _body() -> None: prov = MagicMock() - prov.force_refresh = AsyncMock(return_value=()) + prov._topology_utils.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=prov, + topology_utils=prov._topology_utils, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.5, ) @@ -510,7 +548,7 @@ async def _body() -> None: first_task = monitor._task monitor.start() # should be no-op assert monitor._task is first_task - await monitor.stop() + await monitor.aclose() asyncio.run(_body()) @@ -520,20 +558,20 @@ async def _body() -> None: def test_topology_monitor_enters_high_freq_mode_on_writer_change(): """After a writer-change is observed, monitor ticks at high_refresh_rate.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - - # Build a provider whose force_refresh returns topologies with + # Topology utils whose query returns topologies with # different writers on successive calls topology_1 = (HostInfo(host="w1", port=5432, role=HostRole.WRITER), HostInfo(host="r1", port=5432, role=HostRole.READER)) topology_2 = (HostInfo(host="w2", port=5432, role=HostRole.WRITER), HostInfo(host="r1", port=5432, role=HostRole.READER)) - provider = MagicMock() - provider.force_refresh = AsyncMock(side_effect=[topology_1, topology_2, topology_2, topology_2]) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(side_effect=[topology_1, topology_2, topology_2, topology_2]) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(name="conn"), refresh_interval_sec=0.05, high_refresh_rate_sec=0.01, @@ -543,23 +581,23 @@ async def _run_briefly(): monitor.start() # Allow enough ticks for writer-change detection await asyncio.sleep(1) - await monitor.stop() + await monitor.aclose() asyncio.run(_run_briefly()) # At least 2 force_refresh calls happened (first one sets writer, second detects change) - assert provider.force_refresh.await_count >= 2 + assert provider.query_for_topology.await_count >= 2 def test_topology_monitor_stays_normal_freq_when_no_writer_change(): """No writer change -> normal refresh rate, NOT high-freq mode.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.2, high_refresh_rate_sec=0.01, @@ -569,24 +607,24 @@ async def _run_briefly(): monitor.start() # Only enough time for 1-2 ticks at normal rate await asyncio.sleep(0.1) - await monitor.stop() + await monitor.aclose() asyncio.run(_run_briefly()) # At most 2 refresh calls (initial + maybe one more) -- not spinning at high-freq - assert provider.force_refresh.await_count <= 2 + assert provider.query_for_topology.await_count <= 2 def test_topology_monitor_high_freq_expires_after_period(): """After HIGH_REFRESH_PERIOD_SEC passes, monitor reverts to normal rate.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology_1 = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) topology_2 = (HostInfo(host="w2", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(side_effect=[topology_1] + [topology_2] * 100) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(side_effect=[topology_1] + [topology_2] * 100) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.2, high_refresh_rate_sec=0.01, @@ -597,7 +635,7 @@ def test_topology_monitor_high_freq_expires_after_period(): async def _run_briefly(): monitor.start() await asyncio.sleep(0.15) # past the 50ms high-freq window - await monitor.stop() + await monitor.aclose() # Record state when we stopped now_ns = int(time.time_ns()) return monitor._high_refresh_until_ns, now_ns @@ -613,14 +651,14 @@ async def _run_briefly(): def test_topology_monitor_ignores_requests_after_writer_confirmed(): """After an internal refresh sees a writer, should_ignore_refresh_request returns True for IGNORE_REQUEST_SEC.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.05, high_refresh_rate_sec=0.01, @@ -630,7 +668,7 @@ async def _run(): monitor.start() await asyncio.sleep(1) # let at least one tick complete ignore_during = monitor.should_ignore_refresh_request() - await monitor.stop() + await monitor.aclose() return ignore_during ignored = asyncio.run(_run()) @@ -640,7 +678,9 @@ async def _run(): def test_topology_monitor_does_not_ignore_when_no_writer_seen(): """Before any tick observes a writer, requests are NOT ignored.""" monitor = AsyncClusterTopologyMonitor( - provider=MagicMock(), + topology_utils=_stub_utils(), + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=30.0, ) @@ -649,14 +689,14 @@ def test_topology_monitor_does_not_ignore_when_no_writer_seen(): def test_topology_monitor_ignore_window_expires(): """After IGNORE_REQUEST_SEC passes, requests are no longer ignored.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(), refresh_interval_sec=0.05, high_refresh_rate_sec=0.01, @@ -670,7 +710,7 @@ async def _run(): assert monitor.should_ignore_refresh_request() is True await asyncio.sleep(0.1) # past the 50ms window ignore_after = monitor.should_ignore_refresh_request() - await monitor.stop() + await monitor.aclose() return ignore_after ignored = asyncio.run(_run()) @@ -680,17 +720,17 @@ async def _run(): # ---- G.3: force_refresh_with_connection API ------------------------------ -def test_force_refresh_with_connection_delegates_to_provider(): +def test_force_refresh_with_connection_delegates_to_topology_utils(): """When ignore-window is clear, probe via the caller's connection.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER), HostInfo(host="r1", port=5432, role=HostRole.READER)) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -702,19 +742,19 @@ async def _run(): result = asyncio.run(_run()) assert result == topology - provider.force_refresh.assert_awaited_once_with(caller_conn) + provider.query_for_topology.assert_awaited_once_with(caller_conn) def test_force_refresh_with_connection_respects_ignore_window(): """When in ignore window, returns last-known topology without probing.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -731,7 +771,7 @@ async def _run(): result = asyncio.run(_run()) assert result == topology # Provider NOT called -- we returned cached - provider.force_refresh.assert_not_awaited() + provider.query_for_topology.assert_not_awaited() def test_force_refresh_with_connection_raises_on_timeout(): @@ -739,11 +779,13 @@ def test_force_refresh_with_connection_raises_on_timeout(): async def _slow(*args, **kwargs): await asyncio.sleep(1.0) - provider = MagicMock() - provider.force_refresh = _slow + provider = _stub_utils() + provider.query_for_topology = _slow monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -758,10 +800,10 @@ async def _run(): def test_force_refresh_with_connection_triggers_writer_change_detection(): """A writer change observed via this API also starts the high-freq window.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - monitor = AsyncClusterTopologyMonitor( - provider=MagicMock(), + topology_utils=_stub_utils(), + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -769,7 +811,7 @@ def test_force_refresh_with_connection_triggers_writer_change_detection(): monitor._last_known_writer = "old-writer:5432" new_topology = (HostInfo(host="new-writer", port=5432, role=HostRole.WRITER),) - monitor._provider.force_refresh = AsyncMock(return_value=new_topology) + monitor._topology_utils.query_for_topology = AsyncMock(return_value=new_topology) async def _run(): await monitor.force_refresh_with_connection(MagicMock(), timeout_sec=1.0) @@ -781,14 +823,14 @@ async def _run(): def test_force_refresh_with_connection_bypass_ignore_window(): """bypass_ignore_window=True probes even during the ignore window.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -805,7 +847,7 @@ async def _run(): result = asyncio.run(_run()) assert result == topology # fresh, not stale - provider.force_refresh.assert_awaited_once() + provider.query_for_topology.assert_awaited_once() # ---- G.4: parallel-probe panic mode -------------------------------------- @@ -813,12 +855,12 @@ async def _run(): def test_topology_monitor_panic_mode_disabled_without_probe_host(): """Without probe_host, monitor never enters panic mode (backwards compat).""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, # no conn refresh_interval_sec=0.05, ) @@ -827,7 +869,7 @@ def test_topology_monitor_panic_mode_disabled_without_probe_host(): async def _run(): monitor.start() await asyncio.sleep(0.08) - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) assert monitor.is_in_panic_mode() is False @@ -835,8 +877,6 @@ async def _run(): def test_topology_monitor_enters_panic_mode_when_no_connection(): """With probe_host + no monitoring conn + seeded topology -> panic probes fire.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h1 = HostInfo(host="h1", port=5432, role=HostRole.WRITER) h2 = HostInfo(host="h2", port=5432, role=HostRole.READER) @@ -847,10 +887,12 @@ async def _probe(host_info): # Both return as reader; no winner return MagicMock(name=f"conn-{host_info.host}"), HostRole.READER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -860,7 +902,7 @@ async def _probe(host_info): async def _run(): monitor.start() await asyncio.sleep(0.15) - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) # Both hosts probed @@ -871,8 +913,6 @@ async def _run(): def test_topology_monitor_probe_winner_sets_verified_writer(): """First probe to return (conn, WRITER) sets verified-writer state.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h1 = HostInfo(host="h1", port=5432, role=HostRole.READER) h2 = HostInfo(host="h2", port=5432, role=HostRole.WRITER) @@ -883,10 +923,12 @@ async def _probe(host_info): return winner_conn, HostRole.WRITER return MagicMock(name=f"conn-{host_info.host}"), HostRole.READER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -902,7 +944,7 @@ async def _run(): assert monitor._is_verified_writer_connection is True assert monitor._verified_writer_conn is winner_conn assert monitor._verified_writer_host_info is h2 - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) @@ -912,14 +954,14 @@ def test_topology_monitor_harvests_verified_writer_as_monitoring_conn(): own monitoring connection (sync parity: the monitor loop harvest at cluster_topology_monitor.py:262-284 -- the monitor KEEPS the connection; failover consumes only the published topology).""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - async def _run(): winner_conn = MagicMock() winner_host = HostInfo(host="w", port=5432, role=HostRole.WRITER) monitor = AsyncClusterTopologyMonitor( - provider=MagicMock(), + topology_utils=_stub_utils(), + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, connection_factory=AsyncMock(return_value=MagicMock()), @@ -947,8 +989,6 @@ async def _run(): def test_topology_monitor_probe_dedup(): """Same host doesn't get probed twice across consecutive panic ticks.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h = HostInfo(host="only-host", port=5432, role=HostRole.READER) call_count = [0] @@ -958,10 +998,12 @@ async def _probe(host_info): await asyncio.sleep(0.5) return MagicMock(), HostRole.READER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=0.02, # many ticks probe_host=_probe, @@ -971,7 +1013,7 @@ async def _probe(host_info): async def _run(): monitor.start() await asyncio.sleep(0.15) # enough for 5-7 ticks - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) # Only one probe fired despite multiple ticks (dedup) @@ -980,17 +1022,17 @@ async def _run(): def test_topology_monitor_probe_failure_does_not_crash_loop(): """A probe raising an exception doesn't kill the monitor task.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h = HostInfo(host="flaky", port=5432, role=HostRole.READER) async def _probe(host_info): raise RuntimeError("probe failed") - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1001,7 +1043,7 @@ async def _run(): monitor.start() await asyncio.sleep(0.1) assert monitor.is_running() - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) assert monitor._is_verified_writer_connection is False @@ -1009,8 +1051,6 @@ async def _run(): def test_topology_monitor_loser_probe_closes_its_conn(): """Non-winner probe closes its returned conn.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h1 = HostInfo(host="fast-reader", port=5432, role=HostRole.READER) h2 = HostInfo(host="slow-writer", port=5432, role=HostRole.WRITER) @@ -1025,10 +1065,12 @@ async def _probe(host_info): return winner_conn, HostRole.WRITER return loser_conn, HostRole.READER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1041,7 +1083,7 @@ async def _run(): # While alive: loser closed during the race, winner retained (claimable). loser_conn.close.assert_called() winner_conn.close.assert_not_called() - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) # On stop the unclaimed winner is closed too -- not leaked (audit C2). @@ -1050,8 +1092,6 @@ async def _run(): def test_probe_two_writers_only_first_wins_second_closes_conn(): """Two probes returning WRITER: first stashes its conn, second closes its own.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h1 = HostInfo(host="w1", port=5432, role=HostRole.WRITER) h2 = HostInfo(host="w2", port=5432, role=HostRole.WRITER) @@ -1067,10 +1107,12 @@ async def _probe(host_info): await asyncio.sleep(0.02) return loser_conn, HostRole.WRITER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1085,7 +1127,7 @@ async def _run(): assert monitor._verified_writer_conn is winner_conn loser_conn.close.assert_called() winner_conn.close.assert_not_called() - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) # On stop the unclaimed winner is closed too -- not leaked (audit C2). @@ -1094,8 +1136,6 @@ async def _run(): def test_canceled_probe_conn_closed_on_shutdown(): """Probe canceled mid-flight (before returning a conn) doesn't leak.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - h = HostInfo(host="slow", port=5432, role=HostRole.READER) probe_started = asyncio.Event() released_conn = MagicMock(name="late_conn") @@ -1110,10 +1150,12 @@ async def _probe(host_info): raise return released_conn, HostRole.READER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=()) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1124,7 +1166,7 @@ async def _run(): monitor.start() await probe_started.wait() # Now stop; the finally should await the canceled probe - await monitor.stop() + await monitor.aclose() # Should complete without hanging (finally awaits cancellation) asyncio.run(_run()) @@ -1142,7 +1184,6 @@ def test_build_probe_host_opens_via_plugin_service_force_connect(): cluster_topology_monitor.py:344/:519) and calls get_host_role.""" from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ build_probe_host - from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.hostinfo import HostRole as _Role svc = MagicMock() @@ -1180,8 +1221,6 @@ def test_build_probe_host_propagates_connect_errors(): """Connection errors propagate (caller/monitor handles them).""" from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ build_probe_host - from aws_advanced_python_wrapper.hostinfo import HostInfo - svc = MagicMock() svc.force_connect = AsyncMock(side_effect=OSError("no route to host")) svc.get_host_role = AsyncMock() @@ -1196,17 +1235,17 @@ def test_monitor_closes_stashed_verified_writer_on_stop(): unclaimed (the failover caller never called claim_verified_writer) must be closed when the monitor stops, not leaked. A winning probe task is already done(), so the finally's probe-task cancellation doesn't cover it.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - topology = (HostInfo(host="w1", port=5432, role=HostRole.WRITER),) - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=topology) + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=topology) stashed = MagicMock(name="verified-writer-conn") stashed.close = AsyncMock() monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: MagicMock(name="monitor-conn"), refresh_interval_sec=0.2, high_refresh_rate_sec=0.05, @@ -1221,7 +1260,7 @@ async def _run_briefly(): monitor._verified_writer_host_info = HostInfo( host="w1", port=5432, role=HostRole.WRITER) monitor._is_verified_writer_connection = True - await monitor.stop() + await monitor.aclose() asyncio.run(_run_briefly()) stashed.close.assert_awaited_once() @@ -1233,8 +1272,6 @@ def test_topology_monitor_winner_probe_publishes_topology(): """The winning writer probe fetches topology THROUGH the verified-writer connection and publishes it: monitor state + provider cache + wake event (sync parity: HostMonitor._fetch_topology_and_update_cache, :561).""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - new_writer = HostInfo(host="w-new", port=5432, role=HostRole.WRITER) reader = HostInfo(host="r1", port=5432, role=HostRole.READER) @@ -1243,12 +1280,13 @@ async def _probe(host_info): return MagicMock(name="winner_conn"), HostRole.WRITER return MagicMock(name=f"conn-{host_info.host}"), HostRole.READER - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=(new_writer, reader)) - provider.adopt_topology = MagicMock() + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=(new_writer, reader)) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1258,10 +1296,10 @@ async def _probe(host_info): async def _run(): await monitor._probe_and_report(new_writer) assert monitor._last_topology == (new_writer, reader) - provider.adopt_topology.assert_called_once_with((new_writer, reader)) + assert topology_store.get_topology(monitor._key) == (new_writer, reader) assert monitor._topology_updated.is_set() assert monitor._is_verified_writer_connection is True - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) @@ -1274,8 +1312,6 @@ def test_winner_probe_publishes_role_corrected_topology_on_stale_fetch(): fired, and topology consumers (tracker, RWS) acted on the demoted writer. The winner's publication must overlay the verified writer: its row WRITER, the stale writer row demoted to READER.""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - old_writer_stale = HostInfo(host="w-old", port=5432, role=HostRole.WRITER) new_writer_stale = HostInfo(host="w-new", port=5432, role=HostRole.READER) new_writer_probe = HostInfo(host="w-new", port=5432, role=HostRole.WRITER) @@ -1283,15 +1319,16 @@ def test_winner_probe_publishes_role_corrected_topology_on_stale_fetch(): async def _probe(host_info): return MagicMock(name="winner_conn"), HostRole.WRITER - provider = MagicMock() + provider = _stub_utils() # replica_status lag: the fetch through the NEW writer still claims the # OLD writer is the writer and the new one is a reader. - provider.force_refresh = AsyncMock( + provider.query_for_topology = AsyncMock( return_value=(old_writer_stale, new_writer_stale)) - provider.adopt_topology = MagicMock() monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1304,9 +1341,9 @@ async def _run(): roles = {h.host: h.role for h in published} assert roles["w-new"] == HostRole.WRITER assert roles["w-old"] == HostRole.READER - provider.adopt_topology.assert_called_once_with(published) + assert topology_store.get_topology(monitor._key) == published assert {h.host for h in published} == {"w-old", "w-new"} - await monitor.stop() + await monitor.aclose() asyncio.run(_run()) @@ -1316,14 +1353,14 @@ def test_role_correction_expires_with_settling_window(): again -- a genuinely newer failover must not be masked forever.""" import time as _time - from aws_advanced_python_wrapper.hostinfo import HostInfo - verified = HostInfo(host="w-verified", port=5432, role=HostRole.WRITER) other_writer = HostInfo(host="w-other", port=5432, role=HostRole.WRITER) - provider = MagicMock() + provider = _stub_utils() monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -1348,8 +1385,6 @@ def test_force_monitoring_refresh_verify_writer_panics_and_returns_topology(): (forcing panic), wakes the loop, and blocks until a probe publishes the fresh topology (sync parity: force_refresh(True, t) + _wait_till_topology_gets_updated, cluster_topology_monitor.py:136-178).""" - from aws_advanced_python_wrapper.hostinfo import HostInfo - new_writer = HostInfo(host="w-new", port=5432, role=HostRole.WRITER) reader = HostInfo(host="r1", port=5432, role=HostRole.READER) @@ -1363,12 +1398,13 @@ async def _factory(): # be reopened, so the loop falls through to panic mode. raise OSError("cluster endpoint unreachable") - provider = MagicMock() - provider.force_refresh = AsyncMock(return_value=(new_writer, reader)) - provider.adopt_topology = MagicMock() + provider = _stub_utils() + provider.query_for_topology = AsyncMock(return_value=(new_writer, reader)) monitor = AsyncClusterTopologyMonitor( - provider=provider, + topology_utils=provider, + cluster_id="test-cluster", + key=("test-cluster", "token"), connection_getter=lambda: None, refresh_interval_sec=30.0, # long: proves the tick-request wakeup works probe_host=_probe, @@ -1381,7 +1417,7 @@ async def _run(): monitor.start() topology = await monitor.force_monitoring_refresh(True, timeout_sec=5.0) assert topology == (new_writer, reader) - provider.adopt_topology.assert_called_with((new_writer, reader)) - await monitor.stop() + assert topology_store.get_topology(monitor._key) == (new_writer, reader) + await monitor.aclose() asyncio.run(_run()) diff --git a/tests/unit/test_aio_host_list_provider_monitor_wiring.py b/tests/unit/test_aio_host_list_provider_monitor_wiring.py index dbac4b5cc..7c8c4cd48 100644 --- a/tests/unit/test_aio_host_list_provider_monitor_wiring.py +++ b/tests/unit/test_aio_host_list_provider_monitor_wiring.py @@ -12,15 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""Tests for the N.1b monitor-wiring refactor on AsyncAuroraHostListProvider. - -Verifies: -- force_refresh delegates through AsyncClusterTopologyMonitor (so - panic-mode probing auto-engages). -- Monitor's internal refresh path uses _fetch_from_db (no public-API - recursion). -- Fallback path: if the monitor can't be built or raises, force_refresh - still returns a topology via the direct-DB fallback. +"""Tests for how the async provider acquires its topology monitor. + +The monitor comes from the monitor service, keyed by cluster and event loop, +so providers on one cluster share it. The monitor holds topology utils rather +than a provider, which is what lets it be shared. """ from __future__ import annotations @@ -28,160 +24,170 @@ import asyncio from unittest.mock import AsyncMock, MagicMock -import pytest - from aws_advanced_python_wrapper.aio import cleanup as aio_cleanup from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ AsyncClusterTopologyMonitor from aws_advanced_python_wrapper.aio.host_list_provider import \ AsyncAuroraHostListProvider +from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.properties import Properties +HOST = "cluster.example" -@pytest.fixture(autouse=True) -def _clear_hooks(): - aio_cleanup.clear_shutdown_hooks() - yield - aio_cleanup.clear_shutdown_hooks() +def _provider(rows: list, **props: str) -> AsyncAuroraHostListProvider: + """A provider whose topology query returns ``rows``.""" + base = {"host": HOST, "port": "5432"} + base.update(props) + provider = AsyncAuroraHostListProvider(Properties(base), MagicMock()) -def _provider_with_rows(rows: list) -> AsyncAuroraHostListProvider: - """Build a provider whose _run_topology_query returns ``rows``.""" - provider = AsyncAuroraHostListProvider( - Properties({"host": "cluster.example", "port": "5432"}), - MagicMock(), # driver_dialect not used in these tests - ) - - async def _rows(_conn): # noqa: ARG001 - signature fixed + async def _fetch_all(_conn, _query): return rows - provider._run_topology_query = _rows # type: ignore[method-assign] + provider._topology_utils._fetch_all = _fetch_all # type: ignore[method-assign] return provider -def test_force_refresh_goes_through_monitor() -> None: - """After N.1b, force_refresh must build + consult the monitor - rather than query the DB directly.""" - provider = _provider_with_rows([("srv-1", True), ("srv-2", False)]) +def _monitor_count() -> int: + return services_container.get_monitor_service().count( + AsyncClusterTopologyMonitor) + + +def test_force_refresh_goes_through_the_monitor() -> None: + """Delegating is what engages panic-mode probing when writer discovery + stalls, so a direct query that returns the right hosts is not enough.""" + provider = _provider([("srv-1", True), ("srv-2", False)]) async def _body(): - conn = object() - topology = await provider.force_refresh(conn) - # Topology came back, so either the monitor OR the fallback - # populated the cache. Monitor existence is the marker of - # proper N.1b wiring. - assert provider._monitor is not None - assert isinstance(provider._monitor, AsyncClusterTopologyMonitor) + monitor = provider._get_or_create_monitor() + assert isinstance(monitor, AsyncClusterTopologyMonitor) + spy = AsyncMock(wraps=monitor.force_refresh_with_connection) + monitor.force_refresh_with_connection = spy # type: ignore[method-assign] + + topology = await provider.force_refresh(object()) + + spy.assert_awaited_once() assert len(topology) == 2 - await provider._monitor.stop() + await monitor.aclose() asyncio.run(_body()) -def test_monitor_uses_fetch_from_db_not_force_refresh() -> None: - """Recursion check: monitor's internal refresh path must call - _fetch_from_db, not the public force_refresh (which now routes - through the monitor).""" - provider = _provider_with_rows([("srv-1", True)]) +def test_the_monitor_holds_no_provider_reference() -> None: + """What makes one monitor serve every provider on the cluster.""" + provider = _provider([("srv-1", True)]) - fetch_calls: list = [] - original_fetch = provider._fetch_from_db + async def _body(): + monitor = provider._get_or_create_monitor() + assert monitor is not None + assert monitor._topology_utils is provider._topology_utils + # Nothing on the monitor refers back to a provider. + assert not any(getattr(monitor, name, None) is provider + for name in vars(monitor)) + await monitor.aclose() + + asyncio.run(_body()) - async def _instrumented_fetch(conn): - fetch_calls.append(conn) - return await original_fetch(conn) - provider._fetch_from_db = _instrumented_fetch # type: ignore[method-assign] +def test_two_providers_on_one_cluster_share_one_monitor() -> None: + first = _provider([("srv-1", True)]) + second = _provider([("srv-1", True)]) async def _body(): - monitor = AsyncClusterTopologyMonitor( - provider=provider, - connection_getter=lambda: None, - ) - topology = await monitor.force_refresh_with_connection( - conn=object(), - bypass_ignore_window=True, - ) - assert len(topology) == 1 - # _fetch_from_db was called exactly once (no recursion). - assert len(fetch_calls) == 1 + monitor_one = first._get_or_create_monitor() + monitor_two = second._get_or_create_monitor() + assert monitor_one is monitor_two + assert _monitor_count() == 1 + await monitor_one.aclose() asyncio.run(_body()) -def test_fetch_from_db_does_not_recurse_into_monitor() -> None: - """_fetch_from_db is the internal path used BY the monitor; it - must not itself engage the monitor.""" - provider = _provider_with_rows([("srv-1", True)]) +def test_providers_on_different_clusters_get_different_monitors() -> None: + first = _provider([("srv-1", True)], cluster_id="cluster-a") + second = _provider([("srv-1", True)], cluster_id="cluster-b") async def _body(): - topology = await provider._fetch_from_db(object()) - assert len(topology) == 1 - # _fetch_from_db is the internal path; it must not build a - # monitor. (If it did, we'd recurse.) - assert provider._monitor is None + monitor_one = first._get_or_create_monitor() + monitor_two = second._get_or_create_monitor() + assert monitor_one is not monitor_two + assert _monitor_count() == 2 + await monitor_one.aclose() + await monitor_two.aclose() asyncio.run(_body()) -def test_force_refresh_falls_back_to_direct_query_on_monitor_failure() -> None: - """If the monitor raises, force_refresh still returns a topology - via _fetch_and_cache.""" - provider = _provider_with_rows([("srv-1", True)]) +def test_a_monitor_that_is_not_running_is_replaced() -> None: + """The monitor service has no liveness check of its own. + + Its cache extends expiration on every hit, so a monitor whose loop has + closed would be handed out until the stuck-monitor sweep removed it, and + meanwhile every blocking refresh waits for an update that cannot arrive. + """ + provider = _provider([("srv-1", True)]) + + async def _body(): + first = provider._get_or_create_monitor() + assert first is not None + await first.aclose() + assert not first.is_running() + + second = provider._get_or_create_monitor() + assert second is not first + assert second.is_running() + # The dead one was removed rather than left alongside its replacement. + assert _monitor_count() == 1 + await second.aclose() + + asyncio.run(_body()) + + +def test_force_refresh_falls_back_to_a_direct_query_when_the_monitor_raises() -> None: + provider = _provider([("srv-1", True)]) async def _body(): - # Force a failure by swapping out the monitor's - # force_refresh_with_connection to raise. real_get_monitor = provider._get_or_create_monitor def _broken_monitor(): - m = real_get_monitor() - m.force_refresh_with_connection = AsyncMock( # type: ignore[method-assign] + monitor = real_get_monitor() + monitor.force_refresh_with_connection = AsyncMock( # type: ignore[method-assign] side_effect=RuntimeError("monitor boom")) - return m + return monitor provider._get_or_create_monitor = _broken_monitor # type: ignore[method-assign] topology = await provider.force_refresh(object()) assert len(topology) == 1 - if provider._monitor is not None: - await provider._monitor.stop() asyncio.run(_body()) -def test_monitor_teardown_registered_with_cleanup_hook() -> None: - """Building the monitor must register its stop() with the global - cleanup hook so release_resources_async tears it down.""" - provider = _provider_with_rows([("srv-1", True)]) +def test_monitor_teardown_is_registered_with_the_cleanup_hook() -> None: + """release_resources clears the monitor cache, so the hook must be + registered to survive it.""" + aio_cleanup.clear_shutdown_hooks() + provider = _provider([("srv-1", True)]) async def _body(): - hooks_before = len(aio_cleanup._registered_shutdown_hooks) + before = len(aio_cleanup._registered_shutdown_hooks) monitor = provider._get_or_create_monitor() assert monitor is not None - hooks_after = len(aio_cleanup._registered_shutdown_hooks) - assert hooks_after > hooks_before - await monitor.stop() + assert len(aio_cleanup._registered_shutdown_hooks) > before + await monitor.aclose() asyncio.run(_body()) + aio_cleanup.clear_shutdown_hooks() -def test_refresh_cache_short_circuits_without_hitting_monitor() -> None: - """refresh() with a fresh cache must not build a monitor.""" - provider = _provider_with_rows([("srv-1", True)]) +def test_refresh_returns_the_stored_topology_without_building_a_monitor() -> None: + provider = _provider([("srv-1", True)]) async def _body(): - # Prime the cache via force_refresh. - conn = object() - await provider.force_refresh(conn) - if provider._monitor is not None: - await provider._monitor.stop() - # Clear the monitor reference to simulate post-cleanup state. - provider._monitor = None - - # refresh() should return cached topology without building a - # new monitor. - result = await provider.refresh(conn) + provider._store_topology( + (MagicMock(host="srv-1.example", port=5432),)) + assert _monitor_count() == 0 + result = await provider.refresh(object()) assert len(result) == 1 - assert provider._monitor is None + assert _monitor_count() == 0 asyncio.run(_body()) diff --git a/tests/unit/test_aio_monitor_service_integration.py b/tests/unit/test_aio_monitor_service_integration.py new file mode 100644 index 000000000..2383623c0 --- /dev/null +++ b/tests/unit/test_aio_monitor_service_integration.py @@ -0,0 +1,218 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for the async topology monitor as a managed monitor.""" + +from __future__ import annotations + +import asyncio +from time import perf_counter_ns +from unittest.mock import AsyncMock, MagicMock + +from aws_advanced_python_wrapper.aio import topology_store +from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor +from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncAuroraTopologyUtils +from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.events import (MonitorResetEvent, + MonitorStopEvent) +from aws_advanced_python_wrapper.utils.monitor_service import Monitor +from aws_advanced_python_wrapper.utils.properties import Properties + +CLUSTER_ID = "my-cluster" +KEY = (CLUSTER_ID, "token") +HOSTS = (HostInfo("writer.example", 5432, HostRole.WRITER),) + + +def _utils(topology=()) -> AsyncAuroraTopologyUtils: + utils = AsyncAuroraTopologyUtils( + Properties({"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"}), + "SELECT 1", 5432) + utils.query_for_topology = AsyncMock(return_value=topology) # type: ignore[method-assign] + return utils + + +def _monitor(topology=(), **kwargs) -> AsyncClusterTopologyMonitor: + return AsyncClusterTopologyMonitor( + topology_utils=_utils(topology), + cluster_id=CLUSTER_ID, + key=KEY, + connection_getter=lambda: None, + **kwargs) + + +def test_the_monitor_satisfies_the_monitor_protocol() -> None: + """The monitor service type-checks against this protocol at runtime.""" + assert isinstance(_monitor(), Monitor) + + +def test_stop_does_not_block_on_teardown() -> None: + """MonitorStopEvent is delivered on the publisher's thread and async + blue/green publishes from a coroutine, so a blocking stop would wedge + that loop.""" + async def _body(): + monitor = _monitor() + monitor.start() + assert monitor.is_running() + monitor.stop() # returns immediately, teardown is scheduled + await asyncio.sleep(0) + await asyncio.sleep(0) + assert not monitor.is_running() + + asyncio.run(_body()) + + +def test_stop_without_a_live_loop_does_not_raise() -> None: + """A monitor whose loop is gone cannot close its connection. Say so + rather than report a clean teardown.""" + monitor = _monitor() + monitor.stop() # never started, so no loop was ever recorded + assert not monitor.is_running() + + +def test_aclose_is_idempotent() -> None: + async def _body(): + monitor = _monitor() + monitor.start() + await monitor.aclose() + await monitor.aclose() + assert not monitor.is_running() + + asyncio.run(_body()) + + +def test_aclose_closes_a_monitor_that_never_started() -> None: + """_run's finally releases the connection when its task is cancelled, but + a monitor that never started still owns one.""" + conn = MagicMock() + conn.close = MagicMock() + + async def _body(): + monitor = _monitor() + monitor._owned_conn = conn + await monitor.aclose() + conn.close.assert_called_once() + + asyncio.run(_body()) + + +def test_can_dispose_is_false_while_a_refresh_is_in_flight() -> None: + """Only the expiry path consults can_dispose; the stuck-monitor path + removes regardless, so this does not protect a blocked caller.""" + async def _body(): + monitor = _monitor() + assert monitor.can_dispose is True + + monitor.start() + waiter = asyncio.create_task( + monitor.force_monitoring_refresh(False, timeout_sec=5.0)) + await asyncio.sleep(0.01) + assert monitor.can_dispose is False + + monitor._publish_topology(HOSTS) + await waiter + assert monitor.can_dispose is True + await monitor.aclose() + + asyncio.run(_body()) + + +def test_last_activity_uses_the_same_clock_as_the_cleanup_sweep() -> None: + """MonitorService._run_cleanup compares this against perf_counter_ns, so a + different clock would make every monitor look stuck, or never idle.""" + async def _body(): + before = perf_counter_ns() + monitor = _monitor() + monitor.start() + await asyncio.sleep(0.01) + after = perf_counter_ns() + assert before <= monitor.last_activity_ns <= after + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_reset_event_for_this_cluster_drops_the_stored_topology() -> None: + """A switchover must not keep serving the pre-switchover host list.""" + async def _body(): + monitor = _monitor() + monitor.start() + topology_store.put_topology(KEY, HOSTS) + monitor._last_topology = HOSTS + monitor._last_known_writer = "writer.example:5432" + + monitor.process_event( + MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) + await asyncio.sleep(0) + await asyncio.sleep(0) + + assert topology_store.get_topology(KEY) is None + assert monitor._last_topology == () + assert monitor._last_known_writer is None + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_reset_event_for_another_cluster_is_ignored() -> None: + async def _body(): + monitor = _monitor() + monitor.start() + topology_store.put_topology(KEY, HOSTS) + + monitor.process_event( + MonitorResetEvent(cluster_id="someone-else", endpoints=frozenset())) + await asyncio.sleep(0) + await asyncio.sleep(0) + + assert topology_store.get_topology(KEY) == HOSTS + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_stop_event_disposes_the_registered_monitor() -> None: + async def _body(): + monitor = _monitor() + monitor.start() + monitor_service = services_container.get_monitor_service() + monitor_service.register_monitor_type(AsyncClusterTopologyMonitor) + monitor_service.run_if_absent( + AsyncClusterTopologyMonitor, KEY, lambda: monitor) + assert monitor_service.count(AsyncClusterTopologyMonitor) == 1 + + services_container.get_event_publisher().publish( + MonitorStopEvent(monitor_type=AsyncClusterTopologyMonitor, key=KEY)) + + assert monitor_service.count(AsyncClusterTopologyMonitor) == 0 + await monitor.aclose() + + asyncio.run(_body()) + + +def test_stop_and_remove_value_leaves_a_replacement_alone() -> None: + """Removing by key would dispose whatever sits at the key now, which may + be a replacement another caller is already using.""" + monitor_service = services_container.get_monitor_service() + monitor_service.register_monitor_type(AsyncClusterTopologyMonitor) + + stale, replacement = _monitor(), _monitor() + monitor_service.run_if_absent( + AsyncClusterTopologyMonitor, KEY, lambda: replacement) + + monitor_service.stop_and_remove_value(AsyncClusterTopologyMonitor, stale) + + assert monitor_service.get(AsyncClusterTopologyMonitor, KEY) is replacement diff --git a/tests/unit/test_aio_multi_az_host_list_provider.py b/tests/unit/test_aio_multi_az_host_list_provider.py index 2f8a46a4c..9ccf6afe2 100644 --- a/tests/unit/test_aio_multi_az_host_list_provider.py +++ b/tests/unit/test_aio_multi_az_host_list_provider.py @@ -363,11 +363,9 @@ def test_explicit_cluster_id_respected(): assert prov.get_cluster_id() == "my-multi-az-cluster" -def test_default_cluster_id_uses_host_port(): +def test_default_cluster_id_is_one(): prov = _make_provider() - cid = prov.get_cluster_id() - assert "aurora:" in cid # derived helper is shared - assert "cluster-xyz.example.com" in cid + assert prov.get_cluster_id() == "1" # ---- Query failure tolerance -------------------------------------------- diff --git a/tests/unit/test_aio_topology_storage.py b/tests/unit/test_aio_topology_storage.py new file mode 100644 index 000000000..c25711b3e --- /dev/null +++ b/tests/unit/test_aio_topology_storage.py @@ -0,0 +1,300 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""The async provider's topology lives in the storage service. + +Two things here are easy to break silently and have no other coverage: the +storage key type (the sync and async ``Topology`` aliases are different +objects, so using the wrong one writes to an unregistered cache) and the loop +component of the key (which must not be ``id(loop)``, because addresses are +recycled). +""" + +from __future__ import annotations + +import asyncio +from typing import Any +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio.host_list_provider import \ + AsyncAuroraHostListProvider +from aws_advanced_python_wrapper.aio.topology_store import (StoredTopology, + loop_token) +from aws_advanced_python_wrapper.host_list_provider import \ + Topology as SyncTopology +from aws_advanced_python_wrapper.hostinfo import (HostAvailability, HostInfo, + HostRole) +from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.properties import Properties + + +def _props(**kwargs: Any) -> Properties: + base = {"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"} + base.update({k: str(v) for k, v in kwargs.items()}) + return Properties(base) + + +def _aurora(**kwargs: Any) -> AsyncAuroraHostListProvider: + props = _props( + cluster_instance_host_pattern="?.cluster-xyz.us-east-1.rds.amazonaws.com", + **kwargs) + return AsyncAuroraHostListProvider(props, driver_dialect=MagicMock()) + + +def _storage(): + return services_container.get_storage_service() + + +HOSTS = (HostInfo("writer.com", 5432, HostRole.WRITER), + HostInfo("reader.com", 5432, HostRole.READER)) + + +# ---- The storage key type ------------------------------------------------ + +def test_the_two_topology_aliases_are_not_interchangeable_as_keys(): + """Why the async module must key storage on the sync alias. + + The sync module imports HostInfo under TYPE_CHECKING only, so its alias is + built from a forward reference and is a different object from the async + one. The storage service is keyed by type, and only the sync alias is + registered -- so keying on the async alias would write to a second, + unregistered cache. + """ + from aws_advanced_python_wrapper.aio.host_list_provider import \ + Topology as AsyncTopology + + assert AsyncTopology != SyncTopology + assert StoredTopology is SyncTopology + + +def test_topology_is_written_to_the_registered_storage_service_entry(): + prov = _aurora() + + async def _run(): + prov._store_topology(HOSTS) + assert _storage().get(StoredTopology, prov._storage_key()) == HOSTS + + asyncio.run(_run()) + + +def test_two_providers_for_one_cluster_on_one_loop_share_the_topology(): + """A second connection to the same cluster does not start from an empty + cache.""" + first, second = _aurora(), _aurora() + + async def _run(): + first._store_topology(HOSTS) + assert await second.refresh() == HOSTS + + asyncio.run(_run()) + + +def test_providers_for_different_clusters_do_not_share(): + a = _aurora(cluster_id="cluster-a") + b = _aurora(cluster_id="cluster-b") + + async def _run(): + a._store_topology(HOSTS) + assert b._get_stored_topology() is None + + asyncio.run(_run()) + + +def test_an_async_entry_does_not_collide_with_a_sync_bare_key_entry(): + """Sync keys by bare cluster id in the same process-global store. + + Topology entries hold mutable HostInfo objects whose availability is + written in place, so a shared entry would let one engine mark the other's + hosts unavailable. + """ + prov = _aurora(cluster_id="shared-id") + sync_hosts = (HostInfo("sync-writer.com", 5432, HostRole.WRITER),) + + async def _run(): + _storage().put(StoredTopology, "shared-id", sync_hosts) + prov._store_topology(HOSTS) + + assert _storage().get(StoredTopology, "shared-id") == sync_hosts + assert prov._get_stored_topology() == HOSTS + + asyncio.run(_run()) + + +# ---- refresh() semantics ------------------------------------------------- + +def test_refresh_returns_the_stored_topology_without_querying(): + """There is no provider-side freshness window any more: a present entry is + returned and the monitor is what keeps it fresh.""" + prov = _aurora() + conn = MagicMock() + prov._topology_utils.query_for_topology = AsyncMock( # type: ignore[method-assign] + side_effect=AssertionError("must not query when topology is stored")) + + async def _run(): + prov._store_topology(HOSTS) + assert await prov.refresh(conn) == HOSTS + + asyncio.run(_run()) + + +def test_refresh_with_no_connection_and_nothing_stored_returns_empty(): + prov = _aurora() + + async def _run(): + assert await prov.refresh() == () + + asyncio.run(_run()) + + +def test_reconfiguring_the_query_discards_the_stored_topology(): + """A result produced by the previous dialect's query is stale.""" + prov = _aurora() + + async def _run(): + prov._store_topology(HOSTS) + prov.reconfigure_topology_query("SELECT 1", 3306) + assert prov._get_stored_topology() is None + + asyncio.run(_run()) + + +def test_reconfiguring_the_query_off_loop_does_not_raise(): + """It is a synchronous method, and the key names a loop.""" + prov = _aurora() + prov.reconfigure_topology_query("SELECT 1", 3306) + + +def test_storing_an_empty_topology_does_not_overwrite_a_good_one(): + prov = _aurora() + + async def _run(): + prov._store_topology(HOSTS) + prov._store_topology(()) + assert prov._get_stored_topology() == HOSTS + + asyncio.run(_run()) + + +# ---- The loop component of the key --------------------------------------- + +def testloop_token_is_stable_within_one_loop(): + async def _run(): + loop = asyncio.get_running_loop() + return loop_token(loop), loop_token(loop) + + first, second = asyncio.run(_run()) + assert first == second + + +def test_loop_token_is_not_the_loop_address(): + """``id(loop)`` is recycled: sequential ``asyncio.run`` calls commonly + reuse one address, so an address-keyed entry would be handed to a fresh + loop -- along with HostInfo objects a previous run may have marked + unavailable.""" + tokens, addresses = [], [] + + async def _run(): + loop = asyncio.get_running_loop() + tokens.append(loop_token(loop)) + addresses.append(id(loop)) + + for _ in range(6): + asyncio.run(_run()) + + assert len(set(tokens)) == 6, "tokens must be unique per loop" + # Not asserting addresses collide -- that is allocator-dependent -- only + # that uniqueness does not come from the address. + assert len(set(addresses)) <= 6 + + +def test_a_loop_that_cannot_be_weak_referenced_still_gets_a_token(): + """Accelerated loops (uvloop) are extension types and may not support + weak references. The fallback is the address, which is only safe because + consumers re-check liveness and replace a dead entry.""" + + class _NoWeakRef: + __slots__ = () + + loop = _NoWeakRef() + token = loop_token(loop) # type: ignore[arg-type] + assert token == f"id:{id(loop)}" + + +def test_storage_key_is_none_when_no_loop_is_running(): + prov = _aurora() + assert prov._storage_key() is None + + +def test_storage_key_pairs_the_cluster_id_with_theloop_token(): + prov = _aurora(cluster_id="my-cluster") + + async def _run(): + return prov._storage_key(), loop_token(asyncio.get_running_loop()) + + key, token = asyncio.run(_run()) + assert key == ("my-cluster", token) + + +@pytest.mark.parametrize("stored,expected", [(HOSTS, HOSTS), (None, ())]) +def test_force_refresh_without_a_connection_falls_back_to_the_store( + stored, expected): + prov = _aurora() + + async def _run(): + if stored is not None: + prov._store_topology(stored) + return await prov.force_refresh() + + assert asyncio.run(_run()) == expected + + +def test_a_reader_gets_copies_not_the_stored_hosts(): + """The entry is shared by every provider on the cluster and loop, and + availability is written into a HostInfo in place, so handing out the + stored objects lets one connection rewrite another's hosts.""" + first, second = _aurora(), _aurora() + + async def _run(): + first._store_topology(HOSTS) + mine = await first.refresh() + theirs = await second.refresh() + + assert mine[0] is not theirs[0], "two readers share one HostInfo" + assert mine[0] is not HOSTS[0], "a reader got the stored object" + + # Marking one unavailable must not touch the other's view. + mine[0].set_availability(HostAvailability.UNAVAILABLE) + assert theirs[0].availability is not HostAvailability.UNAVAILABLE + assert HOSTS[0].availability is not HostAvailability.UNAVAILABLE + + asyncio.run(_run()) + + +def test_copies_keep_their_aliases(): + """HostInfo.__copy__ drops aliases, and aliases are how a live connection + is matched back to its topology row.""" + aliased = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1") + aliased.add_alias("srv-1") + prov = _aurora() + + async def _run(): + prov._store_topology((aliased,)) + got = await prov.refresh() + assert got[0] is not aliased + assert "srv-1" in got[0].aliases + assert got[0].host_id == "srv-1" + + asyncio.run(_run()) From 8fc2c5a6ba871e5d8872e878c9c87474a1cd1383 Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:35:03 -0700 Subject: [PATCH 3/4] refactor: identify hosts by host id and host-and-port instead of aliases --- .flake8 | 2 +- .../aio/aurora_connection_tracker.py | 226 +++++-------- ...rora_initial_connection_strategy_plugin.py | 21 +- .../aio/blue_green_plugin.py | 1 - .../aio/cluster_topology_monitor.py | 39 +-- .../aio/default_plugin.py | 11 +- .../aio/dialect_utils.py | 24 +- .../aio/failover_plugin.py | 12 +- .../aio/host_list_provider.py | 29 +- .../aio/host_monitoring_plugin.py | 81 +++-- .../aio/limitless_plugin.py | 15 + .../aio/plugin_service.py | 155 +++++---- .../aio/read_write_splitting_plugin.py | 13 +- aws_advanced_python_wrapper/aio/retry_util.py | 10 +- .../aio/topology_store.py | 18 +- .../aio/topology_utils.py | 21 +- aws_advanced_python_wrapper/aio/wrapper.py | 6 +- .../aurora_connection_tracker_plugin.py | 137 ++++---- ...rora_initial_connection_strategy_plugin.py | 17 +- .../aws_credentials_manager.py | 2 +- .../blue_green_plugin.py | 1 - .../database_dialect.py | 28 +- aws_advanced_python_wrapper/default_plugin.py | 2 +- .../failover_plugin.py | 15 +- .../failover_v2_plugin.py | 4 +- .../host_list_provider.py | 30 +- .../host_monitoring_plugin.py | 135 ++++---- .../host_monitoring_v2_plugin.py | 66 ++-- aws_advanced_python_wrapper/hostinfo.py | 56 +--- .../limitless_plugin.py | 15 + aws_advanced_python_wrapper/plugin_service.py | 141 +++++---- .../read_write_splitting_plugin.py | 15 +- .../reader_failover_handler.py | 6 +- ...dvanced_python_wrapper_messages.properties | 12 - .../utils/concurrent.py | 19 -- .../utils/monitor_service.py | 11 +- .../storage/expiration_tracking_cache.py | 9 +- aws_advanced_python_wrapper/utils/utils.py | 46 +++ aws_advanced_python_wrapper/wrapper.py | 6 +- .../writer_failover_handler.py | 17 +- docs/development-guide/PluginService.md | 18 ++ .../test_aio_aurora_connection_tracker.py | 58 ++-- .../test_aio_aurora_initial_connection.py | 16 +- tests/unit/test_aio_dialect_utils.py | 2 +- tests/unit/test_aio_failover_plugin.py | 8 +- tests/unit/test_aio_host_list_provider.py | 25 +- tests/unit/test_aio_host_monitoring_plugin.py | 2 +- .../test_aio_monitor_lifecycle_regressions.py | 296 ++++++++++++++++++ tests/unit/test_aio_multi_alias_tracker.py | 150 --------- tests/unit/test_aio_multi_key_tracker.py | 133 ++++++++ tests/unit/test_aio_plugin_service_extras.py | 158 ++++++---- tests/unit/test_aio_retry_util.py | 6 +- tests/unit/test_aio_simple_rws.py | 7 +- tests/unit/test_aio_topology_storage.py | 30 +- tests/unit/test_aio_wrapper.py | 11 +- tests/unit/test_aurora_connection_tracker.py | 132 +++++++- tests/unit/test_connection.py | 41 +++ tests/unit/test_expiration_tracking_cache.py | 18 -- tests/unit/test_failover_plugin.py | 11 +- tests/unit/test_host_monitor_v2_plugin.py | 63 +++- tests/unit/test_host_monitoring_plugin.py | 73 +++-- tests/unit/test_hostinfo.py | 35 ++- tests/unit/test_monitor_service.py | 45 +-- .../test_multi_az_rds_host_list_provider.py | 27 ++ .../test_multithreaded_monitor_service.py | 31 +- tests/unit/test_plugin_service.py | 251 ++++++++++++++- tests/unit/test_reader_failover_handler.py | 6 +- tests/unit/test_writer_failover_handler.py | 34 +- 68 files changed, 1982 insertions(+), 1179 deletions(-) create mode 100644 tests/unit/test_aio_monitor_lifecycle_regressions.py delete mode 100644 tests/unit/test_aio_multi_alias_tracker.py create mode 100644 tests/unit/test_aio_multi_key_tracker.py diff --git a/.flake8 b/.flake8 index 26b87807a..0c534ce39 100644 --- a/.flake8 +++ b/.flake8 @@ -1,4 +1,4 @@ [flake8] max-line-length = 150 extend-select = TC, TC1 -exclude = venv/ +exclude = venv/, .venv/ diff --git a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py index 93e287eeb..c338b574a 100644 --- a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py +++ b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py @@ -16,11 +16,11 @@ Port of sync ``aurora_connection_tracker_plugin.py``. Tracks every connection opened through the plugin pipeline in a class-level -:class:`AsyncOpenedConnectionTracker` registry keyed by the RDS -instance-endpoint alias (mirroring sync normalization). On writer -change (detected via ``AsyncPluginService.all_hosts`` or a raised -:class:`FailoverError`), closes every tracked connection to the old -writer so pooled consumers don't reuse a stale demoted-writer socket. +:class:`AsyncOpenedConnectionTracker` registry keyed by host id and by +host and port. On writer change (detected via +``AsyncPluginService.all_hosts`` or a raised :class:`FailoverError`), +closes every tracked connection to the old writer so pooled consumers +don't reuse a stale demoted-writer socket. Simpler than the sync implementation: @@ -47,7 +47,7 @@ import threading from time import perf_counter_ns from typing import (TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, - Optional, Set) + Optional, Set, Tuple) from weakref import WeakSet from aws_advanced_python_wrapper.aio.cleanup import register_shutdown_hook @@ -58,6 +58,7 @@ from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils +from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from aws_advanced_python_wrapper.aio.driver_dialect.base import \ @@ -70,24 +71,17 @@ class AsyncOpenedConnectionTracker: - """Alias-keyed registry of open connections, shared across plugin instances. + """Registry of open connections, shared across plugin instances. - Keys by the RDS **instance** endpoint alias when one is present in - ``host_info.as_aliases()`` -- matching sync's - :class:`OpenedConnectionTracker` at - ``aurora_connection_tracker_plugin.py:47``. Falls back to - ``host_info.as_alias()`` when no RDS instance alias is - discoverable (non-Aurora or custom endpoint connections). + An instance endpoint names the instance already, so its connections are + tracked under one key. Any other endpoint may be a custom domain name, + which is tracked both under the host id and under the endpoint the caller + used, so a later notification naming either one finds the connections. - This lets a cluster-endpoint-connected session still be - invalidated when a later ``CONVERTED_TO_READER`` notification - carries the instance alias. - - Class-level ``_tracked`` mirrors sync ``OpenedConnectionTracker`` at - ``aurora_connection_tracker_plugin.py:47`` so multiple pooled - :class:`AsyncAuroraConnectionTrackerPlugin` instances can coordinate: - one plugin's :meth:`invalidate_all` closes every peer connection to - the same host. + ``_tracked`` is class-level, as sync's registry is, so multiple pooled + :class:`AsyncAuroraConnectionTrackerPlugin` instances coordinate: one + plugin's :meth:`invalidate_all` closes every peer connection to the same + host. Still simpler than sync: @@ -101,74 +95,49 @@ def __init__(self) -> None: # Instance-level nothing -- all state lives on the class dict. pass - @staticmethod - def _canonical_key(host_info: HostInfo) -> str: - """Return the instance-endpoint alias if available, else host:port. + _rds_utils: ClassVar[RdsUtils] = RdsUtils() - Mirrors sync's multi-alias normalization in - ``populate_opened_connection_set``/``invalidate_all_connections``/ - ``remove_connection_tracking`` at - ``aurora_connection_tracker_plugin.py:116-137``. - """ - rds_utils = RdsUtils() - if rds_utils.is_rds_instance(host_info.host): - return host_info.as_alias() - for alias in host_info.as_aliases(): - if rds_utils.is_rds_instance(rds_utils.remove_port(alias)): - return alias - return host_info.as_alias() - - @staticmethod - def _all_keys(host_info: HostInfo) -> Set[str]: - """Return every alias worth tracking ``host_info`` under. - - Sync's ``OpenedConnectionTracker`` tracks connections keyed on - every alias in ``host_info.as_aliases()`` so a later invalidation - via any alias closes the same underlying connection set. We - mirror that here: track under each alias plus the canonical - RDS-instance endpoint. - """ - keys: Set[str] = set() - canonical = AsyncOpenedConnectionTracker._canonical_key(host_info) - if canonical: - keys.add(canonical) - try: - for alias in host_info.as_aliases(): - if alias: - keys.add(alias) - except Exception: # noqa: BLE001 - as_aliases() is best-effort - pass - return keys + @classmethod + def _tracking_keys(cls, host_info: HostInfo) -> Tuple[str, ...]: + """The keys ``host_info``'s connections are tracked under.""" + if cls._rds_utils.is_rds_instance(host_info.host): + return (host_info.get_host_and_port(),) + return tuple( + key for key in (host_info.host_id, host_info.get_host_and_port()) if key) def track(self, host_info: HostInfo, conn: Any) -> None: - for key in self._all_keys(host_info): + for key in self._tracking_keys(host_info): conn_set = AsyncOpenedConnectionTracker._tracked.setdefault( key, WeakSet()) conn_set.add(conn) def remove(self, host_info: HostInfo, conn: Any) -> None: - for key in self._all_keys(host_info): + for key in self._tracking_keys(host_info): conn_set = AsyncOpenedConnectionTracker._tracked.get(key) if conn_set is not None: conn_set.discard(conn) async def invalidate_all(self, host_info: HostInfo) -> None: - """Close every tracked connection reachable via any alias of ``host_info``. - - Best-effort: individual close failures are swallowed so one - broken connection doesn't block closing the rest. Fixes the - prior canonical-key-only semantics that could miss invalidations - when the caller held a non-canonical alias. - """ - # Gather the full connection set from every alias; close each - # connection exactly once, then purge the alias entries. + """Close every connection tracked for ``host_info``.""" logger.debug( "OpenedConnectionTracker.InvalidatingConnections", host_info.url) + await self.invalidate_all_for_keys( + host_info.get_host_and_port(), host_info.host, host_info.host_id) + + async def invalidate_all_for_keys(self, *keys: Optional[str]) -> None: + """Close every connection tracked under any of ``keys``. + + Best-effort: individual close failures are swallowed so one broken + connection does not block closing the rest. + """ seen_conns: Set[int] = set() to_close: list = [] - keys = self._all_keys(host_info) - for key in keys: - conn_set = AsyncOpenedConnectionTracker._tracked.get(key) + present = tuple(key for key in keys if key) + # Drop each key before the first await. Collecting everything first + # and popping afterwards would discard a connection a concurrent + # track() added in between, leaving it open and untracked. + for key in present: + conn_set = AsyncOpenedConnectionTracker._tracked.pop(key, None) if conn_set is None: continue for c in list(conn_set): @@ -205,18 +174,14 @@ async def invalidate_all(self, host_info: HostInfo) -> None: # is_closed=False to its owner. logger.debug( f"[AsyncOpenedConnectionTracker] best-effort close of a " - f"tracked connection to '{host_info.url}' failed: {e}") - - for key in keys: - try: - del AsyncOpenedConnectionTracker._tracked[key] - except KeyError: - pass + f"tracked connection failed: {e}") def _tracked_for(self, host_info: HostInfo) -> WeakSet[Any]: - """Test-only accessor using the canonical key derivation.""" - key = self._canonical_key(host_info) - return AsyncOpenedConnectionTracker._tracked.get(key, WeakSet()) + """Test-only accessor using the first tracking key.""" + keys = self._tracking_keys(host_info) + if not keys: + return WeakSet() + return AsyncOpenedConnectionTracker._tracked.get(keys[0], WeakSet()) def log_opened_connections(self) -> None: """Debug-log the registry contents (sync parity: @@ -295,11 +260,34 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: conn = await connect_func() if conn is not None: - await self._fill_instance_alias(host_info, conn) - self._tracker.track(host_info, conn) - await self._pin_current_writer(host_info, conn) + connection_host_info = await self._identify_connection_host(host_info, conn) + self._tracker.track(connection_host_info, conn) + await self._pin_current_writer(connection_host_info, conn) return conn + async def _identify_connection_host( + self, host_info: HostInfo, conn: Any) -> HostInfo: + """The host this connection actually landed on. + + A cluster, custom-domain or IP endpoint does not name the instance the + connection reached, so ask the database and record the answer as the + routed host. On failure the endpoint the caller used is kept. + """ + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + url_type = AsyncOpenedConnectionTracker._rds_utils.identify_rds_type( + connection_host_info.host) + if not Utils.requires_host_identification(url_type): + return connection_host_info + try: + identified = await self._plugin_service.identify_connection(conn) + except Exception: # noqa: BLE001 - identification is best-effort + return connection_host_info + if identified is None: + return connection_host_info + self._plugin_service.routed_host_info = identified + return identified + async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: """Pin the current writer at connect time so a later failover is detected as a *transition*. @@ -349,39 +337,6 @@ async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: except Exception: # noqa: BLE001 - writer pinning is best-effort pass - async def _fill_instance_alias( - self, host_info: HostInfo, conn: Any) -> None: - """Add the connection's resolved instance endpoint as an alias. - - A cluster-endpoint connection lands on whichever instance the - cluster DNS currently points at, but ``host_info.host`` stays the - cluster endpoint -- so the tracker would key it only under the - cluster alias. On writer failover the change is detected against - the *instance* host (``_current_writer_from_hosts`` returns a - topology row), so ``invalidate_all(writer_instance)`` would never - match the cluster-keyed entry and the stale idle connection would - survive the demotion (``test_writer_failover_in_idle_connections``). - - Mirrors sync ``AuroraConnectionTrackerPlugin.connect`` which calls - ``plugin_service.fill_aliases`` for ``is_rds_cluster`` hosts. Only - cluster-endpoint connections pay the extra identify round-trip; - instance-endpoint connections already key correctly. Best-effort: - on any failure we fall back to cluster-key-only tracking (the - prior behavior), so a transient identify failure never blocks the - connect. - """ - try: - if not RdsUtils().identify_rds_type(host_info.host).is_rds_cluster: - return - identified = await self._plugin_service.identify_connection(conn) - if identified is None: - return - host_info.reset_aliases() - host_info.add_alias(host_info.as_alias()) - host_info.add_alias(*identified.as_aliases()) - except Exception: # noqa: BLE001 - alias enrichment is best-effort - pass - async def execute( self, target: object, @@ -543,14 +498,14 @@ def _current_writer_from_hosts(self) -> Optional[HostInfo]: def _same_host(a: HostInfo, b: HostInfo) -> bool: return a.host == b.host and a.port == b.port - def _spawn_invalidation(self, old_writer: HostInfo) -> None: + def _spawn_invalidation(self, key: str) -> None: """Fire-and-forget invalidation, ONLY for the sync-signature :meth:`notify_host_list_changed` path (cannot await there). The execute/failover path awaits :meth:`_invalidate_writer_change` inline instead -- a spawned task dies un-awaited if the event loop closes before it runs. Pending tasks from this path are drained by :meth:`_shutdown` on ``release_resources_async``.""" - task = asyncio.create_task(self._tracker.invalidate_all(old_writer)) + task = asyncio.create_task(self._tracker.invalidate_all_for_keys(key)) self._pending_invalidations.add(task) task.add_done_callback(self._pending_invalidations.discard) @@ -579,38 +534,15 @@ def notify_host_list_changed( :attr:`_current_writer` so the next ``execute`` re-detects the new writer via :meth:`_update_writer_from_topology`. - With the tracker's canonical-key normalization (instance alias - over cluster alias), a notify carrying the instance alias for a - cluster-connected session now correctly finds and invalidates - the tracked entries. """ - for alias, events in changes.items(): + for host, events in changes.items(): if HostEvent.CONVERTED_TO_READER in events: - host_part, port_part = self._parse_alias(alias) - h = HostInfo(host=host_part, port=port_part) - self._spawn_invalidation(h) + # Change keys are urls; tracking keys are not. + self._spawn_invalidation(host.rstrip("/")) if HostEvent.CONVERTED_TO_WRITER in events: # Force writer recheck on next execute via # _update_writer_from_topology. self._current_writer = None - @staticmethod - def _parse_alias(alias: str) -> tuple: - """Split a ``host:port`` alias into ``(host, port)``. - - Uses ``rpartition(':')`` so IPv6 aliases of the form - ``[::1]:5432`` split correctly on the LAST colon. Falls back to - port 5432 when the alias has no colon (or the port part isn't - numeric). - """ - host_part, sep, port_part = alias.rpartition(":") - if not sep: - # No colon -> treat entire alias as host, port defaults. - return alias, 5432 - try: - return host_part, int(port_part) - except ValueError: - return host_part, 5432 - __all__ = ["AsyncAuroraConnectionTrackerPlugin", "AsyncOpenedConnectionTracker"] diff --git a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py index 20235f68b..d00ff2e83 100644 --- a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py @@ -26,10 +26,6 @@ so auth plugins (IAM, Secrets, Federated, Okta) and connection tracker re-apply on the new connection just like a user-driven connect. -* ``initial_connection_host_info`` is set on the plugin service directly: - ``AsyncPluginServiceImpl`` implements ``AsyncHostListProviderService`` - and ``aio/wrapper.py`` passes it as the host list provider service, so - the two are the same object. """ from __future__ import annotations @@ -102,8 +98,6 @@ def init_host_provider( props: Properties, host_list_provider_service: Any, init_host_provider_func: Callable) -> None: - # Sync captures the service here; async sets initial_connection_host_info on the plugin - # service directly so there is nothing to hold. init_host_provider_func() async def connect( @@ -139,13 +133,13 @@ async def connect( if role_to_verify is None: # No verification required. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn conn_role = await self._plugin_service.get_host_role(candidate_conn) if conn_role == role_to_verify: # Verification succeeded. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn # Verification failed. Retry, unless a reader was requested but the cluster has no readers. @@ -157,7 +151,7 @@ async def connect( logger.debug( "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn logger.debug( @@ -171,7 +165,7 @@ async def connect( if candidate_host is not None: self._plugin_service.set_availability( - candidate_host.as_aliases(), HostAvailability.UNAVAILABLE) + candidate_host, HostAvailability.UNAVAILABLE) if self._plugin_service.is_network_exception(error=e): # Retry connection. @@ -460,13 +454,6 @@ def _has_hosts(self) -> bool: def _has_readers(self) -> bool: return any(host.role == HostRole.READER for host in self._plugin_service.all_hosts) - def _set_initial_connection_host_info( - self, is_initial_connection: bool, host_info: Optional[HostInfo]): - # AsyncPluginServiceImpl implements AsyncHostListProviderService and is passed as the host - # list provider service, so this is the same attribute sync writes through that service. - if is_initial_connection and host_info is not None: - self._plugin_service.initial_connection_host_info = host_info - async def _close_connection( self, connection: Optional[Any], driver_dialect: AsyncDriverDialect) -> None: if connection is None: diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index a61428ecd..7c1898d80 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -400,7 +400,6 @@ async def apply( rerouted_host_info = copy(self._substitute_host_info) rerouted_host_info.host_id = iam_host.host_id rerouted_host_info.availability = HostAvailability.AVAILABLE - rerouted_host_info.add_alias(iam_host.host) rerouted_props = copy(props) WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host) diff --git a/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py b/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py index 0ef7a6f2d..c520ff864 100644 --- a/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py @@ -148,7 +148,7 @@ def __init__( self._is_verified_writer_connection: bool = False self._verified_writer_conn: Optional[Any] = None self._verified_writer_host_info: Optional[HostInfo] = None - self._submitted_host_aliases: Set[str] = set() + self._submitted_hosts: Set[str] = set() self._probe_tasks: Dict[str, asyncio.Task] = {} self._writer_found_event: asyncio.Event = asyncio.Event() @@ -375,8 +375,6 @@ def _role_corrected(self, topology: Topology) -> Topology: if h.role != want_role: fixed = copy.copy(h) fixed.role = want_role - for alias in h.as_aliases(): - fixed.add_alias(alias) corrected.append(fixed) changed = True else: @@ -384,8 +382,6 @@ def _role_corrected(self, topology: Topology) -> Topology: if not found: writer_row = copy.copy(verified) writer_row.role = HostRole.WRITER - for alias in verified.as_aliases(): - writer_row.add_alias(alias) corrected.append(writer_row) changed = True if changed: @@ -429,12 +425,17 @@ async def _wait_for_tick(self, interval: float) -> None: timeout=interval, return_when=asyncio.FIRST_COMPLETED) finally: - for waiter in (stop_waiter, tick_waiter): - if not waiter.done(): - waiter.cancel() - await asyncio.gather( - stop_waiter, tick_waiter, return_exceptions=True) - self._request_tick.clear() + # An application that closes its loop without releasing resources + # leaves this parked. Cancelling or draining a waiter whose loop is + # gone raises, and here that would surface as an unraisable + # exception from the garbage collector. + if not stop_waiter.get_loop().is_closed(): + for waiter in (stop_waiter, tick_waiter): + if not waiter.done(): + waiter.cancel() + await asyncio.gather( + stop_waiter, tick_waiter, return_exceptions=True) + self._request_tick.clear() async def _harvest_verified_writer(self) -> None: """Promote the panic-found verified-writer connection to the monitor's @@ -451,7 +452,7 @@ async def _harvest_verified_writer(self) -> None: if pending: await asyncio.gather(*pending, return_exceptions=True) self._probe_tasks.clear() - self._submitted_host_aliases.clear() + self._submitted_hosts.clear() if conn is None: return if self._connection_factory is None: @@ -480,7 +481,7 @@ def _should_panic(self) -> bool: def _spawn_panic_probes(self) -> None: """Spawn probe tasks for each host in ``last_topology`` not already - submitted. Deduped by ``host_info.as_alias()``. + submitted. Deduped by ``host_info.get_host_and_port()``. """ # Opportunistic cleanup of finished task refs. finished = [k for k, t in self._probe_tasks.items() if t.done()] @@ -488,15 +489,15 @@ def _spawn_panic_probes(self) -> None: self._probe_tasks.pop(k, None) # Release dedup slot so a retry can happen on a later tick if # the earlier probe failed/returned non-writer. - self._submitted_host_aliases.discard(k) + self._submitted_hosts.discard(k) for host_info in self._last_topology: - alias = host_info.as_alias() - if alias in self._submitted_host_aliases: + key = host_info.get_host_and_port() + if key in self._submitted_hosts: continue - self._submitted_host_aliases.add(alias) + self._submitted_hosts.add(key) task = asyncio.create_task(self._probe_and_report(host_info)) - self._probe_tasks[alias] = task + self._probe_tasks[key] = task # Aurora PG briefly rejects IAM/PAM auth on instances mid-promotion # (the PAM service restarts during the writer-role swap). Mirror the @@ -833,7 +834,7 @@ async def _reset(self) -> None: if pending: await asyncio.gather(*pending, return_exceptions=True) self._probe_tasks.clear() - self._submitted_host_aliases.clear() + self._submitted_hosts.clear() await self._drop_owned_connection() if self._verified_writer_conn is not None: await self._close_best_effort(self._verified_writer_conn) diff --git a/aws_advanced_python_wrapper/aio/default_plugin.py b/aws_advanced_python_wrapper/aio/default_plugin.py index 9090b97d9..61ce696bf 100644 --- a/aws_advanced_python_wrapper/aio/default_plugin.py +++ b/aws_advanced_python_wrapper/aio/default_plugin.py @@ -147,18 +147,17 @@ async def force_connect( def _post_connect_bookkeeping(self, host_info: HostInfo, connection_provider: Any) -> None: """Post-connect bookkeeping after a successful connect. - Sync parity: ``DefaultPlugin._connect`` (default_plugin.py:80-82) marks - every alias of the just-connected host AVAILABLE and lets the service - re-pick the driver dialect for the provider that produced the - connection (a no-op on async today). The DATABASE-dialect upgrade + Sync parity: ``DefaultPlugin._connect`` marks the just-connected host + AVAILABLE and lets the service re-pick the driver dialect for the + provider that produced the connection (a no-op on async today). + The DATABASE-dialect upgrade (sync ``plugin_service.update_dialect(conn)``) is invoked by the connect/force_connect callers right after this bookkeeping, mirroring sync's ordering; it is async so it cannot live in this sync helper. """ if self._plugin_service is None: return - self._plugin_service.set_availability( - host_info.as_aliases(), HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE) self._plugin_service.update_driver_dialect(connection_provider) async def execute( diff --git a/aws_advanced_python_wrapper/aio/dialect_utils.py b/aws_advanced_python_wrapper/aio/dialect_utils.py index d01e93bb9..ecb0da57d 100644 --- a/aws_advanced_python_wrapper/aio/dialect_utils.py +++ b/aws_advanced_python_wrapper/aio/dialect_utils.py @@ -23,7 +23,7 @@ from __future__ import annotations import asyncio -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Optional, Tuple from aws_advanced_python_wrapper.errors import (AwsWrapperError, QueryTimeoutError) @@ -83,12 +83,14 @@ async def get_instance_id( conn: Any, driver_dialect: AsyncDriverDialect, host_id_query: str, - timeout_sec: float = 5.0) -> Optional[str]: - """Run the dialect's ``host_id_query`` to learn the Aurora - instance identifier ``conn`` is bound to. Returns ``None`` on - empty result or query failure (best-effort; callers fall back - to topology resolution by host_id). Mirrors sync - DialectUtils.get_instance_id at database_dialect.py. + timeout_sec: float = 5.0) -> Optional[Tuple[str, str]]: + """Run the dialect's ``host_id_query`` for the instance ``conn`` is + bound to, returning ``(instance_id, instance_name)``. + + Aurora returns the same value in both columns. Multi-AZ returns a + numeric id and a short instance name, and callers match on either. + Returns ``None`` on an empty result or a query failure, since + identification is best-effort. """ was_in_txn = await AsyncDialectUtils._safe_in_transaction( conn, driver_dialect) @@ -107,10 +109,12 @@ async def get_instance_id( await AsyncDialectUtils._restore_idle(conn, was_in_txn) if not result: return None - first = result[0] - if first is None: + instance_id = result[0] + if instance_id is None: return None - return str(first) + # A single-column result repeats the id, as the Aurora query does. + instance_name = result[1] if len(result) > 1 and result[1] is not None else instance_id + return str(instance_id), str(instance_name) @staticmethod async def _safe_in_transaction( diff --git a/aws_advanced_python_wrapper/aio/failover_plugin.py b/aws_advanced_python_wrapper/aio/failover_plugin.py index 1655855bc..fa4381427 100644 --- a/aws_advanced_python_wrapper/aio/failover_plugin.py +++ b/aws_advanced_python_wrapper/aio/failover_plugin.py @@ -212,7 +212,7 @@ async def _connect_with_failover( if not self._should_failover(e): raise self._plugin_service.set_availability( - host_info.as_aliases(), HostAvailability.UNAVAILABLE) + host_info, HostAvailability.UNAVAILABLE) await self._do_failover(driver_dialect) else: # Known-dead target: refresh topology and fail over without @@ -424,7 +424,7 @@ async def _do_failover(self, driver_dialect: AsyncDriverDialect) -> None: failed_host = self._plugin_service.current_host_info if failed_host is not None: self._plugin_service.set_availability( - failed_host.as_aliases(), HostAvailability.UNAVAILABLE) + failed_host, HostAvailability.UNAVAILABLE) # Invalidate the current (likely broken) connection before # attempting failover so any pool-proxied target is evicted from @@ -556,7 +556,7 @@ async def _failover_reader_impl( self._open_connection(candidate, driver_dialect), deadline) except Exception as e: # noqa: BLE001 self._plugin_service.set_availability( - candidate.as_aliases(), HostAvailability.UNAVAILABLE) + candidate, HostAvailability.UNAVAILABLE) last_error = e if candidate in remaining: remaining.remove(candidate) @@ -578,7 +578,7 @@ async def _failover_reader_impl( if role == HostRole.READER or self._mode != FailoverMode.STRICT_READER: verified = HostInfo(candidate.host, candidate.port, role) self._plugin_service.set_availability( - candidate.as_aliases(), HostAvailability.AVAILABLE) + candidate, HostAvailability.AVAILABLE) await self._plugin_service.set_current_connection(new_conn, verified) if self._failover_reader_completed is not None: self._failover_reader_completed.inc() @@ -608,7 +608,7 @@ async def _failover_reader_impl( self._open_connection(original_writer, driver_dialect), deadline) except Exception as e: # noqa: BLE001 self._plugin_service.set_availability( - original_writer.as_aliases(), HostAvailability.UNAVAILABLE) + original_writer, HostAvailability.UNAVAILABLE) last_error = e else: role = await self._probe_role(new_conn) @@ -620,7 +620,7 @@ async def _failover_reader_impl( verified = HostInfo( original_writer.host, original_writer.port, role) self._plugin_service.set_availability( - original_writer.as_aliases(), HostAvailability.AVAILABLE) + original_writer, HostAvailability.AVAILABLE) await self._plugin_service.set_current_connection( new_conn, verified) if self._failover_reader_completed is not None: diff --git a/aws_advanced_python_wrapper/aio/host_list_provider.py b/aws_advanced_python_wrapper/aio/host_list_provider.py index 948473081..f9c245ec2 100644 --- a/aws_advanced_python_wrapper/aio/host_list_provider.py +++ b/aws_advanced_python_wrapper/aio/host_list_provider.py @@ -37,6 +37,7 @@ from __future__ import annotations import asyncio +from copy import copy from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, Optional, Protocol, Tuple, runtime_checkable) @@ -46,6 +47,8 @@ from aws_advanced_python_wrapper.aio.topology_utils import ( AsyncAuroraTopologyUtils, AsyncGlobalAuroraTopologyUtils, AsyncMultiAzTopologyUtils, AsyncTopologyUtils) +from aws_advanced_python_wrapper.host_availability import \ + create_host_availability_strategy from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.events import MonitorStopEvent @@ -142,14 +145,21 @@ def __init__(self, props: Properties) -> None: host = props.get("host", "") port_raw = props.get("port") port = int(port_raw) if port_raw is not None else -1 - self._host_info = HostInfo(host=host, port=port, role=HostRole.WRITER) + self._host_info = HostInfo( + host=host, port=port, role=HostRole.WRITER, + host_availability_strategy=create_host_availability_strategy(props)) self._cluster_id = f"static:{host}:{port}" + def _host(self) -> HostInfo: + """A copy, so marking the returned host unavailable does not mark the + one this provider hands to every later caller.""" + return copy(self._host_info) + async def refresh(self, connection: Optional[Any] = None) -> Topology: - return (self._host_info,) + return (self._host(),) async def force_refresh(self, connection: Optional[Any] = None) -> Topology: - return (self._host_info,) + return (self._host(),) def get_cluster_id(self) -> str: return self._cluster_id @@ -441,12 +451,15 @@ def _create_monitor(self, key: TopologyKey) -> Any: # before the teardown stop() scheduled could run, and # release_resources_async only awaits registered hooks. async def _close_and_unregister() -> None: - try: - await monitor.aclose() - finally: - unregister_shutdown_hook(_close_and_unregister) + await monitor.aclose() + + # aclose calls on_closed itself, so this has to be callable without + # awaiting: a coroutine function here is created and dropped, and the + # hook stays registered for the life of the process. + def _unregister() -> None: + unregister_shutdown_hook(_close_and_unregister) - monitor.on_closed = _close_and_unregister + monitor.on_closed = _unregister register_shutdown_hook(_close_and_unregister) return monitor diff --git a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py index 7458f91d7..c26fc7e10 100644 --- a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py @@ -71,6 +71,7 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import \ TelemetryTraceLevel +from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from weakref import ReferenceType @@ -371,7 +372,7 @@ async def _run(self) -> None: if self._is_unhealthy: self._plugin_service.set_availability( - self._host_info.as_aliases(), HostAvailability.UNAVAILABLE) + self._host_info, HostAvailability.UNAVAILABLE) await self._drain_active_contexts() @@ -580,7 +581,7 @@ def __init__( self._failure_detection_count = WrapperProperties.FAILURE_DETECTION_COUNT.get_int(props) self._failure_detection_enabled = WrapperProperties.FAILURE_DETECTION_ENABLED.get_bool(props) - # Subscribe to connect (for cluster-alias resolution) + every + # Subscribe to connect (to record the routed host) + every # network-bound method (so execute() brackets them with monitoring). # notify_* hooks are dispatched to all plugins regardless of this set. self._subscribed: Set[str] = {DbApiMethod.CONNECT.method_name} @@ -600,10 +601,17 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: connection = await connect_func() if connection is not None: - rds_type = self._rds_utils.identify_rds_type(host_info.host) - if rds_type.is_rds_cluster: - host_info.reset_aliases() - await self._fill_aliases(connection, host_info) + # Record which instance a cluster-endpoint connection landed on; + # the monitoring host is derived from it. + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + if self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: + try: + identified = await self._plugin_service.identify_connection(connection) + except Exception: # noqa: BLE001 - identification is best-effort + identified = None + if identified is not None: + self._plugin_service.routed_host_info = identified return connection async def execute( @@ -654,49 +662,34 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]) -> None: _stop_monitors_for_hosts(deleted) async def _get_monitoring_host_info(self) -> HostInfo: - if self._monitoring_host_info is not None: - return self._monitoring_host_info - current_host_info = self._plugin_service.current_host_info - if current_host_info is None: + # Held in a local because notify_connection_changed can clear the + # field while this method is between its assignment and its return. + monitoring_host_info = self._monitoring_host_info + if monitoring_host_info is not None: + return monitoring_host_info + # current_host_info, not routed_host_info: by the time any connection + # exists the wrapper has adopted the routed host, and a value still in + # that field belongs to a connect in flight, possibly another task's. + monitoring_host_info = self._plugin_service.current_host_info + if monitoring_host_info is None: raise AwsWrapperError(Messages.get("HostMonitoringV2Plugin.HostInfoNone")) - self._monitoring_host_info = current_host_info - rds_url_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) + self._monitoring_host_info = monitoring_host_info + rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) try: - if not rds_url_type.is_rds_cluster: - return self._monitoring_host_info + if not Utils.requires_host_identification(rds_url_type): + return monitoring_host_info logger.debug("HostMonitoringV2Plugin.ClusterEndpointHostInfo") - current_connection = self._plugin_service.current_connection - # Async approximation of sync's identify_connection + fill_aliases: - # identify_connection already returns the topology (instance-level) - # HostInfo with its instance aliases, so it doubles as the monitoring - # host and the alias source. - identified = await self._plugin_service.identify_connection(current_connection) - if identified is None: - raise AwsWrapperError(Messages.get_formatted( - "HostMonitoringV2Plugin.UnableToIdentifyConnection", - current_host_info.host, - self._plugin_service.host_list_provider)) - self._monitoring_host_info = identified - except Exception as e: - if isinstance(e, AwsWrapperError): - raise - message = "HostMonitoringV2Plugin.ErrorIdentifyingConnection" - logger.debug(message, e) - raise AwsWrapperError(Messages.get_formatted(message, e)) from e - return self._monitoring_host_info - - async def _fill_aliases(self, connection: Any, host_info: HostInfo) -> None: - """Add the connection's resolved instance endpoint as an alias of a - cluster-endpoint host (async approximation of sync ``fill_aliases``: - ``identify_connection`` + ``as_aliases``). Best-effort.""" - try: - host_info.add_alias(host_info.as_alias()) - identified = await self._plugin_service.identify_connection(connection) + identified = await self._plugin_service.identify_connection( + self._plugin_service.current_connection) if identified is not None: - host_info.add_alias(*identified.as_aliases()) - except Exception: # noqa: BLE001 - alias enrichment is best-effort - pass + monitoring_host_info = identified + self._monitoring_host_info = identified + except Exception as e: # noqa: BLE001 - the host id query failed + # Keep the connection's own host and monitor that. Raising here + # would fail every monitored call on the connection. + logger.debug("HostMonitoringV2Plugin.ErrorIdentifyingConnection", e) + return monitoring_host_info async def release_resources(self) -> None: """Drop this plugin's monitor-service reference. The shared monitors are diff --git a/aws_advanced_python_wrapper/aio/limitless_plugin.py b/aws_advanced_python_wrapper/aio/limitless_plugin.py index 9bd336fe3..4018b1369 100644 --- a/aws_advanced_python_wrapper/aio/limitless_plugin.py +++ b/aws_advanced_python_wrapper/aio/limitless_plugin.py @@ -163,10 +163,18 @@ def __init__( self._limitless_routers = limitless_routers self._connection_plugin = connection_plugin self._plugin_service = plugin_service + self._connection_host_info: Optional[HostInfo] = None def get_host_info(self) -> HostInfo: return self._host_info + def get_connection_host_info(self) -> Optional[HostInfo]: + """The router the connection was actually opened against.""" + return self._connection_host_info + + def set_connection_host_info(self, host_info: HostInfo) -> None: + self._connection_host_info = host_info + def get_props(self) -> Properties: return self._props @@ -486,6 +494,7 @@ async def establish_connection(self, context: AsyncLimitlessContext) -> None: await context.set_connection(await self._plugin_service.connect( selected_host_info, context.get_props(), plugin_to_skip=context.get_connection_plugin())) + context.set_connection_host_info(selected_host_info) except Exception as e: # noqa: BLE001 if self._is_login_exception(e): raise e @@ -542,6 +551,7 @@ async def _retry_connection_with_least_loaded_routers( selected_host_info, context.get_props(), plugin_to_skip=context.get_connection_plugin())) if context.get_connection() is not None: + context.set_connection_host_info(selected_host_info) return except Exception as e: # noqa: BLE001 if self._is_login_exception(e): @@ -762,6 +772,11 @@ async def connect( await self._limitless_router_service.establish_connection(context) connection = context.get_connection() if connection is not None and not await self._plugin_service.driver_dialect.is_closed(connection): + # The connection is on a router, not on the shard group endpoint + # the caller named. + routed_host_info = context.get_connection_host_info() + if routed_host_info is not None: + self._plugin_service.routed_host_info = routed_host_info return connection raise AwsWrapperError(Messages.get_formatted( diff --git a/aws_advanced_python_wrapper/aio/plugin_service.py b/aws_advanced_python_wrapper/aio/plugin_service.py index ba4628192..cd92b57c3 100644 --- a/aws_advanced_python_wrapper/aio/plugin_service.py +++ b/aws_advanced_python_wrapper/aio/plugin_service.py @@ -23,8 +23,8 @@ import asyncio import inspect -from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, FrozenSet, - List, Optional, Protocol, Set, Tuple) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, + Optional, Protocol, Set, Tuple) from aws_advanced_python_wrapper.aio.connection_provider import \ AsyncConnectionProviderManager @@ -42,6 +42,7 @@ ConnectionEvent, HostEvent, OldConnectionSuggestedAction) from aws_advanced_python_wrapper.utils.properties import WrapperProperties from aws_advanced_python_wrapper.utils.storage.cache_map import CacheMap +from aws_advanced_python_wrapper.utils.utils import Utils logger = Logger(__name__) @@ -98,7 +99,7 @@ def database_dialect(self, value: Optional[DatabaseDialect]) -> None: def set_availability( self, - host_aliases: FrozenSet[str], + host_info: HostInfo, availability: HostAvailability) -> None: ... @@ -149,6 +150,27 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: Optional[HostInfo]) -> None: ... + @property + def routed_host_info(self) -> Optional[HostInfo]: + """The host a plugin routed the pending connect to, if any. + + A plugin that connects to a host other than the one it was asked for + records its choice here, and a plugin that wants to know where the + connect went should read it. Do not consume it: connect hooks unwind + from the innermost plugin outwards, so a plugin that took the value + would hide it from every plugin outside it and from the wrapper, which + is what adopts it as the current host. + """ + ... + + @routed_host_info.setter + def routed_host_info(self, value: Optional[HostInfo]) -> None: + ... + + def take_routed_host_info(self) -> Optional[HostInfo]: + """Return the routed host and clear it. For the wrapper's use.""" + ... + async def refresh_host_list( self, connection: Optional[Any] = None) -> None: @@ -190,18 +212,6 @@ async def get_host_role( timeout_sec: Optional[float] = None) -> HostRole: ... - async def fill_aliases( - self, - connection: Optional[Any] = None, - host_info: Optional[HostInfo] = None) -> None: - """Populate ``host_info``'s aliases from the connection. - - Adds the host:port alias plus any aliases reported by the database's - ``host_alias_query`` and by :meth:`identify_connection`. No-op when the - host already has aliases. Mirrors sync ``PluginServiceImpl.fill_aliases``. - """ - ... - async def connect( self, host_info: HostInfo, @@ -392,6 +402,7 @@ def __init__( self._host_list_provider: Optional[AsyncHostListProvider] = None self._all_hosts: Tuple[HostInfo, ...] = () self._initial_connection_host_info: Optional[HostInfo] = None + self._routed_host_info: Optional[HostInfo] = None self._current_host_info: Optional[HostInfo] = host_info self._current_connection: Optional[Any] = None self._telemetry_factory: Optional[TelemetryFactory] = None @@ -500,14 +511,32 @@ def is_read_only_connection_exception( def set_availability( self, - host_aliases: FrozenSet[str], + host_info: HostInfo, availability: HostAvailability) -> None: - for alias in host_aliases: + hosts_to_change = [ + host for host in self._all_hosts if Utils.matches_host(host_info, host)] + if not hosts_to_change: + return + + changes: Dict[str, Set[HostEvent]] = {} + for host in hosts_to_change: + # Through the strategy, not the raw field: a host whose backoff + # window has elapsed reads as available again, and marking it down + # is a change the plugins should hear about. + previous = host.get_availability() + host.set_availability(availability) AsyncPluginServiceImpl._host_availability_expiring_cache.put( - alias, + host.url, availability, AsyncPluginServiceImpl._HOST_AVAILABILITY_EXPIRATION_NANO, ) + if previous != availability: + event = (HostEvent.WENT_UP if availability == HostAvailability.AVAILABLE + else HostEvent.WENT_DOWN) + changes[host.url] = {event, HostEvent.HOST_CHANGED} + + if changes and self._plugin_manager is not None: + self._plugin_manager.notify_host_list_changed(changes) def get_availability(self, host_url: str) -> Optional[HostAvailability]: return AsyncPluginServiceImpl._host_availability_expiring_cache.get(host_url) @@ -684,21 +713,19 @@ async def identify_connection( from aws_advanced_python_wrapper.aio.dialect_utils import \ AsyncDialectUtils - instance_id = await AsyncDialectUtils.get_instance_id( + instance_ids = await AsyncDialectUtils.get_instance_id( conn, self._driver_dialect, self._database_dialect.host_id_query, ) - if instance_id is None: + if instance_ids is None: return None topology = await self._host_list_provider.refresh(conn) - found = next( - (h for h in topology if h.host_id == instance_id), None) + found = Utils.find_host(topology, *instance_ids) if found is None: topology = await self._host_list_provider.force_refresh(conn) - found = next( - (h for h in topology if h.host_id == instance_id), None) + found = Utils.find_host(topology, *instance_ids) return found @property @@ -738,6 +765,19 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: Optional[HostInfo]) -> None: self._initial_connection_host_info = value + @property + def routed_host_info(self) -> Optional[HostInfo]: + return self._routed_host_info + + @routed_host_info.setter + def routed_host_info(self, value: Optional[HostInfo]) -> None: + self._routed_host_info = value + + def take_routed_host_info(self) -> Optional[HostInfo]: + routed = self._routed_host_info + self._routed_host_info = None + return routed + async def refresh_host_list( self, connection: Optional[Any] = None) -> None: @@ -935,64 +975,6 @@ async def get_host_role( timeout_sec=timeout_sec, ) - async def fill_aliases( - self, - connection: Optional[Any] = None, - host_info: Optional[HostInfo] = None) -> None: - """Populate ``host_info``'s aliases -- port of sync - ``PluginServiceImpl.fill_aliases`` (plugin_service.py:671-706). - - Adds the ``host:port`` alias, then any aliases the database reports via - ``host_alias_query``, then the aliases of the host that - :meth:`identify_connection` resolves the connection to. No-op when the - host already carries aliases (idempotent). - """ - connection = self._current_connection if connection is None else connection - host_info = self.current_host_info if host_info is None else host_info - if connection is None or host_info is None: - return - - if len(host_info.aliases) > 0: - logger.debug("PluginServiceImpl.NonEmptyAliases", host_info.aliases) - return - - host_info.add_alias(host_info.as_alias()) - - aux_timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get_float( - self._props) - try: - await asyncio.wait_for( - self._fill_aliases_from_query(connection, host_info), - timeout=aux_timeout_sec) - except asyncio.TimeoutError as e: - from aws_advanced_python_wrapper.errors import QueryTimeoutError - raise QueryTimeoutError( - Messages.get("PluginServiceImpl.FillAliasesTimeout")) from e - except Exception as e: # noqa: BLE001 - alias query is best-effort - logger.debug("PluginServiceImpl.FailedToRetrieveHostPort", e) - - host = await self.identify_connection(connection) - if host: - host_info.add_alias(*host.as_aliases()) - - async def _fill_aliases_from_query( - self, connection: Any, host_info: HostInfo) -> None: - dialect = self._database_dialect - if dialect is None: - return - from aws_advanced_python_wrapper.database_dialect import \ - UnknownDatabaseDialect - if isinstance(dialect, UnknownDatabaseDialect): - return - alias_query = dialect.host_alias_query - if not alias_query: - return - async with connection.cursor() as cur: - await cur.execute(alias_query) - for row in await cur.fetchall(): - if row: - host_info.add_alias(row[0]) - async def connect( self, host_info: HostInfo, @@ -1011,6 +993,9 @@ async def connect( "AsyncPluginService.connect requires target_driver_func " "to be set; AsyncAwsWrapperConnection.connect normally " "wires this.") + # The routed host belongs to one connect. Clearing it here stops this + # connect's plugins reading the host a previous one landed on. + self._routed_host_info = None return await self._plugin_manager.connect( target_driver_func=self._target_driver_func, driver_dialect=self._driver_dialect, @@ -1047,6 +1032,7 @@ async def force_connect( raise AwsWrapperError( "AsyncPluginService.force_connect requires target_driver_func " "to be set; AsyncAwsWrapperConnection.connect normally wires this.") + self._routed_host_info = None return await self._plugin_manager.force_connect( target_driver_func=self._target_driver_func, driver_dialect=self._driver_dialect, @@ -1094,6 +1080,11 @@ async def set_current_connection( self, connection: Any, host_info: HostInfo) -> None: + # Whoever set a routed host has been superseded by this call, which + # names the host the connection is on. Switches that reuse a cached + # connection never run a connect, so this is the only place that + # clears the field for them. + self._routed_host_info = None prev = self._current_connection if prev is None: diff --git a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py index d67c5dbd6..96145ed75 100644 --- a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py @@ -32,6 +32,7 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostRole +from aws_advanced_python_wrapper.pep249 import Error from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages @@ -453,8 +454,16 @@ async def _switch_to_reader_impl( for _ in range(2 * len(reader_candidates)): if not remaining: break - reader = self._plugin_service.get_host_info_by_strategy( - HostRole.READER, strategy, remaining) + try: + reader = self._plugin_service.get_host_info_by_strategy( + HostRole.READER, strategy, remaining) + except Error: + # Every reader is currently marked unavailable. Stop here so + # the caller reports that no reader was available, rather than + # surfacing a host-selector error to the application. Error, + # not AwsWrapperError: the default random selector raises the + # base class, which AwsWrapperError is a subclass of. + break if reader is None: break try: diff --git a/aws_advanced_python_wrapper/aio/retry_util.py b/aws_advanced_python_wrapper/aio/retry_util.py index 8fe668deb..cb6bb63a3 100644 --- a/aws_advanced_python_wrapper/aio/retry_util.py +++ b/aws_advanced_python_wrapper/aio/retry_util.py @@ -128,11 +128,11 @@ async def get_writer_connection( new_conn = await self._bounded( connect_func(writer), timeout_end_time) except Exception as e: # noqa: BLE001 - plugin_service.set_availability(writer.as_aliases(), HostAvailability.UNAVAILABLE) + plugin_service.set_availability(writer, HostAvailability.UNAVAILABLE) last_error = e else: # Connected -> the host is reachable. - plugin_service.set_availability(writer.as_aliases(), HostAvailability.AVAILABLE) + plugin_service.set_availability(writer, HostAvailability.AVAILABLE) # Roles in the topology may be stale right after a failover # (the demoted old writer can still be labeled WRITER), so # verify with a data-plane query before accepting. @@ -222,11 +222,9 @@ async def _refresh_topology_via_reader( reader_conn = await self._bounded( connect_func(reader), timeout_end_time) except Exception: # noqa: BLE001 - try the next reader - plugin_service.set_availability( - reader.as_aliases(), HostAvailability.UNAVAILABLE) + plugin_service.set_availability(reader, HostAvailability.UNAVAILABLE) continue - plugin_service.set_availability( - reader.as_aliases(), HostAvailability.AVAILABLE) + plugin_service.set_availability(reader, HostAvailability.AVAILABLE) try: refreshed = await self._bounded( host_list_provider.force_refresh(reader_conn), timeout_end_time) diff --git a/aws_advanced_python_wrapper/aio/topology_store.py b/aws_advanced_python_wrapper/aio/topology_store.py index d323f7d17..3c85f8ee7 100644 --- a/aws_advanced_python_wrapper/aio/topology_store.py +++ b/aws_advanced_python_wrapper/aio/topology_store.py @@ -29,7 +29,6 @@ from typing import Optional, Tuple from uuid import uuid4 -from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.hostinfo import Topology as StoredTopology from aws_advanced_python_wrapper.utils import services_container @@ -98,22 +97,7 @@ def get_topology( stored = services_container.get_storage_service().get(StoredTopology, key) if stored is None: return None - return tuple(_copy_host(host) for host in stored) - - -def _copy_host(host: HostInfo) -> HostInfo: - """Copy a host, restoring what ``HostInfo.__copy__`` drops. - - It carries neither the aliases, which match a live connection back to its - topology row, nor the availability strategy, which decides when a host - marked unavailable becomes usable again. - """ - clone = copy.copy(host) - clone.host_availability_strategy = host.host_availability_strategy - aliases = host.aliases - if aliases: - clone.add_alias(*aliases) - return clone + return tuple(copy.copy(host) for host in stored) def put_topology(key: Optional[TopologyKey], topology: StoredTopology) -> None: diff --git a/aws_advanced_python_wrapper/aio/topology_utils.py b/aws_advanced_python_wrapper/aio/topology_utils.py index 94c7d11a8..7afa0c157 100644 --- a/aws_advanced_python_wrapper/aio/topology_utils.py +++ b/aws_advanced_python_wrapper/aio/topology_utils.py @@ -27,6 +27,8 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.host_availability import \ + create_host_availability_strategy from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole, Topology from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages @@ -67,9 +69,14 @@ def __init__( self._topology_query = topology_query self._default_port = default_port self._rds_utils = RdsUtils() + # One strategy for every host these utils produce, as the synchronous + # provider does, so the backoff window is per cluster. + self._host_availability_strategy = create_host_availability_strategy(props) self.initial_host_info: HostInfo = HostInfo( - host=str(props.get("host", "")), port=self._port_from_props(default_port)) + host=str(props.get("host", "")), + port=self._port_from_props(default_port), + host_availability_strategy=self._host_availability_strategy) self.instance_template: Optional[HostInfo] = self._build_instance_template() def _port_from_props(self, default_port: int) -> int: @@ -134,8 +141,8 @@ def create_host( # host_id is how identify_connection correlates a live connection # back to its topology row; without it every cluster-endpoint # identification fails. - host_id=str(host_id)) - host_info.add_alias(str(host_id)) + host_id=str(host_id), + host_availability_strategy=self._host_availability_strategy) return host_info def _resolved_port(self) -> int: @@ -333,8 +340,8 @@ def _process_multi_az_query_results( host=host, port=port, role=HostRole.WRITER if row_id == writer_id else HostRole.READER, - host_id=row_id) - host_info.add_alias(host) + host_id=row_id, + host_availability_strategy=self._host_availability_strategy) hosts.append(host_info) if not any(h.role == HostRole.WRITER for h in hosts): @@ -419,8 +426,8 @@ def _process_global_query_results(self, rows: List[tuple]) -> Topology: host=host, port=port, role=HostRole.WRITER if is_writer else HostRole.READER, - host_id=server_id) - host_info.add_alias(host) + host_id=server_id, + host_availability_strategy=self._host_availability_strategy) hosts.append(host_info) writers = [h for h in hosts if h.role == HostRole.WRITER] diff --git a/aws_advanced_python_wrapper/aio/wrapper.py b/aws_advanced_python_wrapper/aio/wrapper.py index 4ec42b833..ac6fba60d 100644 --- a/aws_advanced_python_wrapper/aio/wrapper.py +++ b/aws_advanced_python_wrapper/aio/wrapper.py @@ -1002,7 +1002,11 @@ async def _monitor_conn_factory() -> Any: except Exception: # noqa: BLE001 - best-effort txn cleanup pass - await plugin_service.set_current_connection(target_conn, host_info) + # A plugin may have routed the connect elsewhere; that is the host this + # connection is actually on. + routed = plugin_service.take_routed_host_info() + await plugin_service.set_current_connection( + target_conn, routed if routed is not None else host_info) return AsyncAwsWrapperConnection(plugin_service, plugin_manager) def cursor(self, *args: Any, **kwargs: Any) -> AsyncAwsWrapperCursor: diff --git a/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py b/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py index 012f88fd6..80453d982 100644 --- a/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py +++ b/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py @@ -17,8 +17,8 @@ import threading from threading import Thread from time import perf_counter_ns -from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, FrozenSet, - Optional, Set) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, Optional, + Set, Tuple) from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.utils import Utils @@ -29,7 +29,6 @@ from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.pep249 import Connection - from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType from aws_advanced_python_wrapper.utils.properties import Properties from _weakrefset import WeakSet @@ -113,87 +112,83 @@ def _prune_connections(cls): if not conn_set and host in cls._opened_connections: del cls._opened_connections[host] - def populate_opened_connection_set(self, host_info: HostInfo, conn: Connection): + def _tracking_keys(self, host_info: HostInfo) -> Tuple[str, ...]: + """The keys ``host_info``'s connections are tracked under. + + An instance endpoint names the instance already, so one key is enough. + Anything else may be a custom domain name, which is tracked both under + the host id and under the endpoint the caller used. + """ + if self._rds_utils.is_rds_instance(host_info.host): + return (host_info.get_host_and_port(),) + return tuple(key for key in (host_info.host_id, host_info.get_host_and_port()) if key) + + def populate_opened_connection_set(self, host_info: Optional[HostInfo], conn: Optional[Connection]): """ Add the given connection to the set of tracked connections. :param host_info: host information of the given connection. :param conn: currently opened connection. """ - - aliases: FrozenSet[str] = host_info.as_aliases() - - if self._rds_utils.is_rds_instance(host_info.host): - self._track_connection(host_info.url, conn) + if host_info is None or conn is None: return - instance_endpoint: Optional[str] = next( - (alias for alias in aliases if self._rds_utils.is_rds_instance(self._rds_utils.remove_port(alias))), None) - if not instance_endpoint: + keys = self._tracking_keys(host_info) + if not keys: logger.debug("OpenedConnectionTracker.UnableToPopulateOpenedConnectionSet") return - instance_endpoint = instance_endpoint if instance_endpoint.endswith("/") else instance_endpoint + "/" - self._track_connection(instance_endpoint, conn) + for key in keys: + self._track_connection(key, conn) - def invalidate_all_connections(self, host_info: Optional[HostInfo] = None, host: Optional[FrozenSet[str]] = None): + def invalidate_all_connections(self, host_info: Optional[HostInfo]): """ Invalidates all opened connections pointing to the same host in a daemon thread. - :param host_info: the :py:class:`HostInfo` object containing the URL of the host. - :param host: the set of aliases representing a specific host. + :param host_info: the host whose connections should be closed. """ - - if host_info: - self.invalidate_all_connections(host=frozenset([host_info.url])) - self.invalidate_all_connections(host=host_info.as_aliases()) - return - - instance_endpoint: Optional[str] = None - if host is None: + if host_info is None: return + self.invalidate_all_connections_for_keys( + host_info.get_host_and_port(), host_info.host, host_info.host_id) - for instance in host: - if instance is not None and self._rds_utils.is_rds_instance(self._rds_utils.remove_port(instance)): - instance_endpoint = instance - break + def invalidate_all_connections_for_keys(self, *keys: Optional[str]): + """Invalidate the connections tracked under any of ``keys``. - if not instance_endpoint: - return - - instance_endpoint = instance_endpoint if instance_endpoint.endswith("/") else instance_endpoint + "/" + A connection tracked under more than one key is closed once: closing + a pool-proxied connection twice would invalidate whatever the pool + handed out in between. + """ + present = [key for key in keys if key] + seen: Set[int] = set() + to_close: list = [] with self._lock: - connection_set: Optional[WeakSet] = self._opened_connections.get(instance_endpoint) - if connection_set is not None: - connections_list = list(connection_set) + for key in present: + connection_set: Optional[WeakSet] = self._opened_connections.get(key) + if connection_set is None: + continue + for conn in list(connection_set): + if id(conn) not in seen: + seen.add(id(conn)) + to_close.append(conn) connection_set.clear() - else: - connections_list = None - if connections_list: - self._log_connection_set(instance_endpoint, connections_list) - self._invalidate_connections(connections_list) + if to_close: + self._log_connection_set(", ".join(present), to_close) + self._invalidate_connections(to_close) def remove_connection_tracking(self, host_info: HostInfo, connection: Connection | None): if not connection: return - if self._rds_utils.is_rds_instance(host_info.host): - host = host_info.url - else: - host = next((alias for alias in host_info.as_aliases() - if self._rds_utils.is_rds_instance(self._rds_utils.remove_port(alias))), "") - - if not host: - return - - host = host if host.endswith("/") else host + "/" - + # Every key populate_opened_connection_set used, so a custom-domain + # connection is untracked from both of its keys. with self._lock: - connection_set = self._opened_connections.get(host) - if connection_set: - connection_set.discard(connection) + for key in self._tracking_keys(host_info): + connection_set = self._opened_connections.get(key) + if connection_set: + connection_set.discard(connection) def _track_connection(self, instance_endpoint: str, conn: Connection): with self._lock: @@ -292,12 +287,23 @@ def connect( conn = connect_func() if conn: - url_type: RdsUrlType = self._rds_utils.identify_rds_type(host_info.host) - if url_type.is_rds_cluster: - host_info.reset_aliases() - self._plugin_service.fill_aliases(conn, host_info) - - self._tracker.populate_opened_connection_set(host_info, conn) + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + url_type = self._rds_utils.identify_rds_type(connection_host_info.host) + if Utils.requires_host_identification(url_type): + # The endpoint does not name the instance the connection + # landed on, so ask the database and track that instead. + # Best-effort: a connect must not fail because the host id + # query did. + try: + identified = self._plugin_service.identify_connection(conn) + except Exception: # noqa: BLE001 - identification is best-effort + identified = None + if identified is not None: + connection_host_info = identified + self._plugin_service.routed_host_info = identified + + self._tracker.populate_opened_connection_set(connection_host_info, conn) self._tracker.log_opened_connections() return conn @@ -359,10 +365,11 @@ def _check_writer_changed(self, need_refresh_host_lists: bool): self._need_update_current_writer = False def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): - for node, node_changes in changes.items(): - if HostEvent.CONVERTED_TO_READER in node_changes: - self._tracker.invalidate_all_connections(host=frozenset([node])) - if HostEvent.CONVERTED_TO_WRITER in node_changes: + for host, host_changes in changes.items(): + if HostEvent.CONVERTED_TO_READER in host_changes: + # Change keys are urls; tracking keys are not. + self._tracker.invalidate_all_connections_for_keys(host.rstrip("/")) + if HostEvent.CONVERTED_TO_WRITER in host_changes: self._need_update_current_writer = True diff --git a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py index 8eae5cf7b..2dd6e4023 100644 --- a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py @@ -108,7 +108,6 @@ class AuroraInitialConnectionStrategyPlugin(Plugin): def __init__(self, plugin_service: PluginService, props: Properties): self._plugin_service: PluginService = plugin_service self._rds_utils = RdsUtils() - self._host_list_provider_service: Optional[HostListProviderService] = None self._accessible_regions: Optional[FrozenSet[str]] = AccessibleRegions.parse(props) self._retry_delay_ms: int = WrapperProperties.OPEN_CONNECTION_RETRY_INTERVAL_MS.get_int(props) @@ -138,7 +137,6 @@ def init_host_provider( props: Properties, host_list_provider_service: HostListProviderService, init_host_provider_func: Callable): - self._host_list_provider_service = host_list_provider_service init_host_provider_func() def connect( @@ -172,13 +170,13 @@ def connect( if role_to_verify is None: # No verification required. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn conn_role = self._plugin_service.get_host_role(candidate_conn) if conn_role == role_to_verify: # Verification succeeded. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn # Verification failed. Retry, unless a reader was requested but the cluster has no readers. @@ -190,7 +188,7 @@ def connect( logger.debug( "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn logger.debug( @@ -204,7 +202,7 @@ def connect( if candidate_host is not None: self._plugin_service.set_availability( - candidate_host.as_aliases(), HostAvailability.UNAVAILABLE) + candidate_host, HostAvailability.UNAVAILABLE) if self._plugin_service.is_network_exception(e): # Retry connection. @@ -487,13 +485,6 @@ def _get_candidate_host( # Unable to find a candidate host. return None - def _set_initial_connection_host_info( - self, is_initial_connection: bool, host_info: Optional[HostInfo]): - if (is_initial_connection - and self._host_list_provider_service is not None - and host_info is not None): - self._host_list_provider_service.initial_connection_host_info = host_info - @staticmethod def _find_writer(hosts: Sequence[HostInfo]) -> Optional[HostInfo]: """Return the first WRITER in ``hosts``, or ``None``. diff --git a/aws_advanced_python_wrapper/aws_credentials_manager.py b/aws_advanced_python_wrapper/aws_credentials_manager.py index bee5499d0..36b6ef35a 100644 --- a/aws_advanced_python_wrapper/aws_credentials_manager.py +++ b/aws_advanced_python_wrapper/aws_credentials_manager.py @@ -34,7 +34,7 @@ class AwsCredentialsManager: @staticmethod def get_session(host_info: HostInfo, props: Properties, region: Optional[str] = None) -> Session: profile_name = WrapperProperties.AWS_PROFILE.get(props) - host_key = f'{host_info.as_alias()}{region}{profile_name}' + host_key = f'{host_info.get_host_and_port()}{region}{profile_name}' with AwsCredentialsManager._lock: if host_key in AwsCredentialsManager._sessions: diff --git a/aws_advanced_python_wrapper/blue_green_plugin.py b/aws_advanced_python_wrapper/blue_green_plugin.py index 3e65d3a1a..19adb9d56 100644 --- a/aws_advanced_python_wrapper/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/blue_green_plugin.py @@ -401,7 +401,6 @@ def apply( rerouted_host_info = copy(self._substitute_host_info) rerouted_host_info.host_id = iam_host.host_id rerouted_host_info.availability = HostAvailability.AVAILABLE - rerouted_host_info.add_alias(iam_host.host) rerouted_props = copy(props) WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host) diff --git a/aws_advanced_python_wrapper/database_dialect.py b/aws_advanced_python_wrapper/database_dialect.py index 4c092c507..c944be62a 100644 --- a/aws_advanced_python_wrapper/database_dialect.py +++ b/aws_advanced_python_wrapper/database_dialect.py @@ -135,11 +135,6 @@ class DatabaseDialect(Protocol): def default_port(self) -> int: ... - @property - @abstractmethod - def host_alias_query(self) -> str: - ... - @property @abstractmethod def server_version_query(self) -> str: @@ -217,10 +212,6 @@ class MysqlDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return 3306 - @property - def host_alias_query(self) -> str: - return f"SELECT {self._HOST_ID_EXPRESSION}" - @property def server_version_query(self) -> str: return "SHOW VARIABLES LIKE 'version_comment'" @@ -279,10 +270,6 @@ class PgDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return 5432 - @property - def host_alias_query(self) -> str: - return f"SELECT {self._HOST_ID_EXPRESSION}" - @property def server_version_query(self) -> str: return "SELECT 'version', pg_catalog.VERSION()" @@ -828,10 +815,6 @@ class UnknownDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return HostInfo.NO_PORT - @property - def host_alias_query(self) -> str: - return "" - @property def server_version_query(self) -> str: return "" @@ -1098,7 +1081,16 @@ def get_instance_id(conn: Connection, driver_dialect: DriverDialect, instance_id thread_pool, timeout_sec: float) -> Optional[Tuple[str, str]]: cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( thread_pool, timeout_sec, driver_dialect, conn)(DialectUtils._execute_instance_id_query) - result = cursor_execute_func_with_timeout(conn, instance_id_query) + try: + result = cursor_execute_func_with_timeout(conn, instance_id_query) + except TimeoutError: + # A timeout is transient, so it stays an error the caller can see. + raise + except Exception: # noqa: BLE001 - see below + # A host whose id the database declines to report is simply + # unidentifiable, which every caller handles. Raising instead + # would fail a connect over a host the caller never needed named. + return None if result is not None and len(result) >= 2: return (str(result[0]), str(result[1])) diff --git a/aws_advanced_python_wrapper/default_plugin.py b/aws_advanced_python_wrapper/default_plugin.py index 3d0a92fd3..48fbd0b8e 100644 --- a/aws_advanced_python_wrapper/default_plugin.py +++ b/aws_advanced_python_wrapper/default_plugin.py @@ -77,7 +77,7 @@ def _connect( if context is not None: context.close_context() - self._plugin_service.set_availability(host_info.all_aliases, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE) self._plugin_service.update_driver_dialect(conn_provider) self._plugin_service.update_dialect(conn) diff --git a/aws_advanced_python_wrapper/failover_plugin.py b/aws_advanced_python_wrapper/failover_plugin.py index 99157f659..6ae4d8f47 100644 --- a/aws_advanced_python_wrapper/failover_plugin.py +++ b/aws_advanced_python_wrapper/failover_plugin.py @@ -171,7 +171,7 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args: self._invalidate_current_connection() if self._plugin_service.current_host_info is not None: self._plugin_service.set_availability( - self._plugin_service.current_host_info.aliases, HostAvailability.UNAVAILABLE) + self._plugin_service.current_host_info, HostAvailability.UNAVAILABLE) self._pick_new_connection() self._last_exception = ex @@ -192,10 +192,6 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): if self._is_host_still_valid(current_host.url, changes): return - for alias in current_host.aliases: - if self._is_host_still_valid(alias + '/', changes): - return - logger.debug("FailoverPlugin.InvalidHost", current_host) finally: self._stale_dns_helper.notify_host_list_changed(changes) @@ -237,7 +233,7 @@ def _failover(self, failed_host: Optional[HostInfo]): :param failed_host: The host with network errors. """ if failed_host is not None: - self._plugin_service.set_availability(failed_host.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(failed_host, HostAvailability.UNAVAILABLE) if self._failover_mode == FailoverMode.STRICT_WRITER: self._failover_writer() @@ -264,10 +260,6 @@ def _failover_reader(self, failed_host: Optional[HostInfo]): try: logger.info("FailoverPlugin.StartReaderFailover") - old_aliases = None - if self._plugin_service.current_host_info is not None: - old_aliases = self._plugin_service.current_host_info.aliases - if failed_host is not None and failed_host.get_raw_availability() != HostAvailability.AVAILABLE: failed_host = None @@ -282,9 +274,6 @@ def _failover_reader(self, failed_host: Optional[HostInfo]): if result.connection is not None and result.new_host is not None: self._plugin_service.set_current_connection(result.connection, result.new_host) - if self._plugin_service.current_host_info is not None and old_aliases is not None and len(old_aliases) > 0: - self._plugin_service.current_host_info.remove_alias(old_aliases) - self._update_topology(True) logger.info("FailoverPlugin.EstablishedConnection", self._plugin_service.current_host_info) diff --git a/aws_advanced_python_wrapper/failover_v2_plugin.py b/aws_advanced_python_wrapper/failover_v2_plugin.py index 260706367..65e365d4a 100644 --- a/aws_advanced_python_wrapper/failover_v2_plugin.py +++ b/aws_advanced_python_wrapper/failover_v2_plugin.py @@ -158,7 +158,7 @@ def connect( if not self._should_exception_trigger_connection_switch(e): raise e - self._plugin_service.set_availability(host_info.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(host_info, HostAvailability.UNAVAILABLE) try: self._failover() @@ -200,7 +200,7 @@ def _deal_with_original_exception(self, original_exception: Exception) -> None: (self._should_exception_trigger_connection_switch(original_exception))): self._invalidate_current_connection() self._plugin_service.set_availability( - self._plugin_service.current_host_info.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.current_host_info, HostAvailability.UNAVAILABLE) self._pick_new_connection() self._last_exception_dealt_with = original_exception diff --git a/aws_advanced_python_wrapper/host_list_provider.py b/aws_advanced_python_wrapper/host_list_provider.py index 8d6164ca5..da0bef9f9 100644 --- a/aws_advanced_python_wrapper/host_list_provider.py +++ b/aws_advanced_python_wrapper/host_list_provider.py @@ -18,6 +18,7 @@ from abc import ABC, abstractmethod from concurrent.futures import TimeoutError from contextlib import closing +from copy import copy from dataclasses import dataclass from datetime import datetime from threading import RLock @@ -220,7 +221,7 @@ def _get_topology(self, conn: Optional[Connection], force_update: bool = False) if not conn: # Cannot fetch topology without a connection # Return the original hosts passed to the connect method - return RdsHostListProvider.FetchTopologyResult(self._initial_hosts, False) + return RdsHostListProvider.FetchTopologyResult(self._copy_initial_hosts(), False) hosts = self._force_refresh_monitor(False, self._DEFAULT_TOPOLOGY_QUERY_TIMEOUT_SEC) if hosts is not None and len(hosts) > 0: @@ -229,7 +230,17 @@ def _get_topology(self, conn: Optional[Connection], force_update: bool = False) if cached_hosts: return RdsHostListProvider.FetchTopologyResult(cached_hosts, True) else: - return RdsHostListProvider.FetchTopologyResult(self._initial_hosts, False) + return RdsHostListProvider.FetchTopologyResult(self._copy_initial_hosts(), False) + + def _copy_initial_hosts(self) -> Topology: + """Copies, because the caller publishes these as the host list. + + These are built once and never replaced, so marking a host handed out + here would mark it for every later caller. Hosts from a topology query + are replaced by each refresh, so they are left shared, which is what + makes an availability mark visible across connections. + """ + return tuple(copy(host) for host in self._initial_hosts) def _get_or_create_monitor(self) -> Optional[ClusterTopologyMonitor]: """Get or create monitor - matches Java's getOrCreateMonitor""" @@ -353,11 +364,16 @@ def _initialize(self): def refresh(self, connection: Optional[Connection] = None) -> Topology: self._initialize() - return tuple(self._hosts) + return self._copy_hosts() def force_refresh(self, connection: Optional[Connection] = None) -> Topology: self._initialize() - return tuple(self._hosts) + return self._copy_hosts() + + def _copy_hosts(self) -> Topology: + """Copies, for the same reason as ``RdsHostListProvider``: this host + list is built once.""" + return tuple(copy(host) for host in self._hosts) def get_current_topology(self, connection: Connection, initial_host_info: HostInfo) -> Topology: self._initialize() @@ -553,7 +569,6 @@ def create_host( role=HostRole.WRITER if is_writer else HostRole.READER, last_update_time=last_update, host_id=host_id) - host_info.add_alias(host_id) return host_info def get_writer_id_if_connected(self, connection: Connection, driver_dialect: DriverDialect) -> Optional[str]: @@ -696,9 +711,10 @@ def _create_multi_az_host(self, record: Tuple, writer_id: str) -> HostInfo: if host.find(":") > -1: host, port = host.split(":") + # MySQL reports a numeric id. host_id is compared against the string + # host_id_query returns, so store it as a string. host_info = HostInfo( - host=host, port=port, role=role, availability=HostAvailability.AVAILABLE, weight=0, host_id=id) - host_info.add_alias(host) + host=host, port=port, role=role, availability=HostAvailability.AVAILABLE, weight=0, host_id=str(id)) return host_info diff --git a/aws_advanced_python_wrapper/host_monitoring_plugin.py b/aws_advanced_python_wrapper/host_monitoring_plugin.py index 4f19ca96f..006c903ea 100644 --- a/aws_advanced_python_wrapper/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/host_monitoring_plugin.py @@ -26,7 +26,7 @@ from queue import Queue from threading import Event, Lock, Thread from time import perf_counter_ns -from typing import Any, Callable, Dict, FrozenSet, Optional, Set +from typing import Any, Callable, Dict, Optional, Set from _weakref import ReferenceType, ref @@ -48,7 +48,7 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import ( TelemetryCounter, TelemetryTraceLevel) -from aws_advanced_python_wrapper.utils.utils import QueueUtils +from aws_advanced_python_wrapper.utils.utils import QueueUtils, Utils logger = Logger(__name__) @@ -99,12 +99,23 @@ def connect( connect_func: Callable) -> Connection: conn = connect_func() if conn: - rds_type = self._rds_utils.identify_rds_type(host_info.host) - if rds_type.is_rds_cluster: - host_info.reset_aliases() - self._plugin_service.fill_aliases(conn, host_info) + self._record_routed_host(host_info, conn) return conn + def _record_routed_host(self, host_info: HostInfo, conn: Connection): + """Record which instance a cluster-endpoint connection landed on, since + the monitoring host is derived from it.""" + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + if not self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: + return + try: + identified = self._plugin_service.identify_connection(conn) + except Exception: # noqa: BLE001 - identification is best-effort + return + if identified is not None: + self._plugin_service.routed_host_info = identified + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: connection = self._plugin_service.current_connection if connection is None: @@ -124,7 +135,6 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg logger.debug("HostMonitoringPlugin.ActivatedMonitoring", method_name) monitor_context = self._monitor_service.start_monitoring( connection, - self._get_monitoring_host_info().all_aliases, self._get_monitoring_host_info(), self._props, self._failure_detection_time_ms, @@ -136,18 +146,23 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg if monitor_context: with self._lock: self._monitor_service.stop_monitoring(monitor_context) - if monitor_context.is_host_unavailable(): - self._plugin_service.set_availability( - self._get_monitoring_host_info().all_aliases, HostAvailability.UNAVAILABLE) - - driver_dialect = self._plugin_service.driver_dialect - if driver_dialect is not None and not driver_dialect.is_closed(connection): - try: - connection.close() - except Exception: - pass - raise AwsWrapperError( - Messages.get_formatted("HostMonitoringPlugin.UnavailableHost", host_info.as_alias())) + host_unavailable = monitor_context.is_host_unavailable() + + # Outside the lock: set_availability dispatches to every + # plugin, so holding it here would run arbitrary plugin code + # with this connection's monitoring serialised behind it. + if host_unavailable: + self._plugin_service.set_availability( + self._get_monitoring_host_info(), HostAvailability.UNAVAILABLE) + + driver_dialect = self._plugin_service.driver_dialect + if driver_dialect is not None and not driver_dialect.is_closed(connection): + try: + connection.close() + except Exception: + pass + raise AwsWrapperError( + Messages.get_formatted("HostMonitoringPlugin.UnavailableHost", host_info.get_host_and_port())) logger.debug("HostMonitoringPlugin.MonitoringDeactivated", method_name) return result @@ -160,44 +175,47 @@ def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnect return OldConnectionSuggestedAction.NO_OPINION def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): - if not self._is_connection_initialized: + # Closing a connection drops this plugin's reference to the monitor + # service, and a failover worker outliving that close can still reach + # this plugin when it publishes availability. + if not self._is_connection_initialized or self._monitor_service is None: return for host, events in changes.items(): if HostEvent.WENT_DOWN not in events and HostEvent.HOST_DELETED not in events: - return - - monitoring_aliases = self._get_monitoring_host_info().all_aliases - if len(monitoring_aliases) == 0: - return + continue - if host in monitoring_aliases: - self._monitor_service.stop_monitoring_host(monitoring_aliases) + if host == self._get_monitoring_host_info().url: + self._monitor_service.stop_monitoring_host(host) def _get_monitoring_host_info(self) -> HostInfo: - if self._monitoring_host_info is None: - current_host_info = self._plugin_service.current_host_info - if current_host_info is None: + # Held in a local because notify_connection_changed can clear the + # field while this method is between its assignment and its return. + monitoring_host_info = self._monitoring_host_info + if monitoring_host_info is None: + # current_host_info, not routed_host_info: by the time any + # connection exists the wrapper has adopted the routed host, and + # a value still in that field belongs to a connect in flight, + # possibly another thread's. + monitoring_host_info = self._plugin_service.current_host_info + if monitoring_host_info is None: raise AwsWrapperError("HostMonitoringPlugin.HostInfoNone") - self._monitoring_host_info = current_host_info - rds_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) + self._monitoring_host_info = monitoring_host_info + rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) try: - if rds_type.is_rds_cluster: + if Utils.requires_host_identification(rds_url_type): logger.debug("HostMonitoringPlugin.ClusterEndpointHostInfo") - self._monitoring_host_info = self._plugin_service.identify_connection() - if self._monitoring_host_info is None: - raise AwsWrapperError( - Messages.get_formatted( - "HostMonitoringPlugin.UnableToIdentifyConnection", - current_host_info.host, - self._plugin_service.host_list_provider)) - self._plugin_service.fill_aliases(host_info=self._monitoring_host_info) - except Exception as e: - message = "HostMonitoringPlugin.ErrorIdentifyingConnection" - logger.debug(message, e) - raise AwsWrapperError(Messages.get_formatted(message, e)) from e - return self._monitoring_host_info + identified = self._plugin_service.identify_connection( + self._plugin_service.current_connection) + if identified is not None: + monitoring_host_info = identified + self._monitoring_host_info = identified + except Exception as e: # noqa: BLE001 - the host id query failed + # Keep the connection's own host and monitor that. Raising + # here would fail every monitored call on the connection. + logger.debug("HostMonitoringPlugin.ErrorIdentifyingConnection", e) + return monitoring_host_info def release_resources(self): self._monitor_service = None @@ -585,7 +603,7 @@ def sleep(self, duration: int): class HostMonitorService: def __init__(self, plugin_service: PluginService): self._plugin_service: PluginService = plugin_service - self._cached_monitor_aliases: Optional[FrozenSet[str]] = None + self._cached_monitor_host_url: Optional[str] = None self._cached_monitor: Optional[ReferenceType[Monitor]] = None telemetry_factory = self._plugin_service.get_telemetry_factory() @@ -599,26 +617,23 @@ def __init__(self, plugin_service: PluginService): def start_monitoring(self, conn: Connection, - host_aliases: FrozenSet[str], host_info: HostInfo, props: Properties, failure_detection_time_ms: int, failure_detection_interval_ms: int, failure_detection_count: int) -> MonitoringContext: - if not host_aliases: - raise AwsWrapperError(Messages.get_formatted("MonitorService.EmptyAliasSet", host_info)) + host_url = host_info.url monitor: Optional[Monitor] = None if self._cached_monitor is None else self._cached_monitor() if monitor is None \ or monitor.is_stopped \ - or self._cached_monitor_aliases is None \ - or self._cached_monitor_aliases != host_aliases: - monitor = self._monitor_service.run_if_absent_with_aliases( + or self._cached_monitor_host_url != host_url: + monitor = self._monitor_service.run_if_absent( Monitor, - host_aliases, + host_url, lambda: Monitor(self._plugin_service, host_info, props)) self._cached_monitor = ref(monitor) - self._cached_monitor_aliases = host_aliases + self._cached_monitor_host_url = host_url context = MonitoringContext( monitor, conn, self._plugin_service.driver_dialect, failure_detection_time_ms, @@ -631,9 +646,7 @@ def stop_monitoring(context: MonitoringContext): monitor = context.monitor monitor.stop_monitoring(context) - def stop_monitoring_host(self, host_aliases: FrozenSet): - for alias in host_aliases: - monitor = self._monitor_service.get(Monitor, alias) - if monitor is not None: - monitor.clear_contexts() - return + def stop_monitoring_host(self, host_url: str): + monitor = self._monitor_service.get(Monitor, host_url) + if monitor is not None: + monitor.clear_contexts() diff --git a/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py b/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py index f0ac4fb9d..3427add66 100644 --- a/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py +++ b/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py @@ -41,6 +41,7 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import ( TelemetryCounter, TelemetryFactory, TelemetryTraceLevel) +from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from aws_advanced_python_wrapper.driver_dialect import DriverDialect @@ -87,10 +88,17 @@ def connect( connect_func: Callable) -> Connection: connection = connect_func() if connection: - rds_type = self._rds_utils.identify_rds_type(host_info.host) - if rds_type.is_rds_cluster: - host_info.reset_aliases() - self._plugin_service.fill_aliases(connection, host_info) + # Record which instance a cluster-endpoint connection landed on; + # the monitoring host is derived from it. + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + if self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: + try: + identified = self._plugin_service.identify_connection(connection) + except Exception: # noqa: BLE001 - identification is best-effort + identified = None + if identified is not None: + self._plugin_service.routed_host_info = identified return connection def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: @@ -126,34 +134,34 @@ def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnect return OldConnectionSuggestedAction.NO_OPINION def _get_monitoring_host_info(self) -> HostInfo: - if self._monitoring_host_info is not None: - return self._monitoring_host_info - current_host_info = self._plugin_service.current_host_info - if current_host_info is None: + # Held in a local because notify_connection_changed can clear the + # field while this method is between its assignment and its return. + monitoring_host_info = self._monitoring_host_info + if monitoring_host_info is not None: + return monitoring_host_info + # current_host_info, not routed_host_info: by the time any connection + # exists the wrapper has adopted the routed host, and a value still in + # that field belongs to a connect in flight, possibly another thread's. + monitoring_host_info = self._plugin_service.current_host_info + if monitoring_host_info is None: raise AwsWrapperError(Messages.get("HostMonitoringV2Plugin.HostInfoNone")) - self._monitoring_host_info = current_host_info - rds_url_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) + self._monitoring_host_info = monitoring_host_info + rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) try: - if not rds_url_type.is_rds_cluster: - return self._monitoring_host_info + if not Utils.requires_host_identification(rds_url_type): + return monitoring_host_info logger.debug("HostMonitoringV2Plugin.ClusterEndpointHostInfo") - current_connection = self._plugin_service.current_connection - self._monitoring_host_info = self._plugin_service.identify_connection(current_connection) - if self._monitoring_host_info is None: - raise AwsWrapperError( - Messages.get_formatted( - "HostMonitoringV2Plugin.UnableToIdentifyConnection", - current_host_info.host, - self._plugin_service.host_list_provider)) - self._plugin_service.fill_aliases(current_connection, self._monitoring_host_info) - except Exception as e: - if isinstance(e, AwsWrapperError): - raise e - message = "HostMonitoringV2Plugin.ErrorIdentifyingConnection" - logger.debug(message, e) - raise AwsWrapperError(Messages.get_formatted(message, e)) from e - return self._monitoring_host_info + identified = self._plugin_service.identify_connection( + self._plugin_service.current_connection) + if identified is not None: + monitoring_host_info = identified + self._monitoring_host_info = identified + except Exception as e: # noqa: BLE001 - the host id query failed + # Keep the connection's own host and monitor that. Raising here + # would fail every monitored call on the connection. + logger.debug("HostMonitoringV2Plugin.ErrorIdentifyingConnection", e) + return monitoring_host_info def release_resources(self): if self._monitor_service is not None: @@ -333,7 +341,7 @@ def run(self) -> None: self._update_host_health_status(is_valid, status_check_start_time_ns, status_check_end_time_ns) if self._is_unhealthy: - self._plugin_service.set_availability(self._host_info.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(self._host_info, HostAvailability.UNAVAILABLE) temp_active_context_weak_refs = [] while not self._active_contexts.empty(): diff --git a/aws_advanced_python_wrapper/hostinfo.py b/aws_advanced_python_wrapper/hostinfo.py index 5c9893a9f..3aa895de9 100644 --- a/aws_advanced_python_wrapper/hostinfo.py +++ b/aws_advanced_python_wrapper/hostinfo.py @@ -16,8 +16,7 @@ from dataclasses import dataclass from enum import Enum, auto -from typing import (TYPE_CHECKING, ClassVar, FrozenSet, Optional, Set, Tuple, - TypeAlias) +from typing import TYPE_CHECKING, ClassVar, Optional, Tuple, TypeAlias from aws_advanced_python_wrapper.host_availability import ( HostAvailability, HostAvailabilityStrategy) @@ -45,7 +44,7 @@ def __init__( port: int = NO_PORT, role: HostRole = HostRole.WRITER, availability: HostAvailability = HostAvailability.AVAILABLE, - host_availability_strategy=HostAvailabilityStrategy(), + host_availability_strategy: Optional[HostAvailabilityStrategy] = None, weight: int = DEFAULT_WEIGHT, host_id: Optional[str] = None, last_update_time: Optional[datetime] = None): @@ -53,14 +52,15 @@ def __init__( self.port = port self.role = role self.availability = availability - self.host_availability_strategy = host_availability_strategy + # A default argument is evaluated once, so every host that omitted it + # would share one strategy object. + self.host_availability_strategy = ( + host_availability_strategy if host_availability_strategy is not None + else HostAvailabilityStrategy()) self.weight = weight self.host_id = host_id self.last_update_time = last_update_time - self._aliases: Set[str] = set() - self._all_aliases: Set[str] = {self.as_alias()} - def __eq__(self, other: object): if self is object: return True @@ -84,6 +84,9 @@ def __copy__(self): port=self.port, role=self.role, availability=self.availability, + # Shared by reference, so the copy keeps the original's backoff + # count and retry window rather than starting a fresh one. + host_availability_strategy=self.host_availability_strategy, weight=self.weight, host_id=self.host_id, last_update_time=self.last_update_time @@ -91,46 +94,13 @@ def __copy__(self): @property def url(self): - return f"{self.as_alias()}/" - - @property - def aliases(self) -> FrozenSet[str]: - return frozenset(self._aliases) - - @property - def all_aliases(self) -> FrozenSet[str]: - return frozenset(self._all_aliases) + # The trailing slash is part of the format: the availability cache, the + # notify_host_list_changed change map and the monitor keys all use it. + return f"{self.get_host_and_port()}/" def get_host_and_port(self): return f"{self.host}:{self.port}" if self.is_port_specified() else self.host - def as_alias(self) -> str: - return self.get_host_and_port() - - def add_alias(self, *aliases: str): - if not aliases: - return - - for alias in aliases: - self._aliases.add(alias) - self._all_aliases.add(alias) - - def as_aliases(self) -> FrozenSet[str]: - return frozenset(self.all_aliases) - - def remove_alias(self, *kwargs): - if not kwargs or len(kwargs) == 0: - return - - for x in kwargs: - self._aliases.discard(x) - self._all_aliases.discard(x) - - def reset_aliases(self): - self._aliases.clear() - self._all_aliases.clear() - self._all_aliases.add(self.as_alias()) - def is_port_specified(self) -> bool: return self.port != HostInfo.NO_PORT diff --git a/aws_advanced_python_wrapper/limitless_plugin.py b/aws_advanced_python_wrapper/limitless_plugin.py index 0e47c1abc..2ef659dd7 100644 --- a/aws_advanced_python_wrapper/limitless_plugin.py +++ b/aws_advanced_python_wrapper/limitless_plugin.py @@ -102,6 +102,11 @@ def connect( self._limitless_router_service.establish_connection(self._context) connection = self._context.get_connection() if connection is not None and not self._plugin_service.driver_dialect.is_closed(connection): + # The connection is on a router, not on the shard group endpoint + # the caller named. + routed_host_info = self._context.get_connection_host_info() + if routed_host_info is not None: + self._plugin_service.routed_host_info = routed_host_info return connection raise AwsWrapperError(Messages.get_formatted("LimitlessPlugin.FailedToConnectToHost", host_info.host)) @@ -291,10 +296,18 @@ def __init__(self, self._connect_func = connect_func self._limitless_routers = limitless_routers self._connection_plugin = connection_plugin + self._connection_host_info: Optional[HostInfo] = None def get_host_info(self): return self._host_info + def get_connection_host_info(self) -> Optional[HostInfo]: + """The router the connection was actually opened against.""" + return self._connection_host_info + + def set_connection_host_info(self, host_info: HostInfo): + self._connection_host_info = host_info + def get_props(self): return self._props @@ -393,6 +406,7 @@ def establish_connection(self, context: LimitlessContext) -> None: try: context.set_connection(self._plugin_service.connect(selected_host_info, context.get_props(), context.get_connection_plugin())) + context.set_connection_host_info(selected_host_info) except Exception as e: if self._is_login_exception(e): raise e @@ -452,6 +466,7 @@ def _retry_connection_with_least_loaded_routers(self, context: LimitlessContext) try: context.set_connection(self._plugin_service.connect(selected_host_info, context.get_props(), context.get_connection_plugin())) if context.get_connection() is not None: + context.set_connection_host_info(selected_host_info) return except Exception as e: diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index f6296d876..deb3097e8 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -45,9 +45,7 @@ from abc import abstractmethod from concurrent.futures import TimeoutError -from contextlib import closing -from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, Set, - Tuple) +from typing import Any, Callable, Dict, Optional, Protocol, Set, Tuple from aws_advanced_python_wrapper.allowed_and_blocked_hosts import \ AllowedAndBlockedHosts @@ -60,8 +58,7 @@ from aws_advanced_python_wrapper.connection_provider import ( ConnectionProvider, ConnectionProviderManager) from aws_advanced_python_wrapper.database_dialect import ( - DatabaseDialect, DatabaseDialectManager, DialectUtils, - UnknownDatabaseDialect) + DatabaseDialect, DatabaseDialectManager, DialectUtils) from aws_advanced_python_wrapper.default_plugin import DefaultPlugin from aws_advanced_python_wrapper.developer_plugin import DeveloperPluginFactory from aws_advanced_python_wrapper.driver_configuration_profiles import \ @@ -94,8 +91,6 @@ SimpleReadWriteSplittingPluginFactory from aws_advanced_python_wrapper.stale_dns_plugin import StaleDnsPluginFactory from aws_advanced_python_wrapper.utils import services_container -from aws_advanced_python_wrapper.utils.decorators import \ - preserve_transaction_status_with_timeout from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.notifications import ( @@ -175,6 +170,30 @@ def original_url(self) -> str: def initial_connection_host_info(self) -> Optional[HostInfo]: ... + @property + @abstractmethod + def routed_host_info(self) -> Optional[HostInfo]: + """The host a plugin routed the pending connect to, if any. + + A plugin that connects to a host other than the one it was asked for + records its choice here, and a plugin that wants to know where the + connect went should read it. Do not consume it: connect hooks unwind + from the innermost plugin outwards, so a plugin that took the value + would hide it from every plugin outside it and from the wrapper, which + is what adopts it as the current host. + """ + ... + + @routed_host_info.setter + @abstractmethod + def routed_host_info(self, value: Optional[HostInfo]): + ... + + @abstractmethod + def take_routed_host_info(self) -> Optional[HostInfo]: + """Return the routed host and clear it. For the wrapper's use.""" + ... + @property @abstractmethod def host_list_provider(self) -> HostListProvider: @@ -293,13 +312,14 @@ def force_connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: """ ... - def set_availability(self, host_aliases: FrozenSet[str], availability: HostAvailability): + def set_availability(self, host_info: HostInfo, availability: HostAvailability): + """Mark every host matching ``host_info`` by host id or host name.""" ... - def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: + def get_availability(self, host_url: str) -> Optional[HostAvailability]: ... - def fill_aliases(self, connection: Optional[Connection] = None, host_info: Optional[HostInfo] = None): + def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: ... def get_connection_provider_manager(self) -> ConnectionProviderManager: @@ -323,6 +343,7 @@ def get_status(self, clazz: Type[StatusType], key: str) -> Optional[StatusType]: class PluginServiceImpl(PluginService, HostListProviderService, CanReleaseResources): _STATUS_CACHE_EXPIRATION_NANO = 60 * 60 * 1_000_000_000 # one hour + _HOST_AVAILABILITY_EXPIRATION_NANO = 5 * 60 * 1_000_000_000 # five minutes _host_availability_expiring_cache: CacheMap[str, HostAvailability] = CacheMap() _executor_name: ClassVar[str] = "PluginServiceImplExecutor" @@ -345,6 +366,7 @@ def __init__( self._current_connection: Optional[Connection] = None self._current_host_info: Optional[HostInfo] = None self._initial_connection_host_info: Optional[HostInfo] = None + self._routed_host_info: Optional[HostInfo] = None self._exception_manager: ExceptionManager = ExceptionManager() self._is_in_transaction: bool = False self._dialect_provider = DatabaseDialectManager(props) @@ -394,6 +416,11 @@ def current_connection(self) -> Optional[Connection]: return self._current_connection def set_current_connection(self, connection: Optional[Connection], host_info: Optional[HostInfo]): + # Whoever set a routed host has been superseded by this call, which + # names the host the connection is on. Switches that reuse a cached + # connection never run a connect, so this is the only place that + # clears the field for them. + self._routed_host_info = None old_connection = self._current_connection if self._current_connection is None: @@ -489,6 +516,19 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: HostInfo): self._initial_connection_host_info = value + @property + def routed_host_info(self) -> Optional[HostInfo]: + return self._routed_host_info + + @routed_host_info.setter + def routed_host_info(self, value: Optional[HostInfo]): + self._routed_host_info = value + + def take_routed_host_info(self) -> Optional[HostInfo]: + routed = self._routed_host_info + self._routed_host_info = None + return routed + @property def host_list_provider(self) -> HostListProvider: return self._host_list_provider @@ -608,17 +648,43 @@ def force_monitoring_refresh_host_list(self, should_verify_writer: bool, timeout def connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: Optional[Plugin] = None) -> Connection: plugin_manager: PluginManager = self._container.plugin_manager + # The routed host belongs to one connect. Clearing it here stops this + # connect's plugins reading the host a previous one landed on. + self._routed_host_info = None return plugin_manager.connect( self._target_func, self._driver_dialect, host_info, props, self.current_connection is None, plugin_to_skip) def force_connect( self, host_info: HostInfo, props: Properties, plugin_to_skip: Optional[Plugin] = None) -> Connection: plugin_manager: PluginManager = self._container.plugin_manager + self._routed_host_info = None return plugin_manager.force_connect( self._target_func, self._driver_dialect, host_info, props, self.current_connection is None, plugin_to_skip) - def set_availability(self, host_aliases: FrozenSet[str], availability: HostAvailability): - ... + def set_availability(self, host_info: HostInfo, availability: HostAvailability): + hosts_to_change = [ + host for host in self.all_hosts if Utils.matches_host(host_info, host)] + if not hosts_to_change: + return + + changes: Dict[str, Set[HostEvent]] = {} + for host in hosts_to_change: + # Through the strategy, not the raw field: a host whose backoff + # window has elapsed reads as available again, and marking it down + # is a change the plugins should hear about. + previous = host.get_availability() + host.set_availability(availability) + self._host_availability_expiring_cache.put( + host.url, availability, PluginServiceImpl._HOST_AVAILABILITY_EXPIRATION_NANO) + if previous != availability: + event = HostEvent.WENT_UP if availability == HostAvailability.AVAILABLE else HostEvent.WENT_DOWN + changes[host.url] = {event, HostEvent.HOST_CHANGED} + + if changes: + self._container.plugin_manager.notify_host_list_changed(changes) + + def get_availability(self, host_url: str) -> Optional[HostAvailability]: + return PluginServiceImpl._host_availability_expiring_cache.get(host_url) def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: connection = self.current_connection if connection is None else connection @@ -635,7 +701,10 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option timeout_sec) if instance_ids is None: - raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) + # Not an error: the connect hooks that identify a host call + # this, and a host whose id the database does not report is + # simply unidentifiable, not a failed connect. + return None topology = self.host_list_provider.refresh(connection) is_force_refresh = False @@ -646,19 +715,14 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option if topology is None: return None - instance_name = instance_ids[1] - found_host: Optional[HostInfo] = next( - (host for host in topology if host.host_id == instance_name), - None) + found_host: Optional[HostInfo] = Utils.find_host(topology, *instance_ids) if found_host is None and not is_force_refresh: topology = self.host_list_provider.force_refresh(connection) if topology is None: return None - found_host = next( - (host for host in topology if host.host_id == instance_name), - None) + found_host = Utils.find_host(topology, *instance_ids) return found_host except TimeoutError as e: @@ -668,43 +732,6 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option except Exception as e: raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) from e - def fill_aliases(self, connection: Optional[Connection] = None, host_info: Optional[HostInfo] = None): - connection = self.current_connection if connection is None else connection - host_info = self.current_host_info if host_info is None else host_info - if connection is None or host_info is None: - return - - if len(host_info.aliases) > 0: - logger.debug("PluginServiceImpl.NonEmptyAliases", host_info.aliases) - return - - host_info.add_alias(host_info.as_alias()) - - driver_dialect = self._driver_dialect - try: - timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get(self._props) - cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( - self._thread_pool, timeout_sec, driver_dialect, connection)(self._fill_aliases) - cursor_execute_func_with_timeout(connection, host_info) - except TimeoutError as e: - raise QueryTimeoutError(Messages.get("PluginServiceImpl.FillAliasesTimeout")) from e - except Exception as e: - # log and ignore - logger.debug("PluginServiceImpl.FailedToRetrieveHostPort", e) - - host = self.identify_connection(connection) - if host: - host_info.add_alias(*host.as_aliases()) - - def _fill_aliases(self, conn: Connection, host_info: HostInfo) -> bool: - with closing(conn.cursor()) as cursor: - if not isinstance(self.database_dialect, UnknownDatabaseDialect): - cursor.execute(self.database_dialect.host_alias_query) - for row in cursor.fetchall(): - host_info.add_alias(row[0]) - return True - return False - def is_static_host_list_provider(self) -> bool: return self._host_list_provider is StaticHostListProvider diff --git a/aws_advanced_python_wrapper/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/read_write_splitting_plugin.py index 23bd01742..c55fdff02 100644 --- a/aws_advanced_python_wrapper/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/read_write_splitting_plugin.py @@ -32,6 +32,7 @@ FailoverFailedError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.pep249 import Error from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory from aws_advanced_python_wrapper.utils.log import Logger @@ -613,9 +614,17 @@ def _open_new_reader_connection( host_candidates = self._get_reader_host_candidates() conn_attempts = len(host_candidates) * 2 for _ in range(conn_attempts): - host = self._plugin_service.get_host_info_by_strategy( - HostRole.READER, self._reader_selector_strategy, host_candidates - ) + try: + host = self._plugin_service.get_host_info_by_strategy( + HostRole.READER, self._reader_selector_strategy, host_candidates + ) + except Error: + # Every reader is currently marked unavailable. Stop here so + # the caller reports that no reader was available, rather than + # surfacing a host-selector error to the application. Error, + # not AwsWrapperError: the default random selector raises the + # base class, which AwsWrapperError is a subclass of. + break if host is not None: try: conn = self._plugin_service.connect(host, self._properties, self) diff --git a/aws_advanced_python_wrapper/reader_failover_handler.py b/aws_advanced_python_wrapper/reader_failover_handler.py index e20aba452..28cf86862 100644 --- a/aws_advanced_python_wrapper/reader_failover_handler.py +++ b/aws_advanced_python_wrapper/reader_failover_handler.py @@ -150,7 +150,7 @@ def _internal_failover_task( def _failover_internal(self, hosts: Tuple[HostInfo, ...], current_host: Optional[HostInfo]) -> ReaderFailoverResult: if current_host is not None: - self._plugin_service.set_availability(current_host.all_aliases, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(current_host, HostAvailability.UNAVAILABLE) hosts_by_priority = ReaderFailoverHandlerImpl.get_hosts_by_priority(hosts, self._strict_reader_failover) return self._get_connection_from_host_group(hosts_by_priority) @@ -201,13 +201,13 @@ def attempt_connection(self, host: HostInfo) -> ReaderFailoverResult: try: conn: Connection = self._plugin_service.force_connect(host, props) - self._plugin_service.set_availability(host.all_aliases, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host, HostAvailability.AVAILABLE) logger.debug("ReaderFailoverHandler.SuccessfulReaderConnection", host.url) return ReaderFailoverResult(conn, True, host, None) except Exception as ex: logger.debug("ReaderFailoverHandler.FailedReaderConnection", host.url) - self._plugin_service.set_availability(host.all_aliases, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(host, HostAvailability.UNAVAILABLE) if not self._plugin_service.is_network_exception(ex): return ReaderFailoverResult(None, False, None, ex) diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index b64adb514..221bf2dff 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -256,7 +256,6 @@ HostMonitoringPlugin.ConnectionNone=[HostMonitoringPlugin] Attempted to execute HostMonitoringPlugin.HostInfoNone=[HostMonitoringPlugin] Could not find HostInfo to monitor for the current connection. HostMonitoringPlugin.HostInfoNoneForMethod=[HostMonitoringPlugin] Attempted to execute method '{}' but the current host info is None. HostMonitoringPlugin.ConfigurationNotSupported=[HostMonitoringPlugin] Aborting connections from a separate thread is not supported for the detected driver dialect: '{}'. The EFM plugin requires this feature to be supported. -HostMonitoringPlugin.UnableToIdentifyConnection=[HostMonitoringPlugin] Unable to identify the connected database instance: '{}', please ensure the correct host list provider is specified. The host list provider in use is: '{}'. HostMonitoringPlugin.UnavailableHost=[HostMonitoringPlugin] Host '{}' is unavailable. HostMonitoringV2Plugin.ActivatedMonitoring=[HostMonitoringV2Plugin] Executing method '{}', monitoring is activated. @@ -266,7 +265,6 @@ HostMonitoringV2Plugin.MonitoringDeactivated=[HostMonitoringV2Plugin] Monitoring HostMonitoringV2Plugin.ConnectionNone=[HostMonitoringV2Plugin] Attempted to execute method '{}' but the current connection is None. HostMonitoringV2Plugin.HostInfoNone=[HostMonitoringV2Plugin] Could not find HostInfo to monitor for the current connection. HostMonitoringV2Plugin.ConfigurationNotSupported=[HostMonitoringV2Plugin] Aborting connections from a separate thread is not supported for the detected driver dialect: '{}'. The EFM V2 plugin requires this feature to be supported. -HostMonitoringV2Plugin.UnableToIdentifyConnection=[HostMonitoringV2Plugin] Unable to identify the connected database instance: '{}', please ensure the correct host list provider is specified. The host list provider in use is: '{}'. HostMonitorV2.ExceptionDuringMonitoringStop=[HostMonitorV2] Stopping monitoring after unhandled exception was thrown in monitoring thread for host '{}'. Exception: '{}' HostMonitorV2.MonitorIsStopped=[HostMonitorV2] Monitoring was already stopped for host '{}'. HostMonitorV2.StartMonitoringThreadNewContext=[HostMonitorV2] Start monitoring thread for checking new contexts for '{}'. @@ -342,13 +340,6 @@ MonitorContext.HostAvailable=[MonitorContext] Host '{}' is *available*. MonitorContext.HostNotResponding=[MonitorContext] Host '{}' is not *responding* - failure count: '{}'. MonitorContext.HostUnavailable=[MonitorContext] Host '{}' is *unavailable*. -MonitoringThreadContainer.EmptyHostKeys=[MonitorThreadContainer] The provided host_aliases set was empty. -MonitoringThreadContainer.ErrorGettingMonitor=[MonitorThreadContainer] Unable to find or create monitor for host with aliases '{}'. -MonitoringThreadContainer.SupplierMonitorNone=[MonitorThreadContainer] The monitor supplier passed into get_or_create_monitor returned None. - -MonitorService.EmptyAliasSet=[MonitorService] Empty alias set passed for '{}'. The alias set should not be empty. -MonitorService.ErrorPopulatingAliases=[MonitorService] An error occurred while populating aliases: '{}'. - GDBRegionUtils.UnableToRetrieveGlobalClusterARN=Unable to retrieve the primary global region for the provided global database cluster. GlobalAuroraTopologyUtils.UnsupportedOperationError=[GlobalAuroraTopologyUtils] Aurora global databases does not support this operation {}. @@ -393,12 +384,9 @@ PluginManager.ResortedPlugins=[PluginManager] Plugins order has been rearranged. PluginServiceImpl.CouldNotDetermineCurrentHost=[PluginServiceImpl] The current host could not be determined. PluginServiceImpl.CurrentHostNotAllowed=[PluginServiceImpl] The current host is not in the list of allowed hosts. Current host: '{}'. Allowed hosts: {} -PluginServiceImpl.FailedToRetrieveHostPort=[PluginServiceImpl] Could not retrieve Host:Port for connection. {} -PluginServiceImpl.FillAliasesTimeout=[PluginServiceImpl] The timeout limit was reached while querying for the current host's alias. PluginServiceImpl.GetHostRoleConnectionNone=[PluginServiceImpl] Attempted to evaluate the host role of the given connection, but could not find a non-None connection to evaluate. PluginServiceImpl.HostListEmpty=[PluginServiceImpl] Could not determine the current host info because the current host list is empty. PluginServiceImpl.IncorrectStatusType=[PluginServiceImpl] Received an unexpected type from the status cache. An object of type {} was requested, but the object at key '{}' had a type of {}. The retrieved object was: {}. -PluginServiceImpl.NonEmptyAliases=[PluginServiceImpl] fill_aliases called when HostInfo already contains the following aliases: {}. PluginServiceImpl.SetCurrentHostInfo=[PluginServiceImpl] Set current host info to {} PluginServiceImpl.UnableToUpdateTransactionStatus=[PluginServiceImpl] Unable to update transaction status, current connection is None. PluginServiceImpl.UpdateDialectConnectionNone=[PluginServiceImpl] The plugin service attempted to update the current dialect but could not identify a connection to use. diff --git a/aws_advanced_python_wrapper/utils/concurrent.py b/aws_advanced_python_wrapper/utils/concurrent.py index 5a8250872..b164b480d 100644 --- a/aws_advanced_python_wrapper/utils/concurrent.py +++ b/aws_advanced_python_wrapper/utils/concurrent.py @@ -77,25 +77,6 @@ def compute_if_absent(self, key: K, mapping_func: Callable) -> Optional[V]: return new_value return value - def compute_for_keys( - self, keys, factory: Callable, - on_existing: Optional[Callable] = None) -> V: - with self._lock: - value = None - for key in keys: - value = self._dict.get(key) - if value is not None: - if on_existing: - on_existing(value) - break - - if value is None: - value = factory() - - for key in keys: - self._dict.setdefault(key, value) - return value - def put(self, key: K, value: V): with self._lock: self._dict[key] = value diff --git a/aws_advanced_python_wrapper/utils/monitor_service.py b/aws_advanced_python_wrapper/utils/monitor_service.py index 33a0db5de..6b07ddfa3 100644 --- a/aws_advanced_python_wrapper/utils/monitor_service.py +++ b/aws_advanced_python_wrapper/utils/monitor_service.py @@ -17,8 +17,7 @@ import threading from dataclasses import dataclass from time import perf_counter_ns -from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, - runtime_checkable) +from typing import Any, Callable, Dict, Optional, Protocol, runtime_checkable from aws_advanced_python_wrapper.utils.events import (DataAccessEvent, EventBase, @@ -111,14 +110,6 @@ def run_if_absent( container = self._get_or_create_container(monitor_type) return container.cache.compute_if_absent(key, lambda _: factory()) - def run_if_absent_with_aliases( - self, - monitor_type: type, - aliases: FrozenSet[str], - factory: Callable[[], Any]) -> Any: - container = self._get_or_create_container(monitor_type) - return container.cache.get_or_create_for_aliases(aliases, factory) - def detach(self, monitor_type: type, monitor: Any) -> None: container = self._monitor_caches.get(monitor_type) if container is not None: diff --git a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py index 6c89aeea6..795fb65aa 100644 --- a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py +++ b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py @@ -15,7 +15,7 @@ from __future__ import annotations from time import perf_counter_ns -from typing import Callable, FrozenSet, Generic, List, Optional, Tuple, TypeVar +from typing import Callable, Generic, List, Optional, Tuple, TypeVar from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict @@ -65,13 +65,6 @@ def compute_if_absent(self, key: K, factory: Callable[[K], V]) -> Optional[V]: entry.extend(self._expiration_timeout_ns) return entry.item - def get_or_create_for_aliases(self, aliases: FrozenSet[K], factory: Callable[[], V]) -> V: - entry = self._cache.compute_for_keys( - aliases, - lambda: _CacheItem(factory(), perf_counter_ns() + self._expiration_timeout_ns), - on_existing=lambda e: e.extend(self._expiration_timeout_ns)) - return entry.item - def extend_expiration(self, key: K) -> None: entry = self._cache.get(key) if entry is not None: diff --git a/aws_advanced_python_wrapper/utils/utils.py b/aws_advanced_python_wrapper/utils/utils.py index e6690a410..132bb7041 100644 --- a/aws_advanced_python_wrapper/utils/utils.py +++ b/aws_advanced_python_wrapper/utils/utils.py @@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Optional, Tuple from aws_advanced_python_wrapper.hostinfo import HostRole +from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType if TYPE_CHECKING: from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -98,6 +99,51 @@ def contains_host_and_port(hosts: Tuple[HostInfo, ...], host_and_port: str) -> b return False + @staticmethod + def requires_host_identification(url_type: RdsUrlType) -> bool: + """Whether the instance behind ``url_type`` has to be looked up. + + An instance endpoint names its instance already. A proxy or shard + group endpoint names a router, which stays reachable and is the right + thing to monitor; the instance behind it may not accept a direct + connection at all. + """ + return url_type not in ( + RdsUrlType.RDS_INSTANCE, + RdsUrlType.RDS_PROXY, + RdsUrlType.RDS_AURORA_LIMITLESS_DB_SHARD_GROUP) + + @staticmethod + def matches_host(host: HostInfo, other: HostInfo) -> bool: + """Whether two hosts name the same instance. + + Host ids match exactly; host names are compared case-insensitively, + since DNS names are case-insensitive. + """ + if host.host_id is not None and host.host_id == other.host_id: + return True + return (host.host is not None and other.host is not None + and host.host.casefold() == other.host.casefold()) + + @staticmethod + def find_host( + hosts: Tuple[HostInfo, ...], + instance_id: Optional[str], + instance_name: Optional[str]) -> Optional[HostInfo]: + """Find the host a connection is bound to from what ``host_id_query`` + reported. + + The id is matched against ``host_id`` and the name against ``host``. + The dialects disagree about which column holds which: the Aurora + queries repeat one value, Multi-AZ returns a numeric id and a short + name, and the plain MySQL and PostgreSQL queries return the name + first. Matching on either column covers all of them. + """ + return next( + (host for host in hosts + if host.host_id == instance_id or host.host == instance_name), + None) + @staticmethod def get_writer(hosts: Tuple[HostInfo, ...]) -> Optional[HostInfo]: for host in hosts: diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 9db150c21..8ad8e7eb4 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -78,7 +78,11 @@ def __init__( if not conn: raise AwsWrapperError(Messages.get("AwsWrapperConnection.ConnectionNotOpen")) - plugin_service.set_current_connection(conn, plugin_service.initial_connection_host_info) + # A plugin may have routed the connect elsewhere; that is the host this + # connection is actually on. + routed = plugin_service.take_routed_host_info() + connected_host_info = routed if routed is not None else plugin_service.initial_connection_host_info + plugin_service.set_current_connection(conn, connected_host_info) @property def target_connection(self): diff --git a/aws_advanced_python_wrapper/writer_failover_handler.py b/aws_advanced_python_wrapper/writer_failover_handler.py index 34e04bac2..4ad62e3a1 100644 --- a/aws_advanced_python_wrapper/writer_failover_handler.py +++ b/aws_advanced_python_wrapper/writer_failover_handler.py @@ -116,7 +116,7 @@ def get_writer(self, topology: Tuple[HostInfo, ...]) -> Optional[HostInfo]: def get_result_from_future(self, current_topology: Tuple[HostInfo, ...]) -> WriterFailoverResult: writer_host: Optional[HostInfo] = self.get_writer(current_topology) if writer_host is not None: - self._plugin_service.set_availability(writer_host.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(writer_host, HostAvailability.UNAVAILABLE) executor = ThreadPoolExecutor(thread_name_prefix="WriterFailoverHandlerExecutor") try: @@ -188,7 +188,7 @@ def reconnect_to_writer(self, initial_writer_host: HostInfo): else: success = self.is_current_host_writer(latest_topology, initial_writer_host) - self._plugin_service.set_availability(initial_writer_host.as_aliases(), HostAvailability.AVAILABLE) + self._plugin_service.set_availability(initial_writer_host, HostAvailability.AVAILABLE) return WriterFailoverResult(success, False, latest_topology, conn if success else None, "TaskA", None) except Exception as ex: @@ -208,10 +208,11 @@ def is_current_host_writer(self, latest_topology: Tuple[HostInfo, ...], initial_ if latest_writer is None: return False - latest_writer_all_aliases: frozenset[str] = latest_writer.all_aliases - current_aliases: frozenset[str] = initial_writer_host.all_aliases - - return current_aliases is not None and len(current_aliases) > 0 and bool(current_aliases.intersection(latest_writer_all_aliases)) + return (latest_writer.host_id is not None + and latest_writer.host_id == initial_writer_host.host_id) \ + or (latest_writer.get_host_and_port() is not None + and latest_writer.get_host_and_port().casefold() + == initial_writer_host.get_host_and_port().casefold()) def wait_for_new_writer(self, current_topology: Tuple[HostInfo, ...], current_host: HostInfo) -> WriterFailoverResult: """ @@ -317,11 +318,11 @@ def connect_to_writer(self, writer_candidate: Optional[HostInfo]) -> bool: if writer_candidate is not None: self._current_connection = \ self._plugin_service.force_connect(writer_candidate, self._initial_connection_properties) - self._plugin_service.set_availability(writer_candidate.as_aliases(), HostAvailability.AVAILABLE) + self._plugin_service.set_availability(writer_candidate, HostAvailability.AVAILABLE) return True except Exception: if writer_candidate is not None: - self._plugin_service.set_availability(writer_candidate.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(writer_candidate, HostAvailability.UNAVAILABLE) return False diff --git a/docs/development-guide/PluginService.md b/docs/development-guide/PluginService.md index fce76c2b3..3f5eee7e3 100644 --- a/docs/development-guide/PluginService.md +++ b/docs/development-guide/PluginService.md @@ -9,6 +9,24 @@ It also keeps track of the host list provider in use, and notifies it to update It is expected that the plugins do not establish a connection themselves, but rather call `PluginService.connect()` to establish connections. +## The Routed Host + +A plugin may connect to a host other than the one it was asked for. The Aurora +initial connection strategy plugin substitutes an instance for a cluster +endpoint, and the limitless plugin picks a transaction router. + +A plugin that does this assigns `PluginService.routed_host_info`, and the +wrapper adopts that host as the current host for the connection. + +A plugin that wants to know where the connect was routed should **read** the +property. Connect hooks unwind from the innermost plugin outwards, so a plugin +that consumed the value would hide it from every plugin outside it and from +the wrapper. Only the wrapper consumes it, with `take_routed_host_info()`. + +The value belongs to a single connect. `PluginService.connect()` clears it on +entry and `set_current_connection()` clears it once a host has been adopted, +so a plugin never reads a host left over from an earlier connect. + ## Host List Providers The plugin service uses the host list provider to retrieve the most recent host information or topology information about the database. diff --git a/tests/unit/test_aio_aurora_connection_tracker.py b/tests/unit/test_aio_aurora_connection_tracker.py index 9056d9597..f25f4c20e 100644 --- a/tests/unit/test_aio_aurora_connection_tracker.py +++ b/tests/unit/test_aio_aurora_connection_tracker.py @@ -539,10 +539,10 @@ def test_notify_converted_to_reader_invalidates_that_host(): tracker.track(host, conn) from aws_advanced_python_wrapper.utils.notifications import HostEvent - alias = host.as_alias() async def _run(): - plugin.notify_host_list_changed({alias: {HostEvent.CONVERTED_TO_READER}}) + # Change keys are urls, with a trailing slash; tracking keys are not. + plugin.notify_host_list_changed({host.url: {HostEvent.CONVERTED_TO_READER}}) # Give the spawned invalidation task a moment await asyncio.sleep(0.01) @@ -585,7 +585,7 @@ def test_notify_ignores_events_that_are_not_converted(): async def _run(): plugin.notify_host_list_changed( - {host.as_alias(): {HostEvent.WENT_DOWN}}) + {host.url: {HostEvent.WENT_DOWN}}) await asyncio.sleep(0.01) asyncio.run(_run()) @@ -650,68 +650,54 @@ async def _run(): conn.close.assert_called() -def test_notify_host_list_changed_handles_alias_without_port(): - """An alias with no colon falls back to port 5432 (doesn't raise).""" +def test_notify_host_list_changed_handles_a_key_without_a_port(): + """A change key naming no port still reaches the connections tracked + under it, since a host with no port keys on the bare host name.""" plugin, svc, driver_dialect, tracker = _build() + conn = _plain_conn("conn") + tracker.track(HostInfo(host="host-no-port"), conn) from aws_advanced_python_wrapper.utils.notifications import HostEvent async def _run(): - # Must not raise; _spawn_invalidation schedules via asyncio.create_task - # so needs a running loop. - plugin.notify_host_list_changed({"host-no-port": {HostEvent.CONVERTED_TO_READER}}) + plugin.notify_host_list_changed({"host-no-port/": {HostEvent.CONVERTED_TO_READER}}) await asyncio.sleep(0.01) asyncio.run(_run()) + conn.close.assert_called() -def test_parse_alias_helper(): - """Direct helper test: IPv4, IPv6, bare host, invalid port.""" - from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ - AsyncAuroraConnectionTrackerPlugin - - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h.example:5432") == ("h.example", 5432) - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("[::1]:5432") == ("[::1]", 5432) - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h-no-port") == ("h-no-port", 5432) - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h:not-a-port") == ("h", 5432) - - -def test_tracker_keys_by_instance_endpoint_for_cluster_connected_conn(): - """When tracking via a cluster endpoint HostInfo whose aliases - include the instance endpoint, the canonical key is the instance - endpoint -- so notify-based invalidation by instance alias finds it.""" +def test_tracker_keys_a_cluster_connected_conn_by_its_host_id(): + """A cluster endpoint does not name the instance, so the host id is what a + later invalidation naming the instance has to match on.""" tracker = AsyncOpenedConnectionTracker() - # Cluster endpoint hostname that is NOT an RDS instance per is_rds_instance, - # but aliases include the instance endpoint. cluster_host = HostInfo( host="mydb.cluster-abc123.us-east-1.rds.amazonaws.com", port=5432, role=HostRole.WRITER, + host_id="myinstance", ) - # Add a known RDS instance alias - cluster_host.add_alias("myinstance.abc123.us-east-1.rds.amazonaws.com:5432") conn = _plain_conn("conn") tracker.track(cluster_host, conn) - # Canonical key is the instance alias, not the cluster host:port - assert AsyncOpenedConnectionTracker._canonical_key(cluster_host) == \ - "myinstance.abc123.us-east-1.rds.amazonaws.com:5432" + assert set(AsyncOpenedConnectionTracker._tracking_keys(cluster_host)) == { + "myinstance", "mydb.cluster-abc123.us-east-1.rds.amazonaws.com:5432"} - # invalidate_all via a HostInfo that resolves to the same instance alias - # should close the tracked conn instance_host = HostInfo( host="myinstance.abc123.us-east-1.rds.amazonaws.com", port=5432, + host_id="myinstance", ) asyncio.run(tracker.invalidate_all(instance_host)) conn.close.assert_called() -def test_tracker_fallback_to_host_port_for_non_rds_host(): - """Non-RDS hostnames use host:port as the canonical key (no RDS alias found).""" - host = HostInfo(host="custom.example.com", port=5432) - assert AsyncOpenedConnectionTracker._canonical_key(host) == "custom.example.com:5432" +def test_tracker_keys_an_instance_endpoint_by_host_and_port_alone(): + host = HostInfo(host="instance-1.abc123.us-east-1.rds.amazonaws.com", port=5432, + host_id="instance-1") + assert AsyncOpenedConnectionTracker._tracking_keys(host) == ( + "instance-1.abc123.us-east-1.rds.amazonaws.com:5432",) # ---- B2: post-failover settling window ---------------------------------- diff --git a/tests/unit/test_aio_aurora_initial_connection.py b/tests/unit/test_aio_aurora_initial_connection.py index afd2fa944..59fc5378b 100644 --- a/tests/unit/test_aio_aurora_initial_connection.py +++ b/tests/unit/test_aio_aurora_initial_connection.py @@ -133,7 +133,7 @@ async def _run(): svc.get_host_role.assert_not_awaited() # A non-cluster URL needs no role verification, so the loop records the # original host and returns on the first pass. - assert svc.initial_connection_host_info is host + assert svc.routed_host_info is host # ---- 2. Writer cluster URL + already writer -> direct writer conn ------ @@ -168,7 +168,7 @@ async def _run(): result = asyncio.run(_run()) assert result is writer_conn driver_dialect.connect.assert_awaited_once() - assert svc.initial_connection_host_info is writer + assert svc.routed_host_info is writer # ---- 3. Writer cluster URL + connected to reader -> retry -------------- @@ -207,8 +207,8 @@ async def _run(): driver_dialect.abort_connection.assert_any_await(first_conn) # Topology force-refreshed on the bad conn. svc.force_refresh_host_list.assert_awaited() - # initial_connection_host_info -> writer from topology. - assert svc.initial_connection_host_info is writer + # routed_host_info -> writer from topology. + assert svc.routed_host_info is writer # ---- 4. Reader cluster URL + connected to reader -> returns conn ------- @@ -242,7 +242,7 @@ async def _run(): result = asyncio.run(_run()) assert result is reader_conn - assert svc.initial_connection_host_info is reader + assert svc.routed_host_info is reader # ---- 5. Reader cluster URL + no readers -> writer fallback ------------- @@ -280,7 +280,7 @@ async def _run(): assert result is cluster_conn # The no-readers fallback records the candidate host, which on the stale # path is the original connect host rather than the writer. - assert svc.initial_connection_host_info is host + assert svc.routed_host_info is host # ---- 6. Timeout exhausted -> raises (parity with sync) ----------------- @@ -420,8 +420,8 @@ async def _run(): asyncio.run(_run()) assert svc.set_availability.call_count >= 1 - called_aliases = svc.set_availability.call_args_list[0][0][0] - assert reader.host in "".join(called_aliases) + marked_host = svc.set_availability.call_args_list[0][0][0] + assert marked_host.host == reader.host assert svc.set_availability.call_args_list[0][0][1] == \ HostAvailability.UNAVAILABLE diff --git a/tests/unit/test_aio_dialect_utils.py b/tests/unit/test_aio_dialect_utils.py index 45a003570..edde85f4d 100644 --- a/tests/unit/test_aio_dialect_utils.py +++ b/tests/unit/test_aio_dialect_utils.py @@ -143,5 +143,5 @@ def test_get_instance_id_rolls_back_transient_probe_txn(): dd = MagicMock() dd.is_in_transaction = AsyncMock(return_value=False) iid = asyncio.run(AsyncDialectUtils.get_instance_id(conn, dd, "q")) - assert iid == "inst-1" + assert iid == ("inst-1", "inst-1") conn.rollback.assert_awaited_once() diff --git a/tests/unit/test_aio_failover_plugin.py b/tests/unit/test_aio_failover_plugin.py index e0bd2e23b..0184bc9f8 100644 --- a/tests/unit/test_aio_failover_plugin.py +++ b/tests/unit/test_aio_failover_plugin.py @@ -529,7 +529,7 @@ def test_failover_marks_connected_host_available(): asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) svc.set_availability.assert_any_call( - writer.as_aliases(), HostAvailability.AVAILABLE) + writer, HostAvailability.AVAILABLE) def test_failover_marks_failed_host_unavailable(): @@ -547,7 +547,7 @@ def test_failover_marks_failed_host_unavailable(): asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) svc.set_availability.assert_any_call( - writer.as_aliases(), HostAvailability.UNAVAILABLE) + writer, HostAvailability.UNAVAILABLE) # ---- B.4: reader retry loop + strategy + writer fallback --------------- @@ -950,9 +950,9 @@ async def _dial(): conn = await plugin.connect( MagicMock(), driver_dialect, host, Properties({}), True, _dial) assert conn is failover_conn - marked_aliases, marked_avail = svc.set_availability.call_args_list[0][0] + marked_host, marked_avail = svc.set_availability.call_args_list[0][0] assert marked_avail == HostAvailability.UNAVAILABLE - assert host.as_aliases() == marked_aliases + assert marked_host is host asyncio.run(_body()) diff --git a/tests/unit/test_aio_host_list_provider.py b/tests/unit/test_aio_host_list_provider.py index 23c6451e7..5a242fa37 100644 --- a/tests/unit/test_aio_host_list_provider.py +++ b/tests/unit/test_aio_host_list_provider.py @@ -303,21 +303,24 @@ def test_topology_multiple_writers_without_timestamps_keeps_one(): assert len(writers) == 1 -def test_topology_rows_carry_host_id_and_instance_alias(): - """Integration regression (EFM cluster-RO, both Aurora envs): - _rows_to_topology dropped host_id, so plugin_service.identify_connection - (which matches `h.host_id == instance_id`) could NEVER resolve a - cluster-endpoint connection -- EFM's _get_monitoring_host_info raised - UnableToIdentifyConnection on every cluster-RO connect. Sync parity: - create_host (host_list_provider.py:548-556) sets host_id AND adds the - bare instance id as an alias; the async MultiAz/GlobalAurora providers - already did both.""" +def test_topology_rows_carry_host_id(): + """Integration regression (EFM cluster-RO, both Aurora envs): the row + parser dropped host_id, so identify_connection could never resolve a + cluster-endpoint connection and host monitoring could not pick a + monitoring host.""" rows = [("w-1", True), ("r-1", False)] prov = _aurora() topo = prov._topology_utils._process_query_results(rows) assert {h.host_id for h in topo} == {"w-1", "r-1"} - for h in topo: - assert h.host_id in h.as_aliases() + + +def test_topology_rows_share_one_availability_strategy(): + """One strategy per provider, matching the synchronous provider, so the + backoff window is per cluster rather than per host.""" + prov = _aurora() + topo = prov._topology_utils._process_query_results([("w-1", True), ("r-1", False)]) + strategies = {id(h.host_availability_strategy) for h in topo} + assert strategies == {id(prov._topology_utils._host_availability_strategy)} def test_topology_query_programming_error_raises_invalid_query(): diff --git a/tests/unit/test_aio_host_monitoring_plugin.py b/tests/unit/test_aio_host_monitoring_plugin.py index 88aa91b31..34392d170 100644 --- a/tests/unit/test_aio_host_monitoring_plugin.py +++ b/tests/unit/test_aio_host_monitoring_plugin.py @@ -344,7 +344,7 @@ async def _work(): await asyncio.sleep(0.3) svc.set_availability.assert_any_call( - HostInfo(host="h.example", port=5432).as_aliases(), + HostInfo(host="h.example", port=5432), HostAvailability.UNAVAILABLE) dd.abort_connection.assert_awaited() aborted_with = dd.abort_connection.await_args_list[0].args[0] diff --git a/tests/unit/test_aio_monitor_lifecycle_regressions.py b/tests/unit/test_aio_monitor_lifecycle_regressions.py new file mode 100644 index 000000000..2c86badfe --- /dev/null +++ b/tests/unit/test_aio_monitor_lifecycle_regressions.py @@ -0,0 +1,296 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Lifecycle regressions in the shared async topology monitor. + +Each test pins a defect in the monitor's start, stop, reset or cleanup paths. +""" + +from __future__ import annotations + +import asyncio +import gc +import weakref +from unittest.mock import AsyncMock, MagicMock + +from aws_advanced_python_wrapper.aio import topology_store +from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor +from aws_advanced_python_wrapper.aio.host_list_provider import \ + AsyncAuroraHostListProvider +from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncAuroraTopologyUtils +from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.events import MonitorResetEvent +from aws_advanced_python_wrapper.utils.properties import Properties + +CLUSTER_ID = "my-cluster" +KEY = (CLUSTER_ID, "token") +OLD = (HostInfo("blue-writer.example", 5432, HostRole.WRITER),) +NEW = (HostInfo("green-writer.example", 5432, HostRole.WRITER),) + + +def _utils(topology=()) -> AsyncAuroraTopologyUtils: + utils = AsyncAuroraTopologyUtils( + Properties({"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"}), + "SELECT 1", 5432) + utils.query_for_topology = AsyncMock(return_value=topology) # type: ignore[method-assign] + return utils + + +def _monitor(topology=()) -> AsyncClusterTopologyMonitor: + return AsyncClusterTopologyMonitor( + topology_utils=_utils(topology), + cluster_id=CLUSTER_ID, + key=KEY, + connection_getter=lambda: None) + + +def test_stop_on_a_closed_loop_does_not_raise() -> None: + """Setting the stop event before checking the loop raised "Event loop is + closed", and the monitor service swallowed it at debug level.""" + loop = asyncio.new_event_loop() + monitor = _monitor() + try: + loop.run_until_complete(_start_and_park(monitor)) + finally: + loop.close() + + # A waiter is parked on the stop event, and the loop is gone. + assert monitor._stop_event._waiters # type: ignore[attr-defined] + monitor.stop() # must not raise + + +async def _start_and_park(monitor: AsyncClusterTopologyMonitor) -> None: + monitor.start() + await asyncio.sleep(0.02) + + +def test_the_monitor_does_not_keep_its_event_loop_alive() -> None: + """A shutdown hook holds the monitor for the life of the process, so a + strong loop reference leaks a loop per loop in a loop-per-request app.""" + loop = asyncio.new_event_loop() + monitor = _monitor() + loop.run_until_complete(_start_and_park(monitor)) + loop.run_until_complete(monitor.aclose()) + loop.close() + + ref = weakref.ref(loop) + del loop + gc.collect() + assert ref() is None, "the monitor is still holding its event loop" + + +def test_a_reset_discards_a_publication_that_began_before_it() -> None: + """A refresh in flight when a blue/green reset lands describes the + pre-switchover cluster, so publishing it afterwards restores the host list + the reset just cleared.""" + async def _body(): + monitor = _monitor() + monitor.start() + topology_store.put_topology(KEY, OLD) + + reset_count = monitor._reset_count + monitor.process_event( + MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) + await asyncio.sleep(0) + await asyncio.sleep(0) + assert topology_store.get_topology(KEY) is None + + # The pre-reset fetch now completes and tries to publish. + monitor._publish_topology(OLD, reset_count) + assert topology_store.get_topology(KEY) is None + assert monitor._last_topology == () + + # A publication from after the reset still lands. + monitor._publish_topology(NEW, monitor._reset_count) + assert topology_store.get_topology(KEY) == NEW + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_reset_wakes_the_loop_instead_of_waiting_out_a_tick() -> None: + """Without waking the loop, a switchover serves nothing until the next + tick, which the reset itself just made a full-length one.""" + async def _body(): + monitor = _monitor() + monitor.start() + monitor._request_tick.clear() + + monitor.process_event( + MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) + await asyncio.sleep(0) + await asyncio.sleep(0) + + assert monitor._request_tick.is_set() + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_closed_monitor_is_not_restarted() -> None: + """force_monitoring_refresh auto-starts, and a monitor restarted after + aclose() is out of the cache, so nothing would stop its task.""" + async def _body(): + monitor = _monitor() + monitor.start() + await monitor.aclose() + + monitor.start() + assert not monitor.is_running() + + asyncio.run(_body()) + + +def test_the_inactive_timeout_outlasts_a_long_refresh_interval() -> None: + """Activity is stamped once per tick, so a refresh interval longer than + the inactive timeout had every cleanup sweep disposing a healthy monitor.""" + services_container.get_monitor_service()._monitor_caches.pop( + AsyncClusterTopologyMonitor, None) + props = Properties({ + "host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5432", + "topology_refresh_ms": "300000", # 5 minutes, well past the 3-min default + }) + AsyncAuroraHostListProvider(props, MagicMock()) + + container = services_container.get_monitor_service()._monitor_caches[ + AsyncClusterTopologyMonitor] + assert container.settings.inactive_timeout_ns > 300_000 * 1_000_000 + + +def test_detach_value_reports_whether_it_removed_the_entry() -> None: + """stop_and_remove_value relies on this to tell its caller whether the + removal was theirs.""" + from aws_advanced_python_wrapper.utils.storage.expiration_tracking_cache import \ + ExpirationTrackingCache + + cache: ExpirationTrackingCache = ExpirationTrackingCache( + expiration_timeout_ns=60 * 1_000_000_000) + monitor = _monitor() + cache.compute_if_absent(KEY, lambda _k: monitor) + + assert cache.detach_value(monitor) is True + assert cache.detach_value(monitor) is False + + +def test_a_cluster_on_a_non_default_port_keeps_that_port() -> None: + """The port fell back to the dialect default, so an Aurora cluster reached + on 5433 produced topology hosts on 5432.""" + utils = AsyncAuroraTopologyUtils( + Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5433"}), + "SELECT 1", 5432) + host = utils.create_host("instance-1", is_writer=True) + assert host.port == 5433 + + +def test_global_aurora_reduces_two_writers_to_one() -> None: + """A cross-region switchover can report two writers, and consumers read a + two-writer topology as ambiguous.""" + from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncGlobalAuroraTopologyUtils + + utils = AsyncGlobalAuroraTopologyUtils( + Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5432"}), + "SELECT 1", 5432, + instance_templates_by_region={"us-east-1": "?.a.us-east-1.rds.amazonaws.com", + "us-west-2": "?.b.us-west-2.rds.amazonaws.com"}) + rows = [ + ("old-writer", True, 0, "us-east-1"), + ("new-writer", True, 0, "us-west-2"), + ] + + topology = utils._process_global_query_results(rows) + + writers = [h for h in topology if h.role == HostRole.WRITER] + assert len(writers) == 1, f"expected one writer, got {writers}" + + +def test_aclose_wakes_a_caller_blocked_on_a_refresh() -> None: + """A blocked caller awaits the event object it read, so aclose() has to + set it before swapping in a fresh one or the caller waits out its own + timeout against an orphan.""" + async def _body(): + monitor = _monitor() + monitor.start() + waiter = asyncio.create_task( + monitor.force_monitoring_refresh(False, timeout_sec=30.0)) + await asyncio.sleep(0.01) + assert not waiter.done() + + await monitor.aclose() + + # Returns promptly rather than after the 30 second timeout. + result = await asyncio.wait_for(waiter, timeout=1.0) + assert result == () + + asyncio.run(_body()) + + +def test_stop_releases_the_monitoring_connection() -> None: + """The monitor service disposes a monitor by calling stop(), so a teardown + it does not schedule leaks a connection on every sweep.""" + conn = MagicMock() + conn.close = MagicMock() + + async def _body(): + monitor = _monitor() + monitor.start() + monitor._owned_conn = conn + + monitor.stop() + for _ in range(10): + await asyncio.sleep(0) + + conn.close.assert_called_once() + assert not monitor.is_running() + # Only aclose() sets _closed, so a task that merely exited on the stop + # signal and closed the connection in its own finally does not pass. + assert monitor._closed, "stop() did not schedule aclose()" + + asyncio.run(_body()) + + +def test_the_provider_removes_a_dead_monitor_by_identity() -> None: + """Removing by key would dispose a live replacement a cleanup pass had + already put there, under the caller using it.""" + services_container.get_monitor_service()._monitor_caches.pop( + AsyncClusterTopologyMonitor, None) + provider = AsyncAuroraHostListProvider( + Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5432"}), + MagicMock()) + + async def _body(): + monitor_service = services_container.get_monitor_service() + key = provider._storage_key() + + # A dead monitor is handed out, and a live replacement is already at + # the key by the time the provider reacts. + dead = _monitor() + live = _monitor() + live.start() + monitor_service.run_if_absent(AsyncClusterTopologyMonitor, key, lambda: live) + + monitor_service.stop_and_remove_value(AsyncClusterTopologyMonitor, dead) + + assert monitor_service.get(AsyncClusterTopologyMonitor, key) is live + assert live.is_running(), "the live replacement was disposed" + await live.aclose() + + asyncio.run(_body()) diff --git a/tests/unit/test_aio_multi_alias_tracker.py b/tests/unit/test_aio_multi_alias_tracker.py deleted file mode 100644 index 5e136bce6..000000000 --- a/tests/unit/test_aio_multi_alias_tracker.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for multi-alias invalidation in AsyncOpenedConnectionTracker (N.2). - -Fixes the prior canonical-key-only semantics: a tracked connection is -now reachable from ANY alias in host_info.as_aliases(), so an -invalidate_all() call via any alias closes every peer connection to -the same underlying instance. -""" - -from __future__ import annotations - -import asyncio -from unittest.mock import MagicMock - -import pytest - -from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ - AsyncOpenedConnectionTracker -from aws_advanced_python_wrapper.hostinfo import HostInfo - - -@pytest.fixture(autouse=True) -def _reset_tracker(): - AsyncOpenedConnectionTracker._tracked.clear() - yield - AsyncOpenedConnectionTracker._tracked.clear() - - -def _host_with_aliases(*aliases: str) -> HostInfo: - """Build a HostInfo whose as_aliases() returns ``aliases``.""" - host = HostInfo(host=aliases[0] if aliases else "h", port=5432) - for alias in aliases[1:]: - host.add_alias(alias) - return host - - -def test_track_records_under_every_alias() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - "cluster.abcd.us-east-1.rds.amazonaws.com", - ) - tracker.track(host, conn) - - keys = AsyncOpenedConnectionTracker._tracked - # Both aliases (plus canonical) resolve to this conn. - matching = [ - k for k, weak_set in keys.items() - if conn in list(weak_set) - ] - assert len(matching) >= 2 - - -def test_invalidate_reaches_conn_via_secondary_alias() -> None: - """A HostInfo that shares the same secondary alias reaches the same - tracked connection -- even when its primary host differs from the - one the connection was tracked under.""" - tracker = AsyncOpenedConnectionTracker() - - class _Conn: - def __init__(self) -> None: - self.closed = False - - def close(self) -> None: - self.closed = True - - conn = _Conn() - shared_alias = "cluster.abcd.us-east-1.rds.amazonaws.com" - - # Track via a HostInfo whose primary is the instance endpoint. - track_host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - shared_alias, - ) - tracker.track(track_host, conn) - - # Invalidate via a different HostInfo whose primary is different but - # whose alias set includes the shared cluster endpoint. - invalidate_host = _host_with_aliases( - "instance-7.abcd.us-east-1.rds.amazonaws.com", - shared_alias, - ) - asyncio.run(tracker.invalidate_all(invalidate_host)) - - assert conn.closed is True - - -def test_invalidate_closes_each_conn_exactly_once() -> None: - """Even if a single connection is reachable from multiple aliases, - invalidate_all must only call close() once per connection.""" - tracker = AsyncOpenedConnectionTracker() - - class _Conn: - def __init__(self) -> None: - self.close_count = 0 - - def close(self) -> None: - self.close_count += 1 - - conn = _Conn() - host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - "cluster.abcd.us-east-1.rds.amazonaws.com", - "cluster-ro.abcd.us-east-1.rds.amazonaws.com", - ) - tracker.track(host, conn) - asyncio.run(tracker.invalidate_all(host)) - - assert conn.close_count == 1 - - -def test_invalidate_swallows_close_errors() -> None: - tracker = AsyncOpenedConnectionTracker() - - class _BadConn: - def close(self) -> None: - raise RuntimeError("boom") - - host = _host_with_aliases("instance-1.abcd.us-east-1.rds.amazonaws.com") - tracker.track(host, _BadConn()) - # Must not raise. - asyncio.run(tracker.invalidate_all(host)) - - -def test_remove_clears_conn_from_every_alias() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - "cluster.abcd.us-east-1.rds.amazonaws.com", - ) - tracker.track(host, conn) - tracker.remove(host, conn) - - for weak_set in AsyncOpenedConnectionTracker._tracked.values(): - assert conn not in list(weak_set) diff --git a/tests/unit/test_aio_multi_key_tracker.py b/tests/unit/test_aio_multi_key_tracker.py new file mode 100644 index 000000000..3b87f4300 --- /dev/null +++ b/tests/unit/test_aio_multi_key_tracker.py @@ -0,0 +1,133 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for how AsyncOpenedConnectionTracker keys its connections. + +An instance endpoint names the instance, so one key is enough. Any other +endpoint may be a custom domain name, so the connection is tracked under both +the host id and the endpoint, and an invalidation naming either one finds it. +""" + +from __future__ import annotations + +import asyncio +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ + AsyncOpenedConnectionTracker +from aws_advanced_python_wrapper.hostinfo import HostInfo + +INSTANCE = "instance-1.abcd.us-east-1.rds.amazonaws.com" +CUSTOM = "db.example.com" + + +@pytest.fixture(autouse=True) +def _reset_tracker(): + AsyncOpenedConnectionTracker._tracked.clear() + yield + AsyncOpenedConnectionTracker._tracked.clear() + + +def _keys_holding(conn) -> set: + return { + key for key, conn_set in AsyncOpenedConnectionTracker._tracked.items() + if conn in list(conn_set)} + + +def test_an_instance_endpoint_is_tracked_under_one_key() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + tracker.track(HostInfo(host=INSTANCE, port=5432, host_id="instance-1"), conn) + + assert _keys_holding(conn) == {f"{INSTANCE}:5432"} + + +def test_any_other_endpoint_is_tracked_under_the_host_id_and_the_endpoint() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + tracker.track(HostInfo(host=CUSTOM, port=5432, host_id="instance-1"), conn) + + assert _keys_holding(conn) == {"instance-1", f"{CUSTOM}:5432"} + + +def test_a_host_without_a_host_id_is_tracked_under_the_endpoint_alone() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + tracker.track(HostInfo(host=CUSTOM, port=5432), conn) + + assert _keys_holding(conn) == {f"{CUSTOM}:5432"} + + +def test_invalidate_reaches_a_connection_through_its_host_id() -> None: + """The endpoint a connection was opened against can differ from the one a + later invalidation names; the host id is what they share.""" + tracker = AsyncOpenedConnectionTracker() + + class _Conn: + def __init__(self) -> None: + self.closed = False + + def close(self) -> None: + self.closed = True + + conn = _Conn() + tracker.track(HostInfo(host=CUSTOM, port=5432, host_id="instance-1"), conn) + + asyncio.run(tracker.invalidate_all( + HostInfo(host=INSTANCE, port=5432, host_id="instance-1"))) + + assert conn.closed is True + + +def test_invalidate_closes_each_connection_exactly_once() -> None: + tracker = AsyncOpenedConnectionTracker() + + class _Conn: + def __init__(self) -> None: + self.close_count = 0 + + def close(self) -> None: + self.close_count += 1 + + conn = _Conn() + host = HostInfo(host=CUSTOM, port=5432, host_id="instance-1") + tracker.track(host, conn) + asyncio.run(tracker.invalidate_all(host)) + + assert conn.close_count == 1 + + +def test_invalidate_swallows_close_errors() -> None: + tracker = AsyncOpenedConnectionTracker() + + class _BadConn: + def close(self) -> None: + raise RuntimeError("boom") + + host = HostInfo(host=INSTANCE, port=5432) + tracker.track(host, _BadConn()) + # Must not raise. + asyncio.run(tracker.invalidate_all(host)) + + +def test_remove_clears_the_connection_from_every_key() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + host = HostInfo(host=CUSTOM, port=5432, host_id="instance-1") + tracker.track(host, conn) + tracker.remove(host, conn) + + assert _keys_holding(conn) == set() diff --git a/tests/unit/test_aio_plugin_service_extras.py b/tests/unit/test_aio_plugin_service_extras.py index 3e013a65e..b81fcd75a 100644 --- a/tests/unit/test_aio_plugin_service_extras.py +++ b/tests/unit/test_aio_plugin_service_extras.py @@ -16,6 +16,7 @@ from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.properties import Properties @@ -73,16 +74,97 @@ def test_get_availability_returns_none_when_unset(): def test_set_then_get_availability(): svc = _make_service() - svc.set_availability(frozenset({"host-1.cluster.example"}), HostAvailability.UNAVAILABLE) - assert svc.get_availability("host-1.cluster.example") == HostAvailability.UNAVAILABLE + host = HostInfo("host-1.cluster.example", 5432) + svc._all_hosts = (host,) + svc.set_availability(host, HostAvailability.UNAVAILABLE) -def test_set_availability_covers_all_aliases(): + assert svc.get_availability(host.url) == HostAvailability.UNAVAILABLE + assert host.get_raw_availability() == HostAvailability.UNAVAILABLE + + +def test_set_availability_matches_a_host_by_its_host_id(): + """The caller's host and the topology's host can carry different endpoints + for the same instance, which is what the host id is for.""" + svc = _make_service() + in_topology = HostInfo("instance-1.abc.us-east-1.rds.amazonaws.com", 5432, + host_id="instance-1") + svc._all_hosts = (in_topology,) + + svc.set_availability(HostInfo("db.example.com", 5432, host_id="instance-1"), + HostAvailability.UNAVAILABLE) + + assert in_topology.get_raw_availability() == HostAvailability.UNAVAILABLE + + +def test_set_availability_ignores_a_host_that_is_not_in_the_host_list(): + svc = _make_service() + in_list = HostInfo("h1.example", 5432) + svc._all_hosts = (in_list,) + stranger = HostInfo("stranger.example", 5432) + + svc.set_availability(stranger, HostAvailability.UNAVAILABLE) + + assert svc.get_availability(stranger.url) is None + # Bound both sides: the argument itself is not marked either. + assert stranger.get_raw_availability() == HostAvailability.AVAILABLE + assert in_list.get_raw_availability() == HostAvailability.AVAILABLE + + +def test_set_availability_notifies_only_on_an_actual_change(): + svc = _make_service() + host = HostInfo("h1.example", 5432) + svc._all_hosts = (host,) + manager = MagicMock() + svc.plugin_manager = manager + + # Already AVAILABLE, so nothing changed. + svc.set_availability(host, HostAvailability.AVAILABLE) + manager.notify_host_list_changed.assert_not_called() + + svc.set_availability(host, HostAvailability.UNAVAILABLE) + changes = manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} + + +def test_set_current_connection_clears_the_routed_host(): + """A switch that reuses a cached connection never runs a connect, so this + is the only thing that stops the next reader of the field seeing the host + the connection has already moved off.""" + async def _body(): + svc = _make_service() + reader = HostInfo("reader-1.example", 5432) + writer = HostInfo("writer-1.example", 5432) + svc.routed_host_info = reader + + await svc.set_current_connection(MagicMock(), writer) + + assert svc.routed_host_info is None + + asyncio.run(_body()) + + +def test_take_routed_host_info_returns_it_once(): + svc = _make_service() + routed = HostInfo("instance-1.example", 5432) + svc.routed_host_info = routed + + assert svc.take_routed_host_info() is routed + assert svc.take_routed_host_info() is None + + +def test_set_availability_writes_the_cache_under_the_host_url(): + """_update_host_availability reads back by url, so the write has to use the + same key or a fresh topology never recovers the mark.""" svc = _make_service() - aliases = frozenset({"h1.example", "h1-alias.example"}) - svc.set_availability(aliases, HostAvailability.UNAVAILABLE) - for alias in aliases: - assert svc.get_availability(alias) == HostAvailability.UNAVAILABLE + host = HostInfo("h1.example", 5432) + svc._all_hosts = (host,) + + svc.set_availability(host, HostAvailability.UNAVAILABLE) + + rebuilt = HostInfo("h1.example", 5432) + svc._update_host_availability((rebuilt,)) + assert rebuilt.get_raw_availability() == HostAvailability.UNAVAILABLE def test_default_plugin_accepts_random_strategy(): @@ -496,64 +578,6 @@ def test_current_host_info_raises_when_writer_not_allowed(): _ = svc.current_host_info -# ---- fill_aliases (sync parity) -------------------------------------- - - -def _alias_cursor(rows): - cur = MagicMock() - cur.__aenter__ = AsyncMock(return_value=cur) - cur.__aexit__ = AsyncMock(return_value=None) - cur.execute = AsyncMock() - cur.fetchall = AsyncMock(return_value=rows) - return cur - - -def test_fill_aliases_adds_self_query_and_identify_aliases(): - async def _body(): - svc = _make_service() - dialect = MagicMock(spec=DatabaseDialect) - dialect.host_alias_query = "SELECT CONCAT(...)" - svc.database_dialect = dialect - - conn = MagicMock() - conn.cursor = MagicMock(return_value=_alias_cursor([("db-alias",)])) - - identified = HostInfo("h", 5432) - identified.add_alias("id-alias") - svc.identify_connection = AsyncMock(return_value=identified) - - host = HostInfo("h", 5432) - await svc.fill_aliases(conn, host) - - assert "h:5432" in host.aliases # host:port self-alias - assert "db-alias" in host.aliases # from host_alias_query - assert "id-alias" in host.aliases # from identify_connection - - asyncio.run(_body()) - - -def test_fill_aliases_noop_when_already_has_aliases(): - async def _body(): - svc = _make_service() - host = HostInfo("h", 5432) - host.add_alias("existing") - conn = MagicMock() - await svc.fill_aliases(conn, host) - conn.cursor.assert_not_called() - - asyncio.run(_body()) - - -def test_fill_aliases_noop_when_no_connection(): - async def _body(): - svc = _make_service() - host = HostInfo("h", 5432) - await svc.fill_aliases(None, host) - assert len(host.aliases) == 0 - - asyncio.run(_body()) - - # ---- get_host_role default timeout (sync parity) --------------------- @@ -627,7 +651,7 @@ async def _body(): result = asyncio.run(_body()) assert result is conn svc.set_availability.assert_called_once_with( - host.as_aliases(), HostAvailability.AVAILABLE) + host, HostAvailability.AVAILABLE) svc.update_driver_dialect.assert_called_once_with(provider) @@ -648,7 +672,7 @@ async def _body(): asyncio.run(_body()) svc.set_availability.assert_called_once_with( - host.as_aliases(), HostAvailability.AVAILABLE) + host, HostAvailability.AVAILABLE) svc.update_driver_dialect.assert_called_once_with(provider) diff --git a/tests/unit/test_aio_retry_util.py b/tests/unit/test_aio_retry_util.py index 41dcc385a..20c56f5af 100644 --- a/tests/unit/test_aio_retry_util.py +++ b/tests/unit/test_aio_retry_util.py @@ -244,7 +244,7 @@ async def _connect(_host): assert result.connection is conn assert result.host_info.host == _W.host svc.set_availability.assert_any_call( - _W.as_aliases(), HostAvailability.AVAILABLE) + _W, HostAvailability.AVAILABLE) asyncio.run(_body()) @@ -310,7 +310,7 @@ async def _connect(_host): await util.get_writer_connection( svc, hlp, _connect, (dead,), _deadline(0.25)) svc.set_availability.assert_any_call( - dead.as_aliases(), HostAvailability.UNAVAILABLE) + dead, HostAvailability.UNAVAILABLE) asyncio.run(_body()) @@ -360,7 +360,7 @@ async def _connect(host): assert result.connection is conns["new-writer"] # Dead old writer marked unavailable; the reader probe connection dropped. svc.set_availability.assert_any_call( - old.as_aliases(), HostAvailability.UNAVAILABLE) + old, HostAvailability.UNAVAILABLE) svc.driver_dialect.abort_connection.assert_awaited() asyncio.run(_body()) diff --git a/tests/unit/test_aio_simple_rws.py b/tests/unit/test_aio_simple_rws.py index 4f7a75467..cb764cb42 100644 --- a/tests/unit/test_aio_simple_rws.py +++ b/tests/unit/test_aio_simple_rws.py @@ -223,10 +223,13 @@ def test_verify_retries_then_falls_back_when_role_mismatches_and_current_usable( async def _body() -> None: # Asked for a reader, but every probe says WRITER -> exhaust retries. svc, dd = _build_plugin_service(role_returns=HostRole.WRITER) - # Extra-short timeout to keep the test quick; still exercises >1 loop. + # The budget has to outlast one slow attempt by a wide margin: the + # retry loop checks a wall-clock deadline, and at a 30ms budget a + # scheduling hiccup under the full suite left a single attempt and + # failed the await_count assertions below. props = _base_props( **{ - WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "30", + WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "250", WrapperProperties.SRW_CONNECT_RETRY_INTERVAL_MS.name: "5", } ) diff --git a/tests/unit/test_aio_topology_storage.py b/tests/unit/test_aio_topology_storage.py index c25711b3e..b83e94564 100644 --- a/tests/unit/test_aio_topology_storage.py +++ b/tests/unit/test_aio_topology_storage.py @@ -283,18 +283,32 @@ async def _run(): asyncio.run(_run()) -def test_copies_keep_their_aliases(): - """HostInfo.__copy__ drops aliases, and aliases are how a live connection - is matched back to its topology row.""" - aliased = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1") - aliased.add_alias("srv-1") +def test_copies_keep_their_host_id(): + """host_id is how a live connection is matched back to its topology row.""" + stored = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1") prov = _aurora() async def _run(): - prov._store_topology((aliased,)) + prov._store_topology((stored,)) got = await prov.refresh() - assert got[0] is not aliased - assert "srv-1" in got[0].aliases + assert got[0] is not stored assert got[0].host_id == "srv-1" asyncio.run(_run()) + + +def test_copies_keep_their_availability_strategy(): + """The strategy decides when a host marked unavailable becomes usable + again, so a copy that reverted to the no-op default would report it + available straight away.""" + prov = _aurora() + strategy = prov._topology_utils._host_availability_strategy + stored = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1", + host_availability_strategy=strategy) + + async def _run(): + prov._store_topology((stored,)) + got = await prov.refresh() + assert got[0].host_availability_strategy is strategy + + asyncio.run(_run()) diff --git a/tests/unit/test_aio_wrapper.py b/tests/unit/test_aio_wrapper.py index c27f4b2b9..41a718d3e 100644 --- a/tests/unit/test_aio_wrapper.py +++ b/tests/unit/test_aio_wrapper.py @@ -728,9 +728,14 @@ async def _body() -> None: target=_build_mock_psycopg_connect(raw_conn), conninfo="host=h user=u password=p dbname=d port=5432", ) - async with wrapper.cursor() as cur: - assert isinstance(cur, AsyncAwsWrapperCursor) - mock_cursor.close.assert_awaited_once() + # The mock conn hands out one cursor for everything, including the + # wrapper's own auxiliary queries, so measure across the exit alone. + manager = wrapper.cursor() + cur = await manager.__aenter__() + assert isinstance(cur, AsyncAwsWrapperCursor) + before = mock_cursor.close.await_count + await manager.__aexit__(None, None, None) + assert mock_cursor.close.await_count == before + 1 asyncio.run(_body()) diff --git a/tests/unit/test_aurora_connection_tracker.py b/tests/unit/test_aurora_connection_tracker.py index dac80ae33..daec03efb 100644 --- a/tests/unit/test_aurora_connection_tracker.py +++ b/tests/unit/test_aurora_connection_tracker.py @@ -29,6 +29,7 @@ AuroraConnectionTrackerPlugin, OpenedConnectionTracker) from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType @pytest.fixture @@ -43,7 +44,11 @@ def mock_cursor(mocker): @pytest.fixture def mock_plugin_service(mocker): - return mocker.MagicMock() + service = mocker.MagicMock() + # A MagicMock attribute would stand in for a routed host and send the + # tracker down the identify path. + service.routed_host_info = None + return service @pytest.fixture @@ -67,11 +72,13 @@ def props(): def test_track_new_instance_connection( - mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_cursor, mock_callable): + mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_cursor, mock_callable, + mock_conn): host_info: HostInfo = HostInfo("instance1") mock_plugin_service.all_hosts = [host_info] mock_plugin_service.current_host_info = host_info mock_rds_utils.is_rds_instance.return_value = True + mock_rds_utils.identify_rds_type.return_value = RdsUrlType.RDS_INSTANCE mock_callable.return_value = mock_conn plugin: AuroraConnectionTrackerPlugin = AuroraConnectionTrackerPlugin(mock_plugin_service, Properties(), @@ -80,14 +87,35 @@ def test_track_new_instance_connection( conn: Connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, Properties(), True, mock_callable) assert mock_conn == conn - mock_tracker.populate_opened_connection_queue(host_info, mock_conn) - assert 0 == len(host_info.aliases) + mock_tracker.populate_opened_connection_set.assert_called_with(host_info, mock_conn) + # An instance endpoint names the instance, so there is nothing to identify. + mock_plugin_service.identify_connection.assert_not_called() conn = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, Properties(), False, mock_callable) assert mock_conn == conn - mock_tracker.populate_opened_connection_queue(host_info, mock_conn) - assert 0 == len(host_info.aliases) + mock_tracker.populate_opened_connection_set.assert_called_with(host_info, mock_conn) + mock_plugin_service.identify_connection.assert_not_called() + + +def test_connect_tracks_a_cluster_connection_under_its_identified_host( + mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_callable, mock_conn): + """A cluster endpoint does not name the instance the connection landed on, + so the tracker needs the identified host to key it correctly.""" + cluster_host = HostInfo("mydb.cluster-abc.us-east-2.rds.amazonaws.com", 5432) + identified = HostInfo("instance-1.abc.us-east-2.rds.amazonaws.com", 5432, + host_id="instance-1") + mock_rds_utils.identify_rds_type.return_value = RdsUrlType.RDS_WRITER_CLUSTER + mock_plugin_service.identify_connection.return_value = identified + mock_callable.return_value = mock_conn + + plugin = AuroraConnectionTrackerPlugin( + mock_plugin_service, Properties(), mock_rds_utils, mock_tracker) + plugin.connect( + mocker.MagicMock(), mocker.MagicMock(), cluster_host, Properties(), True, mock_callable) + + mock_tracker.populate_opened_connection_set.assert_called_with(identified, mock_conn) + assert mock_plugin_service.routed_host_info is identified def test_invalidate_opened_connections( @@ -179,6 +207,98 @@ def test_invalidate_all_connections_drains_set(mocker): assert len(captured) == 1 +def _real_tracker(mocker): + """A tracker with a real RdsUtils and no prune thread or closer thread.""" + OpenedConnectionTracker._opened_connections = {} + mocker.patch.object(OpenedConnectionTracker, "_start_prune_thread") + captured: list = [] + mocker.patch.object( + OpenedConnectionTracker, + "_invalidate_connections", + side_effect=lambda connections_list: captured.append(list(connections_list))) + return OpenedConnectionTracker(), captured + + +def test_a_non_instance_endpoint_is_tracked_under_its_host_id_too(mocker): + """The endpoint a connection was opened against can differ from the one a + later invalidation names; the host id is what they share.""" + tracker, _ = _real_tracker(mocker) + conn = mocker.MagicMock() + + tracker.populate_opened_connection_set( + HostInfo("db.example.com", 5432, host_id="instance-1"), conn) + + assert set(OpenedConnectionTracker._opened_connections) == { + "instance-1", "db.example.com:5432"} + + +def test_an_instance_endpoint_is_tracked_under_one_key(mocker): + tracker, _ = _real_tracker(mocker) + + tracker.populate_opened_connection_set( + HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1"), + mocker.MagicMock()) + + assert set(OpenedConnectionTracker._opened_connections) == { + "instance-1.xyz.us-east-2.rds.amazonaws.com:5432"} + + +def test_invalidate_reaches_a_connection_through_its_host_id(mocker): + tracker, captured = _real_tracker(mocker) + conn = mocker.MagicMock() + tracker.populate_opened_connection_set( + HostInfo("db.example.com", 5432, host_id="instance-1"), conn) + + tracker.invalidate_all_connections( + HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1")) + + assert captured and conn in captured[0] + + +def test_invalidate_closes_a_multi_key_connection_once(mocker): + """Closing a pool-proxied connection twice would invalidate whatever the + pool handed out in between.""" + tracker, captured = _real_tracker(mocker) + conn = mocker.MagicMock() + host = HostInfo("db.example.com", 5432, host_id="instance-1") + tracker.populate_opened_connection_set(host, conn) + + tracker.invalidate_all_connections(host) + + assert len(captured) == 1 + assert captured[0].count(conn) == 1 + + +def test_notify_strips_the_trailing_slash_from_a_change_key( + mocker, mock_plugin_service, mock_rds_utils, mock_callable): + """Change keys are urls; tracking keys are not. Matching them without + stripping would never find the connection.""" + from aws_advanced_python_wrapper.utils.notifications import HostEvent + + tracker, captured = _real_tracker(mocker) + conn = mocker.MagicMock() + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + tracker.populate_opened_connection_set(host, conn) + + plugin = AuroraConnectionTrackerPlugin( + mock_plugin_service, Properties(), mock_rds_utils, tracker) + plugin.notify_host_list_changed({host.url: {HostEvent.CONVERTED_TO_READER}}) + + assert captured and conn in captured[0] + + +def test_remove_connection_tracking_clears_every_key(mocker): + tracker, _ = _real_tracker(mocker) + conn = mocker.MagicMock() + host = HostInfo("db.example.com", 5432, host_id="instance-1") + tracker.populate_opened_connection_set(host, conn) + + tracker.remove_connection_tracking(host, conn) + + assert all(conn not in conn_set + for conn_set in OpenedConnectionTracker._opened_connections.values()) + + def test_task_invalidates_pool_proxied_connections(mocker): pool_proxied_conn = mocker.MagicMock() diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index 30b191b15..8e5f20684 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -46,6 +46,47 @@ def test_connection_basic(): password="qwerty") +def _wrapper_with(plugin_service, plugin_manager, conn): + """Drive AwsWrapperConnection.__init__ past its setup to the host-adoption + step, which is what decides the connection's current host.""" + plugin_manager.connect.return_value = conn + plugin_service.database_dialect.get_host_list_provider_supplier.return_value = \ + lambda _service, _props: MagicMock() + wrapper = AwsWrapperConnection.__new__(AwsWrapperConnection) + AwsWrapperConnection.__init__( + wrapper, MagicMock(), MagicMock(), plugin_service, plugin_manager) + return wrapper + + +def test_the_wrapper_adopts_the_host_a_plugin_routed_the_connect_to(): + """The initial connection strategy plugin substitutes an instance for a + cluster endpoint. Binding the connection to the endpoint instead would + leave every later host comparison naming the wrong host.""" + routed = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + conn = MagicMock(spec=psycopg.Connection) + plugin_service = MagicMock() + plugin_service.current_connection = None + plugin_service.initial_connection_host_info = HostInfo("mydb.cluster-xyz.us-east-2.rds.amazonaws.com", 5432) + plugin_service.take_routed_host_info.return_value = routed + + _wrapper_with(plugin_service, MagicMock(), conn) + + plugin_service.set_current_connection.assert_called_once_with(conn, routed) + + +def test_the_wrapper_falls_back_to_the_initial_host_when_nothing_routed(): + initial = HostInfo("mydb.cluster-xyz.us-east-2.rds.amazonaws.com", 5432) + conn = MagicMock(spec=psycopg.Connection) + plugin_service = MagicMock() + plugin_service.current_connection = None + plugin_service.initial_connection_host_info = initial + plugin_service.take_routed_host_info.return_value = None + + _wrapper_with(plugin_service, MagicMock(), conn) + + plugin_service.set_current_connection.assert_called_once_with(conn, initial) + + def test_connection_getattr_delegates_to_underlying_connection(): # Driver-specific extension methods absent from the wrapper's PEP-249 surface # (e.g. psycopg's add_notice_handler, called by SQLAlchemy) must reach the diff --git a/tests/unit/test_expiration_tracking_cache.py b/tests/unit/test_expiration_tracking_cache.py index faa4756ae..a28331ccd 100644 --- a/tests/unit/test_expiration_tracking_cache.py +++ b/tests/unit/test_expiration_tracking_cache.py @@ -66,24 +66,6 @@ def test_compute_if_absent_extends_expiration(): assert cache.get("k1") == "v1" -def test_get_or_create_for_aliases(cache): - result = cache.get_or_create_for_aliases( - frozenset(["a", "b", "c"]), lambda: "val") - assert result == "val" - assert cache.get("a") == "val" - assert cache.get("b") == "val" - assert cache.get("c") == "val" - - -def test_get_or_create_for_aliases_reuses_existing(cache): - cache.put("b", "existing") - result = cache.get_or_create_for_aliases( - frozenset(["a", "b", "c"]), lambda: "new") - assert result == "existing" - # "a" and "c" should also be set - assert cache.get("a") == "existing" - - def test_extend_expiration(): cache = ExpirationTrackingCache(_SHORT_TTL) cache.put("k1", "v1") diff --git a/tests/unit/test_failover_plugin.py b/tests/unit/test_failover_plugin.py index d3aa54284..3d1581d91 100644 --- a/tests/unit/test_failover_plugin.py +++ b/tests/unit/test_failover_plugin.py @@ -22,7 +22,7 @@ if TYPE_CHECKING: from aws_advanced_python_wrapper.writer_failover_handler import WriterFailoverHandler -from typing import Dict, FrozenSet, Set +from typing import Dict, Set from unittest import mock from unittest.mock import MagicMock, PropertyMock @@ -130,27 +130,21 @@ def test_notify_host_list_changed_with_failover_disabled(plugin_service_mock, ho get_current_host_mock = PropertyMock(return_value=host_mock) type(plugin_service_mock).current_host_info = get_current_host_mock - get_aliases_mock = PropertyMock() - type(host_mock).aliases = get_aliases_mock plugin.notify_host_list_changed(changes) get_current_host_mock.assert_not_called() - get_aliases_mock.assert_not_called() WrapperProperties.ENABLE_FAILOVER.set(properties, "True") plugin = FailoverPlugin(plugin_service_mock, properties) plugin.notify_host_list_changed(changes) get_current_host_mock.assert_called() - get_aliases_mock.assert_not_called() def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_service_mock, host_mock): host_mock.url = "cluster-url/" - aliases: FrozenSet[str] = frozenset("instance") - host_mock.aliases = aliases properties = Properties() WrapperProperties.ENABLE_FAILOVER.set(properties, "True") @@ -158,8 +152,6 @@ def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_s get_current_host_mock = PropertyMock(return_value=host_mock) type(plugin_service_mock).current_host_info = get_current_host_mock - get_aliases_mock = PropertyMock() - type(host_mock).aliases = get_aliases_mock changes: Dict[str, Set[HostEvent]] = \ {"cluster-host/": {HostEvent.HOST_DELETED}, @@ -167,7 +159,6 @@ def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_s plugin.notify_host_list_changed(changes) get_current_host_mock.assert_called() - get_aliases_mock.assert_not_called() def test_update_topology( diff --git a/tests/unit/test_host_monitor_v2_plugin.py b/tests/unit/test_host_monitor_v2_plugin.py index 273a2e442..b057e3f4b 100644 --- a/tests/unit/test_host_monitor_v2_plugin.py +++ b/tests/unit/test_host_monitor_v2_plugin.py @@ -46,6 +46,8 @@ def mock_plugin_service(mocker, mock_driver_dialect, mock_conn, host_info): service_mock = mocker.MagicMock() service_mock.current_connection = mock_conn service_mock.current_host_info = host_info + # A MagicMock attribute would stand in for a routed host. + service_mock.routed_host_info = None type(service_mock).driver_dialect = mocker.PropertyMock(return_value=mock_driver_dialect) return service_mock @@ -165,28 +167,67 @@ def test_execute_monitoring_enabled(mocker, plugin, mock_monitor_service, mock_e def test_connect(mocker, plugin, host_info, props, mock_conn, mock_plugin_service): + """A cluster endpoint does not name the instance the connection landed on, + so the instance is identified and recorded as the routed host.""" mock_connect_func = mocker.MagicMock() mock_connect_func.return_value = mock_conn + identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") + mock_plugin_service.identify_connection.return_value = identified connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, props, True, mock_connect_func) - mock_plugin_service.fill_aliases.assert_called_once() + + mock_plugin_service.identify_connection.assert_called_once() + assert mock_plugin_service.routed_host_info is identified assert mock_conn == connection -def test_get_monitoring_host_info_errors(mocker, plugin, mock_plugin_service): - mock_plugin_service.identify_connection.return_value = None +@pytest.mark.parametrize( + "host", + ["db.example.com", # a custom domain, classified OTHER + "10.0.0.5", # an IP address + "mydb.cluster-custom-xyz.us-east-2.rds.amazonaws.com"]) +def test_a_non_instance_endpoint_has_its_instance_identified( + mocker, mock_plugin_service, mock_monitor_service, props, host): + """These endpoints do not name the instance the connection is on, so the + host to probe has to be resolved rather than taken from the endpoint.""" + identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, + host_id="instance-1") + mock_plugin_service.current_host_info = HostInfo(host, 5432) + mock_plugin_service.identify_connection.return_value = identified + plugin = init_plugin(mock_plugin_service, props, mock_monitor_service) - with pytest.raises(AwsWrapperError): - plugin._get_monitoring_host_info() + assert plugin._get_monitoring_host_info() is identified + + +@pytest.mark.parametrize( + "host", + ["instance-1.xyz.us-east-2.rds.amazonaws.com", + "myproxy.proxy-xyz.us-east-2.rds.amazonaws.com", + "myshardgroup.shardgrp-xyz.us-east-2.rds.amazonaws.com"]) +def test_a_managed_router_endpoint_is_monitored_as_itself( + mocker, mock_plugin_service, mock_monitor_service, props, host): + """A proxy or shard group endpoint stays reachable and is the right thing + to probe. The instance behind it may refuse a direct connection, which + would make the monitor declare a healthy host dead.""" + router = HostInfo(host, 5432) + mock_plugin_service.current_host_info = router + plugin = init_plugin(mock_plugin_service, props, mock_monitor_service) + + assert plugin._get_monitoring_host_info() is router + mock_plugin_service.identify_connection.assert_not_called() - expected_exception = Error() - mock_plugin_service.identify_connection.return_value = mocker.MagicMock() - mock_plugin_service.identify_connection.side_effect = expected_exception - with pytest.raises(AwsWrapperError) as exc_info: - plugin._get_monitoring_host_info() - assert expected_exception == exc_info.value.__cause__ +def test_get_monitoring_host_info_keeps_the_host_when_identification_fails( + mocker, plugin, mock_plugin_service, host_info): + """A localhost, IP or custom-domain host cannot be identified. Failing here + would fail every monitored call on a host that is perfectly monitorable.""" + mock_plugin_service.identify_connection.return_value = None + assert plugin._get_monitoring_host_info() is host_info + + plugin._monitoring_host_info = None + mock_plugin_service.identify_connection.side_effect = Error() + assert plugin._get_monitoring_host_info() is host_info def test_release_resources(plugin, mock_monitor_service): diff --git a/tests/unit/test_host_monitoring_plugin.py b/tests/unit/test_host_monitoring_plugin.py index dab274180..788845f32 100644 --- a/tests/unit/test_host_monitoring_plugin.py +++ b/tests/unit/test_host_monitoring_plugin.py @@ -38,6 +38,8 @@ def mock_plugin_service(mocker, mock_driver_dialect, mock_conn, host_info): service_mock = mocker.MagicMock() service_mock.current_connection = mock_conn service_mock.current_host_info = host_info + # A MagicMock attribute would stand in for a routed host. + service_mock.routed_host_info = None type(service_mock).driver_dialect = mocker.PropertyMock(return_value=mock_driver_dialect) return service_mock @@ -157,45 +159,78 @@ def test_execute_cleanup__connection_not_closed( def test_connect(mocker, plugin, host_info, props, mock_conn, mock_plugin_service): + """A cluster endpoint does not name the instance the connection landed on, + so the instance is identified and recorded as the routed host.""" mock_connect_func = mocker.MagicMock() mock_connect_func.return_value = mock_conn + identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") + mock_plugin_service.identify_connection.return_value = identified connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, props, True, mock_connect_func) - mock_plugin_service.fill_aliases.assert_called_once() + + mock_plugin_service.identify_connection.assert_called_once() + assert mock_plugin_service.routed_host_info is identified assert mock_conn == connection @pytest.mark.parametrize( "host_events", - [{"instance-1.xyz.us-east-2.rds.amazonaws.com": {HostEvent.HOST_DELETED}}, - {"instance-1.xyz.us-east-2.rds.amazonaws.com": {HostEvent.WENT_DOWN}}]) + [{"instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.HOST_DELETED}}, + {"instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.WENT_DOWN}}]) def test_notify_host_list_changed( mocker, plugin, host_info, props, mock_conn, mock_plugin_service, mock_monitor_service, host_events): - mock_host_info = mocker.MagicMock() - mock_host_info.host = "instance-1.xyz.us-east-2.rds.amazonaws.com" - aliases = frozenset({"instance-1.xyz.us-east-2.rds.amazonaws.com", "alias1", "alias2"}) - mock_host_info.all_aliases = aliases + monitored = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") plugin._is_connection_initialized = True + plugin._monitoring_host_info = monitored - mock_plugin_service.current_host_info = mock_host_info + mock_plugin_service.current_host_info = monitored plugin.notify_host_list_changed(host_events) - mock_monitor_service.stop_monitoring_host.assert_called_with(aliases) + mock_monitor_service.stop_monitoring_host.assert_called_with(monitored.url) -def test_get_monitoring_host_info_errors(mocker, plugin, mock_plugin_service): - mock_plugin_service.identify_connection.return_value = None +def test_notify_host_list_changed_examines_every_entry( + mocker, plugin, mock_plugin_service, mock_monitor_service): + """set_availability publishes one entry per matched host, so stopping at + the first host with no relevant event drops the rest.""" + monitored = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", host_id="instance-2") + plugin._is_connection_initialized = True + plugin._monitoring_host_info = monitored + mock_plugin_service.current_host_info = monitored - with pytest.raises(AwsWrapperError): - plugin._get_monitoring_host_info() + plugin.notify_host_list_changed({ + "instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.HOST_CHANGED}, + monitored.url: {HostEvent.WENT_DOWN}, + }) - expected_exception = Error() - mock_plugin_service.identify_connection.return_value = mocker.MagicMock() - mock_plugin_service.identify_connection.side_effect = expected_exception - with pytest.raises(AwsWrapperError) as exc_info: - plugin._get_monitoring_host_info() + mock_monitor_service.stop_monitoring_host.assert_called_once_with(monitored.url) + + +def test_notify_host_list_changed_after_release_resources( + mocker, plugin, mock_plugin_service, mock_monitor_service): + """A failover worker thread outlives its connection, so it can mark a host + unavailable after this plugin has dropped its monitor service reference.""" + monitored = HostInfo("instance-3.xyz.us-east-2.rds.amazonaws.com", host_id="instance-3") + plugin._is_connection_initialized = True + plugin._monitoring_host_info = monitored + mock_plugin_service.current_host_info = monitored + + plugin.release_resources() + plugin.notify_host_list_changed({monitored.url: {HostEvent.WENT_DOWN}}) + + mock_monitor_service.stop_monitoring_host.assert_not_called() + + +def test_get_monitoring_host_info_keeps_the_host_when_identification_fails( + mocker, plugin, mock_plugin_service, host_info): + """A localhost, IP or custom-domain host cannot be identified. Failing here + would fail every monitored call on a host that is perfectly monitorable.""" + mock_plugin_service.identify_connection.return_value = None + assert plugin._get_monitoring_host_info() is host_info - assert expected_exception == exc_info.value.__cause__ + plugin._monitoring_host_info = None + mock_plugin_service.identify_connection.side_effect = Error() + assert plugin._get_monitoring_host_info() is host_info def test_release_resources(plugin, mock_monitor_service): diff --git a/tests/unit/test_hostinfo.py b/tests/unit/test_hostinfo.py index 917103e19..19a2e5210 100644 --- a/tests/unit/test_hostinfo.py +++ b/tests/unit/test_hostinfo.py @@ -24,17 +24,38 @@ def test_host_info_defaults(): host_info = HostInfo("testhost") assert host_info.host == "testhost" assert host_info.is_port_specified() is False - assert len(host_info.aliases) == 0 - assert len(host_info._all_aliases) == 1 + assert host_info.get_host_and_port() == "testhost" assert host_info.role == HostRole.WRITER assert host_info.availability == HostAvailability.AVAILABLE - assert list(host_info._all_aliases)[0] == "testhost" -def test_host_as_alias(): - host_info = HostInfo("testhost", 1234) - assert len(host_info._all_aliases) == 1 - assert list(host_info._all_aliases)[0] == "testhost:1234" +def test_host_and_port_includes_the_port_when_specified(): + assert HostInfo("testhost", 1234).get_host_and_port() == "testhost:1234" + + +def test_url_keeps_its_trailing_slash(): + """The availability cache, the notify_host_list_changed change map and the + host monitoring monitor keys are all keyed on this exact string.""" + assert HostInfo("testhost", 1234).url == "testhost:1234/" + + +def test_each_host_gets_its_own_availability_strategy(): + """A shared default would count one host's failures against all of them.""" + first = HostInfo("a") + second = HostInfo("b") + assert first.host_availability_strategy is not second.host_availability_strategy + + +def test_copy_carries_the_availability_strategy(): + from copy import copy + + from aws_advanced_python_wrapper.host_availability import \ + ExponentialBackoffHostAvailabilityStrategy + from aws_advanced_python_wrapper.utils.properties import Properties + + strategy = ExponentialBackoffHostAvailabilityStrategy(Properties()) + original = HostInfo("testhost", 1234, host_availability_strategy=strategy) + assert copy(original).host_availability_strategy is strategy def test_host_info_eq(): diff --git a/tests/unit/test_monitor_service.py b/tests/unit/test_monitor_service.py index b570eb055..d2ae4392e 100644 --- a/tests/unit/test_monitor_service.py +++ b/tests/unit/test_monitor_service.py @@ -12,12 +12,13 @@ # See the License for the specific language governing permissions and # limitations under the License. +from unittest.mock import MagicMock + import psycopg import pytest from _weakref import ref from aws_advanced_python_wrapper import release_resources -from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_monitoring_plugin import \ HostMonitorService from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -56,51 +57,59 @@ def cleanup(): def test_start_monitoring(mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - aliases = frozenset({"instance-1"}) + host_info = HostInfo("instance-1") - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) monitor_service.start_monitoring( - mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, host_info, Properties(), 5000, 1000, 3) mock_monitor.start_monitoring.assert_called_once() assert mock_monitor == monitor_service._cached_monitor() - assert aliases == monitor_service._cached_monitor_aliases + assert host_info.url == monitor_service._cached_monitor_host_url def test_start_monitoring__cached_monitor( mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - aliases = frozenset({"instance-1"}) + host_info = HostInfo("instance-1") monitor_service._cached_monitor = ref(mock_monitor) - monitor_service._cached_monitor_aliases = aliases + monitor_service._cached_monitor_host_url = host_info.url monitor_service.start_monitoring( - mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, host_info, Properties(), 5000, 1000, 3) mock_monitor.start_monitoring.assert_called_once() assert mock_monitor == monitor_service._cached_monitor() - assert aliases == monitor_service._cached_monitor_aliases + assert host_info.url == monitor_service._cached_monitor_host_url + + +def test_start_monitoring__replaces_a_monitor_for_a_different_host( + mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): + """The cached monitor is keyed on one host; another host needs its own.""" + stale = MagicMock() + stale.is_stopped = False + monitor_service._cached_monitor = ref(stale) + monitor_service._cached_monitor_host_url = HostInfo("other").url + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) + monitor_service.start_monitoring( + mock_conn, HostInfo("instance-1"), Properties(), 5000, 1000, 3) -def test_start_monitoring__errors(monitor_service, mock_conn): - with pytest.raises(AwsWrapperError): - monitor_service.start_monitoring( - mock_conn, frozenset(), HostInfo("instance-1"), Properties(), 5000, 1000, 3) + assert mock_monitor == monitor_service._cached_monitor() + stale.start_monitoring.assert_not_called() def test_stop_monitoring(mocker, monitor_service, mock_monitor, mock_conn): - aliases = frozenset({"instance-1"}) - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) context = monitor_service.start_monitoring( - mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, HostInfo("instance-1"), Properties(), 5000, 1000, 3) monitor_service.stop_monitoring(context) mock_monitor.stop_monitoring.assert_called_once_with(context) def test_stop_monitoring_host(mocker, monitor_service, mock_monitor): - aliases = frozenset({"alias-1"}) mocker.patch.object(monitor_service._monitor_service, 'get', return_value=mock_monitor) - monitor_service.stop_monitoring_host(aliases) + monitor_service.stop_monitoring_host(HostInfo("instance-1").url) mock_monitor.clear_contexts.assert_called_once() diff --git a/tests/unit/test_multi_az_rds_host_list_provider.py b/tests/unit/test_multi_az_rds_host_list_provider.py index c15dd6c58..16c236cce 100644 --- a/tests/unit/test_multi_az_rds_host_list_provider.py +++ b/tests/unit/test_multi_az_rds_host_list_provider.py @@ -18,6 +18,7 @@ from aws_advanced_python_wrapper.database_dialect import ( AuroraPgDialect, MultiAzClusterPgDialect) from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.host_list_provider import ( MultiAzTopologyUtils, RdsHostListProvider) from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -159,6 +160,32 @@ def test_get_topology_no_connection(mocker, mock_provider_service, initial_hosts mock_force_refresh.assert_not_called() +def test_multi_az_host_id_is_a_string(mock_provider_service, props): + """MySQL reports a numeric id. identify_connection compares host_id + against the string the host id query returns, so an int never matches and + no cluster-endpoint connection can be identified.""" + provider = create_provider(mock_provider_service, props) + host = provider._topology_utils._create_multi_az_host( + (12345, "instance-1.xyz.us-east-2.rds.amazonaws.com", 5432), 12345) + + assert host.host_id == "12345" + + +def test_initial_hosts_are_handed_out_as_copies(mocker, mock_provider_service, props): + """These are built once and never replaced, so marking a host handed out + here would mark it for every later caller.""" + provider = create_provider(mock_provider_service, props) + provider._initialize() + + first = provider._get_topology(None).hosts + second = provider._get_topology(None).hosts + + assert first[0] is not second[0] + assert first[0] is not provider._initial_hosts[0] + first[0].set_availability(HostAvailability.UNAVAILABLE) + assert provider._initial_hosts[0].get_raw_availability() == HostAvailability.AVAILABLE + + def test_host_pattern_setting(mock_provider_service, props): props = Properties({"host": "127:0:0:1", "port": 5432, WrapperProperties.CLUSTER_INSTANCE_HOST_PATTERN.name: "?.custom-domain.com"}) diff --git a/tests/unit/test_multithreaded_monitor_service.py b/tests/unit/test_multithreaded_monitor_service.py index 3c07731d1..eb6134794 100644 --- a/tests/unit/test_multithreaded_monitor_service.py +++ b/tests/unit/test_multithreaded_monitor_service.py @@ -15,7 +15,7 @@ from concurrent.futures import ThreadPoolExecutor from threading import Barrier from time import sleep -from typing import FrozenSet, List +from typing import List import psycopg import pytest @@ -92,19 +92,19 @@ def test_start_monitoring__connections_to_different_hosts( start_monitoring): num_conns = 10 - host_alias_list = generate_host_aliases(num_conns, True) + hosts = generate_hosts(num_conns, True) services = generate_services(num_conns) mocker.patch( "aws_advanced_python_wrapper.host_monitoring_plugin.Monitor.__init__", return_value=None) mocker.patch.object( - services[0]._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + services[0]._monitor_service, 'run_if_absent', return_value=mock_monitor) # Patch all services to use the same mock for svc in services: svc._monitor_service = services[0]._monitor_service - contexts = start_monitoring(num_conns, services, host_alias_list) + contexts = start_monitoring(num_conns, services, hosts) expected_start_monitoring_calls = [mocker.call(context) for context in contexts] mock_monitor.start_monitoring.assert_has_calls(expected_start_monitoring_calls, True) @@ -119,18 +119,18 @@ def test_start_monitoring__connections_to_same_host( start_monitoring): num_conns = 10 - host_alias_list = generate_host_aliases(num_conns, False) + hosts = generate_hosts(num_conns, False) services = generate_services(num_conns) mocker.patch( "aws_advanced_python_wrapper.host_monitoring_plugin.Monitor.__init__", return_value=None) mocker.patch.object( - services[0]._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + services[0]._monitor_service, 'run_if_absent', return_value=mock_monitor) for svc in services: svc._monitor_service = services[0]._monitor_service - contexts = start_monitoring(num_conns, services, host_alias_list) + contexts = start_monitoring(num_conns, services, hosts) expected_start_monitoring_calls = [mocker.call(context) for context in contexts] mock_monitor.start_monitoring.assert_has_calls(expected_start_monitoring_calls, True) @@ -173,11 +173,10 @@ def test_stop_monitoring__connections_to_same_host( mock_monitor.stop_monitoring.assert_has_calls(expected_stop_monitoring_calls, True) -def generate_host_aliases(num_aliases: int, generate_unique_aliases: bool) -> List[FrozenSet[str]]: - if generate_unique_aliases: - return [frozenset({f"host-{i}"}) for i in range(num_aliases)] - else: - return [frozenset({"single-host"}) for _ in range(num_aliases)] +def generate_hosts(num_hosts: int, generate_unique_hosts: bool) -> List[HostInfo]: + if generate_unique_hosts: + return [HostInfo(f"host-{i}") for i in range(num_hosts)] + return [HostInfo("single-host") for _ in range(num_hosts)] @pytest.fixture @@ -211,7 +210,7 @@ def start_monitoring(counter, concurrent_counter, start_monitoring_thread): def _start_monitoring( num_threads: int, services: List[HostMonitorService], - host_aliases_list: List[FrozenSet[str]]) -> List[MonitoringContext]: + hosts: List[HostInfo]) -> List[MonitoringContext]: barrier = Barrier(num_threads) futures = [] with ThreadPoolExecutor(num_threads) as executor: @@ -222,7 +221,7 @@ def _start_monitoring( counter, concurrent_counter, services[i], - host_aliases_list[i]) + hosts[i]) futures.append(future) return [future.result() for future in futures] return _start_monitoring @@ -231,14 +230,13 @@ def _start_monitoring( @pytest.fixture def start_monitoring_thread( mock_conn, - host_info, props): def _start_monitoring_thread( barrier: Barrier, counter: AtomicInt, concurrent_counter: AtomicInt, service: HostMonitorService, - host_aliases: FrozenSet[str]) -> MonitoringContext: + host_info: HostInfo) -> MonitoringContext: barrier.wait() val = counter.get_and_increment() @@ -247,7 +245,6 @@ def _start_monitoring_thread( context = service.start_monitoring( mock_conn, - host_aliases, host_info, Properties(), 10, diff --git a/tests/unit/test_plugin_service.py b/tests/unit/test_plugin_service.py index 259bc93b3..fb2efa5e7 100644 --- a/tests/unit/test_plugin_service.py +++ b/tests/unit/test_plugin_service.py @@ -13,6 +13,7 @@ # limitations under the License.s from concurrent.futures import TimeoutError +from datetime import datetime, timedelta from unittest.mock import MagicMock, patch import pytest @@ -22,9 +23,12 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, QueryTimeoutError, UnsupportedOperationError) +from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.plugin_service import PluginServiceImpl +from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.utils import Utils def test_get_host_role_unknown_dialect(mocker): @@ -194,7 +198,9 @@ def decorator(func): plugin_service.get_host_role(mock_conn) -def test_identify_connection_error_no_result(mocker): +def test_identify_connection_returns_none_when_the_host_id_query_reports_nothing(mocker): + """Unidentifiable is not a failure: the connect hooks that call this would + otherwise turn an unreported host id into a failed connect.""" mock_conn = MagicMock() mock_cursor = MagicMock() mock_cursor.fetchone.return_value = None @@ -225,8 +231,7 @@ def decorator(func): mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) - with pytest.raises(AwsWrapperError): - plugin_service.identify_connection(mock_conn) + assert plugin_service.identify_connection(mock_conn) is None def test_identify_connection_timeout(mocker): @@ -376,13 +381,15 @@ def decorator(func): def test_identify_connection_host_in_topology_multiaz(mocker): mock_conn = MagicMock() mock_cursor = MagicMock() - # Multi-AZ returns different values: (instanceId, instanceName) + # Multi-AZ returns different values: (instanceId, instanceName). The + # topology carries the id, which is what the first clause matches on. mock_cursor.fetchone.return_value = ("db-WQFQKBTL2LQUPIEFIFBGENS4ZQ", "instance-1") mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) mock_cursor.__exit__ = MagicMock(return_value=False) mock_conn.cursor.return_value = mock_cursor - expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, host_id="instance-1") + expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, + host_id="db-WQFQKBTL2LQUPIEFIFBGENS4ZQ") mock_container = mocker.MagicMock() mock_container.plugin_manager = mocker.MagicMock() @@ -411,7 +418,239 @@ def decorator(func): host_info = plugin_service.identify_connection(mock_conn) assert host_info is not None assert "instance-1.xyz.us-east-2.rds.amazonaws.com" == host_info.host - assert "instance-1" == host_info.host_id + assert "db-WQFQKBTL2LQUPIEFIFBGENS4ZQ" == host_info.host_id + + +def test_identify_connection_matches_on_the_instance_name_column(mocker): + """The second column is matched against the host, not the host id. + + A topology whose host ids come from somewhere other than host_id_query + is still identifiable as long as the name column names the host. + """ + mock_conn = MagicMock() + mock_cursor = MagicMock() + mock_cursor.fetchone.return_value = ( + "unmatched-id", "instance-1.xyz.us-east-2.rds.amazonaws.com") + mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) + mock_cursor.__exit__ = MagicMock(return_value=False) + mock_conn.cursor.return_value = mock_cursor + + expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, + host_id="db-SOMETHINGELSE") + + mock_container = mocker.MagicMock() + mock_container.plugin_manager = mocker.MagicMock() + mock_host_list_provider = mocker.MagicMock() + mock_host_list_provider.refresh.return_value = (expected_host,) + + plugin_service = PluginServiceImpl( + mock_container, + Properties({"host": "test.com", "port": 5432}), + lambda: None, + mocker.MagicMock(), + mocker.MagicMock() + ) + plugin_service._database_dialect = MultiAzClusterPgDialect() + plugin_service._current_connection = mock_conn + plugin_service._host_list_provider = mock_host_list_provider + + def mock_preserve(thread_pool, timeout, driver_dialect, conn): + def decorator(func): + return func + return decorator + + mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) + + assert plugin_service.identify_connection(mock_conn) is expected_host + + +def _service_with_hosts(mocker, hosts, props=None): + container = mocker.MagicMock() + container.plugin_manager = mocker.MagicMock() + service = PluginServiceImpl( + container, + Properties(props or {"host": "test.com"}), + lambda: None, + mocker.MagicMock(), + mocker.MagicMock()) + service._all_hosts = tuple(hosts) + return service, container + + +def test_identify_connection_returns_none_when_the_host_id_query_errors(mocker): + """The connect hooks that identify a host call this. A host the database + declines to name must not fail their connect.""" + mock_conn = MagicMock() + mock_conn.cursor.side_effect = Exception("relation does not exist") + + service, _ = _service_with_hosts(mocker, ()) + service._database_dialect = AuroraPgDialect() + service._current_connection = mock_conn + service._host_list_provider = mocker.MagicMock() + + def mock_preserve(thread_pool, timeout, driver_dialect, conn): + def decorator(func): + return func + return decorator + + mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) + + assert service.identify_connection(mock_conn) is None + + +def test_set_availability_marks_the_host_and_caches_it(mocker): + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + service, container = _service_with_hosts(mocker, (host,)) + + service.set_availability(host, HostAvailability.UNAVAILABLE) + + assert host.get_raw_availability() == HostAvailability.UNAVAILABLE + assert service.get_availability(host.url) == HostAvailability.UNAVAILABLE + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} + + +def test_set_availability_matches_by_host_id_and_is_case_insensitive_on_the_name(mocker): + by_id = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + by_name = HostInfo("Instance-2.XYZ.us-east-2.rds.amazonaws.com", 5432) + untouched = HostInfo("instance-3.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-3") + service, _ = _service_with_hosts(mocker, (by_id, by_name, untouched)) + + service.set_availability(HostInfo("other.example", 5432, host_id="instance-1"), + HostAvailability.UNAVAILABLE) + service.set_availability(HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432), + HostAvailability.UNAVAILABLE) + + assert by_id.get_raw_availability() == HostAvailability.UNAVAILABLE + assert by_name.get_raw_availability() == HostAvailability.UNAVAILABLE + # Bound the other side: a match is not a licence to mark the whole list. + assert untouched.get_raw_availability() == HostAvailability.AVAILABLE + + +def test_set_availability_reports_a_host_coming_back_up(mocker): + """Inverting the event ternary would otherwise pass the suite.""" + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, + availability=HostAvailability.UNAVAILABLE) + service, container = _service_with_hosts(mocker, (host,)) + + service.set_availability(host, HostAvailability.AVAILABLE) + + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_UP, HostEvent.HOST_CHANGED}} + + +def test_set_availability_reports_every_matched_host(mocker): + """One entry per matched host, so a subscriber that stops at the first + one drops the rest.""" + first = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="shared") + second = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="shared") + service, container = _service_with_hosts(mocker, (first, second)) + + service.set_availability(HostInfo("other.example", 5432, host_id="shared"), + HostAvailability.UNAVAILABLE) + + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert set(changes) == {first.url, second.url} + + +def test_set_availability_reads_availability_through_the_backoff_strategy(mocker): + """A host whose backoff window has elapsed reads as available again, so + marking it down is a change the plugins have to hear about.""" + from aws_advanced_python_wrapper.host_availability import \ + ExponentialBackoffHostAvailabilityStrategy + + props = Properties({"host": "test.com", + "host_availability_strategy_initial_backoff_time": "1", + "host_availability_strategy_max_retries": "5"}) + strategy = ExponentialBackoffHostAvailabilityStrategy(props) + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, + availability=HostAvailability.UNAVAILABLE, + host_availability_strategy=strategy) + # Back-date the last change so the retry window has elapsed. + strategy._not_available_count = 1 + strategy._last_changed = datetime.now() - timedelta(seconds=30) + assert host.get_availability() == HostAvailability.AVAILABLE + + service, container = _service_with_hosts(mocker, (host,)) + service.set_availability(host, HostAvailability.UNAVAILABLE) + + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} + + +def test_set_availability_does_not_notify_when_nothing_changed(mocker): + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service, container = _service_with_hosts(mocker, (host,)) + + service.set_availability(host, HostAvailability.AVAILABLE) + + # The host did match, so this is "matched but unchanged" rather than the + # early return for an unmatched host. + assert service.get_availability(host.url) == HostAvailability.AVAILABLE + container.plugin_manager.notify_host_list_changed.assert_not_called() + + +def test_set_availability_ignores_a_host_outside_the_host_list(mocker): + in_list = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service, container = _service_with_hosts(mocker, (in_list,)) + stranger = HostInfo("stranger.example", 5432) + + service.set_availability(stranger, HostAvailability.UNAVAILABLE) + + assert service.get_availability(stranger.url) is None + # Bound both sides: neither the argument nor the host list is touched. + assert stranger.get_raw_availability() == HostAvailability.AVAILABLE + assert in_list.get_raw_availability() == HostAvailability.AVAILABLE + container.plugin_manager.notify_host_list_changed.assert_not_called() + + +def test_connect_clears_a_routed_host_left_by_an_earlier_connect(mocker): + """The routed host belongs to one connect. A value left behind would be + read by the next one, which keys the connection tracker and picks the + monitoring host off the previous connect's instance.""" + service, container = _service_with_hosts(mocker, ()) + stale = HostInfo("reader-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service.routed_host_info = stale + observed = {} + + def _record(*args, **kwargs): + observed["routed"] = service.routed_host_info + return MagicMock() + + container.plugin_manager.connect = _record + service.connect(HostInfo("reader-2.xyz.us-east-2.rds.amazonaws.com", 5432), Properties()) + + assert observed["routed"] is None + + +def test_take_routed_host_info_returns_it_once(mocker): + service, _ = _service_with_hosts(mocker, ()) + routed = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service.routed_host_info = routed + + assert service.take_routed_host_info() is routed + assert service.take_routed_host_info() is None + + +def test_find_host_does_not_match_an_instance_name_against_a_host_id(): + """A name-against-id clause picks the decoy that happens to carry the name + as its id. On Multi-AZ the name and the id come from different columns, so + such a clause would match the wrong row rather than be harmless.""" + decoy = HostInfo("decoy.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + wanted = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="db-AAA") + + found = Utils.find_host((decoy, wanted), "db-AAA", "instance-1.xyz.us-east-2.rds.amazonaws.com") + + assert found is wanted + + +def test_find_host_matches_on_either_column(): + aurora = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + assert Utils.find_host((aurora,), "instance-1", "instance-1") is aurora + + by_name = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="db-BBB") + assert Utils.find_host( + (by_name,), "unmatched", "instance-2.xyz.us-east-2.rds.amazonaws.com") is by_name def test_could_not_determine_current_host_raises_resolved_message(): diff --git a/tests/unit/test_reader_failover_handler.py b/tests/unit/test_reader_failover_handler.py index f4ccc537b..58a056a8d 100644 --- a/tests/unit/test_reader_failover_handler.py +++ b/tests/unit/test_reader_failover_handler.py @@ -75,9 +75,9 @@ def test_failover(plugin_service_mock, connection_mock, default_properties, defa props = default_properties current_host = hosts[2] success_host = hosts[4] - expected = [call(x.all_aliases, HostAvailability.UNAVAILABLE) + expected = [call(x, HostAvailability.UNAVAILABLE) if x != success_host - else call(x.all_aliases, HostAvailability.AVAILABLE) + else call(x, HostAvailability.AVAILABLE) for x in hosts] exception = Exception("Test Exception") @@ -170,7 +170,7 @@ def force_connect_side_effect(host_info, _) -> Connection: assert result.connection == connection_mock assert result.new_host == fast_host - plugin_service_mock.set_availability.assert_any_call(fast_host.all_aliases, HostAvailability.AVAILABLE) + plugin_service_mock.set_availability.assert_any_call(fast_host, HostAvailability.AVAILABLE) def test_get_reader_connection_failure(plugin_service_mock, connection_mock, default_properties, default_hosts): diff --git a/tests/unit/test_writer_failover_handler.py b/tests/unit/test_writer_failover_handler.py index 4eaeccf2f..7a64f6d89 100644 --- a/tests/unit/test_writer_failover_handler.py +++ b/tests/unit/test_writer_failover_handler.py @@ -105,14 +105,6 @@ def new_topology(new_writer_host, reader_a, reader_b): return tuple([new_writer_host, reader_a, reader_b]) -@pytest.fixture(autouse=True) -def setup(writer, new_writer_host, reader_a, reader_b): - writer.add_alias("writer-host") - new_writer_host.add_alias("new-writer-host") - reader_a.add_alias("reader-a") - reader_b.add_alias("reader-b") - - def test_reconnect_to_writer_task_b_reader_exception( writer_connection_mock, plugin_service_mock, reader_failover_mock, default_properties, writer, topology): exception = Exception("Test Exception") @@ -142,8 +134,8 @@ def force_connect_side_effect(host_info, _) -> Connection: assert not result.is_new_host assert result.new_connection is writer_connection_mock - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(writer.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(writer, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -153,8 +145,8 @@ def test_reconnect_to_writer_slow_task_b( reader_a_connection_mock, default_properties, new_writer_host, writer, reader_a, reader_b, topology, new_topology): exception = Exception("Test Exception") - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(writer.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(writer, HostAvailability.AVAILABLE)] mock_hosts_property = mocker.PropertyMock(side_effect=chain((topology,), cycle((new_topology,)))) type(plugin_service_mock).all_hosts = mock_hosts_property @@ -227,8 +219,8 @@ def get_reader_connection_side_effect(_): assert not result.is_new_host assert result.new_connection is writer_connection_mock - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(writer.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(writer, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -274,8 +266,8 @@ def get_reader_connection_side_effect(_): assert result.is_new_host assert result.new_connection is new_writer_connection_mock - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(new_writer_host.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(new_writer_host, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -325,8 +317,8 @@ def get_reader_connection_side_effect(_): assert len(result.topology) == 4 assert "new-writer-host" == result.topology[0].host - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(new_writer_host.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(new_writer_host, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected, any_order=True) @@ -377,7 +369,7 @@ def get_reader_connection_side_effect(_): assert not result.is_connected assert not result.is_new_host - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -420,7 +412,7 @@ def get_reader_connection_side_effect(_): assert not result.is_connected assert not result.is_new_host - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(new_writer_host.as_aliases(), HostAvailability.UNAVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(new_writer_host, HostAvailability.UNAVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected, any_order=True) From bc9610d6bab119dd2be8f1fc7f01b8520c5d139f Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Wed, 21 Oct 2026 16:06:04 -0700 Subject: [PATCH 4/4] chore: bump dependencies --- .../host_monitoring_plugin.py | 3 +- poetry.lock | 129 ++++++++++++++---- pyproject.toml | 6 +- .../scripts/debug_integration_pycharm.py | 2 +- tests/unit/test_aurora_connection_tracker.py | 2 +- tests/unit/test_monitor_service.py | 2 +- 6 files changed, 112 insertions(+), 32 deletions(-) diff --git a/aws_advanced_python_wrapper/host_monitoring_plugin.py b/aws_advanced_python_wrapper/host_monitoring_plugin.py index 006c903ea..c3c7aabc3 100644 --- a/aws_advanced_python_wrapper/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/host_monitoring_plugin.py @@ -22,14 +22,13 @@ from aws_advanced_python_wrapper.pep249 import Connection from aws_advanced_python_wrapper.plugin_service import PluginService +from _weakref import ReferenceType, ref from dataclasses import dataclass from queue import Queue from threading import Event, Lock, Thread from time import perf_counter_ns from typing import Any, Callable, Dict, Optional, Set -from _weakref import ReferenceType, ref - from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.pep249_methods import DbApiMethod diff --git a/poetry.lock b/poetry.lock index 20bb6e276..86966df2f 100644 --- a/poetry.lock +++ b/poetry.lock @@ -1,4 +1,4 @@ -# This file is automatically @generated by Poetry 2.5.1 and should not be changed by hand. +# This file is automatically @generated by Poetry 2.3.3 and should not be changed by hand. [[package]] name = "aiohappyeyeballs" @@ -796,7 +796,7 @@ files = [ [package.dependencies] jmespath = ">=0.7.1,<2.0.0" python-dateutil = ">=2.1,<3.0.0" -urllib3 = ">=1.25.4,!=2.2.0,<3" +urllib3 = ">=1.25.4,<2.2.0 || >2.2.0,<3" [package.extras] crt = ["awscrt (==0.36.0)"] @@ -1153,38 +1153,81 @@ bcrypt = ["bcrypt"] [[package]] name = "django-stubs" -version = "5.2.9" +version = "6.0.9" description = "Mypy stubs for Django" optional = false python-versions = ">=3.10" groups = ["dev"] +markers = "python_version < \"3.13\"" files = [ - {file = "django_stubs-5.2.9-py3-none-any.whl", hash = "sha256:2317a7130afdaa76f6ff7f623650d7f3bf1b6c86a60f95840e14e6ec6de1a7cd"}, - {file = "django_stubs-5.2.9.tar.gz", hash = "sha256:c192257120b08785cfe6f2f1c91f1797aceae8e9daa689c336e52c91e8f6a493"}, + {file = "django_stubs-6.0.9-py3-none-any.whl", hash = "sha256:dbee54721197b453708b39bb6b5988b6543eddf3e5073b8772c13bf4652af17d"}, + {file = "django_stubs-6.0.9.tar.gz", hash = "sha256:ef9928e900a9d226162b579b50c035d08755f6279fd47de9f427de4123c23623"}, ] [package.dependencies] django = "*" -django-stubs-ext = ">=5.2.9" +django-stubs-ext = ">=6.0.2" tomli = {version = "*", markers = "python_full_version < \"3.11.0\""} types-pyyaml = "*" typing-extensions = ">=4.11.0" [package.extras] -compatible-mypy = ["mypy (>=1.13,<1.20)"] +compatible-mypy = ["mypy (>=1.13,<2.4)"] +oracle = ["oracledb"] +redis = ["redis", "types-redis"] + +[[package]] +name = "django-stubs" +version = "6.1.2" +description = "Mypy stubs for Django" +optional = false +python-versions = ">=3.11" +groups = ["dev"] +markers = "python_version >= \"3.13\"" +files = [ + {file = "django_stubs-6.1.2-py3-none-any.whl", hash = "sha256:ffb6e74f54b8c1f9b2f3bc4852c5abbaa2324b2a7cb1c51854c5f95abe67165c"}, + {file = "django_stubs-6.1.2.tar.gz", hash = "sha256:d62b15fa5cbae79b1922d015e1454d299959d230221dadb23f65c749480b97ec"}, +] + +[package.dependencies] +django = "*" +django-stubs-ext = ">=6.0.2" +types-pyyaml = "*" +typing-extensions = ">=4.11.0" + +[package.extras] +compatible-mypy = ["mypy (>=1.13,<2.5)"] oracle = ["oracledb"] redis = ["redis", "types-redis"] [[package]] name = "django-stubs-ext" -version = "5.2.9" +version = "6.0.9" description = "Monkey-patching and extensions for django-stubs" optional = false python-versions = ">=3.10" groups = ["dev"] +markers = "python_version < \"3.13\"" files = [ - {file = "django_stubs_ext-5.2.9-py3-none-any.whl", hash = "sha256:230c51575551b0165be40177f0f6805f1e3ebf799b835c85f5d64c371ca6cf71"}, - {file = "django_stubs_ext-5.2.9.tar.gz", hash = "sha256:6db4054d1580657b979b7d391474719f1a978773e66c7070a5e246cd445a25a9"}, + {file = "django_stubs_ext-6.0.9-py3-none-any.whl", hash = "sha256:267cb4d0bc87a6c2a0edd0f0dfa59696efd3d21a86b1d346b502fe13c6ea28ef"}, + {file = "django_stubs_ext-6.0.9.tar.gz", hash = "sha256:6777de6d0a059f55ea1d53839de84c2ae96eae131b75fd00c3ee8f6678d9f6d7"}, +] + +[package.dependencies] +django = "*" +typing-extensions = "*" + +[[package]] +name = "django-stubs-ext" +version = "6.1.2" +description = "Monkey-patching and extensions for django-stubs" +optional = false +python-versions = ">=3.11" +groups = ["dev"] +markers = "python_version >= \"3.13\"" +files = [ + {file = "django_stubs_ext-6.1.2-py3-none-any.whl", hash = "sha256:7334e687ab6dc78a6c3da90ab1ccb0e412efd827ea11de8d3f85adbad948abb1"}, + {file = "django_stubs_ext-6.1.2.tar.gz", hash = "sha256:2142da7fffbbe897ccecf9b4c97e09ea1a2e9291760b0a824b4c402b375ce6f9"}, ] [package.dependencies] @@ -1405,10 +1448,10 @@ files = [ ] [package.dependencies] -protobuf = ">=3.20.2,!=4.21.1,!=4.21.2,!=4.21.3,!=4.21.4,!=4.21.5,<6.0.0" +protobuf = ">=3.20.2,<4.21.1 || >4.21.1,<4.21.2 || >4.21.2,<4.21.3 || >4.21.3,<4.21.4 || >4.21.4,<4.21.5 || >4.21.5,<6.0.0.dev0" [package.extras] -grpc = ["grpcio (>=1.44.0,<2.0.0)"] +grpc = ["grpcio (>=1.44.0,<2.0.0.dev0)"] [[package]] name = "greenlet" @@ -1600,18 +1643,56 @@ files = [ [[package]] name = "isort" -version = "5.13.2" +version = "9.0.2" description = "A Python utility / library to sort Python imports." optional = false -python-versions = ">=3.8.0" +python-versions = ">=3.10.0" groups = ["dev"] files = [ - {file = "isort-5.13.2-py3-none-any.whl", hash = "sha256:8ca5e72a8d85860d5a3fa69b8745237f2939afe12dbf656afbcb47fe72d947a6"}, - {file = "isort-5.13.2.tar.gz", hash = "sha256:48fdfcb9face5d58a4f6dde2e72a1fb8dcaf8ab26f95ab49fab84c2ddefb0109"}, + {file = "isort-9.0.2-cp310-cp310-macosx_11_0_arm64.whl", hash = "sha256:b3e81cae981a52f94d5b31a474e1cbb033ea9cc850bc4c922117c0534a1864dd"}, + {file = "isort-9.0.2-cp310-cp310-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:3cd67d39c3501d7227e8b229476da1d8679c03e0af97bd295876cf7070e5b709"}, + {file = "isort-9.0.2-cp310-cp310-musllinux_1_2_x86_64.whl", hash = "sha256:288a320e6d52ba2d3447345390c8a8400591e4033ffbe4ce6bc3e50e5b4818e1"}, + {file = "isort-9.0.2-cp310-cp310-win_amd64.whl", hash = "sha256:67b12d9504e5bc6359bb3bb4493f36cf1093d15477c61c349f52f7d04209fb5d"}, + {file = "isort-9.0.2-cp311-cp311-macosx_11_0_arm64.whl", hash = "sha256:e4a54aed1bb731d7cf80ef5dfbae5b960f777cea70523b751ee6049bcb604371"}, + {file = "isort-9.0.2-cp311-cp311-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:b34a165cd4e25726930ed2eed8cf2fe46fb1a5ebacd9b28eaf566b343a6457ca"}, + {file = "isort-9.0.2-cp311-cp311-musllinux_1_2_x86_64.whl", hash = "sha256:5c929e8ec9d9fb83f034d5f50895503f40c624605f552b97ad090a37e62407ca"}, + {file = "isort-9.0.2-cp311-cp311-win_amd64.whl", hash = "sha256:5f448510ef0a92fa626a975759d76bdbe3b721c3d615da6d1010cc451de5610d"}, + {file = "isort-9.0.2-cp312-cp312-macosx_11_0_arm64.whl", hash = "sha256:a05dc63cb6ae2a8e62ec4184153f424b1650593e00a24e6138184c46193891e9"}, + {file = "isort-9.0.2-cp312-cp312-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:af8be0b5cac101202c8255360e5de832ebbb84b2e863dc0f65dbb1a3d63dd40a"}, + {file = "isort-9.0.2-cp312-cp312-musllinux_1_2_x86_64.whl", hash = "sha256:3fe693c1e56781de387a6c206306e9e5e560cfeb4acdfd85f0c46122afd48792"}, + {file = "isort-9.0.2-cp312-cp312-win_amd64.whl", hash = "sha256:f7a9efeb3689c7327a0d637eb4e12691e8d5ab1297caee997b144dc595ccb93f"}, + {file = "isort-9.0.2-cp313-cp313-macosx_11_0_arm64.whl", hash = "sha256:f65ff614632ddc3306c40f619717b3b3ca69938ffee21d97110056d52472c79a"}, + {file = "isort-9.0.2-cp313-cp313-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:e5f11c7ccd5f079ac0431fe52c7b38ea5d9f4e31a1889746de81dac0e7b0a766"}, + {file = "isort-9.0.2-cp313-cp313-musllinux_1_2_x86_64.whl", hash = "sha256:810561edf6f1f5f3600f02aa709603a4360d5290c5fff2ae4b370090dd1a5445"}, + {file = "isort-9.0.2-cp313-cp313-pyemscripten_2025_0_wasm32.whl", hash = "sha256:e2636222848a48cadbd712280058b5da19fa147c501132e04a486a5bddcc9e28"}, + {file = "isort-9.0.2-cp313-cp313-win_amd64.whl", hash = "sha256:71870ac3b1afdf3c259b8404c05076d3ab874122fec6f78339f1c92d2c29b012"}, + {file = "isort-9.0.2-cp314-cp314-macosx_11_0_arm64.whl", hash = "sha256:bd8c4fb9829a5e7117d9f71f540ff1e8caafb471e574012057ce6dc35fda2d7b"}, + {file = "isort-9.0.2-cp314-cp314-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:6eb3e714d64de6eba78ee29051f7fc80613c74e90c6f54f84082f59c429c0a0b"}, + {file = "isort-9.0.2-cp314-cp314-musllinux_1_2_x86_64.whl", hash = "sha256:bf3ef0a91974f29f406e25eef0e04781fd5c2254b8ab55e7655b20d8cd7c5514"}, + {file = "isort-9.0.2-cp314-cp314-pyemscripten_2026_0_wasm32.whl", hash = "sha256:cd1e0e5e61497e95a4e5be269088e6a1013f530aeccf6ebd6134f403285ecd63"}, + {file = "isort-9.0.2-cp314-cp314-win_amd64.whl", hash = "sha256:11da67a30f5a88383c71db075488ca3d081f427f53368f90bb1d74e958a9b040"}, + {file = "isort-9.0.2-cp314-cp314t-macosx_11_0_arm64.whl", hash = "sha256:f7c2fa33e1c9fbcf9fd639997e4550515c0b712b52ed70a059124a5247825480"}, + {file = "isort-9.0.2-cp314-cp314t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:85e859fd72e50c27306d05185f9472ed97fae9e1cce91c0e891260d16f2ecece"}, + {file = "isort-9.0.2-cp314-cp314t-musllinux_1_2_x86_64.whl", hash = "sha256:2a960e4252ac5b00f78adc0f731529e122657ee642e650896b36e1ff83028023"}, + {file = "isort-9.0.2-cp314-cp314t-win_amd64.whl", hash = "sha256:91b60ce3d96fcb0730d61fc5ab84ee5b56d676fbb92550f7ea333f58778f2f20"}, + {file = "isort-9.0.2-cp315-cp315-macosx_11_0_arm64.whl", hash = "sha256:aa810daf72ff5d8ade462b2190dad9c0e16d6d428a3f9aea210f14cca2487d58"}, + {file = "isort-9.0.2-cp315-cp315-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:8dde4e2d9cfb35390437353f0861ec41378f91ff958d8cd3051fb95cae59315a"}, + {file = "isort-9.0.2-cp315-cp315-musllinux_1_2_x86_64.whl", hash = "sha256:4315e23e701bb1fcdfd364da59da61d78c3332c554318b7eb635ea3924d24c5e"}, + {file = "isort-9.0.2-cp315-cp315-pyemscripten_2026_5_wasm32.whl", hash = "sha256:1c134ef9d94943eae14bf31c634db1904dd875e6e7280a60baee10ca06132db6"}, + {file = "isort-9.0.2-cp315-cp315-win_amd64.whl", hash = "sha256:d4da51a99dfd00e5c51e507ed91ebad6aafd44dc65135c17e2ef37355cd9fa98"}, + {file = "isort-9.0.2-cp315-cp315t-macosx_11_0_arm64.whl", hash = "sha256:16436aefeebe3aa2d5d7ae1ca895b2278f770fc4a41d95c22569a30f7413ec45"}, + {file = "isort-9.0.2-cp315-cp315t-manylinux2014_x86_64.manylinux_2_17_x86_64.manylinux_2_28_x86_64.whl", hash = "sha256:a36f30b6b85d9726f79c7623d35f3e966d5d7d9d0a005af91ba19988fccd038b"}, + {file = "isort-9.0.2-cp315-cp315t-musllinux_1_2_x86_64.whl", hash = "sha256:d03c68e9d0a83b51ed381d04b0919f2d918fb66c1ca1766761157ff44149366f"}, + {file = "isort-9.0.2-cp315-cp315t-win_amd64.whl", hash = "sha256:29669ea6c410528ffe3b632a41835757f08282257e4ddac892a5e6d01bd35201"}, + {file = "isort-9.0.2-py3-none-any.whl", hash = "sha256:6c29deeb39698a8717823b7f75b2ac58c5e8ab8dcf6cf31205a72a6617fb454e"}, + {file = "isort-9.0.2.tar.gz", hash = "sha256:d2298980ce44350f11d9d24c8150eaef1883431ec203dddbb4e9b5c3ceb54c70"}, ] +[package.dependencies] +mypy-extensions = ">=1.1.0" + [package.extras] -colors = ["colorama (>=0.4.6)"] +colors = ["colorama"] [[package]] name = "jinja2" @@ -2084,14 +2165,14 @@ reports = ["lxml"] [[package]] name = "mypy-extensions" -version = "1.0.0" +version = "1.1.0" description = "Type system extensions for programs checked with the mypy type checker." optional = false -python-versions = ">=3.5" +python-versions = ">=3.8" groups = ["dev"] files = [ - {file = "mypy_extensions-1.0.0-py3-none-any.whl", hash = "sha256:4392f6c0eb8a5668a69e23d168ffa70f0be9ccfd32b5cc2d26a34ae5b844552d"}, - {file = "mypy_extensions-1.0.0.tar.gz", hash = "sha256:75dbf8955dc00442a438fc4d0666508a9a97b6bd41aa2f0ffe9d2f2725af0782"}, + {file = "mypy_extensions-1.1.0-py3-none-any.whl", hash = "sha256:1be4cccdb0f2482337c4743e60421de3a356cd97508abadd57d47403e94f5505"}, + {file = "mypy_extensions-1.1.0.tar.gz", hash = "sha256:52e68efc3284861e772bbcd66823fde5ae21fd2fdb51c62a211403730b916558"}, ] [[package]] @@ -2631,13 +2712,13 @@ files = [ [[package]] name = "pydevd-pycharm" -version = "233.15619.17" +version = "263.7031.30" description = "PyCharm Debugger (used in PyCharm and PyDev)" optional = false python-versions = "*" groups = ["test"] files = [ - {file = "pydevd_pycharm-233.15619.17.tar.gz", hash = "sha256:eb92c77803279e45ae5a325e5c5777d0e745af651c84856cc3849d48ff188f17"}, + {file = "pydevd_pycharm-263.7031.30.tar.gz", hash = "sha256:132ab3c6476d37714b956ce91ef580ddee6343af36ddccde83c60ef9e33b4f6b"}, ] [[package]] @@ -3845,4 +3926,4 @@ propcache = ">=0.2.1" [metadata] lock-version = "2.1" python-versions = "^3.10.0" -content-hash = "3ebd54efc692385e98378ed04ad017cbfd925e894aaa7685dcd7cb3c1d243843" +content-hash = "ef1d83160e6b4eacd82c37e91fa1c66ca9c0a21ac85b476bfbf0972c5d9791c5" diff --git a/pyproject.toml b/pyproject.toml index 4d8c7cb52..4ded4d606 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -51,14 +51,14 @@ requests = "^2.33.1" mypy = "^1.20.2" flake8 = ">=7.3.0,<8" flake8-type-checking = ">=3.2.0,<4.0" -isort = "^5.13.2" +isort = "^9.0.2" pep8-naming = ">=0.15.1,<0.16.0" SQLAlchemy = "^2.0.49" psycopg = "^3.3.3" psycopg-binary = "^3.3.3" mysql-connector-python = "^9.7.0" django = "^5.2.13" -django-stubs = "^5.2.9" +django-stubs = "^6.0.1" aiomysql = ">=0.2" aiohttp = ">=3" boto3-stubs = "^1.43.0" @@ -69,7 +69,7 @@ boto3 = "^1.42.95" types-boto3 = "^1.42.95" coverage = "^7.13.5" debugpy = "^1.8.20" -pydevd-pycharm = "^233.15619.17" +pydevd-pycharm = "^263.7031.30" pytest = ">=7.4.4,<10.0.0" pytest-mock = "^3.15.1" pytest-html = "^4.2.0" diff --git a/tests/integration/container/scripts/debug_integration_pycharm.py b/tests/integration/container/scripts/debug_integration_pycharm.py index 7a930f071..6241b47ca 100644 --- a/tests/integration/container/scripts/debug_integration_pycharm.py +++ b/tests/integration/container/scripts/debug_integration_pycharm.py @@ -17,7 +17,7 @@ import pydevd_pycharm import pytest -pydevd_pycharm.settrace('host.docker.internal', port=5005, stdoutToServer=True, stderrToServer=True) +pydevd_pycharm.settrace('host.docker.internal', port=5005, stdout_to_server=True, stderr_to_server=True) if __name__ == "__main__": test_filter = sys.argv[1] diff --git a/tests/unit/test_aurora_connection_tracker.py b/tests/unit/test_aurora_connection_tracker.py index daec03efb..6c36d3114 100644 --- a/tests/unit/test_aurora_connection_tracker.py +++ b/tests/unit/test_aurora_connection_tracker.py @@ -14,10 +14,10 @@ from __future__ import annotations +from _weakrefset import WeakSet from typing import TYPE_CHECKING import pytest -from _weakrefset import WeakSet from sqlalchemy.pool import QueuePool from aws_advanced_python_wrapper.errors import FailoverError diff --git a/tests/unit/test_monitor_service.py b/tests/unit/test_monitor_service.py index d2ae4392e..da5235a02 100644 --- a/tests/unit/test_monitor_service.py +++ b/tests/unit/test_monitor_service.py @@ -12,11 +12,11 @@ # See the License for the specific language governing permissions and # limitations under the License. +from _weakref import ref from unittest.mock import MagicMock import psycopg import pytest -from _weakref import ref from aws_advanced_python_wrapper import release_resources from aws_advanced_python_wrapper.host_monitoring_plugin import \