From 152d0ae8504b84b15799e904acf3dacb710d538c Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Mon, 19 Oct 2026 19:35:03 -0700 Subject: [PATCH 1/2] refactor: identify hosts by host id and host-and-port instead of aliases --- .../aio/aurora_connection_tracker.py | 233 +++++--------- ...rora_initial_connection_strategy_plugin.py | 21 +- .../aio/blue_green_plugin.py | 1 - .../aio/cluster_topology_monitor.py | 39 +-- .../aio/default_plugin.py | 11 +- .../aio/dialect_utils.py | 24 +- .../aio/failover_plugin.py | 12 +- .../aio/host_list_provider.py | 15 +- .../aio/host_monitoring_plugin.py | 81 +++-- .../aio/limitless_plugin.py | 15 + .../aio/plugin_service.py | 155 +++++---- .../aio/read_write_splitting_plugin.py | 13 +- aws_advanced_python_wrapper/aio/retry_util.py | 10 +- .../aio/topology_store.py | 18 +- .../aio/topology_utils.py | 21 +- aws_advanced_python_wrapper/aio/wrapper.py | 6 +- .../aurora_connection_tracker_plugin.py | 137 ++++---- ...rora_initial_connection_strategy_plugin.py | 17 +- .../aws_credentials_manager.py | 2 +- .../blue_green_plugin.py | 1 - .../database_dialect.py | 28 +- aws_advanced_python_wrapper/default_plugin.py | 2 +- .../failover_plugin.py | 15 +- .../failover_v2_plugin.py | 4 +- .../host_list_provider.py | 30 +- .../host_monitoring_plugin.py | 135 ++++---- .../host_monitoring_v2_plugin.py | 66 ++-- aws_advanced_python_wrapper/hostinfo.py | 56 +--- .../limitless_plugin.py | 15 + aws_advanced_python_wrapper/plugin_service.py | 141 +++++---- .../read_write_splitting_plugin.py | 15 +- .../reader_failover_handler.py | 6 +- ...dvanced_python_wrapper_messages.properties | 12 - .../utils/concurrent.py | 19 -- .../utils/monitor_service.py | 11 +- .../storage/expiration_tracking_cache.py | 9 +- aws_advanced_python_wrapper/utils/utils.py | 46 +++ aws_advanced_python_wrapper/wrapper.py | 6 +- .../writer_failover_handler.py | 17 +- docs/development-guide/PluginService.md | 18 ++ .../test_aio_aurora_connection_tracker.py | 58 ++-- .../test_aio_aurora_initial_connection.py | 16 +- tests/unit/test_aio_dialect_utils.py | 2 +- tests/unit/test_aio_failover_plugin.py | 8 +- tests/unit/test_aio_host_list_provider.py | 25 +- tests/unit/test_aio_host_monitoring_plugin.py | 2 +- .../test_aio_monitor_lifecycle_regressions.py | 296 ++++++++++++++++++ tests/unit/test_aio_multi_alias_tracker.py | 150 --------- tests/unit/test_aio_multi_key_tracker.py | 133 ++++++++ tests/unit/test_aio_plugin_service_extras.py | 174 +++++----- tests/unit/test_aio_retry_util.py | 6 +- tests/unit/test_aio_simple_rws.py | 7 +- tests/unit/test_aio_topology_storage.py | 30 +- tests/unit/test_aio_wrapper.py | 11 +- tests/unit/test_aurora_connection_tracker.py | 132 +++++++- tests/unit/test_connection.py | 41 +++ tests/unit/test_expiration_tracking_cache.py | 18 -- tests/unit/test_failover_plugin.py | 11 +- tests/unit/test_host_monitor_v2_plugin.py | 63 +++- tests/unit/test_host_monitoring_plugin.py | 73 +++-- tests/unit/test_hostinfo.py | 35 ++- tests/unit/test_monitor_service.py | 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_writer_failover_handler.py | 34 +- 67 files changed, 1979 insertions(+), 1188 deletions(-) create mode 100644 tests/unit/test_aio_monitor_lifecycle_regressions.py delete mode 100644 tests/unit/test_aio_multi_alias_tracker.py create mode 100644 tests/unit/test_aio_multi_key_tracker.py diff --git a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py index 468a8e4eb..c338b574a 100644 --- a/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py +++ b/aws_advanced_python_wrapper/aio/aurora_connection_tracker.py @@ -16,11 +16,11 @@ Port of sync ``aurora_connection_tracker_plugin.py``. Tracks every connection opened through the plugin pipeline in a class-level -:class:`AsyncOpenedConnectionTracker` registry keyed by the RDS -instance-endpoint alias (mirroring sync normalization). On writer -change (detected via ``AsyncPluginService.all_hosts`` or a raised -:class:`FailoverError`), closes every tracked connection to the old -writer so pooled consumers don't reuse a stale demoted-writer socket. +:class:`AsyncOpenedConnectionTracker` registry keyed by host id and by +host and port. On writer change (detected via +``AsyncPluginService.all_hosts`` or a raised :class:`FailoverError`), +closes every tracked connection to the old writer so pooled consumers +don't reuse a stale demoted-writer socket. Simpler than the sync implementation: @@ -47,7 +47,7 @@ import threading from time import perf_counter_ns from typing import (TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, - Optional, Set) + Optional, Set, Tuple) from weakref import WeakSet from aws_advanced_python_wrapper.aio.cleanup import register_shutdown_hook @@ -58,6 +58,7 @@ from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils +from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from aws_advanced_python_wrapper.aio.driver_dialect.base import \ @@ -70,24 +71,17 @@ class AsyncOpenedConnectionTracker: - """Alias-keyed registry of open connections, shared across plugin instances. + """Registry of open connections, shared across plugin instances. - Keys by the RDS **instance** endpoint alias when one is present in - ``host_info.as_aliases()`` -- matching sync's - :class:`OpenedConnectionTracker` at - ``aurora_connection_tracker_plugin.py:47``. Falls back to - ``host_info.as_alias()`` when no RDS instance alias is - discoverable (non-Aurora or custom endpoint connections). + An instance endpoint names the instance already, so its connections are + tracked under one key. Any other endpoint may be a custom domain name, + which is tracked both under the host id and under the endpoint the caller + used, so a later notification naming either one finds the connections. - This lets a cluster-endpoint-connected session still be - invalidated when a later ``CONVERTED_TO_READER`` notification - carries the instance alias. - - Class-level ``_tracked`` mirrors sync ``OpenedConnectionTracker`` at - ``aurora_connection_tracker_plugin.py:47`` so multiple pooled - :class:`AsyncAuroraConnectionTrackerPlugin` instances can coordinate: - one plugin's :meth:`invalidate_all` closes every peer connection to - the same host. + ``_tracked`` is class-level, as sync's registry is, so multiple pooled + :class:`AsyncAuroraConnectionTrackerPlugin` instances coordinate: one + plugin's :meth:`invalidate_all` closes every peer connection to the same + host. Still simpler than sync: @@ -101,74 +95,49 @@ def __init__(self) -> None: # Instance-level nothing -- all state lives on the class dict. pass - @staticmethod - def _canonical_key(host_info: HostInfo) -> str: - """Return the instance-endpoint alias if available, else host:port. - - 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() + _rds_utils: ClassVar[RdsUtils] = RdsUtils() - @staticmethod - def _all_keys(host_info: HostInfo) -> Set[str]: - """Return every alias worth tracking ``host_info`` under. - - Sync's ``OpenedConnectionTracker`` tracks connections keyed on - every alias in ``host_info.as_aliases()`` so a later invalidation - via any alias closes the same underlying connection set. We - mirror that here: track under each alias plus the canonical - RDS-instance endpoint. - """ - keys: Set[str] = set() - canonical = AsyncOpenedConnectionTracker._canonical_key(host_info) - if canonical: - keys.add(canonical) - try: - for alias in host_info.as_aliases(): - if alias: - keys.add(alias) - except Exception: # noqa: BLE001 - as_aliases() is best-effort - pass - return keys + @classmethod + def _tracking_keys(cls, host_info: HostInfo) -> Tuple[str, ...]: + """The keys ``host_info``'s connections are tracked under.""" + if cls._rds_utils.is_rds_instance(host_info.host): + return (host_info.get_host_and_port(),) + return tuple( + key for key in (host_info.host_id, host_info.get_host_and_port()) if key) def track(self, host_info: HostInfo, conn: Any) -> None: - for key in self._all_keys(host_info): + for key in self._tracking_keys(host_info): conn_set = AsyncOpenedConnectionTracker._tracked.setdefault( key, WeakSet()) conn_set.add(conn) def remove(self, host_info: HostInfo, conn: Any) -> None: - for key in self._all_keys(host_info): + for key in self._tracking_keys(host_info): conn_set = AsyncOpenedConnectionTracker._tracked.get(key) if conn_set is not None: conn_set.discard(conn) async def invalidate_all(self, host_info: HostInfo) -> None: - """Close every tracked connection reachable via any alias of ``host_info``. - - Best-effort: individual close failures are swallowed so one - broken connection doesn't block closing the rest. Fixes the - prior canonical-key-only semantics that could miss invalidations - when the caller held a non-canonical alias. - """ - # Gather the full connection set from every alias; close each - # connection exactly once, then purge the alias entries. + """Close every connection tracked for ``host_info``.""" logger.debug( "OpenedConnectionTracker.InvalidatingConnections", host_info.url) + await self.invalidate_all_for_keys( + host_info.get_host_and_port(), host_info.host, host_info.host_id) + + async def invalidate_all_for_keys(self, *keys: Optional[str]) -> None: + """Close every connection tracked under any of ``keys``. + + Best-effort: individual close failures are swallowed so one broken + connection does not block closing the rest. + """ seen_conns: Set[int] = set() to_close: list = [] - keys = self._all_keys(host_info) - for key in keys: - conn_set = AsyncOpenedConnectionTracker._tracked.get(key) + present = tuple(key for key in keys if key) + # Drop each key before the first await. Collecting everything first + # and popping afterwards would discard a connection a concurrent + # track() added in between, leaving it open and untracked. + for key in present: + conn_set = AsyncOpenedConnectionTracker._tracked.pop(key, None) if conn_set is None: continue for c in list(conn_set): @@ -205,18 +174,14 @@ async def invalidate_all(self, host_info: HostInfo) -> None: # is_closed=False to its owner. logger.debug( f"[AsyncOpenedConnectionTracker] best-effort close of a " - f"tracked connection to '{host_info.url}' failed: {e}") - - for key in keys: - try: - del AsyncOpenedConnectionTracker._tracked[key] - except KeyError: - pass + f"tracked connection failed: {e}") def _tracked_for(self, host_info: HostInfo) -> WeakSet[Any]: - """Test-only accessor using the canonical key derivation.""" - key = self._canonical_key(host_info) - return AsyncOpenedConnectionTracker._tracked.get(key, WeakSet()) + """Test-only accessor using the first tracking key.""" + keys = self._tracking_keys(host_info) + if not keys: + return WeakSet() + return AsyncOpenedConnectionTracker._tracked.get(keys[0], WeakSet()) def log_opened_connections(self) -> None: """Debug-log the registry contents (sync parity: @@ -295,11 +260,34 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: conn = await connect_func() if conn is not None: - await self._fill_instance_alias(host_info, conn) - self._tracker.track(host_info, conn) - await self._pin_current_writer(host_info, conn) + connection_host_info = await self._identify_connection_host(host_info, conn) + self._tracker.track(connection_host_info, conn) + await self._pin_current_writer(connection_host_info, conn) return conn + async def _identify_connection_host( + self, host_info: HostInfo, conn: Any) -> HostInfo: + """The host this connection actually landed on. + + A cluster, custom-domain or IP endpoint does not name the instance the + connection reached, so ask the database and record the answer as the + routed host. On failure the endpoint the caller used is kept. + """ + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + url_type = AsyncOpenedConnectionTracker._rds_utils.identify_rds_type( + connection_host_info.host) + if not Utils.requires_host_identification(url_type): + return connection_host_info + try: + identified = await self._plugin_service.identify_connection(conn) + except Exception: # noqa: BLE001 - identification is best-effort + return connection_host_info + if identified is None: + return connection_host_info + self._plugin_service.routed_host_info = identified + return identified + async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: """Pin the current writer at connect time so a later failover is detected as a *transition*. @@ -349,39 +337,6 @@ async def _pin_current_writer(self, host_info: HostInfo, conn: Any) -> None: except Exception: # noqa: BLE001 - writer pinning is best-effort pass - async def _fill_instance_alias( - self, host_info: HostInfo, conn: Any) -> None: - """Add the connection's resolved instance endpoint as an alias. - - A cluster-endpoint connection lands on whichever instance the - cluster DNS currently points at, but ``host_info.host`` stays the - cluster endpoint -- so the tracker would key it only under the - cluster alias. On writer failover the change is detected against - the *instance* host (``_current_writer_from_hosts`` returns a - topology row), so ``invalidate_all(writer_instance)`` would never - match the cluster-keyed entry and the stale idle connection would - survive the demotion (``test_writer_failover_in_idle_connections``). - - Mirrors sync ``AuroraConnectionTrackerPlugin.connect`` which calls - ``plugin_service.fill_aliases`` for ``is_rds_cluster`` hosts. Only - cluster-endpoint connections pay the extra identify round-trip; - instance-endpoint connections already key correctly. Best-effort: - on any failure we fall back to cluster-key-only tracking (the - prior behavior), so a transient identify failure never blocks the - connect. - """ - try: - if not RdsUtils().identify_rds_type(host_info.host).is_rds_cluster: - return - identified = await self._plugin_service.identify_connection(conn) - if identified is None: - return - host_info.reset_aliases() - host_info.add_alias(host_info.as_alias()) - host_info.add_alias(*identified.as_aliases()) - except Exception: # noqa: BLE001 - alias enrichment is best-effort - pass - async def execute( self, target: object, @@ -543,14 +498,14 @@ def _current_writer_from_hosts(self) -> Optional[HostInfo]: def _same_host(a: HostInfo, b: HostInfo) -> bool: return a.host == b.host and a.port == b.port - def _spawn_invalidation(self, old_writer: HostInfo) -> None: + def _spawn_invalidation(self, key: str) -> None: """Fire-and-forget invalidation, ONLY for the sync-signature :meth:`notify_host_list_changed` path (cannot await there). The execute/failover path awaits :meth:`_invalidate_writer_change` inline instead -- a spawned task dies un-awaited if the event loop closes before it runs. Pending tasks from this path are drained by :meth:`_shutdown` on ``release_resources_async``.""" - task = asyncio.create_task(self._tracker.invalidate_all(old_writer)) + task = asyncio.create_task(self._tracker.invalidate_all_for_keys(key)) self._pending_invalidations.add(task) task.add_done_callback(self._pending_invalidations.discard) @@ -579,45 +534,15 @@ def notify_host_list_changed( :attr:`_current_writer` so the next ``execute`` re-detects the new writer via :meth:`_update_writer_from_topology`. - With the tracker's canonical-key normalization (instance alias - over cluster alias), a notify carrying the instance alias for a - cluster-connected session now correctly finds and invalidates - the tracked entries. """ - for alias, events in changes.items(): + for host, events in changes.items(): if HostEvent.CONVERTED_TO_READER in events: - host_part, port_part = self._parse_alias(alias) - h = HostInfo(host=host_part, port=port_part) - self._spawn_invalidation(h) + # Change keys are urls; tracking keys are not. + self._spawn_invalidation(host.rstrip("/")) if HostEvent.CONVERTED_TO_WRITER in events: # Force writer recheck on next execute via # _update_writer_from_topology. self._current_writer = None - @staticmethod - def _parse_alias(alias: str) -> tuple: - """Split a ``host:port`` alias into ``(host, port)``. - - Uses ``rpartition(':')`` so IPv6 aliases of the form - ``[::1]:5432`` split correctly on the LAST colon. Falls back to - port 5432 when the alias has no colon (or the port part isn't - numeric). - - The trailing ``/`` is stripped first because host-list-change keys - are ``HostInfo.url`` (``host:port/``) while tracking keys are - ``host:port``. Without it the port never parses and every - invalidation is aimed at port 5432, so a demoted writer on any - other port keeps its connections. - """ - stripped = alias.rstrip("/") - host_part, sep, port_part = stripped.rpartition(":") - if not sep: - # No colon -> treat entire alias as host, port defaults. - return stripped, 5432 - try: - return host_part, int(port_part) - except ValueError: - return host_part, 5432 - __all__ = ["AsyncAuroraConnectionTrackerPlugin", "AsyncOpenedConnectionTracker"] diff --git a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py index 20235f68b..d00ff2e83 100644 --- a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py @@ -26,10 +26,6 @@ so auth plugins (IAM, Secrets, Federated, Okta) and connection tracker re-apply on the new connection just like a user-driven connect. -* ``initial_connection_host_info`` is set on the plugin service directly: - ``AsyncPluginServiceImpl`` implements ``AsyncHostListProviderService`` - and ``aio/wrapper.py`` passes it as the host list provider service, so - the two are the same object. """ from __future__ import annotations @@ -102,8 +98,6 @@ def init_host_provider( props: Properties, host_list_provider_service: Any, init_host_provider_func: Callable) -> None: - # Sync captures the service here; async sets initial_connection_host_info on the plugin - # service directly so there is nothing to hold. init_host_provider_func() async def connect( @@ -139,13 +133,13 @@ async def connect( if role_to_verify is None: # No verification required. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn conn_role = await self._plugin_service.get_host_role(candidate_conn) if conn_role == role_to_verify: # Verification succeeded. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn # Verification failed. Retry, unless a reader was requested but the cluster has no readers. @@ -157,7 +151,7 @@ async def connect( logger.debug( "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn logger.debug( @@ -171,7 +165,7 @@ async def connect( if candidate_host is not None: self._plugin_service.set_availability( - candidate_host.as_aliases(), HostAvailability.UNAVAILABLE) + candidate_host, HostAvailability.UNAVAILABLE) if self._plugin_service.is_network_exception(error=e): # Retry connection. @@ -460,13 +454,6 @@ def _has_hosts(self) -> bool: def _has_readers(self) -> bool: return any(host.role == HostRole.READER for host in self._plugin_service.all_hosts) - def _set_initial_connection_host_info( - self, is_initial_connection: bool, host_info: Optional[HostInfo]): - # AsyncPluginServiceImpl implements AsyncHostListProviderService and is passed as the host - # list provider service, so this is the same attribute sync writes through that service. - if is_initial_connection and host_info is not None: - self._plugin_service.initial_connection_host_info = host_info - async def _close_connection( self, connection: Optional[Any], driver_dialect: AsyncDriverDialect) -> None: if connection is None: diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index a61428ecd..7c1898d80 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -400,7 +400,6 @@ async def apply( rerouted_host_info = copy(self._substitute_host_info) rerouted_host_info.host_id = iam_host.host_id rerouted_host_info.availability = HostAvailability.AVAILABLE - rerouted_host_info.add_alias(iam_host.host) rerouted_props = copy(props) WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host) diff --git a/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py b/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py index 0ef7a6f2d..c520ff864 100644 --- a/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py +++ b/aws_advanced_python_wrapper/aio/cluster_topology_monitor.py @@ -148,7 +148,7 @@ def __init__( self._is_verified_writer_connection: bool = False self._verified_writer_conn: Optional[Any] = None self._verified_writer_host_info: Optional[HostInfo] = None - self._submitted_host_aliases: Set[str] = set() + self._submitted_hosts: Set[str] = set() self._probe_tasks: Dict[str, asyncio.Task] = {} self._writer_found_event: asyncio.Event = asyncio.Event() @@ -375,8 +375,6 @@ def _role_corrected(self, topology: Topology) -> Topology: if h.role != want_role: fixed = copy.copy(h) fixed.role = want_role - for alias in h.as_aliases(): - fixed.add_alias(alias) corrected.append(fixed) changed = True else: @@ -384,8 +382,6 @@ def _role_corrected(self, topology: Topology) -> Topology: if not found: writer_row = copy.copy(verified) writer_row.role = HostRole.WRITER - for alias in verified.as_aliases(): - writer_row.add_alias(alias) corrected.append(writer_row) changed = True if changed: @@ -429,12 +425,17 @@ async def _wait_for_tick(self, interval: float) -> None: timeout=interval, return_when=asyncio.FIRST_COMPLETED) finally: - for waiter in (stop_waiter, tick_waiter): - if not waiter.done(): - waiter.cancel() - await asyncio.gather( - stop_waiter, tick_waiter, return_exceptions=True) - self._request_tick.clear() + # An application that closes its loop without releasing resources + # leaves this parked. Cancelling or draining a waiter whose loop is + # gone raises, and here that would surface as an unraisable + # exception from the garbage collector. + if not stop_waiter.get_loop().is_closed(): + for waiter in (stop_waiter, tick_waiter): + if not waiter.done(): + waiter.cancel() + await asyncio.gather( + stop_waiter, tick_waiter, return_exceptions=True) + self._request_tick.clear() async def _harvest_verified_writer(self) -> None: """Promote the panic-found verified-writer connection to the monitor's @@ -451,7 +452,7 @@ async def _harvest_verified_writer(self) -> None: if pending: await asyncio.gather(*pending, return_exceptions=True) self._probe_tasks.clear() - self._submitted_host_aliases.clear() + self._submitted_hosts.clear() if conn is None: return if self._connection_factory is None: @@ -480,7 +481,7 @@ def _should_panic(self) -> bool: def _spawn_panic_probes(self) -> None: """Spawn probe tasks for each host in ``last_topology`` not already - submitted. Deduped by ``host_info.as_alias()``. + submitted. Deduped by ``host_info.get_host_and_port()``. """ # Opportunistic cleanup of finished task refs. finished = [k for k, t in self._probe_tasks.items() if t.done()] @@ -488,15 +489,15 @@ def _spawn_panic_probes(self) -> None: self._probe_tasks.pop(k, None) # Release dedup slot so a retry can happen on a later tick if # the earlier probe failed/returned non-writer. - self._submitted_host_aliases.discard(k) + self._submitted_hosts.discard(k) for host_info in self._last_topology: - alias = host_info.as_alias() - if alias in self._submitted_host_aliases: + key = host_info.get_host_and_port() + if key in self._submitted_hosts: continue - self._submitted_host_aliases.add(alias) + self._submitted_hosts.add(key) task = asyncio.create_task(self._probe_and_report(host_info)) - self._probe_tasks[alias] = task + self._probe_tasks[key] = task # Aurora PG briefly rejects IAM/PAM auth on instances mid-promotion # (the PAM service restarts during the writer-role swap). Mirror the @@ -833,7 +834,7 @@ async def _reset(self) -> None: if pending: await asyncio.gather(*pending, return_exceptions=True) self._probe_tasks.clear() - self._submitted_host_aliases.clear() + self._submitted_hosts.clear() await self._drop_owned_connection() if self._verified_writer_conn is not None: await self._close_best_effort(self._verified_writer_conn) diff --git a/aws_advanced_python_wrapper/aio/default_plugin.py b/aws_advanced_python_wrapper/aio/default_plugin.py index 9090b97d9..61ce696bf 100644 --- a/aws_advanced_python_wrapper/aio/default_plugin.py +++ b/aws_advanced_python_wrapper/aio/default_plugin.py @@ -147,18 +147,17 @@ async def force_connect( def _post_connect_bookkeeping(self, host_info: HostInfo, connection_provider: Any) -> None: """Post-connect bookkeeping after a successful connect. - Sync parity: ``DefaultPlugin._connect`` (default_plugin.py:80-82) marks - every alias of the just-connected host AVAILABLE and lets the service - re-pick the driver dialect for the provider that produced the - connection (a no-op on async today). The DATABASE-dialect upgrade + Sync parity: ``DefaultPlugin._connect`` marks the just-connected host + AVAILABLE and lets the service re-pick the driver dialect for the + provider that produced the connection (a no-op on async today). + The DATABASE-dialect upgrade (sync ``plugin_service.update_dialect(conn)``) is invoked by the connect/force_connect callers right after this bookkeeping, mirroring sync's ordering; it is async so it cannot live in this sync helper. """ if self._plugin_service is None: return - self._plugin_service.set_availability( - host_info.as_aliases(), HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE) self._plugin_service.update_driver_dialect(connection_provider) async def execute( diff --git a/aws_advanced_python_wrapper/aio/dialect_utils.py b/aws_advanced_python_wrapper/aio/dialect_utils.py index 99174bf45..51a83e860 100644 --- a/aws_advanced_python_wrapper/aio/dialect_utils.py +++ b/aws_advanced_python_wrapper/aio/dialect_utils.py @@ -23,7 +23,7 @@ from __future__ import annotations import asyncio -from typing import TYPE_CHECKING, Any, Optional +from typing import TYPE_CHECKING, Any, Optional, Tuple from aws_advanced_python_wrapper.errors import (AwsWrapperError, QueryTimeoutError) @@ -83,12 +83,14 @@ async def get_instance_id( conn: Any, driver_dialect: AsyncDriverDialect, host_id_query: str, - timeout_sec: float = 5.0) -> Optional[str]: - """Run the dialect's ``host_id_query`` to learn the Aurora - instance identifier ``conn`` is bound to. Returns ``None`` on - empty result or query failure (best-effort; callers fall back - to topology resolution by host_id). Mirrors sync - DialectUtils.get_instance_id at database_dialect.py. + timeout_sec: float = 5.0) -> Optional[Tuple[str, str]]: + """Run the dialect's ``host_id_query`` for the instance ``conn`` is + bound to, returning ``(instance_id, instance_name)``. + + Aurora returns the same value in both columns. Multi-AZ returns a + numeric id and a short instance name, and callers match on either. + Returns ``None`` on an empty result or a query failure, since + identification is best-effort. """ was_in_txn = await AsyncDialectUtils._safe_in_transaction( conn, driver_dialect) @@ -107,10 +109,12 @@ async def get_instance_id( await AsyncDialectUtils._restore_idle(conn, was_in_txn) if not result: return None - first = result[0] - if first is None: + instance_id = result[0] + if instance_id is None: return None - return str(first) + # A single-column result repeats the id, as the Aurora query does. + instance_name = result[1] if len(result) > 1 and result[1] is not None else instance_id + return str(instance_id), str(instance_name) @staticmethod async def _safe_in_transaction( diff --git a/aws_advanced_python_wrapper/aio/failover_plugin.py b/aws_advanced_python_wrapper/aio/failover_plugin.py index 1655855bc..fa4381427 100644 --- a/aws_advanced_python_wrapper/aio/failover_plugin.py +++ b/aws_advanced_python_wrapper/aio/failover_plugin.py @@ -212,7 +212,7 @@ async def _connect_with_failover( if not self._should_failover(e): raise self._plugin_service.set_availability( - host_info.as_aliases(), HostAvailability.UNAVAILABLE) + host_info, HostAvailability.UNAVAILABLE) await self._do_failover(driver_dialect) else: # Known-dead target: refresh topology and fail over without @@ -424,7 +424,7 @@ async def _do_failover(self, driver_dialect: AsyncDriverDialect) -> None: failed_host = self._plugin_service.current_host_info if failed_host is not None: self._plugin_service.set_availability( - failed_host.as_aliases(), HostAvailability.UNAVAILABLE) + failed_host, HostAvailability.UNAVAILABLE) # Invalidate the current (likely broken) connection before # attempting failover so any pool-proxied target is evicted from @@ -556,7 +556,7 @@ async def _failover_reader_impl( self._open_connection(candidate, driver_dialect), deadline) except Exception as e: # noqa: BLE001 self._plugin_service.set_availability( - candidate.as_aliases(), HostAvailability.UNAVAILABLE) + candidate, HostAvailability.UNAVAILABLE) last_error = e if candidate in remaining: remaining.remove(candidate) @@ -578,7 +578,7 @@ async def _failover_reader_impl( if role == HostRole.READER or self._mode != FailoverMode.STRICT_READER: verified = HostInfo(candidate.host, candidate.port, role) self._plugin_service.set_availability( - candidate.as_aliases(), HostAvailability.AVAILABLE) + candidate, HostAvailability.AVAILABLE) await self._plugin_service.set_current_connection(new_conn, verified) if self._failover_reader_completed is not None: self._failover_reader_completed.inc() @@ -608,7 +608,7 @@ async def _failover_reader_impl( self._open_connection(original_writer, driver_dialect), deadline) except Exception as e: # noqa: BLE001 self._plugin_service.set_availability( - original_writer.as_aliases(), HostAvailability.UNAVAILABLE) + original_writer, HostAvailability.UNAVAILABLE) last_error = e else: role = await self._probe_role(new_conn) @@ -620,7 +620,7 @@ async def _failover_reader_impl( verified = HostInfo( original_writer.host, original_writer.port, role) self._plugin_service.set_availability( - original_writer.as_aliases(), HostAvailability.AVAILABLE) + original_writer, HostAvailability.AVAILABLE) await self._plugin_service.set_current_connection( new_conn, verified) if self._failover_reader_completed is not None: diff --git a/aws_advanced_python_wrapper/aio/host_list_provider.py b/aws_advanced_python_wrapper/aio/host_list_provider.py index 10dc435e5..dccd9cf50 100644 --- a/aws_advanced_python_wrapper/aio/host_list_provider.py +++ b/aws_advanced_python_wrapper/aio/host_list_provider.py @@ -48,6 +48,8 @@ AsyncAuroraTopologyUtils, AsyncGlobalAuroraTopologyUtils, AsyncMultiAzTopologyUtils, AsyncTopologyUtils) 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 from aws_advanced_python_wrapper.utils import services_container from aws_advanced_python_wrapper.utils.events import MonitorStopEvent @@ -152,14 +154,21 @@ def __init__(self, props: Properties) -> None: host = props.get("host", "") port_raw = props.get("port") port = int(port_raw) if port_raw is not None else -1 - self._host_info = HostInfo(host=host, port=port, role=HostRole.WRITER) + self._host_info = HostInfo( + host=host, port=port, role=HostRole.WRITER, + host_availability_strategy=create_host_availability_strategy(props)) self._cluster_id = f"static:{host}:{port}" + def _host(self) -> HostInfo: + """A copy, so marking the returned host unavailable does not mark the + one this provider hands to every later caller.""" + return copy(self._host_info) + async def refresh(self, connection: Optional[Any] = None) -> Topology: - return (self._host_info,) + return (self._host(),) async def force_refresh(self, connection: Optional[Any] = None) -> Topology: - return (self._host_info,) + return (self._host(),) def get_cluster_id(self) -> str: return self._cluster_id diff --git a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py index 7458f91d7..c26fc7e10 100644 --- a/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py +++ b/aws_advanced_python_wrapper/aio/host_monitoring_plugin.py @@ -71,6 +71,7 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import \ TelemetryTraceLevel +from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from weakref import ReferenceType @@ -371,7 +372,7 @@ async def _run(self) -> None: if self._is_unhealthy: self._plugin_service.set_availability( - self._host_info.as_aliases(), HostAvailability.UNAVAILABLE) + self._host_info, HostAvailability.UNAVAILABLE) await self._drain_active_contexts() @@ -580,7 +581,7 @@ def __init__( self._failure_detection_count = WrapperProperties.FAILURE_DETECTION_COUNT.get_int(props) self._failure_detection_enabled = WrapperProperties.FAILURE_DETECTION_ENABLED.get_bool(props) - # Subscribe to connect (for cluster-alias resolution) + every + # Subscribe to connect (to record the routed host) + every # network-bound method (so execute() brackets them with monitoring). # notify_* hooks are dispatched to all plugins regardless of this set. self._subscribed: Set[str] = {DbApiMethod.CONNECT.method_name} @@ -600,10 +601,17 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: connection = await connect_func() if connection is not None: - rds_type = self._rds_utils.identify_rds_type(host_info.host) - if rds_type.is_rds_cluster: - host_info.reset_aliases() - await self._fill_aliases(connection, host_info) + # Record which instance a cluster-endpoint connection landed on; + # the monitoring host is derived from it. + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + if self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: + try: + identified = await self._plugin_service.identify_connection(connection) + except Exception: # noqa: BLE001 - identification is best-effort + identified = None + if identified is not None: + self._plugin_service.routed_host_info = identified return connection async def execute( @@ -654,49 +662,34 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]) -> None: _stop_monitors_for_hosts(deleted) async def _get_monitoring_host_info(self) -> HostInfo: - if self._monitoring_host_info is not None: - return self._monitoring_host_info - current_host_info = self._plugin_service.current_host_info - if current_host_info is None: + # Held in a local because notify_connection_changed can clear the + # field while this method is between its assignment and its return. + monitoring_host_info = self._monitoring_host_info + if monitoring_host_info is not None: + return monitoring_host_info + # current_host_info, not routed_host_info: by the time any connection + # exists the wrapper has adopted the routed host, and a value still in + # that field belongs to a connect in flight, possibly another task's. + monitoring_host_info = self._plugin_service.current_host_info + if monitoring_host_info is None: raise AwsWrapperError(Messages.get("HostMonitoringV2Plugin.HostInfoNone")) - self._monitoring_host_info = current_host_info - rds_url_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) + self._monitoring_host_info = monitoring_host_info + rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) try: - if not rds_url_type.is_rds_cluster: - return self._monitoring_host_info + if not Utils.requires_host_identification(rds_url_type): + return monitoring_host_info logger.debug("HostMonitoringV2Plugin.ClusterEndpointHostInfo") - current_connection = self._plugin_service.current_connection - # Async approximation of sync's identify_connection + fill_aliases: - # identify_connection already returns the topology (instance-level) - # HostInfo with its instance aliases, so it doubles as the monitoring - # host and the alias source. - identified = await self._plugin_service.identify_connection(current_connection) - if identified is None: - raise AwsWrapperError(Messages.get_formatted( - "HostMonitoringV2Plugin.UnableToIdentifyConnection", - current_host_info.host, - self._plugin_service.host_list_provider)) - self._monitoring_host_info = identified - except Exception as e: - if isinstance(e, AwsWrapperError): - raise - message = "HostMonitoringV2Plugin.ErrorIdentifyingConnection" - logger.debug(message, e) - raise AwsWrapperError(Messages.get_formatted(message, e)) from e - return self._monitoring_host_info - - async def _fill_aliases(self, connection: Any, host_info: HostInfo) -> None: - """Add the connection's resolved instance endpoint as an alias of a - cluster-endpoint host (async approximation of sync ``fill_aliases``: - ``identify_connection`` + ``as_aliases``). Best-effort.""" - try: - host_info.add_alias(host_info.as_alias()) - identified = await self._plugin_service.identify_connection(connection) + identified = await self._plugin_service.identify_connection( + self._plugin_service.current_connection) if identified is not None: - host_info.add_alias(*identified.as_aliases()) - except Exception: # noqa: BLE001 - alias enrichment is best-effort - pass + monitoring_host_info = identified + self._monitoring_host_info = identified + except Exception as e: # noqa: BLE001 - the host id query failed + # Keep the connection's own host and monitor that. Raising here + # would fail every monitored call on the connection. + logger.debug("HostMonitoringV2Plugin.ErrorIdentifyingConnection", e) + return monitoring_host_info async def release_resources(self) -> None: """Drop this plugin's monitor-service reference. The shared monitors are diff --git a/aws_advanced_python_wrapper/aio/limitless_plugin.py b/aws_advanced_python_wrapper/aio/limitless_plugin.py index d49cd67f3..353cd5321 100644 --- a/aws_advanced_python_wrapper/aio/limitless_plugin.py +++ b/aws_advanced_python_wrapper/aio/limitless_plugin.py @@ -163,10 +163,18 @@ def __init__( self._limitless_routers = limitless_routers self._connection_plugin = connection_plugin self._plugin_service = plugin_service + self._connection_host_info: Optional[HostInfo] = None def get_host_info(self) -> HostInfo: return self._host_info + def get_connection_host_info(self) -> Optional[HostInfo]: + """The router the connection was actually opened against.""" + return self._connection_host_info + + def set_connection_host_info(self, host_info: HostInfo) -> None: + self._connection_host_info = host_info + def get_props(self) -> Properties: return self._props @@ -486,6 +494,7 @@ async def establish_connection(self, context: AsyncLimitlessContext) -> None: await context.set_connection(await self._plugin_service.connect( selected_host_info, context.get_props(), plugin_to_skip=context.get_connection_plugin())) + context.set_connection_host_info(selected_host_info) except Exception as e: # noqa: BLE001 if self._is_login_exception(e): raise e @@ -542,6 +551,7 @@ async def _retry_connection_with_least_loaded_routers( selected_host_info, context.get_props(), plugin_to_skip=context.get_connection_plugin())) if context.get_connection() is not None: + context.set_connection_host_info(selected_host_info) return except Exception as e: # noqa: BLE001 if self._is_login_exception(e): @@ -762,6 +772,11 @@ async def connect( await self._limitless_router_service.establish_connection(context) connection = context.get_connection() if connection is not None and not await self._plugin_service.driver_dialect.is_closed(connection): + # The connection is on a router, not on the shard group endpoint + # the caller named. + routed_host_info = context.get_connection_host_info() + if routed_host_info is not None: + self._plugin_service.routed_host_info = routed_host_info return connection raise AwsWrapperError(Messages.get_formatted( diff --git a/aws_advanced_python_wrapper/aio/plugin_service.py b/aws_advanced_python_wrapper/aio/plugin_service.py index bc6522d51..d379c7867 100644 --- a/aws_advanced_python_wrapper/aio/plugin_service.py +++ b/aws_advanced_python_wrapper/aio/plugin_service.py @@ -23,8 +23,8 @@ import asyncio import inspect -from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, FrozenSet, - List, Optional, Protocol, Set, Tuple) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, List, + Optional, Protocol, Set, Tuple) from aws_advanced_python_wrapper.aio.connection_provider import \ AsyncConnectionProviderManager @@ -43,6 +43,7 @@ from aws_advanced_python_wrapper.utils.properties import (PropertiesUtils, WrapperProperties) from aws_advanced_python_wrapper.utils.storage.cache_map import CacheMap +from aws_advanced_python_wrapper.utils.utils import Utils logger = Logger(__name__) @@ -110,7 +111,7 @@ def is_dialect_confirmed(self, value: bool) -> None: def set_availability( self, - host_aliases: FrozenSet[str], + host_info: HostInfo, availability: HostAvailability) -> None: ... @@ -161,6 +162,27 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: Optional[HostInfo]) -> None: ... + @property + def routed_host_info(self) -> Optional[HostInfo]: + """The host a plugin routed the pending connect to, if any. + + A plugin that connects to a host other than the one it was asked for + records its choice here, and a plugin that wants to know where the + connect went should read it. Do not consume it: connect hooks unwind + from the innermost plugin outwards, so a plugin that took the value + would hide it from every plugin outside it and from the wrapper, which + is what adopts it as the current host. + """ + ... + + @routed_host_info.setter + def routed_host_info(self, value: Optional[HostInfo]) -> None: + ... + + def take_routed_host_info(self) -> Optional[HostInfo]: + """Return the routed host and clear it. For the wrapper's use.""" + ... + async def refresh_host_list( self, connection: Optional[Any] = None) -> None: @@ -202,18 +224,6 @@ async def get_host_role( timeout_sec: Optional[float] = None) -> HostRole: ... - async def fill_aliases( - self, - connection: Optional[Any] = None, - host_info: Optional[HostInfo] = None) -> None: - """Populate ``host_info``'s aliases from the connection. - - Adds the host:port alias plus any aliases reported by the database's - ``host_alias_query`` and by :meth:`identify_connection`. No-op when the - host already has aliases. Mirrors sync ``PluginServiceImpl.fill_aliases``. - """ - ... - async def connect( self, host_info: HostInfo, @@ -406,6 +416,7 @@ def __init__( self._host_list_provider: Optional[AsyncHostListProvider] = None self._all_hosts: Tuple[HostInfo, ...] = () self._initial_connection_host_info: Optional[HostInfo] = None + self._routed_host_info: Optional[HostInfo] = None self._current_host_info: Optional[HostInfo] = host_info self._current_connection: Optional[Any] = None self._telemetry_factory: Optional[TelemetryFactory] = None @@ -531,14 +542,32 @@ def is_read_only_connection_exception( def set_availability( self, - host_aliases: FrozenSet[str], + host_info: HostInfo, availability: HostAvailability) -> None: - for alias in host_aliases: + hosts_to_change = [ + host for host in self._all_hosts if Utils.matches_host(host_info, host)] + if not hosts_to_change: + return + + changes: Dict[str, Set[HostEvent]] = {} + for host in hosts_to_change: + # Through the strategy, not the raw field: a host whose backoff + # window has elapsed reads as available again, and marking it down + # is a change the plugins should hear about. + previous = host.get_availability() + host.set_availability(availability) AsyncPluginServiceImpl._host_availability_expiring_cache.put( - alias, + host.url, availability, AsyncPluginServiceImpl._HOST_AVAILABILITY_EXPIRATION_NANO, ) + if previous != availability: + event = (HostEvent.WENT_UP if availability == HostAvailability.AVAILABLE + else HostEvent.WENT_DOWN) + changes[host.url] = {event, HostEvent.HOST_CHANGED} + + if changes and self._plugin_manager is not None: + self._plugin_manager.notify_host_list_changed(changes) def get_availability(self, host_url: str) -> Optional[HostAvailability]: return AsyncPluginServiceImpl._host_availability_expiring_cache.get(host_url) @@ -797,21 +826,19 @@ async def identify_connection( from aws_advanced_python_wrapper.aio.dialect_utils import \ AsyncDialectUtils - instance_id = await AsyncDialectUtils.get_instance_id( + instance_ids = await AsyncDialectUtils.get_instance_id( conn, self._driver_dialect, self._database_dialect.host_id_query, ) - if instance_id is None: + if instance_ids is None: return None topology = await self._host_list_provider.refresh(conn) - found = next( - (h for h in topology if h.host_id == instance_id), None) + found = Utils.find_host(topology, *instance_ids) if found is None: topology = await self._host_list_provider.force_refresh(conn) - found = next( - (h for h in topology if h.host_id == instance_id), None) + found = Utils.find_host(topology, *instance_ids) return found @property @@ -851,6 +878,19 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: Optional[HostInfo]) -> None: self._initial_connection_host_info = value + @property + def routed_host_info(self) -> Optional[HostInfo]: + return self._routed_host_info + + @routed_host_info.setter + def routed_host_info(self, value: Optional[HostInfo]) -> None: + self._routed_host_info = value + + def take_routed_host_info(self) -> Optional[HostInfo]: + routed = self._routed_host_info + self._routed_host_info = None + return routed + async def refresh_host_list( self, connection: Optional[Any] = None) -> None: @@ -1048,64 +1088,6 @@ async def get_host_role( timeout_sec=timeout_sec, ) - async def fill_aliases( - self, - connection: Optional[Any] = None, - host_info: Optional[HostInfo] = None) -> None: - """Populate ``host_info``'s aliases -- port of sync - ``PluginServiceImpl.fill_aliases`` (plugin_service.py:671-706). - - Adds the ``host:port`` alias, then any aliases the database reports via - ``host_alias_query``, then the aliases of the host that - :meth:`identify_connection` resolves the connection to. No-op when the - host already carries aliases (idempotent). - """ - connection = self._current_connection if connection is None else connection - host_info = self.current_host_info if host_info is None else host_info - if connection is None or host_info is None: - return - - if len(host_info.aliases) > 0: - logger.debug("PluginServiceImpl.NonEmptyAliases", host_info.aliases) - return - - host_info.add_alias(host_info.as_alias()) - - aux_timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get_float( - self._props) - try: - await asyncio.wait_for( - self._fill_aliases_from_query(connection, host_info), - timeout=aux_timeout_sec) - except asyncio.TimeoutError as e: - from aws_advanced_python_wrapper.errors import QueryTimeoutError - raise QueryTimeoutError( - Messages.get("PluginServiceImpl.FillAliasesTimeout")) from e - except Exception as e: # noqa: BLE001 - alias query is best-effort - logger.debug("PluginServiceImpl.FailedToRetrieveHostPort", e) - - host = await self.identify_connection(connection) - if host: - host_info.add_alias(*host.as_aliases()) - - async def _fill_aliases_from_query( - self, connection: Any, host_info: HostInfo) -> None: - dialect = self._database_dialect - if dialect is None: - return - from aws_advanced_python_wrapper.database_dialect import \ - UnknownDatabaseDialect - if isinstance(dialect, UnknownDatabaseDialect): - return - alias_query = dialect.host_alias_query - if not alias_query: - return - async with connection.cursor() as cur: - await cur.execute(alias_query) - for row in await cur.fetchall(): - if row: - host_info.add_alias(row[0]) - async def connect( self, host_info: HostInfo, @@ -1124,6 +1106,9 @@ async def connect( "AsyncPluginService.connect requires target_driver_func " "to be set; AsyncAwsWrapperConnection.connect normally " "wires this.") + # The routed host belongs to one connect. Clearing it here stops this + # connect's plugins reading the host a previous one landed on. + self._routed_host_info = None return await self._plugin_manager.connect( target_driver_func=self._target_driver_func, driver_dialect=self._driver_dialect, @@ -1160,6 +1145,7 @@ async def force_connect( raise AwsWrapperError( "AsyncPluginService.force_connect requires target_driver_func " "to be set; AsyncAwsWrapperConnection.connect normally wires this.") + self._routed_host_info = None return await self._plugin_manager.force_connect( target_driver_func=self._target_driver_func, driver_dialect=self._driver_dialect, @@ -1207,6 +1193,11 @@ async def set_current_connection( self, connection: Any, host_info: HostInfo) -> None: + # Whoever set a routed host has been superseded by this call, which + # names the host the connection is on. Switches that reuse a cached + # connection never run a connect, so this is the only place that + # clears the field for them. + self._routed_host_info = None prev = self._current_connection if prev is None: diff --git a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py index d67c5dbd6..96145ed75 100644 --- a/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/aio/read_write_splitting_plugin.py @@ -32,6 +32,7 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostRole +from aws_advanced_python_wrapper.pep249 import Error from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages @@ -453,8 +454,16 @@ async def _switch_to_reader_impl( for _ in range(2 * len(reader_candidates)): if not remaining: break - reader = self._plugin_service.get_host_info_by_strategy( - HostRole.READER, strategy, remaining) + try: + reader = self._plugin_service.get_host_info_by_strategy( + HostRole.READER, strategy, remaining) + except Error: + # Every reader is currently marked unavailable. Stop here so + # the caller reports that no reader was available, rather than + # surfacing a host-selector error to the application. Error, + # not AwsWrapperError: the default random selector raises the + # base class, which AwsWrapperError is a subclass of. + break if reader is None: break try: diff --git a/aws_advanced_python_wrapper/aio/retry_util.py b/aws_advanced_python_wrapper/aio/retry_util.py index 8fe668deb..cb6bb63a3 100644 --- a/aws_advanced_python_wrapper/aio/retry_util.py +++ b/aws_advanced_python_wrapper/aio/retry_util.py @@ -128,11 +128,11 @@ async def get_writer_connection( new_conn = await self._bounded( connect_func(writer), timeout_end_time) except Exception as e: # noqa: BLE001 - plugin_service.set_availability(writer.as_aliases(), HostAvailability.UNAVAILABLE) + plugin_service.set_availability(writer, HostAvailability.UNAVAILABLE) last_error = e else: # Connected -> the host is reachable. - plugin_service.set_availability(writer.as_aliases(), HostAvailability.AVAILABLE) + plugin_service.set_availability(writer, HostAvailability.AVAILABLE) # Roles in the topology may be stale right after a failover # (the demoted old writer can still be labeled WRITER), so # verify with a data-plane query before accepting. @@ -222,11 +222,9 @@ async def _refresh_topology_via_reader( reader_conn = await self._bounded( connect_func(reader), timeout_end_time) except Exception: # noqa: BLE001 - try the next reader - plugin_service.set_availability( - reader.as_aliases(), HostAvailability.UNAVAILABLE) + plugin_service.set_availability(reader, HostAvailability.UNAVAILABLE) continue - plugin_service.set_availability( - reader.as_aliases(), HostAvailability.AVAILABLE) + plugin_service.set_availability(reader, HostAvailability.AVAILABLE) try: refreshed = await self._bounded( host_list_provider.force_refresh(reader_conn), timeout_end_time) diff --git a/aws_advanced_python_wrapper/aio/topology_store.py b/aws_advanced_python_wrapper/aio/topology_store.py index d323f7d17..3c85f8ee7 100644 --- a/aws_advanced_python_wrapper/aio/topology_store.py +++ b/aws_advanced_python_wrapper/aio/topology_store.py @@ -29,7 +29,6 @@ from typing import Optional, Tuple from uuid import uuid4 -from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.hostinfo import Topology as StoredTopology from aws_advanced_python_wrapper.utils import services_container @@ -98,22 +97,7 @@ def get_topology( stored = services_container.get_storage_service().get(StoredTopology, key) if stored is None: return None - return tuple(_copy_host(host) for host in stored) - - -def _copy_host(host: HostInfo) -> HostInfo: - """Copy a host, restoring what ``HostInfo.__copy__`` drops. - - It carries neither the aliases, which match a live connection back to its - topology row, nor the availability strategy, which decides when a host - marked unavailable becomes usable again. - """ - clone = copy.copy(host) - clone.host_availability_strategy = host.host_availability_strategy - aliases = host.aliases - if aliases: - clone.add_alias(*aliases) - return clone + return tuple(copy.copy(host) for host in stored) def put_topology(key: Optional[TopologyKey], topology: StoredTopology) -> None: diff --git a/aws_advanced_python_wrapper/aio/topology_utils.py b/aws_advanced_python_wrapper/aio/topology_utils.py index 94c7d11a8..7afa0c157 100644 --- a/aws_advanced_python_wrapper/aio/topology_utils.py +++ b/aws_advanced_python_wrapper/aio/topology_utils.py @@ -27,6 +27,8 @@ from typing import TYPE_CHECKING, Any, Dict, List, Optional, Tuple from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.host_availability import \ + create_host_availability_strategy from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole, Topology from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages @@ -67,9 +69,14 @@ def __init__( self._topology_query = topology_query self._default_port = default_port self._rds_utils = RdsUtils() + # One strategy for every host these utils produce, as the synchronous + # provider does, so the backoff window is per cluster. + self._host_availability_strategy = create_host_availability_strategy(props) self.initial_host_info: HostInfo = HostInfo( - host=str(props.get("host", "")), port=self._port_from_props(default_port)) + host=str(props.get("host", "")), + port=self._port_from_props(default_port), + host_availability_strategy=self._host_availability_strategy) self.instance_template: Optional[HostInfo] = self._build_instance_template() def _port_from_props(self, default_port: int) -> int: @@ -134,8 +141,8 @@ def create_host( # host_id is how identify_connection correlates a live connection # back to its topology row; without it every cluster-endpoint # identification fails. - host_id=str(host_id)) - host_info.add_alias(str(host_id)) + host_id=str(host_id), + host_availability_strategy=self._host_availability_strategy) return host_info def _resolved_port(self) -> int: @@ -333,8 +340,8 @@ def _process_multi_az_query_results( host=host, port=port, role=HostRole.WRITER if row_id == writer_id else HostRole.READER, - host_id=row_id) - host_info.add_alias(host) + host_id=row_id, + host_availability_strategy=self._host_availability_strategy) hosts.append(host_info) if not any(h.role == HostRole.WRITER for h in hosts): @@ -419,8 +426,8 @@ def _process_global_query_results(self, rows: List[tuple]) -> Topology: host=host, port=port, role=HostRole.WRITER if is_writer else HostRole.READER, - host_id=server_id) - host_info.add_alias(host) + host_id=server_id, + host_availability_strategy=self._host_availability_strategy) hosts.append(host_info) writers = [h for h in hosts if h.role == HostRole.WRITER] diff --git a/aws_advanced_python_wrapper/aio/wrapper.py b/aws_advanced_python_wrapper/aio/wrapper.py index a5b2a33c8..25b44b169 100644 --- a/aws_advanced_python_wrapper/aio/wrapper.py +++ b/aws_advanced_python_wrapper/aio/wrapper.py @@ -911,7 +911,11 @@ async def _connect_pipeline( except Exception: # noqa: BLE001 - best-effort txn cleanup pass - await plugin_service.set_current_connection(target_conn, host_info) + # A plugin may have routed the connect elsewhere; that is the host this + # connection is actually on. + routed = plugin_service.take_routed_host_info() + await plugin_service.set_current_connection( + target_conn, routed if routed is not None else host_info) return AsyncAwsWrapperConnection(plugin_service, plugin_manager) def cursor(self, *args: Any, **kwargs: Any) -> AsyncAwsWrapperCursor: diff --git a/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py b/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py index 012f88fd6..80453d982 100644 --- a/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py +++ b/aws_advanced_python_wrapper/aurora_connection_tracker_plugin.py @@ -17,8 +17,8 @@ import threading from threading import Thread from time import perf_counter_ns -from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, FrozenSet, - Optional, Set) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, Optional, + Set, Tuple) from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.utils import Utils @@ -29,7 +29,6 @@ from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.pep249 import Connection - from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType from aws_advanced_python_wrapper.utils.properties import Properties from _weakrefset import WeakSet @@ -113,87 +112,83 @@ def _prune_connections(cls): if not conn_set and host in cls._opened_connections: del cls._opened_connections[host] - def populate_opened_connection_set(self, host_info: HostInfo, conn: Connection): + def _tracking_keys(self, host_info: HostInfo) -> Tuple[str, ...]: + """The keys ``host_info``'s connections are tracked under. + + An instance endpoint names the instance already, so one key is enough. + Anything else may be a custom domain name, which is tracked both under + the host id and under the endpoint the caller used. + """ + if self._rds_utils.is_rds_instance(host_info.host): + return (host_info.get_host_and_port(),) + return tuple(key for key in (host_info.host_id, host_info.get_host_and_port()) if key) + + def populate_opened_connection_set(self, host_info: Optional[HostInfo], conn: Optional[Connection]): """ Add the given connection to the set of tracked connections. :param host_info: host information of the given connection. :param conn: currently opened connection. """ - - aliases: FrozenSet[str] = host_info.as_aliases() - - if self._rds_utils.is_rds_instance(host_info.host): - self._track_connection(host_info.url, conn) + if host_info is None or conn is None: return - instance_endpoint: Optional[str] = next( - (alias for alias in aliases if self._rds_utils.is_rds_instance(self._rds_utils.remove_port(alias))), None) - if not instance_endpoint: + keys = self._tracking_keys(host_info) + if not keys: logger.debug("OpenedConnectionTracker.UnableToPopulateOpenedConnectionSet") return - instance_endpoint = instance_endpoint if instance_endpoint.endswith("/") else instance_endpoint + "/" - self._track_connection(instance_endpoint, conn) + for key in keys: + self._track_connection(key, conn) - def invalidate_all_connections(self, host_info: Optional[HostInfo] = None, host: Optional[FrozenSet[str]] = None): + def invalidate_all_connections(self, host_info: Optional[HostInfo]): """ Invalidates all opened connections pointing to the same host in a daemon thread. - :param host_info: the :py:class:`HostInfo` object containing the URL of the host. - :param host: the set of aliases representing a specific host. + :param host_info: the host whose connections should be closed. """ - - if host_info: - self.invalidate_all_connections(host=frozenset([host_info.url])) - self.invalidate_all_connections(host=host_info.as_aliases()) - return - - instance_endpoint: Optional[str] = None - if host is None: + if host_info is None: return + self.invalidate_all_connections_for_keys( + host_info.get_host_and_port(), host_info.host, host_info.host_id) - for instance in host: - if instance is not None and self._rds_utils.is_rds_instance(self._rds_utils.remove_port(instance)): - instance_endpoint = instance - break + def invalidate_all_connections_for_keys(self, *keys: Optional[str]): + """Invalidate the connections tracked under any of ``keys``. - if not instance_endpoint: - return - - instance_endpoint = instance_endpoint if instance_endpoint.endswith("/") else instance_endpoint + "/" + A connection tracked under more than one key is closed once: closing + a pool-proxied connection twice would invalidate whatever the pool + handed out in between. + """ + present = [key for key in keys if key] + seen: Set[int] = set() + to_close: list = [] with self._lock: - connection_set: Optional[WeakSet] = self._opened_connections.get(instance_endpoint) - if connection_set is not None: - connections_list = list(connection_set) + for key in present: + connection_set: Optional[WeakSet] = self._opened_connections.get(key) + if connection_set is None: + continue + for conn in list(connection_set): + if id(conn) not in seen: + seen.add(id(conn)) + to_close.append(conn) connection_set.clear() - else: - connections_list = None - if connections_list: - self._log_connection_set(instance_endpoint, connections_list) - self._invalidate_connections(connections_list) + if to_close: + self._log_connection_set(", ".join(present), to_close) + self._invalidate_connections(to_close) def remove_connection_tracking(self, host_info: HostInfo, connection: Connection | None): if not connection: return - if self._rds_utils.is_rds_instance(host_info.host): - host = host_info.url - else: - host = next((alias for alias in host_info.as_aliases() - if self._rds_utils.is_rds_instance(self._rds_utils.remove_port(alias))), "") - - if not host: - return - - host = host if host.endswith("/") else host + "/" - + # Every key populate_opened_connection_set used, so a custom-domain + # connection is untracked from both of its keys. with self._lock: - connection_set = self._opened_connections.get(host) - if connection_set: - connection_set.discard(connection) + for key in self._tracking_keys(host_info): + connection_set = self._opened_connections.get(key) + if connection_set: + connection_set.discard(connection) def _track_connection(self, instance_endpoint: str, conn: Connection): with self._lock: @@ -292,12 +287,23 @@ def connect( conn = connect_func() if conn: - url_type: RdsUrlType = self._rds_utils.identify_rds_type(host_info.host) - if url_type.is_rds_cluster: - host_info.reset_aliases() - self._plugin_service.fill_aliases(conn, host_info) - - self._tracker.populate_opened_connection_set(host_info, conn) + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + url_type = self._rds_utils.identify_rds_type(connection_host_info.host) + if Utils.requires_host_identification(url_type): + # The endpoint does not name the instance the connection + # landed on, so ask the database and track that instead. + # Best-effort: a connect must not fail because the host id + # query did. + try: + identified = self._plugin_service.identify_connection(conn) + except Exception: # noqa: BLE001 - identification is best-effort + identified = None + if identified is not None: + connection_host_info = identified + self._plugin_service.routed_host_info = identified + + self._tracker.populate_opened_connection_set(connection_host_info, conn) self._tracker.log_opened_connections() return conn @@ -359,10 +365,11 @@ def _check_writer_changed(self, need_refresh_host_lists: bool): self._need_update_current_writer = False def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): - for node, node_changes in changes.items(): - if HostEvent.CONVERTED_TO_READER in node_changes: - self._tracker.invalidate_all_connections(host=frozenset([node])) - if HostEvent.CONVERTED_TO_WRITER in node_changes: + for host, host_changes in changes.items(): + if HostEvent.CONVERTED_TO_READER in host_changes: + # Change keys are urls; tracking keys are not. + self._tracker.invalidate_all_connections_for_keys(host.rstrip("/")) + if HostEvent.CONVERTED_TO_WRITER in host_changes: self._need_update_current_writer = True diff --git a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py index 8eae5cf7b..2dd6e4023 100644 --- a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py @@ -108,7 +108,6 @@ class AuroraInitialConnectionStrategyPlugin(Plugin): def __init__(self, plugin_service: PluginService, props: Properties): self._plugin_service: PluginService = plugin_service self._rds_utils = RdsUtils() - self._host_list_provider_service: Optional[HostListProviderService] = None self._accessible_regions: Optional[FrozenSet[str]] = AccessibleRegions.parse(props) self._retry_delay_ms: int = WrapperProperties.OPEN_CONNECTION_RETRY_INTERVAL_MS.get_int(props) @@ -138,7 +137,6 @@ def init_host_provider( props: Properties, host_list_provider_service: HostListProviderService, init_host_provider_func: Callable): - self._host_list_provider_service = host_list_provider_service init_host_provider_func() def connect( @@ -172,13 +170,13 @@ def connect( if role_to_verify is None: # No verification required. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn conn_role = self._plugin_service.get_host_role(candidate_conn) if conn_role == role_to_verify: # Verification succeeded. - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn # Verification failed. Retry, unless a reader was requested but the cluster has no readers. @@ -190,7 +188,7 @@ def connect( logger.debug( "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._set_initial_connection_host_info(is_initial_connection, candidate_host) + self._plugin_service.routed_host_info = candidate_host return candidate_conn logger.debug( @@ -204,7 +202,7 @@ def connect( if candidate_host is not None: self._plugin_service.set_availability( - candidate_host.as_aliases(), HostAvailability.UNAVAILABLE) + candidate_host, HostAvailability.UNAVAILABLE) if self._plugin_service.is_network_exception(e): # Retry connection. @@ -487,13 +485,6 @@ def _get_candidate_host( # Unable to find a candidate host. return None - def _set_initial_connection_host_info( - self, is_initial_connection: bool, host_info: Optional[HostInfo]): - if (is_initial_connection - and self._host_list_provider_service is not None - and host_info is not None): - self._host_list_provider_service.initial_connection_host_info = host_info - @staticmethod def _find_writer(hosts: Sequence[HostInfo]) -> Optional[HostInfo]: """Return the first WRITER in ``hosts``, or ``None``. diff --git a/aws_advanced_python_wrapper/aws_credentials_manager.py b/aws_advanced_python_wrapper/aws_credentials_manager.py index bee5499d0..36b6ef35a 100644 --- a/aws_advanced_python_wrapper/aws_credentials_manager.py +++ b/aws_advanced_python_wrapper/aws_credentials_manager.py @@ -34,7 +34,7 @@ class AwsCredentialsManager: @staticmethod def get_session(host_info: HostInfo, props: Properties, region: Optional[str] = None) -> Session: profile_name = WrapperProperties.AWS_PROFILE.get(props) - host_key = f'{host_info.as_alias()}{region}{profile_name}' + host_key = f'{host_info.get_host_and_port()}{region}{profile_name}' with AwsCredentialsManager._lock: if host_key in AwsCredentialsManager._sessions: diff --git a/aws_advanced_python_wrapper/blue_green_plugin.py b/aws_advanced_python_wrapper/blue_green_plugin.py index 3e65d3a1a..19adb9d56 100644 --- a/aws_advanced_python_wrapper/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/blue_green_plugin.py @@ -401,7 +401,6 @@ def apply( rerouted_host_info = copy(self._substitute_host_info) rerouted_host_info.host_id = iam_host.host_id rerouted_host_info.availability = HostAvailability.AVAILABLE - rerouted_host_info.add_alias(iam_host.host) rerouted_props = copy(props) WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host) diff --git a/aws_advanced_python_wrapper/database_dialect.py b/aws_advanced_python_wrapper/database_dialect.py index 5b987b799..feb717997 100644 --- a/aws_advanced_python_wrapper/database_dialect.py +++ b/aws_advanced_python_wrapper/database_dialect.py @@ -140,11 +140,6 @@ class DatabaseDialect(Protocol): def default_port(self) -> int: ... - @property - @abstractmethod - def host_alias_query(self) -> str: - ... - @property @abstractmethod def server_version_query(self) -> str: @@ -267,10 +262,6 @@ class MysqlDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return 3306 - @property - def host_alias_query(self) -> str: - return f"SELECT {self._HOST_ID_EXPRESSION}" - @property def server_version_query(self) -> str: return MysqlDatabaseDialect._SERVER_VERSION_QUERY @@ -325,10 +316,6 @@ class PgDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return 5432 - @property - def host_alias_query(self) -> str: - return f"SELECT {self._HOST_ID_EXPRESSION}" - @property def server_version_query(self) -> str: return "SELECT 'version', pg_catalog.VERSION()" @@ -834,10 +821,6 @@ class UnknownDatabaseDialect(DatabaseDialect): def default_port(self) -> int: return HostInfo.NO_PORT - @property - def host_alias_query(self) -> str: - return "" - @property def server_version_query(self) -> str: return "" @@ -1188,7 +1171,16 @@ def get_instance_id(conn: Connection, driver_dialect: DriverDialect, instance_id thread_pool, timeout_sec: float) -> Optional[Tuple[str, str]]: cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( thread_pool, timeout_sec, driver_dialect, conn)(DialectUtils._execute_instance_id_query) - result = cursor_execute_func_with_timeout(conn, instance_id_query) + try: + result = cursor_execute_func_with_timeout(conn, instance_id_query) + except TimeoutError: + # A timeout is transient, so it stays an error the caller can see. + raise + except Exception: # noqa: BLE001 - see below + # A host whose id the database declines to report is simply + # unidentifiable, which every caller handles. Raising instead + # would fail a connect over a host the caller never needed named. + return None if result is not None and len(result) >= 2: return (str(result[0]), str(result[1])) diff --git a/aws_advanced_python_wrapper/default_plugin.py b/aws_advanced_python_wrapper/default_plugin.py index 3d0a92fd3..48fbd0b8e 100644 --- a/aws_advanced_python_wrapper/default_plugin.py +++ b/aws_advanced_python_wrapper/default_plugin.py @@ -77,7 +77,7 @@ def _connect( if context is not None: context.close_context() - self._plugin_service.set_availability(host_info.all_aliases, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE) self._plugin_service.update_driver_dialect(conn_provider) self._plugin_service.update_dialect(conn) diff --git a/aws_advanced_python_wrapper/failover_plugin.py b/aws_advanced_python_wrapper/failover_plugin.py index b212f5182..ef9e1a093 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.aliases, HostAvailability.UNAVAILABLE) + self._plugin_service.current_host_info, HostAvailability.UNAVAILABLE) self._pick_new_connection() self._last_exception = ex @@ -202,10 +202,6 @@ def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): if self._is_host_still_valid(current_host.url, changes): return - for alias in current_host.aliases: - if self._is_host_still_valid(alias + '/', changes): - return - logger.debug("FailoverPlugin.InvalidHost", current_host) finally: self._stale_dns_helper.notify_host_list_changed(changes) @@ -247,7 +243,7 @@ def _failover(self, failed_host: Optional[HostInfo]): :param failed_host: The host with network errors. """ if failed_host is not None: - self._plugin_service.set_availability(failed_host.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(failed_host, HostAvailability.UNAVAILABLE) if self._failover_mode == FailoverMode.STRICT_WRITER: self._failover_writer() @@ -274,10 +270,6 @@ def _failover_reader(self, failed_host: Optional[HostInfo]): try: logger.info("FailoverPlugin.StartReaderFailover") - old_aliases = None - if self._plugin_service.current_host_info is not None: - old_aliases = self._plugin_service.current_host_info.aliases - if failed_host is not None and failed_host.get_raw_availability() != HostAvailability.AVAILABLE: failed_host = None @@ -292,9 +284,6 @@ def _failover_reader(self, failed_host: Optional[HostInfo]): if result.connection is not None and result.new_host is not None: self._plugin_service.set_current_connection(result.connection, result.new_host) - if self._plugin_service.current_host_info is not None and old_aliases is not None and len(old_aliases) > 0: - self._plugin_service.current_host_info.remove_alias(old_aliases) - self._update_topology(True) logger.info("FailoverPlugin.EstablishedConnection", self._plugin_service.current_host_info) diff --git a/aws_advanced_python_wrapper/failover_v2_plugin.py b/aws_advanced_python_wrapper/failover_v2_plugin.py index 021fb956c..2aa6b2cda 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.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(host_info, 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.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.current_host_info, HostAvailability.UNAVAILABLE) self._pick_new_connection() self._last_exception_dealt_with = original_exception diff --git a/aws_advanced_python_wrapper/host_list_provider.py b/aws_advanced_python_wrapper/host_list_provider.py index 0d2d8e4cb..e136a20f7 100644 --- a/aws_advanced_python_wrapper/host_list_provider.py +++ b/aws_advanced_python_wrapper/host_list_provider.py @@ -18,6 +18,7 @@ from abc import ABC, abstractmethod from concurrent.futures import TimeoutError from contextlib import closing +from copy import copy from dataclasses import dataclass from datetime import datetime from threading import RLock @@ -220,7 +221,7 @@ def _get_topology(self, conn: Optional[Connection], force_update: bool = False) if not conn: # Cannot fetch topology without a connection # Return the original hosts passed to the connect method - return RdsHostListProvider.FetchTopologyResult(self._initial_hosts, False) + return RdsHostListProvider.FetchTopologyResult(self._copy_initial_hosts(), False) if not self._plugin_service.is_dialect_confirmed: # The dialect must be confirmed before the a topology monitor is @@ -235,7 +236,17 @@ def _get_topology(self, conn: Optional[Connection], force_update: bool = False) if cached_hosts: return RdsHostListProvider.FetchTopologyResult(cached_hosts, True) else: - return RdsHostListProvider.FetchTopologyResult(self._initial_hosts, False) + return RdsHostListProvider.FetchTopologyResult(self._copy_initial_hosts(), False) + + def _copy_initial_hosts(self) -> Topology: + """Copies, because the caller publishes these as the host list. + + These are built once and never replaced, so marking a host handed out + here would mark it for every later caller. Hosts from a topology query + are replaced by each refresh, so they are left shared, which is what + makes an availability mark visible across connections. + """ + return tuple(copy(host) for host in self._initial_hosts) def _get_or_create_monitor(self) -> Optional[ClusterTopologyMonitor]: """Get or create monitor - matches Java's getOrCreateMonitor""" @@ -364,11 +375,16 @@ def _initialize(self): def refresh(self, connection: Optional[Connection] = None) -> Topology: self._initialize() - return tuple(self._hosts) + return self._copy_hosts() def force_refresh(self, connection: Optional[Connection] = None) -> Topology: self._initialize() - return tuple(self._hosts) + return self._copy_hosts() + + def _copy_hosts(self) -> Topology: + """Copies, for the same reason as ``RdsHostListProvider``: this host + list is built once.""" + return tuple(copy(host) for host in self._hosts) def get_current_topology(self, connection: Connection, initial_host_info: HostInfo) -> Topology: self._initialize() @@ -564,7 +580,6 @@ def create_host( role=HostRole.WRITER if is_writer else HostRole.READER, last_update_time=last_update, host_id=host_id) - host_info.add_alias(host_id) return host_info def get_writer_id_if_connected(self, connection: Connection, driver_dialect: DriverDialect) -> Optional[str]: @@ -707,9 +722,10 @@ def _create_multi_az_host(self, record: Tuple, writer_id: str) -> HostInfo: if host.find(":") > -1: host, port = host.split(":") + # MySQL reports a numeric id. host_id is compared against the string + # host_id_query returns, so store it as a string. host_info = HostInfo( - host=host, port=port, role=role, availability=HostAvailability.AVAILABLE, weight=0, host_id=id) - host_info.add_alias(host) + host=host, port=port, role=role, availability=HostAvailability.AVAILABLE, weight=0, host_id=str(id)) return host_info diff --git a/aws_advanced_python_wrapper/host_monitoring_plugin.py b/aws_advanced_python_wrapper/host_monitoring_plugin.py index 1cab52b05..c3c7aabc3 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, FrozenSet, Optional, Set +from typing import Any, Callable, Dict, 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 +from aws_advanced_python_wrapper.utils.utils import QueueUtils, Utils logger = Logger(__name__) @@ -98,12 +98,23 @@ def connect( connect_func: Callable) -> Connection: conn = connect_func() if conn: - rds_type = self._rds_utils.identify_rds_type(host_info.host) - if rds_type.is_rds_cluster: - host_info.reset_aliases() - self._plugin_service.fill_aliases(conn, host_info) + self._record_routed_host(host_info, conn) return conn + def _record_routed_host(self, host_info: HostInfo, conn: Connection): + """Record which instance a cluster-endpoint connection landed on, since + the monitoring host is derived from it.""" + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + if not self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: + return + try: + identified = self._plugin_service.identify_connection(conn) + except Exception: # noqa: BLE001 - identification is best-effort + return + if identified is not None: + self._plugin_service.routed_host_info = identified + def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: connection = self._plugin_service.current_connection if connection is None: @@ -123,7 +134,6 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg logger.debug("HostMonitoringPlugin.ActivatedMonitoring", method_name) monitor_context = self._monitor_service.start_monitoring( connection, - self._get_monitoring_host_info().all_aliases, self._get_monitoring_host_info(), self._props, self._failure_detection_time_ms, @@ -135,18 +145,23 @@ def execute(self, target: object, method_name: str, execute_func: Callable, *arg if monitor_context: with self._lock: self._monitor_service.stop_monitoring(monitor_context) - if monitor_context.is_host_unavailable(): - self._plugin_service.set_availability( - self._get_monitoring_host_info().all_aliases, HostAvailability.UNAVAILABLE) - - driver_dialect = self._plugin_service.driver_dialect - if driver_dialect is not None and not driver_dialect.is_closed(connection): - try: - connection.close() - except Exception: - pass - raise AwsWrapperError( - Messages.get_formatted("HostMonitoringPlugin.UnavailableHost", host_info.as_alias())) + host_unavailable = monitor_context.is_host_unavailable() + + # Outside the lock: set_availability dispatches to every + # plugin, so holding it here would run arbitrary plugin code + # with this connection's monitoring serialised behind it. + if host_unavailable: + self._plugin_service.set_availability( + self._get_monitoring_host_info(), HostAvailability.UNAVAILABLE) + + driver_dialect = self._plugin_service.driver_dialect + if driver_dialect is not None and not driver_dialect.is_closed(connection): + try: + connection.close() + except Exception: + pass + raise AwsWrapperError( + Messages.get_formatted("HostMonitoringPlugin.UnavailableHost", host_info.get_host_and_port())) logger.debug("HostMonitoringPlugin.MonitoringDeactivated", method_name) return result @@ -159,44 +174,47 @@ def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnect return OldConnectionSuggestedAction.NO_OPINION def notify_host_list_changed(self, changes: Dict[str, Set[HostEvent]]): - if not self._is_connection_initialized: + # Closing a connection drops this plugin's reference to the monitor + # service, and a failover worker outliving that close can still reach + # this plugin when it publishes availability. + if not self._is_connection_initialized or self._monitor_service is None: return for host, events in changes.items(): if HostEvent.WENT_DOWN not in events and HostEvent.HOST_DELETED not in events: - return - - monitoring_aliases = self._get_monitoring_host_info().all_aliases - if len(monitoring_aliases) == 0: - return + continue - if host in monitoring_aliases: - self._monitor_service.stop_monitoring_host(monitoring_aliases) + if host == self._get_monitoring_host_info().url: + self._monitor_service.stop_monitoring_host(host) def _get_monitoring_host_info(self) -> HostInfo: - if self._monitoring_host_info is None: - current_host_info = self._plugin_service.current_host_info - if current_host_info is None: + # Held in a local because notify_connection_changed can clear the + # field while this method is between its assignment and its return. + monitoring_host_info = self._monitoring_host_info + if monitoring_host_info is None: + # current_host_info, not routed_host_info: by the time any + # connection exists the wrapper has adopted the routed host, and + # a value still in that field belongs to a connect in flight, + # possibly another thread's. + monitoring_host_info = self._plugin_service.current_host_info + if monitoring_host_info is None: raise AwsWrapperError("HostMonitoringPlugin.HostInfoNone") - self._monitoring_host_info = current_host_info - rds_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) + self._monitoring_host_info = monitoring_host_info + rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) try: - if rds_type.is_rds_cluster: + if Utils.requires_host_identification(rds_url_type): logger.debug("HostMonitoringPlugin.ClusterEndpointHostInfo") - self._monitoring_host_info = self._plugin_service.identify_connection() - if self._monitoring_host_info is None: - raise AwsWrapperError( - Messages.get_formatted( - "HostMonitoringPlugin.UnableToIdentifyConnection", - current_host_info.host, - self._plugin_service.host_list_provider)) - self._plugin_service.fill_aliases(host_info=self._monitoring_host_info) - except Exception as e: - message = "HostMonitoringPlugin.ErrorIdentifyingConnection" - logger.debug(message, e) - raise AwsWrapperError(Messages.get_formatted(message, e)) from e - return self._monitoring_host_info + identified = self._plugin_service.identify_connection( + self._plugin_service.current_connection) + if identified is not None: + monitoring_host_info = identified + self._monitoring_host_info = identified + except Exception as e: # noqa: BLE001 - the host id query failed + # Keep the connection's own host and monitor that. Raising + # here would fail every monitored call on the connection. + logger.debug("HostMonitoringPlugin.ErrorIdentifyingConnection", e) + return monitoring_host_info def release_resources(self): self._monitor_service = None @@ -584,7 +602,7 @@ def sleep(self, duration: int): class HostMonitorService: def __init__(self, plugin_service: PluginService): self._plugin_service: PluginService = plugin_service - self._cached_monitor_aliases: Optional[FrozenSet[str]] = None + self._cached_monitor_host_url: Optional[str] = None self._cached_monitor: Optional[ReferenceType[Monitor]] = None telemetry_factory = self._plugin_service.get_telemetry_factory() @@ -598,26 +616,23 @@ def __init__(self, plugin_service: PluginService): def start_monitoring(self, conn: Connection, - host_aliases: FrozenSet[str], host_info: HostInfo, props: Properties, failure_detection_time_ms: int, failure_detection_interval_ms: int, failure_detection_count: int) -> MonitoringContext: - if not host_aliases: - raise AwsWrapperError(Messages.get_formatted("MonitorService.EmptyAliasSet", host_info)) + host_url = host_info.url monitor: Optional[Monitor] = None if self._cached_monitor is None else self._cached_monitor() if monitor is None \ or monitor.is_stopped \ - or self._cached_monitor_aliases is None \ - or self._cached_monitor_aliases != host_aliases: - monitor = self._monitor_service.run_if_absent_with_aliases( + or self._cached_monitor_host_url != host_url: + monitor = self._monitor_service.run_if_absent( Monitor, - host_aliases, + host_url, lambda: Monitor(self._plugin_service, host_info, props)) self._cached_monitor = ref(monitor) - self._cached_monitor_aliases = host_aliases + self._cached_monitor_host_url = host_url context = MonitoringContext( monitor, conn, self._plugin_service.driver_dialect, failure_detection_time_ms, @@ -630,9 +645,7 @@ def stop_monitoring(context: MonitoringContext): monitor = context.monitor monitor.stop_monitoring(context) - def stop_monitoring_host(self, host_aliases: FrozenSet): - for alias in host_aliases: - monitor = self._monitor_service.get(Monitor, alias) - if monitor is not None: - monitor.clear_contexts() - return + def stop_monitoring_host(self, host_url: str): + monitor = self._monitor_service.get(Monitor, host_url) + if monitor is not None: + monitor.clear_contexts() diff --git a/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py b/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py index f0ac4fb9d..3427add66 100644 --- a/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py +++ b/aws_advanced_python_wrapper/host_monitoring_v2_plugin.py @@ -41,6 +41,7 @@ from aws_advanced_python_wrapper.utils.rds_utils import RdsUtils from aws_advanced_python_wrapper.utils.telemetry.telemetry import ( TelemetryCounter, TelemetryFactory, TelemetryTraceLevel) +from aws_advanced_python_wrapper.utils.utils import Utils if TYPE_CHECKING: from aws_advanced_python_wrapper.driver_dialect import DriverDialect @@ -87,10 +88,17 @@ def connect( connect_func: Callable) -> Connection: connection = connect_func() if connection: - rds_type = self._rds_utils.identify_rds_type(host_info.host) - if rds_type.is_rds_cluster: - host_info.reset_aliases() - self._plugin_service.fill_aliases(connection, host_info) + # Record which instance a cluster-endpoint connection landed on; + # the monitoring host is derived from it. + routed = self._plugin_service.routed_host_info + connection_host_info = routed if routed is not None else host_info + if self._rds_utils.identify_rds_type(connection_host_info.host).is_rds_cluster: + try: + identified = self._plugin_service.identify_connection(connection) + except Exception: # noqa: BLE001 - identification is best-effort + identified = None + if identified is not None: + self._plugin_service.routed_host_info = identified return connection def execute(self, target: object, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: @@ -126,34 +134,34 @@ def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnect return OldConnectionSuggestedAction.NO_OPINION def _get_monitoring_host_info(self) -> HostInfo: - if self._monitoring_host_info is not None: - return self._monitoring_host_info - current_host_info = self._plugin_service.current_host_info - if current_host_info is None: + # Held in a local because notify_connection_changed can clear the + # field while this method is between its assignment and its return. + monitoring_host_info = self._monitoring_host_info + if monitoring_host_info is not None: + return monitoring_host_info + # current_host_info, not routed_host_info: by the time any connection + # exists the wrapper has adopted the routed host, and a value still in + # that field belongs to a connect in flight, possibly another thread's. + monitoring_host_info = self._plugin_service.current_host_info + if monitoring_host_info is None: raise AwsWrapperError(Messages.get("HostMonitoringV2Plugin.HostInfoNone")) - self._monitoring_host_info = current_host_info - rds_url_type = self._rds_utils.identify_rds_type(self._monitoring_host_info.host) + self._monitoring_host_info = monitoring_host_info + rds_url_type = self._rds_utils.identify_rds_type(monitoring_host_info.host) try: - if not rds_url_type.is_rds_cluster: - return self._monitoring_host_info + if not Utils.requires_host_identification(rds_url_type): + return monitoring_host_info logger.debug("HostMonitoringV2Plugin.ClusterEndpointHostInfo") - current_connection = self._plugin_service.current_connection - self._monitoring_host_info = self._plugin_service.identify_connection(current_connection) - if self._monitoring_host_info is None: - raise AwsWrapperError( - Messages.get_formatted( - "HostMonitoringV2Plugin.UnableToIdentifyConnection", - current_host_info.host, - self._plugin_service.host_list_provider)) - self._plugin_service.fill_aliases(current_connection, self._monitoring_host_info) - except Exception as e: - if isinstance(e, AwsWrapperError): - raise e - message = "HostMonitoringV2Plugin.ErrorIdentifyingConnection" - logger.debug(message, e) - raise AwsWrapperError(Messages.get_formatted(message, e)) from e - return self._monitoring_host_info + identified = self._plugin_service.identify_connection( + self._plugin_service.current_connection) + if identified is not None: + monitoring_host_info = identified + self._monitoring_host_info = identified + except Exception as e: # noqa: BLE001 - the host id query failed + # Keep the connection's own host and monitor that. Raising here + # would fail every monitored call on the connection. + logger.debug("HostMonitoringV2Plugin.ErrorIdentifyingConnection", e) + return monitoring_host_info def release_resources(self): if self._monitor_service is not None: @@ -333,7 +341,7 @@ def run(self) -> None: self._update_host_health_status(is_valid, status_check_start_time_ns, status_check_end_time_ns) if self._is_unhealthy: - self._plugin_service.set_availability(self._host_info.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(self._host_info, HostAvailability.UNAVAILABLE) temp_active_context_weak_refs = [] while not self._active_contexts.empty(): diff --git a/aws_advanced_python_wrapper/hostinfo.py b/aws_advanced_python_wrapper/hostinfo.py index 5c9893a9f..3aa895de9 100644 --- a/aws_advanced_python_wrapper/hostinfo.py +++ b/aws_advanced_python_wrapper/hostinfo.py @@ -16,8 +16,7 @@ from dataclasses import dataclass from enum import Enum, auto -from typing import (TYPE_CHECKING, ClassVar, FrozenSet, Optional, Set, Tuple, - TypeAlias) +from typing import TYPE_CHECKING, ClassVar, Optional, Tuple, TypeAlias from aws_advanced_python_wrapper.host_availability import ( HostAvailability, HostAvailabilityStrategy) @@ -45,7 +44,7 @@ def __init__( port: int = NO_PORT, role: HostRole = HostRole.WRITER, availability: HostAvailability = HostAvailability.AVAILABLE, - host_availability_strategy=HostAvailabilityStrategy(), + host_availability_strategy: Optional[HostAvailabilityStrategy] = None, weight: int = DEFAULT_WEIGHT, host_id: Optional[str] = None, last_update_time: Optional[datetime] = None): @@ -53,14 +52,15 @@ def __init__( self.port = port self.role = role self.availability = availability - self.host_availability_strategy = host_availability_strategy + # A default argument is evaluated once, so every host that omitted it + # would share one strategy object. + self.host_availability_strategy = ( + host_availability_strategy if host_availability_strategy is not None + else HostAvailabilityStrategy()) self.weight = weight self.host_id = host_id self.last_update_time = last_update_time - self._aliases: Set[str] = set() - self._all_aliases: Set[str] = {self.as_alias()} - def __eq__(self, other: object): if self is object: return True @@ -84,6 +84,9 @@ def __copy__(self): port=self.port, role=self.role, availability=self.availability, + # Shared by reference, so the copy keeps the original's backoff + # count and retry window rather than starting a fresh one. + host_availability_strategy=self.host_availability_strategy, weight=self.weight, host_id=self.host_id, last_update_time=self.last_update_time @@ -91,46 +94,13 @@ def __copy__(self): @property def url(self): - return f"{self.as_alias()}/" - - @property - def aliases(self) -> FrozenSet[str]: - return frozenset(self._aliases) - - @property - def all_aliases(self) -> FrozenSet[str]: - return frozenset(self._all_aliases) + # The trailing slash is part of the format: the availability cache, the + # notify_host_list_changed change map and the monitor keys all use it. + return f"{self.get_host_and_port()}/" def get_host_and_port(self): return f"{self.host}:{self.port}" if self.is_port_specified() else self.host - def as_alias(self) -> str: - return self.get_host_and_port() - - def add_alias(self, *aliases: str): - if not aliases: - return - - for alias in aliases: - self._aliases.add(alias) - self._all_aliases.add(alias) - - def as_aliases(self) -> FrozenSet[str]: - return frozenset(self.all_aliases) - - def remove_alias(self, *kwargs): - if not kwargs or len(kwargs) == 0: - return - - for x in kwargs: - self._aliases.discard(x) - self._all_aliases.discard(x) - - def reset_aliases(self): - self._aliases.clear() - self._all_aliases.clear() - self._all_aliases.add(self.as_alias()) - def is_port_specified(self) -> bool: return self.port != HostInfo.NO_PORT diff --git a/aws_advanced_python_wrapper/limitless_plugin.py b/aws_advanced_python_wrapper/limitless_plugin.py index ca2bf5cf9..cf2a708d8 100644 --- a/aws_advanced_python_wrapper/limitless_plugin.py +++ b/aws_advanced_python_wrapper/limitless_plugin.py @@ -102,6 +102,11 @@ def connect( self._limitless_router_service.establish_connection(self._context) connection = self._context.get_connection() if connection is not None and not self._plugin_service.driver_dialect.is_closed(connection): + # The connection is on a router, not on the shard group endpoint + # the caller named. + routed_host_info = self._context.get_connection_host_info() + if routed_host_info is not None: + self._plugin_service.routed_host_info = routed_host_info return connection raise AwsWrapperError(Messages.get_formatted("LimitlessPlugin.FailedToConnectToHost", host_info.host)) @@ -291,10 +296,18 @@ def __init__(self, self._connect_func = connect_func self._limitless_routers = limitless_routers self._connection_plugin = connection_plugin + self._connection_host_info: Optional[HostInfo] = None def get_host_info(self): return self._host_info + def get_connection_host_info(self) -> Optional[HostInfo]: + """The router the connection was actually opened against.""" + return self._connection_host_info + + def set_connection_host_info(self, host_info: HostInfo): + self._connection_host_info = host_info + def get_props(self): return self._props @@ -393,6 +406,7 @@ def establish_connection(self, context: LimitlessContext) -> None: try: context.set_connection(self._plugin_service.connect(selected_host_info, context.get_props(), context.get_connection_plugin())) + context.set_connection_host_info(selected_host_info) except Exception as e: if self._is_login_exception(e): raise e @@ -452,6 +466,7 @@ def _retry_connection_with_least_loaded_routers(self, context: LimitlessContext) try: context.set_connection(self._plugin_service.connect(selected_host_info, context.get_props(), context.get_connection_plugin())) if context.get_connection() is not None: + context.set_connection_host_info(selected_host_info) return except Exception as e: diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index 74ac133b4..b87b44c00 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -45,9 +45,7 @@ from abc import abstractmethod from concurrent.futures import TimeoutError -from contextlib import closing -from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, Set, - Tuple) +from typing import Any, Callable, Dict, Optional, Protocol, Set, Tuple from aws_advanced_python_wrapper.allowed_and_blocked_hosts import \ AllowedAndBlockedHosts @@ -60,8 +58,7 @@ from aws_advanced_python_wrapper.connection_provider import ( ConnectionProvider, ConnectionProviderManager) from aws_advanced_python_wrapper.database_dialect import ( - DatabaseDialect, DatabaseDialectManager, DialectUtils, - UnknownDatabaseDialect) + DatabaseDialect, DatabaseDialectManager, DialectUtils) from aws_advanced_python_wrapper.default_plugin import DefaultPlugin from aws_advanced_python_wrapper.developer_plugin import DeveloperPluginFactory from aws_advanced_python_wrapper.driver_configuration_profiles import \ @@ -94,8 +91,6 @@ SimpleReadWriteSplittingPluginFactory from aws_advanced_python_wrapper.stale_dns_plugin import StaleDnsPluginFactory from aws_advanced_python_wrapper.utils import services_container -from aws_advanced_python_wrapper.utils.decorators import \ - preserve_transaction_status_with_timeout from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.notifications import ( @@ -175,6 +170,30 @@ def original_url(self) -> str: def initial_connection_host_info(self) -> Optional[HostInfo]: ... + @property + @abstractmethod + def routed_host_info(self) -> Optional[HostInfo]: + """The host a plugin routed the pending connect to, if any. + + A plugin that connects to a host other than the one it was asked for + records its choice here, and a plugin that wants to know where the + connect went should read it. Do not consume it: connect hooks unwind + from the innermost plugin outwards, so a plugin that took the value + would hide it from every plugin outside it and from the wrapper, which + is what adopts it as the current host. + """ + ... + + @routed_host_info.setter + @abstractmethod + def routed_host_info(self, value: Optional[HostInfo]): + ... + + @abstractmethod + def take_routed_host_info(self) -> Optional[HostInfo]: + """Return the routed host and clear it. For the wrapper's use.""" + ... + @property @abstractmethod def host_list_provider(self) -> HostListProvider: @@ -300,13 +319,14 @@ def force_connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: """ ... - def set_availability(self, host_aliases: FrozenSet[str], availability: HostAvailability): + def set_availability(self, host_info: HostInfo, availability: HostAvailability): + """Mark every host matching ``host_info`` by host id or host name.""" ... - def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: + def get_availability(self, host_url: str) -> Optional[HostAvailability]: ... - def fill_aliases(self, connection: Optional[Connection] = None, host_info: Optional[HostInfo] = None): + def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: ... def get_connection_provider_manager(self) -> ConnectionProviderManager: @@ -330,6 +350,7 @@ def get_status(self, clazz: Type[StatusType], key: str) -> Optional[StatusType]: class PluginServiceImpl(PluginService, HostListProviderService, CanReleaseResources): _STATUS_CACHE_EXPIRATION_NANO = 60 * 60 * 1_000_000_000 # one hour + _HOST_AVAILABILITY_EXPIRATION_NANO = 5 * 60 * 1_000_000_000 # five minutes _host_availability_expiring_cache: CacheMap[str, HostAvailability] = CacheMap() _executor_name: ClassVar[str] = "PluginServiceImplExecutor" @@ -352,6 +373,7 @@ def __init__( self._current_connection: Optional[Connection] = None self._current_host_info: Optional[HostInfo] = None self._initial_connection_host_info: Optional[HostInfo] = None + self._routed_host_info: Optional[HostInfo] = None self._exception_manager: ExceptionManager = ExceptionManager() self._is_in_transaction: bool = False self._dialect_provider = DatabaseDialectManager(props) @@ -402,6 +424,11 @@ def current_connection(self) -> Optional[Connection]: return self._current_connection def set_current_connection(self, connection: Optional[Connection], host_info: Optional[HostInfo]): + # Whoever set a routed host has been superseded by this call, which + # names the host the connection is on. Switches that reuse a cached + # connection never run a connect, so this is the only place that + # clears the field for them. + self._routed_host_info = None old_connection = self._current_connection if self._current_connection is None: @@ -497,6 +524,19 @@ def initial_connection_host_info(self) -> Optional[HostInfo]: def initial_connection_host_info(self, value: HostInfo): self._initial_connection_host_info = value + @property + def routed_host_info(self) -> Optional[HostInfo]: + return self._routed_host_info + + @routed_host_info.setter + def routed_host_info(self, value: Optional[HostInfo]): + self._routed_host_info = value + + def take_routed_host_info(self) -> Optional[HostInfo]: + routed = self._routed_host_info + self._routed_host_info = None + return routed + @property def host_list_provider(self) -> HostListProvider: return self._host_list_provider @@ -626,17 +666,43 @@ def force_monitoring_refresh_host_list(self, should_verify_writer: bool, timeout def connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: Optional[Plugin] = None) -> Connection: plugin_manager: PluginManager = self._container.plugin_manager + # The routed host belongs to one connect. Clearing it here stops this + # connect's plugins reading the host a previous one landed on. + self._routed_host_info = None return plugin_manager.connect( self._target_func, self._driver_dialect, host_info, props, self.current_connection is None, plugin_to_skip) def force_connect( self, host_info: HostInfo, props: Properties, plugin_to_skip: Optional[Plugin] = None) -> Connection: plugin_manager: PluginManager = self._container.plugin_manager + self._routed_host_info = None return plugin_manager.force_connect( self._target_func, self._driver_dialect, host_info, props, self.current_connection is None, plugin_to_skip) - def set_availability(self, host_aliases: FrozenSet[str], availability: HostAvailability): - ... + def set_availability(self, host_info: HostInfo, availability: HostAvailability): + hosts_to_change = [ + host for host in self.all_hosts if Utils.matches_host(host_info, host)] + if not hosts_to_change: + return + + changes: Dict[str, Set[HostEvent]] = {} + for host in hosts_to_change: + # Through the strategy, not the raw field: a host whose backoff + # window has elapsed reads as available again, and marking it down + # is a change the plugins should hear about. + previous = host.get_availability() + host.set_availability(availability) + self._host_availability_expiring_cache.put( + host.url, availability, PluginServiceImpl._HOST_AVAILABILITY_EXPIRATION_NANO) + if previous != availability: + event = HostEvent.WENT_UP if availability == HostAvailability.AVAILABLE else HostEvent.WENT_DOWN + changes[host.url] = {event, HostEvent.HOST_CHANGED} + + if changes: + self._container.plugin_manager.notify_host_list_changed(changes) + + def get_availability(self, host_url: str) -> Optional[HostAvailability]: + return PluginServiceImpl._host_availability_expiring_cache.get(host_url) def identify_connection(self, connection: Optional[Connection] = None) -> Optional[HostInfo]: connection = self.current_connection if connection is None else connection @@ -653,7 +719,10 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option timeout_sec) if instance_ids is None: - raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) + # Not an error: the connect hooks that identify a host call + # this, and a host whose id the database does not report is + # simply unidentifiable, not a failed connect. + return None topology = self.host_list_provider.refresh(connection) is_force_refresh = False @@ -664,19 +733,14 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option if topology is None: return None - instance_name = instance_ids[1] - found_host: Optional[HostInfo] = next( - (host for host in topology if host.host_id == instance_name), - None) + found_host: Optional[HostInfo] = Utils.find_host(topology, *instance_ids) if found_host is None and not is_force_refresh: topology = self.host_list_provider.force_refresh(connection) if topology is None: return None - found_host = next( - (host for host in topology if host.host_id == instance_name), - None) + found_host = Utils.find_host(topology, *instance_ids) return found_host except TimeoutError as e: @@ -686,43 +750,6 @@ def identify_connection(self, connection: Optional[Connection] = None) -> Option except Exception as e: raise AwsWrapperError(Messages.get("PluginServiceImpl.ErrorIdentifyConnection")) from e - def fill_aliases(self, connection: Optional[Connection] = None, host_info: Optional[HostInfo] = None): - connection = self.current_connection if connection is None else connection - host_info = self.current_host_info if host_info is None else host_info - if connection is None or host_info is None: - return - - if len(host_info.aliases) > 0: - logger.debug("PluginServiceImpl.NonEmptyAliases", host_info.aliases) - return - - host_info.add_alias(host_info.as_alias()) - - driver_dialect = self._driver_dialect - try: - timeout_sec = WrapperProperties.AUXILIARY_QUERY_TIMEOUT_SEC.get(self._props) - cursor_execute_func_with_timeout = preserve_transaction_status_with_timeout( - self._thread_pool, timeout_sec, driver_dialect, connection)(self._fill_aliases) - cursor_execute_func_with_timeout(connection, host_info) - except TimeoutError as e: - raise QueryTimeoutError(Messages.get("PluginServiceImpl.FillAliasesTimeout")) from e - except Exception as e: - # log and ignore - logger.debug("PluginServiceImpl.FailedToRetrieveHostPort", e) - - host = self.identify_connection(connection) - if host: - host_info.add_alias(*host.as_aliases()) - - def _fill_aliases(self, conn: Connection, host_info: HostInfo) -> bool: - with closing(conn.cursor()) as cursor: - if not isinstance(self.database_dialect, UnknownDatabaseDialect): - cursor.execute(self.database_dialect.host_alias_query) - for row in cursor.fetchall(): - host_info.add_alias(row[0]) - return True - return False - def is_static_host_list_provider(self) -> bool: return self._host_list_provider is StaticHostListProvider diff --git a/aws_advanced_python_wrapper/read_write_splitting_plugin.py b/aws_advanced_python_wrapper/read_write_splitting_plugin.py index 23bd01742..c55fdff02 100644 --- a/aws_advanced_python_wrapper/read_write_splitting_plugin.py +++ b/aws_advanced_python_wrapper/read_write_splitting_plugin.py @@ -32,6 +32,7 @@ FailoverFailedError, ReadWriteSplittingError) from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.pep249 import Error from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory from aws_advanced_python_wrapper.utils.log import Logger @@ -613,9 +614,17 @@ def _open_new_reader_connection( host_candidates = self._get_reader_host_candidates() conn_attempts = len(host_candidates) * 2 for _ in range(conn_attempts): - host = self._plugin_service.get_host_info_by_strategy( - HostRole.READER, self._reader_selector_strategy, host_candidates - ) + try: + host = self._plugin_service.get_host_info_by_strategy( + HostRole.READER, self._reader_selector_strategy, host_candidates + ) + except Error: + # Every reader is currently marked unavailable. Stop here so + # the caller reports that no reader was available, rather than + # surfacing a host-selector error to the application. Error, + # not AwsWrapperError: the default random selector raises the + # base class, which AwsWrapperError is a subclass of. + break if host is not None: try: conn = self._plugin_service.connect(host, self._properties, self) diff --git a/aws_advanced_python_wrapper/reader_failover_handler.py b/aws_advanced_python_wrapper/reader_failover_handler.py index e20aba452..28cf86862 100644 --- a/aws_advanced_python_wrapper/reader_failover_handler.py +++ b/aws_advanced_python_wrapper/reader_failover_handler.py @@ -150,7 +150,7 @@ def _internal_failover_task( def _failover_internal(self, hosts: Tuple[HostInfo, ...], current_host: Optional[HostInfo]) -> ReaderFailoverResult: if current_host is not None: - self._plugin_service.set_availability(current_host.all_aliases, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(current_host, HostAvailability.UNAVAILABLE) hosts_by_priority = ReaderFailoverHandlerImpl.get_hosts_by_priority(hosts, self._strict_reader_failover) return self._get_connection_from_host_group(hosts_by_priority) @@ -201,13 +201,13 @@ def attempt_connection(self, host: HostInfo) -> ReaderFailoverResult: try: conn: Connection = self._plugin_service.force_connect(host, props) - self._plugin_service.set_availability(host.all_aliases, HostAvailability.AVAILABLE) + self._plugin_service.set_availability(host, HostAvailability.AVAILABLE) logger.debug("ReaderFailoverHandler.SuccessfulReaderConnection", host.url) return ReaderFailoverResult(conn, True, host, None) except Exception as ex: logger.debug("ReaderFailoverHandler.FailedReaderConnection", host.url) - self._plugin_service.set_availability(host.all_aliases, HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(host, HostAvailability.UNAVAILABLE) if not self._plugin_service.is_network_exception(ex): return ReaderFailoverResult(None, False, None, ex) diff --git a/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties b/aws_advanced_python_wrapper/resources/aws_advanced_python_wrapper_messages.properties index 3982da77a..a87c4d285 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 @@ -252,7 +252,6 @@ HostMonitoringPlugin.ConnectionNone=[HostMonitoringPlugin] Attempted to execute HostMonitoringPlugin.HostInfoNone=[HostMonitoringPlugin] Could not find HostInfo to monitor for the current connection. HostMonitoringPlugin.HostInfoNoneForMethod=[HostMonitoringPlugin] Attempted to execute method '{}' but the current host info is None. HostMonitoringPlugin.ConfigurationNotSupported=[HostMonitoringPlugin] Aborting connections from a separate thread is not supported for the detected driver dialect: '{}'. The EFM plugin requires this feature to be supported. -HostMonitoringPlugin.UnableToIdentifyConnection=[HostMonitoringPlugin] Unable to identify the connected database instance: '{}', please ensure the correct host list provider is specified. The host list provider in use is: '{}'. HostMonitoringPlugin.UnavailableHost=[HostMonitoringPlugin] Host '{}' is unavailable. HostMonitoringV2Plugin.ActivatedMonitoring=[HostMonitoringV2Plugin] Executing method '{}', monitoring is activated. @@ -262,7 +261,6 @@ HostMonitoringV2Plugin.MonitoringDeactivated=[HostMonitoringV2Plugin] Monitoring HostMonitoringV2Plugin.ConnectionNone=[HostMonitoringV2Plugin] Attempted to execute method '{}' but the current connection is None. HostMonitoringV2Plugin.HostInfoNone=[HostMonitoringV2Plugin] Could not find HostInfo to monitor for the current connection. HostMonitoringV2Plugin.ConfigurationNotSupported=[HostMonitoringV2Plugin] Aborting connections from a separate thread is not supported for the detected driver dialect: '{}'. The EFM V2 plugin requires this feature to be supported. -HostMonitoringV2Plugin.UnableToIdentifyConnection=[HostMonitoringV2Plugin] Unable to identify the connected database instance: '{}', please ensure the correct host list provider is specified. The host list provider in use is: '{}'. HostMonitorV2.ExceptionDuringMonitoringStop=[HostMonitorV2] Stopping monitoring after unhandled exception was thrown in monitoring thread for host '{}'. Exception: '{}' HostMonitorV2.MonitorIsStopped=[HostMonitorV2] Monitoring was already stopped for host '{}'. HostMonitorV2.StartMonitoringThreadNewContext=[HostMonitorV2] Start monitoring thread for checking new contexts for '{}'. @@ -333,13 +331,6 @@ MonitorContext.ExceptionAbortingConnection=[MonitorContext] An exception occurre 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 {}. @@ -383,11 +374,8 @@ 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.NonEmptyAliases=[PluginServiceImpl] fill_aliases called when HostInfo already contains the following aliases: {}. PluginServiceImpl.SetCurrentHostInfo=[PluginServiceImpl] Set current host info to {} PluginServiceImpl.UnableToUpdateTransactionStatus=[PluginServiceImpl] Unable to update transaction status, current connection is None. PluginServiceImpl.UpdateDialectConnectionNone=[PluginServiceImpl] The plugin service attempted to update the current dialect but could not identify a connection to use. diff --git a/aws_advanced_python_wrapper/utils/concurrent.py b/aws_advanced_python_wrapper/utils/concurrent.py index 5a8250872..b164b480d 100644 --- a/aws_advanced_python_wrapper/utils/concurrent.py +++ b/aws_advanced_python_wrapper/utils/concurrent.py @@ -77,25 +77,6 @@ def compute_if_absent(self, key: K, mapping_func: Callable) -> Optional[V]: return new_value return value - def compute_for_keys( - self, keys, factory: Callable, - on_existing: Optional[Callable] = None) -> V: - with self._lock: - value = None - for key in keys: - value = self._dict.get(key) - if value is not None: - if on_existing: - on_existing(value) - break - - if value is None: - value = factory() - - for key in keys: - self._dict.setdefault(key, value) - return value - def put(self, key: K, value: V): with self._lock: self._dict[key] = value diff --git a/aws_advanced_python_wrapper/utils/monitor_service.py b/aws_advanced_python_wrapper/utils/monitor_service.py index 33a0db5de..6b07ddfa3 100644 --- a/aws_advanced_python_wrapper/utils/monitor_service.py +++ b/aws_advanced_python_wrapper/utils/monitor_service.py @@ -17,8 +17,7 @@ import threading from dataclasses import dataclass from time import perf_counter_ns -from typing import (Any, Callable, Dict, FrozenSet, Optional, Protocol, - runtime_checkable) +from typing import Any, Callable, Dict, Optional, Protocol, runtime_checkable from aws_advanced_python_wrapper.utils.events import (DataAccessEvent, EventBase, @@ -111,14 +110,6 @@ def run_if_absent( container = self._get_or_create_container(monitor_type) return container.cache.compute_if_absent(key, lambda _: factory()) - def run_if_absent_with_aliases( - self, - monitor_type: type, - aliases: FrozenSet[str], - factory: Callable[[], Any]) -> Any: - container = self._get_or_create_container(monitor_type) - return container.cache.get_or_create_for_aliases(aliases, factory) - def detach(self, monitor_type: type, monitor: Any) -> None: container = self._monitor_caches.get(monitor_type) if container is not None: diff --git a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py index 6c89aeea6..795fb65aa 100644 --- a/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py +++ b/aws_advanced_python_wrapper/utils/storage/expiration_tracking_cache.py @@ -15,7 +15,7 @@ from __future__ import annotations from time import perf_counter_ns -from typing import Callable, FrozenSet, Generic, List, Optional, Tuple, TypeVar +from typing import Callable, Generic, List, Optional, Tuple, TypeVar from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict @@ -65,13 +65,6 @@ def compute_if_absent(self, key: K, factory: Callable[[K], V]) -> Optional[V]: entry.extend(self._expiration_timeout_ns) return entry.item - def get_or_create_for_aliases(self, aliases: FrozenSet[K], factory: Callable[[], V]) -> V: - entry = self._cache.compute_for_keys( - aliases, - lambda: _CacheItem(factory(), perf_counter_ns() + self._expiration_timeout_ns), - on_existing=lambda e: e.extend(self._expiration_timeout_ns)) - return entry.item - def extend_expiration(self, key: K) -> None: entry = self._cache.get(key) if entry is not None: diff --git a/aws_advanced_python_wrapper/utils/utils.py b/aws_advanced_python_wrapper/utils/utils.py index e6690a410..132bb7041 100644 --- a/aws_advanced_python_wrapper/utils/utils.py +++ b/aws_advanced_python_wrapper/utils/utils.py @@ -21,6 +21,7 @@ from typing import TYPE_CHECKING, Optional, Tuple from aws_advanced_python_wrapper.hostinfo import HostRole +from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType if TYPE_CHECKING: from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -98,6 +99,51 @@ def contains_host_and_port(hosts: Tuple[HostInfo, ...], host_and_port: str) -> b return False + @staticmethod + def requires_host_identification(url_type: RdsUrlType) -> bool: + """Whether the instance behind ``url_type`` has to be looked up. + + An instance endpoint names its instance already. A proxy or shard + group endpoint names a router, which stays reachable and is the right + thing to monitor; the instance behind it may not accept a direct + connection at all. + """ + return url_type not in ( + RdsUrlType.RDS_INSTANCE, + RdsUrlType.RDS_PROXY, + RdsUrlType.RDS_AURORA_LIMITLESS_DB_SHARD_GROUP) + + @staticmethod + def matches_host(host: HostInfo, other: HostInfo) -> bool: + """Whether two hosts name the same instance. + + Host ids match exactly; host names are compared case-insensitively, + since DNS names are case-insensitive. + """ + if host.host_id is not None and host.host_id == other.host_id: + return True + return (host.host is not None and other.host is not None + and host.host.casefold() == other.host.casefold()) + + @staticmethod + def find_host( + hosts: Tuple[HostInfo, ...], + instance_id: Optional[str], + instance_name: Optional[str]) -> Optional[HostInfo]: + """Find the host a connection is bound to from what ``host_id_query`` + reported. + + The id is matched against ``host_id`` and the name against ``host``. + The dialects disagree about which column holds which: the Aurora + queries repeat one value, Multi-AZ returns a numeric id and a short + name, and the plain MySQL and PostgreSQL queries return the name + first. Matching on either column covers all of them. + """ + return next( + (host for host in hosts + if host.host_id == instance_id or host.host == instance_name), + None) + @staticmethod def get_writer(hosts: Tuple[HostInfo, ...]) -> Optional[HostInfo]: for host in hosts: diff --git a/aws_advanced_python_wrapper/wrapper.py b/aws_advanced_python_wrapper/wrapper.py index 9db150c21..8ad8e7eb4 100644 --- a/aws_advanced_python_wrapper/wrapper.py +++ b/aws_advanced_python_wrapper/wrapper.py @@ -78,7 +78,11 @@ def __init__( if not conn: raise AwsWrapperError(Messages.get("AwsWrapperConnection.ConnectionNotOpen")) - plugin_service.set_current_connection(conn, plugin_service.initial_connection_host_info) + # A plugin may have routed the connect elsewhere; that is the host this + # connection is actually on. + routed = plugin_service.take_routed_host_info() + connected_host_info = routed if routed is not None else plugin_service.initial_connection_host_info + plugin_service.set_current_connection(conn, connected_host_info) @property def target_connection(self): diff --git a/aws_advanced_python_wrapper/writer_failover_handler.py b/aws_advanced_python_wrapper/writer_failover_handler.py index 34e04bac2..4ad62e3a1 100644 --- a/aws_advanced_python_wrapper/writer_failover_handler.py +++ b/aws_advanced_python_wrapper/writer_failover_handler.py @@ -116,7 +116,7 @@ def get_writer(self, topology: Tuple[HostInfo, ...]) -> Optional[HostInfo]: def get_result_from_future(self, current_topology: Tuple[HostInfo, ...]) -> WriterFailoverResult: writer_host: Optional[HostInfo] = self.get_writer(current_topology) if writer_host is not None: - self._plugin_service.set_availability(writer_host.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(writer_host, HostAvailability.UNAVAILABLE) executor = ThreadPoolExecutor(thread_name_prefix="WriterFailoverHandlerExecutor") try: @@ -188,7 +188,7 @@ def reconnect_to_writer(self, initial_writer_host: HostInfo): else: success = self.is_current_host_writer(latest_topology, initial_writer_host) - self._plugin_service.set_availability(initial_writer_host.as_aliases(), HostAvailability.AVAILABLE) + self._plugin_service.set_availability(initial_writer_host, HostAvailability.AVAILABLE) return WriterFailoverResult(success, False, latest_topology, conn if success else None, "TaskA", None) except Exception as ex: @@ -208,10 +208,11 @@ def is_current_host_writer(self, latest_topology: Tuple[HostInfo, ...], initial_ if latest_writer is None: return False - latest_writer_all_aliases: frozenset[str] = latest_writer.all_aliases - current_aliases: frozenset[str] = initial_writer_host.all_aliases - - return current_aliases is not None and len(current_aliases) > 0 and bool(current_aliases.intersection(latest_writer_all_aliases)) + return (latest_writer.host_id is not None + and latest_writer.host_id == initial_writer_host.host_id) \ + or (latest_writer.get_host_and_port() is not None + and latest_writer.get_host_and_port().casefold() + == initial_writer_host.get_host_and_port().casefold()) def wait_for_new_writer(self, current_topology: Tuple[HostInfo, ...], current_host: HostInfo) -> WriterFailoverResult: """ @@ -317,11 +318,11 @@ def connect_to_writer(self, writer_candidate: Optional[HostInfo]) -> bool: if writer_candidate is not None: self._current_connection = \ self._plugin_service.force_connect(writer_candidate, self._initial_connection_properties) - self._plugin_service.set_availability(writer_candidate.as_aliases(), HostAvailability.AVAILABLE) + self._plugin_service.set_availability(writer_candidate, HostAvailability.AVAILABLE) return True except Exception: if writer_candidate is not None: - self._plugin_service.set_availability(writer_candidate.as_aliases(), HostAvailability.UNAVAILABLE) + self._plugin_service.set_availability(writer_candidate, HostAvailability.UNAVAILABLE) return False diff --git a/docs/development-guide/PluginService.md b/docs/development-guide/PluginService.md index fce76c2b3..3f5eee7e3 100644 --- a/docs/development-guide/PluginService.md +++ b/docs/development-guide/PluginService.md @@ -9,6 +9,24 @@ It also keeps track of the host list provider in use, and notifies it to update It is expected that the plugins do not establish a connection themselves, but rather call `PluginService.connect()` to establish connections. +## The Routed Host + +A plugin may connect to a host other than the one it was asked for. The Aurora +initial connection strategy plugin substitutes an instance for a cluster +endpoint, and the limitless plugin picks a transaction router. + +A plugin that does this assigns `PluginService.routed_host_info`, and the +wrapper adopts that host as the current host for the connection. + +A plugin that wants to know where the connect was routed should **read** the +property. Connect hooks unwind from the innermost plugin outwards, so a plugin +that consumed the value would hide it from every plugin outside it and from +the wrapper. Only the wrapper consumes it, with `take_routed_host_info()`. + +The value belongs to a single connect. `PluginService.connect()` clears it on +entry and `set_current_connection()` clears it once a host has been adopted, +so a plugin never reads a host left over from an earlier connect. + ## Host List Providers The plugin service uses the host list provider to retrieve the most recent host information or topology information about the database. diff --git a/tests/unit/test_aio_aurora_connection_tracker.py b/tests/unit/test_aio_aurora_connection_tracker.py index a683d23c9..5b31e9397 100644 --- a/tests/unit/test_aio_aurora_connection_tracker.py +++ b/tests/unit/test_aio_aurora_connection_tracker.py @@ -574,10 +574,10 @@ def test_notify_converted_to_reader_invalidates_that_host(): tracker.track(host, conn) from aws_advanced_python_wrapper.utils.notifications import HostEvent - alias = host.as_alias() async def _run(): - plugin.notify_host_list_changed({alias: {HostEvent.CONVERTED_TO_READER}}) + # Change keys are urls, with a trailing slash; tracking keys are not. + plugin.notify_host_list_changed({host.url: {HostEvent.CONVERTED_TO_READER}}) # Give the spawned invalidation task a moment await asyncio.sleep(0.01) @@ -620,7 +620,7 @@ def test_notify_ignores_events_that_are_not_converted(): async def _run(): plugin.notify_host_list_changed( - {host.as_alias(): {HostEvent.WENT_DOWN}}) + {host.url: {HostEvent.WENT_DOWN}}) await asyncio.sleep(0.01) asyncio.run(_run()) @@ -685,68 +685,54 @@ async def _run(): conn.close.assert_called() -def test_notify_host_list_changed_handles_alias_without_port(): - """An alias with no colon falls back to port 5432 (doesn't raise).""" +def test_notify_host_list_changed_handles_a_key_without_a_port(): + """A change key naming no port still reaches the connections tracked + under it, since a host with no port keys on the bare host name.""" plugin, svc, driver_dialect, tracker = _build() + conn = _plain_conn("conn") + tracker.track(HostInfo(host="host-no-port"), conn) from aws_advanced_python_wrapper.utils.notifications import HostEvent async def _run(): - # Must not raise; _spawn_invalidation schedules via asyncio.create_task - # so needs a running loop. - plugin.notify_host_list_changed({"host-no-port": {HostEvent.CONVERTED_TO_READER}}) + plugin.notify_host_list_changed({"host-no-port/": {HostEvent.CONVERTED_TO_READER}}) await asyncio.sleep(0.01) asyncio.run(_run()) + conn.close.assert_called() -def test_parse_alias_helper(): - """Direct helper test: IPv4, IPv6, bare host, invalid port.""" - from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ - AsyncAuroraConnectionTrackerPlugin - - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h.example:5432") == ("h.example", 5432) - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("[::1]:5432") == ("[::1]", 5432) - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h-no-port") == ("h-no-port", 5432) - assert AsyncAuroraConnectionTrackerPlugin._parse_alias("h:not-a-port") == ("h", 5432) - - -def test_tracker_keys_by_instance_endpoint_for_cluster_connected_conn(): - """When tracking via a cluster endpoint HostInfo whose aliases - include the instance endpoint, the canonical key is the instance - endpoint -- so notify-based invalidation by instance alias finds it.""" +def test_tracker_keys_a_cluster_connected_conn_by_its_host_id(): + """A cluster endpoint does not name the instance, so the host id is what a + later invalidation naming the instance has to match on.""" tracker = AsyncOpenedConnectionTracker() - # Cluster endpoint hostname that is NOT an RDS instance per is_rds_instance, - # but aliases include the instance endpoint. cluster_host = HostInfo( host="mydb.cluster-abc123.us-east-1.rds.amazonaws.com", port=5432, role=HostRole.WRITER, + host_id="myinstance", ) - # Add a known RDS instance alias - cluster_host.add_alias("myinstance.abc123.us-east-1.rds.amazonaws.com:5432") conn = _plain_conn("conn") tracker.track(cluster_host, conn) - # Canonical key is the instance alias, not the cluster host:port - assert AsyncOpenedConnectionTracker._canonical_key(cluster_host) == \ - "myinstance.abc123.us-east-1.rds.amazonaws.com:5432" + assert set(AsyncOpenedConnectionTracker._tracking_keys(cluster_host)) == { + "myinstance", "mydb.cluster-abc123.us-east-1.rds.amazonaws.com:5432"} - # invalidate_all via a HostInfo that resolves to the same instance alias - # should close the tracked conn instance_host = HostInfo( host="myinstance.abc123.us-east-1.rds.amazonaws.com", port=5432, + host_id="myinstance", ) asyncio.run(tracker.invalidate_all(instance_host)) conn.close.assert_called() -def test_tracker_fallback_to_host_port_for_non_rds_host(): - """Non-RDS hostnames use host:port as the canonical key (no RDS alias found).""" - host = HostInfo(host="custom.example.com", port=5432) - assert AsyncOpenedConnectionTracker._canonical_key(host) == "custom.example.com:5432" +def test_tracker_keys_an_instance_endpoint_by_host_and_port_alone(): + host = HostInfo(host="instance-1.abc123.us-east-1.rds.amazonaws.com", port=5432, + host_id="instance-1") + assert AsyncOpenedConnectionTracker._tracking_keys(host) == ( + "instance-1.abc123.us-east-1.rds.amazonaws.com:5432",) # ---- B2: post-failover settling window ---------------------------------- diff --git a/tests/unit/test_aio_aurora_initial_connection.py b/tests/unit/test_aio_aurora_initial_connection.py index afd2fa944..59fc5378b 100644 --- a/tests/unit/test_aio_aurora_initial_connection.py +++ b/tests/unit/test_aio_aurora_initial_connection.py @@ -133,7 +133,7 @@ async def _run(): svc.get_host_role.assert_not_awaited() # A non-cluster URL needs no role verification, so the loop records the # original host and returns on the first pass. - assert svc.initial_connection_host_info is host + assert svc.routed_host_info is host # ---- 2. Writer cluster URL + already writer -> direct writer conn ------ @@ -168,7 +168,7 @@ async def _run(): result = asyncio.run(_run()) assert result is writer_conn driver_dialect.connect.assert_awaited_once() - assert svc.initial_connection_host_info is writer + assert svc.routed_host_info is writer # ---- 3. Writer cluster URL + connected to reader -> retry -------------- @@ -207,8 +207,8 @@ async def _run(): driver_dialect.abort_connection.assert_any_await(first_conn) # Topology force-refreshed on the bad conn. svc.force_refresh_host_list.assert_awaited() - # initial_connection_host_info -> writer from topology. - assert svc.initial_connection_host_info is writer + # routed_host_info -> writer from topology. + assert svc.routed_host_info is writer # ---- 4. Reader cluster URL + connected to reader -> returns conn ------- @@ -242,7 +242,7 @@ async def _run(): result = asyncio.run(_run()) assert result is reader_conn - assert svc.initial_connection_host_info is reader + assert svc.routed_host_info is reader # ---- 5. Reader cluster URL + no readers -> writer fallback ------------- @@ -280,7 +280,7 @@ async def _run(): assert result is cluster_conn # The no-readers fallback records the candidate host, which on the stale # path is the original connect host rather than the writer. - assert svc.initial_connection_host_info is host + assert svc.routed_host_info is host # ---- 6. Timeout exhausted -> raises (parity with sync) ----------------- @@ -420,8 +420,8 @@ async def _run(): asyncio.run(_run()) assert svc.set_availability.call_count >= 1 - called_aliases = svc.set_availability.call_args_list[0][0][0] - assert reader.host in "".join(called_aliases) + marked_host = svc.set_availability.call_args_list[0][0][0] + assert marked_host.host == reader.host assert svc.set_availability.call_args_list[0][0][1] == \ HostAvailability.UNAVAILABLE diff --git a/tests/unit/test_aio_dialect_utils.py b/tests/unit/test_aio_dialect_utils.py index 45a003570..edde85f4d 100644 --- a/tests/unit/test_aio_dialect_utils.py +++ b/tests/unit/test_aio_dialect_utils.py @@ -143,5 +143,5 @@ def test_get_instance_id_rolls_back_transient_probe_txn(): dd = MagicMock() dd.is_in_transaction = AsyncMock(return_value=False) iid = asyncio.run(AsyncDialectUtils.get_instance_id(conn, dd, "q")) - assert iid == "inst-1" + assert iid == ("inst-1", "inst-1") conn.rollback.assert_awaited_once() diff --git a/tests/unit/test_aio_failover_plugin.py b/tests/unit/test_aio_failover_plugin.py index e0bd2e23b..0184bc9f8 100644 --- a/tests/unit/test_aio_failover_plugin.py +++ b/tests/unit/test_aio_failover_plugin.py @@ -529,7 +529,7 @@ def test_failover_marks_connected_host_available(): asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) svc.set_availability.assert_any_call( - writer.as_aliases(), HostAvailability.AVAILABLE) + writer, HostAvailability.AVAILABLE) def test_failover_marks_failed_host_unavailable(): @@ -547,7 +547,7 @@ def test_failover_marks_failed_host_unavailable(): asyncio.run(plugin._do_failover(driver_dialect=driver_dialect)) svc.set_availability.assert_any_call( - writer.as_aliases(), HostAvailability.UNAVAILABLE) + writer, HostAvailability.UNAVAILABLE) # ---- B.4: reader retry loop + strategy + writer fallback --------------- @@ -950,9 +950,9 @@ async def _dial(): conn = await plugin.connect( MagicMock(), driver_dialect, host, Properties({}), True, _dial) assert conn is failover_conn - marked_aliases, marked_avail = svc.set_availability.call_args_list[0][0] + marked_host, marked_avail = svc.set_availability.call_args_list[0][0] assert marked_avail == HostAvailability.UNAVAILABLE - assert host.as_aliases() == marked_aliases + assert marked_host is host asyncio.run(_body()) diff --git a/tests/unit/test_aio_host_list_provider.py b/tests/unit/test_aio_host_list_provider.py index e15703d00..4b58c01eb 100644 --- a/tests/unit/test_aio_host_list_provider.py +++ b/tests/unit/test_aio_host_list_provider.py @@ -303,21 +303,24 @@ def test_topology_multiple_writers_without_timestamps_keeps_one(): assert len(writers) == 1 -def test_topology_rows_carry_host_id_and_instance_alias(): - """Integration regression (EFM cluster-RO, both Aurora envs): - _rows_to_topology dropped host_id, so plugin_service.identify_connection - (which matches `h.host_id == instance_id`) could NEVER resolve a - cluster-endpoint connection -- EFM's _get_monitoring_host_info raised - UnableToIdentifyConnection on every cluster-RO connect. Sync parity: - create_host (host_list_provider.py:548-556) sets host_id AND adds the - bare instance id as an alias; the async MultiAz/GlobalAurora providers - already did both.""" +def test_topology_rows_carry_host_id(): + """Integration regression (EFM cluster-RO, both Aurora envs): the row + parser dropped host_id, so identify_connection could never resolve a + cluster-endpoint connection and host monitoring could not pick a + monitoring host.""" rows = [("w-1", True), ("r-1", False)] prov = _aurora() topo = prov._topology_utils._process_query_results(rows) assert {h.host_id for h in topo} == {"w-1", "r-1"} - for h in topo: - assert h.host_id in h.as_aliases() + + +def test_topology_rows_share_one_availability_strategy(): + """One strategy per provider, matching the synchronous provider, so the + backoff window is per cluster rather than per host.""" + prov = _aurora() + topo = prov._topology_utils._process_query_results([("w-1", True), ("r-1", False)]) + strategies = {id(h.host_availability_strategy) for h in topo} + assert strategies == {id(prov._topology_utils._host_availability_strategy)} def test_topology_query_programming_error_raises_invalid_query(): diff --git a/tests/unit/test_aio_host_monitoring_plugin.py b/tests/unit/test_aio_host_monitoring_plugin.py index 88aa91b31..34392d170 100644 --- a/tests/unit/test_aio_host_monitoring_plugin.py +++ b/tests/unit/test_aio_host_monitoring_plugin.py @@ -344,7 +344,7 @@ async def _work(): await asyncio.sleep(0.3) svc.set_availability.assert_any_call( - HostInfo(host="h.example", port=5432).as_aliases(), + HostInfo(host="h.example", port=5432), HostAvailability.UNAVAILABLE) dd.abort_connection.assert_awaited() aborted_with = dd.abort_connection.await_args_list[0].args[0] diff --git a/tests/unit/test_aio_monitor_lifecycle_regressions.py b/tests/unit/test_aio_monitor_lifecycle_regressions.py new file mode 100644 index 000000000..2c86badfe --- /dev/null +++ b/tests/unit/test_aio_monitor_lifecycle_regressions.py @@ -0,0 +1,296 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Lifecycle regressions in the shared async topology monitor. + +Each test pins a defect in the monitor's start, stop, reset or cleanup paths. +""" + +from __future__ import annotations + +import asyncio +import gc +import weakref +from unittest.mock import AsyncMock, MagicMock + +from aws_advanced_python_wrapper.aio import topology_store +from aws_advanced_python_wrapper.aio.cluster_topology_monitor import \ + AsyncClusterTopologyMonitor +from aws_advanced_python_wrapper.aio.host_list_provider import \ + AsyncAuroraHostListProvider +from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncAuroraTopologyUtils +from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole +from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.events import MonitorResetEvent +from aws_advanced_python_wrapper.utils.properties import Properties + +CLUSTER_ID = "my-cluster" +KEY = (CLUSTER_ID, "token") +OLD = (HostInfo("blue-writer.example", 5432, HostRole.WRITER),) +NEW = (HostInfo("green-writer.example", 5432, HostRole.WRITER),) + + +def _utils(topology=()) -> AsyncAuroraTopologyUtils: + utils = AsyncAuroraTopologyUtils( + Properties({"host": "cluster-xyz.us-east-1.rds.amazonaws.com", "port": "5432"}), + "SELECT 1", 5432) + utils.query_for_topology = AsyncMock(return_value=topology) # type: ignore[method-assign] + return utils + + +def _monitor(topology=()) -> AsyncClusterTopologyMonitor: + return AsyncClusterTopologyMonitor( + topology_utils=_utils(topology), + cluster_id=CLUSTER_ID, + key=KEY, + connection_getter=lambda: None) + + +def test_stop_on_a_closed_loop_does_not_raise() -> None: + """Setting the stop event before checking the loop raised "Event loop is + closed", and the monitor service swallowed it at debug level.""" + loop = asyncio.new_event_loop() + monitor = _monitor() + try: + loop.run_until_complete(_start_and_park(monitor)) + finally: + loop.close() + + # A waiter is parked on the stop event, and the loop is gone. + assert monitor._stop_event._waiters # type: ignore[attr-defined] + monitor.stop() # must not raise + + +async def _start_and_park(monitor: AsyncClusterTopologyMonitor) -> None: + monitor.start() + await asyncio.sleep(0.02) + + +def test_the_monitor_does_not_keep_its_event_loop_alive() -> None: + """A shutdown hook holds the monitor for the life of the process, so a + strong loop reference leaks a loop per loop in a loop-per-request app.""" + loop = asyncio.new_event_loop() + monitor = _monitor() + loop.run_until_complete(_start_and_park(monitor)) + loop.run_until_complete(monitor.aclose()) + loop.close() + + ref = weakref.ref(loop) + del loop + gc.collect() + assert ref() is None, "the monitor is still holding its event loop" + + +def test_a_reset_discards_a_publication_that_began_before_it() -> None: + """A refresh in flight when a blue/green reset lands describes the + pre-switchover cluster, so publishing it afterwards restores the host list + the reset just cleared.""" + async def _body(): + monitor = _monitor() + monitor.start() + topology_store.put_topology(KEY, OLD) + + reset_count = monitor._reset_count + monitor.process_event( + MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) + await asyncio.sleep(0) + await asyncio.sleep(0) + assert topology_store.get_topology(KEY) is None + + # The pre-reset fetch now completes and tries to publish. + monitor._publish_topology(OLD, reset_count) + assert topology_store.get_topology(KEY) is None + assert monitor._last_topology == () + + # A publication from after the reset still lands. + monitor._publish_topology(NEW, monitor._reset_count) + assert topology_store.get_topology(KEY) == NEW + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_reset_wakes_the_loop_instead_of_waiting_out_a_tick() -> None: + """Without waking the loop, a switchover serves nothing until the next + tick, which the reset itself just made a full-length one.""" + async def _body(): + monitor = _monitor() + monitor.start() + monitor._request_tick.clear() + + monitor.process_event( + MonitorResetEvent(cluster_id=CLUSTER_ID, endpoints=frozenset())) + await asyncio.sleep(0) + await asyncio.sleep(0) + + assert monitor._request_tick.is_set() + await monitor.aclose() + + asyncio.run(_body()) + + +def test_a_closed_monitor_is_not_restarted() -> None: + """force_monitoring_refresh auto-starts, and a monitor restarted after + aclose() is out of the cache, so nothing would stop its task.""" + async def _body(): + monitor = _monitor() + monitor.start() + await monitor.aclose() + + monitor.start() + assert not monitor.is_running() + + asyncio.run(_body()) + + +def test_the_inactive_timeout_outlasts_a_long_refresh_interval() -> None: + """Activity is stamped once per tick, so a refresh interval longer than + the inactive timeout had every cleanup sweep disposing a healthy monitor.""" + services_container.get_monitor_service()._monitor_caches.pop( + AsyncClusterTopologyMonitor, None) + props = Properties({ + "host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5432", + "topology_refresh_ms": "300000", # 5 minutes, well past the 3-min default + }) + AsyncAuroraHostListProvider(props, MagicMock()) + + container = services_container.get_monitor_service()._monitor_caches[ + AsyncClusterTopologyMonitor] + assert container.settings.inactive_timeout_ns > 300_000 * 1_000_000 + + +def test_detach_value_reports_whether_it_removed_the_entry() -> None: + """stop_and_remove_value relies on this to tell its caller whether the + removal was theirs.""" + from aws_advanced_python_wrapper.utils.storage.expiration_tracking_cache import \ + ExpirationTrackingCache + + cache: ExpirationTrackingCache = ExpirationTrackingCache( + expiration_timeout_ns=60 * 1_000_000_000) + monitor = _monitor() + cache.compute_if_absent(KEY, lambda _k: monitor) + + assert cache.detach_value(monitor) is True + assert cache.detach_value(monitor) is False + + +def test_a_cluster_on_a_non_default_port_keeps_that_port() -> None: + """The port fell back to the dialect default, so an Aurora cluster reached + on 5433 produced topology hosts on 5432.""" + utils = AsyncAuroraTopologyUtils( + Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5433"}), + "SELECT 1", 5432) + host = utils.create_host("instance-1", is_writer=True) + assert host.port == 5433 + + +def test_global_aurora_reduces_two_writers_to_one() -> None: + """A cross-region switchover can report two writers, and consumers read a + two-writer topology as ambiguous.""" + from aws_advanced_python_wrapper.aio.topology_utils import \ + AsyncGlobalAuroraTopologyUtils + + utils = AsyncGlobalAuroraTopologyUtils( + Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5432"}), + "SELECT 1", 5432, + instance_templates_by_region={"us-east-1": "?.a.us-east-1.rds.amazonaws.com", + "us-west-2": "?.b.us-west-2.rds.amazonaws.com"}) + rows = [ + ("old-writer", True, 0, "us-east-1"), + ("new-writer", True, 0, "us-west-2"), + ] + + topology = utils._process_global_query_results(rows) + + writers = [h for h in topology if h.role == HostRole.WRITER] + assert len(writers) == 1, f"expected one writer, got {writers}" + + +def test_aclose_wakes_a_caller_blocked_on_a_refresh() -> None: + """A blocked caller awaits the event object it read, so aclose() has to + set it before swapping in a fresh one or the caller waits out its own + timeout against an orphan.""" + async def _body(): + monitor = _monitor() + monitor.start() + waiter = asyncio.create_task( + monitor.force_monitoring_refresh(False, timeout_sec=30.0)) + await asyncio.sleep(0.01) + assert not waiter.done() + + await monitor.aclose() + + # Returns promptly rather than after the 30 second timeout. + result = await asyncio.wait_for(waiter, timeout=1.0) + assert result == () + + asyncio.run(_body()) + + +def test_stop_releases_the_monitoring_connection() -> None: + """The monitor service disposes a monitor by calling stop(), so a teardown + it does not schedule leaks a connection on every sweep.""" + conn = MagicMock() + conn.close = MagicMock() + + async def _body(): + monitor = _monitor() + monitor.start() + monitor._owned_conn = conn + + monitor.stop() + for _ in range(10): + await asyncio.sleep(0) + + conn.close.assert_called_once() + assert not monitor.is_running() + # Only aclose() sets _closed, so a task that merely exited on the stop + # signal and closed the connection in its own finally does not pass. + assert monitor._closed, "stop() did not schedule aclose()" + + asyncio.run(_body()) + + +def test_the_provider_removes_a_dead_monitor_by_identity() -> None: + """Removing by key would dispose a live replacement a cleanup pass had + already put there, under the caller using it.""" + services_container.get_monitor_service()._monitor_caches.pop( + AsyncClusterTopologyMonitor, None) + provider = AsyncAuroraHostListProvider( + Properties({"host": "mydb.cluster-abc123.us-east-2.rds.amazonaws.com", + "port": "5432"}), + MagicMock()) + + async def _body(): + monitor_service = services_container.get_monitor_service() + key = provider._storage_key() + + # A dead monitor is handed out, and a live replacement is already at + # the key by the time the provider reacts. + dead = _monitor() + live = _monitor() + live.start() + monitor_service.run_if_absent(AsyncClusterTopologyMonitor, key, lambda: live) + + monitor_service.stop_and_remove_value(AsyncClusterTopologyMonitor, dead) + + assert monitor_service.get(AsyncClusterTopologyMonitor, key) is live + assert live.is_running(), "the live replacement was disposed" + await live.aclose() + + asyncio.run(_body()) diff --git a/tests/unit/test_aio_multi_alias_tracker.py b/tests/unit/test_aio_multi_alias_tracker.py deleted file mode 100644 index 5e136bce6..000000000 --- a/tests/unit/test_aio_multi_alias_tracker.py +++ /dev/null @@ -1,150 +0,0 @@ -# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. -# -# Licensed under the Apache License, Version 2.0 (the "License"). -# You may not use this file except in compliance with the License. -# You may obtain a copy of the License at -# -# http://www.apache.org/licenses/LICENSE-2.0 -# -# Unless required by applicable law or agreed to in writing, software -# distributed under the License is distributed on an "AS IS" BASIS, -# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -# See the License for the specific language governing permissions and -# limitations under the License. - -"""Tests for multi-alias invalidation in AsyncOpenedConnectionTracker (N.2). - -Fixes the prior canonical-key-only semantics: a tracked connection is -now reachable from ANY alias in host_info.as_aliases(), so an -invalidate_all() call via any alias closes every peer connection to -the same underlying instance. -""" - -from __future__ import annotations - -import asyncio -from unittest.mock import MagicMock - -import pytest - -from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ - AsyncOpenedConnectionTracker -from aws_advanced_python_wrapper.hostinfo import HostInfo - - -@pytest.fixture(autouse=True) -def _reset_tracker(): - AsyncOpenedConnectionTracker._tracked.clear() - yield - AsyncOpenedConnectionTracker._tracked.clear() - - -def _host_with_aliases(*aliases: str) -> HostInfo: - """Build a HostInfo whose as_aliases() returns ``aliases``.""" - host = HostInfo(host=aliases[0] if aliases else "h", port=5432) - for alias in aliases[1:]: - host.add_alias(alias) - return host - - -def test_track_records_under_every_alias() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - "cluster.abcd.us-east-1.rds.amazonaws.com", - ) - tracker.track(host, conn) - - keys = AsyncOpenedConnectionTracker._tracked - # Both aliases (plus canonical) resolve to this conn. - matching = [ - k for k, weak_set in keys.items() - if conn in list(weak_set) - ] - assert len(matching) >= 2 - - -def test_invalidate_reaches_conn_via_secondary_alias() -> None: - """A HostInfo that shares the same secondary alias reaches the same - tracked connection -- even when its primary host differs from the - one the connection was tracked under.""" - tracker = AsyncOpenedConnectionTracker() - - class _Conn: - def __init__(self) -> None: - self.closed = False - - def close(self) -> None: - self.closed = True - - conn = _Conn() - shared_alias = "cluster.abcd.us-east-1.rds.amazonaws.com" - - # Track via a HostInfo whose primary is the instance endpoint. - track_host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - shared_alias, - ) - tracker.track(track_host, conn) - - # Invalidate via a different HostInfo whose primary is different but - # whose alias set includes the shared cluster endpoint. - invalidate_host = _host_with_aliases( - "instance-7.abcd.us-east-1.rds.amazonaws.com", - shared_alias, - ) - asyncio.run(tracker.invalidate_all(invalidate_host)) - - assert conn.closed is True - - -def test_invalidate_closes_each_conn_exactly_once() -> None: - """Even if a single connection is reachable from multiple aliases, - invalidate_all must only call close() once per connection.""" - tracker = AsyncOpenedConnectionTracker() - - class _Conn: - def __init__(self) -> None: - self.close_count = 0 - - def close(self) -> None: - self.close_count += 1 - - conn = _Conn() - host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - "cluster.abcd.us-east-1.rds.amazonaws.com", - "cluster-ro.abcd.us-east-1.rds.amazonaws.com", - ) - tracker.track(host, conn) - asyncio.run(tracker.invalidate_all(host)) - - assert conn.close_count == 1 - - -def test_invalidate_swallows_close_errors() -> None: - tracker = AsyncOpenedConnectionTracker() - - class _BadConn: - def close(self) -> None: - raise RuntimeError("boom") - - host = _host_with_aliases("instance-1.abcd.us-east-1.rds.amazonaws.com") - tracker.track(host, _BadConn()) - # Must not raise. - asyncio.run(tracker.invalidate_all(host)) - - -def test_remove_clears_conn_from_every_alias() -> None: - tracker = AsyncOpenedConnectionTracker() - conn = MagicMock() - host = _host_with_aliases( - "instance-1.abcd.us-east-1.rds.amazonaws.com", - "cluster.abcd.us-east-1.rds.amazonaws.com", - ) - tracker.track(host, conn) - tracker.remove(host, conn) - - for weak_set in AsyncOpenedConnectionTracker._tracked.values(): - assert conn not in list(weak_set) diff --git a/tests/unit/test_aio_multi_key_tracker.py b/tests/unit/test_aio_multi_key_tracker.py new file mode 100644 index 000000000..3b87f4300 --- /dev/null +++ b/tests/unit/test_aio_multi_key_tracker.py @@ -0,0 +1,133 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Tests for how AsyncOpenedConnectionTracker keys its connections. + +An instance endpoint names the instance, so one key is enough. Any other +endpoint may be a custom domain name, so the connection is tracked under both +the host id and the endpoint, and an invalidation naming either one finds it. +""" + +from __future__ import annotations + +import asyncio +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio.aurora_connection_tracker import \ + AsyncOpenedConnectionTracker +from aws_advanced_python_wrapper.hostinfo import HostInfo + +INSTANCE = "instance-1.abcd.us-east-1.rds.amazonaws.com" +CUSTOM = "db.example.com" + + +@pytest.fixture(autouse=True) +def _reset_tracker(): + AsyncOpenedConnectionTracker._tracked.clear() + yield + AsyncOpenedConnectionTracker._tracked.clear() + + +def _keys_holding(conn) -> set: + return { + key for key, conn_set in AsyncOpenedConnectionTracker._tracked.items() + if conn in list(conn_set)} + + +def test_an_instance_endpoint_is_tracked_under_one_key() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + tracker.track(HostInfo(host=INSTANCE, port=5432, host_id="instance-1"), conn) + + assert _keys_holding(conn) == {f"{INSTANCE}:5432"} + + +def test_any_other_endpoint_is_tracked_under_the_host_id_and_the_endpoint() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + tracker.track(HostInfo(host=CUSTOM, port=5432, host_id="instance-1"), conn) + + assert _keys_holding(conn) == {"instance-1", f"{CUSTOM}:5432"} + + +def test_a_host_without_a_host_id_is_tracked_under_the_endpoint_alone() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + tracker.track(HostInfo(host=CUSTOM, port=5432), conn) + + assert _keys_holding(conn) == {f"{CUSTOM}:5432"} + + +def test_invalidate_reaches_a_connection_through_its_host_id() -> None: + """The endpoint a connection was opened against can differ from the one a + later invalidation names; the host id is what they share.""" + tracker = AsyncOpenedConnectionTracker() + + class _Conn: + def __init__(self) -> None: + self.closed = False + + def close(self) -> None: + self.closed = True + + conn = _Conn() + tracker.track(HostInfo(host=CUSTOM, port=5432, host_id="instance-1"), conn) + + asyncio.run(tracker.invalidate_all( + HostInfo(host=INSTANCE, port=5432, host_id="instance-1"))) + + assert conn.closed is True + + +def test_invalidate_closes_each_connection_exactly_once() -> None: + tracker = AsyncOpenedConnectionTracker() + + class _Conn: + def __init__(self) -> None: + self.close_count = 0 + + def close(self) -> None: + self.close_count += 1 + + conn = _Conn() + host = HostInfo(host=CUSTOM, port=5432, host_id="instance-1") + tracker.track(host, conn) + asyncio.run(tracker.invalidate_all(host)) + + assert conn.close_count == 1 + + +def test_invalidate_swallows_close_errors() -> None: + tracker = AsyncOpenedConnectionTracker() + + class _BadConn: + def close(self) -> None: + raise RuntimeError("boom") + + host = HostInfo(host=INSTANCE, port=5432) + tracker.track(host, _BadConn()) + # Must not raise. + asyncio.run(tracker.invalidate_all(host)) + + +def test_remove_clears_the_connection_from_every_key() -> None: + tracker = AsyncOpenedConnectionTracker() + conn = MagicMock() + host = HostInfo(host=CUSTOM, port=5432, host_id="instance-1") + tracker.track(host, conn) + tracker.remove(host, conn) + + assert _keys_holding(conn) == set() diff --git a/tests/unit/test_aio_plugin_service_extras.py b/tests/unit/test_aio_plugin_service_extras.py index 21bceae2c..837c2eeca 100644 --- a/tests/unit/test_aio_plugin_service_extras.py +++ b/tests/unit/test_aio_plugin_service_extras.py @@ -19,6 +19,7 @@ from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.utils import services_container +from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.properties import Properties @@ -76,21 +77,104 @@ def test_get_availability_returns_none_when_unset(): def test_set_then_get_availability(): svc = _make_service() - svc.set_availability(frozenset({"host-1.cluster.example"}), HostAvailability.UNAVAILABLE) - assert svc.get_availability("host-1.cluster.example") == HostAvailability.UNAVAILABLE + host = HostInfo("host-1.cluster.example", 5432) + svc._all_hosts = (host,) + svc.set_availability(host, HostAvailability.UNAVAILABLE) -def test_set_availability_covers_all_aliases(): + assert svc.get_availability(host.url) == HostAvailability.UNAVAILABLE + assert host.get_raw_availability() == HostAvailability.UNAVAILABLE + + +def test_set_availability_matches_a_host_by_its_host_id(): + """The caller's host and the topology's host can carry different endpoints + for the same instance, which is what the host id is for.""" + svc = _make_service() + in_topology = HostInfo("instance-1.abc.us-east-1.rds.amazonaws.com", 5432, + host_id="instance-1") + svc._all_hosts = (in_topology,) + + svc.set_availability(HostInfo("db.example.com", 5432, host_id="instance-1"), + HostAvailability.UNAVAILABLE) + + assert in_topology.get_raw_availability() == HostAvailability.UNAVAILABLE + + +def test_set_availability_ignores_a_host_that_is_not_in_the_host_list(): + svc = _make_service() + in_list = HostInfo("h1.example", 5432) + svc._all_hosts = (in_list,) + stranger = HostInfo("stranger.example", 5432) + + svc.set_availability(stranger, HostAvailability.UNAVAILABLE) + + assert svc.get_availability(stranger.url) is None + # Bound both sides: the argument itself is not marked either. + assert stranger.get_raw_availability() == HostAvailability.AVAILABLE + assert in_list.get_raw_availability() == HostAvailability.AVAILABLE + + +def test_set_availability_notifies_only_on_an_actual_change(): + svc = _make_service() + host = HostInfo("h1.example", 5432) + svc._all_hosts = (host,) + manager = MagicMock() + svc.plugin_manager = manager + + # Already AVAILABLE, so nothing changed. + svc.set_availability(host, HostAvailability.AVAILABLE) + manager.notify_host_list_changed.assert_not_called() + + svc.set_availability(host, HostAvailability.UNAVAILABLE) + changes = manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} + + +def test_set_current_connection_clears_the_routed_host(): + """A switch that reuses a cached connection never runs a connect, so this + is the only thing that stops the next reader of the field seeing the host + the connection has already moved off.""" + async def _body(): + svc = _make_service() + reader = HostInfo("reader-1.example", 5432) + writer = HostInfo("writer-1.example", 5432) + svc.routed_host_info = reader + + await svc.set_current_connection(MagicMock(), writer) + + assert svc.routed_host_info is None + + asyncio.run(_body()) + + +def test_take_routed_host_info_returns_it_once(): + svc = _make_service() + routed = HostInfo("instance-1.example", 5432) + svc.routed_host_info = routed + + assert svc.take_routed_host_info() is routed + assert svc.take_routed_host_info() is None + + +def test_set_availability_writes_the_cache_under_the_host_url(): + """_update_host_availability reads back by url, so the write has to use the + same key or a fresh topology never recovers the mark.""" svc = _make_service() - aliases = frozenset({"h1.example", "h1-alias.example"}) - svc.set_availability(aliases, HostAvailability.UNAVAILABLE) - for alias in aliases: - assert svc.get_availability(alias) == HostAvailability.UNAVAILABLE + host = HostInfo("h1.example", 5432) + svc._all_hosts = (host,) + svc.set_availability(host, HostAvailability.UNAVAILABLE) -def test_set_availability_marks_only_the_named_host(): - """The mark is keyed by alias, so marking one host must leave the other - hosts in the topology selectable.""" + rebuilt = HostInfo("h1.example", 5432) + svc._update_host_availability((rebuilt,)) + assert rebuilt.get_raw_availability() == HostAvailability.UNAVAILABLE + + +def test_set_availability_marks_only_the_matching_live_host(): + """Host selection reads HostInfo.get_availability() directly, so the mark + has to reach the live object -- and only the host it names. Distinct from + test_set_availability_ignores_a_host_that_is_not_in_the_host_list: this + host IS in the list, and the sibling beside it must stay selectable.""" svc = _make_service() writer = HostInfo(host="instance-1.abc.us-east-2.rds.amazonaws.com", port=3306, role=HostRole.WRITER) @@ -98,12 +182,10 @@ def test_set_availability_marks_only_the_named_host(): port=3306, role=HostRole.READER) svc._all_hosts = (writer, reader) - svc.set_availability(writer.all_aliases, HostAvailability.UNAVAILABLE) + svc.set_availability(writer, HostAvailability.UNAVAILABLE) - for alias in writer.all_aliases: - assert svc.get_availability(alias) == HostAvailability.UNAVAILABLE - for alias in reader.all_aliases: - assert svc.get_availability(alias) is None + assert writer.get_raw_availability() == HostAvailability.UNAVAILABLE + assert reader.get_raw_availability() == HostAvailability.AVAILABLE def test_default_plugin_accepts_random_strategy(): @@ -517,64 +599,6 @@ def test_current_host_info_raises_when_writer_not_allowed(): _ = svc.current_host_info -# ---- fill_aliases (sync parity) -------------------------------------- - - -def _alias_cursor(rows): - cur = MagicMock() - cur.__aenter__ = AsyncMock(return_value=cur) - cur.__aexit__ = AsyncMock(return_value=None) - cur.execute = AsyncMock() - cur.fetchall = AsyncMock(return_value=rows) - return cur - - -def test_fill_aliases_adds_self_query_and_identify_aliases(): - async def _body(): - svc = _make_service() - dialect = MagicMock(spec=DatabaseDialect) - dialect.host_alias_query = "SELECT CONCAT(...)" - svc.database_dialect = dialect - - conn = MagicMock() - conn.cursor = MagicMock(return_value=_alias_cursor([("db-alias",)])) - - identified = HostInfo("h", 5432) - identified.add_alias("id-alias") - svc.identify_connection = AsyncMock(return_value=identified) - - host = HostInfo("h", 5432) - await svc.fill_aliases(conn, host) - - assert "h:5432" in host.aliases # host:port self-alias - assert "db-alias" in host.aliases # from host_alias_query - assert "id-alias" in host.aliases # from identify_connection - - asyncio.run(_body()) - - -def test_fill_aliases_noop_when_already_has_aliases(): - async def _body(): - svc = _make_service() - host = HostInfo("h", 5432) - host.add_alias("existing") - conn = MagicMock() - await svc.fill_aliases(conn, host) - conn.cursor.assert_not_called() - - asyncio.run(_body()) - - -def test_fill_aliases_noop_when_no_connection(): - async def _body(): - svc = _make_service() - host = HostInfo("h", 5432) - await svc.fill_aliases(None, host) - assert len(host.aliases) == 0 - - asyncio.run(_body()) - - # ---- get_host_role default timeout (sync parity) --------------------- @@ -648,7 +672,7 @@ async def _body(): result = asyncio.run(_body()) assert result is conn svc.set_availability.assert_called_once_with( - host.as_aliases(), HostAvailability.AVAILABLE) + host, HostAvailability.AVAILABLE) svc.update_driver_dialect.assert_called_once_with(provider) @@ -669,7 +693,7 @@ async def _body(): asyncio.run(_body()) svc.set_availability.assert_called_once_with( - host.as_aliases(), HostAvailability.AVAILABLE) + host, HostAvailability.AVAILABLE) svc.update_driver_dialect.assert_called_once_with(provider) diff --git a/tests/unit/test_aio_retry_util.py b/tests/unit/test_aio_retry_util.py index 41dcc385a..20c56f5af 100644 --- a/tests/unit/test_aio_retry_util.py +++ b/tests/unit/test_aio_retry_util.py @@ -244,7 +244,7 @@ async def _connect(_host): assert result.connection is conn assert result.host_info.host == _W.host svc.set_availability.assert_any_call( - _W.as_aliases(), HostAvailability.AVAILABLE) + _W, HostAvailability.AVAILABLE) asyncio.run(_body()) @@ -310,7 +310,7 @@ async def _connect(_host): await util.get_writer_connection( svc, hlp, _connect, (dead,), _deadline(0.25)) svc.set_availability.assert_any_call( - dead.as_aliases(), HostAvailability.UNAVAILABLE) + dead, HostAvailability.UNAVAILABLE) asyncio.run(_body()) @@ -360,7 +360,7 @@ async def _connect(host): assert result.connection is conns["new-writer"] # Dead old writer marked unavailable; the reader probe connection dropped. svc.set_availability.assert_any_call( - old.as_aliases(), HostAvailability.UNAVAILABLE) + old, HostAvailability.UNAVAILABLE) svc.driver_dialect.abort_connection.assert_awaited() asyncio.run(_body()) diff --git a/tests/unit/test_aio_simple_rws.py b/tests/unit/test_aio_simple_rws.py index 4f7a75467..cb764cb42 100644 --- a/tests/unit/test_aio_simple_rws.py +++ b/tests/unit/test_aio_simple_rws.py @@ -223,10 +223,13 @@ def test_verify_retries_then_falls_back_when_role_mismatches_and_current_usable( async def _body() -> None: # Asked for a reader, but every probe says WRITER -> exhaust retries. svc, dd = _build_plugin_service(role_returns=HostRole.WRITER) - # Extra-short timeout to keep the test quick; still exercises >1 loop. + # The budget has to outlast one slow attempt by a wide margin: the + # retry loop checks a wall-clock deadline, and at a 30ms budget a + # scheduling hiccup under the full suite left a single attempt and + # failed the await_count assertions below. props = _base_props( **{ - WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "30", + WrapperProperties.SRW_CONNECT_RETRY_TIMEOUT_MS.name: "250", WrapperProperties.SRW_CONNECT_RETRY_INTERVAL_MS.name: "5", } ) diff --git a/tests/unit/test_aio_topology_storage.py b/tests/unit/test_aio_topology_storage.py index 8901d238a..03beb7152 100644 --- a/tests/unit/test_aio_topology_storage.py +++ b/tests/unit/test_aio_topology_storage.py @@ -265,18 +265,32 @@ async def _run(): asyncio.run(_run()) -def test_copies_keep_their_aliases(): - """HostInfo.__copy__ drops aliases, and aliases are how a live connection - is matched back to its topology row.""" - aliased = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1") - aliased.add_alias("srv-1") +def test_copies_keep_their_host_id(): + """host_id is how a live connection is matched back to its topology row.""" + stored = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1") prov = _aurora() async def _run(): - prov._store_topology((aliased,)) + prov._store_topology((stored,)) got = await prov.refresh() - assert got[0] is not aliased - assert "srv-1" in got[0].aliases + assert got[0] is not stored assert got[0].host_id == "srv-1" asyncio.run(_run()) + + +def test_copies_keep_their_availability_strategy(): + """The strategy decides when a host marked unavailable becomes usable + again, so a copy that reverted to the no-op default would report it + available straight away.""" + prov = _aurora() + strategy = prov._topology_utils._host_availability_strategy + stored = HostInfo("writer.example", 5432, HostRole.WRITER, host_id="srv-1", + host_availability_strategy=strategy) + + async def _run(): + prov._store_topology((stored,)) + got = await prov.refresh() + assert got[0].host_availability_strategy is strategy + + asyncio.run(_run()) diff --git a/tests/unit/test_aio_wrapper.py b/tests/unit/test_aio_wrapper.py index ac16601fc..0658d1160 100644 --- a/tests/unit/test_aio_wrapper.py +++ b/tests/unit/test_aio_wrapper.py @@ -737,9 +737,14 @@ async def _body() -> None: target=_build_mock_psycopg_connect(raw_conn), conninfo="host=h user=u password=p dbname=d port=5432", **_NAMED_DIALECT, ) - async with wrapper.cursor() as cur: - assert isinstance(cur, AsyncAwsWrapperCursor) - mock_cursor.close.assert_awaited_once() + # The mock conn hands out one cursor for everything, including the + # wrapper's own auxiliary queries, so measure across the exit alone. + manager = wrapper.cursor() + cur = await manager.__aenter__() + assert isinstance(cur, AsyncAwsWrapperCursor) + before = mock_cursor.close.await_count + await manager.__aexit__(None, None, None) + assert mock_cursor.close.await_count == before + 1 asyncio.run(_body()) diff --git a/tests/unit/test_aurora_connection_tracker.py b/tests/unit/test_aurora_connection_tracker.py index 6ab370fe9..6c36d3114 100644 --- a/tests/unit/test_aurora_connection_tracker.py +++ b/tests/unit/test_aurora_connection_tracker.py @@ -29,6 +29,7 @@ AuroraConnectionTrackerPlugin, OpenedConnectionTracker) from aws_advanced_python_wrapper.hostinfo import HostInfo from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.rds_url_type import RdsUrlType @pytest.fixture @@ -43,7 +44,11 @@ def mock_cursor(mocker): @pytest.fixture def mock_plugin_service(mocker): - return mocker.MagicMock() + service = mocker.MagicMock() + # A MagicMock attribute would stand in for a routed host and send the + # tracker down the identify path. + service.routed_host_info = None + return service @pytest.fixture @@ -67,11 +72,13 @@ def props(): def test_track_new_instance_connection( - mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_cursor, mock_callable): + mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_cursor, mock_callable, + mock_conn): host_info: HostInfo = HostInfo("instance1") mock_plugin_service.all_hosts = [host_info] mock_plugin_service.current_host_info = host_info mock_rds_utils.is_rds_instance.return_value = True + mock_rds_utils.identify_rds_type.return_value = RdsUrlType.RDS_INSTANCE mock_callable.return_value = mock_conn plugin: AuroraConnectionTrackerPlugin = AuroraConnectionTrackerPlugin(mock_plugin_service, Properties(), @@ -80,14 +87,35 @@ def test_track_new_instance_connection( conn: Connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, Properties(), True, mock_callable) assert mock_conn == conn - mock_tracker.populate_opened_connection_queue(host_info, mock_conn) - assert 0 == len(host_info.aliases) + mock_tracker.populate_opened_connection_set.assert_called_with(host_info, mock_conn) + # An instance endpoint names the instance, so there is nothing to identify. + mock_plugin_service.identify_connection.assert_not_called() conn = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, Properties(), False, mock_callable) assert mock_conn == conn - mock_tracker.populate_opened_connection_queue(host_info, mock_conn) - assert 0 == len(host_info.aliases) + mock_tracker.populate_opened_connection_set.assert_called_with(host_info, mock_conn) + mock_plugin_service.identify_connection.assert_not_called() + + +def test_connect_tracks_a_cluster_connection_under_its_identified_host( + mocker, mock_plugin_service, mock_rds_utils, mock_tracker, mock_callable, mock_conn): + """A cluster endpoint does not name the instance the connection landed on, + so the tracker needs the identified host to key it correctly.""" + cluster_host = HostInfo("mydb.cluster-abc.us-east-2.rds.amazonaws.com", 5432) + identified = HostInfo("instance-1.abc.us-east-2.rds.amazonaws.com", 5432, + host_id="instance-1") + mock_rds_utils.identify_rds_type.return_value = RdsUrlType.RDS_WRITER_CLUSTER + mock_plugin_service.identify_connection.return_value = identified + mock_callable.return_value = mock_conn + + plugin = AuroraConnectionTrackerPlugin( + mock_plugin_service, Properties(), mock_rds_utils, mock_tracker) + plugin.connect( + mocker.MagicMock(), mocker.MagicMock(), cluster_host, Properties(), True, mock_callable) + + mock_tracker.populate_opened_connection_set.assert_called_with(identified, mock_conn) + assert mock_plugin_service.routed_host_info is identified def test_invalidate_opened_connections( @@ -179,6 +207,98 @@ def test_invalidate_all_connections_drains_set(mocker): assert len(captured) == 1 +def _real_tracker(mocker): + """A tracker with a real RdsUtils and no prune thread or closer thread.""" + OpenedConnectionTracker._opened_connections = {} + mocker.patch.object(OpenedConnectionTracker, "_start_prune_thread") + captured: list = [] + mocker.patch.object( + OpenedConnectionTracker, + "_invalidate_connections", + side_effect=lambda connections_list: captured.append(list(connections_list))) + return OpenedConnectionTracker(), captured + + +def test_a_non_instance_endpoint_is_tracked_under_its_host_id_too(mocker): + """The endpoint a connection was opened against can differ from the one a + later invalidation names; the host id is what they share.""" + tracker, _ = _real_tracker(mocker) + conn = mocker.MagicMock() + + tracker.populate_opened_connection_set( + HostInfo("db.example.com", 5432, host_id="instance-1"), conn) + + assert set(OpenedConnectionTracker._opened_connections) == { + "instance-1", "db.example.com:5432"} + + +def test_an_instance_endpoint_is_tracked_under_one_key(mocker): + tracker, _ = _real_tracker(mocker) + + tracker.populate_opened_connection_set( + HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1"), + mocker.MagicMock()) + + assert set(OpenedConnectionTracker._opened_connections) == { + "instance-1.xyz.us-east-2.rds.amazonaws.com:5432"} + + +def test_invalidate_reaches_a_connection_through_its_host_id(mocker): + tracker, captured = _real_tracker(mocker) + conn = mocker.MagicMock() + tracker.populate_opened_connection_set( + HostInfo("db.example.com", 5432, host_id="instance-1"), conn) + + tracker.invalidate_all_connections( + HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1")) + + assert captured and conn in captured[0] + + +def test_invalidate_closes_a_multi_key_connection_once(mocker): + """Closing a pool-proxied connection twice would invalidate whatever the + pool handed out in between.""" + tracker, captured = _real_tracker(mocker) + conn = mocker.MagicMock() + host = HostInfo("db.example.com", 5432, host_id="instance-1") + tracker.populate_opened_connection_set(host, conn) + + tracker.invalidate_all_connections(host) + + assert len(captured) == 1 + assert captured[0].count(conn) == 1 + + +def test_notify_strips_the_trailing_slash_from_a_change_key( + mocker, mock_plugin_service, mock_rds_utils, mock_callable): + """Change keys are urls; tracking keys are not. Matching them without + stripping would never find the connection.""" + from aws_advanced_python_wrapper.utils.notifications import HostEvent + + tracker, captured = _real_tracker(mocker) + conn = mocker.MagicMock() + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + tracker.populate_opened_connection_set(host, conn) + + plugin = AuroraConnectionTrackerPlugin( + mock_plugin_service, Properties(), mock_rds_utils, tracker) + plugin.notify_host_list_changed({host.url: {HostEvent.CONVERTED_TO_READER}}) + + assert captured and conn in captured[0] + + +def test_remove_connection_tracking_clears_every_key(mocker): + tracker, _ = _real_tracker(mocker) + conn = mocker.MagicMock() + host = HostInfo("db.example.com", 5432, host_id="instance-1") + tracker.populate_opened_connection_set(host, conn) + + tracker.remove_connection_tracking(host, conn) + + assert all(conn not in conn_set + for conn_set in OpenedConnectionTracker._opened_connections.values()) + + def test_task_invalidates_pool_proxied_connections(mocker): pool_proxied_conn = mocker.MagicMock() diff --git a/tests/unit/test_connection.py b/tests/unit/test_connection.py index 30b191b15..8e5f20684 100644 --- a/tests/unit/test_connection.py +++ b/tests/unit/test_connection.py @@ -46,6 +46,47 @@ def test_connection_basic(): password="qwerty") +def _wrapper_with(plugin_service, plugin_manager, conn): + """Drive AwsWrapperConnection.__init__ past its setup to the host-adoption + step, which is what decides the connection's current host.""" + plugin_manager.connect.return_value = conn + plugin_service.database_dialect.get_host_list_provider_supplier.return_value = \ + lambda _service, _props: MagicMock() + wrapper = AwsWrapperConnection.__new__(AwsWrapperConnection) + AwsWrapperConnection.__init__( + wrapper, MagicMock(), MagicMock(), plugin_service, plugin_manager) + return wrapper + + +def test_the_wrapper_adopts_the_host_a_plugin_routed_the_connect_to(): + """The initial connection strategy plugin substitutes an instance for a + cluster endpoint. Binding the connection to the endpoint instead would + leave every later host comparison naming the wrong host.""" + routed = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + conn = MagicMock(spec=psycopg.Connection) + plugin_service = MagicMock() + plugin_service.current_connection = None + plugin_service.initial_connection_host_info = HostInfo("mydb.cluster-xyz.us-east-2.rds.amazonaws.com", 5432) + plugin_service.take_routed_host_info.return_value = routed + + _wrapper_with(plugin_service, MagicMock(), conn) + + plugin_service.set_current_connection.assert_called_once_with(conn, routed) + + +def test_the_wrapper_falls_back_to_the_initial_host_when_nothing_routed(): + initial = HostInfo("mydb.cluster-xyz.us-east-2.rds.amazonaws.com", 5432) + conn = MagicMock(spec=psycopg.Connection) + plugin_service = MagicMock() + plugin_service.current_connection = None + plugin_service.initial_connection_host_info = initial + plugin_service.take_routed_host_info.return_value = None + + _wrapper_with(plugin_service, MagicMock(), conn) + + plugin_service.set_current_connection.assert_called_once_with(conn, initial) + + def test_connection_getattr_delegates_to_underlying_connection(): # Driver-specific extension methods absent from the wrapper's PEP-249 surface # (e.g. psycopg's add_notice_handler, called by SQLAlchemy) must reach the diff --git a/tests/unit/test_expiration_tracking_cache.py b/tests/unit/test_expiration_tracking_cache.py index faa4756ae..a28331ccd 100644 --- a/tests/unit/test_expiration_tracking_cache.py +++ b/tests/unit/test_expiration_tracking_cache.py @@ -66,24 +66,6 @@ def test_compute_if_absent_extends_expiration(): assert cache.get("k1") == "v1" -def test_get_or_create_for_aliases(cache): - result = cache.get_or_create_for_aliases( - frozenset(["a", "b", "c"]), lambda: "val") - assert result == "val" - assert cache.get("a") == "val" - assert cache.get("b") == "val" - assert cache.get("c") == "val" - - -def test_get_or_create_for_aliases_reuses_existing(cache): - cache.put("b", "existing") - result = cache.get_or_create_for_aliases( - frozenset(["a", "b", "c"]), lambda: "new") - assert result == "existing" - # "a" and "c" should also be set - assert cache.get("a") == "existing" - - def test_extend_expiration(): cache = ExpirationTrackingCache(_SHORT_TTL) cache.put("k1", "v1") diff --git a/tests/unit/test_failover_plugin.py b/tests/unit/test_failover_plugin.py index 726b0d086..2ba1bdbb5 100644 --- a/tests/unit/test_failover_plugin.py +++ b/tests/unit/test_failover_plugin.py @@ -22,7 +22,7 @@ if TYPE_CHECKING: from aws_advanced_python_wrapper.writer_failover_handler import WriterFailoverHandler -from typing import Dict, FrozenSet, Set +from typing import Dict, Set from unittest import mock from unittest.mock import MagicMock, PropertyMock @@ -130,27 +130,21 @@ def test_notify_host_list_changed_with_failover_disabled(plugin_service_mock, ho get_current_host_mock = PropertyMock(return_value=host_mock) type(plugin_service_mock).current_host_info = get_current_host_mock - get_aliases_mock = PropertyMock() - type(host_mock).aliases = get_aliases_mock plugin.notify_host_list_changed(changes) get_current_host_mock.assert_not_called() - get_aliases_mock.assert_not_called() WrapperProperties.ENABLE_FAILOVER.set(properties, "True") plugin = FailoverPlugin(plugin_service_mock, properties) plugin.notify_host_list_changed(changes) get_current_host_mock.assert_called() - get_aliases_mock.assert_not_called() def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_service_mock, host_mock): host_mock.url = "cluster-url/" - aliases: FrozenSet[str] = frozenset("instance") - host_mock.aliases = aliases properties = Properties() WrapperProperties.ENABLE_FAILOVER.set(properties, "True") @@ -158,8 +152,6 @@ def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_s get_current_host_mock = PropertyMock(return_value=host_mock) type(plugin_service_mock).current_host_info = get_current_host_mock - get_aliases_mock = PropertyMock() - type(host_mock).aliases = get_aliases_mock changes: Dict[str, Set[HostEvent]] = \ {"cluster-host/": {HostEvent.HOST_DELETED}, @@ -167,7 +159,6 @@ def test_notify_host_list_changed_with_valid_connection_not_in_topology(plugin_s plugin.notify_host_list_changed(changes) get_current_host_mock.assert_called() - get_aliases_mock.assert_not_called() def test_update_topology( diff --git a/tests/unit/test_host_monitor_v2_plugin.py b/tests/unit/test_host_monitor_v2_plugin.py index 273a2e442..b057e3f4b 100644 --- a/tests/unit/test_host_monitor_v2_plugin.py +++ b/tests/unit/test_host_monitor_v2_plugin.py @@ -46,6 +46,8 @@ def mock_plugin_service(mocker, mock_driver_dialect, mock_conn, host_info): service_mock = mocker.MagicMock() service_mock.current_connection = mock_conn service_mock.current_host_info = host_info + # A MagicMock attribute would stand in for a routed host. + service_mock.routed_host_info = None type(service_mock).driver_dialect = mocker.PropertyMock(return_value=mock_driver_dialect) return service_mock @@ -165,28 +167,67 @@ def test_execute_monitoring_enabled(mocker, plugin, mock_monitor_service, mock_e def test_connect(mocker, plugin, host_info, props, mock_conn, mock_plugin_service): + """A cluster endpoint does not name the instance the connection landed on, + so the instance is identified and recorded as the routed host.""" mock_connect_func = mocker.MagicMock() mock_connect_func.return_value = mock_conn + identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") + mock_plugin_service.identify_connection.return_value = identified connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, props, True, mock_connect_func) - mock_plugin_service.fill_aliases.assert_called_once() + + mock_plugin_service.identify_connection.assert_called_once() + assert mock_plugin_service.routed_host_info is identified assert mock_conn == connection -def test_get_monitoring_host_info_errors(mocker, plugin, mock_plugin_service): - mock_plugin_service.identify_connection.return_value = None +@pytest.mark.parametrize( + "host", + ["db.example.com", # a custom domain, classified OTHER + "10.0.0.5", # an IP address + "mydb.cluster-custom-xyz.us-east-2.rds.amazonaws.com"]) +def test_a_non_instance_endpoint_has_its_instance_identified( + mocker, mock_plugin_service, mock_monitor_service, props, host): + """These endpoints do not name the instance the connection is on, so the + host to probe has to be resolved rather than taken from the endpoint.""" + identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, + host_id="instance-1") + mock_plugin_service.current_host_info = HostInfo(host, 5432) + mock_plugin_service.identify_connection.return_value = identified + plugin = init_plugin(mock_plugin_service, props, mock_monitor_service) - with pytest.raises(AwsWrapperError): - plugin._get_monitoring_host_info() + assert plugin._get_monitoring_host_info() is identified + + +@pytest.mark.parametrize( + "host", + ["instance-1.xyz.us-east-2.rds.amazonaws.com", + "myproxy.proxy-xyz.us-east-2.rds.amazonaws.com", + "myshardgroup.shardgrp-xyz.us-east-2.rds.amazonaws.com"]) +def test_a_managed_router_endpoint_is_monitored_as_itself( + mocker, mock_plugin_service, mock_monitor_service, props, host): + """A proxy or shard group endpoint stays reachable and is the right thing + to probe. The instance behind it may refuse a direct connection, which + would make the monitor declare a healthy host dead.""" + router = HostInfo(host, 5432) + mock_plugin_service.current_host_info = router + plugin = init_plugin(mock_plugin_service, props, mock_monitor_service) + + assert plugin._get_monitoring_host_info() is router + mock_plugin_service.identify_connection.assert_not_called() - expected_exception = Error() - mock_plugin_service.identify_connection.return_value = mocker.MagicMock() - mock_plugin_service.identify_connection.side_effect = expected_exception - with pytest.raises(AwsWrapperError) as exc_info: - plugin._get_monitoring_host_info() - assert expected_exception == exc_info.value.__cause__ +def test_get_monitoring_host_info_keeps_the_host_when_identification_fails( + mocker, plugin, mock_plugin_service, host_info): + """A localhost, IP or custom-domain host cannot be identified. Failing here + would fail every monitored call on a host that is perfectly monitorable.""" + mock_plugin_service.identify_connection.return_value = None + assert plugin._get_monitoring_host_info() is host_info + + plugin._monitoring_host_info = None + mock_plugin_service.identify_connection.side_effect = Error() + assert plugin._get_monitoring_host_info() is host_info def test_release_resources(plugin, mock_monitor_service): diff --git a/tests/unit/test_host_monitoring_plugin.py b/tests/unit/test_host_monitoring_plugin.py index dab274180..788845f32 100644 --- a/tests/unit/test_host_monitoring_plugin.py +++ b/tests/unit/test_host_monitoring_plugin.py @@ -38,6 +38,8 @@ def mock_plugin_service(mocker, mock_driver_dialect, mock_conn, host_info): service_mock = mocker.MagicMock() service_mock.current_connection = mock_conn service_mock.current_host_info = host_info + # A MagicMock attribute would stand in for a routed host. + service_mock.routed_host_info = None type(service_mock).driver_dialect = mocker.PropertyMock(return_value=mock_driver_dialect) return service_mock @@ -157,45 +159,78 @@ def test_execute_cleanup__connection_not_closed( def test_connect(mocker, plugin, host_info, props, mock_conn, mock_plugin_service): + """A cluster endpoint does not name the instance the connection landed on, + so the instance is identified and recorded as the routed host.""" mock_connect_func = mocker.MagicMock() mock_connect_func.return_value = mock_conn + identified = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") + mock_plugin_service.identify_connection.return_value = identified connection = plugin.connect( mocker.MagicMock(), mocker.MagicMock(), host_info, props, True, mock_connect_func) - mock_plugin_service.fill_aliases.assert_called_once() + + mock_plugin_service.identify_connection.assert_called_once() + assert mock_plugin_service.routed_host_info is identified assert mock_conn == connection @pytest.mark.parametrize( "host_events", - [{"instance-1.xyz.us-east-2.rds.amazonaws.com": {HostEvent.HOST_DELETED}}, - {"instance-1.xyz.us-east-2.rds.amazonaws.com": {HostEvent.WENT_DOWN}}]) + [{"instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.HOST_DELETED}}, + {"instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.WENT_DOWN}}]) def test_notify_host_list_changed( mocker, plugin, host_info, props, mock_conn, mock_plugin_service, mock_monitor_service, host_events): - mock_host_info = mocker.MagicMock() - mock_host_info.host = "instance-1.xyz.us-east-2.rds.amazonaws.com" - aliases = frozenset({"instance-1.xyz.us-east-2.rds.amazonaws.com", "alias1", "alias2"}) - mock_host_info.all_aliases = aliases + monitored = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", host_id="instance-1") plugin._is_connection_initialized = True + plugin._monitoring_host_info = monitored - mock_plugin_service.current_host_info = mock_host_info + mock_plugin_service.current_host_info = monitored plugin.notify_host_list_changed(host_events) - mock_monitor_service.stop_monitoring_host.assert_called_with(aliases) + mock_monitor_service.stop_monitoring_host.assert_called_with(monitored.url) -def test_get_monitoring_host_info_errors(mocker, plugin, mock_plugin_service): - mock_plugin_service.identify_connection.return_value = None +def test_notify_host_list_changed_examines_every_entry( + mocker, plugin, mock_plugin_service, mock_monitor_service): + """set_availability publishes one entry per matched host, so stopping at + the first host with no relevant event drops the rest.""" + monitored = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", host_id="instance-2") + plugin._is_connection_initialized = True + plugin._monitoring_host_info = monitored + mock_plugin_service.current_host_info = monitored - with pytest.raises(AwsWrapperError): - plugin._get_monitoring_host_info() + plugin.notify_host_list_changed({ + "instance-1.xyz.us-east-2.rds.amazonaws.com/": {HostEvent.HOST_CHANGED}, + monitored.url: {HostEvent.WENT_DOWN}, + }) - expected_exception = Error() - mock_plugin_service.identify_connection.return_value = mocker.MagicMock() - mock_plugin_service.identify_connection.side_effect = expected_exception - with pytest.raises(AwsWrapperError) as exc_info: - plugin._get_monitoring_host_info() + mock_monitor_service.stop_monitoring_host.assert_called_once_with(monitored.url) + + +def test_notify_host_list_changed_after_release_resources( + mocker, plugin, mock_plugin_service, mock_monitor_service): + """A failover worker thread outlives its connection, so it can mark a host + unavailable after this plugin has dropped its monitor service reference.""" + monitored = HostInfo("instance-3.xyz.us-east-2.rds.amazonaws.com", host_id="instance-3") + plugin._is_connection_initialized = True + plugin._monitoring_host_info = monitored + mock_plugin_service.current_host_info = monitored + + plugin.release_resources() + plugin.notify_host_list_changed({monitored.url: {HostEvent.WENT_DOWN}}) + + mock_monitor_service.stop_monitoring_host.assert_not_called() + + +def test_get_monitoring_host_info_keeps_the_host_when_identification_fails( + mocker, plugin, mock_plugin_service, host_info): + """A localhost, IP or custom-domain host cannot be identified. Failing here + would fail every monitored call on a host that is perfectly monitorable.""" + mock_plugin_service.identify_connection.return_value = None + assert plugin._get_monitoring_host_info() is host_info - assert expected_exception == exc_info.value.__cause__ + plugin._monitoring_host_info = None + mock_plugin_service.identify_connection.side_effect = Error() + assert plugin._get_monitoring_host_info() is host_info def test_release_resources(plugin, mock_monitor_service): diff --git a/tests/unit/test_hostinfo.py b/tests/unit/test_hostinfo.py index 917103e19..19a2e5210 100644 --- a/tests/unit/test_hostinfo.py +++ b/tests/unit/test_hostinfo.py @@ -24,17 +24,38 @@ def test_host_info_defaults(): host_info = HostInfo("testhost") assert host_info.host == "testhost" assert host_info.is_port_specified() is False - assert len(host_info.aliases) == 0 - assert len(host_info._all_aliases) == 1 + assert host_info.get_host_and_port() == "testhost" assert host_info.role == HostRole.WRITER assert host_info.availability == HostAvailability.AVAILABLE - assert list(host_info._all_aliases)[0] == "testhost" -def test_host_as_alias(): - host_info = HostInfo("testhost", 1234) - assert len(host_info._all_aliases) == 1 - assert list(host_info._all_aliases)[0] == "testhost:1234" +def test_host_and_port_includes_the_port_when_specified(): + assert HostInfo("testhost", 1234).get_host_and_port() == "testhost:1234" + + +def test_url_keeps_its_trailing_slash(): + """The availability cache, the notify_host_list_changed change map and the + host monitoring monitor keys are all keyed on this exact string.""" + assert HostInfo("testhost", 1234).url == "testhost:1234/" + + +def test_each_host_gets_its_own_availability_strategy(): + """A shared default would count one host's failures against all of them.""" + first = HostInfo("a") + second = HostInfo("b") + assert first.host_availability_strategy is not second.host_availability_strategy + + +def test_copy_carries_the_availability_strategy(): + from copy import copy + + from aws_advanced_python_wrapper.host_availability import \ + ExponentialBackoffHostAvailabilityStrategy + from aws_advanced_python_wrapper.utils.properties import Properties + + strategy = ExponentialBackoffHostAvailabilityStrategy(Properties()) + original = HostInfo("testhost", 1234, host_availability_strategy=strategy) + assert copy(original).host_availability_strategy is strategy def test_host_info_eq(): diff --git a/tests/unit/test_monitor_service.py b/tests/unit/test_monitor_service.py index 05b297397..da5235a02 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,51 +57,59 @@ def cleanup(): def test_start_monitoring(mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - aliases = frozenset({"instance-1"}) + host_info = HostInfo("instance-1") - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) monitor_service.start_monitoring( - mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, host_info, Properties(), 5000, 1000, 3) mock_monitor.start_monitoring.assert_called_once() assert mock_monitor == monitor_service._cached_monitor() - assert aliases == monitor_service._cached_monitor_aliases + assert host_info.url == monitor_service._cached_monitor_host_url def test_start_monitoring__cached_monitor( mocker, monitor_service, mock_plugin_service, mock_monitor, mock_conn): - aliases = frozenset({"instance-1"}) + host_info = HostInfo("instance-1") monitor_service._cached_monitor = ref(mock_monitor) - monitor_service._cached_monitor_aliases = aliases + monitor_service._cached_monitor_host_url = host_info.url monitor_service.start_monitoring( - mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, host_info, Properties(), 5000, 1000, 3) mock_monitor.start_monitoring.assert_called_once() assert mock_monitor == monitor_service._cached_monitor() - assert aliases == monitor_service._cached_monitor_aliases + assert host_info.url == monitor_service._cached_monitor_host_url -def test_start_monitoring__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_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_stop_monitoring(mocker, monitor_service, mock_monitor, mock_conn): - aliases = frozenset({"instance-1"}) - mocker.patch.object(monitor_service._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + mocker.patch.object(monitor_service._monitor_service, 'run_if_absent', return_value=mock_monitor) context = monitor_service.start_monitoring( - mock_conn, aliases, HostInfo("instance-1"), Properties(), 5000, 1000, 3) + mock_conn, HostInfo("instance-1"), Properties(), 5000, 1000, 3) monitor_service.stop_monitoring(context) mock_monitor.stop_monitoring.assert_called_once_with(context) def test_stop_monitoring_host(mocker, monitor_service, mock_monitor): - aliases = frozenset({"alias-1"}) mocker.patch.object(monitor_service._monitor_service, 'get', return_value=mock_monitor) - monitor_service.stop_monitoring_host(aliases) + monitor_service.stop_monitoring_host(HostInfo("instance-1").url) mock_monitor.clear_contexts.assert_called_once() diff --git a/tests/unit/test_multi_az_rds_host_list_provider.py b/tests/unit/test_multi_az_rds_host_list_provider.py index bcc3f9dde..aafe48036 100644 --- a/tests/unit/test_multi_az_rds_host_list_provider.py +++ b/tests/unit/test_multi_az_rds_host_list_provider.py @@ -18,6 +18,7 @@ from aws_advanced_python_wrapper.database_dialect import ( AuroraPgDialect, MultiAzClusterPgDialect) from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.host_list_provider import ( MultiAzTopologyUtils, RdsHostListProvider) from aws_advanced_python_wrapper.hostinfo import HostInfo @@ -159,6 +160,32 @@ def test_get_topology_no_connection(mocker, mock_provider_service, initial_hosts mock_force_refresh.assert_not_called() +def test_multi_az_host_id_is_a_string(mock_provider_service, props): + """MySQL reports a numeric id. identify_connection compares host_id + against the string the host id query returns, so an int never matches and + no cluster-endpoint connection can be identified.""" + provider = create_provider(mock_provider_service, props) + host = provider._topology_utils._create_multi_az_host( + (12345, "instance-1.xyz.us-east-2.rds.amazonaws.com", 5432), 12345) + + assert host.host_id == "12345" + + +def test_initial_hosts_are_handed_out_as_copies(mocker, mock_provider_service, props): + """These are built once and never replaced, so marking a host handed out + here would mark it for every later caller.""" + provider = create_provider(mock_provider_service, props) + provider._initialize() + + first = provider._get_topology(None).hosts + second = provider._get_topology(None).hosts + + assert first[0] is not second[0] + assert first[0] is not provider._initial_hosts[0] + first[0].set_availability(HostAvailability.UNAVAILABLE) + assert provider._initial_hosts[0].get_raw_availability() == HostAvailability.AVAILABLE + + def test_host_pattern_setting(mock_provider_service, props): props = Properties({"host": "127:0:0:1", "port": 5432, WrapperProperties.CLUSTER_INSTANCE_HOST_PATTERN.name: "?.custom-domain.com"}) diff --git a/tests/unit/test_multithreaded_monitor_service.py b/tests/unit/test_multithreaded_monitor_service.py index 3c07731d1..eb6134794 100644 --- a/tests/unit/test_multithreaded_monitor_service.py +++ b/tests/unit/test_multithreaded_monitor_service.py @@ -15,7 +15,7 @@ from concurrent.futures import ThreadPoolExecutor from threading import Barrier from time import sleep -from typing import FrozenSet, List +from typing import List import psycopg import pytest @@ -92,19 +92,19 @@ def test_start_monitoring__connections_to_different_hosts( start_monitoring): num_conns = 10 - host_alias_list = generate_host_aliases(num_conns, True) + hosts = generate_hosts(num_conns, True) services = generate_services(num_conns) mocker.patch( "aws_advanced_python_wrapper.host_monitoring_plugin.Monitor.__init__", return_value=None) mocker.patch.object( - services[0]._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + services[0]._monitor_service, 'run_if_absent', return_value=mock_monitor) # Patch all services to use the same mock for svc in services: svc._monitor_service = services[0]._monitor_service - contexts = start_monitoring(num_conns, services, host_alias_list) + contexts = start_monitoring(num_conns, services, hosts) expected_start_monitoring_calls = [mocker.call(context) for context in contexts] mock_monitor.start_monitoring.assert_has_calls(expected_start_monitoring_calls, True) @@ -119,18 +119,18 @@ def test_start_monitoring__connections_to_same_host( start_monitoring): num_conns = 10 - host_alias_list = generate_host_aliases(num_conns, False) + hosts = generate_hosts(num_conns, False) services = generate_services(num_conns) mocker.patch( "aws_advanced_python_wrapper.host_monitoring_plugin.Monitor.__init__", return_value=None) mocker.patch.object( - services[0]._monitor_service, 'run_if_absent_with_aliases', return_value=mock_monitor) + services[0]._monitor_service, 'run_if_absent', return_value=mock_monitor) for svc in services: svc._monitor_service = services[0]._monitor_service - contexts = start_monitoring(num_conns, services, host_alias_list) + contexts = start_monitoring(num_conns, services, hosts) expected_start_monitoring_calls = [mocker.call(context) for context in contexts] mock_monitor.start_monitoring.assert_has_calls(expected_start_monitoring_calls, True) @@ -173,11 +173,10 @@ def test_stop_monitoring__connections_to_same_host( mock_monitor.stop_monitoring.assert_has_calls(expected_stop_monitoring_calls, True) -def generate_host_aliases(num_aliases: int, generate_unique_aliases: bool) -> List[FrozenSet[str]]: - if generate_unique_aliases: - return [frozenset({f"host-{i}"}) for i in range(num_aliases)] - else: - return [frozenset({"single-host"}) for _ in range(num_aliases)] +def generate_hosts(num_hosts: int, generate_unique_hosts: bool) -> List[HostInfo]: + if generate_unique_hosts: + return [HostInfo(f"host-{i}") for i in range(num_hosts)] + return [HostInfo("single-host") for _ in range(num_hosts)] @pytest.fixture @@ -211,7 +210,7 @@ def start_monitoring(counter, concurrent_counter, start_monitoring_thread): def _start_monitoring( num_threads: int, services: List[HostMonitorService], - host_aliases_list: List[FrozenSet[str]]) -> List[MonitoringContext]: + hosts: List[HostInfo]) -> List[MonitoringContext]: barrier = Barrier(num_threads) futures = [] with ThreadPoolExecutor(num_threads) as executor: @@ -222,7 +221,7 @@ def _start_monitoring( counter, concurrent_counter, services[i], - host_aliases_list[i]) + hosts[i]) futures.append(future) return [future.result() for future in futures] return _start_monitoring @@ -231,14 +230,13 @@ def _start_monitoring( @pytest.fixture def start_monitoring_thread( mock_conn, - host_info, props): def _start_monitoring_thread( barrier: Barrier, counter: AtomicInt, concurrent_counter: AtomicInt, service: HostMonitorService, - host_aliases: FrozenSet[str]) -> MonitoringContext: + host_info: HostInfo) -> MonitoringContext: barrier.wait() val = counter.get_and_increment() @@ -247,7 +245,6 @@ def _start_monitoring_thread( context = service.start_monitoring( mock_conn, - host_aliases, host_info, Properties(), 10, diff --git a/tests/unit/test_plugin_service.py b/tests/unit/test_plugin_service.py index 259bc93b3..fb2efa5e7 100644 --- a/tests/unit/test_plugin_service.py +++ b/tests/unit/test_plugin_service.py @@ -13,6 +13,7 @@ # limitations under the License.s from concurrent.futures import TimeoutError +from datetime import datetime, timedelta from unittest.mock import MagicMock, patch import pytest @@ -22,9 +23,12 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, QueryTimeoutError, UnsupportedOperationError) +from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.plugin_service import PluginServiceImpl +from aws_advanced_python_wrapper.utils.notifications import HostEvent from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.utils import Utils def test_get_host_role_unknown_dialect(mocker): @@ -194,7 +198,9 @@ def decorator(func): plugin_service.get_host_role(mock_conn) -def test_identify_connection_error_no_result(mocker): +def test_identify_connection_returns_none_when_the_host_id_query_reports_nothing(mocker): + """Unidentifiable is not a failure: the connect hooks that call this would + otherwise turn an unreported host id into a failed connect.""" mock_conn = MagicMock() mock_cursor = MagicMock() mock_cursor.fetchone.return_value = None @@ -225,8 +231,7 @@ def decorator(func): mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) - with pytest.raises(AwsWrapperError): - plugin_service.identify_connection(mock_conn) + assert plugin_service.identify_connection(mock_conn) is None def test_identify_connection_timeout(mocker): @@ -376,13 +381,15 @@ def decorator(func): def test_identify_connection_host_in_topology_multiaz(mocker): mock_conn = MagicMock() mock_cursor = MagicMock() - # Multi-AZ returns different values: (instanceId, instanceName) + # Multi-AZ returns different values: (instanceId, instanceName). The + # topology carries the id, which is what the first clause matches on. mock_cursor.fetchone.return_value = ("db-WQFQKBTL2LQUPIEFIFBGENS4ZQ", "instance-1") mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) mock_cursor.__exit__ = MagicMock(return_value=False) mock_conn.cursor.return_value = mock_cursor - expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, host_id="instance-1") + expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, + host_id="db-WQFQKBTL2LQUPIEFIFBGENS4ZQ") mock_container = mocker.MagicMock() mock_container.plugin_manager = mocker.MagicMock() @@ -411,7 +418,239 @@ def decorator(func): host_info = plugin_service.identify_connection(mock_conn) assert host_info is not None assert "instance-1.xyz.us-east-2.rds.amazonaws.com" == host_info.host - assert "instance-1" == host_info.host_id + assert "db-WQFQKBTL2LQUPIEFIFBGENS4ZQ" == host_info.host_id + + +def test_identify_connection_matches_on_the_instance_name_column(mocker): + """The second column is matched against the host, not the host id. + + A topology whose host ids come from somewhere other than host_id_query + is still identifiable as long as the name column names the host. + """ + mock_conn = MagicMock() + mock_cursor = MagicMock() + mock_cursor.fetchone.return_value = ( + "unmatched-id", "instance-1.xyz.us-east-2.rds.amazonaws.com") + mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) + mock_cursor.__exit__ = MagicMock(return_value=False) + mock_conn.cursor.return_value = mock_cursor + + expected_host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, HostRole.WRITER, + host_id="db-SOMETHINGELSE") + + mock_container = mocker.MagicMock() + mock_container.plugin_manager = mocker.MagicMock() + mock_host_list_provider = mocker.MagicMock() + mock_host_list_provider.refresh.return_value = (expected_host,) + + plugin_service = PluginServiceImpl( + mock_container, + Properties({"host": "test.com", "port": 5432}), + lambda: None, + mocker.MagicMock(), + mocker.MagicMock() + ) + plugin_service._database_dialect = MultiAzClusterPgDialect() + plugin_service._current_connection = mock_conn + plugin_service._host_list_provider = mock_host_list_provider + + def mock_preserve(thread_pool, timeout, driver_dialect, conn): + def decorator(func): + return func + return decorator + + mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) + + assert plugin_service.identify_connection(mock_conn) is expected_host + + +def _service_with_hosts(mocker, hosts, props=None): + container = mocker.MagicMock() + container.plugin_manager = mocker.MagicMock() + service = PluginServiceImpl( + container, + Properties(props or {"host": "test.com"}), + lambda: None, + mocker.MagicMock(), + mocker.MagicMock()) + service._all_hosts = tuple(hosts) + return service, container + + +def test_identify_connection_returns_none_when_the_host_id_query_errors(mocker): + """The connect hooks that identify a host call this. A host the database + declines to name must not fail their connect.""" + mock_conn = MagicMock() + mock_conn.cursor.side_effect = Exception("relation does not exist") + + service, _ = _service_with_hosts(mocker, ()) + service._database_dialect = AuroraPgDialect() + service._current_connection = mock_conn + service._host_list_provider = mocker.MagicMock() + + def mock_preserve(thread_pool, timeout, driver_dialect, conn): + def decorator(func): + return func + return decorator + + mocker.patch('aws_advanced_python_wrapper.database_dialect.preserve_transaction_status_with_timeout', mock_preserve) + + assert service.identify_connection(mock_conn) is None + + +def test_set_availability_marks_the_host_and_caches_it(mocker): + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + service, container = _service_with_hosts(mocker, (host,)) + + service.set_availability(host, HostAvailability.UNAVAILABLE) + + assert host.get_raw_availability() == HostAvailability.UNAVAILABLE + assert service.get_availability(host.url) == HostAvailability.UNAVAILABLE + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} + + +def test_set_availability_matches_by_host_id_and_is_case_insensitive_on_the_name(mocker): + by_id = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + by_name = HostInfo("Instance-2.XYZ.us-east-2.rds.amazonaws.com", 5432) + untouched = HostInfo("instance-3.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-3") + service, _ = _service_with_hosts(mocker, (by_id, by_name, untouched)) + + service.set_availability(HostInfo("other.example", 5432, host_id="instance-1"), + HostAvailability.UNAVAILABLE) + service.set_availability(HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432), + HostAvailability.UNAVAILABLE) + + assert by_id.get_raw_availability() == HostAvailability.UNAVAILABLE + assert by_name.get_raw_availability() == HostAvailability.UNAVAILABLE + # Bound the other side: a match is not a licence to mark the whole list. + assert untouched.get_raw_availability() == HostAvailability.AVAILABLE + + +def test_set_availability_reports_a_host_coming_back_up(mocker): + """Inverting the event ternary would otherwise pass the suite.""" + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, + availability=HostAvailability.UNAVAILABLE) + service, container = _service_with_hosts(mocker, (host,)) + + service.set_availability(host, HostAvailability.AVAILABLE) + + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_UP, HostEvent.HOST_CHANGED}} + + +def test_set_availability_reports_every_matched_host(mocker): + """One entry per matched host, so a subscriber that stops at the first + one drops the rest.""" + first = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="shared") + second = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="shared") + service, container = _service_with_hosts(mocker, (first, second)) + + service.set_availability(HostInfo("other.example", 5432, host_id="shared"), + HostAvailability.UNAVAILABLE) + + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert set(changes) == {first.url, second.url} + + +def test_set_availability_reads_availability_through_the_backoff_strategy(mocker): + """A host whose backoff window has elapsed reads as available again, so + marking it down is a change the plugins have to hear about.""" + from aws_advanced_python_wrapper.host_availability import \ + ExponentialBackoffHostAvailabilityStrategy + + props = Properties({"host": "test.com", + "host_availability_strategy_initial_backoff_time": "1", + "host_availability_strategy_max_retries": "5"}) + strategy = ExponentialBackoffHostAvailabilityStrategy(props) + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, + availability=HostAvailability.UNAVAILABLE, + host_availability_strategy=strategy) + # Back-date the last change so the retry window has elapsed. + strategy._not_available_count = 1 + strategy._last_changed = datetime.now() - timedelta(seconds=30) + assert host.get_availability() == HostAvailability.AVAILABLE + + service, container = _service_with_hosts(mocker, (host,)) + service.set_availability(host, HostAvailability.UNAVAILABLE) + + changes = container.plugin_manager.notify_host_list_changed.call_args.args[0] + assert changes == {host.url: {HostEvent.WENT_DOWN, HostEvent.HOST_CHANGED}} + + +def test_set_availability_does_not_notify_when_nothing_changed(mocker): + host = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service, container = _service_with_hosts(mocker, (host,)) + + service.set_availability(host, HostAvailability.AVAILABLE) + + # The host did match, so this is "matched but unchanged" rather than the + # early return for an unmatched host. + assert service.get_availability(host.url) == HostAvailability.AVAILABLE + container.plugin_manager.notify_host_list_changed.assert_not_called() + + +def test_set_availability_ignores_a_host_outside_the_host_list(mocker): + in_list = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service, container = _service_with_hosts(mocker, (in_list,)) + stranger = HostInfo("stranger.example", 5432) + + service.set_availability(stranger, HostAvailability.UNAVAILABLE) + + assert service.get_availability(stranger.url) is None + # Bound both sides: neither the argument nor the host list is touched. + assert stranger.get_raw_availability() == HostAvailability.AVAILABLE + assert in_list.get_raw_availability() == HostAvailability.AVAILABLE + container.plugin_manager.notify_host_list_changed.assert_not_called() + + +def test_connect_clears_a_routed_host_left_by_an_earlier_connect(mocker): + """The routed host belongs to one connect. A value left behind would be + read by the next one, which keys the connection tracker and picks the + monitoring host off the previous connect's instance.""" + service, container = _service_with_hosts(mocker, ()) + stale = HostInfo("reader-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service.routed_host_info = stale + observed = {} + + def _record(*args, **kwargs): + observed["routed"] = service.routed_host_info + return MagicMock() + + container.plugin_manager.connect = _record + service.connect(HostInfo("reader-2.xyz.us-east-2.rds.amazonaws.com", 5432), Properties()) + + assert observed["routed"] is None + + +def test_take_routed_host_info_returns_it_once(mocker): + service, _ = _service_with_hosts(mocker, ()) + routed = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432) + service.routed_host_info = routed + + assert service.take_routed_host_info() is routed + assert service.take_routed_host_info() is None + + +def test_find_host_does_not_match_an_instance_name_against_a_host_id(): + """A name-against-id clause picks the decoy that happens to carry the name + as its id. On Multi-AZ the name and the id come from different columns, so + such a clause would match the wrong row rather than be harmless.""" + decoy = HostInfo("decoy.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + wanted = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="db-AAA") + + found = Utils.find_host((decoy, wanted), "db-AAA", "instance-1.xyz.us-east-2.rds.amazonaws.com") + + assert found is wanted + + +def test_find_host_matches_on_either_column(): + aurora = HostInfo("instance-1.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="instance-1") + assert Utils.find_host((aurora,), "instance-1", "instance-1") is aurora + + by_name = HostInfo("instance-2.xyz.us-east-2.rds.amazonaws.com", 5432, host_id="db-BBB") + assert Utils.find_host( + (by_name,), "unmatched", "instance-2.xyz.us-east-2.rds.amazonaws.com") is by_name def test_could_not_determine_current_host_raises_resolved_message(): diff --git a/tests/unit/test_reader_failover_handler.py b/tests/unit/test_reader_failover_handler.py index f4ccc537b..58a056a8d 100644 --- a/tests/unit/test_reader_failover_handler.py +++ b/tests/unit/test_reader_failover_handler.py @@ -75,9 +75,9 @@ def test_failover(plugin_service_mock, connection_mock, default_properties, defa props = default_properties current_host = hosts[2] success_host = hosts[4] - expected = [call(x.all_aliases, HostAvailability.UNAVAILABLE) + expected = [call(x, HostAvailability.UNAVAILABLE) if x != success_host - else call(x.all_aliases, HostAvailability.AVAILABLE) + else call(x, HostAvailability.AVAILABLE) for x in hosts] exception = Exception("Test Exception") @@ -170,7 +170,7 @@ def force_connect_side_effect(host_info, _) -> Connection: assert result.connection == connection_mock assert result.new_host == fast_host - plugin_service_mock.set_availability.assert_any_call(fast_host.all_aliases, HostAvailability.AVAILABLE) + plugin_service_mock.set_availability.assert_any_call(fast_host, HostAvailability.AVAILABLE) def test_get_reader_connection_failure(plugin_service_mock, connection_mock, default_properties, default_hosts): diff --git a/tests/unit/test_writer_failover_handler.py b/tests/unit/test_writer_failover_handler.py index 4eaeccf2f..7a64f6d89 100644 --- a/tests/unit/test_writer_failover_handler.py +++ b/tests/unit/test_writer_failover_handler.py @@ -105,14 +105,6 @@ def new_topology(new_writer_host, reader_a, reader_b): return tuple([new_writer_host, reader_a, reader_b]) -@pytest.fixture(autouse=True) -def setup(writer, new_writer_host, reader_a, reader_b): - writer.add_alias("writer-host") - new_writer_host.add_alias("new-writer-host") - reader_a.add_alias("reader-a") - reader_b.add_alias("reader-b") - - def test_reconnect_to_writer_task_b_reader_exception( writer_connection_mock, plugin_service_mock, reader_failover_mock, default_properties, writer, topology): exception = Exception("Test Exception") @@ -142,8 +134,8 @@ def force_connect_side_effect(host_info, _) -> Connection: assert not result.is_new_host assert result.new_connection is writer_connection_mock - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(writer.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(writer, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -153,8 +145,8 @@ def test_reconnect_to_writer_slow_task_b( reader_a_connection_mock, default_properties, new_writer_host, writer, reader_a, reader_b, topology, new_topology): exception = Exception("Test Exception") - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(writer.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(writer, HostAvailability.AVAILABLE)] mock_hosts_property = mocker.PropertyMock(side_effect=chain((topology,), cycle((new_topology,)))) type(plugin_service_mock).all_hosts = mock_hosts_property @@ -227,8 +219,8 @@ def get_reader_connection_side_effect(_): assert not result.is_new_host assert result.new_connection is writer_connection_mock - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(writer.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(writer, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -274,8 +266,8 @@ def get_reader_connection_side_effect(_): assert result.is_new_host assert result.new_connection is new_writer_connection_mock - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(new_writer_host.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(new_writer_host, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -325,8 +317,8 @@ def get_reader_connection_side_effect(_): assert len(result.topology) == 4 assert "new-writer-host" == result.topology[0].host - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(new_writer_host.as_aliases(), HostAvailability.AVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(new_writer_host, HostAvailability.AVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected, any_order=True) @@ -377,7 +369,7 @@ def get_reader_connection_side_effect(_): assert not result.is_connected assert not result.is_new_host - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected) @@ -420,7 +412,7 @@ def get_reader_connection_side_effect(_): assert not result.is_connected assert not result.is_new_host - expected = [call(writer.as_aliases(), HostAvailability.UNAVAILABLE), - call(new_writer_host.as_aliases(), HostAvailability.UNAVAILABLE)] + expected = [call(writer, HostAvailability.UNAVAILABLE), + call(new_writer_host, HostAvailability.UNAVAILABLE)] plugin_service_mock.set_availability.assert_has_calls(expected, any_order=True) From b0720e0cb53e95421daffbf389d61646c0888180 Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Wed, 28 Oct 2026 21:32:08 -0700 Subject: [PATCH 2/2] fix: do not deep copy monitoring properties --- aws_advanced_python_wrapper/utils/properties.py | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index 33b379c40..9623c83fe 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -12,7 +12,6 @@ # See the License for the specific language governing permissions and # limitations under the License. -import copy from typing import Any, Dict, Optional, Type, TypeVar from urllib.parse import unquote @@ -939,7 +938,7 @@ def mask_properties(props: Properties) -> Properties: @staticmethod def create_filtered_properties(props: Properties, prefix: str) -> Properties: - monitoring_properties = copy.deepcopy(props) + monitoring_properties = Properties(props) for property_key in list(monitoring_properties.keys()): if property_key.startswith(prefix): monitoring_properties[