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
+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)