Skip to content

Commit 69c14e6

Browse files
committed
fix: build the host list provider from a verified database dialect
1 parent 8feea85 commit 69c14e6

25 files changed

Lines changed: 2254 additions & 646 deletions

‎aws_advanced_python_wrapper/aio/aurora_connection_tracker.py‎

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -602,7 +602,15 @@ def _parse_alias(alias: str) -> tuple:
602602
``[::1]:5432`` split correctly on the LAST colon. Falls back to
603603
port 5432 when the alias has no colon (or the port part isn't
604604
numeric).
605+
606+
The trailing slash is stripped first: host-list-change keys are
607+
``HostInfo.url``, which is ``host:port/``. Without this, ``int()``
608+
fails on ``"3306/"`` and the port silently became 5432, so a
609+
rebuilt key never matched the tracked one and a demoted MySQL
610+
writer's connections were never invalidated.
605611
"""
612+
if alias.endswith("/"):
613+
alias = alias[:-1]
606614
host_part, sep, port_part = alias.rpartition(":")
607615
if not sep:
608616
# No colon -> treat entire alias as host, port defaults.

‎aws_advanced_python_wrapper/aio/dialect_utils.py‎

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -171,6 +171,33 @@ async def _execute_scalar_query(
171171
except Exception: # noqa: BLE001 - cursor close best-effort
172172
pass
173173

174+
@staticmethod
175+
async def fetch_one(conn: Any, query: str) -> Optional[tuple]:
176+
"""Run the provided query and fetch the first row.
177+
"""
178+
return await AsyncDialectUtils._execute_scalar_query(conn, query)
179+
180+
@staticmethod
181+
async def fetch_all(conn: Any, query: str) -> list:
182+
"""Run the provided query and fetch all rows. Returns an empty list on no results.
183+
"""
184+
cursor_ret = conn.cursor()
185+
cursor = await cursor_ret if asyncio.iscoroutine(cursor_ret) else cursor_ret
186+
try:
187+
await cursor.execute(query)
188+
return list(await cursor.fetchall())
189+
finally:
190+
# Call close on the curosor if it has a close method.
191+
# Some async DBAPI implementations may not have a close method on their cursor.
192+
close = getattr(cursor, "close", None)
193+
if close is not None:
194+
try:
195+
result = close()
196+
if asyncio.iscoroutine(result):
197+
await result
198+
except Exception: # noqa: BLE001 - cursor close best-effort
199+
pass
200+
174201
@staticmethod
175202
async def _execute_is_reader_query(
176203
conn: Any,

‎aws_advanced_python_wrapper/aio/gdb_failover_plugin.py‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -260,8 +260,8 @@ async def _failover_with_mode(
260260
# deadline (validated on Aurora: 2592 reconnects to the stale
261261
# host over 5 min, then timeout).
262262
# STRICT_WRITER means "reconnect to the new writer" -- exactly
263-
# failover_v2's job. (Requires the real topology provider, i.e.
264-
# gdb_failover present in wrapper._TOPOLOGY_REQUIRING_PLUGINS.)
263+
# failover_v2's job. (Requires a real topology provider, which
264+
# the Global Aurora dialects supply.)
265265
await self._failover_writer(
266266
self._plugin_service.all_hosts, driver_dialect, deadline, None)
267267
case GdbFailoverMode.STRICT_HOME_READER:

‎aws_advanced_python_wrapper/aio/host_list_provider.py‎

Lines changed: 140 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -141,6 +141,13 @@ def initial_connection_host_info(self, value: HostInfo) -> None:
141141
def is_static_host_list_provider(self) -> bool:
142142
...
143143

144+
@property
145+
def is_dialect_confirmed(self) -> bool:
146+
...
147+
148+
def get_target_driver_func(self) -> Optional[Callable]:
149+
...
150+
144151

145152
class AsyncStaticHostListProvider:
146153
"""Static host list -- one host built from connection props.
@@ -221,7 +228,9 @@ def __init__(
221228
cluster_id: Optional[str] = None,
222229
default_port: int = 5432,
223230
monitor_connection_factory: Optional[
224-
Callable[[], Awaitable[Any]]] = None) -> None:
231+
Callable[[], Awaitable[Any]]] = None,
232+
provider_service: Optional[AsyncHostListProviderService] = None) -> None:
233+
self._provider_service = provider_service
225234
self._props = props
226235
self._driver_dialect = driver_dialect
227236
self._topology_query = topology_query
@@ -247,6 +256,22 @@ def __init__(
247256
# the wrapper once the plugin service exists -- see
248257
# aio/wrapper.py and cluster_topology_monitor.build_probe_host.
249258
self._probe_host: Optional[Callable[..., Any]] = None
259+
self._instance_host_pattern, self._instance_pattern_port = \
260+
self._resolve_instance_pattern()
261+
# Resolve initial host
262+
port_raw = props.get("port")
263+
self._initial_hosts: Topology = (
264+
HostInfo(
265+
host=props.get("host", ""),
266+
port=int(port_raw) if port_raw is not None else default_port,
267+
role=HostRole.WRITER),)
268+
269+
def _is_dialect_confirmed(self) -> bool:
270+
"""Whether the database dialect is finalized and whether topology may be queried yet.
271+
"""
272+
if self._provider_service is None:
273+
return True
274+
return self._provider_service.is_dialect_confirmed
250275

251276
def set_probe_host(self, probe_host: Callable[..., Any]) -> None:
252277
"""Arm panic-mode writer discovery on the (future) topology monitor.
@@ -258,25 +283,6 @@ def set_probe_host(self, probe_host: Callable[..., Any]) -> None:
258283
"""
259284
self._probe_host = probe_host
260285

261-
def reconfigure_topology_query(
262-
self, topology_query: str, default_port: Optional[int] = None) -> None:
263-
"""Re-point the provider at a (post-connect) resolved dialect's query.
264-
265-
The provider is built BEFORE the connection exists, so an
266-
instance-endpoint MySQL connection starts with the PostgreSQL-default
267-
topology query + port (the ctor default). Once the database dialect is
268-
resolved/upgraded to the Aurora MySQL dialect we swap in its topology
269-
query and the MySQL port so discovery actually works. Clears the cache
270-
so the next refresh re-probes with the new query (any cached PG-query
271-
result is stale/empty).
272-
"""
273-
if topology_query:
274-
self._topology_query = topology_query
275-
if default_port:
276-
self._default_port = default_port
277-
self._topology_cache = None
278-
self._last_refresh_ns = 0
279-
280286
@staticmethod
281287
def _derive_cluster_id(props: Properties) -> str:
282288
# Only treat `cluster_id` as explicit when present in the props dict;
@@ -325,6 +331,11 @@ async def force_refresh(self, connection: Optional[Any] = None) -> Topology:
325331
return self._topology_cache
326332
return ()
327333

334+
if not self._is_dialect_confirmed():
335+
# No topology query and no monitor until the dialect is
336+
# confirmed. Report the host from the connection properties in the meantime.
337+
return self._topology_cache or self._initial_hosts
338+
328339
async with self._refresh_lock:
329340
monitor = self._get_or_create_monitor()
330341
if monitor is None:
@@ -366,6 +377,10 @@ async def force_monitoring_refresh(
366377
querying through a caller connection. Falls back to
367378
:meth:`force_refresh` when no monitor can be built (static dialects).
368379
"""
380+
if not self._is_dialect_confirmed():
381+
# No topology query and no monitor until the dialect is
382+
# confirmed. Report the host from the connection properties in the meantime.
383+
return self._topology_cache or self._initial_hosts
369384
monitor = self._get_or_create_monitor()
370385
if monitor is None:
371386
return await self.force_refresh(self._last_conn)
@@ -507,7 +522,7 @@ def _rows_to_topology(self, rows: List[tuple]) -> Topology:
507522
# The instance host pattern may carry an explicit ``:port`` (proxied
508523
# test endpoints do); use it for every topology host. See
509524
# :meth:`_resolve_instance_pattern`.
510-
_, pattern_port = self._resolve_instance_pattern()
525+
pattern_port = self._instance_pattern_port
511526
port = pattern_port if pattern_port is not None else self._default_port
512527
# Dedup by resolved host (a row may repeat), matching sync
513528
# AuroraTopologyUtils._process_query_results (:603-606).
@@ -573,6 +588,11 @@ def _rows_to_topology(self, rows: List[tuple]) -> Topology:
573588
def _resolve_instance_pattern(self) -> Tuple[Optional[str], Optional[int]]:
574589
"""Resolve the instance host pattern and its explicit port (if any).
575590
591+
Called once, from ``__init__``; read afterwards through
592+
``_instance_host_pattern`` / ``_instance_pattern_port``. Keep it that
593+
way -- it validates (and so can raise) and builds ``RdsUtils``, which
594+
is why it does not belong on the per-row path.
595+
576596
Returns ``(host_pattern_with_'?', port)``; ``port`` is ``None`` when the
577597
pattern carries no explicit ``:port`` suffix.
578598
@@ -645,7 +665,7 @@ def _host_from_server_id(self, server_id: str) -> str:
645665
ID yields a non-resolvable name, so every reader/failover connect to a
646666
topology host fails with "failed to resolve host '<server_id>'".
647667
"""
648-
host_pattern, _ = self._resolve_instance_pattern()
668+
host_pattern = self._instance_host_pattern
649669
if host_pattern:
650670
return host_pattern.replace("?", server_id)
651671
return server_id
@@ -708,6 +728,7 @@ def __init__(
708728
monitor_connection_factory: Optional[
709729
Callable[[], Awaitable[Any]]] = None,
710730
writer_host_column_index: int = 0,
731+
provider_service: Optional[AsyncHostListProviderService] = None,
711732
) -> None:
712733
super().__init__(
713734
props=props,
@@ -716,6 +737,7 @@ def __init__(
716737
cluster_id=cluster_id,
717738
default_port=default_port,
718739
monitor_connection_factory=monitor_connection_factory,
740+
provider_service=provider_service,
719741
)
720742
self._writer_host_query = writer_host_query
721743
self._host_id_query = host_id_query
@@ -859,6 +881,7 @@ def __init__(
859881
default_port: int = 5432,
860882
monitor_connection_factory: Optional[
861883
Callable[[], Awaitable[Any]]] = None,
884+
provider_service: Optional[AsyncHostListProviderService] = None,
862885
) -> None:
863886
super().__init__(
864887
props=props,
@@ -867,6 +890,7 @@ def __init__(
867890
cluster_id=cluster_id,
868891
default_port=default_port,
869892
monitor_connection_factory=monitor_connection_factory,
893+
provider_service=provider_service,
870894
)
871895
if instance_templates_by_region is None:
872896
raw = WrapperProperties.GLOBAL_CLUSTER_INSTANCE_HOST_PATTERNS.get(
@@ -954,3 +978,97 @@ def _rows_to_topology(self, rows: List[tuple]) -> Topology:
954978
# Writer first, readers after -- matches the other async providers.
955979
hosts.sort(key=lambda h: 0 if h.role == HostRole.WRITER else 1)
956980
return tuple(hosts)
981+
982+
983+
def build_monitor_connection_factory(
984+
provider_service: AsyncHostListProviderService,
985+
props: Properties) -> Callable[[], Awaitable[Any]]:
986+
"""Build the factory the topology monitor uses for its own connection.
987+
"""
988+
from aws_advanced_python_wrapper.utils.properties import (Properties,
989+
PropertiesUtils)
990+
991+
async def _connect() -> Any:
992+
target_func = provider_service.get_target_driver_func()
993+
if target_func is None:
994+
raise AwsWrapperError(
995+
Messages.get_formatted(
996+
"HostListProvider.MonitorConnectionNoTargetDriverFunc",
997+
type(provider_service).__name__))
998+
host_info = (provider_service.initial_connection_host_info
999+
or provider_service.current_host_info)
1000+
if host_info is None:
1001+
raise AwsWrapperError(
1002+
Messages.get_formatted(
1003+
"HostListProvider.MonitorConnectionNoSeedHost",
1004+
type(provider_service).__name__))
1005+
monitoring_props = PropertiesUtils.create_topology_monitoring_properties(
1006+
Properties(dict(props)))
1007+
return await provider_service.driver_dialect.connect(
1008+
host_info, monitoring_props, target_func)
1009+
1010+
return _connect
1011+
1012+
1013+
def create_static_provider(
1014+
provider_service: AsyncHostListProviderService,
1015+
props: Properties) -> AsyncHostListProvider:
1016+
"""Supplier body for dialects with no topology: a single seed host."""
1017+
return AsyncStaticHostListProvider(props)
1018+
1019+
1020+
def create_aurora_provider(
1021+
provider_service: AsyncHostListProviderService,
1022+
props: Properties,
1023+
*,
1024+
topology_query: str,
1025+
default_port: int) -> AsyncHostListProvider:
1026+
"""Supplier body for the Aurora topology dialects."""
1027+
return AsyncAuroraHostListProvider(
1028+
props,
1029+
provider_service.driver_dialect,
1030+
topology_query=topology_query,
1031+
default_port=default_port,
1032+
monitor_connection_factory=build_monitor_connection_factory(
1033+
provider_service, props),
1034+
provider_service=provider_service)
1035+
1036+
1037+
def create_global_aurora_provider(
1038+
provider_service: AsyncHostListProviderService,
1039+
props: Properties,
1040+
*,
1041+
topology_query: str,
1042+
default_port: int) -> AsyncHostListProvider:
1043+
"""Supplier body for the Aurora Global Database dialects."""
1044+
return AsyncGlobalAuroraHostListProvider(
1045+
props,
1046+
provider_service.driver_dialect,
1047+
topology_query=topology_query,
1048+
default_port=default_port,
1049+
monitor_connection_factory=build_monitor_connection_factory(
1050+
provider_service, props),
1051+
provider_service=provider_service)
1052+
1053+
1054+
def create_multi_az_provider(
1055+
provider_service: AsyncHostListProviderService,
1056+
props: Properties,
1057+
*,
1058+
writer_host_query: str,
1059+
topology_query: str,
1060+
host_id_query: str,
1061+
default_port: int,
1062+
writer_host_column_index: int = 0) -> AsyncHostListProvider:
1063+
"""Supplier body for the RDS Multi-AZ DB cluster dialects."""
1064+
return AsyncMultiAzHostListProvider(
1065+
props,
1066+
provider_service.driver_dialect,
1067+
writer_host_query=writer_host_query,
1068+
topology_query=topology_query,
1069+
host_id_query=host_id_query,
1070+
default_port=default_port,
1071+
writer_host_column_index=writer_host_column_index,
1072+
monitor_connection_factory=build_monitor_connection_factory(
1073+
provider_service, props),
1074+
provider_service=provider_service)

0 commit comments

Comments
 (0)