feat(dl): add opt-in per-caller completion archive

This commit is contained in:
Fiszu
2026-12-01 21:58:17 -06:00
committed by GitHub
parent 7a5bac7878
commit e36236d5cc
14 changed files with 853 additions and 3 deletions
+131
View File
@@ -0,0 +1,131 @@
"""Service-independent completion archive matching and persistence."""
import json
from concurrent.futures import ThreadPoolExecutor
from dataclasses import replace
import pytest
from unshackle.core.download_archive import PARTIAL_MODES, ArchiveEntry, DownloadArchive, archive_entries
from unshackle.core.titles import Episode
from unshackle.core.tracks import Tracks, Video
class EXAMPLE:
pass
def episode(height=720, **video_options):
title = Episode(id_="example-episode-1", service=EXAMPLE, title="Example", season=1, number=1)
title.tracks = Tracks(
Video(
id_="video",
url="https://example.invalid/video",
language="en",
height=height,
width=height * 16 // 9 if height else None,
codec=Video.Codec.AVC,
range_=Video.Range.SDR,
**video_options,
)
)
return title
def test_exact_resolved_variant_not_requested_quality(tmp_path):
archive = DownloadArchive(tmp_path)
entries = archive_entries("EXAMPLE", episode(), {})
assert not archive.contains(entries)
archive.record(entries)
assert DownloadArchive(tmp_path).contains(archive_entries("EXAMPLE", episode(), {}))
for change in (
{"quality": 1080},
{"range": "DV"},
{"codec": "H.265"},
{"service": "EXAMPLE2"},
{"title_id": "other-id"},
):
assert not archive.contains([replace(entries[0], **change)])
# A lower explicit request is also a distinct variant.
assert not archive.contains([replace(entries[0], quality=480)])
def test_all_variants_must_be_recorded(tmp_path):
archive = DownloadArchive(tmp_path)
entries = archive_entries("EXAMPLE", episode(), {})
higher = replace(entries[0], quality=1080)
archive.record(entries)
assert not archive.contains([*entries, higher])
archive.record([higher])
assert archive.contains([*entries, higher])
@pytest.mark.parametrize("mode", PARTIAL_MODES)
def test_partial_and_non_download_modes_never_check_or_record(mode):
assert archive_entries("EXAMPLE", episode(), {mode: True}) == []
def test_unknown_video_metadata_never_matches():
assert archive_entries("EXAMPLE", episode(height=None), {}) == []
title = episode()
for attribute in ("codec", "range"):
old = getattr(title.tracks.videos[0], attribute)
setattr(title.tracks.videos[0], attribute, None)
assert archive_entries("EXAMPLE", title, {}) == []
setattr(title.tracks.videos[0], attribute, old)
title.id = {"unsupported": "id"}
assert archive_entries("EXAMPLE", title, {}) == []
def test_scopes_and_typed_ids_do_not_cross(tmp_path):
cli = DownloadArchive(tmp_path)
first = DownloadArchive(tmp_path, "api-" + "a" * 64)
second = DownloadArchive(tmp_path, "api-" + "b" * 64)
entries = [ArchiveEntry("EXAMPLE", 1234, 720, "SDR", "H.264")]
first.record(entries)
assert first.contains(entries)
assert not second.contains(entries)
assert not cli.contains(entries)
assert not first.contains([replace(entries[0], title_id="1234")])
for scope in ("../cli", "api-unowned", "api-../../cli", "/tmp/receipt"):
with pytest.raises(ValueError):
DownloadArchive(tmp_path, scope)
def test_history_and_file_deletion_have_no_effect(tmp_path):
archive = DownloadArchive(tmp_path)
entries = archive_entries("EXAMPLE", episode(), {})
output = tmp_path / "output.mkv"
history = tmp_path / "api_history.jsonl"
output.touch()
history.touch()
archive.record(entries)
output.unlink()
history.unlink()
assert DownloadArchive(tmp_path).contains(entries)
text = archive.path.read_text()
assert "output.mkv" not in text and "api_history" not in text
def test_concurrent_append_and_truncated_receipt(tmp_path):
archive = DownloadArchive(tmp_path)
entries = [ArchiveEntry("EXAMPLE", f"episode-{n}", 720, "SDR", "H.264") for n in range(20)]
archive.path.parent.mkdir(parents=True)
archive.path.write_text('{"version":1,"service":"unfinished')
with ThreadPoolExecutor(4) as pool:
list(pool.map(lambda entry: DownloadArchive(tmp_path).record([entry]), entries))
assert archive.contains(entries)
archive.record(entries)
valid = [json.loads(line) for line in archive.path.read_text().splitlines()[1:] if line]
assert len(valid) == len(entries)
def test_existing_reader_observes_another_writer(tmp_path):
archive = DownloadArchive(tmp_path)
first = ArchiveEntry("EXAMPLE", "episode-1", 720, "SDR", "H.264")
second = replace(first, title_id="episode-2")
archive.record([first])
assert archive.contains([first])
assert not archive.contains([second])
DownloadArchive(tmp_path).record([second])
assert archive.contains([first, second])
+271
View File
@@ -0,0 +1,271 @@
"""Exercise the real selection, publication and completion loop with an in-memory service."""
import inspect
import logging
from pathlib import Path
from types import SimpleNamespace
import pytest
import requests
from unshackle.commands.dl import dl
from unshackle.core.config import config
from unshackle.core.constants import DOWNLOAD_CANCELLED, DOWNLOAD_LICENCE_ONLY
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
from unshackle.core.download_archive import DownloadArchive
from unshackle.core.title_source import TitleSource
from unshackle.core.titles import Episode, Series
from unshackle.core.tracks import Audio, Tracks, Video
class EXAMPLE(TitleSource):
NO_SUBTITLES = True
def __init__(self, height=720, count=1):
self.height = height
self.count = count
self.session = requests.Session()
self.ctx = None
def authenticate(self, *args):
pass
def get_titles(self):
return Series(
Episode(id_=f"example-episode-{n}", service=EXAMPLE, title="Example", season=1, number=n, language="en")
for n in range(1, self.count + 1)
)
def get_tracks(self, title):
return Tracks(
[
Video(
id_=f"v-{title.number}",
url="https://example.invalid/video",
language="en",
codec=Video.Codec.AVC,
range_=Video.Range.SDR,
height=self.height,
width=self.height * 16 // 9,
bitrate=1_000_000,
),
Audio(
id_=f"a-{title.number}",
url="https://example.invalid/audio",
language="en",
codec=Audio.Codec.AAC,
bitrate=128_000,
),
]
)
def get_chapters(self, title):
return []
def close(self):
self.session.close()
def __getattr__(self, name):
if name.startswith(("on_", "get_")):
return lambda *a, **k: None
raise AttributeError(name)
class Harness(dl):
def __getattr__(self, name):
return None
@pytest.fixture
def run(monkeypatch, tmp_path):
import unshackle.commands.dl as module
monkeypatch.setattr(config.directories, "cache", tmp_path / "cache")
monkeypatch.setattr(config.directories, "downloads", tmp_path / "downloads")
monkeypatch.setattr(config.directories, "temp", tmp_path / "temp")
monkeypatch.setattr(config, "subtitle", {})
monkeypatch.setattr("unshackle.core.providers.search_metadata", lambda *a, **k: None)
monkeypatch.setattr(
module, "load_tracks", lambda service, title, **k: setattr(title, "tracks", service.get_tracks(title))
)
monkeypatch.setattr(module.tags, "tag_file", lambda *a, **k: None)
monkeypatch.setattr(module.MediaInfo, "parse", lambda *a, **k: SimpleNamespace())
monkeypatch.setattr(
Episode,
"get_filename",
lambda self, *a, folder=False, **k: "Example" if folder else f"Example.S01E{self.number:02}",
)
monkeypatch.setattr(module, "dispatch", lambda *a, **k: None)
downloads = []
muxes = []
def download(tracks, *a, **k):
for track in tracks:
config.directories.temp.mkdir(parents=True, exist_ok=True)
track.path = config.directories.temp / f"{track.id}.bin"
track.path.write_bytes(b"test")
downloads.append(track.id)
monkeypatch.setattr(module, "download_tracks_in_passes", download)
def mux(self, *a, **k):
muxes.append(list(self.videos))
path = config.directories.temp / f"mux-{len(muxes)}.mkv"
path.write_bytes(b"test mux")
return path, 0, []
monkeypatch.setattr(Tracks, "mux", mux)
def invoke(height=720, count=1, scope="cli", **flags):
cmd = Harness.__new__(Harness)
cmd.log = logging.getLogger("archive-test")
cmd.service = "EXAMPLE"
cmd.completed_files = []
cmd.already_present = []
cmd.skipped_titles = []
cmd.skipped_subtitles = []
cmd.archive_scope = scope
cmd.archive_cache = None
kwargs = {}
for name, param in inspect.signature(dl.result).parameters.items():
if name in DEFAULT_DOWNLOAD_PARAMS:
kwargs[name] = DEFAULT_DOWNLOAD_PARAMS[name]
elif name not in ("self", "service"):
kwargs[name] = None if param.default is inspect.Parameter.empty else param.default
kwargs.update(
quality=[], vcodec=[], acodec=[], range_=[], wanted=[], cdm_only=None, downloads=1, skip_existing=True
)
kwargs.update(flags)
try:
cmd.result(EXAMPLE(height, count), **kwargs)
finally:
DOWNLOAD_CANCELLED.clear()
DOWNLOAD_LICENCE_ONLY.clear()
return cmd
invoke.downloads = downloads
invoke.muxes = muxes
return invoke
def test_second_run_skips_and_force_downloads(run):
first = run()
assert len(first.completed_files) == 1 and not first.already_present
count = len(run.downloads)
progress = []
second = run(progress_sink=progress.append)
assert len(run.downloads) == count
assert not second.completed_files and not second.skipped_titles
assert second.already_present[0]["reason"] == "already_present"
assert any(event.get("already_present") for event in progress)
forced = run(force=True)
assert len(run.downloads) > count
assert forced.completed_files and not forced.already_present
def test_new_best_quality_downloads_instead_of_skipping(run):
run(height=720)
count = len(run.downloads)
assert run(height=1080).completed_files
assert len(run.downloads) > count
assert run(height=1080).already_present
def test_failed_publication_does_not_record(monkeypatch, run):
import unshackle.commands.dl as module
monkeypatch.setattr(module.os, "replace", lambda *a: (_ for _ in ()).throw(OSError("publication failed")))
monkeypatch.setattr(module.shutil, "move", lambda *a: (_ for _ in ()).throw(OSError("publication failed")))
with pytest.raises(OSError, match="publication failed"):
run()
assert not DownloadArchive(config.directories.cache).path.exists()
def test_all_archived_titles_complete_successfully(run):
run(count=2)
result = run(count=2)
assert len(result.already_present) == 2
assert not result.completed_files and not result.skipped_titles
def test_api_scopes_and_unowned_worker_do_not_use_cli_archive(run):
run()
assert run(scope="api-" + "a" * 64).completed_files
assert run(scope="api-" + "b" * 64).completed_files
assert run(scope="api-" + "a" * 64).already_present
assert run(scope="api-unowned").completed_files
def test_mux_failure_does_not_record(monkeypatch, run):
monkeypatch.setattr(Tracks, "mux", lambda *a, **k: (Path("unused.mkv"), 2, ["mux failed"]))
with pytest.raises(SystemExit) as exc:
run()
assert exc.value.code == 1
assert not DownloadArchive(config.directories.cache).path.exists()
def test_download_failure_does_not_record(monkeypatch, run):
import unshackle.commands.dl as module
def fail(*a, **k):
raise RuntimeError("test download failure")
monkeypatch.setattr(module, "download_tracks_in_passes", fail)
result = run()
assert result.download_error is not None
assert not DownloadArchive(config.directories.cache).path.exists()
def test_opt_out_does_not_read_or_write_archive(run):
run()
result = run(skip_existing=False)
assert result.completed_files and not result.already_present
def test_missing_requested_quality_still_fails(run):
run(height=720)
with pytest.raises(SystemExit) as exc:
run(height=720, quality=[1080])
assert exc.value.code == 1
def test_partial_publication_of_multiple_variants_does_not_record(monkeypatch, run):
import unshackle.commands.dl as module
get_tracks = EXAMPLE.get_tracks
replace_file = module.os.replace
def variants(self, title):
tracks = get_tracks(self, title)
tracks.add(
Video(
id_="v-higher",
url="https://example.invalid/video",
language="en",
codec=Video.Codec.AVC,
range_=Video.Range.SDR,
height=1080,
width=1920,
bitrate=2_000_000,
)
)
return tracks
monkeypatch.setattr(EXAMPLE, "get_tracks", variants)
published = []
def replace(source, target):
if published:
raise OSError("second variant failed")
replace_file(source, target)
published.append(target)
def fail_move(*a, **k):
raise OSError("second variant failed")
monkeypatch.setattr(module.os, "replace", replace)
monkeypatch.setattr(module.shutil, "move", fail_move)
with pytest.raises(OSError, match="second variant failed"):
run(quality=[720, 1080])
assert len(published) == 1 and published[0].exists()
assert not DownloadArchive(config.directories.cache).path.exists()
@@ -0,0 +1,156 @@
"""Completion reporting survives the worker boundary and is scoped by the server."""
import asyncio
import hashlib
import json
from pathlib import Path
import click
import pytest
from unshackle.core.api import download_manager as dm
from unshackle.core.api import download_worker
from unshackle.core.api.job_channel import WorkerResult
from unshackle.core.config import config
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS
PRESENT = [
{
"service": "EXAMPLE",
"title_id": "example-1",
"reason": "already_present",
"variants": [{"quality": 720, "range": "SDR", "codec": "H.264"}],
}
]
@pytest.mark.parametrize("fails", [False, True], ids=["success", "later-failure"])
def test_worker_takes_the_payload_scope_and_reports_already_present(monkeypatch, tmp_path, fails):
seen = {}
def perform(*args, **kwargs):
seen.update(kwargs)
kwargs["progress_callback"]({"already_present": PRESENT})
if fails:
raise RuntimeError("later title failed")
return []
monkeypatch.setattr(download_worker, "perform_download", perform)
monkeypatch.setattr(download_worker, "relay_prompts", lambda *a: None)
payload = tmp_path / "payload.json"
progress = tmp_path / "progress.json"
scope = "api-" + "a" * 64
payload.write_text(
json.dumps(
{
"job_id": "test",
"service": "EXAMPLE",
"title_id": "example-1",
"archive_scope": scope,
"parameters": {"archive_scope": "cli"},
}
)
)
assert download_worker.main(["worker", str(payload), str(tmp_path / "result.json"), str(progress)]) == int(fails)
assert seen["archive_scope"] == scope
assert json.loads(progress.read_text())["already_present"] == PRESENT
def test_api_options_default_off():
assert DEFAULT_DOWNLOAD_PARAMS["skip_existing"] is False
assert DEFAULT_DOWNLOAD_PARAMS["force"] is False
def test_manager_uses_owner_scope_and_keeps_already_present_in_history(monkeypatch, tmp_path):
payloads = []
class FakeWorker:
returncode = 0
async def wait(self, timeout):
return True
def read_progress(self):
return {"already_present": PRESENT}
def output(self):
return "", ""
async def result(self):
return WorkerResult(status="success")
async def close(self):
pass
async def spawn(payload):
payloads.append(payload)
return FakeWorker()
monkeypatch.setattr(dm.WorkerProcess, "spawn", spawn)
history = tmp_path / "api_history.jsonl"
monkeypatch.setattr(dm, "history_path", lambda: history)
manager = dm.DownloadQueueManager()
job = manager.create_job("EXAMPLE", "example-1", owner_key="test-owner", archive_scope="cli")
assert asyncio.run(manager.run_download_async(job)) == []
assert [p.archive_scope for p in payloads] == ["api-" + hashlib.sha256(b"test-owner").hexdigest()]
assert job.to_dict()["already_present"] == PRESENT
assert job.skipped_titles == []
job.status = dm.JobStatus.COMPLETED
dm.record_job_history(job)
assert json.loads(history.read_text())["already_present"] == PRESENT
def test_ownerless_job_has_no_archive_scope(monkeypatch):
payloads = []
async def spawn(payload):
payloads.append(payload)
raise RuntimeError("stop")
monkeypatch.setattr(dm.WorkerProcess, "spawn", spawn)
manager = dm.DownloadQueueManager()
with pytest.raises(RuntimeError, match="stop"):
asyncio.run(manager.run_download_async(manager.create_job("EXAMPLE", "example-1")))
assert payloads[0].archive_scope == "api-unowned"
def test_request_cannot_choose_archive_scope_or_credential_namespace(monkeypatch, tmp_path):
import unshackle.commands.dl as dl_module
from unshackle.core.api import handlers
from unshackle.core.services import Services
seen = {}
class Captured(Exception):
pass
class FakeDl:
cli = dl_module.dl.cli
def __init__(self, ctx, **kwargs):
pass
def result(self, **kwargs):
seen.update(scope=self.archive_scope, cache=self.archive_cache)
raise Captured
class FakeService:
cli = click.Command("svc", callback=lambda title: object())
monkeypatch.setattr(dl_module, "dl", FakeDl)
monkeypatch.setattr(Services, "get_path", staticmethod(lambda s: tmp_path))
monkeypatch.setattr(Services, "load", staticmethod(lambda s: FakeService))
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
monkeypatch.setattr(config.directories, "cache", tmp_path / "cache")
monkeypatch.setattr(config, "credentials", {})
scope = "api-" + "c" * 64
with pytest.raises(Captured):
dm.perform_download(
"test",
"EXAMPLE",
"example-1",
{"archive_scope": "cli", "archive_cache": "/not-allowed", "credential": "test-user:test-password"},
archive_scope=scope,
)
assert seen == {"scope": scope, "cache": tmp_path / "cache"}
assert Path(config.directories.cache) != tmp_path / "cache"
+1 -1
View File
@@ -542,7 +542,7 @@ import sys, time
from unshackle.core import process_exit
from unshackle.core.api import download_worker
def perform(*args, progress_callback):
def perform(*args, progress_callback, **kwargs):
process_exit.ends.add(lambda: time.sleep(0.3))
progress_callback({"title": "EXAMPLE"})
print("ready", flush=True)