"""A failed track's kept segments survive the per-run temp dir and come back in the next run.""" from __future__ import annotations import contextlib import os import shutil import time from functools import partial from pathlib import Path from types import SimpleNamespace import pytest from filelock import FileLock from unshackle.core.config import config from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY, DownloadCancelled from unshackle.core.temp import LOCK_NAME, RESUME_STASH, STASH_MAX_AGE, resume_stash, sweep_task_dirs, task_temp_dir from unshackle.core.tracks import Video from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore pytestmark = pytest.mark.unit SEGMENTS = [("https://example.test/0.mp4", None)] SEG_NAME = "Video_t1.mp4_segments" @pytest.fixture def temp_root(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: root = tmp_path / "temp" root.mkdir() monkeypatch.setattr(config.directories, "temp", root) DOWNLOAD_CANCELLED.clear() DOWNLOAD_LICENCE_ONLY.clear() yield root DOWNLOAD_CANCELLED.clear() def make_track() -> Video: return Video( id_="t1", url="https://example.test/manifest.mpd", language="en", codec=Video.Codec.AVC, range_=Video.Range.SDR, width=1920, height=1080, bitrate=5_000_000, descriptor=Video.Descriptor.DASH, ) def run_download(monkeypatch: pytest.MonkeyPatch, parser) -> None: import requests as requests_lib from unshackle.core.manifests import DASH monkeypatch.setattr(DASH, "download_track", staticmethod(parser)) make_track().download( session=requests_lib.Session(), prepare_drm=partial(lambda *a, **kw: None), progress=partial(lambda **kw: None), ) def store(save_dir: Path) -> SegmentStore: return SegmentStore(make_track(), save_dir) def open_store(save_dir: Path) -> bool: return store(save_dir).open(make_track().url, SEGMENTS, mode=DownloadMode()) def seed(ctx): open_store(ctx.save_dir) (ctx.save_dir / "0.mp4").write_bytes(b"complete segment") def failing_parser(track, ctx): seed(ctx) (ctx.save_dir / "1.mp4.p.!dev").write_bytes(b"partial") raise RuntimeError("simulated crash") def cancelled_parser(track, ctx): seed(ctx) (ctx.save_dir / "1.mp4.p.!dev").write_bytes(b"partial") raise DownloadCancelled def test_failed_track_resumes_in_next_run(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir(): with pytest.raises(RuntimeError): run_download(monkeypatch, failing_parser) stashed = temp_root / RESUME_STASH / SEG_NAME assert (stashed / "0.mp4").read_bytes() == b"complete segment" assert store(stashed).sidecar.exists() seen = {} def second_parser(track, ctx): seen["bytes"] = (ctx.save_dir / "0.mp4").read_bytes() seen["reusable"] = open_store(ctx.save_dir) ctx.save_path.write_bytes(b"output") track.path = ctx.save_path with task_temp_dir(): run_download(monkeypatch, second_parser) assert seen == {"bytes": b"complete segment", "reusable": True} assert not stashed.exists() def killed_run(temp_root: Path, name: str = "task_killed", segments: str = SEG_NAME) -> Path: """The task dir of a run killed mid-download: its lock file, a sidecar, a complete and a partial segment.""" task_dir = temp_root / name task_dir.mkdir() (task_dir / LOCK_NAME).touch() save_dir = task_dir / segments seed(SimpleNamespace(save_dir=save_dir)) (save_dir / "1.mp4.p.!dev").write_bytes(b"partial") return task_dir def test_a_killed_run_resumes_from_its_task_dir(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) killed = killed_run(temp_root) seen = {} def second_parser(track, ctx): seen["files"] = sorted(path.name for path in ctx.save_dir.iterdir()) seen["reusable"] = open_store(ctx.save_dir) ctx.save_path.write_bytes(b"output") track.path = ctx.save_path with task_temp_dir(): run_download(monkeypatch, second_parser) assert seen == {"files": ["0.mp4"], "reusable": True} assert not (killed / SEG_NAME / "0.mp4").exists() def test_the_sweep_stashes_what_a_killed_run_keeps_and_removes_the_rest(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) killed = killed_run(temp_root) (killed / "Audio_t2.mp4").write_bytes(b"a finished track") old = killed_run(temp_root, "task_old", "Video_old.mp4_segments") when = time.time() - STASH_MAX_AGE - 60 for save_dir in (killed / SEG_NAME, old / "Video_old.mp4_segments"): for path in (save_dir.parent, save_dir, store(save_dir).sidecar): os.utime(path, (when, when)) sweep_task_dirs(temp_root) stashed = temp_root / RESUME_STASH / SEG_NAME assert (stashed / "0.mp4").read_bytes() == b"complete segment" assert store(stashed).sidecar.exists() assert not killed.exists() assert not old.exists() # the stash ages an entry from when it arrived there, not from when the killed run wrote it assert len(list((temp_root / RESUME_STASH).iterdir())) == 4 def test_a_killed_run_resumes_after_the_sweep_probed_its_lock(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) killed = killed_run(temp_root) when = time.time() - 120 os.utime(killed, (when, when)) with task_temp_dir() as task_dir: store(task_dir / SEG_NAME).restore() assert (task_dir / SEG_NAME / "0.mp4").read_bytes() == b"complete segment" def test_a_running_task_keeps_its_segments(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) running = killed_run(temp_root) with FileLock(running / LOCK_NAME), task_temp_dir() as task_dir: store(task_dir / SEG_NAME).restore() assert not (task_dir / SEG_NAME).exists() assert (running / SEG_NAME / "0.mp4").exists() def test_flag_off_stashes_nothing(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", False) with task_temp_dir(): with pytest.raises(RuntimeError): run_download(monkeypatch, failing_parser) assert not (temp_root / RESUME_STASH).exists() def test_partials_are_not_stashed(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir(): with pytest.raises(RuntimeError): run_download(monkeypatch, failing_parser) assert (temp_root / RESUME_STASH / SEG_NAME / "0.mp4").exists() assert not list((temp_root / RESUME_STASH).rglob("*.!dev")) def test_a_checkpointed_output_is_stashed_beside_its_segments(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: save_dir = task_dir / SEG_NAME rolling = store(save_dir) rolling.open(make_track().url, SEGMENTS, mode=DownloadMode(rolling_merge=True)) (save_dir / "1.mp4").write_bytes(b"next segment") (save_dir / "2.mp4").write_bytes(b"written") (save_dir / "2.mp4.!dev").write_bytes(b"control") (task_dir / "Video_t1.mp4").write_bytes(b"init+0") assert rolling.checkpoint(1, 6) rolling.abandon() stashed = temp_root / RESUME_STASH / SEG_NAME assert sorted(path.name for path in stashed.iterdir()) == ["1.mp4"] assert (temp_root / RESUME_STASH / "Video_t1.mp4").read_bytes() == b"init+0" @pytest.mark.skipif(os.name == "nt", reason="a symlink needs a privilege on Windows") def test_a_symlinked_output_is_never_stashed(temp_root, monkeypatch, tmp_path): monkeypatch.setattr(config, "continue_downloads", True) elsewhere = tmp_path / "elsewhere.mp4" elsewhere.write_bytes(b"not ours") with task_temp_dir() as task_dir: save_dir = task_dir / SEG_NAME rolling = store(save_dir) rolling.open(make_track().url, SEGMENTS, mode=DownloadMode(rolling_merge=True)) (save_dir / "1.mp4").write_bytes(b"next segment") (task_dir / "Video_t1.mp4").symlink_to(elsewhere) rolling._record["merge"] = [1, 6] rolling._write() rolling.abandon() assert not (temp_root / RESUME_STASH / "Video_t1.mp4").exists() assert elsewhere.read_bytes() == b"not ours" def test_existing_stash_target_is_left_alone(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: target = temp_root / RESUME_STASH / SEG_NAME target.mkdir(parents=True) (target / "old.mp4").write_bytes(b"old") save_dir = task_dir / SEG_NAME open_store(save_dir) (save_dir / "new.mp4").write_bytes(b"new") store(save_dir).abandon() assert (target / "old.mp4").read_bytes() == b"old" assert not (target / "new.mp4").exists() assert save_dir.exists() def test_restore_is_a_noop_without_stash_or_with_present_dir(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: save_dir = task_dir / SEG_NAME store(save_dir).restore() assert not save_dir.exists() target = temp_root / RESUME_STASH / SEG_NAME target.mkdir(parents=True) (target / "a.mp4").write_bytes(b"a") save_dir.mkdir() store(save_dir).restore() assert (target / "a.mp4").exists() assert not (save_dir / "a.mp4").exists() def test_move_failure_never_replaces_download_error(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) def deny(self, target): raise PermissionError("locked") with task_temp_dir(): monkeypatch.setattr(Path, "rename", deny) monkeypatch.setattr(Path, "replace", deny) with pytest.raises(RuntimeError, match="simulated crash"): run_download(monkeypatch, failing_parser) def test_locked_segment_never_replaces_download_error(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", False) rmtree = shutil.rmtree def locked(path, *args, **kwargs): if Path(path).name == SEG_NAME and not kwargs.get("ignore_errors"): raise PermissionError(32, "being used by another process", str(path)) rmtree(path, *args, **kwargs) monkeypatch.setattr(shutil, "rmtree", locked) with task_temp_dir(): with pytest.raises(RuntimeError, match="simulated crash"): run_download(monkeypatch, failing_parser) @pytest.mark.parametrize("parser", [failing_parser, cancelled_parser]) def test_locked_partial_still_stashes(temp_root, monkeypatch, parser): monkeypatch.setattr(config, "continue_downloads", True) unlink = Path.unlink def locked(self, missing_ok=False): if self.name.endswith(".!dev"): raise PermissionError(32, "being used by another process", str(self)) unlink(self, missing_ok=missing_ok) with task_temp_dir(): monkeypatch.setattr(Path, "unlink", locked) with contextlib.suppress(RuntimeError): run_download(monkeypatch, parser) assert (temp_root / RESUME_STASH / SEG_NAME / "0.mp4").read_bytes() == b"complete segment" def test_sweep_removes_only_old_stash_entries(temp_root): stash = temp_root / RESUME_STASH old, fresh = stash / "old_segments", stash / "fresh_segments" old.mkdir(parents=True) fresh.mkdir() old_sidecar = stash / "old_segments.resume.json" old_sidecar.write_text("{}") stamp = time.time() - STASH_MAX_AGE - 60 for path in (old, old_sidecar): os.utime(path, (stamp, stamp)) sweep_task_dirs(temp_root) assert not old.exists() assert not old_sidecar.exists() assert fresh.exists() def test_no_stash_outside_task_dir(temp_root): assert resume_stash() is None def test_cancelled_track_is_stashed(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir(): run_download(monkeypatch, cancelled_parser) stashed = temp_root / RESUME_STASH / SEG_NAME assert (stashed / "0.mp4").read_bytes() == b"complete segment" assert store(stashed).sidecar.exists() def test_presized_data_file_is_dropped_with_its_control_file(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) def parser(track, ctx): seed(ctx) (ctx.save_dir / "1.mp4").write_bytes(b"\0" * 8) (ctx.save_dir / "1.mp4.!dev").write_bytes(b"") raise RuntimeError("simulated crash") with task_temp_dir(): with pytest.raises(RuntimeError): run_download(monkeypatch, parser) stashed = temp_root / RESUME_STASH / SEG_NAME assert (stashed / "0.mp4").exists() assert not (stashed / "1.mp4").exists() assert not (stashed / "1.mp4.!dev").exists() def test_stash_refreshes_mtime(temp_root, monkeypatch): monkeypatch.setattr(config, "continue_downloads", True) with task_temp_dir() as task_dir: save_dir = task_dir / SEG_NAME open_store(save_dir) stamp = time.time() - STASH_MAX_AGE - 60 os.utime(save_dir, (stamp, stamp)) store(save_dir).abandon() target = temp_root / RESUME_STASH / SEG_NAME assert time.time() - target.stat().st_mtime < 60 def test_a_partial_still_open_does_not_block_the_stash(temp_root, monkeypatch): """On Windows a worker that still writes a partial file after the failure blocks the rename of its directory. The directory patches emulate that, so a stash that renames the directory finds nothing stashed. """ monkeypatch.setattr(config, "continue_downloads", True) rename, replace, unlink = Path.rename, Path.replace, Path.unlink def refuse_dir(move): def windows(self, target): if self.is_dir(): raise PermissionError(5, "Access is denied", str(self)) return move(self, target) return windows def locked(self, missing_ok=False): if self.name.endswith(".!dev"): raise PermissionError(32, "being used by another process", str(self)) unlink(self, missing_ok=missing_ok) with task_temp_dir(), pytest.MonkeyPatch.context() as windows_fs: windows_fs.setattr(Path, "rename", refuse_dir(rename)) windows_fs.setattr(Path, "replace", refuse_dir(replace)) windows_fs.setattr(Path, "unlink", locked) with pytest.raises(RuntimeError): run_download(monkeypatch, failing_parser) stashed = temp_root / RESUME_STASH / SEG_NAME assert store(stashed).sidecar.exists() assert not list(stashed.rglob("*.!dev")) seen = {} def second_parser(track, ctx): seen["bytes"] = (ctx.save_dir / "0.mp4").read_bytes() seen["reused"] = open_store(ctx.save_dir) ctx.save_path.write_bytes(b"output") track.path = ctx.save_path with task_temp_dir(): run_download(monkeypatch, second_parser) assert seen == {"bytes": b"complete segment", "reused": True}