diff --git a/backend/app/shorts_oauth.py b/backend/app/shorts_oauth.py index 716be3a..ab90a17 100644 --- a/backend/app/shorts_oauth.py +++ b/backend/app/shorts_oauth.py @@ -50,24 +50,52 @@ _oauth_states: dict[str, tuple[str, float, str, str] | tuple[str, float, str, st _OAUTH_STATE_KEY = "shorts_oauth_pending_states" +_OAUTH_STATE_TTL_SEC = 1800.0 # 30min — Google consent + brand pick can be slow + + def _persist_oauth_states() -> None: """Survive API restarts between Google consent and callback.""" now = time.time() - payload: dict[str, list[Any]] = {} + # Merge with DB so another worker's pending states are not wiped. + try: + db._invalidate_settings_cache() + except Exception: + pass + try: + raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {} + except Exception: + raw = {} + merged: dict[str, list[Any]] = {} + if isinstance(raw, dict): + for k, packed in raw.items(): + if not isinstance(packed, (list, tuple)) or len(packed) < 4: + continue + try: + exp = float(packed[1]) + except Exception: + continue + if exp < now: + continue + merged[str(k)] = list(packed) for k, packed in list(_oauth_states.items()): if len(packed) < 2 or float(packed[1]) < now: _oauth_states.pop(k, None) continue - payload[k] = list(packed) + merged[str(k)] = list(packed) + _oauth_states[str(k)] = packed try: - db.update_settings_map({_OAUTH_STATE_KEY: payload}) + db.update_settings_map({_OAUTH_STATE_KEY: merged}) except Exception: pass -def _hydrate_oauth_states() -> None: - if _oauth_states: - return +def _hydrate_oauth_states(*, force: bool = False) -> None: + """Load pending states from DB. Always merge — never skip when memory is non-empty.""" + try: + if force: + db._invalidate_settings_cache() + except Exception: + pass try: raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {} except Exception: @@ -84,8 +112,11 @@ def _hydrate_oauth_states() -> None: continue if exp < now: continue + key = str(k) + if (not force) and key in _oauth_states: + continue if len(packed) >= 5: - _oauth_states[str(k)] = ( + _oauth_states[key] = ( str(packed[0]), exp, str(packed[2]), @@ -93,7 +124,29 @@ def _hydrate_oauth_states() -> None: str(packed[4] or ""), ) else: - _oauth_states[str(k)] = (str(packed[0]), exp, str(packed[2]), str(packed[3])) + _oauth_states[key] = (str(packed[0]), exp, str(packed[2]), str(packed[3])) + + +def _pop_oauth_state(state: str) -> tuple | None: + """Pop state from memory+DB (force hydrate first — fixes multi-worker / restart).""" + st = str(state or "").strip() + if not st: + return None + _hydrate_oauth_states(force=True) + packed = _oauth_states.pop(st, None) + if packed is None: + # One more direct DB peek in case cache raced + try: + db._invalidate_settings_cache() + raw = (_cfg() or {}).get(_OAUTH_STATE_KEY) or {} + if isinstance(raw, dict) and st in raw: + row = raw.get(st) + if isinstance(row, (list, tuple)) and len(row) >= 4: + packed = tuple(row[:5] if len(row) >= 5 else row[:4]) # type: ignore[assignment] + except Exception: + packed = None + _persist_oauth_states() + return packed # type: ignore[return-value] def _stamp_oauth_error(channel_pk: str, err: str) -> None: @@ -120,13 +173,28 @@ def _oauth_log(msg: str) -> None: def _google_http_proxy() -> str: - """Google APIs must egress via ShellCrash on China physical hosts.""" + """Google API egress proxy. + + - Prefer egress_hub (China physical / ShellCrash). + - Else use local clash :7890 only if it accepts connections. + - Else direct (overseas VPS / ytshort). Never force a dead 7890. + """ try: from . import egress_hub - return egress_hub.google_http_proxy() + p = str(egress_hub.google_http_proxy() or "").strip() + if p: + return p except Exception: + pass + try: + import socket + + s = socket.create_connection(("127.0.0.1", 7890), timeout=0.2) + s.close() return "http://127.0.0.1:7890" + except Exception: + return "" def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]: @@ -142,6 +210,38 @@ def _google_client_kwargs(*, timeout: float = 45.0) -> dict[str, Any]: return kw +def _find_shorts_by_youtube_id(yt_id: str) -> dict[str, Any] | None: + yt = str(yt_id or "").strip() + if not yt: + return None + for ch in db.list_shorts_channels(enabled=None) or []: + if str(ch.get("youtube_channel_id") or "").strip() == yt: + return ch + return None + + +def _dedupe_shorts_channel_by_youtube_id(prefer_pk: str, yt_id: str) -> str: + """Warn-only: never delete cards during/after OAuth (operator data loss).""" + yt_id = str(yt_id or "").strip() + prefer_pk = str(prefer_pk or "").strip() + if not yt_id: + return "" + rows = [ + ch + for ch in (db.list_shorts_channels(enabled=None) or []) + if str(ch.get("youtube_channel_id") or "").strip() == yt_id + ] + if len(rows) < 2: + return "" + others = [str(r.get("name") or r.get("id") or "") for r in rows if str(r.get("id") or "") != prefer_pk] + if not others: + return "" + return ( + f"注意:YouTube 频道 {yt_id} 仍挂在多张卡上({', '.join(others[:3])})。" + "未自动删除任何卡片,请手动删掉重复卡。" + ) + + def _cfg() -> dict[str, Any]: return db.get_settings_map() @@ -398,16 +498,21 @@ def build_authorize_url( if ret and (not ret.startswith("/") or ret.startswith("//")): ret = "" now = time.time() - # Drop expired + any prior pending state for this same card (double-click / double-fetch). + # Drop expired + older pending states for this same card (double-click / React remount). for k, packed in list(_oauth_states.items()): - if len(packed) < 2 or packed[1] < now or str(packed[0]) == str(channel_pk): + if len(packed) < 2 or packed[1] < now: + _oauth_states.pop(k, None) + continue + if str(packed[0]) == str(channel_pk): _oauth_states.pop(k, None) state = secrets.token_urlsafe(24) + exp = now + _OAUTH_STATE_TTL_SEC if ret: - _oauth_states[state] = (channel_pk, now + 600, client_id, client_secret, ret) + _oauth_states[state] = (channel_pk, exp, client_id, client_secret, ret) else: - _oauth_states[state] = (channel_pk, now + 600, client_id, client_secret) + _oauth_states[state] = (channel_pk, exp, client_id, client_secret) _persist_oauth_states() + _oauth_log(f"authorize_start pk={channel_pk} state={state[:10]} exp={int(exp)}") scope = authorize_scopes(include_monetary=bool(include_monetary)) params = { "client_id": client_id, @@ -445,21 +550,48 @@ def authorize_scopes(*, include_monetary: bool = False) -> str: FORCE_SSL_SCOPE = "https://www.googleapis.com/auth/youtube.force-ssl" -async def token_scopes(access_token: str) -> set[str]: - """Granted scopes on an access token (tokeninfo).""" +async def token_scopes(access_token: str) -> set[str] | None: + """Granted scopes on an access token (tokeninfo). + + Returns None when egress/network failed — callers must NOT treat that as + 「缺 force-ssl」(empty set used to false-flag OAuth 异常). + """ if not access_token: return set() + last_err = "" try: - async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client: - resp = await client.get( - "https://oauth2.googleapis.com/tokeninfo", - params={"access_token": access_token}, - ) - data = resp.json() if resp.content else {} - raw = str(data.get("scope") or "") - return {s for s in raw.split() if s.strip()} + from . import egress_hub + + proxies = egress_hub.google_http_proxy_candidates() except Exception: - return set() + proxies = [str((_google_http_proxy() or "")).strip()] + if "" not in proxies: + proxies.append("") + for proxy in proxies: + try: + try: + from . import egress_hub + + kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=10.0 if proxy else 20.0) + except Exception: + kw = _google_client_kwargs(timeout=10.0 if proxy else 20.0) + if proxy: + kw = {**kw, "proxy": proxy} + elif "proxy" in kw: + kw = {k: v for k, v in kw.items() if k != "proxy"} + async with httpx.AsyncClient(**kw) as client: + resp = await client.get( + "https://oauth2.googleapis.com/tokeninfo", + params={"access_token": access_token}, + ) + data = resp.json() if resp.content else {} + raw = str(data.get("scope") or "") + return {s for s in raw.split() if s.strip()} + except Exception as exc: + last_err = f"{type(exc).__name__}: {exc}"[:160] + continue + _oauth_log(f"token_scopes_fail {last_err}") + return None def missing_required_scopes(granted: set[str]) -> list[str]: @@ -485,21 +617,17 @@ async def revoke_refresh_token(*, refresh_token: str, client_id: str = "", clien async def prepare_reauthorize(channel_pk: str) -> None: - """Soft-mark OAuth start on the clicked card — never revoke sibling brands.""" + """Mark OAuth start time only — do not stamp oauth_error (that looks like a failure).""" ch = db.get_shorts_channel(channel_pk) or {} if not ch: return - db.update_shorts_channel( - channel_pk, - oauth_checked_at=time.time(), - oauth_error="授权中:完成 Google 后凭证写入本卡片", - ) + # Keep existing oauth_ok / oauth_error so the board does not flash「OAuth 异常」 + # while the operator is mid-consent on Google. + db.update_shorts_channel(channel_pk, oauth_checked_at=time.time()) async def exchange_code(*, code: str, state: str, request_base: str = "") -> dict[str, Any]: - _hydrate_oauth_states() - packed = _oauth_states.pop(state, None) - _persist_oauth_states() + packed = _pop_oauth_state(state) if not packed: _oauth_log(f"state_miss state={state[:12]} mem={len(_oauth_states)}") raise ValueError("授权 state 无效或已过期,请重新点击授权") @@ -509,7 +637,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic return_to = str(packed[4]).strip() if len(packed) >= 5 else "" if return_to and (not return_to.startswith("/") or return_to.startswith("//")): return_to = "" - if exp < time.time(): + if float(exp) < time.time(): _stamp_oauth_error(channel_pk, "授权已过期,请重新点击授权") raise ValueError("授权已过期,请重新点击授权") cfg = _cfg() @@ -535,6 +663,16 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic f"exchange pk={channel_pk} redirect={redirect_uri} " f"secret_tail={client_secret[-4:]} proxy={proxy or 'direct'}" ) + yt_id = "" + yt_title = "" + yt_handle = "" + google_email = "" + access = "" + refresh = "" + expected_uc = str(channel.get("youtube_channel_id") or "").strip() + expected_name = str(channel.get("name") or "").strip() + mismatch_warn = "" + dup_warn = "" try: async with httpx.AsyncClient(**_google_client_kwargs(timeout=60.0)) as client: token_resp = await client.post( @@ -588,7 +726,7 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic _stamp_oauth_error(channel_pk, err) raise ValueError(err) items = ch_data.get("items") or [] - # Prefer the brand that already matches this card's UC (multi-brand Google logins). + # Card name ≠ brand title. Prefer UC match in token list; else authorized brand (items[0]). expected_uc = str(channel.get("youtube_channel_id") or "").strip() expected_name = str(channel.get("name") or "").strip() chosen: dict[str, Any] | None = None @@ -617,66 +755,16 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic _stamp_oauth_error(channel_pk, err) raise ValueError(err) - # Hard lock: re-auth must not rewrite this card into another brand. - # (Previously we overwrote youtube_channel_id + name → duplicate 「nomad Street Food」.) - if expected_uc and yt_id != expected_uc: - err = ( - f"授权选中的 YouTube 频道是「{yt_title or yt_id}」({yt_id})," - f"但本卡绑定的是「{expected_name or expected_uc}」({expected_uc})。" - "凭证未写入。请重新点授权,在 Google 账号/品牌列表里选对本卡的频道。" - ) - _stamp_oauth_error(channel_pk, err) - # Best-effort revoke the wrong-brand grant so it does not linger. - try: - async with httpx.AsyncClient(**_google_client_kwargs(timeout=15.0)) as client: - await client.post( - "https://oauth2.googleapis.com/revoke", - data={"token": access}, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - ) - if refresh: - await client.post( - "https://oauth2.googleapis.com/revoke", - data={"token": refresh}, - headers={"Content-Type": "application/x-www-form-urlencoded"}, - ) - except Exception: - pass - raise ValueError(err) - google_email = await fetch_google_account_email(access) - # Soft-warn if the same YouTube channel is already bound to another Shorts card. - dup_warn = "" - if yt_id: - try: - for other in db.list_shorts_channels(enabled=None): - oid = str(other.get("id") or "") - if oid == channel_pk: - continue - if str(other.get("youtube_channel_id") or "").strip() == yt_id: - dup_warn = ( - f"注意:YouTube 频道 {yt_id} 已挂在另一张卡 " - f"「{other.get('name') or oid}」。两张卡会共用同一频道身份,建议删掉重复卡。" - ) - try: - db.add_event( - kind="ops", - level="warn", - message=dup_warn, - meta={"channel_pk": channel_pk, "dup_channel_pk": oid, "youtube_channel_id": yt_id}, - ) - except Exception: - pass - break - except Exception: - pass + # Resolve target card by authorized brand UC: + # exist → update that card; missing → create new card. + # Never delete the clicked card. Never wipe unrelated cards. had_old = bool(str(channel.get("refresh_token") or "").strip()) if not refresh: if had_old: refresh = str(channel.get("refresh_token") or "").strip() else: - # Revoke this access so the next consent can mint a refresh_token. try: async with httpx.AsyncClient(**_google_client_kwargs(timeout=20.0)) as client: await client.post( @@ -694,28 +782,133 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic _stamp_oauth_error(channel_pk, err) raise ValueError(err) + click_pk = str(channel_pk) + click_name = str(channel.get("name") or click_pk) + existing = _find_shorts_by_youtube_id(yt_id) if yt_id else None + target_pk = click_pk + resolve_note = "" + created_new = False + removed_stub = False + + def _is_empty_stub(ch: dict[str, Any]) -> bool: + return ( + not str(ch.get("youtube_channel_id") or "").strip() + and not str(ch.get("refresh_token") or "").strip() + ) + + if existing and str(existing.get("id") or "") != click_pk: + target_pk = str(existing.get("id") or click_pk) + resolve_note = ( + f"选中品牌「{yt_title or yt_id}」已有卡片「{existing.get('name') or target_pk}」," + f"凭证已写入该卡。" + ) + elif existing: + target_pk = str(existing.get("id") or click_pk) + resolve_note = "" + elif expected_uc and expected_uc != yt_id: + # Clicked card bound to another UC; brand is new → create. + try: + created = db.create_shorts_channel( + name=(yt_title or "Shorts Channel").strip() or "Shorts Channel", + youtube_channel_id=yt_id, + oauth_profile_id=profile_id or str(channel.get("oauth_profile_id") or ""), + enabled=True, + ) + target_pk = str(created.get("id") or "") + created_new = True + resolve_note = ( + f"选中品牌「{yt_title or yt_id}」原先没有卡片,已新建;" + f"你点的「{click_name}」保持原样。" + ) + except ValueError as exc: + again = _find_shorts_by_youtube_id(yt_id) + if again: + target_pk = str(again.get("id") or click_pk) + resolve_note = ( + f"选中品牌「{yt_title or yt_id}」已有卡片「{again.get('name') or target_pk}」," + f"凭证已写入该卡({exc})。" + ) + else: + raise + else: + # Clicked card empty UC or same UC → update clicked card in place. + target_pk = click_pk + if expected_uc and expected_uc != yt_id: + resolve_note = ( + f"选中品牌「{yt_title or yt_id}」与原绑定不同,已更新本卡 UC" + "(卡片显示名不改成品牌名)。" + ) + + # Empty stub (no UC / no token) used only as authorize entry → remove after + # credentials land on the real brand card. Never delete cards that already have UC/tokens. + if target_pk != click_pk and _is_empty_stub(channel): + try: + db.delete_shorts_channel(click_pk) + removed_stub = True + resolve_note = ( + f"{resolve_note} 已自动移除空壳卡「{click_name}」。".strip() + ) + _oauth_log(f"removed_empty_stub click={click_pk} target={target_pk}") + except Exception as exc: + _oauth_log(f"remove_stub_fail click={click_pk} err={exc!r}") + try: + db.update_shorts_channel( + click_pk, + enabled=False, + oauth_ok=0, + oauth_error=f"空壳卡:授权已写入「{(existing or {}).get('name') or target_pk}」,可手动删除", + ) + except Exception: + pass + elif target_pk != click_pk: + # Real card clicked but brand bound elsewhere — clear stuck「授权中」. + try: + db.update_shorts_channel( + click_pk, + oauth_ok=0, + oauth_checked_at=time.time(), + oauth_error=( + f"本次授权写入了「{(db.get_shorts_channel(target_pk) or existing or {}).get('name') or target_pk}」," + f"本卡「{click_name}」未改动。" + )[:500], + ) + except Exception: + pass + patch: dict[str, Any] = { "client_id": client_id, "client_secret": client_secret, "refresh_token": refresh, + "youtube_channel_id": yt_id, } - # Only set UC when card had none; never swap to a different UC (guarded above). - if yt_id and not expected_uc: - patch["youtube_channel_id"] = yt_id if google_email: patch["oauth_email"] = google_email - # Keep operator card title on reauth — never auto-rename into another brand's title. - if yt_title and not expected_name: - patch["name"] = yt_title - if profile_id and not str(channel.get("oauth_profile_id") or "").strip(): + if profile_id: patch["oauth_profile_id"] = profile_id + # Never rename operator card into brand title on update — except empty / 未命名 stubs. + target_row = db.get_shorts_channel(target_pk) or {} + cur_name = str(target_row.get("name") or "").strip() + if (not created_new) and yt_title and ( + not cur_name or cur_name in ("未命名频道", "Shorts Channel", "Shorts") + ): + patch["name"] = yt_title + elif created_new and yt_title: + pass # create already named + + # Success card: keep oauth_error clean (info goes to warning toast, not 「OAuth 异常」). updated = db.update_shorts_channel( - channel_pk, + target_pk, **patch, oauth_ok=1, oauth_checked_at=time.time(), oauth_error="", ) + dup_warn = _dedupe_shorts_channel_by_youtube_id(target_pk, yt_id) if yt_id else "" + mismatch_warn = resolve_note + brand_mismatch = bool(resolve_note) and ( + created_new or (existing is not None and str(existing.get("id") or "") != click_pk) + ) + if google_email and profile_id: try: set_oauth_profile_email(profile_id, google_email) @@ -732,22 +925,29 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic try: from . import youtube_manage as ytm - await ytm.fetch_channel_profile(channel_pk) + await ytm.fetch_channel_profile(target_pk) except Exception as exc: profile_err = str(exc).strip() or "拉取频道资料失败" try: from .yt_long_monetize import refresh_ypp_for_shorts_channel - ypp_r = await refresh_ypp_for_shorts_channel(channel_pk) + ypp_r = await refresh_ypp_for_shorts_channel(target_pk) if not ypp_r.get("ok"): ypp_err = str(ypp_r.get("error") or "YPP 探测失败")[:200] except Exception as exc: ypp_err = str(exc).strip() or "YPP 探测失败" note = " · ".join(x for x in (profile_err, ypp_err) if x) if note: - db.update_shorts_channel(channel_pk, oauth_error=note) - updated = db.get_shorts_channel(channel_pk) or updated - _oauth_log(f"exchange_ok pk={channel_pk} yt={yt_id} title={yt_title} profile_err={profile_err!r} ypp_err={ypp_err!r}") + try: + db.update_shorts_channel(target_pk, oauth_error=note[:500]) + updated = db.get_shorts_channel(target_pk) or updated + except Exception: + pass + _oauth_log( + f"exchange_ok click={click_pk} target={target_pk} created={created_new} " + f"removed_stub={removed_stub} yt={yt_id} title={yt_title} note={resolve_note!r}" + ) + warn_out = " · ".join(x for x in (mismatch_warn, dup_warn) if x) return { "ok": True, "channel": updated, @@ -762,7 +962,11 @@ async def exchange_code(*, code: str, state: str, request_base: str = "") -> dic "ypp_ok": not bool(ypp_err), "profile_error": profile_err, "ypp_error": ypp_err, - "duplicate_channel_warning": dup_warn, + "brand_mismatch": brand_mismatch, + "created_channel": created_new, + "removed_empty_stub": removed_stub, + "target_channel_pk": target_pk, + "duplicate_channel_warning": warn_out, "return_to": return_to, } except ValueError: @@ -786,11 +990,12 @@ def channel_oauth_creds(channel: dict[str, Any], cfg: dict[str, Any] | None = No async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | None = None) -> dict[str, Any]: """Try refresh_token once; persist oauth_ok / oauth_error on the channel.""" - from .shorts_upload import refresh_access_token + from .shorts_upload import is_transient_oauth_error_message, refresh_access_token creds = channel_oauth_creds(channel, cfg) cid = str(channel.get("id") or "") now = time.time() + prev_ok = int(channel.get("oauth_ok") if channel.get("oauth_ok") is not None else -1) if not cid: return {"ok": False, "error": "频道 ID 缺失"} if not (creds["refresh_token"] and creds["client_id"] and creds["client_secret"]): @@ -807,7 +1012,13 @@ async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | Non client_secret=creds["client_secret"], refresh_token=creds["refresh_token"], ) - missing = missing_required_scopes(await token_scopes(str(access))) + granted = await token_scopes(str(access)) + if granted is None: + # Token refresh succeeded; scope check egress failed — do not false-flag. + err = "OAuth 出口不稳定:令牌可用但权限校验超时,请稍后重试或检查住宅代理" + db.update_shorts_channel(cid, oauth_ok=1, oauth_checked_at=now, oauth_error=err) + return {"ok": True, "channel_id": cid, "warning": err, "scopes_unchecked": True} + missing = missing_required_scopes(granted) if missing: err = "OAuth 权限不足(缺 force-ssl),请点「重授权」升级 YPP 获利权限" db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err) @@ -825,7 +1036,22 @@ async def probe_channel_oauth(channel: dict[str, Any], cfg: dict[str, Any] | Non db.update_shorts_channel(cid, **patch) return {"ok": True, "channel_id": cid, "oauth_email": google_email} except Exception as exc: - err = str(exc)[:240] + err = str(exc).strip()[:240] or f"{type(exc).__name__}: OAuth 探测失败" + # Transient egress noise must NOT flip a previously-good token to oauth_ok=0 + # (UI sticky 「OAuth 异常」 while refresh_token is still valid). + if is_transient_oauth_error_message(err): + keep_ok = 1 if prev_ok == 1 else prev_ok + if keep_ok == 1: + db.update_shorts_channel( + cid, + oauth_ok=1, + oauth_checked_at=now, + oauth_error=f"探测暂失败(令牌未判定失效): {err}"[:500], + ) + return {"ok": True, "channel_id": cid, "warning": err, "transient": True} + # Never authorized / unknown: record soft error without hard fail banner pressure. + db.update_shorts_channel(cid, oauth_checked_at=now, oauth_error=err) + return {"ok": False, "error": err, "channel_id": cid, "transient": True} db.update_shorts_channel(cid, oauth_ok=0, oauth_checked_at=now, oauth_error=err) return {"ok": False, "error": err, "channel_id": cid} diff --git a/backend/app/shorts_pipeline.py b/backend/app/shorts_pipeline.py index 9d9aa8a..7b974bb 100644 --- a/backend/app/shorts_pipeline.py +++ b/backend/app/shorts_pipeline.py @@ -18,6 +18,7 @@ from __future__ import annotations import asyncio import random +import threading import time from typing import Any, Optional @@ -124,7 +125,7 @@ def _try_rebind_shorts_job_to_live(job: dict[str, Any], cfg: dict[str, Any] | No clip_path="", clip_seconds=0, clip_offset_sec=offset, - error="原直播间已停播,已换源重录", + error="rebind:1 原直播间已停播,已换源重录", finished_at=0, upload_at=0, youtube_video_id="", @@ -195,7 +196,7 @@ def _enqueue_job( channel: dict[str, Any] | None = None if channel_pk: ch = db.get_shorts_channel(channel_pk) - if ch and ch.get("enabled"): + if ch and ch.get("enabled") and db.shorts_channel_oauth_ready(ch): used = db.shorts_channel_upload_count(channel_pk, day) uploaded = db.shorts_channel_uploaded_count(channel_pk, day) daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) @@ -208,10 +209,9 @@ def _enqueue_job( channel = db.pick_shorts_channel(day, settings, require_upload_quota=require_upload_quota) if require_channel and not channel: return None - # Same channel + same room today → skip (create_shorts_job also enforces). + # Same channel + same room today is OK when clip offsets differ (create_shorts_job + # dedupes on room+channel+offset). Only hard-skip when global room-day lock is on. ch_id = str((channel or {}).get("id") or "") - if room_id and ch_id and not dedupe_global and db.has_shorts_job_for_room_day(room_id, day, ch_id): - return None clip_sec = int(settings.get("shorts_clip_sec") or 15) try: clip_sec = db.room_clip_seconds(room, default=clip_sec, platform="shorts") @@ -275,15 +275,24 @@ def try_enqueue_on_live( def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: """Pick currently-live rooms and enqueue. Same room may feed multiple channels - with distinct clip offsets unless shorts_dedupe_room_day is on.""" + with distinct clip offsets unless shorts_dedupe_room_day is on. + + Recording does **not** require YouTube Data API upload quota — only the upload + worker respects profile blocks. Otherwise a Gmail quota burn stops 待录 forever + while 缺 N stays high. + """ try: settings = cfg or db.get_settings_map() if not settings.get("shorts_enabled"): return 0 if not settings.get("shorts_live_sample", True): return 0 + # Uploads frozen → do not keep enqueueing samples into scheduled. + if ShortsPipeline._all_channel_profiles_upload_blocked(settings): + return 0 day = push_date_from_ts(time.time()) - if not db.pick_shorts_channel(day, settings): + # Pipeline room left (pending→done), ignore upload API self-blocks. + if not db.pick_shorts_channel(day, settings, require_upload_quota=False): return 0 batch = max(1, min(int(settings.get("shorts_live_sample_batch") or 1), 5)) any_live = settings.get("shorts_sample_any_live", True) @@ -317,12 +326,18 @@ def try_sample_live_rooms(cfg: dict[str, Any] | None = None) -> int: break sid = str(room.get("active_session_id") or "") session = db.get_session(sid) if sid else None - job = _enqueue_job(session=session, room=room, stream_url="", cfg=settings) + job = _enqueue_job( + session=session, + room=room, + stream_url="", + cfg=settings, + require_upload_quota=False, + ) if job: enqueued += 1 if dedupe_global: used.add(str(room.get("room_id") or "")) - if not db.pick_shorts_channel(day, settings): + if not db.pick_shorts_channel(day, settings, require_upload_quota=False): break return enqueued except Exception: @@ -391,6 +406,9 @@ def sample_live_now(cfg: dict[str, Any] | None = None) -> dict[str, Any]: } +_quota_fill_lock = threading.Lock() + + def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: """Enqueue live-room clips toward daily_min first, then daily_max (Beijing day). @@ -398,11 +416,15 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: (0–15s / 15–30s / …) so materials are never identical. Prefer rooms with fewer jobs today for diversity. When behind daily_min, raise batch size. """ + # Non-blocking: overlapping fills (52s+ previously) pegged a whole core forever. + if not _quota_fill_lock.acquire(blocking=False): + return 0 try: settings = cfg or db.get_settings_map() if not settings.get("shorts_enabled"): return 0 - if not any_profile_uploads_available(settings): + # All OAuth Clients cool-down → stop stuffing pipeline (disk / CPU waste). + if ShortsPipeline._all_channel_profiles_upload_blocked(settings): return 0 day = push_date_from_ts(time.time()) summary = db.shorts_channels_quota_summary(day) @@ -410,7 +432,7 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: need_any = [r for r in summary if int(r.get("gap") or 0) > 0] if not need_any: return 0 - if not db.pick_shorts_channel(day, settings): + if not db.pick_shorts_channel(day, settings, require_upload_quota=False): return 0 from .timeutil import beijing_day_bounds @@ -421,20 +443,34 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: gap_total = sum(int(r.get("gap") or 0) for r in need_any) min_gap = sum(max(0, int(r.get("daily_min") or 0) - int(r.get("used") or 0)) for r in under_min) - base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 9)) + # Hard cap — large batches + N×DB in the loop previously burned 50s+/tick. + base_batch = max(1, min(int(settings.get("shorts_quota_fill_batch") or 3), 6)) if under_min: - base_batch = max(base_batch, min(max(min_gap, len(under_min)), 12)) - if day_progress > 0.45 and under_min: - base_batch = max(base_batch, min(gap_total, max(8, min_gap))) - if day_progress > 0.7: - base_batch = max(base_batch, min(gap_total, 14)) - if day_progress > 0.85 or (day_progress > 0.6 and under_min): - base_batch = max(base_batch, min(gap_total, 20)) + base_batch = max(base_batch, min(len(under_min), 6)) + if day_progress > 0.7 and under_min: + base_batch = max(base_batch, min(8, gap_total, max(min_gap, 1))) + base_batch = min(base_batch, 8) + + # Backlog gate: don't keep stuffing when workers are already behind. + try: + st = db.shorts_stats(day) or {} + by = st.get("by_status") or st.get("status") or {} + if isinstance(by, dict): + backlog = int(by.get("pending") or 0) + int(by.get("recording") or 0) + else: + backlog = 0 + except Exception: + backlog = 0 + # Hard stop so fill never outruns recorders (was flooding 30+ pending). + backlog_cap = 12 + if backlog >= backlog_cap: + return 0 + base_batch = min(base_batch, max(1, backlog_cap - backlog)) any_live = settings.get("shorts_sample_any_live", True) dedupe_global = bool(settings.get("shorts_dedupe_room_day", False)) used_rooms = db.room_ids_with_shorts_job_today(day) if dedupe_global else set() - rooms = db.list_live_douyin_rooms_for_shorts(limit=400) + rooms = db.list_live_douyin_rooms_for_shorts(limit=80) candidates: list[dict[str, Any]] = [] for room in rooms: rid = str(room.get("room_id") or "") @@ -446,11 +482,12 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: candidates.append(room) if not candidates: return 0 - # Prefer less-used rooms first, then shuffle within similar load. + + rooms_with_job = used_rooms if dedupe_global else db.room_ids_with_shorts_job_today(day) if not dedupe_global: candidates.sort( key=lambda r: ( - 1 if db.has_shorts_job_for_room_day(str(r.get("room_id") or ""), day) else 0, + 1 if str(r.get("room_id") or "") in rooms_with_job else 0, random.random(), ) ) @@ -463,14 +500,22 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: if not target_ids: return 0 + # Prefetch — avoid per-attempt get_channel / count / has_job queries. + channels = { + str(c.get("id") or ""): c + for c in (db.list_shorts_channels(enabled=True) or []) + if str(c.get("id") or "") + } + pipeline_by = {str(r["id"]): int(r.get("pipeline") or 0) for r in summary} + uploaded_by = {str(r["id"]): int(r.get("uploaded") or 0) for r in summary} + max_by = {str(r["id"]): int(r.get("daily_max") or SHORTS_DAILY_FORCE) for r in summary} + occupied = db.shorts_job_room_channel_pairs_today(day) + enqueued = 0 ti = 0 - # Allow cycling the same live rooms across channels (distinct offsets). room_cycle = list(candidates) - if not room_cycle: - return 0 attempts = 0 - max_attempts = max(base_batch * 4, len(target_ids) * 2) + max_attempts = max(base_batch * 2, len(target_ids)) while enqueued < base_batch and attempts < max_attempts: attempts += 1 room = room_cycle[(attempts - 1) % len(room_cycle)] @@ -479,19 +524,15 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: for _ in range(len(target_ids)): tid = target_ids[ti % len(target_ids)] ti += 1 - ch = db.get_shorts_channel(tid) + ch = channels.get(tid) if not ch or not ch.get("enabled"): continue - used = db.shorts_channel_upload_count(tid, day) - uploaded = db.shorts_channel_uploaded_count(tid, day) - daily_max = _normalize_daily_quota(ch.get("daily_max"), default=SHORTS_DAILY_FORCE) - if used >= daily_max or uploaded >= daily_max: + daily_max = max_by.get(tid, SHORTS_DAILY_FORCE) + if pipeline_by.get(tid, 0) >= daily_max or uploaded_by.get(tid, 0) >= daily_max: continue - if rid and db.has_shorts_job_for_room_day(rid, day, tid): + if rid and (rid, tid) in occupied: continue - from .shorts_yt_quota import profile_id_for_channel, project_uploads_available - - if not project_uploads_available(settings, profile_id=profile_id_for_channel(ch)): + if dedupe_global and rid in used_rooms: continue sid = str(room.get("active_session_id") or "") session = db.get_session(sid) if sid else None @@ -501,19 +542,26 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int: stream_url="", cfg=settings, channel_pk=tid, + require_upload_quota=False, ) if job: enqueued += 1 - if dedupe_global: + occupied.add((rid, tid)) + pipeline_by[tid] = int(pipeline_by.get(tid, 0)) + 1 + if dedupe_global and rid: used_rooms.add(rid) assigned = True break if not assigned and dedupe_global: - # Exhausted unique rooms under legacy mode. continue return enqueued except Exception: return 0 + finally: + try: + _quota_fill_lock.release() + except Exception: + pass class ShortsPipeline: @@ -529,6 +577,15 @@ class ShortsPipeline: self._last_quota_alert_at = 0.0 self._last_oauth_check_at = 0.0 self._last_auto_retry_at = 0.0 + self._last_housekeep_at = 0.0 + self._upload_max_cached_at = 0.0 + self._upload_max_cached_val = 2 + self._record_max_cached_at = 0.0 + self._record_max_cached_val = 1 + self._catchup_cached_at = 0.0 + self._catchup_cached_val = False + self._under_min_cached_at = 0.0 + self._under_min_cached_val = False self.last_error = "" self.processed = 0 self.sampled = 0 @@ -689,24 +746,88 @@ class ShortsPipeline: except Exception: return False + def _catchup_cached(self, cfg: dict[str, Any]) -> bool: + """Return last housekeep-computed catchup flag — never recompute on hot path.""" + if self._catchup_cached_at <= 0: + return False + return bool(self._catchup_cached_val) + @staticmethod - def _upload_max(cfg: dict[str, Any]) -> int: + def _all_channel_profiles_upload_blocked(cfg: dict[str, Any] | None = None) -> bool: + """True when every enabled channel's OAuth profile is in YouTube upload cool-down. + + Recording into scheduled while uploads are frozen fills disk; pause fill/record then. + """ + try: + settings = cfg or db.get_settings_map() + blocked = blocked_profile_ids(settings) + if not blocked: + return False + chs = db.list_shorts_channels(enabled=True) or [] + if not chs: + return False + for ch in chs: + if not db.shorts_channel_oauth_ready(ch): + continue + pid = profile_id_for_channel(ch) + if pid not in blocked: + return False + # At least one oauth-ready channel exists and all such are blocked. + return any(db.shorts_channel_oauth_ready(ch) for ch in chs) + except Exception: + return False + + @staticmethod + def _upload_max(cfg: dict[str, Any], *, catchup: bool | None = None) -> int: explicit = int(cfg.get("shorts_upload_max_concurrent") or 0) if explicit > 0: base = max(1, min(explicit, 5)) else: base = max(2, int(cfg.get("shorts_max_concurrent") or 1)) - if ShortsPipeline._end_of_day_catchup(cfg): + if catchup is None: + catchup = ShortsPipeline._end_of_day_catchup(cfg) + if catchup: return min(5, max(base, 4)) return base + def _upload_max_cached(self, cfg: dict[str, Any]) -> int: + """Never call fleet_pace_plan here — housekeep refreshes the cache in a thread.""" + now = time.time() + if now - self._upload_max_cached_at < 45.0 and self._upload_max_cached_at > 0: + return max(1, int(self._upload_max_cached_val)) + explicit = int(cfg.get("shorts_upload_max_concurrent") or 0) + if explicit > 0: + base = max(1, min(explicit, 5)) + else: + base = max(2, int(cfg.get("shorts_max_concurrent") or 1)) + if self._catchup_cached(cfg): + base = min(5, max(base, 4)) + self._upload_max_cached_val = base + self._upload_max_cached_at = now + return max(1, base) + @staticmethod - def _record_max(cfg: dict[str, Any]) -> int: + def _record_max(cfg: dict[str, Any], *, catchup: bool | None = None) -> int: base = max(1, int(cfg.get("shorts_max_concurrent") or 1)) - if ShortsPipeline._end_of_day_catchup(cfg): - return min(8, max(base, 5)) + if catchup is None: + catchup = ShortsPipeline._end_of_day_catchup(cfg) + if catchup: + # Cap hard — 5 parallel resolve/record pegs a small VPS. + return min(2, max(base, 2)) return base + def _record_max_cached(self, cfg: dict[str, Any]) -> int: + """Never call fleet_pace_plan here — housekeep refreshes the cache in a thread.""" + now = time.time() + if now - self._record_max_cached_at < 45.0 and self._record_max_cached_at > 0: + return max(1, int(self._record_max_cached_val)) + base = max(1, int(cfg.get("shorts_max_concurrent") or 1)) + if self._catchup_cached(cfg): + base = min(2, max(base, 2)) + self._record_max_cached_val = base + self._record_max_cached_at = now + return max(1, base) + def status(self) -> dict[str, Any]: now = time.time() cached = getattr(self, "_status_cache", None) @@ -743,11 +864,15 @@ class ShortsPipeline: board = {} oauth_issues = [] try: + from .shorts_upload import is_transient_oauth_error_message + for ch in db.list_shorts_channels(enabled=True): ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1) err = str(ch.get("oauth_error") or "") has_rt = bool(str(ch.get("refresh_token") or "").strip()) - if has_rt and "重授权中" in err: + if "授权中" in err: + continue + if has_rt and ok_flag == 0 and is_transient_oauth_error_message(err): continue if not has_rt or ok_flag == 0: oauth_issues.append( @@ -771,6 +896,7 @@ class ShortsPipeline: try: from . import douyin_live + # Prefer warm cache; never force a full rebuild on UI poll. live_count = int(douyin_live.build_live_map().get("live_count") or 0) except Exception: live_count = 0 @@ -818,6 +944,7 @@ class ShortsPipeline: "yt_upload_used": yt_used, "yt_upload_remaining": yt_remaining, "yt_quota_by_profile": yt_by_profile, + "reauth_needed": list(cfg.get("shorts_reauth_needed") or [])[:20], "last_error": last_error, "clip_sec": int(cfg.get("shorts_clip_sec") or 15), "live_sample": bool(cfg.get("shorts_live_sample", True)), @@ -828,7 +955,7 @@ class ShortsPipeline: "upload_min_gap_sec": float(cfg.get("shorts_upload_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC), "channel_min_gap_sec": float(cfg.get("shorts_channel_min_gap_sec") or CHANNEL_GAP_FLOOR_SEC), "max_concurrent": max(1, int(cfg.get("shorts_max_concurrent") or 1)), - "upload_max_concurrent": self._upload_max(cfg), + "upload_max_concurrent": self._upload_max_cached(cfg), "delete_clip_after_upload": bool(cfg.get("shorts_delete_clip_after_upload", True)), "stats": stats, "board": board, @@ -871,11 +998,15 @@ class ShortsPipeline: stats = {} oauth_issues = [] try: + from .shorts_upload import is_transient_oauth_error_message + for ch in db.list_shorts_channels(enabled=True): ok_flag = int(ch.get("oauth_ok") if ch.get("oauth_ok") is not None else -1) err = str(ch.get("oauth_error") or "") has_rt = bool(str(ch.get("refresh_token") or "").strip()) - if has_rt and "重授权中" in err: + if "授权中" in err: + continue + if has_rt and ok_flag == 0 and is_transient_oauth_error_message(err): continue if not has_rt or ok_flag == 0: oauth_issues.append( @@ -890,9 +1021,7 @@ class ShortsPipeline: except Exception: pass try: - from . import douyin_live - - live_count = int(douyin_live.build_live_map().get("live_count") or 0) + live_count = len(db.list_live_douyin_rooms_for_shorts(limit=50) or []) except Exception: live_count = 0 yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A") @@ -922,6 +1051,7 @@ class ShortsPipeline: "yt_upload_used": yt_used, "yt_upload_remaining": yt_remaining, "yt_quota_by_profile": yt_by_profile, + "reauth_needed": list(cfg.get("shorts_reauth_needed") or [])[:20], "last_error": self.last_error, "douyin_live_count": live_count, "stats": stats, @@ -947,8 +1077,12 @@ class ShortsPipeline: clear_stale_quota_errors_for_open_profiles() db.purge_orphan_shorts_jobs(limit=500) db.dedupe_shorts_jobs_room_day() + # Restart leaves DB rows in `recording` with no owner — requeue before loop. + db.reset_orphan_shorts_recordings() except Exception: pass + self._active_records = 0 + self._active_uploads = 0 self._stop.clear() self._task = asyncio.create_task(self._loop(), name="shorts-pipeline") @@ -986,13 +1120,15 @@ class ShortsPipeline: async def _loop(self) -> None: while not self._stop.is_set(): try: - cfg = db.get_settings_map() + # Never touch SQLite on the asyncio thread — workers holding db._lock + # would freeze /api/health and look like a full site outage. + cfg = await asyncio.to_thread(db.get_settings_map) if not cfg.get("shorts_enabled"): await asyncio.sleep(5) continue try: - db.enforce_shorts_daily_force() + await asyncio.to_thread(db.enforce_shorts_daily_force) except Exception: pass @@ -1001,34 +1137,41 @@ class ShortsPipeline: interval = max(60.0, interval) if cfg.get("shorts_live_sample", True) and (time.time() - self._last_sample_at) >= interval: self._last_sample_at = time.time() - n = try_sample_live_rooms(cfg) + n = await asyncio.to_thread(try_sample_live_rooms, cfg) if n: self.sampled += n quota_interval = float(cfg.get("shorts_quota_fill_interval_sec") or 120) quota_interval = max(60.0, quota_interval) try: - day_now = push_date_from_ts(time.time()) - under = [r for r in db.shorts_channels_quota_summary(day_now) if not r.get("min_met")] - if under: - # Behind daily_min: fill more often so Beijing-day minimum is reachable. - quota_interval = min(quota_interval, 60.0) + # Cache under-min probe — full quota summary every tick burned a core. + now_ts = time.time() + if now_ts - self._under_min_cached_at >= 30.0: + day_now = push_date_from_ts(now_ts) + summary_now = await asyncio.to_thread(db.shorts_channels_quota_summary, day_now) + self._under_min_cached_val = any(not r.get("min_met") for r in summary_now) + self._under_min_cached_at = now_ts + if self._under_min_cached_val: + # Behind daily_min: fill a bit more often, but never sub-minute (CPU thrash). + quota_interval = min(quota_interval, 90.0) from .timeutil import beijing_day_bounds + day_now = push_date_from_ts(now_ts) ds, de = beijing_day_bounds(day_now) - prog = max(0.0, min(1.0, (time.time() - ds) / max(1.0, de - ds))) + prog = max(0.0, min(1.0, (now_ts - ds) / max(1.0, de - ds))) if prog > 0.7: - quota_interval = 45.0 + quota_interval = 75.0 except Exception: pass if (time.time() - self._last_quota_fill_at) >= quota_interval: self._last_quota_fill_at = time.time() - qn = try_fill_daily_quota(cfg) + # Heavy SQLite + room scans must not block asyncio (API health / UI). + qn = await asyncio.to_thread(try_fill_daily_quota, cfg) if qn: self.quota_filled += qn try: - self._maybe_alert_quota_behind(cfg) + await asyncio.to_thread(self._maybe_alert_quota_behind, cfg) except Exception: pass @@ -1042,73 +1185,97 @@ class ShortsPipeline: if cfg.get("shorts_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval: self._last_auto_retry_at = time.time() try: - n = self._auto_retry_failed(cfg) + n = await asyncio.to_thread(self._auto_retry_failed, cfg) if n: self.auto_retried += n except Exception: pass # Legacy recorded clips without upload_at → schedule irregularly - try: - self._backfill_schedules(cfg) - except Exception: - pass - try: - from .shorts_schedule import pull_forward_due_uploads + # Heavy SQLite housekeep must not run on the asyncio thread every tick. + if (time.time() - self._last_housekeep_at) >= 45.0: + self._last_housekeep_at = time.time() - if pull_forward_due_uploads(cfg): - pass - except Exception: - pass - try: - skip_or_rebind_offline_pending(cfg, limit=60) - except Exception: - pass + def _housekeep() -> None: + try: + self._backfill_schedules(cfg) + except Exception: + pass + try: + from .shorts_schedule import pull_forward_due_uploads - try: - n = db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0) - if n: - self.last_error = "" - except Exception: - pass + pull_forward_due_uploads(cfg) + except Exception: + pass + try: + skip_or_rebind_offline_pending(cfg, limit=40) + except Exception: + pass + try: + db.reclaim_stale_shorts_uploads(max_age_sec=900, retry_at=0.0) + except Exception: + pass + try: + db.reclaim_stale_shorts_recordings(max_age_sec=180) + except Exception: + pass + try: + db.reconcile_missing_shorts_clips(limit=40) + except Exception: + pass + try: + db.reconcile_false_failed_shorts(limit=40) + except Exception: + pass + try: + catchup = bool(self._end_of_day_catchup(cfg)) + self._catchup_cached_val = catchup + self._catchup_cached_at = time.time() + self._upload_max_cached_val = int(self._upload_max(cfg, catchup=catchup)) + self._upload_max_cached_at = time.time() + self._record_max_cached_val = int(self._record_max(cfg, catchup=catchup)) + self._record_max_cached_at = time.time() + except Exception: + pass - try: - missing = db.reconcile_missing_shorts_clips(limit=80) - if missing: - self.last_error = "" - except Exception: - pass + await asyncio.to_thread(_housekeep) + record_max = self._record_max_cached(cfg) + upload_max = self._upload_max_cached(cfg) + uploads_frozen = False try: - healed = db.reconcile_false_failed_shorts(limit=80) - if healed: - self.last_error = "" + uploads_frozen = await asyncio.to_thread( + self._all_channel_profiles_upload_blocked, cfg + ) except Exception: - pass - - record_max = self._record_max(cfg) - upload_max = self._upload_max(cfg) + uploads_frozen = False job: dict[str, Any] | None = None runner: str = "" if self._active_uploads < upload_max: # Skip Clients in YouTube-API cool-down (manual upload still allowed). - skip = blocked_profile_ids(cfg) - job = db.claim_due_shorts_upload(skip_profile_ids=skip or None) + skip = await asyncio.to_thread(blocked_profile_ids, cfg) + job = await asyncio.to_thread( + db.claim_due_shorts_upload, skip_profile_ids=skip or None + ) if job: runner = "upload" - if not job and self._active_records < record_max: + # All Clients cool-down → stop filming into scheduled (disk fill). + if not job and not uploads_frozen and self._active_records < record_max: try: from .host_metrics import clip_encode_defer_reason - defer_rec = clip_encode_defer_reason() + defer_rec = await asyncio.to_thread(clip_encode_defer_reason) except Exception: defer_rec = "" if not defer_rec: - job = db.claim_pending_shorts_record() + job = await asyncio.to_thread( + db.claim_pending_shorts_record, max_concurrent=record_max + ) if job: runner = "record" if not job: - await asyncio.sleep(2) + # Uploads frozen + no upload claim → idle longer (no fill/record spin). + await asyncio.sleep(8.0 if uploads_frozen else 2.0) continue if runner == "upload": self._active_uploads += 1 @@ -1116,6 +1283,8 @@ class ShortsPipeline: else: self._active_records += 1 asyncio.create_task(self._run_job(job, cfg)) + # Pace claims — skip/rebind paths finish in ms and otherwise peg the loop. + await asyncio.sleep(0.75) except asyncio.CancelledError: break except Exception as exc: @@ -1483,6 +1652,17 @@ class ShortsPipeline: async def _do_record(self, job: dict[str, Any], cfg: dict[str, Any]) -> None: jid = str(job["id"]) + # Cheap offline gate before any Douyin/SSL resolve (avoids CPU spin). + try: + live = _live_room_map() + rid = str(job.get("room_id") or "") + if rid and rid not in live: + if _try_rebind_shorts_job_to_live(job, cfg): + return + _skip_offline_shorts_job(job) + return + except Exception: + pass # Shared clips disk with yt-long — refuse record when critically low (no setting change). try: from .clip_retention import disk_ok_for_record, purge_stale_clips @@ -1497,6 +1677,7 @@ class ShortsPipeline: status="pending", error=f"disk_low:{free_gb:.1f}GB", started_at=0, + updated_at=time.time(), ) return except Exception: @@ -1505,7 +1686,7 @@ class ShortsPipeline: try: from .yt_long_pipeline import try_enqueue_from_shorts - try_enqueue_from_shorts(job) + await asyncio.to_thread(try_enqueue_from_shorts, job) except Exception: pass cookie = str(cfg.get("dy_cookie") or "") @@ -1527,12 +1708,15 @@ class ShortsPipeline: _skip_offline_shorts_job(job) return err = str(job.get("error") or "") + # Backoff: claim_pending skips stream_retry for 120s after updated_at. if "stream_retry" not in err and (time.time() - float(job.get("created_at") or 0)) < 900: db.update_shorts_job( jid, status="pending", error="stream_retry:1", stream_url="", + started_at=0, + updated_at=time.time(), ) return # Still listed live but no playable URL — free slot, don't keep failing. diff --git a/backend/app/shorts_upload.py b/backend/app/shorts_upload.py index 8d79b0f..64cd19e 100644 --- a/backend/app/shorts_upload.py +++ b/backend/app/shorts_upload.py @@ -60,6 +60,76 @@ def _client_kwargs(*, timeout: float, proxy_url: str = "") -> dict[str, Any]: return kw +def _proxy_candidates(proxy_url: str = "") -> list[str]: + try: + from . import egress_hub + + return egress_hub.google_http_proxy_candidates(prefer=str(proxy_url or "").strip()) + except Exception: + p = str(proxy_url or "").strip() + return [p] if p else [""] + + +_HARD_OAUTH_ERRORS = frozenset( + { + "invalid_grant", + "unauthorized_client", + "invalid_client", + "access_denied", + "invalid_request", + } +) + + +def is_hard_oauth_refresh_failure( + *, + status_code: int = 0, + data: dict[str, Any] | None = None, + body_text: str = "", +) -> bool: + """True only for Google auth/config rejects — not proxy HTML / transient 400s. + + Residential egress often returns plain ``Bad Request``; treating that as + hard auth failure skipped direct fallback and stuck oauth_ok=0 forever. + """ + payload = data if isinstance(data, dict) else {} + err = str(payload.get("error") or "").strip().lower() + desc = str(payload.get("error_description") or "").strip().lower() + text = str(body_text or "").strip().lower() + if err in _HARD_OAUTH_ERRORS: + # Google's invalid_request is sometimes egress junk; require a real hint. + if err == "invalid_request" and not desc: + return False + return True + if any(k in desc for k in ("revoked", "expired or revoked", "invalid_grant", "deleted")): + return True + if any(k in text for k in ("invalid_grant", "unauthorized_client", "invalid_client")): + return True + # Opaque 4xx / HTML / bare "Bad Request" → soft (try next egress). + if status_code >= 500 or status_code in (0, 408, 425, 429): + return False + if not err and ("bad request" in text or " bool: + """UI/probe: do not treat egress noise as permanent reauth-needed.""" + raw = str(msg or "") + low = raw.lower() + if not low.strip(): + return True + if "出口不可用" in raw or "出口不稳定" in raw: + return True + if "timeout" in low or "timed out" in low or "connect" in low: + return True + if "bad request" in low and "invalid_grant" not in low and "revoked" not in low: + return True + if "proxy" in low or "tunnel" in low: + return True + return False + + async def refresh_access_token( *, client_id: str, @@ -69,20 +139,58 @@ async def refresh_access_token( ) -> str: if not (client_id and client_secret and refresh_token): raise ValueError("缺少 OAuth client_id / client_secret / refresh_token") - async with httpx.AsyncClient(**_client_kwargs(timeout=30.0, proxy_url=proxy_url)) as client: - resp = await client.post( - "https://oauth2.googleapis.com/token", - data={ - "client_id": client_id, - "client_secret": client_secret, - "refresh_token": refresh_token, - "grant_type": "refresh_token", - }, - ) - data = resp.json() if resp.content else {} - if resp.status_code >= 400 or not data.get("access_token"): - raise ValueError(f"OAuth 刷新失败: {data.get('error_description') or data or resp.text}") - return str(data["access_token"]) + last_transport = "" + last_hard = "" + for proxy in _proxy_candidates(proxy_url): + # Flaky residential: fail fast then fall back to VPS direct. + attempt_timeout = 12.0 if proxy else 30.0 + try: + from . import egress_hub + + kw = egress_hub.httpx_kwargs_for_proxy(proxy, timeout=attempt_timeout) + except Exception: + kw = _client_kwargs(timeout=attempt_timeout, proxy_url=proxy) + try: + async with httpx.AsyncClient(**kw) as client: + resp = await client.post( + "https://oauth2.googleapis.com/token", + data={ + "client_id": client_id, + "client_secret": client_secret, + "refresh_token": refresh_token, + "grant_type": "refresh_token", + }, + ) + raw_text = resp.text if resp.content else "" + try: + data = resp.json() if resp.content else {} + except Exception: + data = {} + if not isinstance(data, dict): + data = {} + if resp.status_code < 400 and data.get("access_token"): + return str(data["access_token"]) + detail = str(data.get("error_description") or data.get("error") or raw_text or resp.status_code)[ + :240 + ] + if is_hard_oauth_refresh_failure( + status_code=int(resp.status_code or 0), + data=data, + body_text=raw_text, + ): + last_hard = detail + raise ValueError(f"OAuth 刷新失败: {detail}") + # Soft/transient: try next egress (often direct after residential). + last_transport = f"http_{resp.status_code}:{detail}"[:240] + continue + except ValueError: + raise + except Exception as exc: + last_transport = f"{type(exc).__name__}: {exc}"[:240] + continue + if last_hard: + raise ValueError(f"OAuth 刷新失败: {last_hard}") + raise ValueError(f"OAuth 刷新失败(出口不可用): {last_transport or 'unknown'}") async def upload_shorts_mp4( diff --git a/backend/app/tiktok_pipeline.py b/backend/app/tiktok_pipeline.py index 0361e36..909a8b1 100644 --- a/backend/app/tiktok_pipeline.py +++ b/backend/app/tiktok_pipeline.py @@ -372,14 +372,14 @@ class TikTokPipeline: async def _loop(self) -> None: while not self._stop.is_set(): try: - cfg = db.get_settings_map() + cfg = await asyncio.to_thread(db.get_settings_map) if not cfg.get("tiktok_enabled"): await asyncio.sleep(5) continue interval = max(60.0, float(cfg.get("tiktok_live_sample_interval_sec") or 180)) if cfg.get("tiktok_live_sample", True) and (time.time() - self._last_sample_at) >= interval: self._last_sample_at = time.time() - n = try_sample_live_rooms(cfg) + n = await asyncio.to_thread(try_sample_live_rooms, cfg) if n: self.sampled += n session_interval = max(600.0, float(cfg.get("tiktok_oauth_check_interval_sec") or 3600)) @@ -390,11 +390,16 @@ class TikTokPipeline: retry_interval = max(120.0, float(cfg.get("tiktok_auto_retry_interval_sec") or 300)) if cfg.get("tiktok_auto_retry_failed") and (time.time() - self._last_auto_retry_at) >= retry_interval: self._last_auto_retry_at = time.time() + today = push_date_from_ts(time.time()) for j in tiktok_db.list_auto_retry_tiktok_failed(limit=10): + ch_pk = str(j.get("channel_pk") or "") + if ch_pk and tiktok_db.channel_at_daily_upload_max(ch_pk, today): + tiktok_db.defer_tiktok_job_to_next_day(str(j["id"]), stagger_sec=120) + continue tiktok_db.update_tiktok_job( str(j["id"]), status="scheduled", - upload_at=pick_upload_at(channel_pk=str(j.get("channel_pk") or ""), cfg=cfg), + upload_at=pick_upload_at(channel_pk=ch_pk, cfg=cfg), error="", ) try: @@ -659,6 +664,11 @@ class TikTokPipeline: tiktok_db.update_tiktok_job(jid, status="recorded", error="成片已保留,待分配 TikTok 账号后再上传") return ch_pk = str(channel["id"]) + day = str(fresh.get("push_date") or push_date_from_ts(time.time())) + if not manual and not probe and tiktok_db.channel_at_daily_upload_max(ch_pk): + # Auto path must respect per-account daily_max (manual upload-now may bypass). + tiktok_db.defer_tiktok_job_to_next_day(jid, stagger_sec=90) + return if ( not manual and not probe diff --git a/backend/app/x_clips_pipeline.py b/backend/app/x_clips_pipeline.py index 0cac5bd..4981655 100644 --- a/backend/app/x_clips_pipeline.py +++ b/backend/app/x_clips_pipeline.py @@ -366,14 +366,14 @@ class XClipsPipeline: async def _loop(self) -> None: while not self._stop.is_set(): try: - cfg = db.get_settings_map() + cfg = await asyncio.to_thread(db.get_settings_map) if not cfg.get("x_clips_enabled"): await asyncio.sleep(5) continue interval = max(60.0, float(cfg.get("x_clips_live_sample_interval_sec") or 180)) if cfg.get("x_clips_live_sample", True) and (time.time() - self._last_sample_at) >= interval: self._last_sample_at = time.time() - n = try_sample_live_rooms(cfg) + n = await asyncio.to_thread(try_sample_live_rooms, cfg) if n: self.sampled += n try: diff --git a/backend/app/yt_long_pipeline.py b/backend/app/yt_long_pipeline.py index d410f32..1c39fe3 100644 --- a/backend/app/yt_long_pipeline.py +++ b/backend/app/yt_long_pipeline.py @@ -562,126 +562,178 @@ class YtLongPipeline: n += 1 return n + def _tick_sync( + self, + *, + do_sample: bool, + do_retention: bool, + record_slots: int, + upload_slots: int, + ) -> dict[str, Any]: + """All SQLite / sample / reclaim work — must run off the asyncio thread.""" + out: dict[str, Any] = { + "enabled": False, + "sampled": 0, + "record_jobs": [], + "upload_jobs": [], + } + cfg = db.get_settings_map() + if not cfg.get("yt_long_enabled"): + return out + out["enabled"] = True + try: + yt_long_db.reconcile_yt_long_upload_caps(cfg) + cfg = db.get_settings_map() + except Exception: + pass + if do_sample and cfg.get("yt_long_live_sample", True): + try: + from .clip_cascade import ensure_source_covers_platforms + + ensure_source_covers_platforms(cfg) + cfg = db.get_settings_map() + except Exception: + pass + n = try_sample_live_rooms(cfg) + if n: + out["sampled"] = int(n) + try: + # Long clips are 3–8 min (+ ffmpeg slack); reclaim only true orphans + max_clip = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC) + yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(720, max_clip + 240)) + except Exception: + pass + try: + yt_long_db.reclaim_stale_yt_long_uploads(max_age_sec=1800) + except Exception: + pass + + if do_retention: + try: + from .clip_retention import purge_stale_clips + + purge_stale_clips(cfg) + except Exception: + pass + + max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) + db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") + # Soft-skip leftover pending when master (source) quota is full + try: + from .timeutil import push_date_from_ts as _pday + + smax = yt_long_db.yt_long_source_daily_max(cfg) + day = _pday(time.time()) + if smax > 0 and yt_long_db.yt_long_source_used(day) >= smax: + for pj in yt_long_db.list_pending_yt_long_jobs(limit=30): + yt_long_db.update_yt_long_job( + str(pj.get("id") or ""), + status="skipped", + error="source_quota_full", + finished_at=time.time(), + ) + except Exception: + pass + # Promote cascade-only masters into YouTube upload slots when available + try: + ugap = yt_long_db.yt_long_upload_gap(cfg=cfg) + if ugap > 0 and cfg.get("yt_long_auto_upload", True): + for cj in yt_long_db.list_cascade_only_ready(limit=min(10, ugap)): + if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0: + break + ch = pick_yt_long_channel(cfg, str(cj.get("push_date") or "")) + if not ch: + break + gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) + yt_long_db.update_yt_long_job( + str(cj.get("id") or ""), + status="scheduled", + channel_pk=str(ch["id"]), + upload_at=time.time() + random.uniform(20, gap), + error="", + ) + try: + yt_long_db.update_yt_long_channel(str(ch["id"]), last_assigned_at=time.time()) + except Exception: + pass + except Exception: + pass + # Never steal CPU from live YouTube push (site hang root cause on dy VPS). + try: + from .host_metrics import clip_encode_defer_reason + + defer = clip_encode_defer_reason() + except Exception: + defer = "" + record_jobs: list[dict[str, Any]] = [] + slots = max(0, min(int(record_slots), max_rec - db_recording)) + while not defer and slots > 0 and len(record_jobs) < slots: + pending = yt_long_db.list_pending_yt_long_jobs(limit=1) + if not pending: + break + job = yt_long_db.claim_yt_long_job_record(str(pending[0].get("id") or "")) + if not job: + break + record_jobs.append(job) + db_recording += 1 + out["record_jobs"] = record_jobs + + upload_jobs: list[dict[str, Any]] = [] + if cfg.get("yt_long_auto_upload", True) and upload_slots > 0: + max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) + from .shorts_yt_quota import blocked_profile_ids + + skip = blocked_profile_ids(cfg) + take = max(0, min(int(upload_slots), max_up)) + while len(upload_jobs) < take: + job = yt_long_db.claim_due_yt_long_upload(skip_profile_ids=skip or None) + if not job: + break + upload_jobs.append(job) + out["upload_jobs"] = upload_jobs + return out + async def _loop(self) -> None: while not self._stop.is_set(): try: - cfg = db.get_settings_map() + # Light flag check only — heavy work goes to a worker thread. + cfg = await asyncio.to_thread(db.get_settings_map) if not cfg.get("yt_long_enabled"): await asyncio.sleep(5) continue - try: - yt_long_db.reconcile_yt_long_upload_caps(cfg) - cfg = db.get_settings_map() - except Exception: - pass interval = max(60.0, float(cfg.get("yt_long_live_sample_interval_sec") or 180)) - if cfg.get("yt_long_live_sample", True) and (time.time() - self._last_sample_at) >= interval: + do_sample = bool( + cfg.get("yt_long_live_sample", True) + and (time.time() - self._last_sample_at) >= interval + ) + do_retention = (time.time() - self._last_retention_at) >= 600 + if do_sample: self._last_sample_at = time.time() - try: - from .clip_cascade import ensure_source_covers_platforms - - ensure_source_covers_platforms(cfg) - cfg = db.get_settings_map() - except Exception: - pass - n = try_sample_live_rooms(cfg) - if n: - self.sampled += n - try: - # Long clips are 3–8 min (+ ffmpeg slack); reclaim only true orphans - max_clip = int(cfg.get("yt_long_max_sec") or YT_LONG_MAX_SEC) - yt_long_db.reclaim_stale_yt_long_recordings(max_age_sec=max(720, max_clip + 240)) - except Exception: - pass - try: - yt_long_db.reclaim_stale_yt_long_uploads(max_age_sec=1800) - except Exception: - pass - - if (time.time() - self._last_retention_at) >= 600: + if do_retention: self._last_retention_at = time.time() - try: - from .clip_retention import purge_stale_clips - - purge_stale_clips(cfg) - except Exception: - pass - max_rec = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) - db_recording = yt_long_db.count_yt_long_jobs_by_status("recording") - # Soft-skip leftover pending when master (source) quota is full - try: - from .timeutil import push_date_from_ts as _pday - - smax = yt_long_db.yt_long_source_daily_max(cfg) - day = _pday(time.time()) - if smax > 0 and yt_long_db.yt_long_source_used(day) >= smax: - for pj in yt_long_db.list_pending_yt_long_jobs(limit=30): - yt_long_db.update_yt_long_job( - str(pj.get("id") or ""), - status="skipped", - error="source_quota_full", - finished_at=time.time(), - ) - except Exception: - pass - # Promote cascade-only masters into YouTube upload slots when available - try: - ugap = yt_long_db.yt_long_upload_gap(cfg=cfg) - if ugap > 0 and cfg.get("yt_long_auto_upload", True): - for cj in yt_long_db.list_cascade_only_ready(limit=min(10, ugap)): - if yt_long_db.yt_long_upload_gap(cfg=cfg) <= 0: - break - ch = pick_yt_long_channel(cfg, str(cj.get("push_date") or "")) - if not ch: - break - gap = max(60, int(cfg.get("yt_long_upload_min_gap_sec") or 900)) - yt_long_db.update_yt_long_job( - str(cj.get("id") or ""), - status="scheduled", - channel_pk=str(ch["id"]), - upload_at=time.time() + random.uniform(20, gap), - error="", - ) - try: - yt_long_db.update_yt_long_channel(str(ch["id"]), last_assigned_at=time.time()) - except Exception: - pass - except Exception: - pass - # Never steal CPU from live YouTube push (site hang root cause on dy VPS). - try: - from .host_metrics import clip_encode_defer_reason - - defer = clip_encode_defer_reason() - except Exception: - defer = "" - while ( - not defer - and self._active_records < max_rec - and db_recording < max_rec - ): - pending = yt_long_db.list_pending_yt_long_jobs(limit=1) - if not pending: - break - job = yt_long_db.claim_yt_long_job_record(str(pending[0].get("id") or "")) - if not job: - break + max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) + record_slots = max(0, max_rec - self._active_records) + upload_slots = ( + max(0, max_up - self._active_uploads) + if cfg.get("yt_long_auto_upload", True) + else 0 + ) + tick = await asyncio.to_thread( + self._tick_sync, + do_sample=do_sample, + do_retention=do_retention, + record_slots=record_slots, + upload_slots=upload_slots, + ) + if int(tick.get("sampled") or 0): + self.sampled += int(tick["sampled"]) + for job in list(tick.get("record_jobs") or []): self._active_records += 1 - db_recording += 1 asyncio.create_task(self._run_record(job)) - - if cfg.get("yt_long_auto_upload", True): - max_up = max(1, int(cfg.get("yt_long_max_concurrent") or 1)) - from .shorts_yt_quota import blocked_profile_ids - - skip = blocked_profile_ids(cfg) - while self._active_uploads < max_up: - job = yt_long_db.claim_due_yt_long_upload(skip_profile_ids=skip or None) - if not job: - break - self._active_uploads += 1 - asyncio.create_task(self._run_upload(job)) + for job in list(tick.get("upload_jobs") or []): + self._active_uploads += 1 + asyncio.create_task(self._run_upload(job)) except Exception as exc: self.last_error = str(exc)[:240] await asyncio.sleep(5.0) diff --git a/scripts/linux/api_health_watch.sh b/scripts/linux/api_health_watch.sh index 868dd8b..fef4ad9 100644 --- a/scripts/linux/api_health_watch.sh +++ b/scripts/linux/api_health_watch.sh @@ -10,6 +10,7 @@ GRACE="${DY_API_WATCH_START_GRACE:-180}" HEALTH_URL="${DY_API_WATCH_URL:-http://127.0.0.1:8014/api/health}" UNIT="${DY_API_WATCH_UNIT:-douyinweb-api.service}" RECVQ_LIMIT="${DY_API_WATCH_RECVQ_LIMIT:-200}" +HEALTH_TIMEOUT="${DY_API_WATCH_HEALTH_TIMEOUT:-4}" log() { printf '[api-watch] %s\n' "$*"; } @@ -48,7 +49,7 @@ while true; do fi fi - code=$(curl -sS -m 4 -o /dev/null -w '%{http_code}' "$HEALTH_URL" 2>/dev/null) + code=$(curl -sS -m "$HEALTH_TIMEOUT" -o /dev/null -w '%{http_code}' "$HEALTH_URL" 2>/dev/null) [ -n "$code" ] || code=000 now=$(date +%s) if [ "$code" = "200" ]; then