feat(api): rate limit Libro.fm API calls (#15)
Implement a rate limiter for concurrent Libro.fm API requests to prevent overwhelming the service, especially during parallel downloads. This caps concurrent lookup calls for M4B, MP3, and PDF, while allowing CDN downloads and initial authentication/library fetching to proceed unimpeded.
This commit is contained in:
4 files changed
+319
-16
No files matched your search
@@ -327,3 +327,241 @@ class TestFetchPdfExtraUrl:
|
||||
|
||||
with pytest.raises(AuthError, match="Not authenticated"):
|
||||
client.fetch_pdf_extra_url("9781234567890", "map.pdf")
|
||||
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# API Rate Limiter — Issue #15
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
import threading
|
||||
import time
|
||||
|
||||
|
||||
class TestApiRateLimiter:
|
||||
"""threading.Semaphore(3) caps concurrent Libro.fm API calls.
|
||||
|
||||
Applied to: fetch_m4b_url, fetch_download_manifest, fetch_pdf_extra_url.
|
||||
NOT applied to: authenticate, fetch_library, CDN downloads.
|
||||
"""
|
||||
|
||||
def test_semaphore_blocks_at_capacity(self):
|
||||
"""4 concurrent callers: 3 proceed immediately, 4th blocks until one finishes."""
|
||||
client = LibroFmClient(
|
||||
base_url="https://libro.fm",
|
||||
username="alice",
|
||||
password="secret123",
|
||||
)
|
||||
|
||||
call_can_finish: threading.Event = threading.Event()
|
||||
state_lock = threading.Lock()
|
||||
state = {"in_flight": 0, "max_in_flight": 0}
|
||||
|
||||
def slow_handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
with state_lock:
|
||||
state["in_flight"] += 1
|
||||
if state["in_flight"] > state["max_in_flight"]:
|
||||
state["max_in_flight"] = state["in_flight"]
|
||||
call_can_finish.wait(timeout=5)
|
||||
with state_lock:
|
||||
state["in_flight"] -= 1
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"m4b_url": "https://cdn.libro.fm/test.m4b"},
|
||||
)
|
||||
|
||||
transport = httpx.MockTransport(slow_handler)
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
errors: list[BaseException] = []
|
||||
|
||||
def fetch_thread(isbn: str):
|
||||
try:
|
||||
client.fetch_m4b_url(isbn, transport=transport)
|
||||
except BaseException as exc:
|
||||
errors.append(exc)
|
||||
|
||||
threads = [
|
||||
threading.Thread(target=fetch_thread, args=(f"978{i}",))
|
||||
for i in range(4)
|
||||
]
|
||||
for t in threads:
|
||||
t.start()
|
||||
|
||||
time.sleep(0.5)
|
||||
call_can_finish.set()
|
||||
for t in threads:
|
||||
t.join(timeout=10)
|
||||
|
||||
assert not errors, f"Unexpected errors: {errors}"
|
||||
assert state["max_in_flight"] <= 3, (
|
||||
f"Max in-flight was {state['max_in_flight']}, expected <= 3"
|
||||
)
|
||||
|
||||
def test_semaphore_releases_on_exception(self):
|
||||
"""Semaphore is released even when the API call raises an exception."""
|
||||
client = LibroFmClient(
|
||||
base_url="https://libro.fm",
|
||||
username="alice",
|
||||
password="secret123",
|
||||
)
|
||||
|
||||
call_number = [1] # Use list for mutability in closure
|
||||
|
||||
def handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
n = call_number[0]
|
||||
call_number[0] += 1
|
||||
if n == 2:
|
||||
return httpx.Response(404)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"m4b_url": "https://cdn.libro.fm/test.m4b"},
|
||||
)
|
||||
|
||||
transport = httpx.MockTransport(handler)
|
||||
client.authenticate(transport=transport)
|
||||
|
||||
# First call should succeed (releases semaphore normally)
|
||||
result = client.fetch_m4b_url("978111", transport=transport)
|
||||
assert result == "https://cdn.libro.fm/test.m4b"
|
||||
|
||||
# Second call should raise (semaphore must still be released after this)
|
||||
with pytest.raises(M4BUnavailableError):
|
||||
client.fetch_m4b_url("978222", transport=transport)
|
||||
|
||||
# Third call should succeed — proves semaphore was released by the failed call
|
||||
result3 = client.fetch_m4b_url("978333", transport=transport)
|
||||
assert result3 == "https://cdn.libro.fm/test.m4b"
|
||||
|
||||
def test_cdn_downloads_bypass_semaphore(self):
|
||||
"""CDN downloads (download_m4b, download_zip_part) are NOT limited by the API semaphore."""
|
||||
import tempfile
|
||||
|
||||
from librofm_downloader.downloader import download_m4b
|
||||
|
||||
client = LibroFmClient(
|
||||
base_url="https://libro.fm",
|
||||
username="alice",
|
||||
password="secret123",
|
||||
)
|
||||
|
||||
# Fill all 3 API semaphore slots with slow calls that block
|
||||
api_calls_blocked: threading.Event = threading.Event()
|
||||
|
||||
def slow_api_handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
# Block — holds the semaphore slot indefinitely (until test ends)
|
||||
api_calls_blocked.wait(timeout=5)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"m4b_url": "https://cdn.libro.fm/test.m4b"},
|
||||
)
|
||||
|
||||
api_transport = httpx.MockTransport(slow_api_handler)
|
||||
client.authenticate(transport=api_transport)
|
||||
|
||||
# Occupy all 3 semaphore slots with blocked API calls
|
||||
api_threads = [
|
||||
threading.Thread(target=client.fetch_m4b_url, args=(f"978block{i}",), kwargs={"transport": api_transport})
|
||||
for i in range(3)
|
||||
]
|
||||
for t in api_threads:
|
||||
t.start()
|
||||
time.sleep(0.2) # Let them acquire the semaphore
|
||||
|
||||
# Now try a CDN download — it should succeed immediately, not block on semaphore
|
||||
cdn_started = False
|
||||
|
||||
def cdn_handler(request: httpx.Request) -> httpx.Response:
|
||||
nonlocal cdn_started
|
||||
cdn_started = True
|
||||
return httpx.Response(200, content=b"fake m4b data")
|
||||
|
||||
cdn_transport = httpx.MockTransport(cdn_handler)
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmpdir:
|
||||
output_path = f"{tmpdir}/test.m4b"
|
||||
# This should NOT block even though all 3 API slots are occupied
|
||||
result = download_m4b("https://cdn.example.com/test.m4b", output_path, transport=cdn_transport)
|
||||
assert result.name.endswith("test.m4b")
|
||||
|
||||
assert cdn_started, "CDN download should have proceeded without waiting for API semaphore"
|
||||
|
||||
# Clean up blocked threads
|
||||
api_calls_blocked.set()
|
||||
for t in api_threads:
|
||||
t.join(timeout=5)
|
||||
|
||||
def test_authenticate_and_fetch_library_not_limited(self):
|
||||
"""authenticate() and fetch_library() do NOT acquire the API semaphore."""
|
||||
client = LibroFmClient(
|
||||
base_url="https://libro.fm",
|
||||
username="alice",
|
||||
password="secret123",
|
||||
)
|
||||
|
||||
# Fill all 3 API semaphore slots with blocked calls
|
||||
api_calls_blocked: threading.Event = threading.Event()
|
||||
|
||||
def slow_api_handler(request: httpx.Request) -> httpx.Response:
|
||||
if request.url.path == "/oauth/token":
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_abc", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
api_calls_blocked.wait(timeout=5)
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"m4b_url": "https://cdn.libro.fm/test.m4b"},
|
||||
)
|
||||
|
||||
api_transport = httpx.MockTransport(slow_api_handler)
|
||||
client.authenticate(transport=api_transport)
|
||||
|
||||
# Occupy all 3 slots
|
||||
api_threads = [
|
||||
threading.Thread(target=client.fetch_m4b_url, args=(f"978block{i}",), kwargs={"transport": api_transport})
|
||||
for i in range(3)
|
||||
]
|
||||
for t in api_threads:
|
||||
t.start()
|
||||
time.sleep(0.2)
|
||||
|
||||
# authenticate() should work fine — it doesn't use the semaphore
|
||||
def auth_handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(
|
||||
200,
|
||||
json={"access_token": "tok_new", "token_type": "bearer", "expires_in": 7200},
|
||||
)
|
||||
|
||||
auth_transport = httpx.MockTransport(auth_handler)
|
||||
token = client.authenticate(transport=auth_transport)
|
||||
assert token == "tok_new"
|
||||
|
||||
# fetch_library() should also work — it doesn't use the semaphore
|
||||
def library_handler(request: httpx.Request) -> httpx.Response:
|
||||
return httpx.Response(200, json={"audiobooks": []})
|
||||
|
||||
library_transport = httpx.MockTransport(library_handler)
|
||||
books = client.fetch_library(transport=library_transport)
|
||||
assert books == []
|
||||
|
||||
# Clean up
|
||||
api_calls_blocked.set()
|
||||
for t in api_threads:
|
||||
t.join(timeout=5)
|
||||
Reference in new issue
Block a user