feat(alerts): proxy balance watcher — nag on Telegram until topped up

The residential proxy ran out of traffic (407 TRAFFIC_EXHAUSTED,
19-aug-2026) and every YouTube-URL job failed with only easy-to-miss
one-shot alerts. Now:

- cloud/alerts.py: a background watcher probes the proxy every 30 min
  (generate_204, a few bytes of paid traffic). On failure it alerts
  immediately, re-alerts every 2 h while the proxy stays down, and sends
  a recovery confirmation when it answers again — so exhaustion is caught
  even before the next user job fails.
- record_job_outcome: a proxy-classified job failure also opens the
  incident, so job-driven detection and the probe share one state.
- app.py: the watcher starts from the lifespan in managed mode.
- tests/test_proxy_watch.py: state machine (first alert, renotify window,
  recovery + reset, job-error trigger).
This commit is contained in:
juancarlos.cavero 2026-08-19 17:07:09 +02:00
parent f8535b2584
commit 5e84e6486a
3 changed files with 204 additions and 8 deletions

4
app.py
View file

@ -1152,6 +1152,10 @@ async def lifespan(app: FastAPI):
cleanup_task = asyncio.create_task(cleanup_jobs())
if BILLING_ENABLED:
await cloud.setup_async(app, keep_reservation_ids=_resumed_reservation_ids)
# Nag on Telegram while the residential proxy is down/out of credits —
# a single job-failure alert is easy to miss and ingest stays broken
# until someone tops the balance up.
asyncio.create_task(_alerts.proxy_watch_loop())
yield
# Cleanup (optional: cancel worker)

View file

@ -3,6 +3,8 @@
Tracks recent managed-job outcomes in memory and emails ADMIN_EMAIL (via Resend)
when something looks broken, with a per-alert cooldown so it never spams.
"""
import asyncio
import os
import time
from collections import deque
@ -117,16 +119,25 @@ 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
# 1) Proxy / credits problem — most urgent, alert immediately.
if _looks_like_proxy_error(error_text) and _cooldown_ok("proxy"):
# 1) Proxy / credits problem — most urgent, alert immediately AND open the
# incident so the proxy watcher keeps nagging until the balance is back
# (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 _cooldown_ok("proxy"):
await send_admin_alert(
"⚠️ Proxy error — may be out of credits",
"🔴 Proxy error — may be out of credits",
"A managed job failed with a proxy-related error. Check your proxy "
"balance — downloads will keep failing until it's topped up.\n\n"
"balance — downloads will keep failing until it's topped up.\n"
"This repeats every 2 h until the proxy answers again.\n\n"
f"Error:\n{error_text[:1200]}",
)
return
@ -142,3 +153,85 @@ async def record_job_outcome(ok: bool, error_text: str = ""):
f"{fails} of the last {len(recent)} managed jobs failed.\n\n"
f"Last error:\n{error_text[:1200]}",
)
# --- 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_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.
_PROXY_PROBE_URL = "https://www.google.com/generate_204"
_proxy_down_since = None
_proxy_last_nag = 0.0
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
try:
import httpx
async with httpx.AsyncClient(proxy=proxy, timeout=20) as client:
resp = await client.get(_PROXY_PROBE_URL)
if resp.status_code < 400:
return True, ""
return False, f"HTTP {resp.status_code}"
except Exception as e:
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
now = time.time()
if ok:
if _proxy_down_since:
mins = int((now - _proxy_down_since) / 60)
await send_admin_alert(
"✅ Proxy recovered",
f"The residential proxy answers again after ~{mins} min down. "
"YouTube-URL ingest should be back.",
)
_proxy_down_since = None
_proxy_last_nag = 0.0
return
if not _proxy_down_since:
_proxy_down_since = now
_proxy_last_nag = 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"Probe error: {detail[:400]}",
)
elif now - _proxy_last_nag >= _PROXY_RENOTIFY:
_proxy_last_nag = now
hours = (now - _proxy_down_since) / 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]}",
)
async def proxy_watch_loop():
"""Background task started from the app lifespan (managed mode only)."""
while True:
try:
await proxy_watch_tick()
except Exception as e:
print(f"⚠️ Proxy watch error: {e}")
await asyncio.sleep(_PROXY_PROBE_INTERVAL)

99
tests/test_proxy_watch.py Normal file
View file

@ -0,0 +1,99 @@
"""Proxy balance watcher: alert on down, nag until topped up, 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.
"""
import asyncio
import pytest
from cloud import alerts
def _run(coro):
return asyncio.run(coro)
@pytest.fixture(autouse=True)
def _reset_state(monkeypatch):
alerts._proxy_down_since = None
alerts._proxy_last_nag = 0.0
alerts._last_alert.clear()
sent = []
async def fake_alert(subject, body):
sent.append(subject)
monkeypatch.setattr(alerts, "send_admin_alert", fake_alert)
yield sent
alerts._proxy_down_since = None
alerts._proxy_last_nag = 0.0
def _probe_returning(value):
async def fake_probe():
return value
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
def test_healthy_proxy_is_silent(self, _reset_state, monkeypatch):
monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning((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")))
_run(alerts.proxy_watch_tick())
_run(alerts.proxy_watch_tick()) # next probe, renotify window not due
assert len(_reset_state) == 1
assert "DOWN" in _reset_state[0]
assert alerts._proxy_down_since is not None
def test_nags_again_after_renotify_window(self, _reset_state, monkeypatch):
monkeypatch.setattr(
alerts, "_probe_proxy", _probe_returning((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
_run(alerts.proxy_watch_tick())
assert len(_reset_state) == 2
assert "STILL down" in _reset_state[1]
def test_recovery_confirms_and_resets(self, _reset_state, monkeypatch):
monkeypatch.setattr(
alerts, "_probe_proxy", _probe_returning((False, "HTTP 407")))
_run(alerts.proxy_watch_tick())
monkeypatch.setattr(alerts, "_probe_proxy", _probe_returning((True, "")))
_run(alerts.proxy_watch_tick())
assert any("recovered" in s for s in _reset_state)
assert alerts._proxy_down_since is None
# A later failure is a NEW incident and alerts again.
monkeypatch.setattr(
alerts, "_probe_proxy", _probe_returning((False, "HTTP 407")))
_run(alerts.proxy_watch_tick())
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):
_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 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