From fbd6443b2fbced5cc264ea8a2a487c3344d505ad Mon Sep 17 00:00:00 2001 From: karezche <64801825+karenc-bq@users.noreply.github.com> Date: Mon, 5 Oct 2026 14:57:47 -0700 Subject: [PATCH] fix: initial connection strategy retry and routing --- ...rora_initial_connection_strategy_plugin.py | 198 ++++++++----- ...rora_initial_connection_strategy_plugin.py | 273 +++++++++++++----- ...dvanced_python_wrapper_messages.properties | 5 +- .../PYTHON-WRAPPER-CONFIGURATION-ASSISTANT.md | 25 +- ...heAuroraInitialConnectionStrategyPlugin.md | 14 +- .../test_aio_aurora_initial_connection.py | 216 +++++++++++++- ...rora_initial_connection_strategy_plugin.py | 47 ++- 7 files changed, 609 insertions(+), 169 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aio/aurora_initial_connection_strategy_plugin.py index d00ff2e83..d24cf2f3f 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 @@ -37,7 +37,8 @@ from aws_advanced_python_wrapper.aio.plugin import AsyncPlugin from aws_advanced_python_wrapper.aurora_initial_connection_strategy_plugin import ( - InstanceSubstitutionStrategy, RoleVerificationSetting) + InstanceSubstitutionStrategy, RoleVerificationSetting, + _inactive_cluster_writer_role, _inactive_cluster_writer_strategy) from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole @@ -110,79 +111,117 @@ async def connect( connect_func: Callable[..., Awaitable[Any]]) -> Any: original_host = host_info.host url_type: RdsUrlType = self._rds_utils.identify_rds_type(original_host) - substitution_strategy = self._get_instance_substitution_strategy( - props, url_type, is_initial_connection, original_host) - role_to_verify = self._get_role_to_verify(url_type, is_initial_connection, props, original_host) loop = asyncio.get_running_loop() deadline = loop.time() + (self._open_connection_retry_timeout_ns / 1_000_000_000) + last_error: Optional[Exception] = None + + while True: + substitution_strategy = self._get_instance_substitution_strategy( + props, url_type, is_initial_connection, original_host) + role_to_verify = self._get_role_to_verify(url_type, is_initial_connection, props, original_host) + + if (substitution_strategy is InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE + and role_to_verify is None): + # Nothing to substitute and no role to verify, so retrying cannot change the + # outcome. Connect once and let the driver's own error surface. Nothing is + # recorded as routed: this plugin did not reroute the connect. + return await connect_func() - while loop.time() < deadline: candidate_conn: Optional[Any] = None candidate_host: Optional[HostInfo] = None + attempted: List[HostInfo] = [] try: candidate_host, candidate_conn = await self._open_candidate_connection( - host_info, url_type, substitution_strategy, props, connect_func, driver_dialect) - - if candidate_conn is None: - # _open_candidate_connection always returns a connection on success; if none is - # present the attempt did not yield a usable connection, so retry until the - # timeout is reached. - continue - - if role_to_verify is None: - # No verification required. - 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._plugin_service.routed_host_info = candidate_host - return candidate_conn - - # Verification failed. Retry, unless a reader was requested but the cluster has no readers. - await self._plugin_service.force_refresh_host_list(candidate_conn) - if role_to_verify == HostRole.READER and self._has_hosts() and not self._has_readers(): - # A reader was requested but the cluster has no readers. - # Simulate the reader cluster endpoint logic and return the current (writer) connection. - if self._verify_role_prop_value == RoleVerificationSetting.READER.value: - logger.debug( - "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", - WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._plugin_service.routed_host_info = candidate_host - return candidate_conn - - logger.debug( - "AuroraInitialConnectionStrategyPlugin.IncorrectRole", candidate_host.host, role_to_verify) - await self._close_connection(candidate_conn, driver_dialect) - await self._delay(self._retry_delay_ms) + host_info, url_type, substitution_strategy, props, connect_func, driver_dialect, + attempted) + + if candidate_conn is not None: + if role_to_verify is None: + # No verification required. + self._record_routed_host(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._record_routed_host(host_info, candidate_host) + return candidate_conn + + # Verification failed. Retry, unless a reader was requested but the cluster + # has no readers. + await self._plugin_service.force_refresh_host_list(candidate_conn) + if role_to_verify == HostRole.READER and self._has_hosts() and not self._has_readers(): + # A reader was requested but the cluster has no readers. Simulate the + # reader cluster endpoint logic and return the current (writer) connection. + if self._verify_role_prop_value == RoleVerificationSetting.READER.value: + logger.debug( + "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", + WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) + self._record_routed_host(host_info, candidate_host) + return candidate_conn + + last_error = AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.IncorrectRole", + candidate_host.host, role_to_verify.name.lower(), conn_role.name.lower())) + logger.debug( + "AuroraInitialConnectionStrategyPlugin.IncorrectRole", + candidate_host.host, role_to_verify.name.lower(), conn_role.name.lower()) + await self._close_connection(candidate_conn, driver_dialect) except Exception as e: await self._close_connection(candidate_conn, driver_dialect) if self._plugin_service.is_login_exception(error=e): raise - if candidate_host is not None: + last_error = e + # Marked only for a substituted candidate, and only once the candidate is known. + failed_host = attempted[-1] if attempted else None + if failed_host is not None: self._plugin_service.set_availability( - candidate_host, HostAvailability.UNAVAILABLE) - - if self._plugin_service.is_network_exception(error=e): - # Retry connection. - continue + failed_host, HostAvailability.UNAVAILABLE) - if (self._plugin_service.is_read_only_connection_exception(error=e) + retryable = ( + self._plugin_service.is_network_exception(error=e) + or (self._plugin_service.is_read_only_connection_exception(error=e) and (role_to_verify == HostRole.WRITER - or substitution_strategy is InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER)): - # Retry connection. - continue + or substitution_strategy is InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER))) + if not retryable: + raise - raise + # Checked after the attempt rather than before it, so a zero retry budget means + # "try once" rather than "never connect at all". + if not await self._delay_unless_expired(loop, deadline): + break + timeout_ms = self._open_connection_retry_timeout_ns // 1_000_000 + if last_error is None: + raise AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.Timeout", + timeout_ms, WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name)) raise AwsWrapperError(Messages.get_formatted( - "AuroraInitialConnectionStrategyPlugin.Timeout", - self._open_connection_retry_timeout_ns // 1_000_000, - WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name)) + "AuroraInitialConnectionStrategyPlugin.TimeoutWithCause", + timeout_ms, WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name, str(last_error)), + last_error) from last_error + + def _record_routed_host(self, requested_host: HostInfo, connected_host: HostInfo) -> None: + # Only a substituted host is a routing decision. Recording the requested endpoint would + # overwrite the instance that an inner plugin identified for this connection. + if connected_host is not requested_host: + self._plugin_service.routed_host_info = connected_host + + async def _delay_unless_expired(self, loop: asyncio.AbstractEventLoop, deadline: float) -> bool: + """Sleep the retry interval, reporting whether the retry budget allows another attempt. + + Returns ``False`` once the budget is exhausted. The sleep never overshoots the + deadline, so a budget shorter than the retry interval does not stretch the call. + """ + remaining_sec = deadline - loop.time() + if remaining_sec <= 0: + return False + + await self._delay(min(self._retry_delay_ms, int(remaining_sec * 1000))) + return loop.time() < deadline async def _open_candidate_connection( self, @@ -191,7 +230,8 @@ async def _open_candidate_connection( substitution_strategy: InstanceSubstitutionStrategy, props: Properties, connect_func: Callable[..., Awaitable[Any]], - driver_dialect: AsyncDriverDialect) -> Tuple[HostInfo, Optional[Any]]: + driver_dialect: AsyncDriverDialect, + attempted: Optional[List[HostInfo]] = None) -> Tuple[HostInfo, Optional[Any]]: """Opens a candidate connection, returning the host that was connected to and the connection. If no substitution is needed, the original endpoint is used. Otherwise, an instance host is @@ -199,6 +239,10 @@ async def _open_candidate_connection( opened via the initial endpoint (which also confirms the dialect and acts as a fallback) and, when ``wait_for_initial_topology_ms > 0``, the topology fetch is awaited before re-attempting instance selection. + + Each substituted host is appended to ``attempted`` before it is connected to. The caller + cannot otherwise learn which host failed, because an exception here means its return value + was never unpacked -- which left the caller unable to mark anything unavailable. """ if substitution_strategy is InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE: return original_connect_host, await connect_func() @@ -208,6 +252,8 @@ async def _open_candidate_connection( # Topology is already available; connect to the selected instance. Skipping this plugin # avoids re-entering the pipeline here, while still letting the auth plugins (IAM, # Secrets, Federated, Okta) re-apply on the new connection. + if attempted is not None: + attempted.append(candidate_host) return candidate_host, await self._plugin_service.connect( candidate_host, props, plugin_to_skip=self) @@ -217,13 +263,19 @@ async def _open_candidate_connection( # topology, and it serves as a fallback connection if instance selection or connection fails. candidate_conn = await connect_func() - if self._wait_for_initial_topology_ms <= 0: - # Feature disabled. Preserve the previous behavior. - await self._plugin_service.force_refresh_host_list(candidate_conn) - return original_connect_host, candidate_conn + try: + if self._wait_for_initial_topology_ms <= 0: + # Feature disabled. Preserve the previous behavior. + await self._plugin_service.force_refresh_host_list(candidate_conn) + return original_connect_host, candidate_conn - return await self._wait_for_topology_and_connect_to_instance( - original_connect_host, url_type, substitution_strategy, props, candidate_conn, driver_dialect) + return await self._wait_for_topology_and_connect_to_instance( + original_connect_host, url_type, substitution_strategy, props, candidate_conn, driver_dialect) + except BaseException: + # BaseException, not Exception: a cancelled connect raises asyncio.CancelledError at the awaits above, and + # this connection would otherwise stay open on the server, because no caller has received it yet. + await self._close_connection(candidate_conn, driver_dialect) + raise async def _wait_for_topology_and_connect_to_instance( self, @@ -249,8 +301,11 @@ async def _wait_for_topology_and_connect_to_instance( # Unlike sync, this needs no guard: async providers without monitor support fall back to a # plain refresh and report whether any topology is held, rather than raising. + # + # Deliberately does not ask for the writer to be verified. Doing so closes the shared + # per-cluster monitoring connection and clears its verified-writer state. timeout_sec = self._wait_for_initial_topology_ms / 1000 - topology_fetched = await self._plugin_service.force_monitoring_refresh_host_list(True, timeout_sec) + topology_fetched = await self._plugin_service.force_monitoring_refresh_host_list(False, timeout_sec) if not topology_fetched: logger.debug( @@ -298,7 +353,7 @@ def _get_instance_substitution_strategy( if url_type == RdsUrlType.RDS_WRITER_CLUSTER: writer = self._get_writer() if writer is None or not self._rds_utils.is_rds_instance(writer.host): - return InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE + return _inactive_cluster_writer_strategy(props) if self._rds_utils.is_same_region(writer.host, original_host): return InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER @@ -307,10 +362,7 @@ def _get_instance_substitution_strategy( # This means the cluster is an Aurora Global Database and the cluster writer endpoint is in a # secondary region. In this case the cluster writer endpoint is inactive and doesn't represent # the current writer. A user setting decides whether to substitute it with a writer instance URL. - inactive_strategy = InstanceSubstitutionStrategy.from_property_value( - WrapperProperties.INACTIVE_CLUSTER_WRITER_SUBSTITUTION_ROLE.get(props)) - return inactive_strategy if inactive_strategy is not None \ - else InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER + return _inactive_cluster_writer_strategy(props) if url_type == RdsUrlType.RDS_READER_CLUSTER: return InstanceSubstitutionStrategy.SUBSTITUTE_WITH_READER @@ -327,6 +379,14 @@ def _validate_substitution_strategy( "AuroraInitialConnectionStrategyPlugin.InvalidSettingForInstanceEndpoint", WrapperProperties.ENDPOINT_SUBSTITUTION_ROLE.name)) + if url_type in (RdsUrlType.RDS_PROXY, RdsUrlType.RDS_AURORA_LIMITLESS_DB_SHARD_GROUP): + # Substituting an instance host would route connections around the endpoint the + # user asked to connect through, losing its pooling, authentication handling and + # failover behaviour. + raise AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.InvalidSettingForManagedEndpoint", + WrapperProperties.ENDPOINT_SUBSTITUTION_ROLE.name, setting.value)) + if not url_type.is_rds_cluster: return @@ -384,9 +444,7 @@ def _get_role_to_verify( # Writer is not found (topology cache may not be available yet) or the cluster writer endpoint # belongs to a different region. In either case, assume the cluster writer endpoint may be # inactive and use the corresponding setting. - inactive_strategy = InstanceSubstitutionStrategy.from_property_value( - WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.get(props)) - return inactive_strategy.to_target_role() if inactive_strategy is not None else HostRole.WRITER + return _inactive_cluster_writer_role(props) if url_type == RdsUrlType.RDS_READER_CLUSTER: return HostRole.READER diff --git a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py index 2dd6e4023..0af32d3b5 100644 --- a/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py +++ b/aws_advanced_python_wrapper/aurora_initial_connection_strategy_plugin.py @@ -101,6 +101,57 @@ def from_property_value(cls, value: Optional[str]) -> Optional[RoleVerificationS item.value: item for item in RoleVerificationSetting } +_INACTIVE_SUBSTITUTION_STRATEGY_BY_KEY: Dict[str, InstanceSubstitutionStrategy] = { + InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER.value: InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER, + InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE.value: InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE, +} + +_INACTIVE_VERIFICATION_ROLE_BY_KEY: Dict[str, Optional[HostRole]] = { + "writer": HostRole.WRITER, + "none": None, +} + + +def _parse_restricted( + value: str, allowed: Dict, prop) -> object: + """Look ``value`` up in ``allowed``, raising with the allowed values when absent.""" + key = value.lower() + if key not in allowed: + raise AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.InvalidPropertyValue", + prop.name, value, ", ".join(sorted(allowed)))) + return allowed[key] + + +def _inactive_cluster_writer_strategy(props: Properties) -> InstanceSubstitutionStrategy: + """Return whether an inactive cluster writer endpoint should be substituted.""" + # return_default=False because the declared default is 'writer' + value = WrapperProperties.INACTIVE_CLUSTER_WRITER_SUBSTITUTION_ROLE.get(props, return_default=False) + if value is None: + return InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER + + strategy = _parse_restricted( + value, _INACTIVE_SUBSTITUTION_STRATEGY_BY_KEY, + WrapperProperties.INACTIVE_CLUSTER_WRITER_SUBSTITUTION_ROLE) + assert isinstance(strategy, InstanceSubstitutionStrategy) + return strategy + + +def _inactive_cluster_writer_role(props: Properties) -> Optional[HostRole]: + """Return the role a connection through an inactive cluster writer endpoint must have.""" + # return_default=False because the declared default is 'writer' + value = WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.get(props, return_default=False) + if value is not None: + role = _parse_restricted( + value, _INACTIVE_VERIFICATION_ROLE_BY_KEY, + WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE) + assert role is None or isinstance(role, HostRole) + return role + + if _inactive_cluster_writer_strategy(props) is InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE: + return None + return HostRole.WRITER + class AuroraInitialConnectionStrategyPlugin(Plugin): _SUBSCRIBED_METHODS: Set[str] = {"init_host_provider", "connect"} @@ -149,77 +200,130 @@ def connect( connect_func: Callable) -> Connection: original_host = host_info.host url_type: RdsUrlType = self._rds_utils.identify_rds_type(original_host) - substitution_strategy = self._get_instance_substitution_strategy( - props, url_type, is_initial_connection, original_host) - role_to_verify = self._get_role_to_verify(url_type, is_initial_connection, props, original_host) end_time_ns = perf_counter_ns() + self._open_connection_retry_timeout_ns + # Carries the most recent attempt failure into the timeout error, so the caller is + # told what kept failing rather than only that time ran out. + last_error: Optional[Exception] = None + + while True: + # Both are re-derived every attempt because both read the topology, which the + # previous attempt may have refreshed. Deriving the strategy once pinned a + # connection whose topology was empty for the whole retry window, so it could + # never substitute the writer it had just discovered. The role can change across + # attempts too, and that is deliberate: a cold topology makes a writer cluster + # endpoint look inactive, and once a refresh names a same-region writer the + # endpoint is an active cluster writer endpoint whose role must be verified. + substitution_strategy = self._get_instance_substitution_strategy( + props, url_type, is_initial_connection, original_host) + role_to_verify = self._get_role_to_verify(url_type, is_initial_connection, props, original_host) + + if (substitution_strategy is InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE + and role_to_verify is None): + # Nothing to substitute and no role to verify, so retrying cannot change the + # outcome. Connect once and let the driver's own error surface instead of + # replacing it with a timeout that names a parameter the caller never set. + # Nothing is recorded as routed: this plugin did not reroute the connect. + return connect_func() - while perf_counter_ns() < end_time_ns: candidate_conn: Optional[Connection] = None candidate_host: Optional[HostInfo] = None + attempted: List[HostInfo] = [] try: candidate_host, candidate_conn = self._open_candidate_connection( - host_info, url_type, substitution_strategy, props, connect_func) - - if candidate_conn is None: - # _open_candidate_connection always returns a connection on success; if none is - # present the attempt did not yield a usable connection, so retry until the - # timeout is reached. - continue - - if role_to_verify is None: - # No verification required. - 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._plugin_service.routed_host_info = candidate_host - return candidate_conn - - # Verification failed. Retry, unless a reader was requested but the cluster has no readers. - self._plugin_service.force_refresh_host_list(candidate_conn) - if role_to_verify == HostRole.READER and self._has_hosts() and not self._has_readers(): - # A reader was requested but the cluster has no readers. - # Simulate the reader cluster endpoint logic and return the current (writer) connection. - if self._verify_role_prop_value == RoleVerificationSetting.READER.value: - logger.debug( - "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", - WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) - self._plugin_service.routed_host_info = candidate_host - return candidate_conn - - logger.debug( - "AuroraInitialConnectionStrategyPlugin.IncorrectRole", candidate_host.host, role_to_verify) - self._close_connection(candidate_conn) - self._delay(self._retry_delay_ms) + host_info, url_type, substitution_strategy, props, connect_func, attempted) + + if candidate_conn is not None: + if role_to_verify is None: + # No verification required. + self._record_routed_host(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._record_routed_host(host_info, candidate_host) + return candidate_conn + + # Verification failed. Retry, unless a reader was requested but the cluster + # has no readers. + self._plugin_service.force_refresh_host_list(candidate_conn) + if role_to_verify == HostRole.READER and self._has_hosts() and not self._has_readers(): + # A reader was requested but the cluster has no readers. Simulate the + # reader cluster endpoint logic and return the current (writer) connection. + if self._verify_role_prop_value == RoleVerificationSetting.READER.value: + logger.debug( + "AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist", + WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name) + self._record_routed_host(host_info, candidate_host) + return candidate_conn + + last_error = AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.IncorrectRole", + candidate_host.host, role_to_verify.name.lower(), conn_role.name.lower())) + logger.debug( + "AuroraInitialConnectionStrategyPlugin.IncorrectRole", + candidate_host.host, role_to_verify.name.lower(), conn_role.name.lower()) + self._close_connection(candidate_conn) except Exception as e: self._close_connection(candidate_conn) if self._plugin_service.is_login_exception(e): raise - if candidate_host is not None: + last_error = e + # Marked only for a substituted candidate, and only once the candidate is known. + # Reading it back from the unpacked return value never worked, because an + # exception means there was nothing to unpack -- so a reader that refused a + # connection was never marked, and the next attempt's selector could keep + # choosing it for the whole retry window. Marking the host the user named in + # the connection string is deliberately skipped: that would hand the selectors + # a verdict about a host they were never asked to choose. + failed_host = attempted[-1] if attempted else None + if failed_host is not None: self._plugin_service.set_availability( - candidate_host, HostAvailability.UNAVAILABLE) + failed_host, HostAvailability.UNAVAILABLE) - if self._plugin_service.is_network_exception(e): - # Retry connection. - continue - - if (self._plugin_service.is_read_only_connection_exception(e) + retryable = ( + self._plugin_service.is_network_exception(e) + or (self._plugin_service.is_read_only_connection_exception(e) and (role_to_verify == HostRole.WRITER - or substitution_strategy is InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER)): - # Retry connection. - continue + or substitution_strategy is InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER))) + if not retryable: + raise - raise + # Checked after the attempt rather than before it, so a zero retry budget means + # "try once" rather than "never connect at all". + if not self._delay_unless_expired(end_time_ns): + break + timeout_ms = self._open_connection_retry_timeout_ns // 1_000_000 + if last_error is None: + raise AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.Timeout", + timeout_ms, WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name)) raise AwsWrapperError(Messages.get_formatted( - "AuroraInitialConnectionStrategyPlugin.Timeout", - self._open_connection_retry_timeout_ns // 1_000_000, - WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name)) + "AuroraInitialConnectionStrategyPlugin.TimeoutWithCause", + timeout_ms, WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name, str(last_error)), + last_error) from last_error + + def _record_routed_host(self, requested_host: HostInfo, connected_host: HostInfo) -> None: + # Only a substituted host is a routing decision. Recording the requested endpoint would + # overwrite the instance that an inner plugin identified for this connection. + if connected_host is not requested_host: + self._plugin_service.routed_host_info = connected_host + + def _delay_unless_expired(self, end_time_ns: int) -> bool: + """Sleep the retry interval, reporting whether the retry budget allows another attempt. + + Returns ``False`` once the budget is exhausted. The sleep never overshoots the + deadline, so a budget shorter than the retry interval does not stretch the call. + """ + remaining_ns = end_time_ns - perf_counter_ns() + if remaining_ns <= 0: + return False + + self._delay(min(self._retry_delay_ms, remaining_ns // 1_000_000)) + return perf_counter_ns() < end_time_ns def _open_candidate_connection( self, @@ -227,7 +331,8 @@ def _open_candidate_connection( url_type: RdsUrlType, substitution_strategy: InstanceSubstitutionStrategy, props: Properties, - connect_func: Callable) -> Tuple[HostInfo, Optional[Connection]]: + connect_func: Callable, + attempted: Optional[List[HostInfo]] = None) -> Tuple[HostInfo, Optional[Connection]]: """Opens a candidate connection, returning the host that was connected to and the connection. If no substitution is needed, the original endpoint is used. Otherwise, an instance host is @@ -235,6 +340,10 @@ def _open_candidate_connection( opened via the initial endpoint (which also confirms the dialect and acts as a fallback) and, when ``wait_for_initial_topology_ms > 0``, the topology fetch is awaited before re-attempting instance selection. + + Each substituted host is appended to ``attempted`` before it is connected to. The caller + cannot otherwise learn which host failed, because an exception here means its return value + was never unpacked -- which left the caller unable to mark anything unavailable. """ if substitution_strategy is InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE: return original_connect_host, connect_func() @@ -242,6 +351,8 @@ def _open_candidate_connection( candidate_host = self._get_candidate_host(original_connect_host, url_type, substitution_strategy) if candidate_host is not None and self._rds_utils.is_rds_instance(candidate_host.host): # Topology is already available; connect to the selected instance. + if attempted is not None: + attempted.append(candidate_host) return candidate_host, self._plugin_service.connect(candidate_host, props, self) # Unable to find an instance URL host. Topology may not exist yet, or may be outdated. @@ -250,13 +361,17 @@ def _open_candidate_connection( # topology, and it serves as a fallback connection if instance selection or connection fails. candidate_conn = connect_func() - if self._wait_for_initial_topology_ms <= 0: - # Feature disabled. Preserve the previous behavior. - self._plugin_service.force_refresh_host_list(candidate_conn) - return original_connect_host, candidate_conn + try: + if self._wait_for_initial_topology_ms <= 0: + # Feature disabled. Preserve the previous behavior. + self._plugin_service.force_refresh_host_list(candidate_conn) + return original_connect_host, candidate_conn - return self._wait_for_topology_and_connect_to_instance( - original_connect_host, url_type, substitution_strategy, props, candidate_conn) + return self._wait_for_topology_and_connect_to_instance( + original_connect_host, url_type, substitution_strategy, props, candidate_conn) + except Exception: + self._close_connection(candidate_conn) + raise def _wait_for_topology_and_connect_to_instance( self, @@ -283,8 +398,18 @@ def _wait_for_topology_and_connect_to_instance( # providers without monitor support raise instead of returning their host list. timeout_sec = self._wait_for_initial_topology_ms / 1000 try: - topology_fetched = self._plugin_service.force_monitoring_refresh_host_list(True, timeout_sec) - except Exception: + # Deliberately does not ask for the writer to be verified. Doing so closes the + # shared per-cluster monitoring connection and clears its verified-writer state, + # which is right after a failover but not at connect time, when nothing has failed + # over: under a pool prefill every arriving connection would tear down what the + # previous one had just established. The role of the connection returned here is + # verified directly, on the real connection, by the caller. + topology_fetched = self._plugin_service.force_monitoring_refresh_host_list(False, timeout_sec) + except Exception as e: + # A provider without monitor support raises rather than returning a host list, and + # so does a genuine refresh failure. Both fall back to the endpoint connection, but + # a failure is not a timeout and must not be reported as one. + logger.debug("AuroraInitialConnectionStrategyPlugin.WaitForTopologyError", str(e)) topology_fetched = False if not topology_fetched: @@ -330,7 +455,12 @@ def _get_instance_substitution_strategy( if url_type == RdsUrlType.RDS_WRITER_CLUSTER: writer = self._find_writer(self._plugin_service.all_hosts) if writer is None or not self._rds_utils.is_rds_instance(writer.host): - return InstanceSubstitutionStrategy.DO_NOT_SUBSTITUTE + # With no topology there is no way to tell an active cluster writer endpoint + # from an inactive one, so this defers to the same setting the cross-region + # case below uses. Without that, a request not to substitute an inactive + # endpoint would be overridden on the first connection of every process, and + # then overridden again with a writer in another region once topology arrived. + return _inactive_cluster_writer_strategy(props) if self._rds_utils.is_same_region(writer.host, original_host): return InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER @@ -339,10 +469,7 @@ def _get_instance_substitution_strategy( # This means the cluster is an Aurora Global Database and the cluster writer endpoint is in a # secondary region. In this case the cluster writer endpoint is inactive and doesn't represent # the current writer. A user setting decides whether to substitute it with a writer instance URL. - inactive_strategy = InstanceSubstitutionStrategy.from_property_value( - WrapperProperties.INACTIVE_CLUSTER_WRITER_SUBSTITUTION_ROLE.get(props)) - return inactive_strategy if inactive_strategy is not None \ - else InstanceSubstitutionStrategy.SUBSTITUTE_WITH_WRITER + return _inactive_cluster_writer_strategy(props) if url_type == RdsUrlType.RDS_READER_CLUSTER: return InstanceSubstitutionStrategy.SUBSTITUTE_WITH_READER @@ -359,6 +486,14 @@ def _validate_substitution_strategy( "AuroraInitialConnectionStrategyPlugin.InvalidSettingForInstanceEndpoint", WrapperProperties.ENDPOINT_SUBSTITUTION_ROLE.name)) + if url_type in (RdsUrlType.RDS_PROXY, RdsUrlType.RDS_AURORA_LIMITLESS_DB_SHARD_GROUP): + # Substituting an instance host would route connections around the endpoint the + # user asked to connect through, losing its pooling, authentication handling and + # failover behaviour. + raise AwsWrapperError(Messages.get_formatted( + "AuroraInitialConnectionStrategyPlugin.InvalidSettingForManagedEndpoint", + WrapperProperties.ENDPOINT_SUBSTITUTION_ROLE.name, setting.value)) + if not url_type.is_rds_cluster: return @@ -416,9 +551,7 @@ def _get_role_to_verify( # Writer is not found (topology cache may not be available yet) or the cluster writer endpoint # belongs to a different region. In either case, assume the cluster writer endpoint may be # inactive and use the corresponding setting. - inactive_strategy = InstanceSubstitutionStrategy.from_property_value( - WrapperProperties.VERIFY_INACTIVE_CLUSTER_WRITER_CONNECTION_ROLE.get(props)) - return inactive_strategy.to_target_role() if inactive_strategy is not None else HostRole.WRITER + return _inactive_cluster_writer_role(props) if url_type == RdsUrlType.RDS_READER_CLUSTER: return HostRole.READER 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 3c5726725..07c338bbf 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 @@ -19,7 +19,10 @@ AuroraInitialConnectionStrategyPlugin.InvalidSettingForEndpoint=[AuroraInitialCo AuroraInitialConnectionStrategyPlugin.InvalidSettingForInstanceEndpoint=[AuroraInitialConnectionStrategyPlugin] Parameter '{}' cannot be set when using an instance endpoint. Please see the Aurora Initial Connection Strategy Plugin documentation for valid setting/endpoint combinations. AuroraInitialConnectionStrategyPlugin.InvalidPropertyValue=[AuroraInitialConnectionStrategyPlugin] Received an invalid value for parameter '{}'. Received '{}', valid values are {}. AuroraInitialConnectionStrategyPlugin.Timeout=[AuroraInitialConnectionStrategyPlugin] The Aurora Initial Connection Strategy Plugin attempted to connect but timed out after {}ms. Please ensure that your URL is correct, there are no network issues, and you are connecting to the correct role if '{}' was set. -AuroraInitialConnectionStrategyPlugin.IncorrectRole=[AuroraInitialConnectionStrategyPlugin] The connection opened to '{}' did not have the expected role '{}'. Retrying. +AuroraInitialConnectionStrategyPlugin.TimeoutWithCause=[AuroraInitialConnectionStrategyPlugin] The Aurora Initial Connection Strategy Plugin attempted to connect but timed out after {}ms. Please ensure that your URL is correct, there are no network issues, and you are connecting to the correct role if '{}' was set. The last failure was: {} +AuroraInitialConnectionStrategyPlugin.InvalidSettingForManagedEndpoint=[AuroraInitialConnectionStrategyPlugin] Parameter '{}' cannot be set to '{}' when using a proxy or Limitless shard group endpoint, because substituting an instance host would bypass that endpoint. +AuroraInitialConnectionStrategyPlugin.WaitForTopologyError=[AuroraInitialConnectionStrategyPlugin] An error occurred while waiting for the cluster topology to be fetched: {}. Falling back to connecting via the provided endpoint. +AuroraInitialConnectionStrategyPlugin.IncorrectRole=[AuroraInitialConnectionStrategyPlugin] The connection opened to '{}' should have the role '{}' but has the role '{}'. AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist=[AuroraInitialConnectionStrategyPlugin] Parameter '{}' was set to 'reader' but no readers were detected in the topology. The writer will be used as a fallback. AuroraInitialConnectionStrategyPlugin.WaitingForTopology=[AuroraInitialConnectionStrategyPlugin] Waiting up to {}ms for the cluster topology of '{}' to be fetched before opening a new connection. AuroraInitialConnectionStrategyPlugin.WaitForTopologyTimeout=[AuroraInitialConnectionStrategyPlugin] Timed out after {}ms while waiting for the cluster topology of '{}' to be fetched. Falling back to connecting via the provided endpoint. diff --git a/docs/PYTHON-WRAPPER-CONFIGURATION-ASSISTANT.md b/docs/PYTHON-WRAPPER-CONFIGURATION-ASSISTANT.md index c7d116ade..aa4edb4ae 100644 --- a/docs/PYTHON-WRAPPER-CONFIGURATION-ASSISTANT.md +++ b/docs/PYTHON-WRAPPER-CONFIGURATION-ASSISTANT.md @@ -2420,8 +2420,9 @@ and replaces it with the current writer. - **In the default list:** yes. - **Use with:** Aurora writer and reader cluster endpoints, custom cluster endpoints, and the Global Database writer endpoint. -- With an instance endpoint the only valid setting is `none`, so the - plugin does not substitute or verify. +- With an instance endpoint the only valid `endpoint_substitution_role` + is `none`, so the plugin does not substitute. It verifies the role only + when `verify_opened_connection_type` is set. **Parameters:** @@ -2431,9 +2432,9 @@ and replaces it with the current writer. | `reader_initial_connection_host_selector_strategy` | `random` | Deprecated. Read only when `initial_connection_host_selector_strategy` is not set at all. | | `endpoint_substitution_role` | (derived) | `writer`, `reader` or `none`. When unset: `writer` for writer cluster and global writer endpoints, `reader` for reader cluster endpoints, `none` for everything else. | | `verify_opened_connection_type` | (derived) | `writer`, `reader` or `none`. When unset it follows the same rule as `endpoint_substitution_role`. Invalid values raise `InvalidPropertyValue`. | -| `inactive_cluster_writer_endpoint_substitution_role` | `writer` | Global Database: whether to replace the writer endpoint of a cluster that is not currently primary. `writer` or `none`. | -| `verify_inactive_cluster_writer_endpoint_connection_type` | `writer` | Global Database: whether to verify a connection opened through that endpoint is a writer. `writer` or `none`. | -| `open_connection_retry_timeout_ms` | `30000` | Maximum time in milliseconds for connection retries. | +| `inactive_cluster_writer_endpoint_substitution_role` | `writer` | Global Database: whether to replace the writer endpoint of a cluster that is not currently primary. `writer` or `none`. Also decides any writer cluster endpoint while the topology is not known yet, such as the first connection a process opens. | +| `verify_inactive_cluster_writer_endpoint_connection_type` | `writer`, or `none` when unset and `inactive_cluster_writer_endpoint_substitution_role` is `none` | Global Database: whether to verify a connection opened through that endpoint is a writer. `writer` or `none`. | +| `open_connection_retry_timeout_ms` | `30000` | Maximum time in milliseconds for connection retries. `0` makes one attempt with no retries. | | `open_connection_retry_interval_ms` | `1000` | Wait in milliseconds between retries. | | `wait_for_initial_topology_ms` | `0` | When above 0, wait up to this long for the topology before the first connection, so the strategy can spread concurrent and pool-prefill connections across instances instead of sending all of them to the one host DNS returns. `0` turns the wait off. | | `gdb_accessible_regions` | (all regions) | Skip hosts outside these regions. Sync only in 3.1.0. | @@ -2448,16 +2449,20 @@ an error: | Reader cluster | `reader`, `none` | `reader`, `none` | | Custom cluster | `reader`, `none` | `reader`, `none` | | Instance | `none` only | `writer`, `reader` or `none` (not restricted) | +| RDS Proxy or Limitless shard group | `none` only | `writer`, `reader` or `none` (not restricted) | `endpoint_substitution_role=any` is accepted for a custom cluster endpoint but raises an unsupported-strategy error at connect in 3.1.0. Use `reader` or `none`. -**Behavior to tell the user about:** a network error while connecting -is retried until `open_connection_retry_timeout_ms` runs out, and then -the plugin raises `AwsWrapperError`. So when the database is down, a -connect call can take up to 30 seconds with the defaults before it -fails. A login error is not retried. When a reader is requested but the +**Behavior to tell the user about:** for writer, reader and global +writer cluster endpoints, a network error while connecting is retried +until `open_connection_retry_timeout_ms` runs out, and then the plugin +raises `AwsWrapperError` naming the last failure. So when the database +is down, a connect call can take up to 30 seconds with the defaults +before it fails. When the plugin has nothing to substitute and no role +to verify (instance endpoints, RDS Proxy, custom cluster endpoints by +default), it connects once and raises the driver's error. A login error is not retried. When a reader is requested but the cluster is without readers, the plugin returns the writer connection, as the reader cluster endpoint would. diff --git a/docs/using-the-python-wrapper/using-plugins/UsingTheAuroraInitialConnectionStrategyPlugin.md b/docs/using-the-python-wrapper/using-plugins/UsingTheAuroraInitialConnectionStrategyPlugin.md index ad94447ca..8f02d8245 100644 --- a/docs/using-the-python-wrapper/using-plugins/UsingTheAuroraInitialConnectionStrategyPlugin.md +++ b/docs/using-the-python-wrapper/using-plugins/UsingTheAuroraInitialConnectionStrategyPlugin.md @@ -5,6 +5,7 @@ The following sequence diagram describes the default plugin behaviour if no cust
The AWS Advanced Python Wrapper may retry the connection attempts multiple times until it is able to connect to a valid reader instance or a valid writer instance. You can configure how often to retry a connection and the maximum allowed time to obtain a connection using the `open_connection_retry_interval_ms` and the `open_connection_retry_timeout_ms` parameters respectively. +When the plugin has nothing to substitute and no role to verify, for example with an instance endpoint, an RDS Proxy endpoint or a custom cluster endpoint with the default settings, it connects once and raises the driver's error without retrying. When this plugin is enabled, if the initial connection is to a reader cluster or custom cluster endpoint, the connected host will be chosen based on the configured selection strategy specified using the `initial_connection_host_selector_strategy` parameter. See [initial connection strategy](../ReaderSelectionStrategies.md) for all possible strategies. @@ -30,10 +31,10 @@ The following properties can be used to configure the Aurora Initial Connection | ~~`reader_initial_connection_host_selector_strategy`~~ | String | No | **Deprecated. Use `initial_connection_host_selector_strategy` instead.** During the migration period, the value of `reader_initial_connection_host_selector_strategy` is used only when `initial_connection_host_selector_strategy` is omitted. | `least_connections`| `random` | | `endpoint_substitution_role` | String | No | Defines whether the initial connection URL should be replaced with an instance URL from the topology when available, and if so, the role of the instance URL to select. Set this only when using a URL that resolves to a cluster endpoint (global writer, writer, reader, or custom).

For writer cluster or global writer endpoints, valid values are `writer` and `none`. For reader endpoints, valid values are `reader` and `none`. For custom cluster endpoints, valid values are `reader` and `none`. If set to `none`, the initial URL is not replaced. | `reader` | `writer` for writer/global writer cluster endpoints.

`reader` for reader cluster endpoints.

Otherwise: `none` (no substitution). | | `verify_opened_connection_type` | String | No | Defines whether an opened connection should be verified to be a writer or reader after connecting, or if no role verification should be performed.

For writer or global writer endpoints, valid values are `writer` and `none`. For reader and custom endpoints, valid values are `reader` and `none`. The value `none` performs no role verification. | `reader` | `writer` for writer/global writer cluster endpoints.

`reader` for reader cluster endpoints.

Otherwise: `none`. | -| `inactive_cluster_writer_endpoint_substitution_role` | String | No | Applicable to Aurora Global Databases. Defines whether the inactive cluster writer endpoint in the initial connection URL should be replaced with a writer instance URL from the topology when available. Region-bound cluster writer endpoints may be inactive depending on the Global Database primary region; this parameter configures the desired behavior for them. Valid values are `writer` and `none`. | `none` | `writer` | -| `verify_inactive_cluster_writer_endpoint_connection_type` | String | No | Applicable to Aurora Global Databases. Defines whether a connection opened via an inactive cluster writer endpoint should be verified to be a writer, or if no role verification should be performed. Valid values are `writer` and `none`. | `none` | `writer` | -| `wait_for_initial_topology_ms` | Integer | No | Maximum time, in milliseconds, to wait for the cluster topology to be fetched before opening a new connection. When set greater than `0` and the topology is not yet available, the plugin blocks until the topology is discovered (or this timeout is reached) instead of falling back to connecting via the initial endpoint. This lets host selection strategies such as `round_robin` distribute concurrent and connection-pool prefill connections across instances rather than routing them all to a single DNS-resolved instance. The wait is scoped to the cluster. When set to `0` (the default) the previous behavior is preserved. | `30000` | `0` | -| `open_connection_retry_timeout_ms` | Integer | No | The maximum allowed time for retries when opening a connection in milliseconds. | `40000` | `30000` | +| `inactive_cluster_writer_endpoint_substitution_role` | String | No | Applicable to Aurora Global Databases. Defines whether the inactive cluster writer endpoint in the initial connection URL should be replaced with a writer instance URL from the topology when available. Region-bound cluster writer endpoints may be inactive depending on the Global Database primary region; this parameter configures the desired behavior for them. Valid values are `writer` and `none`.

This parameter also applies to any writer cluster endpoint when the topology is not known yet, such as the first connection a process opens, because the plugin cannot tell an active writer cluster endpoint from an inactive one until it has the topology. | `none` | `writer` | +| `verify_inactive_cluster_writer_endpoint_connection_type` | String | No | Applicable to Aurora Global Databases. Defines whether a connection opened via an inactive cluster writer endpoint should be verified to be a writer, or if no role verification should be performed. Valid values are `writer` and `none`.

When this parameter is not set and `inactive_cluster_writer_endpoint_substitution_role` is `none`, no role is verified: requiring a writer while forbidding the substitution that would produce one cannot be satisfied, so the two are coupled. Set this parameter explicitly to verify a role regardless. | `none` | `writer` | +| `wait_for_initial_topology_ms` | Integer | No | Maximum time, in milliseconds, to wait for the cluster topology to be fetched before opening a new connection. When set greater than `0` and the topology is not yet available, the plugin blocks until the topology is discovered (or this timeout is reached) instead of falling back to connecting via the initial endpoint. This lets host selection strategies such as `round_robin` distribute concurrent and connection-pool prefill connections across instances rather than routing them all to a single DNS-resolved instance. The wait is scoped to the cluster. When set to `0` (the default), the plugin does not wait: it connects through the initial endpoint and refreshes the topology on that connection. | `30000` | `0` | +| `open_connection_retry_timeout_ms` | Integer | No | The maximum allowed time for retries when opening a connection in milliseconds. A value of `0` makes one connection attempt with no retries. | `40000` | `30000` | | `open_connection_retry_interval_ms` | Integer | No | The time between retries when opening a connection in milliseconds. | `2000` | `1000` | ### Valid setting/endpoint combinations @@ -45,9 +46,10 @@ The following properties can be used to configure the Aurora Initial Connection | Writer cluster / global writer | `writer`, `none` | `writer`, `none` | | Reader cluster | `reader`, `none` | `reader`, `none` | | Custom cluster | `reader`, `none` | `reader`, `none` | -| Instance | `none` only | `none` only | +| Instance | `none` only | `writer`, `reader`, `none` (not restricted) | +| Proxy / Limitless shard group | `none` only | `writer`, `reader`, `none` (not restricted) | -Setting a value outside the valid set for the given endpoint raises an error. +Setting a value outside the valid set for the given endpoint raises an error. The verify column is not checked for instance, RDS Proxy and Limitless shard group endpoints. > **Note:** `endpoint_substitution_role=any` is accepted only for a custom cluster endpoint, but host selection for the `any` role is not currently supported — it raises an unsupported-strategy error at connect time. Use `reader` or `none` for custom cluster endpoints. diff --git a/tests/unit/test_aio_aurora_initial_connection.py b/tests/unit/test_aio_aurora_initial_connection.py index 42c41165c..7b63bf545 100644 --- a/tests/unit/test_aio_aurora_initial_connection.py +++ b/tests/unit/test_aio_aurora_initial_connection.py @@ -131,9 +131,64 @@ async def _run(): # No verification path taken. driver_dialect.connect.assert_not_awaited() svc.get_host_role.assert_not_awaited() - # A non-cluster URL needs no role verification, so the loop records the - # original host and returns on the first pass. - assert svc.routed_host_info is host + # A non-cluster URL is neither substituted nor verified, so nothing is + # recorded as routed. + assert svc.routed_host_info is None + + +def test_routed_host_from_an_inner_plugin_is_kept_when_nothing_is_substituted(): + """An inner plugin that identified the instance keeps its record.""" + plugin, svc, driver_dialect = _build() + host = HostInfo(host="some-random.example.com", port=5432) + identified = HostInfo(host="instance-1.xyz.us-east-1.rds.amazonaws.com", port=5432) + expected = MagicMock(name="conn") + + async def _connect_func(): + svc.routed_host_info = identified + return expected + + async def _run(): + return await plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=driver_dialect, + host_info=host, + props=svc.props, + is_initial_connection=True, + connect_func=_connect_func, + ) + + assert asyncio.run(_run()) is expected + assert svc.routed_host_info is identified + + +def test_timeout_chains_the_last_failure(): + """The timeout error keeps the driver exception, so callers can classify it.""" + plugin, svc, driver_dialect = _build( + all_hosts=(_writer_host(),), + role=HostRole.READER, + ) + driver_error = OSError("connection refused") + driver_dialect.connect.side_effect = driver_error + svc.is_network_exception = MagicMock(return_value=True) + + async def _connect_func(): + raise driver_error + + async def _run(): + return await plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=driver_dialect, + host_info=_cluster_host_info(_WRITER_CLUSTER), + props=svc.props, + is_initial_connection=True, + connect_func=_connect_func, + ) + + with pytest.raises(AwsWrapperError, match="connection refused") as exc_info: + asyncio.run(_run()) + + assert exc_info.value.driver_error is driver_error + assert exc_info.value.__cause__ is driver_error # ---- 2. Writer cluster URL + already writer -> direct writer conn ------ @@ -278,9 +333,9 @@ async def _run(): result = asyncio.run(_run()) assert result is cluster_conn - # The no-readers fallback records the candidate host, which on the stale - # path is the original connect host rather than the writer. - assert svc.routed_host_info is host + # On the stale path the no-readers fallback returns the original connect + # host, which is not a routing decision, so nothing is recorded. + assert svc.routed_host_info is None # ---- 6. Timeout exhausted -> raises (parity with sync) ----------------- @@ -386,9 +441,11 @@ async def _run(): def test_availability_marked_when_verification_fails_after_connecting(): - """set_availability is reached only when the failure happens after - _open_candidate_connection returned a host. When the candidate connect - itself throws, candidate_host is still None and the mark is skipped.""" + """set_availability is reached for any failure against a substituted candidate. + + The candidate is recorded before it is connected to, so a failure in the connect + itself is marked too. Relying on the unpacked return value meant an exception from + the connect left the host unknown and the mark was silently skipped.""" reader = _reader_host() plugin, svc, driver_dialect = _build( all_hosts=(_writer_host(), reader), @@ -774,3 +831,144 @@ def test_wait_for_initial_topology_defaults_to_zero(): """get_int returns -1 for an absent property; the plugin normalizes it to 0.""" plugin, _, _ = _build() assert plugin._wait_for_initial_topology_ms == 0 + + +# ---- Regression tests for the ported defect fixes ----------------------- + + +def test_topology_wait_does_not_ask_the_monitor_to_verify_the_writer(): + """Verifying the writer closes the shared per-cluster monitoring connection. + + That is right after a failover but not at connect time, when nothing has failed over: + under a pool prefill every arriving connection would tear down what the previous one + had just established, which is the opposite of what the wait exists to achieve. The + role of the returned connection is verified directly on the connection instead. + """ + # The topology is deliberately empty: with an instance already available the plugin + # connects straight to it and the wait is never reached. + plugin, svc, driver_dialect = _build( + all_hosts=(), + role=HostRole.WRITER, + strategy_pick=None, + props_overrides={"wait_for_initial_topology_ms": "5000"}, + ) + svc.force_monitoring_refresh_host_list = AsyncMock( + return_value=False) + + async def _connect_func(): + return MagicMock(name="endpoint_conn") + + async def _run(): + return await plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=driver_dialect, + host_info=_cluster_host_info(_WRITER_CLUSTER), + props=svc.props, + is_initial_connection=True, + connect_func=_connect_func, + ) + + asyncio.run(_run()) + + svc.force_monitoring_refresh_host_list.assert_awaited_once_with(False, 5.0) + + +def test_zero_retry_budget_still_makes_one_attempt(): + """A zero budget means "do not retry", not "do not connect". + + The budget is checked after an attempt rather than before one. Checking it first meant + any deployment carrying 0 failed every connection without ever calling the driver. + """ + plugin, svc, driver_dialect = _build( + all_hosts=(), + role=HostRole.READER, + props_overrides={ + "open_connection_retry_timeout_ms": "0", + "open_connection_retry_interval_ms": "600000", + }, + ) + + calls = 0 + + async def _connect_func(): + nonlocal calls + calls += 1 + return MagicMock(name="endpoint_conn") + + async def _run(): + return await plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=driver_dialect, + host_info=_cluster_host_info(_WRITER_CLUSTER), + props=svc.props, + is_initial_connection=True, + connect_func=_connect_func, + ) + + with pytest.raises(AwsWrapperError): + asyncio.run(_run()) + + assert calls == 1 + + +def test_inactive_cluster_writer_none_alone_does_not_deadlock_async(): + """Declining to substitute must also stop the role being verified. + + Both parameters default to ``writer``, so leaving them independent made the request + unsatisfiable and burned the whole retry window on every connection. + """ + remote_writer = HostInfo( + host="my-cluster-inst-9.XYZ.eu-west-1.rds.amazonaws.com", port=5432, role=HostRole.WRITER) + plugin, svc, driver_dialect = _build( + all_hosts=(remote_writer,), + role=HostRole.READER, + props_overrides={"inactive_cluster_writer_endpoint_substitution_role": "none"}, + ) + + expected = MagicMock(name="endpoint_conn") + calls = 0 + + async def _connect_func(): + nonlocal calls + calls += 1 + return expected + + async def _run(): + return await plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=driver_dialect, + host_info=_cluster_host_info(_WRITER_CLUSTER), + props=svc.props, + is_initial_connection=True, + connect_func=_connect_func, + ) + + result = asyncio.run(_run()) + + assert result is expected + assert calls == 1, "the connection must not be retried to the timeout" + svc.get_host_role.assert_not_awaited() + + +def test_cancelled_topology_refresh_closes_the_endpoint_connection(): + """A connect cancelled while the endpoint connection is open closes that connection before the cancel propagates.""" + plugin, svc, driver_dialect = _build() + svc.force_refresh_host_list = AsyncMock(side_effect=asyncio.CancelledError()) + endpoint_conn = MagicMock(name="endpoint_conn") + + async def _connect_func(): + return endpoint_conn + + async def _run(): + return await plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=driver_dialect, + host_info=_cluster_host_info(_READER_CLUSTER), + props=svc.props, + is_initial_connection=True, + connect_func=_connect_func, + ) + + with pytest.raises(asyncio.CancelledError): + asyncio.run(_run()) + driver_dialect.abort_connection.assert_awaited_once_with(endpoint_conn) diff --git a/tests/unit/test_aurora_initial_connection_strategy_plugin.py b/tests/unit/test_aurora_initial_connection_strategy_plugin.py index 08bf92e3a..0cc0962dd 100644 --- a/tests/unit/test_aurora_initial_connection_strategy_plugin.py +++ b/tests/unit/test_aurora_initial_connection_strategy_plugin.py @@ -45,7 +45,9 @@ def _plugin(props, all_hosts=()): def test_retry_deadline_uses_timeout_property(): props = Properties({}) - # Zero total budget: the retry loop must not run even once despite the long interval. + # A zero total budget means "do not retry", not "do not connect". The budget is checked + # after an attempt rather than before one, so exactly one attempt is made however long + # the retry interval is -- and the interval is never slept, because there is no retry. WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.set(props, "0") WrapperProperties.OPEN_CONNECTION_RETRY_INTERVAL_MS.set(props, "600000") @@ -56,7 +58,7 @@ def test_retry_deadline_uses_timeout_property(): plugin.connect( MagicMock(), MagicMock(), HostInfo(WRITER_CLUSTER), props, True, connect_func) - connect_func.assert_not_called() + assert connect_func.call_count == 1 def test_wait_for_initial_topology_disabled_by_default(): @@ -112,7 +114,10 @@ def populate_topology(*_args, **_kwargs): assert conn is instance_conn assert host.host == WRITER_INSTANCE # The timeout must reach the monitor in seconds. - plugin_service.force_monitoring_refresh_host_list.assert_called_once_with(True, 5.0) + # Deliberately False: asking the monitor to verify the writer closes the shared + # per-cluster monitoring connection, which under a pool prefill means every arriving + # connection tears down what the previous one established. + plugin_service.force_monitoring_refresh_host_list.assert_called_once_with(False, 5.0) fallback_conn.close.assert_called_once() @@ -327,3 +332,39 @@ def test_candidate_host_substitute_with_reader_uses_reader_role(): assert result is reader assert plugin_service.get_host_info_by_strategy.call_args.args[0] == HostRole.READER + + +def test_timeout_chains_the_last_failure(): + """The timeout error keeps the driver exception, so callers can classify it.""" + props = Properties({}) + WrapperProperties.OPEN_CONNECTION_RETRY_TIMEOUT_MS.set(props, "0") + plugin, plugin_service = _plugin(props) + plugin_service.is_network_exception.return_value = True + driver_error = OSError("connection refused") + connect_func = MagicMock(side_effect=driver_error) + + with pytest.raises(AwsWrapperError, match="connection refused") as exc_info: + plugin.connect( + MagicMock(), MagicMock(), HostInfo(WRITER_CLUSTER), props, True, connect_func) + + assert exc_info.value.driver_error is driver_error + assert exc_info.value.__cause__ is driver_error + + +def test_routed_host_from_an_inner_plugin_is_kept_when_nothing_is_substituted(): + """An inner plugin that identified the instance keeps its record.""" + props = Properties({}) + plugin, plugin_service = _plugin(props) + plugin_service.routed_host_info = None + identified = HostInfo(WRITER_INSTANCE) + conn = MagicMock(name="conn") + + def connect_func(): + plugin_service.routed_host_info = identified + return conn + + result = plugin.connect( + MagicMock(), MagicMock(), HostInfo("db.example.com"), props, True, connect_func) + + assert result is conn + assert plugin_service.routed_host_info is identified