Fix Pro config SSOT, event FSM, FFmpeg error tiers, relay heartbeat, and ingest auth while keeping relay snapshot, quality guard, and event hub hidden in the UI. Co-authored-by: Cursor <cursoragent@cursor.com>
215 lines
7.4 KiB
Python
215 lines
7.4 KiB
Python
from __future__ import annotations
|
|
|
|
import subprocess
|
|
from datetime import datetime, timezone
|
|
from pathlib import Path
|
|
from typing import Any, Iterable
|
|
|
|
from src.youtube_pro_runtime import normalize_youtube_pro_channels
|
|
|
|
MIN_NEKO_INSTANCES = 2
|
|
MAX_MANAGED_NEKO_INSTANCES = 64
|
|
|
|
|
|
def desired_neko_count_for_youtube_channels(channels: Iterable[Any]) -> int:
|
|
normalized = normalize_youtube_pro_channels(channels)
|
|
return max(MIN_NEKO_INSTANCES, min(MAX_MANAGED_NEKO_INSTANCES, len(normalized) or MIN_NEKO_INSTANCES))
|
|
|
|
|
|
def _env_int(value: str | None) -> int | None:
|
|
if value is None:
|
|
return None
|
|
try:
|
|
return int(value.strip())
|
|
except (TypeError, ValueError):
|
|
return None
|
|
|
|
|
|
def _read_env_value(path: Path, key: str) -> str | None:
|
|
if not path.is_file():
|
|
return None
|
|
try:
|
|
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
except OSError:
|
|
return None
|
|
prefix = f"{key}="
|
|
for raw in lines:
|
|
line = raw.strip()
|
|
if line.startswith(prefix):
|
|
return line.split("=", 1)[1].strip().strip('"').strip("'")
|
|
return None
|
|
|
|
|
|
def upsert_env_value(path: Path, key: str, value: str) -> bool:
|
|
path.parent.mkdir(parents=True, exist_ok=True)
|
|
lines: list[str]
|
|
if path.is_file():
|
|
lines = path.read_text(encoding="utf-8", errors="replace").splitlines()
|
|
else:
|
|
lines = []
|
|
prefix = f"{key}="
|
|
next_line = f"{key}={value}"
|
|
changed = False
|
|
for idx, raw in enumerate(lines):
|
|
if raw.strip().startswith(prefix):
|
|
if raw != next_line:
|
|
lines[idx] = next_line
|
|
changed = True
|
|
break
|
|
else:
|
|
if lines and lines[-1].strip():
|
|
lines.append("")
|
|
lines.append(next_line)
|
|
changed = True
|
|
if changed:
|
|
path.write_text("\n".join(lines).rstrip() + "\n", encoding="utf-8")
|
|
return changed
|
|
|
|
|
|
def _compose_has_neko_service(root: Path, idx: int) -> bool:
|
|
compose = root / "services" / "neko" / "docker-compose.generated.yml"
|
|
if not compose.is_file():
|
|
return False
|
|
try:
|
|
text = compose.read_text(encoding="utf-8", errors="replace")
|
|
except OSError:
|
|
return False
|
|
return f" neko{idx}:" in text and f"container_name: live-neko-{idx}" in text
|
|
|
|
|
|
def _restart_timeout_seconds(env_path: Path) -> int:
|
|
raw = _read_env_value(env_path, "NEKO_CAPACITY_RESTART_TIMEOUT")
|
|
value = _env_int(raw)
|
|
if value is None:
|
|
return 180
|
|
return max(15, min(900, value))
|
|
|
|
|
|
def _render_compose(root: Path, desired: int, log_file: Path) -> tuple[bool, str]:
|
|
renderer = root / "tools" / "render_neko_compose.py"
|
|
if not renderer.is_file():
|
|
return False, "compose_renderer_missing"
|
|
output = root / "services" / "neko" / "docker-compose.generated.yml"
|
|
try:
|
|
with log_file.open("ab") as stream:
|
|
stamp = datetime.now(timezone.utc).isoformat()
|
|
stream.write(f"\n[{stamp}] rendering Neko compose count={desired}\n".encode("utf-8"))
|
|
completed = subprocess.run(
|
|
["python3", str(renderer), "--count", str(desired), "--output", str(output)],
|
|
cwd=str(root),
|
|
stdout=stream,
|
|
stderr=subprocess.STDOUT,
|
|
timeout=30,
|
|
check=False,
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return False, "compose_render_timeout"
|
|
except OSError as exc:
|
|
return False, f"compose_render_failed: {exc}"
|
|
if completed.returncode != 0:
|
|
return False, f"compose_render_exit_{completed.returncode}"
|
|
return True, ""
|
|
|
|
|
|
def _start_neko(root: Path, env_path: Path, log_file: Path) -> tuple[bool, str]:
|
|
service_ctl = root / "scripts" / "linux" / "service_ctl.sh"
|
|
if not service_ctl.is_file():
|
|
return False, "service_ctl_missing"
|
|
timeout = _restart_timeout_seconds(env_path)
|
|
try:
|
|
with log_file.open("ab") as stream:
|
|
stamp = datetime.now(timezone.utc).isoformat()
|
|
stream.write(f"\n[{stamp}] ensuring Neko capacity via service_ctl start\n".encode("utf-8"))
|
|
completed = subprocess.run(
|
|
["bash", str(service_ctl), "neko", "start"],
|
|
cwd=str(root),
|
|
stdout=stream,
|
|
stderr=subprocess.STDOUT,
|
|
timeout=timeout,
|
|
check=False,
|
|
)
|
|
except subprocess.TimeoutExpired:
|
|
return False, f"start_timeout_after_{timeout}s"
|
|
except OSError as exc:
|
|
return False, f"start_failed: {exc}"
|
|
if completed.returncode != 0:
|
|
return False, f"start_exit_{completed.returncode}"
|
|
return True, ""
|
|
|
|
|
|
def ensure_neko_capacity_for_youtube_channels(
|
|
repo_root: Path | None,
|
|
channels: Iterable[Any],
|
|
*,
|
|
restart: bool = True,
|
|
) -> dict[str, Any]:
|
|
desired = desired_neko_count_for_youtube_channels(channels)
|
|
if repo_root is None:
|
|
return {"desired": desired, "changed": False, "restarted": False, "reason": "repo_root_missing"}
|
|
root = Path(repo_root)
|
|
env_path = root / "config" / "system-stack.env"
|
|
current_raw = _read_env_value(env_path, "NEKO_INSTANCE_COUNT")
|
|
current = _env_int(current_raw)
|
|
compose_ready = _compose_has_neko_service(root, desired)
|
|
if current is not None and current >= desired and compose_ready:
|
|
return {
|
|
"ok": True,
|
|
"desired": desired,
|
|
"current": current,
|
|
"changed": False,
|
|
"restart_required": False,
|
|
"restarted": False,
|
|
"compose_ready": True,
|
|
}
|
|
|
|
changed = False
|
|
log_dir = root / "logs"
|
|
log_dir.mkdir(parents=True, exist_ok=True)
|
|
log_file = log_dir / "neko-capacity.log"
|
|
if current is None or current < desired:
|
|
changed = upsert_env_value(env_path, "NEKO_INSTANCE_COUNT", str(desired))
|
|
current_raw = str(desired)
|
|
current = desired
|
|
elif not compose_ready:
|
|
rendered, render_reason = _render_compose(root, desired, log_file)
|
|
reason = "compose_missing_desired_service"
|
|
if render_reason:
|
|
reason = f"{reason}; {render_reason}"
|
|
compose_ready = _compose_has_neko_service(root, desired)
|
|
return {
|
|
"ok": compose_ready,
|
|
"desired": desired,
|
|
"current": current,
|
|
"changed": False,
|
|
"restart_required": False,
|
|
"restarted": False,
|
|
"started": False,
|
|
"compose_ready": compose_ready,
|
|
"rendered": rendered,
|
|
"reason": reason,
|
|
}
|
|
started = False
|
|
reason = "" if changed else "compose_missing_desired_service"
|
|
restart_required = changed
|
|
if restart and restart_required:
|
|
started, start_reason = _start_neko(root, env_path, log_file)
|
|
if start_reason:
|
|
reason = f"{reason}; {start_reason}" if reason else start_reason
|
|
compose_ready = _compose_has_neko_service(root, desired)
|
|
if started and not compose_ready:
|
|
suffix = "compose_missing_desired_service_after_restart"
|
|
reason = f"{reason}; {suffix}" if reason else suffix
|
|
elif restart_required and not restart:
|
|
reason = reason or "restart_disabled"
|
|
return {
|
|
"ok": not restart_required or (started and compose_ready),
|
|
"desired": desired,
|
|
"current": current_raw,
|
|
"changed": changed,
|
|
"restart_required": restart_required,
|
|
"restarted": False,
|
|
"started": started,
|
|
"compose_ready": compose_ready,
|
|
"reason": reason,
|
|
}
|