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
|
|
@ -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