diff --git a/backend/app/main.py b/backend/app/main.py index 6105630..ede8998 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -12,13 +12,17 @@ from starlette.types import Scope class SPAStaticFiles(StaticFiles): """Falls back to index.html for unknown paths so client-side routes - (e.g. /categories) work on direct navigation/refresh, not just /.""" + (e.g. /categories) work on direct navigation/refresh, not just /. + + Never for /api/*: an unknown API path must stay a JSON 404 (it used to + come back as index.html with HTTP 200, which silently "succeeds" for any + mistyped endpoint, e.g. from a future mobile client).""" async def get_response(self, path: str, scope: Scope): try: return await super().get_response(path, scope) except StarletteHTTPException as exc: - if exc.status_code == 404: + if exc.status_code == 404 and not (path == "api" or path.startswith("api/")): return await super().get_response("index.html", scope) raise diff --git a/backend/app/services/sync.py b/backend/app/services/sync.py index 95ec767..1cbd826 100644 --- a/backend/app/services/sync.py +++ b/backend/app/services/sync.py @@ -123,6 +123,21 @@ def sync_subscriptions(db: Session) -> dict: except Exception: logger.exception("Failed to fetch uploads playlists during subscriptions sync") + # channels.list silently omits some channels (seen in production for + # three region-restricted TV channels) and then those never get a + # videos sync at all, even though their uploads playlist is reachable. + # The uploads id is derivable from the channel id, so fall back to it. + derived = 0 + for channel in existing.values(): + if channel.subscribed and not channel.uploads_playlist_id: + fallback = youtube_client.derive_uploads_playlist_id(channel.youtube_channel_id) + if fallback: + channel.uploads_playlist_id = fallback + derived += 1 + if derived: + db.commit() + logger.info("Derived uploads playlist id for %d channel(s) missing from channels.list", derived) + result = { "status": "completed", "started_at": started_at, @@ -180,29 +195,32 @@ def sync_videos(db: Session) -> dict: known_ids_by_channel.setdefault(channel_id, set()).add(youtube_video_id) candidate_video_ids: set[str] = set() - for channel in channels: - try: - # videos_backfill_cap is a hard history-depth limit per - # channel: only the newest N playlist items are ever - # considered; anything older is not backfilled by design. - # The early stop on consecutive known ids saves playlistItems - # pages on repeated syncs inside that window. - new_ids = youtube_client.fetch_playlist_video_ids_incremental( - credentials, - channel.uploads_playlist_id, - known_ids_by_channel.get(channel.id, set()), - settings.videos_backfill_cap, - settings.videos_known_stop_threshold, - ) - candidate_video_ids.update(new_ids) - except Exception: - logger.exception("Failed to fetch playlist items for channel %s", channel.youtube_channel_id) + # One pooled HTTP client for the whole run instead of a fresh TLS + # handshake per channel (see youtube_client.youtube_session). + with youtube_client.youtube_session(): + for channel in channels: + try: + # videos_backfill_cap is a hard history-depth limit per + # channel: only the newest N playlist items are ever + # considered; anything older is not backfilled by design. + # The early stop on consecutive known ids saves playlistItems + # pages on repeated syncs inside that window. + new_ids = youtube_client.fetch_playlist_video_ids_incremental( + credentials, + channel.uploads_playlist_id, + known_ids_by_channel.get(channel.id, set()), + settings.videos_backfill_cap, + settings.videos_known_stop_threshold, + ) + candidate_video_ids.update(new_ids) + except Exception: + logger.exception("Failed to fetch playlist items for channel %s", channel.youtube_channel_id) - # Details are fetched only for ids that are not in the DB yet (the - # incremental fetch above already filters out known ids), so every - # returned item is a new video to insert. Existing videos' metadata is - # deliberately not refreshed by the videos sync. - details = youtube_client.fetch_videos_details(credentials, list(candidate_video_ids)) + # Details are fetched only for ids that are not in the DB yet (the + # incremental fetch above already filters out known ids), so every + # returned item is a new video to insert. Existing videos' metadata is + # deliberately not refreshed by the videos sync. + details = youtube_client.fetch_videos_details(credentials, list(candidate_video_ids)) added = 0 skipped = 0 diff --git a/backend/app/services/youtube_client.py b/backend/app/services/youtube_client.py index 0a64f07..58885bc 100644 --- a/backend/app/services/youtube_client.py +++ b/backend/app/services/youtube_client.py @@ -1,4 +1,8 @@ import logging +import threading +import time +from contextlib import contextmanager +from typing import Iterator import httpx from google.oauth2.credentials import Credentials @@ -15,6 +19,21 @@ BATCH_SIZE = 50 # together if more is ever needed. MAX_PLAYLIST_PAGES = 10 +# Transient-failure policy for every YouTube Data API call. Production logs +# showed ~2-4% of per-channel requests in a videos sync dying with +# "[SSL: UNEXPECTED_EOF_WHILE_READING]" at TLS setup, and one scheduled +# subscriptions sync failing outright on the same error; a short retry with +# backoff absorbs that. 4xx (quota, auth, not found) is never retried. +MAX_ATTEMPTS = 3 +RETRY_BACKOFF_SECONDS = (0.5, 2.0) +RETRYABLE_STATUS_CODES = frozenset({500, 502, 503, 504}) + +# A sync makes hundreds of calls (one playlistItems request per channel); +# opening a fresh httpx.Client -- and a fresh TLS handshake -- for each one +# is both slow and where those EOF failures came from. youtube_session() +# lets a caller share one pooled client across all calls on this thread. +_thread_state = threading.local() + class YouTubeQuotaExceeded(Exception): pass @@ -32,6 +51,63 @@ class YouTubeInsufficientScope(Exception): pass +@contextmanager +def youtube_session() -> Iterator[None]: + """Share one pooled httpx.Client across every youtube_client call made on + this thread inside the block (nested blocks reuse the outermost client).""" + if getattr(_thread_state, "client", None) is not None: + yield + return + with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + _thread_state.client = client + try: + yield + finally: + _thread_state.client = None + + +@contextmanager +def _client() -> Iterator[httpx.Client]: + shared = getattr(_thread_state, "client", None) + if shared is not None: + yield shared + return + with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + yield client + + +def _request(client: httpx.Client, method: str, url: str, **kwargs) -> httpx.Response: + """client.(url, **kwargs) with retries on transport errors and + 5xx responses. Returns the final response; non-retryable statuses are + returned as-is for the caller's _raise_for_status.""" + send = getattr(client, method) + for attempt in range(1, MAX_ATTEMPTS + 1): + try: + response = send(url, **kwargs) + except httpx.TransportError as exc: + if attempt >= MAX_ATTEMPTS: + raise + delay = RETRY_BACKOFF_SECONDS[attempt - 1] + logger.warning( + "YouTube API transport error on %s (attempt %d/%d, retrying in %.1fs): %s", + url, attempt, MAX_ATTEMPTS, delay, exc, + ) + time.sleep(delay) + continue + + if response.status_code in RETRYABLE_STATUS_CODES and attempt < MAX_ATTEMPTS: + delay = RETRY_BACKOFF_SECONDS[attempt - 1] + logger.warning( + "YouTube API returned %s on %s (attempt %d/%d, retrying in %.1fs)", + response.status_code, url, attempt, MAX_ATTEMPTS, delay, + ) + time.sleep(delay) + continue + return response + + raise AssertionError("unreachable") # pragma: no cover + + def _headers(credentials: Credentials) -> dict: return {"Authorization": f"Bearer {credentials.token}"} @@ -59,11 +135,21 @@ def _raise_for_status(response: httpx.Response) -> None: raise YouTubeAPIError(f"{response.status_code}: {message}") +def derive_uploads_playlist_id(youtube_channel_id: str) -> str | None: + """YouTube's uploads playlist id is the channel id with the "UC" prefix + swapped for "UU". channels.list omits some channels entirely (e.g. ones + YouTube restricts regionally) yet their uploads playlist still serves via + playlistItems -- this derived id is the fallback for those.""" + if youtube_channel_id and youtube_channel_id.startswith("UC") and len(youtube_channel_id) > 2: + return "UU" + youtube_channel_id[2:] + return None + + def fetch_subscriptions(credentials: Credentials) -> list[dict]: subscriptions: list[dict] = [] page_token: str | None = None - with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + with _client() as client: while True: params = { "part": "snippet,contentDetails", @@ -73,7 +159,7 @@ def fetch_subscriptions(credentials: Credentials) -> list[dict]: if page_token: params["pageToken"] = page_token - response = client.get(f"{settings.youtube_api_base_url}/subscriptions", params=params, headers=_headers(credentials)) + response = _request(client, "get", f"{settings.youtube_api_base_url}/subscriptions", params=params, headers=_headers(credentials)) _raise_for_status(response) data = response.json() @@ -116,7 +202,7 @@ def fetch_playlist_video_ids(credentials: Credentials, playlist_id: str, max_res page_token: str | None = None pages_fetched = 0 - with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + with _client() as client: while pages_fetched < MAX_PLAYLIST_PAGES and len(video_ids) < max_results: params = { "part": "contentDetails", @@ -126,7 +212,7 @@ def fetch_playlist_video_ids(credentials: Credentials, playlist_id: str, max_res if page_token: params["pageToken"] = page_token - response = client.get(f"{settings.youtube_api_base_url}/playlistItems", params=params, headers=_headers(credentials)) + response = _request(client, "get", f"{settings.youtube_api_base_url}/playlistItems", params=params, headers=_headers(credentials)) if response.status_code == 404: return [] _raise_for_status(response) @@ -171,7 +257,7 @@ def fetch_playlist_video_ids_incremental( page_token: str | None = None pages_fetched = 0 - with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + with _client() as client: while pages_fetched < MAX_PLAYLIST_PAGES and len(new_ids) < max_results: params = { "part": "contentDetails", @@ -181,7 +267,7 @@ def fetch_playlist_video_ids_incremental( if page_token: params["pageToken"] = page_token - response = client.get(f"{settings.youtube_api_base_url}/playlistItems", params=params, headers=_headers(credentials)) + response = _request(client, "get", f"{settings.youtube_api_base_url}/playlistItems", params=params, headers=_headers(credentials)) if response.status_code == 404: return new_ids _raise_for_status(response) @@ -213,7 +299,7 @@ def fetch_playlist_video_ids_incremental( def fetch_videos_details(credentials: Credentials, video_ids: list[str]) -> list[dict]: results: list[dict] = [] - with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + with _client() as client: for i in range(0, len(video_ids), BATCH_SIZE): batch = video_ids[i : i + BATCH_SIZE] params = { @@ -221,7 +307,7 @@ def fetch_videos_details(credentials: Credentials, video_ids: list[str]) -> list "id": ",".join(batch), "maxResults": BATCH_SIZE, } - response = client.get(f"{settings.youtube_api_base_url}/videos", params=params, headers=_headers(credentials)) + response = _request(client, "get", f"{settings.youtube_api_base_url}/videos", params=params, headers=_headers(credentials)) _raise_for_status(response) data = response.json() @@ -247,8 +333,10 @@ def fetch_videos_details(credentials: Credentials, video_ids: list[str]) -> list def unsubscribe(credentials: Credentials, youtube_subscription_id: str) -> None: - with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: - response = client.delete( + with _client() as client: + response = _request( + client, + "delete", f"{settings.youtube_api_base_url}/subscriptions", params={"id": youtube_subscription_id}, headers=_headers(credentials), @@ -272,7 +360,7 @@ def _parse_subscriber_count(statistics: dict) -> int | None: def fetch_uploads_playlists(credentials: Credentials, channel_ids: list[str]) -> dict[str, dict]: result: dict[str, dict] = {} - with httpx.Client(timeout=settings.metube_request_timeout_seconds) as client: + with _client() as client: for i in range(0, len(channel_ids), BATCH_SIZE): batch = channel_ids[i : i + BATCH_SIZE] params = { @@ -280,7 +368,7 @@ def fetch_uploads_playlists(credentials: Credentials, channel_ids: list[str]) -> "id": ",".join(batch), "maxResults": BATCH_SIZE, } - response = client.get(f"{settings.youtube_api_base_url}/channels", params=params, headers=_headers(credentials)) + response = _request(client, "get", f"{settings.youtube_api_base_url}/channels", params=params, headers=_headers(credentials)) _raise_for_status(response) data = response.json() diff --git a/tests/test_spa_fallback.py b/tests/test_spa_fallback.py new file mode 100644 index 0000000..949af97 --- /dev/null +++ b/tests/test_spa_fallback.py @@ -0,0 +1,40 @@ +from fastapi import FastAPI +from fastapi.testclient import TestClient + +from app.main import SPAStaticFiles + + +def _app(tmp_path): + (tmp_path / "index.html").write_text("spa") + (tmp_path / "asset.js").write_text("console.log(1)") + app = FastAPI() + + @app.get("/api/known") + def known(): + return {"ok": True} + + app.mount("/", SPAStaticFiles(directory=tmp_path, html=True), name="static") + return TestClient(app) + + +def test_client_side_routes_fall_back_to_index(tmp_path): + client = _app(tmp_path) + for path in ("/", "/categories", "/video/abc", "/deep/nested/route"): + response = client.get(path) + assert response.status_code == 200, path + assert "spa" in response.text + + +def test_real_assets_are_served_as_is(tmp_path): + response = _app(tmp_path).get("/asset.js") + assert response.status_code == 200 + assert "console.log" in response.text + + +def test_unknown_api_paths_are_json_404_not_index(tmp_path): + client = _app(tmp_path) + assert client.get("/api/known").json() == {"ok": True} + for path in ("/api", "/api/nonexistent", "/api/categories/999999", "/api/feed/typo"): + response = client.get(path) + assert response.status_code == 404, path + assert response.json() == {"detail": "Not Found"}, path diff --git a/tests/test_sync.py b/tests/test_sync.py index 2294bb7..a0d31e5 100644 --- a/tests/test_sync.py +++ b/tests/test_sync.py @@ -567,3 +567,77 @@ def test_is_videos_sync_running_reflects_lock(): finally: sync._videos_lock.release() assert sync.is_videos_sync_running() is False + + +def test_sync_subscriptions_derives_uploads_playlist_when_channels_list_omits_channel(monkeypatch, db_session): + """channels.list omits some channels entirely (seen in production for + region-restricted TV channels) -- without a fallback they never get a + videos sync. The uploads playlist id is derivable from the channel id.""" + monkeypatch.setattr(sync.google_oauth, "get_credentials", lambda db: object()) + monkeypatch.setattr( + sync.youtube_client, + "fetch_subscriptions", + lambda creds: [ + {"youtube_channel_id": "UCknown00000000000000000", "youtube_subscription_id": "s1", "title": "Known", "description": "", "thumbnail_url": None}, + {"youtube_channel_id": "UComitted0000000000000000", "youtube_subscription_id": "s2", "title": "Omitted", "description": "", "thumbnail_url": None}, + {"youtube_channel_id": "UCnouploads00000000000000", "youtube_subscription_id": "s3", "title": "NoUploads", "description": "", "thumbnail_url": None}, + ], + ) + # Only the first channel comes back from channels.list; the third comes + # back without an uploads playlist at all. + monkeypatch.setattr( + sync.youtube_client, + "fetch_uploads_playlists", + lambda creds, ids: { + "UCknown00000000000000000": {"uploads_playlist_id": "UUfromapi", "subscriber_count": 5}, + "UCnouploads00000000000000": {"uploads_playlist_id": None, "subscriber_count": None}, + }, + ) + + sync.sync_subscriptions(db_session) + + by_id = {c.youtube_channel_id: c for c in db_session.query(Channel).all()} + assert by_id["UCknown00000000000000000"].uploads_playlist_id == "UUfromapi" # API value wins + assert by_id["UComitted0000000000000000"].uploads_playlist_id == "UUomitted0000000000000000" + assert by_id["UCnouploads00000000000000"].uploads_playlist_id == "UUnouploads00000000000000" + + +def test_sync_subscriptions_derives_uploads_playlist_even_if_channels_list_fails(monkeypatch, db_session): + monkeypatch.setattr(sync.google_oauth, "get_credentials", lambda db: object()) + monkeypatch.setattr( + sync.youtube_client, + "fetch_subscriptions", + lambda creds: [ + {"youtube_channel_id": "UCabc", "youtube_subscription_id": "s1", "title": "A", "description": "", "thumbnail_url": None}, + ], + ) + + def boom(creds, ids): + raise RuntimeError("channels.list down") + + monkeypatch.setattr(sync.youtube_client, "fetch_uploads_playlists", boom) + + result = sync.sync_subscriptions(db_session) + + assert result["status"] == "completed" + assert db_session.query(Channel).one().uploads_playlist_id == "UUabc" + + +def test_sync_videos_uses_one_http_client_for_the_whole_run(monkeypatch, db_session): + for i in range(3): + _seed_channel(db_session, youtube_channel_id=f"chan{i}", uploads_playlist_id=f"UUchan{i}") + constructed = [] + + def make_client(timeout): + client = _FakeClient([_page(["v"]), _page(["v"]), _page(["v"]), _FakeResponse({"items": []})]) + constructed.append(client) + return client + + monkeypatch.setattr(sync.google_oauth, "get_credentials", lambda db: _FakeCredentials()) + monkeypatch.setattr(sync.youtube_client.httpx, "Client", make_client) + + sync.sync_videos(db_session) + + # 3 playlistItems calls + 1 videos.list call, all through a single client. + assert len(constructed) == 1 + assert len(constructed[0].requests) == 4 diff --git a/tests/test_youtube_client.py b/tests/test_youtube_client.py index ac14db9..d342de4 100644 --- a/tests/test_youtube_client.py +++ b/tests/test_youtube_client.py @@ -393,3 +393,113 @@ def test_fetch_uploads_playlists_subscriber_count_not_an_int_is_none(monkeypatch result = youtube_client.fetch_uploads_playlists(_credentials(), ["chanA"]) assert result == {"chanA": {"uploads_playlist_id": "UUchanA", "subscriber_count": None}} + + +# --- retry / shared-client behaviour ----------------------------------------- + + +class FlakyClient(FakeClient): + """Raises the given transport errors first, then serves canned responses.""" + + def __init__(self, failures, responses): + super().__init__(responses) + self._failures = list(failures) + self.calls = 0 + + def get(self, url, params=None, headers=None): + self.calls += 1 + if self._failures: + raise self._failures.pop(0) + return self._responses.pop(0) + + +@pytest.fixture +def no_sleep(monkeypatch): + slept = [] + monkeypatch.setattr(youtube_client.time, "sleep", lambda s: slept.append(s)) + return slept + + +def test_retries_transport_error_then_succeeds(monkeypatch, no_sleep): + ok = FakeResponse(200, {"items": [{"contentDetails": {"videoId": "vid1"}}]}) + client = FlakyClient([youtube_client.httpx.ConnectError("[SSL: UNEXPECTED_EOF_WHILE_READING]")], [ok]) + monkeypatch.setattr(youtube_client.httpx, "Client", lambda timeout: client) + + result = youtube_client.fetch_playlist_video_ids(_credentials(), "UUplaylist", 10) + + assert result == ["vid1"] + assert client.calls == 2 + assert no_sleep == [youtube_client.RETRY_BACKOFF_SECONDS[0]] + + +def test_retries_5xx_then_succeeds(monkeypatch, no_sleep): + client = FakeClient([FakeResponse(503, {"error": {"message": "backend"}}), FakeResponse(200, {"items": []})]) + monkeypatch.setattr(youtube_client.httpx, "Client", lambda timeout: client) + + assert youtube_client.fetch_videos_details(_credentials(), ["vid1"]) == [] + assert len(no_sleep) == 1 + + +def test_gives_up_after_max_attempts(monkeypatch, no_sleep): + errors = [youtube_client.httpx.ConnectError("eof")] * youtube_client.MAX_ATTEMPTS + client = FlakyClient(errors, []) + monkeypatch.setattr(youtube_client.httpx, "Client", lambda timeout: client) + + with pytest.raises(youtube_client.httpx.ConnectError): + youtube_client.fetch_playlist_video_ids(_credentials(), "UUplaylist", 10) + + assert client.calls == youtube_client.MAX_ATTEMPTS + assert len(no_sleep) == youtube_client.MAX_ATTEMPTS - 1 + + +def test_4xx_is_not_retried(monkeypatch, no_sleep): + quota = FakeResponse(403, {"error": {"message": "Quota exceeded", "errors": [{"reason": "quotaExceeded"}]}}) + client = FlakyClient([], [quota]) + monkeypatch.setattr(youtube_client.httpx, "Client", lambda timeout: client) + + with pytest.raises(youtube_client.YouTubeQuotaExceeded): + youtube_client.fetch_subscriptions(_credentials()) + + assert client.calls == 1 + assert no_sleep == [] + + +def test_youtube_session_shares_one_client_across_calls(monkeypatch): + constructed = [] + + def make_client(timeout): + client = FakeClient([FakeResponse(200, {"items": []})] * 10) + constructed.append(client) + return client + + monkeypatch.setattr(youtube_client.httpx, "Client", make_client) + + with youtube_client.youtube_session(): + for _ in range(3): + youtube_client.fetch_playlist_video_ids(_credentials(), "UUplaylist", 10) + youtube_client.fetch_videos_details(_credentials(), ["vid1"]) + assert len(constructed) == 1 + + # Outside a session every call still gets its own client, as before. + youtube_client.fetch_videos_details(_credentials(), ["vid1"]) + assert len(constructed) == 2 + + +def test_youtube_session_is_cleared_after_block(monkeypatch): + monkeypatch.setattr(youtube_client.httpx, "Client", lambda timeout: FakeClient([])) + with youtube_client.youtube_session(): + assert youtube_client._thread_state.client is not None + assert youtube_client._thread_state.client is None + + +@pytest.mark.parametrize( + "channel_id,expected", + [ + ("UCRds47MZ1Ng7KCLseg2TkWA", "UURds47MZ1Ng7KCLseg2TkWA"), + ("UC", None), + ("HC123", None), + ("", None), + ], +) +def test_derive_uploads_playlist_id(channel_id, expected): + assert youtube_client.derive_uploads_playlist_id(channel_id) == expected