| 1 | """Direct transcript fallback must finish within the YouTube lane budget.""" |
| 2 | |
| 3 | import contextlib |
| 4 | import io |
| 5 | import json |
| 6 | import threading |
| 7 | import time |
| 8 | import urllib.request |
| 9 | from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer |
| 10 | from urllib.parse import urlsplit |
| 11 | |
| 12 | import pytest |
| 13 | |
| 14 | from lib import bounded_get, subproc, youtube_yt |
| 15 | |
| 16 | |
| 17 | _VTT = "WEBVTT\n\n00:00:00.000 --> 00:00:02.000\nThe comparison has useful details.\n" |
| 18 | |
| 19 | |
| 20 | def _watch_page(captions=True): |
| 21 | tracks = [{"languageCode": "en", "baseUrl": "https://www.youtube.com/captions"}] if captions else [] |
| 22 | player = {"captions": {"playerCaptionsTracklistRenderer": {"captionTracks": tracks}}} |
| 23 | return f"<script>var ytInitialPlayerResponse = {json.dumps(player)};</script>" |
| 24 | |
| 25 | |
| 26 | def test_expired_ssh_transcript_fallback_starts_no_http(monkeypatch, tmp_path): |
| 27 | requests = [] |
| 28 | launches = [] |
| 29 | |
| 30 | def urlopen(req, **kwargs): |
| 31 | requests.append(req.full_url) |
| 32 | return io.BytesIO(_watch_page(captions=False).encode()) |
| 33 | |
| 34 | def launch(*args, **kwargs): |
| 35 | launches.append(args) |
| 36 | return subproc.SubprocResult(returncode=1, stdout="", stderr="") |
| 37 | |
| 38 | monkeypatch.setenv("LAST30DAYS_YOUTUBE_SSH_HOST", "test-transcript-host") |
| 39 | monkeypatch.setattr(urllib.request, "urlopen", urlopen) |
| 40 | monkeypatch.setattr(subproc, "run_with_timeout", launch) |
| 41 | deadline = time.monotonic() + youtube_yt._LANE_RETURN_MARGIN_SECONDS - 1 |
| 42 | |
| 43 | with youtube_yt.sc_spend_until(lambda: False, deadline=deadline): |
| 44 | result = youtube_yt.fetch_transcript("expired", str(tmp_path), {}) |
| 45 | |
| 46 | assert result is None |
| 47 | assert launches == [], "an expired lane launched an SSH subprocess" |
| 48 | assert requests == [], "the expired SSH attempt started direct HTTP fallback" |
| 49 | |
| 50 | |
| 51 | @pytest.mark.parametrize("lane_bound", [False, True]) |
| 52 | @pytest.mark.parametrize("captions", [False, True]) |
| 53 | def test_direct_transcript_preserves_results_and_bounds_both_requests(monkeypatch, lane_bound, captions): |
| 54 | plain_requests = [] |
| 55 | bounded_requests = [] |
| 56 | cancel = threading.Event() |
| 57 | deadline = time.monotonic() + 30 |
| 58 | cutoff = deadline - youtube_yt._LANE_RETURN_MARGIN_SECONDS |
| 59 | |
| 60 | def body(req): |
| 61 | return (_watch_page(captions) if urlsplit(req.full_url).path == "/watch" else _VTT).encode() |
| 62 | |
| 63 | def urlopen(req, **kwargs): |
| 64 | plain_requests.append(req.full_url) |
| 65 | return io.BytesIO(body(req)) |
| 66 | |
| 67 | def bounded(req, **kwargs): |
| 68 | bounded_requests.append((req.full_url, kwargs)) |
| 69 | return 200, body(req), None |
| 70 | |
| 71 | monkeypatch.setattr(urllib.request, "urlopen", urlopen) |
| 72 | monkeypatch.setattr(bounded_get, "get", bounded) |
| 73 | context = ( |
| 74 | youtube_yt.sc_spend_until(lambda: False, cancel=cancel, deadline=deadline) |
| 75 | if lane_bound else contextlib.nullcontext() |
| 76 | ) |
| 77 | status = {} |
| 78 | with context: |
| 79 | result = youtube_yt._fetch_transcript_direct("direct", status=status) |
| 80 | |
| 81 | assert result == (_VTT if captions else None) |
| 82 | assert status == ({} if captions else {"no_caption_tracks": True}) |
| 83 | expected_paths = ["/watch", "/captions"] if captions else ["/watch"] |
| 84 | if lane_bound: |
| 85 | assert [urlsplit(url).path for url, _ in bounded_requests] == expected_paths |
| 86 | assert plain_requests == [], "lane-bound transcript bypassed the bounded transport" |
| 87 | for _, bounds in bounded_requests: |
| 88 | assert bounds["deadline_monotonic"] == pytest.approx(cutoff, rel=0, abs=0.001) |
| 89 | assert bounds["cancel"] is cancel |
| 90 | assert bounds["read_error_body"] is False |
| 91 | else: |
| 92 | assert [urlsplit(url).path for url in plain_requests] == expected_paths |
| 93 | assert bounded_requests == [] |
| 94 | |
| 95 | |
| 96 | @pytest.mark.parametrize("held_path", ["/watch", "/captions"]) |
| 97 | def test_direct_transcript_reaps_held_body_before_lane_cutoff(monkeypatch, held_path): |
| 98 | started = threading.Event() |
| 99 | release = threading.Event() |
| 100 | returned = threading.Event() |
| 101 | result = {} |
| 102 | children = [] |
| 103 | original_popen = subproc.subprocess.Popen |
| 104 | original_urlopen = urllib.request.urlopen |
| 105 | original_bounded = bounded_get.get |
| 106 | |
| 107 | class Handler(BaseHTTPRequestHandler): |
| 108 | def log_message(self, *args): |
| 109 | pass |
| 110 | |
| 111 | def do_GET(self): |
| 112 | path = urlsplit(self.path).path |
| 113 | body = (_watch_page() if path == "/watch" else _VTT).encode() |
| 114 | self.send_response(200) |
| 115 | self.send_header("Content-Length", str(len(body))) |
| 116 | self.end_headers() |
| 117 | if path == held_path: |
| 118 | started.set() |
| 119 | release.wait(10) |
| 120 | try: |
| 121 | self.wfile.write(body) |
| 122 | except (BrokenPipeError, ConnectionResetError): |
| 123 | pass |
| 124 | |
| 125 | server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) |
| 126 | server_thread = threading.Thread(target=server.serve_forever) |
| 127 | server_thread.start() |
| 128 | |
| 129 | def local_request(req): |
| 130 | parsed = urlsplit(req.full_url) |
| 131 | url = f"http://127.0.0.1:{server.server_port}{parsed.path}" |
| 132 | if parsed.query: |
| 133 | url += f"?{parsed.query}" |
| 134 | return urllib.request.Request(url, headers=dict(req.header_items())) |
| 135 | |
| 136 | def urlopen(req, **kwargs): |
| 137 | return original_urlopen(local_request(req), **kwargs) |
| 138 | |
| 139 | def bounded(req, **kwargs): |
| 140 | return original_bounded(local_request(req), **kwargs) |
| 141 | |
| 142 | def popen(*args, **kwargs): |
| 143 | process = original_popen(*args, **kwargs) |
| 144 | children.append(process) |
| 145 | return process |
| 146 | |
| 147 | monkeypatch.setattr(urllib.request, "urlopen", urlopen) |
| 148 | monkeypatch.setattr(bounded_get, "get", bounded) |
| 149 | monkeypatch.setattr(subproc.subprocess, "Popen", popen) |
| 150 | monkeypatch.setattr(youtube_yt, "_LANE_RETURN_MARGIN_SECONDS", 1.0) |
| 151 | deadline = time.monotonic() + 3 |
| 152 | cutoff = deadline - 1 |
| 153 | |
| 154 | def fetch(): |
| 155 | try: |
| 156 | with youtube_yt.sc_spend_until(lambda: False, deadline=deadline): |
| 157 | result["transcript"] = youtube_yt._fetch_transcript_direct("held", timeout=10) |
| 158 | except BaseException as error: |
| 159 | result["error"] = error |
| 160 | finally: |
| 161 | returned.set() |
| 162 | |
| 163 | caller = threading.Thread(target=fetch) |
| 164 | caller.start() |
| 165 | try: |
| 166 | assert started.wait(1), "the real HTTP body read was not reached" |
| 167 | assert returned.wait(max(0, cutoff - time.monotonic()) + 0.3), "direct HTTP outlived the lane cutoff" |
| 168 | assert result == {"transcript": None} |
| 169 | assert children, "the deadline-bound request had no owned transport" |
| 170 | assert all(child.poll() is not None for child in children), "an HTTP worker survived the lane cutoff" |
| 171 | assert all(child.pid not in subproc._child_pids for child in children) |
| 172 | finally: |
| 173 | release.set() |
| 174 | caller.join(3) |
| 175 | server.shutdown() |
| 176 | server.server_close() |
| 177 | server_thread.join(3) |
| 178 | assert not caller.is_alive() |
| 179 | assert not server_thread.is_alive() |
| 180 |