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:
vrubelroman 2026-10-20 20:20:27 +00:00
parent 906a142796
commit f97ef0d54d
6 changed files with 370 additions and 36 deletions

View file

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

View file

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

View file

@ -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.<method>(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()