diff --git a/CHANGELOG.md b/CHANGELOG.md index 03eec8a12..ae5e20c68 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,6 +6,7 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), ## [Unreleased] ### :magic_wand: Added +* The `connection_lifetime` plugin, bounding how long a physical connection is used. Once `connection_lifetime_ms` has elapsed, the next network-bound call either closes the connection or reconnects through the host the application originally supplied, depending on `connection_lifetime_action`. Expiration is deferred while a transaction is open, and reports through `ConnectionLifetimeSuccessError`, `ConnectionLifetimeExpiredError` or `ConnectionLifetimeFailedError` so a connection pool can tell a usable connection from a dead one. With an internal connection pool, the plugin evicts an expired connection so the pool closes it instead of handing it out again. Available in both the synchronous and asynchronous wrapper. See [Connection Lifetime Plugin](./docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md). * The `failover` and `failover_v2` plugins currently rewraps all errors to an AwsWrapperError even when the errors do not trigger failover. Set the `preserve_driver_exception_type` configuration parameter to `True` to re-raise the target driver errors as-is for the failover plugins. Failover errors are unaffected and are still raised as `FailoverSuccessError`, `FailoverFailedError` or `TransactionResolutionUnknownError`. This is useful for ORMs to properly classify the errors. ([Issue #1275](https://github.com/aws/aws-advanced-python-wrapper/issues/1275)) ## [3.1.0] - 2026-08-24 diff --git a/README.md b/README.md index 2587072eb..0307a9043 100644 --- a/README.md +++ b/README.md @@ -107,6 +107,8 @@ The following table lists the connection properties used with the AWS Advanced P | `failover_reader_connect_timeout_sec` | [Failover Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md) | | `failover_timeout_sec` | [Failover Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md) | | `failover_writer_reconnect_interval_sec` | [Failover Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheFailoverPlugin.md) | +| `connection_lifetime_ms` | [Connection Lifetime Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md) | +| `connection_lifetime_action` | [Connection Lifetime Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md) | | `failure_detection_count` | [Host Monitoring Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheHostMonitoringPlugin.md) | | `failure_detection_enabled` | [Host Monitoring Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheHostMonitoringPlugin.md) | | `failure_detection_interval_ms` | [Host Monitoring Plugin](docs/using-the-python-wrapper/using-plugins/UsingTheHostMonitoringPlugin.md) | diff --git a/aws_advanced_python_wrapper/aio/connection_lifetime_plugin.py b/aws_advanced_python_wrapper/aio/connection_lifetime_plugin.py new file mode 100644 index 000000000..85bfed282 --- /dev/null +++ b/aws_advanced_python_wrapper/aio/connection_lifetime_plugin.py @@ -0,0 +1,295 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Async counterpart of :class:`ConnectionLifetimePlugin`. + +Same contract as the sync plugin -- stamp each physical connection, and on +the first network-bound call after ``connection_lifetime_ms`` has elapsed +either close the connection or replace it with one on the host the +application originally asked for. Property parsing and the action enum are +shared with the sync module so the two cannot disagree on what a +configuration value means. +""" + +from __future__ import annotations + +from time import monotonic_ns +from typing import TYPE_CHECKING, Any, Callable, Optional, Set + +from aws_advanced_python_wrapper.aio.plugin import AsyncPlugin +from aws_advanced_python_wrapper.connection_lifetime_plugin import ( + LIFECYCLE_METHODS, ConnectionCreationTimes, ConnectionLifetimeAction, + parse_connection_lifetime_action, parse_connection_lifetime_ns) +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + ConnectionLifetimeExpiredError, + ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.notifications import ( + ConnectionEvent, OldConnectionSuggestedAction) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.aio.driver_dialect.base import \ + AsyncDriverDialect + from aws_advanced_python_wrapper.aio.plugin_service import \ + AsyncPluginService + from aws_advanced_python_wrapper.hostinfo import HostInfo + from aws_advanced_python_wrapper.utils.properties import Properties + +logger = Logger(__name__) + + +class AsyncConnectionLifetimePlugin(AsyncPlugin): + def __init__( + self, + plugin_service: AsyncPluginService, + props: Properties, + clock_ns: Callable[[], int] = monotonic_ns): + self._plugin_service = plugin_service + self._props = props + # Injected only by the tests, which need to move time without sleeping. + self._clock_ns = clock_ns + self._connection_lifetime_ns = parse_connection_lifetime_ns(props) + self._action = parse_connection_lifetime_action(props) + + subscribed = set(plugin_service.network_bound_methods) + subscribed.update({ + DbApiMethod.CONNECT.method_name, + DbApiMethod.FORCE_CONNECT.method_name, + DbApiMethod.NOTIFY_CONNECTION_CHANGED.method_name, + }) + self._subscribed_methods = subscribed + + self._connection_creation_times = ConnectionCreationTimes() + self._original_host_info: Optional[HostInfo] = None + self._timed_connection: Optional[Any] = None + self._connection_creation_time_ns: Optional[int] = None + self._terminal = False + + @property + def subscribed_methods(self) -> Set[str]: + return self._subscribed_methods + + async def connect( + self, + target_driver_func: Callable, + driver_dialect: AsyncDriverDialect, + host_info: HostInfo, + props: Properties, + is_initial_connection: bool, + connect_func: Callable) -> Any: + return await self._connect(host_info, is_initial_connection, connect_func) + + async def force_connect( + self, + target_driver_func: Callable, + driver_dialect: AsyncDriverDialect, + host_info: HostInfo, + props: Properties, + is_initial_connection: bool, + force_connect_func: Callable) -> Any: + return await self._connect(host_info, is_initial_connection, force_connect_func) + + async def _connect( + self, + host_info: HostInfo, + is_initial_connection: bool, + connect_func: Callable) -> Any: + # Sync parity (connection_lifetime_plugin.py): the reconnect host is + # the application's own, captured from the first initial connect + # because the plugin service does not yet carry it during + # init_host_provider. + if is_initial_connection and self._original_host_info is None: + self._original_host_info = host_info + + connection = await connect_func() + self._connection_creation_times.record(connection, self._clock_ns()) + return connection + + def notify_connection_changed( + self, changes: Set[ConnectionEvent]) -> Optional[OldConnectionSuggestedAction]: + if (ConnectionEvent.INITIAL_CONNECTION in changes + or ConnectionEvent.CONNECTION_OBJECT_CHANGED in changes): + self._select_current_connection_timestamp() + return OldConnectionSuggestedAction.NO_OPINION + + async def execute( + self, + target: object, + method_name: str, + execute_func: Callable, + *args: Any, + **kwargs: Any) -> Any: + if (method_name in LIFECYCLE_METHODS + or not self._plugin_service.is_network_bound_method(method_name)): + return await execute_func() + + if self._terminal: + raise ConnectionLifetimeExpiredError( + Messages.get("ConnectionLifetimePlugin.ConnectionClosed")) + + if not self._is_current_connection_expired(): + return await execute_func() + + # An open transaction finishes on the connection it started on, so + # commit and rollback are not cut off mid-way. Deferring does not + # extend the lifetime. + if self._plugin_service.is_in_transaction: + logger.debug("ConnectionLifetimePlugin.ActionDeferred", method_name) + return await execute_func() + + if self._action == ConnectionLifetimeAction.CLOSE: + await self._close_current_connection() + else: + await self._reconnect() + + def _select_current_connection_timestamp(self) -> None: + current_connection = self._plugin_service.current_connection + creation_time = None + if current_connection is not None: + creation_time = self._connection_creation_times.get(current_connection) + if creation_time is None: + creation_time = self._clock_ns() + self._connection_creation_times.record(current_connection, creation_time) + + self._timed_connection = current_connection + self._connection_creation_time_ns = creation_time + + def _is_current_connection_expired(self) -> bool: + current_connection = self._plugin_service.current_connection + if current_connection is not self._timed_connection or self._connection_creation_time_ns is None: + self._select_current_connection_timestamp() + + creation_time = self._connection_creation_time_ns + # Inclusive boundary: a 1000 ms lifetime expires at exactly 1000 ms. + return (creation_time is not None + and self._clock_ns() - creation_time >= self._connection_lifetime_ns) + + async def _close_current_connection(self) -> None: + self._terminal = True + current_connection = self._plugin_service.current_connection + close_failure: Optional[Exception] = None + + if current_connection is not None: + self._connection_creation_times.forget(current_connection) + # Closing a pooled connection returns it to its pool, so evict it first. + self._evict(current_connection) + try: + await self._close(current_connection) + except Exception as e: + close_failure = e + logger.warning("ConnectionLifetimePlugin.CloseConnectionFailed", e) + + error = ConnectionLifetimeExpiredError( + Messages.get("ConnectionLifetimePlugin.ConnectionClosed")) + if close_failure is not None: + raise error from close_failure + raise error + + async def _reconnect(self) -> None: + previous_connection = self._plugin_service.current_connection + replacement_connection = None + try: + reconnect_host_info = self._original_host_info + if reconnect_host_info is None: + reconnect_host_info = self._plugin_service.initial_connection_host_info + if reconnect_host_info is None: + raise AwsWrapperError( + Messages.get("ConnectionLifetimePlugin.OriginalHostUnavailable")) + + logger.debug("ConnectionLifetimePlugin.Reconnecting", reconnect_host_info.url) + replacement_connection = await self._plugin_service.connect( + reconnect_host_info, self._props, self) + if replacement_connection is None: + raise AwsWrapperError( + Messages.get("ConnectionLifetimePlugin.ReconnectReturnedNone")) + replacement_creation_time = self._clock_ns() + + # Evict before the plugin service closes the expired connection, which + # would return a pooled one to its pool. If another plugin preserves it, + # it stays usable and leaves the pool once it is closed. + if previous_connection is not None and previous_connection is not replacement_connection: + self._evict(previous_connection) + await self._plugin_service.set_current_connection( + replacement_connection, reconnect_host_info) + await self._forget_closed_connection(previous_connection) + self._connection_creation_times.record(replacement_connection, replacement_creation_time) + self._timed_connection = replacement_connection + self._connection_creation_time_ns = replacement_creation_time + except Exception as e: + await self._cleanup_failed_replacement(replacement_connection, previous_connection) + raise ConnectionLifetimeFailedError( + Messages.get("ConnectionLifetimePlugin.UnableToReconnect")) from e + + raise ConnectionLifetimeSuccessError( + Messages.get("ConnectionLifetimePlugin.ConnectionChanged")) + + async def _forget_closed_connection(self, connection: Optional[Any]) -> None: + if connection is None: + return + + try: + closed = await self._plugin_service.driver_dialect.is_closed(connection) + except Exception: + # A connection that cannot report its state is unusable; do not retain it. + closed = True + + if closed: + self._connection_creation_times.forget(connection) + + def _evict(self, connection: Any) -> None: + self._plugin_service.get_connection_provider_manager().evict_connection(connection) + + async def _cleanup_failed_replacement( + self, + replacement_connection: Optional[Any], + previous_connection: Optional[Any]) -> None: + if (replacement_connection is not None + and replacement_connection is self._plugin_service.current_connection + and replacement_connection is not previous_connection): + # The replacement was installed and the failure came after, so + # neither connection can be relied on from here. The previous + # connection was evicted before the replacement was installed. + self._terminal = True + await self._close_after_failed_installation(replacement_connection) + await self._close_after_failed_installation(previous_connection) + return + + await self._close_unattached_replacement(replacement_connection) + + async def _close_after_failed_installation(self, connection: Optional[Any]) -> None: + if connection is None: + return + + self._connection_creation_times.forget(connection) + try: + await self._close(connection) + except Exception as e: + logger.warning("ConnectionLifetimePlugin.FailedInstallationConnectionCloseFailed", e) + + async def _close_unattached_replacement(self, replacement_connection: Optional[Any]) -> None: + if (replacement_connection is None + or replacement_connection is self._plugin_service.current_connection): + return + + self._connection_creation_times.forget(replacement_connection) + try: + await self._close(replacement_connection) + except Exception as e: + logger.warning("ConnectionLifetimePlugin.ReplacementCloseFailed", e) + + async def _close(self, connection: Any) -> None: + await self._plugin_service.driver_dialect.close_connection(connection) diff --git a/aws_advanced_python_wrapper/aio/connection_provider.py b/aws_advanced_python_wrapper/aio/connection_provider.py index e465de871..f1e9c64b9 100644 --- a/aws_advanced_python_wrapper/aio/connection_provider.py +++ b/aws_advanced_python_wrapper/aio/connection_provider.py @@ -33,6 +33,7 @@ from typing import (TYPE_CHECKING, Any, Awaitable, Callable, ClassVar, Dict, Mapping, Optional, Protocol, Tuple) +from aws_advanced_python_wrapper.connection_provider import CanEvictConnection from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_selector import ( HighestWeightHostSelector, HostSelector, RandomHostSelector, @@ -228,6 +229,22 @@ def get_host_info_by_strategy( return self._default_provider.get_host_info_by_strategy( hosts, role, strategy, props) + def evict_connection(self, connection: Any) -> bool: + """Evict a connection from the pool of the provider that issued it. + + See :meth:`CanEvictConnection.evict_connection`. Returns True if one + of the available providers evicted the connection. + """ + with AsyncConnectionProviderManager._lock: + custom = AsyncConnectionProviderManager._conn_provider + + if isinstance(custom, CanEvictConnection) and custom.evict_connection(connection): + return True + + return (self._default_provider is not custom + and isinstance(self._default_provider, CanEvictConnection) + and self._default_provider.evict_connection(connection)) + @staticmethod def reset_provider() -> None: """Clear the non-default provider if one was installed.""" diff --git a/aws_advanced_python_wrapper/aio/driver_dialect/aiomysql.py b/aws_advanced_python_wrapper/aio/driver_dialect/aiomysql.py index deff2033f..194dba8e7 100644 --- a/aws_advanced_python_wrapper/aio/driver_dialect/aiomysql.py +++ b/aws_advanced_python_wrapper/aio/driver_dialect/aiomysql.py @@ -32,6 +32,7 @@ from __future__ import annotations import asyncio +import inspect from typing import TYPE_CHECKING, Any, Awaitable, Callable from aws_advanced_python_wrapper.aio.driver_dialect.base import \ @@ -202,6 +203,23 @@ async def abort_connection(self, conn: Any) -> None: # loss. conn.close() + async def close_connection(self, conn: Any) -> None: + # aiomysql's close() is synchronous and drops the socket without + # telling the server, while its ensure_closed() coroutine sends + # COM_QUIT first. Checking the class rather than the instance keeps a + # mock or a pool proxy, neither of which defines ensure_closed on its + # class, on the close() path. + if not inspect.iscoroutinefunction(getattr(type(conn), "ensure_closed", None)): + await super().close_connection(conn) + return + try: + await conn.ensure_closed() + except Exception: + # ensure_closed() only closes the socket once COM_QUIT has been + # sent, so close it here or the transport stays open. + conn.close() + raise + async def is_in_transaction(self, conn: Any) -> bool: # aiomysql tracks the REAL transaction state via MySQL's # SERVER_STATUS_IN_TRANS flag (refreshed from every statement's OK diff --git a/aws_advanced_python_wrapper/aio/driver_dialect/base.py b/aws_advanced_python_wrapper/aio/driver_dialect/base.py index 01b489076..a695871f4 100644 --- a/aws_advanced_python_wrapper/aio/driver_dialect/base.py +++ b/aws_advanced_python_wrapper/aio/driver_dialect/base.py @@ -27,6 +27,7 @@ from __future__ import annotations +import asyncio from abc import ABC, abstractmethod from typing import TYPE_CHECKING, Any, Awaitable, Callable, Set @@ -147,6 +148,18 @@ async def is_closed(self, conn: Any) -> bool: async def abort_connection(self, conn: Any) -> None: raise NotImplementedError + async def close_connection(self, conn: Any) -> None: + """Close ``conn`` gracefully, telling the server first when the driver supports it. + + Unlike :meth:`abort_connection`, which interrupts an in-flight call, + this is the normal teardown of an idle connection. The default calls + ``close()`` and awaits it when the driver returns a coroutine, as + psycopg's ``AsyncConnection.close()`` does. + """ + result = conn.close() + if asyncio.iscoroutine(result): + await result + @abstractmethod async def is_in_transaction(self, conn: Any) -> bool: raise NotImplementedError diff --git a/aws_advanced_python_wrapper/aio/plugin_factory.py b/aws_advanced_python_wrapper/aio/plugin_factory.py index 41c16df97..ddcc448ad 100644 --- a/aws_advanced_python_wrapper/aio/plugin_factory.py +++ b/aws_advanced_python_wrapper/aio/plugin_factory.py @@ -178,6 +178,14 @@ def get_instance( return AsyncAuroraConnectionTrackerPlugin(plugin_service) +class _ConnectionLifetimeFactory: + def get_instance( + self, plugin_service, props, host_list_provider=None): + from aws_advanced_python_wrapper.aio.connection_lifetime_plugin import \ + AsyncConnectionLifetimePlugin + return AsyncConnectionLifetimePlugin(plugin_service, props) + + class _ConnectTimeFactory: def get_instance( self, plugin_service, props, host_list_provider=None): @@ -275,6 +283,7 @@ def get_instance( "federated_auth": _FederatedAuthFactory(), "okta": _OktaAuthFactory(), "aurora_connection_tracker": _AuroraConnectionTrackerFactory(), + "connection_lifetime": _ConnectionLifetimeFactory(), "connect_time": _ConnectTimeFactory(), "execute_time": _ExecuteTimeFactory(), "dev": _DeveloperFactory(), @@ -297,6 +306,7 @@ def get_instance( # (the v1/v2 sync codes collapse onto one async factory, which takes the # v1 slot: failover 400, host_monitoring 500). PLUGIN_FACTORY_WEIGHTS: Dict[Type[Any], int] = { + _ConnectionLifetimeFactory: 30, _CustomEndpointFactory: 40, _InitialConnectionFactory: 50, _AuroraConnectionTrackerFactory: 100, diff --git a/aws_advanced_python_wrapper/aio/pooled_connection_provider.py b/aws_advanced_python_wrapper/aio/pooled_connection_provider.py index e49d75992..a2bb2fd69 100644 --- a/aws_advanced_python_wrapper/aio/pooled_connection_provider.py +++ b/aws_advanced_python_wrapper/aio/pooled_connection_provider.py @@ -32,6 +32,7 @@ from aws_advanced_python_wrapper.aio.plugin import AsyncCanReleaseResources from aws_advanced_python_wrapper.aio.storage.sliding_expiration_cache_async import \ AsyncSlidingExpirationCache +from aws_advanced_python_wrapper.connection_provider import CanEvictConnection from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_selector import ( HighestWeightHostSelector, HostSelector, RandomHostSelector, @@ -234,7 +235,7 @@ def __getattr__(self, name: str) -> Any: return getattr(self._raw, name) -class AsyncPooledConnectionProvider(AsyncCanReleaseResources): +class AsyncPooledConnectionProvider(AsyncCanReleaseResources, CanEvictConnection): """Async counterpart of :class:`SqlAlchemyPooledConnectionProvider`. Per-host pooling keyed by ``PoolKey(host.url, extra_key)``. Pools @@ -369,6 +370,19 @@ async def _create(_key: PoolKey) -> Tuple[_AsyncPool, Properties]: raw_conn = await pool.acquire() return _PooledAsyncConnectionProxy(raw_conn, pool) + def evict_connection(self, connection: Any) -> bool: + """Close ``connection``'s raw connection on close instead of pooling it. + + Call it before closing the connection: a released proxy has already + returned its raw connection to the pool. + """ + if not isinstance(connection, _PooledAsyncConnectionProxy) or connection._released: + return False + + connection.invalidate() + logger.debug("AsyncPooledConnectionProvider.ConnectionEvicted") + return True + def _get_extra_key(self, host_info: HostInfo, props: Properties) -> str: if self._pool_mapping is not None: return self._pool_mapping(host_info, props) diff --git a/aws_advanced_python_wrapper/connection_lifetime_plugin.py b/aws_advanced_python_wrapper/connection_lifetime_plugin.py new file mode 100644 index 000000000..06ecf990d --- /dev/null +++ b/aws_advanced_python_wrapper/connection_lifetime_plugin.py @@ -0,0 +1,392 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +"""Bounds how long the wrapper keeps a physical connection. + +The plugin stamps every physical connection it sees created, and before each +network-bound call checks whether the current one has outlived +``connection_lifetime_ms``. An expired connection is either closed or replaced +by a fresh one on the host the application originally asked for. There is no +background timer: an expired connection stays open until the next +network-bound call. +""" + +from __future__ import annotations + +from enum import Enum +from time import monotonic_ns +from typing import TYPE_CHECKING, Any, Callable, Optional, Set +from weakref import WeakKeyDictionary + +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + ConnectionLifetimeExpiredError, + ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory +from aws_advanced_python_wrapper.utils.log import Logger +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.notifications import ( + ConnectionEvent, OldConnectionSuggestedAction) +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) + +if TYPE_CHECKING: + from aws_advanced_python_wrapper.driver_dialect import DriverDialect + from aws_advanced_python_wrapper.hostinfo import HostInfo + from aws_advanced_python_wrapper.pep249 import Connection + from aws_advanced_python_wrapper.plugin_service import PluginService + +logger = Logger(__name__) + +# Teardown calls never trigger the lifetime action, even though the driver +# dialects count them as network-bound. Closing an expired connection has to +# keep working -- raising here would mean a connection could not be disposed +# of, and would surface out of a ``with`` block's exit in place of whatever +# the body raised. +LIFECYCLE_METHODS = frozenset({ + DbApiMethod.CONNECTION_CLOSE.method_name, + DbApiMethod.CONNECTION_IS_CLOSED.method_name, + DbApiMethod.CURSOR_CLOSE.method_name, +}) + + +class ConnectionLifetimeAction(Enum): + CLOSE = "close" + RECONNECT = "reconnect" + + +def parse_connection_lifetime_ns(props: Properties) -> int: + """Read ``connection_lifetime_ms`` as nanoseconds, or raise. + + The property is required and has no default, so an absent, non-numeric or + non-positive value is a configuration error worth failing the connect on + rather than silently disabling the plugin. + """ + raw = WrapperProperties.CONNECTION_LIFETIME_MS.get(props) + try: + lifetime_ms = int(raw) # type: ignore[arg-type] + except (TypeError, ValueError): + raise AwsWrapperError( + Messages.get_formatted("ConnectionLifetimePlugin.InvalidConnectionLifetime", raw)) + + if lifetime_ms < 1: + raise AwsWrapperError( + Messages.get_formatted("ConnectionLifetimePlugin.InvalidConnectionLifetime", raw)) + + return lifetime_ms * 1_000_000 + + +def parse_connection_lifetime_action(props: Properties) -> ConnectionLifetimeAction: + """Read ``connection_lifetime_action``, ignoring surrounding space and case.""" + configured = WrapperProperties.CONNECTION_LIFETIME_ACTION.get(props) + try: + return ConnectionLifetimeAction(str(configured).strip().lower()) + except ValueError: + raise AwsWrapperError( + Messages.get_formatted( + "ConnectionLifetimePlugin.InvalidConnectionLifetimeAction", configured)) + + +class ConnectionCreationTimes: + """Creation times of the physical connections the plugin has seen. + + Weak keys keep a connection the pipeline opened and then discarded from + being held alive here. A connection that cannot be weak-referenced is + never stored: every lookup misses, so the plugin times it from first use. + """ + + def __init__(self) -> None: + self._times: WeakKeyDictionary = WeakKeyDictionary() + + def record(self, connection: Optional[Any], time_ns: int) -> None: + if connection is None: + return + try: + self._times[connection] = time_ns + except TypeError: + pass + + def get(self, connection: Optional[Any]) -> Optional[int]: + if connection is None: + return None + try: + return self._times.get(connection) + except TypeError: + return None + + def forget(self, connection: Optional[Any]) -> None: + if connection is None: + return + try: + self._times.pop(connection, None) + except TypeError: + pass + + +class ConnectionLifetimePlugin(Plugin): + def __init__( + self, + plugin_service: PluginService, + props: Properties, + clock_ns: Callable[[], int] = monotonic_ns): + self._plugin_service = plugin_service + self._props = props + # Injected only by the tests, which need to move time without sleeping. + self._clock_ns = clock_ns + self._connection_lifetime_ns = parse_connection_lifetime_ns(props) + self._action = parse_connection_lifetime_action(props) + + subscribed = set(plugin_service.network_bound_methods) + subscribed.update({ + DbApiMethod.CONNECT.method_name, + DbApiMethod.FORCE_CONNECT.method_name, + DbApiMethod.NOTIFY_CONNECTION_CHANGED.method_name, + }) + self._subscribed_methods = subscribed + + self._connection_creation_times = ConnectionCreationTimes() + self._original_host_info: Optional[HostInfo] = None + self._timed_connection: Optional[Connection] = None + self._connection_creation_time_ns: Optional[int] = None + self._terminal = False + + @property + def subscribed_methods(self) -> Set[str]: + return self._subscribed_methods + + def connect( + self, + target_driver_func: Callable, + driver_dialect: DriverDialect, + host_info: HostInfo, + props: Properties, + is_initial_connection: bool, + connect_func: Callable) -> Connection: + return self._connect(host_info, is_initial_connection, connect_func) + + def force_connect( + self, + target_driver_func: Callable, + driver_dialect: DriverDialect, + host_info: HostInfo, + props: Properties, + is_initial_connection: bool, + force_connect_func: Callable) -> Connection: + return self._connect(host_info, is_initial_connection, force_connect_func) + + def _connect( + self, + host_info: HostInfo, + is_initial_connection: bool, + connect_func: Callable) -> Connection: + # The host to reconnect through is the one the application asked for, + # not one a later routing, read/write-splitting or failover decision + # landed on. It cannot be read from the plugin service in + # init_host_provider: AwsWrapperConnection.__init__ only fills that + # field in the refresh_host_list() that runs after the + # init_host_provider pipeline, so it is still None inside the hook. + # The first initial connect carries the same host, and this plugin is + # the outermost one in the chain, so it sees that host before any + # nested connect a routing plugin makes. + # + # Note this names the host the reconnect *asks* for. Plugins beneath + # this one may route the replacement elsewhere -- initial_connection + # substitutes a writer instance for a cluster endpoint on a + # non-initial connect. + if is_initial_connection and self._original_host_info is None: + self._original_host_info = host_info + + connection = connect_func() + self._connection_creation_times.record(connection, self._clock_ns()) + return connection + + def notify_connection_changed(self, changes: Set[ConnectionEvent]) -> OldConnectionSuggestedAction: + if (ConnectionEvent.INITIAL_CONNECTION in changes + or ConnectionEvent.CONNECTION_OBJECT_CHANGED in changes): + self._select_current_connection_timestamp() + return OldConnectionSuggestedAction.NO_OPINION + + def execute(self, target: type, method_name: str, execute_func: Callable, *args: Any, **kwargs: Any) -> Any: + if (method_name in LIFECYCLE_METHODS + or not self._plugin_service.is_network_bound_method(method_name)): + return execute_func() + + if self._terminal: + raise ConnectionLifetimeExpiredError( + Messages.get("ConnectionLifetimePlugin.ConnectionClosed")) + + if not self._is_current_connection_expired(): + return execute_func() + + # Let an open transaction finish on the connection it started on, so + # commit and rollback are not cut off mid-way. Deferring does not + # extend the lifetime: the action runs on the first eligible call once + # the transaction ends. + if self._plugin_service.is_in_transaction: + logger.debug("ConnectionLifetimePlugin.ActionDeferred", method_name) + return execute_func() + + if self._action == ConnectionLifetimeAction.CLOSE: + self._close_current_connection() + else: + self._reconnect() + + def _select_current_connection_timestamp(self) -> None: + current_connection = self._plugin_service.current_connection + creation_time = None + if current_connection is not None: + creation_time = self._connection_creation_times.get(current_connection) + if creation_time is None: + creation_time = self._clock_ns() + self._connection_creation_times.record(current_connection, creation_time) + + self._timed_connection = current_connection + self._connection_creation_time_ns = creation_time + + def _is_current_connection_expired(self) -> bool: + current_connection = self._plugin_service.current_connection + if current_connection is not self._timed_connection or self._connection_creation_time_ns is None: + self._select_current_connection_timestamp() + + creation_time = self._connection_creation_time_ns + # The boundary is inclusive: a 1000 ms lifetime expires at exactly 1000 ms. + return (creation_time is not None + and self._clock_ns() - creation_time >= self._connection_lifetime_ns) + + def _close_current_connection(self) -> None: + # Set before closing: once the physical connection is on its way out + # the wrapper connection is unusable whether or not close() succeeds. + self._terminal = True + current_connection = self._plugin_service.current_connection + close_failure: Optional[Exception] = None + + if current_connection is not None: + self._connection_creation_times.forget(current_connection) + # Closing a pooled connection returns it to its pool, so evict it first. + self._evict(current_connection) + try: + current_connection.close() + except Exception as e: + close_failure = e + logger.warning("ConnectionLifetimePlugin.CloseConnectionFailed", e) + + error = ConnectionLifetimeExpiredError( + Messages.get("ConnectionLifetimePlugin.ConnectionClosed")) + if close_failure is not None: + raise error from close_failure + raise error + + def _reconnect(self) -> None: + previous_connection = self._plugin_service.current_connection + replacement_connection = None + try: + reconnect_host_info = self._original_host_info + if reconnect_host_info is None: + # Fall back to whatever the plugin service still reports; a + # pipeline that never ran an initial connect through this + # plugin (a pooled connection handed over, say) has no + # application host recorded. + reconnect_host_info = self._plugin_service.initial_connection_host_info + if reconnect_host_info is None: + raise AwsWrapperError( + Messages.get("ConnectionLifetimePlugin.OriginalHostUnavailable")) + + logger.debug("ConnectionLifetimePlugin.Reconnecting", reconnect_host_info.url) + replacement_connection = self._plugin_service.connect( + reconnect_host_info, self._props, self) + if replacement_connection is None: + raise AwsWrapperError( + Messages.get("ConnectionLifetimePlugin.ReconnectReturnedNone")) + replacement_creation_time = self._clock_ns() + + # Installs the replacement and disposes the old connection. The + # timer is only reset once this has succeeded. + # Evict before the plugin service closes the expired connection, which + # would return a pooled one to its pool. If another plugin preserves it, + # it stays usable and leaves the pool once it is closed. + if previous_connection is not None and previous_connection is not replacement_connection: + self._evict(previous_connection) + self._plugin_service.set_current_connection(replacement_connection, reconnect_host_info) + self._forget_closed_connection(previous_connection) + self._connection_creation_times.record(replacement_connection, replacement_creation_time) + self._timed_connection = replacement_connection + self._connection_creation_time_ns = replacement_creation_time + except Exception as e: + self._cleanup_failed_replacement(replacement_connection, previous_connection) + raise ConnectionLifetimeFailedError( + Messages.get("ConnectionLifetimePlugin.UnableToReconnect")) from e + + raise ConnectionLifetimeSuccessError( + Messages.get("ConnectionLifetimePlugin.ConnectionChanged")) + + def _forget_closed_connection(self, connection: Optional[Connection]) -> None: + if connection is None: + return + + try: + closed = self._plugin_service.driver_dialect.is_closed(connection) + except Exception: + # A connection that cannot report its state is unusable; do not retain it. + closed = True + + if closed: + self._connection_creation_times.forget(connection) + + def _evict(self, connection: Any) -> None: + self._plugin_service.get_connection_provider_manager().evict_connection(connection) + + def _cleanup_failed_replacement( + self, + replacement_connection: Optional[Connection], + previous_connection: Optional[Connection]) -> None: + if (replacement_connection is not None + and replacement_connection is self._plugin_service.current_connection + and replacement_connection is not previous_connection): + # The replacement was installed and the failure came after, so + # neither connection can be relied on from here. The previous + # connection was evicted before the replacement was installed. + self._terminal = True + self._close_after_failed_installation(replacement_connection) + self._close_after_failed_installation(previous_connection) + return + + self._close_unattached_replacement(replacement_connection) + + def _close_after_failed_installation(self, connection: Optional[Connection]) -> None: + if connection is None: + return + + self._connection_creation_times.forget(connection) + try: + connection.close() + except Exception as e: + logger.warning("ConnectionLifetimePlugin.FailedInstallationConnectionCloseFailed", e) + + def _close_unattached_replacement(self, replacement_connection: Optional[Connection]) -> None: + if (replacement_connection is None + or replacement_connection is self._plugin_service.current_connection): + return + + self._connection_creation_times.forget(replacement_connection) + try: + replacement_connection.close() + except Exception as e: + logger.warning("ConnectionLifetimePlugin.ReplacementCloseFailed", e) + + +class ConnectionLifetimePluginFactory(PluginFactory): + @staticmethod + def get_instance(plugin_service: PluginService, props: Properties) -> Plugin: + return ConnectionLifetimePlugin(plugin_service, props) diff --git a/aws_advanced_python_wrapper/connection_provider.py b/aws_advanced_python_wrapper/connection_provider.py index 4547ccd69..312712822 100644 --- a/aws_advanced_python_wrapper/connection_provider.py +++ b/aws_advanced_python_wrapper/connection_provider.py @@ -15,8 +15,8 @@ from __future__ import annotations from types import MappingProxyType -from typing import (TYPE_CHECKING, Callable, ClassVar, Dict, Mapping, Optional, - Protocol, Tuple) +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, Mapping, + Optional, Protocol, Tuple, runtime_checkable) if TYPE_CHECKING: from aws_advanced_python_wrapper.database_dialect import DatabaseDialect @@ -97,6 +97,21 @@ def connect( ... +@runtime_checkable +class CanEvictConnection(Protocol): + def evict_connection(self, connection: Any) -> bool: + """ + Keep a connection this provider issued from being handed out again. + + Call it before closing the connection, because closing returns it to the pool. + The connection stays usable until the caller closes it. The pool then closes its physical connection instead of keeping it. + + :param connection: a connection returned by this provider's ``connect``. + :return: `True` if the connection came from this provider's pool and was evicted, `False` otherwise. + """ + ... + + class DriverConnectionProvider(ConnectionProvider): _accepted_strategies: Dict[str, HostSelector] = {"random": RandomHostSelector(), "round_robin": RoundRobinHostSelector(), @@ -226,6 +241,23 @@ def get_host_info_by_strategy( return self._default_provider.get_host_info_by_strategy(hosts, role, strategy, props) + def evict_connection(self, connection: Any) -> bool: + """ + Evict a connection from the pool of the provider that issued it. See :py:method:`CanEvictConnection.evict_connection`. + + :param connection: the connection to evict. + :return: `True` if one of the available providers evicted the connection. + """ + with ConnectionProviderManager._lock: + custom_provider = ConnectionProviderManager._conn_provider + + if isinstance(custom_provider, CanEvictConnection) and custom_provider.evict_connection(connection): + return True + + return (self._default_provider is not custom_provider + and isinstance(self._default_provider, CanEvictConnection) + and self._default_provider.evict_connection(connection)) + @staticmethod def reset_provider(): """ diff --git a/aws_advanced_python_wrapper/errors.py b/aws_advanced_python_wrapper/errors.py index 7af9a752e..3f31e961a 100644 --- a/aws_advanced_python_wrapper/errors.py +++ b/aws_advanced_python_wrapper/errors.py @@ -67,6 +67,31 @@ class FailoverSuccessError(FailoverError): __module__ = "aws_advanced_python_wrapper" +class ConnectionLifetimeError(AwsWrapperError, OperationalError): + __module__ = "aws_advanced_python_wrapper" + + +class ConnectionLifetimeExpiredError(ConnectionLifetimeError): + # connection_lifetime_action=close: the physical connection is gone and + # the wrapper connection is permanently unusable. + __module__ = "aws_advanced_python_wrapper" + sqlstate = "08003" + + +class ConnectionLifetimeSuccessError(ConnectionLifetimeError): + # connection_lifetime_action=reconnect succeeded: the wrapper connection + # now holds a replacement physical connection and may be retried once the + # caller re-creates its cursors. + __module__ = "aws_advanced_python_wrapper" + sqlstate = "08S02" + + +class ConnectionLifetimeFailedError(ConnectionLifetimeError): + # connection_lifetime_action=reconnect failed: no usable connection. + __module__ = "aws_advanced_python_wrapper" + sqlstate = "08001" + + class ReadWriteSplittingError(AwsWrapperError, InterfaceError): __module__ = "aws_advanced_python_wrapper" diff --git a/aws_advanced_python_wrapper/pep249.py b/aws_advanced_python_wrapper/pep249.py index 3e486b17f..6f82e6558 100644 --- a/aws_advanced_python_wrapper/pep249.py +++ b/aws_advanced_python_wrapper/pep249.py @@ -47,8 +47,8 @@ class Warning(Exception): class Error(Exception): __module__ = "aws_advanced_python_wrapper" - errno = None - sqlstate = None + errno: Optional[int] = None + sqlstate: Optional[str] = None class InterfaceError(Error): diff --git a/aws_advanced_python_wrapper/plugin_service.py b/aws_advanced_python_wrapper/plugin_service.py index 469303799..cba1874bb 100644 --- a/aws_advanced_python_wrapper/plugin_service.py +++ b/aws_advanced_python_wrapper/plugin_service.py @@ -55,6 +55,8 @@ AwsSecretsManagerPluginFactory from aws_advanced_python_wrapper.connect_time_plugin import \ ConnectTimePluginFactory +from aws_advanced_python_wrapper.connection_lifetime_plugin import \ + ConnectionLifetimePluginFactory from aws_advanced_python_wrapper.connection_provider import ( ConnectionProvider, ConnectionProviderManager) from aws_advanced_python_wrapper.database_dialect import ( @@ -884,6 +886,7 @@ class PluginManager(CanReleaseResources): "fastest_response_strategy": FastestResponseStrategyPluginFactory, "stale_dns": StaleDnsPluginFactory, "custom_endpoint": CustomEndpointPluginFactory, + "connection_lifetime": ConnectionLifetimePluginFactory, "connect_time": ConnectTimePluginFactory, "execute_time": ExecuteTimePluginFactory, "dev": DeveloperPluginFactory, @@ -900,6 +903,7 @@ class PluginManager(CanReleaseResources): # the highest values. The first plugin of the list will have the lowest weight, and the # last one will have the highest weight. PLUGIN_FACTORY_WEIGHTS: Dict[Type[PluginFactory], int] = { + ConnectionLifetimePluginFactory: 30, CustomEndpointPluginFactory: 40, AuroraInitialConnectionStrategyPluginFactory: 50, AuroraConnectionTrackerPluginFactory: 100, 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..b1e962b08 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 @@ -116,6 +116,19 @@ conftest.ExceptionWhileObtainingInstanceIDs=[conftest] An exception was thrown w ConnectTimePlugin.ConnectTime=[ConnectTimePlugin] Connected in {} nanos. +ConnectionLifetimePlugin.InvalidConnectionLifetime=[ConnectionLifetimePlugin] The configuration property 'connection_lifetime_ms' is required and must be a positive whole number of milliseconds. Received: '{}'. +ConnectionLifetimePlugin.InvalidConnectionLifetimeAction=[ConnectionLifetimePlugin] The configuration property 'connection_lifetime_action' must be either 'close' or 'reconnect'. Received: '{}'. +ConnectionLifetimePlugin.ConnectionClosed=[ConnectionLifetimePlugin] The connection has reached its maximum lifetime and is closed. +ConnectionLifetimePlugin.ActionDeferred=[ConnectionLifetimePlugin] The connection has reached its maximum lifetime, but the lifetime action is deferred while a transaction is active. Executing '{}' on the current connection. +ConnectionLifetimePlugin.CloseConnectionFailed=[ConnectionLifetimePlugin] Unable to close the expired connection: {} +ConnectionLifetimePlugin.OriginalHostUnavailable=[ConnectionLifetimePlugin] The original application host is unavailable for connection-lifetime reconnection. +ConnectionLifetimePlugin.Reconnecting=[ConnectionLifetimePlugin] The connection has reached its maximum lifetime. Reconnecting to the original application host '{}'. +ConnectionLifetimePlugin.ReconnectReturnedNone=[ConnectionLifetimePlugin] The connection-lifetime reconnect attempt did not return a connection. +ConnectionLifetimePlugin.ReplacementCloseFailed=[ConnectionLifetimePlugin] Unable to close the unused replacement connection after a connection-lifetime reconnect failure: {} +ConnectionLifetimePlugin.FailedInstallationConnectionCloseFailed=[ConnectionLifetimePlugin] Unable to close a connection after a replacement connection was only partially installed: {} +ConnectionLifetimePlugin.ConnectionChanged=[ConnectionLifetimePlugin] The active connection changed because its configured maximum lifetime was reached. Re-create any cursors before retrying the operation. +ConnectionLifetimePlugin.UnableToReconnect=[ConnectionLifetimePlugin] Unable to establish a replacement connection after the configured maximum connection lifetime was reached. + ConnectionProvider.UnsupportedHostSelectorStrategy=[ConnectionProvider] Unsupported host selection strategy '{}' specified for this connection provider '{}'. Please visit the documentation for all supported strategies. CustomEndpointMonitor.DetectedChangeInCustomEndpointInfo=[CustomEndpointMonitor] Detected change in custom endpoint info for '{}':\n{} @@ -459,8 +472,10 @@ GdbReadWriteSplittingPlugin.WriterNotInAccessibleRegion=[GdbReadWriteSplittingPl GdbReadWriteSplittingPlugin.HomeRegionNotInAccessibleRegions=[GdbReadWriteSplittingPlugin] Home region '{}' is not included in the list of accessible regions {}. The home region must be accessible. SqlAlchemyPooledConnectionProvider.PoolNone=[SqlAlchemyPooledConnectionProvider] Attempted to find or create a pool for '{}' but the result of the attempt evaluated to None. +SqlAlchemyPooledConnectionProvider.ConnectionEvicted=[SqlAlchemyPooledConnectionProvider] Evicted a connection from its internal connection pool. The pool closes the physical connection when the connection is returned to it. SqlAlchemyPooledConnectionProvider.UnableToCreateDefaultKey=[SqlAlchemyPooledConnectionProvider] Unable to create a default key for internal connection pools. By default, the user parameter is used, but the given user evaluated to None or the empty string (""). Please ensure you have passed a valid user in the connection properties. AsyncPooledConnectionProvider.PoolNone=[AsyncPooledConnectionProvider] Attempted to find or create a pool for '{}' but the result of the attempt evaluated to None. +AsyncPooledConnectionProvider.ConnectionEvicted=[AsyncPooledConnectionProvider] Evicted a connection from its internal connection pool. The pool closes the physical connection when the connection is returned to it. AsyncPooledConnectionProvider.UnableToCreateDefaultKey=[AsyncPooledConnectionProvider] Unable to create a default key for internal connection pools. By default, the user parameter is used, but the given user evaluated to None or the empty string (""). Please ensure you have passed a valid user in the connection properties. AsyncPooledConnectionProvider.PoolDisposed=[AsyncPooledConnectionProvider] PoolDisposed: Cannot acquire a connection from the pool for '{}' because the pool is being disposed. diff --git a/aws_advanced_python_wrapper/sql_alchemy_connection_provider.py b/aws_advanced_python_wrapper/sql_alchemy_connection_provider.py index b7ce17529..219a17702 100644 --- a/aws_advanced_python_wrapper/sql_alchemy_connection_provider.py +++ b/aws_advanced_python_wrapper/sql_alchemy_connection_provider.py @@ -14,21 +14,24 @@ from __future__ import annotations -from typing import TYPE_CHECKING, Callable, ClassVar, Dict, Optional, Tuple +from typing import (TYPE_CHECKING, Any, Callable, ClassVar, Dict, Optional, + Tuple) if TYPE_CHECKING: from aws_advanced_python_wrapper.database_dialect import DatabaseDialect from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.driver_dialect import DriverDialect -from sqlalchemy import QueuePool, pool +from sqlalchemy import PoolProxiedConnection, QueuePool, event, pool -from aws_advanced_python_wrapper.connection_provider import ConnectionProvider +from aws_advanced_python_wrapper.connection_provider import ( + CanEvictConnection, ConnectionProvider) from aws_advanced_python_wrapper.errors import AwsWrapperError from aws_advanced_python_wrapper.host_selector import ( HighestWeightHostSelector, HostSelector, RandomHostSelector, RoundRobinHostSelector, WeightedRandomHostSelector) from aws_advanced_python_wrapper.plugin import CanReleaseResources +from aws_advanced_python_wrapper.utils.log import Logger from aws_advanced_python_wrapper.utils.messages import Messages from aws_advanced_python_wrapper.utils.pool_key import PoolKey from aws_advanced_python_wrapper.utils.properties import (Properties, @@ -38,8 +41,19 @@ from aws_advanced_python_wrapper.utils.storage.sliding_expiration_cache import \ SlidingExpirationCache +logger = Logger(__name__) -class SqlAlchemyPooledConnectionProvider(ConnectionProvider, CanReleaseResources): +_EVICTED = "aws_advanced_python_wrapper.evicted" + + +def _close_evicted_connection(dbapi_connection: Any, connection_record: Any) -> None: + # Pool checkin listener: hard invalidation closes the physical connection, and the + # pool then holds an empty slot that opens a new connection on its next checkout. + if connection_record.info.pop(_EVICTED, False): + connection_record.invalidate() + + +class SqlAlchemyPooledConnectionProvider(ConnectionProvider, CanReleaseResources, CanEvictConnection): """ This class can be passed to :py:method:`ConnectionProviderManager.connection_provider` to enable internal connection pools for each database instance in a cluster. By maintaining internal connection pools, @@ -178,7 +192,23 @@ def _get_connection_func(self, target_connect_func: Callable, props: Properties) return lambda: target_connect_func(**props) def _create_sql_alchemy_pool(self, **kwargs): - return pool.QueuePool(**kwargs) + queue_pool = pool.QueuePool(**kwargs) + event.listen(queue_pool, "checkin", _close_evicted_connection) + return queue_pool + + def evict_connection(self, connection: Any) -> bool: + if (not isinstance(connection, PoolProxiedConnection) + or connection.is_detached or not connection.is_valid): + return False + + # Evict before close(): once the connection is checked in, the proxy no longer + # refers to its pool slot. Soft invalidation keeps the connection usable and makes + # the pool replace it instead of handing it out again. The flag lets the checkin + # listener close it as soon as it is returned. + connection.info[_EVICTED] = True + connection.invalidate(soft=True) + logger.debug("SqlAlchemyPooledConnectionProvider.ConnectionEvicted") + return True def release_resources(self): for _, cache_item in SqlAlchemyPooledConnectionProvider._database_pools.items(): diff --git a/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py b/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py index e4706293b..b836d0698 100644 --- a/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py +++ b/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql.py @@ -102,8 +102,12 @@ def is_disconnect(self, e, connection, cursor): # through to upstream's e.errno probe and raised AttributeError out of # SA's unguarded is_disconnect call. See # sqlalchemy_dialects/_exception_handling.py. - from aws_advanced_python_wrapper.errors import (FailoverError, - FailoverFailedError) + from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeError, ConnectionLifetimeSuccessError, + FailoverError, FailoverFailedError) + + if isinstance(e, ConnectionLifetimeError): + return not isinstance(e, ConnectionLifetimeSuccessError) # Catch the whole FailoverError family (FailoverSuccessError, # FailoverFailedError, AND TransactionResolutionUnknownError) before the diff --git a/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql_async.py b/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql_async.py index 58d056caf..c90062bf3 100644 --- a/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql_async.py +++ b/aws_advanced_python_wrapper/sqlalchemy_dialects/mysql_async.py @@ -231,8 +231,12 @@ def is_disconnect(self, e, connection, cursor): # return True so SA invalidates and the creator retries. # _AsyncDriverErrorNormalizeMixin handles the do_execute path; # this handles the cursor-creation path that runs earlier. - from aws_advanced_python_wrapper.errors import (FailoverError, - FailoverFailedError) + from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeError, ConnectionLifetimeSuccessError, + FailoverError, FailoverFailedError) + + if isinstance(e, ConnectionLifetimeError): + return not isinstance(e, ConnectionLifetimeSuccessError) # Catch the whole FailoverError family -- including # TransactionResolutionUnknownError -- before upstream probes diff --git a/aws_advanced_python_wrapper/sqlalchemy_dialects/pg.py b/aws_advanced_python_wrapper/sqlalchemy_dialects/pg.py index a5a9728ca..80541b484 100644 --- a/aws_advanced_python_wrapper/sqlalchemy_dialects/pg.py +++ b/aws_advanced_python_wrapper/sqlalchemy_dialects/pg.py @@ -104,8 +104,12 @@ def is_disconnect(self, e, connection, cursor): # bound to the new writer via plugin_service.current_connection; # SA should reuse it, not invalidate). # - FailoverFailedError → True (no usable connection; invalidate). - from aws_advanced_python_wrapper.errors import (FailoverError, - FailoverFailedError) + from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeError, ConnectionLifetimeSuccessError, + FailoverError, FailoverFailedError) + + if isinstance(e, ConnectionLifetimeError): + return not isinstance(e, ConnectionLifetimeSuccessError) # Catch the whole FailoverError family -- including # TransactionResolutionUnknownError -- before the upstream is_disconnect diff --git a/aws_advanced_python_wrapper/sqlalchemy_dialects/pg_async.py b/aws_advanced_python_wrapper/sqlalchemy_dialects/pg_async.py index 132640d76..992309a1a 100644 --- a/aws_advanced_python_wrapper/sqlalchemy_dialects/pg_async.py +++ b/aws_advanced_python_wrapper/sqlalchemy_dialects/pg_async.py @@ -154,8 +154,12 @@ def is_disconnect(self, e, connection, cursor): # - FailoverFailedError → True (no usable connection). # Complements _AsyncDriverErrorNormalizeMixin for the # cursor-creation path that runs before do_execute. - from aws_advanced_python_wrapper.errors import (FailoverError, - FailoverFailedError) + from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeError, ConnectionLifetimeSuccessError, + FailoverError, FailoverFailedError) + + if isinstance(e, ConnectionLifetimeError): + return not isinstance(e, ConnectionLifetimeSuccessError) # Catch the whole FailoverError family -- including # TransactionResolutionUnknownError -- before upstream probes diff --git a/aws_advanced_python_wrapper/utils/properties.py b/aws_advanced_python_wrapper/utils/properties.py index f84b8fbe0..7787e729f 100644 --- a/aws_advanced_python_wrapper/utils/properties.py +++ b/aws_advanced_python_wrapper/utils/properties.py @@ -358,6 +358,19 @@ class WrapperProperties: 5_000, ) + # ConnectionLifetimePlugin + CONNECTION_LIFETIME_MS = WrapperProperty( + "connection_lifetime_ms", + """Maximum lifetime of a physical connection, in milliseconds. Required by the connection_lifetime + plugin, and must be at least 1.""", + ) + CONNECTION_LIFETIME_ACTION = WrapperProperty( + "connection_lifetime_action", + """Action to take once a physical connection reaches its configured lifetime. Supported values are + 'close' and 'reconnect'.""", + "reconnect", + ) + # Host Availability Strategy DEFAULT_HOST_AVAILABILITY_STRATEGY = WrapperProperty( "default_host_availability_strategy", diff --git a/docs/README.md b/docs/README.md index a1ceef710..63ed2edaa 100644 --- a/docs/README.md +++ b/docs/README.md @@ -27,6 +27,7 @@ - [Reader Selection Strategies](using-the-python-wrapper/ReaderSelectionStrategies.md) - [Simple Read Write Splitting Plugin](using-the-python-wrapper/using-plugins/UsingTheSimpleReadWriteSplittingPlugin.md) - [Fastest Response Strategy Plugin](using-the-python-wrapper/using-plugins/UsingTheFastestResponseStrategyPlugin.md) + - [Connection Lifetime Plugin](using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md) - [Host Availability Strategy](using-the-python-wrapper/HostAvailabilityStrategy.md) - [Development Guide](./development-guide/DevelopmentGuide.md) - [Setup](./development-guide/DevelopmentGuide.md#setup) diff --git a/docs/using-the-python-wrapper/PluginChainCompatibility.md b/docs/using-the-python-wrapper/PluginChainCompatibility.md index 02b543843..4f7e1828c 100644 --- a/docs/using-the-python-wrapper/PluginChainCompatibility.md +++ b/docs/using-the-python-wrapper/PluginChainCompatibility.md @@ -16,6 +16,12 @@ a chain you haven't used before. |---------------------|-----------------------------------|-----| | `read_write_splitting` | `failover_v2` (not `failover`) | `failover_v2` starts the cluster topology monitor on the **initial** connect. With plain `failover`, the host list stays at `{writer-only}` until a later failover signal fires, and `conn.read_only = True` flips silently fall back to the writer rather than splitting to a reader. | +## Host-selection interactions + +| Plugin | Interacts with | Why | +|-----------------------|-------------------------------------------------|-----| +| `connection_lifetime` | `read_write_splitting`, `srw`, `gdb_rw`, `failover`, `failover_v2` | With `connection_lifetime_action=reconnect` the replacement connection always goes to the host the application originally supplied, never to the reader a splitting plugin switched to or the writer a failover landed on. An expired reader connection therefore returns to the original endpoint. Use `connection_lifetime_action=close` if the application should pick its own host again. | + ## Driver-specific incompatibilities | Plugin | Incompatible with | Why | diff --git a/docs/using-the-python-wrapper/SqlAlchemySupport.md b/docs/using-the-python-wrapper/SqlAlchemySupport.md index b4d5afd76..1a30432db 100644 --- a/docs/using-the-python-wrapper/SqlAlchemySupport.md +++ b/docs/using-the-python-wrapper/SqlAlchemySupport.md @@ -182,6 +182,7 @@ Plugins are configured identically to non-SA usage — via the `plugins` connect | [Fastest Response Strategy Plugin](using-plugins/UsingTheFastestResponseStrategyPlugin.md) | `fastest_response_strategy` | ✓ | | [Blue/Green Deployment Plugin](using-plugins/UsingTheBlueGreenPlugin.md) | `bg` | ✓ | | [Limitless Plugin](using-plugins/UsingTheLimitlessPlugin.md) | `limitless` | ✓ | +| [Connection Lifetime Plugin](using-plugins/UsingTheConnectionLifetimePlugin.md) | `connection_lifetime` | ✓ | | [Read Write Splitting Plugin](using-plugins/UsingTheReadWriteSplittingPlugin.md) | `read_write_splitting` | ✗ | | [Simple Read Write Splitting Plugin](using-plugins/UsingTheSimpleReadWriteSplittingPlugin.md) | `srw` | ✗ | diff --git a/docs/using-the-python-wrapper/UsingThePythonWrapper.md b/docs/using-the-python-wrapper/UsingThePythonWrapper.md index 384dc1fb5..1ef5676a9 100644 --- a/docs/using-the-python-wrapper/UsingThePythonWrapper.md +++ b/docs/using-the-python-wrapper/UsingThePythonWrapper.md @@ -107,6 +107,7 @@ The AWS Advanced Python Wrapper has several built-in plugins that are available | [Fastest Response Strategy Plugin](./using-plugins/UsingTheFastestResponseStrategyPlugin.md) | `fastest_response_strategy` | Aurora | A host selection strategy plugin that uses a host monitoring service to monitor each reader host's response time and choose the host with the fastest response. | None | | [Blue/Green Deployment Plugin](./using-plugins/UsingTheBlueGreenPlugin.md) | `bg` | Aurora,
RDS Instance | Enables client-side Blue/Green Deployment support. | None | | [Limitless Plugin](./using-plugins/UsingTheLimitlessPlugin.md) | `limitless` | Aurora | Enables client-side load-balancing of Transaction Routers on Amazon Aurora Limitless Databases. | None | +| [Connection Lifetime Plugin](./using-plugins/UsingTheConnectionLifetimePlugin.md) | `connection_lifetime` | Any database | Limits the lifetime of a physical connection and either closes it or reconnects through the host the application originally supplied, before the next network-bound call. | None | In addition to the built-in plugins, you can also create custom plugins more suitable for your needs. For more information, see [Custom Plugins](../development-guide/LoadablePlugins.md#using-custom-plugins). diff --git a/docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md b/docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md new file mode 100644 index 000000000..17a80bfea --- /dev/null +++ b/docs/using-the-python-wrapper/using-plugins/UsingTheConnectionLifetimePlugin.md @@ -0,0 +1,134 @@ +# Connection Lifetime Plugin + +The Connection Lifetime Plugin limits how long the AWS Advanced Python Wrapper uses a physical database connection. +When an expired connection is about to make a network-bound call, the plugin either closes the connection or reconnects to the host originally supplied by the application. + +## Enabling the Connection Lifetime Plugin + +Add the plugin code `connection_lifetime` to the [`plugins`](../UsingThePythonWrapper.md#aws-advanced-python-wrapper-parameters) parameter. +The `connection_lifetime_ms` parameter is required. + +```python +params = { + "host": "db-identifier.cluster-XYZ.us-east-2.rds.amazonaws.com", + "dbname": "postgres", + "user": "username", + "password": "password", + "plugins": "connection_lifetime", + "connection_lifetime_ms": 300000 +} + +conn = AwsWrapperConnection.connect(psycopg.Connection.connect, **params) +``` + +Unless `auto_sort_wrapper_plugin_order` is set to `False`, the Connection Lifetime Plugin automatically runs before every other plugin. + +## Configuration Parameters + +| Parameter | Value | Required | Description | Default Value | +|------------------------------|:-----:|:--------:|:-----------------------------------------------------------------------------------------------------------------------------|---------------| +| `connection_lifetime_ms` | `int` | Yes | Maximum physical connection lifetime in milliseconds. The value must be a whole number of at least `1`. | None | +| `connection_lifetime_action` | `str` | No | Action taken after the connection expires. Accepted values are `reconnect` and `close`, ignoring case and surrounding spaces. | `reconnect` | + +A missing or invalid `connection_lifetime_ms` value, or an unsupported `connection_lifetime_action` value, raises an `AwsWrapperError` when the connection is opened. + +## Expiration Checks + +The lifetime starts when a physical connection is created. +A connection the plugin did not see being created, for example one opened while the plugin was skipped, is timestamped when the plugin first notices it. +A connection is expired when its elapsed lifetime is greater than or equal to `connection_lifetime_ms`. +The boundary is inclusive, so a connection with a configured lifetime of 1000 ms is expired at exactly 1000 ms. + +The plugin checks the lifetime immediately before the calls the driver dialect marks as network-bound, such as: + +- `Connection.cursor`, `Connection.commit` and `Connection.rollback` +- `Cursor.execute`, `Cursor.callproc` and the `Cursor.fetch*` methods +- reading or setting `autocommit` and `read_only` + +It does not run a background timer. +An expired connection therefore stays open until the next network-bound call triggers the configured action. + +`Connection.close`, `Cursor.close` and the closed-state check never trigger the action, so an expired connection can always be closed. + +The plugin applies only to the connection used by the application. +Internal connections opened by other plugins, such as monitoring or topology connections, have their own lifecycle and are not tracked. + +The configured action runs before the pending call, and the pending call is not executed. + +## Close Action + +With `connection_lifetime_action` set to `close`, the plugin closes the current physical connection and raises a `ConnectionLifetimeExpiredError`. +If closing the connection fails, the failure is available as the error's `__cause__`. + +The wrapper connection remains permanently unusable after this error, and every later network-bound call raises `ConnectionLifetimeExpiredError`. +Close the wrapper connection and open a new one. + +## Reconnect Action + +With the default `connection_lifetime_action` of `reconnect`, the plugin opens a replacement physical connection to the host and port the application originally supplied. +It does not use a host selected later by read/write splitting, failover or another plugin. +The replacement becomes the wrapper connection's current connection, and the lifetime is reset only after that switch succeeds. + +After a successful reconnect, the plugin raises a `ConnectionLifetimeSuccessError`. +The wrapper connection already holds the replacement connection, but the pending call was not executed. +Re-create any cursors, reconfigure any session state that is not transferred automatically, and retry the operation. + +`ConnectionLifetimeSuccessError` does not extend `FailoverSuccessError`. +Application code that retries after a [successful failover](./UsingTheFailoverPlugin.md#failoversuccesserror) must also catch `ConnectionLifetimeSuccessError` to retry after a successful reconnect. + +If opening or installing the replacement connection fails, the plugin raises a `ConnectionLifetimeFailedError`, with the original failure available as its `__cause__`. +The lifetime is not reset, so the next network-bound call tries to reconnect again. +If the replacement was installed but the switch did not complete, the plugin closes both connections and later network-bound calls raise `ConnectionLifetimeExpiredError`. + +## Transactions + +Neither action runs while a transaction is active. +If the lifetime expires during a transaction, network-bound calls continue on the current physical connection, so `commit` and `rollback` complete normally. +Deferral does not extend or reset the lifetime. + +After the transaction ends, the first network-bound call runs the configured action before that call. + +## Error Handling + +| Error | Connection Usable Afterwards | SQLSTATE | What To Do | +|----------------------------------|:----------------------------:|:--------:|--------------------------------------------------------------------------------------------| +| `ConnectionLifetimeSuccessError` | Yes | `08S02` | Re-create cursors, reconfigure session state if required and retry the pending operation. | +| `ConnectionLifetimeFailedError` | Not always | `08001` | Retry later, or close the connection and open a new one if the error is repeated. | +| `ConnectionLifetimeExpiredError` | No | `08003` | Close the connection and open a new one. | + +All three errors are defined in `aws_advanced_python_wrapper.errors` and extend `ConnectionLifetimeError`, which extends `AwsWrapperError` and `OperationalError`. +Catch `ConnectionLifetimeError` to handle every lifetime outcome in one place, or check the subclasses to tell them apart. + +```python +from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeExpiredError, ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) + +try: + cursor = conn.cursor() + cursor.execute("SELECT 1") +except ConnectionLifetimeSuccessError: + # The connection now holds a new physical connection. Re-create the cursor and retry. + cursor = conn.cursor() + cursor.execute("SELECT 1") +except ConnectionLifetimeFailedError: + # The replacement connection could not be opened. Retry later, or open a new connection. + ... +except ConnectionLifetimeExpiredError: + # The connection was closed. Open a new connection. + ... +``` + +The asynchronous wrapper raises the same errors. + +## Connection Pooling + +The plugin measures the lifetime of the connection held by one wrapper connection. +With [internal connection pooling](./UsingTheReadWriteSplittingPlugin.md#internal-connection-pooling) through `SqlAlchemyPooledConnectionProvider` or the asynchronous pooled connection provider, the lifetime is measured from the time the connection was taken from the pool rather than from the time the physical connection was opened. +When the plugin closes or replaces an expired pooled connection, it evicts the connection first, so the pool closes the physical connection instead of handing it out again. +A connection taken from the pool may already be older than `connection_lifetime_ms`. +A connection that a read/write splitting plugin keeps cached is not evicted while it is cached. +It keeps its creation time, so if the application switches back to it after it has expired, the configured action runs on it, and a reconnect goes to the host the application originally supplied rather than to the reader. +To bound the age of pooled physical connections, use the pool's own settings, such as SQLAlchemy's `pool_recycle`. + +With SQLAlchemy, the wrapper dialects treat `ConnectionLifetimeSuccessError` as a usable connection and the other lifetime errors as a disconnect, so the pool invalidates a connection that cannot be used again. diff --git a/tests/unit/test_aio_connection_lifetime_plugin.py b/tests/unit/test_aio_connection_lifetime_plugin.py new file mode 100644 index 000000000..f1b4dc7be --- /dev/null +++ b/tests/unit/test_aio_connection_lifetime_plugin.py @@ -0,0 +1,711 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +import asyncio +from typing import Any, List, Optional +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio.connection_lifetime_plugin import \ + AsyncConnectionLifetimePlugin +from aws_advanced_python_wrapper.aio.driver_dialect.aiomysql import \ + AsyncAiomysqlDriverDialect +from aws_advanced_python_wrapper.aio.plugin_factory import ( + PLUGIN_FACTORY_WEIGHTS, WEIGHT_RELATIVE_TO_PRIOR_PLUGIN, + _ConnectionLifetimeFactory) +from aws_advanced_python_wrapper.connection_lifetime_plugin import \ + LIFECYCLE_METHODS +from aws_advanced_python_wrapper.errors import (ConnectionLifetimeError, + ConnectionLifetimeExpiredError, + ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.utils.properties import Properties + +EXECUTE = DbApiMethod.CURSOR_EXECUTE.method_name +LIFETIME_MS = 1000 +MS = 1_000_000 +HOST = HostInfo("instance-1.xyz.us-east-1.rds.amazonaws.com") + + +class AiomysqlLikeConnection: + """close() is synchronous; ensure_closed() is the graceful coroutine.""" + + def __init__(self, ensure_closed_error: Optional[Exception] = None) -> None: + self.closed = False + self.ensure_closed_calls = 0 + self._ensure_closed_error = ensure_closed_error + + def close(self) -> None: + self.closed = True + + async def ensure_closed(self) -> None: + self.ensure_closed_calls += 1 + if self._ensure_closed_error is not None: + raise self._ensure_closed_error + self.close() + + +class FailingAiomysqlLikeConnection: + """Both ensure_closed() and close() raise, as on a socket that is already gone.""" + + def __init__(self, name: str) -> None: + self.name = name + self.closed = False + self.ensure_closed_calls = 0 + self.close_calls = 0 + + def close(self) -> None: + self.close_calls += 1 + raise RuntimeError(f"{self.name} close failed") + + async def ensure_closed(self) -> None: + self.ensure_closed_calls += 1 + raise ConnectionResetError(f"{self.name} peer reset while sending COM_QUIT") + + +class PsycopgLikeConnection: + """close() is a coroutine.""" + + def __init__(self) -> None: + self.closed = False + + async def close(self) -> None: + self.closed = True + + +class FailingPsycopgLikeConnection(PsycopgLikeConnection): + def __init__(self) -> None: + super().__init__() + self.close_calls = 0 + + async def close(self) -> None: + self.close_calls += 1 + raise RuntimeError("close failed") + + +class FakeClock: + def __init__(self) -> None: + self.now_ns = 0 + + def __call__(self) -> int: + return self.now_ns + + def advance_ms(self, ms: int) -> None: + self.now_ns += ms * MS + + +class FakeDriverDialect: + # Closing goes through the real aiomysql dialect, which takes the graceful + # ensure_closed() path for aiomysql-like connections and close() otherwise. + _closer = AsyncAiomysqlDriverDialect() + + async def is_closed(self, connection: Any) -> bool: + return bool(connection.closed) + + async def close_connection(self, connection: Any) -> None: + await self._closer.close_connection(connection) + + +class FakeAsyncPluginService: + def __init__(self) -> None: + self.network_bound_methods = {EXECUTE, DbApiMethod.CONNECTION_CLOSE.method_name} + self.current_connection: Optional[Any] = None + self.is_in_transaction = False + self.initial_connection_host_info: Optional[HostInfo] = None + self.replacements: List[Any] = [] + self.connect_hosts: List[HostInfo] = [] + self.connect_props: List[Properties] = [] + self.connect_error: Optional[Exception] = None + self.driver_dialect = FakeDriverDialect() + self.preserve_previous = False + self.install_error: Optional[Exception] = None + # Each evicted connection with whether it was already closed at the time. + self.evicted: List[Any] = [] + self.connection_provider_manager = MagicMock() + self.connection_provider_manager.evict_connection.side_effect = \ + lambda conn: self.evicted.append((conn, bool(conn.closed))) + + def get_connection_provider_manager(self) -> Any: + return self.connection_provider_manager + + def is_network_bound_method(self, method_name: str) -> bool: + return method_name in self.network_bound_methods + + async def connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: Any) -> Any: + self.connect_hosts.append(host_info) + self.connect_props.append(props) + if self.connect_error is not None: + raise self.connect_error + return self.replacements.pop(0) + + async def set_current_connection(self, connection: Any, host_info: HostInfo) -> None: + previous = self.current_connection + self.current_connection = connection + if previous is not None and previous is not connection and not self.preserve_previous: + result = previous.close() + if asyncio.iscoroutine(result): + await result + if self.install_error is not None: + raise self.install_error + + +def make_props(action: str = "reconnect") -> Properties: + return Properties({ + "connection_lifetime_ms": str(LIFETIME_MS), + "connection_lifetime_action": action, + }) + + +def make_plugin( + plugin_service, clock, action: str = "reconnect", props: Optional[Properties] = None) -> AsyncConnectionLifetimePlugin: + return AsyncConnectionLifetimePlugin(plugin_service, props if props is not None else make_props(action), clock_ns=clock) + + +async def open_connection(plugin, plugin_service, connection) -> None: + async def connect_func() -> Any: + return connection + + await plugin.connect(None, None, HOST, Properties(), True, connect_func) + plugin_service.current_connection = connection + plugin.notify_connection_changed(set()) + + +async def execute(plugin, result: str = "rows") -> Any: + async def execute_func() -> str: + return result + + return await plugin.execute(None, EXECUTE, execute_func) + + +def test_subscribed_methods_are_network_bound_methods_and_connect_hooks(): + plugin = make_plugin(FakeAsyncPluginService(), FakeClock()) + + assert plugin.subscribed_methods == { + EXECUTE, + DbApiMethod.CONNECTION_CLOSE.method_name, + DbApiMethod.CONNECT.method_name, + DbApiMethod.FORCE_CONNECT.method_name, + DbApiMethod.NOTIFY_CONNECTION_CHANGED.method_name, + } + + +def test_plugin_has_the_lowest_weight(): + # Relative-weight entries are a sentinel placed after the prior plugin, not a position. + weights = { + factory: weight for factory, weight in PLUGIN_FACTORY_WEIGHTS.items() + if weight != WEIGHT_RELATIVE_TO_PRIOR_PLUGIN} + lifetime_weight = weights.pop(_ConnectionLifetimeFactory) + + assert all(lifetime_weight < weight for weight in weights.values()) + + +def test_connection_before_lifetime_is_used(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = PsycopgLikeConnection() + await open_connection(plugin, plugin_service, connection) + + clock.advance_ms(LIFETIME_MS - 1) + + assert await execute(plugin) == "rows" + assert not connection.closed + + asyncio.run(_body()) + + +def test_lifetime_boundary_is_inclusive(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + await open_connection(plugin, plugin_service, PsycopgLikeConnection()) + + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + asyncio.run(_body()) + + +def test_non_network_bound_method_is_not_checked(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = PsycopgLikeConnection() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + async def local() -> str: + return "local" + + assert await plugin.execute(None, DbApiMethod.CONNECTION_COMMIT.method_name, local) == "local" + assert not connection.closed + + asyncio.run(_body()) + + +@pytest.mark.parametrize("action", ["close", "reconnect"]) +@pytest.mark.parametrize("method_name", sorted(LIFECYCLE_METHODS)) +def test_teardown_methods_never_trigger_action_on_expired_connection(action, method_name): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin_service.network_bound_methods = {EXECUTE, *LIFECYCLE_METHODS} + plugin = make_plugin(plugin_service, clock, action) + connection = PsycopgLikeConnection() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + async def teardown() -> str: + return "teardown" + + assert await plugin.execute(None, method_name, teardown) == "teardown" + + assert not connection.closed + assert plugin_service.connect_hosts == [] + assert plugin_service.evicted == [] + # The connection is still expired, so the next network-bound call runs the action. + plugin_service.replacements.append(PsycopgLikeConnection()) + with pytest.raises(ConnectionLifetimeError): + await execute(plugin) + + asyncio.run(_body()) + + +def test_close_action_uses_ensure_closed_for_aiomysql(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = AiomysqlLikeConnection() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + assert connection.ensure_closed_calls == 1 + assert connection.closed + + asyncio.run(_body()) + + +def test_close_action_closes_socket_when_ensure_closed_fails(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + quit_error = ConnectionResetError("peer reset while sending COM_QUIT") + connection = AiomysqlLikeConnection(ensure_closed_error=quit_error) + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError) as raised: + await execute(plugin) + + assert raised.value.__cause__ is quit_error + assert connection.closed + + asyncio.run(_body()) + + +def test_close_action_awaits_psycopg_close(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = PsycopgLikeConnection() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + assert connection.closed + + asyncio.run(_body()) + + +def test_close_action_evicts_before_closing(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = PsycopgLikeConnection() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + assert plugin_service.evicted == [(connection, False)] + assert connection.closed + + asyncio.run(_body()) + + +def test_close_action_on_mock_connection_calls_close(): + # A MagicMock answers every attribute, including ensure_closed; the plugin + # must not mistake that for aiomysql's coroutine. + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = MagicMock() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + connection.close.assert_called_once() + connection.ensure_closed.assert_not_called() + + asyncio.run(_body()) + + +def test_closed_wrapper_connection_stays_closed(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + await open_connection(plugin, plugin_service, PsycopgLikeConnection()) + clock.advance_ms(LIFETIME_MS) + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + async def must_not_run() -> None: + raise AssertionError("execute_func ran on a closed wrapper connection") + + with pytest.raises(ConnectionLifetimeExpiredError): + await plugin.execute(None, EXECUTE, must_not_run) + + asyncio.run(_body()) + + +def test_action_waits_for_open_transaction(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock, "close") + connection = PsycopgLikeConnection() + await open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + plugin_service.is_in_transaction = True + assert await execute(plugin) == "rows" + assert not connection.closed + + plugin_service.is_in_transaction = False + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + asyncio.run(_body()) + + +def test_reconnect_action_replaces_connection_on_original_host(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + replacement = PsycopgLikeConnection() + plugin_service.replacements.append(replacement) + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + + assert plugin_service.connect_hosts == [HOST] + assert plugin_service.current_connection is replacement + assert first.closed + + clock.advance_ms(LIFETIME_MS - 1) + assert await execute(plugin) == "rows" + + asyncio.run(_body()) + + +def test_reconnect_action_waits_for_open_transaction(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + replacement = PsycopgLikeConnection() + plugin_service.replacements.append(replacement) + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + plugin_service.is_in_transaction = True + assert await execute(plugin) == "rows" + assert plugin_service.connect_hosts == [] + assert plugin_service.current_connection is first + + plugin_service.is_in_transaction = False + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + assert plugin_service.current_connection is replacement + + asyncio.run(_body()) + + +def test_reconnect_passes_the_plugin_properties(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + props = make_props() + plugin = make_plugin(plugin_service, clock, props=props) + plugin_service.replacements.append(PsycopgLikeConnection()) + await open_connection(plugin, plugin_service, PsycopgLikeConnection()) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + + assert len(plugin_service.connect_props) == 1 + assert plugin_service.connect_props[0] is props + assert plugin_service.connect_props[0] == { + "connection_lifetime_ms": str(LIFETIME_MS), + "connection_lifetime_action": "reconnect", + } + + asyncio.run(_body()) + + +def test_reconnect_returning_the_current_connection_keeps_it(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + plugin_service.replacements.append(first) + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + + assert plugin_service.current_connection is first + assert plugin_service.evicted == [] + assert not first.closed + # The timer restarts from the reconnect. + clock.advance_ms(LIFETIME_MS - 1) + assert await execute(plugin) == "rows" + + asyncio.run(_body()) + + +def test_failed_install_of_the_current_connection_leaves_it_open(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + install_error = RuntimeError("session state could not be applied") + plugin_service.replacements.append(first) + plugin_service.install_error = install_error + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + await execute(plugin) + + assert raised.value.__cause__ is install_error + assert plugin_service.current_connection is first + assert plugin_service.evicted == [] + assert not first.closed + + asyncio.run(_body()) + + +def test_reconnect_evicts_superseded_connection_before_closing(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + plugin_service.replacements.append(PsycopgLikeConnection()) + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + + assert plugin_service.evicted == [(first, False)] + assert first.closed + + asyncio.run(_body()) + + +def test_reconnect_leaves_preserved_connection_open(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + plugin_service.replacements.append(PsycopgLikeConnection()) + plugin_service.preserve_previous = True + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + + # Eviction only marks the connection; the plugin that preserved it can keep using it. + assert plugin_service.evicted == [(first, False)] + assert not first.closed + + asyncio.run(_body()) + + +def test_terminal_reconnect_failure_evicts_only_previous_connection(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + replacement = PsycopgLikeConnection() + plugin_service.replacements.append(replacement) + plugin_service.install_error = RuntimeError("session state could not be applied") + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError): + await execute(plugin) + + assert plugin_service.evicted == [(first, False)] + assert first.closed + assert replacement.closed + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + asyncio.run(_body()) + + +def test_failed_close_of_both_connections_keeps_reconnect_failure_as_cause(): + # ensure_closed() and the close() fallback both fail on each connection. + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = FailingAiomysqlLikeConnection("first") + replacement = FailingAiomysqlLikeConnection("replacement") + install_error = RuntimeError("session state could not be applied") + plugin_service.replacements.append(replacement) + # The plugin service keeps the previous connection, so only the plugin's cleanup closes it. + plugin_service.preserve_previous = True + plugin_service.install_error = install_error + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + await execute(plugin) + + assert raised.value.__cause__ is install_error + for connection in (first, replacement): + assert connection.ensure_closed_calls == 1 + assert connection.close_calls == 1 + with pytest.raises(ConnectionLifetimeExpiredError): + await execute(plugin) + + asyncio.run(_body()) + + +def test_failed_close_of_unattached_replacement_keeps_reconnect_failure_as_cause(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + replacement = FailingPsycopgLikeConnection() + install_error = RuntimeError("replacement rejected before install") + plugin_service.replacements.append(replacement) + + async def reject(connection: Any, host_info: HostInfo) -> None: + raise install_error + + plugin_service.set_current_connection = reject # type: ignore[method-assign] + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + await execute(plugin) + + assert raised.value.__cause__ is install_error + assert replacement.close_calls == 1 + assert plugin_service.current_connection is first + assert not first.closed + + asyncio.run(_body()) + + +def test_failed_reconnect_keeps_previous_connection(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = PsycopgLikeConnection() + connect_error = RuntimeError("host unreachable") + plugin_service.connect_error = connect_error + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + await execute(plugin) + + assert raised.value.__cause__ is connect_error + assert plugin_service.current_connection is first + assert not first.closed + assert plugin_service.evicted == [] + + asyncio.run(_body()) + + +def test_failed_reconnect_is_retried_on_next_call(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + replacement = PsycopgLikeConnection() + plugin_service.connect_error = RuntimeError("host unreachable") + await open_connection(plugin, plugin_service, PsycopgLikeConnection()) + clock.advance_ms(LIFETIME_MS) + with pytest.raises(ConnectionLifetimeFailedError): + await execute(plugin) + + plugin_service.connect_error = None + plugin_service.replacements.append(replacement) + with pytest.raises(ConnectionLifetimeSuccessError): + await execute(plugin) + + assert plugin_service.connect_hosts == [HOST, HOST] + assert plugin_service.current_connection is replacement + + asyncio.run(_body()) + + +def test_reconnect_closes_unattached_aiomysql_replacement_with_ensure_closed(): + async def _body() -> None: + plugin_service, clock = FakeAsyncPluginService(), FakeClock() + plugin = make_plugin(plugin_service, clock) + first = AiomysqlLikeConnection() + replacement = AiomysqlLikeConnection() + install_error = RuntimeError("replacement rejected before install") + plugin_service.replacements.append(replacement) + + async def reject(connection: Any, host_info: HostInfo) -> None: + raise install_error + + plugin_service.set_current_connection = reject # type: ignore[method-assign] + await open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + await execute(plugin) + + assert raised.value.__cause__ is install_error + assert replacement.ensure_closed_calls == 1 + assert replacement.closed + assert first.ensure_closed_calls == 0 + assert not first.closed + + asyncio.run(_body()) diff --git a/tests/unit/test_aio_connection_provider.py b/tests/unit/test_aio_connection_provider.py index ee64afaab..f71749a9e 100644 --- a/tests/unit/test_aio_connection_provider.py +++ b/tests/unit/test_aio_connection_provider.py @@ -88,6 +88,17 @@ async def release_resources(self) -> None: self.resources_released = True +class _EvictingProvider(_RecordingProvider): + def __init__(self, evicts: bool) -> None: + super().__init__() + self._evicts = evicts + self.evicted: list = [] + + def evict_connection(self, connection: Any) -> bool: + self.evicted.append(connection) + return self._evicts + + def _reader_host(name: str) -> HostInfo: """Build a READER host that selectors consider eligible.""" host = HostInfo(name, role=HostRole.READER) @@ -214,3 +225,37 @@ def test_manager_release_resources_awaits_async_teardown() -> None: def test_manager_release_resources_noop_when_unset() -> None: # Should not raise even with no custom provider installed. asyncio.run(AsyncConnectionProviderManager.release_resources()) + + +def test_manager_evict_connection_without_evicting_provider() -> None: + AsyncConnectionProviderManager.set_connection_provider(_RecordingProvider()) + + assert not AsyncConnectionProviderManager().evict_connection(object()) + + +def test_manager_evict_connection_uses_custom_provider_first() -> None: + custom, default = _EvictingProvider(evicts=True), _EvictingProvider(evicts=True) + AsyncConnectionProviderManager.set_connection_provider(custom) + connection = object() + + assert AsyncConnectionProviderManager(default).evict_connection(connection) + assert custom.evicted == [connection] + assert default.evicted == [] + + +def test_manager_evict_connection_falls_back_to_default_provider() -> None: + custom, default = _EvictingProvider(evicts=False), _EvictingProvider(evicts=True) + AsyncConnectionProviderManager.set_connection_provider(custom) + connection = object() + + assert AsyncConnectionProviderManager(default).evict_connection(connection) + assert default.evicted == [connection] + + +def test_manager_evict_connection_asks_a_shared_provider_once() -> None: + shared = _EvictingProvider(evicts=False) + AsyncConnectionProviderManager.set_connection_provider(shared) + connection = object() + + assert not AsyncConnectionProviderManager(shared).evict_connection(connection) + assert shared.evicted == [connection] diff --git a/tests/unit/test_aio_plugin_factory.py b/tests/unit/test_aio_plugin_factory.py index c2cbd6afa..b2dfcaf7b 100644 --- a/tests/unit/test_aio_plugin_factory.py +++ b/tests/unit/test_aio_plugin_factory.py @@ -258,6 +258,7 @@ async def _body() -> None: # SRW endpoints are required at construction time. "srw_read_endpoint": "reader.example.com", "srw_write_endpoint": "writer.example.com", + "connection_lifetime_ms": "60000", }) # Use Aurora-capable hlp so failover / rws / custom_endpoint # don't error. diff --git a/tests/unit/test_aio_pooled_connection_provider.py b/tests/unit/test_aio_pooled_connection_provider.py index 087bfb61e..c95d90a07 100644 --- a/tests/unit/test_aio_pooled_connection_provider.py +++ b/tests/unit/test_aio_pooled_connection_provider.py @@ -549,3 +549,82 @@ async def inner(): assert provider.num_pools == 0 asyncio.run(inner()) + + +def test_evicted_connection_is_closed_instead_of_reused(): + async def inner(): + _reset_class_state() + provider = AsyncPooledConnectionProvider() + host = _make_host_info() + props = _make_props() + first_raw, second_raw = AsyncMock(), AsyncMock() + target = AsyncMock(side_effect=[first_raw, second_raw]) + driver_dialect = MagicMock() + driver_dialect.prepare_connect_info = MagicMock(return_value=props) + database_dialect = MagicMock() + + proxy = await provider.connect(target, driver_dialect, database_dialect, host, props) + assert provider.evict_connection(proxy) + first_raw.close.assert_not_awaited() + await proxy.close() + first_raw.close.assert_awaited_once() + + replacement = await provider.connect(target, driver_dialect, database_dialect, host, props) + assert replacement.driver_connection is second_raw + await replacement.close() + + asyncio.run(inner()) + + +def test_evict_connection_rejects_connections_it_cannot_evict(): + async def inner(): + pool = _AsyncPool(creator=AsyncMock(), max_size=1, max_overflow=0) + proxy = _PooledAsyncConnectionProxy(await pool.acquire(), pool) + await proxy.close() + provider = AsyncPooledConnectionProvider() + + assert not provider.evict_connection(proxy) + assert not provider.evict_connection(MagicMock()) + + asyncio.run(inner()) + + +def test_evicting_a_connection_leaves_other_connections_and_pools_untouched(): + async def inner(): + _reset_class_state() + provider = AsyncPooledConnectionProvider() + host = _make_host_info() + evicted_raw, same_pool_raw, other_pool_raw = AsyncMock(), AsyncMock(), AsyncMock() + target = AsyncMock(side_effect=[evicted_raw, same_pool_raw, other_pool_raw]) + driver_dialect = MagicMock() + driver_dialect.prepare_connect_info = MagicMock(side_effect=lambda h, p: p) + database_dialect = MagicMock() + + async def connect(user: str): + return await provider.connect(target, driver_dialect, database_dialect, host, _make_props(user=user)) + + evicted = await connect("user1") + same_pool = await connect("user1") + other_pool = await connect("user2") + assert provider.num_pools == 2 + + assert provider.evict_connection(evicted) + for proxy in (evicted, same_pool, other_pool): + await proxy.close() + + evicted_raw.close.assert_awaited_once() + same_pool_raw.close.assert_not_awaited() + other_pool_raw.close.assert_not_awaited() + + # Both pools still hand out their kept connections; only the evicted one is replaced. + reused_same = await connect("user1") + reused_other = await connect("user2") + assert reused_same.driver_connection is same_pool_raw + assert reused_other.driver_connection is other_pool_raw + assert target.await_count == 3 + assert provider.num_pools == 2 + await reused_same.close() + await reused_other.close() + await provider.release_resources() + + asyncio.run(inner()) diff --git a/tests/unit/test_aio_sqlalchemy_dialect.py b/tests/unit/test_aio_sqlalchemy_dialect.py index 28a1c5a4a..cde72fc84 100644 --- a/tests/unit/test_aio_sqlalchemy_dialect.py +++ b/tests/unit/test_aio_sqlalchemy_dialect.py @@ -338,3 +338,27 @@ class _NativeLike: called_arg = fetch_mock.call_args.args[0] assert called_arg is native + + +# ---- is_disconnect classification --------------------------------------- + + +def test_async_dialects_classify_the_connection_lifetime_error_family(): + """Only a successful reconnect leaves the pool slot's wrapper usable. + + The close action and a failed reconnect leave nothing to reuse, and none + of the three carry the driver attributes upstream's ``is_disconnect`` + probes, so they have to be classified before falling through. + """ + from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeExpiredError, ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) + from aws_advanced_python_wrapper.sqlalchemy_dialects.mysql_async import \ + AwsWrapperMySQLAiomysqlAsyncDialect + + for dialect_cls in (AwsWrapperPGPsycopgAsyncDialect, + AwsWrapperMySQLAiomysqlAsyncDialect): + d = dialect_cls.__new__(dialect_cls) + assert d.is_disconnect(ConnectionLifetimeSuccessError("x"), None, None) is False + assert d.is_disconnect(ConnectionLifetimeExpiredError("x"), None, None) is True + assert d.is_disconnect(ConnectionLifetimeFailedError("x"), None, None) is True diff --git a/tests/unit/test_connection_lifetime_plugin.py b/tests/unit/test_connection_lifetime_plugin.py new file mode 100644 index 000000000..4bf8e47ee --- /dev/null +++ b/tests/unit/test_connection_lifetime_plugin.py @@ -0,0 +1,609 @@ +# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"). +# You may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from __future__ import annotations + +from typing import Any, List, Optional + +import pytest + +from aws_advanced_python_wrapper.connection_lifetime_plugin import ( + LIFECYCLE_METHODS, ConnectionCreationTimes, ConnectionLifetimeAction, + ConnectionLifetimePlugin, ConnectionLifetimePluginFactory, + parse_connection_lifetime_action, parse_connection_lifetime_ns) +from aws_advanced_python_wrapper.errors import (AwsWrapperError, + ConnectionLifetimeError, + ConnectionLifetimeExpiredError, + ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.pep249 import OperationalError +from aws_advanced_python_wrapper.pep249_methods import DbApiMethod +from aws_advanced_python_wrapper.plugin_service import PluginManager +from aws_advanced_python_wrapper.utils.notifications import ConnectionEvent +from aws_advanced_python_wrapper.utils.properties import Properties + +EXECUTE = DbApiMethod.CURSOR_EXECUTE.method_name +LIFETIME_MS = 1000 +MS = 1_000_000 + + +class FakeConnection: + def __init__(self, name: str) -> None: + self.name = name + self.closed = False + + def close(self) -> None: + self.closed = True + + +class FailingCloseConnection(FakeConnection): + def __init__(self, name: str) -> None: + super().__init__(name) + self.close_attempts = 0 + + def close(self) -> None: + self.close_attempts += 1 + raise RuntimeError(f"{self.name} close failed") + + +class UnreferenceableConnection: + # No __weakref__ slot, so weakref.ref() raises TypeError for it. + __slots__ = ("name", "closed") + + def __init__(self, name: str) -> None: + self.name = name + self.closed = False + + def close(self) -> None: + self.closed = True + + +class FakeClock: + def __init__(self) -> None: + self.now_ns = 0 + + def __call__(self) -> int: + return self.now_ns + + def advance_ms(self, ms: int) -> None: + self.now_ns += ms * MS + + +class FakePluginService: + def __init__(self, mocker) -> None: + self.network_bound_methods = {EXECUTE, DbApiMethod.CONNECTION_CLOSE.method_name} + self.current_connection: Optional[Any] = None + self.current_host_info: Optional[HostInfo] = None + self.is_in_transaction = False + self.initial_connection_host_info: Optional[HostInfo] = None + self.replacements: List[Any] = [] + self.connect_hosts: List[HostInfo] = [] + self.connect_props: List[Properties] = [] + self.connect_error: Optional[Exception] = None + self.driver_dialect = mocker.MagicMock() + self.driver_dialect.is_closed.side_effect = lambda conn: conn.closed + self.preserve_previous = False + self.install_error: Optional[Exception] = None + # Each evicted connection with whether it was already closed at the time. + self.evicted: List[Any] = [] + self.connection_provider_manager = mocker.MagicMock() + self.connection_provider_manager.evict_connection.side_effect = \ + lambda conn: self.evicted.append((conn, conn.closed)) + + def get_connection_provider_manager(self) -> Any: + return self.connection_provider_manager + + def is_network_bound_method(self, method_name: str) -> bool: + return method_name in self.network_bound_methods + + def connect(self, host_info: HostInfo, props: Properties, plugin_to_skip: Any) -> Any: + self.connect_hosts.append(host_info) + self.connect_props.append(props) + if self.connect_error is not None: + raise self.connect_error + return self.replacements.pop(0) + + def set_current_connection(self, connection: Any, host_info: HostInfo) -> None: + previous = self.current_connection + self.current_connection = connection + self.current_host_info = host_info + if previous is not None and previous is not connection and not self.preserve_previous: + previous.close() + if self.install_error is not None: + raise self.install_error + + +HOST = HostInfo("instance-1.xyz.us-east-1.rds.amazonaws.com") + + +@pytest.fixture +def clock(): + return FakeClock() + + +@pytest.fixture +def plugin_service(mocker): + return FakePluginService(mocker) + + +def make_props(action: str = "reconnect") -> Properties: + return Properties({ + "connection_lifetime_ms": str(LIFETIME_MS), + "connection_lifetime_action": action, + }) + + +def make_plugin( + plugin_service, clock, action: str = "reconnect", props: Optional[Properties] = None) -> ConnectionLifetimePlugin: + return ConnectionLifetimePlugin(plugin_service, props if props is not None else make_props(action), clock_ns=clock) + + +def open_connection(plugin, plugin_service, connection) -> None: + # Runs the initial connect through the plugin, then installs the result + # the way the plugin service does. + plugin.connect(None, None, HOST, Properties(), True, lambda: connection) + plugin_service.current_connection = connection + plugin.notify_connection_changed(set()) + + +def execute(plugin, result: str = "rows") -> Any: + return plugin.execute(None, EXECUTE, lambda: result) + + +@pytest.mark.parametrize("error_class", [ + ConnectionLifetimeExpiredError, ConnectionLifetimeSuccessError, ConnectionLifetimeFailedError]) +def test_lifetime_errors_are_wrapper_operational_errors(error_class): + assert issubclass(error_class, ConnectionLifetimeError) + assert issubclass(error_class, AwsWrapperError) + assert issubclass(error_class, OperationalError) + assert error_class("closed").driver_error is None + + +@pytest.mark.parametrize("raw", [None, "", "abc", "0", "-5"]) +def test_invalid_connection_lifetime_is_rejected(raw): + props = Properties({} if raw is None else {"connection_lifetime_ms": raw}) + with pytest.raises(AwsWrapperError): + parse_connection_lifetime_ns(props) + + +@pytest.mark.parametrize("raw, expected_ms", [ + ("1", 1), + ("250", 250), + (" 300000 ", 300000), + (5000, 5000), +]) +def test_connection_lifetime_is_read_as_nanoseconds(raw, expected_ms): + assert parse_connection_lifetime_ns(Properties({"connection_lifetime_ms": raw})) == expected_ms * MS + + +def test_subscribed_methods_are_network_bound_methods_and_connect_hooks(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + + assert plugin.subscribed_methods == { + EXECUTE, + DbApiMethod.CONNECTION_CLOSE.method_name, + DbApiMethod.CONNECT.method_name, + DbApiMethod.FORCE_CONNECT.method_name, + DbApiMethod.NOTIFY_CONNECTION_CHANGED.method_name, + } + + +def test_plugin_has_the_lowest_weight(): + # Relative-weight entries are a sentinel placed after the prior plugin, not a position. + weights = { + factory: weight for factory, weight in PluginManager.PLUGIN_FACTORY_WEIGHTS.items() + if weight != PluginManager.WEIGHT_RELATIVE_TO_PRIOR_PLUGIN} + lifetime_weight = weights.pop(ConnectionLifetimePluginFactory) + + assert all(lifetime_weight < weight for weight in weights.values()) + + +@pytest.mark.parametrize("raw, expected", [ + (" CLOSE ", ConnectionLifetimeAction.CLOSE), + ("Reconnect", ConnectionLifetimeAction.RECONNECT), +]) +def test_connection_lifetime_action_ignores_case_and_space(raw, expected): + assert parse_connection_lifetime_action(Properties({"connection_lifetime_action": raw})) == expected + + +def test_connection_lifetime_action_defaults_to_reconnect(): + assert parse_connection_lifetime_action(Properties()) == ConnectionLifetimeAction.RECONNECT + + +def test_invalid_connection_lifetime_action_is_rejected(): + with pytest.raises(AwsWrapperError): + parse_connection_lifetime_action(Properties({"connection_lifetime_action": "drop"})) + + +def test_connection_before_lifetime_is_used(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + connection = FakeConnection("first") + open_connection(plugin, plugin_service, connection) + + clock.advance_ms(LIFETIME_MS - 1) + + assert execute(plugin) == "rows" + assert not connection.closed + + +def test_lifetime_boundary_is_inclusive(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + connection = FakeConnection("first") + open_connection(plugin, plugin_service, connection) + + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + + +def test_close_action_closes_connection_and_stays_closed(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + connection = FakeConnection("first") + open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + assert connection.closed + + def must_not_run(): + raise AssertionError("execute_func ran on a closed wrapper connection") + + with pytest.raises(ConnectionLifetimeExpiredError): + plugin.execute(None, EXECUTE, must_not_run) + + +def test_close_action_evicts_before_closing(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + connection = FakeConnection("first") + open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + + assert plugin_service.evicted == [(connection, False)] + assert connection.closed + + +def test_close_action_chains_close_failure(plugin_service, clock, mocker): + plugin = make_plugin(plugin_service, clock, "close") + connection = FakeConnection("first") + close_error = RuntimeError("socket already gone") + mocker.patch.object(connection, "close", side_effect=close_error) + open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeExpiredError) as raised: + execute(plugin) + assert raised.value.__cause__ is close_error + + +@pytest.mark.parametrize("action", ["close", "reconnect"]) +@pytest.mark.parametrize("method_name", sorted(LIFECYCLE_METHODS)) +def test_teardown_methods_never_trigger_action_on_expired_connection(plugin_service, clock, action, method_name): + plugin_service.network_bound_methods = {EXECUTE, *LIFECYCLE_METHODS} + plugin = make_plugin(plugin_service, clock, action) + connection = FakeConnection("first") + open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + assert plugin.execute(None, method_name, lambda: "teardown") == "teardown" + + assert not connection.closed + assert plugin_service.connect_hosts == [] + assert plugin_service.evicted == [] + # The connection is still expired, so the next network-bound call runs the action. + plugin_service.replacements.append(FakeConnection("replacement")) + with pytest.raises(ConnectionLifetimeError): + execute(plugin) + + +def test_lifecycle_methods_run_on_expired_connection(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + open_connection(plugin, plugin_service, FakeConnection("first")) + clock.advance_ms(LIFETIME_MS) + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + + assert plugin.execute(None, DbApiMethod.CONNECTION_CLOSE.method_name, lambda: "closed") == "closed" + + +def test_non_network_bound_method_is_not_checked(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + open_connection(plugin, plugin_service, FakeConnection("first")) + clock.advance_ms(LIFETIME_MS) + + assert plugin.execute(None, DbApiMethod.CONNECTION_COMMIT.method_name, lambda: "local") == "local" + + +def test_action_waits_for_open_transaction(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + connection = FakeConnection("first") + open_connection(plugin, plugin_service, connection) + clock.advance_ms(LIFETIME_MS) + + plugin_service.is_in_transaction = True + assert execute(plugin) == "rows" + assert not connection.closed + + plugin_service.is_in_transaction = False + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + assert connection.closed + + +def test_reconnect_action_replaces_connection_on_original_host(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + replacement = FakeConnection("replacement") + plugin_service.replacements.append(replacement) + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + assert plugin_service.connect_hosts == [HOST] + assert plugin_service.current_connection is replacement + assert first.closed + assert not replacement.closed + + +def test_reconnect_passes_the_plugin_properties(plugin_service, clock): + props = make_props() + plugin = make_plugin(plugin_service, clock, props=props) + plugin_service.replacements.append(FakeConnection("replacement")) + open_connection(plugin, plugin_service, FakeConnection("first")) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + assert len(plugin_service.connect_props) == 1 + assert plugin_service.connect_props[0] is props + assert plugin_service.connect_props[0] == { + "connection_lifetime_ms": str(LIFETIME_MS), + "connection_lifetime_action": "reconnect", + } + + +def test_reconnect_returning_the_current_connection_keeps_it(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + plugin_service.replacements.append(first) + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + assert plugin_service.current_connection is first + assert plugin_service.evicted == [] + assert not first.closed + # The timer restarts from the reconnect. + clock.advance_ms(LIFETIME_MS - 1) + assert execute(plugin) == "rows" + + +def test_failed_install_of_the_current_connection_leaves_it_open(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + install_error = RuntimeError("session state could not be applied") + plugin_service.replacements.append(first) + plugin_service.install_error = install_error + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + execute(plugin) + + assert raised.value.__cause__ is install_error + assert plugin_service.current_connection is first + assert plugin_service.evicted == [] + assert not first.closed + + +def test_reconnect_evicts_superseded_connection_before_closing(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + plugin_service.replacements.append(FakeConnection("replacement")) + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + assert plugin_service.evicted == [(first, False)] + assert first.closed + + +def test_reconnect_leaves_preserved_connection_open(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + plugin_service.replacements.append(FakeConnection("replacement")) + plugin_service.preserve_previous = True + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + # Eviction only marks the connection; the plugin that preserved it can keep using it. + assert plugin_service.evicted == [(first, False)] + assert not first.closed + + +def test_terminal_reconnect_failure_evicts_only_previous_connection(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + replacement = FakeConnection("replacement") + plugin_service.replacements.append(replacement) + plugin_service.install_error = RuntimeError("session state could not be applied") + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError): + execute(plugin) + + assert plugin_service.evicted == [(first, False)] + assert first.closed + assert replacement.closed + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + + +def test_failed_close_of_both_connections_keeps_reconnect_failure_as_cause(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FailingCloseConnection("first") + replacement = FailingCloseConnection("replacement") + install_error = RuntimeError("session state could not be applied") + plugin_service.replacements.append(replacement) + # The plugin service keeps the previous connection, so only the plugin's cleanup closes it. + plugin_service.preserve_previous = True + plugin_service.install_error = install_error + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + execute(plugin) + + assert raised.value.__cause__ is install_error + assert first.close_attempts == 1 + assert replacement.close_attempts == 1 + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + + +def test_failed_close_of_unattached_replacement_keeps_reconnect_failure_as_cause(plugin_service, clock, mocker): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + replacement = FailingCloseConnection("replacement") + install_error = RuntimeError("replacement rejected before install") + plugin_service.replacements.append(replacement) + mocker.patch.object(plugin_service, "set_current_connection", side_effect=install_error) + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + execute(plugin) + + assert raised.value.__cause__ is install_error + assert replacement.close_attempts == 1 + assert plugin_service.current_connection is first + assert not first.closed + + +def test_reconnected_connection_gets_a_fresh_lifetime(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + plugin_service.replacements.append(FakeConnection("replacement")) + open_connection(plugin, plugin_service, FakeConnection("first")) + clock.advance_ms(LIFETIME_MS) + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + clock.advance_ms(LIFETIME_MS - 1) + + assert execute(plugin) == "rows" + + +def test_reconnect_without_initial_connect_uses_plugin_service_host(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + fallback_host = HostInfo("cluster.cluster-xyz.us-east-1.rds.amazonaws.com") + plugin_service.initial_connection_host_info = fallback_host + plugin_service.replacements.append(FakeConnection("replacement")) + plugin_service.current_connection = FakeConnection("pooled") + plugin.notify_connection_changed({ConnectionEvent.INITIAL_CONNECTION}) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + assert plugin_service.connect_hosts == [fallback_host] + + +def test_reconnect_without_any_host_fails(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + plugin_service.current_connection = FakeConnection("pooled") + plugin.notify_connection_changed({ConnectionEvent.INITIAL_CONNECTION}) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError): + execute(plugin) + assert plugin_service.connect_hosts == [] + + +def test_failed_reconnect_keeps_previous_connection(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + connect_error = RuntimeError("host unreachable") + plugin_service.connect_error = connect_error + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + + with pytest.raises(ConnectionLifetimeFailedError) as raised: + execute(plugin) + + assert raised.value.__cause__ is connect_error + assert plugin_service.current_connection is first + assert not first.closed + assert plugin_service.evicted == [] + + +def test_failed_reconnect_is_retried_on_next_call(plugin_service, clock): + plugin = make_plugin(plugin_service, clock) + first = FakeConnection("first") + replacement = FakeConnection("replacement") + plugin_service.connect_error = RuntimeError("host unreachable") + open_connection(plugin, plugin_service, first) + clock.advance_ms(LIFETIME_MS) + with pytest.raises(ConnectionLifetimeFailedError): + execute(plugin) + + plugin_service.connect_error = None + plugin_service.replacements.append(replacement) + with pytest.raises(ConnectionLifetimeSuccessError): + execute(plugin) + + assert plugin_service.connect_hosts == [HOST, HOST] + assert plugin_service.current_connection is replacement + + +def test_connection_creation_times_ignore_unreferenceable_connections(): + times = ConnectionCreationTimes() + connection = UnreferenceableConnection("no-weakref") + + times.record(connection, 5) + + assert times.get(connection) is None + times.forget(connection) + + +def test_unreferenceable_connection_is_timed_from_first_use(plugin_service, clock): + plugin = make_plugin(plugin_service, clock, "close") + connection = UnreferenceableConnection("no-weakref") + open_connection(plugin, plugin_service, connection) + + # The connect could not be stamped, so the lifetime starts here. + clock.advance_ms(LIFETIME_MS) + assert execute(plugin) == "rows" + + clock.advance_ms(LIFETIME_MS - 1) + assert execute(plugin) == "rows" + + clock.advance_ms(1) + with pytest.raises(ConnectionLifetimeExpiredError): + execute(plugin) + assert connection.closed diff --git a/tests/unit/test_connection_provider.py b/tests/unit/test_connection_provider.py index bfda70ade..dd4e32ab7 100644 --- a/tests/unit/test_connection_provider.py +++ b/tests/unit/test_connection_provider.py @@ -181,6 +181,39 @@ def test_release_resources(connection_mock, set_provider_mock): set_provider_mock.release_resources.assert_called_once() +def test_evict_connection_without_evicting_provider(connection_mock, default_provider_mock): + connection_provider_manager = ConnectionProviderManager(default_provider_mock) + + assert not connection_provider_manager.evict_connection(connection_mock) + + +def test_evict_connection_uses_custom_provider_first(connection_mock, set_provider_mock, mocker): + default_provider = mocker.MagicMock(spec=SqlAlchemyPooledConnectionProvider) + set_provider_mock.evict_connection.return_value = True + ConnectionProviderManager.set_connection_provider(set_provider_mock) + + assert ConnectionProviderManager(default_provider).evict_connection(connection_mock) + default_provider.evict_connection.assert_not_called() + + +def test_evict_connection_falls_back_to_default_provider(connection_mock, set_provider_mock, mocker): + default_provider = mocker.MagicMock(spec=SqlAlchemyPooledConnectionProvider) + default_provider.evict_connection.return_value = True + set_provider_mock.evict_connection.return_value = False + ConnectionProviderManager.set_connection_provider(set_provider_mock) + + assert ConnectionProviderManager(default_provider).evict_connection(connection_mock) + set_provider_mock.evict_connection.assert_called_once_with(connection_mock) + + +def test_evict_connection_asks_a_shared_provider_once(connection_mock, set_provider_mock): + set_provider_mock.evict_connection.return_value = False + ConnectionProviderManager.set_connection_provider(set_provider_mock) + + assert not ConnectionProviderManager(set_provider_mock).evict_connection(connection_mock) + set_provider_mock.evict_connection.assert_called_once_with(connection_mock) + + def test_driver_connection_provider_accepted_strategies_returns_mapping(): from types import MappingProxyType diff --git a/tests/unit/test_sql_alchemy_pooled_connection_provider.py b/tests/unit/test_sql_alchemy_pooled_connection_provider.py index 9454a9a5f..8985bb1cb 100644 --- a/tests/unit/test_sql_alchemy_pooled_connection_provider.py +++ b/tests/unit/test_sql_alchemy_pooled_connection_provider.py @@ -12,6 +12,8 @@ # See the License for the specific language governing permissions and # limitations under the License. +import sqlite3 + import psycopg import pytest @@ -235,3 +237,116 @@ def test_release_resources(provider, mocker): pool1.dispose.assert_called_once() pool2.dispose.assert_called_once() assert 0 == len(SqlAlchemyPooledConnectionProvider._database_pools) + + +@pytest.fixture +def sqlite_pool_connect(host_info, mock_dialects): + # A real SQLAlchemy QueuePool over sqlite3, so eviction is checked against the pool itself. + provider = SqlAlchemyPooledConnectionProvider(pool_configurator=lambda _, __: {"pool_size": 1, "max_overflow": 0}) + physical_connections: list = [] + + def target_connect(**kwargs): + physical_connections.append(sqlite3.connect(":memory:")) + return physical_connections[-1] + + def connect(): + driver_dialect, database_dialect = mock_dialects + props = Properties({WrapperProperties.USER.name: "user1"}) + return provider.connect(target_connect, driver_dialect, database_dialect, host_info, props) + + yield provider, connect, physical_connections + provider.release_resources() + + +def is_open(physical_connection) -> bool: + try: + physical_connection.execute("SELECT 1") + return True + except sqlite3.ProgrammingError: + return False + + +def test_closed_connection_is_reused_without_eviction(sqlite_pool_connect): + _, connect, physical_connections = sqlite_pool_connect + + connect().close() + connect().close() + + assert len(physical_connections) == 1 + + +def test_evicted_connection_is_closed_instead_of_reused(sqlite_pool_connect): + provider, connect, physical_connections = sqlite_pool_connect + + conn = connect() + assert provider.evict_connection(conn) + conn.close() + assert not is_open(physical_connections[0]) + + connect().close() + assert len(physical_connections) == 2 + assert is_open(physical_connections[1]) + + +def test_evicted_connection_stays_usable_until_closed(sqlite_pool_connect): + provider, connect, physical_connections = sqlite_pool_connect + + conn = connect() + assert provider.evict_connection(conn) + + assert conn.cursor().execute("SELECT 1").fetchone() == (1,) + conn.close() + assert not is_open(physical_connections[0]) + + +def test_evict_connection_rejects_connections_it_cannot_evict(sqlite_pool_connect, mock_conn): + provider, connect, _ = sqlite_pool_connect + + conn = connect() + conn.close() + + assert not provider.evict_connection(conn) + assert not provider.evict_connection(mock_conn) + + +def test_evicting_a_connection_leaves_other_connections_and_pools_untouched(host_info, mock_dialects): + provider = SqlAlchemyPooledConnectionProvider(pool_configurator=lambda _, __: {"pool_size": 2, "max_overflow": 0}) + driver_dialect, database_dialect = mock_dialects + physical_connections: list = [] + + def target_connect(**kwargs): + physical_connections.append(sqlite3.connect(":memory:")) + return physical_connections[-1] + + def connect(user: str): + props = Properties({WrapperProperties.USER.name: user}) + return provider.connect(target_connect, driver_dialect, database_dialect, host_info, props) + + try: + evicted, same_pool, other_pool = connect("user1"), connect("user1"), connect("user2") + evicted_raw, same_pool_raw, other_pool_raw = physical_connections + assert provider.num_pools == 2 + + assert provider.evict_connection(evicted) + assert same_pool.cursor().execute("SELECT 1").fetchone() == (1,) + assert other_pool.cursor().execute("SELECT 1").fetchone() == (1,) + for conn in (evicted, same_pool, other_pool): + conn.close() + + assert not is_open(evicted_raw) + assert is_open(same_pool_raw) + assert is_open(other_pool_raw) + + # Both pools still hand out their kept connections; only the evicted one is replaced. + user1_connections = [connect("user1"), connect("user1")] + reused_other = connect("user2") + user1_raws = [conn.driver_connection for conn in user1_connections] + assert same_pool_raw in user1_raws + assert evicted_raw not in user1_raws + assert reused_other.driver_connection is other_pool_raw + assert len(physical_connections) == 4 + assert provider.num_pools == 2 + for conn in (*user1_connections, reused_other): + conn.close() + finally: + provider.release_resources() diff --git a/tests/unit/test_sqlalchemy_dialects.py b/tests/unit/test_sqlalchemy_dialects.py index 073535d72..10104f0ca 100644 --- a/tests/unit/test_sqlalchemy_dialects.py +++ b/tests/unit/test_sqlalchemy_dialects.py @@ -74,6 +74,22 @@ def test_is_disconnect_handles_full_failover_error_family(dialect_cls): assert d.is_disconnect(FailoverFailedError("x"), None, None) is True +@pytest.mark.parametrize( + "dialect_cls", [AwsWrapperMySQLConnectorDialect, AwsWrapperPGPsycopgDialect]) +def test_is_disconnect_handles_the_connection_lifetime_error_family(dialect_cls): + # Only a successful reconnect leaves the pool slot's wrapper usable; the + # close action and a failed reconnect leave nothing to reuse. None of + # these carry ``errno``, so they have to be classified before the + # upstream probe, same as the FailoverError family above. + from aws_advanced_python_wrapper.errors import ( + ConnectionLifetimeExpiredError, ConnectionLifetimeFailedError, + ConnectionLifetimeSuccessError) + d = dialect_cls.__new__(dialect_cls) # avoid full dialect __init__/dbapi + assert d.is_disconnect(ConnectionLifetimeSuccessError("x"), None, None) is False + assert d.is_disconnect(ConnectionLifetimeExpiredError("x"), None, None) is True + assert d.is_disconnect(ConnectionLifetimeFailedError("x"), None, None) is True + + # Registration uses the SA . convention: the wrapper plugs in # as a driver under the stock ``postgresql`` / ``mysql`` dialects, so the URL is # ``postgresql+aws_wrapper_psycopg`` / ``mysql+aws_wrapper_mysqlconnector``.