feat(download): flat-rate static ISP proxies before the per-GB proxy
New STATIC_PROXY_URLS env (comma-separated): dedicated ISP IPs with unlimited traffic, tried after the direct attempt and before the per-GB paid proxy. With it unset the chain is byte-identical to before. - plan_download_attempts: pure, unit-tested attempt ordering. Cheapest bandwidth first: direct -> statics (rotated per job, uncapped 1080p, free bytes) -> paid HD (720p cost cap) -> fallback via paid. - The 720p cap and the PROXY_BYTES monthly counter now apply ONLY to attempts that actually bill per GB — static downloads come in at 1080p and don't count toward the cost alert. - alerts.py watcher generalized to multiple targets: the static pool (down = ingest silently moves to per-GB billing, nag with a cost hint) and the paid proxy (down = ingest at risk), each with its own down/nag/recovered incident state. Context: the server's IPv4 is hard-banned by YouTube (19-aug-2026), so DIRECT_FIRST serves nothing and every download was going through DataImpulse at $1/GB capped to 720p. Verified from prod: all 3 Decodo dedicated IPs pass the bot-check with cookies+bgutil at 1080p.
This commit is contained in:
parent
72288bba82
commit
dfa31241ca
4 changed files with 246 additions and 101 deletions
117
cloud/alerts.py
117
cloud/alerts.py
|
|
@ -119,7 +119,6 @@ async def send_admin_alert(subject: str, body: str):
|
||||||
|
|
||||||
async def record_job_outcome(ok: bool, error_text: str = ""):
|
async def record_job_outcome(ok: bool, error_text: str = ""):
|
||||||
"""Record a managed job's result and fire an alert if the picture looks bad."""
|
"""Record a managed job's result and fire an alert if the picture looks bad."""
|
||||||
global _proxy_down_since, _proxy_last_nag
|
|
||||||
_recent.append(bool(ok))
|
_recent.append(bool(ok))
|
||||||
if ok:
|
if ok:
|
||||||
return
|
return
|
||||||
|
|
@ -129,9 +128,9 @@ async def record_job_outcome(ok: bool, error_text: str = ""):
|
||||||
# (one alert at 3am is easy to miss; an exhausted proxy takes all
|
# (one alert at 3am is easy to miss; an exhausted proxy takes all
|
||||||
# YouTube-URL ingest down until someone tops it up).
|
# YouTube-URL ingest down until someone tops it up).
|
||||||
if _looks_like_proxy_error(error_text):
|
if _looks_like_proxy_error(error_text):
|
||||||
if not _proxy_down_since:
|
if not _watch_down.get(_PAID_TARGET):
|
||||||
_proxy_down_since = time.time()
|
_watch_down[_PAID_TARGET] = time.time()
|
||||||
_proxy_last_nag = time.time()
|
_watch_nag[_PAID_TARGET] = time.time()
|
||||||
if _cooldown_ok("proxy"):
|
if _cooldown_ok("proxy"):
|
||||||
await send_admin_alert(
|
await send_admin_alert(
|
||||||
"🔴 Proxy error — may be out of credits",
|
"🔴 Proxy error — may be out of credits",
|
||||||
|
|
@ -155,13 +154,18 @@ async def record_job_outcome(ok: bool, error_text: str = ""):
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
# --- Proxy balance watcher ----------------------------------------------------
|
# --- Proxy watcher --------------------------------------------------------------
|
||||||
# An exhausted residential proxy takes ALL YouTube-URL ingest down (when the
|
# A dead download route takes YouTube-URL ingest down (or silently moves it to
|
||||||
# datacenter IP is blocked, the proxy is the only working route), and a single
|
# per-GB billing), and a single alert at the moment it dies is easy to miss.
|
||||||
# alert at the moment it dies is easy to miss. This watcher probes the proxy on
|
# The watcher probes every configured route on a schedule, keeps nagging on
|
||||||
# a schedule, keeps nagging on Telegram until the balance is topped up, and
|
# Telegram until it's fixed, and confirms recovery (incident of 19-aug-2026:
|
||||||
# confirms recovery — so exhaustion is caught even before the next user job
|
# DataImpulse 407 TRAFFIC_EXHAUSTED, found by accident hours later).
|
||||||
# fails (incident of 19-aug-2026: 407 TRAFFIC_EXHAUSTED, found by accident).
|
#
|
||||||
|
# Watched targets:
|
||||||
|
# - "static proxy pool" (STATIC_PROXY_URLS): flat-rate ISP IPs, the primary
|
||||||
|
# route. Ingest still works when they die (paid fallback) but every GB
|
||||||
|
# starts costing money — that's worth a nag of its own.
|
||||||
|
# - "paid proxy" (PROXY_URL): the per-GB last resort; dead = ingest at risk.
|
||||||
_PROXY_PROBE_INTERVAL = 1800 # seconds between probes (30 min)
|
_PROXY_PROBE_INTERVAL = 1800 # seconds between probes (30 min)
|
||||||
_PROXY_RENOTIFY = 7200 # keep nagging every 2 h while it stays down
|
_PROXY_RENOTIFY = 7200 # keep nagging every 2 h while it stays down
|
||||||
# 204-No-Content endpoint: the probe costs a handful of bytes of paid traffic.
|
# 204-No-Content endpoint: the probe costs a handful of bytes of paid traffic.
|
||||||
|
|
@ -170,16 +174,28 @@ _PROXY_RENOTIFY = 7200 # keep nagging every 2 h while it stays down
|
||||||
# with it), which would make an HTTPS probe cry wolf. An exhausted balance
|
# with it), which would make an HTTPS probe cry wolf. An exhausted balance
|
||||||
# rejects the request before forwarding, so HTTP still detects the 407.
|
# rejects the request before forwarding, so HTTP still detects the 407.
|
||||||
_PROXY_PROBE_URL = "http://www.google.com/generate_204"
|
_PROXY_PROBE_URL = "http://www.google.com/generate_204"
|
||||||
_proxy_down_since = None
|
_watch_down = {} # target name -> down-since epoch
|
||||||
_proxy_last_nag = 0.0
|
_watch_nag = {} # target name -> last-nag epoch
|
||||||
|
|
||||||
|
_PAID_TARGET = "paid proxy"
|
||||||
|
_STATIC_TARGET = "static proxy pool"
|
||||||
|
|
||||||
|
|
||||||
async def _probe_proxy():
|
def _watch_targets():
|
||||||
"""(ok, detail) for one cheap request through the residential proxy, or
|
"""[(name, [proxy urls])] — a target is up if ANY of its urls answers."""
|
||||||
None when no proxy is configured (nothing to watch)."""
|
targets = []
|
||||||
proxy = os.environ.get("PROXY_URL", "").strip()
|
statics = [p.strip() for p in
|
||||||
if not proxy:
|
os.environ.get("STATIC_PROXY_URLS", "").split(",") if p.strip()]
|
||||||
return None
|
if statics:
|
||||||
|
targets.append((_STATIC_TARGET, statics))
|
||||||
|
paid = os.environ.get("PROXY_URL", "").strip()
|
||||||
|
if paid:
|
||||||
|
targets.append((_PAID_TARGET, [paid]))
|
||||||
|
return targets
|
||||||
|
|
||||||
|
|
||||||
|
async def _probe_one(proxy):
|
||||||
|
"""(ok, detail) for one cheap request through one proxy."""
|
||||||
try:
|
try:
|
||||||
import httpx
|
import httpx
|
||||||
async with httpx.AsyncClient(proxy=proxy, timeout=20) as client:
|
async with httpx.AsyncClient(proxy=proxy, timeout=20) as client:
|
||||||
|
|
@ -191,46 +207,53 @@ async def _probe_proxy():
|
||||||
return False, f"{type(e).__name__}: {e}"
|
return False, f"{type(e).__name__}: {e}"
|
||||||
|
|
||||||
|
|
||||||
async def proxy_watch_tick():
|
async def _watch_update(name, ok, detail):
|
||||||
"""One probe cycle: open the incident, nag while down, confirm recovery."""
|
"""Shared incident state machine: alert on down, nag, confirm recovery."""
|
||||||
global _proxy_down_since, _proxy_last_nag
|
|
||||||
result = await _probe_proxy()
|
|
||||||
if result is None:
|
|
||||||
return
|
|
||||||
ok, detail = result
|
|
||||||
now = time.time()
|
now = time.time()
|
||||||
if ok:
|
if ok:
|
||||||
if _proxy_down_since:
|
if _watch_down.get(name):
|
||||||
mins = int((now - _proxy_down_since) / 60)
|
mins = int((now - _watch_down[name]) / 60)
|
||||||
await send_admin_alert(
|
await send_admin_alert(
|
||||||
"✅ Proxy recovered",
|
f"✅ {name} recovered",
|
||||||
f"The residential proxy answers again after ~{mins} min down. "
|
f"The {name} answers again after ~{mins} min down.",
|
||||||
"YouTube-URL ingest should be back.",
|
|
||||||
)
|
)
|
||||||
_proxy_down_since = None
|
_watch_down[name] = None
|
||||||
_proxy_last_nag = 0.0
|
_watch_nag[name] = 0.0
|
||||||
return
|
return
|
||||||
if not _proxy_down_since:
|
hint = ("YouTube-URL jobs are falling back to the PER-GB paid proxy — "
|
||||||
_proxy_down_since = now
|
"ingest still works but every download now costs money."
|
||||||
_proxy_last_nag = now
|
if name == _STATIC_TARGET else
|
||||||
|
"YouTube-URL jobs will keep failing on this route until it's "
|
||||||
|
"topped up / fixed.")
|
||||||
|
if not _watch_down.get(name):
|
||||||
|
_watch_down[name] = now
|
||||||
|
_watch_nag[name] = now
|
||||||
await send_admin_alert(
|
await send_admin_alert(
|
||||||
"🔴 Proxy DOWN — likely out of credits",
|
f"🔴 {name} DOWN",
|
||||||
"The residential proxy probe failed. YouTube-URL jobs will keep "
|
f"The {name} probe failed. {hint}\n"
|
||||||
"failing until the balance is topped up.\n"
|
"This alert repeats every 2 h until it answers again.\n\n"
|
||||||
"This alert repeats every 2 h until the proxy answers again.\n\n"
|
|
||||||
f"Probe error: {detail[:400]}",
|
f"Probe error: {detail[:400]}",
|
||||||
)
|
)
|
||||||
elif now - _proxy_last_nag >= _PROXY_RENOTIFY:
|
elif now - _watch_nag[name] >= _PROXY_RENOTIFY:
|
||||||
_proxy_last_nag = now
|
_watch_nag[name] = now
|
||||||
hours = (now - _proxy_down_since) / 3600
|
hours = (now - _watch_down[name]) / 3600
|
||||||
await send_admin_alert(
|
await send_admin_alert(
|
||||||
f"🔴 Proxy STILL down ({hours:.1f} h)",
|
f"🔴 {name} STILL down ({hours:.1f} h)",
|
||||||
"The residential proxy still fails — YouTube-URL ingest remains "
|
f"{hint}\n\nProbe error: {detail[:400]}",
|
||||||
"broken until the balance is topped up.\n\n"
|
|
||||||
f"Probe error: {detail[:400]}",
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
async def proxy_watch_tick():
|
||||||
|
"""One probe cycle over every configured route."""
|
||||||
|
for name, urls in _watch_targets():
|
||||||
|
ok, detail = False, "no urls"
|
||||||
|
for u in urls:
|
||||||
|
ok, detail = await _probe_one(u)
|
||||||
|
if ok:
|
||||||
|
break
|
||||||
|
await _watch_update(name, ok, detail)
|
||||||
|
|
||||||
|
|
||||||
async def proxy_watch_loop():
|
async def proxy_watch_loop():
|
||||||
"""Background task started from the app lifespan (managed mode only)."""
|
"""Background task started from the app lifespan (managed mode only)."""
|
||||||
while True:
|
while True:
|
||||||
|
|
|
||||||
63
main.py
63
main.py
|
|
@ -602,6 +602,26 @@ def sanitize_filename(filename):
|
||||||
return truncate_bytes(filename, MAX_TITLE_BYTES)
|
return truncate_bytes(filename, MAX_TITLE_BYTES)
|
||||||
|
|
||||||
|
|
||||||
|
def plan_download_attempts(direct_first, statics, paid, have_hd):
|
||||||
|
"""Ordered (label, capped, proxy) download plan — pure, unit-tested.
|
||||||
|
|
||||||
|
Cheapest bandwidth first: the server's own IP, then the flat-rate static
|
||||||
|
ISP proxies (uncapped 1080p, free bytes), then the per-GB paid proxy
|
||||||
|
(720p cost cap), and last the conservative fallback strategy through the
|
||||||
|
paid proxy (or a static/direct when no paid proxy is configured).
|
||||||
|
``capped`` marks attempts whose bytes are billed per GB."""
|
||||||
|
plan = []
|
||||||
|
if direct_first:
|
||||||
|
plan.append(('HD-direct', False, None))
|
||||||
|
if have_hd:
|
||||||
|
for i, s in enumerate(statics):
|
||||||
|
plan.append((f'HD-static{i + 1}', False, s))
|
||||||
|
plan.append(('HD', bool(paid), paid))
|
||||||
|
plan.append(('fallback', bool(paid),
|
||||||
|
paid if paid else (statics[0] if statics else None)))
|
||||||
|
return plan
|
||||||
|
|
||||||
|
|
||||||
def download_youtube_video(url, output_dir="."):
|
def download_youtube_video(url, output_dir="."):
|
||||||
"""
|
"""
|
||||||
Downloads a YouTube video using yt-dlp.
|
Downloads a YouTube video using yt-dlp.
|
||||||
|
|
@ -640,6 +660,20 @@ def download_youtube_video(url, output_dir="."):
|
||||||
if _proxy:
|
if _proxy:
|
||||||
print("🌐 Using proxy for download.")
|
print("🌐 Using proxy for download.")
|
||||||
|
|
||||||
|
# Flat-rate static ISP proxies (STATIC_PROXY_URLS, comma-separated), tried
|
||||||
|
# BEFORE the per-GB proxy: dedicated IPs with unlimited traffic, so their
|
||||||
|
# bandwidth costs nothing per job and carries no 720p cost cap. Rotated per
|
||||||
|
# job to spread load (and YouTube's attention) across the pool. PROXY_URL
|
||||||
|
# stays the paid last resort — with STATIC_PROXY_URLS unset the behavior is
|
||||||
|
# byte-identical to before.
|
||||||
|
_statics = [p.strip() for p in
|
||||||
|
os.environ.get("STATIC_PROXY_URLS", "").split(",") if p.strip()]
|
||||||
|
if _statics:
|
||||||
|
import random as _random
|
||||||
|
k = _random.randrange(len(_statics))
|
||||||
|
_statics = _statics[k:] + _statics[:k]
|
||||||
|
print(f"🌐 {len(_statics)} static ISP proxies configured.")
|
||||||
|
|
||||||
# Two download strategies, tried in order so a break in the HD path degrades
|
# Two download strategies, tried in order so a break in the HD path degrades
|
||||||
# gracefully instead of failing the whole job: an HD attempt first, then a
|
# gracefully instead of failing the whole job: an HD attempt first, then a
|
||||||
# conservative fallback (also the only strategy for self-host).
|
# conservative fallback (also the only strategy for self-host).
|
||||||
|
|
@ -658,15 +692,16 @@ def download_youtube_video(url, output_dir="."):
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
# Cap at 720p ONLY when the bytes actually go through the paid proxy — that
|
# Cap at 720p ONLY when the bytes actually go through the PER-GB paid proxy
|
||||||
# cap exists to control bandwidth cost, and the direct attempt has none.
|
# — that cap exists to control bandwidth cost, and the direct attempt and
|
||||||
|
# the flat-rate static proxies have none.
|
||||||
#
|
#
|
||||||
# This is per-attempt on purpose. Deciding it once from `_proxy` capped the
|
# This is per-attempt on purpose. Deciding it once from `_proxy` capped the
|
||||||
# DIRECT attempt too, so with DIRECT_FIRST=1 (which serves most downloads)
|
# DIRECT attempt too, so with DIRECT_FIRST=1 (which serves most downloads)
|
||||||
# every YouTube source arrived at 720p and, since the reframe inherits the
|
# every YouTube source arrived at 720p and, since the reframe inherits the
|
||||||
# source height, 80% of delivered clips came out 406x720 (audited 25-jul-2026).
|
# source height, 80% of delivered clips came out 406x720 (audited 25-jul-2026).
|
||||||
def _hd_fmt_for(proxy):
|
def _hd_fmt_for(capped):
|
||||||
if proxy:
|
if capped:
|
||||||
return ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
|
return ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/'
|
||||||
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/'
|
'bestvideo[vcodec^=avc1][height<=720]+bestaudio/'
|
||||||
'best[height<=720][ext=mp4]/best[height<=720]/best')
|
'best[height<=720][ext=mp4]/best[height<=720]/best')
|
||||||
|
|
@ -723,13 +758,16 @@ def download_youtube_video(url, output_dir="."):
|
||||||
# Needs cookies + a PO-token provider — without both, YouTube flags the
|
# Needs cookies + a PO-token provider — without both, YouTube flags the
|
||||||
# datacenter IP after the first request (verified in prod, 21-jul-2026).
|
# datacenter IP after the first request (verified in prod, 21-jul-2026).
|
||||||
_direct_first = (os.environ.get("DIRECT_FIRST", "").strip() == "1"
|
_direct_first = (os.environ.get("DIRECT_FIRST", "").strip() == "1"
|
||||||
and _proxy and hd_args and cookies_path)
|
and (_proxy or _statics) and hd_args and cookies_path)
|
||||||
|
|
||||||
attempts = (
|
attempts = [
|
||||||
([('HD-direct', hd_args, _hd_fmt_for(None), None)] if _direct_first else [])
|
(label,
|
||||||
+ ([('HD', hd_args, _hd_fmt_for(_proxy), _proxy)] if hd_args else [])
|
fallback_args if label == 'fallback' else hd_args,
|
||||||
+ [('fallback', fallback_args, fallback_fmt, _proxy)]
|
fallback_fmt if label == 'fallback' else _hd_fmt_for(capped),
|
||||||
)
|
proxy)
|
||||||
|
for label, capped, proxy in plan_download_attempts(
|
||||||
|
_direct_first, _statics, _proxy, bool(hd_args))
|
||||||
|
]
|
||||||
|
|
||||||
sanitized_title = None
|
sanitized_title = None
|
||||||
last_err = None
|
last_err = None
|
||||||
|
|
@ -743,7 +781,10 @@ def download_youtube_video(url, output_dir="."):
|
||||||
try:
|
try:
|
||||||
print(f"📥 Download attempt: {label}" + (f" (retry {retry})" if retry else ""))
|
print(f"📥 Download attempt: {label}" + (f" (retry {retry})" if retry else ""))
|
||||||
sanitized_title = _attempt(ea, fmt, proxy)
|
sanitized_title = _attempt(ea, fmt, proxy)
|
||||||
used_proxy = proxy is not None
|
# Only bytes through the PER-GB proxy cost money; direct and
|
||||||
|
# the flat-rate static proxies are free bandwidth for the
|
||||||
|
# monthly counter's purposes.
|
||||||
|
used_proxy = proxy is not None and proxy == _proxy
|
||||||
print(f"✅ Download succeeded ({label}).")
|
print(f"✅ Download succeeded ({label}).")
|
||||||
break
|
break
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
|
|
|
||||||
47
tests/test_download_plan.py
Normal file
47
tests/test_download_plan.py
Normal file
|
|
@ -0,0 +1,47 @@
|
||||||
|
"""Download attempt ordering: cheapest bandwidth first.
|
||||||
|
|
||||||
|
Direct (server IP) -> flat-rate static ISP proxies (uncapped 1080p, free
|
||||||
|
bytes) -> per-GB paid proxy (720p cost cap) -> conservative fallback. The
|
||||||
|
``capped`` flag marks the attempts whose bytes are billed per GB (drives the
|
||||||
|
720p format cap and the PROXY_BYTES monthly counter).
|
||||||
|
"""
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
main = pytest.importorskip("main")
|
||||||
|
|
||||||
|
plan = main.plan_download_attempts
|
||||||
|
|
||||||
|
STATICS = ["http://s1", "http://s2", "http://s3"]
|
||||||
|
PAID = "http://paid"
|
||||||
|
|
||||||
|
|
||||||
|
class TestOrdering:
|
||||||
|
def test_full_chain(self):
|
||||||
|
got = plan(True, STATICS, PAID, True)
|
||||||
|
assert got == [
|
||||||
|
('HD-direct', False, None),
|
||||||
|
('HD-static1', False, "http://s1"),
|
||||||
|
('HD-static2', False, "http://s2"),
|
||||||
|
('HD-static3', False, "http://s3"),
|
||||||
|
('HD', True, PAID),
|
||||||
|
('fallback', True, PAID),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_statics_only_fallback_uses_a_static(self):
|
||||||
|
got = plan(False, STATICS, None, True)
|
||||||
|
assert got[-1] == ('fallback', False, "http://s1")
|
||||||
|
assert ('HD', False, None) in got # direct HD still tried, uncapped
|
||||||
|
|
||||||
|
def test_selfhost_no_proxies_matches_legacy_chain(self):
|
||||||
|
assert plan(False, [], None, True) == [
|
||||||
|
('HD', False, None),
|
||||||
|
('fallback', False, None),
|
||||||
|
]
|
||||||
|
|
||||||
|
def test_no_hd_args_still_has_fallback(self):
|
||||||
|
assert plan(False, [], PAID, False) == [('fallback', True, PAID)]
|
||||||
|
|
||||||
|
def test_paid_attempts_are_the_only_capped_ones(self):
|
||||||
|
got = plan(True, STATICS, PAID, True)
|
||||||
|
for _label, capped, proxy in got:
|
||||||
|
assert capped == (proxy == PAID)
|
||||||
|
|
@ -1,9 +1,9 @@
|
||||||
"""Proxy balance watcher: alert on down, nag until topped up, confirm recovery.
|
"""Proxy watcher: alert on down, nag until fixed, confirm recovery.
|
||||||
|
|
||||||
Born from the 19-aug-2026 incident: DataImpulse ran out of traffic
|
Born from the 19-aug-2026 incident: DataImpulse ran out of traffic
|
||||||
(407 TRAFFIC_EXHAUSTED), every YouTube-URL job failed, and nobody was told
|
(407 TRAFFIC_EXHAUSTED), every YouTube-URL job failed, and nobody was told
|
||||||
more than once. The watcher must keep nagging while the proxy is down and
|
more than once. The watcher probes every configured route (static ISP pool
|
||||||
close the loop when it answers again.
|
first, per-GB paid proxy last) and keeps nagging while one is down.
|
||||||
"""
|
"""
|
||||||
import asyncio
|
import asyncio
|
||||||
|
|
||||||
|
|
@ -18,82 +18,116 @@ def _run(coro):
|
||||||
|
|
||||||
@pytest.fixture(autouse=True)
|
@pytest.fixture(autouse=True)
|
||||||
def _reset_state(monkeypatch):
|
def _reset_state(monkeypatch):
|
||||||
alerts._proxy_down_since = None
|
alerts._watch_down.clear()
|
||||||
alerts._proxy_last_nag = 0.0
|
alerts._watch_nag.clear()
|
||||||
alerts._last_alert.clear()
|
alerts._last_alert.clear()
|
||||||
sent = []
|
sent = []
|
||||||
|
|
||||||
async def fake_alert(subject, body):
|
async def fake_alert(subject, body):
|
||||||
sent.append(subject)
|
sent.append((subject, body))
|
||||||
|
|
||||||
monkeypatch.setattr(alerts, "send_admin_alert", fake_alert)
|
monkeypatch.setattr(alerts, "send_admin_alert", fake_alert)
|
||||||
yield sent
|
yield sent
|
||||||
alerts._proxy_down_since = None
|
alerts._watch_down.clear()
|
||||||
alerts._proxy_last_nag = 0.0
|
alerts._watch_nag.clear()
|
||||||
|
|
||||||
|
|
||||||
def _probe_returning(value):
|
def _probes(results):
|
||||||
async def fake_probe():
|
"""Fake _probe_one returning per-url results (dict url -> (ok, detail))."""
|
||||||
return value
|
async def fake_probe(url):
|
||||||
|
return results[url]
|
||||||
return fake_probe
|
return fake_probe
|
||||||
|
|
||||||
|
|
||||||
class TestProxyWatchTick:
|
class TestWatchTargets:
|
||||||
def test_no_proxy_configured_is_silent(self, _reset_state, monkeypatch):
|
def test_no_env_no_targets(self, monkeypatch):
|
||||||
monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning(None))
|
monkeypatch.delenv("STATIC_PROXY_URLS", raising=False)
|
||||||
_run(alerts.proxy_watch_tick())
|
monkeypatch.delenv("PROXY_URL", raising=False)
|
||||||
assert _reset_state == []
|
assert alerts._watch_targets() == []
|
||||||
assert alerts._proxy_down_since is None
|
|
||||||
|
|
||||||
def test_healthy_proxy_is_silent(self, _reset_state, monkeypatch):
|
def test_both_pools_in_order(self, monkeypatch):
|
||||||
monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning((True, "")))
|
monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1, http://s2 ,")
|
||||||
|
monkeypatch.setenv("PROXY_URL", "http://paid")
|
||||||
|
assert alerts._watch_targets() == [
|
||||||
|
(alerts._STATIC_TARGET, ["http://s1", "http://s2"]),
|
||||||
|
(alerts._PAID_TARGET, ["http://paid"]),
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
|
class TestWatchTick:
|
||||||
|
def _env(self, monkeypatch, statics="http://s1,http://s2", paid="http://paid"):
|
||||||
|
if statics:
|
||||||
|
monkeypatch.setenv("STATIC_PROXY_URLS", statics)
|
||||||
|
else:
|
||||||
|
monkeypatch.delenv("STATIC_PROXY_URLS", raising=False)
|
||||||
|
if paid:
|
||||||
|
monkeypatch.setenv("PROXY_URL", paid)
|
||||||
|
else:
|
||||||
|
monkeypatch.delenv("PROXY_URL", raising=False)
|
||||||
|
|
||||||
|
def test_all_healthy_is_silent(self, _reset_state, monkeypatch):
|
||||||
|
self._env(monkeypatch)
|
||||||
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
|
"http://s1": (True, ""), "http://paid": (True, "")}))
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
assert _reset_state == []
|
assert _reset_state == []
|
||||||
|
|
||||||
def test_first_failure_alerts_once(self, _reset_state, monkeypatch):
|
def test_pool_is_up_if_any_ip_answers(self, _reset_state, monkeypatch):
|
||||||
monkeypatch.setattr(
|
self._env(monkeypatch)
|
||||||
alerts, "_probe_proxy",
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
_probe_returning((False, "HTTP 407 TRAFFIC_EXHAUSTED")))
|
"http://s1": (False, "HTTP 407"), "http://s2": (True, ""),
|
||||||
|
"http://paid": (True, "")}))
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
_run(alerts.proxy_watch_tick()) # next probe, renotify window not due
|
assert _reset_state == []
|
||||||
|
|
||||||
|
def test_static_pool_down_alerts_with_cost_hint(self, _reset_state, monkeypatch):
|
||||||
|
self._env(monkeypatch)
|
||||||
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
|
"http://s1": (False, "boom"), "http://s2": (False, "boom"),
|
||||||
|
"http://paid": (True, "")}))
|
||||||
|
_run(alerts.proxy_watch_tick())
|
||||||
|
_run(alerts.proxy_watch_tick()) # renotify window not due yet
|
||||||
assert len(_reset_state) == 1
|
assert len(_reset_state) == 1
|
||||||
assert "DOWN" in _reset_state[0]
|
subject, body = _reset_state[0]
|
||||||
assert alerts._proxy_down_since is not None
|
assert alerts._STATIC_TARGET in subject and "DOWN" in subject
|
||||||
|
assert "costs money" in body
|
||||||
|
|
||||||
def test_nags_again_after_renotify_window(self, _reset_state, monkeypatch):
|
def test_paid_down_alerts_and_nags_after_window(self, _reset_state, monkeypatch):
|
||||||
monkeypatch.setattr(
|
self._env(monkeypatch, statics=None)
|
||||||
alerts, "_probe_proxy", _probe_returning((False, "HTTP 407")))
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
|
"http://paid": (False, "HTTP 407")}))
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
# Pretend the last nag was over the renotify window ago.
|
alerts._watch_nag[alerts._PAID_TARGET] -= alerts._PROXY_RENOTIFY + 1
|
||||||
alerts._proxy_last_nag -= alerts._PROXY_RENOTIFY + 1
|
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
assert len(_reset_state) == 2
|
assert len(_reset_state) == 2
|
||||||
assert "STILL down" in _reset_state[1]
|
assert "STILL down" in _reset_state[1][0]
|
||||||
|
|
||||||
def test_recovery_confirms_and_resets(self, _reset_state, monkeypatch):
|
def test_recovery_confirms_and_resets(self, _reset_state, monkeypatch):
|
||||||
monkeypatch.setattr(
|
self._env(monkeypatch, statics=None)
|
||||||
alerts, "_probe_proxy", _probe_returning((False, "HTTP 407")))
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
|
"http://paid": (False, "HTTP 407")}))
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning((True, "")))
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
|
"http://paid": (True, "")}))
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
assert any("recovered" in s for s in _reset_state)
|
assert any("recovered" in s for s, _ in _reset_state)
|
||||||
assert alerts._proxy_down_since is None
|
assert not alerts._watch_down.get(alerts._PAID_TARGET)
|
||||||
# A later failure is a NEW incident and alerts again.
|
# A later failure is a NEW incident and alerts again.
|
||||||
monkeypatch.setattr(
|
monkeypatch.setattr(alerts, "_probe_one", _probes({
|
||||||
alerts, "_probe_proxy", _probe_returning((False, "HTTP 407")))
|
"http://paid": (False, "HTTP 407")}))
|
||||||
_run(alerts.proxy_watch_tick())
|
_run(alerts.proxy_watch_tick())
|
||||||
assert sum("DOWN" in s for s in _reset_state) == 2
|
assert sum("DOWN" in s for s, _ in _reset_state) == 2
|
||||||
|
|
||||||
|
|
||||||
class TestJobFailureOpensIncident:
|
class TestJobFailureOpensIncident:
|
||||||
def test_proxy_job_error_opens_incident_and_alerts(self, _reset_state):
|
def test_proxy_job_error_opens_paid_incident_and_alerts(self, _reset_state):
|
||||||
_run(alerts.record_job_outcome(
|
_run(alerts.record_job_outcome(
|
||||||
False,
|
False,
|
||||||
"yt_dlp.utils.DownloadError: Unable to connect to proxy "
|
"yt_dlp.utils.DownloadError: Unable to connect to proxy "
|
||||||
"('Tunnel connection failed: 407 TRAFFIC_EXHAUSTED')"))
|
"('Tunnel connection failed: 407 TRAFFIC_EXHAUSTED')"))
|
||||||
assert alerts._proxy_down_since is not None
|
assert alerts._watch_down.get(alerts._PAID_TARGET)
|
||||||
assert len(_reset_state) == 1
|
assert len(_reset_state) == 1
|
||||||
|
|
||||||
def test_non_proxy_error_leaves_incident_closed(self, _reset_state):
|
def test_non_proxy_error_leaves_incident_closed(self, _reset_state):
|
||||||
_run(alerts.record_job_outcome(False, "ffmpeg exploded"))
|
_run(alerts.record_job_outcome(False, "ffmpeg exploded"))
|
||||||
assert alerts._proxy_down_since is None
|
assert not alerts._watch_down.get(alerts._PAID_TARGET)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue