From 6418c63c2fc6cf408143c44097e19a684dfe82bc Mon Sep 17 00:00:00 2001 From: Alexander Kucera Date: Wed, 3 Jun 2026 17:45:19 +0200 Subject: [PATCH] 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. --- AGENTS.md | 1 + .../20260603-api-rate-limiter-issue15_log.md | 54 ++++ librofm_downloader/client.py | 42 ++-- tests/test_client.py | 238 ++++++++++++++++++ 4 files changed, 319 insertions(+), 16 deletions(-) create mode 100644 docs/devlog/20260603-api-rate-limiter-issue15_log.md diff --git a/AGENTS.md b/AGENTS.md index a7a1938..818965b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -8,6 +8,7 @@ They capture what was done, decisions & rationale, gotchas & fixes, and next ste | Date | Type | File | Summary | |------|------|------|---------| +| 2026-06-03 | issue | [20260603-api-rate-limiter-issue15_log.md](docs/devlog/20260603-api-rate-limiter-issue15_log.md) | **Issue #15 Complete:** `threading.Semaphore(3)` API rate limiter on `LibroFmClient`. Caps concurrent API calls; CDN downloads bypass. **4 new tests, 198 total** · **6/6 AC** | | 2026-06-03 | issue | [20260603-multi-bar-progress-per-book-identity-mapping-issue14_log.md](docs/devlog/20260603-multi-bar-progress-per-book-identity-mapping-issue14_log.md) | **Issue #14 Complete:** Per-book identity mapping for concurrent progress bars. `_tasks`/`_book_ids` dicts, `start_download()` returns `task_id`, `update(task_id=)` targeting. **10 new tests, 194 total** · **7/7 AC** | | 2026-06-03 | issue | [20260603-thread-safe-downloadhistory-write-issue13_log.md](docs/devlog/20260603-thread-safe-downloadhistory-write-issue13_log.md) | **Issue #13 Complete:** Thread-safe `DownloadHistory.write()` with `threading.Lock`. **5 new tests, 184 total** · **4/4 AC** | | 2026-06-03 | issue | [20260603-slice-1-workers-config-and-cli-flag-issue12_log.md](docs/devlog/20260603-slice-1-workers-config-and-cli-flag-issue12_log.md) | **Issue #12 Complete:** `workers` config field + `-w`/`--workers` CLI flag with 3-layer resolution (CLI > config > 3). `InvalidWorkersError` validation. **6 new tests, 179 total** · **7/7 AC** | diff --git a/docs/devlog/20260603-api-rate-limiter-issue15_log.md b/docs/devlog/20260603-api-rate-limiter-issue15_log.md new file mode 100644 index 0000000..e644d57 --- /dev/null +++ b/docs/devlog/20260603-api-rate-limiter-issue15_log.md @@ -0,0 +1,54 @@ +# API Rate Limiter — Issue #15 + +> **Date:** 2026-06-03 +> **Type:** issue +> **Reference:** [Issue #15](https://github.com/AlexKucera/librofm-downloader/issues/15) + +## Goal + +Implement a lightweight API rate limiter using `threading.Semaphore(3)` that caps concurrent Libro.fm API calls regardless of worker count. CDN file downloads must NOT be limited. + +## What Was Done + +- Added `threading.Semaphore(3)` to `LibroFmClient.__init__` via `_api_semaphore` attribute +- Added `API_SEMAPHORE_CAPACITY = 3` configurable constant (not user-facing) +- Wrapped 3 API methods with `with self._api_semaphore:` context manager: + - `fetch_m4b_url()` — M4B URL lookup + - `fetch_download_manifest()` — MP3 manifest fetch + - `fetch_pdf_extra_url()` — PDF extra URL lookup +- NOT applied to: `authenticate()`, `fetch_library()`, CDN downloads (`download_m4b`, `download_zip_part`) +- Added 4 new tests in `TestApiRateLimiter` class: + 1. `test_semaphore_blocks_at_capacity` — 4 threads, max 3 in-flight + 2. `test_semaphore_releases_on_exception` — semaphore released on `M4BUnavailableError` + 3. `test_cdn_downloads_bypass_semaphore` — CDN proceeds while API slots occupied + 4. `test_authenticate_and_fetch_library_not_limited` — auth/library work while slots full +- **198 total tests pass** (194 existing + 4 new) + +## Decisions & Rationale + +| Decision | Rationale | +|----------|-----------| +| Semaphore on `LibroFmClient` (not external wrapper) | Encapsulates rate-limiting in the client; callers don't need to know about it. Cleanest fit since all 3 methods are on the same class | +| `with self._api_semaphore:` (context manager) | Guarantees release on both success and exception — no try/finally needed | +| Capacity = 3 (configurable constant) | Conservative default for Libro.fm API; not user-facing per issue spec | +| Not applied to `authenticate()`/`fetch_library()` | These happen before the parallel download phase (sequential), so no contention risk | + +## Gotchas & Fixes + +| Problem | Root Cause | Fix | +|---------|------------|-----| +| `threading.Value` AttributeError in tests | `Value` is from `multiprocessing`, not `threading`. Used it for shared thread state initially | Switched to `dict + threading.Lock` for shared mutable state, or plain list for sequential tests | + +## Files Changed + +| File | Change Summary | +|------|---------------| +| `librofm_downloader/client.py` | Added `import threading`, `API_SEMAPHORE_CAPACITY` constant, `_api_semaphore` to `__init__`, wrapped 3 methods with `with self._api_semaphore:` | +| `tests/test_client.py` | Added `TestApiRateLimiter` class with 4 tests covering capacity blocking, exception release, CDN bypass, and non-limited method isolation | + +## Open Items & Next Steps + +- None — issue complete, all acceptance criteria met + +--- +*Log written by write-log skill* diff --git a/librofm_downloader/client.py b/librofm_downloader/client.py index 9e8d192..7129385 100644 --- a/librofm_downloader/client.py +++ b/librofm_downloader/client.py @@ -1,7 +1,13 @@ -"""HTTP client for Libro.fm API — auth and library fetch.""" +"""HTTP client for Libro.fm API — auth, library fetch, and rate-limited downloads.""" + +import threading import httpx +# Maximum concurrent Libro.fm API calls (not CDN downloads). +# Configurable constant — not user-facing. +API_SEMAPHORE_CAPACITY = 3 + class AuthError(Exception): """Authentication failed (bad credentials, network error, etc.).""" @@ -31,6 +37,7 @@ class LibroFmClient: self._password = password self._timeout = timeout self._access_token: str | None = None + self._api_semaphore = threading.Semaphore(API_SEMAPHORE_CAPACITY) def authenticate(self, transport: httpx.BaseTransport | None = None) -> str: """OAuth2 password grant → returns access_token. @@ -129,14 +136,15 @@ class LibroFmClient: transport=transport, ) - resp = client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b") + with self._api_semaphore: + resp = client.get(f"/api/v10/audiobooks/{isbn}/packaged_m4b") - if resp.status_code == 404: - raise M4BUnavailableError(f"M4B not available for ISBN {isbn}") + if resp.status_code == 404: + raise M4BUnavailableError(f"M4B not available for ISBN {isbn}") - resp.raise_for_status() - data = resp.json() - return data["m4b_url"] + resp.raise_for_status() + data = resp.json() + return data["m4b_url"] def fetch_download_manifest( self, @@ -169,13 +177,14 @@ class LibroFmClient: transport=transport, ) - resp = client.get("/api/v10/download-manifest", params={"isbn": isbn}) + with self._api_semaphore: + resp = client.get("/api/v10/download-manifest", params={"isbn": isbn}) - if resp.status_code == 404: - raise M4BUnavailableError(f"MP3 manifest not available for ISBN {isbn}") + if resp.status_code == 404: + raise M4BUnavailableError(f"MP3 manifest not available for ISBN {isbn}") - resp.raise_for_status() - return resp.json() + resp.raise_for_status() + return resp.json() def fetch_pdf_extra_url( self, @@ -208,8 +217,9 @@ class LibroFmClient: transport=transport, ) - resp = client.get(f"/api/v10/library/{isbn}/pdf_extra_url", params={"filename": filename}) + with self._api_semaphore: + resp = client.get(f"/api/v10/library/{isbn}/pdf_extra_url", params={"filename": filename}) - resp.raise_for_status() - data = resp.json() - return data["pdf_url"] + resp.raise_for_status() + data = resp.json() + return data["pdf_url"] diff --git a/tests/test_client.py b/tests/test_client.py index f096dc5..87d9868 100644 --- a/tests/test_client.py +++ b/tests/test_client.py @@ -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) \ No newline at end of file