mirror of
https://github.com/unshackle-dl/unshackle.git
synced 2026-11-29 12:35:13 +00:00
fix(tracks): keep segment resume across an hls merge failure and a locked partial on windows
This commit is contained in:
@@ -140,7 +140,7 @@ def test_existing_stash_target_is_left_alone(temp_root, monkeypatch):
|
||||
target.mkdir(parents=True)
|
||||
(target / "old.mp4").write_bytes(b"old")
|
||||
save_dir = task_dir / SEG_NAME
|
||||
save_dir.mkdir()
|
||||
open_store(save_dir)
|
||||
(save_dir / "new.mp4").write_bytes(b"new")
|
||||
|
||||
store(save_dir).abandon()
|
||||
@@ -168,7 +168,7 @@ def test_restore_is_a_noop_without_stash_or_with_present_dir(temp_root, monkeypa
|
||||
assert not (save_dir / "a.mp4").exists()
|
||||
|
||||
|
||||
def test_rename_failure_never_replaces_download_error(temp_root, monkeypatch):
|
||||
def test_move_failure_never_replaces_download_error(temp_root, monkeypatch):
|
||||
monkeypatch.setattr(config, "continue_downloads", True)
|
||||
|
||||
def deny(self, target):
|
||||
@@ -176,6 +176,7 @@ def test_rename_failure_never_replaces_download_error(temp_root, monkeypatch):
|
||||
|
||||
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)
|
||||
|
||||
@@ -278,3 +279,49 @@ def test_stash_refreshes_mtime(temp_root, monkeypatch):
|
||||
|
||||
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}
|
||||
|
||||
@@ -6,12 +6,14 @@ from __future__ import annotations
|
||||
import importlib
|
||||
import json
|
||||
import shutil
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
from uuid import UUID
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from tests.core.test_hls_kid_from_init import KEY_LINE, no_kid_pssh
|
||||
from tests.core.test_rolling_merge_hls_ism import INIT, PARTS, hls_track, ism_track, make_ctx
|
||||
from tests.core.test_rolling_merge_hls_ism import no_cancel as no_cancel # noqa: F401
|
||||
from tests.core.test_rolling_merge_hls_ism import no_decrypt
|
||||
@@ -23,6 +25,7 @@ from unshackle.core.constants import DOWNLOAD_CANCELLED
|
||||
from unshackle.core.drm import ClearKey, ClearKeyCENC
|
||||
from unshackle.core.manifests import HLS, ISM
|
||||
from unshackle.core.manifests import hls as hls_module
|
||||
from unshackle.core.temp import RESUME_STASH, task_temp_dir
|
||||
from unshackle.core.tracks import Video
|
||||
from unshackle.core.tracks.segment_store import DownloadMode, SegmentStore, fingerprint
|
||||
|
||||
@@ -261,3 +264,103 @@ def test_hls_resumes_when_the_init_turns_segment_decryption_off(server, tmp_path
|
||||
output = two_runs(server, ctx, HLS, make, "/part3.m4s", ctx.save_dir / "segments" / "1.m4s")
|
||||
|
||||
assert output == INIT + PARTS[0] + b"\xee" * 10 + b"".join(PARTS[2:])
|
||||
|
||||
|
||||
class Routes(dict):
|
||||
"""Server routes that count the requests for each path and fail them from a given request on."""
|
||||
|
||||
def __init__(self, routes: dict[str, bytes]) -> None:
|
||||
super().__init__(routes)
|
||||
self.hits: Counter[str] = Counter()
|
||||
self.fail_from: dict[str, int] = {}
|
||||
|
||||
def get(self, path, default=None):
|
||||
self.hits[path] += 1
|
||||
if path in self.fail_from and self.hits[path] >= self.fail_from[path]:
|
||||
return default
|
||||
return super().get(path, default)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("encrypted", [False, True], ids=["clear", "widevine"])
|
||||
def test_hls_resumes_after_a_failure_in_the_merge(server, tmp_path, monkeypatch, one_attempt, encrypted):
|
||||
"""The init fetch of the merge fails after every segment landed: the next run reuses all of them."""
|
||||
no_decrypt(monkeypatch)
|
||||
|
||||
def make():
|
||||
track = hls_track(server, False)
|
||||
track.drm = [widevine()] if encrypted else []
|
||||
return track
|
||||
|
||||
ctx = make_ctx(tmp_path, "hls.mp4")
|
||||
ctx.license_widevine = lambda *a, **kw: None
|
||||
|
||||
output = two_runs(server, ctx, HLS, make, "/init.mp4", ctx.save_dir / "segments" / "1.m4s")
|
||||
|
||||
assert output == INIT + PARTS[0] + b"\xee" * 10 + b"".join(PARTS[2:])
|
||||
|
||||
|
||||
def test_hls_never_reuses_segments_after_the_merge_rewrote_them(server, tmp_path, monkeypatch, one_attempt):
|
||||
"""A failure after the first discontinuity merge leaves no sidecar, so the next run downloads every segment."""
|
||||
server.routes = Routes(server.routes)
|
||||
ctx = make_ctx(tmp_path, "hls.mp4")
|
||||
server.routes.fail_from["/init.mp4"] = 2
|
||||
with pytest.raises(requests.HTTPError):
|
||||
HLS.download_track(hls_track(server, True), ctx)
|
||||
assert not SegmentStore(hls_track(server, True), ctx.save_dir).sidecar.exists()
|
||||
|
||||
server.routes.fail_from.clear()
|
||||
server.routes.hits.clear()
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
HLS.download_track(hls_track(server, True), ctx)
|
||||
|
||||
assert ctx.save_path.read_bytes().endswith(INIT + b"".join(PARTS[2:]))
|
||||
assert all(server.routes.hits[f"/part{i}.m4s"] == 1 for i in range(len(PARTS)))
|
||||
|
||||
|
||||
def test_hls_never_reuses_segments_after_a_key_change_merged_them(server, tmp_path, monkeypatch, one_attempt):
|
||||
"""The licence of a later key fails after the merge joined the first key range: the next run starts clean."""
|
||||
no_decrypt(monkeypatch)
|
||||
server.routes = Routes(server.routes)
|
||||
|
||||
def make():
|
||||
track = hls_track(server, False)
|
||||
lines = ["#EXTM3U", "#EXT-X-VERSION:7", "#EXT-X-TARGETDURATION:4", '#EXT-X-MAP:URI="init.mp4"']
|
||||
for i in range(len(PARTS)):
|
||||
if i in (0, 2):
|
||||
lines.append(KEY_LINE.format(pssh=no_kid_pssh(bytes([i]))))
|
||||
lines += ["#EXTINF:4.0,", f"part{i}.m4s"]
|
||||
server.routes["/media.m3u8"] = "\n".join(lines + ["#EXT-X-ENDLIST"]).encode()
|
||||
monkeypatch.setattr(type(track), "get_key_id", lambda self, *a, **kw: KID)
|
||||
return track
|
||||
|
||||
licences: list[object] = []
|
||||
|
||||
def licence(drm, **kw):
|
||||
licences.append(drm)
|
||||
if len(licences) == 2:
|
||||
raise PermissionError("EXAMPLE licence refused")
|
||||
|
||||
ctx = make_ctx(tmp_path, "hls.mp4")
|
||||
ctx.license_widevine = licence
|
||||
with pytest.raises(PermissionError):
|
||||
HLS.download_track(make(), ctx)
|
||||
assert not SegmentStore(make(), ctx.save_dir).sidecar.exists()
|
||||
|
||||
server.routes.hits.clear()
|
||||
DOWNLOAD_CANCELLED.clear()
|
||||
HLS.download_track(make(), ctx)
|
||||
|
||||
assert all(server.routes.hits[f"/part{i}.m4s"] == 1 for i in range(len(PARTS)))
|
||||
|
||||
|
||||
def test_abandon_drops_a_directory_without_a_sidecar(tmp_path, keep, monkeypatch):
|
||||
monkeypatch.setattr(config.directories, "temp", tmp_path)
|
||||
with task_temp_dir() as task_dir:
|
||||
store = SegmentStore(make_track(), task_dir / "Video_x.mp4_segments")
|
||||
store.save_dir.mkdir()
|
||||
(store.save_dir / "0.mp4").write_bytes(b"segment")
|
||||
|
||||
store.abandon()
|
||||
|
||||
assert not store.save_dir.exists()
|
||||
assert not (tmp_path / RESUME_STASH).exists()
|
||||
|
||||
Reference in New Issue
Block a user