Block FFmpeg until Neko YouTube Live page is freshly settled.
Remove skip-neko-wait on stale telemetry; require new livestreaming heartbeats for 25s after slot switch. Add youtube_live_confirmed to relay status and unit tests. Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
parent
11394a2a80
commit
b6a66fbddf
@ -822,32 +822,99 @@ def ensure_instance_running(instance_id: int) -> dict[str, Any]:
|
||||
return {"ok": True, "id": idx, "started": True}
|
||||
|
||||
|
||||
def recent_live_studio_seen(*, max_age_sec: float = 120.0) -> bool:
|
||||
"""True if any recent studio telemetry URL is YouTube Live Control Room."""
|
||||
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_stream_confirmed(payload: dict[str, Any] | None) -> bool:
|
||||
"""True when Studio telemetry says this channel is actually live / healthy."""
|
||||
body = payload or {}
|
||||
status = str(body.get("live_status") or "").strip().lower()
|
||||
health = str(body.get("health") or "").strip().lower()
|
||||
if status in {"live", "streaming"}:
|
||||
return True
|
||||
if health in {"excellent", "good"}:
|
||||
return True
|
||||
text = str(body.get("text") or "").lower()
|
||||
if any(
|
||||
x in text
|
||||
for x in (
|
||||
"you're live",
|
||||
"you are live",
|
||||
"stream is healthy",
|
||||
"excellent connection",
|
||||
"正在直播",
|
||||
"直播中",
|
||||
"连接状况极佳",
|
||||
"状况良好",
|
||||
)
|
||||
):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def latest_live_studio_event(
|
||||
*,
|
||||
max_age_sec: float = 60.0,
|
||||
since_ts: float = 0.0,
|
||||
) -> dict[str, Any] | None:
|
||||
"""Newest Studio Control Room telemetry, optionally only after `since_ts`."""
|
||||
import time as _time
|
||||
|
||||
now = _time.time()
|
||||
for ev in _studio_events[:40]:
|
||||
age = now - float(ev.get("received_at") or 0)
|
||||
if age > max_age_sec:
|
||||
since = float(since_ts 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 {}
|
||||
url = str(payload.get("url") or "").lower()
|
||||
path = str((payload.get("signals") or {}).get("path") or "").lower()
|
||||
if "livestreaming" in url or "livestreaming" in path:
|
||||
return True
|
||||
return False
|
||||
if not _payload_is_livestreaming(payload if isinstance(payload, dict) else {}):
|
||||
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) -> dict[str, Any]:
|
||||
"""Detect whether Studio reports 1 live stream is truly on-air."""
|
||||
ev = latest_live_studio_event(max_age_sec=max_age_sec, since_ts=since_ts)
|
||||
if not ev:
|
||||
return {"ok": False, "live": False, "reason": "no_live_studio_page"}
|
||||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||||
confirmed = _payload_stream_confirmed(payload)
|
||||
return {
|
||||
"ok": True,
|
||||
"live": confirmed,
|
||||
"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),
|
||||
"reason": "stream_confirmed" if confirmed else "page_open_not_confirmed_live",
|
||||
}
|
||||
|
||||
|
||||
def wait_instance_ready_for_live(
|
||||
instance_id: int,
|
||||
*,
|
||||
timeout_sec: float = 90.0,
|
||||
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 running/ready and (optionally) Studio livestreaming is open.
|
||||
"""Block until Neko is up AND Studio livestreaming page is freshly open + settled.
|
||||
|
||||
In exclusive mode only one Neko runs, so global livestreaming telemetry is enough.
|
||||
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
|
||||
|
||||
@ -858,41 +925,84 @@ def wait_instance_ready_for_live(
|
||||
if not started.get("ok") and not started.get("already"):
|
||||
return {"ok": False, "id": idx, "error": started.get("error") or "neko_start_failed"}
|
||||
|
||||
deadline = _time.time() + max(15.0, float(timeout_sec))
|
||||
# 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
|
||||
|
||||
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 running and ready:
|
||||
if not ready_at:
|
||||
ready_at = _time.time()
|
||||
if not require_live_page:
|
||||
return {"ok": True, "id": idx, "ready": True, "live_studio": False}
|
||||
if recent_live_studio_seen(max_age_sec=180.0):
|
||||
return {"ok": True, "id": idx, "ready": True, "live_studio": True}
|
||||
# Give extension/browser time to land on livestreaming after container ready.
|
||||
if ready_at and (_time.time() - ready_at) >= 25.0:
|
||||
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}
|
||||
|
||||
# Fresh Control Room heartbeat after exclusive switch / this wait started.
|
||||
ev = latest_live_studio_event(max_age_sec=45.0, since_ts=wait_since)
|
||||
if ev is None:
|
||||
# Also accept very fresh events that slightly overlap ensure_instance_running.
|
||||
ev = latest_live_studio_event(max_age_sec=20.0, since_ts=wait_since - 5.0)
|
||||
if ev is not None:
|
||||
last_ev = ev
|
||||
if not page_first_seen:
|
||||
page_first_seen = float(ev.get("received_at") or _time.time())
|
||||
settled_for = _time.time() - page_first_seen
|
||||
# Keep getting heartbeat during settle so the tab is alive, not a one-shot flash.
|
||||
if settled_for >= settle_need:
|
||||
payload = ev.get("payload") if isinstance(ev.get("payload"), dict) else {}
|
||||
return {
|
||||
"ok": True,
|
||||
"id": idx,
|
||||
"ready": True,
|
||||
"live_studio": False,
|
||||
"note": "neko_ready_waited_for_live_page",
|
||||
"live_studio": True,
|
||||
"settled": True,
|
||||
"settle_sec": round(settled_for, 1),
|
||||
"wait_since": wait_since,
|
||||
"live_status": str(payload.get("live_status") or ""),
|
||||
"health": str(payload.get("health") or ""),
|
||||
"url": str(payload.get("url") or "")[:200],
|
||||
"note": "live_studio_page_settled",
|
||||
}
|
||||
_time.sleep(2.0)
|
||||
|
||||
if last.get("running"):
|
||||
page_open = page_first_seen > 0 or recent_live_studio_seen(max_age_sec=45.0, since_ts=wait_since)
|
||||
if strict and require_live_page:
|
||||
return {
|
||||
"ok": True,
|
||||
"ok": False,
|
||||
"id": idx,
|
||||
"ready": bool(last.get("ready")),
|
||||
"live_studio": recent_live_studio_seen(max_age_sec=180.0),
|
||||
"live_studio": bool(page_open),
|
||||
"timeout": True,
|
||||
"note": "neko_running_after_timeout",
|
||||
"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": False, "id": idx, "error": "Neko 未在时限内启动成功", "state": last}
|
||||
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 restore_enabled_instances() -> dict[str, Any]:
|
||||
|
||||
@ -281,7 +281,14 @@ class YoutubeRelayPipeline:
|
||||
"schedule": schedule,
|
||||
"exclusive_winner_group_id": self._exclusive_winner,
|
||||
"neko_paused_instances": sorted(self._neko_paused_instances),
|
||||
"studio_live": None,
|
||||
}
|
||||
try:
|
||||
from . import youtube_neko
|
||||
|
||||
payload["studio_live"] = youtube_neko.youtube_live_confirmed(max_age_sec=60.0)
|
||||
except Exception:
|
||||
payload["studio_live"] = {"ok": False, "live": False, "reason": "unavailable"}
|
||||
self._status_cache = payload
|
||||
self._status_cache_at = time.time()
|
||||
return payload
|
||||
@ -849,52 +856,50 @@ class YoutubeRelayPipeline:
|
||||
|
||||
await self._enforce_exclusive_live(gid, group)
|
||||
|
||||
# VPS: wait until winner Neko is up and Studio Live page is open before FFmpeg.
|
||||
# Exclusive / time-slot: NEVER start FFmpeg until Studio Live Control Room is
|
||||
# freshly open and settled. Skipping on stale telemetry causes YouTube green-loading.
|
||||
neko_id = int(group.get("neko_instance_id") or 0)
|
||||
if neko_id > 0 and (_time_slot_mode(cfg) or bool(cfg.get("youtube_relay_exclusive_live", True))):
|
||||
from . import youtube_neko
|
||||
|
||||
skip_neko_wait = False
|
||||
try:
|
||||
inst = youtube_neko.list_instances(neko_id, check_http=False)
|
||||
row = next((x for x in inst if int(x.get("id") or 0) == neko_id), None)
|
||||
if isinstance(row, dict) and row.get("running") and (
|
||||
row.get("ready") or youtube_neko.recent_live_studio_seen(max_age_sec=300.0)
|
||||
):
|
||||
skip_neko_wait = True
|
||||
except Exception:
|
||||
skip_neko_wait = False
|
||||
|
||||
if not skip_neko_wait:
|
||||
boot_log.append(f"[relay] waiting neko-{neko_id} ready + YouTube Live…")
|
||||
boot_log.append(
|
||||
f"[relay] waiting neko-{neko_id} YouTube Live 控制页就绪"
|
||||
f"(须新遥测 + 稳定 ≥25s,禁止抢跑)…"
|
||||
)
|
||||
youtube_relay_db.upsert_relay_state(
|
||||
gid,
|
||||
status="starting",
|
||||
error="等待 Neko 打开 YouTube Live 控制页…",
|
||||
recent_log=boot_log[-40:],
|
||||
)
|
||||
neko_wait = await asyncio.to_thread(
|
||||
youtube_neko.wait_instance_ready_for_live,
|
||||
neko_id,
|
||||
timeout_sec=180.0,
|
||||
require_live_page=True,
|
||||
settle_sec=25.0,
|
||||
strict=True,
|
||||
)
|
||||
if not neko_wait.get("ok") or not neko_wait.get("live_studio"):
|
||||
err = str(
|
||||
neko_wait.get("error")
|
||||
or "YouTube Live 控制页未就绪,暂不推流(避免绿点无效 ingest)"
|
||||
)
|
||||
boot_log.append(f"[relay] neko wait blocked: {err}")
|
||||
youtube_relay_db.upsert_relay_state(
|
||||
gid,
|
||||
status="starting",
|
||||
error="",
|
||||
status="waiting",
|
||||
error=err,
|
||||
recent_log=boot_log[-40:],
|
||||
)
|
||||
neko_wait = await asyncio.to_thread(
|
||||
youtube_neko.wait_instance_ready_for_live,
|
||||
neko_id,
|
||||
timeout_sec=90.0,
|
||||
require_live_page=True,
|
||||
)
|
||||
if not neko_wait.get("ok"):
|
||||
err = str(neko_wait.get("error") or "Neko 未就绪,暂不推流")
|
||||
boot_log.append(f"[relay] neko wait failed: {err}")
|
||||
youtube_relay_db.upsert_relay_state(
|
||||
gid,
|
||||
status="waiting",
|
||||
error=err,
|
||||
recent_log=boot_log[-40:],
|
||||
)
|
||||
return {"ok": True, "waiting": True, "group_id": gid, "note": err, "neko": neko_wait}
|
||||
boot_log.append(
|
||||
f"[relay] neko ready live_studio={bool(neko_wait.get('live_studio'))} "
|
||||
f"timeout={bool(neko_wait.get('timeout'))} note={neko_wait.get('note') or '-'}"
|
||||
)
|
||||
else:
|
||||
boot_log.append(f"[relay] neko-{neko_id} already ready — skip wait")
|
||||
return {"ok": True, "waiting": True, "group_id": gid, "note": err, "neko": neko_wait}
|
||||
boot_log.append(
|
||||
f"[relay] neko Live 页就绪 settled={bool(neko_wait.get('settled'))} "
|
||||
f"settle={neko_wait.get('settle_sec')}s "
|
||||
f"live_status={neko_wait.get('live_status') or '-'} "
|
||||
f"health={neko_wait.get('health') or '-'} "
|
||||
f"url={(neko_wait.get('url') or '-')[:80]}"
|
||||
)
|
||||
|
||||
sess = RelayPushSession(
|
||||
group_id=gid,
|
||||
|
||||
46
backend/tests/test_youtube_neko_live.py
Normal file
46
backend/tests/test_youtube_neko_live.py
Normal file
@ -0,0 +1,46 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
from app import youtube_neko
|
||||
|
||||
|
||||
def _reset_events() -> None:
|
||||
youtube_neko._studio_events.clear() # noqa: SLF001
|
||||
|
||||
|
||||
def test_payload_stream_confirmed_live_status() -> None:
|
||||
assert youtube_neko._payload_stream_confirmed({"live_status": "live"}) is True
|
||||
assert youtube_neko._payload_stream_confirmed({"health": "excellent"}) is True
|
||||
assert youtube_neko._payload_stream_confirmed({"live_status": "waiting"}) is False
|
||||
|
||||
|
||||
def test_latest_live_studio_event_since_ts() -> None:
|
||||
_reset_events()
|
||||
now = time.time()
|
||||
youtube_neko.ingest_studio_telemetry(
|
||||
{
|
||||
"url": "https://studio.youtube.com/channel/abc/livestreaming",
|
||||
"live_status": "waiting",
|
||||
"received_at": now - 10,
|
||||
}
|
||||
)
|
||||
assert youtube_neko.latest_live_studio_event(max_age_sec=60.0, since_ts=now) is None
|
||||
youtube_neko.ingest_studio_telemetry(
|
||||
{
|
||||
"url": "https://studio.youtube.com/channel/abc/livestreaming",
|
||||
"live_status": "live",
|
||||
"received_at": now + 1,
|
||||
}
|
||||
)
|
||||
ev = youtube_neko.latest_live_studio_event(max_age_sec=60.0, since_ts=now)
|
||||
assert ev is not None
|
||||
assert youtube_neko.youtube_live_confirmed(max_age_sec=60.0, since_ts=now)["live"] is True
|
||||
|
||||
|
||||
def test_youtube_live_confirmed_no_event() -> None:
|
||||
_reset_events()
|
||||
out = youtube_neko.youtube_live_confirmed(max_age_sec=30.0)
|
||||
assert out["ok"] is False
|
||||
assert out["live"] is False
|
||||
78
scripts/_deploy_neko_live_wait.py
Normal file
78
scripts/_deploy_neko_live_wait.py
Normal file
@ -0,0 +1,78 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""Deploy Neko Live-page strict wait before FFmpeg."""
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import paramiko
|
||||
|
||||
sys.stdout.reconfigure(encoding="utf-8", errors="replace")
|
||||
|
||||
HOST = "108.174.50.68"
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
APP = "/opt/douyinWEB"
|
||||
|
||||
FILES = [
|
||||
"backend/app/youtube_neko.py",
|
||||
"backend/app/youtube_relay_pipeline.py",
|
||||
]
|
||||
|
||||
REMOTE = """#!/usr/bin/env bash
|
||||
set -euo pipefail
|
||||
systemctl restart douyinweb-api
|
||||
sleep 5
|
||||
systemctl is-active douyinweb-api
|
||||
curl -sS http://127.0.0.1:8014/api/youtube/relay/status | python3 -c "
|
||||
import sys,json
|
||||
d=json.load(sys.stdin)
|
||||
print('slot', d.get('settings',{}).get('youtube_relay_time_slot_mode'))
|
||||
print('studio_live', d.get('studio_live'))
|
||||
for g in d.get('groups',[]):
|
||||
if g.get('is_pushing') or 'Evan' in str(g.get('name','')):
|
||||
print('---', g.get('name'), g.get('business_status'), g.get('status'))
|
||||
rl=g.get('recent_log')
|
||||
if isinstance(rl,list):
|
||||
for line in rl[-5:]:
|
||||
print(' ', line[:180])
|
||||
"
|
||||
echo DONE
|
||||
"""
|
||||
|
||||
|
||||
def main() -> None:
|
||||
c = paramiko.SSHClient()
|
||||
c.set_missing_host_key_policy(paramiko.AutoAddPolicy())
|
||||
c.connect(HOST, 22, "root", "Xiao4669805", timeout=60, allow_agent=False, look_for_keys=False)
|
||||
sftp = c.open_sftp()
|
||||
for rel in FILES:
|
||||
print("upload", rel)
|
||||
sftp.put(str(ROOT / rel), f"{APP}/{rel.replace(chr(92), '/')}")
|
||||
with sftp.file("/tmp/deploy_neko_wait.sh", "w") as f:
|
||||
f.write(REMOTE)
|
||||
sftp.chmod("/tmp/deploy_neko_wait.sh", 0o755)
|
||||
sftp.close()
|
||||
|
||||
chan = c.get_transport().open_session()
|
||||
chan.settimeout(120)
|
||||
chan.exec_command("bash /tmp/deploy_neko_wait.sh")
|
||||
out = b""
|
||||
deadline = time.time() + 110
|
||||
while time.time() < deadline:
|
||||
if chan.recv_ready():
|
||||
out += chan.recv(8192)
|
||||
elif chan.exit_status_ready():
|
||||
while chan.recv_ready():
|
||||
out += chan.recv(8192)
|
||||
break
|
||||
else:
|
||||
time.sleep(0.5)
|
||||
print(out.decode("utf-8", "replace"))
|
||||
if chan.exit_status_ready():
|
||||
print("exit", chan.recv_exit_status())
|
||||
c.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Loading…
Reference in New Issue
Block a user