Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
233 changes: 79 additions & 154 deletions aws_advanced_python_wrapper/aio/aurora_connection_tracker.py

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,6 @@
so auth plugins (IAM, Secrets, Federated, Okta) and connection
tracker re-apply on the new connection just like a user-driven
connect.
* ``initial_connection_host_info`` is set on the plugin service directly:
``AsyncPluginServiceImpl`` implements ``AsyncHostListProviderService``
and ``aio/wrapper.py`` passes it as the host list provider service, so
the two are the same object.
"""

from __future__ import annotations
Expand Down Expand Up @@ -102,8 +98,6 @@ def init_host_provider(
props: Properties,
host_list_provider_service: Any,
init_host_provider_func: Callable) -> None:
# Sync captures the service here; async sets initial_connection_host_info on the plugin
# service directly so there is nothing to hold.
init_host_provider_func()

async def connect(
Expand Down Expand Up @@ -139,13 +133,13 @@ async def connect(

if role_to_verify is None:
# No verification required.
self._set_initial_connection_host_info(is_initial_connection, candidate_host)
self._plugin_service.routed_host_info = candidate_host
return candidate_conn

conn_role = await self._plugin_service.get_host_role(candidate_conn)
if conn_role == role_to_verify:
# Verification succeeded.
self._set_initial_connection_host_info(is_initial_connection, candidate_host)
self._plugin_service.routed_host_info = candidate_host
return candidate_conn

# Verification failed. Retry, unless a reader was requested but the cluster has no readers.
Expand All @@ -157,7 +151,7 @@ async def connect(
logger.debug(
"AuroraInitialConnectionStrategyPlugin.VerifyReaderConfiguredButNoReadersExist",
WrapperProperties.VERIFY_OPENED_CONNECTION_TYPE.name)
self._set_initial_connection_host_info(is_initial_connection, candidate_host)
self._plugin_service.routed_host_info = candidate_host
return candidate_conn

logger.debug(
Expand All @@ -171,7 +165,7 @@ async def connect(

if candidate_host is not None:
self._plugin_service.set_availability(
candidate_host.as_aliases(), HostAvailability.UNAVAILABLE)
candidate_host, HostAvailability.UNAVAILABLE)

if self._plugin_service.is_network_exception(error=e):
# Retry connection.
Expand Down Expand Up @@ -460,13 +454,6 @@ def _has_hosts(self) -> bool:
def _has_readers(self) -> bool:
return any(host.role == HostRole.READER for host in self._plugin_service.all_hosts)

def _set_initial_connection_host_info(
self, is_initial_connection: bool, host_info: Optional[HostInfo]):
# AsyncPluginServiceImpl implements AsyncHostListProviderService and is passed as the host
# list provider service, so this is the same attribute sync writes through that service.
if is_initial_connection and host_info is not None:
self._plugin_service.initial_connection_host_info = host_info

async def _close_connection(
self, connection: Optional[Any], driver_dialect: AsyncDriverDialect) -> None:
if connection is None:
Expand Down
1 change: 0 additions & 1 deletion aws_advanced_python_wrapper/aio/blue_green_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,6 @@ async def apply(
rerouted_host_info = copy(self._substitute_host_info)
rerouted_host_info.host_id = iam_host.host_id
rerouted_host_info.availability = HostAvailability.AVAILABLE
rerouted_host_info.add_alias(iam_host.host)

rerouted_props = copy(props)
WrapperProperties.IAM_HOST.set(rerouted_props, iam_host.host)
Expand Down
39 changes: 20 additions & 19 deletions aws_advanced_python_wrapper/aio/cluster_topology_monitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ def __init__(
self._is_verified_writer_connection: bool = False
self._verified_writer_conn: Optional[Any] = None
self._verified_writer_host_info: Optional[HostInfo] = None
self._submitted_host_aliases: Set[str] = set()
self._submitted_hosts: Set[str] = set()
self._probe_tasks: Dict[str, asyncio.Task] = {}
self._writer_found_event: asyncio.Event = asyncio.Event()

Expand Down Expand Up @@ -375,17 +375,13 @@ def _role_corrected(self, topology: Topology) -> Topology:
if h.role != want_role:
fixed = copy.copy(h)
fixed.role = want_role
for alias in h.as_aliases():
fixed.add_alias(alias)
corrected.append(fixed)
changed = True
else:
corrected.append(h)
if not found:
writer_row = copy.copy(verified)
writer_row.role = HostRole.WRITER
for alias in verified.as_aliases():
writer_row.add_alias(alias)
corrected.append(writer_row)
changed = True
if changed:
Expand Down Expand Up @@ -429,12 +425,17 @@ async def _wait_for_tick(self, interval: float) -> None:
timeout=interval,
return_when=asyncio.FIRST_COMPLETED)
finally:
for waiter in (stop_waiter, tick_waiter):
if not waiter.done():
waiter.cancel()
await asyncio.gather(
stop_waiter, tick_waiter, return_exceptions=True)
self._request_tick.clear()
# An application that closes its loop without releasing resources
# leaves this parked. Cancelling or draining a waiter whose loop is
# gone raises, and here that would surface as an unraisable
# exception from the garbage collector.
if not stop_waiter.get_loop().is_closed():
for waiter in (stop_waiter, tick_waiter):
if not waiter.done():
waiter.cancel()
await asyncio.gather(
stop_waiter, tick_waiter, return_exceptions=True)
self._request_tick.clear()

async def _harvest_verified_writer(self) -> None:
"""Promote the panic-found verified-writer connection to the monitor's
Expand All @@ -451,7 +452,7 @@ async def _harvest_verified_writer(self) -> None:
if pending:
await asyncio.gather(*pending, return_exceptions=True)
self._probe_tasks.clear()
self._submitted_host_aliases.clear()
self._submitted_hosts.clear()
if conn is None:
return
if self._connection_factory is None:
Expand Down Expand Up @@ -480,23 +481,23 @@ def _should_panic(self) -> bool:

def _spawn_panic_probes(self) -> None:
"""Spawn probe tasks for each host in ``last_topology`` not already
submitted. Deduped by ``host_info.as_alias()``.
submitted. Deduped by ``host_info.get_host_and_port()``.
"""
# Opportunistic cleanup of finished task refs.
finished = [k for k, t in self._probe_tasks.items() if t.done()]
for k in finished:
self._probe_tasks.pop(k, None)
# Release dedup slot so a retry can happen on a later tick if
# the earlier probe failed/returned non-writer.
self._submitted_host_aliases.discard(k)
self._submitted_hosts.discard(k)

for host_info in self._last_topology:
alias = host_info.as_alias()
if alias in self._submitted_host_aliases:
key = host_info.get_host_and_port()
if key in self._submitted_hosts:
continue
self._submitted_host_aliases.add(alias)
self._submitted_hosts.add(key)
task = asyncio.create_task(self._probe_and_report(host_info))
self._probe_tasks[alias] = task
self._probe_tasks[key] = task

# Aurora PG briefly rejects IAM/PAM auth on instances mid-promotion
# (the PAM service restarts during the writer-role swap). Mirror the
Expand Down Expand Up @@ -833,7 +834,7 @@ async def _reset(self) -> None:
if pending:
await asyncio.gather(*pending, return_exceptions=True)
self._probe_tasks.clear()
self._submitted_host_aliases.clear()
self._submitted_hosts.clear()
await self._drop_owned_connection()
if self._verified_writer_conn is not None:
await self._close_best_effort(self._verified_writer_conn)
Expand Down
11 changes: 5 additions & 6 deletions aws_advanced_python_wrapper/aio/default_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,18 +147,17 @@ async def force_connect(
def _post_connect_bookkeeping(self, host_info: HostInfo, connection_provider: Any) -> None:
"""Post-connect bookkeeping after a successful connect.

Sync parity: ``DefaultPlugin._connect`` (default_plugin.py:80-82) marks
every alias of the just-connected host AVAILABLE and lets the service
re-pick the driver dialect for the provider that produced the
connection (a no-op on async today). The DATABASE-dialect upgrade
Sync parity: ``DefaultPlugin._connect`` marks the just-connected host
AVAILABLE and lets the service re-pick the driver dialect for the
provider that produced the connection (a no-op on async today).
The DATABASE-dialect upgrade
(sync ``plugin_service.update_dialect(conn)``) is invoked by the
connect/force_connect callers right after this bookkeeping, mirroring
sync's ordering; it is async so it cannot live in this sync helper.
"""
if self._plugin_service is None:
return
self._plugin_service.set_availability(
host_info.as_aliases(), HostAvailability.AVAILABLE)
self._plugin_service.set_availability(host_info, HostAvailability.AVAILABLE)
self._plugin_service.update_driver_dialect(connection_provider)

async def execute(
Expand Down
24 changes: 14 additions & 10 deletions aws_advanced_python_wrapper/aio/dialect_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@
from __future__ import annotations

import asyncio
from typing import TYPE_CHECKING, Any, Optional
from typing import TYPE_CHECKING, Any, Optional, Tuple

from aws_advanced_python_wrapper.errors import (AwsWrapperError,
QueryTimeoutError)
Expand Down Expand Up @@ -83,12 +83,14 @@ async def get_instance_id(
conn: Any,
driver_dialect: AsyncDriverDialect,
host_id_query: str,
timeout_sec: float = 5.0) -> Optional[str]:
"""Run the dialect's ``host_id_query`` to learn the Aurora
instance identifier ``conn`` is bound to. Returns ``None`` on
empty result or query failure (best-effort; callers fall back
to topology resolution by host_id). Mirrors sync
DialectUtils.get_instance_id at database_dialect.py.
timeout_sec: float = 5.0) -> Optional[Tuple[str, str]]:
"""Run the dialect's ``host_id_query`` for the instance ``conn`` is
bound to, returning ``(instance_id, instance_name)``.

Aurora returns the same value in both columns. Multi-AZ returns a
numeric id and a short instance name, and callers match on either.
Returns ``None`` on an empty result or a query failure, since
identification is best-effort.
"""
was_in_txn = await AsyncDialectUtils._safe_in_transaction(
conn, driver_dialect)
Expand All @@ -107,10 +109,12 @@ async def get_instance_id(
await AsyncDialectUtils._restore_idle(conn, was_in_txn)
if not result:
return None
first = result[0]
if first is None:
instance_id = result[0]
if instance_id is None:
return None
return str(first)
# A single-column result repeats the id, as the Aurora query does.
instance_name = result[1] if len(result) > 1 and result[1] is not None else instance_id
return str(instance_id), str(instance_name)

@staticmethod
async def _safe_in_transaction(
Expand Down
12 changes: 6 additions & 6 deletions aws_advanced_python_wrapper/aio/failover_plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ async def _connect_with_failover(
if not self._should_failover(e):
raise
self._plugin_service.set_availability(
host_info.as_aliases(), HostAvailability.UNAVAILABLE)
host_info, HostAvailability.UNAVAILABLE)
await self._do_failover(driver_dialect)
else:
# Known-dead target: refresh topology and fail over without
Expand Down Expand Up @@ -424,7 +424,7 @@ async def _do_failover(self, driver_dialect: AsyncDriverDialect) -> None:
failed_host = self._plugin_service.current_host_info
if failed_host is not None:
self._plugin_service.set_availability(
failed_host.as_aliases(), HostAvailability.UNAVAILABLE)
failed_host, HostAvailability.UNAVAILABLE)

# Invalidate the current (likely broken) connection before
# attempting failover so any pool-proxied target is evicted from
Expand Down Expand Up @@ -556,7 +556,7 @@ async def _failover_reader_impl(
self._open_connection(candidate, driver_dialect), deadline)
except Exception as e: # noqa: BLE001
self._plugin_service.set_availability(
candidate.as_aliases(), HostAvailability.UNAVAILABLE)
candidate, HostAvailability.UNAVAILABLE)
last_error = e
if candidate in remaining:
remaining.remove(candidate)
Expand All @@ -578,7 +578,7 @@ async def _failover_reader_impl(
if role == HostRole.READER or self._mode != FailoverMode.STRICT_READER:
verified = HostInfo(candidate.host, candidate.port, role)
self._plugin_service.set_availability(
candidate.as_aliases(), HostAvailability.AVAILABLE)
candidate, HostAvailability.AVAILABLE)
await self._plugin_service.set_current_connection(new_conn, verified)
if self._failover_reader_completed is not None:
self._failover_reader_completed.inc()
Expand Down Expand Up @@ -608,7 +608,7 @@ async def _failover_reader_impl(
self._open_connection(original_writer, driver_dialect), deadline)
except Exception as e: # noqa: BLE001
self._plugin_service.set_availability(
original_writer.as_aliases(), HostAvailability.UNAVAILABLE)
original_writer, HostAvailability.UNAVAILABLE)
last_error = e
else:
role = await self._probe_role(new_conn)
Expand All @@ -620,7 +620,7 @@ async def _failover_reader_impl(
verified = HostInfo(
original_writer.host, original_writer.port, role)
self._plugin_service.set_availability(
original_writer.as_aliases(), HostAvailability.AVAILABLE)
original_writer, HostAvailability.AVAILABLE)
await self._plugin_service.set_current_connection(
new_conn, verified)
if self._failover_reader_completed is not None:
Expand Down
15 changes: 12 additions & 3 deletions aws_advanced_python_wrapper/aio/host_list_provider.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,8 @@
AsyncAuroraTopologyUtils, AsyncGlobalAuroraTopologyUtils,
AsyncMultiAzTopologyUtils, AsyncTopologyUtils)
from aws_advanced_python_wrapper.errors import AwsWrapperError
from aws_advanced_python_wrapper.host_availability import \
create_host_availability_strategy
from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole
from aws_advanced_python_wrapper.utils import services_container
from aws_advanced_python_wrapper.utils.events import MonitorStopEvent
Expand Down Expand Up @@ -152,14 +154,21 @@ def __init__(self, props: Properties) -> None:
host = props.get("host", "")
port_raw = props.get("port")
port = int(port_raw) if port_raw is not None else -1
self._host_info = HostInfo(host=host, port=port, role=HostRole.WRITER)
self._host_info = HostInfo(
host=host, port=port, role=HostRole.WRITER,
host_availability_strategy=create_host_availability_strategy(props))
self._cluster_id = f"static:{host}:{port}"

def _host(self) -> HostInfo:
"""A copy, so marking the returned host unavailable does not mark the
one this provider hands to every later caller."""
return copy(self._host_info)

async def refresh(self, connection: Optional[Any] = None) -> Topology:
return (self._host_info,)
return (self._host(),)

async def force_refresh(self, connection: Optional[Any] = None) -> Topology:
return (self._host_info,)
return (self._host(),)

def get_cluster_id(self) -> str:
return self._cluster_id
Expand Down
Loading
Loading