refactor(api): resolve service options once with requested_service_options

This commit is contained in:
imSp4rky
2026-11-28 13:44:57 -07:00
parent 32250f6f95
commit 63dd037ebd
4 changed files with 52 additions and 20 deletions
+4 -2
View File
@@ -498,8 +498,10 @@ Make a download job. It requires `service` and `title_id`. Every other field is
**Service options.** A service's own CLI options travel in the same body. Send them in a nested
`service_params` object, or as flat top-level keys. When the body has `service_params`, the server
reads service options only from it, and every flat key is a `dl` value. Without it, a flat key that
is also a `dl` option, such as `quality` or `lang`, stays a `dl` value. An option you leave out
reads service options only from it, and every flat key is a `dl` value. A name in `service_params`
can be the option's flag, such as `zone` for `--zone`, or its parameter name. Without
`service_params`, a flat key that is also a `dl` option, such as `quality` or `lang`, stays a `dl`
value, and the server logs a warning when the service has an option of the same name. An option you leave out
takes the default declared on the service's `cli` command, so the job matches the equivalent `dl`
run. The server checks each service option against that option's type, and a value it refuses gets
`400 INVALID_PARAMETERS`. `profile` at the top level always means the credential
@@ -156,6 +156,14 @@ def test_a_json_shape_click_cannot_convert_is_a_400(env, monkeypatch, name, valu
assert name in exc_info.value.message
def test_a_flat_dl_key_never_fills_a_service_option_of_the_same_name(env, monkeypatch):
def test_a_flat_dl_key_never_fills_a_service_option_of_the_same_name(env, monkeypatch, caplog):
use_cli(monkeypatch, click.Option(["--quality"], type=click.Choice(["SD", "HD"]), default="HD"))
with caplog.at_level("WARNING", logger="api"):
assert env(body={"quality": [1080]})["service_params"] == {}
assert "Ignoring flat 'quality' as a service option" in caplog.text
def test_a_flag_keyed_service_option_is_stored_under_its_dest_name(env, monkeypatch):
use_cli(monkeypatch, click.Option(["--zone", "zone_code"]), click.Option(["--2fa", "two_fa"]))
stored = env(body={"service_params": {"zone": "eu", "2fa": "123"}})["service_params"]
assert stored == {"zone_code": "eu", "two_fa": "123"}
+36 -14
View File
@@ -10,7 +10,7 @@ import time
import uuid
import zlib
from collections import Counter
from collections.abc import Callable, Iterable
from collections.abc import Callable, Iterable, Sequence
from collections.abc import Set as AbstractSet
from contextlib import suppress
from dataclasses import dataclass, field
@@ -171,6 +171,37 @@ def cast_or_refuse(params: Iterable[click.Parameter], ctx: Any, options: dict[st
) from e
def requested_service_options(
data: dict[str, Any], cli_params: Sequence[click.Parameter], transport_keys: AbstractSet[str]
) -> tuple[dict[str, Any], list[str]]:
"""The ``service_options`` in ``data`` under their dest names, and the flat keys left as dl values.
A ``service_params`` entry can use an option's flag spelling: ``zone`` for ``--zone`` with dest ``zone_code``.
"""
names = {p.name for p in cli_params if p.name and p.name != "title"}
nested = data.get("service_params")
if isinstance(nested, dict):
flagged = {o.lstrip("-/").replace("-", "_").lower(): p.name for p in cli_params for o in p.opts}
renamed = {flagged.get(k, k): v for k, v in nested.items() if k not in names}
data = {**data, "service_params": {**renamed, **nested}}
ignored = (
sorted(
k
for k in names & transport_keys & data.keys()
if k not in FLAT_DL_KEYS - {"profile"} and data.get(k) is not None
)
if nested is None
else []
)
return service_options(data, names, transport_keys), ignored
def warn_ignored(ignored: Iterable[str]) -> None:
"""Log each flat key that ``requested_service_options`` kept as a dl value."""
for k in ignored:
log.warning(f"Ignoring flat '{sanitize_log(k)}' as a service option, send it under 'service_params'")
def instantiate_service(
parent_ctx: Any,
service_module: Any,
@@ -178,24 +209,15 @@ def instantiate_service(
data: dict[str, Any] | None = None,
transport_keys: AbstractSet[str] = frozenset(),
) -> Any:
"""Instantiate a service by invoking its click cli with the ``service_options`` in ``data``.
"""Instantiate a service by invoking its click cli with the ``requested_service_options`` in ``data``.
Click fills the option defaults, but ``ctx.invoke`` passes the given kwargs uncast, so each value
goes through its option's type here: JSON or a remote client's str-typed stub can send "1" for an int.
"""
cli_params = getattr(getattr(service_module, "cli", None), "params", []) or []
names = {p.name for p in cli_params if getattr(p, "name", None) and p.name != "title"}
data = data or {}
nested = data.get("service_params")
if isinstance(nested, dict):
flagged = {click.Option(p.opts).name: p.name for p in cli_params if p.param_type_name == "option" and p.opts}
renamed = {flagged.get(k, k): v for k, v in nested.items() if k not in names}
data = {**data, "service_params": {**renamed, **nested}}
extras = cast_or_refuse(cli_params, parent_ctx, service_options(data, names, transport_keys))
if data and data.get("service_params") is None:
for k in names & transport_keys & data.keys():
if k not in ("service", "title_id", "proxy", "no_proxy") and data.get(k) is not None:
log.warning(f"Ignoring flat '{sanitize_log(k)}' as a service option, send it under 'service_params'")
options, ignored = requested_service_options(data or {}, cli_params, transport_keys)
extras = cast_or_refuse(cli_params, parent_ctx, options)
warn_ignored(ignored)
return parent_ctx.invoke(service_module.cli, title=title, **extras)
+2 -2
View File
@@ -18,7 +18,6 @@ from unshackle.core.remote_protocol import APIErrorCode
from unshackle.core.run_plan import PlanError, api_plan
from unshackle.core.services import ROUTING_PARAMS, Services
from unshackle.core.utils.collections import as_list, ci_get
from unshackle.core.utils.service_params import service_options
ENVELOPE_KEYS = ("service", "title_id", "owner_key")
log = logging.getLogger("api")
@@ -97,8 +96,9 @@ def job_spec(data: dict[str, Any], server: str | None, request: web.Request | No
# when the worker builds the service. A remote service applies its own on the remote server.
cli_params = None if server else getattr(getattr(Services.load(service), "cli", None), "params", None)
if cli_params is not None:
options = service_options(data, {param.name for param in cli_params}, handlers.DL_TRANSPORT_KEYS)
options, ignored = handlers.requested_service_options(data, cli_params, handlers.DL_TRANSPORT_KEYS)
handlers.cast_or_refuse(cli_params, click.Context(click.Command(service)), options)
handlers.warn_ignored(ignored)
params["service_params"] = options
params["server_proxy"] = handlers.request_policy(request).allows("server_proxy")
return JobSpec(service, data["title_id"], params)