forked from kenzuya/unshackle
fix(api): check serve and service dl defaults at job admission
This commit is contained in:
@@ -538,6 +538,8 @@ profile, never a service's own `--profile` option.
|
|||||||
|
|
||||||
On the server, unshackle merges the effective parameters in this order: defaults → `serve:` config overrides → service-specific defaults → your request body.
|
On the server, unshackle merges the effective parameters in this order: defaults → `serve:` config overrides → service-specific defaults → your request body.
|
||||||
|
|
||||||
|
The server checks each `serve:` and `services.<TAG>.dl` value that a job uses with the rules of a request body. A bad value refuses the job with `400 INVALID_PARAMETERS`, and the message starts with the config block, for example `serve: workers must be a positive integer`. A value that your request body replaces is not checked.
|
||||||
|
|
||||||
| Status | Error code | Meaning |
|
| Status | Error code | Meaning |
|
||||||
| --- | --- | --- |
|
| --- | --- | --- |
|
||||||
| `202` | - | Job queued. |
|
| `202` | - | Job queued. |
|
||||||
|
|||||||
@@ -105,7 +105,9 @@ dl:
|
|||||||
The [`serve`](services.md#serve) block accepts most of the same `dl` option keys at its top level
|
The [`serve`](services.md#serve) block accepts most of the same `dl` option keys at its top level
|
||||||
to set server-wide download defaults for every request it handles. The API ignores the
|
to set server-wide download defaults for every request it handles. The API ignores the
|
||||||
config keys it does not know there, `speed_limit` for example. `serve` has its own
|
config keys it does not know there, `speed_limit` for example. `serve` has its own
|
||||||
`global_speed_limit`.
|
`global_speed_limit`. A `serve` or `services.<TAG>.dl` value that the API refuses in a
|
||||||
|
request body, `workers: 0` for example, makes each job that uses it fail at submit with
|
||||||
|
`400 INVALID_PARAMETERS`.
|
||||||
|
|
||||||
## `continue_downloads`
|
## `continue_downloads`
|
||||||
|
|
||||||
|
|||||||
@@ -84,6 +84,50 @@ def test_a_serve_default_that_dl_refuses_with_the_request_is_refused_at_create(s
|
|||||||
assert "--include-sample" in ei.value.message
|
assert "--include-sample" in ei.value.message
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
("serve", "services", "body", "prefix"),
|
||||||
|
[
|
||||||
|
({"workers": 0}, {}, {}, "serve: workers"),
|
||||||
|
({}, {"EXAMPLE": {"dl": {"imdb_id": "nope"}}}, {}, "services.EXAMPLE.dl: imdb_id"),
|
||||||
|
({"no_subs": "maybe"}, {}, {}, "serve: Invalid no_subs"),
|
||||||
|
({"wanted": "zz"}, {}, {}, "serve: Invalid wanted"),
|
||||||
|
({"all_drm": True}, {}, {"cdm": "dev"}, "all_drm needs a CDM"),
|
||||||
|
],
|
||||||
|
)
|
||||||
|
def test_a_bad_config_default_is_refused_at_admission(server, monkeypatch, serve, services, body, prefix):
|
||||||
|
monkeypatch.setattr(handlers.config, "serve", serve)
|
||||||
|
monkeypatch.setattr(handlers.config, "services", services)
|
||||||
|
with pytest.raises(APIError) as ei:
|
||||||
|
admit(body)
|
||||||
|
assert ei.value.error_code is APIErrorCode.INVALID_PARAMETERS
|
||||||
|
assert ei.value.message.startswith(prefix)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_bad_config_default_that_a_later_layer_replaces_is_not_read(server, monkeypatch):
|
||||||
|
monkeypatch.setattr(handlers.config, "serve", {"workers": 0, "imdb_id": "nope"})
|
||||||
|
monkeypatch.setattr(handlers.config, "services", {"EXAMPLE": {"dl": {"workers": 4, "tmdb_id": -3}}})
|
||||||
|
params = admit({"imdb_id": "tt1", "tmdb_id": None}).params
|
||||||
|
assert (params["workers"], params["imdb_id"]) == (4, "tt1")
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_relayed_job_does_not_read_the_local_service_defaults(server, monkeypatch):
|
||||||
|
async def relay(data, request):
|
||||||
|
return "box", {"tag": "EXAMPLE"}, {**data, "service": "EXAMPLE"}
|
||||||
|
|
||||||
|
monkeypatch.setattr(handlers, "relay_target", relay)
|
||||||
|
monkeypatch.setattr(handlers.config, "services", {"EXAMPLE": {"dl": {"workers": 0}}})
|
||||||
|
assert admit({"remote": "box"}).params["workers"] is None
|
||||||
|
|
||||||
|
|
||||||
|
def test_config_defaults_in_their_cli_form_pass_and_are_stored_raw(server, monkeypatch):
|
||||||
|
serve = {"lang": "en", "a_lang": "orig,-es", "latest_episodes": "3", "output_dir": "/elsewhere", "profile": "my p"}
|
||||||
|
monkeypatch.setattr(handlers.config, "serve", serve)
|
||||||
|
monkeypatch.setattr(handlers.config, "services", {"EXAMPLE": {"dl": {"quality": "1080p", "no_subs": "yes"}}})
|
||||||
|
params = admit({}).params
|
||||||
|
assert {k: params[k] for k in serve} == serve
|
||||||
|
assert (params["quality"], params["no_subs"]) == ("1080p", "yes")
|
||||||
|
|
||||||
|
|
||||||
def test_a_relayed_retry_resubmits_only_what_the_client_sent(server, monkeypatch):
|
def test_a_relayed_retry_resubmits_only_what_the_client_sent(server, monkeypatch):
|
||||||
async def relay(data, request):
|
async def relay(data, request):
|
||||||
return "box", {"tag": "EXAMPLE"}, {**data, "service": "EXAMPLE"}
|
return "box", {"tag": "EXAMPLE"}, {**data, "service": "EXAMPLE"}
|
||||||
|
|||||||
@@ -13,9 +13,9 @@ from unshackle.core.api import handlers
|
|||||||
from unshackle.core.api.download_manager import plan_keys, stamped_keys
|
from unshackle.core.api.download_manager import plan_keys, stamped_keys
|
||||||
from unshackle.core.api.errors import APIError
|
from unshackle.core.api.errors import APIError
|
||||||
from unshackle.core.config import config
|
from unshackle.core.config import config
|
||||||
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_API_NAMES
|
from unshackle.core.dl_options import DEFAULT_DOWNLOAD_PARAMS, DL_OPTION_ALIASES, DL_OPTION_API_NAMES
|
||||||
from unshackle.core.remote_protocol import APIErrorCode
|
from unshackle.core.remote_protocol import APIErrorCode
|
||||||
from unshackle.core.run_plan import PlanError, api_plan
|
from unshackle.core.run_plan import PlanError, api_plan, cast_plan
|
||||||
from unshackle.core.services import ROUTING_PARAMS, Services
|
from unshackle.core.services import ROUTING_PARAMS, Services
|
||||||
from unshackle.core.utils.collections import as_list, ci_get
|
from unshackle.core.utils.collections import as_list, ci_get
|
||||||
|
|
||||||
@@ -81,10 +81,13 @@ def job_spec(data: dict[str, Any], server: str | None, request: web.Request | No
|
|||||||
sent = {k: v for k, v in data.items() if k not in ENVELOPE_KEYS}
|
sent = {k: v for k, v in data.items() if k not in ENVELOPE_KEYS}
|
||||||
serve_defaults = {k: v for k, v in (config.serve or {}).items() if k in DEFAULT_DOWNLOAD_PARAMS and v is not None}
|
serve_defaults = {k: v for k, v in (config.serve or {}).items() if k in DEFAULT_DOWNLOAD_PARAMS and v is not None}
|
||||||
# A relayed job gets no local service overrides, so none of its keys may count as defaults.
|
# A relayed job gets no local service overrides, so none of its keys may count as defaults.
|
||||||
|
service_defaults = {} if server else service_dl_defaults(service)
|
||||||
|
check_defaults("serve", serve_defaults, {**service_defaults, **sent}, data)
|
||||||
|
check_defaults(f"services.{service}.dl", service_defaults, sent, data)
|
||||||
params = {
|
params = {
|
||||||
**DEFAULT_DOWNLOAD_PARAMS,
|
**DEFAULT_DOWNLOAD_PARAMS,
|
||||||
**serve_defaults,
|
**serve_defaults,
|
||||||
**({} if server else service_dl_defaults(service)),
|
**service_defaults,
|
||||||
**sent,
|
**sent,
|
||||||
"client_keys": sorted(sent),
|
"client_keys": sorted(sent),
|
||||||
}
|
}
|
||||||
@@ -148,11 +151,6 @@ def check_parameters(data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
raise invalid("output_dir must be a path under the server's downloads directory.", data)
|
raise invalid("output_dir must be a path under the server's downloads directory.", data)
|
||||||
checked["output_dir"] = str(target)
|
checked["output_dir"] = str(target)
|
||||||
|
|
||||||
if data.get("all_drm") and data.get("cdm"):
|
|
||||||
raise invalid(
|
|
||||||
"all_drm needs a CDM for each DRM system, so it cannot be used with cdm, which selects one device.", data
|
|
||||||
)
|
|
||||||
|
|
||||||
for name in POSITIVE_INT_KEYS:
|
for name in POSITIVE_INT_KEYS:
|
||||||
value = data.get(name)
|
value = data.get(name)
|
||||||
if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value <= 0):
|
if value is not None and (isinstance(value, bool) or not isinstance(value, int) or value <= 0):
|
||||||
@@ -184,10 +182,32 @@ def check_parameters(data: dict[str, Any]) -> dict[str, Any]:
|
|||||||
return checked
|
return checked
|
||||||
|
|
||||||
|
|
||||||
|
def check_defaults(source: str, defaults: dict[str, Any], overrides: dict[str, Any], data: dict[str, Any]) -> None:
|
||||||
|
"""INVALID_PARAMETERS, prefixed with the config block ``source``, for a default that a request body could not send.
|
||||||
|
|
||||||
|
Only the defaults that ``overrides`` does not replace are read, as click reads a default only for an option not
|
||||||
|
given. They are read as dl casts them, so a value in the CLI form of the config (``lang: en``) passes. The
|
||||||
|
operator's ``output_dir`` and ``profile`` are not held to the client rules.
|
||||||
|
"""
|
||||||
|
used = {k: v for k, v in defaults.items() if k not in overrides and k not in ("output_dir", "profile")}
|
||||||
|
if not used:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
cast = cast_plan(used, ()).params
|
||||||
|
check_parameters({k: cast[DL_OPTION_ALIASES.get(k, k)] for k in used})
|
||||||
|
except (PlanError, APIError) as e:
|
||||||
|
raise invalid(f"{source}: {e.message}", data) from None
|
||||||
|
|
||||||
|
|
||||||
def check_plan(params: dict[str, Any]) -> None:
|
def check_plan(params: dict[str, Any]) -> None:
|
||||||
"""INVALID_PARAMETERS when dl would refuse the job's merged parameters, as the worker plans them."""
|
"""INVALID_PARAMETERS when dl would refuse the job's merged parameters, as the worker plans them, or when they
|
||||||
|
pair ``all_drm`` with a ``cdm``."""
|
||||||
from unshackle.commands.dl import subtitle_look
|
from unshackle.commands.dl import subtitle_look
|
||||||
|
|
||||||
|
if params.get("all_drm") and params.get("cdm"):
|
||||||
|
raise invalid(
|
||||||
|
"all_drm needs a CDM for each DRM system, so it cannot be used with cdm, which selects one device.", params
|
||||||
|
)
|
||||||
try:
|
try:
|
||||||
plan = api_plan(params, plan_keys(params)).params
|
plan = api_plan(params, plan_keys(params)).params
|
||||||
except PlanError as e:
|
except PlanError as e:
|
||||||
|
|||||||
@@ -46,6 +46,9 @@ def cast_service_options(params: Iterable[click.Parameter], ctx: Any, options: d
|
|||||||
raise click.BadParameter("expected a number, not a boolean", ctx=ctx, param=param)
|
raise click.BadParameter("expected a number, not a boolean", ctx=ctx, param=param)
|
||||||
try:
|
try:
|
||||||
cast[k] = param.type_cast_value(ctx, v)
|
cast[k] = param.type_cast_value(ctx, v)
|
||||||
|
except click.BadParameter as e:
|
||||||
|
e.param = e.param or param
|
||||||
|
raise
|
||||||
except (TypeError, ValueError, AttributeError, OverflowError) as e:
|
except (TypeError, ValueError, AttributeError, OverflowError) as e:
|
||||||
raise click.BadParameter(f"not a valid {param.type.name} value", ctx=ctx, param=param) from e
|
raise click.BadParameter(f"not a valid {param.type.name} value", ctx=ctx, param=param) from e
|
||||||
return cast
|
return cast
|
||||||
|
|||||||
Reference in New Issue
Block a user