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
