sh2/d2ypp2/src/neko_capacity.py
2026-06-02 03:19:23 -05:00

167 lines
5.7 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 _restart_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 restart\n".encode("utf-8"))
completed = subprocess.run(
["bash", str(service_ctl), "neko", "restart"],
cwd=str(root),
stdout=stream,
stderr=subprocess.STDOUT,
timeout=timeout,
check=False,
)
except subprocess.TimeoutExpired:
return False, f"restart_timeout_after_{timeout}s"
except OSError as exc:
return False, f"restart_failed: {exc}"
if completed.returncode != 0:
return False, f"restart_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
if current is None or current < desired:
changed = upsert_env_value(env_path, "NEKO_INSTANCE_COUNT", str(desired))
restarted = False
reason = "compose_missing_desired_service" if current is not None and current >= desired and not compose_ready else ""
restart_required = changed or not compose_ready
if restart and restart_required:
log_dir = root / "logs"
log_dir.mkdir(parents=True, exist_ok=True)
restarted, restart_reason = _restart_neko(root, env_path, log_dir / "neko-capacity.log")
if restart_reason:
reason = f"{reason}; {restart_reason}" if reason else restart_reason
compose_ready = _compose_has_neko_service(root, desired)
if restarted 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 (restarted and compose_ready),
"desired": desired,
"current": current_raw,
"changed": changed,
"restart_required": restart_required,
"restarted": restarted,
"compose_ready": compose_ready,
"reason": reason,
}