fix(alerts): probe the static pool the way the download asks
The watcher fetched the YouTube watch page through each static IP with a
bare httpx client and no cookies. Anonymously, a datacenter IP making ~400
YouTube hits a day is rate-limited into "Sign in to confirm you're not a
bot", so playabilityStatus comes back LOGIN_REQUIRED and the watcher
declared the pool down. Those same IPs were serving every real download
fine, because a download carries YOUTUBE_COOKIES.
Measured in production on 8-sep-2026, all three statics, same minute:
anonymous (what the watcher did) -> LOGIN_REQUIRED
with the download's cookies -> OK
while proxy_usage showed 119 YouTube jobs routed to HD-static1 in the last
24 h with zero paid bytes. So the page that said "every download costs
money until the statics are back" fired while nothing was being spent, and
it re-nags every 2 h.
CLAUDE.md already recorded this shape for cloud/metering.probe_url_minutes
("The probe also carries YOUTUBE_COOKIES, like the download does"); the
watcher probe never got the same treatment. It does now, parsed once and
cached, and a blob that is not a Netscape cookie file is recognised before
the stdlib prints "http.cookiejar bug!" into the log every 30 minutes.
The paid probe stays anonymous on the cheap HTTP 204: it is billed per GB
and has no reason to carry a session.
The failure detail now names what YouTube actually said
(playabilityStatus: LOGIN_REQUIRED / UNPLAYABLE / ...) instead of blaming
the IP for every case. With cookies configured, LOGIN_REQUIRED means the
session expired and wants rotating, which is not the same problem as a
flagged address and should not read as one.
Claude-Session: https://claude.ai/code/session_01UZGqjYcZyfmKww1gcyKrp5
This commit is contained in:
parent
41aa9bc013
commit
5a6f428075
3 changed files with 194 additions and 4 deletions
|
|
@ -200,6 +200,62 @@ _PROXY_PROBE_URL = "http://www.google.com/generate_204"
|
|||
# through the statics are flat-rate, so the ~600 KB page is free.
|
||||
_STATIC_PROBE_URL = "https://www.youtube.com/watch?v=jNQXAC9IVRw"
|
||||
_STATIC_OK_MARKERS = ('"playabilityStatus"', '"status":"OK"')
|
||||
# The probe has to ask the way the DOWNLOAD asks, or it measures a question
|
||||
# nobody in production is asking. Anonymously, a datacenter IP making ~400
|
||||
# YouTube hits a day is rate-limited into "Sign in to confirm you're not a
|
||||
# bot" — playabilityStatus comes back LOGIN_REQUIRED — while the very same IP
|
||||
# serves every real download fine, because those carry these cookies.
|
||||
# Measured 8-sep-2026 on all three statics: anonymous LOGIN_REQUIRED, with
|
||||
# cookies OK, while proxy_usage showed 119 YouTube jobs on HD-static1 in 24 h
|
||||
# and zero paid bytes. Without this the watcher cries wolf every 2 h and the
|
||||
# alert tells you money is burning when none is.
|
||||
_static_cookie_jar = None
|
||||
_static_cookie_src = None
|
||||
|
||||
|
||||
def _probe_cookies():
|
||||
"""The download's YOUTUBE_COOKIES as a jar httpx can send, or None.
|
||||
|
||||
Parsed once and cached (the probe runs every 30 minutes). Never logged:
|
||||
the blob is a live YouTube session.
|
||||
"""
|
||||
global _static_cookie_jar, _static_cookie_src
|
||||
raw = os.environ.get("YOUTUBE_COOKIES", "")
|
||||
if not raw:
|
||||
return None
|
||||
if raw == _static_cookie_src:
|
||||
return _static_cookie_jar
|
||||
jar = None
|
||||
try:
|
||||
import tempfile
|
||||
from http.cookiejar import MozillaCookieJar
|
||||
# Pre-validate: handed a blob that is not a cookie file, the stdlib
|
||||
# prints "http.cookiejar bug!" with a traceback before raising. That
|
||||
# would land in the container log every 30 minutes, so recognise the
|
||||
# shape ourselves (a Netscape record is 7 tab-separated fields).
|
||||
if not any(len(ln.split("\t")) == 7
|
||||
for ln in raw.splitlines() if ln and not ln.startswith("#")):
|
||||
raise ValueError("not a Netscape cookie file")
|
||||
body = raw if raw.lstrip().startswith("# Netscape") else \
|
||||
"# Netscape HTTP Cookie File\n" + raw
|
||||
path = os.path.join(tempfile.mkdtemp(), "yt_cookies.txt")
|
||||
with open(path, "w") as fh:
|
||||
fh.write(body if body.endswith("\n") else body + "\n")
|
||||
jar = MozillaCookieJar(path)
|
||||
jar.load(ignore_discard=True, ignore_expires=True)
|
||||
except Exception as e:
|
||||
print(f"\u26a0\ufe0f Static probe could not read YOUTUBE_COOKIES ({type(e).__name__}); "
|
||||
f"probing anonymously, which YouTube bot-checks.")
|
||||
jar = None
|
||||
_static_cookie_src, _static_cookie_jar = raw, jar
|
||||
return jar
|
||||
|
||||
|
||||
def _playability(body):
|
||||
"""The playabilityStatus value in a watch page, for the alert detail."""
|
||||
import re as _re
|
||||
m = _re.search(r'"playabilityStatus":\{"status":"([A-Z_]+)"', body or "")
|
||||
return m.group(1) if m else "no player response"
|
||||
_PROXY_STRIKES = 2 # consecutive failed probes before alerting
|
||||
_watch_down = {} # target name -> down-since epoch
|
||||
_watch_nag = {} # target name -> last-nag epoch
|
||||
|
|
@ -234,7 +290,12 @@ async def _probe_one(proxy):
|
|||
is_paid = proxy == os.environ.get("PROXY_URL", "").strip()
|
||||
try:
|
||||
import httpx
|
||||
async with httpx.AsyncClient(proxy=proxy, timeout=20) as client:
|
||||
kwargs = {"proxy": proxy, "timeout": 20}
|
||||
if not is_paid:
|
||||
jar = _probe_cookies()
|
||||
if jar is not None:
|
||||
kwargs["cookies"] = jar
|
||||
async with httpx.AsyncClient(**kwargs) as client:
|
||||
resp = await client.get(_PROXY_PROBE_URL if is_paid else _STATIC_PROBE_URL,
|
||||
follow_redirects=not is_paid)
|
||||
if resp.status_code >= 400:
|
||||
|
|
@ -244,8 +305,11 @@ async def _probe_one(proxy):
|
|||
body = resp.text or ""
|
||||
if all(m in body for m in _STATIC_OK_MARKERS):
|
||||
return True, ""
|
||||
return False, ("YouTube answered but without a playable page "
|
||||
"(IP flagged: bot-check or 'unavailable')")
|
||||
# Name what YouTube actually said. "LOGIN_REQUIRED" with cookies
|
||||
# configured means the session expired (rotate them); the old wording
|
||||
# blamed the IP for every case and sent us hunting the wrong thing.
|
||||
return False, (f"YouTube answered but the video is not playable "
|
||||
f"(playabilityStatus: {_playability(body)})")
|
||||
except Exception as e:
|
||||
return False, f"{type(e).__name__}: {e}"
|
||||
|
||||
|
|
|
|||
|
|
@ -288,7 +288,17 @@ class TestStaticProbeAgainstYouTube:
|
|||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
alerts, _ = self._client(monkeypatch, body="<html>consent page</html>")
|
||||
ok, detail = asyncio.run(alerts._probe_one("http://static1"))
|
||||
assert not ok and "flagged" in detail
|
||||
assert not ok and "not playable" in detail
|
||||
|
||||
def test_the_detail_names_what_youtube_said(self, monkeypatch):
|
||||
""""IP flagged" blamed the IP for every miss. LOGIN_REQUIRED with
|
||||
cookies configured is an expired session, not a banned address."""
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
alerts, _ = self._client(
|
||||
monkeypatch,
|
||||
body='{"playabilityStatus":{"status":"LOGIN_REQUIRED","reason":"x"}}')
|
||||
ok, detail = asyncio.run(alerts._probe_one("http://static1"))
|
||||
assert not ok and "LOGIN_REQUIRED" in detail
|
||||
|
||||
def test_paid_probe_keeps_the_cheap_http_204(self, monkeypatch):
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
|
|
|
|||
116
tests/test_static_probe_cookies.py
Normal file
116
tests/test_static_probe_cookies.py
Normal file
|
|
@ -0,0 +1,116 @@
|
|||
"""The static-pool probe must ask the way the download asks.
|
||||
|
||||
The watcher fetched the YouTube watch page through each static IP with a bare
|
||||
httpx client: no cookies. Anonymously, a datacenter IP making ~400 YouTube hits
|
||||
a day is rate-limited into "Sign in to confirm you're not a bot", so
|
||||
playabilityStatus comes back LOGIN_REQUIRED and the watcher declared the pool
|
||||
down. The same IPs were serving every real download fine, because those carry
|
||||
YOUTUBE_COOKIES.
|
||||
|
||||
Measured in production on 8-sep-2026, all three statics, same request, same
|
||||
minute: anonymous LOGIN_REQUIRED, with the download's cookies OK — while
|
||||
proxy_usage showed 119 YouTube jobs routed to HD-static1 in 24 h and zero paid
|
||||
bytes. The alert said "every download costs money until the statics are back"
|
||||
and not one cent was being spent.
|
||||
|
||||
CLAUDE.md already recorded this for cloud/metering.probe_url_minutes ("The
|
||||
probe also carries YOUTUBE_COOKIES, like the download does"); the watcher probe
|
||||
never got the same treatment.
|
||||
"""
|
||||
import asyncio
|
||||
|
||||
import pytest
|
||||
|
||||
alerts = pytest.importorskip("cloud.alerts")
|
||||
|
||||
NETSCAPE = (
|
||||
"# Netscape HTTP Cookie File\n"
|
||||
".youtube.com\tTRUE\t/\tTRUE\t0\tSID\tsomevalue\n"
|
||||
".youtube.com\tTRUE\t/\tTRUE\t0\tHSID\tanother\n"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _clear_cache():
|
||||
alerts._static_cookie_src = None
|
||||
alerts._static_cookie_jar = None
|
||||
yield
|
||||
alerts._static_cookie_src = None
|
||||
alerts._static_cookie_jar = None
|
||||
|
||||
|
||||
def _spy(monkeypatch, body='{"playabilityStatus":{"status":"OK"}}'):
|
||||
seen = {}
|
||||
|
||||
class _Resp:
|
||||
status_code = 200
|
||||
text = body
|
||||
|
||||
class _Client:
|
||||
def __init__(self, **kw):
|
||||
seen["cookies"] = kw.get("cookies")
|
||||
seen["proxy"] = kw.get("proxy")
|
||||
|
||||
async def __aenter__(self):
|
||||
return self
|
||||
|
||||
async def __aexit__(self, *a):
|
||||
return False
|
||||
|
||||
async def get(self, url, **kw):
|
||||
seen["url"] = url
|
||||
return _Resp()
|
||||
|
||||
import httpx
|
||||
monkeypatch.setattr(httpx, "AsyncClient", _Client)
|
||||
return seen
|
||||
|
||||
|
||||
class TestTheProbeCarriesTheDownloadsCookies:
|
||||
def test_the_static_probe_sends_them(self, monkeypatch):
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
monkeypatch.setenv("YOUTUBE_COOKIES", NETSCAPE)
|
||||
seen = _spy(monkeypatch)
|
||||
ok, _ = asyncio.run(alerts._probe_one("http://static1"))
|
||||
assert ok
|
||||
assert seen["cookies"] is not None, "static probe went out anonymously"
|
||||
assert len(seen["cookies"]) == 2
|
||||
|
||||
def test_a_headerless_blob_is_still_accepted(self, monkeypatch):
|
||||
"""The env var is pasted by hand; the Netscape header is often missing."""
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
monkeypatch.setenv("YOUTUBE_COOKIES",
|
||||
".youtube.com\tTRUE\t/\tTRUE\t0\tSID\tsomevalue\n")
|
||||
seen = _spy(monkeypatch)
|
||||
asyncio.run(alerts._probe_one("http://static1"))
|
||||
assert seen["cookies"] is not None and len(seen["cookies"]) == 1
|
||||
|
||||
def test_no_cookies_configured_still_probes(self, monkeypatch):
|
||||
"""Self-host has no cookies: probe anonymously rather than crash."""
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
monkeypatch.delenv("YOUTUBE_COOKIES", raising=False)
|
||||
seen = _spy(monkeypatch)
|
||||
ok, _ = asyncio.run(alerts._probe_one("http://static1"))
|
||||
assert ok and seen["cookies"] is None
|
||||
|
||||
def test_an_unparseable_blob_does_not_break_the_watcher(self, monkeypatch):
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
monkeypatch.setenv("YOUTUBE_COOKIES", "not a cookie file at all")
|
||||
seen = _spy(monkeypatch)
|
||||
ok, _ = asyncio.run(alerts._probe_one("http://static1"))
|
||||
assert ok and seen["cookies"] is None
|
||||
|
||||
def test_the_paid_probe_stays_anonymous_and_cheap(self, monkeypatch):
|
||||
"""DataImpulse is billed per GB: keep the 204, and send it no session."""
|
||||
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||
monkeypatch.setenv("YOUTUBE_COOKIES", NETSCAPE)
|
||||
seen = _spy(monkeypatch, body="")
|
||||
ok, _ = asyncio.run(alerts._probe_one("http://paid"))
|
||||
assert ok
|
||||
assert seen["cookies"] is None
|
||||
assert seen["url"].startswith("http://www.google.com")
|
||||
|
||||
def test_the_jar_is_parsed_once(self, monkeypatch):
|
||||
monkeypatch.setenv("YOUTUBE_COOKIES", NETSCAPE)
|
||||
first = alerts._probe_cookies()
|
||||
assert alerts._probe_cookies() is first
|
||||
Loading…
Reference in a new issue