From 539f71f99b5e41ea0254bb2fada37c198b3c7e39 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Sat, 7 Nov 2026 09:07:44 -0700 Subject: [PATCH 1/4] test: reproduce Blue/Green switchover hang and unmatched routings (#1352) Add unit tests that reproduce the two defects reported in #1352. test_blue_green_switchover_loops.py suspends a sync execute or connect while the switchover is IN_PROGRESS and then moves the status on. On main the call keeps re-selecting the stale suspend routing and never returns, even with a short bg_connect_timeout_ms; an async test checks that the aio loop still resumes. test_blue_green_routing_match.py and test_aio_blue_green_routing_match.py build routings with the endpoints the status provider builds. On main none of them match, because is_match compares with HostInfo.url and its trailing slash, so a connect during PREPARATION or POST goes to the host name instead of the substituted IP. Guards check that another host, port or role still doesn't match. The 8 reproduction tests are strict xfails, so the suite stays green on main. The fix for #1352 must remove the markers and update test_substitute_connect_routing_is_match_by_url, which asserts the current is_match behaviour. --- .../unit/test_aio_blue_green_routing_match.py | 131 +++++++++ tests/unit/test_blue_green_routing_match.py | 160 +++++++++++ .../unit/test_blue_green_switchover_loops.py | 265 ++++++++++++++++++ 3 files changed, 556 insertions(+) create mode 100644 tests/unit/test_aio_blue_green_routing_match.py create mode 100644 tests/unit/test_blue_green_routing_match.py create mode 100644 tests/unit/test_blue_green_switchover_loops.py diff --git a/tests/unit/test_aio_blue_green_routing_match.py b/tests/unit/test_aio_blue_green_routing_match.py new file mode 100644 index 000000000..9c0bba721 --- /dev/null +++ b/tests/unit/test_aio_blue_green_routing_match.py @@ -0,0 +1,131 @@ +# 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. + +"""Endpoint matching of the async Blue/Green routings (issue #1352). + +The status provider gives a routing an endpoint of the form ``host``, +``host:port``, ``ip`` or ``ip:port``. These tests build the routings with +those endpoints and check that they match the host they name, and that a +connection to that host is then routed by them. +""" + +from __future__ import annotations + +import asyncio +from types import SimpleNamespace +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio.blue_green_plugin import ( + AsyncBlueGreenPlugin, BlueGreenPhase, BlueGreenRole, BlueGreenStatus, + RejectConnectRouting, SubstituteConnectRouting, SuspendConnectRouting, + SuspendExecuteRouting, SuspendUntilCorrespondingHostFoundConnectRouting) +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.utils.properties import Properties + +BG_ID = "1" +PORT = 3306 +BLUE_HOST = "database-1.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +GREEN_HOST = "database-1-green-abc123.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +BLUE_IP = "10.0.1.10" +GREEN_IP = "10.0.1.20" + + +@pytest.fixture(autouse=True) +def no_status_monitors(monkeypatch): + # A real status provider starts monitor tasks that query the database; these tests publish the status + # themselves. + monkeypatch.setattr(AsyncBlueGreenPlugin, "_init_status_provider", lambda self, initial_host_info: None) + yield + AsyncBlueGreenPlugin._reset_for_tests() + + +@pytest.mark.xfail(strict=True, reason="#1352: C6 async routings never match the host, host:port, ip or ip:port they name") +def test_async_routings_match_the_endpoints_the_status_provider_builds(): + """Each async routing built with an endpoint of the form the status provider uses matches a host with that + name and port, so the routing applies to connections and calls on that host.""" + blue = HostInfo(BLUE_HOST, PORT) + blue_ip = HostInfo(BLUE_IP, PORT) + cases = [ + (SubstituteConnectRouting(blue_ip, BLUE_HOST, BlueGreenRole.SOURCE, (blue,)), HostInfo(BLUE_HOST)), + (SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (blue,)), blue), + # A host name given in upper case still has a role, since the role lookup ignores case. + (SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (blue,)), + HostInfo(BLUE_HOST.upper(), PORT)), + (SuspendUntilCorrespondingHostFoundConnectRouting(BLUE_HOST, BlueGreenRole.SOURCE, BG_ID), HostInfo(BLUE_HOST)), + (SuspendUntilCorrespondingHostFoundConnectRouting(f"{BLUE_HOST}:{PORT}", None, BG_ID), blue), + (SuspendConnectRouting(BLUE_IP, None, BG_ID), HostInfo(BLUE_IP)), + (SuspendConnectRouting(f"{BLUE_IP}:{PORT}", None, BG_ID), blue_ip), + (SuspendExecuteRouting(BLUE_IP, None, BG_ID), HostInfo(BLUE_IP)), + (SuspendExecuteRouting(f"{BLUE_IP}:{PORT}", None, BG_ID), blue_ip), + ] + + misses = [f"{type(routing).__name__} for {host_info.get_host_and_port()}" + for routing, host_info in cases if not routing.is_match(host_info, BlueGreenRole.SOURCE)] + assert misses == [], f"C6: {len(misses)} of {len(cases)} routings did not match the host they name: {misses}" + + +def test_async_routings_do_not_match_another_host_port_or_role(): + """An async routing with an endpoint doesn't match another host, the same host on another port, a host in the + other role, or no host; a routing without an endpoint doesn't match the other role.""" + routing = SubstituteConnectRouting( + HostInfo(GREEN_IP, PORT), f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (HostInfo(BLUE_HOST, PORT),)) + + assert routing.is_match(HostInfo(GREEN_HOST, PORT), BlueGreenRole.SOURCE) is False + assert routing.is_match(HostInfo(BLUE_HOST, PORT + 1), BlueGreenRole.SOURCE) is False + assert routing.is_match(HostInfo(BLUE_HOST, PORT), BlueGreenRole.TARGET) is False + assert routing.is_match(None, BlueGreenRole.SOURCE) is False + assert SuspendConnectRouting(BLUE_IP, None, BG_ID).is_match(HostInfo(GREEN_IP), BlueGreenRole.SOURCE) is False + assert SuspendExecuteRouting(None, BlueGreenRole.SOURCE, BG_ID).is_match( + HostInfo(GREEN_HOST, PORT), BlueGreenRole.TARGET) is False + + +# If a routing returns no connection, the connect loop tries again for as long as the status stays the same, +# which here is for ever; the timeout ends such a call. +@pytest.mark.timeout(20) +@pytest.mark.xfail(strict=True, reason="#1352: C6 async connect during POST goes to the blue name, not the green IP") +def test_async_connect_during_post_goes_to_the_green_ip(): + """During POST, a new async connection to the blue host and port is opened to the green host's IP address that + the substitute routing names, instead of to the blue name, which DNS may still resolve to blue.""" + green_ip = HostInfo(GREEN_IP, PORT) + iam_hosts = (HostInfo(GREEN_HOST, PORT), HostInfo(BLUE_HOST, PORT)) + status = BlueGreenStatus( + BG_ID, + BlueGreenPhase.POST, + connect_routings=[ + SubstituteConnectRouting(green_ip, BLUE_HOST, BlueGreenRole.SOURCE, iam_hosts), + SubstituteConnectRouting(green_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, iam_hosts), + RejectConnectRouting(None, BlueGreenRole.TARGET), + ], + role_by_host={BLUE_HOST: BlueGreenRole.SOURCE, GREEN_HOST: BlueGreenRole.TARGET}) + plugin_service = MagicMock() + plugin_service.network_bound_methods = set() + plugin_service.get_status.return_value = status + # Each fake connection remembers the host it was opened to: a routing opens the host it is given through the + # plugin service, and connect_func opens the host the caller asked for. + plugin_service.connect = AsyncMock( + side_effect=lambda target_host, props, plugin_to_skip=None: SimpleNamespace(host=target_host.host)) + plugin = AsyncBlueGreenPlugin(plugin_service, Properties()) + + conn = asyncio.run(plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=MagicMock(), + host_info=HostInfo(BLUE_HOST, PORT), + props=Properties(), + is_initial_connection=True, + connect_func=AsyncMock(return_value=SimpleNamespace(host=BLUE_HOST)))) + + assert conn.host == GREEN_IP, \ + f"C6: async connect() during POST opened '{conn.host}' instead of the green IP '{GREEN_IP}'" diff --git a/tests/unit/test_blue_green_routing_match.py b/tests/unit/test_blue_green_routing_match.py new file mode 100644 index 000000000..0f71d1e1b --- /dev/null +++ b/tests/unit/test_blue_green_routing_match.py @@ -0,0 +1,160 @@ +# 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. + +"""Endpoint matching of the sync Blue/Green routings (issue #1352). + +The status provider gives a routing an endpoint of the form ``host``, +``host:port``, ``ip`` or ``ip:port``. These tests build the routings with +those endpoints and check that they match the host they name, and that a +connection to that host is then routed by them. +""" + +from __future__ import annotations + +from types import SimpleNamespace +from typing import Any +from unittest.mock import MagicMock + +import pytest + +from aws_advanced_python_wrapper.blue_green_plugin import ( + BlueGreenPhase, BlueGreenPlugin, BlueGreenRole, BlueGreenStatus, + RejectConnectRouting, SubstituteConnectRouting, SuspendConnectRouting, + SuspendExecuteRouting, SuspendUntilCorrespondingHostFoundConnectRouting) +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.utils.properties import Properties + +BG_ID = "1" +PORT = 3306 +BLUE_HOST = "database-1.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +GREEN_HOST = "database-1-green-abc123.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +BLUE_IP = "10.0.1.10" +GREEN_IP = "10.0.1.20" + + +@pytest.fixture(autouse=True) +def no_status_monitors(monkeypatch): + # A real status provider starts monitor threads that query the database; these tests publish the status + # themselves. + monkeypatch.setattr(BlueGreenPlugin, "_init_status_provider", lambda self: None) + yield + BlueGreenPlugin._status_providers.clear() + + +def _connect(status: BlueGreenStatus, host_info: HostInfo) -> Any: + plugin_service = MagicMock() + plugin_service.network_bound_methods = set() + plugin_service.get_status.return_value = status + plugin_service.is_plugin_in_use.return_value = False + # Each fake connection remembers the host it was opened to: a routing opens the host it is given through the + # plugin service, and connect_func opens the host the caller asked for. + plugin_service.connect.side_effect = \ + lambda target_host, props, plugin_to_skip=None: SimpleNamespace(host=target_host.host) + plugin = BlueGreenPlugin(plugin_service, Properties()) + + return plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=MagicMock(), + host_info=host_info, + props=Properties(), + is_initial_connection=True, + connect_func=lambda: SimpleNamespace(host=host_info.host)) + + +@pytest.mark.xfail(strict=True, reason="#1352: C5 sync routings never match the host, host:port, ip or ip:port they name") +def test_routings_match_the_endpoints_the_status_provider_builds(): + """Each routing built with an endpoint of the form the status provider uses matches a host with that name and + port, so the routing applies to connections and calls on that host.""" + blue = HostInfo(BLUE_HOST, PORT) + blue_ip = HostInfo(BLUE_IP, PORT) + cases = [ + (SubstituteConnectRouting(blue_ip, BLUE_HOST, BlueGreenRole.SOURCE, (blue,)), HostInfo(BLUE_HOST)), + (SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (blue,)), blue), + # A host name given in upper case still has a role, since the role lookup ignores case. + (SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (blue,)), + HostInfo(BLUE_HOST.upper(), PORT)), + (SuspendUntilCorrespondingHostFoundConnectRouting(BLUE_HOST, BlueGreenRole.SOURCE, BG_ID), HostInfo(BLUE_HOST)), + (SuspendUntilCorrespondingHostFoundConnectRouting(f"{BLUE_HOST}:{PORT}", None, BG_ID), blue), + (SuspendConnectRouting(BLUE_IP, None, BG_ID), HostInfo(BLUE_IP)), + (SuspendConnectRouting(f"{BLUE_IP}:{PORT}", None, BG_ID), blue_ip), + (SuspendExecuteRouting(BLUE_IP, None, BG_ID), HostInfo(BLUE_IP)), + (SuspendExecuteRouting(f"{BLUE_IP}:{PORT}", None, BG_ID), blue_ip), + ] + + misses = [f"{type(routing).__name__} for {host_info.get_host_and_port()}" + for routing, host_info in cases if not routing.is_match(host_info, BlueGreenRole.SOURCE)] + assert misses == [], f"C5: {len(misses)} of {len(cases)} routings did not match the host they name: {misses}" + + +def test_routings_do_not_match_another_host_port_or_role(): + """A routing with an endpoint doesn't match another host, the same host on another port, a host in the other + role, or no host; a routing without an endpoint doesn't match the other role.""" + routing = SubstituteConnectRouting( + HostInfo(GREEN_IP, PORT), f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, (HostInfo(BLUE_HOST, PORT),)) + + assert routing.is_match(HostInfo(GREEN_HOST, PORT), BlueGreenRole.SOURCE) is False + assert routing.is_match(HostInfo(BLUE_HOST, PORT + 1), BlueGreenRole.SOURCE) is False + assert routing.is_match(HostInfo(BLUE_HOST, PORT), BlueGreenRole.TARGET) is False + assert routing.is_match(None, BlueGreenRole.SOURCE) is False + assert SuspendConnectRouting(BLUE_IP, None, BG_ID).is_match(HostInfo(GREEN_IP), BlueGreenRole.SOURCE) is False + assert SuspendExecuteRouting(None, BlueGreenRole.SOURCE, BG_ID).is_match( + HostInfo(GREEN_HOST, PORT), BlueGreenRole.TARGET) is False + + +# If a routing returns no connection, the connect loop tries again for as long as the status stays the same, +# which here is for ever; the timeout ends such a call. +@pytest.mark.timeout(20) +@pytest.mark.xfail(strict=True, reason="#1352: C7 sync connect during POST goes to the blue name, not the green IP") +def test_connect_during_post_goes_to_the_green_ip(): + """During POST, a new connection to the blue host and port is opened to the green host's IP address that the + substitute routing names, instead of to the blue name, which DNS may still resolve to blue.""" + green_ip = HostInfo(GREEN_IP, PORT) + iam_hosts = (HostInfo(GREEN_HOST, PORT), HostInfo(BLUE_HOST, PORT)) + status = BlueGreenStatus( + BG_ID, + BlueGreenPhase.POST, + connect_routings=[ + SubstituteConnectRouting(green_ip, BLUE_HOST, BlueGreenRole.SOURCE, iam_hosts), + SubstituteConnectRouting(green_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, iam_hosts), + RejectConnectRouting(None, BlueGreenRole.TARGET), + ], + role_by_host={BLUE_HOST: BlueGreenRole.SOURCE, GREEN_HOST: BlueGreenRole.TARGET}) + + conn = _connect(status, HostInfo(BLUE_HOST, PORT)) + + assert conn.host == GREEN_IP, f"C7: connect() during POST opened '{conn.host}' instead of the green IP '{GREEN_IP}'" + + +# If a routing returns no connection, the connect loop tries again for as long as the status stays the same, +# which here is for ever; the timeout ends such a call. +@pytest.mark.timeout(20) +@pytest.mark.xfail(strict=True, reason="#1352: C7 sync connect during PREPARATION goes to the blue name, not its IP") +def test_connect_during_preparation_goes_to_the_blue_ip(): + """During PREPARATION, a new connection to the blue host (no port given) is opened to the blue IP address that + the substitute routing names, so it isn't affected when DNS changes during the switchover.""" + blue_ip = HostInfo(BLUE_IP, PORT) + iam_hosts = (HostInfo(BLUE_HOST, PORT),) + status = BlueGreenStatus( + BG_ID, + BlueGreenPhase.PREPARATION, + connect_routings=[ + SubstituteConnectRouting(blue_ip, BLUE_HOST, BlueGreenRole.SOURCE, iam_hosts), + SubstituteConnectRouting(blue_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, iam_hosts), + ], + role_by_host={BLUE_HOST: BlueGreenRole.SOURCE, GREEN_HOST: BlueGreenRole.TARGET}) + + conn = _connect(status, HostInfo(BLUE_HOST)) + + assert conn.host == BLUE_IP, \ + f"C7: connect() during PREPARATION opened '{conn.host}' instead of the blue IP '{BLUE_IP}'" diff --git a/tests/unit/test_blue_green_switchover_loops.py b/tests/unit/test_blue_green_switchover_loops.py new file mode 100644 index 000000000..fc85a32cf --- /dev/null +++ b/tests/unit/test_blue_green_switchover_loops.py @@ -0,0 +1,265 @@ +# 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. + +"""Calls suspended by the Blue/Green plugin while a switchover is IN_PROGRESS +(issue #1352). + +Each test suspends a call on IN_PROGRESS, publishes the next phase, and +checks that the call comes back within a bound with what the new phase's +routings give. +""" + +from __future__ import annotations + +import asyncio +import logging +from itertools import count +from threading import Event, Thread +from typing import Any, Callable, List, Optional +from unittest.mock import AsyncMock, MagicMock + +import pytest + +from aws_advanced_python_wrapper.aio import blue_green_plugin as aio_bg +from aws_advanced_python_wrapper.blue_green_plugin import ( + BlueGreenPhase, BlueGreenPlugin, BlueGreenRole, BlueGreenStatus, + RejectConnectRouting, SubstituteConnectRouting, SuspendConnectRouting, + SuspendExecuteRouting) +from aws_advanced_python_wrapper.errors import AwsWrapperError +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict +from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import Properties +from aws_advanced_python_wrapper.utils.telemetry.null_telemetry import \ + NullTelemetryFactory + +BG_ID = "1" +PORT = 3306 +BLUE_HOST = "database-1.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +GREEN_HOST = "database-1-green-abc123.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +GREEN_IP = "10.0.1.20" +# Bounds for the test setup, not for the plugin: how long the call may take to reach the suspend routing, and how +# long the stop switch may take to end a call that spins. +SUSPENDED_WITHIN_SEC = 5 +STOP_WITHIN_SEC = 5 + + +@pytest.fixture(autouse=True) +def no_status_monitors(monkeypatch): + # A real status provider starts monitor threads or tasks that query the database; these tests publish the + # status themselves. + monkeypatch.setattr(BlueGreenPlugin, "_init_status_provider", lambda self: None) + monkeypatch.setattr(aio_bg.AsyncBlueGreenPlugin, "_init_status_provider", lambda self, initial_host_info: None) + yield + BlueGreenPlugin._status_providers.clear() + aio_bg.AsyncBlueGreenPlugin._reset_for_tests() + + +@pytest.fixture(autouse=True) +def no_debug_records(caplog): + # The unit suite logs at DEBUG, and a call that spins logs a record on every pass; pytest would keep them all + # in memory and print them with the failure. + caplog.set_level(logging.INFO, logger="aws_advanced_python_wrapper.blue_green_plugin") + caplog.set_level(logging.INFO, logger="aws_advanced_python_wrapper.aio.blue_green_plugin") + + +def _plugin_service(published: List[Any], suspended: Event, current_host_info: Optional[HostInfo] = None) \ + -> MagicMock: + plugin_service = MagicMock() + plugin_service.network_bound_methods = set() + plugin_service.current_host_info = current_host_info + plugin_service.is_plugin_in_use.return_value = False + # Plain functions, not mocks, on the calls a suspended call repeats: a call that spins would otherwise record + # a mock call on every pass and grow without bound. The last status in `published` is the current one. + telemetry_factory = NullTelemetryFactory() + plugin_service.get_telemetry_factory = lambda: telemetry_factory + reads = count(1) + + def get_status(*args, **kwargs): + # The plugin reads the status when the call starts, and the suspend routing reads it on entry and again as + # it starts waiting for the phase to change, so a third read means the call is suspended. + if next(reads) >= 3: + suspended.set() + return published[-1] + + plugin_service.get_status = get_status + return plugin_service + + +def _call_across_move( + call: Callable[[], Any], published: List[Any], suspended: Event, next_status: Any, bound_sec: float) \ + -> List[Any]: + """Runs `call` in a daemon thread, publishes `next_status` once the call is suspended on IN_PROGRESS, and + returns the call's result or exception in a list, or an empty list if it didn't return or raise within + `bound_sec` of the move.""" + outcome: List[Any] = [] + + def run(): + try: + outcome.append(call()) + except Exception as e: # a caller sees the exception, so the test gets it as the outcome + outcome.append(e) + finally: + # A call that ends without being suspended mustn't leave the wait below to run to its bound. + suspended.set() + + # A call that spins never returns, so it runs in a daemon thread and is only waited for with a bound. + worker = Thread(target=run, daemon=True) + worker.start() + assert suspended.wait(SUSPENDED_WITHIN_SEC), \ + f"setup: the call didn't reach the suspend routing within {SUSPENDED_WITHIN_SEC} s" + assert not outcome, f"setup: the call ended while the phase was still IN_PROGRESS: {outcome!r}" + + published.append(next_status) + worker.join(bound_sec) + returned = list(outcome) + if not returned: + # Stop switch: with no status published the plugin calls straight through, so a call that spins ends + # here instead of burning a CPU for the rest of the session. + published.append(None) + worker.join(STOP_WITHIN_SEC) + assert not worker.is_alive(), \ + f"setup: the stop switch didn't end the call within {STOP_WITHIN_SEC} s; it still runs in the background" + + return returned + + +def _role_by_host() -> ConcurrentDict[str, BlueGreenRole]: + role_by_host: ConcurrentDict[str, BlueGreenRole] = ConcurrentDict() + role_by_host.put_all({BLUE_HOST: BlueGreenRole.SOURCE, GREEN_HOST: BlueGreenRole.TARGET}) + return role_by_host + + +def _in_progress() -> BlueGreenStatus: + return BlueGreenStatus( + BG_ID, + BlueGreenPhase.IN_PROGRESS, + connect_routings=[SuspendConnectRouting(None, BlueGreenRole.TARGET, BG_ID)], + execute_routings=[ + SuspendExecuteRouting(None, BlueGreenRole.SOURCE, BG_ID), + SuspendExecuteRouting(None, BlueGreenRole.TARGET, BG_ID), + ], + role_by_host=_role_by_host()) + + +def _post() -> BlueGreenStatus: + # POST suspends no calls: new blue connections go to the green IP and new green connections are rejected. + green_ip = HostInfo(GREEN_IP, PORT) + iam_hosts = (HostInfo(GREEN_HOST, PORT), HostInfo(BLUE_HOST, PORT)) + return BlueGreenStatus( + BG_ID, + BlueGreenPhase.POST, + connect_routings=[ + SubstituteConnectRouting(green_ip, BLUE_HOST, BlueGreenRole.SOURCE, iam_hosts), + SubstituteConnectRouting(green_ip, f"{BLUE_HOST}:{PORT}", BlueGreenRole.SOURCE, iam_hosts), + RejectConnectRouting(None, BlueGreenRole.TARGET), + ], + role_by_host=_role_by_host()) + + +@pytest.mark.timeout(20) +@pytest.mark.xfail(strict=True, reason="#1352: C1 sync execute keeps spinning on the IN_PROGRESS routing after the phase moves on") +def test_suspended_execute_returns_after_switchover_moves_past_in_progress(): + """An execute suspended during IN_PROGRESS runs and returns its result soon after the status moves to POST.""" + published: List[Any] = [_in_progress()] + suspended = Event() + plugin = BlueGreenPlugin(_plugin_service(published, suspended, HostInfo(BLUE_HOST, PORT)), Properties()) + + outcome = _call_across_move( + lambda: plugin.execute(MagicMock(), "Cursor.execute", lambda: "result"), published, suspended, _post(), 2) + + assert outcome, "C1: execute() did not return within 2 s after the phase left IN_PROGRESS" + assert outcome == ["result"], f"C1: execute() ended with {outcome[0]!r} instead of the target's result" + + +@pytest.mark.timeout(20) +@pytest.mark.xfail(strict=True, reason="#1352: C2 sync connect keeps spinning on the IN_PROGRESS routing after the phase moves on") +def test_suspended_connect_ends_after_switchover_moves_past_in_progress(): + """A connect to a green host suspended during IN_PROGRESS fails with the reject routing's error soon after the + status moves to POST, which rejects new connections to green hosts.""" + published: List[Any] = [_in_progress()] + suspended = Event() + plugin = BlueGreenPlugin(_plugin_service(published, suspended), Properties()) + host_info = HostInfo(GREEN_HOST, PORT) + + outcome = _call_across_move( + lambda: plugin.connect( + target_driver_func=MagicMock(), + driver_dialect=MagicMock(), + host_info=host_info, + props=Properties(), + is_initial_connection=True, + connect_func=MagicMock()), + published, suspended, _post(), 2) + + assert outcome, "C2: connect() did not return or raise within 2 s after the phase left IN_PROGRESS" + # A connect that skips the POST routings opens the green host, or ends with an error of its own, instead of + # raising the error of POST's RejectConnectRouting. + rejected = Messages.get("RejectConnectRouting.InProgressCantConnect") + assert isinstance(outcome[0], AwsWrapperError) and str(outcome[0]) == rejected, \ + f"C2: connect() to a green host after the move to POST ended with {outcome[0]!r} instead of the POST reject error" + + +@pytest.mark.timeout(20) +@pytest.mark.xfail(strict=True, reason="#1352: C3 bg_connect_timeout_ms doesn't bound the sync execute loop") +def test_suspended_execute_with_short_connect_timeout_ends_after_switchover(): + """With bg_connect_timeout_ms=500, an execute suspended during IN_PROGRESS returns its result or raises a + timeout error within 3 s of the status moving to POST, long after that timeout has passed.""" + published: List[Any] = [_in_progress()] + suspended = Event() + props = Properties({"bg_connect_timeout_ms": "500"}) + plugin = BlueGreenPlugin(_plugin_service(published, suspended, HostInfo(BLUE_HOST, PORT)), props) + + outcome = _call_across_move( + lambda: plugin.execute(MagicMock(), "Cursor.execute", lambda: "result"), published, suspended, _post(), 3) + + assert outcome, \ + "C3: execute() with bg_connect_timeout_ms=500 did not return or raise within 3 s after the phase left IN_PROGRESS" + # Either the loop takes the new status and runs the target, or the timeout ends it; any other error is a fault + # in the call, not the timeout applying. + assert outcome == ["result"] or isinstance(outcome[0], (TimeoutError, AwsWrapperError)), \ + f"C3: execute() with bg_connect_timeout_ms=500 ended with {outcome[0]!r}, neither the target's result nor a timeout" + + +@pytest.mark.timeout(20) +def test_async_suspended_execute_returns_after_switchover_moves_past_in_progress(): + """The async plugin's execute suspended during IN_PROGRESS returns its result soon after the status moves to + POST. A guard: the async loops already take the latest status, so this passes on main.""" + in_progress = aio_bg.BlueGreenStatus( + BG_ID, + aio_bg.BlueGreenPhase.IN_PROGRESS, + connect_routings=[aio_bg.SuspendConnectRouting(None, aio_bg.BlueGreenRole.TARGET, BG_ID)], + execute_routings=[ + aio_bg.SuspendExecuteRouting(None, aio_bg.BlueGreenRole.SOURCE, BG_ID), + aio_bg.SuspendExecuteRouting(None, aio_bg.BlueGreenRole.TARGET, BG_ID), + ], + role_by_host={BLUE_HOST: aio_bg.BlueGreenRole.SOURCE, GREEN_HOST: aio_bg.BlueGreenRole.TARGET}) + post = aio_bg.BlueGreenStatus( + BG_ID, + aio_bg.BlueGreenPhase.POST, + connect_routings=[aio_bg.RejectConnectRouting(None, aio_bg.BlueGreenRole.TARGET)], + role_by_host={BLUE_HOST: aio_bg.BlueGreenRole.SOURCE, GREEN_HOST: aio_bg.BlueGreenRole.TARGET}) + published: List[Any] = [in_progress] + suspended = Event() + # The async plugin service's get_status is synchronous too, so the same fake serves the async plugin. + plugin = aio_bg.AsyncBlueGreenPlugin( + _plugin_service(published, suspended, HostInfo(BLUE_HOST, PORT)), Properties()) + execute_func = AsyncMock(return_value="result") + + outcome = _call_across_move( + lambda: asyncio.run(plugin.execute(MagicMock(), "Cursor.execute", execute_func)), + published, suspended, post, 2) + + assert outcome, "C4: async execute() did not return within 2 s after the phase left IN_PROGRESS" + assert outcome == ["result"], f"C4: async execute() ended with {outcome[0]!r} instead of the target's result" From ad72ac6a806ffda2dd53581f20127a95e9d33665 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Sun, 8 Nov 2026 01:56:54 -0700 Subject: [PATCH 2/4] fix: select blue/green routings from the latest status and match them by host and port The sync connect and execute loops chose the next routing from the status captured before the loop, so a call suspended during IN_PROGRESS spun forever once the phase moved on. They now re-read the status, recompute the role and select from it, as the asyncio loops do. BaseRouting.is_match compared the endpoint with HostInfo.url, which ends in "/", so no routing matched. It now compares get_host_and_port().lower() in both engines. With routings matching, ADFS and Okta count as IAM in use for SubstituteConnectRouting, and the corresponding-host lookups ignore case. Fixes #1352. --- .../aio/blue_green_plugin.py | 8 +-- .../blue_green_plugin.py | 29 +++++--- tests/unit/test_aio_blue_green_plugin.py | 66 ++++++++++++++++-- .../unit/test_aio_blue_green_routing_match.py | 2 - tests/unit/test_blue_green_plugin.py | 68 +++++++++++++++++++ tests/unit/test_blue_green_routing_match.py | 3 - .../unit/test_blue_green_switchover_loops.py | 3 - 7 files changed, 152 insertions(+), 27 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index 7c1898d80..1b002df9f 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -86,7 +86,7 @@ # Plugin codes (see aio/plugin_factory.py) whose presence implies IAM token # authentication is active, gating the SubstituteConnectRouting IAM-host # rerouting. Approximation of sync's plugin_service.is_plugin_in_use. -_IAM_PLUGIN_CODES: frozenset = frozenset({"iam"}) +_IAM_PLUGIN_CODES: frozenset = frozenset({"iam", "federated_auth", "okta"}) # ---- Enums ----------------------------------------------------------- @@ -318,7 +318,7 @@ def is_match(self, host_info: Optional[HostInfo], bg_role: BlueGreenRole) -> boo if host_info is None: return False - return self._endpoint == host_info.url.lower() and (self._bg_role is None or self._bg_role == bg_role) + return self._endpoint == host_info.get_host_and_port().lower() and (self._bg_role is None or self._bg_role == bg_role) def __str__(self) -> str: endpoint_str = "None" if self._endpoint is None else f"'{self._endpoint}'" @@ -501,7 +501,7 @@ async def apply( SuspendUntilCorrespondingHostFoundConnectRouting._TELEMETRY_SWITCHOVER, TelemetryTraceLevel.NESTED) bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id) - corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host) + corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower()) timeout_ms = WrapperProperties.BG_CONNECT_TIMEOUT_MS.get_int(props) loop = asyncio.get_running_loop() @@ -517,7 +517,7 @@ async def apply( await self.delay( SuspendUntilCorrespondingHostFoundConnectRouting._SLEEP_TIME_MS, bg_status, plugin_service, self._bg_id) bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id) - corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host) + corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower()) if bg_status is None or bg_status.phase == BlueGreenPhase.COMPLETED: logger.debug( diff --git a/aws_advanced_python_wrapper/blue_green_plugin.py b/aws_advanced_python_wrapper/blue_green_plugin.py index 19adb9d56..fb36b4aab 100644 --- a/aws_advanced_python_wrapper/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/blue_green_plugin.py @@ -39,9 +39,11 @@ from aws_advanced_python_wrapper.errors import (AwsWrapperError, UnsupportedOperationError) +from aws_advanced_python_wrapper.federated_plugin import FederatedAuthPlugin from aws_advanced_python_wrapper.host_availability import HostAvailability from aws_advanced_python_wrapper.hostinfo import HostInfo, HostRole from aws_advanced_python_wrapper.iam_plugin import IamAuthPlugin +from aws_advanced_python_wrapper.okta_plugin import OktaAuthPlugin from aws_advanced_python_wrapper.pep249_methods import DbApiMethod from aws_advanced_python_wrapper.plugin import Plugin, PluginFactory from aws_advanced_python_wrapper.utils import services_container @@ -315,7 +317,7 @@ def is_match(self, host_info: Optional[HostInfo], bg_role: BlueGreenRole) -> boo if host_info is None: return False - return self._endpoint == host_info.url.lower() and (self._bg_role is None or self._bg_role == bg_role) + return self._endpoint == host_info.get_host_and_port().lower() and (self._bg_role is None or self._bg_role == bg_role) def __str__(self): endpoint_str = "None" if self._endpoint is None else f"'{self._endpoint}'" @@ -390,7 +392,7 @@ def apply( if not SubstituteConnectRouting._rds_utils.is_ip(self._substitute_host_info.host): return plugin_service.connect(self._substitute_host_info, props, plugin) - is_iam_in_use = plugin_service.is_plugin_in_use(IamAuthPlugin) + is_iam_in_use = any(plugin_service.is_plugin_in_use(p) for p in (IamAuthPlugin, FederatedAuthPlugin, OktaAuthPlugin)) if not is_iam_in_use: return plugin_service.connect(self._substitute_host_info, props, plugin) @@ -507,7 +509,7 @@ def apply( SuspendUntilCorrespondingHostFoundConnectRouting._TELEMETRY_SWITCHOVER, TelemetryTraceLevel.NESTED) bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id) - corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host) + corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower()) timeout_ms = WrapperProperties.BG_CONNECT_TIMEOUT_MS.get_int(props) start_time_sec = time.time() @@ -522,7 +524,7 @@ def apply( self.delay( SuspendUntilCorrespondingHostFoundConnectRouting._SLEEP_TIME_MS, bg_status, plugin_service, self._bg_id) bg_status = plugin_service.get_status(BlueGreenStatus, self._bg_id) - corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host) + corresponding_pair = None if bg_status is None else bg_status.corresponding_hosts.get(host_info.host.lower()) if bg_status is None or bg_status.phase == BlueGreenPhase.COMPLETED: logger.debug( @@ -684,13 +686,21 @@ def connect( if conn is not None: break + # Re-select against the LATEST published status: a suspend/wait + # routing returns None once switchover moves past its phase, so + # the current routing table (not the stale captured one) decides + # what happens next. Falls through to connect_func when the + # latest status no longer matches. latest_status = self._plugin_service.get_status(BlueGreenStatus, self._bg_id) if latest_status is None: self._end_time_ns.set(perf_counter_ns()) return self._open_direct_connection(connect_func, is_initial_connection) - routing = \ - next((r for r in self._bg_status.connect_routings if r.is_match(host_info, bg_role)), None) + self._bg_status = latest_status + bg_role = latest_status.get_role(host_info) + if bg_role is None: + break + routing = next((r for r in latest_status.connect_routings if r.is_match(host_info, bg_role)), None) self._end_time_ns.set(perf_counter_ns()) if conn is None: @@ -761,8 +771,11 @@ def execute(self, target: type, method_name: str, execute_func: Callable, *args: self._end_time_ns.set(perf_counter_ns()) return execute_func() - routing = \ - next((r for r in self._bg_status.execute_routings if r.is_match(host_info, bg_role)), None) + self._bg_status = latest_status + bg_role = None if host_info is None else latest_status.get_role(host_info) + if bg_role is None: + break + routing = next((r for r in latest_status.execute_routings if r.is_match(host_info, bg_role)), None) self._end_time_ns.set(perf_counter_ns()) if result_container.is_present(): diff --git a/tests/unit/test_aio_blue_green_plugin.py b/tests/unit/test_aio_blue_green_plugin.py index 2ef8deecf..dc7986f5c 100644 --- a/tests/unit/test_aio_blue_green_plugin.py +++ b/tests/unit/test_aio_blue_green_plugin.py @@ -25,21 +25,24 @@ from __future__ import annotations import asyncio -from typing import Any, Optional -from unittest.mock import AsyncMock, MagicMock +from typing import Any, Optional, Tuple +from unittest.mock import AsyncMock, MagicMock, patch import pytest from aws_advanced_python_wrapper.aio.blue_green_plugin import ( AsyncBlueGreenPlugin, AsyncBlueGreenStatusProvider, BlueGreenPhase, BlueGreenRole, BlueGreenStatus, ConnectRouting, PassThroughConnectRouting, - RejectConnectRouting, SubstituteConnectRouting) + RejectConnectRouting, SubstituteConnectRouting, + SuspendUntilCorrespondingHostFoundConnectRouting) from aws_advanced_python_wrapper.aio.plugin_factory import PLUGIN_FACTORIES from aws_advanced_python_wrapper.database_dialect import BlueGreenDialect from aws_advanced_python_wrapper.errors import AwsWrapperError 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 +from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) @pytest.fixture(autouse=True) @@ -299,14 +302,63 @@ def test_execute_passes_through_when_host_not_in_bg(): execute_func.assert_awaited_once() -def test_substitute_connect_routing_is_match_by_url(): - """Endpoint matching mirrors sync BaseRouting.is_match (host_info.url).""" +def test_substitute_connect_routing_is_match_by_host_and_port(): + """An endpoint of host and port matches the host with that name and port, and not another host.""" routing = SubstituteConnectRouting( - HostInfo("10.0.0.1", 5432), "h:5432/", BlueGreenRole.SOURCE) + HostInfo("10.0.0.1", 5432), "h:5432", BlueGreenRole.SOURCE) assert routing.is_match(HostInfo("h", 5432), BlueGreenRole.SOURCE) is True assert routing.is_match(HostInfo("other", 5432), BlueGreenRole.SOURCE) is False +@pytest.mark.parametrize("plugin_code", ["federated_auth", "okta"]) +def test_substitute_connect_routing_to_an_ip_sets_the_iam_host_for_federated_and_okta_auth(plugin_code): + """The ADFS and Okta plugins get an IAM token for the host they connect to and reject an IP, so a connect + substituted by an IP sets the IAM host for them as it does for the IAM plugin.""" + plugin = MagicMock() + plugin.plugin_service.connect = AsyncMock() + routing = SubstituteConnectRouting( + HostInfo("10.0.0.1", 5432), "h:5432", BlueGreenRole.SOURCE, (HostInfo("h-green", 5432),)) + + _run(routing.apply( + plugin, HostInfo("h", 5432), Properties({"plugins": f"bg,{plugin_code}"}), True, AsyncMock())) + + rerouted_props = plugin.plugin_service.connect.call_args.args[1] + assert WrapperProperties.IAM_HOST.get(rerouted_props) == "h-green" + + +def _corresponding_hosts() -> ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]]: + corresponding_hosts: ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]] = ConcurrentDict() + corresponding_hosts.put_all({"h": (HostInfo("h", 5432), HostInfo("h-green", 5432))}) + return corresponding_hosts + + +def test_suspend_until_corresponding_host_found_does_not_wait_for_a_known_host_given_in_upper_case(): + """The corresponding hosts are keyed by lower-case host name, so a host given in upper case whose + corresponding host is already known continues at once.""" + plugin = MagicMock() + plugin.plugin_service.get_status.return_value = BlueGreenStatus( + "1", BlueGreenPhase.POST, corresponding_hosts=_corresponding_hosts()) + props = Properties({WrapperProperties.BG_CONNECT_TIMEOUT_MS.name: 500}) + routing = SuspendUntilCorrespondingHostFoundConnectRouting("h:5432", BlueGreenRole.SOURCE, "1") + + with patch.object(routing, "delay", wraps=routing.delay) as delay: + assert _run(routing.apply(plugin, HostInfo("H", 5432), props, True, AsyncMock())) is None + delay.assert_not_called() + + +def test_suspend_until_corresponding_host_found_continues_when_a_host_given_in_upper_case_is_found(): + """A host given in upper case continues once a later status has its corresponding host, instead of waiting + out bg_connect_timeout_ms.""" + found = BlueGreenStatus("1", BlueGreenPhase.POST, corresponding_hosts=_corresponding_hosts()) + statuses = iter([BlueGreenStatus("1", BlueGreenPhase.POST)]) + plugin = MagicMock() + plugin.plugin_service.get_status.side_effect = lambda *args: next(statuses, found) + props = Properties({WrapperProperties.BG_CONNECT_TIMEOUT_MS.name: 500}) + routing = SuspendUntilCorrespondingHostFoundConnectRouting("h:5432", BlueGreenRole.SOURCE, "1") + + assert _run(routing.apply(plugin, HostInfo("H", 5432), props, True, AsyncMock())) is None + + def test_factory_produces_async_blue_green_plugin(): factory = PLUGIN_FACTORIES["bg"] svc = _mock_service() diff --git a/tests/unit/test_aio_blue_green_routing_match.py b/tests/unit/test_aio_blue_green_routing_match.py index 9c0bba721..fa5bfe26d 100644 --- a/tests/unit/test_aio_blue_green_routing_match.py +++ b/tests/unit/test_aio_blue_green_routing_match.py @@ -52,7 +52,6 @@ def no_status_monitors(monkeypatch): AsyncBlueGreenPlugin._reset_for_tests() -@pytest.mark.xfail(strict=True, reason="#1352: C6 async routings never match the host, host:port, ip or ip:port they name") def test_async_routings_match_the_endpoints_the_status_provider_builds(): """Each async routing built with an endpoint of the form the status provider uses matches a host with that name and port, so the routing applies to connections and calls on that host.""" @@ -95,7 +94,6 @@ def test_async_routings_do_not_match_another_host_port_or_role(): # If a routing returns no connection, the connect loop tries again for as long as the status stays the same, # which here is for ever; the timeout ends such a call. @pytest.mark.timeout(20) -@pytest.mark.xfail(strict=True, reason="#1352: C6 async connect during POST goes to the blue name, not the green IP") def test_async_connect_during_post_goes_to_the_green_ip(): """During POST, a new async connection to the blue host and port is opened to the green host's IP address that the substitute routing names, instead of to the blue name, which DNS may still resolve to blue.""" diff --git a/tests/unit/test_blue_green_plugin.py b/tests/unit/test_blue_green_plugin.py index c28726095..3f8b1eeea 100644 --- a/tests/unit/test_blue_green_plugin.py +++ b/tests/unit/test_blue_green_plugin.py @@ -12,7 +12,27 @@ # See the License for the specific language governing permissions and # limitations under the License. +from typing import Optional, Tuple +from unittest.mock import MagicMock, patch + +import pytest + +from aws_advanced_python_wrapper.blue_green_plugin import ( + BlueGreenPhase, BlueGreenRole, BlueGreenStatus, SubstituteConnectRouting, + SuspendUntilCorrespondingHostFoundConnectRouting) +from aws_advanced_python_wrapper.federated_plugin import FederatedAuthPlugin +from aws_advanced_python_wrapper.hostinfo import HostInfo +from aws_advanced_python_wrapper.okta_plugin import OktaAuthPlugin +from aws_advanced_python_wrapper.utils.concurrent import ConcurrentDict from aws_advanced_python_wrapper.utils.messages import Messages +from aws_advanced_python_wrapper.utils.properties import (Properties, + WrapperProperties) + +BG_ID = "1" +PORT = 3306 +BLUE_HOST = "database-1.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +GREEN_HOST = "database-1-green-abc123.cluster-c1a2b3c4d5e6.us-east-1.rds.amazonaws.com" +GREEN_IP = "10.0.1.20" def test_blue_green_log_message_keys_resolve(): @@ -25,3 +45,51 @@ def test_blue_green_log_message_keys_resolve(): "SuspendConnectRouting.WaitConnectUntilCorrespondingHostFound", "host-1") assert "host-1" in formatted assert Messages.get("BlueGreenStatusProvider.AllGreenHostsChangedName") + + +@pytest.mark.parametrize("auth_plugin", [FederatedAuthPlugin, OktaAuthPlugin]) +def test_substitute_connect_routing_to_an_ip_sets_the_iam_host_for_federated_and_okta_auth(auth_plugin): + """The ADFS and Okta plugins get an IAM token for the host they connect to and reject an IP, so a connect + substituted by an IP sets the IAM host for them as it does for the IAM plugin.""" + plugin_service = MagicMock() + plugin_service.is_plugin_in_use.side_effect = lambda plugin_class: plugin_class is auth_plugin + routing = SubstituteConnectRouting( + HostInfo(GREEN_IP, PORT), BLUE_HOST, BlueGreenRole.SOURCE, (HostInfo(GREEN_HOST, PORT),)) + + routing.apply(MagicMock(), HostInfo(BLUE_HOST, PORT), Properties(), True, MagicMock(), plugin_service) + + rerouted_props = plugin_service.connect.call_args.args[1] + assert WrapperProperties.IAM_HOST.get(rerouted_props) == GREEN_HOST + + +def _corresponding_hosts() -> ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]]: + corresponding_hosts: ConcurrentDict[str, Tuple[HostInfo, Optional[HostInfo]]] = ConcurrentDict() + corresponding_hosts.put_all({BLUE_HOST: (HostInfo(BLUE_HOST, PORT), HostInfo(GREEN_HOST, PORT))}) + return corresponding_hosts + + +def test_suspend_until_corresponding_host_found_does_not_wait_for_a_known_host_given_in_upper_case(): + """The corresponding hosts are keyed by lower-case host name, so a host given in upper case whose + corresponding host is already known continues at once.""" + plugin_service = MagicMock() + plugin_service.get_status.return_value = BlueGreenStatus( + BG_ID, BlueGreenPhase.POST, corresponding_hosts=_corresponding_hosts()) + props = Properties({WrapperProperties.BG_CONNECT_TIMEOUT_MS.name: 500}) + routing = SuspendUntilCorrespondingHostFoundConnectRouting(BLUE_HOST, BlueGreenRole.SOURCE, BG_ID) + + with patch.object(routing, "delay", wraps=routing.delay) as delay: + assert routing.apply(MagicMock(), HostInfo(BLUE_HOST.upper(), PORT), props, True, MagicMock(), plugin_service) is None + delay.assert_not_called() + + +def test_suspend_until_corresponding_host_found_continues_when_a_host_given_in_upper_case_is_found(): + """A host given in upper case continues once a later status has its corresponding host, instead of waiting + out bg_connect_timeout_ms.""" + found = BlueGreenStatus(BG_ID, BlueGreenPhase.POST, corresponding_hosts=_corresponding_hosts()) + statuses = iter([BlueGreenStatus(BG_ID, BlueGreenPhase.POST)]) + plugin_service = MagicMock() + plugin_service.get_status.side_effect = lambda *args: next(statuses, found) + props = Properties({WrapperProperties.BG_CONNECT_TIMEOUT_MS.name: 500}) + routing = SuspendUntilCorrespondingHostFoundConnectRouting(BLUE_HOST, BlueGreenRole.SOURCE, BG_ID) + + assert routing.apply(MagicMock(), HostInfo(BLUE_HOST.upper(), PORT), props, True, MagicMock(), plugin_service) is None diff --git a/tests/unit/test_blue_green_routing_match.py b/tests/unit/test_blue_green_routing_match.py index 0f71d1e1b..acb98a7ca 100644 --- a/tests/unit/test_blue_green_routing_match.py +++ b/tests/unit/test_blue_green_routing_match.py @@ -72,7 +72,6 @@ def _connect(status: BlueGreenStatus, host_info: HostInfo) -> Any: connect_func=lambda: SimpleNamespace(host=host_info.host)) -@pytest.mark.xfail(strict=True, reason="#1352: C5 sync routings never match the host, host:port, ip or ip:port they name") def test_routings_match_the_endpoints_the_status_provider_builds(): """Each routing built with an endpoint of the form the status provider uses matches a host with that name and port, so the routing applies to connections and calls on that host.""" @@ -115,7 +114,6 @@ def test_routings_do_not_match_another_host_port_or_role(): # If a routing returns no connection, the connect loop tries again for as long as the status stays the same, # which here is for ever; the timeout ends such a call. @pytest.mark.timeout(20) -@pytest.mark.xfail(strict=True, reason="#1352: C7 sync connect during POST goes to the blue name, not the green IP") def test_connect_during_post_goes_to_the_green_ip(): """During POST, a new connection to the blue host and port is opened to the green host's IP address that the substitute routing names, instead of to the blue name, which DNS may still resolve to blue.""" @@ -139,7 +137,6 @@ def test_connect_during_post_goes_to_the_green_ip(): # If a routing returns no connection, the connect loop tries again for as long as the status stays the same, # which here is for ever; the timeout ends such a call. @pytest.mark.timeout(20) -@pytest.mark.xfail(strict=True, reason="#1352: C7 sync connect during PREPARATION goes to the blue name, not its IP") def test_connect_during_preparation_goes_to_the_blue_ip(): """During PREPARATION, a new connection to the blue host (no port given) is opened to the blue IP address that the substitute routing names, so it isn't affected when DNS changes during the switchover.""" diff --git a/tests/unit/test_blue_green_switchover_loops.py b/tests/unit/test_blue_green_switchover_loops.py index fc85a32cf..01b592004 100644 --- a/tests/unit/test_blue_green_switchover_loops.py +++ b/tests/unit/test_blue_green_switchover_loops.py @@ -169,7 +169,6 @@ def _post() -> BlueGreenStatus: @pytest.mark.timeout(20) -@pytest.mark.xfail(strict=True, reason="#1352: C1 sync execute keeps spinning on the IN_PROGRESS routing after the phase moves on") def test_suspended_execute_returns_after_switchover_moves_past_in_progress(): """An execute suspended during IN_PROGRESS runs and returns its result soon after the status moves to POST.""" published: List[Any] = [_in_progress()] @@ -184,7 +183,6 @@ def test_suspended_execute_returns_after_switchover_moves_past_in_progress(): @pytest.mark.timeout(20) -@pytest.mark.xfail(strict=True, reason="#1352: C2 sync connect keeps spinning on the IN_PROGRESS routing after the phase moves on") def test_suspended_connect_ends_after_switchover_moves_past_in_progress(): """A connect to a green host suspended during IN_PROGRESS fails with the reject routing's error soon after the status moves to POST, which rejects new connections to green hosts.""" @@ -212,7 +210,6 @@ def test_suspended_connect_ends_after_switchover_moves_past_in_progress(): @pytest.mark.timeout(20) -@pytest.mark.xfail(strict=True, reason="#1352: C3 bg_connect_timeout_ms doesn't bound the sync execute loop") def test_suspended_execute_with_short_connect_timeout_ends_after_switchover(): """With bg_connect_timeout_ms=500, an execute suspended during IN_PROGRESS returns its result or raises a timeout error within 3 s of the status moving to POST, long after that timeout has passed.""" From 294de40cd7f888c32aeb50c92047e657dd23f037 Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Thu, 12 Nov 2026 18:33:35 -0700 Subject: [PATCH 3/4] refactor: rename _IAM_PLUGIN_CODES to _IAM_TOKEN_AUTH_PLUGIN_CODES The set now holds the iam, federated_auth and okta plugin codes, all of which authenticate with an IAM token, so name it for that. --- aws_advanced_python_wrapper/aio/blue_green_plugin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index 1b002df9f..0ce8195c3 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -86,7 +86,7 @@ # Plugin codes (see aio/plugin_factory.py) whose presence implies IAM token # authentication is active, gating the SubstituteConnectRouting IAM-host # rerouting. Approximation of sync's plugin_service.is_plugin_in_use. -_IAM_PLUGIN_CODES: frozenset = frozenset({"iam", "federated_auth", "okta"}) +_IAM_TOKEN_AUTH_PLUGIN_CODES: frozenset = frozenset({"iam", "federated_auth", "okta"}) # ---- Enums ----------------------------------------------------------- @@ -616,7 +616,7 @@ def _is_iam_in_use(props: Properties) -> bool: if not plugins: return False codes = {code.strip() for code in str(plugins).split(",")} - return bool(codes & _IAM_PLUGIN_CODES) + return bool(codes & _IAM_TOKEN_AUTH_PLUGIN_CODES) # ---- Plugin ---------------------------------------------------------- From 4a53eee114ab5c87ba084d4c60141187e40428dd Mon Sep 17 00:00:00 2001 From: Juan Lee Date: Thu, 12 Nov 2026 20:43:54 -0700 Subject: [PATCH 4/4] refactor: rename _IAM_TOKEN_AUTH_PLUGIN_CODES to _AUTH_PLUGIN_CODES --- aws_advanced_python_wrapper/aio/blue_green_plugin.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/aws_advanced_python_wrapper/aio/blue_green_plugin.py b/aws_advanced_python_wrapper/aio/blue_green_plugin.py index 0ce8195c3..b1e53519a 100644 --- a/aws_advanced_python_wrapper/aio/blue_green_plugin.py +++ b/aws_advanced_python_wrapper/aio/blue_green_plugin.py @@ -86,7 +86,7 @@ # Plugin codes (see aio/plugin_factory.py) whose presence implies IAM token # authentication is active, gating the SubstituteConnectRouting IAM-host # rerouting. Approximation of sync's plugin_service.is_plugin_in_use. -_IAM_TOKEN_AUTH_PLUGIN_CODES: frozenset = frozenset({"iam", "federated_auth", "okta"}) +_AUTH_PLUGIN_CODES: frozenset = frozenset({"iam", "federated_auth", "okta"}) # ---- Enums ----------------------------------------------------------- @@ -616,7 +616,7 @@ def _is_iam_in_use(props: Properties) -> bool: if not plugins: return False codes = {code.strip() for code in str(plugins).split(",")} - return bool(codes & _IAM_TOKEN_AUTH_PLUGIN_CODES) + return bool(codes & _AUTH_PLUGIN_CODES) # ---- Plugin ----------------------------------------------------------