From 5459f69ec6eaaf888c283b12f8bb55800455a4e1 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Wed, 2 Sep 2026 13:25:06 +0200 Subject: [PATCH] feat(proxy): daily budget cap for the paid proxy, and probe the statics against YouTube PAID_PROXY_DAILY_MB (default 500): past it, the per-GB proxy is dropped from the duration probe and from every new job's env until UTC midnight, with one Telegram note per day. A repeat of 28-aug (statics refused by YouTube for hours) now costs $0.50 at worst instead of $14. The watcher probed the statics against google.com/generate_204, which kept answering 204 that whole day while YouTube served the static IPs fake 'Video unavailable'. A static now has to return a real watch page with a playable player response; the paid probe keeps the cheap plain-HTTP 204 (HTTPS through DataImpulse breaks in httpx even when healthy). Claude-Session: https://claude.ai/code/session_014i9z6mLTy978uRCfSsMfBq --- .env.example | 5 ++ CLAUDE.md | 7 ++- app.py | 25 +++++++++- cloud/alerts.py | 31 ++++++++++-- cloud/metering.py | 4 +- cloud/proxy_ledger.py | 70 ++++++++++++++++++++++++++ tests/test_proxy_ledger.py | 100 +++++++++++++++++++++++++++++++++++++ 7 files changed, 234 insertions(+), 8 deletions(-) diff --git a/.env.example b/.env.example index 3a687cd..6443358 100644 --- a/.env.example +++ b/.env.example @@ -65,3 +65,8 @@ GEMINI_IMAGE_MODEL=gemini-3.1-flash-image # LLM_API_KEY= # LLM_SCORE_BATCH=3 # LLM_TIMEOUT=600 + +# Hard daily ceiling for the per-GB paid proxy (UTC day, MB). Above it, +# DataImpulse is removed from every chain until midnight and the jobs that +# needed it fail with a clear error. 0 disables the cap. Default 500. +# PAID_PROXY_DAILY_MB=500 diff --git a/CLAUDE.md b/CLAUDE.md index c3e73ee..25b8614 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -349,7 +349,12 @@ paid ones, each free attempt's error); `app.py` persists it as a `proxy_usage` row at job end and pages Telegram when the paid proxy carried bytes, folding a burst into one message per 5 min. The in-memory monthly counter and the container log (rotates within the hour) cannot answer "what -cost $14 on the 28th"; the table can. On the dev Mac, do not keep +cost $14 on the 28th"; the table can. `PAID_PROXY_DAILY_MB` (default +500) is the hard ceiling: past it the paid proxy is dropped from the probe +and from every new job's env until UTC midnight. The watcher probes the +static pool against a real YouTube watch page (playable markers), not +google.com — the 28th happened because YouTube refused the static IPs while +google kept answering 204. On the dev Mac, do not keep `PROXY_URL` in `.env`: every local `main.py` run then bills DataImpulse. ### Deploys and running jobs (handover + drain) diff --git a/app.py b/app.py index 14e36c2..3b4a106 100644 --- a/app.py +++ b/app.py @@ -297,11 +297,20 @@ async def reserve_process_minutes(request, url, input_path, job_id): # job cap. _check_probe_rate(user.id) - # Probe input duration (blocking → run in a thread). + # Probe input duration (blocking → run in a thread). When today's paid + # traffic is over budget, the probe (and below, the job itself) runs + # without the per-GB proxy: statics or nothing. + try: + from cloud import proxy_ledger as _pl + paid_allowed = not await _pl.budget_exceeded() + except Exception: + pass loop = asyncio.get_event_loop() try: if url: - minutes = await loop.run_in_executor(None, _metering.probe_url_minutes, url) + minutes = await loop.run_in_executor( + None, functools.partial(_metering.probe_url_minutes, url, + allow_paid=paid_allowed)) else: minutes = await loop.run_in_executor(None, _metering.probe_file_minutes, input_path) except Exception: @@ -896,6 +905,12 @@ def _resume_interrupted_jobs() -> set: # Rebuild env from scratch — the manifest holds no secrets. Managed # (cloud) jobs get the server key; self-host falls back to its env key. env = os.environ.copy() + try: + from cloud import proxy_ledger as _pl + if BILLING_ENABLED and _pl.budget_exceeded_sync(): + env.pop("PROXY_URL", None) # daily paid-proxy budget hit + except Exception: + pass if BILLING_ENABLED and user_id is not None: try: env["GEMINI_API_KEY"] = managed_keys.gemini_key() @@ -2169,6 +2184,9 @@ async def process_endpoint( raise gemini_missing_error() ack_flag = str(acknowledged).lower() in ("1", "true", "yes") + # May be lowered by the paid-proxy budget check in the metering block + # below; self-host never runs that block, so it must default here. + paid_allowed = True force_low = str(force_low_quality).lower() in ("1", "true", "yes") # Handle JSON body manually for URL payload @@ -2289,6 +2307,9 @@ async def process_endpoint( # probe above already gets this right. cmd = [sys.executable, "-u", "main.py"] # -u for unbuffered env = os.environ.copy() + if not paid_allowed: + # Daily paid-proxy budget hit: this job runs on the free routes only. + env.pop("PROXY_URL", None) if api_key: env["GEMINI_API_KEY"] = api_key # Override with key from request else: diff --git a/cloud/alerts.py b/cloud/alerts.py index e4635dd..2432a53 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -178,6 +178,14 @@ _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" +# The static pool gets probed against YouTube itself, not google.com: on +# 28-aug-2026 YouTube refused the static IPs for hours ("Video unavailable" / +# bot-check) while google.com kept answering 204, so the watcher said UP and +# every job silently moved to the per-GB proxy ($14 that day). A healthy +# static must return the watch page with a playable player response; bytes +# 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"') _PROXY_STRIKES = 2 # consecutive failed probes before alerting _watch_down = {} # target name -> down-since epoch _watch_nag = {} # target name -> last-nag epoch @@ -201,14 +209,29 @@ def _watch_targets(): async def _probe_one(proxy): - """(ok, detail) for one cheap request through one proxy.""" + """(ok, detail) for one request through one proxy. + + The paid proxy keeps the plain-HTTP 204 probe (HTTPS through DataImpulse + breaks in httpx even when healthy). A static IP is probed against a real + YouTube watch page: answering is not enough, the page must carry a + playable player response, or the IP is flagged and every download is + about to fall through to per-GB billing. + """ + is_paid = proxy == os.environ.get("PROXY_URL", "").strip() 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: + resp = await client.get(_PROXY_PROBE_URL if is_paid else _STATIC_PROBE_URL, + follow_redirects=not is_paid) + if resp.status_code >= 400: + return False, f"HTTP {resp.status_code}" + if is_paid: return True, "" - return False, f"HTTP {resp.status_code}" + 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')") except Exception as e: return False, f"{type(e).__name__}: {e}" diff --git a/cloud/metering.py b/cloud/metering.py index 74ff6c0..405b14c 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -144,7 +144,7 @@ def is_youtube_url(url: str) -> bool: "music.youtube.com") or host.endswith(".youtube.com") -def probe_url_minutes(url: str) -> float: +def probe_url_minutes(url: str, allow_paid: bool = True) -> float: """Return the video duration in minutes from yt-dlp metadata (no download). Uses the same proxy order + extractor settings as the actual download @@ -181,6 +181,8 @@ def probe_url_minutes(url: str) -> float: k = random.randrange(len(statics)) statics = statics[k:] + statics[:k] paid = os.environ.get("PROXY_URL", "").strip() + if not allow_paid: + paid = "" # daily budget hit (cloud/proxy_ledger.budget_exceeded) # Same rule as the download plan: a non-YouTube URL never touches the # per-GB proxy (main.plan_download_attempts, youtube=False). Twitch, Kick, # Rumble, product pages and drive links were all reaching it here. diff --git a/cloud/proxy_ledger.py b/cloud/proxy_ledger.py index 854f55b..10f48c9 100644 --- a/cloud/proxy_ledger.py +++ b/cloud/proxy_ledger.py @@ -17,7 +17,9 @@ job would have been 180 messages saying the same thing. from __future__ import annotations import asyncio +import datetime as _dt import json +import os import time from typing import Optional from urllib.parse import urlparse @@ -25,6 +27,16 @@ from urllib.parse import urlparse PAID_LABELS = {"HD", "fallback"} # download attempts billed per GB (main.plan_download_attempts) ALERT_COOLDOWN_SECONDS = 300 +# Hard ceiling on paid-proxy traffic per UTC day. Above it the paid proxy is +# taken out of every chain until midnight: jobs that need it fail with a clear +# message instead of bleeding money. 28-aug-2026 was $14 in one day because +# nothing capped the fallback while the static IPs were being refused by +# YouTube for hours. 0 disables the cap. +DAILY_BUDGET_MB = float(os.environ.get("PAID_PROXY_DAILY_MB", "500")) + +_budget_cache = {"at": 0.0, "bytes": -1} +_budget_alerted = {"day": None} + _pending = {"count": 0, "bytes": 0, "lines": [], "last_sent": 0.0} _lock = asyncio.Lock() @@ -128,6 +140,64 @@ async def flush_alerts(): pass +async def paid_bytes_today() -> int: + """Paid bytes recorded since UTC midnight (60 s cache; -1 -> unknown).""" + now = time.time() + if now - _budget_cache["at"] < 60 and _budget_cache["bytes"] >= 0: + return _budget_cache["bytes"] + try: + from sqlalchemy import func, select + from . import database as _db + from .models import ProxyUsage + day_start = _dt.datetime.now(_dt.timezone.utc).replace(hour=0, minute=0, + second=0, microsecond=0) + async with _db.session() as sess: + total = (await sess.execute( + select(func.coalesce(func.sum(ProxyUsage.paid_bytes), 0)) + .where(ProxyUsage.created_at >= day_start))).scalar_one() + _budget_cache.update(at=now, bytes=int(total or 0)) + return _budget_cache["bytes"] + except Exception as e: + print(f"⚠️ paid_bytes_today failed ({e}); treating budget as not exceeded") + return 0 + + +async def budget_exceeded() -> bool: + """True when today's paid traffic is over PAID_PROXY_DAILY_MB. + + Fails open (False) when the DB is unreachable: refusing every YouTube job + because the accounting query broke would be the worse failure. Alerts + once per UTC day when the cap trips. + """ + if DAILY_BUDGET_MB <= 0: + return False + used = await paid_bytes_today() + if used < DAILY_BUDGET_MB * 1e6: + return False + day = _dt.datetime.now(_dt.timezone.utc).strftime("%Y-%m-%d") + if _budget_alerted["day"] != day: + _budget_alerted["day"] = day + try: + from . import alerts + await alerts.send_telegram( + f"⛔ Paid proxy daily budget hit: {used / 1e6:.0f} MB of " + f"{DAILY_BUDGET_MB:.0f} MB used today. DataImpulse is disabled " + "until UTC midnight; jobs that need it will fail with a clear error. " + "Raise PAID_PROXY_DAILY_MB if this is expected.") + except Exception: + pass + return True + + +def budget_exceeded_sync() -> bool: + """Non-blocking view for sync callers (the resume scan): last cached + value only, unknown counts as not exceeded.""" + if DAILY_BUDGET_MB <= 0: + return False + cached = _budget_cache["bytes"] + return cached >= 0 and cached >= DAILY_BUDGET_MB * 1e6 + + async def record_download(job_id: str, route: Optional[dict], source_url: Optional[str] = None): """Persist a download's route; alert when the paid proxy was involved.""" if not route: diff --git a/tests/test_proxy_ledger.py b/tests/test_proxy_ledger.py index ea2d2be..e1dca6f 100644 --- a/tests/test_proxy_ledger.py +++ b/tests/test_proxy_ledger.py @@ -186,3 +186,103 @@ def test_job_source_url_skips_the_interpreter_flag(): job = {"cmd": ["/usr/bin/python3", "-u", "main.py", "-u", "https://www.youtube.com/watch?v=x", "-o", "out"]} assert app._job_source_url(job) == "https://www.youtube.com/watch?v=x" assert app._job_source_url({"cmd": ["/usr/bin/python3", "-u", "main.py", "-i", "file.mp4"]}) is None + + +# --- daily budget ---------------------------------------------------------- + +class TestDailyBudget: + def _prime(self, monkeypatch, used_mb, budget_mb=500): + async def fake_today(): + return int(used_mb * 1e6) + monkeypatch.setattr(proxy_ledger, "paid_bytes_today", fake_today) + monkeypatch.setattr(proxy_ledger, "DAILY_BUDGET_MB", budget_mb) + proxy_ledger._budget_alerted["day"] = None + + def test_under_budget_allows_paid(self, monkeypatch): + self._prime(monkeypatch, used_mb=100) + assert asyncio.run(proxy_ledger.budget_exceeded()) is False + + def test_over_budget_blocks_and_alerts_once_per_day(self, monkeypatch): + self._prime(monkeypatch, used_mb=600) + sent = [] + + async def fake_send(text): + sent.append(text) + import cloud.alerts as alerts + monkeypatch.setattr(alerts, "send_telegram", fake_send) + assert asyncio.run(proxy_ledger.budget_exceeded()) is True + assert asyncio.run(proxy_ledger.budget_exceeded()) is True + assert len(sent) == 1 and "budget" in sent[0].lower() + + def test_zero_disables_the_cap(self, monkeypatch): + self._prime(monkeypatch, used_mb=99999, budget_mb=0) + assert asyncio.run(proxy_ledger.budget_exceeded()) is False + + +def test_probe_allow_paid_false_never_uses_the_paid_proxy(monkeypatch): + monkeypatch.setenv("PROXY_URL", "http://paid") + monkeypatch.setenv("STATIC_PROXY_URLS", "http://s1") + monkeypatch.delenv("DIRECT_FIRST", raising=False) + monkeypatch.setenv("BGUTIL_SCRIPT_PATH", "") + monkeypatch.setenv("BGUTIL_BASE_URL", "") + seen = [] + + class _FakeYDL: + def __init__(self, opts): seen.append(opts.get("proxy")) + def __enter__(self): return self + def __exit__(self, *a): return False + def extract_info(self, url, download=False): + raise RuntimeError("Sign in to confirm you're not a bot") + + monkeypatch.setattr(yt_dlp, "YoutubeDL", _FakeYDL) + monkeypatch.setattr(metering, "_ffprobe_url_seconds", lambda url, timeout=30: 0.0) + with pytest.raises(ValueError): + metering.probe_url_minutes("https://www.youtube.com/watch?v=x", allow_paid=False) + assert "http://paid" not in seen + + +# --- the watcher's static probe -------------------------------------------- + +class TestStaticProbeAgainstYouTube: + """google.com answered 204 through statics YouTube was refusing (28-aug): + the static probe now has to see a playable watch page.""" + + def _client(self, monkeypatch, status=200, body="", raise_exc=None): + import cloud.alerts as alerts + calls = {} + + class _Resp: + status_code = status + text = body + + class _Client: + def __init__(self, **kw): calls["proxy"] = kw.get("proxy") + async def __aenter__(self): return self + async def __aexit__(self, *a): return False + async def get(self, url, **kw): + calls["url"] = url + if raise_exc: + raise raise_exc + return _Resp() + + import httpx + monkeypatch.setattr(httpx, "AsyncClient", _Client) + return alerts, calls + + def test_static_needs_the_playable_markers(self, monkeypatch): + monkeypatch.setenv("PROXY_URL", "http://paid") + alerts, calls = self._client(monkeypatch, body='{"playabilityStatus":{"status":"OK"}}') + ok, _ = asyncio.run(alerts._probe_one("http://static1")) + assert ok and "youtube.com/watch" in calls["url"] + + def test_static_answering_without_player_is_a_miss(self, monkeypatch): + monkeypatch.setenv("PROXY_URL", "http://paid") + alerts, _ = self._client(monkeypatch, body="consent page") + ok, detail = asyncio.run(alerts._probe_one("http://static1")) + assert not ok and "flagged" in detail + + def test_paid_probe_keeps_the_cheap_http_204(self, monkeypatch): + monkeypatch.setenv("PROXY_URL", "http://paid") + alerts, calls = self._client(monkeypatch, status=204, body="") + ok, _ = asyncio.run(alerts._probe_one("http://paid")) + assert ok and calls["url"].startswith("http://www.google.com")