From dfa31241ca87dc0ad5a06bc60dfe6898d0573080 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Wed, 19 Aug 2026 19:28:52 +0200 Subject: [PATCH] feat(download): flat-rate static ISP proxies before the per-GB proxy MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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. --- cloud/alerts.py | 117 +++++++++++++++++++++-------------- main.py | 63 +++++++++++++++---- tests/test_download_plan.py | 47 ++++++++++++++ tests/test_proxy_watch.py | 120 +++++++++++++++++++++++------------- 4 files changed, 246 insertions(+), 101 deletions(-) create mode 100644 tests/test_download_plan.py diff --git a/cloud/alerts.py b/cloud/alerts.py index f62d81b..8b4ffcb 100644 --- a/cloud/alerts.py +++ b/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 = ""): """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)) if ok: 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 # YouTube-URL ingest down until someone tops it up). if _looks_like_proxy_error(error_text): - if not _proxy_down_since: - _proxy_down_since = time.time() - _proxy_last_nag = time.time() + if not _watch_down.get(_PAID_TARGET): + _watch_down[_PAID_TARGET] = time.time() + _watch_nag[_PAID_TARGET] = time.time() if _cooldown_ok("proxy"): await send_admin_alert( "🔴 Proxy error — may be out of credits", @@ -155,13 +154,18 @@ async def record_job_outcome(ok: bool, error_text: str = ""): ) -# --- Proxy balance watcher ---------------------------------------------------- -# An exhausted residential proxy takes ALL YouTube-URL ingest down (when the -# datacenter IP is blocked, the proxy is the only working route), and a single -# alert at the moment it dies is easy to miss. This watcher probes the proxy on -# a schedule, keeps nagging on Telegram until the balance is topped up, and -# confirms recovery — so exhaustion is caught even before the next user job -# fails (incident of 19-aug-2026: 407 TRAFFIC_EXHAUSTED, found by accident). +# --- Proxy watcher -------------------------------------------------------------- +# A dead download route takes YouTube-URL ingest down (or silently moves it to +# per-GB billing), and a single alert at the moment it dies is easy to miss. +# The watcher probes every configured route on a schedule, keeps nagging on +# Telegram until it's fixed, and confirms recovery (incident of 19-aug-2026: +# DataImpulse 407 TRAFFIC_EXHAUSTED, found by accident hours later). +# +# 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_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. @@ -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 # rejects the request before forwarding, so HTTP still detects the 407. _PROXY_PROBE_URL = "http://www.google.com/generate_204" -_proxy_down_since = None -_proxy_last_nag = 0.0 +_watch_down = {} # target name -> down-since epoch +_watch_nag = {} # target name -> last-nag epoch + +_PAID_TARGET = "paid proxy" +_STATIC_TARGET = "static proxy pool" -async def _probe_proxy(): - """(ok, detail) for one cheap request through the residential proxy, or - None when no proxy is configured (nothing to watch).""" - proxy = os.environ.get("PROXY_URL", "").strip() - if not proxy: - return None +def _watch_targets(): + """[(name, [proxy urls])] — a target is up if ANY of its urls answers.""" + targets = [] + statics = [p.strip() for p in + os.environ.get("STATIC_PROXY_URLS", "").split(",") if p.strip()] + 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: import httpx 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}" -async def proxy_watch_tick(): - """One probe cycle: open the incident, nag while down, confirm recovery.""" - global _proxy_down_since, _proxy_last_nag - result = await _probe_proxy() - if result is None: - return - ok, detail = result +async def _watch_update(name, ok, detail): + """Shared incident state machine: alert on down, nag, confirm recovery.""" now = time.time() if ok: - if _proxy_down_since: - mins = int((now - _proxy_down_since) / 60) + if _watch_down.get(name): + mins = int((now - _watch_down[name]) / 60) await send_admin_alert( - "✅ Proxy recovered", - f"The residential proxy answers again after ~{mins} min down. " - "YouTube-URL ingest should be back.", + f"✅ {name} recovered", + f"The {name} answers again after ~{mins} min down.", ) - _proxy_down_since = None - _proxy_last_nag = 0.0 + _watch_down[name] = None + _watch_nag[name] = 0.0 return - if not _proxy_down_since: - _proxy_down_since = now - _proxy_last_nag = now + hint = ("YouTube-URL jobs are falling back to the PER-GB paid proxy — " + "ingest still works but every download now costs money." + 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( - "🔴 Proxy DOWN — likely out of credits", - "The residential proxy probe failed. YouTube-URL jobs will keep " - "failing until the balance is topped up.\n" - "This alert repeats every 2 h until the proxy answers again.\n\n" + f"🔴 {name} DOWN", + f"The {name} probe failed. {hint}\n" + "This alert repeats every 2 h until it answers again.\n\n" f"Probe error: {detail[:400]}", ) - elif now - _proxy_last_nag >= _PROXY_RENOTIFY: - _proxy_last_nag = now - hours = (now - _proxy_down_since) / 3600 + elif now - _watch_nag[name] >= _PROXY_RENOTIFY: + _watch_nag[name] = now + hours = (now - _watch_down[name]) / 3600 await send_admin_alert( - f"🔴 Proxy STILL down ({hours:.1f} h)", - "The residential proxy still fails — YouTube-URL ingest remains " - "broken until the balance is topped up.\n\n" - f"Probe error: {detail[:400]}", + f"🔴 {name} STILL down ({hours:.1f} h)", + f"{hint}\n\nProbe 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(): """Background task started from the app lifespan (managed mode only).""" while True: diff --git a/main.py b/main.py index 6a2f73a..904e924 100644 --- a/main.py +++ b/main.py @@ -602,6 +602,26 @@ def sanitize_filename(filename): 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="."): """ Downloads a YouTube video using yt-dlp. @@ -640,6 +660,20 @@ def download_youtube_video(url, output_dir="."): if _proxy: 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 # gracefully instead of failing the whole job: an HD attempt first, then a # 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 exists to control bandwidth cost, and the direct attempt has none. + # Cap at 720p ONLY when the bytes actually go through the PER-GB paid proxy + # — 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 # DIRECT attempt too, so with DIRECT_FIRST=1 (which serves most downloads) # 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). - def _hd_fmt_for(proxy): - if proxy: + def _hd_fmt_for(capped): + if capped: return ('bestvideo[vcodec^=avc1][height<=720][ext=mp4]+bestaudio[ext=m4a]/' 'bestvideo[vcodec^=avc1][height<=720]+bestaudio/' '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 # datacenter IP after the first request (verified in prod, 21-jul-2026). _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 = ( - ([('HD-direct', hd_args, _hd_fmt_for(None), None)] if _direct_first else []) - + ([('HD', hd_args, _hd_fmt_for(_proxy), _proxy)] if hd_args else []) - + [('fallback', fallback_args, fallback_fmt, _proxy)] - ) + attempts = [ + (label, + fallback_args if label == 'fallback' else hd_args, + 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 last_err = None @@ -743,7 +781,10 @@ def download_youtube_video(url, output_dir="."): try: print(f"📥 Download attempt: {label}" + (f" (retry {retry})" if retry else "")) 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}).") break except Exception as e: diff --git a/tests/test_download_plan.py b/tests/test_download_plan.py new file mode 100644 index 0000000..5e33d82 --- /dev/null +++ b/tests/test_download_plan.py @@ -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) diff --git a/tests/test_proxy_watch.py b/tests/test_proxy_watch.py index c975537..c8e8d7e 100644 --- a/tests/test_proxy_watch.py +++ b/tests/test_proxy_watch.py @@ -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 (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 -close the loop when it answers again. +more than once. The watcher probes every configured route (static ISP pool +first, per-GB paid proxy last) and keeps nagging while one is down. """ import asyncio @@ -18,82 +18,116 @@ def _run(coro): @pytest.fixture(autouse=True) def _reset_state(monkeypatch): - alerts._proxy_down_since = None - alerts._proxy_last_nag = 0.0 + alerts._watch_down.clear() + alerts._watch_nag.clear() alerts._last_alert.clear() sent = [] async def fake_alert(subject, body): - sent.append(subject) + sent.append((subject, body)) monkeypatch.setattr(alerts, "send_admin_alert", fake_alert) yield sent - alerts._proxy_down_since = None - alerts._proxy_last_nag = 0.0 + alerts._watch_down.clear() + alerts._watch_nag.clear() -def _probe_returning(value): - async def fake_probe(): - return value +def _probes(results): + """Fake _probe_one returning per-url results (dict url -> (ok, detail)).""" + async def fake_probe(url): + return results[url] return fake_probe -class TestProxyWatchTick: - def test_no_proxy_configured_is_silent(self, _reset_state, monkeypatch): - monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning(None)) - _run(alerts.proxy_watch_tick()) - assert _reset_state == [] - assert alerts._proxy_down_since is None +class TestWatchTargets: + def test_no_env_no_targets(self, monkeypatch): + monkeypatch.delenv("STATIC_PROXY_URLS", raising=False) + monkeypatch.delenv("PROXY_URL", raising=False) + assert alerts._watch_targets() == [] - def test_healthy_proxy_is_silent(self, _reset_state, monkeypatch): - monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning((True, ""))) + def test_both_pools_in_order(self, monkeypatch): + 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()) assert _reset_state == [] - def test_first_failure_alerts_once(self, _reset_state, monkeypatch): - monkeypatch.setattr( - alerts, "_probe_proxy", - _probe_returning((False, "HTTP 407 TRAFFIC_EXHAUSTED"))) + def test_pool_is_up_if_any_ip_answers(self, _reset_state, monkeypatch): + self._env(monkeypatch) + monkeypatch.setattr(alerts, "_probe_one", _probes({ + "http://s1": (False, "HTTP 407"), "http://s2": (True, ""), + "http://paid": (True, "")})) _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 "DOWN" in _reset_state[0] - assert alerts._proxy_down_since is not None + subject, body = _reset_state[0] + 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): - monkeypatch.setattr( - alerts, "_probe_proxy", _probe_returning((False, "HTTP 407"))) + def test_paid_down_alerts_and_nags_after_window(self, _reset_state, monkeypatch): + self._env(monkeypatch, statics=None) + monkeypatch.setattr(alerts, "_probe_one", _probes({ + "http://paid": (False, "HTTP 407")})) _run(alerts.proxy_watch_tick()) - # Pretend the last nag was over the renotify window ago. - alerts._proxy_last_nag -= alerts._PROXY_RENOTIFY + 1 + alerts._watch_nag[alerts._PAID_TARGET] -= alerts._PROXY_RENOTIFY + 1 _run(alerts.proxy_watch_tick()) 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): - monkeypatch.setattr( - alerts, "_probe_proxy", _probe_returning((False, "HTTP 407"))) + self._env(monkeypatch, statics=None) + monkeypatch.setattr(alerts, "_probe_one", _probes({ + "http://paid": (False, "HTTP 407")})) _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()) - assert any("recovered" in s for s in _reset_state) - assert alerts._proxy_down_since is None + assert any("recovered" in s for s, _ in _reset_state) + assert not alerts._watch_down.get(alerts._PAID_TARGET) # A later failure is a NEW incident and alerts again. - monkeypatch.setattr( - alerts, "_probe_proxy", _probe_returning((False, "HTTP 407"))) + monkeypatch.setattr(alerts, "_probe_one", _probes({ + "http://paid": (False, "HTTP 407")})) _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: - 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( False, "yt_dlp.utils.DownloadError: Unable to connect to proxy " "('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 def test_non_proxy_error_leaves_incident_closed(self, _reset_state): _run(alerts.record_job_outcome(False, "ffmpeg exploded")) - assert alerts._proxy_down_since is None + assert not alerts._watch_down.get(alerts._PAID_TARGET)