From 5f8af95f26c3d006c5a64a633f7bb889c510a558 Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Mon, 26 Oct 2026 14:29:00 -0700 Subject: [PATCH] refactor: revert the alias removal and async topology move --- .../aio/aurora_connection_tracker.py | 226 +++-- ...rora_initial_connection_strategy_plugin.py | 21 +- .../aio/blue_green_plugin.py | 1 + aws_advanced_python_wrapper/aio/cleanup.py | 12 - .../aio/cluster_topology_monitor.py | 320 ++----- .../aio/default_plugin.py | 11 +- .../aio/dialect_utils.py | 24 +- .../aio/failover_plugin.py | 12 +- .../aio/host_list_provider.py | 787 +++++++++++++----- .../aio/host_monitoring_plugin.py | 81 +- .../aio/limitless_plugin.py | 15 - .../aio/plugin_service.py | 155 ++-- .../aio/read_write_splitting_plugin.py | 13 +- aws_advanced_python_wrapper/aio/retry_util.py | 10 +- .../aio/topology_store.py | 112 --- .../aio/topology_utils.py | 448 ---------- aws_advanced_python_wrapper/aio/wrapper.py | 6 +- .../aurora_connection_tracker_plugin.py | 137 ++- ...rora_initial_connection_strategy_plugin.py | 17 +- .../aws_credentials_manager.py | 2 +- .../blue_green_plugin.py | 1 + .../cluster_topology_monitor.py | 5 +- .../database_dialect.py | 28 +- aws_advanced_python_wrapper/default_plugin.py | 2 +- .../failover_plugin.py | 15 +- .../failover_v2_plugin.py | 4 +- .../host_list_provider.py | 30 +- .../host_monitoring_plugin.py | 135 ++- .../host_monitoring_v2_plugin.py | 66 +- aws_advanced_python_wrapper/hostinfo.py | 56 +- .../limitless_plugin.py | 15 - aws_advanced_python_wrapper/plugin_service.py | 141 ++-- .../read_write_splitting_plugin.py | 15 +- .../reader_failover_handler.py | 6 +- ...dvanced_python_wrapper_messages.properties | 17 +- .../utils/concurrent.py | 19 + .../utils/monitor_service.py | 24 +- .../storage/expiration_tracking_cache.py | 12 +- .../utils/storage/storage_service.py | 11 +- aws_advanced_python_wrapper/utils/utils.py | 46 - aws_advanced_python_wrapper/wrapper.py | 6 +- .../writer_failover_handler.py | 17 +- docs/development-guide/PluginService.md | 18 - tests/unit/conftest.py | 4 - .../test_aio_aurora_connection_tracker.py | 58 +- .../test_aio_aurora_initial_connection.py | 16 +- tests/unit/test_aio_dialect_utils.py | 2 +- tests/unit/test_aio_failover_plugin.py | 8 +- ...st_aio_global_aurora_host_list_provider.py | 28 +- tests/unit/test_aio_host_list_provider.py | 477 +++++------ ...t_aio_host_list_provider_monitor_wiring.py | 210 +++-- tests/unit/test_aio_host_monitoring_plugin.py | 2 +- .../test_aio_monitor_lifecycle_regressions.py | 296 ------- .../test_aio_monitor_service_integration.py | 218 ----- tests/unit/test_aio_multi_alias_tracker.py | 150 ++++ .../test_aio_multi_az_host_list_provider.py | 6 +- tests/unit/test_aio_multi_key_tracker.py | 133 --- tests/unit/test_aio_plugin_service_extras.py | 158 ++-- tests/unit/test_aio_retry_util.py | 6 +- tests/unit/test_aio_simple_rws.py | 7 +- tests/unit/test_aio_topology_storage.py | 314 ------- tests/unit/test_aio_wrapper.py | 11 +- tests/unit/test_aurora_connection_tracker.py | 132 +-- tests/unit/test_cluster_topology_monitor.py | 22 - tests/unit/test_connection.py | 41 - tests/unit/test_expiration_tracking_cache.py | 18 + tests/unit/test_failover_plugin.py | 11 +- tests/unit/test_host_monitor_v2_plugin.py | 63 +- tests/unit/test_host_monitoring_plugin.py | 73 +- tests/unit/test_hostinfo.py | 35 +- tests/unit/test_monitor_service.py | 44 +- .../test_multi_az_rds_host_list_provider.py | 27 - .../test_multithreaded_monitor_service.py | 31 +- tests/unit/test_plugin_service.py | 251 +----- tests/unit/test_reader_failover_handler.py | 6 +- tests/unit/test_storage_service.py | 23 - tests/unit/test_writer_failover_handler.py | 34 +- 77 files changed, 2103 insertions(+), 3911 deletions(-) delete mode 100644 aws_advanced_python_wrapper/aio/topology_store.py delete mode 100644 aws_advanced_python_wrapper/aio/topology_utils.py delete mode 100644 tests/unit/test_aio_monitor_lifecycle_regressions.py delete mode 100644 tests/unit/test_aio_monitor_service_integration.py create mode 100644 tests/unit/test_aio_multi_alias_tracker.py delete mode 100644 tests/unit/test_aio_multi_key_tracker.py delete mode 100644 tests/unit/test_aio_topology_storage.py diff --git a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py index c338b574a..93e287eeb 100644 --- a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py +++ b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py @@ -16,11 +16,11 @@ Port of sync ``aurora_connection_tracker_plugin.py``. Tracks every connection opened through the plugin pipeline in a class-level -:class:`AsyncOpenedConnectionTracker` registry keyed by host id and by -host and port. On writer change (detected via -``AsyncPluginService.all_hosts`` or a raised :class:`FailoverError`), -closes every tracked connection to the old writer so pooled consumers -don't reuse a stale demoted-writer socket. +:class:`AsyncOpenedConnectionTracker` registry keyed by the RDS +instance-endpoint alias (mirroring sync normalization). On writer +change (detected via ``AsyncPluginService.all_hosts`` or a raised +:class:`FailoverError`), closes every tracked connection to the old +writer so pooled consumers don't reuse a stale demoted-writer socket. Simpler than the sync implementation: @@ -47,7 +47,7 @@ import threading from time import perf_counter_ns from typing import (TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, - Optional, Set, Tuple) + Optional, Set) from weakref import WeakSet from aws_advanced_python_wrapper.aio.cleanup import register_shutdown_hook @@ -58,7 +58,6 @@ from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils -from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from aws_advanced_python_wrapper.aio.driver_dialect.base import \ @@ -71,17 +70,24 @@ class AsyncOpenedConnectionTracker: - """Registry of open connections, shared across plugin instances. + """Alias-keyed registry of open connections, shared across plugin instances. - An instance endpoint names the instance already, so its connections are - tracked under one key. Any other endpoint may be a custom domain name, - which is tracked both under the host id and under the endpoint the caller - used, so a later notification naming either one finds the connections. + Keys by the RDS **instance** endpoint alias when one is present in + ``host_info.as_aliases()`` -- matching sync's + :class:`OpenedConnectionTracker` at + ``aurora_connection_tracker_plugin.py:47``. Falls back to + ``host_info.as_alias()`` when no RDS instance alias is + discoverable (non-Aurora or custom endpoint connections). - ``_tracked`` is class-level, as sync's registry is, so multiple pooled - :class:`AsyncAuroraConnectionTrackerPlugin` instances coordinate: one - plugin's :meth:`invalidate_all` closes every peer connection to the same - host. + This lets a cluster-endpoint-connected session still be + invalidated when a later ``CONVERTED_TO_READER`` notification + carries the instance alias. + + Class-level ``_tracked`` mirrors sync ``OpenedConnectionTracker`` at + ``aurora_connection_tracker_plugin.py:47`` so multiple pooled + :class:`AsyncAuroraConnectionTrackerPlugin` instances can coordinate: + one plugin's :meth:`invalidate_all` closes every peer connection to + the same host. Still simpler than sync: @@ -95,49 +101,74 @@ def __init__(self) -> None: # Instance-level nothing -- all state lives on the class dict. pass - _rds_utils: ClassVar[RdsUtils] = RdsUtils() + @staticmethod + def _canonical_key(host_info: HostInfo) -> str: + """Return the instance-endpoint alias if available, else host:port. - @classmethod - def _tracking_keys(cls, host_info: HostInfo) -> Tuple[str, ...]: - """The keys ``host_info``'s connections are tracked under.""" - if cls._rds_utils.is_rds_instance(host_info.host): - return (host_info.get_host_and_port(),) - return tuple( - key for key in (host_info.host_id, host_info.get_host_and_port()) if key) + Mirrors sync's multi-alias normalization in + ``populate_opened_connection_set``/``invalidate_all_connections``/ + ``remove_connection_tracking`` at + ``aurora_connection_tracker_plugin.py:116-137``. + """ + rds_utils = RdsUtils() + if rds_utils.is_rds_instance(host_info.host): + return host_info.as_alias() + for alias in host_info.as_aliases(): + if rds_utils.is_rds_instance(rds_utils.remove_port(alias)): + return alias + return host_info.as_alias() + + @staticmethod + def _all_keys(host_info: HostInfo) -> Set[str]: + """Return every alias worth tracking ``host_info`` under. + + Sync's ``OpenedConnectionTracker`` tracks connections keyed on + every alias in ``host_info.as_aliases()`` so a later invalidation + via any alias closes the same underlying connection set. We + mirror that here: track under each alias plus the canonical + RDS-instance endpoint. + """ + keys: Set[str] = set() + canonical = AsyncOpenedConnectionTracker._canonical_key(host_info) + if canonical: + keys.add(canonical) + try: + for alias in host_info.as_aliases(): + if alias: + keys.add(alias) + except Exception: # noqa: BLE001 - as_aliases() is best-effort + pass + return keys def track(self, host_info: HostInfo, conn: Any) -> None: - for key in self._tracking_keys(host_info): + for key in self._all_keys(host_info): conn_set = AsyncOpenedConnectionTracker._tracked.setdefault( key, WeakSet()) conn_set.add(conn) def remove(self, host_info: HostInfo, conn: Any) -> None: - for key in self._tracking_keys(host_info): + for key in self._all_keys(host_info): conn_set = AsyncOpenedConnectionTracker._tracked.get(key) if conn_set is not None: conn_set.discard(conn) async def invalidate_all(self, host_info: HostInfo) -> None: - """Close every connection tracked for ``host_info``.""" - logger.debug( - "OpenedConnectionTracker.InvalidatingConnections", host_info.url) - await self.invalidate_all_for_keys( - host_info.get_host_and_port(), host_info.host, host_info.host_id) - - async def invalidate_all_for_keys(self, *keys: Optional[str]) -> None: - """Close every connection tracked under any of ``keys``. + """Close every tracked connection reachable via any alias of ``host_info``. - Best-effort: individual close failures are swallowed so one broken - connection does not block closing the rest. + Best-effort: individual close failures are swallowed so one + broken connection doesn't block closing the rest. Fixes the + prior canonical-key-only semantics that could miss invalidations + when the caller held a non-canonical alias. """ + # Gather the full connection set from every alias; close each + # connection exactly once, then purge the alias entries. + logger.debug( + "OpenedConnectionTracker.InvalidatingConnections", host_info.url) seen_conns: Set[int] = set() to_close: list = [] - present = tuple(key for key in keys if key) - # Drop each key before the first await. Collecting everything first - # and popping afterwards would discard a connection a concurrent - # track() added in between, leaving it open and untracked. - for key in present: - conn_set = AsyncOpenedConnectionTracker._tracked.pop(key, None) + keys = self._all_keys(host_info) + for key in keys: + conn_set = AsyncOpenedConnectionTracker._tracked.get(key) if conn_set is None: continue for c in list(conn_set): @@ -174,14 +205,18 @@ async def invalidate_all_for_keys(self, *keys: Optional[str]) -> None: # is_closed=False to its owner. logger.debug( f"[AsyncOpenedConnectionTracker] best-effort close of a " - f"tracked connection failed: {e}") + f"tracked connection to '{host_info.url}' failed: {e}") + + for key in keys: + try: + del AsyncOpenedConnectionTracker._tracked[key] + except KeyError: + pass def _tracked_for(self, host_info: HostInfo) -> WeakSet[Any]: - """Test-only accessor using the first tracking key.""" - keys = self._tracking_keys(host_info) - if not keys: - return WeakSet() - return AsyncOpenedConnectionTracker._tracked.get(keys[0], WeakSet()) + """Test-only accessor using the canonical key derivation.""" + key = self._canonical_key(host_info) + return AsyncOpenedConnectionTracker._tracked.get(key, WeakSet()) def log_opened_connections(self) -> None: """Debug-log the registry contents (sync parity: @@ -260,34 +295,11 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: conn = await connect_func() if conn is not None: - connection_host_info = await self._identify_connection_host(host_info, conn) - self._tracker.track(connection_host_info, conn) - await self._pin_current_writer(connection_host_info, conn) + await self._fill_instance_alias(host_info, conn) + self._tracker.track(host_info, conn) + await self._pin_current_writer(host_info, conn) return conn - async def _identify_connection_host( - self, host_info: HostInfo, conn: Any) -> HostInfo: - """The host this connection actually landed on. - - A cluster, custom-domain or IP endpoint does not name the instance the - connection reached, so ask the database and record the answer as the - routed host. On failure the endpoint the caller used is kept. - """ - routed = self._plugin_service.routed_host_info - connection_host_info = routed if routed is not None else host_info - url_type = AsyncOpenedConnectionTracker._rds_utils.identify_rds_type( - connection_host_info.host) - if not Utils.requires_host_identification(url_type): - return connection_host_info - try: - identified = await self._plugin_service.identify_connection(conn) - except Exception: # noqa: BLE001 - identification is best-effort - return connection_host_info - if identified is None: - return connection_host_info - self._plugin_service.routed_host_info = identified - return identified - async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: """Pin the current writer at connect time so a later failover is detected as a *transition*. @@ -337,6 +349,39 @@ async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: except Exception: # noqa: BLE001 - writer pinning is best-effort pass + async def _fill_instance_alias( + self, host_info: HostInfo, conn: Any) -> None: + """Add the connection's resolved instance endpoint as an alias. + + A cluster-endpoint connection lands on whichever instance the + cluster DNS currently points at, but ``host_info.host`` stays the + cluster endpoint -- so the tracker would key it only under the + cluster alias. On writer failover the change is detected against + the *instance* host (``_current_writer_from_hosts`` returns a + topology row), so ``invalidate_all(writer_instance)`` would never + match the cluster-keyed entry and the stale idle connection would + survive the demotion (``test_writer_failover_in_idle_connections``). + + Mirrors sync ``AuroraConnectionTrackerPlugin.connect`` which calls + ``plugin_service.fill_aliases`` for ``is_rds_cluster`` hosts. Only + cluster-endpoint connections pay the extra identify round-trip; + instance-endpoint connections already key correctly. Best-effort: + on any failure we fall back to cluster-key-only tracking (the + prior behavior), so a transient identify failure never blocks the + connect. + """ + try: + if not RdsUtils().identify_rds_type(host_info.host).is_rds_cluster: + return + identified = await self._plugin_service.identify_connection(conn) + if identified is None: + return + host_info.reset_aliases() + host_info.add_alias(host_info.as_alias()) + host_info.add_alias(*identified.as_aliases()) + except Exception: # noqa: BLE001 - alias enrichment is best-effort + pass + async def execute( self, target: object, @@ -498,14 +543,14 @@ def _current_writer_from_hosts(self) -> Optional[HostInfo]: def _same_host(a: HostInfo, b: HostInfo) -> bool: return a.host == b.host and a.port == b.port - def _spawn_invalidation(self, key: str) -> None: + def _spawn_invalidation(self, old_writer: HostInfo) -> None: """Fire-and-forget invalidation, ONLY for the sync-signature :meth:`notify_host_list_changed` path (cannot await there). The execute/failover path awaits :meth:`_invalidate_writer_change` inline instead -- a spawned task dies un-awaited if the event loop closes before it runs. Pending tasks from this path are drained by :meth:`_shutdown` on ``release_resources_async``.""" - task = asyncio.create_task(self._tracker.invalidate_all_for_keys(key)) + task = asyncio.create_task(self._tracker.invalidate_all(old_writer)) self._pending_invalidations.add(task) task.add_done_callback(self._pending_invalidations.discard) @@ -534,15 +579,38 @@ def notify_host_list_changed( :attr:`_current_writer` so the next ``execute`` re-detects the new writer via :meth:`_update_writer_from_topology`. + With the tracker's canonical-key normalization (instance alias + over cluster alias), a notify carrying the instance alias for a + cluster-connected session now correctly finds and invalidates + the tracked entries. """ - for host, events in changes.items(): + for alias, events in changes.items(): if HostEvent.CONVERTED_TO_READER in events: - # Change keys are urls; tracking keys are not. - self._spawn_invalidation(host.rstrip("/")) + host_part, port_part = self._parse_alias(alias) + h = HostInfo(host=host_part, port=port_part) + self._spawn_invalidation(h) if HostEvent.CONVERTED_TO_WRITER in events: # Force writer recheck on next execute via # _update_writer_from_topology. self._current_writer = None + @staticmethod + def _parse_alias(alias: str) -> tuple: + """Split a ``host:port`` alias into ``(host, port)``. + + Uses ``rpartition(':')`` so IPv6 aliases of the form + ``[::1]:5432`` split correctly on the LAST colon. Falls back to + port 5432 when the alias has no colon (or the port part isn't + numeric). + """ + host_part, sep, port_part = alias.rpartition(":") + if not sep: + # No colon -> treat entire alias as host, port defaults. + return alias, 5432 + try: + return host_part, int(port_part) + except ValueError: + return host_part, 5432 + __all__ = ["AsyncAuroraConnectionTrackerPlugin", "AsyncOpenedConnectionTracker"] diff --git a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py index d00ff2e83..20235f68b 100644 --- a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py @@ -26,6 +26,10 @@ so auth plugins (IAM, Secrets, Federated, Okta) and connection tracker re-apply on the new connection just like a user-driven connect. +* ``initial_connection_host_info`` is set on the plugin service directly: + ``AsyncPluginServiceImpl`` implements ``AsyncHostListProviderService`` + and ``aio/wrapper.py`` passes it as the host list provider service, so + the two are the same object. """ from __future__ import annotations @@ -98,6 +102,8 @@ def init_host_provider( props: Properties, host_list_provider_service: Any, init_host_provider_func: Callable) -> None: + # Sync captures the service here; async sets initial_connection_host_info on the plugin + # service directly so there is nothing to hold. init_host_provider_func() async def connect( @@ -133,13 +139,13 @@ async def connect( if role_to_verify is None: # No verification required. - self._plugin_service.routed_host_info = candidate_host + self._set_initial_connection_host_info(is_initial_connection, candidate_host) return candidate_conn conn_role = await self._plugin_service.get_host_role(candidate_conn) if conn_role == role_to_verify: # Verification succeeded. - self._plugin_service.routed_host_info = candidate_host + self._set_initial_connection_host_info(is_initial_connection, candidate_host) return candidate_conn # Verification failed. Retry, unless a reader was requested but the cluster has no readers. @@ -151,7 +157,7 @@ async def connect( logger.debug( "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._plugin_service.routed_host_info = candidate_host + self._set_initial_connection_host_info(is_initial_connection, candidate_host) return candidate_conn logger.debug( @@ -165,7 +171,7 @@ async def connect( if candidate_host is not None: self._plugin_service.set_availability( - candidate_host, HostAvailability.UNAVAILABLE) + candidate_host.as_aliases(), HostAvailability.UNAVAILABLE) if self._plugin_service.is_network_exception(error=e): # Retry connection. @@ -454,6 +460,13 @@ def _has_hosts(self) -> bool: def _has_readers(self) -> bool: return any(host.role == HostRole.READER for host in self._plugin_service.all_hosts) + def _set_initial_connection_host_info( + self, is_initial_connection: bool, host_info: Optional[HostInfo]): + # AsyncPluginServiceImpl implements AsyncHostListProviderService and is passed as the host + # list provider service, so this is the same attribute sync writes through that service. + if is_initial_connection and host_info is not None: + self._plugin_service.initial_connection_host_info = host_info + async def _close_connection( self, connection: Optional[Any], driver_dialect: AsyncDriverDialect) -> None: if connection is None: diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index 7c1898d80..a61428ecd 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -400,6 +400,7 @@ async def apply( rerouted_host_info = copy(self._substitute_host_info) rerouted_host_info.host_id = iam_host.host_id rerouted_host_info.availability = HostAvailability.AVAILABLE + rerouted_host_info.add_alias(iam_host.host) rerouted_props = copy(props) WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host) diff --git a/aws_advanced_python_wrapper/aio/cleanup.py b/aws_advanced_python_wrapper/aio/cleanup.py index 77134b678..12d092ee2 100644 --- a/aws_advanced_python_wrapper/aio/cleanup.py +++ b/aws_advanced_python_wrapper/aio/cleanup.py @@ -71,18 +71,6 @@ 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 c520ff864..265f8aa8b 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,22 +45,18 @@ 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 @@ -75,9 +71,7 @@ class AsyncClusterTopologyMonitor: def __init__( self, - topology_utils: AsyncTopologyUtils, - cluster_id: str, - key: TopologyKey, + provider: AsyncAuroraHostListProvider, connection_getter: Any, refresh_interval_sec: float = 30.0, high_refresh_rate_sec: float = 1.0, @@ -86,13 +80,8 @@ def __init__( connection_factory: Optional[Callable[[], Awaitable[Any]]] = None, ) -> None: """ - :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 provider: the host list provider whose ``force_refresh`` to + call each tick. :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. @@ -116,9 +105,7 @@ def __init__( ``plugin_service.force_connect(initial_host, monitoring_props)``. When ``None``, falls back to ``connection_getter`` (test/back-compat). """ - self._topology_utils = topology_utils - self._cluster_id = cluster_id - self._key = key + self._provider = provider self._connection_getter = connection_getter self._connection_factory = connection_factory self._owned_conn: Optional[Any] = None @@ -136,10 +123,6 @@ 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() @@ -148,24 +131,10 @@ def __init__( self._is_verified_writer_connection: bool = False self._verified_writer_conn: Optional[Any] = None self._verified_writer_host_info: Optional[HostInfo] = None - self._submitted_hosts: Set[str] = set() + self._submitted_host_aliases: Set[str] = set() 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).""" @@ -209,21 +178,17 @@ 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() or self._closed: + if self.is_running(): 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: @@ -259,8 +224,6 @@ 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 @@ -268,7 +231,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._topology_utils.query_for_topology(conn) + topology = await self._fetch_via_provider(conn) except Exception as ex: # Monitor failures shouldn't crash the task; the cached # topology remains usable. A failure may mean the owned @@ -280,7 +243,7 @@ async def _run(self) -> None: # on the next tick. logger.debug( "ClusterTopologyMonitor.ErrorFetchingTopology", - self._cluster_id, ex) + self._provider.get_cluster_id(), ex) await self._drop_owned_connection() if topology: # Adopt only a NON-EMPTY result. A query through a dead / @@ -290,7 +253,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, reset_count) + self._publish_topology(topology) else: # Empty/failed refresh: drop the (likely dead) connection # so the next tick reopens to a live host; KEEP the cached @@ -375,6 +338,8 @@ def _role_corrected(self, topology: Topology) -> Topology: if h.role != want_role: fixed = copy.copy(h) fixed.role = want_role + for alias in h.as_aliases(): + fixed.add_alias(alias) corrected.append(fixed) changed = True else: @@ -382,6 +347,8 @@ def _role_corrected(self, topology: Topology) -> Topology: if not found: writer_row = copy.copy(verified) writer_row.role = HostRole.WRITER + for alias in verified.as_aliases(): + writer_row.add_alias(alias) corrected.append(writer_row) changed = True if changed: @@ -391,27 +358,23 @@ 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, - 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. - """ + 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).""" 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) - topology_store.put_topology(self._key, 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 self._topology_updated.set() async def _wait_for_tick(self, interval: float) -> None: @@ -425,17 +388,12 @@ async def _wait_for_tick(self, interval: float) -> None: timeout=interval, return_when=asyncio.FIRST_COMPLETED) finally: - # An application that closes its loop without releasing resources - # leaves this parked. Cancelling or draining a waiter whose loop is - # gone raises, and here that would surface as an unraisable - # exception from the garbage collector. - if not stop_waiter.get_loop().is_closed(): - for waiter in (stop_waiter, tick_waiter): - if not waiter.done(): - waiter.cancel() - await asyncio.gather( - stop_waiter, tick_waiter, return_exceptions=True) - self._request_tick.clear() + for waiter in (stop_waiter, tick_waiter): + if not waiter.done(): + waiter.cancel() + await asyncio.gather( + stop_waiter, tick_waiter, return_exceptions=True) + self._request_tick.clear() async def _harvest_verified_writer(self) -> None: """Promote the panic-found verified-writer connection to the monitor's @@ -452,7 +410,7 @@ async def _harvest_verified_writer(self) -> None: if pending: await asyncio.gather(*pending, return_exceptions=True) self._probe_tasks.clear() - self._submitted_hosts.clear() + self._submitted_host_aliases.clear() if conn is None: return if self._connection_factory is None: @@ -481,7 +439,7 @@ def _should_panic(self) -> bool: def _spawn_panic_probes(self) -> None: """Spawn probe tasks for each host in ``last_topology`` not already - submitted. Deduped by ``host_info.get_host_and_port()``. + submitted. Deduped by ``host_info.as_alias()``. """ # Opportunistic cleanup of finished task refs. finished = [k for k, t in self._probe_tasks.items() if t.done()] @@ -489,15 +447,15 @@ def _spawn_panic_probes(self) -> None: self._probe_tasks.pop(k, None) # Release dedup slot so a retry can happen on a later tick if # the earlier probe failed/returned non-writer. - self._submitted_hosts.discard(k) + self._submitted_host_aliases.discard(k) for host_info in self._last_topology: - key = host_info.get_host_and_port() - if key in self._submitted_hosts: + alias = host_info.as_alias() + if alias in self._submitted_host_aliases: continue - self._submitted_hosts.add(key) + self._submitted_host_aliases.add(alias) task = asyncio.create_task(self._probe_and_report(host_info)) - self._probe_tasks[key] = task + self._probe_tasks[alias] = task # Aurora PG briefly rejects IAM/PAM auth on instances mid-promotion # (the PAM service restarts during the writer-role swap). Mirror the @@ -512,7 +470,6 @@ 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): @@ -558,10 +515,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._topology_utils.query_for_topology(conn) + topology = await self._fetch_via_provider(conn) except Exception: # noqa: BLE001 - publication is best-effort topology = () - self._publish_topology(topology, reset_count) + self._publish_topology(topology) self._writer_found_event.set() return @@ -574,7 +531,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._topology_utils.query_for_topology(conn) + topology = await self._fetch_via_provider(conn) except Exception: # noqa: BLE001 - publication is best-effort topology = () if topology: @@ -583,7 +540,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, reset_count) + self._publish_topology(topology) # Lost the race OR role is reader: close the conn. if conn is not None: @@ -669,185 +626,54 @@ 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._topology_utils.query_for_topology(conn), + self._fetch_via_provider(conn), timeout=timeout_sec, ) except asyncio.TimeoutError as e: raise TimeoutError(Messages.get_formatted( "ClusterTopologyMonitor.TopologyNotUpdated", - self._cluster_id, timeout_sec * 1000)) from e + self._provider.get_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, reset_count) + self._publish_topology(topology) return topology - 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. + 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. """ + 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._closed: + if self._task is None: return - self._closed = True - task = self._task - self._task = None - if task is not None and not task.done(): - task.cancel() + if not self._task.done(): + self._task.cancel() try: - await task + await self._task except (asyncio.CancelledError, Exception): pass - # _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_hosts.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() + self._task = None def build_probe_host( diff --git a/aws_advanced_python_wrapper/aio/default_plugin.py b/aws_advanced_python_wrapper/aio/default_plugin.py index 61ce696bf..9090b97d9 100644 --- a/aws_advanced_python_wrapper/aio/default_plugin.py +++ b/aws_advanced_python_wrapper/aio/default_plugin.py @@ -147,17 +147,18 @@ async def force_connect( def _post_connect_bookkeeping(self, host_info: HostInfo, connection_provider: Any) -> None: """Post-connect bookkeeping after a successful connect. - Sync parity: ``DefaultPlugin._connect`` marks the just-connected host - AVAILABLE and lets the service re-pick the driver dialect for the - provider that produced the connection (a no-op on async today). - The DATABASE-dialect upgrade + Sync parity: ``DefaultPlugin._connect`` (default_plugin.py:80-82) marks + every alias of the just-connected host AVAILABLE and lets the service + re-pick the driver dialect for the provider that produced the + connection (a no-op on async today). The DATABASE-dialect upgrade (sync ``plugin_service.update_dialect(conn)``) is invoked by the connect/force_connect callers right after this bookkeeping, mirroring sync's ordering; it is async so it cannot live in this sync helper. """ if self._plugin_service is None: return - self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE) + self._plugin_service.set_availability( + host_info.as_aliases(), HostAvailability.AVAILABLE) self._plugin_service.update_driver_dialect(connection_provider) async def execute( diff --git a/aws_advanced_python_wrapper/aio/dialect_utils.py b/aws_advanced_python_wrapper/aio/dialect_utils.py index ecb0da57d..d01e93bb9 100644 --- a/aws_advanced_python_wrapper/aio/dialect_utils.py +++ b/aws_advanced_python_wrapper/aio/dialect_utils.py @@ -23,7 +23,7 @@ from __future__ import annotations import asyncio -from typing import TYPE_CHECKING, Any, Optional, Tuple +from typing import TYPE_CHECKING, Any, Optional from aws_advanced_python_wrapper.errors import (AwsWrapperError, QueryTimeoutError) @@ -83,14 +83,12 @@ async def get_instance_id( conn: Any, driver_dialect: AsyncDriverDialect, host_id_query: str, - timeout_sec: float = 5.0) -> Optional[Tuple[str, str]]: - """Run the dialect's ``host_id_query`` for the instance ``conn`` is - bound to, returning ``(instance_id, instance_name)``. - - Aurora returns the same value in both columns. Multi-AZ returns a - numeric id and a short instance name, and callers match on either. - Returns ``None`` on an empty result or a query failure, since - identification is best-effort. + timeout_sec: float = 5.0) -> Optional[str]: + """Run the dialect's ``host_id_query`` to learn the Aurora + instance identifier ``conn`` is bound to. Returns ``None`` on + empty result or query failure (best-effort; callers fall back + to topology resolution by host_id). Mirrors sync + DialectUtils.get_instance_id at database_dialect.py. """ was_in_txn = await AsyncDialectUtils._safe_in_transaction( conn, driver_dialect) @@ -109,12 +107,10 @@ async def get_instance_id( await AsyncDialectUtils._restore_idle(conn, was_in_txn) if not result: return None - instance_id = result[0] - if instance_id is None: + first = result[0] + if first is None: return None - # A single-column result repeats the id, as the Aurora query does. - instance_name = result[1] if len(result) > 1 and result[1] is not None else instance_id - return str(instance_id), str(instance_name) + return str(first) @staticmethod async def _safe_in_transaction( diff --git a/aws_advanced_python_wrapper/aio/failover_plugin.py b/aws_advanced_python_wrapper/aio/failover_plugin.py index fa4381427..1655855bc 100644 --- a/aws_advanced_python_wrapper/aio/failover_plugin.py +++ b/aws_advanced_python_wrapper/aio/failover_plugin.py @@ -212,7 +212,7 @@ async def _connect_with_failover( if not self._should_failover(e): raise self._plugin_service.set_availability( - host_info, HostAvailability.UNAVAILABLE) + host_info.as_aliases(), HostAvailability.UNAVAILABLE) await self._do_failover(driver_dialect) else: # Known-dead target: refresh topology and fail over without @@ -424,7 +424,7 @@ async def _do_failover(self, driver_dialect: AsyncDriverDialect) -> None: failed_host = self._plugin_service.current_host_info if failed_host is not None: self._plugin_service.set_availability( - failed_host, HostAvailability.UNAVAILABLE) + failed_host.as_aliases(), HostAvailability.UNAVAILABLE) # Invalidate the current (likely broken) connection before # attempting failover so any pool-proxied target is evicted from @@ -556,7 +556,7 @@ async def _failover_reader_impl( self._open_connection(candidate, driver_dialect), deadline) except Exception as e: # noqa: BLE001 self._plugin_service.set_availability( - candidate, HostAvailability.UNAVAILABLE) + candidate.as_aliases(), HostAvailability.UNAVAILABLE) last_error = e if candidate in remaining: remaining.remove(candidate) @@ -578,7 +578,7 @@ async def _failover_reader_impl( if role == HostRole.READER or self._mode != FailoverMode.STRICT_READER: verified = HostInfo(candidate.host, candidate.port, role) self._plugin_service.set_availability( - candidate, HostAvailability.AVAILABLE) + candidate.as_aliases(), HostAvailability.AVAILABLE) await self._plugin_service.set_current_connection(new_conn, verified) if self._failover_reader_completed is not None: self._failover_reader_completed.inc() @@ -608,7 +608,7 @@ async def _failover_reader_impl( self._open_connection(original_writer, driver_dialect), deadline) except Exception as e: # noqa: BLE001 self._plugin_service.set_availability( - original_writer, HostAvailability.UNAVAILABLE) + original_writer.as_aliases(), HostAvailability.UNAVAILABLE) last_error = e else: role = await self._probe_role(new_conn) @@ -620,7 +620,7 @@ async def _failover_reader_impl( verified = HostInfo( original_writer.host, original_writer.port, role) self._plugin_service.set_availability( - original_writer, HostAvailability.AVAILABLE) + original_writer.as_aliases(), HostAvailability.AVAILABLE) await self._plugin_service.set_current_connection( new_conn, verified) if self._failover_reader_completed is not None: diff --git a/aws_advanced_python_wrapper/aio/host_list_provider.py b/aws_advanced_python_wrapper/aio/host_list_provider.py index f9c245ec2..38345699c 100644 --- a/aws_advanced_python_wrapper/aio/host_list_provider.py +++ b/aws_advanced_python_wrapper/aio/host_list_provider.py @@ -37,22 +37,14 @@ from __future__ import annotations import asyncio -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.host_availability import \ - create_host_availability_strategy +from datetime import datetime +from typing import (TYPE_CHECKING, Any, Awaitable, Callable, Dict, List, + Optional, Protocol, Tuple, runtime_checkable) + +from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole -from aws_advanced_python_wrapper.utils import services_container -from aws_advanced_python_wrapper.utils.events import MonitorStopEvent from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.properties import WrapperProperties logger = Logger(__name__) @@ -60,7 +52,6 @@ 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 @@ -68,6 +59,23 @@ 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.""" @@ -145,21 +153,14 @@ def __init__(self, props: Properties) -> None: host = props.get("host", "") port_raw = props.get("port") port = int(port_raw) if port_raw is not None else -1 - self._host_info = HostInfo( - host=host, port=port, role=HostRole.WRITER, - host_availability_strategy=create_host_availability_strategy(props)) + self._host_info = HostInfo(host=host, port=port, role=HostRole.WRITER) self._cluster_id = f"static:{host}:{port}" - def _host(self) -> HostInfo: - """A copy, so marking the returned host unavailable does not mark the - one this provider hands to every later caller.""" - return copy(self._host_info) - async def refresh(self, connection: Optional[Any] = None) -> Topology: - return (self._host(),) + return (self._host_info,) async def force_refresh(self, connection: Optional[Any] = None) -> Topology: - return (self._host(),) + return (self._host_info,) def get_cluster_id(self) -> str: return self._cluster_id @@ -171,22 +172,29 @@ async def stop(self) -> None: class AsyncAuroraHostListProvider: """Aurora topology discovery over an async driver connection. - 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. + 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`. """ _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, @@ -213,42 +221,25 @@ def __init__( cluster_id: Optional[str] = None, default_port: int = 5432, monitor_connection_factory: Optional[ - Callable[[], Awaitable[Any]]] = None, - topology_utils: Optional[AsyncTopologyUtils] = None) -> None: + Callable[[], Awaitable[Any]]] = None) -> None: self._props = props self._driver_dialect = driver_dialect + self._topology_query = topology_query self._default_port = default_port self._monitor_connection_factory = monitor_connection_factory self._cluster_id = cluster_id or self._derive_cluster_id(props) + self._topology_cache: Optional[Topology] = None + self._last_refresh_ns: int = 0 self._refresh_lock = asyncio.Lock() refresh_ms = WrapperProperties.TOPOLOGY_REFRESH_MS.get(props) self._refresh_ns: int = ( int(refresh_ms) * 1_000_000 if refresh_ms is not None else self._DEFAULT_REFRESH_RATE_NS ) - # 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)) + # Monitor wiring (N.1b). Lazy-created on first refresh so + # provider construction stays cheap and test-friendly. + self._monitor: Optional[Any] = None # AsyncClusterTopologyMonitor 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 @@ -269,64 +260,52 @@ def set_probe_host(self, probe_host: Callable[..., Any]) -> None: def reconfigure_topology_query( self, topology_query: str, default_port: Optional[int] = None) -> None: - """Re-point the provider at a resolved dialect's query. - - The provider is built before the connection exists, so an - instance-endpoint MySQL connection starts with the PostgreSQL default - query and port. Once the dialect is upgraded to Aurora MySQL the real - query and port are swapped in, and the stored topology is dropped - because anything the old query produced is stale or empty. + """Re-point the provider at a (post-connect) resolved dialect's query. + + The provider is built BEFORE the connection exists, so an + instance-endpoint MySQL connection starts with the PostgreSQL-default + topology query + port (the ctor default). Once the database dialect is + resolved/upgraded to the Aurora MySQL dialect we swap in its topology + query and the MySQL port so discovery actually works. Clears the cache + so the next refresh re-probes with the new query (any cached PG-query + result is stale/empty). """ - self._topology_utils.reconfigure(topology_query, default_port) + if topology_query: + self._topology_query = topology_query if default_port: self._default_port = default_port - self._discard_stored_topology() + self._topology_cache = None + self._last_refresh_ns = 0 @staticmethod def _derive_cluster_id(props: Properties) -> str: - """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") + # 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}" 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 the stored topology if there is one, else force a refresh. + """Return cached topology if still fresh, else force a refresh. - 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. + 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). """ if connection is not None: self._last_conn = connection - stored = self._get_stored_topology() - if stored: - return stored + 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 return await self.force_refresh(connection) async def force_refresh(self, connection: Optional[Any] = None) -> Topology: @@ -342,7 +321,9 @@ async def force_refresh(self, connection: Optional[Any] = None) -> Topology: self._last_conn = connection if connection is None: - return self._get_stored_topology() or () + if self._topology_cache is not None: + return self._topology_cache + return () async with self._refresh_lock: monitor = self._get_or_create_monitor() @@ -354,8 +335,25 @@ 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) - self._store_topology(topology) - return topology or (self._get_stored_topology() or ()) + 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) async def force_monitoring_refresh( self, @@ -377,63 +375,40 @@ async def force_monitoring_refresh( return topology or () def _get_or_create_monitor(self) -> Optional[Any]: - """Get the cluster's topology monitor from the monitor service. + """Lazy-construct the per-provider topology monitor. - 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. - - 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. + 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`. """ - key = self._storage_key() - if key is None or not self._topology_utils.topology_query: + if self._monitor is not None and self._monitor.is_running(): + return self._monitor + if not self._topology_query: return None - 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: + try: + from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor + except Exception: # noqa: BLE001 - defensive import guard 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 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. + # 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. if self._monitor_connection_factory is None: logger.warning( - "AsyncAuroraHostListProvider.NoMonitoringConnectionFactory", - self._cluster_id) + "[AsyncAuroraHostListProvider] no dedicated monitoring " + "connection factory wired; background topology refresh disabled " + "to avoid racing the shared application connection.") monitor = AsyncClusterTopologyMonitor( - topology_utils=self._topology_utils, - cluster_id=self._cluster_id, - key=key, + provider=self, connection_getter=( (lambda: self._last_conn) if self._monitor_connection_factory is not None @@ -445,44 +420,250 @@ def _create_monitor(self, key: TopologyKey) -> Any: connection_factory=self._monitor_connection_factory, ) monitor.start() - - # 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) + self._monitor = monitor + # Register monitor teardown with the global cleanup hook so + # release_resources_async() tears it down. + try: + from aws_advanced_python_wrapper.aio.cleanup import \ + register_shutdown_hook + register_shutdown_hook(monitor.stop) + except Exception: # noqa: BLE001 + pass return monitor async def _fetch_and_cache(self, connection: Any) -> Topology: - """Direct 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 ()) + """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 async def stop(self) -> None: - """Stop the cluster's topology monitor. + """Tear down the provider's background topology monitor. - 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. + 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). """ - 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)) + monitor = self._monitor + self._monitor = None + if monitor is not None: + try: + await monitor.stop() + except Exception: # noqa: BLE001 - best-effort teardown + pass class AsyncMultiAzHostListProvider(AsyncAuroraHostListProvider): @@ -535,27 +716,136 @@ def __init__( cluster_id=cluster_id, default_port=default_port, monitor_connection_factory=monitor_connection_factory, - topology_utils=AsyncMultiAzTopologyUtils( - props=props, - topology_query=topology_query, - default_port=default_port, - writer_host_query=writer_host_query, - host_id_query=host_id_query, - writer_host_column_index=writer_host_column_index, - instance_template_host=instance_template_host), ) + self._writer_host_query = writer_host_query + self._host_id_query = host_id_query + # Column of ``writer_host_query``'s result row holding the writer's + # ID. PG's query returns a single column (index 0); MySQL's + # ``SHOW REPLICA STATUS`` carries the source host at column 39 -- + # matching sync ``MultiAzTopologyUtils`` / + # ``MultiAzClusterMysqlDialect._WRITER_HOST_COLUMN_INDEX``. + self._writer_host_column_index = writer_host_column_index + self._instance_template_host = instance_template_host + # Import locally to avoid widening the module's top-level import set. + from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils + self._rds_utils = RdsUtils() + self._writer_id: Optional[str] = None + + async def _run_topology_query(self, connection: Any) -> List[tuple]: + """Two-step MultiAz topology query. + + Step 1: ``writer_host_query``. Empty row => fall through to + ``host_id_query`` (we are the writer, MySQL-style). + Step 2: ``topology_query`` for the full host list. + + We stash the identified writer ID on ``self._writer_id`` so + :meth:`_rows_to_topology` can assign roles. A failure at any step + returns ``[]`` so callers fall back to cache, matching + :meth:`AsyncAuroraHostListProvider._run_topology_query`. + """ + try: + # Bind the ENTERED cursor (``as cur``) -- aiomysql's cursor() is a + # _ContextManager whose __aenter__ yields the real cursor; the bare + # manager has no ``.execute``. See AsyncAuroraHostListProvider. + async with connection.cursor() as cur: + # Step 1: writer host query. Empty row => we're the writer + # (MySQL), fall back to host_id_query. + await cur.execute(self._writer_host_query) + writer_row = await cur.fetchone() + if writer_row is not None: + writer_id = str(writer_row[self._writer_host_column_index]) + else: + await cur.execute(self._host_id_query) + self_row = await cur.fetchone() + if self_row is None: + return [] + writer_id = str(self_row[0]) + + # Step 2: topology query. + await cur.execute(self._topology_query) + rows = list(await cur.fetchall()) + + self._writer_id = writer_id + return rows + except Exception as ex: + # A ProgrammingError means the query itself is invalid -- surface it + # (sync MultiAzTopologyUtils._query_for_topology:659-660). Any other + # failure yields an empty topology so callers fall back to cache. + if _is_programming_error(ex): + raise AwsWrapperError( + Messages.get("RdsHostListProvider.InvalidQuery")) from ex + logger.debug( + f"[AsyncMultiAzHostListProvider] topology query failed; " + f"returning empty topology (caller falls back to cache): {ex}") + return [] + + def _rows_to_topology(self, rows: List[tuple]) -> Topology: + writer_id = self._writer_id + hosts: List[HostInfo] = [] + for row in rows: + if len(row) < 3: + continue + row_id = str(row[0]) + host = str(row[1]) + try: + port = int(row[2]) + except (TypeError, ValueError): + port = self._default_port + + role = HostRole.WRITER if row_id == writer_id else HostRole.READER + + # Optional instance-template substitution. Matches sync + # MultiAzTopologyUtils._create_multi_az_host. + if self._instance_template_host: + instance_name = self._rds_utils.get_instance_id(host) + if instance_name: + substituted = self._instance_template_host.replace( + "?", instance_name + ) + if ":" in substituted: + host_part, _, port_part = substituted.partition(":") + host = host_part + if port_part.isdigit(): + port = int(port_part) + else: + host = substituted + + host_info = HostInfo( + host=host, + port=port, + role=role, + host_id=row_id, + ) + host_info.add_alias(host) + hosts.append(host_info) + + # Validate: must have exactly one writer (sync MultiAz clears + # everything if no writer is found). + writers = [h for h in hosts if h.role == HostRole.WRITER] + if not writers: + return () + # Writer first, readers after -- matches AsyncAuroraHostListProvider. + hosts.sort(key=lambda h: 0 if h.role == HostRole.WRITER else 1) + return tuple(hosts) class AsyncGlobalAuroraHostListProvider(AsyncAuroraHostListProvider): - """Async 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. + """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). """ def __init__( @@ -577,9 +867,90 @@ def __init__( cluster_id=cluster_id, default_port=default_port, monitor_connection_factory=monitor_connection_factory, - topology_utils=AsyncGlobalAuroraTopologyUtils( - props=props, - topology_query=topology_query, - default_port=default_port, - instance_templates_by_region=instance_templates_by_region), ) + if instance_templates_by_region is None: + raw = WrapperProperties.GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.get( + props + ) + if raw: + instance_templates_by_region = self._parse_templates(raw) + else: + instance_templates_by_region = {} + self._templates_by_region: Dict[str, str] = instance_templates_by_region + + @staticmethod + def _parse_templates(raw: str) -> Dict[str, str]: + """Parse ``'region:host:port,region:host,...'`` into a dict. + + Same format as the sync ``GlobalAuroraTopologyUtils.parse_instance_templates`` + (``region:host:port`` or ``region:host``, comma-separated) so one + ``global_cluster_instance_host_patterns`` value works for both the + sync and async wrappers. A pair without a host raises, matching sync. + """ + result: Dict[str, str] = {} + for pair in raw.split(","): + pair = pair.strip() + if not pair: + continue + parts = pair.split(":", 2) + if len(parts) < 2 or not parts[0].strip() or not parts[1].strip(): + raise AwsWrapperError(Messages.get_formatted( + "GlobalAuroraTopologyUtils.invalidInstanceTemplate", pair)) + region = parts[0].strip() + pattern = parts[1].strip() + if len(parts) > 2 and parts[2].strip(): + pattern = f"{pattern}:{parts[2].strip()}" + result[region] = pattern + return result + + def _rows_to_topology(self, rows: List[tuple]) -> Topology: + """Override. Rows are ``(server_id, is_writer, lag, aws_region)`` — + the sync Global Aurora topology-query shape (``SERVER_ID``, + ``SESSION_ID``-derived writer flag, ``VISIBILITY_LAG_IN_MSEC``, + ``AWS_REGION``); the lag column is unused, matching sync. + + Each row's host is built from the region-specific template. Rows + referencing a region without a configured template are skipped. + Returns an empty tuple if no writer is present (matches + :class:`AsyncMultiAzHostListProvider`). + """ + hosts: List[HostInfo] = [] + for row in rows: + if len(row) < 4: + continue + server_id = str(row[0]) + is_writer = bool(row[1]) + region = str(row[3]) + template = self._templates_by_region.get(region) + if template is None: + # No template for this region -- skip the host. + continue + host_str = template.replace("?", server_id) + host = host_str + port = self._default_port + if ":" in host_str: + host_part, port_part = host_str.rsplit(":", 1) + try: + port = int(port_part) + host = host_part + except ValueError: + # Non-numeric port -- treat whole string as host. + pass + role = HostRole.WRITER if is_writer else HostRole.READER + host_info = HostInfo( + host=host, + port=port, + role=role, + host_id=server_id, + ) + host_info.add_alias(host) + hosts.append(host_info) + + # Validate: at least one writer. Match the MultiAz/sync convention + # of returning an empty topology when no writer is found so callers + # fall back to the cache. + if not any(h.role == HostRole.WRITER for h in hosts): + return () + # Writer first, readers after -- matches the other async providers. + hosts.sort(key=lambda h: 0 if h.role == HostRole.WRITER else 1) + return tuple(hosts) diff --git a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py index c26fc7e10..7458f91d7 100644 --- a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py @@ -71,7 +71,6 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import \ TelemetryTraceLevel -from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from weakref import ReferenceType @@ -372,7 +371,7 @@ async def _run(self) -> None: if self._is_unhealthy: self._plugin_service.set_availability( - self._host_info, HostAvailability.UNAVAILABLE) + self._host_info.as_aliases(), HostAvailability.UNAVAILABLE) await self._drain_active_contexts() @@ -581,7 +580,7 @@ def __init__( self._failure_detection_count = WrapperProperties.FAILURE_DETECTION_COUNT.get_int(props) self._failure_detection_enabled = WrapperProperties.FAILURE_DETECTION_ENABLED.get_bool(props) - # Subscribe to connect (to record the routed host) + every + # Subscribe to connect (for cluster-alias resolution) + every # network-bound method (so execute() brackets them with monitoring). # notify_* hooks are dispatched to all plugins regardless of this set. self._subscribed: Set[str] = {DbApiMethod.CONNECT.method_name} @@ -601,17 +600,10 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: connection = await connect_func() if connection is not None: - # Record which instance a cluster-endpoint connection landed on; - # the monitoring host is derived from it. - routed = self._plugin_service.routed_host_info - connection_host_info = routed if routed is not None else host_info - if self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: - try: - identified = await self._plugin_service.identify_connection(connection) - except Exception: # noqa: BLE001 - identification is best-effort - identified = None - if identified is not None: - self._plugin_service.routed_host_info = identified + rds_type = self._rds_utils.identify_rds_type(host_info.host) + if rds_type.is_rds_cluster: + host_info.reset_aliases() + await self._fill_aliases(connection, host_info) return connection async def execute( @@ -662,34 +654,49 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]) -> None: _stop_monitors_for_hosts(deleted) async def _get_monitoring_host_info(self) -> HostInfo: - # Held in a local because notify_connection_changed can clear the - # field while this method is between its assignment and its return. - monitoring_host_info = self._monitoring_host_info - if monitoring_host_info is not None: - return monitoring_host_info - # current_host_info, not routed_host_info: by the time any connection - # exists the wrapper has adopted the routed host, and a value still in - # that field belongs to a connect in flight, possibly another task's. - monitoring_host_info = self._plugin_service.current_host_info - if monitoring_host_info is None: + if self._monitoring_host_info is not None: + return self._monitoring_host_info + current_host_info = self._plugin_service.current_host_info + if current_host_info is None: raise AwsWrapperError(Messages.get("HostMonitoringV2Plugin.HostInfoNone")) - self._monitoring_host_info = monitoring_host_info - rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) + self._monitoring_host_info = current_host_info + rds_url_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) try: - if not Utils.requires_host_identification(rds_url_type): - return monitoring_host_info + if not rds_url_type.is_rds_cluster: + return self._monitoring_host_info logger.debug("HostMonitoringV2Plugin.ClusterEndpointHostInfo") - identified = await self._plugin_service.identify_connection( - self._plugin_service.current_connection) + current_connection = self._plugin_service.current_connection + # Async approximation of sync's identify_connection + fill_aliases: + # identify_connection already returns the topology (instance-level) + # HostInfo with its instance aliases, so it doubles as the monitoring + # host and the alias source. + identified = await self._plugin_service.identify_connection(current_connection) + if identified is None: + raise AwsWrapperError(Messages.get_formatted( + "HostMonitoringV2Plugin.UnableToIdentifyConnection", + current_host_info.host, + self._plugin_service.host_list_provider)) + self._monitoring_host_info = identified + except Exception as e: + if isinstance(e, AwsWrapperError): + raise + message = "HostMonitoringV2Plugin.ErrorIdentifyingConnection" + logger.debug(message, e) + raise AwsWrapperError(Messages.get_formatted(message, e)) from e + return self._monitoring_host_info + + async def _fill_aliases(self, connection: Any, host_info: HostInfo) -> None: + """Add the connection's resolved instance endpoint as an alias of a + cluster-endpoint host (async approximation of sync ``fill_aliases``: + ``identify_connection`` + ``as_aliases``). Best-effort.""" + try: + host_info.add_alias(host_info.as_alias()) + identified = await self._plugin_service.identify_connection(connection) if identified is not None: - monitoring_host_info = identified - self._monitoring_host_info = identified - except Exception as e: # noqa: BLE001 - the host id query failed - # Keep the connection's own host and monitor that. Raising here - # would fail every monitored call on the connection. - logger.debug("HostMonitoringV2Plugin.ErrorIdentifyingConnection", e) - return monitoring_host_info + host_info.add_alias(*identified.as_aliases()) + except Exception: # noqa: BLE001 - alias enrichment is best-effort + pass async def release_resources(self) -> None: """Drop this plugin's monitor-service reference. The shared monitors are diff --git a/aws_advanced_python_wrapper/aio/limitless_plugin.py b/aws_advanced_python_wrapper/aio/limitless_plugin.py index 4018b1369..9bd336fe3 100644 --- a/aws_advanced_python_wrapper/aio/limitless_plugin.py +++ b/aws_advanced_python_wrapper/aio/limitless_plugin.py @@ -163,18 +163,10 @@ def __init__( self._limitless_routers = limitless_routers self._connection_plugin = connection_plugin self._plugin_service = plugin_service - self._connection_host_info: Optional[HostInfo] = None def get_host_info(self) -> HostInfo: return self._host_info - def get_connection_host_info(self) -> Optional[HostInfo]: - """The router the connection was actually opened against.""" - return self._connection_host_info - - def set_connection_host_info(self, host_info: HostInfo) -> None: - self._connection_host_info = host_info - def get_props(self) -> Properties: return self._props @@ -494,7 +486,6 @@ async def establish_connection(self, context: AsyncLimitlessContext) -> None: await context.set_connection(await self._plugin_service.connect( selected_host_info, context.get_props(), plugin_to_skip=context.get_connection_plugin())) - context.set_connection_host_info(selected_host_info) except Exception as e: # noqa: BLE001 if self._is_login_exception(e): raise e @@ -551,7 +542,6 @@ async def _retry_connection_with_least_loaded_routers( selected_host_info, context.get_props(), plugin_to_skip=context.get_connection_plugin())) if context.get_connection() is not None: - context.set_connection_host_info(selected_host_info) return except Exception as e: # noqa: BLE001 if self._is_login_exception(e): @@ -772,11 +762,6 @@ async def connect( await self._limitless_router_service.establish_connection(context) connection = context.get_connection() if connection is not None and not await self._plugin_service.driver_dialect.is_closed(connection): - # The connection is on a router, not on the shard group endpoint - # the caller named. - routed_host_info = context.get_connection_host_info() - if routed_host_info is not None: - self._plugin_service.routed_host_info = routed_host_info return connection raise AwsWrapperError(Messages.get_formatted( diff --git a/aws_advanced_python_wrapper/aio/plugin_service.py b/aws_advanced_python_wrapper/aio/plugin_service.py index cd92b57c3..ba4628192 100644 --- a/aws_advanced_python_wrapper/aio/plugin_service.py +++ b/aws_advanced_python_wrapper/aio/plugin_service.py @@ -23,8 +23,8 @@ import asyncio import inspect -from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, - Optional, Protocol, Set, Tuple) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, FrozenSet, + List, Optional, Protocol, Set, Tuple) from aws_advanced_python_wrapper.aio.connection_provider import \ AsyncConnectionProviderManager @@ -42,7 +42,6 @@ ConnectionEvent, HostEvent, OldConnectionSuggestedAction) from aws_advanced_python_wrapper.utils.properties import WrapperProperties from aws_advanced_python_wrapper.utils.storage.cache_map import CacheMap -from aws_advanced_python_wrapper.utils.utils import Utils logger = Logger(__name__) @@ -99,7 +98,7 @@ def database_dialect(self, value: Optional[DatabaseDialect]) -> None: def set_availability( self, - host_info: HostInfo, + host_aliases: FrozenSet[str], availability: HostAvailability) -> None: ... @@ -150,27 +149,6 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: Optional[HostInfo]) -> None: ... - @property - def routed_host_info(self) -> Optional[HostInfo]: - """The host a plugin routed the pending connect to, if any. - - A plugin that connects to a host other than the one it was asked for - records its choice here, and a plugin that wants to know where the - connect went should read it. Do not consume it: connect hooks unwind - from the innermost plugin outwards, so a plugin that took the value - would hide it from every plugin outside it and from the wrapper, which - is what adopts it as the current host. - """ - ... - - @routed_host_info.setter - def routed_host_info(self, value: Optional[HostInfo]) -> None: - ... - - def take_routed_host_info(self) -> Optional[HostInfo]: - """Return the routed host and clear it. For the wrapper's use.""" - ... - async def refresh_host_list( self, connection: Optional[Any] = None) -> None: @@ -212,6 +190,18 @@ async def get_host_role( timeout_sec: Optional[float] = None) -> HostRole: ... + async def fill_aliases( + self, + connection: Optional[Any] = None, + host_info: Optional[HostInfo] = None) -> None: + """Populate ``host_info``'s aliases from the connection. + + Adds the host:port alias plus any aliases reported by the database's + ``host_alias_query`` and by :meth:`identify_connection`. No-op when the + host already has aliases. Mirrors sync ``PluginServiceImpl.fill_aliases``. + """ + ... + async def connect( self, host_info: HostInfo, @@ -402,7 +392,6 @@ def __init__( self._host_list_provider: Optional[AsyncHostListProvider] = None self._all_hosts: Tuple[HostInfo, ...] = () self._initial_connection_host_info: Optional[HostInfo] = None - self._routed_host_info: Optional[HostInfo] = None self._current_host_info: Optional[HostInfo] = host_info self._current_connection: Optional[Any] = None self._telemetry_factory: Optional[TelemetryFactory] = None @@ -511,32 +500,14 @@ def is_read_only_connection_exception( def set_availability( self, - host_info: HostInfo, + host_aliases: FrozenSet[str], availability: HostAvailability) -> None: - hosts_to_change = [ - host for host in self._all_hosts if Utils.matches_host(host_info, host)] - if not hosts_to_change: - return - - changes: Dict[str, Set[HostEvent]] = {} - for host in hosts_to_change: - # Through the strategy, not the raw field: a host whose backoff - # window has elapsed reads as available again, and marking it down - # is a change the plugins should hear about. - previous = host.get_availability() - host.set_availability(availability) + for alias in host_aliases: AsyncPluginServiceImpl._host_availability_expiring_cache.put( - host.url, + alias, availability, AsyncPluginServiceImpl._HOST_AVAILABILITY_EXPIRATION_NANO, ) - if previous != availability: - event = (HostEvent.WENT_UP if availability == HostAvailability.AVAILABLE - else HostEvent.WENT_DOWN) - changes[host.url] = {event, HostEvent.HOST_CHANGED} - - if changes and self._plugin_manager is not None: - self._plugin_manager.notify_host_list_changed(changes) def get_availability(self, host_url: str) -> Optional[HostAvailability]: return AsyncPluginServiceImpl._host_availability_expiring_cache.get(host_url) @@ -713,19 +684,21 @@ async def identify_connection( from aws_advanced_python_wrapper.aio.dialect_utils import \ AsyncDialectUtils - instance_ids = await AsyncDialectUtils.get_instance_id( + instance_id = await AsyncDialectUtils.get_instance_id( conn, self._driver_dialect, self._database_dialect.host_id_query, ) - if instance_ids is None: + if instance_id is None: return None topology = await self._host_list_provider.refresh(conn) - found = Utils.find_host(topology, *instance_ids) + found = next( + (h for h in topology if h.host_id == instance_id), None) if found is None: topology = await self._host_list_provider.force_refresh(conn) - found = Utils.find_host(topology, *instance_ids) + found = next( + (h for h in topology if h.host_id == instance_id), None) return found @property @@ -765,19 +738,6 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: Optional[HostInfo]) -> None: self._initial_connection_host_info = value - @property - def routed_host_info(self) -> Optional[HostInfo]: - return self._routed_host_info - - @routed_host_info.setter - def routed_host_info(self, value: Optional[HostInfo]) -> None: - self._routed_host_info = value - - def take_routed_host_info(self) -> Optional[HostInfo]: - routed = self._routed_host_info - self._routed_host_info = None - return routed - async def refresh_host_list( self, connection: Optional[Any] = None) -> None: @@ -975,6 +935,64 @@ async def get_host_role( timeout_sec=timeout_sec, ) + async def fill_aliases( + self, + connection: Optional[Any] = None, + host_info: Optional[HostInfo] = None) -> None: + """Populate ``host_info``'s aliases -- port of sync + ``PluginServiceImpl.fill_aliases`` (plugin_service.py:671-706). + + Adds the ``host:port`` alias, then any aliases the database reports via + ``host_alias_query``, then the aliases of the host that + :meth:`identify_connection` resolves the connection to. No-op when the + host already carries aliases (idempotent). + """ + connection = self._current_connection if connection is None else connection + host_info = self.current_host_info if host_info is None else host_info + if connection is None or host_info is None: + return + + if len(host_info.aliases) > 0: + logger.debug("PluginServiceImpl.NonEmptyAliases", host_info.aliases) + return + + host_info.add_alias(host_info.as_alias()) + + aux_timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get_float( + self._props) + try: + await asyncio.wait_for( + self._fill_aliases_from_query(connection, host_info), + timeout=aux_timeout_sec) + except asyncio.TimeoutError as e: + from aws_advanced_python_wrapper.errors import QueryTimeoutError + raise QueryTimeoutError( + Messages.get("PluginServiceImpl.FillAliasesTimeout")) from e + except Exception as e: # noqa: BLE001 - alias query is best-effort + logger.debug("PluginServiceImpl.FailedToRetrieveHostPort", e) + + host = await self.identify_connection(connection) + if host: + host_info.add_alias(*host.as_aliases()) + + async def _fill_aliases_from_query( + self, connection: Any, host_info: HostInfo) -> None: + dialect = self._database_dialect + if dialect is None: + return + from aws_advanced_python_wrapper.database_dialect import \ + UnknownDatabaseDialect + if isinstance(dialect, UnknownDatabaseDialect): + return + alias_query = dialect.host_alias_query + if not alias_query: + return + async with connection.cursor() as cur: + await cur.execute(alias_query) + for row in await cur.fetchall(): + if row: + host_info.add_alias(row[0]) + async def connect( self, host_info: HostInfo, @@ -993,9 +1011,6 @@ async def connect( "AsyncPluginService.connect requires target_driver_func " "to be set; AsyncAwsWrapperConnection.connect normally " "wires this.") - # The routed host belongs to one connect. Clearing it here stops this - # connect's plugins reading the host a previous one landed on. - self._routed_host_info = None return await self._plugin_manager.connect( target_driver_func=self._target_driver_func, driver_dialect=self._driver_dialect, @@ -1032,7 +1047,6 @@ async def force_connect( raise AwsWrapperError( "AsyncPluginService.force_connect requires target_driver_func " "to be set; AsyncAwsWrapperConnection.connect normally wires this.") - self._routed_host_info = None return await self._plugin_manager.force_connect( target_driver_func=self._target_driver_func, driver_dialect=self._driver_dialect, @@ -1080,11 +1094,6 @@ async def set_current_connection( self, connection: Any, host_info: HostInfo) -> None: - # Whoever set a routed host has been superseded by this call, which - # names the host the connection is on. Switches that reuse a cached - # connection never run a connect, so this is the only place that - # clears the field for them. - self._routed_host_info = None prev = self._current_connection if prev is None: diff --git a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py index 96145ed75..d67c5dbd6 100644 --- a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py @@ -32,7 +32,6 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostRole -from aws_advanced_python_wrapper.pep249 import Error from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages @@ -454,16 +453,8 @@ async def _switch_to_reader_impl( for _ in range(2 * len(reader_candidates)): if not remaining: break - try: - reader = self._plugin_service.get_host_info_by_strategy( - HostRole.READER, strategy, remaining) - except Error: - # Every reader is currently marked unavailable. Stop here so - # the caller reports that no reader was available, rather than - # surfacing a host-selector error to the application. Error, - # not AwsWrapperError: the default random selector raises the - # base class, which AwsWrapperError is a subclass of. - break + reader = self._plugin_service.get_host_info_by_strategy( + HostRole.READER, strategy, remaining) if reader is None: break try: diff --git a/aws_advanced_python_wrapper/aio/retry_util.py b/aws_advanced_python_wrapper/aio/retry_util.py index cb6bb63a3..8fe668deb 100644 --- a/aws_advanced_python_wrapper/aio/retry_util.py +++ b/aws_advanced_python_wrapper/aio/retry_util.py @@ -128,11 +128,11 @@ async def get_writer_connection( new_conn = await self._bounded( connect_func(writer), timeout_end_time) except Exception as e: # noqa: BLE001 - plugin_service.set_availability(writer, HostAvailability.UNAVAILABLE) + plugin_service.set_availability(writer.as_aliases(), HostAvailability.UNAVAILABLE) last_error = e else: # Connected -> the host is reachable. - plugin_service.set_availability(writer, HostAvailability.AVAILABLE) + plugin_service.set_availability(writer.as_aliases(), HostAvailability.AVAILABLE) # Roles in the topology may be stale right after a failover # (the demoted old writer can still be labeled WRITER), so # verify with a data-plane query before accepting. @@ -222,9 +222,11 @@ async def _refresh_topology_via_reader( reader_conn = await self._bounded( connect_func(reader), timeout_end_time) except Exception: # noqa: BLE001 - try the next reader - plugin_service.set_availability(reader, HostAvailability.UNAVAILABLE) + plugin_service.set_availability( + reader.as_aliases(), HostAvailability.UNAVAILABLE) continue - plugin_service.set_availability(reader, HostAvailability.AVAILABLE) + plugin_service.set_availability( + reader.as_aliases(), HostAvailability.AVAILABLE) try: refreshed = await self._bounded( host_list_provider.force_refresh(reader_conn), timeout_end_time) diff --git a/aws_advanced_python_wrapper/aio/topology_store.py b/aws_advanced_python_wrapper/aio/topology_store.py deleted file mode 100644 index 3c85f8ee7..000000000 --- a/aws_advanced_python_wrapper/aio/topology_store.py +++ /dev/null @@ -1,112 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""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 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.copy(host) for host in stored) - - -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 deleted file mode 100644 index 7afa0c157..000000000 --- a/aws_advanced_python_wrapper/aio/topology_utils.py +++ /dev/null @@ -1,448 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""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.host_availability import \ - create_host_availability_strategy -from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole, Topology -from aws_advanced_python_wrapper.utils.log import Logger -from aws_advanced_python_wrapper.utils.messages import Messages -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() - # One strategy for every host these utils produce, as the synchronous - # provider does, so the backoff window is per cluster. - self._host_availability_strategy = create_host_availability_strategy(props) - - self.initial_host_info: HostInfo = HostInfo( - host=str(props.get("host", "")), - port=self._port_from_props(default_port), - host_availability_strategy=self._host_availability_strategy) - 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_availability_strategy=self._host_availability_strategy) - 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_availability_strategy=self._host_availability_strategy) - 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_availability_strategy=self._host_availability_strategy) - 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/aio/wrapper.py b/aws_advanced_python_wrapper/aio/wrapper.py index ac6fba60d..4ec42b833 100644 --- a/aws_advanced_python_wrapper/aio/wrapper.py +++ b/aws_advanced_python_wrapper/aio/wrapper.py @@ -1002,11 +1002,7 @@ async def _monitor_conn_factory() -> Any: except Exception: # noqa: BLE001 - best-effort txn cleanup pass - # A plugin may have routed the connect elsewhere; that is the host this - # connection is actually on. - routed = plugin_service.take_routed_host_info() - await plugin_service.set_current_connection( - target_conn, routed if routed is not None else host_info) + await plugin_service.set_current_connection(target_conn, host_info) return AsyncAwsWrapperConnection(plugin_service, plugin_manager) def cursor(self, *args: Any, **kwargs: Any) -> AsyncAwsWrapperCursor: diff --git a/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py b/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py index 80453d982..012f88fd6 100644 --- a/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py +++ b/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py @@ -17,8 +17,8 @@ import threading from threading import Thread from time import perf_counter_ns -from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, Optional, - Set, Tuple) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, FrozenSet, + Optional, Set) from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.utils import Utils @@ -29,6 +29,7 @@ from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.pep249 import Connection + from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType from aws_advanced_python_wrapper.utils.properties import Properties from _weakrefset import WeakSet @@ -112,83 +113,87 @@ def _prune_connections(cls): if not conn_set and host in cls._opened_connections: del cls._opened_connections[host] - def _tracking_keys(self, host_info: HostInfo) -> Tuple[str, ...]: - """The keys ``host_info``'s connections are tracked under. - - An instance endpoint names the instance already, so one key is enough. - Anything else may be a custom domain name, which is tracked both under - the host id and under the endpoint the caller used. - """ - if self._rds_utils.is_rds_instance(host_info.host): - return (host_info.get_host_and_port(),) - return tuple(key for key in (host_info.host_id, host_info.get_host_and_port()) if key) - - def populate_opened_connection_set(self, host_info: Optional[HostInfo], conn: Optional[Connection]): + def populate_opened_connection_set(self, host_info: HostInfo, conn: Connection): """ Add the given connection to the set of tracked connections. :param host_info: host information of the given connection. :param conn: currently opened connection. """ - if host_info is None or conn is None: + + aliases: FrozenSet[str] = host_info.as_aliases() + + if self._rds_utils.is_rds_instance(host_info.host): + self._track_connection(host_info.url, conn) return - keys = self._tracking_keys(host_info) - if not keys: + instance_endpoint: Optional[str] = next( + (alias for alias in aliases if self._rds_utils.is_rds_instance(self._rds_utils.remove_port(alias))), None) + if not instance_endpoint: logger.debug("OpenedConnectionTracker.UnableToPopulateOpenedConnectionSet") return - for key in keys: - self._track_connection(key, conn) + instance_endpoint = instance_endpoint if instance_endpoint.endswith("/") else instance_endpoint + "/" + self._track_connection(instance_endpoint, conn) - def invalidate_all_connections(self, host_info: Optional[HostInfo]): + def invalidate_all_connections(self, host_info: Optional[HostInfo] = None, host: Optional[FrozenSet[str]] = None): """ Invalidates all opened connections pointing to the same host in a daemon thread. - :param host_info: the host whose connections should be closed. + :param host_info: the :py:class:`HostInfo` object containing the URL of the host. + :param host: the set of aliases representing a specific host. """ - if host_info is None: + + if host_info: + self.invalidate_all_connections(host=frozenset([host_info.url])) + self.invalidate_all_connections(host=host_info.as_aliases()) return - self.invalidate_all_connections_for_keys( - host_info.get_host_and_port(), host_info.host, host_info.host_id) - def invalidate_all_connections_for_keys(self, *keys: Optional[str]): - """Invalidate the connections tracked under any of ``keys``. + instance_endpoint: Optional[str] = None + if host is None: + return - A connection tracked under more than one key is closed once: closing - a pool-proxied connection twice would invalidate whatever the pool - handed out in between. - """ - present = [key for key in keys if key] - seen: Set[int] = set() - to_close: list = [] + for instance in host: + if instance is not None and self._rds_utils.is_rds_instance(self._rds_utils.remove_port(instance)): + instance_endpoint = instance + break + + if not instance_endpoint: + return + + instance_endpoint = instance_endpoint if instance_endpoint.endswith("/") else instance_endpoint + "/" with self._lock: - for key in present: - connection_set: Optional[WeakSet] = self._opened_connections.get(key) - if connection_set is None: - continue - for conn in list(connection_set): - if id(conn) not in seen: - seen.add(id(conn)) - to_close.append(conn) + connection_set: Optional[WeakSet] = self._opened_connections.get(instance_endpoint) + if connection_set is not None: + connections_list = list(connection_set) connection_set.clear() + else: + connections_list = None - if to_close: - self._log_connection_set(", ".join(present), to_close) - self._invalidate_connections(to_close) + if connections_list: + self._log_connection_set(instance_endpoint, connections_list) + self._invalidate_connections(connections_list) def remove_connection_tracking(self, host_info: HostInfo, connection: Connection | None): if not connection: return - # Every key populate_opened_connection_set used, so a custom-domain - # connection is untracked from both of its keys. + if self._rds_utils.is_rds_instance(host_info.host): + host = host_info.url + else: + host = next((alias for alias in host_info.as_aliases() + if self._rds_utils.is_rds_instance(self._rds_utils.remove_port(alias))), "") + + if not host: + return + + host = host if host.endswith("/") else host + "/" + with self._lock: - for key in self._tracking_keys(host_info): - connection_set = self._opened_connections.get(key) - if connection_set: - connection_set.discard(connection) + connection_set = self._opened_connections.get(host) + if connection_set: + connection_set.discard(connection) def _track_connection(self, instance_endpoint: str, conn: Connection): with self._lock: @@ -287,23 +292,12 @@ def connect( conn = connect_func() if conn: - routed = self._plugin_service.routed_host_info - connection_host_info = routed if routed is not None else host_info - url_type = self._rds_utils.identify_rds_type(connection_host_info.host) - if Utils.requires_host_identification(url_type): - # The endpoint does not name the instance the connection - # landed on, so ask the database and track that instead. - # Best-effort: a connect must not fail because the host id - # query did. - try: - identified = self._plugin_service.identify_connection(conn) - except Exception: # noqa: BLE001 - identification is best-effort - identified = None - if identified is not None: - connection_host_info = identified - self._plugin_service.routed_host_info = identified - - self._tracker.populate_opened_connection_set(connection_host_info, conn) + url_type: RdsUrlType = self._rds_utils.identify_rds_type(host_info.host) + if url_type.is_rds_cluster: + host_info.reset_aliases() + self._plugin_service.fill_aliases(conn, host_info) + + self._tracker.populate_opened_connection_set(host_info, conn) self._tracker.log_opened_connections() return conn @@ -365,11 +359,10 @@ def _check_writer_changed(self, need_refresh_host_lists: bool): self._need_update_current_writer = False def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): - for host, host_changes in changes.items(): - if HostEvent.CONVERTED_TO_READER in host_changes: - # Change keys are urls; tracking keys are not. - self._tracker.invalidate_all_connections_for_keys(host.rstrip("/")) - if HostEvent.CONVERTED_TO_WRITER in host_changes: + for node, node_changes in changes.items(): + if HostEvent.CONVERTED_TO_READER in node_changes: + self._tracker.invalidate_all_connections(host=frozenset([node])) + if HostEvent.CONVERTED_TO_WRITER in node_changes: self._need_update_current_writer = True diff --git a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py index 2dd6e4023..8eae5cf7b 100644 --- a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py @@ -108,6 +108,7 @@ class AuroraInitialConnectionStrategyPlugin(Plugin): def __init__(self, plugin_service: PluginService, props: Properties): self._plugin_service: PluginService = plugin_service self._rds_utils = RdsUtils() + self._host_list_provider_service: Optional[HostListProviderService] = None self._accessible_regions: Optional[FrozenSet[str]] = AccessibleRegions.parse(props) self._retry_delay_ms: int = WrapperProperties.OPEN_CONNECTION_RETRY_INTERVAL_MS.get_int(props) @@ -137,6 +138,7 @@ def init_host_provider( props: Properties, host_list_provider_service: HostListProviderService, init_host_provider_func: Callable): + self._host_list_provider_service = host_list_provider_service init_host_provider_func() def connect( @@ -170,13 +172,13 @@ def connect( if role_to_verify is None: # No verification required. - self._plugin_service.routed_host_info = candidate_host + self._set_initial_connection_host_info(is_initial_connection, candidate_host) return candidate_conn conn_role = self._plugin_service.get_host_role(candidate_conn) if conn_role == role_to_verify: # Verification succeeded. - self._plugin_service.routed_host_info = candidate_host + self._set_initial_connection_host_info(is_initial_connection, candidate_host) return candidate_conn # Verification failed. Retry, unless a reader was requested but the cluster has no readers. @@ -188,7 +190,7 @@ def connect( logger.debug( "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._plugin_service.routed_host_info = candidate_host + self._set_initial_connection_host_info(is_initial_connection, candidate_host) return candidate_conn logger.debug( @@ -202,7 +204,7 @@ def connect( if candidate_host is not None: self._plugin_service.set_availability( - candidate_host, HostAvailability.UNAVAILABLE) + candidate_host.as_aliases(), HostAvailability.UNAVAILABLE) if self._plugin_service.is_network_exception(e): # Retry connection. @@ -485,6 +487,13 @@ def _get_candidate_host( # Unable to find a candidate host. return None + def _set_initial_connection_host_info( + self, is_initial_connection: bool, host_info: Optional[HostInfo]): + if (is_initial_connection + and self._host_list_provider_service is not None + and host_info is not None): + self._host_list_provider_service.initial_connection_host_info = host_info + @staticmethod def _find_writer(hosts: Sequence[HostInfo]) -> Optional[HostInfo]: """Return the first WRITER in ``hosts``, or ``None``. diff --git a/aws_advanced_python_wrapper/aws_credentials_manager.py b/aws_advanced_python_wrapper/aws_credentials_manager.py index 36b6ef35a..bee5499d0 100644 --- a/aws_advanced_python_wrapper/aws_credentials_manager.py +++ b/aws_advanced_python_wrapper/aws_credentials_manager.py @@ -34,7 +34,7 @@ class AwsCredentialsManager: @staticmethod def get_session(host_info: HostInfo, props: Properties, region: Optional[str] = None) -> Session: profile_name = WrapperProperties.AWS_PROFILE.get(props) - host_key = f'{host_info.get_host_and_port()}{region}{profile_name}' + host_key = f'{host_info.as_alias()}{region}{profile_name}' with AwsCredentialsManager._lock: if host_key in AwsCredentialsManager._sessions: diff --git a/aws_advanced_python_wrapper/blue_green_plugin.py b/aws_advanced_python_wrapper/blue_green_plugin.py index 19adb9d56..3e65d3a1a 100644 --- a/aws_advanced_python_wrapper/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/blue_green_plugin.py @@ -401,6 +401,7 @@ def apply( rerouted_host_info = copy(self._substitute_host_info) rerouted_host_info.host_id = iam_host.host_id rerouted_host_info.availability = HostAvailability.AVAILABLE + rerouted_host_info.add_alias(iam_host.host) rerouted_props = copy(props) WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host) diff --git a/aws_advanced_python_wrapper/cluster_topology_monitor.py b/aws_advanced_python_wrapper/cluster_topology_monitor.py index ae3df67ab..b125a0664 100644 --- a/aws_advanced_python_wrapper/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/cluster_topology_monitor.py @@ -217,10 +217,7 @@ def _wait_till_topology_gets_updated(self, timeout_sec: float) -> Topology: self._cluster_id, timeout_sec * 1000)) def _get_stored_hosts(self) -> Topology: - # 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) + hosts = services_container.get_storage_service().get(Topology, self._cluster_id) if hosts is None: return () return hosts diff --git a/aws_advanced_python_wrapper/database_dialect.py b/aws_advanced_python_wrapper/database_dialect.py index c944be62a..4c092c507 100644 --- a/aws_advanced_python_wrapper/database_dialect.py +++ b/aws_advanced_python_wrapper/database_dialect.py @@ -135,6 +135,11 @@ class DatabaseDialect(Protocol): def default_port(self) -> int: ... + @property + @abstractmethod + def host_alias_query(self) -> str: + ... + @property @abstractmethod def server_version_query(self) -> str: @@ -212,6 +217,10 @@ class MysqlDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return 3306 + @property + def host_alias_query(self) -> str: + return f"SELECT {self._HOST_ID_EXPRESSION}" + @property def server_version_query(self) -> str: return "SHOW VARIABLES LIKE 'version_comment'" @@ -270,6 +279,10 @@ class PgDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return 5432 + @property + def host_alias_query(self) -> str: + return f"SELECT {self._HOST_ID_EXPRESSION}" + @property def server_version_query(self) -> str: return "SELECT 'version', pg_catalog.VERSION()" @@ -815,6 +828,10 @@ class UnknownDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return HostInfo.NO_PORT + @property + def host_alias_query(self) -> str: + return "" + @property def server_version_query(self) -> str: return "" @@ -1081,16 +1098,7 @@ def get_instance_id(conn: Connection, driver_dialect: DriverDialect, instance_id thread_pool, timeout_sec: float) -> Optional[Tuple[str, str]]: cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( thread_pool, timeout_sec, driver_dialect, conn)(DialectUtils._execute_instance_id_query) - try: - result = cursor_execute_func_with_timeout(conn, instance_id_query) - except TimeoutError: - # A timeout is transient, so it stays an error the caller can see. - raise - except Exception: # noqa: BLE001 - see below - # A host whose id the database declines to report is simply - # unidentifiable, which every caller handles. Raising instead - # would fail a connect over a host the caller never needed named. - return None + result = cursor_execute_func_with_timeout(conn, instance_id_query) if result is not None and len(result) >= 2: return (str(result[0]), str(result[1])) diff --git a/aws_advanced_python_wrapper/default_plugin.py b/aws_advanced_python_wrapper/default_plugin.py index 48fbd0b8e..3d0a92fd3 100644 --- a/aws_advanced_python_wrapper/default_plugin.py +++ b/aws_advanced_python_wrapper/default_plugin.py @@ -77,7 +77,7 @@ def _connect( if context is not None: context.close_context() - self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host_info.all_aliases, HostAvailability.AVAILABLE) self._plugin_service.update_driver_dialect(conn_provider) self._plugin_service.update_dialect(conn) diff --git a/aws_advanced_python_wrapper/failover_plugin.py b/aws_advanced_python_wrapper/failover_plugin.py index ef9e1a093..b212f5182 100644 --- a/aws_advanced_python_wrapper/failover_plugin.py +++ b/aws_advanced_python_wrapper/failover_plugin.py @@ -172,7 +172,7 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args: self._invalidate_current_connection() if self._plugin_service.current_host_info is not None: self._plugin_service.set_availability( - self._plugin_service.current_host_info, HostAvailability.UNAVAILABLE) + self._plugin_service.current_host_info.aliases, HostAvailability.UNAVAILABLE) self._pick_new_connection() self._last_exception = ex @@ -202,6 +202,10 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): if self._is_host_still_valid(current_host.url, changes): return + for alias in current_host.aliases: + if self._is_host_still_valid(alias + '/', changes): + return + logger.debug("FailoverPlugin.InvalidHost", current_host) finally: self._stale_dns_helper.notify_host_list_changed(changes) @@ -243,7 +247,7 @@ def _failover(self, failed_host: Optional[HostInfo]): :param failed_host: The host with network errors. """ if failed_host is not None: - self._plugin_service.set_availability(failed_host, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(failed_host.as_aliases(), HostAvailability.UNAVAILABLE) if self._failover_mode == FailoverMode.STRICT_WRITER: self._failover_writer() @@ -270,6 +274,10 @@ def _failover_reader(self, failed_host: Optional[HostInfo]): try: logger.info("FailoverPlugin.StartReaderFailover") + old_aliases = None + if self._plugin_service.current_host_info is not None: + old_aliases = self._plugin_service.current_host_info.aliases + if failed_host is not None and failed_host.get_raw_availability() != HostAvailability.AVAILABLE: failed_host = None @@ -284,6 +292,9 @@ def _failover_reader(self, failed_host: Optional[HostInfo]): if result.connection is not None and result.new_host is not None: self._plugin_service.set_current_connection(result.connection, result.new_host) + if self._plugin_service.current_host_info is not None and old_aliases is not None and len(old_aliases) > 0: + self._plugin_service.current_host_info.remove_alias(old_aliases) + self._update_topology(True) logger.info("FailoverPlugin.EstablishedConnection", self._plugin_service.current_host_info) diff --git a/aws_advanced_python_wrapper/failover_v2_plugin.py b/aws_advanced_python_wrapper/failover_v2_plugin.py index 73d8cdead..ba6d85633 100644 --- a/aws_advanced_python_wrapper/failover_v2_plugin.py +++ b/aws_advanced_python_wrapper/failover_v2_plugin.py @@ -157,7 +157,7 @@ def connect( if not self._should_exception_trigger_connection_switch(e): raise e - self._plugin_service.set_availability(host_info, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(host_info.as_aliases(), HostAvailability.UNAVAILABLE) try: self._failover() @@ -199,7 +199,7 @@ def _deal_with_original_exception(self, original_exception: Exception) -> NoRetu (self._should_exception_trigger_connection_switch(original_exception))): self._invalidate_current_connection() self._plugin_service.set_availability( - self._plugin_service.current_host_info, HostAvailability.UNAVAILABLE) + self._plugin_service.current_host_info.as_aliases(), HostAvailability.UNAVAILABLE) self._pick_new_connection() self._last_exception_dealt_with = original_exception diff --git a/aws_advanced_python_wrapper/host_list_provider.py b/aws_advanced_python_wrapper/host_list_provider.py index da0bef9f9..8d6164ca5 100644 --- a/aws_advanced_python_wrapper/host_list_provider.py +++ b/aws_advanced_python_wrapper/host_list_provider.py @@ -18,7 +18,6 @@ from abc import ABC, abstractmethod from concurrent.futures import TimeoutError from contextlib import closing -from copy import copy from dataclasses import dataclass from datetime import datetime from threading import RLock @@ -221,7 +220,7 @@ def _get_topology(self, conn: Optional[Connection], force_update: bool = False) if not conn: # Cannot fetch topology without a connection # Return the original hosts passed to the connect method - return RdsHostListProvider.FetchTopologyResult(self._copy_initial_hosts(), False) + return RdsHostListProvider.FetchTopologyResult(self._initial_hosts, False) hosts = self._force_refresh_monitor(False, self._DEFAULT_TOPOLOGY_QUERY_TIMEOUT_SEC) if hosts is not None and len(hosts) > 0: @@ -230,17 +229,7 @@ def _get_topology(self, conn: Optional[Connection], force_update: bool = False) if cached_hosts: return RdsHostListProvider.FetchTopologyResult(cached_hosts, True) else: - return RdsHostListProvider.FetchTopologyResult(self._copy_initial_hosts(), False) - - def _copy_initial_hosts(self) -> Topology: - """Copies, because the caller publishes these as the host list. - - These are built once and never replaced, so marking a host handed out - here would mark it for every later caller. Hosts from a topology query - are replaced by each refresh, so they are left shared, which is what - makes an availability mark visible across connections. - """ - return tuple(copy(host) for host in self._initial_hosts) + return RdsHostListProvider.FetchTopologyResult(self._initial_hosts, False) def _get_or_create_monitor(self) -> Optional[ClusterTopologyMonitor]: """Get or create monitor - matches Java's getOrCreateMonitor""" @@ -364,16 +353,11 @@ def _initialize(self): def refresh(self, connection: Optional[Connection] = None) -> Topology: self._initialize() - return self._copy_hosts() + return tuple(self._hosts) def force_refresh(self, connection: Optional[Connection] = None) -> Topology: self._initialize() - return self._copy_hosts() - - def _copy_hosts(self) -> Topology: - """Copies, for the same reason as ``RdsHostListProvider``: this host - list is built once.""" - return tuple(copy(host) for host in self._hosts) + return tuple(self._hosts) def get_current_topology(self, connection: Connection, initial_host_info: HostInfo) -> Topology: self._initialize() @@ -569,6 +553,7 @@ def create_host( role=HostRole.WRITER if is_writer else HostRole.READER, last_update_time=last_update, host_id=host_id) + host_info.add_alias(host_id) return host_info def get_writer_id_if_connected(self, connection: Connection, driver_dialect: DriverDialect) -> Optional[str]: @@ -711,10 +696,9 @@ def _create_multi_az_host(self, record: Tuple, writer_id: str) -> HostInfo: if host.find(":") > -1: host, port = host.split(":") - # MySQL reports a numeric id. host_id is compared against the string - # host_id_query returns, so store it as a string. host_info = HostInfo( - host=host, port=port, role=role, availability=HostAvailability.AVAILABLE, weight=0, host_id=str(id)) + host=host, port=port, role=role, availability=HostAvailability.AVAILABLE, weight=0, host_id=id) + host_info.add_alias(host) return host_info diff --git a/aws_advanced_python_wrapper/host_monitoring_plugin.py b/aws_advanced_python_wrapper/host_monitoring_plugin.py index c3c7aabc3..1cab52b05 100644 --- a/aws_advanced_python_wrapper/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/host_monitoring_plugin.py @@ -27,7 +27,7 @@ from queue import Queue from threading import Event, Lock, Thread from time import perf_counter_ns -from typing import Any, Callable, Dict, Optional, Set +from typing import Any, Callable, Dict, FrozenSet, Optional, Set from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_availability import HostAvailability @@ -47,7 +47,7 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import ( TelemetryCounter, TelemetryTraceLevel) -from aws_advanced_python_wrapper.utils.utils import QueueUtils, Utils +from aws_advanced_python_wrapper.utils.utils import QueueUtils logger = Logger(__name__) @@ -98,23 +98,12 @@ def connect( connect_func: Callable) -> Connection: conn = connect_func() if conn: - self._record_routed_host(host_info, conn) + rds_type = self._rds_utils.identify_rds_type(host_info.host) + if rds_type.is_rds_cluster: + host_info.reset_aliases() + self._plugin_service.fill_aliases(conn, host_info) return conn - def _record_routed_host(self, host_info: HostInfo, conn: Connection): - """Record which instance a cluster-endpoint connection landed on, since - the monitoring host is derived from it.""" - routed = self._plugin_service.routed_host_info - connection_host_info = routed if routed is not None else host_info - if not self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: - return - try: - identified = self._plugin_service.identify_connection(conn) - except Exception: # noqa: BLE001 - identification is best-effort - return - if identified is not None: - self._plugin_service.routed_host_info = identified - def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: connection = self._plugin_service.current_connection if connection is None: @@ -134,6 +123,7 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg logger.debug("HostMonitoringPlugin.ActivatedMonitoring", method_name) monitor_context = self._monitor_service.start_monitoring( connection, + self._get_monitoring_host_info().all_aliases, self._get_monitoring_host_info(), self._props, self._failure_detection_time_ms, @@ -145,23 +135,18 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg if monitor_context: with self._lock: self._monitor_service.stop_monitoring(monitor_context) - host_unavailable = monitor_context.is_host_unavailable() - - # Outside the lock: set_availability dispatches to every - # plugin, so holding it here would run arbitrary plugin code - # with this connection's monitoring serialised behind it. - if host_unavailable: - self._plugin_service.set_availability( - self._get_monitoring_host_info(), HostAvailability.UNAVAILABLE) - - driver_dialect = self._plugin_service.driver_dialect - if driver_dialect is not None and not driver_dialect.is_closed(connection): - try: - connection.close() - except Exception: - pass - raise AwsWrapperError( - Messages.get_formatted("HostMonitoringPlugin.UnavailableHost", host_info.get_host_and_port())) + if monitor_context.is_host_unavailable(): + self._plugin_service.set_availability( + self._get_monitoring_host_info().all_aliases, HostAvailability.UNAVAILABLE) + + driver_dialect = self._plugin_service.driver_dialect + if driver_dialect is not None and not driver_dialect.is_closed(connection): + try: + connection.close() + except Exception: + pass + raise AwsWrapperError( + Messages.get_formatted("HostMonitoringPlugin.UnavailableHost", host_info.as_alias())) logger.debug("HostMonitoringPlugin.MonitoringDeactivated", method_name) return result @@ -174,47 +159,44 @@ def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnect return OldConnectionSuggestedAction.NO_OPINION def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): - # Closing a connection drops this plugin's reference to the monitor - # service, and a failover worker outliving that close can still reach - # this plugin when it publishes availability. - if not self._is_connection_initialized or self._monitor_service is None: + if not self._is_connection_initialized: return for host, events in changes.items(): if HostEvent.WENT_DOWN not in events and HostEvent.HOST_DELETED not in events: - continue + return + + monitoring_aliases = self._get_monitoring_host_info().all_aliases + if len(monitoring_aliases) == 0: + return - if host == self._get_monitoring_host_info().url: - self._monitor_service.stop_monitoring_host(host) + if host in monitoring_aliases: + self._monitor_service.stop_monitoring_host(monitoring_aliases) def _get_monitoring_host_info(self) -> HostInfo: - # Held in a local because notify_connection_changed can clear the - # field while this method is between its assignment and its return. - monitoring_host_info = self._monitoring_host_info - if monitoring_host_info is None: - # current_host_info, not routed_host_info: by the time any - # connection exists the wrapper has adopted the routed host, and - # a value still in that field belongs to a connect in flight, - # possibly another thread's. - monitoring_host_info = self._plugin_service.current_host_info - if monitoring_host_info is None: + if self._monitoring_host_info is None: + current_host_info = self._plugin_service.current_host_info + if current_host_info is None: raise AwsWrapperError("HostMonitoringPlugin.HostInfoNone") - self._monitoring_host_info = monitoring_host_info - rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) + self._monitoring_host_info = current_host_info + rds_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) try: - if Utils.requires_host_identification(rds_url_type): + if rds_type.is_rds_cluster: logger.debug("HostMonitoringPlugin.ClusterEndpointHostInfo") - identified = self._plugin_service.identify_connection( - self._plugin_service.current_connection) - if identified is not None: - monitoring_host_info = identified - self._monitoring_host_info = identified - except Exception as e: # noqa: BLE001 - the host id query failed - # Keep the connection's own host and monitor that. Raising - # here would fail every monitored call on the connection. - logger.debug("HostMonitoringPlugin.ErrorIdentifyingConnection", e) - return monitoring_host_info + self._monitoring_host_info = self._plugin_service.identify_connection() + if self._monitoring_host_info is None: + raise AwsWrapperError( + Messages.get_formatted( + "HostMonitoringPlugin.UnableToIdentifyConnection", + current_host_info.host, + self._plugin_service.host_list_provider)) + self._plugin_service.fill_aliases(host_info=self._monitoring_host_info) + except Exception as e: + message = "HostMonitoringPlugin.ErrorIdentifyingConnection" + logger.debug(message, e) + raise AwsWrapperError(Messages.get_formatted(message, e)) from e + return self._monitoring_host_info def release_resources(self): self._monitor_service = None @@ -602,7 +584,7 @@ def sleep(self, duration: int): class HostMonitorService: def __init__(self, plugin_service: PluginService): self._plugin_service: PluginService = plugin_service - self._cached_monitor_host_url: Optional[str] = None + self._cached_monitor_aliases: Optional[FrozenSet[str]] = None self._cached_monitor: Optional[ReferenceType[Monitor]] = None telemetry_factory = self._plugin_service.get_telemetry_factory() @@ -616,23 +598,26 @@ def __init__(self, plugin_service: PluginService): def start_monitoring(self, conn: Connection, + host_aliases: FrozenSet[str], host_info: HostInfo, props: Properties, failure_detection_time_ms: int, failure_detection_interval_ms: int, failure_detection_count: int) -> MonitoringContext: - host_url = host_info.url + if not host_aliases: + raise AwsWrapperError(Messages.get_formatted("MonitorService.EmptyAliasSet", host_info)) monitor: Optional[Monitor] = None if self._cached_monitor is None else self._cached_monitor() if monitor is None \ or monitor.is_stopped \ - or self._cached_monitor_host_url != host_url: - monitor = self._monitor_service.run_if_absent( + or self._cached_monitor_aliases is None \ + or self._cached_monitor_aliases != host_aliases: + monitor = self._monitor_service.run_if_absent_with_aliases( Monitor, - host_url, + host_aliases, lambda: Monitor(self._plugin_service, host_info, props)) self._cached_monitor = ref(monitor) - self._cached_monitor_host_url = host_url + self._cached_monitor_aliases = host_aliases context = MonitoringContext( monitor, conn, self._plugin_service.driver_dialect, failure_detection_time_ms, @@ -645,7 +630,9 @@ def stop_monitoring(context: MonitoringContext): monitor = context.monitor monitor.stop_monitoring(context) - def stop_monitoring_host(self, host_url: str): - monitor = self._monitor_service.get(Monitor, host_url) - if monitor is not None: - monitor.clear_contexts() + def stop_monitoring_host(self, host_aliases: FrozenSet): + for alias in host_aliases: + monitor = self._monitor_service.get(Monitor, alias) + if monitor is not None: + monitor.clear_contexts() + return diff --git a/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py b/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py index 3427add66..f0ac4fb9d 100644 --- a/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py +++ b/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py @@ -41,7 +41,6 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import ( TelemetryCounter, TelemetryFactory, TelemetryTraceLevel) -from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from aws_advanced_python_wrapper.driver_dialect import DriverDialect @@ -88,17 +87,10 @@ def connect( connect_func: Callable) -> Connection: connection = connect_func() if connection: - # Record which instance a cluster-endpoint connection landed on; - # the monitoring host is derived from it. - routed = self._plugin_service.routed_host_info - connection_host_info = routed if routed is not None else host_info - if self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: - try: - identified = self._plugin_service.identify_connection(connection) - except Exception: # noqa: BLE001 - identification is best-effort - identified = None - if identified is not None: - self._plugin_service.routed_host_info = identified + rds_type = self._rds_utils.identify_rds_type(host_info.host) + if rds_type.is_rds_cluster: + host_info.reset_aliases() + self._plugin_service.fill_aliases(connection, host_info) return connection def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: @@ -134,34 +126,34 @@ def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnect return OldConnectionSuggestedAction.NO_OPINION def _get_monitoring_host_info(self) -> HostInfo: - # Held in a local because notify_connection_changed can clear the - # field while this method is between its assignment and its return. - monitoring_host_info = self._monitoring_host_info - if monitoring_host_info is not None: - return monitoring_host_info - # current_host_info, not routed_host_info: by the time any connection - # exists the wrapper has adopted the routed host, and a value still in - # that field belongs to a connect in flight, possibly another thread's. - monitoring_host_info = self._plugin_service.current_host_info - if monitoring_host_info is None: + if self._monitoring_host_info is not None: + return self._monitoring_host_info + current_host_info = self._plugin_service.current_host_info + if current_host_info is None: raise AwsWrapperError(Messages.get("HostMonitoringV2Plugin.HostInfoNone")) - self._monitoring_host_info = monitoring_host_info - rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) + self._monitoring_host_info = current_host_info + rds_url_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) try: - if not Utils.requires_host_identification(rds_url_type): - return monitoring_host_info + if not rds_url_type.is_rds_cluster: + return self._monitoring_host_info logger.debug("HostMonitoringV2Plugin.ClusterEndpointHostInfo") - identified = self._plugin_service.identify_connection( - self._plugin_service.current_connection) - if identified is not None: - monitoring_host_info = identified - self._monitoring_host_info = identified - except Exception as e: # noqa: BLE001 - the host id query failed - # Keep the connection's own host and monitor that. Raising here - # would fail every monitored call on the connection. - logger.debug("HostMonitoringV2Plugin.ErrorIdentifyingConnection", e) - return monitoring_host_info + current_connection = self._plugin_service.current_connection + self._monitoring_host_info = self._plugin_service.identify_connection(current_connection) + if self._monitoring_host_info is None: + raise AwsWrapperError( + Messages.get_formatted( + "HostMonitoringV2Plugin.UnableToIdentifyConnection", + current_host_info.host, + self._plugin_service.host_list_provider)) + self._plugin_service.fill_aliases(current_connection, self._monitoring_host_info) + except Exception as e: + if isinstance(e, AwsWrapperError): + raise e + message = "HostMonitoringV2Plugin.ErrorIdentifyingConnection" + logger.debug(message, e) + raise AwsWrapperError(Messages.get_formatted(message, e)) from e + return self._monitoring_host_info def release_resources(self): if self._monitor_service is not None: @@ -341,7 +333,7 @@ def run(self) -> None: self._update_host_health_status(is_valid, status_check_start_time_ns, status_check_end_time_ns) if self._is_unhealthy: - self._plugin_service.set_availability(self._host_info, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(self._host_info.as_aliases(), HostAvailability.UNAVAILABLE) temp_active_context_weak_refs = [] while not self._active_contexts.empty(): diff --git a/aws_advanced_python_wrapper/hostinfo.py b/aws_advanced_python_wrapper/hostinfo.py index 3aa895de9..5c9893a9f 100644 --- a/aws_advanced_python_wrapper/hostinfo.py +++ b/aws_advanced_python_wrapper/hostinfo.py @@ -16,7 +16,8 @@ from dataclasses import dataclass from enum import Enum, auto -from typing import TYPE_CHECKING, ClassVar, Optional, Tuple, TypeAlias +from typing import (TYPE_CHECKING, ClassVar, FrozenSet, Optional, Set, Tuple, + TypeAlias) from aws_advanced_python_wrapper.host_availability import ( HostAvailability, HostAvailabilityStrategy) @@ -44,7 +45,7 @@ def __init__( port: int = NO_PORT, role: HostRole = HostRole.WRITER, availability: HostAvailability = HostAvailability.AVAILABLE, - host_availability_strategy: Optional[HostAvailabilityStrategy] = None, + host_availability_strategy=HostAvailabilityStrategy(), weight: int = DEFAULT_WEIGHT, host_id: Optional[str] = None, last_update_time: Optional[datetime] = None): @@ -52,15 +53,14 @@ def __init__( self.port = port self.role = role self.availability = availability - # A default argument is evaluated once, so every host that omitted it - # would share one strategy object. - self.host_availability_strategy = ( - host_availability_strategy if host_availability_strategy is not None - else HostAvailabilityStrategy()) + self.host_availability_strategy = host_availability_strategy self.weight = weight self.host_id = host_id self.last_update_time = last_update_time + self._aliases: Set[str] = set() + self._all_aliases: Set[str] = {self.as_alias()} + def __eq__(self, other: object): if self is object: return True @@ -84,9 +84,6 @@ def __copy__(self): port=self.port, role=self.role, availability=self.availability, - # Shared by reference, so the copy keeps the original's backoff - # count and retry window rather than starting a fresh one. - host_availability_strategy=self.host_availability_strategy, weight=self.weight, host_id=self.host_id, last_update_time=self.last_update_time @@ -94,13 +91,46 @@ def __copy__(self): @property def url(self): - # The trailing slash is part of the format: the availability cache, the - # notify_host_list_changed change map and the monitor keys all use it. - return f"{self.get_host_and_port()}/" + return f"{self.as_alias()}/" + + @property + def aliases(self) -> FrozenSet[str]: + return frozenset(self._aliases) + + @property + def all_aliases(self) -> FrozenSet[str]: + return frozenset(self._all_aliases) def get_host_and_port(self): return f"{self.host}:{self.port}" if self.is_port_specified() else self.host + def as_alias(self) -> str: + return self.get_host_and_port() + + def add_alias(self, *aliases: str): + if not aliases: + return + + for alias in aliases: + self._aliases.add(alias) + self._all_aliases.add(alias) + + def as_aliases(self) -> FrozenSet[str]: + return frozenset(self.all_aliases) + + def remove_alias(self, *kwargs): + if not kwargs or len(kwargs) == 0: + return + + for x in kwargs: + self._aliases.discard(x) + self._all_aliases.discard(x) + + def reset_aliases(self): + self._aliases.clear() + self._all_aliases.clear() + self._all_aliases.add(self.as_alias()) + def is_port_specified(self) -> bool: return self.port != HostInfo.NO_PORT diff --git a/aws_advanced_python_wrapper/limitless_plugin.py b/aws_advanced_python_wrapper/limitless_plugin.py index 2ef659dd7..0e47c1abc 100644 --- a/aws_advanced_python_wrapper/limitless_plugin.py +++ b/aws_advanced_python_wrapper/limitless_plugin.py @@ -102,11 +102,6 @@ def connect( self._limitless_router_service.establish_connection(self._context) connection = self._context.get_connection() if connection is not None and not self._plugin_service.driver_dialect.is_closed(connection): - # The connection is on a router, not on the shard group endpoint - # the caller named. - routed_host_info = self._context.get_connection_host_info() - if routed_host_info is not None: - self._plugin_service.routed_host_info = routed_host_info return connection raise AwsWrapperError(Messages.get_formatted("LimitlessPlugin.FailedToConnectToHost", host_info.host)) @@ -296,18 +291,10 @@ def __init__(self, self._connect_func = connect_func self._limitless_routers = limitless_routers self._connection_plugin = connection_plugin - self._connection_host_info: Optional[HostInfo] = None def get_host_info(self): return self._host_info - def get_connection_host_info(self) -> Optional[HostInfo]: - """The router the connection was actually opened against.""" - return self._connection_host_info - - def set_connection_host_info(self, host_info: HostInfo): - self._connection_host_info = host_info - def get_props(self): return self._props @@ -406,7 +393,6 @@ def establish_connection(self, context: LimitlessContext) -> None: try: context.set_connection(self._plugin_service.connect(selected_host_info, context.get_props(), context.get_connection_plugin())) - context.set_connection_host_info(selected_host_info) except Exception as e: if self._is_login_exception(e): raise e @@ -466,7 +452,6 @@ def _retry_connection_with_least_loaded_routers(self, context: LimitlessContext) try: context.set_connection(self._plugin_service.connect(selected_host_info, context.get_props(), context.get_connection_plugin())) if context.get_connection() is not None: - context.set_connection_host_info(selected_host_info) return except Exception as e: diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index deb3097e8..f6296d876 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -45,7 +45,9 @@ from abc import abstractmethod from concurrent.futures import TimeoutError -from typing import Any, Callable, Dict, Optional, Protocol, Set, Tuple +from contextlib import closing +from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, Set, + Tuple) from aws_advanced_python_wrapper.allowed_and_blocked_hosts import \ AllowedAndBlockedHosts @@ -58,7 +60,8 @@ from aws_advanced_python_wrapper.connection_provider import ( ConnectionProvider, ConnectionProviderManager) from aws_advanced_python_wrapper.database_dialect import ( - DatabaseDialect, DatabaseDialectManager, DialectUtils) + DatabaseDialect, DatabaseDialectManager, DialectUtils, + UnknownDatabaseDialect) from aws_advanced_python_wrapper.default_plugin import DefaultPlugin from aws_advanced_python_wrapper.developer_plugin import DeveloperPluginFactory from aws_advanced_python_wrapper.driver_configuration_profiles import \ @@ -91,6 +94,8 @@ SimpleReadWriteSplittingPluginFactory from aws_advanced_python_wrapper.stale_dns_plugin import StaleDnsPluginFactory from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.decorators import \ + preserve_transaction_status_with_timeout from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.notifications import ( @@ -170,30 +175,6 @@ def original_url(self) -> str: def initial_connection_host_info(self) -> Optional[HostInfo]: ... - @property - @abstractmethod - def routed_host_info(self) -> Optional[HostInfo]: - """The host a plugin routed the pending connect to, if any. - - A plugin that connects to a host other than the one it was asked for - records its choice here, and a plugin that wants to know where the - connect went should read it. Do not consume it: connect hooks unwind - from the innermost plugin outwards, so a plugin that took the value - would hide it from every plugin outside it and from the wrapper, which - is what adopts it as the current host. - """ - ... - - @routed_host_info.setter - @abstractmethod - def routed_host_info(self, value: Optional[HostInfo]): - ... - - @abstractmethod - def take_routed_host_info(self) -> Optional[HostInfo]: - """Return the routed host and clear it. For the wrapper's use.""" - ... - @property @abstractmethod def host_list_provider(self) -> HostListProvider: @@ -312,14 +293,13 @@ def force_connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: """ ... - def set_availability(self, host_info: HostInfo, availability: HostAvailability): - """Mark every host matching ``host_info`` by host id or host name.""" + def set_availability(self, host_aliases: FrozenSet[str], availability: HostAvailability): ... - def get_availability(self, host_url: str) -> Optional[HostAvailability]: + def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: ... - def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: + def fill_aliases(self, connection: Optional[Connection] = None, host_info: Optional[HostInfo] = None): ... def get_connection_provider_manager(self) -> ConnectionProviderManager: @@ -343,7 +323,6 @@ def get_status(self, clazz: Type[StatusType], key: str) -> Optional[StatusType]: class PluginServiceImpl(PluginService, HostListProviderService, CanReleaseResources): _STATUS_CACHE_EXPIRATION_NANO = 60 * 60 * 1_000_000_000 # one hour - _HOST_AVAILABILITY_EXPIRATION_NANO = 5 * 60 * 1_000_000_000 # five minutes _host_availability_expiring_cache: CacheMap[str, HostAvailability] = CacheMap() _executor_name: ClassVar[str] = "PluginServiceImplExecutor" @@ -366,7 +345,6 @@ def __init__( self._current_connection: Optional[Connection] = None self._current_host_info: Optional[HostInfo] = None self._initial_connection_host_info: Optional[HostInfo] = None - self._routed_host_info: Optional[HostInfo] = None self._exception_manager: ExceptionManager = ExceptionManager() self._is_in_transaction: bool = False self._dialect_provider = DatabaseDialectManager(props) @@ -416,11 +394,6 @@ def current_connection(self) -> Optional[Connection]: return self._current_connection def set_current_connection(self, connection: Optional[Connection], host_info: Optional[HostInfo]): - # Whoever set a routed host has been superseded by this call, which - # names the host the connection is on. Switches that reuse a cached - # connection never run a connect, so this is the only place that - # clears the field for them. - self._routed_host_info = None old_connection = self._current_connection if self._current_connection is None: @@ -516,19 +489,6 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: HostInfo): self._initial_connection_host_info = value - @property - def routed_host_info(self) -> Optional[HostInfo]: - return self._routed_host_info - - @routed_host_info.setter - def routed_host_info(self, value: Optional[HostInfo]): - self._routed_host_info = value - - def take_routed_host_info(self) -> Optional[HostInfo]: - routed = self._routed_host_info - self._routed_host_info = None - return routed - @property def host_list_provider(self) -> HostListProvider: return self._host_list_provider @@ -648,43 +608,17 @@ def force_monitoring_refresh_host_list(self, should_verify_writer: bool, timeout def connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: Optional[Plugin] = None) -> Connection: plugin_manager: PluginManager = self._container.plugin_manager - # The routed host belongs to one connect. Clearing it here stops this - # connect's plugins reading the host a previous one landed on. - self._routed_host_info = None return plugin_manager.connect( self._target_func, self._driver_dialect, host_info, props, self.current_connection is None, plugin_to_skip) def force_connect( self, host_info: HostInfo, props: Properties, plugin_to_skip: Optional[Plugin] = None) -> Connection: plugin_manager: PluginManager = self._container.plugin_manager - self._routed_host_info = None return plugin_manager.force_connect( self._target_func, self._driver_dialect, host_info, props, self.current_connection is None, plugin_to_skip) - def set_availability(self, host_info: HostInfo, availability: HostAvailability): - hosts_to_change = [ - host for host in self.all_hosts if Utils.matches_host(host_info, host)] - if not hosts_to_change: - return - - changes: Dict[str, Set[HostEvent]] = {} - for host in hosts_to_change: - # Through the strategy, not the raw field: a host whose backoff - # window has elapsed reads as available again, and marking it down - # is a change the plugins should hear about. - previous = host.get_availability() - host.set_availability(availability) - self._host_availability_expiring_cache.put( - host.url, availability, PluginServiceImpl._HOST_AVAILABILITY_EXPIRATION_NANO) - if previous != availability: - event = HostEvent.WENT_UP if availability == HostAvailability.AVAILABLE else HostEvent.WENT_DOWN - changes[host.url] = {event, HostEvent.HOST_CHANGED} - - if changes: - self._container.plugin_manager.notify_host_list_changed(changes) - - def get_availability(self, host_url: str) -> Optional[HostAvailability]: - return PluginServiceImpl._host_availability_expiring_cache.get(host_url) + def set_availability(self, host_aliases: FrozenSet[str], availability: HostAvailability): + ... def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: connection = self.current_connection if connection is None else connection @@ -701,10 +635,7 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option timeout_sec) if instance_ids is None: - # Not an error: the connect hooks that identify a host call - # this, and a host whose id the database does not report is - # simply unidentifiable, not a failed connect. - return None + raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) topology = self.host_list_provider.refresh(connection) is_force_refresh = False @@ -715,14 +646,19 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option if topology is None: return None - found_host: Optional[HostInfo] = Utils.find_host(topology, *instance_ids) + instance_name = instance_ids[1] + found_host: Optional[HostInfo] = next( + (host for host in topology if host.host_id == instance_name), + None) if found_host is None and not is_force_refresh: topology = self.host_list_provider.force_refresh(connection) if topology is None: return None - found_host = Utils.find_host(topology, *instance_ids) + found_host = next( + (host for host in topology if host.host_id == instance_name), + None) return found_host except TimeoutError as e: @@ -732,6 +668,43 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option except Exception as e: raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) from e + def fill_aliases(self, connection: Optional[Connection] = None, host_info: Optional[HostInfo] = None): + connection = self.current_connection if connection is None else connection + host_info = self.current_host_info if host_info is None else host_info + if connection is None or host_info is None: + return + + if len(host_info.aliases) > 0: + logger.debug("PluginServiceImpl.NonEmptyAliases", host_info.aliases) + return + + host_info.add_alias(host_info.as_alias()) + + driver_dialect = self._driver_dialect + try: + timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get(self._props) + cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( + self._thread_pool, timeout_sec, driver_dialect, connection)(self._fill_aliases) + cursor_execute_func_with_timeout(connection, host_info) + except TimeoutError as e: + raise QueryTimeoutError(Messages.get("PluginServiceImpl.FillAliasesTimeout")) from e + except Exception as e: + # log and ignore + logger.debug("PluginServiceImpl.FailedToRetrieveHostPort", e) + + host = self.identify_connection(connection) + if host: + host_info.add_alias(*host.as_aliases()) + + def _fill_aliases(self, conn: Connection, host_info: HostInfo) -> bool: + with closing(conn.cursor()) as cursor: + if not isinstance(self.database_dialect, UnknownDatabaseDialect): + cursor.execute(self.database_dialect.host_alias_query) + for row in cursor.fetchall(): + host_info.add_alias(row[0]) + return True + return False + def is_static_host_list_provider(self) -> bool: return self._host_list_provider is StaticHostListProvider diff --git a/aws_advanced_python_wrapper/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/read_write_splitting_plugin.py index c55fdff02..23bd01742 100644 --- a/aws_advanced_python_wrapper/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/read_write_splitting_plugin.py @@ -32,7 +32,6 @@ FailoverFailedError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole -from aws_advanced_python_wrapper.pep249 import Error from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory from aws_advanced_python_wrapper.utils.log import Logger @@ -614,17 +613,9 @@ def _open_new_reader_connection( host_candidates = self._get_reader_host_candidates() conn_attempts = len(host_candidates) * 2 for _ in range(conn_attempts): - try: - host = self._plugin_service.get_host_info_by_strategy( - HostRole.READER, self._reader_selector_strategy, host_candidates - ) - except Error: - # Every reader is currently marked unavailable. Stop here so - # the caller reports that no reader was available, rather than - # surfacing a host-selector error to the application. Error, - # not AwsWrapperError: the default random selector raises the - # base class, which AwsWrapperError is a subclass of. - break + host = self._plugin_service.get_host_info_by_strategy( + HostRole.READER, self._reader_selector_strategy, host_candidates + ) if host is not None: try: conn = self._plugin_service.connect(host, self._properties, self) diff --git a/aws_advanced_python_wrapper/reader_failover_handler.py b/aws_advanced_python_wrapper/reader_failover_handler.py index 28cf86862..e20aba452 100644 --- a/aws_advanced_python_wrapper/reader_failover_handler.py +++ b/aws_advanced_python_wrapper/reader_failover_handler.py @@ -150,7 +150,7 @@ def _internal_failover_task( def _failover_internal(self, hosts: Tuple[HostInfo, ...], current_host: Optional[HostInfo]) -> ReaderFailoverResult: if current_host is not None: - self._plugin_service.set_availability(current_host, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(current_host.all_aliases, HostAvailability.UNAVAILABLE) hosts_by_priority = ReaderFailoverHandlerImpl.get_hosts_by_priority(hosts, self._strict_reader_failover) return self._get_connection_from_host_group(hosts_by_priority) @@ -201,13 +201,13 @@ def attempt_connection(self, host: HostInfo) -> ReaderFailoverResult: try: conn: Connection = self._plugin_service.force_connect(host, props) - self._plugin_service.set_availability(host, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host.all_aliases, HostAvailability.AVAILABLE) logger.debug("ReaderFailoverHandler.SuccessfulReaderConnection", host.url) return ReaderFailoverResult(conn, True, host, None) except Exception as ex: logger.debug("ReaderFailoverHandler.FailedReaderConnection", host.url) - self._plugin_service.set_availability(host, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(host.all_aliases, HostAvailability.UNAVAILABLE) if not self._plugin_service.is_network_exception(ex): return ReaderFailoverResult(None, False, None, ex) diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 221bf2dff..911056ccf 100644 --- a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties +++ b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties @@ -34,12 +34,7 @@ AdfsCredentialsProviderFactory.SignOnPagePostActionUrl=[AdfsCredentialsProviderF AdfsCredentialsProviderFactory.SignOnPagePostActionRequestFailed=[AdfsCredentialsProviderFactory] ADFS SignOn Page POST action failed with HTTP status '{}', reason phrase '{}', and response '{}' AdfsCredentialsProviderFactory.SignOnPageUrl=[AdfsCredentialsProviderFactory] ADFS SignOn URL: '{}' -AsyncAuroraHostListProvider.NoMonitoringConnectionFactory=[AsyncAuroraHostListProvider, clusterId: '{}'] No monitoring connection is available, so background topology refresh is disabled. Topology is still refreshed on demand. -AsyncClusterTopologyMonitor.StopWithoutLoop=[AsyncClusterTopologyMonitor, clusterId: '{}'] The monitor was asked to stop after its event loop closed; its monitoring connection could not be closed. AsyncPluginService.HostListProviderNotSet=[AsyncPluginService] Host list provider is not set. Ensure AsyncAwsWrapperConnection.connect has populated it before calling refresh. -AsyncTopologyUtils.MultipleWriters=[AsyncTopologyUtils] The topology query returned {} writers; using the most recently updated one. -AsyncTopologyUtils.NoTemplateForRegion=[AsyncTopologyUtils] Skipping instance '{}': no instance template is configured for region '{}'. Set 'global_cluster_instance_host_patterns' to include this region. -AsyncTopologyUtils.TopologyQueryFailed=[{}] The topology query failed; the previously stored topology will be used: {} AwsSdk.UnsupportedRegion=[AwsSdk] Unsupported AWS region {}. Please check AWS documentation for supported AWS regions. @@ -256,6 +251,7 @@ HostMonitoringPlugin.ConnectionNone=[HostMonitoringPlugin] Attempted to execute HostMonitoringPlugin.HostInfoNone=[HostMonitoringPlugin] Could not find HostInfo to monitor for the current connection. HostMonitoringPlugin.HostInfoNoneForMethod=[HostMonitoringPlugin] Attempted to execute method '{}' but the current host info is None. HostMonitoringPlugin.ConfigurationNotSupported=[HostMonitoringPlugin] Aborting connections from a separate thread is not supported for the detected driver dialect: '{}'. The EFM plugin requires this feature to be supported. +HostMonitoringPlugin.UnableToIdentifyConnection=[HostMonitoringPlugin] Unable to identify the connected database instance: '{}', please ensure the correct host list provider is specified. The host list provider in use is: '{}'. HostMonitoringPlugin.UnavailableHost=[HostMonitoringPlugin] Host '{}' is unavailable. HostMonitoringV2Plugin.ActivatedMonitoring=[HostMonitoringV2Plugin] Executing method '{}', monitoring is activated. @@ -265,6 +261,7 @@ HostMonitoringV2Plugin.MonitoringDeactivated=[HostMonitoringV2Plugin] Monitoring HostMonitoringV2Plugin.ConnectionNone=[HostMonitoringV2Plugin] Attempted to execute method '{}' but the current connection is None. HostMonitoringV2Plugin.HostInfoNone=[HostMonitoringV2Plugin] Could not find HostInfo to monitor for the current connection. HostMonitoringV2Plugin.ConfigurationNotSupported=[HostMonitoringV2Plugin] Aborting connections from a separate thread is not supported for the detected driver dialect: '{}'. The EFM V2 plugin requires this feature to be supported. +HostMonitoringV2Plugin.UnableToIdentifyConnection=[HostMonitoringV2Plugin] Unable to identify the connected database instance: '{}', please ensure the correct host list provider is specified. The host list provider in use is: '{}'. HostMonitorV2.ExceptionDuringMonitoringStop=[HostMonitorV2] Stopping monitoring after unhandled exception was thrown in monitoring thread for host '{}'. Exception: '{}' HostMonitorV2.MonitorIsStopped=[HostMonitorV2] Monitoring was already stopped for host '{}'. HostMonitorV2.StartMonitoringThreadNewContext=[HostMonitorV2] Start monitoring thread for checking new contexts for '{}'. @@ -340,6 +337,13 @@ MonitorContext.HostAvailable=[MonitorContext] Host '{}' is *available*. MonitorContext.HostNotResponding=[MonitorContext] Host '{}' is not *responding* - failure count: '{}'. MonitorContext.HostUnavailable=[MonitorContext] Host '{}' is *unavailable*. +MonitoringThreadContainer.EmptyHostKeys=[MonitorThreadContainer] The provided host_aliases set was empty. +MonitoringThreadContainer.ErrorGettingMonitor=[MonitorThreadContainer] Unable to find or create monitor for host with aliases '{}'. +MonitoringThreadContainer.SupplierMonitorNone=[MonitorThreadContainer] The monitor supplier passed into get_or_create_monitor returned None. + +MonitorService.EmptyAliasSet=[MonitorService] Empty alias set passed for '{}'. The alias set should not be empty. +MonitorService.ErrorPopulatingAliases=[MonitorService] An error occurred while populating aliases: '{}'. + GDBRegionUtils.UnableToRetrieveGlobalClusterARN=Unable to retrieve the primary global region for the provided global database cluster. GlobalAuroraTopologyUtils.UnsupportedOperationError=[GlobalAuroraTopologyUtils] Aurora global databases does not support this operation {}. @@ -384,9 +388,12 @@ PluginManager.ResortedPlugins=[PluginManager] Plugins order has been rearranged. PluginServiceImpl.CouldNotDetermineCurrentHost=[PluginServiceImpl] The current host could not be determined. PluginServiceImpl.CurrentHostNotAllowed=[PluginServiceImpl] The current host is not in the list of allowed hosts. Current host: '{}'. Allowed hosts: {} +PluginServiceImpl.FailedToRetrieveHostPort=[PluginServiceImpl] Could not retrieve Host:Port for connection. {} +PluginServiceImpl.FillAliasesTimeout=[PluginServiceImpl] The timeout limit was reached while querying for the current host's alias. PluginServiceImpl.GetHostRoleConnectionNone=[PluginServiceImpl] Attempted to evaluate the host role of the given connection, but could not find a non-None connection to evaluate. PluginServiceImpl.HostListEmpty=[PluginServiceImpl] Could not determine the current host info because the current host list is empty. PluginServiceImpl.IncorrectStatusType=[PluginServiceImpl] Received an unexpected type from the status cache. An object of type {} was requested, but the object at key '{}' had a type of {}. The retrieved object was: {}. +PluginServiceImpl.NonEmptyAliases=[PluginServiceImpl] fill_aliases called when HostInfo already contains the following aliases: {}. PluginServiceImpl.SetCurrentHostInfo=[PluginServiceImpl] Set current host info to {} PluginServiceImpl.UnableToUpdateTransactionStatus=[PluginServiceImpl] Unable to update transaction status, current connection is None. PluginServiceImpl.UpdateDialectConnectionNone=[PluginServiceImpl] The plugin service attempted to update the current dialect but could not identify a connection to use. diff --git a/aws_advanced_python_wrapper/utils/concurrent.py b/aws_advanced_python_wrapper/utils/concurrent.py index b164b480d..5a8250872 100644 --- a/aws_advanced_python_wrapper/utils/concurrent.py +++ b/aws_advanced_python_wrapper/utils/concurrent.py @@ -77,6 +77,25 @@ def compute_if_absent(self, key: K, mapping_func: Callable) -> Optional[V]: return new_value return value + def compute_for_keys( + self, keys, factory: Callable, + on_existing: Optional[Callable] = None) -> V: + with self._lock: + value = None + for key in keys: + value = self._dict.get(key) + if value is not None: + if on_existing: + on_existing(value) + break + + if value is None: + value = factory() + + for key in keys: + self._dict.setdefault(key, value) + return value + def put(self, key: K, value: V): with self._lock: self._dict[key] = value diff --git a/aws_advanced_python_wrapper/utils/monitor_service.py b/aws_advanced_python_wrapper/utils/monitor_service.py index 6b07ddfa3..2a7006dfa 100644 --- a/aws_advanced_python_wrapper/utils/monitor_service.py +++ b/aws_advanced_python_wrapper/utils/monitor_service.py @@ -17,7 +17,8 @@ import threading from dataclasses import dataclass from time import perf_counter_ns -from typing import Any, Callable, Dict, Optional, Protocol, runtime_checkable +from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, + runtime_checkable) from aws_advanced_python_wrapper.utils.events import (DataAccessEvent, EventBase, @@ -110,6 +111,14 @@ def run_if_absent( container = self._get_or_create_container(monitor_type) return container.cache.compute_if_absent(key, lambda _: factory()) + def run_if_absent_with_aliases( + self, + monitor_type: type, + aliases: FrozenSet[str], + factory: Callable[[], Any]) -> Any: + container = self._get_or_create_container(monitor_type) + return container.cache.get_or_create_for_aliases(aliases, factory) + def detach(self, monitor_type: type, monitor: Any) -> None: container = self._monitor_caches.get(monitor_type) if container is not None: @@ -132,19 +141,6 @@ 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 795fb65aa..304140639 100644 --- a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py +++ b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py @@ -15,7 +15,7 @@ from __future__ import annotations from time import perf_counter_ns -from typing import Callable, Generic, List, Optional, Tuple, TypeVar +from typing import Callable, FrozenSet, Generic, List, Optional, Tuple, TypeVar from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict @@ -65,6 +65,13 @@ def compute_if_absent(self, key: K, factory: Callable[[K], V]) -> Optional[V]: entry.extend(self._expiration_timeout_ns) return entry.item + def get_or_create_for_aliases(self, aliases: FrozenSet[K], factory: Callable[[], V]) -> V: + entry = self._cache.compute_for_keys( + aliases, + lambda: _CacheItem(factory(), perf_counter_ns() + self._expiration_timeout_ns), + on_existing=lambda e: e.extend(self._expiration_timeout_ns)) + return entry.item + def extend_expiration(self, key: K) -> None: entry = self._cache.get(key) if entry is not None: @@ -82,7 +89,8 @@ 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: - return self._cache.remove(key) is not None + self._cache.remove(key) + return True 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 19f42b573..2df472442 100644 --- a/aws_advanced_python_wrapper/utils/storage/storage_service.py +++ b/aws_advanced_python_wrapper/utils/storage/storage_service.py @@ -52,19 +52,12 @@ def register( should_dispose_func=should_dispose, item_disposal_func=on_dispose)) - 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. - """ + def get(self, item_type: Type[V], key: Any) -> Optional[V]: cache = self._caches.get(item_type) if cache is None: return None value = cache.get(key) - if value is not None and register_data_access: + if value is not None: self._event_publisher.publish(DataAccessEvent(data_type=item_type, key=key)) return value diff --git a/aws_advanced_python_wrapper/utils/utils.py b/aws_advanced_python_wrapper/utils/utils.py index 132bb7041..e6690a410 100644 --- a/aws_advanced_python_wrapper/utils/utils.py +++ b/aws_advanced_python_wrapper/utils/utils.py @@ -21,7 +21,6 @@ from typing import TYPE_CHECKING, Optional, Tuple from aws_advanced_python_wrapper.hostinfo import HostRole -from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType if TYPE_CHECKING: from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -99,51 +98,6 @@ def contains_host_and_port(hosts: Tuple[HostInfo, ...], host_and_port: str) -> b return False - @staticmethod - def requires_host_identification(url_type: RdsUrlType) -> bool: - """Whether the instance behind ``url_type`` has to be looked up. - - An instance endpoint names its instance already. A proxy or shard - group endpoint names a router, which stays reachable and is the right - thing to monitor; the instance behind it may not accept a direct - connection at all. - """ - return url_type not in ( - RdsUrlType.RDS_INSTANCE, - RdsUrlType.RDS_PROXY, - RdsUrlType.RDS_AURORA_LIMITLESS_DB_SHARD_GROUP) - - @staticmethod - def matches_host(host: HostInfo, other: HostInfo) -> bool: - """Whether two hosts name the same instance. - - Host ids match exactly; host names are compared case-insensitively, - since DNS names are case-insensitive. - """ - if host.host_id is not None and host.host_id == other.host_id: - return True - return (host.host is not None and other.host is not None - and host.host.casefold() == other.host.casefold()) - - @staticmethod - def find_host( - hosts: Tuple[HostInfo, ...], - instance_id: Optional[str], - instance_name: Optional[str]) -> Optional[HostInfo]: - """Find the host a connection is bound to from what ``host_id_query`` - reported. - - The id is matched against ``host_id`` and the name against ``host``. - The dialects disagree about which column holds which: the Aurora - queries repeat one value, Multi-AZ returns a numeric id and a short - name, and the plain MySQL and PostgreSQL queries return the name - first. Matching on either column covers all of them. - """ - return next( - (host for host in hosts - if host.host_id == instance_id or host.host == instance_name), - None) - @staticmethod def get_writer(hosts: Tuple[HostInfo, ...]) -> Optional[HostInfo]: for host in hosts: diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 8ad8e7eb4..9db150c21 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -78,11 +78,7 @@ def __init__( if not conn: raise AwsWrapperError(Messages.get("AwsWrapperConnection.ConnectionNotOpen")) - # A plugin may have routed the connect elsewhere; that is the host this - # connection is actually on. - routed = plugin_service.take_routed_host_info() - connected_host_info = routed if routed is not None else plugin_service.initial_connection_host_info - plugin_service.set_current_connection(conn, connected_host_info) + plugin_service.set_current_connection(conn, plugin_service.initial_connection_host_info) @property def target_connection(self): diff --git a/aws_advanced_python_wrapper/writer_failover_handler.py b/aws_advanced_python_wrapper/writer_failover_handler.py index 4ad62e3a1..34e04bac2 100644 --- a/aws_advanced_python_wrapper/writer_failover_handler.py +++ b/aws_advanced_python_wrapper/writer_failover_handler.py @@ -116,7 +116,7 @@ def get_writer(self, topology: Tuple[HostInfo, ...]) -> Optional[HostInfo]: def get_result_from_future(self, current_topology: Tuple[HostInfo, ...]) -> WriterFailoverResult: writer_host: Optional[HostInfo] = self.get_writer(current_topology) if writer_host is not None: - self._plugin_service.set_availability(writer_host, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(writer_host.as_aliases(), HostAvailability.UNAVAILABLE) executor = ThreadPoolExecutor(thread_name_prefix="WriterFailoverHandlerExecutor") try: @@ -188,7 +188,7 @@ def reconnect_to_writer(self, initial_writer_host: HostInfo): else: success = self.is_current_host_writer(latest_topology, initial_writer_host) - self._plugin_service.set_availability(initial_writer_host, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(initial_writer_host.as_aliases(), HostAvailability.AVAILABLE) return WriterFailoverResult(success, False, latest_topology, conn if success else None, "TaskA", None) except Exception as ex: @@ -208,11 +208,10 @@ def is_current_host_writer(self, latest_topology: Tuple[HostInfo, ...], initial_ if latest_writer is None: return False - return (latest_writer.host_id is not None - and latest_writer.host_id == initial_writer_host.host_id) \ - or (latest_writer.get_host_and_port() is not None - and latest_writer.get_host_and_port().casefold() - == initial_writer_host.get_host_and_port().casefold()) + latest_writer_all_aliases: frozenset[str] = latest_writer.all_aliases + current_aliases: frozenset[str] = initial_writer_host.all_aliases + + return current_aliases is not None and len(current_aliases) > 0 and bool(current_aliases.intersection(latest_writer_all_aliases)) def wait_for_new_writer(self, current_topology: Tuple[HostInfo, ...], current_host: HostInfo) -> WriterFailoverResult: """ @@ -318,11 +317,11 @@ def connect_to_writer(self, writer_candidate: Optional[HostInfo]) -> bool: if writer_candidate is not None: self._current_connection = \ self._plugin_service.force_connect(writer_candidate, self._initial_connection_properties) - self._plugin_service.set_availability(writer_candidate, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(writer_candidate.as_aliases(), HostAvailability.AVAILABLE) return True except Exception: if writer_candidate is not None: - self._plugin_service.set_availability(writer_candidate, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(writer_candidate.as_aliases(), HostAvailability.UNAVAILABLE) return False diff --git a/docs/development-guide/PluginService.md b/docs/development-guide/PluginService.md index 3f5eee7e3..fce76c2b3 100644 --- a/docs/development-guide/PluginService.md +++ b/docs/development-guide/PluginService.md @@ -9,24 +9,6 @@ It also keeps track of the host list provider in use, and notifies it to update It is expected that the plugins do not establish a connection themselves, but rather call `PluginService.connect()` to establish connections. -## The Routed Host - -A plugin may connect to a host other than the one it was asked for. The Aurora -initial connection strategy plugin substitutes an instance for a cluster -endpoint, and the limitless plugin picks a transaction router. - -A plugin that does this assigns `PluginService.routed_host_info`, and the -wrapper adopts that host as the current host for the connection. - -A plugin that wants to know where the connect was routed should **read** the -property. Connect hooks unwind from the innermost plugin outwards, so a plugin -that consumed the value would hide it from every plugin outside it and from -the wrapper. Only the wrapper consumes it, with `take_routed_host_info()`. - -The value belongs to a single connect. `PluginService.connect()` clears it on -entry and `set_current_connection()` clears it once a host has been adopted, -so a plugin never reads a host left over from an earlier connect. - ## Host List Providers The plugin service uses the host list provider to retrieve the most recent host information or topology information about the database. diff --git a/tests/unit/conftest.py b/tests/unit/conftest.py index 95a1ae254..80cdb2dbc 100644 --- a/tests/unit/conftest.py +++ b/tests/unit/conftest.py @@ -29,10 +29,6 @@ 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_aurora_connection_tracker.py b/tests/unit/test_aio_aurora_connection_tracker.py index f25f4c20e..9056d9597 100644 --- a/tests/unit/test_aio_aurora_connection_tracker.py +++ b/tests/unit/test_aio_aurora_connection_tracker.py @@ -539,10 +539,10 @@ def test_notify_converted_to_reader_invalidates_that_host(): tracker.track(host, conn) from aws_advanced_python_wrapper.utils.notifications import HostEvent + alias = host.as_alias() async def _run(): - # Change keys are urls, with a trailing slash; tracking keys are not. - plugin.notify_host_list_changed({host.url: {HostEvent.CONVERTED_TO_READER}}) + plugin.notify_host_list_changed({alias: {HostEvent.CONVERTED_TO_READER}}) # Give the spawned invalidation task a moment await asyncio.sleep(0.01) @@ -585,7 +585,7 @@ def test_notify_ignores_events_that_are_not_converted(): async def _run(): plugin.notify_host_list_changed( - {host.url: {HostEvent.WENT_DOWN}}) + {host.as_alias(): {HostEvent.WENT_DOWN}}) await asyncio.sleep(0.01) asyncio.run(_run()) @@ -650,54 +650,68 @@ async def _run(): conn.close.assert_called() -def test_notify_host_list_changed_handles_a_key_without_a_port(): - """A change key naming no port still reaches the connections tracked - under it, since a host with no port keys on the bare host name.""" +def test_notify_host_list_changed_handles_alias_without_port(): + """An alias with no colon falls back to port 5432 (doesn't raise).""" plugin, svc, driver_dialect, tracker = _build() - conn = _plain_conn("conn") - tracker.track(HostInfo(host="host-no-port"), conn) from aws_advanced_python_wrapper.utils.notifications import HostEvent async def _run(): - plugin.notify_host_list_changed({"host-no-port/": {HostEvent.CONVERTED_TO_READER}}) + # Must not raise; _spawn_invalidation schedules via asyncio.create_task + # so needs a running loop. + plugin.notify_host_list_changed({"host-no-port": {HostEvent.CONVERTED_TO_READER}}) await asyncio.sleep(0.01) asyncio.run(_run()) - conn.close.assert_called() -def test_tracker_keys_a_cluster_connected_conn_by_its_host_id(): - """A cluster endpoint does not name the instance, so the host id is what a - later invalidation naming the instance has to match on.""" +def test_parse_alias_helper(): + """Direct helper test: IPv4, IPv6, bare host, invalid port.""" + from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ + AsyncAuroraConnectionTrackerPlugin + + assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h.example:5432") == ("h.example", 5432) + assert AsyncAuroraConnectionTrackerPlugin._parse_alias("[::1]:5432") == ("[::1]", 5432) + assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h-no-port") == ("h-no-port", 5432) + assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h:not-a-port") == ("h", 5432) + + +def test_tracker_keys_by_instance_endpoint_for_cluster_connected_conn(): + """When tracking via a cluster endpoint HostInfo whose aliases + include the instance endpoint, the canonical key is the instance + endpoint -- so notify-based invalidation by instance alias finds it.""" tracker = AsyncOpenedConnectionTracker() + # Cluster endpoint hostname that is NOT an RDS instance per is_rds_instance, + # but aliases include the instance endpoint. cluster_host = HostInfo( host="mydb.cluster-abc123.us-east-1.rds.amazonaws.com", port=5432, role=HostRole.WRITER, - host_id="myinstance", ) + # Add a known RDS instance alias + cluster_host.add_alias("myinstance.abc123.us-east-1.rds.amazonaws.com:5432") conn = _plain_conn("conn") tracker.track(cluster_host, conn) - assert set(AsyncOpenedConnectionTracker._tracking_keys(cluster_host)) == { - "myinstance", "mydb.cluster-abc123.us-east-1.rds.amazonaws.com:5432"} + # Canonical key is the instance alias, not the cluster host:port + assert AsyncOpenedConnectionTracker._canonical_key(cluster_host) == \ + "myinstance.abc123.us-east-1.rds.amazonaws.com:5432" + # invalidate_all via a HostInfo that resolves to the same instance alias + # should close the tracked conn instance_host = HostInfo( host="myinstance.abc123.us-east-1.rds.amazonaws.com", port=5432, - host_id="myinstance", ) asyncio.run(tracker.invalidate_all(instance_host)) conn.close.assert_called() -def test_tracker_keys_an_instance_endpoint_by_host_and_port_alone(): - host = HostInfo(host="instance-1.abc123.us-east-1.rds.amazonaws.com", port=5432, - host_id="instance-1") - assert AsyncOpenedConnectionTracker._tracking_keys(host) == ( - "instance-1.abc123.us-east-1.rds.amazonaws.com:5432",) +def test_tracker_fallback_to_host_port_for_non_rds_host(): + """Non-RDS hostnames use host:port as the canonical key (no RDS alias found).""" + host = HostInfo(host="custom.example.com", port=5432) + assert AsyncOpenedConnectionTracker._canonical_key(host) == "custom.example.com:5432" # ---- B2: post-failover settling window ---------------------------------- diff --git a/tests/unit/test_aio_aurora_initial_connection.py b/tests/unit/test_aio_aurora_initial_connection.py index 59fc5378b..afd2fa944 100644 --- a/tests/unit/test_aio_aurora_initial_connection.py +++ b/tests/unit/test_aio_aurora_initial_connection.py @@ -133,7 +133,7 @@ async def _run(): svc.get_host_role.assert_not_awaited() # A non-cluster URL needs no role verification, so the loop records the # original host and returns on the first pass. - assert svc.routed_host_info is host + assert svc.initial_connection_host_info is host # ---- 2. Writer cluster URL + already writer -> direct writer conn ------ @@ -168,7 +168,7 @@ async def _run(): result = asyncio.run(_run()) assert result is writer_conn driver_dialect.connect.assert_awaited_once() - assert svc.routed_host_info is writer + assert svc.initial_connection_host_info is writer # ---- 3. Writer cluster URL + connected to reader -> retry -------------- @@ -207,8 +207,8 @@ async def _run(): driver_dialect.abort_connection.assert_any_await(first_conn) # Topology force-refreshed on the bad conn. svc.force_refresh_host_list.assert_awaited() - # routed_host_info -> writer from topology. - assert svc.routed_host_info is writer + # initial_connection_host_info -> writer from topology. + assert svc.initial_connection_host_info is writer # ---- 4. Reader cluster URL + connected to reader -> returns conn ------- @@ -242,7 +242,7 @@ async def _run(): result = asyncio.run(_run()) assert result is reader_conn - assert svc.routed_host_info is reader + assert svc.initial_connection_host_info is reader # ---- 5. Reader cluster URL + no readers -> writer fallback ------------- @@ -280,7 +280,7 @@ async def _run(): assert result is cluster_conn # The no-readers fallback records the candidate host, which on the stale # path is the original connect host rather than the writer. - assert svc.routed_host_info is host + assert svc.initial_connection_host_info is host # ---- 6. Timeout exhausted -> raises (parity with sync) ----------------- @@ -420,8 +420,8 @@ async def _run(): asyncio.run(_run()) assert svc.set_availability.call_count >= 1 - marked_host = svc.set_availability.call_args_list[0][0][0] - assert marked_host.host == reader.host + called_aliases = svc.set_availability.call_args_list[0][0][0] + assert reader.host in "".join(called_aliases) assert svc.set_availability.call_args_list[0][0][1] == \ HostAvailability.UNAVAILABLE diff --git a/tests/unit/test_aio_dialect_utils.py b/tests/unit/test_aio_dialect_utils.py index edde85f4d..45a003570 100644 --- a/tests/unit/test_aio_dialect_utils.py +++ b/tests/unit/test_aio_dialect_utils.py @@ -143,5 +143,5 @@ def test_get_instance_id_rolls_back_transient_probe_txn(): dd = MagicMock() dd.is_in_transaction = AsyncMock(return_value=False) iid = asyncio.run(AsyncDialectUtils.get_instance_id(conn, dd, "q")) - assert iid == ("inst-1", "inst-1") + assert iid == "inst-1" conn.rollback.assert_awaited_once() diff --git a/tests/unit/test_aio_failover_plugin.py b/tests/unit/test_aio_failover_plugin.py index 0184bc9f8..e0bd2e23b 100644 --- a/tests/unit/test_aio_failover_plugin.py +++ b/tests/unit/test_aio_failover_plugin.py @@ -529,7 +529,7 @@ def test_failover_marks_connected_host_available(): asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) svc.set_availability.assert_any_call( - writer, HostAvailability.AVAILABLE) + writer.as_aliases(), HostAvailability.AVAILABLE) def test_failover_marks_failed_host_unavailable(): @@ -547,7 +547,7 @@ def test_failover_marks_failed_host_unavailable(): asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) svc.set_availability.assert_any_call( - writer, HostAvailability.UNAVAILABLE) + writer.as_aliases(), HostAvailability.UNAVAILABLE) # ---- B.4: reader retry loop + strategy + writer fallback --------------- @@ -950,9 +950,9 @@ async def _dial(): conn = await plugin.connect( MagicMock(), driver_dialect, host, Properties({}), True, _dial) assert conn is failover_conn - marked_host, marked_avail = svc.set_availability.call_args_list[0][0] + marked_aliases, marked_avail = svc.set_availability.call_args_list[0][0] assert marked_avail == HostAvailability.UNAVAILABLE - assert marked_host is host + assert host.as_aliases() == marked_aliases asyncio.run(_body()) 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 2bb693856..867d5e3f7 100644 --- a/tests/unit/test_aio_global_aurora_host_list_provider.py +++ b/tests/unit/test_aio_global_aurora_host_list_provider.py @@ -31,8 +31,6 @@ 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 @@ -61,7 +59,7 @@ def _make_provider(**overrides: Any) -> AsyncGlobalAuroraHostListProvider: return AsyncGlobalAuroraHostListProvider(**kwargs) -# ---- parse_instance_templates ---------------------------------------------------- +# ---- _parse_templates ---------------------------------------------------- def test_parse_templates_colon_format_pairs(): @@ -72,7 +70,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 = AsyncGlobalAuroraTopologyUtils.parse_instance_templates(raw) + parsed = AsyncGlobalAuroraHostListProvider._parse_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", @@ -83,11 +81,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): - AsyncGlobalAuroraTopologyUtils.parse_instance_templates( + AsyncGlobalAuroraHostListProvider._parse_templates( "us-east-1:?.xyz.us-east-1.rds.amazonaws.com:5432,bad-entry-no-colon") -# ---- _process_global_query_results --------------------------------------------------- +# ---- _rows_to_topology --------------------------------------------------- def test_empty_templates_returns_empty_topology(): @@ -97,7 +95,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._topology_utils._process_global_query_results(rows) == () + assert prov._rows_to_topology(rows) == () def test_region_without_matching_template_skipped(): @@ -115,7 +113,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._topology_utils._process_global_query_results(rows) + topo = prov._rows_to_topology(rows) assert len(topo) == 1 assert topo[0].host == "instance-1.xyz.us-east-1.rds.amazonaws.com" assert topo[0].port == 5432 @@ -130,7 +128,7 @@ def test_template_substitution_with_port(): }, ) rows = [("my-instance", True, 0.0, "us-east-1")] - topo = prov._topology_utils._process_global_query_results(rows) + topo = prov._rows_to_topology(rows) assert len(topo) == 1 assert topo[0].host == "my-instance.xyz.us-east-1.rds.amazonaws.com" assert topo[0].port == 6000 @@ -146,7 +144,7 @@ def test_template_substitution_without_port_uses_default_port(): }, ) rows = [("my-instance", True, 0.0, "us-east-1")] - topo = prov._topology_utils._process_global_query_results(rows) + topo = prov._rows_to_topology(rows) assert len(topo) == 1 assert topo[0].host == "my-instance.xyz.us-east-1.rds.amazonaws.com" assert topo[0].port == 5433 @@ -166,7 +164,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._topology_utils._process_global_query_results(rows) + topo = prov._rows_to_topology(rows) assert len(topo) == 3 # Writer first. assert topo[0].role == HostRole.WRITER @@ -188,7 +186,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._topology_utils._process_global_query_results(rows) + topo = prov._rows_to_topology(rows) assert [h.host_id for h in topo] == ["writer-a"] @@ -204,7 +202,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._topology_utils._process_global_query_results(rows) == () + assert prov._rows_to_topology(rows) == () # ---- Property-based construction ---------------------------------------- @@ -214,7 +212,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 - row parsing uses that map.""" + ``_rows_to_topology`` calls use 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" @@ -226,7 +224,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._topology_utils._process_global_query_results(rows) + topo = prov._rows_to_topology(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 5a242fa37..8cf91b0b2 100644 --- a/tests/unit/test_aio_host_list_provider.py +++ b/tests/unit/test_aio_host_list_provider.py @@ -24,33 +24,16 @@ 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 HostInfo, HostRole -from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.hostinfo import HostRole 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) @@ -142,17 +125,11 @@ def test_static_provider_implements_protocol(): # ---- Aurora provider tests --------------------------------------------- -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_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_aurora_provider_cluster_id_uses_explicit_cluster_id_prop(): @@ -171,7 +148,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._topology_utils._host_from_host_id("test-pg-x-2") + assert (prov._host_from_server_id("test-pg-x-2") == "test-pg-x-2.abc123.us-east-2.rds.amazonaws.com") @@ -179,7 +156,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._topology_utils._host_from_host_id("inst-1") == "inst-1.custom.example.com" + assert prov._host_from_server_id("inst-1") == "inst-1.custom.example.com" def test_host_from_server_id_strips_port_suffix_from_pattern(): @@ -191,12 +168,11 @@ 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._topology_utils._host_from_host_id("inst-1") + assert (prov._host_from_server_id("inst-1") == "inst-1.cvqiy8.us-east-2.rds.amazonaws.com.proxied") - 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 + host_pattern, port = prov._resolve_instance_pattern() + assert host_pattern == "?.cvqiy8.us-east-2.rds.amazonaws.com.proxied" + assert port == 8666 def test_topology_hosts_use_pattern_port_and_clean_host(): @@ -284,7 +260,7 @@ def test_topology_multiple_writers_picks_latest_updated_writer(): ("r-1", False, 0, 0, newer), ] prov = _aurora() - topo = prov._topology_utils._process_query_results(rows) + topo = prov._rows_to_topology(rows) writers = [h for h in topo if h.role == HostRole.WRITER] readers = [h for h in topo if h.role == HostRole.READER] @@ -298,29 +274,26 @@ 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._topology_utils._process_query_results(rows) + topo = prov._rows_to_topology(rows) writers = [h for h in topo if h.role == HostRole.WRITER] assert len(writers) == 1 -def test_topology_rows_carry_host_id(): - """Integration regression (EFM cluster-RO, both Aurora envs): the row - parser dropped host_id, so identify_connection could never resolve a - cluster-endpoint connection and host monitoring could not pick a - monitoring host.""" +def test_topology_rows_carry_host_id_and_instance_alias(): + """Integration regression (EFM cluster-RO, both Aurora envs): + _rows_to_topology dropped host_id, so plugin_service.identify_connection + (which matches `h.host_id == instance_id`) could NEVER resolve a + cluster-endpoint connection -- EFM's _get_monitoring_host_info raised + UnableToIdentifyConnection on every cluster-RO connect. Sync parity: + create_host (host_list_provider.py:548-556) sets host_id AND adds the + bare instance id as an alias; the async MultiAz/GlobalAurora providers + already did both.""" rows = [("w-1", True), ("r-1", False)] prov = _aurora() - topo = prov._topology_utils._process_query_results(rows) + topo = prov._rows_to_topology(rows) assert {h.host_id for h in topo} == {"w-1", "r-1"} - - -def test_topology_rows_share_one_availability_strategy(): - """One strategy per provider, matching the synchronous provider, so the - backoff window is per cluster rather than per host.""" - prov = _aurora() - topo = prov._topology_utils._process_query_results([("w-1", True), ("r-1", False)]) - strategies = {id(h.host_availability_strategy) for h in topo} - assert strategies == {id(prov._topology_utils._host_availability_strategy)} + for h in topo: + assert h.host_id in h.as_aliases() def test_topology_query_programming_error_raises_invalid_query(): @@ -328,7 +301,7 @@ async def _body() -> None: prov = _aurora() conn = _build_error_conn(ProgrammingError("bad topology sql")) with pytest.raises(AwsWrapperError, match="Aurora"): - await prov._topology_utils.query_for_topology(conn) + await prov._run_topology_query(conn) asyncio.run(_body()) @@ -338,61 +311,57 @@ 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._topology_utils.query_for_topology(conn) == () + assert await prov._run_topology_query(conn) == [] asyncio.run(_body()) -# ---- host pattern validation, at construction as sync does ----------------------------- +# ---- _validate_host_pattern (sync parity) ----------------------------- 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"): - AsyncAuroraHostListProvider( - _props(cluster_instance_host_pattern="no-placeholder.example.com"), - driver_dialect=MagicMock()) + prov._resolve_instance_pattern() 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"): - AsyncAuroraHostListProvider( - _props(cluster_instance_host_pattern="?.proxy-abc123.us-east-1.rds.amazonaws.com"), - driver_dialect=MagicMock()) + prov._resolve_instance_pattern() 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"): - AsyncAuroraHostListProvider( - _props(cluster_instance_host_pattern="?.cluster-custom-abc123.us-east-1.rds.amazonaws.com"), - driver_dialect=MagicMock()) + prov._resolve_instance_pattern() def test_validate_accepts_normal_cluster_pattern(): prov = _aurora() - 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 + host_pattern, port = prov._resolve_instance_pattern() + assert host_pattern == "?.cluster-xyz.us-east-1.rds.amazonaws.com" + assert port is None # ---- provider.stop() tears down the 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.""" +def test_provider_stop_stops_monitor(): async def _body() -> None: prov = _aurora() - monitor = prov._get_or_create_monitor() - assert monitor is not None - monitor_service = services_container.get_monitor_service() - assert monitor_service.count(AsyncClusterTopologyMonitor) == 1 - + mock_monitor = MagicMock() + mock_monitor.stop = AsyncMock() + prov._monitor = mock_monitor await prov.stop() - - assert monitor_service.count(AsyncClusterTopologyMonitor) == 0 - await monitor.aclose() + mock_monitor.stop.assert_awaited_once() + assert prov._monitor is None asyncio.run(_body()) @@ -422,7 +391,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(). query_for_topology + # from connection.cursor() itself -- not from execute(). _run_topology_query # 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 @@ -453,46 +422,42 @@ async def _body() -> None: def test_topology_monitor_starts_and_stops_cleanly(): async def _body() -> None: prov = MagicMock() - prov._topology_utils.query_for_topology = AsyncMock(return_value=()) + prov.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=prov._topology_utils, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=prov, 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.aclose() + await monitor.stop() assert monitor.is_running() is False asyncio.run(_body()) -def test_topology_monitor_queries_topology_at_least_once(): +def test_topology_monitor_calls_force_refresh_at_least_once(): async def _body() -> None: prov = MagicMock() - query_calls: List[int] = [] + refresh_calls: List[int] = [] async def _refresh(conn: Any = None) -> tuple: - query_calls.append(1) + refresh_calls.append(1) return () - prov._topology_utils.query_for_topology = _refresh + prov.force_refresh = _refresh conn = MagicMock() monitor = AsyncClusterTopologyMonitor( - topology_utils=prov._topology_utils, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=prov, 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.aclose() - assert len(query_calls) >= 1 + await monitor.stop() + assert len(refresh_calls) >= 1 asyncio.run(_body()) @@ -500,18 +465,16 @@ async def _refresh(conn: Any = None) -> tuple: def test_topology_monitor_skips_refresh_when_getter_returns_none(): async def _body() -> None: prov = MagicMock() - prov._topology_utils.query_for_topology = AsyncMock(return_value=()) + prov.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=prov._topology_utils, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=prov, connection_getter=lambda: None, refresh_interval_sec=0.5, ) monitor.start() await asyncio.sleep(0.05) - await monitor.aclose() - prov._topology_utils.query_for_topology.assert_not_called() + await monitor.stop() + prov.force_refresh.assert_not_called() asyncio.run(_body()) @@ -519,11 +482,9 @@ async def _body() -> None: def test_topology_monitor_survives_provider_exception(): async def _body() -> None: prov = MagicMock() - prov._topology_utils.query_for_topology = AsyncMock(side_effect=RuntimeError("topology failure")) + prov.force_refresh = AsyncMock(side_effect=RuntimeError("topology failure")) monitor = AsyncClusterTopologyMonitor( - topology_utils=prov._topology_utils, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=prov, connection_getter=lambda: MagicMock(), refresh_interval_sec=0.5, ) @@ -531,7 +492,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.aclose() + await monitor.stop() asyncio.run(_body()) @@ -539,11 +500,9 @@ async def _body() -> None: def test_topology_monitor_start_is_idempotent(): async def _body() -> None: prov = MagicMock() - prov._topology_utils.query_for_topology = AsyncMock(return_value=()) + prov.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=prov._topology_utils, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=prov, connection_getter=lambda: MagicMock(), refresh_interval_sec=0.5, ) @@ -551,7 +510,7 @@ async def _body() -> None: first_task = monitor._task monitor.start() # should be no-op assert monitor._task is first_task - await monitor.aclose() + await monitor.stop() asyncio.run(_body()) @@ -561,20 +520,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.""" - # Topology utils whose query returns topologies with + from aws_advanced_python_wrapper.hostinfo import HostInfo + + # Build a provider whose force_refresh 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 = _stub_utils() - provider.query_for_topology = AsyncMock(side_effect=[topology_1, topology_2, topology_2, topology_2]) + provider = MagicMock() + provider.force_refresh = AsyncMock(side_effect=[topology_1, topology_2, topology_2, topology_2]) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: MagicMock(name="conn"), refresh_interval_sec=0.05, high_refresh_rate_sec=0.01, @@ -584,23 +543,23 @@ async def _run_briefly(): monitor.start() # Allow enough ticks for writer-change detection await asyncio.sleep(1) - await monitor.aclose() + await monitor.stop() asyncio.run(_run_briefly()) # At least 2 force_refresh calls happened (first one sets writer, second detects change) - assert provider.query_for_topology.await_count >= 2 + assert provider.force_refresh.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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: MagicMock(), refresh_interval_sec=0.2, high_refresh_rate_sec=0.01, @@ -610,24 +569,24 @@ async def _run_briefly(): monitor.start() # Only enough time for 1-2 ticks at normal rate await asyncio.sleep(0.1) - await monitor.aclose() + await monitor.stop() asyncio.run(_run_briefly()) # At most 2 refresh calls (initial + maybe one more) -- not spinning at high-freq - assert provider.query_for_topology.await_count <= 2 + assert provider.force_refresh.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 = _stub_utils() - provider.query_for_topology = AsyncMock(side_effect=[topology_1] + [topology_2] * 100) + provider = MagicMock() + provider.force_refresh = AsyncMock(side_effect=[topology_1] + [topology_2] * 100) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: MagicMock(), refresh_interval_sec=0.2, high_refresh_rate_sec=0.01, @@ -638,7 +597,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.aclose() + await monitor.stop() # Record state when we stopped now_ns = int(time.time_ns()) return monitor._high_refresh_until_ns, now_ns @@ -654,14 +613,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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: MagicMock(), refresh_interval_sec=0.05, high_refresh_rate_sec=0.01, @@ -671,7 +630,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.aclose() + await monitor.stop() return ignore_during ignored = asyncio.run(_run()) @@ -681,9 +640,7 @@ 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( - topology_utils=_stub_utils(), - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=MagicMock(), connection_getter=lambda: MagicMock(), refresh_interval_sec=30.0, ) @@ -692,14 +649,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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: MagicMock(), refresh_interval_sec=0.05, high_refresh_rate_sec=0.01, @@ -713,7 +670,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.aclose() + await monitor.stop() return ignore_after ignored = asyncio.run(_run()) @@ -723,17 +680,17 @@ async def _run(): # ---- G.3: force_refresh_with_connection API ------------------------------ -def test_force_refresh_with_connection_delegates_to_topology_utils(): +def test_force_refresh_with_connection_delegates_to_provider(): """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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -745,19 +702,19 @@ async def _run(): result = asyncio.run(_run()) assert result == topology - provider.query_for_topology.assert_awaited_once_with(caller_conn) + provider.force_refresh.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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -774,7 +731,7 @@ async def _run(): result = asyncio.run(_run()) assert result == topology # Provider NOT called -- we returned cached - provider.query_for_topology.assert_not_awaited() + provider.force_refresh.assert_not_awaited() def test_force_refresh_with_connection_raises_on_timeout(): @@ -782,13 +739,11 @@ def test_force_refresh_with_connection_raises_on_timeout(): async def _slow(*args, **kwargs): await asyncio.sleep(1.0) - provider = _stub_utils() - provider.query_for_topology = _slow + provider = MagicMock() + provider.force_refresh = _slow monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -803,10 +758,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( - topology_utils=_stub_utils(), - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=MagicMock(), connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -814,7 +769,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._topology_utils.query_for_topology = AsyncMock(return_value=new_topology) + monitor._provider.force_refresh = AsyncMock(return_value=new_topology) async def _run(): await monitor.force_refresh_with_connection(MagicMock(), timeout_sec=1.0) @@ -826,14 +781,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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -850,7 +805,7 @@ async def _run(): result = asyncio.run(_run()) assert result == topology # fresh, not stale - provider.query_for_topology.assert_awaited_once() + provider.force_refresh.assert_awaited_once() # ---- G.4: parallel-probe panic mode -------------------------------------- @@ -858,12 +813,12 @@ async def _run(): def test_topology_monitor_panic_mode_disabled_without_probe_host(): """Without probe_host, monitor never enters panic mode (backwards compat).""" - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + from aws_advanced_python_wrapper.hostinfo import HostInfo + + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, # no conn refresh_interval_sec=0.05, ) @@ -872,7 +827,7 @@ def test_topology_monitor_panic_mode_disabled_without_probe_host(): async def _run(): monitor.start() await asyncio.sleep(0.08) - await monitor.aclose() + await monitor.stop() asyncio.run(_run()) assert monitor.is_in_panic_mode() is False @@ -880,6 +835,8 @@ 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) @@ -890,12 +847,10 @@ async def _probe(host_info): # Both return as reader; no winner return MagicMock(name=f"conn-{host_info.host}"), HostRole.READER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -905,7 +860,7 @@ async def _probe(host_info): async def _run(): monitor.start() await asyncio.sleep(0.15) - await monitor.aclose() + await monitor.stop() asyncio.run(_run()) # Both hosts probed @@ -916,6 +871,8 @@ 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) @@ -926,12 +883,10 @@ async def _probe(host_info): return winner_conn, HostRole.WRITER return MagicMock(name=f"conn-{host_info.host}"), HostRole.READER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -947,7 +902,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.aclose() + await monitor.stop() asyncio.run(_run()) @@ -957,14 +912,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( - topology_utils=_stub_utils(), - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=MagicMock(), connection_getter=lambda: None, refresh_interval_sec=30.0, connection_factory=AsyncMock(return_value=MagicMock()), @@ -992,6 +947,8 @@ 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] @@ -1001,12 +958,10 @@ async def _probe(host_info): await asyncio.sleep(0.5) return MagicMock(), HostRole.READER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=0.02, # many ticks probe_host=_probe, @@ -1016,7 +971,7 @@ async def _probe(host_info): async def _run(): monitor.start() await asyncio.sleep(0.15) # enough for 5-7 ticks - await monitor.aclose() + await monitor.stop() asyncio.run(_run()) # Only one probe fired despite multiple ticks (dedup) @@ -1025,17 +980,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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1046,7 +1001,7 @@ async def _run(): monitor.start() await asyncio.sleep(0.1) assert monitor.is_running() - await monitor.aclose() + await monitor.stop() asyncio.run(_run()) assert monitor._is_verified_writer_connection is False @@ -1054,6 +1009,8 @@ 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) @@ -1068,12 +1025,10 @@ async def _probe(host_info): return winner_conn, HostRole.WRITER return loser_conn, HostRole.READER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1086,7 +1041,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.aclose() + await monitor.stop() asyncio.run(_run()) # On stop the unclaimed winner is closed too -- not leaked (audit C2). @@ -1095,6 +1050,8 @@ 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) @@ -1110,12 +1067,10 @@ async def _probe(host_info): await asyncio.sleep(0.02) return loser_conn, HostRole.WRITER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1130,7 +1085,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.aclose() + await monitor.stop() asyncio.run(_run()) # On stop the unclaimed winner is closed too -- not leaked (audit C2). @@ -1139,6 +1094,8 @@ 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") @@ -1153,12 +1110,10 @@ async def _probe(host_info): raise return released_conn, HostRole.READER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=()) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=()) monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1169,7 +1124,7 @@ async def _run(): monitor.start() await probe_started.wait() # Now stop; the finally should await the canceled probe - await monitor.aclose() + await monitor.stop() # Should complete without hanging (finally awaits cancellation) asyncio.run(_run()) @@ -1187,6 +1142,7 @@ 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() @@ -1224,6 +1180,8 @@ 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() @@ -1238,17 +1196,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 = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=topology) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=topology) stashed = MagicMock(name="verified-writer-conn") stashed.close = AsyncMock() monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: MagicMock(name="monitor-conn"), refresh_interval_sec=0.2, high_refresh_rate_sec=0.05, @@ -1263,7 +1221,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.aclose() + await monitor.stop() asyncio.run(_run_briefly()) stashed.close.assert_awaited_once() @@ -1275,6 +1233,8 @@ 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) @@ -1283,13 +1243,12 @@ async def _probe(host_info): return MagicMock(name="winner_conn"), HostRole.WRITER return MagicMock(name=f"conn-{host_info.host}"), HostRole.READER - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=(new_writer, reader)) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=(new_writer, reader)) + provider.adopt_topology = MagicMock() monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1299,10 +1258,10 @@ async def _probe(host_info): async def _run(): await monitor._probe_and_report(new_writer) assert monitor._last_topology == (new_writer, reader) - assert topology_store.get_topology(monitor._key) == (new_writer, reader) + provider.adopt_topology.assert_called_once_with((new_writer, reader)) assert monitor._topology_updated.is_set() assert monitor._is_verified_writer_connection is True - await monitor.aclose() + await monitor.stop() asyncio.run(_run()) @@ -1315,6 +1274,8 @@ 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) @@ -1322,16 +1283,15 @@ def test_winner_probe_publishes_role_corrected_topology_on_stale_fetch(): async def _probe(host_info): return MagicMock(name="winner_conn"), HostRole.WRITER - provider = _stub_utils() + provider = MagicMock() # 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.query_for_topology = AsyncMock( + provider.force_refresh = AsyncMock( return_value=(old_writer_stale, new_writer_stale)) + provider.adopt_topology = MagicMock() monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, probe_host=_probe, @@ -1344,9 +1304,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 - assert topology_store.get_topology(monitor._key) == published + provider.adopt_topology.assert_called_once_with(published) assert {h.host for h in published} == {"w-old", "w-new"} - await monitor.aclose() + await monitor.stop() asyncio.run(_run()) @@ -1356,14 +1316,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 = _stub_utils() + provider = MagicMock() monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, ) @@ -1388,6 +1348,8 @@ 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) @@ -1401,13 +1363,12 @@ async def _factory(): # be reopened, so the loop falls through to panic mode. raise OSError("cluster endpoint unreachable") - provider = _stub_utils() - provider.query_for_topology = AsyncMock(return_value=(new_writer, reader)) + provider = MagicMock() + provider.force_refresh = AsyncMock(return_value=(new_writer, reader)) + provider.adopt_topology = MagicMock() monitor = AsyncClusterTopologyMonitor( - topology_utils=provider, - cluster_id="test-cluster", - key=("test-cluster", "token"), + provider=provider, connection_getter=lambda: None, refresh_interval_sec=30.0, # long: proves the tick-request wakeup works probe_host=_probe, @@ -1420,7 +1381,7 @@ async def _run(): monitor.start() topology = await monitor.force_monitoring_refresh(True, timeout_sec=5.0) assert topology == (new_writer, reader) - assert topology_store.get_topology(monitor._key) == (new_writer, reader) - await monitor.aclose() + provider.adopt_topology.assert_called_with((new_writer, reader)) + await monitor.stop() asyncio.run(_run()) diff --git a/tests/unit/test_aio_host_list_provider_monitor_wiring.py b/tests/unit/test_aio_host_list_provider_monitor_wiring.py index 7c8c4cd48..dbac4b5cc 100644 --- a/tests/unit/test_aio_host_list_provider_monitor_wiring.py +++ b/tests/unit/test_aio_host_list_provider_monitor_wiring.py @@ -12,11 +12,15 @@ # See the License for the specific language governing permissions and # limitations under the License. -"""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. +"""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. """ from __future__ import annotations @@ -24,170 +28,160 @@ 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()) - async def _fetch_all(_conn, _query): +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 return rows - provider._topology_utils._fetch_all = _fetch_all # type: ignore[method-assign] + provider._run_topology_query = _rows # type: ignore[method-assign] return provider -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)]) +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)]) async def _body(): - 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() + 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) assert len(topology) == 2 - await monitor.aclose() + await provider._monitor.stop() asyncio.run(_body()) -def test_the_monitor_holds_no_provider_reference() -> None: - """What makes one monitor serve every provider on the cluster.""" - provider = _provider([("srv-1", True)]) +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)]) - 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()) + fetch_calls: list = [] + original_fetch = provider._fetch_from_db + async def _instrumented_fetch(conn): + fetch_calls.append(conn) + return await original_fetch(conn) -def test_two_providers_on_one_cluster_share_one_monitor() -> None: - first = _provider([("srv-1", True)]) - second = _provider([("srv-1", True)]) + provider._fetch_from_db = _instrumented_fetch # type: ignore[method-assign] async def _body(): - 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_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(): - 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() + 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 asyncio.run(_body()) -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)]) +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)]) 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() + 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 asyncio.run(_body()) -def test_force_refresh_falls_back_to_a_direct_query_when_the_monitor_raises() -> None: - provider = _provider([("srv-1", True)]) +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)]) 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(): - monitor = real_get_monitor() - monitor.force_refresh_with_connection = AsyncMock( # type: ignore[method-assign] + m = real_get_monitor() + m.force_refresh_with_connection = AsyncMock( # type: ignore[method-assign] side_effect=RuntimeError("monitor boom")) - return monitor + return m 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_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)]) +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)]) async def _body(): - before = len(aio_cleanup._registered_shutdown_hooks) + hooks_before = len(aio_cleanup._registered_shutdown_hooks) monitor = provider._get_or_create_monitor() assert monitor is not None - assert len(aio_cleanup._registered_shutdown_hooks) > before - await monitor.aclose() + hooks_after = len(aio_cleanup._registered_shutdown_hooks) + assert hooks_after > hooks_before + await monitor.stop() asyncio.run(_body()) - aio_cleanup.clear_shutdown_hooks() -def test_refresh_returns_the_stored_topology_without_building_a_monitor() -> None: - provider = _provider([("srv-1", True)]) +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)]) async def _body(): - provider._store_topology( - (MagicMock(host="srv-1.example", port=5432),)) - assert _monitor_count() == 0 - result = await provider.refresh(object()) + # 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) assert len(result) == 1 - assert _monitor_count() == 0 + assert provider._monitor is None asyncio.run(_body()) diff --git a/tests/unit/test_aio_host_monitoring_plugin.py b/tests/unit/test_aio_host_monitoring_plugin.py index 34392d170..88aa91b31 100644 --- a/tests/unit/test_aio_host_monitoring_plugin.py +++ b/tests/unit/test_aio_host_monitoring_plugin.py @@ -344,7 +344,7 @@ async def _work(): await asyncio.sleep(0.3) svc.set_availability.assert_any_call( - HostInfo(host="h.example", port=5432), + HostInfo(host="h.example", port=5432).as_aliases(), HostAvailability.UNAVAILABLE) dd.abort_connection.assert_awaited() aborted_with = dd.abort_connection.await_args_list[0].args[0] diff --git a/tests/unit/test_aio_monitor_lifecycle_regressions.py b/tests/unit/test_aio_monitor_lifecycle_regressions.py deleted file mode 100644 index 2c86badfe..000000000 --- a/tests/unit/test_aio_monitor_lifecycle_regressions.py +++ /dev/null @@ -1,296 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Lifecycle regressions in the shared async topology monitor. - -Each test pins a defect in the monitor's start, stop, reset or cleanup paths. -""" - -from __future__ import annotations - -import asyncio -import gc -import weakref -from unittest.mock import AsyncMock, MagicMock - -from aws_advanced_python_wrapper.aio import topology_store -from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ - AsyncClusterTopologyMonitor -from aws_advanced_python_wrapper.aio.host_list_provider import \ - AsyncAuroraHostListProvider -from aws_advanced_python_wrapper.aio.topology_utils import \ - AsyncAuroraTopologyUtils -from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole -from aws_advanced_python_wrapper.utils import services_container -from aws_advanced_python_wrapper.utils.events import MonitorResetEvent -from aws_advanced_python_wrapper.utils.properties import Properties - -CLUSTER_ID = "my-cluster" -KEY = (CLUSTER_ID, "token") -OLD = (HostInfo("blue-writer.example", 5432, HostRole.WRITER),) -NEW = (HostInfo("green-writer.example", 5432, HostRole.WRITER),) - - -def _utils(topology=()) -> AsyncAuroraTopologyUtils: - utils = AsyncAuroraTopologyUtils( - Properties({"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"}), - "SELECT 1", 5432) - utils.query_for_topology = AsyncMock(return_value=topology) # type: ignore[method-assign] - return utils - - -def _monitor(topology=()) -> AsyncClusterTopologyMonitor: - return AsyncClusterTopologyMonitor( - topology_utils=_utils(topology), - cluster_id=CLUSTER_ID, - key=KEY, - connection_getter=lambda: None) - - -def test_stop_on_a_closed_loop_does_not_raise() -> None: - """Setting the stop event before checking the loop raised "Event loop is - closed", and the monitor service swallowed it at debug level.""" - loop = asyncio.new_event_loop() - monitor = _monitor() - try: - loop.run_until_complete(_start_and_park(monitor)) - finally: - loop.close() - - # A waiter is parked on the stop event, and the loop is gone. - assert monitor._stop_event._waiters # type: ignore[attr-defined] - monitor.stop() # must not raise - - -async def _start_and_park(monitor: AsyncClusterTopologyMonitor) -> None: - monitor.start() - await asyncio.sleep(0.02) - - -def test_the_monitor_does_not_keep_its_event_loop_alive() -> None: - """A shutdown hook holds the monitor for the life of the process, so a - strong loop reference leaks a loop per loop in a loop-per-request app.""" - loop = asyncio.new_event_loop() - monitor = _monitor() - loop.run_until_complete(_start_and_park(monitor)) - loop.run_until_complete(monitor.aclose()) - loop.close() - - ref = weakref.ref(loop) - del loop - gc.collect() - assert ref() is None, "the monitor is still holding its event loop" - - -def test_a_reset_discards_a_publication_that_began_before_it() -> None: - """A refresh in flight when a blue/green reset lands describes the - pre-switchover cluster, so publishing it afterwards restores the host list - the reset just cleared.""" - async def _body(): - monitor = _monitor() - monitor.start() - topology_store.put_topology(KEY, OLD) - - reset_count = monitor._reset_count - monitor.process_event( - MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) - await asyncio.sleep(0) - await asyncio.sleep(0) - assert topology_store.get_topology(KEY) is None - - # The pre-reset fetch now completes and tries to publish. - monitor._publish_topology(OLD, reset_count) - assert topology_store.get_topology(KEY) is None - assert monitor._last_topology == () - - # A publication from after the reset still lands. - monitor._publish_topology(NEW, monitor._reset_count) - assert topology_store.get_topology(KEY) == NEW - await monitor.aclose() - - asyncio.run(_body()) - - -def test_a_reset_wakes_the_loop_instead_of_waiting_out_a_tick() -> None: - """Without waking the loop, a switchover serves nothing until the next - tick, which the reset itself just made a full-length one.""" - async def _body(): - monitor = _monitor() - monitor.start() - monitor._request_tick.clear() - - monitor.process_event( - MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) - await asyncio.sleep(0) - await asyncio.sleep(0) - - assert monitor._request_tick.is_set() - await monitor.aclose() - - asyncio.run(_body()) - - -def test_a_closed_monitor_is_not_restarted() -> None: - """force_monitoring_refresh auto-starts, and a monitor restarted after - aclose() is out of the cache, so nothing would stop its task.""" - async def _body(): - monitor = _monitor() - monitor.start() - await monitor.aclose() - - monitor.start() - assert not monitor.is_running() - - asyncio.run(_body()) - - -def test_the_inactive_timeout_outlasts_a_long_refresh_interval() -> None: - """Activity is stamped once per tick, so a refresh interval longer than - the inactive timeout had every cleanup sweep disposing a healthy monitor.""" - services_container.get_monitor_service()._monitor_caches.pop( - AsyncClusterTopologyMonitor, None) - props = Properties({ - "host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", - "port": "5432", - "topology_refresh_ms": "300000", # 5 minutes, well past the 3-min default - }) - AsyncAuroraHostListProvider(props, MagicMock()) - - container = services_container.get_monitor_service()._monitor_caches[ - AsyncClusterTopologyMonitor] - assert container.settings.inactive_timeout_ns > 300_000 * 1_000_000 - - -def test_detach_value_reports_whether_it_removed_the_entry() -> None: - """stop_and_remove_value relies on this to tell its caller whether the - removal was theirs.""" - from aws_advanced_python_wrapper.utils.storage.expiration_tracking_cache import \ - ExpirationTrackingCache - - cache: ExpirationTrackingCache = ExpirationTrackingCache( - expiration_timeout_ns=60 * 1_000_000_000) - monitor = _monitor() - cache.compute_if_absent(KEY, lambda _k: monitor) - - assert cache.detach_value(monitor) is True - assert cache.detach_value(monitor) is False - - -def test_a_cluster_on_a_non_default_port_keeps_that_port() -> None: - """The port fell back to the dialect default, so an Aurora cluster reached - on 5433 produced topology hosts on 5432.""" - utils = AsyncAuroraTopologyUtils( - Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", - "port": "5433"}), - "SELECT 1", 5432) - host = utils.create_host("instance-1", is_writer=True) - assert host.port == 5433 - - -def test_global_aurora_reduces_two_writers_to_one() -> None: - """A cross-region switchover can report two writers, and consumers read a - two-writer topology as ambiguous.""" - from aws_advanced_python_wrapper.aio.topology_utils import \ - AsyncGlobalAuroraTopologyUtils - - utils = AsyncGlobalAuroraTopologyUtils( - Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", - "port": "5432"}), - "SELECT 1", 5432, - instance_templates_by_region={"us-east-1": "?.a.us-east-1.rds.amazonaws.com", - "us-west-2": "?.b.us-west-2.rds.amazonaws.com"}) - rows = [ - ("old-writer", True, 0, "us-east-1"), - ("new-writer", True, 0, "us-west-2"), - ] - - topology = utils._process_global_query_results(rows) - - writers = [h for h in topology if h.role == HostRole.WRITER] - assert len(writers) == 1, f"expected one writer, got {writers}" - - -def test_aclose_wakes_a_caller_blocked_on_a_refresh() -> None: - """A blocked caller awaits the event object it read, so aclose() has to - set it before swapping in a fresh one or the caller waits out its own - timeout against an orphan.""" - async def _body(): - monitor = _monitor() - monitor.start() - waiter = asyncio.create_task( - monitor.force_monitoring_refresh(False, timeout_sec=30.0)) - await asyncio.sleep(0.01) - assert not waiter.done() - - await monitor.aclose() - - # Returns promptly rather than after the 30 second timeout. - result = await asyncio.wait_for(waiter, timeout=1.0) - assert result == () - - asyncio.run(_body()) - - -def test_stop_releases_the_monitoring_connection() -> None: - """The monitor service disposes a monitor by calling stop(), so a teardown - it does not schedule leaks a connection on every sweep.""" - conn = MagicMock() - conn.close = MagicMock() - - async def _body(): - monitor = _monitor() - monitor.start() - monitor._owned_conn = conn - - monitor.stop() - for _ in range(10): - await asyncio.sleep(0) - - conn.close.assert_called_once() - assert not monitor.is_running() - # Only aclose() sets _closed, so a task that merely exited on the stop - # signal and closed the connection in its own finally does not pass. - assert monitor._closed, "stop() did not schedule aclose()" - - asyncio.run(_body()) - - -def test_the_provider_removes_a_dead_monitor_by_identity() -> None: - """Removing by key would dispose a live replacement a cleanup pass had - already put there, under the caller using it.""" - services_container.get_monitor_service()._monitor_caches.pop( - AsyncClusterTopologyMonitor, None) - provider = AsyncAuroraHostListProvider( - Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", - "port": "5432"}), - MagicMock()) - - async def _body(): - monitor_service = services_container.get_monitor_service() - key = provider._storage_key() - - # A dead monitor is handed out, and a live replacement is already at - # the key by the time the provider reacts. - dead = _monitor() - live = _monitor() - live.start() - monitor_service.run_if_absent(AsyncClusterTopologyMonitor, key, lambda: live) - - monitor_service.stop_and_remove_value(AsyncClusterTopologyMonitor, dead) - - assert monitor_service.get(AsyncClusterTopologyMonitor, key) is live - assert live.is_running(), "the live replacement was disposed" - await live.aclose() - - asyncio.run(_body()) diff --git a/tests/unit/test_aio_monitor_service_integration.py b/tests/unit/test_aio_monitor_service_integration.py deleted file mode 100644 index 2383623c0..000000000 --- a/tests/unit/test_aio_monitor_service_integration.py +++ /dev/null @@ -1,218 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for 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_alias_tracker.py b/tests/unit/test_aio_multi_alias_tracker.py new file mode 100644 index 000000000..5e136bce6 --- /dev/null +++ b/tests/unit/test_aio_multi_alias_tracker.py @@ -0,0 +1,150 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for multi-alias invalidation in AsyncOpenedConnectionTracker (N.2). + +Fixes the prior canonical-key-only semantics: a tracked connection is +now reachable from ANY alias in host_info.as_aliases(), so an +invalidate_all() call via any alias closes every peer connection to +the same underlying instance. +""" + +from __future__ import annotations + +import asyncio +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ + AsyncOpenedConnectionTracker +from aws_advanced_python_wrapper.hostinfo import HostInfo + + +@pytest.fixture(autouse=True) +def _reset_tracker(): + AsyncOpenedConnectionTracker._tracked.clear() + yield + AsyncOpenedConnectionTracker._tracked.clear() + + +def _host_with_aliases(*aliases: str) -> HostInfo: + """Build a HostInfo whose as_aliases() returns ``aliases``.""" + host = HostInfo(host=aliases[0] if aliases else "h", port=5432) + for alias in aliases[1:]: + host.add_alias(alias) + return host + + +def test_track_records_under_every_alias() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + host = _host_with_aliases( + "instance-1.abcd.us-east-1.rds.amazonaws.com", + "cluster.abcd.us-east-1.rds.amazonaws.com", + ) + tracker.track(host, conn) + + keys = AsyncOpenedConnectionTracker._tracked + # Both aliases (plus canonical) resolve to this conn. + matching = [ + k for k, weak_set in keys.items() + if conn in list(weak_set) + ] + assert len(matching) >= 2 + + +def test_invalidate_reaches_conn_via_secondary_alias() -> None: + """A HostInfo that shares the same secondary alias reaches the same + tracked connection -- even when its primary host differs from the + one the connection was tracked under.""" + tracker = AsyncOpenedConnectionTracker() + + class _Conn: + def __init__(self) -> None: + self.closed = False + + def close(self) -> None: + self.closed = True + + conn = _Conn() + shared_alias = "cluster.abcd.us-east-1.rds.amazonaws.com" + + # Track via a HostInfo whose primary is the instance endpoint. + track_host = _host_with_aliases( + "instance-1.abcd.us-east-1.rds.amazonaws.com", + shared_alias, + ) + tracker.track(track_host, conn) + + # Invalidate via a different HostInfo whose primary is different but + # whose alias set includes the shared cluster endpoint. + invalidate_host = _host_with_aliases( + "instance-7.abcd.us-east-1.rds.amazonaws.com", + shared_alias, + ) + asyncio.run(tracker.invalidate_all(invalidate_host)) + + assert conn.closed is True + + +def test_invalidate_closes_each_conn_exactly_once() -> None: + """Even if a single connection is reachable from multiple aliases, + invalidate_all must only call close() once per connection.""" + tracker = AsyncOpenedConnectionTracker() + + class _Conn: + def __init__(self) -> None: + self.close_count = 0 + + def close(self) -> None: + self.close_count += 1 + + conn = _Conn() + host = _host_with_aliases( + "instance-1.abcd.us-east-1.rds.amazonaws.com", + "cluster.abcd.us-east-1.rds.amazonaws.com", + "cluster-ro.abcd.us-east-1.rds.amazonaws.com", + ) + tracker.track(host, conn) + asyncio.run(tracker.invalidate_all(host)) + + assert conn.close_count == 1 + + +def test_invalidate_swallows_close_errors() -> None: + tracker = AsyncOpenedConnectionTracker() + + class _BadConn: + def close(self) -> None: + raise RuntimeError("boom") + + host = _host_with_aliases("instance-1.abcd.us-east-1.rds.amazonaws.com") + tracker.track(host, _BadConn()) + # Must not raise. + asyncio.run(tracker.invalidate_all(host)) + + +def test_remove_clears_conn_from_every_alias() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + host = _host_with_aliases( + "instance-1.abcd.us-east-1.rds.amazonaws.com", + "cluster.abcd.us-east-1.rds.amazonaws.com", + ) + tracker.track(host, conn) + tracker.remove(host, conn) + + for weak_set in AsyncOpenedConnectionTracker._tracked.values(): + assert conn not in list(weak_set) diff --git a/tests/unit/test_aio_multi_az_host_list_provider.py b/tests/unit/test_aio_multi_az_host_list_provider.py index 9ccf6afe2..2f8a46a4c 100644 --- a/tests/unit/test_aio_multi_az_host_list_provider.py +++ b/tests/unit/test_aio_multi_az_host_list_provider.py @@ -363,9 +363,11 @@ def test_explicit_cluster_id_respected(): assert prov.get_cluster_id() == "my-multi-az-cluster" -def test_default_cluster_id_is_one(): +def test_default_cluster_id_uses_host_port(): prov = _make_provider() - assert prov.get_cluster_id() == "1" + cid = prov.get_cluster_id() + assert "aurora:" in cid # derived helper is shared + assert "cluster-xyz.example.com" in cid # ---- Query failure tolerance -------------------------------------------- diff --git a/tests/unit/test_aio_multi_key_tracker.py b/tests/unit/test_aio_multi_key_tracker.py deleted file mode 100644 index 3b87f4300..000000000 --- a/tests/unit/test_aio_multi_key_tracker.py +++ /dev/null @@ -1,133 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for how AsyncOpenedConnectionTracker keys its connections. - -An instance endpoint names the instance, so one key is enough. Any other -endpoint may be a custom domain name, so the connection is tracked under both -the host id and the endpoint, and an invalidation naming either one finds it. -""" - -from __future__ import annotations - -import asyncio -from unittest.mock import MagicMock - -import pytest - -from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ - AsyncOpenedConnectionTracker -from aws_advanced_python_wrapper.hostinfo import HostInfo - -INSTANCE = "instance-1.abcd.us-east-1.rds.amazonaws.com" -CUSTOM = "db.example.com" - - -@pytest.fixture(autouse=True) -def _reset_tracker(): - AsyncOpenedConnectionTracker._tracked.clear() - yield - AsyncOpenedConnectionTracker._tracked.clear() - - -def _keys_holding(conn) -> set: - return { - key for key, conn_set in AsyncOpenedConnectionTracker._tracked.items() - if conn in list(conn_set)} - - -def test_an_instance_endpoint_is_tracked_under_one_key() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - tracker.track(HostInfo(host=INSTANCE, port=5432, host_id="instance-1"), conn) - - assert _keys_holding(conn) == {f"{INSTANCE}:5432"} - - -def test_any_other_endpoint_is_tracked_under_the_host_id_and_the_endpoint() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - tracker.track(HostInfo(host=CUSTOM, port=5432, host_id="instance-1"), conn) - - assert _keys_holding(conn) == {"instance-1", f"{CUSTOM}:5432"} - - -def test_a_host_without_a_host_id_is_tracked_under_the_endpoint_alone() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - tracker.track(HostInfo(host=CUSTOM, port=5432), conn) - - assert _keys_holding(conn) == {f"{CUSTOM}:5432"} - - -def test_invalidate_reaches_a_connection_through_its_host_id() -> None: - """The endpoint a connection was opened against can differ from the one a - later invalidation names; the host id is what they share.""" - tracker = AsyncOpenedConnectionTracker() - - class _Conn: - def __init__(self) -> None: - self.closed = False - - def close(self) -> None: - self.closed = True - - conn = _Conn() - tracker.track(HostInfo(host=CUSTOM, port=5432, host_id="instance-1"), conn) - - asyncio.run(tracker.invalidate_all( - HostInfo(host=INSTANCE, port=5432, host_id="instance-1"))) - - assert conn.closed is True - - -def test_invalidate_closes_each_connection_exactly_once() -> None: - tracker = AsyncOpenedConnectionTracker() - - class _Conn: - def __init__(self) -> None: - self.close_count = 0 - - def close(self) -> None: - self.close_count += 1 - - conn = _Conn() - host = HostInfo(host=CUSTOM, port=5432, host_id="instance-1") - tracker.track(host, conn) - asyncio.run(tracker.invalidate_all(host)) - - assert conn.close_count == 1 - - -def test_invalidate_swallows_close_errors() -> None: - tracker = AsyncOpenedConnectionTracker() - - class _BadConn: - def close(self) -> None: - raise RuntimeError("boom") - - host = HostInfo(host=INSTANCE, port=5432) - tracker.track(host, _BadConn()) - # Must not raise. - asyncio.run(tracker.invalidate_all(host)) - - -def test_remove_clears_the_connection_from_every_key() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - host = HostInfo(host=CUSTOM, port=5432, host_id="instance-1") - tracker.track(host, conn) - tracker.remove(host, conn) - - assert _keys_holding(conn) == set() diff --git a/tests/unit/test_aio_plugin_service_extras.py b/tests/unit/test_aio_plugin_service_extras.py index b81fcd75a..3e013a65e 100644 --- a/tests/unit/test_aio_plugin_service_extras.py +++ b/tests/unit/test_aio_plugin_service_extras.py @@ -16,7 +16,6 @@ from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole -from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.properties import Properties @@ -74,97 +73,16 @@ def test_get_availability_returns_none_when_unset(): def test_set_then_get_availability(): svc = _make_service() - host = HostInfo("host-1.cluster.example", 5432) - svc._all_hosts = (host,) + svc.set_availability(frozenset({"host-1.cluster.example"}), HostAvailability.UNAVAILABLE) + assert svc.get_availability("host-1.cluster.example") == HostAvailability.UNAVAILABLE - svc.set_availability(host, HostAvailability.UNAVAILABLE) - assert svc.get_availability(host.url) == HostAvailability.UNAVAILABLE - assert host.get_raw_availability() == HostAvailability.UNAVAILABLE - - -def test_set_availability_matches_a_host_by_its_host_id(): - """The caller's host and the topology's host can carry different endpoints - for the same instance, which is what the host id is for.""" - svc = _make_service() - in_topology = HostInfo("instance-1.abc.us-east-1.rds.amazonaws.com", 5432, - host_id="instance-1") - svc._all_hosts = (in_topology,) - - svc.set_availability(HostInfo("db.example.com", 5432, host_id="instance-1"), - HostAvailability.UNAVAILABLE) - - assert in_topology.get_raw_availability() == HostAvailability.UNAVAILABLE - - -def test_set_availability_ignores_a_host_that_is_not_in_the_host_list(): - svc = _make_service() - in_list = HostInfo("h1.example", 5432) - svc._all_hosts = (in_list,) - stranger = HostInfo("stranger.example", 5432) - - svc.set_availability(stranger, HostAvailability.UNAVAILABLE) - - assert svc.get_availability(stranger.url) is None - # Bound both sides: the argument itself is not marked either. - assert stranger.get_raw_availability() == HostAvailability.AVAILABLE - assert in_list.get_raw_availability() == HostAvailability.AVAILABLE - - -def test_set_availability_notifies_only_on_an_actual_change(): - svc = _make_service() - host = HostInfo("h1.example", 5432) - svc._all_hosts = (host,) - manager = MagicMock() - svc.plugin_manager = manager - - # Already AVAILABLE, so nothing changed. - svc.set_availability(host, HostAvailability.AVAILABLE) - manager.notify_host_list_changed.assert_not_called() - - svc.set_availability(host, HostAvailability.UNAVAILABLE) - changes = manager.notify_host_list_changed.call_args.args[0] - assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} - - -def test_set_current_connection_clears_the_routed_host(): - """A switch that reuses a cached connection never runs a connect, so this - is the only thing that stops the next reader of the field seeing the host - the connection has already moved off.""" - async def _body(): - svc = _make_service() - reader = HostInfo("reader-1.example", 5432) - writer = HostInfo("writer-1.example", 5432) - svc.routed_host_info = reader - - await svc.set_current_connection(MagicMock(), writer) - - assert svc.routed_host_info is None - - asyncio.run(_body()) - - -def test_take_routed_host_info_returns_it_once(): - svc = _make_service() - routed = HostInfo("instance-1.example", 5432) - svc.routed_host_info = routed - - assert svc.take_routed_host_info() is routed - assert svc.take_routed_host_info() is None - - -def test_set_availability_writes_the_cache_under_the_host_url(): - """_update_host_availability reads back by url, so the write has to use the - same key or a fresh topology never recovers the mark.""" +def test_set_availability_covers_all_aliases(): svc = _make_service() - host = HostInfo("h1.example", 5432) - svc._all_hosts = (host,) - - svc.set_availability(host, HostAvailability.UNAVAILABLE) - - rebuilt = HostInfo("h1.example", 5432) - svc._update_host_availability((rebuilt,)) - assert rebuilt.get_raw_availability() == HostAvailability.UNAVAILABLE + aliases = frozenset({"h1.example", "h1-alias.example"}) + svc.set_availability(aliases, HostAvailability.UNAVAILABLE) + for alias in aliases: + assert svc.get_availability(alias) == HostAvailability.UNAVAILABLE def test_default_plugin_accepts_random_strategy(): @@ -578,6 +496,64 @@ def test_current_host_info_raises_when_writer_not_allowed(): _ = svc.current_host_info +# ---- fill_aliases (sync parity) -------------------------------------- + + +def _alias_cursor(rows): + cur = MagicMock() + cur.__aenter__ = AsyncMock(return_value=cur) + cur.__aexit__ = AsyncMock(return_value=None) + cur.execute = AsyncMock() + cur.fetchall = AsyncMock(return_value=rows) + return cur + + +def test_fill_aliases_adds_self_query_and_identify_aliases(): + async def _body(): + svc = _make_service() + dialect = MagicMock(spec=DatabaseDialect) + dialect.host_alias_query = "SELECT CONCAT(...)" + svc.database_dialect = dialect + + conn = MagicMock() + conn.cursor = MagicMock(return_value=_alias_cursor([("db-alias",)])) + + identified = HostInfo("h", 5432) + identified.add_alias("id-alias") + svc.identify_connection = AsyncMock(return_value=identified) + + host = HostInfo("h", 5432) + await svc.fill_aliases(conn, host) + + assert "h:5432" in host.aliases # host:port self-alias + assert "db-alias" in host.aliases # from host_alias_query + assert "id-alias" in host.aliases # from identify_connection + + asyncio.run(_body()) + + +def test_fill_aliases_noop_when_already_has_aliases(): + async def _body(): + svc = _make_service() + host = HostInfo("h", 5432) + host.add_alias("existing") + conn = MagicMock() + await svc.fill_aliases(conn, host) + conn.cursor.assert_not_called() + + asyncio.run(_body()) + + +def test_fill_aliases_noop_when_no_connection(): + async def _body(): + svc = _make_service() + host = HostInfo("h", 5432) + await svc.fill_aliases(None, host) + assert len(host.aliases) == 0 + + asyncio.run(_body()) + + # ---- get_host_role default timeout (sync parity) --------------------- @@ -651,7 +627,7 @@ async def _body(): result = asyncio.run(_body()) assert result is conn svc.set_availability.assert_called_once_with( - host, HostAvailability.AVAILABLE) + host.as_aliases(), HostAvailability.AVAILABLE) svc.update_driver_dialect.assert_called_once_with(provider) @@ -672,7 +648,7 @@ async def _body(): asyncio.run(_body()) svc.set_availability.assert_called_once_with( - host, HostAvailability.AVAILABLE) + host.as_aliases(), HostAvailability.AVAILABLE) svc.update_driver_dialect.assert_called_once_with(provider) diff --git a/tests/unit/test_aio_retry_util.py b/tests/unit/test_aio_retry_util.py index 20c56f5af..41dcc385a 100644 --- a/tests/unit/test_aio_retry_util.py +++ b/tests/unit/test_aio_retry_util.py @@ -244,7 +244,7 @@ async def _connect(_host): assert result.connection is conn assert result.host_info.host == _W.host svc.set_availability.assert_any_call( - _W, HostAvailability.AVAILABLE) + _W.as_aliases(), HostAvailability.AVAILABLE) asyncio.run(_body()) @@ -310,7 +310,7 @@ async def _connect(_host): await util.get_writer_connection( svc, hlp, _connect, (dead,), _deadline(0.25)) svc.set_availability.assert_any_call( - dead, HostAvailability.UNAVAILABLE) + dead.as_aliases(), HostAvailability.UNAVAILABLE) asyncio.run(_body()) @@ -360,7 +360,7 @@ async def _connect(host): assert result.connection is conns["new-writer"] # Dead old writer marked unavailable; the reader probe connection dropped. svc.set_availability.assert_any_call( - old, HostAvailability.UNAVAILABLE) + old.as_aliases(), HostAvailability.UNAVAILABLE) svc.driver_dialect.abort_connection.assert_awaited() asyncio.run(_body()) diff --git a/tests/unit/test_aio_simple_rws.py b/tests/unit/test_aio_simple_rws.py index cb764cb42..4f7a75467 100644 --- a/tests/unit/test_aio_simple_rws.py +++ b/tests/unit/test_aio_simple_rws.py @@ -223,13 +223,10 @@ def test_verify_retries_then_falls_back_when_role_mismatches_and_current_usable( async def _body() -> None: # Asked for a reader, but every probe says WRITER -> exhaust retries. svc, dd = _build_plugin_service(role_returns=HostRole.WRITER) - # The budget has to outlast one slow attempt by a wide margin: the - # retry loop checks a wall-clock deadline, and at a 30ms budget a - # scheduling hiccup under the full suite left a single attempt and - # failed the await_count assertions below. + # Extra-short timeout to keep the test quick; still exercises >1 loop. props = _base_props( **{ - WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "250", + WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "30", WrapperProperties.SRW_CONNECT_RETRY_INTERVAL_MS.name: "5", } ) diff --git a/tests/unit/test_aio_topology_storage.py b/tests/unit/test_aio_topology_storage.py deleted file mode 100644 index b83e94564..000000000 --- a/tests/unit/test_aio_topology_storage.py +++ /dev/null @@ -1,314 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""The async provider's topology lives in the storage service. - -Two things here are easy to break silently and have no other coverage: the -storage key type (the sync and async ``Topology`` aliases are different -objects, so using the wrong one writes to an unregistered cache) and the loop -component of the key (which must not be ``id(loop)``, because addresses are -recycled). -""" - -from __future__ import annotations - -import asyncio -from typing import Any -from unittest.mock import AsyncMock, MagicMock - -import pytest - -from aws_advanced_python_wrapper.aio.host_list_provider import \ - AsyncAuroraHostListProvider -from aws_advanced_python_wrapper.aio.topology_store import (StoredTopology, - loop_token) -from aws_advanced_python_wrapper.host_list_provider import \ - Topology as SyncTopology -from aws_advanced_python_wrapper.hostinfo import (HostAvailability, HostInfo, - HostRole) -from aws_advanced_python_wrapper.utils import services_container -from aws_advanced_python_wrapper.utils.properties import Properties - - -def _props(**kwargs: Any) -> Properties: - base = {"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"} - base.update({k: str(v) for k, v in kwargs.items()}) - return Properties(base) - - -def _aurora(**kwargs: Any) -> AsyncAuroraHostListProvider: - props = _props( - cluster_instance_host_pattern="?.cluster-xyz.us-east-1.rds.amazonaws.com", - **kwargs) - return AsyncAuroraHostListProvider(props, driver_dialect=MagicMock()) - - -def _storage(): - return services_container.get_storage_service() - - -HOSTS = (HostInfo("writer.com", 5432, HostRole.WRITER), - HostInfo("reader.com", 5432, HostRole.READER)) - - -# ---- The storage key type ------------------------------------------------ - -def test_the_two_topology_aliases_are_not_interchangeable_as_keys(): - """Why the async module must key storage on the sync alias. - - The sync module imports HostInfo under TYPE_CHECKING only, so its alias is - built from a forward reference and is a different object from the async - one. The storage service is keyed by type, and only the sync alias is - registered -- so keying on the async alias would write to a second, - unregistered cache. - """ - from aws_advanced_python_wrapper.aio.host_list_provider import \ - Topology as AsyncTopology - - assert AsyncTopology != SyncTopology - assert StoredTopology is SyncTopology - - -def test_topology_is_written_to_the_registered_storage_service_entry(): - prov = _aurora() - - async def _run(): - prov._store_topology(HOSTS) - assert _storage().get(StoredTopology, prov._storage_key()) == HOSTS - - asyncio.run(_run()) - - -def test_two_providers_for_one_cluster_on_one_loop_share_the_topology(): - """A second connection to the same cluster does not start from an empty - cache.""" - first, second = _aurora(), _aurora() - - async def _run(): - first._store_topology(HOSTS) - assert await second.refresh() == HOSTS - - asyncio.run(_run()) - - -def test_providers_for_different_clusters_do_not_share(): - a = _aurora(cluster_id="cluster-a") - b = _aurora(cluster_id="cluster-b") - - async def _run(): - a._store_topology(HOSTS) - assert b._get_stored_topology() is None - - asyncio.run(_run()) - - -def test_an_async_entry_does_not_collide_with_a_sync_bare_key_entry(): - """Sync keys by bare cluster id in the same process-global store. - - Topology entries hold mutable HostInfo objects whose availability is - written in place, so a shared entry would let one engine mark the other's - hosts unavailable. - """ - prov = _aurora(cluster_id="shared-id") - sync_hosts = (HostInfo("sync-writer.com", 5432, HostRole.WRITER),) - - async def _run(): - _storage().put(StoredTopology, "shared-id", sync_hosts) - prov._store_topology(HOSTS) - - assert _storage().get(StoredTopology, "shared-id") == sync_hosts - assert prov._get_stored_topology() == HOSTS - - asyncio.run(_run()) - - -# ---- refresh() semantics ------------------------------------------------- - -def test_refresh_returns_the_stored_topology_without_querying(): - """There is no provider-side freshness window any more: a present entry is - returned and the monitor is what keeps it fresh.""" - prov = _aurora() - conn = MagicMock() - prov._topology_utils.query_for_topology = AsyncMock( # type: ignore[method-assign] - side_effect=AssertionError("must not query when topology is stored")) - - async def _run(): - prov._store_topology(HOSTS) - assert await prov.refresh(conn) == HOSTS - - asyncio.run(_run()) - - -def test_refresh_with_no_connection_and_nothing_stored_returns_empty(): - prov = _aurora() - - async def _run(): - assert await prov.refresh() == () - - asyncio.run(_run()) - - -def test_reconfiguring_the_query_discards_the_stored_topology(): - """A result produced by the previous dialect's query is stale.""" - prov = _aurora() - - async def _run(): - prov._store_topology(HOSTS) - prov.reconfigure_topology_query("SELECT 1", 3306) - assert prov._get_stored_topology() is None - - asyncio.run(_run()) - - -def test_reconfiguring_the_query_off_loop_does_not_raise(): - """It is a synchronous method, and the key names a loop.""" - prov = _aurora() - prov.reconfigure_topology_query("SELECT 1", 3306) - - -def test_storing_an_empty_topology_does_not_overwrite_a_good_one(): - prov = _aurora() - - async def _run(): - prov._store_topology(HOSTS) - prov._store_topology(()) - assert prov._get_stored_topology() == HOSTS - - asyncio.run(_run()) - - -# ---- The loop component of the key --------------------------------------- - -def testloop_token_is_stable_within_one_loop(): - async def _run(): - loop = asyncio.get_running_loop() - return loop_token(loop), loop_token(loop) - - first, second = asyncio.run(_run()) - assert first == second - - -def test_loop_token_is_not_the_loop_address(): - """``id(loop)`` is recycled: sequential ``asyncio.run`` calls commonly - reuse one address, so an address-keyed entry would be handed to a fresh - loop -- along with HostInfo objects a previous run may have marked - unavailable.""" - tokens, addresses = [], [] - - async def _run(): - loop = asyncio.get_running_loop() - tokens.append(loop_token(loop)) - addresses.append(id(loop)) - - for _ in range(6): - asyncio.run(_run()) - - assert len(set(tokens)) == 6, "tokens must be unique per loop" - # Not asserting addresses collide -- that is allocator-dependent -- only - # that uniqueness does not come from the address. - assert len(set(addresses)) <= 6 - - -def test_a_loop_that_cannot_be_weak_referenced_still_gets_a_token(): - """Accelerated loops (uvloop) are extension types and may not support - weak references. The fallback is the address, which is only safe because - consumers re-check liveness and replace a dead entry.""" - - class _NoWeakRef: - __slots__ = () - - loop = _NoWeakRef() - token = loop_token(loop) # type: ignore[arg-type] - assert token == f"id:{id(loop)}" - - -def test_storage_key_is_none_when_no_loop_is_running(): - prov = _aurora() - assert prov._storage_key() is None - - -def test_storage_key_pairs_the_cluster_id_with_theloop_token(): - prov = _aurora(cluster_id="my-cluster") - - async def _run(): - return prov._storage_key(), loop_token(asyncio.get_running_loop()) - - key, token = asyncio.run(_run()) - assert key == ("my-cluster", token) - - -@pytest.mark.parametrize("stored,expected", [(HOSTS, HOSTS), (None, ())]) -def test_force_refresh_without_a_connection_falls_back_to_the_store( - stored, expected): - prov = _aurora() - - async def _run(): - if stored is not None: - prov._store_topology(stored) - return await prov.force_refresh() - - assert asyncio.run(_run()) == expected - - -def test_a_reader_gets_copies_not_the_stored_hosts(): - """The entry is shared by every provider on the cluster and loop, and - availability is written into a HostInfo in place, so handing out the - stored objects lets one connection rewrite another's hosts.""" - first, second = _aurora(), _aurora() - - async def _run(): - first._store_topology(HOSTS) - mine = await first.refresh() - theirs = await second.refresh() - - assert mine[0] is not theirs[0], "two readers share one HostInfo" - assert mine[0] is not HOSTS[0], "a reader got the stored object" - - # Marking one unavailable must not touch the other's view. - mine[0].set_availability(HostAvailability.UNAVAILABLE) - assert theirs[0].availability is not HostAvailability.UNAVAILABLE - assert HOSTS[0].availability is not HostAvailability.UNAVAILABLE - - asyncio.run(_run()) - - -def test_copies_keep_their_host_id(): - """host_id is how a live connection is matched back to its topology row.""" - stored = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1") - prov = _aurora() - - async def _run(): - prov._store_topology((stored,)) - got = await prov.refresh() - assert got[0] is not stored - assert got[0].host_id == "srv-1" - - asyncio.run(_run()) - - -def test_copies_keep_their_availability_strategy(): - """The strategy decides when a host marked unavailable becomes usable - again, so a copy that reverted to the no-op default would report it - available straight away.""" - prov = _aurora() - strategy = prov._topology_utils._host_availability_strategy - stored = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1", - host_availability_strategy=strategy) - - async def _run(): - prov._store_topology((stored,)) - got = await prov.refresh() - assert got[0].host_availability_strategy is strategy - - asyncio.run(_run()) diff --git a/tests/unit/test_aio_wrapper.py b/tests/unit/test_aio_wrapper.py index 41a718d3e..c27f4b2b9 100644 --- a/tests/unit/test_aio_wrapper.py +++ b/tests/unit/test_aio_wrapper.py @@ -728,14 +728,9 @@ async def _body() -> None: target=_build_mock_psycopg_connect(raw_conn), conninfo="host=h user=u password=p dbname=d port=5432", ) - # The mock conn hands out one cursor for everything, including the - # wrapper's own auxiliary queries, so measure across the exit alone. - manager = wrapper.cursor() - cur = await manager.__aenter__() - assert isinstance(cur, AsyncAwsWrapperCursor) - before = mock_cursor.close.await_count - await manager.__aexit__(None, None, None) - assert mock_cursor.close.await_count == before + 1 + async with wrapper.cursor() as cur: + assert isinstance(cur, AsyncAwsWrapperCursor) + mock_cursor.close.assert_awaited_once() asyncio.run(_body()) diff --git a/tests/unit/test_aurora_connection_tracker.py b/tests/unit/test_aurora_connection_tracker.py index 6c36d3114..6ab370fe9 100644 --- a/tests/unit/test_aurora_connection_tracker.py +++ b/tests/unit/test_aurora_connection_tracker.py @@ -29,7 +29,6 @@ AuroraConnectionTrackerPlugin, OpenedConnectionTracker) from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.utils.properties import Properties -from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType @pytest.fixture @@ -44,11 +43,7 @@ def mock_cursor(mocker): @pytest.fixture def mock_plugin_service(mocker): - service = mocker.MagicMock() - # A MagicMock attribute would stand in for a routed host and send the - # tracker down the identify path. - service.routed_host_info = None - return service + return mocker.MagicMock() @pytest.fixture @@ -72,13 +67,11 @@ def props(): def test_track_new_instance_connection( - mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_cursor, mock_callable, - mock_conn): + mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_cursor, mock_callable): host_info: HostInfo = HostInfo("instance1") mock_plugin_service.all_hosts = [host_info] mock_plugin_service.current_host_info = host_info mock_rds_utils.is_rds_instance.return_value = True - mock_rds_utils.identify_rds_type.return_value = RdsUrlType.RDS_INSTANCE mock_callable.return_value = mock_conn plugin: AuroraConnectionTrackerPlugin = AuroraConnectionTrackerPlugin(mock_plugin_service, Properties(), @@ -87,35 +80,14 @@ def test_track_new_instance_connection( conn: Connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, Properties(), True, mock_callable) assert mock_conn == conn - mock_tracker.populate_opened_connection_set.assert_called_with(host_info, mock_conn) - # An instance endpoint names the instance, so there is nothing to identify. - mock_plugin_service.identify_connection.assert_not_called() + mock_tracker.populate_opened_connection_queue(host_info, mock_conn) + assert 0 == len(host_info.aliases) conn = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, Properties(), False, mock_callable) assert mock_conn == conn - mock_tracker.populate_opened_connection_set.assert_called_with(host_info, mock_conn) - mock_plugin_service.identify_connection.assert_not_called() - - -def test_connect_tracks_a_cluster_connection_under_its_identified_host( - mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_callable, mock_conn): - """A cluster endpoint does not name the instance the connection landed on, - so the tracker needs the identified host to key it correctly.""" - cluster_host = HostInfo("mydb.cluster-abc.us-east-2.rds.amazonaws.com", 5432) - identified = HostInfo("instance-1.abc.us-east-2.rds.amazonaws.com", 5432, - host_id="instance-1") - mock_rds_utils.identify_rds_type.return_value = RdsUrlType.RDS_WRITER_CLUSTER - mock_plugin_service.identify_connection.return_value = identified - mock_callable.return_value = mock_conn - - plugin = AuroraConnectionTrackerPlugin( - mock_plugin_service, Properties(), mock_rds_utils, mock_tracker) - plugin.connect( - mocker.MagicMock(), mocker.MagicMock(), cluster_host, Properties(), True, mock_callable) - - mock_tracker.populate_opened_connection_set.assert_called_with(identified, mock_conn) - assert mock_plugin_service.routed_host_info is identified + mock_tracker.populate_opened_connection_queue(host_info, mock_conn) + assert 0 == len(host_info.aliases) def test_invalidate_opened_connections( @@ -207,98 +179,6 @@ def test_invalidate_all_connections_drains_set(mocker): assert len(captured) == 1 -def _real_tracker(mocker): - """A tracker with a real RdsUtils and no prune thread or closer thread.""" - OpenedConnectionTracker._opened_connections = {} - mocker.patch.object(OpenedConnectionTracker, "_start_prune_thread") - captured: list = [] - mocker.patch.object( - OpenedConnectionTracker, - "_invalidate_connections", - side_effect=lambda connections_list: captured.append(list(connections_list))) - return OpenedConnectionTracker(), captured - - -def test_a_non_instance_endpoint_is_tracked_under_its_host_id_too(mocker): - """The endpoint a connection was opened against can differ from the one a - later invalidation names; the host id is what they share.""" - tracker, _ = _real_tracker(mocker) - conn = mocker.MagicMock() - - tracker.populate_opened_connection_set( - HostInfo("db.example.com", 5432, host_id="instance-1"), conn) - - assert set(OpenedConnectionTracker._opened_connections) == { - "instance-1", "db.example.com:5432"} - - -def test_an_instance_endpoint_is_tracked_under_one_key(mocker): - tracker, _ = _real_tracker(mocker) - - tracker.populate_opened_connection_set( - HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1"), - mocker.MagicMock()) - - assert set(OpenedConnectionTracker._opened_connections) == { - "instance-1.xyz.us-east-2.rds.amazonaws.com:5432"} - - -def test_invalidate_reaches_a_connection_through_its_host_id(mocker): - tracker, captured = _real_tracker(mocker) - conn = mocker.MagicMock() - tracker.populate_opened_connection_set( - HostInfo("db.example.com", 5432, host_id="instance-1"), conn) - - tracker.invalidate_all_connections( - HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1")) - - assert captured and conn in captured[0] - - -def test_invalidate_closes_a_multi_key_connection_once(mocker): - """Closing a pool-proxied connection twice would invalidate whatever the - pool handed out in between.""" - tracker, captured = _real_tracker(mocker) - conn = mocker.MagicMock() - host = HostInfo("db.example.com", 5432, host_id="instance-1") - tracker.populate_opened_connection_set(host, conn) - - tracker.invalidate_all_connections(host) - - assert len(captured) == 1 - assert captured[0].count(conn) == 1 - - -def test_notify_strips_the_trailing_slash_from_a_change_key( - mocker, mock_plugin_service, mock_rds_utils, mock_callable): - """Change keys are urls; tracking keys are not. Matching them without - stripping would never find the connection.""" - from aws_advanced_python_wrapper.utils.notifications import HostEvent - - tracker, captured = _real_tracker(mocker) - conn = mocker.MagicMock() - host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) - tracker.populate_opened_connection_set(host, conn) - - plugin = AuroraConnectionTrackerPlugin( - mock_plugin_service, Properties(), mock_rds_utils, tracker) - plugin.notify_host_list_changed({host.url: {HostEvent.CONVERTED_TO_READER}}) - - assert captured and conn in captured[0] - - -def test_remove_connection_tracking_clears_every_key(mocker): - tracker, _ = _real_tracker(mocker) - conn = mocker.MagicMock() - host = HostInfo("db.example.com", 5432, host_id="instance-1") - tracker.populate_opened_connection_set(host, conn) - - tracker.remove_connection_tracking(host, conn) - - assert all(conn not in conn_set - for conn_set in OpenedConnectionTracker._opened_connections.values()) - - def test_task_invalidates_pool_proxied_connections(mocker): pool_proxied_conn = mocker.MagicMock() diff --git a/tests/unit/test_cluster_topology_monitor.py b/tests/unit/test_cluster_topology_monitor.py index 66f39f73f..a740c831d 100644 --- a/tests/unit/test_cluster_topology_monitor.py +++ b/tests/unit/test_cluster_topology_monitor.py @@ -357,25 +357,3 @@ 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_connection.py b/tests/unit/test_connection.py index 8e5f20684..30b191b15 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -46,47 +46,6 @@ def test_connection_basic(): password="qwerty") -def _wrapper_with(plugin_service, plugin_manager, conn): - """Drive AwsWrapperConnection.__init__ past its setup to the host-adoption - step, which is what decides the connection's current host.""" - plugin_manager.connect.return_value = conn - plugin_service.database_dialect.get_host_list_provider_supplier.return_value = \ - lambda _service, _props: MagicMock() - wrapper = AwsWrapperConnection.__new__(AwsWrapperConnection) - AwsWrapperConnection.__init__( - wrapper, MagicMock(), MagicMock(), plugin_service, plugin_manager) - return wrapper - - -def test_the_wrapper_adopts_the_host_a_plugin_routed_the_connect_to(): - """The initial connection strategy plugin substitutes an instance for a - cluster endpoint. Binding the connection to the endpoint instead would - leave every later host comparison naming the wrong host.""" - routed = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) - conn = MagicMock(spec=psycopg.Connection) - plugin_service = MagicMock() - plugin_service.current_connection = None - plugin_service.initial_connection_host_info = HostInfo("mydb.cluster-xyz.us-east-2.rds.amazonaws.com", 5432) - plugin_service.take_routed_host_info.return_value = routed - - _wrapper_with(plugin_service, MagicMock(), conn) - - plugin_service.set_current_connection.assert_called_once_with(conn, routed) - - -def test_the_wrapper_falls_back_to_the_initial_host_when_nothing_routed(): - initial = HostInfo("mydb.cluster-xyz.us-east-2.rds.amazonaws.com", 5432) - conn = MagicMock(spec=psycopg.Connection) - plugin_service = MagicMock() - plugin_service.current_connection = None - plugin_service.initial_connection_host_info = initial - plugin_service.take_routed_host_info.return_value = None - - _wrapper_with(plugin_service, MagicMock(), conn) - - plugin_service.set_current_connection.assert_called_once_with(conn, initial) - - def test_connection_getattr_delegates_to_underlying_connection(): # Driver-specific extension methods absent from the wrapper's PEP-249 surface # (e.g. psycopg's add_notice_handler, called by SQLAlchemy) must reach the diff --git a/tests/unit/test_expiration_tracking_cache.py b/tests/unit/test_expiration_tracking_cache.py index a28331ccd..faa4756ae 100644 --- a/tests/unit/test_expiration_tracking_cache.py +++ b/tests/unit/test_expiration_tracking_cache.py @@ -66,6 +66,24 @@ def test_compute_if_absent_extends_expiration(): assert cache.get("k1") == "v1" +def test_get_or_create_for_aliases(cache): + result = cache.get_or_create_for_aliases( + frozenset(["a", "b", "c"]), lambda: "val") + assert result == "val" + assert cache.get("a") == "val" + assert cache.get("b") == "val" + assert cache.get("c") == "val" + + +def test_get_or_create_for_aliases_reuses_existing(cache): + cache.put("b", "existing") + result = cache.get_or_create_for_aliases( + frozenset(["a", "b", "c"]), lambda: "new") + assert result == "existing" + # "a" and "c" should also be set + assert cache.get("a") == "existing" + + def test_extend_expiration(): cache = ExpirationTrackingCache(_SHORT_TTL) cache.put("k1", "v1") diff --git a/tests/unit/test_failover_plugin.py b/tests/unit/test_failover_plugin.py index 2ba1bdbb5..726b0d086 100644 --- a/tests/unit/test_failover_plugin.py +++ b/tests/unit/test_failover_plugin.py @@ -22,7 +22,7 @@ if TYPE_CHECKING: from aws_advanced_python_wrapper.writer_failover_handler import WriterFailoverHandler -from typing import Dict, Set +from typing import Dict, FrozenSet, Set from unittest import mock from unittest.mock import MagicMock, PropertyMock @@ -130,21 +130,27 @@ def test_notify_host_list_changed_with_failover_disabled(plugin_service_mock, ho get_current_host_mock = PropertyMock(return_value=host_mock) type(plugin_service_mock).current_host_info = get_current_host_mock + get_aliases_mock = PropertyMock() + type(host_mock).aliases = get_aliases_mock plugin.notify_host_list_changed(changes) get_current_host_mock.assert_not_called() + get_aliases_mock.assert_not_called() WrapperProperties.ENABLE_FAILOVER.set(properties, "True") plugin = FailoverPlugin(plugin_service_mock, properties) plugin.notify_host_list_changed(changes) get_current_host_mock.assert_called() + get_aliases_mock.assert_not_called() def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_service_mock, host_mock): host_mock.url = "cluster-url/" + aliases: FrozenSet[str] = frozenset("instance") + host_mock.aliases = aliases properties = Properties() WrapperProperties.ENABLE_FAILOVER.set(properties, "True") @@ -152,6 +158,8 @@ def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_s get_current_host_mock = PropertyMock(return_value=host_mock) type(plugin_service_mock).current_host_info = get_current_host_mock + get_aliases_mock = PropertyMock() + type(host_mock).aliases = get_aliases_mock changes: Dict[str, Set[HostEvent]] = \ {"cluster-host/": {HostEvent.HOST_DELETED}, @@ -159,6 +167,7 @@ def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_s plugin.notify_host_list_changed(changes) get_current_host_mock.assert_called() + get_aliases_mock.assert_not_called() def test_update_topology( diff --git a/tests/unit/test_host_monitor_v2_plugin.py b/tests/unit/test_host_monitor_v2_plugin.py index b057e3f4b..273a2e442 100644 --- a/tests/unit/test_host_monitor_v2_plugin.py +++ b/tests/unit/test_host_monitor_v2_plugin.py @@ -46,8 +46,6 @@ def mock_plugin_service(mocker, mock_driver_dialect, mock_conn, host_info): service_mock = mocker.MagicMock() service_mock.current_connection = mock_conn service_mock.current_host_info = host_info - # A MagicMock attribute would stand in for a routed host. - service_mock.routed_host_info = None type(service_mock).driver_dialect = mocker.PropertyMock(return_value=mock_driver_dialect) return service_mock @@ -167,67 +165,28 @@ def test_execute_monitoring_enabled(mocker, plugin, mock_monitor_service, mock_e def test_connect(mocker, plugin, host_info, props, mock_conn, mock_plugin_service): - """A cluster endpoint does not name the instance the connection landed on, - so the instance is identified and recorded as the routed host.""" mock_connect_func = mocker.MagicMock() mock_connect_func.return_value = mock_conn - identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") - mock_plugin_service.identify_connection.return_value = identified connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, props, True, mock_connect_func) - - mock_plugin_service.identify_connection.assert_called_once() - assert mock_plugin_service.routed_host_info is identified + mock_plugin_service.fill_aliases.assert_called_once() assert mock_conn == connection -@pytest.mark.parametrize( - "host", - ["db.example.com", # a custom domain, classified OTHER - "10.0.0.5", # an IP address - "mydb.cluster-custom-xyz.us-east-2.rds.amazonaws.com"]) -def test_a_non_instance_endpoint_has_its_instance_identified( - mocker, mock_plugin_service, mock_monitor_service, props, host): - """These endpoints do not name the instance the connection is on, so the - host to probe has to be resolved rather than taken from the endpoint.""" - identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, - host_id="instance-1") - mock_plugin_service.current_host_info = HostInfo(host, 5432) - mock_plugin_service.identify_connection.return_value = identified - plugin = init_plugin(mock_plugin_service, props, mock_monitor_service) - - assert plugin._get_monitoring_host_info() is identified - - -@pytest.mark.parametrize( - "host", - ["instance-1.xyz.us-east-2.rds.amazonaws.com", - "myproxy.proxy-xyz.us-east-2.rds.amazonaws.com", - "myshardgroup.shardgrp-xyz.us-east-2.rds.amazonaws.com"]) -def test_a_managed_router_endpoint_is_monitored_as_itself( - mocker, mock_plugin_service, mock_monitor_service, props, host): - """A proxy or shard group endpoint stays reachable and is the right thing - to probe. The instance behind it may refuse a direct connection, which - would make the monitor declare a healthy host dead.""" - router = HostInfo(host, 5432) - mock_plugin_service.current_host_info = router - plugin = init_plugin(mock_plugin_service, props, mock_monitor_service) - - assert plugin._get_monitoring_host_info() is router - mock_plugin_service.identify_connection.assert_not_called() +def test_get_monitoring_host_info_errors(mocker, plugin, mock_plugin_service): + mock_plugin_service.identify_connection.return_value = None + with pytest.raises(AwsWrapperError): + plugin._get_monitoring_host_info() -def test_get_monitoring_host_info_keeps_the_host_when_identification_fails( - mocker, plugin, mock_plugin_service, host_info): - """A localhost, IP or custom-domain host cannot be identified. Failing here - would fail every monitored call on a host that is perfectly monitorable.""" - mock_plugin_service.identify_connection.return_value = None - assert plugin._get_monitoring_host_info() is host_info + expected_exception = Error() + mock_plugin_service.identify_connection.return_value = mocker.MagicMock() + mock_plugin_service.identify_connection.side_effect = expected_exception + with pytest.raises(AwsWrapperError) as exc_info: + plugin._get_monitoring_host_info() - plugin._monitoring_host_info = None - mock_plugin_service.identify_connection.side_effect = Error() - assert plugin._get_monitoring_host_info() is host_info + assert expected_exception == exc_info.value.__cause__ def test_release_resources(plugin, mock_monitor_service): diff --git a/tests/unit/test_host_monitoring_plugin.py b/tests/unit/test_host_monitoring_plugin.py index 788845f32..dab274180 100644 --- a/tests/unit/test_host_monitoring_plugin.py +++ b/tests/unit/test_host_monitoring_plugin.py @@ -38,8 +38,6 @@ def mock_plugin_service(mocker, mock_driver_dialect, mock_conn, host_info): service_mock = mocker.MagicMock() service_mock.current_connection = mock_conn service_mock.current_host_info = host_info - # A MagicMock attribute would stand in for a routed host. - service_mock.routed_host_info = None type(service_mock).driver_dialect = mocker.PropertyMock(return_value=mock_driver_dialect) return service_mock @@ -159,78 +157,45 @@ def test_execute_cleanup__connection_not_closed( def test_connect(mocker, plugin, host_info, props, mock_conn, mock_plugin_service): - """A cluster endpoint does not name the instance the connection landed on, - so the instance is identified and recorded as the routed host.""" mock_connect_func = mocker.MagicMock() mock_connect_func.return_value = mock_conn - identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") - mock_plugin_service.identify_connection.return_value = identified connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, props, True, mock_connect_func) - - mock_plugin_service.identify_connection.assert_called_once() - assert mock_plugin_service.routed_host_info is identified + mock_plugin_service.fill_aliases.assert_called_once() assert mock_conn == connection @pytest.mark.parametrize( "host_events", - [{"instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.HOST_DELETED}}, - {"instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.WENT_DOWN}}]) + [{"instance-1.xyz.us-east-2.rds.amazonaws.com": {HostEvent.HOST_DELETED}}, + {"instance-1.xyz.us-east-2.rds.amazonaws.com": {HostEvent.WENT_DOWN}}]) def test_notify_host_list_changed( mocker, plugin, host_info, props, mock_conn, mock_plugin_service, mock_monitor_service, host_events): - monitored = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") + mock_host_info = mocker.MagicMock() + mock_host_info.host = "instance-1.xyz.us-east-2.rds.amazonaws.com" + aliases = frozenset({"instance-1.xyz.us-east-2.rds.amazonaws.com", "alias1", "alias2"}) + mock_host_info.all_aliases = aliases plugin._is_connection_initialized = True - plugin._monitoring_host_info = monitored - mock_plugin_service.current_host_info = monitored + mock_plugin_service.current_host_info = mock_host_info plugin.notify_host_list_changed(host_events) - mock_monitor_service.stop_monitoring_host.assert_called_with(monitored.url) - - -def test_notify_host_list_changed_examines_every_entry( - mocker, plugin, mock_plugin_service, mock_monitor_service): - """set_availability publishes one entry per matched host, so stopping at - the first host with no relevant event drops the rest.""" - monitored = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", host_id="instance-2") - plugin._is_connection_initialized = True - plugin._monitoring_host_info = monitored - mock_plugin_service.current_host_info = monitored + mock_monitor_service.stop_monitoring_host.assert_called_with(aliases) - plugin.notify_host_list_changed({ - "instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.HOST_CHANGED}, - monitored.url: {HostEvent.WENT_DOWN}, - }) - mock_monitor_service.stop_monitoring_host.assert_called_once_with(monitored.url) - - -def test_notify_host_list_changed_after_release_resources( - mocker, plugin, mock_plugin_service, mock_monitor_service): - """A failover worker thread outlives its connection, so it can mark a host - unavailable after this plugin has dropped its monitor service reference.""" - monitored = HostInfo("instance-3.xyz.us-east-2.rds.amazonaws.com", host_id="instance-3") - plugin._is_connection_initialized = True - plugin._monitoring_host_info = monitored - mock_plugin_service.current_host_info = monitored - - plugin.release_resources() - plugin.notify_host_list_changed({monitored.url: {HostEvent.WENT_DOWN}}) - - mock_monitor_service.stop_monitoring_host.assert_not_called() +def test_get_monitoring_host_info_errors(mocker, plugin, mock_plugin_service): + mock_plugin_service.identify_connection.return_value = None + with pytest.raises(AwsWrapperError): + plugin._get_monitoring_host_info() -def test_get_monitoring_host_info_keeps_the_host_when_identification_fails( - mocker, plugin, mock_plugin_service, host_info): - """A localhost, IP or custom-domain host cannot be identified. Failing here - would fail every monitored call on a host that is perfectly monitorable.""" - mock_plugin_service.identify_connection.return_value = None - assert plugin._get_monitoring_host_info() is host_info + expected_exception = Error() + mock_plugin_service.identify_connection.return_value = mocker.MagicMock() + mock_plugin_service.identify_connection.side_effect = expected_exception + with pytest.raises(AwsWrapperError) as exc_info: + plugin._get_monitoring_host_info() - plugin._monitoring_host_info = None - mock_plugin_service.identify_connection.side_effect = Error() - assert plugin._get_monitoring_host_info() is host_info + assert expected_exception == exc_info.value.__cause__ def test_release_resources(plugin, mock_monitor_service): diff --git a/tests/unit/test_hostinfo.py b/tests/unit/test_hostinfo.py index 19a2e5210..917103e19 100644 --- a/tests/unit/test_hostinfo.py +++ b/tests/unit/test_hostinfo.py @@ -24,38 +24,17 @@ def test_host_info_defaults(): host_info = HostInfo("testhost") assert host_info.host == "testhost" assert host_info.is_port_specified() is False - assert host_info.get_host_and_port() == "testhost" + assert len(host_info.aliases) == 0 + assert len(host_info._all_aliases) == 1 assert host_info.role == HostRole.WRITER assert host_info.availability == HostAvailability.AVAILABLE + assert list(host_info._all_aliases)[0] == "testhost" -def test_host_and_port_includes_the_port_when_specified(): - assert HostInfo("testhost", 1234).get_host_and_port() == "testhost:1234" - - -def test_url_keeps_its_trailing_slash(): - """The availability cache, the notify_host_list_changed change map and the - host monitoring monitor keys are all keyed on this exact string.""" - assert HostInfo("testhost", 1234).url == "testhost:1234/" - - -def test_each_host_gets_its_own_availability_strategy(): - """A shared default would count one host's failures against all of them.""" - first = HostInfo("a") - second = HostInfo("b") - assert first.host_availability_strategy is not second.host_availability_strategy - - -def test_copy_carries_the_availability_strategy(): - from copy import copy - - from aws_advanced_python_wrapper.host_availability import \ - ExponentialBackoffHostAvailabilityStrategy - from aws_advanced_python_wrapper.utils.properties import Properties - - strategy = ExponentialBackoffHostAvailabilityStrategy(Properties()) - original = HostInfo("testhost", 1234, host_availability_strategy=strategy) - assert copy(original).host_availability_strategy is strategy +def test_host_as_alias(): + host_info = HostInfo("testhost", 1234) + assert len(host_info._all_aliases) == 1 + assert list(host_info._all_aliases)[0] == "testhost:1234" def test_host_info_eq(): diff --git a/tests/unit/test_monitor_service.py b/tests/unit/test_monitor_service.py index da5235a02..05b297397 100644 --- a/tests/unit/test_monitor_service.py +++ b/tests/unit/test_monitor_service.py @@ -13,12 +13,12 @@ # limitations under the License. from _weakref import ref -from unittest.mock import MagicMock import psycopg import pytest from aws_advanced_python_wrapper import release_resources +from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_monitoring_plugin import \ HostMonitorService from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -57,59 +57,51 @@ def cleanup(): def test_start_monitoring(mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - host_info = HostInfo("instance-1") + aliases = frozenset({"instance-1"}) - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) monitor_service.start_monitoring( - mock_conn, host_info, Properties(), 5000, 1000, 3) + mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) mock_monitor.start_monitoring.assert_called_once() assert mock_monitor == monitor_service._cached_monitor() - assert host_info.url == monitor_service._cached_monitor_host_url + assert aliases == monitor_service._cached_monitor_aliases def test_start_monitoring__cached_monitor( mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - host_info = HostInfo("instance-1") + aliases = frozenset({"instance-1"}) monitor_service._cached_monitor = ref(mock_monitor) - monitor_service._cached_monitor_host_url = host_info.url + monitor_service._cached_monitor_aliases = aliases monitor_service.start_monitoring( - mock_conn, host_info, Properties(), 5000, 1000, 3) + mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) mock_monitor.start_monitoring.assert_called_once() assert mock_monitor == monitor_service._cached_monitor() - assert host_info.url == monitor_service._cached_monitor_host_url + assert aliases == monitor_service._cached_monitor_aliases -def test_start_monitoring__replaces_a_monitor_for_a_different_host( - mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - """The cached monitor is keyed on one host; another host needs its own.""" - stale = MagicMock() - stale.is_stopped = False - monitor_service._cached_monitor = ref(stale) - monitor_service._cached_monitor_host_url = HostInfo("other").url - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) - - monitor_service.start_monitoring( - mock_conn, HostInfo("instance-1"), Properties(), 5000, 1000, 3) - - assert mock_monitor == monitor_service._cached_monitor() - stale.start_monitoring.assert_not_called() +def test_start_monitoring__errors(monitor_service, mock_conn): + with pytest.raises(AwsWrapperError): + monitor_service.start_monitoring( + mock_conn, frozenset(), HostInfo("instance-1"), Properties(), 5000, 1000, 3) def test_stop_monitoring(mocker, monitor_service, mock_monitor, mock_conn): - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) + aliases = frozenset({"instance-1"}) + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) context = monitor_service.start_monitoring( - mock_conn, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) monitor_service.stop_monitoring(context) mock_monitor.stop_monitoring.assert_called_once_with(context) def test_stop_monitoring_host(mocker, monitor_service, mock_monitor): + aliases = frozenset({"alias-1"}) mocker.patch.object(monitor_service._monitor_service, 'get', return_value=mock_monitor) - monitor_service.stop_monitoring_host(HostInfo("instance-1").url) + monitor_service.stop_monitoring_host(aliases) mock_monitor.clear_contexts.assert_called_once() diff --git a/tests/unit/test_multi_az_rds_host_list_provider.py b/tests/unit/test_multi_az_rds_host_list_provider.py index 16c236cce..c15dd6c58 100644 --- a/tests/unit/test_multi_az_rds_host_list_provider.py +++ b/tests/unit/test_multi_az_rds_host_list_provider.py @@ -18,7 +18,6 @@ from aws_advanced_python_wrapper.database_dialect import ( AuroraPgDialect, MultiAzClusterPgDialect) from aws_advanced_python_wrapper.errors import AwsWrapperError -from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.host_list_provider import ( MultiAzTopologyUtils, RdsHostListProvider) from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -160,32 +159,6 @@ def test_get_topology_no_connection(mocker, mock_provider_service, initial_hosts mock_force_refresh.assert_not_called() -def test_multi_az_host_id_is_a_string(mock_provider_service, props): - """MySQL reports a numeric id. identify_connection compares host_id - against the string the host id query returns, so an int never matches and - no cluster-endpoint connection can be identified.""" - provider = create_provider(mock_provider_service, props) - host = provider._topology_utils._create_multi_az_host( - (12345, "instance-1.xyz.us-east-2.rds.amazonaws.com", 5432), 12345) - - assert host.host_id == "12345" - - -def test_initial_hosts_are_handed_out_as_copies(mocker, mock_provider_service, props): - """These are built once and never replaced, so marking a host handed out - here would mark it for every later caller.""" - provider = create_provider(mock_provider_service, props) - provider._initialize() - - first = provider._get_topology(None).hosts - second = provider._get_topology(None).hosts - - assert first[0] is not second[0] - assert first[0] is not provider._initial_hosts[0] - first[0].set_availability(HostAvailability.UNAVAILABLE) - assert provider._initial_hosts[0].get_raw_availability() == HostAvailability.AVAILABLE - - def test_host_pattern_setting(mock_provider_service, props): props = Properties({"host": "127:0:0:1", "port": 5432, WrapperProperties.CLUSTER_INSTANCE_HOST_PATTERN.name: "?.custom-domain.com"}) diff --git a/tests/unit/test_multithreaded_monitor_service.py b/tests/unit/test_multithreaded_monitor_service.py index eb6134794..3c07731d1 100644 --- a/tests/unit/test_multithreaded_monitor_service.py +++ b/tests/unit/test_multithreaded_monitor_service.py @@ -15,7 +15,7 @@ from concurrent.futures import ThreadPoolExecutor from threading import Barrier from time import sleep -from typing import List +from typing import FrozenSet, List import psycopg import pytest @@ -92,19 +92,19 @@ def test_start_monitoring__connections_to_different_hosts( start_monitoring): num_conns = 10 - hosts = generate_hosts(num_conns, True) + host_alias_list = generate_host_aliases(num_conns, True) services = generate_services(num_conns) mocker.patch( "aws_advanced_python_wrapper.host_monitoring_plugin.Monitor.__init__", return_value=None) mocker.patch.object( - services[0]._monitor_service, 'run_if_absent', return_value=mock_monitor) + services[0]._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) # Patch all services to use the same mock for svc in services: svc._monitor_service = services[0]._monitor_service - contexts = start_monitoring(num_conns, services, hosts) + contexts = start_monitoring(num_conns, services, host_alias_list) expected_start_monitoring_calls = [mocker.call(context) for context in contexts] mock_monitor.start_monitoring.assert_has_calls(expected_start_monitoring_calls, True) @@ -119,18 +119,18 @@ def test_start_monitoring__connections_to_same_host( start_monitoring): num_conns = 10 - hosts = generate_hosts(num_conns, False) + host_alias_list = generate_host_aliases(num_conns, False) services = generate_services(num_conns) mocker.patch( "aws_advanced_python_wrapper.host_monitoring_plugin.Monitor.__init__", return_value=None) mocker.patch.object( - services[0]._monitor_service, 'run_if_absent', return_value=mock_monitor) + services[0]._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) for svc in services: svc._monitor_service = services[0]._monitor_service - contexts = start_monitoring(num_conns, services, hosts) + contexts = start_monitoring(num_conns, services, host_alias_list) expected_start_monitoring_calls = [mocker.call(context) for context in contexts] mock_monitor.start_monitoring.assert_has_calls(expected_start_monitoring_calls, True) @@ -173,10 +173,11 @@ def test_stop_monitoring__connections_to_same_host( mock_monitor.stop_monitoring.assert_has_calls(expected_stop_monitoring_calls, True) -def generate_hosts(num_hosts: int, generate_unique_hosts: bool) -> List[HostInfo]: - if generate_unique_hosts: - return [HostInfo(f"host-{i}") for i in range(num_hosts)] - return [HostInfo("single-host") for _ in range(num_hosts)] +def generate_host_aliases(num_aliases: int, generate_unique_aliases: bool) -> List[FrozenSet[str]]: + if generate_unique_aliases: + return [frozenset({f"host-{i}"}) for i in range(num_aliases)] + else: + return [frozenset({"single-host"}) for _ in range(num_aliases)] @pytest.fixture @@ -210,7 +211,7 @@ def start_monitoring(counter, concurrent_counter, start_monitoring_thread): def _start_monitoring( num_threads: int, services: List[HostMonitorService], - hosts: List[HostInfo]) -> List[MonitoringContext]: + host_aliases_list: List[FrozenSet[str]]) -> List[MonitoringContext]: barrier = Barrier(num_threads) futures = [] with ThreadPoolExecutor(num_threads) as executor: @@ -221,7 +222,7 @@ def _start_monitoring( counter, concurrent_counter, services[i], - hosts[i]) + host_aliases_list[i]) futures.append(future) return [future.result() for future in futures] return _start_monitoring @@ -230,13 +231,14 @@ def _start_monitoring( @pytest.fixture def start_monitoring_thread( mock_conn, + host_info, props): def _start_monitoring_thread( barrier: Barrier, counter: AtomicInt, concurrent_counter: AtomicInt, service: HostMonitorService, - host_info: HostInfo) -> MonitoringContext: + host_aliases: FrozenSet[str]) -> MonitoringContext: barrier.wait() val = counter.get_and_increment() @@ -245,6 +247,7 @@ def _start_monitoring_thread( context = service.start_monitoring( mock_conn, + host_aliases, host_info, Properties(), 10, diff --git a/tests/unit/test_plugin_service.py b/tests/unit/test_plugin_service.py index fb2efa5e7..259bc93b3 100644 --- a/tests/unit/test_plugin_service.py +++ b/tests/unit/test_plugin_service.py @@ -13,7 +13,6 @@ # limitations under the License.s from concurrent.futures import TimeoutError -from datetime import datetime, timedelta from unittest.mock import MagicMock, patch import pytest @@ -23,12 +22,9 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, QueryTimeoutError, UnsupportedOperationError) -from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.plugin_service import PluginServiceImpl -from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.properties import Properties -from aws_advanced_python_wrapper.utils.utils import Utils def test_get_host_role_unknown_dialect(mocker): @@ -198,9 +194,7 @@ def decorator(func): plugin_service.get_host_role(mock_conn) -def test_identify_connection_returns_none_when_the_host_id_query_reports_nothing(mocker): - """Unidentifiable is not a failure: the connect hooks that call this would - otherwise turn an unreported host id into a failed connect.""" +def test_identify_connection_error_no_result(mocker): mock_conn = MagicMock() mock_cursor = MagicMock() mock_cursor.fetchone.return_value = None @@ -231,7 +225,8 @@ def decorator(func): mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) - assert plugin_service.identify_connection(mock_conn) is None + with pytest.raises(AwsWrapperError): + plugin_service.identify_connection(mock_conn) def test_identify_connection_timeout(mocker): @@ -381,15 +376,13 @@ def decorator(func): def test_identify_connection_host_in_topology_multiaz(mocker): mock_conn = MagicMock() mock_cursor = MagicMock() - # Multi-AZ returns different values: (instanceId, instanceName). The - # topology carries the id, which is what the first clause matches on. + # Multi-AZ returns different values: (instanceId, instanceName) mock_cursor.fetchone.return_value = ("db-WQFQKBTL2LQUPIEFIFBGENS4ZQ", "instance-1") mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) mock_cursor.__exit__ = MagicMock(return_value=False) mock_conn.cursor.return_value = mock_cursor - expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, - host_id="db-WQFQKBTL2LQUPIEFIFBGENS4ZQ") + expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, host_id="instance-1") mock_container = mocker.MagicMock() mock_container.plugin_manager = mocker.MagicMock() @@ -418,239 +411,7 @@ def decorator(func): host_info = plugin_service.identify_connection(mock_conn) assert host_info is not None assert "instance-1.xyz.us-east-2.rds.amazonaws.com" == host_info.host - assert "db-WQFQKBTL2LQUPIEFIFBGENS4ZQ" == host_info.host_id - - -def test_identify_connection_matches_on_the_instance_name_column(mocker): - """The second column is matched against the host, not the host id. - - A topology whose host ids come from somewhere other than host_id_query - is still identifiable as long as the name column names the host. - """ - mock_conn = MagicMock() - mock_cursor = MagicMock() - mock_cursor.fetchone.return_value = ( - "unmatched-id", "instance-1.xyz.us-east-2.rds.amazonaws.com") - mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) - mock_cursor.__exit__ = MagicMock(return_value=False) - mock_conn.cursor.return_value = mock_cursor - - expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, - host_id="db-SOMETHINGELSE") - - mock_container = mocker.MagicMock() - mock_container.plugin_manager = mocker.MagicMock() - mock_host_list_provider = mocker.MagicMock() - mock_host_list_provider.refresh.return_value = (expected_host,) - - plugin_service = PluginServiceImpl( - mock_container, - Properties({"host": "test.com", "port": 5432}), - lambda: None, - mocker.MagicMock(), - mocker.MagicMock() - ) - plugin_service._database_dialect = MultiAzClusterPgDialect() - plugin_service._current_connection = mock_conn - plugin_service._host_list_provider = mock_host_list_provider - - def mock_preserve(thread_pool, timeout, driver_dialect, conn): - def decorator(func): - return func - return decorator - - mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) - - assert plugin_service.identify_connection(mock_conn) is expected_host - - -def _service_with_hosts(mocker, hosts, props=None): - container = mocker.MagicMock() - container.plugin_manager = mocker.MagicMock() - service = PluginServiceImpl( - container, - Properties(props or {"host": "test.com"}), - lambda: None, - mocker.MagicMock(), - mocker.MagicMock()) - service._all_hosts = tuple(hosts) - return service, container - - -def test_identify_connection_returns_none_when_the_host_id_query_errors(mocker): - """The connect hooks that identify a host call this. A host the database - declines to name must not fail their connect.""" - mock_conn = MagicMock() - mock_conn.cursor.side_effect = Exception("relation does not exist") - - service, _ = _service_with_hosts(mocker, ()) - service._database_dialect = AuroraPgDialect() - service._current_connection = mock_conn - service._host_list_provider = mocker.MagicMock() - - def mock_preserve(thread_pool, timeout, driver_dialect, conn): - def decorator(func): - return func - return decorator - - mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) - - assert service.identify_connection(mock_conn) is None - - -def test_set_availability_marks_the_host_and_caches_it(mocker): - host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") - service, container = _service_with_hosts(mocker, (host,)) - - service.set_availability(host, HostAvailability.UNAVAILABLE) - - assert host.get_raw_availability() == HostAvailability.UNAVAILABLE - assert service.get_availability(host.url) == HostAvailability.UNAVAILABLE - changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] - assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} - - -def test_set_availability_matches_by_host_id_and_is_case_insensitive_on_the_name(mocker): - by_id = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") - by_name = HostInfo("Instance-2.XYZ.us-east-2.rds.amazonaws.com", 5432) - untouched = HostInfo("instance-3.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-3") - service, _ = _service_with_hosts(mocker, (by_id, by_name, untouched)) - - service.set_availability(HostInfo("other.example", 5432, host_id="instance-1"), - HostAvailability.UNAVAILABLE) - service.set_availability(HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432), - HostAvailability.UNAVAILABLE) - - assert by_id.get_raw_availability() == HostAvailability.UNAVAILABLE - assert by_name.get_raw_availability() == HostAvailability.UNAVAILABLE - # Bound the other side: a match is not a licence to mark the whole list. - assert untouched.get_raw_availability() == HostAvailability.AVAILABLE - - -def test_set_availability_reports_a_host_coming_back_up(mocker): - """Inverting the event ternary would otherwise pass the suite.""" - host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, - availability=HostAvailability.UNAVAILABLE) - service, container = _service_with_hosts(mocker, (host,)) - - service.set_availability(host, HostAvailability.AVAILABLE) - - changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] - assert changes == {host.url: {HostEvent.WENT_UP, HostEvent.HOST_CHANGED}} - - -def test_set_availability_reports_every_matched_host(mocker): - """One entry per matched host, so a subscriber that stops at the first - one drops the rest.""" - first = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="shared") - second = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="shared") - service, container = _service_with_hosts(mocker, (first, second)) - - service.set_availability(HostInfo("other.example", 5432, host_id="shared"), - HostAvailability.UNAVAILABLE) - - changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] - assert set(changes) == {first.url, second.url} - - -def test_set_availability_reads_availability_through_the_backoff_strategy(mocker): - """A host whose backoff window has elapsed reads as available again, so - marking it down is a change the plugins have to hear about.""" - from aws_advanced_python_wrapper.host_availability import \ - ExponentialBackoffHostAvailabilityStrategy - - props = Properties({"host": "test.com", - "host_availability_strategy_initial_backoff_time": "1", - "host_availability_strategy_max_retries": "5"}) - strategy = ExponentialBackoffHostAvailabilityStrategy(props) - host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, - availability=HostAvailability.UNAVAILABLE, - host_availability_strategy=strategy) - # Back-date the last change so the retry window has elapsed. - strategy._not_available_count = 1 - strategy._last_changed = datetime.now() - timedelta(seconds=30) - assert host.get_availability() == HostAvailability.AVAILABLE - - service, container = _service_with_hosts(mocker, (host,)) - service.set_availability(host, HostAvailability.UNAVAILABLE) - - changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] - assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} - - -def test_set_availability_does_not_notify_when_nothing_changed(mocker): - host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) - service, container = _service_with_hosts(mocker, (host,)) - - service.set_availability(host, HostAvailability.AVAILABLE) - - # The host did match, so this is "matched but unchanged" rather than the - # early return for an unmatched host. - assert service.get_availability(host.url) == HostAvailability.AVAILABLE - container.plugin_manager.notify_host_list_changed.assert_not_called() - - -def test_set_availability_ignores_a_host_outside_the_host_list(mocker): - in_list = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) - service, container = _service_with_hosts(mocker, (in_list,)) - stranger = HostInfo("stranger.example", 5432) - - service.set_availability(stranger, HostAvailability.UNAVAILABLE) - - assert service.get_availability(stranger.url) is None - # Bound both sides: neither the argument nor the host list is touched. - assert stranger.get_raw_availability() == HostAvailability.AVAILABLE - assert in_list.get_raw_availability() == HostAvailability.AVAILABLE - container.plugin_manager.notify_host_list_changed.assert_not_called() - - -def test_connect_clears_a_routed_host_left_by_an_earlier_connect(mocker): - """The routed host belongs to one connect. A value left behind would be - read by the next one, which keys the connection tracker and picks the - monitoring host off the previous connect's instance.""" - service, container = _service_with_hosts(mocker, ()) - stale = HostInfo("reader-1.xyz.us-east-2.rds.amazonaws.com", 5432) - service.routed_host_info = stale - observed = {} - - def _record(*args, **kwargs): - observed["routed"] = service.routed_host_info - return MagicMock() - - container.plugin_manager.connect = _record - service.connect(HostInfo("reader-2.xyz.us-east-2.rds.amazonaws.com", 5432), Properties()) - - assert observed["routed"] is None - - -def test_take_routed_host_info_returns_it_once(mocker): - service, _ = _service_with_hosts(mocker, ()) - routed = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) - service.routed_host_info = routed - - assert service.take_routed_host_info() is routed - assert service.take_routed_host_info() is None - - -def test_find_host_does_not_match_an_instance_name_against_a_host_id(): - """A name-against-id clause picks the decoy that happens to carry the name - as its id. On Multi-AZ the name and the id come from different columns, so - such a clause would match the wrong row rather than be harmless.""" - decoy = HostInfo("decoy.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") - wanted = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="db-AAA") - - found = Utils.find_host((decoy, wanted), "db-AAA", "instance-1.xyz.us-east-2.rds.amazonaws.com") - - assert found is wanted - - -def test_find_host_matches_on_either_column(): - aurora = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") - assert Utils.find_host((aurora,), "instance-1", "instance-1") is aurora - - by_name = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="db-BBB") - assert Utils.find_host( - (by_name,), "unmatched", "instance-2.xyz.us-east-2.rds.amazonaws.com") is by_name + assert "instance-1" == host_info.host_id def test_could_not_determine_current_host_raises_resolved_message(): diff --git a/tests/unit/test_reader_failover_handler.py b/tests/unit/test_reader_failover_handler.py index 58a056a8d..f4ccc537b 100644 --- a/tests/unit/test_reader_failover_handler.py +++ b/tests/unit/test_reader_failover_handler.py @@ -75,9 +75,9 @@ def test_failover(plugin_service_mock, connection_mock, default_properties, defa props = default_properties current_host = hosts[2] success_host = hosts[4] - expected = [call(x, HostAvailability.UNAVAILABLE) + expected = [call(x.all_aliases, HostAvailability.UNAVAILABLE) if x != success_host - else call(x, HostAvailability.AVAILABLE) + else call(x.all_aliases, HostAvailability.AVAILABLE) for x in hosts] exception = Exception("Test Exception") @@ -170,7 +170,7 @@ def force_connect_side_effect(host_info, _) -> Connection: assert result.connection == connection_mock assert result.new_host == fast_host - plugin_service_mock.set_availability.assert_any_call(fast_host, HostAvailability.AVAILABLE) + plugin_service_mock.set_availability.assert_any_call(fast_host.all_aliases, HostAvailability.AVAILABLE) def test_get_reader_connection_failure(plugin_service_mock, connection_mock, default_properties, default_hosts): diff --git a/tests/unit/test_storage_service.py b/tests/unit/test_storage_service.py index 893979df4..69d44c0b5 100644 --- a/tests/unit/test_storage_service.py +++ b/tests/unit/test_storage_service.py @@ -147,29 +147,6 @@ 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") diff --git a/tests/unit/test_writer_failover_handler.py b/tests/unit/test_writer_failover_handler.py index 7a64f6d89..4eaeccf2f 100644 --- a/tests/unit/test_writer_failover_handler.py +++ b/tests/unit/test_writer_failover_handler.py @@ -105,6 +105,14 @@ def new_topology(new_writer_host, reader_a, reader_b): return tuple([new_writer_host, reader_a, reader_b]) +@pytest.fixture(autouse=True) +def setup(writer, new_writer_host, reader_a, reader_b): + writer.add_alias("writer-host") + new_writer_host.add_alias("new-writer-host") + reader_a.add_alias("reader-a") + reader_b.add_alias("reader-b") + + def test_reconnect_to_writer_task_b_reader_exception( writer_connection_mock, plugin_service_mock, reader_failover_mock, default_properties, writer, topology): exception = Exception("Test Exception") @@ -134,8 +142,8 @@ def force_connect_side_effect(host_info, _) -> Connection: assert not result.is_new_host assert result.new_connection is writer_connection_mock - expected = [call(writer, HostAvailability.UNAVAILABLE), - call(writer, HostAvailability.AVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), + call(writer.as_aliases(), HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -145,8 +153,8 @@ def test_reconnect_to_writer_slow_task_b( reader_a_connection_mock, default_properties, new_writer_host, writer, reader_a, reader_b, topology, new_topology): exception = Exception("Test Exception") - expected = [call(writer, HostAvailability.UNAVAILABLE), - call(writer, HostAvailability.AVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), + call(writer.as_aliases(), HostAvailability.AVAILABLE)] mock_hosts_property = mocker.PropertyMock(side_effect=chain((topology,), cycle((new_topology,)))) type(plugin_service_mock).all_hosts = mock_hosts_property @@ -219,8 +227,8 @@ def get_reader_connection_side_effect(_): assert not result.is_new_host assert result.new_connection is writer_connection_mock - expected = [call(writer, HostAvailability.UNAVAILABLE), - call(writer, HostAvailability.AVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), + call(writer.as_aliases(), HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -266,8 +274,8 @@ def get_reader_connection_side_effect(_): assert result.is_new_host assert result.new_connection is new_writer_connection_mock - expected = [call(writer, HostAvailability.UNAVAILABLE), - call(new_writer_host, HostAvailability.AVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), + call(new_writer_host.as_aliases(), HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -317,8 +325,8 @@ def get_reader_connection_side_effect(_): assert len(result.topology) == 4 assert "new-writer-host" == result.topology[0].host - expected = [call(writer, HostAvailability.UNAVAILABLE), - call(new_writer_host, HostAvailability.AVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), + call(new_writer_host.as_aliases(), HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected, any_order=True) @@ -369,7 +377,7 @@ def get_reader_connection_side_effect(_): assert not result.is_connected assert not result.is_new_host - expected = [call(writer, HostAvailability.UNAVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -412,7 +420,7 @@ def get_reader_connection_side_effect(_): assert not result.is_connected assert not result.is_new_host - expected = [call(writer, HostAvailability.UNAVAILABLE), - call(new_writer_host, HostAvailability.UNAVAILABLE)] + expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), + call(new_writer_host.as_aliases(), HostAvailability.UNAVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected, any_order=True)