refactor(api): give every served service its dl options from the run plan

This commit is contained in:
imSp4rky
2026-11-28 14:02:44 -07:00
parent 63dd037ebd
commit 053d83874d
18 changed files with 285 additions and 205 deletions
+6
View File
@@ -85,6 +85,12 @@ def test_language_range_passes_exclusion_tokens_through(value, expected):
assert LANGUAGE_RANGE.convert(value) == expected
@pytest.mark.parametrize("value", [[None], ["en", 1], [{"x": "en"}]])
def test_language_range_refuses_a_list_item_that_is_not_a_string(value):
with pytest.raises(click.BadParameter):
LANGUAGE_RANGE.convert(value)
def parse(*tokens: str) -> list[str]:
return SeasonRange().parse_tokens(*tokens)
+58
View File
@@ -146,3 +146,61 @@ def test_each_builder_sets_its_launch_keys(
) -> None:
params = build(monkeypatch, tmp_path).params
assert {key: params[key] for key in LaunchKeys.__annotations__ if key in params} == expected
def served_paths(monkeypatch: pytest.MonkeyPatch) -> dict[str, Callable[[dict], click.Context]]:
"""Each served builder, as a function of the request body to the parent context its service gets."""
from unshackle.core import remote_service
handlers, seen = rest_handlers(monkeypatch)
monkeypatch.setattr(remote_service, "make_remote_service", lambda ctx, *a, **k: ctx)
def instantiate(parent_ctx: click.Context, *a: Any) -> Any:
seen["ctx"] = parent_ctx
return SimpleNamespace(authenticate=lambda cookies, credential: None, search=lambda: iter(()))
monkeypatch.setattr(handlers, "instantiate_service", instantiate)
def captured(call: Callable[[], Any]) -> click.Context:
call()
return seen["ctx"]
return {
"relay": lambda data: handlers.relay_service(data, "server", None, "t").parent,
"list": lambda data: captured(lambda: handlers.setup_list_service(data, "EXAMPLE", None, "t")),
"search": lambda data: captured(lambda: handlers.run_service_search(data, "EXAMPLE", "query")),
"session": lambda data: captured(
lambda: handlers.create_service_instance("EXAMPLE", "t", data, None, [], None)
),
}
@pytest.mark.parametrize("path", ["relay", "list", "search", "session"])
def test_every_served_path_takes_its_dl_options_from_the_served_plan(
monkeypatch: pytest.MonkeyPatch, path: str
) -> None:
from unshackle.core.tracks import Video
data = {"service": "EXAMPLE", "service_params": {}, "range_": ["DV"], "dl_params": {"a_lang": ["en"]}}
params = served_paths(monkeypatch)[path](data).params
assert (params["range_"], params["a_lang"], params["served"]) == ([Video.Range.DV], ["en"], True)
@pytest.mark.parametrize("path", ["relay", "list", "search", "session"])
def test_every_served_path_refuses_an_unknown_range(monkeypatch: pytest.MonkeyPatch, path: str) -> None:
from unshackle.core.api.errors import APIError
from unshackle.core.remote_protocol import APIErrorCode
with pytest.raises(APIError) as exc:
served_paths(monkeypatch)[path]({"service": "EXAMPLE", "service_params": {}, "range_": ["NOPE"]})
assert exc.value.error_code is APIErrorCode.INVALID_PARAMETERS
def test_a_relay_session_is_pooled_per_dl_selection() -> None:
from unshackle.core.api.handlers import remote_pool_key
data = {"service": "EXAMPLE", "dl_params": {"a_lang": ["en"]}}
keys = {
remote_pool_key(d, "server", {}, None, "t", None) for d in (data, {**data, "dl_params": {"a_lang": ["fr"]}})
}
assert len(keys) == 2
+81 -3
View File
@@ -1,4 +1,4 @@
"""The run plan: one check of the dl options for the CLI and the REST download job."""
"""The run plan: one check of the dl options for the CLI and the REST download job, one cast for a served service."""
from __future__ import annotations
@@ -11,9 +11,10 @@ from click.core import ParameterSource
from unshackle.commands.dl import dl
from unshackle.core.api.errors import categorize_exception
from unshackle.core.config import config
from unshackle.core.dl_options import remote_dl_params
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.run_plan import PlanError, api_plan, bitrate_range, check_options
from unshackle.core.tracks import Video
from unshackle.core.run_plan import PlanError, api_plan, bitrate_range, check_options, served_plan
from unshackle.core.tracks import Audio, Video
def cli_params(*args: str) -> dict[str, Any]:
@@ -107,3 +108,80 @@ def test_dl_checks_the_plan_before_the_service_loads(monkeypatch: pytest.MonkeyP
monkeypatch.setattr(config, "output_template", {"movies": "{title}"})
with pytest.raises(PlanError, match="--sample and --include-sample"):
dl.cli.main(["--sample", "--include-sample", "EXAMPLE", "t"], standalone_mode=False)
def test_the_served_plan_reads_what_a_remote_client_sends() -> None:
parent = {
"lang": ["orig", "es-419"],
"v_lang": [],
"a_lang": ["en"],
"s_lang": ["all"],
"acodec": [Audio.Codec.EC3],
"forced_subs": True,
"exact_lang": True,
}
data = {
"range_": ["DV", "HDR10P"],
"vcodec": ["HEVC"],
"quality": [720, 1080],
"best_available": True,
"generate_dv": True,
"no_proxy": True,
"dl_params": remote_dl_params(parent),
"service_params": {},
}
plan = served_plan(data, "http://proxy", "work")
assert plan.params["range_"] == [Video.Range.DV, Video.Range.HDR10P]
assert plan.params["vcodec"] == [Video.Codec.HEVC]
assert plan.params["quality"] == [1080, 720]
assert {k: plan.params[k] for k in ("best_available", "generate_dv", "no_proxy")} == dict.fromkeys(
("best_available", "generate_dv", "no_proxy"), True
)
assert {k: plan.params[k] for k in parent} == parent
assert (plan.params["proxy"], plan.params["profile"]) == ("http://proxy", "work")
assert plan.sources["range_"] is ParameterSource.COMMANDLINE
assert plan.sources["proxy"] is ParameterSource.COMMANDLINE
assert plan.sources["workers"] is ParameterSource.DEFAULT
def test_the_served_plan_gives_an_old_client_the_dl_defaults() -> None:
params = served_plan({}).params
assert params["range_"] == [Video.Range.SDR]
assert (params["vcodec"], params["quality"], params["acodec"]) == ([], [], [])
assert (params["lang"], params["s_lang"]) == (["orig"], ["all"])
assert (params["forced_subs"], params["exact_lang"], params["no_proxy"]) == (False, False, False)
def test_dl_params_set_only_the_options_a_remote_client_forwards() -> None:
data = {"dl_params": {"proxy": "http://other", "no_cache": True, "range": ["DV"], "lang": ["en"]}}
params = served_plan(data, "http://server").params
assert (params["proxy"], params["no_cache"], params["range_"]) == ("http://server", False, [Video.Range.SDR])
assert params["lang"] == ["en"]
def test_a_flat_key_counts_only_when_it_cannot_be_a_service_option() -> None:
assert served_plan({"quality": "UHD"}).params["quality"] == []
assert served_plan({"quality": [1080]}, flat={"quality"}).params["quality"] == [1080]
assert served_plan({"quality": [1080], "service_params": {}}).params["quality"] == [1080]
@pytest.mark.parametrize(("value", "expected"), [("false", True), (1, True), (0, False), (None, False)])
def test_no_proxy_counts_by_truth_value_as_the_proxy_gate_reads_it(value: Any, expected: bool) -> None:
assert served_plan({"no_proxy": value}).params["no_proxy"] is expected
@pytest.mark.parametrize(
("data", "key"),
[
({"range_": ["SDR", "NOPE"]}, "range"),
({"vcodec": ["NOPE"]}, "vcodec"),
({"quality": ["best"]}, "quality"),
({"quality": [1080, 0]}, "quality"),
({"dl_params": {"acodec": ["NOPE"]}}, "acodec"),
({"dl_params": {"lang": [None, {"x": 1}]}}, "lang"),
({"dl_params": {"a_lang": [1]}}, "a_lang"),
],
)
def test_the_served_plan_refuses_an_unknown_value(data: dict[str, Any], key: str) -> None:
with pytest.raises(PlanError, match=f"Invalid {key}"):
served_plan({**data, "service_params": {}})