fix(metering): size direct video URLs with ffprobe when yt-dlp reports no duration

Cloud metering probed the source with yt-dlp only; its generic extractor
never returns a duration for a plain mp4 URL, so every direct-file job
(agent uploads on tmpfiles/uguu, a CDN link) died at submit with 'Could
not determine the video duration'. On a generic hit the probe now stops
walking proxies and reads the container header over HTTP with ffprobe
(range requests, browser UA, 30 s timeout); tmpfiles links are refreshed
first. Reported by a user driving the MCP from claude.ai.
This commit is contained in:
juancarlos.cavero 2026-08-27 17:10:13 +02:00
parent f4c227e624
commit 15195f591a
2 changed files with 65 additions and 0 deletions

View file

@ -98,6 +98,10 @@ def probe_url_minutes(url: str) -> float:
# SSRF guard: reject non-http(s) / private / metadata hosts before probing. # SSRF guard: reject non-http(s) / private / metadata hosts before probing.
from security_utils import assert_public_url from security_utils import assert_public_url
assert_public_url(url) assert_public_url(url)
# Throwaway hosts (tmpfiles.org) sign links with a short-lived stamp; take
# the live one so the probe sees the file and not an HTML page.
import file_hosts
url = file_hosts.resolve(url)
bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip() bgutil_http = os.environ.get("BGUTIL_BASE_URL", "").strip()
bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip() bgutil_script = os.environ.get("BGUTIL_SCRIPT_PATH", "").strip()
@ -151,11 +155,39 @@ def probe_url_minutes(url: str) -> float:
if duration: if duration:
return float(duration) / 60.0 return float(duration) / 60.0
last_err = ValueError("no duration in metadata") last_err = ValueError("no duration in metadata")
if info.get("extractor") == "generic":
# A direct media file: yt-dlp's generic extractor never
# reports a duration, so stop trying proxies and read the
# container header over HTTP instead.
break
except Exception as e: except Exception as e:
last_err = e last_err = e
else:
continue
break
# 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.
try:
seconds = _ffprobe_url_seconds(url)
if seconds > 0:
return seconds / 60.0
except Exception as e:
last_err = e
raise ValueError(f"Could not determine video duration ({last_err})") raise ValueError(f"Could not determine video duration ({last_err})")
def _ffprobe_url_seconds(url: str, timeout: int = 30) -> float:
out = subprocess.check_output(
["ffprobe", "-v", "error", "-rw_timeout", str(timeout * 1_000_000),
"-user_agent", "Mozilla/5.0 (OpenShorts probe)",
"-show_entries", "format=duration",
"-of", "default=noprint_wrappers=1:nokey=1", url],
stderr=subprocess.STDOUT, timeout=timeout + 5,
)
return float(out.decode().strip() or 0)
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #
# Balance computation (assumes caller holds the user lock when mutating) # Balance computation (assumes caller holds the user lock when mutating)
# --------------------------------------------------------------------------- # # --------------------------------------------------------------------------- #

View file

@ -33,3 +33,36 @@ class TestOrdering:
def test_no_statics_matches_legacy_paid_only_behavior(self): def test_no_statics_matches_legacy_paid_only_behavior(self):
assert plan(False, [], PAID) == [PAID] assert plan(False, [], PAID) == [PAID]
class TestDirectFileProbe:
"""yt-dlp's generic extractor reports no duration for a plain mp4 URL; the
probe must fall back to ffprobe over HTTP instead of 400-ing the job."""
def test_generic_extractor_falls_back_to_ffprobe(self, monkeypatch):
import types, sys, security_utils
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
class _YDL:
def __init__(self, opts): pass
def __enter__(self): return self
def __exit__(self, *a): return False
def extract_info(self, url, download=False):
return {"extractor": "generic", "duration": None}
monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL))
monkeypatch.setattr(metering, "_ffprobe_url_seconds", lambda url, timeout=30: 559.4)
assert abs(metering.probe_url_minutes("https://cdn.example.com/v.mp4") - 559.4 / 60) < 1e-6
def test_both_fail_raises(self, monkeypatch):
import types, sys, security_utils
monkeypatch.setattr(security_utils, "assert_public_url", lambda u: u)
class _YDL:
def __init__(self, opts): pass
def __enter__(self): return self
def __exit__(self, *a): return False
def extract_info(self, url, download=False):
raise RuntimeError("Unsupported URL")
monkeypatch.setitem(sys.modules, "yt_dlp", types.SimpleNamespace(YoutubeDL=_YDL))
def boom(url, timeout=30): raise RuntimeError("no moov")
monkeypatch.setattr(metering, "_ffprobe_url_seconds", boom)
with pytest.raises(ValueError):
metering.probe_url_minutes("https://cdn.example.com/v.mp4")