Files
unshackle/tests/remote/unit/test_run_cancel.py
T

670 lines
23 KiB
Python

"""Ctrl+C in the download pool ends every wait of a track for the remote server, and a failed track ends none."""
from __future__ import annotations
import asyncio
import contextlib
import json
import signal
import socket
import subprocess
import time
from collections.abc import Callable, Iterator
from pathlib import Path
from threading import Event, Thread, Timer
from types import SimpleNamespace
from typing import Any, cast
from urllib.parse import urlsplit
import pytest
from aiohttp import web
from tests.remote.unit.test_process_exit import ( # noqa: F401
COMMAND,
DEADLINE,
HeldDelete,
held_delete,
lasting_sessions,
logins,
posix,
run,
saved,
sessions,
settings,
store_cache,
wait_line,
)
from tests.remote.unit.test_remote_loopback import StubService, count, forget, server # noqa: F401
from tests.remote.unit.test_tunnel import wait_until
from unshackle.core import remote_channel
from unshackle.core.api import routes, session_store
from unshackle.core.constants import RunCancel
from unshackle.core.proxies.controld import relay
from unshackle.core.remote_channel import ServerMessages
from unshackle.core.remote_protocol import (
LOGS_ROUTE,
PROMPT_ROUTE,
SESSION_CREATE_ROUTE,
SESSION_ROUTE,
TITLES_ROUTE,
TRACKS_ROUTE,
AuthStatus,
)
from unshackle.core.tracks import Audio, Tracks
pytestmark = [pytest.mark.unit, pytest.mark.process, posix]
BOUND = 8.0
WAITING = "Waiting for the remote server"
LIMITED = "Rate limited by the server"
CLIENT = """
import contextlib, logging, sys
from threading import Event
from types import SimpleNamespace
from uuid import UUID
import click
from unshackle.core import process_exit, remote_channel, remote_service
from unshackle.core.config import config
config.__init__(directories={"cache": sys.argv[2], "cookies": sys.argv[2] + "/cookies"})
logging.basicConfig(level=logging.INFO, stream=sys.stdout, format="%(message)s")
from tests.core.key_resolver import resolver
from tests.remote.unit.test_remote_loopback import make_client
from unshackle.commands.dl import download_tracks_in_passes
from unshackle.core.constants import DOWNLOAD_CANCELLED, RunCancel
from unshackle.core.tracks.track import Track
phase = sys.argv[3]
service = make_client(sys.argv[1])
keys = resolver()
if phase == "push":
remote_service.KEYS_TIMEOUT = 60
if "polling" in sys.argv[4:]:
remote_channel.WebSocketChannel.open = lambda self, timeout=0: False
def say(line):
print(line, flush=True)
def set_and_say(real=DOWNLOAD_CANCELLED.set):
real()
if RunCancel.pressed:
say("cancelled")
def hold(line):
say(line)
while not RunCancel.pressed:
Event().wait(0.01)
def drain_logs(real=service.drain_server_logs):
real()
if phase == "login-done" and service._tracks_by_title:
hold("login done")
service.drain_server_logs = drain_logs
def login_material(profile, real=service.client_login):
if phase == "login-material" and service._titles:
hold("login material")
return real(profile)
DOWNLOAD_CANCELLED.set = set_and_say
service.client_login = login_material
def titles(sid):
return service.client.get(f"/api/session/{sid}/titles")
def push():
track = SimpleNamespace(id="example-1-login1")
return keys.VAULT_WRITER.submit(service.server_vault.add_keys, "EXAMPLE", {UUID(int=1): "ab" * 16}, track)
calls = {
"url": service.track_url,
"licence": lambda track: service.license_track(
track, type("Widevine", (), {"pssh": SimpleNamespace(dumps=lambda: "AAAA")})()
),
"file": service.license_file,
"relay": lambda track: service.proxy_license(b"c", track, "widevine"),
"certificate": lambda track: service.get_widevine_service_certificate(challenge=b"c", title=None, track=track),
"filter": lambda track: service.remote_segment_filter(track.id)(None),
"samples": lambda track: service.get_sample_decrypter(track, 0),
}
def run_one(track, index):
if phase == "fails" and index == 1:
sys.stdin.readline()
DOWNLOAD_CANCELLED.set()
say("failed")
raise ValueError("EXAMPLE failed")
if phase == "push":
push()
if phase in calls:
service._server_cdm_request = phase == "file"
try:
calls[phase](track)
except Exception as e:
say(type(e).__name__)
raise
service.session_call(titles)
say("called")
def download(count):
tracks = [SimpleNamespace(id=str(n)) for n in range(count)]
download_tracks_in_passes(tracks, count, run_one, skip_subtitle_errors=False, on_subtitle_skipped=None)
@click.command()
@click.pass_context
def main(ctx):
ctx.with_resource(process_exit.unwinding(linger="job" not in sys.argv[4:]))
service.authenticate()
remote_channel.AUTH_POLL_INTERVAL = 600
say("ready")
sys.stdin.readline()
if phase == "main":
service.session_call(titles)
if phase in ("tracks", "login-material", "login-done"):
service.get_tracks(service.get_titles()[0])
say("tracks")
sys.stdin.readline()
try:
download(2 if phase in ("pool", "fails") else 1)
except ValueError:
say("title failed")
service.session_call(titles)
say("next title")
except KeyboardInterrupt:
say("Download Cancelled")
if phase == "lost-push":
push()
keys.wait_vault_writes()
say("vault writes done")
main(args=[])
"""
class Gate:
"""A port in front of the server. ``close`` takes it away as a dead server does, and lets no other process have it."""
def __init__(self, url: str) -> None:
self.server = (urlsplit(url).hostname, urlsplit(url).port)
self.port = 0
self.held = socket.socket()
self.open()
self.url = f"http://127.0.0.1:{self.port}"
def open(self) -> None:
self.links: list[socket.socket] = []
self.held.close()
self.listener = socket.create_server(("127.0.0.1", self.port), backlog=32)
self.port = self.listener.getsockname()[1]
Thread(target=self.accept, args=[self.listener], daemon=True).start()
def accept(self, listener: socket.socket) -> None:
with contextlib.suppress(OSError):
while True:
near = listener.accept()[0]
far = socket.create_connection(self.server)
self.links += [near, far]
for source, sink in ((near, far), (far, near)):
Thread(target=relay, args=[source, sink], daemon=True).start()
def close(self) -> None:
for end in (self.listener, *self.links):
with contextlib.suppress(OSError):
end.shutdown(socket.SHUT_RDWR)
end.close()
self.held.close()
self.held = socket.socket()
self.held.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.held.bind(("127.0.0.1", self.port))
@pytest.fixture
def gate(server: SimpleNamespace, logins: list[Any]) -> Iterator[Gate]: # noqa: F811
gate = Gate(server.url)
yield gate
gate.close()
gate.held.close()
def go(process: subprocess.Popen[str]) -> None:
assert process.stdin is not None
process.stdin.write("\n")
process.stdin.flush()
def creates(server: SimpleNamespace) -> int: # noqa: F811
return len([seen for seen in server.seen if seen == ("POST", SESSION_CREATE_ROUTE, 200)])
@pytest.fixture
def launch(run: Callable[..., Any]) -> Iterator[Callable[..., subprocess.Popen[str]]]: # noqa: F811
"""Start a process that does not outlive twice the deadline, so a client that waits on fails its test."""
timers: list[Timer] = []
def start(*argv: str) -> subprocess.Popen[str]:
process = run("-c", *argv, stdin=subprocess.PIPE)
timers.append(Timer(2 * DEADLINE, process.kill))
timers[-1].start()
return process
yield start
for timer in timers:
timer.cancel()
@pytest.fixture
def client(gate: Gate, launch: Callable[..., Any], tmp_path: Path) -> Callable[..., subprocess.Popen[str]]:
"""Start a client with a remote session, which calls the server when the test says so."""
def start(*argv: str) -> subprocess.Popen[str]:
process = launch(CLIENT, gate.url, str(tmp_path / "client"), *argv)
wait_line(process, "ready")
return process
return start
def press(process: subprocess.Popen[str]) -> str:
"""Send Ctrl+C, and return what the client prints before it ends in time."""
sent = time.monotonic()
process.send_signal(signal.SIGINT)
output, _ = process.communicate(timeout=DEADLINE)
assert time.monotonic() - sent < BOUND, output
assert "Traceback" not in output
return output
def limit(monkeypatch: pytest.MonkeyPatch, handler: str) -> None:
"""Answer one route of the server with a 429 that asks for an hour, before its first heartbeat sends a 200."""
async def refuse(*args: Any) -> web.Response:
return web.json_response({"error_code": "RATE_LIMITED"}, status=429, headers={"Retry-After": "3600"})
monkeypatch.setattr(routes, "HEARTBEAT_INTERVAL", 30.0)
monkeypatch.setattr(routes, handler, refuse)
class Held:
"""A handler of the server that waits for ``release`` before it does its work, from the first call that ``when`` takes."""
def __init__(self, monkeypatch: pytest.MonkeyPatch, name: str, when: Callable[[], bool] = lambda: True) -> None:
self.started, self.release = Event(), Event()
handler = getattr(routes, name)
async def held(*args: Any) -> Any:
if when():
self.started.set()
while not self.release.is_set():
await asyncio.sleep(0.01)
return await handler(*args)
monkeypatch.setattr(routes, name, held)
def __enter__(self) -> Held:
return self
def __exit__(self, *_: object) -> None:
self.release.set()
def lose(server: SimpleNamespace, gate: Gate, monkeypatch: pytest.MonkeyPatch, wait: str) -> str: # noqa: F811
"""Make the next call of the client wait, and return the line that the client prints for it."""
if wait == "dead":
gate.close()
elif wait == "draining":
store = session_store.get_session_store()
monkeypatch.setattr(store, "draining", True)
forget(server, sessions()[0].session_id)
else:
limit(monkeypatch, "session_titles_handler")
return LIMITED
return WAITING
@pytest.mark.parametrize("wait", ["dead", "draining", "limited"])
def test_a_ctrl_c_ends_the_wait_of_each_track(
server: SimpleNamespace, # noqa: F811
gate: Gate,
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
wait: str,
) -> None:
"""Two tracks wait: one in its wait and one for the lock of that wait."""
process = client("pool")
line = lose(server, gate, monkeypatch, wait)
go(process)
wait_line(process, line)
if wait != "dead":
assert wait_until(lambda: count(server, "GET", TITLES_ROUTE) == 2, DEADLINE)
seen = len(server.seen)
output = press(process)
assert output.split("\n")[:-1] == ["cancelled", "Download Cancelled", "vault writes done"]
assert {(method, status) for method, _, status in server.seen[seen:]} <= {("DELETE", 200), ("GET", 101)}
assert wait == "dead" or sessions() == []
@pytest.mark.parametrize("wait", ["dead", "limited", "login"])
def test_a_ctrl_c_in_the_main_thread_ends_its_wait(
server: SimpleNamespace, # noqa: F811
gate: Gate,
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
wait: str,
) -> None:
process = client("main")
if wait == "login":
login = hold_login(monkeypatch)
forget(server, sessions()[0].session_id)
go(process)
assert login.started.wait(DEADLINE)
assert wait_until(lambda: sessions() and sessions()[0].channel.attached, DEADLINE)
try:
output = press(process)
finally:
login.release.set()
else:
line = lose(server, gate, monkeypatch, wait)
go(process)
wait_line(process, line)
output = press(process)
assert "Aborted" in output
def hold_login(monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace:
login = SimpleNamespace(started=Event(), release=Event())
def hold(stub: StubService, cookies: Any, credential: Any) -> None:
login.started.set()
login.release.wait(DEADLINE)
monkeypatch.setattr(StubService, "authenticate", hold)
return login
@pytest.mark.parametrize("channel", ["socket", "polling"])
def test_a_ctrl_c_in_the_login_of_a_reopen_deletes_the_new_session(
server: SimpleNamespace, # noqa: F811
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
channel: str,
) -> None:
"""The client of the polling channel does not know yet that its login succeeded, so the DELETE returns a cache."""
process = client("pool", channel)
login = hold_login(monkeypatch)
forget(server, sessions()[0].session_id)
polls = count(server, "GET", PROMPT_ROUTE)
go(process)
try:
assert login.started.wait(DEADLINE)
if channel == "socket":
assert wait_until(lambda: sessions()[0].channel.attached, DEADLINE)
else:
assert wait_until(lambda: count(server, "GET", PROMPT_ROUTE) > polls, DEADLINE)
login.release.set()
assert wait_until(lambda: sessions()[0].auth_status == AuthStatus.AUTHENTICATED, DEADLINE)
store_cache()
created, (entry,) = count(server, "POST", SESSION_CREATE_ROUTE), sessions()
output = press(process)
finally:
login.release.set()
assert "Download Cancelled" in output and "called" not in output and "error" not in output.lower()
assert sessions() == [] and count(server, "POST", SESSION_CREATE_ROUTE) == created
assert count(server, "DELETE", SESSION_ROUTE, entry.session_id) == 1
assert channel == "socket" or saved(tmp_path / "client")
def test_a_failed_track_does_not_stop_the_reopen_of_the_others(
server: SimpleNamespace, # noqa: F811
gate: Gate,
client: Callable[..., Any],
) -> None:
"""The failed track cancels the downloads while the server restarts, and the next title has a remote session."""
process = client("fails")
gate.close()
forget(server, sessions()[0].session_id)
go(process)
wait_line(process, WAITING)
go(process)
wait_line(process, "failed")
gate.open()
output, _ = process.communicate(timeout=DEADLINE)
assert output.split("\n")[-4:-1] == ["called", "title failed", "next title"], output
assert creates(server) == 2
def test_a_ctrl_c_after_a_failed_track_ends_the_wait_of_the_others(gate: Gate, client: Callable[..., Any]) -> None:
process = client("fails")
gate.close()
go(process)
wait_line(process, WAITING)
go(process)
wait_line(process, "failed")
assert press(process).split("\n")[:-1] == ["cancelled", "Download Cancelled", "vault writes done"]
def test_a_push_in_flight_reaches_the_server_before_the_end(
server: SimpleNamespace, # noqa: F811
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
) -> None:
held = Held(monkeypatch, "session_keys_handler")
limit(monkeypatch, "session_titles_handler")
process = client("push")
go(process)
wait_line(process, LIMITED)
with held:
assert held.started.wait(DEADLINE)
process.send_signal(signal.SIGINT)
wait_line(process, "Download Cancelled")
assert count(server, "DELETE", SESSION_ROUTE) == 0
output, _ = process.communicate(timeout=DEADLINE)
assert "vault writes done" in output
(push,) = [seen for seen in server.seen if seen[0] == "POST" and seen[1].endswith("/keys")]
assert [seen for seen in server.seen[server.seen.index(push) :] if seen[0] == "DELETE"] and sessions() == []
def test_a_push_to_a_lost_server_gives_up(gate: Gate, client: Callable[..., Any]) -> None:
process = client("lost-push")
gate.close()
go(process)
wait_line(process, WAITING)
assert "vault writes done" in press(process)
@pytest.mark.parametrize(
("phase", "handler"),
[
("url", "session_segments_handler"),
("licence", "session_license_handler"),
("file", "session_license_handler"),
("relay", "session_license_handler"),
("certificate", "session_license_handler"),
("filter", "session_segment_filter_handler"),
("samples", "session_samples_handler"),
],
)
def test_a_track_whose_wait_was_cancelled_did_not_fail(
client: Callable[..., Any], monkeypatch: pytest.MonkeyPatch, phase: str, handler: str
) -> None:
limit(monkeypatch, handler)
process = client(phase)
go(process)
wait_line(process, LIMITED)
lines = press(process).split("\n")[:-1]
assert sorted(lines) == ["Download Cancelled", "DownloadCancelled", "cancelled", "vault writes done"]
def test_a_cancelled_call_of_the_polling_channel_fetches_no_server_log(
server: SimpleNamespace, # noqa: F811
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
) -> None:
limit(monkeypatch, "session_segments_handler")
process = client("url", "polling")
fetched = count(server, "GET", LOGS_ROUTE)
go(process)
wait_line(process, LIMITED)
press(process)
assert count(server, "GET", LOGS_ROUTE) == fetched > 0
@pytest.mark.parametrize("cancelled", [False, True])
def test_a_cancelled_login_shows_no_notice(monkeypatch: pytest.MonkeyPatch, cancelled: bool) -> None:
shown: list[Any] = []
monkeypatch.setattr(remote_channel, "show_notice", lambda *args: shown.append(args))
monkeypatch.setattr(RunCancel, "pressed", cancelled)
messages = ServerMessages(cast(Any, SimpleNamespace(auth_notice=None, auth_qr=None)))
messages.recent_logs.append("Approve at example.com")
messages.note_waiting(0)
assert bool(shown) is not cancelled
def test_a_stop_of_a_job_cancels_its_tracks_too(
client: Callable[..., Any],
held_delete: HeldDelete, # noqa: F811
monkeypatch: pytest.MonkeyPatch,
) -> None:
"""A job worker gets no KeyboardInterrupt, and its cancelled track must not look like a failed or a finished one."""
limit(monkeypatch, "session_segments_handler")
process = client("url", "job")
go(process)
wait_line(process, LIMITED)
process.send_signal(signal.SIGTERM)
assert held_delete.started.wait(DEADLINE)
lines = [wait_line(process, "Download").strip() for _ in range(2)]
held_delete.release.set()
assert lines == ["DownloadCancelled", "Download Cancelled"]
assert process.wait(DEADLINE) == 128 + signal.SIGTERM
def cancel_in(process: subprocess.Popen[str], held: Held, then: Callable[[], None] = lambda: None) -> str:
"""Send Ctrl+C while the server holds a request of the pool, which no cancel can reach, and then let it answer."""
with held:
assert held.started.wait(DEADLINE)
process.send_signal(signal.SIGINT)
wait_line(process, "cancelled")
then()
output, _ = process.communicate(timeout=DEADLINE)
assert "Download Cancelled" in output
return output
@pytest.mark.parametrize(
("name", "line"), [("latest_release", WAITING), ("session_info_handler", "The remote session was lost")]
)
def test_a_request_of_the_recovery_that_ends_after_the_ctrl_c_is_silent(
server: SimpleNamespace, # noqa: F811
gate: Gate,
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
name: str,
line: str,
) -> None:
process = client("call")
held = Held(monkeypatch, name)
forget(server, sessions()[0].session_id)
go(process)
output = cancel_in(process, held, gate.close if line == WAITING else lambda: None)
assert line not in output and creates(server) == 1
def test_a_session_that_is_alive_after_the_ctrl_c_gets_no_second_call(
server: SimpleNamespace, # noqa: F811
gate: Gate,
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
) -> None:
process = client("call")
gate.close()
go(process)
wait_line(process, WAITING)
held = Held(monkeypatch, "session_info_handler")
gate.open()
cancel_in(process, held)
assert count(server, "GET", TITLES_ROUTE) == 0 and sessions() == []
@pytest.mark.parametrize(("name", "tracks"), [("session_titles_handler", 1), ("session_tracks_handler", 2)])
def test_a_reopen_stops_after_the_request_of_the_ctrl_c(
server: SimpleNamespace, # noqa: F811
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
name: str,
tracks: int,
) -> None:
process = client("tracks")
go(process)
wait_line(process, "tracks")
held = Held(monkeypatch, name, lambda: creates(server) == 2)
forget(server, sessions()[0].session_id)
go(process)
cancel_in(process, held)
assert count(server, "GET", TITLES_ROUTE) == 3
assert count(server, "POST", TRACKS_ROUTE) == tracks and sessions() == []
@pytest.mark.parametrize(("phase", "created"), [("login-material", 1), ("login-done", 2)])
def test_a_ctrl_c_in_a_reopen_stops_it_at_its_next_step(
server: SimpleNamespace, # noqa: F811
client: Callable[..., Any],
phase: str,
created: int,
) -> None:
process = client(phase)
go(process)
wait_line(process, "tracks")
forget(server, sessions()[0].session_id)
titles = count(server, "GET", TITLES_ROUTE)
go(process)
wait_line(process, phase.replace("-", " "))
press(process)
assert creates(server) == created and sessions() == []
assert count(server, "GET", TITLES_ROUTE) == titles + 1
def test_a_ctrl_c_ends_the_wait_for_the_channel_of_a_reopen(
server: SimpleNamespace, # noqa: F811
client: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
) -> None:
process = client("call")
held = Held(monkeypatch, "session_channel_handler", lambda: creates(server) == 2)
forget(server, sessions()[0].session_id)
go(process)
with held:
assert held.started.wait(DEADLINE)
press(process)
assert sessions() == []
def test_the_command_prints_one_line_and_starts_with_no_cancel(
server: SimpleNamespace, # noqa: F811
logins: list[Any], # noqa: F811
example_service: None,
launch: Callable[..., Any],
monkeypatch: pytest.MonkeyPatch,
tmp_path: Path,
) -> None:
def tracks(stub: StubService, title: Any) -> Tracks:
audio = Audio(url="", language="en", codec=Audio.Codec.AAC, bitrate=128_000, channels=2, id_="a1")
audio.resolve_url = lambda: "https://cdn.example/a1.m4a"
return Tracks([audio])
monkeypatch.setattr(StubService, "get_tracks", tracks)
limit(monkeypatch, "session_segments_handler")
script = "from unshackle.core.constants import RunCancel\nRunCancel.pressed = True\n" + COMMAND
argv = ["dl", "--remote", "--no-proxy", "--audio-only", "-l", "en", "-w", "1", "EXAMPLE", "example-1"]
process = launch(script, json.dumps(settings(server.url, tmp_path)), *argv)
wait_line(process, LIMITED)
output = press(process)
assert process.returncode == 0 and sessions() == []
after = output[output.index("Download Cancelled") :]
assert after.strip() == "Download Cancelled..." and "FAILED" not in output and "ERROR" not in output