Keep /api/health instant, isolate ffmpeg cgroups, defer clip encodes while live push runs, and align dy.live systemd with dylive. README covers the hang root cause and /yt-revenue. Co-authored-by: Cursor <cursoragent@cursor.com>
3893 lines
148 KiB
Python
3893 lines
148 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""Per-channel Neko browser (Docker) for YouTube Studio on US VPS.
|
||
|
||
Aligned with sh2/d2ypp2 lessons, adapted for cloud:
|
||
- No ShellClash / WireGuard — browser egress is direct (US IP).
|
||
- HTTP stays on 127.0.0.1 behind nginx HTTPS (/neko/{id}/ → :920x).
|
||
- WebRTC UDP/TCP mux + EPR published on 0.0.0.0 (nginx cannot proxy WebRTC).
|
||
- ICE Lite OFF (sh2 forces 0 for stable remote ICE).
|
||
- NAT1TO1 = public VPS IP so clients get reachable ICE candidates.
|
||
- Containers created by default; running only when neko_enabled.
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import shutil
|
||
import socket
|
||
import subprocess
|
||
import threading
|
||
import urllib.request
|
||
from pathlib import Path
|
||
from typing import Any
|
||
from urllib.parse import urlparse
|
||
|
||
from .config import settings
|
||
|
||
_lock = threading.RLock()
|
||
|
||
|
||
def _max_instances() -> int:
|
||
try:
|
||
n = int(getattr(settings, "neko_max_instances", 256) or 256)
|
||
except Exception:
|
||
n = 256
|
||
return max(1, min(n, 1024))
|
||
|
||
|
||
# Back-compat alias used across this module
|
||
MAX_INSTANCES = _max_instances()
|
||
_nat_ip_cache: str = ""
|
||
_nat_ip_cached_at: float = 0.0
|
||
_NAT_CACHE_TTL_SEC = 3600.0
|
||
_list_cache_at: float = 0.0
|
||
_list_cache_count: int = -1
|
||
_list_cache_rows: list[dict[str, Any]] = []
|
||
_LIST_CACHE_TTL_SEC = 5.0
|
||
_list_cache_check_http: bool = False
|
||
|
||
|
||
def _neko_root() -> Path:
|
||
p = settings.data_dir / "neko"
|
||
p.mkdir(parents=True, exist_ok=True)
|
||
(p / "profiles").mkdir(parents=True, exist_ok=True)
|
||
return p
|
||
|
||
|
||
def _asset_root() -> Path:
|
||
"""Repo-bundled sh2 Neko assets: Tampermonkey seed, policies, browser-launch, live-ops."""
|
||
# backend/app/youtube_neko.py → backend/neko/
|
||
return Path(__file__).resolve().parent.parent / "neko"
|
||
|
||
|
||
def _neko_browser_proxy_value() -> str:
|
||
"""Host-reachable proxy for Chromium inside the container."""
|
||
try:
|
||
from . import egress_hub
|
||
|
||
return str(egress_hub.neko_browser_proxy() or "").strip()
|
||
except Exception:
|
||
return str(os.environ.get("DY_NEKO_BROWSER_PROXY") or "").strip()
|
||
|
||
|
||
def refresh_compose_for_egress() -> dict[str, Any]:
|
||
"""Rewrite compose with current NEKO_BROWSER_PROXY and recreate stopped containers."""
|
||
with _lock:
|
||
try:
|
||
desired = max(1, min(_max_instances(), int(_desired_from_db())))
|
||
except Exception:
|
||
desired = 2
|
||
compose = _compose_path()
|
||
text = _render_compose(desired)
|
||
compose.write_text(text, encoding="utf-8")
|
||
# Recreate so env NEKO_BROWSER_PROXY is picked up; keep running set running.
|
||
running: set[int] = set()
|
||
try:
|
||
for idx in range(1, desired + 1):
|
||
name = _container_name(idx)
|
||
code, out = _run(["docker", "inspect", "-f", "{{.State.Running}}", name], timeout=8)
|
||
if code == 0 and "true" in (out or "").lower():
|
||
running.add(idx)
|
||
except Exception:
|
||
pass
|
||
code, out = _run(
|
||
_compose_cmd("up", "-d", "--force-recreate", "--no-start"),
|
||
timeout=900,
|
||
)
|
||
started: list[int] = []
|
||
errors: list[str] = []
|
||
if code != 0:
|
||
errors.append(out[-500:])
|
||
for idx in sorted(running):
|
||
c2, o2 = _run(_compose_cmd("start", f"neko{idx}"), timeout=120)
|
||
if c2 == 0:
|
||
started.append(idx)
|
||
else:
|
||
errors.append(f"neko{idx}: {o2[-200:]}")
|
||
proxy = _neko_browser_proxy_value()
|
||
return {
|
||
"ok": code == 0 and not errors,
|
||
"desired": desired,
|
||
"proxy": proxy,
|
||
"restarted": started,
|
||
"error": "; ".join(errors) if errors else "",
|
||
}
|
||
|
||
|
||
def _compose_path() -> Path:
|
||
return _neko_root() / "docker-compose.yml"
|
||
|
||
|
||
def _supervisor_conf_name() -> str:
|
||
image = str(getattr(settings, "neko_image", "") or "").lower()
|
||
if "google-chrome" in image or "chrome" in image:
|
||
return "google-chrome.conf"
|
||
return "chromium.conf"
|
||
|
||
|
||
def _managed_policies_enabled() -> bool:
|
||
raw = str(getattr(settings, "neko_managed_policies", "") or os.environ.get("DY_NEKO_MANAGED_POLICIES") or "0")
|
||
return raw.strip().lower() in {"1", "true", "yes", "on"}
|
||
|
||
|
||
def _http_port(instance_id: int) -> int:
|
||
return int(getattr(settings, "neko_http_port_base", 9200) or 9200) + instance_id - 1
|
||
|
||
|
||
def _http_bind() -> str:
|
||
"""Host bind for Neko HTTP publish.
|
||
|
||
VPS colocated (nginx/Caddy on same box): 127.0.0.1
|
||
Physical (edge TLS on VPS via WireGuard): 0.0.0.0 so 10.8.0.2:920x is reachable
|
||
"""
|
||
raw = str(os.environ.get("DY_NEKO_HTTP_BIND") or getattr(settings, "neko_http_bind", "") or "").strip()
|
||
if raw:
|
||
return raw
|
||
if str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip():
|
||
return "0.0.0.0"
|
||
return "127.0.0.1"
|
||
|
||
|
||
def _ensure_browser_launch_exec() -> None:
|
||
"""Windows→Linux deploys often drop +x; Chromium supervisor requires executable."""
|
||
path = _asset_root() / "browser-launch.sh"
|
||
try:
|
||
if path.is_file():
|
||
os.chmod(path, 0o755)
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _webrtc_mux(instance_id: int) -> int:
|
||
return int(getattr(settings, "neko_webrtc_mux_base", 52300) or 52300) + instance_id - 1
|
||
|
||
|
||
def _udp_range(instance_id: int) -> str:
|
||
"""Match sh2 default_udp_range — avoid .99 collision patterns."""
|
||
idx = int(instance_id)
|
||
if idx == 1:
|
||
return "52000-52098"
|
||
if idx == 2:
|
||
return "52101-52199"
|
||
if idx == 3:
|
||
return "52201-52299"
|
||
start = 52400 + ((idx - 4) * 100)
|
||
return f"{start}-{start + 99}"
|
||
|
||
|
||
def _container_name(instance_id: int) -> str:
|
||
return f"douyinweb-neko-{instance_id}"
|
||
|
||
|
||
def _docker_available() -> bool:
|
||
return bool(shutil.which("docker"))
|
||
|
||
|
||
def _run(cmd: list[str], *, timeout: float = 120.0, input_text: str | None = None) -> tuple[int, str]:
|
||
try:
|
||
proc = subprocess.run(
|
||
cmd,
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=timeout,
|
||
check=False,
|
||
input=input_text,
|
||
)
|
||
out = (proc.stdout or "") + (proc.stderr or "")
|
||
return proc.returncode, out.strip()
|
||
except subprocess.TimeoutExpired:
|
||
return 124, "timeout"
|
||
except OSError as exc:
|
||
return 1, str(exc)
|
||
|
||
|
||
def _public_base() -> str:
|
||
base = str(settings.public_base_url or "").strip().rstrip("/")
|
||
if base:
|
||
return base
|
||
for key in ("DY_PUBLIC_BASE_URL", "PUBLIC_BASE"):
|
||
alt = str(os.environ.get(key) or "").strip().rstrip("/")
|
||
if alt:
|
||
return alt
|
||
return ""
|
||
|
||
|
||
def _physical_dual_edge() -> bool:
|
||
"""Physical guest: TLS on VPS/Tencent, app + Neko on this host via WireGuard.
|
||
|
||
Do NOT treat the overseas VPS (WG *server* + colocated app) as physical just because
|
||
``wg-dy`` exists — that wrongly empties preferred public base / ICE logic.
|
||
"""
|
||
if str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "").strip():
|
||
return True
|
||
shape = str(os.environ.get("DY_INSTALL_SHAPE") or os.environ.get("INSTALL_SHAPE") or "").strip().lower()
|
||
if shape in {"vps", "colocated", "dylive"}:
|
||
return False
|
||
if shape in {"physical", "phys", "guest"}:
|
||
return True
|
||
# VPS colocated binds Neko to loopback; physical guest publishes on 0.0.0.0 for WG.
|
||
bind = str(
|
||
getattr(settings, "neko_http_bind", "")
|
||
or os.environ.get("DY_NEKO_HTTP_BIND")
|
||
or ""
|
||
).strip()
|
||
if bind in {"127.0.0.1", "localhost", "::1"}:
|
||
return False
|
||
sysnet = Path("/sys/class/net")
|
||
if not sysnet.is_dir():
|
||
return False
|
||
return (sysnet / "wg-dy").exists() or (sysnet / "wg-dy-cn").exists()
|
||
|
||
|
||
def preferred_neko_public_base(*, override: str = "") -> str:
|
||
"""Physical Neko open URL: Tencent (.cn) when wg-dy-cn is up, else VPS (.com).
|
||
|
||
Colocated VPS (dylive): always the configured public base — never 127.0.0.1.
|
||
"""
|
||
primary = (override or "").strip().rstrip("/") or _public_base()
|
||
if not _physical_dual_edge():
|
||
return primary
|
||
cn = _derive_cn_public_base(primary)
|
||
if cn and cn_edge_usable():
|
||
return cn
|
||
return primary or cn
|
||
|
||
|
||
def public_studio_url(instance_id: int) -> str:
|
||
"""Browser-openable assign Neko URL (must be public HTTPS path, not loopback port)."""
|
||
idx = int(instance_id or 0)
|
||
base = preferred_neko_public_base()
|
||
if base and "127.0.0.1" not in base and "localhost" not in base.lower():
|
||
return f"{base}/neko/{idx}/"
|
||
# Misconfigured env: still prefer path-style URL on known sites over :920x loopback.
|
||
for key in ("DY_PUBLIC_BASE_URL", "PUBLIC_BASE", "DY_SITE_URL"):
|
||
alt = str(os.environ.get(key) or "").strip().rstrip("/")
|
||
if alt and "127.0.0.1" not in alt and "localhost" not in alt.lower():
|
||
return f"{alt}/neko/{idx}/"
|
||
# Last resort for server-side probes only — UI should never hit this on a configured VPS.
|
||
return f"http://127.0.0.1:{_http_port(idx)}/"
|
||
|
||
|
||
def _wg_iface_usable(iface: str, *, peer: str, max_age_sec: int = 180) -> bool:
|
||
"""Handshake fresh enough, or peer ICMP reachable."""
|
||
if not Path(f"/sys/class/net/{iface}").exists():
|
||
return False
|
||
import time as _time
|
||
|
||
code, out = _run(["wg", "show", iface, "latest-handshakes"], timeout=5)
|
||
if code == 0 and out.strip():
|
||
parts = out.split()
|
||
if len(parts) >= 2:
|
||
try:
|
||
ts = int(parts[-1])
|
||
except ValueError:
|
||
ts = 0
|
||
if ts > 0 and (_time.time() - ts) <= max_age_sec:
|
||
return True
|
||
if peer:
|
||
c2, o2 = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6)
|
||
if c2 == 0 and ("bytes from" in o2 or "ttl=" in o2.lower() or "1 received" in o2):
|
||
return True
|
||
return False
|
||
|
||
|
||
_cn_edge_cache: tuple[float, bool] | None = None
|
||
_CN_EDGE_CACHE_TTL_SEC = 30.0
|
||
|
||
|
||
def cn_edge_usable() -> bool:
|
||
"""Tencent wg-dy-cn preferred path for physical Neko HTTP/ICE.
|
||
|
||
Prefer CN whenever the iface is up and either handshake is fresh or peer pings.
|
||
Slightly stale handshake alone should not flip ICE to the overseas VPS IP.
|
||
Cached briefly — status/sync paths used to spawn ping -W 2 on every call and
|
||
saturate the default thread pool (Recv-Q hang / health timeout).
|
||
"""
|
||
global _cn_edge_cache
|
||
import time as _time
|
||
|
||
now = _time.time()
|
||
if _cn_edge_cache is not None:
|
||
cached_at, cached_ok = _cn_edge_cache
|
||
if now - cached_at < _CN_EDGE_CACHE_TTL_SEC:
|
||
return cached_ok
|
||
|
||
ok = False
|
||
if Path("/sys/class/net/wg-dy-cn").exists():
|
||
peer = str(os.environ.get("DY_WG_CN_PEER_IP") or "10.9.0.1").strip() or "10.9.0.1"
|
||
if _wg_iface_usable("wg-dy-cn", peer=peer, max_age_sec=600):
|
||
ok = True
|
||
elif peer:
|
||
c2, o2 = _run(["ping", "-c", "1", "-W", "2", peer], timeout=6)
|
||
if c2 == 0 and ("bytes from" in o2 or "ttl=" in o2.lower() or "1 received" in o2):
|
||
ok = True
|
||
else:
|
||
# Last resort: iface up counts as usable so NAT1TO1 stays on Tencent DNAT
|
||
ok = True
|
||
else:
|
||
ok = True
|
||
_cn_edge_cache = (now, ok)
|
||
return ok
|
||
|
||
|
||
def _derive_cn_public_base(primary: str) -> str:
|
||
env = str(os.environ.get("DY_NEKO_CN_PUBLIC_BASE") or "").strip().rstrip("/")
|
||
if env:
|
||
return env
|
||
base = (primary or "").strip().rstrip("/")
|
||
if not base:
|
||
return ""
|
||
if base.endswith(".nomadro.com"):
|
||
return base[: -len(".nomadro.com")] + ".nomadro.cn"
|
||
if "nomadro.com" in base:
|
||
return base.replace("nomadro.com", "nomadro.cn")
|
||
return ""
|
||
|
||
|
||
def _detect_public_ip() -> str:
|
||
"""Resolve reachable public IP for WebRTC ICE (NAT1TO1).
|
||
|
||
Physical dual-edge: Tencent ``DY_NEKO_CN_NAT1TO1`` (or ``DY_NEKO_NAT1TO1``) while
|
||
wg-dy-cn is usable; otherwise ``DY_NEKO_VPS_NAT1TO1`` / fallback. Cached briefly.
|
||
"""
|
||
global _nat_ip_cache, _nat_ip_cached_at
|
||
import time as _time
|
||
|
||
cn_ip = str(os.environ.get("DY_NEKO_CN_NAT1TO1") or "").strip()
|
||
vps_ip = str(os.environ.get("DY_NEKO_VPS_NAT1TO1") or "").strip()
|
||
configured = str(getattr(settings, "neko_nat1to1", "") or "").strip()
|
||
env_ip = str(os.environ.get("DY_NEKO_NAT1TO1") or "").strip()
|
||
|
||
if _physical_dual_edge():
|
||
if cn_edge_usable():
|
||
pick = cn_ip or configured or env_ip
|
||
if pick:
|
||
return pick
|
||
pick = vps_ip or (env_ip if env_ip != cn_ip else "") or configured
|
||
if pick:
|
||
return pick
|
||
else:
|
||
if configured:
|
||
return configured
|
||
if env_ip:
|
||
return env_ip
|
||
|
||
now = _time.time()
|
||
if _nat_ip_cache and (now - _nat_ip_cached_at) < _NAT_CACHE_TTL_SEC:
|
||
return _nat_ip_cache
|
||
|
||
cache_file = _neko_root() / "nat1to1.txt"
|
||
if cache_file.is_file():
|
||
try:
|
||
cached = cache_file.read_text(encoding="utf-8").strip()
|
||
if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", cached):
|
||
_nat_ip_cache = cached
|
||
_nat_ip_cached_at = now
|
||
return cached
|
||
except OSError:
|
||
pass
|
||
|
||
ip = ""
|
||
proxy = ""
|
||
try:
|
||
from . import egress_hub
|
||
|
||
proxy = str(egress_hub.google_http_proxy() or "").strip()
|
||
except Exception:
|
||
proxy = ""
|
||
for url in (
|
||
"https://checkip.amazonaws.com",
|
||
"https://api.ipify.org",
|
||
"https://ifconfig.me/ip",
|
||
):
|
||
try:
|
||
if proxy:
|
||
import httpx
|
||
|
||
with httpx.Client(timeout=6.0, trust_env=False, proxy=proxy) as client:
|
||
cand = (client.get(url).text or "").strip()
|
||
else:
|
||
with urllib.request.urlopen(url, timeout=4) as resp:
|
||
cand = (resp.read().decode("utf-8", "replace") or "").strip()
|
||
if re.fullmatch(r"\d{1,3}(?:\.\d{1,3}){3}", cand):
|
||
ip = cand
|
||
break
|
||
except Exception:
|
||
continue
|
||
if not ip:
|
||
try:
|
||
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
|
||
s.settimeout(2)
|
||
s.connect(("8.8.8.8", 80))
|
||
cand = s.getsockname()[0]
|
||
s.close()
|
||
if cand and not cand.startswith("127."):
|
||
ip = cand
|
||
except OSError:
|
||
pass
|
||
if not ip:
|
||
# Prefer explicit NAT1TO1; never invent a datacenter IP for the wrong host.
|
||
ip = vps_ip or env_ip or cn_ip or configured or _nat_ip_cache or ""
|
||
if ip:
|
||
_nat_ip_cache = ip
|
||
_nat_ip_cached_at = now
|
||
try:
|
||
cache_file.write_text(ip + "\n", encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
return ip
|
||
|
||
|
||
def _desired_from_db() -> int:
|
||
"""Max assigned neko_instance_id across assign groups (never shrink on single-instance start)."""
|
||
try:
|
||
from . import yt_assign_db
|
||
|
||
groups = yt_assign_db.list_groups(include_urls=False)
|
||
ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
|
||
return max(ids) if ids else 0
|
||
except Exception:
|
||
return 0
|
||
|
||
|
||
def _ensure_profile(instance_id: int) -> Path:
|
||
profile = _neko_root() / "profiles" / str(instance_id)
|
||
profile.mkdir(parents=True, exist_ok=True)
|
||
try:
|
||
os.chmod(profile, 0o777)
|
||
except OSError:
|
||
pass
|
||
# Tampermonkey/script seeding is sh2's job: browser-launch.sh + Chrome policies
|
||
# (NEKO_MANAGED_POLICIES=1 → ExtensionInstallForcelist + jsonImport from :18080).
|
||
return profile
|
||
|
||
|
||
def _ensure_instance_id_file(instance_id: int) -> Path:
|
||
"""Per-container file bind-mounted into the live-ops extension for telemetry tagging."""
|
||
meta = _neko_root() / "instance-meta" / str(int(instance_id))
|
||
meta.mkdir(parents=True, exist_ok=True)
|
||
path = meta / "instance_id.txt"
|
||
want = f"{int(instance_id)}\n"
|
||
try:
|
||
if not path.exists() or path.read_text(encoding="utf-8") != want:
|
||
path.write_text(want, encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
return path
|
||
|
||
|
||
_TM_EXT_ID = "dhdgffkkebhmkfjojejmpbldmpobfkfo"
|
||
|
||
def _q(value: str) -> str:
|
||
return json.dumps(str(value), ensure_ascii=False)
|
||
|
||
|
||
def compose_service_lines(
|
||
*,
|
||
service_key: str,
|
||
container_name: str,
|
||
instance_id_label: str,
|
||
http_port: int,
|
||
mux: int,
|
||
udp: str,
|
||
profile: Path,
|
||
instance_id_file: Path,
|
||
http_bind: str | None = None,
|
||
) -> list[str]:
|
||
"""One Docker Compose service — shared by assign fleet and ops-neko tab.
|
||
|
||
Same image/env/assets/proxy/Studio start URL so YouTube live tooling matches.
|
||
Only ports / names / profile dirs differ between fleets.
|
||
"""
|
||
image = str(
|
||
getattr(settings, "neko_image", "") or "ghcr.io/m1k1o/neko/google-chrome:3.0.0"
|
||
)
|
||
user_pass = str(getattr(settings, "neko_user_pass", "") or "douyinweb")
|
||
admin_pass = str(getattr(settings, "neko_admin_pass", "") or "Xiao4669805@")
|
||
nat1to1 = _detect_public_ip()
|
||
shm = str(getattr(settings, "neko_shm_size", "") or "512mb")
|
||
# Defaults match Settings / YouTube unattended-live (low CPU Studio remote).
|
||
screen = str(getattr(settings, "neko_desktop_screen", "") or "1024x576@10")
|
||
max_fps = str(getattr(settings, "neko_max_fps", "") or "10")
|
||
bitrate = str(getattr(settings, "neko_video_bitrate", "") or "700")
|
||
icelite = str(getattr(settings, "neko_webrtc_icelite", "") or "0")
|
||
mem_limit = str(getattr(settings, "neko_mem_limit", "") or "1536m").strip()
|
||
if mem_limit.lower() in {"", "0", "none", "off", "unlimited"}:
|
||
mem_limit = ""
|
||
start_url = str(
|
||
getattr(settings, "neko_start_url", "")
|
||
or "https://accounts.google.com/ServiceLogin?continue=https://studio.youtube.com/"
|
||
)
|
||
tz = "America/Chicago"
|
||
assets = _asset_root()
|
||
managed = _managed_policies_enabled()
|
||
policy_dir = assets / ("policies" if managed else "no-managed-policies")
|
||
seed_dir = assets / "tampermonkey-seed"
|
||
live_ops_dir = assets / "live-ops-extension"
|
||
provisioning_dir = assets / "provisioning"
|
||
browser_launch = assets / "browser-launch.sh"
|
||
supervisor_name = _supervisor_conf_name()
|
||
supervisor = assets / supervisor_name
|
||
for required in (seed_dir, live_ops_dir, provisioning_dir, browser_launch, supervisor, policy_dir):
|
||
if not required.exists():
|
||
raise RuntimeError(f"Neko sh2 asset missing: {required}")
|
||
_ensure_browser_launch_exec()
|
||
bind = (http_bind or _http_bind()).strip() or "127.0.0.1"
|
||
lines = [
|
||
f" {service_key}:",
|
||
f" image: {_q(image)}",
|
||
' restart: "no"',
|
||
f" shm_size: {_q(shm)}",
|
||
]
|
||
# Hard cap: runaway Studio/Chrome OOMs the container, not the whole VPS.
|
||
# Negative oom_score_adj: host kills API/other apps before Neko/Chrome.
|
||
if mem_limit:
|
||
lines.extend(
|
||
[
|
||
f" mem_limit: {_q(mem_limit)}",
|
||
f" memswap_limit: {_q(mem_limit)}",
|
||
" oom_score_adj: -800",
|
||
]
|
||
)
|
||
else:
|
||
lines.append(" oom_score_adj: -800")
|
||
lines.extend(
|
||
[
|
||
" cap_add:",
|
||
" - SYS_ADMIN",
|
||
" security_opt:",
|
||
" - apparmor:unconfined",
|
||
" extra_hosts:",
|
||
' - "host.docker.internal:host-gateway"',
|
||
f" container_name: {container_name}",
|
||
" environment:",
|
||
f" TZ: {_q(tz)}",
|
||
' DISPLAY: ":99.0"',
|
||
' ENV_DISPLAY: ":99.0"',
|
||
' ENV_USER: "neko"',
|
||
' USER: "neko"',
|
||
' HOME: "/home/neko"',
|
||
' NEKO_CONTAINER_USER: "neko"',
|
||
' NEKO_CONTAINER_HOME: "/home/neko"',
|
||
f" NEKO_INSTANCE_ID: {_q(str(instance_id_label))}",
|
||
' NEKO_SERVER_BIND: ":8080"',
|
||
# Trust X-Forwarded-* from nginx/Caddy; NO path prefix (edge strips /neko/N/ or /ops-neko/N/).
|
||
' NEKO_SERVER_PROXY: "true"',
|
||
' NEKO_MEMBER_PROVIDER: "multiuser"',
|
||
f" NEKO_MEMBER_MULTIUSER_USER_PASSWORD: {_q(user_pass)}",
|
||
f" NEKO_MEMBER_MULTIUSER_ADMIN_PASSWORD: {_q(admin_pass)}",
|
||
f" NEKO_DESKTOP_SCREEN: {_q(screen)}",
|
||
f" NEKO_MAX_FPS: {_q(max_fps)}",
|
||
f" NEKO_VIDEO_BITRATE: {_q(bitrate)}",
|
||
f" NEKO_WEBRTC_ICELITE: {_q(icelite)}",
|
||
f" NEKO_WEBRTC_NAT1TO1: {_q(nat1to1)}",
|
||
f" NEKO_WEBRTC_TCPMUX: {_q(str(mux))}",
|
||
f" NEKO_WEBRTC_UDPMUX: {_q(str(mux))}",
|
||
f" NEKO_WEBRTC_EPR: {_q(udp)}",
|
||
f" NEKO_START_URL: {_q(start_url)}",
|
||
f" NEKO_BROWSER_PROXY: {_q(_neko_browser_proxy_value())}",
|
||
' NEKO_BROWSER_RENDER_MODE: "auto"',
|
||
f" NEKO_MANAGED_POLICIES: {_q('1' if managed else '0')}",
|
||
' NEKO_TAMPERMONKEY_REPAIR: "1"',
|
||
' NEKO_LIVE_OPS_EXTENSION: "1"',
|
||
' NEKO_LIVE_OPS_EXTENSION_DIR: "/etc/neko/live-ops-extension"',
|
||
' NEKO_TAMPERMONKEY_SEED_DIR: "/etc/neko/tampermonkey-seed"',
|
||
" ports:",
|
||
f' - "{bind}:{int(http_port)}:8080"',
|
||
f' - "{int(mux)}:{int(mux)}/tcp"',
|
||
f' - "{int(mux)}:{int(mux)}/udp"',
|
||
f' - "{udp}:{udp}/udp"',
|
||
" volumes:",
|
||
f" - {_q(f'{profile}:/home/neko/.config/chromium')}",
|
||
f" - {_q(f'{profile}:/home/neko/.config/google-chrome')}",
|
||
f" - {_q(f'{policy_dir}:/etc/chromium/policies/managed:ro')}",
|
||
f" - {_q(f'{policy_dir}:/etc/chromium-browser/policies/managed:ro')}",
|
||
f" - {_q(f'{policy_dir}:/etc/opt/chrome/policies/managed:ro')}",
|
||
f" - {_q(f'{seed_dir}:/etc/neko/tampermonkey-seed:ro')}",
|
||
f" - {_q(f'{live_ops_dir}:/etc/neko/live-ops-extension:ro')}",
|
||
f" - {_q(f'{instance_id_file}:/etc/neko/live-ops-extension/instance_id.txt:ro')}",
|
||
f" - {_q(f'{provisioning_dir}:/var/www/provisioning:ro')}",
|
||
f" - {_q(f'{browser_launch}:/etc/neko/browser-launch.sh:ro')}",
|
||
f" - {_q(f'{supervisor}:/etc/neko/supervisord/{supervisor_name}:ro')}",
|
||
]
|
||
)
|
||
return lines
|
||
|
||
|
||
def _render_compose(count: int) -> str:
|
||
# x86 US VPS → google-chrome (sh2); override via DY_NEKO_IMAGE.
|
||
lines = [
|
||
"# Generated by douyinWEB youtube_neko — sh2-aligned assets; do not edit",
|
||
"services:",
|
||
]
|
||
for idx in range(1, count + 1):
|
||
lines.extend(
|
||
compose_service_lines(
|
||
service_key=f"neko{idx}",
|
||
container_name=_container_name(idx),
|
||
instance_id_label=str(idx),
|
||
http_port=_http_port(idx),
|
||
mux=_webrtc_mux(idx),
|
||
udp=_udp_range(idx),
|
||
profile=_ensure_profile(idx),
|
||
instance_id_file=_ensure_instance_id_file(idx),
|
||
)
|
||
)
|
||
return "\n".join(lines) + "\n"
|
||
|
||
|
||
def _compose_cmd(*args: str) -> list[str]:
|
||
path = str(_compose_path())
|
||
if shutil.which("docker-compose"):
|
||
return ["docker-compose", "-f", path, *args]
|
||
code, _ = _run(["docker", "compose", "version"], timeout=15)
|
||
if code == 0:
|
||
return ["docker", "compose", "-f", path, *args]
|
||
raise RuntimeError("未找到 docker-compose 或 docker compose,请安装 Docker Compose")
|
||
|
||
|
||
def _compose_up(*, desired: int, start_instances: set[int]) -> tuple[int, str]:
|
||
"""Create all containers stopped; start only requested instances.
|
||
|
||
Do NOT use --remove-orphans — starting a lower id must never wipe higher instances.
|
||
"""
|
||
code, out = _run(_compose_cmd("up", "-d", "--no-start"), timeout=600)
|
||
if code != 0 and "--no-start" in out.lower():
|
||
code, out = _run(_compose_cmd("up", "-d"), timeout=600)
|
||
if code != 0:
|
||
return code, out
|
||
for idx in range(1, desired + 1):
|
||
if idx not in start_instances:
|
||
_run(["docker", "stop", "-t", "5", _container_name(idx)], timeout=30)
|
||
return code, out
|
||
if code != 0:
|
||
return code, out
|
||
for idx in sorted(start_instances):
|
||
if 1 <= idx <= desired:
|
||
_run(["docker", "start", _container_name(idx)], timeout=60)
|
||
return code, out
|
||
|
||
|
||
def _open_firewall(desired: int) -> None:
|
||
"""Best-effort UFW rules for WebRTC ports (HTTP stays nginx-only)."""
|
||
if not shutil.which("ufw"):
|
||
return
|
||
mux_lo = _webrtc_mux(1)
|
||
mux_hi = _webrtc_mux(max(1, desired))
|
||
_run(["ufw", "allow", f"{mux_lo}:{mux_hi}/tcp"], timeout=30)
|
||
_run(["ufw", "allow", f"{mux_lo}:{mux_hi}/udp"], timeout=30)
|
||
for idx in range(1, desired + 1):
|
||
udp = _udp_range(idx)
|
||
_run(["ufw", "allow", f"{udp}/udp"], timeout=30)
|
||
|
||
|
||
def _container_state(instance_id: int, *, check_http: bool = False) -> dict[str, Any]:
|
||
name = _container_name(instance_id)
|
||
port = _http_port(instance_id)
|
||
out: dict[str, Any] = {
|
||
"id": instance_id,
|
||
"container": name,
|
||
"http_port": port,
|
||
"webrtc_mux": _webrtc_mux(instance_id),
|
||
"udp_range": _udp_range(instance_id),
|
||
"studio_url": public_studio_url(instance_id),
|
||
"exists": False,
|
||
"running": False,
|
||
"ready": False,
|
||
"status": "missing",
|
||
"detail": "",
|
||
}
|
||
if not _docker_available():
|
||
out["detail"] = "docker_unavailable"
|
||
return out
|
||
code, text = _run(
|
||
["docker", "inspect", name, "--format", "{{json .State}}"],
|
||
timeout=15,
|
||
)
|
||
if code != 0:
|
||
out["detail"] = text[:200]
|
||
return out
|
||
out["exists"] = True
|
||
try:
|
||
state = json.loads(text or "{}")
|
||
except json.JSONDecodeError:
|
||
out["detail"] = text[:200]
|
||
return out
|
||
running = bool(state.get("Running"))
|
||
health = str((state.get("Health") or {}).get("Status") or "")
|
||
out["running"] = running
|
||
out["oom_killed"] = bool(state.get("OOMKilled"))
|
||
try:
|
||
out["exit_code"] = int(state.get("ExitCode") or 0)
|
||
except (TypeError, ValueError):
|
||
out["exit_code"] = 0
|
||
out["finished_at"] = str(state.get("FinishedAt") or "")[:40]
|
||
if not running:
|
||
out["status"] = "oom" if out["oom_killed"] else "stopped"
|
||
else:
|
||
out["status"] = health if health else "running"
|
||
if running:
|
||
if check_http:
|
||
# Expensive: subprocess curl per instance — only for explicit readiness probes.
|
||
code, text = _run(
|
||
["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"],
|
||
timeout=8,
|
||
)
|
||
out["ready"] = code == 0 and text.strip().endswith("200")
|
||
else:
|
||
# Hot path (relay status polls): docker health / running is enough.
|
||
out["ready"] = health in {"", "healthy", "starting"} or not health
|
||
if health == "unhealthy":
|
||
out["ready"] = False
|
||
return out
|
||
|
||
|
||
def _empty_instance_row(instance_id: int) -> dict[str, Any]:
|
||
return {
|
||
"id": instance_id,
|
||
"container": _container_name(instance_id),
|
||
"http_port": _http_port(instance_id),
|
||
"webrtc_mux": _webrtc_mux(instance_id),
|
||
"udp_range": _udp_range(instance_id),
|
||
"studio_url": public_studio_url(instance_id),
|
||
"exists": False,
|
||
"running": False,
|
||
"ready": False,
|
||
"status": "missing",
|
||
"detail": "",
|
||
}
|
||
|
||
|
||
def _batch_container_states(count: int, *, check_http: bool = False) -> list[dict[str, Any]]:
|
||
"""One `docker ps` for all neko containers — avoids N inspect + N curl on every poll."""
|
||
n = max(0, int(count))
|
||
rows = [_empty_instance_row(i) for i in range(1, n + 1)]
|
||
if n <= 0:
|
||
return rows
|
||
if not _docker_available():
|
||
for r in rows:
|
||
r["detail"] = "docker_unavailable"
|
||
return rows
|
||
|
||
code, text = _run(
|
||
[
|
||
"docker",
|
||
"ps",
|
||
"-a",
|
||
"--filter",
|
||
"name=douyinweb-neko-",
|
||
"--format",
|
||
"{{.Names}}\t{{.State}}\t{{.Status}}",
|
||
],
|
||
timeout=12,
|
||
)
|
||
if code != 0:
|
||
# Fallback to per-instance inspect without HTTP.
|
||
return [_container_state(i, check_http=check_http) for i in range(1, n + 1)]
|
||
|
||
by_name: dict[str, tuple[str, str]] = {}
|
||
for line in (text or "").splitlines():
|
||
parts = line.split("\t")
|
||
if len(parts) < 2:
|
||
continue
|
||
name = parts[0].strip().lstrip("/")
|
||
state = parts[1].strip().lower()
|
||
status = parts[2].strip() if len(parts) > 2 else ""
|
||
by_name[name] = (state, status)
|
||
|
||
for i, row in enumerate(rows, start=1):
|
||
name = _container_name(i)
|
||
hit = by_name.get(name)
|
||
if not hit:
|
||
continue
|
||
state, status = hit
|
||
row["exists"] = True
|
||
running = state == "running"
|
||
row["running"] = running
|
||
status_l = status.lower()
|
||
if not running:
|
||
row["status"] = "stopped"
|
||
row["ready"] = False
|
||
elif "(healthy)" in status_l:
|
||
row["status"] = "healthy"
|
||
row["ready"] = True
|
||
elif "(unhealthy)" in status_l:
|
||
row["status"] = "unhealthy"
|
||
row["ready"] = False
|
||
elif "(health: starting)" in status_l:
|
||
row["status"] = "starting"
|
||
row["ready"] = True
|
||
else:
|
||
row["status"] = "running"
|
||
row["ready"] = True
|
||
if running and check_http:
|
||
port = int(row["http_port"])
|
||
c2, t2 = _run(
|
||
["curl", "-sS", "-o", "/dev/null", "-w", "%{http_code}", f"http://127.0.0.1:{port}/"],
|
||
timeout=8,
|
||
)
|
||
row["ready"] = c2 == 0 and t2.strip().endswith("200")
|
||
return rows
|
||
|
||
|
||
def ensure_capacity(
|
||
desired: int,
|
||
*,
|
||
start_instances: set[int] | None = None,
|
||
reconcile_running: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""Render compose for `desired` instances; create all, start only requested.
|
||
|
||
reconcile_running=True (sync_for_groups): stop instances not in start_instances.
|
||
reconcile_running=False (single start/restart): never stop siblings.
|
||
"""
|
||
_ensure_browser_launch_exec()
|
||
desired = max(0, min(_max_instances(), int(desired or 0)))
|
||
# Never shrink below DB assignment (protects against start(#2) wiping #3+).
|
||
desired = max(desired, _desired_from_db())
|
||
if desired == 0:
|
||
return {"ok": True, "desired": 0, "changed": False, "message": "no_instances"}
|
||
if not _docker_available():
|
||
return {"ok": False, "desired": desired, "error": "Docker 不可用,请先在服务器安装 Docker"}
|
||
|
||
start_set = set(start_instances or ())
|
||
|
||
with _lock:
|
||
try:
|
||
compose = _compose_path()
|
||
text = _render_compose(desired)
|
||
changed = not compose.is_file() or compose.read_text(encoding="utf-8") != text
|
||
if changed:
|
||
# Persist desired compose for next explicit recreate — do NOT force
|
||
# `compose up` solely because YAML text changed (that kills keep-warm
|
||
# Chrome logins/tabs on every API deploy that touches render).
|
||
compose.write_text(text, encoding="utf-8")
|
||
|
||
missing = [i for i in range(1, desired + 1) if not _container_state(i).get("exists")]
|
||
need_up = bool(missing)
|
||
out = ""
|
||
if need_up:
|
||
code, out = _compose_up(desired=desired, start_instances=start_set)
|
||
if code != 0:
|
||
return {"ok": False, "desired": desired, "error": out[:800] or "compose up failed"}
|
||
else:
|
||
for idx in sorted(start_set):
|
||
if 1 <= idx <= desired and not _container_state(idx).get("running"):
|
||
_run(["docker", "start", _container_name(idx)], timeout=60)
|
||
|
||
stopped: list[int] = []
|
||
if reconcile_running:
|
||
for idx in range(1, desired + 1):
|
||
st = _container_state(idx)
|
||
if st.get("running") and idx not in start_set:
|
||
_run(["docker", "stop", "-t", "8", _container_name(idx)], timeout=45)
|
||
stopped.append(idx)
|
||
|
||
if changed or need_up:
|
||
_open_firewall(desired)
|
||
sync_nginx_proxy(desired)
|
||
created = sum(1 for i in range(1, desired + 1) if _container_state(i).get("exists"))
|
||
return {
|
||
"ok": True,
|
||
"desired": desired,
|
||
"created": created,
|
||
"changed": changed,
|
||
"compose_up": need_up,
|
||
"started": sorted(start_set),
|
||
"stopped": stopped,
|
||
"nat1to1": _detect_public_ip(),
|
||
"detail": (out or "")[:300],
|
||
}
|
||
except RuntimeError as exc:
|
||
return {"ok": False, "desired": desired, "error": str(exc)}
|
||
|
||
|
||
def sync_nginx_proxy(count: int) -> dict[str, Any]:
|
||
"""Nginx: /neko/{id}/ → http://127.0.0.1:920x/ (strip prefix; Neko has no path_prefix)."""
|
||
caddy = sync_caddy_neko_snippet(count)
|
||
base = _public_base()
|
||
if not base:
|
||
return {"ok": False, "skipped": "no_public_base", "caddy": caddy}
|
||
host = urlparse(base).hostname or ""
|
||
if not host:
|
||
return {"ok": False, "skipped": "no_host", "caddy": caddy}
|
||
if not Path("/etc/nginx/conf.d").is_dir():
|
||
return {"ok": False, "skipped": "no_nginx", "caddy": caddy}
|
||
|
||
blocks: list[str] = []
|
||
for idx in range(1, max(0, int(count)) + 1):
|
||
port = _http_port(idx)
|
||
# Trailing slash on proxy_pass strips /neko/{idx}/ → container /
|
||
blocks.append(
|
||
f"""
|
||
location = /neko/{idx} {{
|
||
return 301 /neko/{idx}/;
|
||
}}
|
||
location ^~ /neko/{idx}/ {{
|
||
proxy_pass http://127.0.0.1:{port}/;
|
||
proxy_http_version 1.1;
|
||
proxy_set_header Host $host;
|
||
proxy_set_header X-Real-IP $remote_addr;
|
||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||
proxy_set_header X-Forwarded-Proto $scheme;
|
||
proxy_set_header Upgrade $http_upgrade;
|
||
proxy_set_header Connection "upgrade";
|
||
proxy_cache_bypass $http_upgrade;
|
||
proxy_read_timeout 3600s;
|
||
proxy_send_timeout 3600s;
|
||
}}"""
|
||
)
|
||
|
||
include_path = Path("/etc/nginx/conf.d/douyinweb-neko-locations.inc")
|
||
try:
|
||
include_path.write_text("\n".join(blocks) + "\n", encoding="utf-8")
|
||
legacy = Path("/etc/nginx/conf.d/douyinweb-neko-locations.conf")
|
||
if legacy.is_file():
|
||
legacy.unlink()
|
||
|
||
vhost = Path("/etc/nginx/conf.d/dy-nomadro-live.conf")
|
||
if not vhost.is_file():
|
||
for p in Path("/etc/nginx/conf.d").glob("*.conf"):
|
||
if "nomadro" in p.name or "douyin" in p.name:
|
||
vhost = p
|
||
break
|
||
if vhost.is_file():
|
||
raw = vhost.read_text(encoding="utf-8")
|
||
marker = f"include {include_path};"
|
||
legacy_marker = "include /etc/nginx/conf.d/douyinweb-neko-locations.conf;"
|
||
if legacy_marker in raw:
|
||
raw = raw.replace(legacy_marker, marker)
|
||
elif marker not in raw and "douyinweb-neko-locations" not in raw:
|
||
raw = raw.replace(
|
||
"location / {",
|
||
f" {marker}\n\n location / {{",
|
||
1,
|
||
)
|
||
vhost.write_text(raw, encoding="utf-8")
|
||
|
||
code, out = _run(["nginx", "-t"], timeout=15)
|
||
if code != 0:
|
||
return {"ok": False, "error": out[:400] or "nginx -t failed"}
|
||
_run(["systemctl", "reload", "nginx"], timeout=15)
|
||
return {"ok": True, "instances": count, "caddy": caddy}
|
||
except OSError as exc:
|
||
return {"ok": False, "error": str(exc), "caddy": caddy}
|
||
|
||
|
||
def sync_caddy_neko_snippet(count: int) -> dict[str, Any]:
|
||
"""Write Caddy fragment for edges.
|
||
|
||
Preferred (unlimited): single `/neko/*` → `{upstream}:{gateway_port}` where the
|
||
physical API runs neko_edge_gateway. Legacy per-id blocks still generated as
|
||
fallback when DY_NEKO_GATEWAY_ENABLED=0.
|
||
"""
|
||
n = max(0, min(_max_instances(), int(count or 0)))
|
||
upstream_host = str(os.environ.get("DY_NEKO_EDGE_UPSTREAM") or "127.0.0.1").strip() or "127.0.0.1"
|
||
gw_port = int(getattr(settings, "neko_gateway_port", 9199) or 9199)
|
||
gw_on = True
|
||
try:
|
||
from . import neko_edge_gateway
|
||
|
||
gw_on = neko_edge_gateway.gateway_enabled()
|
||
except Exception:
|
||
gw_on = bool(getattr(settings, "neko_gateway_enabled", True))
|
||
|
||
lines = [
|
||
"# Generated by douyinWEB youtube_neko.sync_caddy_neko_snippet — do not hand-edit",
|
||
f"# instances={n} upstream={upstream_host} gateway={gw_on} gw_port={gw_port}",
|
||
]
|
||
if gw_on:
|
||
lines.extend(
|
||
[
|
||
"handle /neko {",
|
||
"\tredir /neko/ 308",
|
||
"}",
|
||
"@neko path /neko /neko/*",
|
||
"handle @neko {",
|
||
f"\treverse_proxy {upstream_host}:{gw_port} {{",
|
||
"\t\theader_up Host {host}",
|
||
"\t\theader_up X-Forwarded-Proto {scheme}",
|
||
"\t\theader_up X-Forwarded-Host {host}",
|
||
"\t}",
|
||
"}",
|
||
]
|
||
)
|
||
else:
|
||
for idx in range(1, n + 1):
|
||
port = _http_port(idx)
|
||
lines.extend(
|
||
[
|
||
f"handle /neko/{idx} {{",
|
||
f"\tredir /neko/{idx}/ 308",
|
||
"}",
|
||
f"handle_path /neko/{idx}/* {{",
|
||
f"\treverse_proxy {upstream_host}:{port} {{",
|
||
"\t\theader_up Host {host}",
|
||
"\t\theader_up X-Forwarded-Proto {scheme}",
|
||
"\t}",
|
||
"}",
|
||
]
|
||
)
|
||
out = _neko_root() / "caddy-neko.snippet"
|
||
try:
|
||
_neko_root().mkdir(parents=True, exist_ok=True)
|
||
out.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||
return {
|
||
"ok": True,
|
||
"path": str(out),
|
||
"instances": n,
|
||
"upstream": upstream_host,
|
||
"gateway": gw_on,
|
||
"gateway_port": gw_port,
|
||
}
|
||
except OSError as exc:
|
||
return {"ok": False, "error": str(exc)}
|
||
|
||
|
||
def _host_http_ok(instance_id: int) -> bool:
|
||
"""True when published host port answers (detects stale containers with empty PortBindings)."""
|
||
port = _http_port(int(instance_id))
|
||
# Always bypass env HTTP(S)_PROXY — otherwise curl to 127.0.0.1:920x goes via proxy
|
||
# and falsely reports dead, triggering endless force-recreate → public /neko/N 502.
|
||
code, text = _run(
|
||
[
|
||
"curl",
|
||
"-sS",
|
||
"--noproxy",
|
||
"*",
|
||
"-o",
|
||
"/dev/null",
|
||
"-w",
|
||
"%{http_code}",
|
||
"--connect-timeout",
|
||
"2",
|
||
f"http://127.0.0.1:{port}/",
|
||
],
|
||
timeout=6,
|
||
)
|
||
return code == 0 and (text or "").strip() in {"200", "401", "403"}
|
||
|
||
|
||
def instance_action(instance_id: int, action: str) -> dict[str, Any]:
|
||
action = str(action or "").strip().lower()
|
||
if action not in {"status", "start", "stop", "restart"}:
|
||
raise ValueError(f"不支持的操作: {action}")
|
||
if instance_id < 1 or instance_id > _max_instances():
|
||
raise ValueError(f"实例编号须在 1–{_max_instances()}")
|
||
|
||
before = _container_state(instance_id)
|
||
message = f"Neko {instance_id}: {before.get('status')}"
|
||
# Always provision to max assigned id so --remove-orphans cannot wipe siblings.
|
||
desired = max(instance_id, _desired_from_db())
|
||
name = _container_name(instance_id)
|
||
svc = f"neko{int(instance_id)}"
|
||
|
||
if action == "start":
|
||
ensure_capacity(desired, start_instances={instance_id})
|
||
code, out = _run(["docker", "start", name], timeout=60)
|
||
if code != 0 or not _host_http_ok(instance_id):
|
||
# Stale container (e.g. created while :920x was occupied) — force recreate.
|
||
_run(["docker", "rm", "-f", name], timeout=30)
|
||
ensure_capacity(desired, start_instances=set())
|
||
code, out = _run(
|
||
_compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc),
|
||
timeout=300,
|
||
)
|
||
if code != 0:
|
||
raise RuntimeError(out or "force-recreate 失败")
|
||
code, out = _run(["docker", "start", name], timeout=60)
|
||
if code != 0:
|
||
raise RuntimeError(out or "启动失败")
|
||
if not _host_http_ok(instance_id):
|
||
raise RuntimeError(
|
||
f"Neko {instance_id} 已启动但主机口 {_http_port(instance_id)} 不可达"
|
||
"(检查是否有其它进程占用,或 FRP 辅路误绑 :920x)"
|
||
)
|
||
message = f"Neko {instance_id} 已启动"
|
||
elif action == "stop":
|
||
if before.get("exists"):
|
||
code, out = _run(["docker", "stop", "-t", "10", name], timeout=45)
|
||
if code != 0:
|
||
raise RuntimeError(out or "停止失败")
|
||
message = f"Neko {instance_id} 已停止"
|
||
elif action == "restart":
|
||
ensure_capacity(desired, start_instances={instance_id})
|
||
code, out = _run(["docker", "restart", "-t", "8", name], timeout=90)
|
||
if code != 0 or not _host_http_ok(instance_id):
|
||
_run(["docker", "rm", "-f", name], timeout=30)
|
||
ensure_capacity(desired, start_instances=set())
|
||
code, out = _run(
|
||
_compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc),
|
||
timeout=300,
|
||
)
|
||
if code != 0:
|
||
raise RuntimeError(out or "force-recreate 失败")
|
||
code, out = _run(["docker", "start", name], timeout=60)
|
||
if code != 0:
|
||
raise RuntimeError(out or "重启失败")
|
||
message = f"Neko {instance_id} 已重启"
|
||
|
||
after = _container_state(instance_id)
|
||
after["action"] = action
|
||
after["message"] = message
|
||
after["available"] = _docker_available()
|
||
_invalidate_list_cache()
|
||
return after
|
||
|
||
|
||
def list_instances(count: int, *, check_http: bool = False) -> list[dict[str, Any]]:
|
||
"""Read container states; TTL cache for relay status polls (no HTTP curl by default)."""
|
||
global _list_cache_at, _list_cache_count, _list_cache_rows, _list_cache_check_http
|
||
import time as _time
|
||
|
||
n = max(0, int(count))
|
||
now = _time.time()
|
||
if (
|
||
_list_cache_rows
|
||
and _list_cache_count == n
|
||
and _list_cache_check_http == bool(check_http)
|
||
and (now - _list_cache_at) < _LIST_CACHE_TTL_SEC
|
||
):
|
||
return list(_list_cache_rows)
|
||
rows = _batch_container_states(n, check_http=bool(check_http))
|
||
_list_cache_rows = rows
|
||
_list_cache_count = n
|
||
_list_cache_check_http = bool(check_http)
|
||
_list_cache_at = now
|
||
return list(rows)
|
||
|
||
|
||
def _invalidate_list_cache() -> None:
|
||
global _list_cache_at
|
||
_list_cache_at = 0.0
|
||
|
||
|
||
def _docker_max_instance_id() -> int:
|
||
"""Highest douyinweb-neko-N that exists (even if groups table is empty)."""
|
||
if not _docker_available():
|
||
return 0
|
||
code, text = _run(
|
||
[
|
||
"docker",
|
||
"ps",
|
||
"-a",
|
||
"--filter",
|
||
"name=douyinweb-neko-",
|
||
"--format",
|
||
"{{.Names}}",
|
||
],
|
||
timeout=12,
|
||
)
|
||
if code != 0:
|
||
return 0
|
||
best = 0
|
||
for line in (text or "").splitlines():
|
||
name = line.strip().lstrip("/")
|
||
if not name.startswith("douyinweb-neko-"):
|
||
continue
|
||
suffix = name[len("douyinweb-neko-") :]
|
||
try:
|
||
best = max(best, int(suffix))
|
||
except ValueError:
|
||
continue
|
||
return best
|
||
|
||
|
||
def status_summary(*, desired: int) -> dict[str, Any]:
|
||
"""Read-only status — does not run compose/nginx."""
|
||
desired = max(0, min(_max_instances(), int(desired or 0)))
|
||
if desired < 1:
|
||
desired = _desired_from_db()
|
||
# Physical / ops: show already-created containers even before assign groups exist.
|
||
desired = max(desired, _docker_max_instance_id())
|
||
instances = list_instances(desired)
|
||
running = sum(1 for x in instances if x.get("running"))
|
||
assets = _asset_root()
|
||
return {
|
||
"available": _docker_available(),
|
||
"desired": desired,
|
||
"running": running,
|
||
"instances": instances,
|
||
"enabled": bool(getattr(settings, "neko_enabled", True)),
|
||
"nat1to1": _detect_public_ip(),
|
||
"http_bind": _http_bind(),
|
||
# No plaintext passwords in API responses.
|
||
"login_hint": "用户名任意;普通密码见 DY_NEKO_USER_PASS;管理员密码见 DY_NEKO_ADMIN_PASS",
|
||
"assets": {
|
||
"root": str(assets),
|
||
"tampermonkey_seed": (assets / "tampermonkey-seed" / "Default" / "Extensions").is_dir(),
|
||
"userscript": (assets / "provisioning" / "youtube-studio-auto-dismiss.user.js").is_file(),
|
||
"browser_launch": (assets / "browser-launch.sh").is_file(),
|
||
"live_ops": (assets / "live-ops-extension" / "manifest.json").is_file(),
|
||
"managed_policies": _managed_policies_enabled(),
|
||
},
|
||
"studio_telemetry": latest_studio_telemetry(limit=8),
|
||
}
|
||
|
||
|
||
def sync_for_groups(
|
||
groups: list[dict[str, Any]],
|
||
*,
|
||
reconcile_running: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""Ensure docker containers exist for all assign groups; start only neko_enabled.
|
||
|
||
reconcile_running=False (default): create capacity / start enabled — never stop
|
||
siblings (physical keep-warm + exclusive-live Studio must survive API boot).
|
||
True: stop containers whose groups are not neko_enabled (explicit ops only).
|
||
"""
|
||
ids = [int(g.get("neko_instance_id") or 0) for g in groups if int(g.get("neko_instance_id") or 0) > 0]
|
||
desired = max(ids) if ids else 0
|
||
if desired == 0:
|
||
return {"ok": True, "desired": 0}
|
||
start_set = {
|
||
int(g.get("neko_instance_id") or 0)
|
||
for g in groups
|
||
if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
|
||
}
|
||
return ensure_capacity(desired, start_instances=start_set, reconcile_running=reconcile_running)
|
||
|
||
|
||
def _graceful_chrome_quit(instance_id: int, *, wait_sec: float = 6.0) -> dict[str, Any]:
|
||
"""Ask Chrome inside Neko to exit cleanly so Sessions/tabs flush before docker stop."""
|
||
import time as _time
|
||
|
||
name = _container_name(instance_id)
|
||
# SIGTERM chrome first (session flush); fall back to pkill names used in image.
|
||
script = (
|
||
"set +e; "
|
||
"pkill -TERM -f '/opt/google/chrome/chrome' 2>/dev/null; "
|
||
"pkill -TERM -f 'google-chrome' 2>/dev/null; "
|
||
"pkill -TERM -f 'chromium' 2>/dev/null; "
|
||
"exit 0"
|
||
)
|
||
_run(["docker", "exec", name, "sh", "-c", script], timeout=10)
|
||
deadline = _time.time() + max(2.0, float(wait_sec))
|
||
while _time.time() < deadline:
|
||
code, out = _run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
name,
|
||
"sh",
|
||
"-c",
|
||
"pgrep -f '/opt/google/chrome/chrome|google-chrome|chromium' >/dev/null 2>&1; echo $?",
|
||
],
|
||
timeout=8,
|
||
)
|
||
# echo $? → 1 means no matching process
|
||
if (out or "").strip().splitlines()[-1:] == ["1"]:
|
||
return {"ok": True, "quit": True}
|
||
_time.sleep(0.4)
|
||
return {"ok": True, "quit": False, "note": "chrome_still_running"}
|
||
|
||
|
||
def cdp_end_studio_stream(instance_id: int) -> dict[str, Any]:
|
||
"""Click Studio End Stream (+ confirm) via CDP inside a running Neko."""
|
||
idx = int(instance_id or 0)
|
||
if idx < 1:
|
||
return {"ok": False, "error": "bad_id"}
|
||
st = _container_state(idx, check_http=False)
|
||
if not st.get("running"):
|
||
return {"ok": False, "error": "neko_not_running", "id": idx}
|
||
script = _asset_root() / "cdp_end_stream.py"
|
||
if not script.is_file():
|
||
return {"ok": False, "error": "end_stream_script_missing"}
|
||
try:
|
||
script_text = script.read_text(encoding="utf-8")
|
||
except OSError as exc:
|
||
return {"ok": False, "error": f"read_script:{exc}"}
|
||
name = _container_name(idx)
|
||
# Prefer focusing live tab first (no-op if already open).
|
||
try:
|
||
_cdp_nudge_live_studio_tab(idx)
|
||
except Exception:
|
||
pass
|
||
code, out = _run(
|
||
["docker", "exec", "-i", name, "python3", "-"],
|
||
timeout=35,
|
||
input_text=script_text,
|
||
)
|
||
try:
|
||
line = (out or "").strip().splitlines()[-1] if (out or "").strip() else "{}"
|
||
row = json.loads(line)
|
||
if isinstance(row, dict):
|
||
row["id"] = idx
|
||
return row
|
||
except Exception:
|
||
pass
|
||
return {"ok": False, "id": idx, "error": (out or f"exit_{code}")[:220]}
|
||
|
||
|
||
def end_live_session(
|
||
instance_id: int,
|
||
*,
|
||
channel_pk: str = "",
|
||
wait_encoder_lost_sec: float = 12.0,
|
||
settle_sec: float = 3.0,
|
||
) -> dict[str, Any]:
|
||
"""Graceful YouTube live end while Neko is still up.
|
||
|
||
Order: wait briefly for encoder-lost UI → CDP End Stream → OAuth complete fallback.
|
||
Does **not** stop the Neko container.
|
||
"""
|
||
import time as _time
|
||
|
||
idx = int(instance_id or 0)
|
||
out: dict[str, Any] = {"ok": False, "id": idx, "steps": []}
|
||
if idx < 1:
|
||
out["error"] = "bad_id"
|
||
return out
|
||
st = _container_state(idx, check_http=False)
|
||
if not st.get("running"):
|
||
out["ok"] = True
|
||
out["skipped"] = "neko_not_running"
|
||
return out
|
||
|
||
# Give Studio a moment to flip Excellent → No data after FFmpeg stop.
|
||
wait_need = max(0.0, float(wait_encoder_lost_sec))
|
||
deadline = _time.time() + wait_need
|
||
saw_lost = False
|
||
while _time.time() < deadline:
|
||
try:
|
||
sig = _cdp_studio_page_signals(idx, max_age_sec=0.0, force=True)
|
||
except Exception:
|
||
sig = {}
|
||
live_status = str((sig or {}).get("live_status") or "").lower()
|
||
if live_status in {"encoder_lost", "ended", "waiting"} or not bool((sig or {}).get("on_air")):
|
||
if live_status == "ended":
|
||
out["ok"] = True
|
||
out["steps"].append({"cdp_wait": "already_ended"})
|
||
return out
|
||
saw_lost = True
|
||
break
|
||
_time.sleep(1.0)
|
||
out["steps"].append({"encoder_lost_wait": True, "saw_hint": saw_lost})
|
||
|
||
cdp = cdp_end_studio_stream(idx)
|
||
out["steps"].append({"cdp_end": cdp})
|
||
cdp_ok = bool(cdp.get("ok"))
|
||
|
||
api: dict[str, Any] = {"skipped": True}
|
||
if (not cdp_ok) and str(channel_pk or "").strip():
|
||
try:
|
||
import asyncio
|
||
|
||
from . import youtube_manage
|
||
|
||
try:
|
||
loop = asyncio.get_running_loop()
|
||
except RuntimeError:
|
||
loop = None
|
||
if loop and loop.is_running():
|
||
# Sync caller inside async context — use a dedicated loop in a thread.
|
||
import concurrent.futures
|
||
|
||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as pool:
|
||
api = pool.submit(
|
||
lambda: asyncio.run(
|
||
youtube_manage.complete_active_live_broadcast(str(channel_pk))
|
||
)
|
||
).result(timeout=60)
|
||
else:
|
||
api = asyncio.run(youtube_manage.complete_active_live_broadcast(str(channel_pk)))
|
||
except Exception as exc:
|
||
api = {"ok": False, "error": str(exc)[:200]}
|
||
out["steps"].append({"api_complete": api})
|
||
|
||
settle = max(0.0, float(settle_sec))
|
||
if settle:
|
||
_time.sleep(settle)
|
||
out["ok"] = cdp_ok or bool(api.get("ok") or api.get("skipped") == "no_active_live")
|
||
if not out["ok"] and not out.get("error"):
|
||
out["error"] = "end_stream_unconfirmed"
|
||
return out
|
||
|
||
|
||
def stop_instance(instance_id: int) -> dict[str, Any]:
|
||
"""Stop one Neko container (time-slot off-duty). Does not change neko_enabled."""
|
||
idx = int(instance_id or 0)
|
||
if idx < 1:
|
||
return {"ok": False, "skipped": "no_instance"}
|
||
st = _container_state(idx)
|
||
if not st.get("running"):
|
||
return {"ok": True, "id": idx, "already_stopped": True}
|
||
# Flush Chrome session before container SIGKILL window — keeps operator tabs on next start.
|
||
try:
|
||
_graceful_chrome_quit(idx, wait_sec=6.0)
|
||
except Exception:
|
||
pass
|
||
code, out = _run(["docker", "stop", "-t", "12", _container_name(idx)], timeout=50)
|
||
if code != 0:
|
||
return {"ok": False, "id": idx, "error": (out or "stop failed")[:300]}
|
||
return {"ok": True, "id": idx, "stopped": True}
|
||
|
||
|
||
def stop_instances_except(keep_instance_id: int) -> list[int]:
|
||
"""Stop running Neko containers except `keep_instance_id`. Does not change neko_enabled."""
|
||
keep = int(keep_instance_id or 0)
|
||
desired = max(_desired_from_db(), keep, 0)
|
||
stopped: list[int] = []
|
||
for idx in range(1, desired + 1):
|
||
if idx == keep:
|
||
continue
|
||
st = _container_state(idx)
|
||
if not st.get("running"):
|
||
continue
|
||
res = stop_instance(idx)
|
||
if res.get("ok") and res.get("stopped"):
|
||
stopped.append(idx)
|
||
return stopped
|
||
|
||
|
||
def _host_http_published(instance_id: int) -> bool:
|
||
"""True when docker-proxy has the instance HTTP port (even if app still booting)."""
|
||
port = _http_port(int(instance_id))
|
||
code, text = _run(
|
||
["ss", "-lnt"],
|
||
timeout=6,
|
||
)
|
||
needle = f":{port}"
|
||
return code == 0 and needle in (text or "")
|
||
|
||
|
||
def ensure_instance_running(instance_id: int) -> dict[str, Any]:
|
||
"""Ensure one Neko container exists and is running (for exclusive-live winner)."""
|
||
import time as _time
|
||
|
||
_ensure_browser_launch_exec()
|
||
idx = int(instance_id or 0)
|
||
if idx < 1:
|
||
return {"ok": False, "skipped": "no_instance"}
|
||
desired = max(_desired_from_db(), idx)
|
||
ensure_capacity(desired, start_instances={idx}, reconcile_running=False)
|
||
name = _container_name(idx)
|
||
svc = f"neko{idx}"
|
||
st = _container_state(idx)
|
||
if st.get("running") and _host_http_ok(idx):
|
||
return {"ok": True, "id": idx, "already": True}
|
||
|
||
# Booting: port published but / not answering yet — wait, do not recreate (avoids 502 races).
|
||
if st.get("running") and _host_http_published(idx) and not _host_http_ok(idx):
|
||
for _ in range(20):
|
||
_time.sleep(2.0)
|
||
if _host_http_ok(idx):
|
||
return {"ok": True, "id": idx, "waited_boot": True}
|
||
# fall through to recreate only if still dead after ~40s
|
||
|
||
# Stale exists with no published HTTP — force remove then compose up once.
|
||
if st.get("exists") and (not st.get("running") or not _host_http_ok(idx)):
|
||
_run(["docker", "rm", "-f", name], timeout=45)
|
||
ensure_capacity(desired, start_instances=set())
|
||
code, out = _run(
|
||
_compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc),
|
||
timeout=300,
|
||
)
|
||
if code != 0:
|
||
return {"ok": False, "id": idx, "error": (out or "force-recreate failed")[:300]}
|
||
_run(["docker", "start", name], timeout=60)
|
||
for _ in range(20):
|
||
if _host_http_ok(idx):
|
||
return {"ok": True, "id": idx, "recreated": True}
|
||
_time.sleep(2.0)
|
||
return {
|
||
"ok": False,
|
||
"id": idx,
|
||
"error": f"recreated but host port {_http_port(idx)} unreachable",
|
||
}
|
||
|
||
code, out = _run(["docker", "start", name], timeout=60)
|
||
if code != 0:
|
||
return {"ok": False, "id": idx, "error": (out or "start failed")[:300]}
|
||
for _ in range(15):
|
||
if _host_http_ok(idx):
|
||
return {"ok": True, "id": idx, "started": True}
|
||
_time.sleep(2.0)
|
||
if not _host_http_ok(idx):
|
||
_run(["docker", "rm", "-f", name], timeout=45)
|
||
ensure_capacity(desired, start_instances=set())
|
||
code, out = _run(
|
||
_compose_cmd("up", "-d", "--force-recreate", "--no-deps", svc),
|
||
timeout=300,
|
||
)
|
||
if code != 0:
|
||
return {"ok": False, "id": idx, "error": (out or "force-recreate failed")[:300]}
|
||
_run(["docker", "start", name], timeout=60)
|
||
for _ in range(20):
|
||
if _host_http_ok(idx):
|
||
return {"ok": True, "id": idx, "recreated": True}
|
||
_time.sleep(2.0)
|
||
return {
|
||
"ok": False,
|
||
"id": idx,
|
||
"error": f"started but host port {_http_port(idx)} unreachable",
|
||
}
|
||
return {"ok": True, "id": idx, "started": True}
|
||
|
||
|
||
# Soft heal: restart crashed/OOM Nekos that Live still needs. Never wipe volumes.
|
||
_NEKO_HEAL_LAST: dict[int, float] = {}
|
||
_NEKO_HEAL_COOLDOWN_SEC = 180.0
|
||
|
||
|
||
def _neko_ids_needed_for_live() -> set[int]:
|
||
"""Instances that must stay up: DB enabled, exclusive winner, or actively pushing."""
|
||
needed: set[int] = set()
|
||
try:
|
||
from . import yt_assign_db
|
||
|
||
for g in yt_assign_db.list_groups(include_urls=False):
|
||
try:
|
||
nid = int(g.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
if nid < 1:
|
||
continue
|
||
if g.get("neko_enabled"):
|
||
needed.add(nid)
|
||
except Exception:
|
||
pass
|
||
try:
|
||
from . import youtube_relay_db
|
||
from .youtube_relay_pipeline import youtube_relay_pipeline
|
||
|
||
winner = str(getattr(youtube_relay_pipeline, "_exclusive_winner", None) or "").strip()
|
||
if winner:
|
||
from . import yt_assign_db
|
||
|
||
wg = yt_assign_db.get_group(winner) or {}
|
||
try:
|
||
wn = int(wg.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
wn = 0
|
||
if wn > 0:
|
||
needed.add(wn)
|
||
for row in youtube_relay_db.list_relay_states():
|
||
st = str(row.get("status") or "")
|
||
if st not in {"pushing", "starting", "reconnecting"}:
|
||
continue
|
||
gid = str(row.get("group_id") or "")
|
||
if not gid:
|
||
continue
|
||
from . import yt_assign_db
|
||
|
||
g = yt_assign_db.get_group(gid) or {}
|
||
try:
|
||
nid = int(g.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
if nid > 0:
|
||
needed.add(nid)
|
||
except Exception:
|
||
pass
|
||
# In-memory sessions are authoritative after API restart orphans DB rows.
|
||
try:
|
||
from .youtube_relay_pipeline import youtube_relay_pipeline
|
||
from . import yt_assign_db
|
||
|
||
for gid in list(getattr(youtube_relay_pipeline, "_sessions", {}) or {}):
|
||
g = yt_assign_db.get_group(str(gid)) or {}
|
||
try:
|
||
nid = int(g.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
if nid > 0:
|
||
needed.add(nid)
|
||
except Exception:
|
||
pass
|
||
return needed
|
||
|
||
|
||
def heal_crashed_assign_nekos() -> dict[str, Any]:
|
||
"""If a needed Neko exited / OOM-killed, docker start it (profile volumes untouched).
|
||
|
||
Does NOT start idle disabled instances. Cooldown 180s per instance.
|
||
"""
|
||
import time as _time
|
||
|
||
needed = _neko_ids_needed_for_live()
|
||
if not needed:
|
||
return {"ok": True, "needed": 0, "healed": [], "skipped": []}
|
||
now = _time.time()
|
||
healed: list[dict[str, Any]] = []
|
||
skipped: list[dict[str, Any]] = []
|
||
for nid in sorted(needed):
|
||
last = float(_NEKO_HEAL_LAST.get(nid) or 0)
|
||
if now - last < _NEKO_HEAL_COOLDOWN_SEC:
|
||
skipped.append({"id": nid, "reason": "cooldown"})
|
||
continue
|
||
st = _container_state(nid, check_http=False)
|
||
if st.get("running"):
|
||
skipped.append({"id": nid, "reason": "already_running"})
|
||
continue
|
||
reason = "oom" if st.get("oom_killed") else f"exit:{st.get('exit_code')}"
|
||
_NEKO_HEAL_LAST[nid] = now
|
||
res = ensure_instance_running(nid)
|
||
healed.append({"id": nid, "reason": reason, "result": res})
|
||
return {"ok": True, "needed": len(needed), "healed": healed, "skipped": skipped}
|
||
|
||
|
||
_CHROME_HEAL_LAST: dict[int, float] = {}
|
||
_CHROME_HEAL_COOLDOWN_SEC = 120.0
|
||
_CDP_FAIL_STREAK: dict[int, int] = {}
|
||
_RENDERER_FAIL_STREAK: dict[int, int] = {}
|
||
|
||
|
||
def _devtools_version_ok(instance_id: int) -> bool:
|
||
name = _container_name(instance_id)
|
||
code, _out = _run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
name,
|
||
"bash",
|
||
"-lc",
|
||
"curl -fsS -m 2 http://127.0.0.1:9222/json/version >/dev/null 2>&1 "
|
||
"|| wget -q -T 2 -O /dev/null http://127.0.0.1:9222/json/version >/dev/null 2>&1",
|
||
],
|
||
timeout=12,
|
||
)
|
||
return code == 0
|
||
|
||
|
||
def _chrome_log_recent_sigill(instance_id: int, *, window_sec: int = 600) -> bool:
|
||
"""True if google-chrome.log mentions SIGILL and was written recently."""
|
||
name = _container_name(instance_id)
|
||
# mtime within window + any SIGILL/Illegal instruction hit in the log file.
|
||
py = (
|
||
"import os,re,time\n"
|
||
f"win={int(window_sec)}\n"
|
||
"p='/var/log/neko/google-chrome.log'\n"
|
||
"try:\n"
|
||
" st=os.stat(p)\n"
|
||
"except OSError:\n"
|
||
" print('0'); raise SystemExit\n"
|
||
"if time.time()-st.st_mtime>win:\n"
|
||
" print('0'); raise SystemExit\n"
|
||
"try:\n"
|
||
" data=open(p,'rb').read()[-250000].decode('utf-8','ignore')\n"
|
||
"except OSError:\n"
|
||
" print('0'); raise SystemExit\n"
|
||
"print('1' if re.search(r'SIGILL|Illegal instruction|STATUS_INVALID_IMAGE_HASH|"
|
||
"Aw,\\s*Snap', data, re.I) else '0')\n"
|
||
)
|
||
code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=12)
|
||
return code == 0 and str(out or "").strip().endswith("1")
|
||
|
||
|
||
def _chrome_renderer_probe(instance_id: int) -> str:
|
||
"""Probe real page DOM via CDP Runtime.evaluate.
|
||
|
||
Tab metadata often still says "YouTube Creator Studio" while Aw Snap / SIGILL
|
||
is on screen — evaluate title/body (or timeout) is the reliable signal.
|
||
Empty string = healthy / inconclusive (no page tab).
|
||
"""
|
||
name = _container_name(instance_id)
|
||
# Compact WS client — same framing as cdp_studio_scrape.py; 4s eval deadline.
|
||
script = r'''
|
||
import base64,json,os,socket,struct,sys,time,urllib.request
|
||
def ws_connect(url):
|
||
hostport,path=url[5:].split('/',1); path='/'+path
|
||
host,port=hostport.split(':'); port=int(port)
|
||
key=base64.b64encode(os.urandom(16)).decode()
|
||
s=socket.create_connection((host,port),timeout=5)
|
||
s.settimeout(5)
|
||
s.sendall(f"GET {path} HTTP/1.1\r\nHost: {hostport}\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Key: {key}\r\nSec-WebSocket-Version: 13\r\n\r\n".encode())
|
||
buf=b''
|
||
while b'\r\n\r\n' not in buf:
|
||
c=s.recv(4096)
|
||
if not c: raise RuntimeError('hs')
|
||
buf+=c
|
||
return s
|
||
def ws_send(s,payload):
|
||
data=json.dumps(payload).encode(); mask=os.urandom(4)
|
||
h=bytearray([0x81]); n=len(data)
|
||
if n<126: h.append(0x80|n)
|
||
elif n<65536: h.append(0x80|126); h.extend(struct.pack('!H',n))
|
||
else: h.append(0x80|127); h.extend(struct.pack('!Q',n))
|
||
h.extend(mask); s.sendall(bytes(h)+bytes(b^mask[i%4] for i,b in enumerate(data)))
|
||
def ws_recv(s):
|
||
def ex(n):
|
||
o=b''
|
||
while len(o)<n:
|
||
c=s.recv(n-len(o))
|
||
if not c: raise RuntimeError('closed')
|
||
o+=c
|
||
return o
|
||
b1,b2=ex(2); opcode=b1&0x0f; masked=(b2&0x80)!=0; ln=b2&0x7f
|
||
if ln==126: ln=struct.unpack('!H',ex(2))[0]
|
||
elif ln==127: ln=struct.unpack('!Q',ex(8))[0]
|
||
mask=ex(4) if masked else b''; data=ex(ln)
|
||
if masked: data=bytes(b^mask[i%4] for i,b in enumerate(data))
|
||
if opcode==8: return None
|
||
if opcode!=1: return {'id':None}
|
||
return json.loads(data.decode())
|
||
try:
|
||
tabs=json.load(urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=3))
|
||
except Exception as e:
|
||
print(json.dumps({'reason':'cdp_list_fail','err':str(e)[:80]})); raise SystemExit
|
||
pages=[t for t in tabs if (t.get('type') or '')=='page']
|
||
if not pages:
|
||
print(json.dumps({'reason':''})); raise SystemExit
|
||
# Prefer Studio Live tab; else first page.
|
||
pick=None
|
||
for t in pages:
|
||
u=(t.get('url') or '').lower()
|
||
if 'studio.youtube.com' in u and 'livestreaming' in u:
|
||
pick=t; break
|
||
if pick is None:
|
||
pick=pages[0]
|
||
ws=pick.get('webSocketDebuggerUrl') or ''
|
||
if not ws:
|
||
print(json.dumps({'reason':'no_ws'})); raise SystemExit
|
||
expr="(()=>{const t=document.title||''; const b=(document.body&&(document.body.innerText||''))||''; const blob=(t+' '+b).slice(0,800); return {title:t.slice(0,120), body:b.slice(0,400), blob};})()"
|
||
try:
|
||
s=ws_connect(ws)
|
||
ws_send(s,{'id':1,'method':'Runtime.evaluate','params':{'expression':expr,'returnByValue':True}})
|
||
deadline=time.time()+4.0
|
||
val=None
|
||
while time.time()<deadline:
|
||
msg=ws_recv(s)
|
||
if not msg: break
|
||
if msg.get('id')==1:
|
||
val=((msg.get('result') or {}).get('result') or {}).get('value')
|
||
break
|
||
try: s.close()
|
||
except Exception: pass
|
||
except Exception as e:
|
||
print(json.dumps({'reason':'eval_timeout','err':str(e)[:80]})); raise SystemExit
|
||
if not isinstance(val, dict):
|
||
print(json.dumps({'reason':'eval_empty'})); raise SystemExit
|
||
blob=str(val.get('blob') or '').lower()
|
||
title=str(val.get('title') or '').lower()
|
||
if 'sigill' in blob: print(json.dumps({'reason':'sigill','title':title})); raise SystemExit
|
||
if 'aw, snap' in blob or 'aw snap' in blob: print(json.dumps({'reason':'aw_snap','title':title})); raise SystemExit
|
||
if 'status_invalid' in blob or 'something went wrong' in title: print(json.dumps({'reason':'chrome_crash_ui','title':title})); raise SystemExit
|
||
if 'chrome-error' in blob or 'chromewebdata' in blob: print(json.dumps({'reason':'chrome_error','title':title})); raise SystemExit
|
||
print(json.dumps({'reason':'','title':title}))
|
||
'''
|
||
code, out = _run(
|
||
["docker", "exec", "-i", name, "python3", "-"],
|
||
timeout=18,
|
||
input_text=script,
|
||
)
|
||
try:
|
||
line = (out or "").strip().splitlines()[-1] if (out or "").strip() else "{}"
|
||
parsed = json.loads(line)
|
||
if isinstance(parsed, dict):
|
||
return str(parsed.get("reason") or "").strip()
|
||
except Exception:
|
||
pass
|
||
if code != 0:
|
||
return "eval_timeout"
|
||
return "eval_empty"
|
||
|
||
|
||
def _chrome_tab_crash_reason(instance_id: int) -> str:
|
||
"""Detect Aw Snap / SIGILL / chrome-error / wedged renderer. Empty = healthy."""
|
||
# 1) Tab metadata (cheap; often stale on Aw Snap — still catch obvious cases).
|
||
for tab in _cdp_fetch_tabs(instance_id):
|
||
title = str(tab.get("title") or "")
|
||
url = str(tab.get("url") or "").lower()
|
||
blob = f"{title} {url}".lower()
|
||
if "sigill" in blob:
|
||
return "sigill"
|
||
if "aw, snap" in blob or "aw snap" in blob:
|
||
return "aw_snap"
|
||
if "chrome-error://" in url or "chromewebdata" in url:
|
||
return "chrome_error"
|
||
if "status/crashed" in url or tab.get("type") == "crash":
|
||
return "tab_crashed"
|
||
# 2) Recent chrome log SIGILL (renderer crash often doesn't update tab title).
|
||
try:
|
||
if _chrome_log_recent_sigill(instance_id):
|
||
return "sigill_log"
|
||
except Exception:
|
||
pass
|
||
# 3) Real DOM / evaluate — catches Aw Snap while metadata still says Creator Studio.
|
||
try:
|
||
reason = _chrome_renderer_probe(instance_id)
|
||
except Exception:
|
||
reason = "eval_timeout"
|
||
if reason in {"sigill", "aw_snap", "chrome_error", "chrome_crash_ui", "no_ws"}:
|
||
_RENDERER_FAIL_STREAK[instance_id] = 0
|
||
return reason
|
||
if reason in {"eval_timeout", "eval_empty", "cdp_list_fail"}:
|
||
# Studio Live tab present + wedged evaluate → heal after 2 consecutive fails.
|
||
streak = int(_RENDERER_FAIL_STREAK.get(instance_id) or 0) + 1
|
||
_RENDERER_FAIL_STREAK[instance_id] = streak
|
||
live_tabs = False
|
||
try:
|
||
live_tabs = bool(_cdp_live_studio_urls(instance_id))
|
||
except Exception:
|
||
live_tabs = False
|
||
# Live Studio tab + wedged evaluate is enough — metadata still looks healthy.
|
||
if live_tabs and streak >= 1:
|
||
return f"renderer_wedged_{reason}"
|
||
return ""
|
||
_RENDERER_FAIL_STREAK[instance_id] = 0
|
||
return ""
|
||
|
||
|
||
def _restart_chrome_in_container(instance_id: int) -> dict[str, Any]:
|
||
"""supervisorctl restart google-chrome — keeps Neko session / profile volume."""
|
||
name = _container_name(instance_id)
|
||
# Prefer supervisor program; fall back to pkill+browser-launch supervised restart.
|
||
cmds = [
|
||
"supervisorctl restart google-chrome",
|
||
"supervisorctl restart chromium",
|
||
]
|
||
last = ""
|
||
for cmd in cmds:
|
||
code, out = _run(["docker", "exec", name, "bash", "-lc", cmd], timeout=45)
|
||
last = (out or "")[:240]
|
||
if code == 0:
|
||
return {"ok": True, "method": cmd, "detail": last}
|
||
# Hard fallback: kill chrome processes; supervisord autorestart=true should revive.
|
||
code, out = _run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
name,
|
||
"bash",
|
||
"-lc",
|
||
"pkill -TERM -f '/opt/google/chrome/chrome|google-chrome|chromium' 2>/dev/null; sleep 2; "
|
||
"supervisorctl start google-chrome 2>/dev/null || supervisorctl start chromium 2>/dev/null || true; echo done",
|
||
],
|
||
timeout=50,
|
||
)
|
||
return {"ok": code == 0, "method": "pkill+supervisor", "detail": (out or last)[:240]}
|
||
|
||
|
||
def heal_unhealthy_chrome_in_nekos() -> dict[str, Any]:
|
||
"""Auto-detect CDP-dead / Aw Snap / SIGILL and restart Chrome inside needed Nekos.
|
||
|
||
Never wipes profiles. Cooldown 120s. After restart, nudge YouTube Live Studio tab.
|
||
"""
|
||
import time as _time
|
||
|
||
ids = set(_neko_ids_needed_for_live())
|
||
try:
|
||
ids |= set(_neko_ids_for_cdp_poll())
|
||
except Exception:
|
||
pass
|
||
if not ids:
|
||
return {"ok": True, "checked": 0, "healed": [], "skipped": []}
|
||
now = _time.time()
|
||
healed: list[dict[str, Any]] = []
|
||
skipped: list[dict[str, Any]] = []
|
||
for nid in sorted(ids):
|
||
st = _container_state(nid, check_http=False)
|
||
if not st.get("running"):
|
||
skipped.append({"id": nid, "reason": "not_running"})
|
||
continue
|
||
last = float(_CHROME_HEAL_LAST.get(nid) or 0)
|
||
if now - last < _CHROME_HEAL_COOLDOWN_SEC:
|
||
skipped.append({"id": nid, "reason": "cooldown"})
|
||
continue
|
||
reason = ""
|
||
crash = ""
|
||
try:
|
||
crash = _chrome_tab_crash_reason(nid)
|
||
except Exception:
|
||
crash = ""
|
||
if crash:
|
||
reason = crash
|
||
elif not _devtools_version_ok(nid):
|
||
streak = int(_CDP_FAIL_STREAK.get(nid) or 0) + 1
|
||
_CDP_FAIL_STREAK[nid] = streak
|
||
if streak < 2:
|
||
skipped.append({"id": nid, "reason": f"cdp_fail_streak_{streak}"})
|
||
continue
|
||
reason = "cdp_dead"
|
||
else:
|
||
_CDP_FAIL_STREAK[nid] = 0
|
||
skipped.append({"id": nid, "reason": "chrome_ok"})
|
||
continue
|
||
_CHROME_HEAL_LAST[nid] = now
|
||
_CDP_FAIL_STREAK[nid] = 0
|
||
_RENDERER_FAIL_STREAK[nid] = 0
|
||
res = _restart_chrome_in_container(nid)
|
||
# Give Chrome a moment, then reopen Live control room.
|
||
_time.sleep(4.0)
|
||
nudge: dict[str, Any] = {}
|
||
try:
|
||
nudge = _cdp_nudge_live_studio_tab(nid)
|
||
except Exception as exc:
|
||
nudge = {"ok": False, "error": str(exc)[:120]}
|
||
healed.append({"id": nid, "reason": reason, "restart": res, "nudge": nudge})
|
||
return {"ok": True, "checked": len(ids), "healed": healed, "skipped": skipped}
|
||
|
||
|
||
def heal_neko_runtime() -> dict[str, Any]:
|
||
"""Combined soft-heal: container OOM/exit + Chrome SIGILL/Aw Snap/CDP dead."""
|
||
a = heal_crashed_assign_nekos()
|
||
b = heal_unhealthy_chrome_in_nekos()
|
||
return {
|
||
"ok": True,
|
||
"container": a,
|
||
"chrome": b,
|
||
"healed": list(a.get("healed") or []) + list(b.get("healed") or []),
|
||
}
|
||
|
||
|
||
def _payload_is_livestreaming(payload: dict[str, Any] | None) -> bool:
|
||
body = payload or {}
|
||
url = str(body.get("url") or "").lower()
|
||
path = str((body.get("signals") or {}).get("path") or "").lower()
|
||
return "livestreaming" in url or "livestreaming" in path
|
||
|
||
|
||
def _payload_session_live(payload: dict[str, Any] | None) -> bool:
|
||
"""YouTube broadcast session is open (LIVE pill / End Stream) — includes 断播."""
|
||
body = payload or {}
|
||
signals = body.get("signals") if isinstance(body.get("signals"), dict) else {}
|
||
if signals.get("session_live") or signals.get("encoder_lost"):
|
||
return True
|
||
status = str(body.get("live_status") or "").strip().lower()
|
||
if status in {"live", "encoder_lost", "stalled"}:
|
||
return True
|
||
try:
|
||
if body.get("live_duration_sec") is not None and float(body.get("live_duration_sec") or 0) > 0:
|
||
return True
|
||
except (TypeError, ValueError):
|
||
pass
|
||
if str(body.get("live_duration") or "").strip():
|
||
return True
|
||
text = str(body.get("text") or "").lower()
|
||
has_timer = bool(re.search(r"\blive\b[\s\S]{0,48}\d{1,2}:\d{2}", text))
|
||
has_end = "end stream" in text or "stop streaming" in text or "结束直播" in text
|
||
return has_timer and (has_end or "live" in text)
|
||
|
||
|
||
def _payload_encoder_lost(payload: dict[str, Any] | None) -> bool:
|
||
"""断播: session still live but encoder NODATA / will end shortly — not 待开播."""
|
||
body = payload or {}
|
||
signals = body.get("signals") if isinstance(body.get("signals"), dict) else {}
|
||
if signals.get("encoder_lost"):
|
||
return True
|
||
status = str(body.get("live_status") or "").strip().lower()
|
||
if status in {"encoder_lost", "stalled"}:
|
||
return True
|
||
if not _payload_session_live(body):
|
||
return False
|
||
text = str(body.get("text") or "").lower()
|
||
if any(
|
||
x in text
|
||
for x in (
|
||
"will end shortly",
|
||
"restart it in your streaming software",
|
||
"unless you restart",
|
||
"即将结束",
|
||
"断流",
|
||
)
|
||
):
|
||
return True
|
||
if signals.get("nodata"):
|
||
return True
|
||
return "no data" in text or "nodata" in text or "无数据" in text
|
||
|
||
|
||
def _payload_stream_confirmed(payload: dict[str, Any] | None) -> bool:
|
||
"""True when Studio is 开播 with encoder data (not 待开播, not 断播)."""
|
||
body = payload or {}
|
||
text = str(body.get("text") or "").lower()
|
||
signals = body.get("signals") if isinstance(body.get("signals"), dict) else {}
|
||
status = str(body.get("live_status") or "").strip().lower()
|
||
# 断播 / 待开播 / Preparing stream are never on-air.
|
||
if status in {
|
||
"encoder_lost",
|
||
"stalled",
|
||
"waiting",
|
||
"ready",
|
||
"ended",
|
||
"offline",
|
||
"signed_out",
|
||
"streaming",
|
||
"preparing",
|
||
}:
|
||
return False
|
||
if signals.get("encoder_lost") or _payload_encoder_lost(body):
|
||
return False
|
||
if signals.get("preparing_stream") or "preparing stream" in text or "preparing your stream" in text:
|
||
return False
|
||
if signals.get("pending_go_live") and not _payload_session_live(body):
|
||
return False
|
||
# Bare NODATA without an active LIVE session = 待开播.
|
||
if (signals.get("nodata") or "no data" in text or "nodata" in text or "无数据" in text) and not (
|
||
status == "live" and not signals.get("nodata")
|
||
):
|
||
if _payload_session_live(body) or status == "live":
|
||
return False # 断播 or nodata-while-live
|
||
return False
|
||
if any(
|
||
x in text
|
||
for x in (
|
||
"waiting for you to start",
|
||
"待开播",
|
||
"start sending us your video",
|
||
"直播已结束",
|
||
"未在直播",
|
||
)
|
||
) and not _payload_session_live(body):
|
||
return False
|
||
# "Connect your encoder" alone on a LIVE session = 断播 (already returned False above).
|
||
if "connect your encoder" in text and not _payload_session_live(body):
|
||
return False
|
||
health = str(body.get("health") or "").strip().lower()
|
||
if status == "live":
|
||
return True
|
||
# Concurrent viewers > 0 on Control Room ≈ on-air (0 alone is not).
|
||
try:
|
||
viewers = body.get("viewer_count")
|
||
if viewers is not None and int(viewers) > 0 and _payload_is_livestreaming(body):
|
||
return True
|
||
except (TypeError, ValueError):
|
||
pass
|
||
if any(
|
||
x in text
|
||
for x in (
|
||
"you're live",
|
||
"you are live",
|
||
"watching now",
|
||
"正在直播",
|
||
"直播中",
|
||
"人正在观看",
|
||
)
|
||
):
|
||
return True
|
||
if health in {"excellent", "good"} and any(
|
||
x in text for x in ("stream is healthy", "excellent connection", "连接状况极佳", "状况良好")
|
||
):
|
||
if _payload_is_livestreaming(body) and "connect your encoder" not in text:
|
||
return True
|
||
return False
|
||
|
||
|
||
def _payload_nodata_or_pending(payload: dict[str, Any] | None) -> bool:
|
||
"""True only for 待开播 / pre-go-live NODATA — never for 断播 (encoder_lost)."""
|
||
body = payload or {}
|
||
signals = body.get("signals") if isinstance(body.get("signals"), dict) else {}
|
||
status = str(body.get("live_status") or "").strip().lower()
|
||
text = str(body.get("text") or "").lower()
|
||
# Preparing stream can coexist with Excellent / LIVE chrome — still not ready.
|
||
if (
|
||
status == "preparing"
|
||
or signals.get("preparing_stream")
|
||
or "preparing stream" in text
|
||
or "preparing your stream" in text
|
||
):
|
||
return True
|
||
if _payload_encoder_lost(body) or _payload_session_live(body):
|
||
# Session already started: NODATA here is 断播, not 待开播.
|
||
return False
|
||
if signals.get("pending_go_live"):
|
||
return True
|
||
if signals.get("nodata"):
|
||
return True
|
||
if status in {"waiting", "ready", "signed_out", "offline"}:
|
||
return True
|
||
return any(
|
||
x in text
|
||
for x in (
|
||
"no data",
|
||
"nodata",
|
||
"无数据",
|
||
"待开播",
|
||
"connect your encoder",
|
||
"start sending us your video",
|
||
"waiting for you to start",
|
||
)
|
||
)
|
||
|
||
|
||
def _cdp_fetch_tabs(instance_id: int) -> list[dict[str, Any]]:
|
||
"""List Chrome tabs via DevTools inside a Neko container."""
|
||
name = _container_name(instance_id)
|
||
py = (
|
||
"import json,urllib.request\n"
|
||
"try:\n"
|
||
" r=urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4)\n"
|
||
" print(r.read().decode())\n"
|
||
"except Exception:\n"
|
||
" print('[]')"
|
||
)
|
||
code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=15)
|
||
if code != 0:
|
||
return []
|
||
try:
|
||
data = json.loads(out or "[]")
|
||
return data if isinstance(data, list) else []
|
||
except json.JSONDecodeError:
|
||
return []
|
||
|
||
|
||
def _cdp_live_studio_urls(instance_id: int) -> list[str]:
|
||
from urllib.parse import urlparse
|
||
|
||
urls: list[str] = []
|
||
for tab in _cdp_fetch_tabs(instance_id):
|
||
u = str(tab.get("url") or "").strip()
|
||
try:
|
||
p = urlparse(u)
|
||
except Exception:
|
||
continue
|
||
host = (p.netloc or "").lower()
|
||
path = (p.path or "").lower()
|
||
if host.endswith("studio.youtube.com") and "livestreaming" in path:
|
||
urls.append(u)
|
||
return urls
|
||
|
||
|
||
_cdp_signal_cache: dict[int, tuple[float, dict[str, Any]]] = {}
|
||
|
||
|
||
def _cdp_studio_page_signals(
|
||
instance_id: int,
|
||
*,
|
||
max_age_sec: float = 45.0,
|
||
force: bool = False,
|
||
) -> dict[str, Any]:
|
||
"""Read-only CDP scrape of Studio Live page text (no tab close / no Chrome restart).
|
||
|
||
Script is fed via ``docker exec -i … python3 -`` stdin (no docker cp / no Chrome restart).
|
||
"""
|
||
import time as _time
|
||
|
||
nid = int(instance_id or 0)
|
||
if nid < 1:
|
||
return {"ok": False, "error": "bad_id"}
|
||
now = _time.time()
|
||
cached = _cdp_signal_cache.get(nid)
|
||
if (not force) and cached and (now - float(cached[0])) <= max_age_sec:
|
||
return dict(cached[1])
|
||
|
||
name = _container_name(nid)
|
||
script = _asset_root() / "cdp_studio_scrape.py"
|
||
if not script.is_file():
|
||
row = {"ok": False, "error": "scrape_script_missing"}
|
||
_cdp_signal_cache[nid] = (now, row)
|
||
return row
|
||
|
||
# Feed script via stdin — avoids docker cp onto read-only overlay mounts.
|
||
try:
|
||
script_text = script.read_text(encoding="utf-8")
|
||
except OSError as exc:
|
||
row = {"ok": False, "error": f"read_script:{exc}"}
|
||
_cdp_signal_cache[nid] = (now, row)
|
||
return row
|
||
code, out = _run(
|
||
["docker", "exec", "-i", name, "python3", "-"],
|
||
timeout=25,
|
||
input_text=script_text,
|
||
)
|
||
row: dict[str, Any] = {"ok": False, "error": "cdp_scrape_failed"}
|
||
try:
|
||
line = (out or "").strip().splitlines()[-1] if (out or "").strip() else "{}"
|
||
parsed = json.loads(line)
|
||
if isinstance(parsed, dict):
|
||
row = parsed
|
||
except Exception:
|
||
row = {"ok": False, "error": (out or f"exit_{code}")[:220]}
|
||
_cdp_signal_cache[nid] = (now, row)
|
||
return row
|
||
|
||
|
||
def studio_live_control_url(youtube_channel_id: str = "", *, fallback: str = "") -> str:
|
||
"""Canonical Studio Live Control Room URL for a channel (待开播 / 直播控制页)."""
|
||
yt = str(youtube_channel_id or "").strip()
|
||
if yt.startswith("UC") and len(yt) >= 20:
|
||
return f"https://studio.youtube.com/channel/{yt}/livestreaming"
|
||
fb = str(fallback or "").strip()
|
||
if fb:
|
||
return fb
|
||
return "https://studio.youtube.com/"
|
||
|
||
|
||
def _cdp_ensure_live_studio_in_container(
|
||
container_name: str,
|
||
*,
|
||
studio_url: str = "",
|
||
) -> dict[str, Any]:
|
||
"""Inside a Neko Chrome: focus existing Live tab, or open ``studio_url`` via CDP."""
|
||
name = str(container_name or "").strip()
|
||
if not name:
|
||
return {"ok": False, "error": "empty_container"}
|
||
want = str(studio_url or "").strip() or "https://studio.youtube.com/"
|
||
# Keep URL safe for embedding in single-quoted python -c
|
||
want_js = json.dumps(want)
|
||
py = (
|
||
"import json,urllib.parse,urllib.request\n"
|
||
f"WANT={want_js}\n"
|
||
"def fetch():\n"
|
||
" with urllib.request.urlopen('http://127.0.0.1:9222/json/list',timeout=4) as r:\n"
|
||
" return json.loads(r.read().decode())\n"
|
||
"def is_live(u):\n"
|
||
" u=(u or '').lower()\n"
|
||
" return 'studio.youtube.com' in u and 'livestreaming' in u\n"
|
||
"def is_studio(u):\n"
|
||
" u=(u or '').lower()\n"
|
||
" return 'studio.youtube.com' in u\n"
|
||
"try:\n"
|
||
" tabs=fetch()\n"
|
||
"except Exception as e:\n"
|
||
" print(json.dumps({'ok':False,'error':str(e)})); raise SystemExit(0)\n"
|
||
"pages=[t for t in tabs if (t.get('type') or 'page')=='page']\n"
|
||
"live=[t for t in pages if is_live(t.get('url') or '')]\n"
|
||
"studio=[t for t in pages if is_studio(t.get('url') or '')]\n"
|
||
"pick=(live or studio or [None])[0]\n"
|
||
"if pick:\n"
|
||
" tid=pick.get('id')\n"
|
||
" if tid:\n"
|
||
" try: urllib.request.urlopen(f'http://127.0.0.1:9222/json/activate/{tid}',timeout=2)\n"
|
||
" except Exception: pass\n"
|
||
" print(json.dumps({'ok':True,'url':pick.get('url',''),'action':'activate'})); raise SystemExit(0)\n"
|
||
"q=urllib.parse.quote(WANT, safe='')\n"
|
||
"try:\n"
|
||
" req=urllib.request.Request('http://127.0.0.1:9222/json/new?'+q, method='PUT')\n"
|
||
" with urllib.request.urlopen(req, timeout=8) as r:\n"
|
||
" data=json.loads(r.read().decode())\n"
|
||
" print(json.dumps({'ok':True,'url':data.get('url',WANT),'action':'open','id':data.get('id')})); raise SystemExit(0)\n"
|
||
"except Exception as e:\n"
|
||
" try:\n"
|
||
" with urllib.request.urlopen('http://127.0.0.1:9222/json/new?'+q, timeout=8) as r:\n"
|
||
" data=json.loads(r.read().decode())\n"
|
||
" print(json.dumps({'ok':True,'url':data.get('url',WANT),'action':'open_get'})); raise SystemExit(0)\n"
|
||
" except Exception as e2:\n"
|
||
" print(json.dumps({'ok':False,'error':str(e2)}))"
|
||
)
|
||
code, out = _run(["docker", "exec", name, "python3", "-c", py], timeout=25)
|
||
try:
|
||
row = json.loads((out or "").strip().split("\n")[-1] or "{}")
|
||
if isinstance(row, dict):
|
||
return row
|
||
except json.JSONDecodeError:
|
||
pass
|
||
return {"ok": False, "error": (out or f"cdp_ensure_exit_{code}")[:200]}
|
||
|
||
|
||
def _cdp_nudge_live_studio_tab(instance_id: int) -> dict[str, Any]:
|
||
"""Focus existing Live tab or open channel Live Control Room (local assign Neko)."""
|
||
name = _container_name(instance_id)
|
||
studio_url = ""
|
||
try:
|
||
from . import yt_assign_db
|
||
|
||
for g in yt_assign_db.list_groups(include_urls=False):
|
||
if int(g.get("neko_instance_id") or 0) == int(instance_id):
|
||
studio_url = studio_live_control_url(str(g.get("youtube_channel_id") or ""))
|
||
break
|
||
except Exception:
|
||
studio_url = ""
|
||
return _cdp_ensure_live_studio_in_container(name, studio_url=studio_url)
|
||
|
||
|
||
def latest_live_studio_event(
|
||
*,
|
||
max_age_sec: float = 60.0,
|
||
since_ts: float = 0.0,
|
||
neko_id: int = 0,
|
||
) -> dict[str, Any] | None:
|
||
"""Newest Studio Control Room telemetry, optionally only after `since_ts`."""
|
||
import time as _time
|
||
|
||
now = _time.time()
|
||
since = float(since_ts or 0)
|
||
want = int(neko_id or 0)
|
||
for ev in _studio_events[:80]:
|
||
received = float(ev.get("received_at") or 0)
|
||
if since > 0 and received < since:
|
||
continue
|
||
if now - received > max_age_sec:
|
||
continue
|
||
payload = ev.get("payload") or {}
|
||
if not _payload_is_livestreaming(payload if isinstance(payload, dict) else {}):
|
||
continue
|
||
ev_nid = int(ev.get("neko_instance_id") or 0)
|
||
if want > 0:
|
||
# Strict: only events tagged for this instance (never share untagged globally).
|
||
if ev_nid == want:
|
||
return ev
|
||
continue
|
||
return ev
|
||
return None
|
||
|
||
|
||
def recent_live_studio_seen(*, max_age_sec: float = 120.0, since_ts: float = 0.0) -> bool:
|
||
"""True if any recent studio telemetry URL is YouTube Live Control Room."""
|
||
return latest_live_studio_event(max_age_sec=max_age_sec, since_ts=since_ts) is not None
|
||
|
||
|
||
def youtube_live_confirmed(*, max_age_sec: float = 45.0, since_ts: float = 0.0, neko_id: int = 0) -> dict[str, Any]:
|
||
"""Detect whether Studio reports a stream is truly on-air (tab open alone is NOT live)."""
|
||
ev = latest_live_studio_event(max_age_sec=max_age_sec, since_ts=since_ts, neko_id=neko_id)
|
||
if ev:
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
confirmed = _payload_stream_confirmed(payload)
|
||
return {
|
||
"ok": True,
|
||
"live": confirmed,
|
||
"page_open": _payload_is_livestreaming(payload),
|
||
"live_status": str(payload.get("live_status") or ""),
|
||
"health": str(payload.get("health") or ""),
|
||
"url": str(payload.get("url") or "")[:200],
|
||
"received_at": float(ev.get("received_at") or 0),
|
||
"neko_instance_id": int(ev.get("neko_instance_id") or neko_id or 0),
|
||
"viewer_count": payload.get("viewer_count"),
|
||
"reason": "stream_confirmed" if confirmed else "page_open_not_confirmed_live",
|
||
"detect_source": "telemetry",
|
||
}
|
||
if neko_id > 0:
|
||
# Prefer cached CDP DOM (poller / prior lookup); do not treat bare tab URL as on-air.
|
||
try:
|
||
sig = _cdp_studio_page_signals(int(neko_id), max_age_sec=max(45.0, float(max_age_sec)))
|
||
except Exception:
|
||
sig = {}
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
on_air = bool(sig.get("on_air"))
|
||
return {
|
||
"ok": True,
|
||
"live": on_air,
|
||
"page_open": True,
|
||
"live_status": str(sig.get("live_status") or ""),
|
||
"health": str(sig.get("health") or ""),
|
||
"url": str(sig.get("url") or "")[:200],
|
||
"received_at": 0.0,
|
||
"neko_instance_id": int(neko_id),
|
||
"viewer_count": sig.get("viewer_count"),
|
||
"reason": "cdp_dom_on_air" if on_air else "cdp_dom_page_not_on_air",
|
||
"detect_source": "cdp_dom",
|
||
}
|
||
cdp_urls = _cdp_live_studio_urls(neko_id)
|
||
if cdp_urls:
|
||
return {
|
||
"ok": True,
|
||
"live": False,
|
||
"page_open": True,
|
||
"live_status": "cdp_live_tab",
|
||
"health": "",
|
||
"url": cdp_urls[0][:200],
|
||
"received_at": 0.0,
|
||
"neko_instance_id": int(neko_id),
|
||
"viewer_count": None,
|
||
"reason": "cdp_livestreaming_tab_not_confirmed",
|
||
"detect_source": "cdp",
|
||
}
|
||
return {"ok": False, "live": False, "page_open": False, "reason": "no_live_studio_page"}
|
||
|
||
def wait_instance_ready_for_live(
|
||
instance_id: int,
|
||
*,
|
||
timeout_sec: float = 180.0,
|
||
require_live_page: bool = True,
|
||
settle_sec: float = 25.0,
|
||
strict: bool = True,
|
||
) -> dict[str, Any]:
|
||
"""Block until Neko is up AND Studio livestreaming page is freshly open + settled.
|
||
|
||
Time-slot / exclusive mode must pass ``strict=True`` so FFmpeg never starts on a
|
||
stale telemetry hit or a soft timeout (that causes YouTube green-loading RTMP).
|
||
Telemetry must arrive *after* this wait begins (post exclusive Neko switch).
|
||
"""
|
||
import time as _time
|
||
|
||
idx = int(instance_id or 0)
|
||
if idx < 1:
|
||
return {"ok": True, "skipped": "no_instance"}
|
||
started = ensure_instance_running(idx)
|
||
if not started.get("ok") and not started.get("already"):
|
||
return {"ok": False, "id": idx, "error": started.get("error") or "neko_start_failed"}
|
||
|
||
# Ignore telemetry from the previous slot/channel (green-loading root cause).
|
||
wait_since = _time.time()
|
||
settle_need = max(8.0, float(settle_sec))
|
||
deadline = wait_since + max(settle_need + 20.0, float(timeout_sec))
|
||
ready_at = 0.0
|
||
page_first_seen = 0.0
|
||
last: dict[str, Any] = {}
|
||
last_ev: dict[str, Any] | None = None
|
||
last_cdp_url = ""
|
||
nudge_at = 0.0
|
||
|
||
while _time.time() < deadline:
|
||
last = _container_state(idx, check_http=False)
|
||
running = bool(last.get("running"))
|
||
ready = bool(last.get("ready")) or (
|
||
running and str(last.get("status") or "") in {"running", "healthy", "starting"}
|
||
)
|
||
if not (running and ready):
|
||
_time.sleep(2.0)
|
||
continue
|
||
if not ready_at:
|
||
ready_at = _time.time()
|
||
if not require_live_page:
|
||
return {"ok": True, "id": idx, "ready": True, "live_studio": False, "wait_since": wait_since}
|
||
|
||
now = _time.time()
|
||
page_detected = False
|
||
detect_source = ""
|
||
detect_url = ""
|
||
|
||
# 1) Chrome extension telemetry (preferred when ingest works)
|
||
# Strict: only events tagged for THIS local instance (never share siblings).
|
||
ev = latest_live_studio_event(max_age_sec=45.0, since_ts=wait_since, neko_id=idx)
|
||
if ev is None:
|
||
ev = latest_live_studio_event(max_age_sec=20.0, since_ts=wait_since - 5.0, neko_id=idx)
|
||
if ev is not None:
|
||
last_ev = ev
|
||
page_detected = True
|
||
detect_source = "telemetry"
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
detect_url = str(payload.get("url") or "")
|
||
|
||
# 2) CDP inside container — extension ingest often fails from Docker
|
||
if not page_detected:
|
||
cdp_urls = _cdp_live_studio_urls(idx)
|
||
if cdp_urls:
|
||
page_detected = True
|
||
detect_source = "cdp"
|
||
detect_url = cdp_urls[0]
|
||
last_cdp_url = detect_url
|
||
elif now - nudge_at >= 10.0:
|
||
nudge_at = now
|
||
_cdp_nudge_live_studio_tab(idx)
|
||
|
||
if page_detected:
|
||
if not page_first_seen:
|
||
page_first_seen = now
|
||
settled_for = now - page_first_seen
|
||
if settled_for >= settle_need:
|
||
live_status = ""
|
||
health = ""
|
||
if last_ev and isinstance(last_ev.get("payload"), dict):
|
||
live_status = str(last_ev["payload"].get("live_status") or "")
|
||
health = str(last_ev["payload"].get("health") or "")
|
||
# Strict: CDP must confirm control-room chrome and NOT "Preparing stream".
|
||
# URL/telemetry settle alone still races green-loading RTMP.
|
||
control_ready = True
|
||
preparing = False
|
||
if strict:
|
||
try:
|
||
sig = _cdp_studio_page_signals(idx, max_age_sec=0.0, force=True)
|
||
except Exception:
|
||
sig = {}
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
preparing = bool(sig.get("preparing_stream"))
|
||
control_ready = bool(sig.get("control_ready"))
|
||
chrome_offline = bool(sig.get("chrome_offline")) or (
|
||
"err_internet" in str(sig.get("text") or "").lower()
|
||
or "no internet" in str(sig.get("text") or "").lower()
|
||
)
|
||
encoder_receiving = bool(
|
||
(sig.get("encoder_receiving") or sig.get("on_air"))
|
||
and not chrome_offline
|
||
)
|
||
if sig.get("live_status"):
|
||
live_status = str(sig.get("live_status") or live_status)
|
||
if sig.get("health"):
|
||
health = str(sig.get("health") or health)
|
||
if chrome_offline:
|
||
# Chrome interstitial ≠ Studio receiving — keep waiting.
|
||
_time.sleep(2.0)
|
||
continue
|
||
if preparing:
|
||
# Keep waiting — never hand off to FFmpeg while preview spins.
|
||
_time.sleep(2.0)
|
||
continue
|
||
# Receiving-first: Studio already accepting encoder → do not block on
|
||
# SPA chrome flags (control_ready can lag while ingest is healthy).
|
||
if encoder_receiving:
|
||
control_ready = True
|
||
if not live_status:
|
||
live_status = "live" if sig.get("on_air") else "receiving"
|
||
if not control_ready and live_status not in {
|
||
"live",
|
||
"waiting",
|
||
"encoder_lost",
|
||
"receiving",
|
||
}:
|
||
_time.sleep(2.0)
|
||
continue
|
||
return {
|
||
"ok": True,
|
||
"id": idx,
|
||
"ready": True,
|
||
"live_studio": True,
|
||
"settled": True,
|
||
"settle_sec": round(settled_for, 1),
|
||
"wait_since": wait_since,
|
||
"live_status": live_status,
|
||
"health": health,
|
||
"control_ready": control_ready,
|
||
"preparing_stream": preparing,
|
||
"url": (detect_url or last_cdp_url)[:200],
|
||
"detect_source": detect_source,
|
||
"note": f"live_studio_{detect_source}_settled",
|
||
}
|
||
_time.sleep(2.0)
|
||
|
||
page_open = page_first_seen > 0 or bool(_cdp_live_studio_urls(idx))
|
||
if not page_open:
|
||
page_open = recent_live_studio_seen(max_age_sec=45.0, since_ts=wait_since)
|
||
if strict and require_live_page:
|
||
return {
|
||
"ok": False,
|
||
"id": idx,
|
||
"ready": bool(last.get("ready")),
|
||
"live_studio": bool(page_open),
|
||
"timeout": True,
|
||
"wait_since": wait_since,
|
||
"error": (
|
||
"Neko 已启动,但 YouTube Live 控制页未在时限内稳定打开"
|
||
if not page_open
|
||
else f"YouTube Live 页已打开,但未稳定满 {int(settle_need)}s(避免绿点无效推流)"
|
||
),
|
||
"state": last,
|
||
"last_event_at": float((last_ev or {}).get("received_at") or 0),
|
||
}
|
||
return {
|
||
"ok": bool(last.get("running")),
|
||
"id": idx,
|
||
"ready": bool(last.get("ready")),
|
||
"live_studio": bool(page_open),
|
||
"timeout": True,
|
||
"wait_since": wait_since,
|
||
"note": "neko_running_after_timeout",
|
||
"state": last,
|
||
}
|
||
|
||
|
||
def wait_group_ready_for_live(
|
||
group: dict[str, Any] | None,
|
||
*,
|
||
timeout_sec: float = 120.0,
|
||
settle_sec: float = 20.0,
|
||
strict: bool = True,
|
||
) -> dict[str, Any]:
|
||
"""Wait for the group's preferred Neko (local or remote ops) Live Control Room.
|
||
|
||
Design: once bind is confirmed, Chrome must have YouTube Live tab open (待开播).
|
||
Prefer remote ops-neko when ``neko_open_prefer=remote`` and ops URL/slot are set.
|
||
"""
|
||
import time as _time
|
||
|
||
g = group if isinstance(group, dict) else {}
|
||
prefer = str(g.get("neko_open_prefer") or "local").strip().lower()
|
||
remote_bound = bool(str(g.get("ops_neko_open_url") or "").strip())
|
||
ops_slot = int(g.get("ops_neko_slot") or 0)
|
||
local_id = int(g.get("neko_instance_id") or 0)
|
||
yt_id = str(g.get("youtube_channel_id") or "").strip()
|
||
studio_url = studio_live_control_url(yt_id)
|
||
|
||
use_remote = prefer == "remote" and remote_bound and ops_slot > 0
|
||
if use_remote:
|
||
wait_since = _time.time()
|
||
settle_need = max(8.0, float(settle_sec))
|
||
deadline = wait_since + max(settle_need + 20.0, float(timeout_sec))
|
||
page_first_seen = 0.0
|
||
last_url = ""
|
||
last_nudge: dict[str, Any] = {}
|
||
nudge_at = 0.0
|
||
while _time.time() < deadline:
|
||
now = _time.time()
|
||
# Edge host: open Live tab via CDP. Hub (VPS) only waits on mirrored telemetry.
|
||
if now - nudge_at >= 8.0:
|
||
nudge_at = now
|
||
try:
|
||
from . import ops_neko
|
||
from . import ops_neko_db
|
||
|
||
if str(ops_neko_db.peer_status().get("role") or "") == "edge":
|
||
last_nudge = ops_neko.ensure_slot_live_studio(
|
||
ops_slot, youtube_channel_id=yt_id
|
||
)
|
||
else:
|
||
last_nudge = {"ok": True, "skipped": "hub_waits_edge_sync"}
|
||
except Exception as exc:
|
||
last_nudge = {"ok": False, "error": str(exc)[:160]}
|
||
snap = studio_snapshot_for_ref(f"ops:{ops_slot}", max_age_sec=45.0)
|
||
page_open = bool(snap.get("live_page_open")) or (
|
||
"livestreaming" in str(snap.get("url") or "").lower()
|
||
)
|
||
# Also accept fresh mirrored telemetry event
|
||
if not page_open:
|
||
ev = None
|
||
if f"ops:{ops_slot}" in _studio_latest_by_ref:
|
||
ev = _studio_latest_by_ref.get(f"ops:{ops_slot}")
|
||
if ev and (_time.time() - float(ev.get("received_at") or 0)) <= 45.0:
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
if _payload_is_livestreaming(payload):
|
||
page_open = True
|
||
last_url = str(payload.get("url") or "")
|
||
if page_open:
|
||
if not page_first_seen:
|
||
page_first_seen = now
|
||
last_url = last_url or str(snap.get("url") or "")
|
||
if now - page_first_seen >= settle_need:
|
||
return {
|
||
"ok": True,
|
||
"neko_kind": "ops",
|
||
"ops_slot": ops_slot,
|
||
"live_studio": True,
|
||
"settled": True,
|
||
"settle_sec": round(now - page_first_seen, 1),
|
||
"url": (last_url or studio_url)[:200],
|
||
"detect_source": str(snap.get("detect_source") or "ops_telemetry"),
|
||
"live_status": str(snap.get("live_status") or ""),
|
||
"health": str(snap.get("health") or ""),
|
||
"nudge": last_nudge,
|
||
"wait_since": wait_since,
|
||
}
|
||
_time.sleep(2.0)
|
||
page_open = page_first_seen > 0
|
||
err = (
|
||
f"远程 Ops Neko #{ops_slot} YouTube Live 控制页未在时限内稳定打开"
|
||
if not page_open
|
||
else f"远程 Ops Neko #{ops_slot} Live 页已打开,但未稳定满 {int(settle_need)}s"
|
||
)
|
||
if strict:
|
||
return {
|
||
"ok": False,
|
||
"neko_kind": "ops",
|
||
"ops_slot": ops_slot,
|
||
"live_studio": bool(page_open),
|
||
"timeout": True,
|
||
"error": err,
|
||
"nudge": last_nudge,
|
||
"wait_since": wait_since,
|
||
"url": studio_url,
|
||
}
|
||
return {
|
||
"ok": True,
|
||
"neko_kind": "ops",
|
||
"ops_slot": ops_slot,
|
||
"live_studio": bool(page_open),
|
||
"timeout": True,
|
||
"note": "ops_soft_timeout",
|
||
"nudge": last_nudge,
|
||
}
|
||
|
||
if local_id > 0:
|
||
out = wait_instance_ready_for_live(
|
||
local_id,
|
||
timeout_sec=timeout_sec,
|
||
require_live_page=True,
|
||
settle_sec=settle_sec,
|
||
strict=strict,
|
||
)
|
||
out["neko_kind"] = "local"
|
||
out["neko_instance_id"] = local_id
|
||
return out
|
||
return {"ok": True, "skipped": "no_neko_bind", "neko_kind": "none"}
|
||
|
||
|
||
def restore_enabled_instances() -> dict[str, Any]:
|
||
"""Start all neko_enabled assign groups (after exclusive-live release)."""
|
||
from . import yt_assign_db
|
||
|
||
return sync_for_groups(yt_assign_db.list_groups(include_urls=False))
|
||
|
||
|
||
def recreate_all_instances(*, start_enabled: bool = True) -> dict[str, Any]:
|
||
"""Force-recreate every Neko container so bind-mounted assets (browser-launch.sh) refresh."""
|
||
desired = _desired_from_db()
|
||
if desired <= 0:
|
||
return {"ok": True, "desired": 0, "message": "no_instances"}
|
||
if not _docker_available():
|
||
return {"ok": False, "desired": desired, "error": "Docker 不可用"}
|
||
with _lock:
|
||
compose = _compose_path()
|
||
compose.write_text(_render_compose(desired), encoding="utf-8")
|
||
code, out = _run(_compose_cmd("up", "-d", "--force-recreate", "--no-start"), timeout=900)
|
||
if code != 0:
|
||
return {"ok": False, "desired": desired, "error": (out or "compose recreate failed")[:800]}
|
||
started: list[int] = []
|
||
if start_enabled:
|
||
from . import yt_assign_db
|
||
|
||
groups = yt_assign_db.list_groups(include_urls=False)
|
||
start_set = {
|
||
int(g.get("neko_instance_id") or 0)
|
||
for g in groups
|
||
if g.get("neko_enabled") and int(g.get("neko_instance_id") or 0) > 0
|
||
}
|
||
for idx in sorted(start_set):
|
||
if 1 <= idx <= desired:
|
||
_run(["docker", "start", _container_name(idx)], timeout=60)
|
||
started.append(idx)
|
||
_open_firewall(desired)
|
||
sync_nginx_proxy(desired)
|
||
return {
|
||
"ok": True,
|
||
"desired": desired,
|
||
"started": started,
|
||
"detail": (out or "")[-400:],
|
||
}
|
||
|
||
|
||
# --- Studio telemetry ingest (sh2 live-ops extension) ---
|
||
_studio_events: list[dict[str, Any]] = []
|
||
# Keep ring buffer small — dozens of Nekos POSTing every few seconds otherwise
|
||
# retain hundreds of full Studio payloads and push RSS over MemoryHigh.
|
||
_STUDIO_EVENTS_MAX = 80
|
||
_studio_latest_by_neko: dict[int, dict[str, Any]] = {}
|
||
_studio_latest_by_ref: dict[str, dict[str, Any]] = {}
|
||
_studio_minute_reports: dict[int, list[dict[str, Any]]] = {}
|
||
_studio_minute_reports_by_ref: dict[str, list[dict[str, Any]]] = {}
|
||
_studio_minute_last_at: dict[int, float] = {}
|
||
_studio_minute_last_at_by_ref: dict[str, float] = {}
|
||
_STUDIO_MINUTE_MAX = 60
|
||
_studio_bootstrapped = False
|
||
_CDP_POLL_INTERVAL_SEC = 55.0
|
||
# Per-ref coalesce: drop duplicate ingest storms that only update timestamps.
|
||
_studio_ingest_last_fp: dict[str, tuple[float, str]] = {}
|
||
_STUDIO_INGEST_COALESCE_SEC = 12.0
|
||
_STUDIO_DISK_WRITE_MIN_INTERVAL = 30.0
|
||
_studio_disk_write_at = 0.0
|
||
|
||
|
||
def parse_neko_ref(raw: Any) -> tuple[str, str, int]:
|
||
"""Return (kind, ref_key, local_int). kind is local|remote; ref_key like local:3 / ops:1."""
|
||
text = str(raw or "").strip()
|
||
if not text:
|
||
return "local", "", 0
|
||
low = text.lower()
|
||
if low.startswith("ops-") or low.startswith("ops:"):
|
||
digits = "".join(ch for ch in low.split("-", 1)[-1].split(":", 1)[-1] if ch.isdigit())
|
||
try:
|
||
slot = int(digits or 0)
|
||
except ValueError:
|
||
slot = 0
|
||
if slot > 0:
|
||
return "remote", f"ops:{slot}", 0
|
||
try:
|
||
nid = int(float(text)) if text.replace(".", "", 1).isdigit() or text.isdigit() else int(text)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
if nid > 0:
|
||
return "local", f"local:{nid}", nid
|
||
return "local", "", 0
|
||
|
||
|
||
def _group_for_neko_ref(*, kind: str, local_id: int = 0, ops_slot: int = 0) -> dict[str, Any] | None:
|
||
try:
|
||
from . import yt_assign_db
|
||
|
||
groups = yt_assign_db.list_groups(include_urls=False)
|
||
except Exception:
|
||
return None
|
||
if kind == "remote" and ops_slot > 0:
|
||
for g in groups:
|
||
if int(g.get("ops_neko_slot") or 0) == ops_slot and str(g.get("ops_neko_open_url") or "").strip():
|
||
return g
|
||
return None
|
||
if local_id > 0:
|
||
for g in groups:
|
||
if int(g.get("neko_instance_id") or 0) == local_id:
|
||
return g
|
||
return None
|
||
|
||
|
||
def _enrich_context_for_group(group: dict[str, Any] | None) -> dict[str, Any]:
|
||
"""Attach YouTube channel + current Douyin relay source for analytics joins."""
|
||
out: dict[str, Any] = {
|
||
"group_id": "",
|
||
"channel_pk": "",
|
||
"youtube_channel_id": "",
|
||
"source_room_id": "",
|
||
"source_url": "",
|
||
"anchor_name": "",
|
||
"relay_session_uuid": "",
|
||
}
|
||
if not group:
|
||
return out
|
||
gid = str(group.get("id") or "")
|
||
out["group_id"] = gid
|
||
out["channel_pk"] = str(group.get("channel_pk") or "")
|
||
out["youtube_channel_id"] = str(group.get("youtube_channel_id") or "")
|
||
try:
|
||
from . import youtube_relay_db
|
||
|
||
st = youtube_relay_db.get_relay_state(gid) or {}
|
||
out["source_room_id"] = str(st.get("source_room_id") or "")
|
||
out["source_url"] = str(st.get("source_url") or "")
|
||
out["anchor_name"] = str(st.get("anchor_name") or "")
|
||
except Exception:
|
||
pass
|
||
return out
|
||
|
||
|
||
def _persist_minute_report(neko_id: int, report: dict[str, Any]) -> None:
|
||
nid = int(neko_id or 0)
|
||
if nid < 1:
|
||
return
|
||
try:
|
||
path = _minute_report_dir() / f"{nid}.jsonl"
|
||
with path.open("a", encoding="utf-8") as fh:
|
||
fh.write(json.dumps(report, ensure_ascii=False) + "\n")
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _persist_minute_report_ref(ref_key: str, report: dict[str, Any]) -> None:
|
||
key = str(ref_key or "").strip().replace(":", "_")
|
||
if not key:
|
||
return
|
||
try:
|
||
path = _minute_report_dir() / f"{key}.jsonl"
|
||
with path.open("a", encoding="utf-8") as fh:
|
||
fh.write(json.dumps(report, ensure_ascii=False) + "\n")
|
||
except OSError:
|
||
pass
|
||
|
||
|
||
def _minute_report_dir() -> Path:
|
||
d = _neko_root() / "studio_minute"
|
||
d.mkdir(parents=True, exist_ok=True)
|
||
return d
|
||
|
||
|
||
def _bootstrap_minute_reports_from_disk() -> None:
|
||
"""Load recent per-neko minute reports after API restart."""
|
||
try:
|
||
root = _minute_report_dir()
|
||
except Exception:
|
||
return
|
||
for path in root.glob("*.jsonl"):
|
||
stem = path.stem
|
||
kind, ref_key, nid = parse_neko_ref(stem.replace("_", ":", 1) if stem.startswith("ops_") or stem.startswith("local_") else stem)
|
||
if not ref_key and nid < 1:
|
||
try:
|
||
nid = int(stem)
|
||
kind, ref_key, nid = "local", f"local:{nid}", nid
|
||
except ValueError:
|
||
continue
|
||
rows: list[dict[str, Any]] = []
|
||
try:
|
||
lines = path.read_text(encoding="utf-8").splitlines()
|
||
except OSError:
|
||
continue
|
||
for line in lines[-_STUDIO_MINUTE_MAX :]:
|
||
line = (line or "").strip()
|
||
if not line:
|
||
continue
|
||
try:
|
||
row = json.loads(line)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
if isinstance(row, dict):
|
||
rows.append(row)
|
||
if not rows:
|
||
continue
|
||
rows.reverse() # newest first
|
||
if ref_key:
|
||
_studio_minute_reports_by_ref[ref_key] = rows[:_STUDIO_MINUTE_MAX]
|
||
try:
|
||
_studio_minute_last_at_by_ref[ref_key] = float(rows[0].get("ts") or 0)
|
||
except (TypeError, ValueError):
|
||
pass
|
||
if nid > 0:
|
||
_studio_minute_reports[nid] = rows[:_STUDIO_MINUTE_MAX]
|
||
try:
|
||
_studio_minute_last_at[nid] = float(rows[0].get("ts") or 0)
|
||
except (TypeError, ValueError):
|
||
pass
|
||
|
||
|
||
def _bootstrap_studio_telemetry_from_disk() -> None:
|
||
"""Reload last telemetry after API restart so live-map isn't empty until next Chrome tick."""
|
||
global _studio_bootstrapped
|
||
if _studio_bootstrapped:
|
||
return
|
||
_studio_bootstrapped = True
|
||
_bootstrap_minute_reports_from_disk()
|
||
try:
|
||
path = _neko_root() / "studio_telemetry_latest.json"
|
||
if not path.exists():
|
||
return
|
||
raw = json.loads(path.read_text(encoding="utf-8"))
|
||
if not isinstance(raw, dict) or not isinstance(raw.get("payload"), dict):
|
||
return
|
||
neko_id = int(raw.get("neko_instance_id") or raw["payload"].get("neko_instance_id") or 0)
|
||
if neko_id < 1:
|
||
neko_id = _resolve_neko_id_for_payload(raw["payload"])
|
||
event = {
|
||
"id": str(raw.get("id") or "disk"),
|
||
"received_at": float(raw.get("received_at") or 0),
|
||
"neko_instance_id": neko_id,
|
||
"payload": raw["payload"],
|
||
}
|
||
if event["received_at"] <= 0:
|
||
return
|
||
_studio_events.insert(0, event)
|
||
if neko_id > 0:
|
||
_studio_latest_by_neko[neko_id] = event
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _extract_studio_video_id(url: str) -> str:
|
||
import re
|
||
|
||
m = re.search(r"/video/([^/]+)/livestreaming", str(url or ""), re.I)
|
||
return str(m.group(1) if m else "").strip()
|
||
|
||
|
||
def _resolve_neko_ref_for_payload(payload: dict[str, Any]) -> tuple[str, str, int]:
|
||
"""Resolve (kind, ref_key, local_id) from extension/CDP payload."""
|
||
body = payload or {}
|
||
for key in ("neko_ref", "neko_instance_id", "neko_id", "instance_id"):
|
||
kind, ref_key, nid = parse_neko_ref(body.get(key))
|
||
if ref_key:
|
||
return kind, ref_key, nid
|
||
|
||
url = str(body.get("url") or "")
|
||
video_id = _extract_studio_video_id(url)
|
||
try:
|
||
from . import yt_assign_db
|
||
|
||
for g in yt_assign_db.list_groups(include_urls=False):
|
||
try:
|
||
nid = int(g.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
if nid < 1:
|
||
continue
|
||
studio = str(g.get("neko_studio_url") or "")
|
||
if video_id and video_id in studio:
|
||
return "local", f"local:{nid}", nid
|
||
if url and studio and (studio.rstrip("/") in url or url.rstrip("/") in studio):
|
||
return "local", f"local:{nid}", nid
|
||
remote = str(g.get("ops_neko_open_url") or "")
|
||
slot = int(g.get("ops_neko_slot") or 0)
|
||
if slot > 0 and remote and url and (remote.rstrip("/") in url or url.rstrip("/") in remote):
|
||
return "remote", f"ops:{slot}", 0
|
||
except Exception:
|
||
pass
|
||
return "local", "", 0
|
||
|
||
|
||
def _resolve_neko_id_for_payload(payload: dict[str, Any]) -> int:
|
||
"""Tag telemetry to a local Neko instance id (0 when ops-only)."""
|
||
_kind, _ref, nid = _resolve_neko_ref_for_payload(payload)
|
||
return int(nid or 0)
|
||
|
||
|
||
def _maybe_append_minute_report(neko_id: int, event: dict[str, Any], *, ref_key: str = "", kind: str = "local") -> None:
|
||
import time as _time
|
||
|
||
nid = int(neko_id or 0)
|
||
key = str(ref_key or (f"local:{nid}" if nid > 0 else "")).strip()
|
||
if not key and nid < 1:
|
||
return
|
||
now = float(event.get("received_at") or _time.time())
|
||
last = float(_studio_minute_last_at_by_ref.get(key) or _studio_minute_last_at.get(nid) or 0)
|
||
if last and (now - last) < 55.0:
|
||
return
|
||
payload = event.get("payload") if isinstance(event.get("payload"), dict) else {}
|
||
report = {
|
||
"ts": int(now),
|
||
"neko_instance_id": nid,
|
||
"neko_ref": key,
|
||
"neko_kind": kind if kind in {"local", "remote"} else ("remote" if key.startswith("ops:") else "local"),
|
||
"live_page_open": bool(_payload_is_livestreaming(payload)),
|
||
"on_air": bool(_payload_stream_confirmed(payload)),
|
||
"live_status": str(payload.get("live_status") or ""),
|
||
"health": str(payload.get("health") or ""),
|
||
"viewer_count": payload.get("viewer_count"),
|
||
"total_views": payload.get("total_views"),
|
||
"live_duration": str(payload.get("live_duration") or "")[:16],
|
||
"live_duration_sec": payload.get("live_duration_sec"),
|
||
"like_count": payload.get("like_count"),
|
||
"stream_title": str(payload.get("stream_title") or "")[:120],
|
||
"url": str(payload.get("url") or "")[:200],
|
||
"source": str(payload.get("source") or "extension")[:32],
|
||
}
|
||
if key:
|
||
bucket = _studio_minute_reports_by_ref.setdefault(key, [])
|
||
bucket.insert(0, report)
|
||
del bucket[_STUDIO_MINUTE_MAX:]
|
||
_studio_minute_last_at_by_ref[key] = now
|
||
_persist_minute_report_ref(key, report)
|
||
if nid > 0:
|
||
bucket2 = _studio_minute_reports.setdefault(nid, [])
|
||
bucket2.insert(0, report)
|
||
del bucket2[_STUDIO_MINUTE_MAX:]
|
||
_studio_minute_last_at[nid] = now
|
||
_persist_minute_report(nid, report)
|
||
|
||
# Analytics DB: Douyin room ↔ YT channel ↔ Neko dimensions
|
||
try:
|
||
from . import yt_studio_db
|
||
|
||
ops_slot = 0
|
||
if key.startswith("ops:"):
|
||
try:
|
||
ops_slot = int(key.split(":", 1)[1])
|
||
except ValueError:
|
||
ops_slot = 0
|
||
group = _group_for_neko_ref(kind=report["neko_kind"], local_id=nid, ops_slot=ops_slot)
|
||
ctx = _enrich_context_for_group(group)
|
||
peak = None
|
||
try:
|
||
vals = [
|
||
int(r.get("viewer_count"))
|
||
for r in (bucket if key else bucket2)
|
||
if r.get("viewer_count") is not None
|
||
]
|
||
peak = max(vals) if vals else None
|
||
except Exception:
|
||
peak = None
|
||
yt_studio_db.insert_sample(
|
||
ts=now,
|
||
group_id=ctx["group_id"],
|
||
channel_pk=ctx["channel_pk"],
|
||
youtube_channel_id=ctx["youtube_channel_id"],
|
||
source_room_id=ctx["source_room_id"],
|
||
source_url=ctx["source_url"],
|
||
anchor_name=ctx["anchor_name"],
|
||
neko_kind=report["neko_kind"],
|
||
neko_ref=key,
|
||
live_page_open=bool(report["live_page_open"]),
|
||
on_air=bool(report["on_air"]),
|
||
live_status=str(report["live_status"] or ""),
|
||
health=str(report["health"] or ""),
|
||
viewer_count=report.get("viewer_count"),
|
||
total_views=report.get("total_views"),
|
||
like_count=report.get("like_count"),
|
||
live_duration_sec=report.get("live_duration_sec"),
|
||
live_duration=str(report.get("live_duration") or ""),
|
||
stream_title=str(report.get("stream_title") or ""),
|
||
studio_url=str(report.get("url") or ""),
|
||
detect_source=str(report.get("source") or ""),
|
||
peak_viewers=peak,
|
||
relay_session_uuid=ctx.get("relay_session_uuid") or "",
|
||
)
|
||
except Exception:
|
||
pass
|
||
|
||
|
||
def _studio_ingest_fingerprint(body: dict[str, Any]) -> str:
|
||
"""Cheap fingerprint so unchanged Studio chrome doesn't allocate new events.
|
||
|
||
Intentionally ignores tick-level viewer_count / duration — those change every few
|
||
seconds during a live and would defeat coalesce (dy RSS climb).
|
||
"""
|
||
signals = body.get("signals") if isinstance(body.get("signals"), dict) else {}
|
||
return "|".join(
|
||
[
|
||
str(body.get("live_status") or ""),
|
||
str(body.get("health") or ""),
|
||
"1" if body.get("on_air") else "0",
|
||
"1" if signals.get("encoder_receiving") else "0",
|
||
"1" if signals.get("nodata") else "0",
|
||
"1" if signals.get("encoder_lost") else "0",
|
||
"1" if signals.get("chrome_offline") else "0",
|
||
str(body.get("url") or "")[-48:],
|
||
]
|
||
)
|
||
|
||
|
||
def ingest_studio_telemetry(payload: dict[str, Any] | None) -> dict[str, Any]:
|
||
"""Accept Studio telemetry from in-container Chrome extension (local or ops-neko).
|
||
|
||
Hot path must stay allocation-light: Neko tabs POST every few seconds. Duplicate
|
||
fingerprints are coalesced in-place so RSS cannot climb into MemoryHigh thrash
|
||
(dy historically hung in D-state with /api/health timing out while PID stayed "active").
|
||
"""
|
||
import time as _time
|
||
import uuid
|
||
|
||
global _studio_disk_write_at
|
||
|
||
_bootstrap_studio_telemetry_from_disk()
|
||
body = dict(payload or {})
|
||
kind, ref_key, neko_id = _resolve_neko_ref_for_payload(body)
|
||
if neko_id > 0:
|
||
body["neko_instance_id"] = neko_id
|
||
if ref_key:
|
||
body["neko_ref"] = ref_key
|
||
body["neko_kind"] = kind
|
||
now = float(body.get("received_at") or _time.time())
|
||
coalesce_key = ref_key or (f"local:{neko_id}" if neko_id > 0 else "")
|
||
fp = _studio_ingest_fingerprint(body)
|
||
if coalesce_key:
|
||
prev = _studio_ingest_last_fp.get(coalesce_key)
|
||
if prev and (now - float(prev[0])) < _STUDIO_INGEST_COALESCE_SEC and prev[1] == fp:
|
||
# Refresh latest timestamp + volatile counters in-place — no new event alloc.
|
||
existing = _studio_latest_by_ref.get(coalesce_key) or (
|
||
_studio_latest_by_neko.get(neko_id) if neko_id > 0 else None
|
||
)
|
||
if isinstance(existing, dict):
|
||
existing["received_at"] = now
|
||
payload_ex = existing.get("payload")
|
||
if isinstance(payload_ex, dict):
|
||
payload_ex["received_at"] = now
|
||
for k in (
|
||
"viewer_count",
|
||
"total_views",
|
||
"like_count",
|
||
"live_duration",
|
||
"live_duration_sec",
|
||
"stream_title",
|
||
):
|
||
if k in body and body.get(k) is not None:
|
||
payload_ex[k] = body.get(k)
|
||
# Still stamp minute buckets while coalescing (55s gate inside).
|
||
try:
|
||
_maybe_append_minute_report(
|
||
neko_id,
|
||
existing,
|
||
ref_key=ref_key or coalesce_key,
|
||
kind=kind,
|
||
)
|
||
except Exception:
|
||
pass
|
||
# Slide coalesce window so stable live doesn't allocate every 12s forever.
|
||
_studio_ingest_last_fp[coalesce_key] = (now, fp)
|
||
return {
|
||
"ok": True,
|
||
"coalesced": True,
|
||
"event": {
|
||
"id": existing.get("id"),
|
||
"received_at": now,
|
||
"neko_instance_id": neko_id,
|
||
"neko_ref": ref_key,
|
||
"neko_kind": kind,
|
||
},
|
||
}
|
||
_studio_ingest_last_fp[coalesce_key] = (now, fp)
|
||
# Bound coalesce map (ops refs can churn over weeks).
|
||
if len(_studio_ingest_last_fp) > 256:
|
||
oldest = sorted(_studio_ingest_last_fp.items(), key=lambda kv: float(kv[1][0]))[:64]
|
||
for k, _ in oldest:
|
||
_studio_ingest_last_fp.pop(k, None)
|
||
|
||
event = {
|
||
"id": str(uuid.uuid4()),
|
||
"received_at": now,
|
||
"neko_instance_id": neko_id,
|
||
"neko_ref": ref_key,
|
||
"neko_kind": kind,
|
||
"payload": body,
|
||
}
|
||
_studio_events.insert(0, event)
|
||
del _studio_events[_STUDIO_EVENTS_MAX:]
|
||
if ref_key:
|
||
_studio_latest_by_ref[ref_key] = event
|
||
_maybe_append_minute_report(neko_id, event, ref_key=ref_key, kind=kind)
|
||
elif neko_id > 0:
|
||
_studio_latest_by_neko[neko_id] = event
|
||
_maybe_append_minute_report(neko_id, event, ref_key=f"local:{neko_id}", kind="local")
|
||
if neko_id > 0:
|
||
_studio_latest_by_neko[neko_id] = event
|
||
# Debounce disk persist — under MemoryHigh reclaim, sync writes → D-state hangs.
|
||
if now - _studio_disk_write_at >= _STUDIO_DISK_WRITE_MIN_INTERVAL:
|
||
_studio_disk_write_at = now
|
||
try:
|
||
path = _neko_root() / "studio_telemetry_latest.json"
|
||
path.write_text(json.dumps(event, ensure_ascii=False, separators=(",", ":")), encoding="utf-8")
|
||
except OSError:
|
||
pass
|
||
return {
|
||
"ok": True,
|
||
"event": {
|
||
"id": event["id"],
|
||
"received_at": event["received_at"],
|
||
"neko_instance_id": event["neko_instance_id"],
|
||
"neko_ref": ref_key,
|
||
"neko_kind": kind,
|
||
},
|
||
}
|
||
|
||
|
||
def latest_studio_telemetry(*, limit: int = 20) -> list[dict[str, Any]]:
|
||
_bootstrap_studio_telemetry_from_disk()
|
||
return list(_studio_events[: max(1, min(100, int(limit)))])
|
||
|
||
|
||
def list_studio_minute_reports(neko_id: int = 0, *, limit: int = 30, neko_ref: str = "") -> list[dict[str, Any]]:
|
||
_bootstrap_studio_telemetry_from_disk()
|
||
lim = max(1, min(120, int(limit)))
|
||
key = str(neko_ref or "").strip()
|
||
if key:
|
||
return list(_studio_minute_reports_by_ref.get(key, [])[:lim])
|
||
nid = int(neko_id or 0)
|
||
if nid > 0:
|
||
return list(_studio_minute_reports.get(nid, [])[:lim])
|
||
out: list[dict[str, Any]] = []
|
||
for rows in _studio_minute_reports_by_ref.values():
|
||
out.extend(rows)
|
||
for rows in _studio_minute_reports.values():
|
||
out.extend(rows)
|
||
out.sort(key=lambda r: float(r.get("ts") or 0), reverse=True)
|
||
return out[:lim]
|
||
|
||
|
||
def studio_snapshot_for_ref(
|
||
ref_key: str,
|
||
*,
|
||
max_age_sec: float = 90.0,
|
||
local_id: int = 0,
|
||
include_minute_reports: bool = True,
|
||
) -> dict[str, Any]:
|
||
"""UI snapshot by neko_ref (local:N or ops:N)."""
|
||
import time as _time
|
||
|
||
key = str(ref_key or "").strip()
|
||
kind, key2, nid = parse_neko_ref(key)
|
||
if key2:
|
||
key = key2
|
||
if local_id > 0 and not key:
|
||
key = f"local:{local_id}"
|
||
nid = local_id
|
||
kind = "local"
|
||
now = _time.time()
|
||
out: dict[str, Any] = {
|
||
"neko_instance_id": nid,
|
||
"neko_ref": key,
|
||
"neko_kind": kind,
|
||
"live_page_open": False,
|
||
"on_air": False,
|
||
"live_status": "",
|
||
"health": "",
|
||
"viewer_count": None,
|
||
"like_count": None,
|
||
"total_views": None,
|
||
"live_duration": "",
|
||
"live_duration_sec": None,
|
||
"stream_title": "",
|
||
"url": "",
|
||
"received_at": 0.0,
|
||
"age_sec": None,
|
||
"detect_source": "",
|
||
"minute_reports": (
|
||
list_studio_minute_reports(nid, limit=90, neko_ref=key)
|
||
if include_minute_reports and key
|
||
else []
|
||
),
|
||
}
|
||
if not key:
|
||
return out
|
||
_bootstrap_studio_telemetry_from_disk()
|
||
ev = _studio_latest_by_ref.get(key)
|
||
if not isinstance(ev, dict) and nid > 0:
|
||
ev = _studio_latest_by_neko.get(nid)
|
||
if isinstance(ev, dict):
|
||
received0 = float(ev.get("received_at") or 0)
|
||
if received0 and (now - received0) > max_age_sec:
|
||
ev = None
|
||
if isinstance(ev, dict):
|
||
received = float(ev.get("received_at") or 0)
|
||
age = (now - received) if received else None
|
||
if age is None or age <= max_age_sec:
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
page_open = _payload_is_livestreaming(payload)
|
||
on_air = _payload_stream_confirmed(payload) if page_open else False
|
||
encoder_lost = _payload_encoder_lost(payload) if page_open else False
|
||
session_live = _payload_session_live(payload) if page_open else False
|
||
signals = payload.get("signals") if isinstance(payload.get("signals"), dict) else {}
|
||
encoder_receiving = bool(signals.get("encoder_receiving")) or (
|
||
on_air and not encoder_lost
|
||
)
|
||
out.update(
|
||
{
|
||
"live_page_open": page_open,
|
||
"on_air": on_air,
|
||
"encoder_lost": encoder_lost,
|
||
"encoder_receiving": encoder_receiving,
|
||
"session_live": session_live,
|
||
"live_status": str(payload.get("live_status") or ""),
|
||
"health": str(payload.get("health") or ""),
|
||
"viewer_count": payload.get("viewer_count"),
|
||
"like_count": payload.get("like_count"),
|
||
"total_views": payload.get("total_views"),
|
||
"live_duration": str(payload.get("live_duration") or "")[:16],
|
||
"live_duration_sec": payload.get("live_duration_sec"),
|
||
"stream_title": str(payload.get("stream_title") or "")[:120],
|
||
"url": str(payload.get("url") or "")[:200],
|
||
"received_at": received,
|
||
"age_sec": round(age, 1) if age is not None else None,
|
||
"detect_source": str(payload.get("source") or ev.get("neko_kind") or "telemetry"),
|
||
}
|
||
)
|
||
return out
|
||
|
||
|
||
def studio_snapshot_for_group(
|
||
group: dict[str, Any] | None,
|
||
*,
|
||
max_age_sec: float = 120.0,
|
||
include_minute_reports: bool = True,
|
||
) -> dict[str, Any]:
|
||
"""Prefer remote ops telemetry when group opens remote Neko; else local assign Neko."""
|
||
empty = {
|
||
"neko_instance_id": 0,
|
||
"neko_ref": "",
|
||
"neko_kind": "local",
|
||
"live_page_open": False,
|
||
"on_air": False,
|
||
"live_status": "",
|
||
"health": "",
|
||
"viewer_count": None,
|
||
"like_count": None,
|
||
"total_views": None,
|
||
"live_duration": "",
|
||
"live_duration_sec": None,
|
||
"stream_title": "",
|
||
"url": "",
|
||
"received_at": 0.0,
|
||
"age_sec": None,
|
||
"detect_source": "",
|
||
"minute_reports": [],
|
||
"ui_source": "none",
|
||
}
|
||
if not group:
|
||
return empty
|
||
prefer = str(group.get("neko_open_prefer") or group.get("neko_open_source") or "local").strip().lower()
|
||
remote_bound = bool(str(group.get("ops_neko_open_url") or "").strip())
|
||
ops_slot = int(group.get("ops_neko_slot") or 0)
|
||
local_id = int(group.get("neko_instance_id") or 0)
|
||
|
||
remote_snap = None
|
||
if remote_bound and ops_slot > 0:
|
||
remote_snap = studio_snapshot_for_ref(
|
||
f"ops:{ops_slot}", max_age_sec=max_age_sec, include_minute_reports=include_minute_reports
|
||
)
|
||
remote_snap["ui_source"] = "remote"
|
||
local_snap = None
|
||
if local_id > 0:
|
||
# allow_cdp=True: use host CDP poll cache when extension ingest is quiet
|
||
# (common when neko_enabled=0 but container still running for a live push).
|
||
local_snap = studio_snapshot_for_instance(
|
||
local_id,
|
||
max_age_sec=max_age_sec,
|
||
allow_cdp=True,
|
||
include_minute_reports=include_minute_reports,
|
||
)
|
||
local_snap["neko_ref"] = f"local:{local_id}"
|
||
local_snap["neko_kind"] = "local"
|
||
local_snap["ui_source"] = "local"
|
||
|
||
def _fresh(snap: dict[str, Any] | None) -> bool:
|
||
if not isinstance(snap, dict):
|
||
return False
|
||
age = snap.get("age_sec")
|
||
if age is None:
|
||
return bool(snap.get("live_page_open") or snap.get("on_air") or snap.get("received_at"))
|
||
try:
|
||
return float(age) <= float(max_age_sec)
|
||
except (TypeError, ValueError):
|
||
return False
|
||
|
||
def _live_ui(snap: dict[str, Any] | None) -> bool:
|
||
"""Studio Live control page open and/or Studio marks on-air — scrape-worthy."""
|
||
if not isinstance(snap, dict):
|
||
return False
|
||
return bool(snap.get("live_page_open") or snap.get("on_air"))
|
||
|
||
# Evidence-first: never let prefer=local + "fresh but page closed" hide a remote
|
||
# Live page that is actually open (UI would wrongly say「Live 页未打开」).
|
||
# neko_open_prefer still wins when BOTH sides have Live UI, or neither does.
|
||
local_fresh = _fresh(local_snap)
|
||
remote_fresh = _fresh(remote_snap)
|
||
local_live = local_fresh and _live_ui(local_snap)
|
||
remote_live = remote_fresh and _live_ui(remote_snap)
|
||
|
||
if remote_live and not local_live:
|
||
out = dict(remote_snap or empty)
|
||
out["ui_source"] = "remote" if (prefer == "remote" and remote_bound) else "remote_fallback"
|
||
return out
|
||
if local_live and not remote_live:
|
||
out = dict(local_snap or empty)
|
||
out["ui_source"] = "local" if prefer != "remote" else "local_fallback"
|
||
return out
|
||
|
||
if prefer == "remote" and remote_bound:
|
||
if remote_fresh:
|
||
return remote_snap or empty
|
||
if local_fresh:
|
||
out = dict(local_snap or empty)
|
||
out["ui_source"] = "local_fallback"
|
||
return out
|
||
return remote_snap or local_snap or empty
|
||
|
||
if local_fresh:
|
||
return local_snap or empty
|
||
if remote_fresh:
|
||
out = dict(remote_snap or empty)
|
||
out["ui_source"] = "remote_fallback"
|
||
return out
|
||
return local_snap or remote_snap or empty
|
||
|
||
|
||
def ingest_remote_studio_mirror(slot: int, studio: dict[str, Any] | None) -> dict[str, Any]:
|
||
"""Hub-side: accept studio snapshot pushed from physical edge catalog sync."""
|
||
import time as _time
|
||
|
||
slot_i = int(slot or 0)
|
||
if slot_i < 1 or not isinstance(studio, dict):
|
||
return {"ok": False, "skipped": True}
|
||
raw_status = str(studio.get("live_status") or "").strip().lower()
|
||
# Never invent "streaming"/"live" from page_open alone — that caused false on_air on hub.
|
||
if raw_status in {"ready", "streaming"}:
|
||
raw_status = "waiting"
|
||
on_air = bool(studio.get("on_air"))
|
||
page_open = bool(studio.get("live_page_open") or on_air or studio.get("session_live"))
|
||
encoder_lost = bool(studio.get("encoder_lost")) or raw_status in {"encoder_lost", "stalled"}
|
||
session_live = bool(studio.get("session_live")) or encoder_lost or raw_status in {"live", "encoder_lost"}
|
||
nodata = bool(studio.get("nodata"))
|
||
if on_air and not raw_status:
|
||
raw_status = "live"
|
||
elif encoder_lost and raw_status not in {"encoder_lost", "stalled"}:
|
||
raw_status = "encoder_lost"
|
||
elif page_open and not raw_status:
|
||
raw_status = "waiting"
|
||
url = str(studio.get("url") or "").strip()
|
||
# Refuse synthetic placeholder URLs that only exist to satisfy livestreaming helpers.
|
||
if "/video/x/livestreaming" in url.lower():
|
||
url = ""
|
||
signals: dict[str, Any] = {"path": "/livestreaming"} if page_open else {}
|
||
if nodata:
|
||
signals["nodata"] = True
|
||
if encoder_lost:
|
||
signals["encoder_lost"] = True
|
||
signals["session_live"] = True
|
||
signals["pending_go_live"] = False
|
||
elif session_live or on_air:
|
||
signals["session_live"] = True
|
||
signals["pending_go_live"] = False
|
||
elif page_open and not on_air:
|
||
signals["pending_go_live"] = True
|
||
if raw_status in {"waiting", "signed_out", "offline"} and not session_live and not encoder_lost:
|
||
signals["pending_go_live"] = True
|
||
payload = {
|
||
"neko_ref": f"ops-{slot_i}",
|
||
"neko_instance_id": f"ops-{slot_i}",
|
||
"source": str(studio.get("detect_source") or "edge_sync"),
|
||
"live_status": raw_status,
|
||
"health": studio.get("health") or "",
|
||
"viewer_count": studio.get("viewer_count"),
|
||
"total_views": studio.get("total_views"),
|
||
"like_count": studio.get("like_count"),
|
||
"live_duration": studio.get("live_duration") or "",
|
||
"live_duration_sec": studio.get("live_duration_sec"),
|
||
"stream_title": studio.get("stream_title") or "",
|
||
"url": url,
|
||
"received_at": studio.get("received_at") or _time.time(),
|
||
"signals": signals,
|
||
"text": str(studio.get("text") or "")[:2200],
|
||
}
|
||
out = ingest_studio_telemetry(payload)
|
||
# Also seed minute reports if edge included them
|
||
reports = studio.get("minute_reports") if isinstance(studio.get("minute_reports"), list) else []
|
||
key = f"ops:{slot_i}"
|
||
if reports:
|
||
cleaned = [r for r in reports if isinstance(r, dict)][:_STUDIO_MINUTE_MAX]
|
||
if cleaned:
|
||
_studio_minute_reports_by_ref[key] = cleaned
|
||
try:
|
||
_studio_minute_last_at_by_ref[key] = float(cleaned[0].get("ts") or 0)
|
||
except (TypeError, ValueError):
|
||
pass
|
||
return out
|
||
|
||
|
||
def studio_snapshot_for_instance(
|
||
neko_id: int,
|
||
*,
|
||
max_age_sec: float = 90.0,
|
||
allow_cdp: bool = False,
|
||
include_minute_reports: bool = True,
|
||
) -> dict[str, Any]:
|
||
"""UI-facing Neko Studio feedback: Live page open? On-air? Viewers? Health?"""
|
||
import time as _time
|
||
|
||
nid = int(neko_id or 0)
|
||
now = _time.time()
|
||
out: dict[str, Any] = {
|
||
"neko_instance_id": nid,
|
||
"live_page_open": False,
|
||
"on_air": False,
|
||
"live_status": "",
|
||
"health": "",
|
||
"viewer_count": None,
|
||
"like_count": None,
|
||
"total_views": None,
|
||
"live_duration": "",
|
||
"live_duration_sec": None,
|
||
"stream_title": "",
|
||
"url": "",
|
||
"received_at": 0.0,
|
||
"age_sec": None,
|
||
"detect_source": "",
|
||
# ~90 pts ≈ 1.5h at 1/min — enough for Studio-style viewer timeline chart
|
||
"minute_reports": (
|
||
list_studio_minute_reports(nid, limit=90) if include_minute_reports and nid > 0 else []
|
||
),
|
||
}
|
||
if nid < 1:
|
||
return out
|
||
|
||
_bootstrap_studio_telemetry_from_disk()
|
||
ev = _studio_latest_by_neko.get(nid)
|
||
if isinstance(ev, dict):
|
||
received0 = float(ev.get("received_at") or 0)
|
||
if received0 and (now - received0) > max_age_sec:
|
||
ev = None
|
||
if not isinstance(ev, dict):
|
||
ev = latest_live_studio_event(max_age_sec=max_age_sec, neko_id=nid)
|
||
if isinstance(ev, dict):
|
||
received = float(ev.get("received_at") or 0)
|
||
age = (now - received) if received else None
|
||
if age is None or age <= max_age_sec:
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
page_open = _payload_is_livestreaming(payload)
|
||
on_air = _payload_stream_confirmed(payload) if page_open else False
|
||
encoder_lost = _payload_encoder_lost(payload) if page_open else False
|
||
session_live = _payload_session_live(payload) if page_open else False
|
||
out.update(
|
||
{
|
||
"live_page_open": page_open,
|
||
"on_air": on_air,
|
||
"encoder_lost": encoder_lost,
|
||
"session_live": session_live,
|
||
"live_status": str(payload.get("live_status") or ""),
|
||
"health": str(payload.get("health") or ""),
|
||
"viewer_count": payload.get("viewer_count"),
|
||
"like_count": payload.get("like_count"),
|
||
"total_views": payload.get("total_views"),
|
||
"live_duration": str(payload.get("live_duration") or "")[:16],
|
||
"live_duration_sec": payload.get("live_duration_sec"),
|
||
"stream_title": str(payload.get("stream_title") or "")[:120],
|
||
"url": str(payload.get("url") or "")[:200],
|
||
"received_at": received,
|
||
"age_sec": round(age, 1) if age is not None else None,
|
||
"detect_source": "telemetry",
|
||
}
|
||
)
|
||
# Telemetry can claim live/Excellent while Studio preview still shows Preparing stream.
|
||
try:
|
||
sig = _cdp_studio_page_signals(nid, max_age_sec=90.0)
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
if sig.get("preparing_stream") or str(sig.get("live_status") or "") == "preparing":
|
||
out["preparing_stream"] = True
|
||
out["on_air"] = False
|
||
out["live_status"] = "preparing"
|
||
if sig.get("control_ready") is not None:
|
||
out["control_ready"] = bool(sig.get("control_ready"))
|
||
except Exception:
|
||
pass
|
||
return out
|
||
|
||
if not allow_cdp:
|
||
return out
|
||
|
||
# CDP fallback when extension ingest is quiet but Chrome still has Live tab.
|
||
# Prefer cached DOM signals from the host poller (never force a fresh scrape here).
|
||
try:
|
||
st = _container_state(nid, check_http=False)
|
||
if st.get("running"):
|
||
sig = _cdp_studio_page_signals(nid, max_age_sec=90.0)
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
preparing = bool(sig.get("preparing_stream")) or str(sig.get("live_status") or "") == "preparing"
|
||
on_air = bool(sig.get("on_air")) and not preparing
|
||
out.update(
|
||
{
|
||
"live_page_open": True,
|
||
"on_air": on_air,
|
||
"preparing_stream": preparing,
|
||
"control_ready": bool(sig.get("control_ready")),
|
||
"live_status": (
|
||
"preparing"
|
||
if preparing
|
||
else str(sig.get("live_status") or ("live" if on_air else ""))
|
||
),
|
||
"health": str(sig.get("health") or ""),
|
||
"viewer_count": sig.get("viewer_count"),
|
||
"total_views": sig.get("total_views"),
|
||
"live_duration": str(sig.get("live_duration") or "")[:16],
|
||
"live_duration_sec": sig.get("live_duration_sec"),
|
||
"url": str(sig.get("url") or "")[:200],
|
||
"detect_source": "cdp_dom",
|
||
"received_at": now,
|
||
"age_sec": 0.0,
|
||
}
|
||
)
|
||
return out
|
||
urls = _cdp_live_studio_urls(nid)
|
||
if urls:
|
||
out.update(
|
||
{
|
||
"live_page_open": True,
|
||
"on_air": False,
|
||
"live_status": "cdp_live_tab",
|
||
"url": urls[0][:200],
|
||
"detect_source": "cdp",
|
||
}
|
||
)
|
||
except Exception:
|
||
pass
|
||
return out
|
||
|
||
|
||
def studio_on_air_lookup(neko_id: int, *, max_age_sec: float = 120.0) -> dict[str, Any]:
|
||
"""Non-destructive live detect: telemetry first, then read-only CDP URL match.
|
||
|
||
Safe for keep-warm Nekos: never restarts Chrome / never recreates containers.
|
||
"""
|
||
import time as _time
|
||
|
||
nid = int(neko_id or 0)
|
||
snap = studio_snapshot_for_instance(nid, max_age_sec=max_age_sec, allow_cdp=False)
|
||
if snap.get("on_air"):
|
||
# Enrich missing Analytics fields from CDP cache (Views / LIVE duration).
|
||
if nid > 0 and (snap.get("total_views") is None or not snap.get("live_duration")):
|
||
try:
|
||
sig = _cdp_studio_page_signals(nid, max_age_sec=90.0)
|
||
except Exception:
|
||
sig = {}
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
if snap.get("total_views") is None and sig.get("total_views") is not None:
|
||
snap["total_views"] = sig.get("total_views")
|
||
if not snap.get("live_duration") and sig.get("live_duration"):
|
||
snap["live_duration"] = str(sig.get("live_duration") or "")[:16]
|
||
snap["live_duration_sec"] = sig.get("live_duration_sec")
|
||
if snap.get("viewer_count") is None and sig.get("viewer_count") is not None:
|
||
snap["viewer_count"] = sig.get("viewer_count")
|
||
return snap
|
||
|
||
urls: list[str] = []
|
||
if nid > 0:
|
||
try:
|
||
st = _container_state(nid, check_http=False)
|
||
if st.get("running"):
|
||
urls = _cdp_live_studio_urls(nid)
|
||
except Exception:
|
||
urls = []
|
||
|
||
if urls:
|
||
snap["live_page_open"] = True
|
||
if not snap.get("url"):
|
||
snap["url"] = urls[0][:200]
|
||
if not snap.get("detect_source"):
|
||
snap["detect_source"] = "cdp"
|
||
|
||
vids = [v for v in (_extract_studio_video_id(u) for u in urls) if v]
|
||
if not vids and snap.get("url"):
|
||
v0 = _extract_studio_video_id(str(snap.get("url") or ""))
|
||
if v0:
|
||
vids = [v0]
|
||
|
||
now = _time.time()
|
||
|
||
# CDP DOM first — ground truth from the open Studio tab (read-only). Prefer poller cache.
|
||
if nid > 0 and urls:
|
||
try:
|
||
sig = _cdp_studio_page_signals(nid, max_age_sec=55.0)
|
||
except Exception:
|
||
sig = {}
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
snap["live_page_open"] = True
|
||
if sig.get("url"):
|
||
snap["url"] = str(sig.get("url") or "")[:200]
|
||
snap["live_status"] = str(sig.get("live_status") or "")
|
||
snap["health"] = str(sig.get("health") or "")
|
||
if sig.get("viewer_count") is not None:
|
||
snap["viewer_count"] = sig.get("viewer_count")
|
||
if sig.get("total_views") is not None:
|
||
snap["total_views"] = sig.get("total_views")
|
||
if sig.get("live_duration"):
|
||
snap["live_duration"] = str(sig.get("live_duration") or "")[:16]
|
||
snap["live_duration_sec"] = sig.get("live_duration_sec")
|
||
snap["detect_source"] = "cdp_dom"
|
||
snap["received_at"] = now
|
||
snap["age_sec"] = 0.0
|
||
if sig.get("on_air"):
|
||
snap["on_air"] = True
|
||
if not snap.get("live_status"):
|
||
snap["live_status"] = "live"
|
||
return snap
|
||
if str(sig.get("live_status") or "") in {"waiting", "ended", "signed_out", "preparing"}:
|
||
snap["on_air"] = False
|
||
if str(sig.get("live_status") or "") == "preparing" or sig.get("preparing_stream"):
|
||
snap["preparing_stream"] = True
|
||
snap["live_status"] = "preparing"
|
||
return snap
|
||
|
||
if not vids:
|
||
return snap
|
||
|
||
_bootstrap_studio_telemetry_from_disk()
|
||
for ev in _studio_events[:60]:
|
||
received = float(ev.get("received_at") or 0)
|
||
if received and (now - received) > max_age_sec:
|
||
continue
|
||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||
url = str(payload.get("url") or "")
|
||
if not any(v in url for v in vids):
|
||
continue
|
||
if not _payload_stream_confirmed(payload):
|
||
if _payload_is_livestreaming(payload):
|
||
snap.setdefault("live_status", str(payload.get("live_status") or ""))
|
||
snap.setdefault("health", str(payload.get("health") or ""))
|
||
snap["viewer_count"] = payload.get("viewer_count")
|
||
snap["received_at"] = received
|
||
snap["age_sec"] = round(now - received, 1) if received else None
|
||
snap["detect_source"] = "cdp_telemetry_page"
|
||
continue
|
||
snap.update(
|
||
{
|
||
"on_air": True,
|
||
"live_page_open": True,
|
||
"live_status": str(payload.get("live_status") or "live"),
|
||
"health": str(payload.get("health") or ""),
|
||
"viewer_count": payload.get("viewer_count"),
|
||
"like_count": payload.get("like_count"),
|
||
"stream_title": str(payload.get("stream_title") or "")[:120],
|
||
"url": url[:200],
|
||
"received_at": received,
|
||
"age_sec": round(now - received, 1) if received else None,
|
||
"detect_source": "cdp_telemetry_match",
|
||
"neko_instance_id": nid,
|
||
}
|
||
)
|
||
return snap
|
||
return snap
|
||
|
||
|
||
def _neko_ids_for_cdp_poll() -> list[int]:
|
||
"""Neko instances that should get Studio CDP backup scrapes.
|
||
|
||
Include:
|
||
- assign groups with neko_enabled (warm Studio)
|
||
- any assign-bound instance whose container is already running
|
||
(relay may leave Chrome up while DB neko_enabled=0 — still must scrape)
|
||
"""
|
||
ids: list[int] = []
|
||
try:
|
||
from . import yt_assign_db
|
||
|
||
for g in yt_assign_db.list_groups(include_urls=False):
|
||
try:
|
||
nid = int(g.get("neko_instance_id") or 0)
|
||
except (TypeError, ValueError):
|
||
nid = 0
|
||
if nid < 1:
|
||
continue
|
||
if g.get("neko_enabled"):
|
||
ids.append(nid)
|
||
continue
|
||
try:
|
||
if _container_state(nid, check_http=False).get("running"):
|
||
ids.append(nid)
|
||
except Exception:
|
||
continue
|
||
except Exception:
|
||
return []
|
||
return sorted(set(ids))
|
||
|
||
|
||
def _ingest_cdp_signals(neko_id: int, sig: dict[str, Any]) -> dict[str, Any]:
|
||
"""Turn a CDP scrape result into the same telemetry / minute-report path as the extension."""
|
||
nid = int(neko_id or 0)
|
||
if nid < 1 or not isinstance(sig, dict) or not sig.get("ok"):
|
||
return {"ok": False, "skipped": True, "neko_instance_id": nid}
|
||
url = str(sig.get("url") or "")
|
||
live_status = str(sig.get("live_status") or "")
|
||
payload: dict[str, Any] = {
|
||
"neko_instance_id": nid,
|
||
"url": url[:400],
|
||
"live_status": live_status,
|
||
"health": str(sig.get("health") or ""),
|
||
"viewer_count": sig.get("viewer_count"),
|
||
"total_views": sig.get("total_views"),
|
||
"live_duration": str(sig.get("live_duration") or "")[:16],
|
||
"live_duration_sec": sig.get("live_duration_sec"),
|
||
"text": str(sig.get("text") or "")[:800],
|
||
"source": "cdp",
|
||
"signals": {"path": "/livestreaming"} if ("livestreaming" in url.lower() or live_status) else {},
|
||
}
|
||
if sig.get("on_air") and not payload["live_status"]:
|
||
payload["live_status"] = "live"
|
||
return ingest_studio_telemetry(payload)
|
||
|
||
|
||
def poll_studio_cdp_once() -> dict[str, Any]:
|
||
"""One host-side CDP pass over running Nekos. Never restarts Chrome / never recreates containers."""
|
||
import time as _time
|
||
|
||
ids = _neko_ids_for_cdp_poll()
|
||
polled: list[dict[str, Any]] = []
|
||
for nid in ids:
|
||
try:
|
||
st = _container_state(nid, check_http=False)
|
||
if not st.get("running"):
|
||
polled.append({"neko_instance_id": nid, "skipped": "not_running"})
|
||
continue
|
||
sig = _cdp_studio_page_signals(nid, force=True)
|
||
if isinstance(sig, dict) and sig.get("ok"):
|
||
ingest = _ingest_cdp_signals(nid, sig)
|
||
polled.append(
|
||
{
|
||
"neko_instance_id": nid,
|
||
"ok": True,
|
||
"on_air": bool(sig.get("on_air")),
|
||
"live_status": str(sig.get("live_status") or ""),
|
||
"viewer_count": sig.get("viewer_count"),
|
||
"ingested": bool(ingest.get("ok")),
|
||
}
|
||
)
|
||
else:
|
||
polled.append(
|
||
{
|
||
"neko_instance_id": nid,
|
||
"ok": False,
|
||
"error": str((sig or {}).get("error") or "cdp_failed")[:120],
|
||
}
|
||
)
|
||
except Exception as exc:
|
||
polled.append({"neko_instance_id": nid, "ok": False, "error": str(exc)[:160]})
|
||
_time.sleep(0.35)
|
||
return {"ok": True, "count": len(polled), "polled": polled}
|
||
|
||
|
||
async def studio_cdp_poll_loop() -> None:
|
||
"""Background ~55s CDP backup for Studio on-air + soft-heal crashed needed Nekos."""
|
||
import asyncio
|
||
import logging
|
||
|
||
log = logging.getLogger("youtube_neko")
|
||
if str(os.environ.get("DY_DISABLE_STUDIO_CDP_LOOP") or "").strip().lower() in {"1", "true", "yes"}:
|
||
return
|
||
try:
|
||
await asyncio.sleep(50)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
while True:
|
||
try:
|
||
await asyncio.wait_for(asyncio.to_thread(poll_studio_cdp_once), timeout=240)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
# Soft heal: OOM/exit containers + Chrome SIGILL/Aw Snap/CDP-dead (never wipe profiles).
|
||
if str(os.environ.get("DY_DISABLE_NEKO_SOFT_HEAL") or "").strip().lower() not in {
|
||
"1",
|
||
"true",
|
||
"yes",
|
||
}:
|
||
try:
|
||
heal = await asyncio.wait_for(asyncio.to_thread(heal_neko_runtime), timeout=180)
|
||
if heal.get("healed"):
|
||
log.warning("neko_runtime_heal %s", heal)
|
||
except asyncio.CancelledError:
|
||
raise
|
||
except Exception:
|
||
pass
|
||
try:
|
||
await asyncio.sleep(_CDP_POLL_INTERVAL_SEC)
|
||
except asyncio.CancelledError:
|
||
raise
|