fix(proxy): probe the duration over the static pool, not the per-GB proxy

The static ISP pool (dfa3124) moved downloads off the paid proxy but never
touched cloud/metering.py, so probe_url_minutes kept reading PROXY_URL alone.
Every managed YouTube submission still paid DataImpulse for 0.2-1 MB of yt-dlp
metadata (measured through a counting proxy) while the download itself went out
free over Decodo — and invisibly, because PROXY_BYTES only counts the bytes of
the winning download attempt.

The probe now walks the same cheapest-first chain as the download: direct when
DIRECT_FIRST=1, then the statics rotated per probe, then the paid proxy as the
last resort. Proxies are the outer loop and extractor strategies the inner one,
so the paid route is only reached after every free one has failed on both.
That also stops a drained paid proxy from taking YouTube ingest down on its own
("Could not determine the video duration") while the statics are healthy.

Two smaller cuts on the same path: a user with no minutes left now gets its 402
before the probe instead of after it, and a failed route no longer dumps a
yt-dlp ERROR block per proxy per strategy into the API log (the watcher is what
reports a dead route).
This commit is contained in:
juancarlos.cavero 2026-08-21 22:45:53 +02:00
parent 119a6da8be
commit 658defe614
3 changed files with 114 additions and 17 deletions

14
app.py
View file

@ -244,6 +244,20 @@ async def reserve_process_minutes(request, url, input_path, job_id):
raise HTTPException(status_code=429,
detail="You already have the maximum number of jobs running. Please wait.")
# Out of minutes -> 402 before probing. The probe is a real yt-dlp metadata
# fetch through the download proxies, and every job costs at least one
# minute, so a user at zero can be turned away without spending bandwidth on
# a duration we are about to reject anyway (4 of 12 submissions in the
# 21-aug-2026 sample were quota 402s that had already paid for their probe).
balance = await _metering.get_balance(user.id)
if balance["remaining"] < 1:
_maybe_send_quota_email(user)
raise HTTPException(status_code=402, detail={
"error": "quota_exceeded",
"minutes_required": 1,
"minutes_remaining": balance["remaining"],
})
# Probe rate limit: probing costs a (cheap) proxied metadata call. The
# 20-minute monthly quota is the real bound on free usage; there is no daily
# job cap.

View file

@ -20,6 +20,7 @@ import asyncio
import json
import math
import os
import random
import subprocess
from datetime import datetime, timezone, timedelta
from decimal import Decimal
@ -63,11 +64,34 @@ def probe_file_minutes(path: str) -> float:
return seconds / 60.0
def plan_probe_proxies(direct_first, statics, paid):
"""Ordered proxies for a metadata probe — pure, unit-tested.
Same cheapest-first order as the download plan (``main.plan_download_attempts``):
the server's own IP when the operator allows it, then the flat-rate static ISP
pool, then the per-GB paid proxy. ``None`` means "no proxy" (direct).
This probe used to read ``PROXY_URL`` only, which it kept doing after the
static pool landed (dfa3124, 19-aug-2026) because that commit never touched
this file. Every managed YouTube submission then paid the per-GB proxy for
~0.2-1 MB of metadata while the download itself went out free over the
statics — and invisibly, since ``PROXY_BYTES`` (main.py) only counts the
bytes of the winning *download* attempt.
"""
order = []
if direct_first or not (statics or paid):
order.append(None)
order.extend(statics)
if paid:
order.append(paid)
return order
def probe_url_minutes(url: str) -> float:
"""Return the video duration in minutes from yt-dlp metadata (no download).
Uses the same proxy + extractor settings as the actual download (main.py) so
the probe behaves consistently with it. Metadata only — negligible bandwidth.
Uses the same proxy order + extractor settings as the actual download
(main.py) so the probe behaves consistently with it and bills the same way.
Raises ValueError if the duration is unknown (e.g. live streams).
"""
import yt_dlp
@ -77,7 +101,6 @@ def probe_url_minutes(url: str) -> float:
bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
proxy = os.environ.get("PROXY_URL", "").strip()
conservative = {"youtube": {"player_client": ["tv_embed", "android", "mweb", "web"],
"player_skip": ["webpage", "configs"]}}
# Try the bgutil/HD extractor first (http or baked-in script), then the
@ -90,10 +113,35 @@ def probe_url_minutes(url: str) -> float:
hd = []
strategies = hd + [conservative]
# Rotated per probe to spread load across the pool, like the download does.
statics = [p.strip() for p in
os.environ.get("STATIC_PROXY_URLS", "").split(",") if p.strip()]
if statics:
k = random.randrange(len(statics))
statics = statics[k:] + statics[:k]
proxies = plan_probe_proxies(
os.environ.get("DIRECT_FIRST", "").strip() == "1",
statics,
os.environ.get("PROXY_URL", "").strip(),
)
# 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
# strategy would just flood the API log. The reason still reaches the caller
# through ``last_err`` below.
class _QuietLogger:
def debug(self, msg): pass
def info(self, msg): pass
def warning(self, msg): pass
def error(self, msg): pass
# Proxies outer, strategies inner: the paid proxy is only reached once every
# free route has failed on both extractors.
last_err = None
for proxy in proxies:
for extractor_args in strategies:
opts = {"skip_download": True, "quiet": True, "no_warnings": True,
"extractor_args": extractor_args}
"logger": _QuietLogger(), "extractor_args": extractor_args}
if proxy:
opts["proxy"] = proxy
try:

35
tests/test_probe_plan.py Normal file
View file

@ -0,0 +1,35 @@
"""Duration-probe proxy ordering: cheapest bandwidth first.
The probe runs on every managed YouTube submission. It read PROXY_URL only
until 21-aug-2026, so it kept paying the per-GB proxy for metadata long after
downloads had moved to the flat-rate static pool — invisibly, because the
PROXY_BYTES counter only sees download bytes.
"""
import pytest
metering = pytest.importorskip("cloud.metering")
plan = metering.plan_probe_proxies
STATICS = ["http://s1", "http://s2", "http://s3"]
PAID = "http://paid"
class TestOrdering:
def test_full_chain(self):
assert plan(True, STATICS, PAID) == [None] + STATICS + [PAID]
def test_paid_is_last_resort(self):
got = plan(False, STATICS, PAID)
assert got == STATICS + [PAID]
assert got.index(PAID) == len(got) - 1
def test_statics_only_never_reaches_a_paid_proxy(self):
assert plan(False, STATICS, "") == STATICS
def test_selfhost_no_proxies_probes_direct(self):
assert plan(False, [], "") == [None]
assert plan(True, [], "") == [None]
def test_no_statics_matches_legacy_paid_only_behavior(self):
assert plan(False, [], PAID) == [PAID]