Files
Kronic-Krusaders/resolver_manager.py
2026-11-25 20:20:43 -06:00

278 lines
6.1 KiB
Python

from __future__ import annotations
import atexit
import json
import os
import signal
import subprocess
import sys
import threading
import time
from pathlib import Path
from urllib.error import URLError
from urllib.request import urlopen
from dotenv import load_dotenv
BASE_DIR = Path(__file__).resolve().parent
load_dotenv(BASE_DIR / "config.env")
KRONIC_DIR = Path(
os.getenv(
"KRONIC_DIR",
str(BASE_DIR / "kronic"),
)
).expanduser().resolve()
RESOLVER_HOST = os.getenv(
"KRONIC_RESOLVER_HOST",
"127.0.0.1",
).strip() or "127.0.0.1"
RESOLVER_PORT = int(
os.getenv(
"KRONIC_RESOLVER_PORT",
"3030",
)
)
RESOLVER_START_TIMEOUT = float(
os.getenv(
"KRONIC_RESOLVER_START_TIMEOUT",
"30",
)
)
RESOLVER_URL = (
f"http://{RESOLVER_HOST}:{RESOLVER_PORT}"
)
_PROCESS: subprocess.Popen | None = None
_LOCK = threading.Lock()
_OWNS_PROCESS = False
def _health_url() -> str:
return f"{RESOLVER_URL}/health"
def resolver_is_ready(
timeout: float = 1.0,
) -> bool:
try:
with urlopen(
_health_url(),
timeout=timeout,
) as response:
if response.status < 200 or response.status >= 300:
return False
# The Kronic resolver currently returns JSON, but health only
# needs a successful HTTP response.
try:
json.loads(
response.read().decode(
"utf-8",
"replace",
)
)
except Exception:
pass
return True
except Exception:
return False
def _required_paths() -> list[Path]:
return [
KRONIC_DIR / "resolver" / "__init__.py",
KRONIC_DIR / "resolver" / "app.py",
KRONIC_DIR / "resolver" / "app_spotdl.py",
KRONIC_DIR / "resolver" / "spotdl_router.py",
KRONIC_DIR / "resolver" / "models.py",
KRONIC_DIR / "resolver" / "net.py",
KRONIC_DIR / "resolver" / "ytdlp_service.py",
]
def validate_resolver_tree() -> None:
missing = [
path
for path in _required_paths()
if not path.is_file()
]
if missing:
formatted = "\n".join(
f" - {path}"
for path in missing
)
raise RuntimeError(
"Kronic resolver files are missing:\n"
f"{formatted}\n"
"Expected the resolver beneath "
f"{KRONIC_DIR}"
)
def start_resolver() -> bool:
"""
Start kronic.resolver.app_spotdl:app as a child of the media server.
Returns True when this process started the resolver.
Returns False when a compatible resolver was already listening.
"""
global _PROCESS, _OWNS_PROCESS
with _LOCK:
if _PROCESS is not None and _PROCESS.poll() is None:
return True
# If something is already listening and healthy, use it rather than
# starting a duplicate listener.
if resolver_is_ready():
print(
f"[RESOLVER] Existing resolver detected at {RESOLVER_URL}",
flush=True,
)
_OWNS_PROCESS = False
return False
validate_resolver_tree()
command = [
sys.executable,
"-m",
"uvicorn",
"kronic.resolver.app_spotdl:app",
"--host",
RESOLVER_HOST,
"--port",
str(RESOLVER_PORT),
"--log-level",
os.getenv(
"KRONIC_RESOLVER_LOG_LEVEL",
"warning",
),
]
env = os.environ.copy()
env.setdefault(
"PYTHONUNBUFFERED",
"1",
)
print(
"[RESOLVER] Starting embedded Kronic resolver:",
" ".join(command),
flush=True,
)
_PROCESS = subprocess.Popen(
command,
cwd=str(BASE_DIR),
env=env,
stdin=subprocess.DEVNULL,
)
_OWNS_PROCESS = True
deadline = (
time.monotonic()
+ RESOLVER_START_TIMEOUT
)
while time.monotonic() < deadline:
process = _PROCESS
if process is None:
break
return_code = process.poll()
if return_code is not None:
_PROCESS = None
_OWNS_PROCESS = False
raise RuntimeError(
"Embedded Kronic resolver exited during startup "
f"with return code {return_code}"
)
if resolver_is_ready(
timeout=1.0
):
print(
f"[RESOLVER] Ready at {RESOLVER_URL}",
flush=True,
)
return True
time.sleep(0.25)
stop_resolver()
raise RuntimeError(
"Embedded Kronic resolver did not become ready within "
f"{RESOLVER_START_TIMEOUT:.1f} seconds"
)
def stop_resolver() -> None:
global _PROCESS, _OWNS_PROCESS
with _LOCK:
process = _PROCESS
owns_process = _OWNS_PROCESS
_PROCESS = None
_OWNS_PROCESS = False
if process is None or not owns_process:
return
if process.poll() is not None:
return
print(
"[RESOLVER] Stopping embedded Kronic resolver...",
flush=True,
)
try:
process.terminate()
process.wait(timeout=8)
except subprocess.TimeoutExpired:
process.kill()
process.wait(timeout=3)
except Exception as error:
print(
f"[RESOLVER] Stop error: {error}",
flush=True,
)
def resolver_status() -> dict:
process = _PROCESS
return {
"url": RESOLVER_URL,
"ready": resolver_is_ready(),
"managed": bool(
process is not None
and _OWNS_PROCESS
),
"pid": (
process.pid
if process is not None
and process.poll() is None
else None
),
"kronic_dir": str(KRONIC_DIR),
}
atexit.register(
stop_resolver
)