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 d71df4293..10dc435e5 100644 --- a/aws_advanced_python_wrapper/aio/host_list_provider.py +++ b/aws_advanced_python_wrapper/aio/host_list_provider.py @@ -37,12 +37,20 @@ 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 copy import copy +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.errors import AwsWrapperError 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 @@ -52,6 +60,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 +68,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.""" @@ -179,29 +171,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, @@ -229,26 +214,43 @@ def __init__( default_port: int = 5432, monitor_connection_factory: Optional[ Callable[[], Awaitable[Any]]] = None, + topology_utils: Optional[AsyncTopologyUtils] = None, provider_service: Optional[AsyncHostListProviderService] = None) -> None: self._provider_service = provider_service 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 @@ -268,18 +270,17 @@ def _seed_topology(self) -> Topology: """The host from the connection properties, reported until the dialect is confirmed. - Built fresh on each call rather than held as one object: the default - availability strategy never expires a mark, so a shared seed host - would let a single failed connect pin it UNAVAILABLE for the life of - the process, with nothing to clear it. + Taken from the topology utils rather than rebuilt here, so it carries + the cluster's availability strategy and the same port resolution every + topology host gets. Copied on each call because the default + availability strategy never expires a mark: handing out the one object + would let a single failed connect pin the seed host UNAVAILABLE for + the life of the process, with nothing to clear it. """ - if self._topology_cache: - return self._topology_cache - try: - port = int(self._props["port"]) - except (KeyError, TypeError, ValueError): - port = self._default_port - return (HostInfo(host=str(self._props.get("host", "")), port=port),) + stored = self._get_stored_topology() + if stored: + return stored + return (copy(self._topology_utils.initial_host_info),) def set_probe_host(self, probe_host: Callable[..., Any]) -> None: """Arm panic-mode writer discovery on the (future) topology monitor. @@ -293,33 +294,49 @@ def set_probe_host(self, probe_host: Callable[..., Any]) -> None: @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: @@ -340,9 +357,7 @@ async def force_refresh(self, connection: Optional[Any] = None) -> Topology: return self._seed_topology() 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() @@ -354,25 +369,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, @@ -398,40 +396,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 @@ -443,250 +464,44 @@ 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 + + # 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: + 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 = _unregister + register_shutdown_hook(_close_and_unregister) 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) - - async def _run_topology_query(self, connection: Any) -> List[tuple]: - """Execute the topology query and return its rows. - - 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 + """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): @@ -740,137 +555,28 @@ 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), provider_service=provider_service, ) - 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__( @@ -893,94 +599,13 @@ 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), provider_service=provider_service, ) - 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) def build_monitor_connection_factory( diff --git a/aws_advanced_python_wrapper/aio/plugin_service.py b/aws_advanced_python_wrapper/aio/plugin_service.py index ad64c6291..bc6522d51 100644 --- a/aws_advanced_python_wrapper/aio/plugin_service.py +++ b/aws_advanced_python_wrapper/aio/plugin_service.py @@ -716,6 +716,10 @@ async def update_database_dialect(self, connection: Any) -> None: # driver dialect, provider service, monitor factory) comes from this # plugin service and is identical either way. # + # They live on the provider's topology utils, which is where the + # dialect's SQL and port landed; only the static provider has no utils + # at all. + # # Kept in step with the suppliers by # test_provider_identity_covers_every_dialect_supplied_argument, which # fails if a supplier gains an argument this list does not name. @@ -732,11 +736,12 @@ def _provider_identity(provider: Any) -> tuple: """What makes a provider the right one for a dialect. ``getattr`` with a default rather than direct access: the static - (no-topology) provider carries no topology query or port, and only - the Multi-AZ provider carries the writer/host-id queries. + (no-topology) provider has no topology utils, and only the Multi-AZ + utils carry the writer/host-id queries. """ + utils = getattr(provider, "_topology_utils", None) return (type(provider),) + tuple( - getattr(provider, attr, None) + getattr(utils, attr, None) for attr in AsyncPluginServiceImpl._PROVIDER_DIALECT_ATTRS) async def _update_host_list_provider(self, connection: Any) -> None: 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 b125a0664..ae3df67ab 100644 --- a/aws_advanced_python_wrapper/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/cluster_topology_monitor.py @@ -217,7 +217,10 @@ 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) + # 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: return () return hosts 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 295de3ca9..3982da77a 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 @@ -29,12 +29,17 @@ AdfsCredentialsProviderFactory.FailedLogin=[AdfsCredentialsProviderFactory] Fail AdfsCredentialsProviderFactory.SignOnPagePostActionUrl=[AdfsCredentialsProviderFactory] ADFS SignOn Action URL: '{}' 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.DatabaseDialectConfirmed=[AsyncPluginService] Database dialect confirmed: {}. AsyncPluginService.DatabaseDialectUnconfirmed=[AsyncPluginService] Database dialect probe did not complete, so the dialect stays an unconfirmed guess: {}. Topology queries are deferred and the next connect will retry the probe. AsyncPluginService.DatabaseDialectUpdated=[AsyncPluginService] Database dialect updated: {} -> {}. Rebuilding the host list provider for the new dialect. AsyncPluginService.HostListProviderNotSet=[AsyncPluginService] Host list provider is not set. Ensure AsyncAwsWrapperConnection.connect has populated it before calling refresh. AsyncPluginService.HostListProviderReplaced=[AsyncPluginService] Host list provider replaced for dialect {}: {} -> {}. AsyncPluginService.HostListProviderUnchanged=[AsyncPluginService] Dialect {} supplies the host list provider already in use ({}), so it was kept along with its topology monitor and cached topology. +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: {} AwsSecretsManagerPlugin.ConnectException=[AwsSecretsManagerPlugin] Error occurred while opening a connection: {} 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/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/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 5bcc641a6..e15703d00 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,12 +335,12 @@ 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 ----------------------------- # @@ -328,48 +352,52 @@ async def _body() -> None: 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()) @@ -399,7 +427,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 @@ -430,42 +458,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()) @@ -473,16 +505,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()) @@ -490,9 +524,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, ) @@ -500,7 +536,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()) @@ -508,9 +544,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, ) @@ -518,7 +556,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()) @@ -528,20 +566,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, @@ -551,23 +589,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, @@ -577,24 +615,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, @@ -605,7 +643,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 @@ -621,14 +659,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, @@ -638,7 +676,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()) @@ -648,7 +686,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, ) @@ -657,14 +697,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, @@ -678,7 +718,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()) @@ -688,17 +728,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, ) @@ -710,19 +750,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, ) @@ -739,7 +779,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(): @@ -747,11 +787,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, ) @@ -766,10 +808,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, ) @@ -777,7 +819,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) @@ -789,14 +831,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, ) @@ -813,7 +855,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 -------------------------------------- @@ -821,12 +863,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, ) @@ -835,7 +877,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 @@ -843,8 +885,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) @@ -855,10 +895,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, @@ -868,7 +910,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 @@ -879,8 +921,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) @@ -891,10 +931,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, @@ -910,7 +952,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()) @@ -920,14 +962,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()), @@ -955,8 +997,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] @@ -966,10 +1006,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, @@ -979,7 +1021,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) @@ -988,17 +1030,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, @@ -1009,7 +1051,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 @@ -1017,8 +1059,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) @@ -1033,10 +1073,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, @@ -1049,7 +1091,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). @@ -1058,8 +1100,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) @@ -1075,10 +1115,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, @@ -1093,7 +1135,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). @@ -1102,8 +1144,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") @@ -1118,10 +1158,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, @@ -1132,7 +1174,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()) @@ -1150,7 +1192,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() @@ -1188,8 +1229,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() @@ -1204,17 +1243,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, @@ -1229,7 +1268,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() @@ -1241,8 +1280,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) @@ -1251,12 +1288,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, @@ -1266,10 +1304,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()) @@ -1282,8 +1320,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) @@ -1291,15 +1327,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, @@ -1312,9 +1349,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()) @@ -1324,14 +1361,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, ) @@ -1356,8 +1393,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) @@ -1371,12 +1406,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, @@ -1389,7 +1425,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_autodetect.py b/tests/unit/test_aio_host_list_provider_autodetect.py index 79663d74c..9d5aaf094 100644 --- a/tests/unit/test_aio_host_list_provider_autodetect.py +++ b/tests/unit/test_aio_host_list_provider_autodetect.py @@ -34,6 +34,8 @@ from aws_advanced_python_wrapper.aio.host_list_provider import ( AsyncAuroraHostListProvider, AsyncGlobalAuroraHostListProvider, AsyncMultiAzHostListProvider, AsyncStaticHostListProvider) +from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncMultiAzTopologyUtils from aws_advanced_python_wrapper.database_dialect import ( AuroraMysqlDialect, AuroraPgDialect, GlobalAuroraMysqlDialect, GlobalAuroraPgDialect, MultiAzClusterMysqlDialect, MultiAzClusterPgDialect, @@ -97,8 +99,8 @@ def test_no_topology_dialects_return_static(dialect) -> None: def test_aurora_pg_dialect_selects_aurora_provider() -> None: provider = _build(AuroraPgDialect()) assert type(provider) is AsyncAuroraHostListProvider - assert provider._topology_query == AuroraPgDialect().topology_query - assert provider._default_port == PG_PORT + assert provider._topology_utils._topology_query == AuroraPgDialect().topology_query + assert provider._topology_utils._default_port == PG_PORT def test_aurora_mysql_dialect_selects_aurora_provider_with_mysql_sql() -> None: @@ -107,8 +109,8 @@ def test_aurora_mysql_dialect_selects_aurora_provider_with_mysql_sql() -> None: # port 5432, so discovery returned nothing until a later reconfigure. provider = _build(AuroraMysqlDialect(), AsyncAiomysqlDriverDialect()) assert type(provider) is AsyncAuroraHostListProvider - assert provider._topology_query == AuroraMysqlDialect().topology_query - assert provider._default_port == MYSQL_PORT + assert provider._topology_utils._topology_query == AuroraMysqlDialect().topology_query + assert provider._topology_utils._default_port == MYSQL_PORT def test_global_aurora_pg_dialect_selects_global_provider() -> None: @@ -119,25 +121,27 @@ def test_global_aurora_pg_dialect_selects_global_provider() -> None: "us-east-1:global-db-us-east-1.cluster-xyz.us-east-1.rds.amazonaws.com"), })) assert isinstance(provider, AsyncGlobalAuroraHostListProvider) - assert provider._topology_query == GlobalAuroraPgDialect().topology_query + assert provider._topology_utils._topology_query == GlobalAuroraPgDialect().topology_query def test_global_aurora_mysql_dialect_selects_global_provider() -> None: provider = _build(GlobalAuroraMysqlDialect(), AsyncAiomysqlDriverDialect()) assert isinstance(provider, AsyncGlobalAuroraHostListProvider) - assert provider._topology_query == GlobalAuroraMysqlDialect().topology_query - assert provider._default_port == MYSQL_PORT + assert provider._topology_utils._topology_query == GlobalAuroraMysqlDialect().topology_query + assert provider._topology_utils._default_port == MYSQL_PORT def test_multi_az_pg_dialect_selects_multi_az_provider() -> None: dialect = MultiAzClusterPgDialect() provider = _build(dialect) assert isinstance(provider, AsyncMultiAzHostListProvider) - assert provider._topology_query == dialect.topology_query - assert provider._writer_host_query == dialect.writer_id_query - assert provider._host_id_query == dialect.host_id_query + topology_utils = provider._topology_utils + assert isinstance(topology_utils, AsyncMultiAzTopologyUtils) + assert topology_utils._topology_query == dialect.topology_query + assert topology_utils._writer_host_query == dialect.writer_id_query + assert topology_utils._host_id_query == dialect.host_id_query # The PG writer query returns a single column. - assert provider._writer_host_column_index == 0 + assert topology_utils._writer_host_column_index == 0 def test_multi_az_mysql_dialect_carries_writer_column_index() -> None: @@ -146,8 +150,10 @@ def test_multi_az_mysql_dialect_carries_writer_column_index() -> None: dialect = MultiAzClusterMysqlDialect() provider = _build(dialect, AsyncAiomysqlDriverDialect()) assert isinstance(provider, AsyncMultiAzHostListProvider) - assert provider._writer_host_column_index == dialect._WRITER_HOST_COLUMN_INDEX - assert provider._default_port == MYSQL_PORT + topology_utils = provider._topology_utils + assert isinstance(topology_utils, AsyncMultiAzTopologyUtils) + assert topology_utils._writer_host_column_index == dialect._WRITER_HOST_COLUMN_INDEX + assert topology_utils._default_port == MYSQL_PORT def test_provider_receives_provider_service_for_dialect_confirmation() -> None: 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_plugin_service_extras.py b/tests/unit/test_aio_plugin_service_extras.py index d5763ce06..21bceae2c 100644 --- a/tests/unit/test_aio_plugin_service_extras.py +++ b/tests/unit/test_aio_plugin_service_extras.py @@ -6,6 +6,8 @@ import pytest +from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor from aws_advanced_python_wrapper.aio.default_plugin import AsyncDefaultPlugin from aws_advanced_python_wrapper.aio.driver_dialect.base import \ AsyncDriverDialect @@ -16,6 +18,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 import services_container from aws_advanced_python_wrapper.utils.properties import Properties @@ -1017,8 +1020,8 @@ async def _run(): assert isinstance(provider, AsyncAuroraHostListProvider) # The replacement carries the MySQL topology SQL and port, not the # provider ctor's PostgreSQL defaults. - assert provider._topology_query == AuroraMysqlDialect().topology_query - assert provider._default_port == 3306 + assert provider._topology_utils._topology_query == AuroraMysqlDialect().topology_query + assert provider._topology_utils._default_port == 3306 asyncio.run(_run()) @@ -1265,18 +1268,19 @@ async def _run(): provider = svc.host_list_provider assert provider is not existing assert type(provider) is type(existing) - assert provider._topology_query == AuroraMysqlDialect().topology_query - assert provider._default_port == 3306 + assert provider._topology_utils._topology_query == AuroraMysqlDialect().topology_query + assert provider._topology_utils._default_port == 3306 asyncio.run(_run()) -def test_replacing_the_provider_does_not_stop_the_outgoing_one(): - """The outgoing provider is left alone, which is only safe because it has - nothing to stop: its monitor is built on the first refresh, and a provider - built from an unconfirmed dialect refuses to refresh. Awaiting its stop - would instead close a monitor connection on the path that needed a dialect - upgrade.""" +def test_replacing_the_provider_leaves_the_cluster_topology_monitor_running(): + """The monitor is keyed by cluster id, which defaults to "1", and one + monitor serves every provider on that key, so stopping it reaches every + live connection on the cluster rather than this one. Nothing needs + stopping either: no monitor is built until the dialect is confirmed, so + the outgoing provider never had one, and a monitor at that key belongs to + another connection that resolved the same endpoint to the same dialect.""" from aws_advanced_python_wrapper.database_dialect import ( AuroraMysqlDialect, MultiAzClusterMysqlDialect) @@ -1287,13 +1291,24 @@ def test_replacing_the_provider_does_not_stop_the_outgoing_one(): svc.host_list_provider = existing svc.force_refresh_host_list = AsyncMock() + # Stand in for another connection's provider, which owns the shared + # monitor under the same cluster key. + other = MultiAzClusterMysqlDialect().get_async_host_list_provider_supplier()(svc, props) + svc.database_dialect = MultiAzClusterMysqlDialect() async def _run(): - await svc._update_host_list_provider(MagicMock(name="conn")) - existing.stop.assert_not_awaited() - assert existing._monitor is None - assert svc.host_list_provider is not existing + monitor = other._get_or_create_monitor() + assert monitor is not None + try: + await svc._update_host_list_provider(MagicMock(name="conn")) + existing.stop.assert_not_awaited() + assert services_container.get_monitor_service().get( + AsyncClusterTopologyMonitor, other._storage_key()) is monitor + finally: + services_container.get_monitor_service().stop_and_remove( + AsyncClusterTopologyMonitor, other._storage_key()) + await monitor.aclose() asyncio.run(_run()) @@ -1312,7 +1327,8 @@ def test_no_topology_monitor_is_built_before_the_dialect_is_confirmed(): async def _run(): assert svc.is_dialect_confirmed is False await provider.force_refresh(MagicMock(name="conn")) - assert provider._monitor is None + assert services_container.get_monitor_service().get( + AsyncClusterTopologyMonitor, provider._storage_key()) is None asyncio.run(_run()) @@ -1482,7 +1498,7 @@ def test_unconfirmed_dialect_reports_the_seed_host_without_querying(): conn = MagicMock(name="conn") conn.cursor = MagicMock(return_value=cursor) - seed = provider._seed_topology()[0] + seed = provider._topology_utils.initial_host_info async def _run(): for topology in (await provider.refresh(conn), @@ -1490,8 +1506,7 @@ async def _run(): assert [(h.host, h.port) for h in topology] == [(seed.host, seed.port)] # The gate is the point: no SQL ran and no monitor was built. cursor.execute.assert_not_awaited() - assert provider._topology_cache is None - assert provider._monitor is None + assert provider._get_stored_topology() is None # And the gate tracks the service flag rather than latching. The # open direction is asserted on the predicate, not on downstream diff --git a/tests/unit/test_aio_topology_storage.py b/tests/unit/test_aio_topology_storage.py new file mode 100644 index 000000000..8901d238a --- /dev/null +++ b/tests/unit/test_aio_topology_storage.py @@ -0,0 +1,282 @@ +# 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_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()) 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")