Harden YouTube sync: retries + pooled client, uploads-playlist fallback, JSON 404 for /api/*
Findings from a full audit of the live instance, each with tests:
1. Transient TLS failures to Google ("[SSL: UNEXPECTED_EOF_WHILE_READING]")
were silently dropping 2-4% of channels from every videos sync and once
failed a whole scheduled subscriptions sync. youtube_client now retries
transport errors and 5xx (3 attempts, 0.5s/2s backoff; 4xx never), and
sync_videos runs under youtube_session() so the ~240 calls of a run share
one pooled client instead of a fresh TLS handshake each. Verified live:
one EOF during the next sync was retried and the run lost no channels.
2. channels.list omits some channels entirely (three region-restricted TV
channels here), so they never got an uploads_playlist_id and never had a
videos sync. The id is derivable ("UC..." -> "UU..."); sync_subscriptions
falls back to it, also when channels.list fails. Verified live: all three
now have 200 videos each.
3. SPAStaticFiles served index.html with HTTP 200 for any unknown /api/*
path (a mistyped endpoint "succeeded" with HTML). /api/* now stays a JSON
404; client-side routes still fall back to the SPA.
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
This commit is contained in:
parent
906a142796
commit
f97ef0d54d
6 changed files with 370 additions and 36 deletions
40
tests/test_spa_fallback.py
Normal file
40
tests/test_spa_fallback.py
Normal file
|
|
@ -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("<html>spa</html>")
|
||||
(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
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -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
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue