|
| 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