|
| 1 | +# ============================================================================= |
| 2 | +# MIT License |
| 3 | +# Copyright (c) 2024 RocketRide Inc. |
| 4 | +# ============================================================================= |
| 5 | + |
| 6 | +"""Unit tests for the token-bucket rate limiter.""" |
| 7 | + |
| 8 | +from __future__ import annotations |
| 9 | + |
| 10 | +import threading |
| 11 | +import time |
| 12 | + |
| 13 | +import sys |
| 14 | +from pathlib import Path |
| 15 | + |
| 16 | +import pytest |
| 17 | + |
| 18 | +# Add the node source directory to sys.path so we can import the module |
| 19 | +# without triggering the top-level nodes/__init__.py (which requires the |
| 20 | +# engine runtime). |
| 21 | +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / 'src' / 'nodes' / 'tool_http_request')) |
| 22 | + |
| 23 | +from rate_limiter import RateLimiter, RateLimitError # noqa: E402 |
| 24 | + |
| 25 | + |
| 26 | +class TestAcquireRelease: |
| 27 | + """Normal acquire / release cycle.""" |
| 28 | + |
| 29 | + def test_single_acquire_release(self): |
| 30 | + rl = RateLimiter(max_per_second=5, max_per_minute=100, max_concurrent=2) |
| 31 | + rl.acquire() |
| 32 | + rl.release() |
| 33 | + |
| 34 | + def test_multiple_sequential_acquires(self): |
| 35 | + rl = RateLimiter(max_per_second=3, max_per_minute=100, max_concurrent=3) |
| 36 | + for _ in range(3): |
| 37 | + rl.acquire() |
| 38 | + for _ in range(3): |
| 39 | + rl.release() |
| 40 | + |
| 41 | + |
| 42 | +class TestPerSecondEnforcement: |
| 43 | + """Per-second token bucket rejects once exhausted.""" |
| 44 | + |
| 45 | + def test_exceeds_per_second_limit(self): |
| 46 | + rl = RateLimiter(max_per_second=2, max_per_minute=100, max_concurrent=10) |
| 47 | + rl.acquire() |
| 48 | + rl.acquire() |
| 49 | + with pytest.raises(RateLimitError, match='per second'): |
| 50 | + rl.acquire() |
| 51 | + # Clean up |
| 52 | + rl.release() |
| 53 | + rl.release() |
| 54 | + |
| 55 | + def test_per_second_refills_over_time(self): |
| 56 | + rl = RateLimiter(max_per_second=2, max_per_minute=100, max_concurrent=10) |
| 57 | + rl.acquire() |
| 58 | + rl.acquire() |
| 59 | + rl.release() |
| 60 | + rl.release() |
| 61 | + # Wait long enough for tokens to refill |
| 62 | + time.sleep(1.1) |
| 63 | + rl.acquire() |
| 64 | + rl.release() |
| 65 | + |
| 66 | + |
| 67 | +class TestPerMinuteEnforcement: |
| 68 | + """Per-minute token bucket rejects once exhausted.""" |
| 69 | + |
| 70 | + def test_exceeds_per_minute_limit(self): |
| 71 | + rl = RateLimiter(max_per_second=100, max_per_minute=3, max_concurrent=10) |
| 72 | + rl.acquire() |
| 73 | + rl.acquire() |
| 74 | + rl.acquire() |
| 75 | + with pytest.raises(RateLimitError, match='per minute'): |
| 76 | + rl.acquire() |
| 77 | + for _ in range(3): |
| 78 | + rl.release() |
| 79 | + |
| 80 | + |
| 81 | +class TestSemaphoreExhaustion: |
| 82 | + """Concurrency semaphore rejects when all slots are occupied.""" |
| 83 | + |
| 84 | + def test_exceeds_concurrent_limit(self): |
| 85 | + rl = RateLimiter(max_per_second=100, max_per_minute=100, max_concurrent=2) |
| 86 | + rl.acquire() |
| 87 | + rl.acquire() |
| 88 | + with pytest.raises(RateLimitError, match='concurrent'): |
| 89 | + rl.acquire() |
| 90 | + rl.release() |
| 91 | + rl.release() |
| 92 | + |
| 93 | + def test_release_frees_slot(self): |
| 94 | + rl = RateLimiter(max_per_second=100, max_per_minute=100, max_concurrent=1) |
| 95 | + rl.acquire() |
| 96 | + rl.release() |
| 97 | + # Should succeed now that the slot is freed. |
| 98 | + rl.acquire() |
| 99 | + rl.release() |
| 100 | + |
| 101 | + |
| 102 | +class TestTokenRestorationOnSemaphoreRejection: |
| 103 | + """Tokens must NOT be consumed when the semaphore rejects the request.""" |
| 104 | + |
| 105 | + def test_tokens_preserved_after_semaphore_rejection(self): |
| 106 | + rl = RateLimiter(max_per_second=2, max_per_minute=100, max_concurrent=1) |
| 107 | + |
| 108 | + # Use up the only concurrency slot. |
| 109 | + rl.acquire() |
| 110 | + |
| 111 | + # This should fail on the semaphore. Tokens must not be consumed. |
| 112 | + with pytest.raises(RateLimitError, match='concurrent'): |
| 113 | + rl.acquire() |
| 114 | + |
| 115 | + # Release the held slot. |
| 116 | + rl.release() |
| 117 | + |
| 118 | + # We should still have 1 per-second token left (only 1 was consumed |
| 119 | + # by the first successful acquire). If the bug existed (tokens |
| 120 | + # consumed before semaphore check) this second acquire would fail |
| 121 | + # with a per-second error. |
| 122 | + rl.acquire() |
| 123 | + rl.release() |
| 124 | + |
| 125 | + def test_semaphore_not_leaked_on_token_rejection(self): |
| 126 | + """Semaphore slot is released when token-bucket check fails. |
| 127 | +
|
| 128 | + With max_concurrent=2 and max_per_second=2: after two successful |
| 129 | + acquires exhaust the per-second tokens, a third acquire will pass |
| 130 | + the semaphore but fail on tokens. The implementation must release |
| 131 | + the semaphore slot in that case. We verify by releasing all held |
| 132 | + slots, waiting for token refill, then acquiring both concurrent |
| 133 | + slots again — which would fail if one was leaked. |
| 134 | + """ |
| 135 | + rl = RateLimiter(max_per_second=2, max_per_minute=100, max_concurrent=2) |
| 136 | + |
| 137 | + # Exhaust both per-second tokens (each also takes a semaphore slot). |
| 138 | + rl.acquire() |
| 139 | + rl.acquire() |
| 140 | + |
| 141 | + # Release one semaphore slot so the next acquire can get past the |
| 142 | + # semaphore check and fail on the token bucket instead. |
| 143 | + rl.release() |
| 144 | + |
| 145 | + # This acquire gets a semaphore slot but fails on per-second tokens. |
| 146 | + with pytest.raises(RateLimitError, match='per second'): |
| 147 | + rl.acquire() |
| 148 | + |
| 149 | + # Release the remaining held slot. |
| 150 | + rl.release() |
| 151 | + |
| 152 | + # Wait for per-second tokens to fully refill (capacity=2). |
| 153 | + time.sleep(1.2) |
| 154 | + |
| 155 | + # Both semaphore slots should be free. If the failed acquire |
| 156 | + # leaked a slot, the second acquire here would raise a |
| 157 | + # concurrency error. |
| 158 | + rl.acquire() |
| 159 | + rl.acquire() |
| 160 | + rl.release() |
| 161 | + rl.release() |
| 162 | + |
| 163 | + |
| 164 | +class TestThreadSafety: |
| 165 | + """Basic smoke test for concurrent usage.""" |
| 166 | + |
| 167 | + def test_concurrent_acquires(self): |
| 168 | + rl = RateLimiter(max_per_second=50, max_per_minute=500, max_concurrent=5) |
| 169 | + errors: list[Exception] = [] |
| 170 | + |
| 171 | + def worker(): |
| 172 | + try: |
| 173 | + rl.acquire() |
| 174 | + time.sleep(0.01) |
| 175 | + rl.release() |
| 176 | + except RateLimitError: |
| 177 | + pass |
| 178 | + except Exception as exc: |
| 179 | + errors.append(exc) |
| 180 | + |
| 181 | + threads = [threading.Thread(target=worker) for _ in range(20)] |
| 182 | + for t in threads: |
| 183 | + t.start() |
| 184 | + for t in threads: |
| 185 | + t.join(timeout=5) |
| 186 | + |
| 187 | + assert not errors, f'Unexpected errors in threads: {errors}' |
0 commit comments