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": {}})
-35
View File
@@ -1,7 +1,6 @@
from __future__ import annotations
import inspect
import logging
import click
import pytest
@@ -16,7 +15,6 @@ from unshackle.core.dl_options import (
DL_OPTIONS,
FORWARDED_DL_PARAMS,
cast_dl_params,
forwarded_dl_params,
remote_dl_params,
)
from unshackle.core.tracks import Audio, Subtitle, Video
@@ -39,19 +37,6 @@ def test_the_openapi_yaml_names_each_api_dl_option_and_no_other():
assert properties.keys() - DEFAULT_DOWNLOAD_PARAMS.keys() == {"service", "title_id", "remote", "client_name", "cdm"}
def test_the_server_reads_back_what_a_remote_client_forwards():
params = {
"lang": ["orig", "es-419"],
"v_lang": [],
"a_lang": ["en"],
"s_lang": ["all"],
"acodec": [Audio.Codec.EC3],
"forced_subs": True,
"exact_lang": True,
}
assert forwarded_dl_params({"dl_params": remote_dl_params(params)}) == params
def test_api_defaults_cast_to_the_dl_defaults():
"""``wanted`` keeps its API default of no keys, which dl reads as every title, like the CLI's None."""
ctx = click.Context(dl.cli)
@@ -121,26 +106,6 @@ def test_every_dl_option_reaches_dl_result():
}
def test_the_server_reads_the_forwarded_dl_params(caplog):
data = {
"dl_params": {"a_lang": "x", "acodec": ["ddp", "NOPE"], "exact_lang": 1, "forced_subs": True, "lang": ["en"]}
}
with caplog.at_level(logging.WARNING, logger="api"):
assert list(forwarded_dl_params(data).items()) == [
("lang", ["en"]),
("v_lang", []),
("a_lang", []),
("s_lang", ["all"]),
("acodec", [Audio.Codec.EC3]),
("forced_subs", True),
("exact_lang", False),
]
assert [(r.name, r.getMessage()) for r in caplog.records] == [
("api", "Ignoring dl_params.a_lang: it must be an array of strings"),
("api", "Ignoring unknown dl_params.acodec value: NOPE"),
]
@pytest.mark.parametrize(
"parent_params,sent",
[
+1 -1
View File
@@ -74,4 +74,4 @@ def test_a_remote_session_gets_quality_as_heights(monkeypatch: pytest.MonkeyPatc
def test_a_remote_session_refuses_a_malformed_quality(monkeypatch: pytest.MonkeyPatch, quality: str) -> None:
with pytest.raises(handlers.APIError) as exc:
session_params(monkeypatch, {"quality": quality})
assert exc.value.error_code == handlers.APIErrorCode.INVALID_INPUT
assert exc.value.error_code == handlers.APIErrorCode.INVALID_PARAMETERS
+3 -2
View File
@@ -21,6 +21,7 @@ from unshackle.core.api.input_bridge import InputBridge
from unshackle.core.cdm.client_relay import ClientDeviceCdm, answer_cdm_call
from unshackle.core.launch import served_context
from unshackle.core.remote_protocol import APIErrorCode, AuthStatus
from unshackle.core.run_plan import served_plan
from unshackle.core.utils.click_types import ContextData
pytestmark = pytest.mark.unit
@@ -174,7 +175,7 @@ def test_a_relaying_client_gets_a_stand_in_with_its_device_facts(monkeypatch: py
monkeypatch.setattr(
handlers,
"served_context",
lambda obj, params, keys: built.update(cdm=obj.cdm, config=obj.config, params={**params, **keys}),
lambda obj, plan, keys: built.update(cdm=obj.cdm, config=obj.config, params={**plan.params, **keys}),
)
monkeypatch.setattr(handlers.Services, "load", lambda tag: Declares)
monkeypatch.setattr(handlers, "instantiate_service", lambda *a, **k: "service")
@@ -502,7 +503,7 @@ def test_a_lent_device_without_the_vault_grant_asks_the_server_for_no_key() -> N
@pytest.mark.parametrize("params", [{}, {"quality": None}])
def test_every_service_context_defaults_quality_to_a_list(params: Any) -> None:
parent = served_context(ContextData(config={}, cdm=None, proxy_providers=[]), params, {})
parent = served_context(ContextData(config={}, cdm=None, proxy_providers=[]), served_plan(params), {})
assert parent.params["quality"] == []
@@ -365,17 +365,3 @@ async def test_search_unknown_service_raises_invalid_service() -> None:
with pytest.raises(APIError) as exc:
await search_handler({"service": "NOPE_THIS_IS_NOT_REAL_", "query": "x"}, None)
assert exc.value.error_code == APIErrorCode.INVALID_SERVICE
def test_resolve_vcodec_rejects_junk_as_invalid_input() -> None:
"""Session routes skip the download job admission, so a bad codec must be a 400, not a 500."""
from unshackle.core.api.handlers import resolve_vcodec
from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.tracks import Video
assert resolve_vcodec(["H265"]) == [Video.Codec.HEVC]
assert resolve_vcodec(None) is None
for junk in ("XVID", 5, [5]):
with pytest.raises(APIError) as exc:
resolve_vcodec(junk)
assert exc.value.error_code == APIErrorCode.INVALID_INPUT
+2 -2
View File
@@ -202,9 +202,9 @@ async def test_list_tracks_service_sees_dl_params(seen):
@pytest.mark.asyncio
async def test_search_service_gets_no_dl_params(seen):
async def test_search_service_sees_dl_params(seen):
await handlers.search_handler({"service": "EXAMPLE", "query": "q", "dl_params": {"a_lang": ["es-419"]}})
assert "a_lang" not in seen["parent_params"]
assert seen["parent_params"]["a_lang"] == ["es-419"]
@pytest.mark.asyncio
+12 -11
View File
@@ -178,7 +178,7 @@ def test_nested_dl_params_reach_the_parent_ctx(monkeypatch):
"v_lang": ["ja"],
"a_lang": ["es-419"],
"s_lang": ["ko"],
"acodec": ["EC3", "NOPE", "AAC"],
"acodec": ["EC3", "AAC"],
"forced_subs": True,
"exact_lang": True,
}
@@ -211,20 +211,21 @@ def test_a_service_lang_option_never_gets_the_dl_lang(monkeypatch):
assert "dl_params" in handlers.SESSION_TRANSPORT_KEYS
@pytest.mark.parametrize(
"dl_params",
[
"en",
{"lang": "en", "v_lang": "ja", "a_lang": {"x": 1}, "acodec": "EC3", "forced_subs": "yes", "exact_lang": "yes"},
{"lang": [1], "v_lang": [None], "a_lang": ["en", None], "acodec": [3], "forced_subs": 1, "exact_lang": 1},
],
)
def test_malformed_dl_params_are_ignored(monkeypatch, dl_params):
svc = _create_with_real_ctx(monkeypatch, {"dl_params": dl_params})
def test_dl_params_that_are_not_an_object_are_ignored(monkeypatch):
svc = _create_with_real_ctx(monkeypatch, {"dl_params": "en"})
selection = {k: svc.parent_params[k] for k in (*DL_DEFAULTS,)}
assert selection == DL_DEFAULTS
@pytest.mark.parametrize(
"dl_params", [{"a_lang": {"x": 1}}, {"acodec": ["EC3", "NOPE"]}, {"acodec": [3]}, {"forced_subs": "maybe"}]
)
def test_a_malformed_dl_param_is_refused(monkeypatch, dl_params):
with pytest.raises(handlers.APIError) as exc:
_create_with_real_ctx(monkeypatch, {"dl_params": dl_params})
assert exc.value.error_code is handlers.APIErrorCode.INVALID_PARAMETERS
def test_profile_reaches_the_parent_ctx_params(monkeypatch):
monkeypatch.setattr(key_policy, "load_service_config", lambda s: {})
monkeypatch.setattr(handlers, "load_full_cdm", lambda *a: None)
@@ -108,10 +108,10 @@ def test_above_the_cap_without_a_device_is_refused_at_create():
assert ei.value.details == {"reason": "server_cdm_max_height", "max_height": 1080}
def test_bad_quality_is_invalid_input():
def test_bad_quality_is_invalid_parameters():
with pytest.raises(APIError) as ei:
handlers.choose_session_cdm(KeyPolicy(USERS["flat"]), "EXAMPLE1", {"quality": ["best"]})
assert ei.value.error_code is APIErrorCode.INVALID_INPUT
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
@pytest.mark.parametrize(
@@ -249,10 +249,10 @@ def test_an_ultrawide_track_is_measured_as_the_smallest_quality_that_selects_it(
@pytest.mark.parametrize("quality", [[-1], [0], [1080, 0]])
def test_a_height_of_zero_or_less_is_invalid_input(quality):
def test_a_height_of_zero_or_less_is_invalid_parameters(quality):
with pytest.raises(APIError) as ei:
job_admission.enforce_download_gates({"service": "EXAMPLE1", "quality": quality}, request("flat"))
assert ei.value.error_code is APIErrorCode.INVALID_INPUT
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
def test_a_capped_download_job_cannot_set_best_available():