|
| 1 | +"""Rate-limit parsing + sliding-window counter + e2e enforcement.""" |
| 2 | + |
| 3 | +import asyncio |
| 4 | +import socket |
| 5 | +import threading |
| 6 | +import time |
| 7 | + |
| 8 | +import pytest |
| 9 | + |
| 10 | +from zhub.ratelimit import parse_rate, SlidingWindow |
| 11 | + |
| 12 | + |
| 13 | +def test_parse_rate_per_second(): |
| 14 | + assert parse_rate("10/s") == (10, 1.0) |
| 15 | + |
| 16 | + |
| 17 | +def test_parse_rate_per_minute(): |
| 18 | + assert parse_rate("60/min") == (60, 60.0) |
| 19 | + |
| 20 | + |
| 21 | +def test_parse_rate_per_hour(): |
| 22 | + assert parse_rate("1000/hour") == (1000, 3600.0) |
| 23 | + |
| 24 | + |
| 25 | +def test_parse_rate_per_day(): |
| 26 | + assert parse_rate("100000/day") == (100000, 86400.0) |
| 27 | + |
| 28 | + |
| 29 | +def test_parse_rate_default_when_unset(): |
| 30 | + assert parse_rate(None) == (60, 60.0) |
| 31 | + assert parse_rate("") == (60, 60.0) |
| 32 | + |
| 33 | + |
| 34 | +def test_parse_rate_garbage_falls_back_to_default(): |
| 35 | + assert parse_rate("not-a-rate") == (60, 60.0) |
| 36 | + assert parse_rate("60") == (60, 60.0) |
| 37 | + assert parse_rate("/min") == (60, 60.0) |
| 38 | + |
| 39 | + |
| 40 | +def test_sliding_window_under_limit_allows(): |
| 41 | + clock = [0.0] |
| 42 | + w = SlidingWindow(limit=3, period_seconds=10.0, now_fn=lambda: clock[0]) |
| 43 | + assert w.check("k") == (True, None) |
| 44 | + clock[0] = 1.0 |
| 45 | + assert w.check("k") == (True, None) |
| 46 | + clock[0] = 2.0 |
| 47 | + assert w.check("k") == (True, None) |
| 48 | + |
| 49 | + |
| 50 | +def test_sliding_window_at_limit_denies(): |
| 51 | + clock = [0.0] |
| 52 | + w = SlidingWindow(limit=3, period_seconds=10.0, now_fn=lambda: clock[0]) |
| 53 | + for _ in range(3): |
| 54 | + ok, _ = w.check("k") |
| 55 | + assert ok |
| 56 | + ok, retry_after = w.check("k") |
| 57 | + assert ok is False |
| 58 | + assert retry_after is not None and retry_after > 0 |
| 59 | + |
| 60 | + |
| 61 | +def test_sliding_window_expires_old_hits(): |
| 62 | + clock = [0.0] |
| 63 | + w = SlidingWindow(limit=2, period_seconds=10.0, now_fn=lambda: clock[0]) |
| 64 | + assert w.check("k")[0] is True |
| 65 | + assert w.check("k")[0] is True |
| 66 | + assert w.check("k")[0] is False # at limit |
| 67 | + clock[0] = 11.0 # past the 10s window |
| 68 | + assert w.check("k")[0] is True |
| 69 | + |
| 70 | + |
| 71 | +def test_sliding_window_per_key_isolation(): |
| 72 | + clock = [0.0] |
| 73 | + w = SlidingWindow(limit=1, period_seconds=10.0, now_fn=lambda: clock[0]) |
| 74 | + assert w.check("a")[0] is True |
| 75 | + assert w.check("b")[0] is True # different key, different bucket |
| 76 | + assert w.check("a")[0] is False # a hit limit |
| 77 | + |
| 78 | + |
| 79 | +# ---- e2e enforcement ---- |
| 80 | + |
| 81 | +try: |
| 82 | + import fastapi # noqa |
| 83 | + import uvicorn # noqa |
| 84 | + SERVER_AVAILABLE = True |
| 85 | +except ImportError: |
| 86 | + SERVER_AVAILABLE = False |
| 87 | + |
| 88 | +if SERVER_AVAILABLE: |
| 89 | + from zhub.server import create_app |
| 90 | +from zhub import publish, Manifest, Capability |
| 91 | + |
| 92 | + |
| 93 | +def _free_port() -> int: |
| 94 | + with socket.socket() as s: |
| 95 | + s.bind(("", 0)) |
| 96 | + return s.getsockname()[1] |
| 97 | + |
| 98 | + |
| 99 | +@pytest.fixture(scope="module") |
| 100 | +def hub_port(): |
| 101 | + if not SERVER_AVAILABLE: |
| 102 | + pytest.skip("fastapi/uvicorn not installed") |
| 103 | + port = _free_port() |
| 104 | + |
| 105 | + def run(): |
| 106 | + config = uvicorn.Config(create_app(), host="127.0.0.1", port=port, log_level="warning") |
| 107 | + asyncio.run(uvicorn.Server(config).serve()) |
| 108 | + |
| 109 | + threading.Thread(target=run, daemon=True).start() |
| 110 | + for _ in range(30): |
| 111 | + try: |
| 112 | + with socket.create_connection(("127.0.0.1", port), timeout=0.1): |
| 113 | + break |
| 114 | + except OSError: |
| 115 | + time.sleep(0.1) |
| 116 | + yield port |
| 117 | + |
| 118 | + |
| 119 | +@pytest.mark.asyncio |
| 120 | +async def test_rate_limit_429_after_quota(hub_port): |
| 121 | + """Publisher with 3/s rate limit. Hit chat endpoint 4x rapidly. First 3 |
| 122 | + succeed; 4th returns 429 with Retry-After header + body.""" |
| 123 | + if not SERVER_AVAILABLE: |
| 124 | + pytest.skip() |
| 125 | + |
| 126 | + pub = publish( |
| 127 | + name="rl", |
| 128 | + description="rate limit test", |
| 129 | + chat_handler=lambda m, o: "ok", |
| 130 | + hub_url=f"ws://127.0.0.1:{hub_port}", |
| 131 | + rate_limit="3/s", |
| 132 | + ) |
| 133 | + for _ in range(50): |
| 134 | + if pub.api_key: |
| 135 | + break |
| 136 | + await asyncio.sleep(0.05) |
| 137 | + assert pub.api_key |
| 138 | + |
| 139 | + import httpx |
| 140 | + base = f"http://127.0.0.1:{hub_port}/rl/v1/chat/completions" |
| 141 | + headers = {"Authorization": f"Bearer {pub.api_key}", "Content-Type": "application/json"} |
| 142 | + body = {"messages": [{"role": "user", "content": "hi"}]} |
| 143 | + |
| 144 | + async with httpx.AsyncClient() as c: |
| 145 | + # First 3 should succeed |
| 146 | + for i in range(3): |
| 147 | + r = await c.post(base, json=body, headers=headers) |
| 148 | + assert r.status_code == 200, f"call #{i+1}: {r.status_code} {r.text}" |
| 149 | + # 4th should be rate-limited |
| 150 | + r4 = await c.post(base, json=body, headers=headers) |
| 151 | + assert r4.status_code == 429, f"expected 429, got {r4.status_code}: {r4.text}" |
| 152 | + assert "Retry-After" in r4.headers, f"missing Retry-After header: {dict(r4.headers)}" |
| 153 | + body_json = r4.json() |
| 154 | + assert body_json["error"]["code"] == "rate_limited" |
| 155 | + |
| 156 | + |
| 157 | +@pytest.mark.asyncio |
| 158 | +async def test_rate_limit_per_publisher_isolation(hub_port): |
| 159 | + """Two publishers with separate rate limits don't interfere with each other.""" |
| 160 | + if not SERVER_AVAILABLE: |
| 161 | + pytest.skip() |
| 162 | + |
| 163 | + pub_a = publish(name="rla", description="a", chat_handler=lambda m, o: "a", |
| 164 | + hub_url=f"ws://127.0.0.1:{hub_port}", rate_limit="2/s") |
| 165 | + pub_b = publish(name="rlb", description="b", chat_handler=lambda m, o: "b", |
| 166 | + hub_url=f"ws://127.0.0.1:{hub_port}", rate_limit="2/s") |
| 167 | + for _ in range(50): |
| 168 | + if pub_a.api_key and pub_b.api_key: |
| 169 | + break |
| 170 | + await asyncio.sleep(0.05) |
| 171 | + |
| 172 | + import httpx |
| 173 | + body = {"messages": [{"role": "user", "content": "hi"}]} |
| 174 | + async with httpx.AsyncClient() as c: |
| 175 | + # Exhaust A's quota |
| 176 | + for _ in range(2): |
| 177 | + r = await c.post(f"http://127.0.0.1:{hub_port}/rla/v1/chat/completions", |
| 178 | + json=body, headers={"Authorization": f"Bearer {pub_a.api_key}"}) |
| 179 | + assert r.status_code == 200 |
| 180 | + r = await c.post(f"http://127.0.0.1:{hub_port}/rla/v1/chat/completions", |
| 181 | + json=body, headers={"Authorization": f"Bearer {pub_a.api_key}"}) |
| 182 | + assert r.status_code == 429 |
| 183 | + # B is unaffected |
| 184 | + r = await c.post(f"http://127.0.0.1:{hub_port}/rlb/v1/chat/completions", |
| 185 | + json=body, headers={"Authorization": f"Bearer {pub_b.api_key}"}) |
| 186 | + assert r.status_code == 200 |
0 commit comments