|
| 1 | +"""The listener warms the connection a publish will use (GH #880). |
| 2 | +
|
| 3 | +``publish`` runs under a 1 s budget in the request's response cycle, and the |
| 4 | +client's command connection opens lazily. Without a warm-up the first publish |
| 5 | +after boot, or after an outage, paid the TCP connect inside that second and lost |
| 6 | +the message under load. The listener PINGs the command client after every |
| 7 | +successful SUBSCRIBE, off the request path, so that connection is already open. |
| 8 | +""" |
| 9 | + |
| 10 | +from __future__ import annotations |
| 11 | + |
| 12 | +import asyncio |
| 13 | +import os |
| 14 | +import uuid |
| 15 | + |
| 16 | +import pytest |
| 17 | +from background_tasks.core import invalidation as bg_invalidation |
| 18 | +from background_tasks.core.invalidation import RedisInvalidationTransport |
| 19 | +from simple_module_core.invalidation import Invalidation, InvalidationBus |
| 20 | +from simple_module_test import wait_for |
| 21 | + |
| 22 | +_CHANNEL = "sm.invalidation.warmup" |
| 23 | + |
| 24 | + |
| 25 | +class _PubSub: |
| 26 | + def __init__(self, frames, subscribe_error) -> None: |
| 27 | + self._frames = list(frames) |
| 28 | + self._subscribe_error = subscribe_error |
| 29 | + self.subscribed = False |
| 30 | + |
| 31 | + async def subscribe(self, channel: str) -> None: |
| 32 | + if self._subscribe_error is not None: |
| 33 | + raise self._subscribe_error |
| 34 | + self.subscribed = True |
| 35 | + |
| 36 | + async def get_message(self, ignore_subscribe_messages: bool = False, timeout=None): |
| 37 | + if self._frames: |
| 38 | + return self._frames.pop(0) |
| 39 | + await asyncio.sleep(timeout or 0) # intentional-sleep: fake idle-channel poll interval |
| 40 | + return None |
| 41 | + |
| 42 | + async def aclose(self) -> None: ... |
| 43 | + |
| 44 | + |
| 45 | +class _Redis: |
| 46 | + """Records PINGs; the first ``fail_subscribes`` subscriptions raise.""" |
| 47 | + |
| 48 | + def __init__(self, frames=(), fail_subscribes=0, ping_error=None, ping_hangs=False) -> None: |
| 49 | + self.pings = 0 |
| 50 | + self.pubsubs: list[_PubSub] = [] |
| 51 | + self._frames = frames |
| 52 | + self._fail_subscribes = fail_subscribes |
| 53 | + self._ping_error = ping_error |
| 54 | + self._ping_hangs = ping_hangs |
| 55 | + |
| 56 | + def pubsub(self) -> _PubSub: |
| 57 | + error = None |
| 58 | + if self._fail_subscribes: |
| 59 | + self._fail_subscribes -= 1 |
| 60 | + error = ConnectionError("redis down") |
| 61 | + ps = _PubSub(self._frames, error) |
| 62 | + self.pubsubs.append(ps) |
| 63 | + return ps |
| 64 | + |
| 65 | + async def ping(self) -> bool: |
| 66 | + self.pings += 1 |
| 67 | + if self._ping_hangs: |
| 68 | + await asyncio.Event().wait() |
| 69 | + if self._ping_error is not None: |
| 70 | + raise self._ping_error |
| 71 | + return True |
| 72 | + |
| 73 | + async def aclose(self) -> None: ... |
| 74 | + |
| 75 | + |
| 76 | +@pytest.fixture |
| 77 | +def fake_redis(monkeypatch): |
| 78 | + import redis.asyncio as aioredis |
| 79 | + |
| 80 | + def install(**kwargs) -> _Redis: |
| 81 | + fake = _Redis(**kwargs) |
| 82 | + monkeypatch.setattr(aioredis, "from_url", lambda *a, **kw: fake) |
| 83 | + return fake |
| 84 | + |
| 85 | + monkeypatch.setattr(bg_invalidation, "INITIAL_BACKOFF_SECONDS", 0.01) |
| 86 | + monkeypatch.setattr(bg_invalidation, "LISTEN_POLL_SECONDS", 0.01) |
| 87 | + return install |
| 88 | + |
| 89 | + |
| 90 | +def _frame(key: str) -> dict: |
| 91 | + wire = Invalidation(channel=_CHANNEL, key=key, origin="elsewhere").to_wire() |
| 92 | + return {"type": "message", "data": wire.encode()} |
| 93 | + |
| 94 | + |
| 95 | +class TestWarmUp: |
| 96 | + async def test_the_listener_pings_once_it_has_subscribed(self, fake_redis): |
| 97 | + fake = fake_redis() |
| 98 | + transport = RedisInvalidationTransport(InvalidationBus(), "redis://fake", _CHANNEL) |
| 99 | + await transport.start() |
| 100 | + try: |
| 101 | + await wait_for(lambda: fake.pings == 1) |
| 102 | + assert fake.pubsubs[0].subscribed |
| 103 | + finally: |
| 104 | + await transport.stop() |
| 105 | + |
| 106 | + async def test_a_reconnect_warms_again(self, fake_redis): |
| 107 | + """A Redis restart drops both connections; the resubscribe re-warms.""" |
| 108 | + fake = fake_redis(fail_subscribes=1) |
| 109 | + transport = RedisInvalidationTransport(InvalidationBus(), "redis://fake", _CHANNEL) |
| 110 | + await transport.start() |
| 111 | + try: |
| 112 | + await wait_for(lambda: fake.pings == 1) |
| 113 | + assert [ps.subscribed for ps in fake.pubsubs] == [False, True] |
| 114 | + finally: |
| 115 | + await transport.stop() |
| 116 | + |
| 117 | + async def test_no_ping_before_a_subscribe_succeeds(self, fake_redis): |
| 118 | + fake = fake_redis(fail_subscribes=10**6) |
| 119 | + transport = RedisInvalidationTransport(InvalidationBus(), "redis://fake", _CHANNEL) |
| 120 | + await transport.start() |
| 121 | + try: |
| 122 | + await wait_for(lambda: len(fake.pubsubs) >= 3) |
| 123 | + assert fake.pings == 0 |
| 124 | + finally: |
| 125 | + await transport.stop() |
| 126 | + |
| 127 | + |
| 128 | +class TestAFailedWarmUpIsHarmless: |
| 129 | + @pytest.mark.parametrize("ping", ["raises", "hangs"]) |
| 130 | + async def test_the_listener_still_delivers(self, fake_redis, monkeypatch, ping): |
| 131 | + monkeypatch.setattr(bg_invalidation, "SUBSCRIBE_TIMEOUT_SECONDS", 0.05) |
| 132 | + if ping == "raises": |
| 133 | + fake = fake_redis(frames=[_frame("k")], ping_error=ConnectionError("no")) |
| 134 | + else: |
| 135 | + fake = fake_redis(frames=[_frame("k")], ping_hangs=True) |
| 136 | + bus = InvalidationBus() |
| 137 | + seen: list[Invalidation] = [] |
| 138 | + bus.subscribe(_CHANNEL, seen.append) |
| 139 | + transport = RedisInvalidationTransport(bus, "redis://fake", _CHANNEL) |
| 140 | + await transport.start() |
| 141 | + try: |
| 142 | + await wait_for(lambda: bool(seen)) |
| 143 | + finally: |
| 144 | + await transport.stop() |
| 145 | + |
| 146 | + assert [i.key for i in seen] == ["k"] |
| 147 | + assert len(fake.pubsubs) == 1, "a failed warm-up must not restart the listener" |
| 148 | + |
| 149 | + |
| 150 | +class TestAgainstARealServer: |
| 151 | + async def test_a_publish_reuses_the_warmed_connection(self, redis_server): |
| 152 | + """The server sees the PING'd connection, and the publish arrives on it. |
| 153 | +
|
| 154 | + Clients are found by a per-test ``client_name`` (parsed from the URL by |
| 155 | + redis-py): under xdist every worker shares one Redis, so counting all of |
| 156 | + the server's clients would race the other workers. |
| 157 | + """ |
| 158 | + import redis.asyncio as aioredis |
| 159 | + |
| 160 | + name = f"sm-warmup-{os.getpid()}-{uuid.uuid4().hex[:8]}" |
| 161 | + sep = "&" if "?" in redis_server else "?" |
| 162 | + transport = RedisInvalidationTransport( |
| 163 | + InvalidationBus(), f"{redis_server}{sep}client_name={name}", _CHANNEL |
| 164 | + ) |
| 165 | + probe = aioredis.from_url(redis_server) |
| 166 | + |
| 167 | + async def ours() -> list[dict]: |
| 168 | + return [c for c in await probe.client_list() if c.get("name") == name] |
| 169 | + |
| 170 | + async def warmed() -> list[dict]: |
| 171 | + clients = await ours() |
| 172 | + return clients if any(c["cmd"] == "ping" for c in clients) else [] |
| 173 | + |
| 174 | + await transport.start() |
| 175 | + try: |
| 176 | + before = await wait_for(warmed, timeout=5.0) |
| 177 | + await transport.publish( |
| 178 | + Invalidation(channel=_CHANNEL, key="k", origin="elsewhere").to_wire() |
| 179 | + ) |
| 180 | + after = await ours() |
| 181 | + finally: |
| 182 | + await transport.stop() |
| 183 | + await probe.aclose() |
| 184 | + |
| 185 | + assert len(before) == 2, "expected the subscription plus one warmed command connection" |
| 186 | + warmed_id = next(c["id"] for c in before if c["cmd"] == "ping") |
| 187 | + assert {c["id"] for c in after} == {c["id"] for c in before}, ( |
| 188 | + "publish opened a new connection" |
| 189 | + ) |
| 190 | + assert next(c["cmd"] for c in after if c["id"] == warmed_id) == "publish" |
0 commit comments