feat(serve): relay approval messages to jobs and proxy remote downloads

A REST job shows a wait_for_approval message as its notice field. search, list-titles and list-tracks fail at once on a login that needs the user. A remote client downloads through the --proxy it sends.
This commit is contained in:
imSp4rky
2026-10-07 11:15:16 -06:00
parent 5b0369e63a
commit 09cae2ec3f
16 changed files with 233 additions and 28 deletions
+6
View File
@@ -126,6 +126,8 @@ class DownloadJob:
# Prompt a service raised through prompt_user() and waits on; answered by submit_input().
input_prompt: Optional[str] = None
# Message a service shows through show_notice() while it waits for an approval; needs no answer.
notice: Optional[str] = None
# Subtitles skipped under skip_subtitle_errors (non-fatal). Each entry is a dl.SkippedSubtitle
# dict (id / language / title) so a client can report which weren't available.
@@ -160,6 +162,7 @@ class DownloadJob:
"speed": self.speed,
"skipped_subtitles": self.skipped_subtitles,
"input_prompt": self.input_prompt,
"notice": self.notice,
}
if include_full_details:
@@ -1109,6 +1112,8 @@ class DownloadQueueManager:
job.speed = str(progress_data["speed"])
if "input_prompt" in progress_data:
job.input_prompt = progress_data["input_prompt"]
if "notice" in progress_data:
job.notice = progress_data["notice"]
if progress_data.get("skipped_subtitles"):
job.skipped_subtitles = progress_data["skipped_subtitles"]
if "progress" in progress_data:
@@ -1195,6 +1200,7 @@ class DownloadQueueManager:
self._download_processes.pop(job.job_id, None)
job.input_prompt = None
job.notice = None
temp_paths = self._job_temp_files.pop(job.job_id, {})
for path in temp_paths.values():
+3 -2
View File
@@ -16,7 +16,7 @@ from typing import Any, Callable, Dict
from uuid import uuid4
from unshackle.core.api.input_bridge import AUTH_INPUT_TIMEOUT
from unshackle.core.console import set_prompt_handler
from unshackle.core.console import set_notice_handler, set_prompt_handler
from .download_manager import perform_download
@@ -64,7 +64,7 @@ def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
The parent writes each answer as one JSON string per line, so an answer can hold a newline. The reader
uses unbuffered stdin: a daemon thread blocked in ``sys.stdin.buffer`` aborts the interpreter at shutdown.
Prompts go out one at a time, and a prompt discards answers that arrived before it, such as a late
answer to a prompt that timed out.
answer to a prompt that timed out. A show_notice() message goes out as ``notice`` progress and needs no answer.
"""
answers: queue.Queue[str] = queue.Queue()
one_prompt = threading.Lock()
@@ -92,6 +92,7 @@ def relay_prompts(progress_callback: Callable[[Dict[str, Any]], None]) -> None:
progress_callback({"input_prompt": None})
set_prompt_handler(ask)
set_notice_handler(lambda message: progress_callback({"notice": message}))
def main(argv: list[str]) -> int:
+3 -1
View File
@@ -20,7 +20,7 @@ from aiohttp import web
from unshackle.core.api.compression import safe_inflate
from unshackle.core.api.errors import APIError, APIErrorCode, categorize_exception, handle_api_exception
from unshackle.core.api.input_bridge import AuthStatus, InputBridge
from unshackle.core.api.input_bridge import AuthStatus, InputBridge, NoUserBridge
from unshackle.core.api.sanitize import MAX_SESSION_CACHE_KEYS, safe_cache_key, sanitize_log
from unshackle.core.api.session_log import SessionLogBuffer, SessionLogMirror, capture_service_logs
from unshackle.core.api.session_store import SessionStore
@@ -443,6 +443,7 @@ def setup_list_service(
elif request_cache is not None:
client_login = cookies is not None or credential is not None
request_cache.attach(service_instance, data, normalized_service, request, client_login)
service_instance._input_bridge = NoUserBridge()
service_instance.authenticate(cookies, credential)
return service_instance
@@ -503,6 +504,7 @@ def run_service_search(
elif request_cache is not None:
client_login = cookies is not None or credential is not None
request_cache.attach(service_instance, data, normalized_service, request, client_login)
service_instance._input_bridge = NoUserBridge()
service_instance.authenticate(cookies, credential)
results: List[Dict[str, Any]] = []
+20 -4
View File
@@ -185,11 +185,11 @@ class InputBridge:
self._picked_up.set()
self._response_ready.set()
@property
def cancelled(self) -> bool:
"""``True`` once the server cancelled the bridge, so a login loop must stop."""
def ensure_active(self) -> None:
"""Raise RuntimeError once the server cancelled the bridge, so a login loop stops."""
with self._lock:
return self._cancelled
if self._cancelled:
raise RuntimeError("Session was cancelled")
@property
def status(self) -> AuthStatus:
@@ -200,3 +200,19 @@ class InputBridge:
def status(self, value: AuthStatus) -> None:
with self._lock:
self._status = value
NO_USER_MESSAGE = (
"This login needs the user, and this request cannot reach the user. "
"Start a download job or a remote session to complete the authentication"
)
class NoUserBridge(InputBridge):
"""Bridge for a request with no channel to the user: a login step that needs the user fails at once."""
def request_input(self, prompt: str, timeout: float = AUTH_INPUT_TIMEOUT) -> str:
raise RuntimeError(NO_USER_MESSAGE)
def ensure_active(self) -> None:
raise RuntimeError(NO_USER_MESSAGE)
+2 -1
View File
@@ -1375,7 +1375,8 @@ async def download_job_input(request: web.Request) -> web.Response:
description: >
Submit the answer to the prompt a running job waits on (an OTP code, a PIN, a device-code
confirmation). The job shows the prompt in its `input_prompt` field and in its SSE `progress`
events. The job fails if nobody answers within the prompt timeout.
events. The job fails if nobody answers within the prompt timeout. A job that waits for an
approval on another device shows the message in its `notice` field, which takes no answer.
parameters:
- name: job_id
in: path
+17
View File
@@ -490,6 +490,21 @@ def prompt_user(prompt: str) -> str:
return console.input(body)
_notice_handler: Optional[Callable[[Optional[str]], None]] = None
def set_notice_handler(handler: Optional[Callable[[Optional[str]], None]]) -> None:
"""Route every :func:`show_notice` call to *handler*, for a process whose log output no user reads."""
global _notice_handler
_notice_handler = handler
def show_notice(message: Optional[str]) -> None:
"""Give *message* to the notice handler, or None to clear it. Without a handler this does nothing."""
if _notice_handler is not None:
_notice_handler(message)
__all__ = (
"ComfyLogRenderer",
"ComfyRichHandler",
@@ -501,5 +516,7 @@ __all__ = (
"listing_table",
"print_wide",
"prompt_user",
"set_notice_handler",
"set_prompt_handler",
"show_notice",
)
+3
View File
@@ -1020,6 +1020,9 @@ class RemoteService:
if create_data.get("proxy") and is_loopback(create_data["proxy"]) and not is_loopback(self.client.server_url):
# the local CLI resolves the proxy, so a local-only URI is useless to a server elsewhere
raise click.ClickException("That proxy is on your machine, so --remote cannot use it.")
local_proxy = None if no_proxy else (proxy or create_data.get("proxy"))
if local_proxy:
self._session.proxies["all"] = local_proxy
if not no_proxy and not proxy and client_region:
create_data["client_region"] = client_region
+17 -12
View File
@@ -19,7 +19,7 @@ from rich.rule import Rule
from unshackle.core.cacher import Cacher
from unshackle.core.config import config
from unshackle.core.console import console, prompt_user
from unshackle.core.console import console, prompt_user, show_notice
from unshackle.core.constants import AnyTrack
from unshackle.core.credential import Credential
from unshackle.core.drm import DRM_T
@@ -489,20 +489,25 @@ class Service(metaclass=ABCMeta):
"""Show ``message``, then call ``check`` until it returns a value.
Use it for a login that the user approves on another device, such as a pair code.
``check`` returns None while the approval is pending. Raises TimeoutError after
``timeout`` seconds, and RuntimeError when the remote session no longer exists.
``check`` returns None while the approval is pending, and must return within a few
seconds. Raises TimeoutError after ``timeout`` seconds, and RuntimeError when the
remote session no longer exists. A REST download job shows ``message`` as its ``notice``.
"""
self.log.info(message)
show_notice(message)
deadline = time.monotonic() + timeout
while True:
if self._input_bridge is not None and self._input_bridge.cancelled:
raise RuntimeError("Session was cancelled")
result = check()
if result is not None:
return result
if time.monotonic() + interval >= deadline:
raise TimeoutError(f"No approval within {timeout:.0f}s")
time.sleep(interval)
try:
while True:
if self._input_bridge is not None:
self._input_bridge.ensure_active()
result = check()
if result is not None:
return result
if time.monotonic() + interval >= deadline:
raise TimeoutError(f"No approval within {timeout:.0f}s")
time.sleep(interval)
finally:
show_notice(None)
def search(self) -> Generator[SearchResult, None, None]:
"""