From 4748e1bfa60c079bd50e1d48a9c0aef7b11111b4 Mon Sep 17 00:00:00 2001 From: "juancarlos.cavero" Date: Tue, 1 Sep 2026 14:54:20 +0200 Subject: [PATCH] fix(proxy): keep the per-GB proxy at zero and leave a durable trail when it is used DataImpulse showed ~0.2 $/day with the static pool healthy, and $14 on 28-aug that nothing on the server could explain: the monthly counter is in-memory and the container log rotates within the hour. The panel's per-host rows for 31-aug/1-sep pointed at two leaks. The duration probe (cloud/metering.probe_url_minutes) walked every URL that failed on the statics through the paid proxy with both extractors, ~1.7 MB a time: private, removed and members-only videos, live streams with no duration, and every non-YouTube URL (Twitch, Kick, Rumble, product pages, drive links) that the download plan itself never sends there. It now reaches the paid proxy only for a failure another IP can fix (bot-check, 403/429, proxy or network errors) and never for a non-YouTube URL. main.py prints PROXY_ROUTE= after every download: the winning attempt, paid bytes summed over every attempt that used the per-GB proxy (failed ones included; a paid attempt that died after three fragments was billed for them), and each free attempt's error text. app.py persists it as a proxy_usage row at job end and pages Telegram whenever the paid proxy carried bytes, folding a burst into one message per 5 min; a probe that reached the paid proxy is recorded the same way. Claude-Session: https://claude.ai/code/session_014i9z6mLTy978uRCfSsMfBq --- CLAUDE.md | 20 +++++ app.py | 40 ++++++++- cloud/alerts.py | 7 ++ cloud/metering.py | 89 ++++++++++++++++++- cloud/models.py | 23 +++++ cloud/proxy_ledger.py | 163 +++++++++++++++++++++++++++++++++ main.py | 36 ++++++-- tests/test_proxy_ledger.py | 178 +++++++++++++++++++++++++++++++++++++ 8 files changed, 548 insertions(+), 8 deletions(-) create mode 100644 cloud/proxy_ledger.py create mode 100644 tests/test_proxy_ledger.py diff --git a/CLAUDE.md b/CLAUDE.md index 94d6d1a..c3e73ee 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -332,6 +332,26 @@ Stripe retry the same doomed event for three days. ### Concurrency Model Async job queue with semaphore-based concurrency control. Configure via `MAX_CONCURRENT_JOBS` env var (default: 5). Jobs auto-cleanup after 1 hour. +### Paid proxy accounting (`cloud/proxy_ledger.py`) + +Downloads go direct → static ISP proxies (flat rate) → DataImpulse (per GB), +and the duration probe (`cloud/metering.probe_url_minutes`) follows the same +order. Two rules keep the per-GB proxy at zero on a normal day: the probe +reaches it **only** when a static route failed for a reason another IP can +fix (`static_failure_warrants_paid`: bot-check, 403/429, proxy/network +errors), never for a private/removed/members-only video or a live stream +with no duration (those failed the same on every IP and used to cost ~1.7 MB +× 2 extractors each), and **never for a non-YouTube URL** (the download +plan already excluded those; Twitch, Kick, Rumble and product pages were +reaching it through the probe). `main.py` prints `PROXY_ROUTE=` after +every download (winner, paid bytes across all attempts including failed +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 +`PROXY_URL` in `.env`: every local `main.py` run then bills DataImpulse. + ### Deploys and running jobs (handover + drain) Every push to `main` redeploys the API container. Coolify starts the NEW diff --git a/app.py b/app.py index 9bc5b7b..376be87 100644 --- a/app.py +++ b/app.py @@ -307,6 +307,14 @@ async def reserve_process_minutes(request, url, input_path, job_id): except Exception: raise HTTPException(status_code=400, detail="Could not determine the video duration. Try a different source.") + finally: + # A probe that had to reach the paid proxy leaves an event behind; + # record it (DB row + Telegram) whether or not the probe succeeded. + try: + from cloud import proxy_ledger as _pl + await _pl.drain_probe_events() + except Exception: + pass minutes = max(1, math.ceil(minutes)) try: @@ -1133,8 +1141,27 @@ _proxy_month = {"month": None, "bytes": 0, "alerted": False} PROXY_ALERT_GB = 100 +def _job_source_url(job) -> Optional[str]: + """The ``-u`` argument of the job's main.py command, if it was a URL job.""" + cmd = list((job or {}).get('cmd') or []) + for flag in ('-u', '--url'): + if flag in cmd: + i = cmd.index(flag) + return cmd[i + 1] if i + 1 < len(cmd) else None + return None + + async def _track_proxy_usage(job_id): - nbytes = (jobs.get(job_id) or {}).get('proxy_bytes') or 0 + job = jobs.get(job_id) or {} + # Durable trail + Telegram page whenever the per-GB proxy carried bytes + # (cloud mode only: self-host has no DB and pays nobody per GB). + if BILLING_ENABLED and job.get('proxy_route'): + try: + from cloud import proxy_ledger as _pl + await _pl.record_download(job_id, job.get('proxy_route'), _job_source_url(job)) + except Exception as e: + print(f"⚠️ proxy ledger failed for {job_id}: {e}") + nbytes = job.get('proxy_bytes') or 0 if not nbytes: return month = datetime.now(timezone.utc).strftime("%Y-%m") @@ -1726,6 +1753,17 @@ def enqueue_output(out, job_id): except ValueError: pass continue + if decoded_line.startswith("PROXY_ROUTE="): + # Which download attempt won and why the free ones failed; + # persisted at job end (cloud/proxy_ledger). Not shown to clients. + try: + from cloud import proxy_ledger as _pl + route = _pl.parse_route_line(decoded_line) + if route is not None and job_id in jobs: + jobs[job_id]['proxy_route'] = route + except Exception: + pass + continue print(f"📝 [Job Output] {decoded_line}") if job_id in jobs: jobs[job_id]['logs'].append(decoded_line) diff --git a/cloud/alerts.py b/cloud/alerts.py index 293bcb5..e4635dd 100644 --- a/cloud/alerts.py +++ b/cloud/alerts.py @@ -273,6 +273,13 @@ async def _watch_update(name, ok, detail): async def proxy_watch_tick(): """One probe cycle over every configured route.""" + # Paid-proxy events held back by the ledger's cooldown go out with the + # next tick at the latest (cloud/proxy_ledger.flush_alerts). + try: + from . import proxy_ledger + await proxy_ledger.flush_alerts() + except Exception: + pass for name, urls in _watch_targets(): ok, detail = False, "no urls" for u in urls: diff --git a/cloud/metering.py b/cloud/metering.py index 9b09509..eddb7bc 100644 --- a/cloud/metering.py +++ b/cloud/metering.py @@ -20,6 +20,7 @@ import asyncio import json import math import os +from urllib.parse import urlparse import random import subprocess from datetime import datetime, timezone, timedelta @@ -64,6 +65,49 @@ def probe_file_minutes(path: str) -> float: return seconds / 60.0 +# Errors on a free (static) route that a different IP could fix. Only these +# justify spending the per-GB proxy on the same URL; a private, removed or +# members-only video fails the same on every IP, and a live stream has no +# duration anywhere. Before this list every one of those went to the paid +# proxy twice (both extractors), ~1.7 MB a time — the "1.76 MB, 2 requests" +# rows that filled the DataImpulse panel on 31-aug-2026. +_IP_SPECIFIC_HINTS = ( + "sign in to confirm you", "not a bot", "http error 403", "http error 429", + "http error 407", "http error 502", "http error 503", "proxyerror", + "tunnel connection failed", "connection reset", "timed out", "timeout", + "unable to download webpage", "unable to download api page", + "available in your country", "in your country", "geo-restricted", "geoblock", + "blocked it in your country", + "remote end closed", "connection refused", "network is unreachable", + "name or service not known", "eof occurred", +) +_CONTENT_HINTS = ( + "private video", "video unavailable", "has been removed", "members-only", + "join this channel", "not available on this app", "is not a valid url", + "unsupported url", "no video formats found", "premieres in", "will begin in", + "this live event", "no duration in metadata", "requested format is not available", + "account has been terminated", "video is age", "confirm your age", +) + + +def static_failure_warrants_paid(err) -> bool: + """Does this failure on a free route justify retrying through the paid proxy?""" + e = str(err or "").lower() + if any(h in e for h in _CONTENT_HINTS): + return False + return any(h in e for h in _IP_SPECIFIC_HINTS) + + +# Paid-probe events queued for app.py (thread-safe enough: appended from the +# executor thread that runs the probe, drained on the event loop). +_paid_probe_events: list = [] + + +def pop_paid_probe_events() -> list: + out, _paid_probe_events[:] = list(_paid_probe_events), [] + return out + + def plan_probe_proxies(direct_first, statics, paid): """Ordered proxies for a metadata probe — pure, unit-tested. @@ -87,6 +131,12 @@ def plan_probe_proxies(direct_first, statics, paid): return order +def is_youtube_url(url: str) -> bool: + host = (urlparse(url or "").hostname or "").lower() + return host in ("youtube.com", "www.youtube.com", "m.youtube.com", "youtu.be", + "music.youtube.com") or host.endswith(".youtube.com") + + def probe_url_minutes(url: str) -> float: """Return the video duration in minutes from yt-dlp metadata (no download). @@ -123,11 +173,18 @@ def probe_url_minutes(url: str) -> float: if statics: k = random.randrange(len(statics)) statics = statics[k:] + statics[:k] + paid = os.environ.get("PROXY_URL", "").strip() + # 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. + if not is_youtube_url(url): + paid = "" proxies = plan_probe_proxies( os.environ.get("DIRECT_FIRST", "").strip() == "1", statics, - os.environ.get("PROXY_URL", "").strip(), + paid, ) + static_errors: dict = {} # A dead route in the chain is routine (the proxy watcher is what reports # it, on Telegram); yt-dlp printing a full ERROR block per failed proxy per @@ -143,6 +200,14 @@ def probe_url_minutes(url: str) -> float: # free route has failed on both extractors. last_err = None for proxy in proxies: + is_paid = bool(paid) and proxy == paid + if is_paid: + # Only spend the per-GB proxy when a free route failed for a + # reason another IP can fix. Content errors and "no duration" + # (live streams) are the same on every IP. + if not static_errors or not any(static_failure_warrants_paid(e) + for e in static_errors.values()): + break for extractor_args in strategies: opts = {"skip_download": True, "quiet": True, "no_warnings": True, "logger": _QuietLogger(), "extractor_args": extractor_args} @@ -153,6 +218,10 @@ def probe_url_minutes(url: str) -> float: info = ydl.extract_info(url, download=False) duration = info.get("duration") if duration: + if is_paid: + _paid_probe_events.append({ + "url": url, "static_errors": dict(static_errors), + "bytes_estimate": 1_800_000 * (1 + list(strategies).index(extractor_args))}) return float(duration) / 60.0 last_err = ValueError("no duration in metadata") if info.get("extractor") == "generic": @@ -163,8 +232,16 @@ def probe_url_minutes(url: str) -> float: except Exception as e: last_err = e else: + if not is_paid: + static_errors[_route_name(proxy, proxies)] = str(last_err)[:300] continue break + if paid and any(p == paid for p in proxies) and static_errors and \ + any(static_failure_warrants_paid(e) for e in static_errors.values()) and last_err is not None \ + and not isinstance(last_err, ValueError): + # The paid route was tried and failed too: still worth a trail line. + _paid_probe_events.append({"url": url, "static_errors": dict(static_errors), + "bytes_estimate": 3_600_000, "paid_failed": str(last_err)[:200]}) # Direct file URLs (agent uploads on tmpfiles/uguu/R2, a CDN mp4): ffprobe # fetches just the moov atom via range requests. Also the last resort for # any URL yt-dlp could not size. @@ -177,6 +254,16 @@ def probe_url_minutes(url: str) -> float: raise ValueError(f"Could not determine video duration ({last_err})") +def _route_name(proxy, proxies) -> str: + if proxy is None: + return "direct" + statics = [p for p in proxies if p is not None] + try: + return f"static{statics.index(proxy) + 1}" + except ValueError: + return "proxy" + + def _ffprobe_url_seconds(url: str, timeout: int = 30) -> float: out = subprocess.check_output( ["ffprobe", "-v", "error", "-rw_timeout", str(timeout * 1_000_000), diff --git a/cloud/models.py b/cloud/models.py index 6cd8c1d..0ce0821 100644 --- a/cloud/models.py +++ b/cloud/models.py @@ -286,3 +286,26 @@ class OAuthCode(Base): scope = Column(Text, nullable=True) expires_at = Column(DateTime(timezone=True), nullable=False) used_at = Column(DateTime(timezone=True), nullable=True) + + +class ProxyUsage(Base): + """One row per event that put bytes through the per-GB paid proxy, or per + download route decision worth keeping (the winner and why the free routes + failed). + + The monthly proxy counter in app.py is in-memory and the container log + rotates within the hour, so on 28-aug-2026 a $14 DataImpulse day could not + be reconstructed at all. This is the durable trail: which job, which route + won, how many paid bytes, and the failure text of every free attempt that + was tried first. Not user-owned data (no FK to users): it is operational + accounting and survives account erasure on purpose. + """ + __tablename__ = "proxy_usage" + id = Column(UUID(as_uuid=True), primary_key=True, default=_uuid) + created_at = Column(DateTime(timezone=True), server_default=func.now(), index=True) + source = Column(String(16), nullable=False) # download | probe + job_id = Column(String(64), nullable=True, index=True) + url_host = Column(String(120), nullable=True) + route = Column(String(32), nullable=True) # winning attempt label, or "none" + paid_bytes = Column(Integer, nullable=False, default=0) + detail = Column(JSONB, nullable=True) # attempts: [{label, ok, bytes, error}] diff --git a/cloud/proxy_ledger.py b/cloud/proxy_ledger.py new file mode 100644 index 0000000..854f55b --- /dev/null +++ b/cloud/proxy_ledger.py @@ -0,0 +1,163 @@ +"""Durable trail + Telegram alert for every byte sent through the paid proxy. + +Two producers: +- ``main.py`` prints ``PROXY_ROUTE=`` after a download (winner label, + paid bytes summed over every attempt that used the per-GB proxy, and the + error text of each free attempt that failed first). ``app.py``'s log reader + parses it and calls :func:`record_download` when the job ends. +- ``cloud.metering.probe_url_minutes`` appends an event when the duration + probe had to reach the paid proxy; ``app.py`` drains those right after the + probe with :func:`drain_probe_events`. + +Both persist a ``proxy_usage`` row (best effort) and page the admin. The +alert has a short cooldown that folds a burst into one message: on a day like +28-aug-2026, when every job fell to the paid proxy, one Telegram line per +job would have been 180 messages saying the same thing. +""" +from __future__ import annotations + +import asyncio +import json +import time +from typing import Optional +from urllib.parse import urlparse + +PAID_LABELS = {"HD", "fallback"} # download attempts billed per GB (main.plan_download_attempts) +ALERT_COOLDOWN_SECONDS = 300 + +_pending = {"count": 0, "bytes": 0, "lines": [], "last_sent": 0.0} +_lock = asyncio.Lock() + + +def host_of(url: Optional[str]) -> Optional[str]: + try: + return urlparse(url or "").hostname or None + except Exception: + return None + + +def parse_route_line(line: str) -> Optional[dict]: + """``PROXY_ROUTE={...}`` -> dict, or None for anything malformed.""" + if not line.startswith("PROXY_ROUTE="): + return None + try: + data = json.loads(line.split("=", 1)[1]) + except ValueError: + return None + return data if isinstance(data, dict) else None + + +def paid_bytes_of(route: Optional[dict]) -> int: + try: + return int((route or {}).get("paid_bytes") or 0) + except (TypeError, ValueError): + return 0 + + +def used_paid(route: Optional[dict]) -> bool: + """True when the paid proxy carried bytes or won the download.""" + if not route: + return False + return paid_bytes_of(route) > 0 or str(route.get("winner") or "") in PAID_LABELS + + +def describe_failures(route: Optional[dict], limit: int = 3) -> str: + """The free attempts that failed before the paid one, one per line.""" + out = [] + for a in (route or {}).get("attempts") or []: + if a.get("ok") or a.get("label") in PAID_LABELS: + continue + err = str(a.get("error") or "").strip().replace("\n", " ") + if err: + out.append(f" {a.get('label')}: {err[:140]}") + if len(out) >= limit: + break + return "\n".join(out) + + +async def _persist(source: str, job_id: Optional[str], url_host: Optional[str], + route_label: Optional[str], paid_bytes: int, detail: Optional[dict]): + try: + from . import database as _db + from .models import ProxyUsage + async with _db.session() as s: + s.add(ProxyUsage(source=source, job_id=job_id, url_host=url_host, + route=route_label, paid_bytes=int(paid_bytes or 0), + detail=detail)) + await s.commit() + except Exception as e: # accounting must never break a job + print(f"⚠️ proxy_usage row not written: {e}") + + +async def _alert(line: str, nbytes: int): + """Page the admin, folding events inside the cooldown into one message.""" + try: + from . import alerts + except Exception: + return + async with _lock: + _pending["count"] += 1 + _pending["bytes"] += int(nbytes or 0) + if len(_pending["lines"]) < 5: + _pending["lines"].append(line) + now = time.time() + if now - _pending["last_sent"] < ALERT_COOLDOWN_SECONDS: + return + count, total = _pending["count"], _pending["bytes"] + lines = list(_pending["lines"]) + _pending.update(count=0, bytes=0, lines=[], last_sent=now) + head = ("💸 Paid proxy (DataImpulse) used" + + (f": {count} events, {total / 1e6:.1f} MB in the last {ALERT_COOLDOWN_SECONDS // 60} min" + if count > 1 else "")) + await alerts.send_telegram(head + "\n" + "\n".join(lines)) + + +async def flush_alerts(): + """Send whatever the cooldown is still holding (called by a periodic tick).""" + async with _lock: + if not _pending["count"] or time.time() - _pending["last_sent"] < ALERT_COOLDOWN_SECONDS: + return + count, total = _pending["count"], _pending["bytes"] + lines = list(_pending["lines"]) + _pending.update(count=0, bytes=0, lines=[], last_sent=time.time()) + try: + from . import alerts + await alerts.send_telegram( + f"💸 Paid proxy (DataImpulse) used: {count} events, {total / 1e6:.1f} MB\n" + "\n".join(lines)) + except Exception: + pass + + +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: + return + nbytes = paid_bytes_of(route) + paid = used_paid(route) + await _persist("download", job_id, host_of(source_url), str(route.get("winner") or "none"), + nbytes if paid else 0, route) + if paid: + why = describe_failures(route) + await _alert(f"download job {job_id[:8]}: {nbytes / 1e6:.1f} MB via '{route.get('winner')}'" + + (f"\n{why}" if why else ""), nbytes) + + +async def record_probe(event: dict): + """A duration probe that reached the paid proxy (see cloud.metering).""" + url_host = host_of(event.get("url")) + await _persist("probe", event.get("job_id"), url_host, "paid-probe", + int(event.get("bytes_estimate") or 0), event) + fails = "\n".join(f" {k}: {str(v)[:140]}" for k, v in (event.get("static_errors") or {}).items()) + await _alert(f"probe {url_host or '?'}: statics failed, paid proxy answered" + + (f"\n{fails}" if fails else ""), int(event.get("bytes_estimate") or 0)) + + +async def drain_probe_events(): + """Record every paid probe the metering module queued since the last call.""" + try: + from . import metering + events = metering.pop_paid_probe_events() + except Exception: + return + for ev in events: + await record_probe(ev) diff --git a/main.py b/main.py index ad5dc7f..c4b8bd6 100644 --- a/main.py +++ b/main.py @@ -822,16 +822,22 @@ def download_youtube_video(url, output_dir="."): # Wire bytes actually pulled through the (paid) proxy, summed across # fragments/streams. Reported to app.py via the PROXY_BYTES= line below. - _dl_bytes = {"total": 0} + _dl_bytes = {"total": 0, "partial": 0} def _progress_hook(d): - if d.get('status') == 'finished': + if d.get('status') == 'downloading': + # Bytes of a fragment still in flight: a failed attempt has + # already paid for these even though 'finished' never fires. + _dl_bytes["partial"] = int(d.get('downloaded_bytes') or 0) + elif d.get('status') == 'finished': + _dl_bytes["partial"] = 0 _dl_bytes["total"] += int(d.get('total_bytes') or d.get('total_bytes_estimate') or d.get('downloaded_bytes') or 0) def _attempt(extractor_args, fmt, proxy): _dl_bytes["total"] = 0 + _dl_bytes["partial"] = 0 with yt_dlp.YoutubeDL(_base_opts(extractor_args, proxy)) as ydl: info = ydl.extract_info(url, download=False) sanitized = sanitize_filename(info.get('title', 'youtube_video')) @@ -869,6 +875,10 @@ def download_youtube_video(url, output_dir="."): sanitized_title = None last_err = None used_proxy = False + # Every attempt, with its bytes and failure text: printed as PROXY_ROUTE= + # below so app.py can keep a durable trail of WHY a job reached the paid + # proxy (the container log rotates within the hour; see cloud/proxy_ledger). + attempt_log = [] for label, ea, fmt, proxy in attempts: # A 403 on the media fetch is usually transient: the googlevideo URL is # bound to the IP that extracted it, and the residential proxy rotates @@ -882,10 +892,17 @@ def download_youtube_video(url, output_dir="."): # the flat-rate static proxies are free bandwidth for the # monthly counter's purposes. used_proxy = proxy is not None and proxy == _proxy + attempt_log.append({"label": label, "ok": True, + "bytes": _dl_bytes["total"] + _dl_bytes["partial"], + "paid": used_proxy}) print(f"✅ Download succeeded ({label}).") break except Exception as e: last_err = e + attempt_log.append({"label": label, "ok": False, + "bytes": _dl_bytes["total"] + _dl_bytes["partial"], + "paid": proxy is not None and proxy == _proxy, + "error": str(e)[:300]}) print(f"⚠️ Download attempt '{label}' failed: {str(e)[:200]}") retryable = '403' in str(e) or 'Forbidden' in str(e) if not retryable or retry == 1: @@ -917,12 +934,19 @@ Technical Details: {str(last_err)} downloaded_file = os.path.join(output_dir, f) break - if used_proxy and _dl_bytes["total"]: + # Paid bytes across EVERY attempt that used the per-GB proxy, failed ones + # included: a paid attempt that died after three 10 MB fragments was + # billed for them even though a later attempt won. + paid_bytes = sum(int(a.get("bytes") or 0) for a in attempt_log if a.get("paid")) + print("PROXY_ROUTE=" + json.dumps({ + "winner": attempt_log[-1]["label"] if attempt_log and attempt_log[-1].get("ok") else None, + "paid_bytes": paid_bytes, + "attempts": attempt_log, + }, ensure_ascii=False)) + if paid_bytes: # Machine-parseable marker consumed by app.py's log reader for the # monthly proxy-bandwidth counter. Not shown to clients (log filter). - # Only emitted when the winning attempt actually went through the - # proxy — direct-first successes are free bandwidth. - print(f"PROXY_BYTES={_dl_bytes['total']}") + print(f"PROXY_BYTES={paid_bytes}") print(f"✅ Video downloaded in {time.time() - step_start_time:.2f}s: {downloaded_file}") return downloaded_file, sanitized_title diff --git a/tests/test_proxy_ledger.py b/tests/test_proxy_ledger.py new file mode 100644 index 0000000..3ddf896 --- /dev/null +++ b/tests/test_proxy_ledger.py @@ -0,0 +1,178 @@ +"""Where the paid proxy bytes come from, and the trail that survives a deploy. + +DataImpulse showed ~0.2 $/day of traffic with the static pool healthy, and +$14 on 28-aug-2026 that nothing on the server could explain (in-memory +counter, hourly log rotation). These pin the two leaks found and the ledger. +""" +import asyncio +import json + +import pytest +import yt_dlp + +from cloud import metering, proxy_ledger + + +# --- probe policy ---------------------------------------------------------- + +class TestStaticFailureWarrantsPaid: + def test_ip_specific_failures_do(self): + for err in ("ERROR: Sign in to confirm you're not a bot", + "HTTP Error 403: Forbidden", "HTTP Error 429: Too Many Requests", + "ProxyError: Tunnel connection failed: 407", + "Unable to download webpage: The read operation timed out", + "The uploader has not made this video available in your country"): + assert metering.static_failure_warrants_paid(err), err + + def test_content_failures_do_not(self): + for err in ("ERROR: Private video. Sign in if you've been granted access", + "ERROR: Video unavailable", "This video has been removed by the uploader", + "Join this channel to get access to members-only content", + "no duration in metadata", "Premieres in 3 hours", + "Unsupported URL: https://shopee.vn/product", "Sign in to confirm your age"): + assert not metering.static_failure_warrants_paid(err), err + + def test_unknown_errors_stay_free(self): + assert not metering.static_failure_warrants_paid("something odd happened") + assert not metering.static_failure_warrants_paid("") + + +def test_non_youtube_urls_are_recognised(): + assert metering.is_youtube_url("https://www.youtube.com/watch?v=x") + assert metering.is_youtube_url("https://youtu.be/x") + assert metering.is_youtube_url("https://m.youtube.com/shorts/x") + for u in ("https://www.twitch.tv/videos/1", "https://kick.com/x", "https://rumble.com/v", + "https://drive.google.com/file/d/x", "https://www.openshorts.app/videos/x.mp4"): + assert not metering.is_youtube_url(u), u + + +def test_probe_never_reaches_paid_for_non_youtube(monkeypatch): + """Twitch/Kick/Rumble/product pages were all showing up on the paid proxy.""" + 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("HTTP Error 403: Forbidden") + + 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.twitch.tv/videos/123") + assert "http://paid" not in seen + assert metering.pop_paid_probe_events() == [] + + +def test_probe_reaches_paid_only_for_ip_specific_failures(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", "") + + def run(static_error): + seen = [] + + class _FakeYDL: + def __init__(self, opts): self.proxy = opts.get("proxy"); seen.append(self.proxy) + def __enter__(self): return self + def __exit__(self, *a): return False + def extract_info(self, url, download=False): + if self.proxy == "http://paid": + return {"duration": 600} + raise RuntimeError(static_error) + + monkeypatch.setattr(yt_dlp, "YoutubeDL", _FakeYDL) + monkeypatch.setattr(metering, "_ffprobe_url_seconds", lambda url, timeout=30: 0.0) + metering.pop_paid_probe_events() + try: + minutes = metering.probe_url_minutes("https://www.youtube.com/watch?v=abc") + except ValueError: + minutes = None + return minutes, seen, metering.pop_paid_probe_events() + + minutes, seen, events = run("Sign in to confirm you're not a bot") + assert minutes == 10.0 and "http://paid" in seen + assert len(events) == 1 and "static1" in events[0]["static_errors"] + + minutes, seen, events = run("ERROR: Private video") + assert minutes is None and "http://paid" not in seen and events == [] + + +# --- the trail ------------------------------------------------------------- + +def _route(winner, attempts): + return {"winner": winner, "paid_bytes": sum(a["bytes"] for a in attempts if a.get("paid")), + "attempts": attempts} + + +def test_route_line_round_trip(): + route = _route("fallback", [ + {"label": "HD-static1", "ok": False, "bytes": 0, "paid": False, "error": "HTTP Error 403"}, + {"label": "HD", "ok": False, "bytes": 31_000_000, "paid": True, "error": "read timed out"}, + {"label": "fallback", "ok": True, "bytes": 70_000_000, "paid": True}, + ]) + parsed = proxy_ledger.parse_route_line("PROXY_ROUTE=" + json.dumps(route)) + assert parsed == route + assert proxy_ledger.parse_route_line("PROXY_ROUTE=not json") is None + assert proxy_ledger.parse_route_line("other") is None + + +def test_paid_bytes_count_failed_paid_attempts_too(): + route = _route("fallback", [ + {"label": "HD", "ok": False, "bytes": 31_000_000, "paid": True, "error": "x"}, + {"label": "fallback", "ok": True, "bytes": 70_000_000, "paid": True}, + ]) + assert proxy_ledger.paid_bytes_of(route) == 101_000_000 + assert proxy_ledger.used_paid(route) + + +def test_free_download_is_not_paid(): + route = _route("HD-static1", [{"label": "HD-static1", "ok": True, "bytes": 90_000_000, "paid": False}]) + assert not proxy_ledger.used_paid(route) + assert proxy_ledger.describe_failures(route) == "" + + +def test_failure_summary_names_the_free_routes_that_failed(): + route = _route("HD", [ + {"label": "HD-static1", "ok": False, "bytes": 0, "paid": False, "error": "Sign in to confirm you're not a bot"}, + {"label": "HD-static2", "ok": False, "bytes": 0, "paid": False, "error": "HTTP Error 429"}, + {"label": "HD", "ok": True, "bytes": 50_000_000, "paid": True}, + ]) + text = proxy_ledger.describe_failures(route) + assert "HD-static1: Sign in" in text and "HD-static2: HTTP Error 429" in text + assert "HD:" not in text + + +def test_alert_folds_a_burst_into_one_message(monkeypatch): + sent = [] + + async def fake_send(text): + sent.append(text) + + import cloud.alerts as alerts + monkeypatch.setattr(alerts, "send_telegram", fake_send) + monkeypatch.setattr(proxy_ledger, "_persist", lambda *a, **k: asyncio.sleep(0)) + proxy_ledger._pending.update(count=0, bytes=0, lines=[], last_sent=0.0) + + async def go(): + for i in range(4): + await proxy_ledger.record_download(f"job{i}xxxx", _route("fallback", [ + {"label": "HD-static1", "ok": False, "bytes": 0, "paid": False, "error": "HTTP Error 403"}, + {"label": "fallback", "ok": True, "bytes": 10_000_000, "paid": True}]), + "https://www.youtube.com/watch?v=x") + asyncio.run(go()) + assert len(sent) == 1 # the other three wait for the cooldown + assert "DataImpulse" in sent[0] and "10.0 MB" in sent[0] and "HD-static1: HTTP Error 403" in sent[0] + assert proxy_ledger._pending["count"] == 3 + + +def test_host_of_strips_credentials_and_paths(): + assert proxy_ledger.host_of("https://user:pw@www.youtube.com/watch?v=1") == "www.youtube.com" + assert proxy_ledger.host_of(None) is None