Skip to content

Commit 5825d73

Browse files
authored
refactor: aio storage and monitor services (#1295)
1 parent f9aa187 commit 5825d73

22 files changed

Lines changed: 2015 additions & 992 deletions

‎aws_advanced_python_wrapper/aio/cleanup.py‎

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,18 @@ def register_shutdown_hook(hook: Callable[[], Awaitable[None]]) -> None:
7171
_registered_shutdown_hooks.append(hook)
7272

7373

74+
def unregister_shutdown_hook(hook: Callable[[], Awaitable[None]]) -> None:
75+
"""Drop a hook once the object that registered it has torn itself down.
76+
77+
The registry is process-global and otherwise only emptied on release, so
78+
a caller that registers one hook per instance has to remove it.
79+
"""
80+
try:
81+
_registered_shutdown_hooks.remove(hook)
82+
except ValueError:
83+
pass
84+
85+
7486
def clear_shutdown_hooks() -> None:
7587
"""Testing helper: drop all registered hooks without awaiting them."""
7688
_registered_shutdown_hooks.clear()

‎aws_advanced_python_wrapper/aio/cluster_topology_monitor.py‎

Lines changed: 228 additions & 55 deletions
Large diffs are not rendered by default.

‎aws_advanced_python_wrapper/aio/host_list_provider.py‎

Lines changed: 196 additions & 571 deletions
Large diffs are not rendered by default.

‎aws_advanced_python_wrapper/aio/plugin_service.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -716,6 +716,10 @@ async def update_database_dialect(self, connection: Any) -> None:
716716
# driver dialect, provider service, monitor factory) comes from this
717717
# plugin service and is identical either way.
718718
#
719+
# They live on the provider's topology utils, which is where the
720+
# dialect's SQL and port landed; only the static provider has no utils
721+
# at all.
722+
#
719723
# Kept in step with the suppliers by
720724
# test_provider_identity_covers_every_dialect_supplied_argument, which
721725
# fails if a supplier gains an argument this list does not name.
@@ -732,11 +736,12 @@ def _provider_identity(provider: Any) -> tuple:
732736
"""What makes a provider the right one for a dialect.
733737
734738
``getattr`` with a default rather than direct access: the static
735-
(no-topology) provider carries no topology query or port, and only
736-
the Multi-AZ provider carries the writer/host-id queries.
739+
(no-topology) provider has no topology utils, and only the Multi-AZ
740+
utils carry the writer/host-id queries.
737741
"""
742+
utils = getattr(provider, "_topology_utils", None)
738743
return (type(provider),) + tuple(
739-
getattr(provider, attr, None)
744+
getattr(utils, attr, None)
740745
for attr in AsyncPluginServiceImpl._PROVIDER_DIALECT_ATTRS)
741746

742747
async def _update_host_list_provider(self, connection: Any) -> None:
Lines changed: 128 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,128 @@
1+
# Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
2+
#
3+
# Licensed under the Apache License, Version 2.0 (the "License").
4+
# You may not use this file except in compliance with the License.
5+
# You may obtain a copy of the License at
6+
#
7+
# http://www.apache.org/licenses/LICENSE-2.0
8+
#
9+
# Unless required by applicable law or agreed to in writing, software
10+
# distributed under the License is distributed on an "AS IS" BASIS,
11+
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12+
# See the License for the specific language governing permissions and
13+
# limitations under the License.
14+
15+
"""Shared access to the stored async topology.
16+
17+
The host list provider and the topology monitor both read and write the
18+
cluster's topology, and they key the storage service and the monitor service
19+
the same way, so the key and the accessors live here rather than on either of
20+
them.
21+
"""
22+
23+
from __future__ import annotations
24+
25+
import asyncio
26+
import copy
27+
import threading
28+
import weakref
29+
from typing import Optional, Tuple
30+
from uuid import uuid4
31+
32+
from aws_advanced_python_wrapper.hostinfo import HostInfo
33+
from aws_advanced_python_wrapper.hostinfo import Topology as StoredTopology
34+
from aws_advanced_python_wrapper.utils import services_container
35+
36+
# The storage service is keyed by type, and the sync Topology alias is a
37+
# forward reference, so an async-side alias is a different object. Only the
38+
# sync alias is registered, so keying on anything else writes to an
39+
# unregistered cache.
40+
41+
TopologyKey = Tuple[str, str]
42+
43+
_loop_tokens: weakref.WeakKeyDictionary[asyncio.AbstractEventLoop, str] = \
44+
weakref.WeakKeyDictionary()
45+
# setdefault on a WeakKeyDictionary is not documented atomic, and two threads
46+
# minting competing tokens for one loop would split its topology entries.
47+
_loop_tokens_lock = threading.Lock()
48+
49+
50+
def loop_token(loop: asyncio.AbstractEventLoop) -> str:
51+
"""A stable identity for ``loop``, for use in a storage or monitor key.
52+
53+
Deliberately not ``id(loop)``: addresses are reused, so a fresh loop could
54+
be handed a dead loop's entry, including HostInfo objects a previous run
55+
marked unavailable.
56+
"""
57+
with _loop_tokens_lock:
58+
try:
59+
token = _loop_tokens.get(loop)
60+
if token is None:
61+
token = uuid4().hex
62+
_loop_tokens[loop] = token
63+
return token
64+
except TypeError:
65+
# Some accelerated loops (Cython extension types) are not
66+
# weak-referenceable, and the lookup raises as readily as the
67+
# assignment. Falling back to the address is only safe because
68+
# every consumer re-checks liveness and replaces a dead entry, so
69+
# a recycled address is detected rather than silently reused.
70+
return f"id:{id(loop)}"
71+
72+
73+
def topology_key(cluster_id: str) -> Optional[TopologyKey]:
74+
"""The key for this cluster's topology on the running event loop.
75+
76+
Compound because the store is process-global and shared with the sync
77+
provider, which keys by bare cluster id. ``None`` off-loop: the key names
78+
a loop, so there is no entry to read or invalidate.
79+
"""
80+
try:
81+
loop = asyncio.get_running_loop()
82+
except RuntimeError:
83+
return None
84+
return (cluster_id, loop_token(loop))
85+
86+
87+
def get_topology(
88+
key: Optional[TopologyKey]) -> Optional[StoredTopology]:
89+
"""Read the stored topology as fresh HostInfo objects.
90+
91+
The entry is shared by every provider on this cluster and loop, and
92+
availability is written into a HostInfo in place, so handing out the
93+
stored objects would let one connection's availability marking rewrite
94+
the hosts another connection is holding.
95+
"""
96+
if key is None:
97+
return None
98+
stored = services_container.get_storage_service().get(StoredTopology, key)
99+
if stored is None:
100+
return None
101+
return tuple(_copy_host(host) for host in stored)
102+
103+
104+
def _copy_host(host: HostInfo) -> HostInfo:
105+
"""Copy a host, restoring what ``HostInfo.__copy__`` drops.
106+
107+
It carries neither the aliases, which match a live connection back to its
108+
topology row, nor the availability strategy, which decides when a host
109+
marked unavailable becomes usable again.
110+
"""
111+
clone = copy.copy(host)
112+
clone.host_availability_strategy = host.host_availability_strategy
113+
aliases = host.aliases
114+
if aliases:
115+
clone.add_alias(*aliases)
116+
return clone
117+
118+
119+
def put_topology(key: Optional[TopologyKey], topology: StoredTopology) -> None:
120+
if key is None or not topology:
121+
return
122+
services_container.get_storage_service().put(StoredTopology, key, topology)
123+
124+
125+
def remove_topology(key: Optional[TopologyKey]) -> None:
126+
if key is None:
127+
return
128+
services_container.get_storage_service().remove(StoredTopology, key)

0 commit comments

Comments
 (0)