douyinWEB/backend/app/shorts_yt_quota.py
2026-09-13 22:10:49 -05:00

457 lines
16 KiB
Python

# -*- coding: utf-8 -*-
"""YouTube Data API upload counters — per OAuth Client profile (A/B/C/D).
Local upload *counts* are display-only and must not gate uploads by themselves.
When YouTube returns a real 429 / quota-exceeded, we set a short API cool-down
per Client so the worker stops hammering (and ntfy spam). Manual upload paths
never consult that cool-down.
"""
from __future__ import annotations
import time
from typing import Any
from . import db
from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts
YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90
QUOTA_MAP_KEY = "shorts_yt_quota_by_profile"
# After a real YouTube 429, pause auto-uploads for this Client (manual still OK).
DEFAULT_API_COOLDOWN_SEC = 3600.0
def normalize_profile_id(raw: Any) -> str:
pid = str(raw or "").strip().upper()
return pid or "A"
def profile_id_for_channel(channel: dict[str, Any] | None) -> str:
return normalize_profile_id((channel or {}).get("oauth_profile_id"))
def profile_id_for_job(job: dict[str, Any] | None) -> str:
job = job or {}
ch = db.get_shorts_channel(str(job.get("channel_pk") or ""))
if ch:
return profile_id_for_channel(ch)
return normalize_profile_id(job.get("oauth_profile_id"))
def yt_daily_limit(cfg: dict[str, Any] | None = None) -> int:
settings = cfg if cfg is not None else db.get_settings_map()
return max(1, int(settings.get("shorts_yt_daily_upload_limit") or YT_DAILY_UPLOAD_LIMIT_DEFAULT))
def api_cooldown_sec(cfg: dict[str, Any] | None = None) -> float:
settings = cfg if cfg is not None else db.get_settings_map()
try:
return max(
300.0,
min(12 * 3600.0, float(settings.get("shorts_yt_quota_cooldown_sec") or DEFAULT_API_COOLDOWN_SEC)),
)
except (TypeError, ValueError):
return DEFAULT_API_COOLDOWN_SEC
def _empty_entry() -> dict[str, Any]:
return {"date": "", "count": 0, "blocked_until": 0.0, "quota_ntfy_at": 0.0}
def _load_quota_map(cfg: dict[str, Any]) -> dict[str, dict[str, Any]]:
raw = cfg.get(QUOTA_MAP_KEY)
out: dict[str, dict[str, Any]] = {}
if isinstance(raw, dict):
for k, v in raw.items():
pid = normalize_profile_id(k)
if not isinstance(v, dict):
continue
out[pid] = {
"date": str(v.get("date") or ""),
"count": int(v.get("count") or 0),
"blocked_until": float(v.get("blocked_until") or 0),
"quota_ntfy_at": float(v.get("quota_ntfy_at") or 0),
}
# One-time migrate legacy global counters into profile A if map empty
if not out:
legacy_until = float(cfg.get("shorts_yt_upload_blocked_until") or 0)
legacy_date = str(cfg.get("shorts_yt_uploads_pt_date") or "")
legacy_count = int(cfg.get("shorts_yt_uploads_pt_count") or 0)
if legacy_date or legacy_count or legacy_until > time.time():
out["A"] = {
"date": legacy_date,
"count": legacy_count,
"blocked_until": legacy_until if legacy_until > time.time() else 0.0,
"quota_ntfy_at": 0.0,
}
return out
def _save_quota_map(quota_map: dict[str, dict[str, Any]]) -> None:
try:
db.update_settings_map(
{
QUOTA_MAP_KEY: quota_map,
# Clear legacy global block so it cannot freeze all profiles
"shorts_yt_upload_blocked_until": 0,
}
)
except Exception:
pass
def _count_uploads_from_db_pt_day(profile_id: str, day: str = "") -> int:
"""Count upload API uses in the Pacific day for channels on this profile."""
pid = normalize_profile_id(profile_id)
pt_day = day or pacific_day_from_ts(time.time())
start, end = pacific_day_bounds(pt_day)
with db._lock:
conn = db._connect()
try:
if pid == "A":
ch_rows = conn.execute(
"""
SELECT id FROM shorts_channels
WHERE UPPER(TRIM(oauth_profile_id)) = 'A'
OR TRIM(oauth_profile_id) = ''
OR oauth_profile_id IS NULL
"""
).fetchall()
else:
ch_rows = conn.execute(
"""
SELECT id FROM shorts_channels
WHERE UPPER(TRIM(oauth_profile_id)) = ?
""",
(pid,),
).fetchall()
ch_ids = [str(r["id"]) for r in ch_rows]
if not ch_ids:
return 0
placeholders = ",".join("?" for _ in ch_ids)
row = conn.execute(
f"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE youtube_video_id != ''
AND finished_at >= ? AND finished_at < ?
AND channel_pk IN ({placeholders})
""",
(start, end, *ch_ids),
).fetchone()
uploaded = int(row["c"] if row else 0)
row2 = conn.execute(
f"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE status = 'uploading'
AND clip_path != ''
AND youtube_video_id = ''
AND channel_pk IN ({placeholders})
""",
tuple(ch_ids),
).fetchone()
in_flight = int(row2["c"] if row2 else 0)
row3 = conn.execute(
f"""
SELECT COUNT(*) AS c FROM shorts_jobs
WHERE status IN ('failed', 'scheduled')
AND error LIKE '%429%'
AND updated_at >= ? AND updated_at < ?
AND channel_pk IN ({placeholders})
""",
(start, end, *ch_ids),
).fetchone()
quota_fails = int(row3["c"] if row3 else 0)
return uploaded + in_flight + quota_fails
finally:
conn.close()
def _sync_profile_entry(
profile_id: str,
cfg: dict[str, Any],
quota_map: dict[str, dict[str, Any]],
) -> dict[str, Any]:
pid = normalize_profile_id(profile_id)
entry = dict(quota_map.get(pid) or _empty_entry())
pt_day = pacific_day_from_ts(time.time())
stored_day = str(entry.get("date") or "")
stored_count = int(entry.get("count") or 0)
blocked_until = float(entry.get("blocked_until") or 0)
ntfy_at = float(entry.get("quota_ntfy_at") or 0)
now = time.time()
if blocked_until and blocked_until <= now:
blocked_until = 0.0
if stored_day != pt_day:
db_count = _count_uploads_from_db_pt_day(pid, pt_day)
stored_count = max(stored_count, db_count) if stored_day else db_count
stored_day = pt_day
# New Pacific day clears cool-down (YouTube quota also resets at PT midnight)
blocked_until = 0.0
ntfy_at = 0.0
entry = {
"date": stored_day,
"count": stored_count,
"blocked_until": blocked_until,
"quota_ntfy_at": ntfy_at,
}
quota_map[pid] = entry
return entry
def yt_upload_budget(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> tuple[int, int, int]:
"""Return (limit, used, remaining) for one OAuth Client profile."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
limit = yt_daily_limit(settings)
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(profile_id, settings, quota_map)
if settings.get(QUOTA_MAP_KEY) != quota_map:
_save_quota_map(quota_map)
settings[QUOTA_MAP_KEY] = quota_map
used = int(entry.get("count") or 0)
remaining = max(0, limit - used)
return limit, used, remaining
def note_yt_upload_attempt(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> None:
"""UI counter only — does not clear API cool-down."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
entry["count"] = int(entry.get("count") or 0) + 1
entry["date"] = pacific_day_from_ts(time.time())
quota_map[pid] = entry
_save_quota_map(quota_map)
def reserve_yt_upload_slot(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> bool:
"""Always allow reservation for UI counter. Cool-down is enforced at claim time."""
note_yt_upload_attempt(cfg, profile_id=profile_id)
return True
def project_uploads_available(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> bool:
"""True unless this Client is in a YouTube-API cool-down window."""
blocked, _ = profile_upload_blocked(cfg, profile_id=profile_id)
return not blocked
def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
"""True if at least one Client is not in API cool-down (or map is empty)."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
blocked = blocked_profile_ids(settings)
if not blocked:
return True
for pid in ("A", "B", "C", "D"):
if pid not in blocked:
return True
return False
def profile_upload_blocked(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
) -> tuple[bool, float]:
"""True while YouTube API cool-down is active for this Client."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
until = float(entry.get("blocked_until") or 0)
if until > time.time():
return True, until
return False, 0.0
def blocked_profile_ids(cfg: dict[str, Any] | None = None) -> set[str]:
"""Clients currently in API cool-down (worker should skip auto-upload)."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
quota_map = _load_quota_map(settings)
out: set[str] = set()
now = time.time()
pids = set(quota_map.keys()) | {"A", "B", "C", "D"}
for pid in pids:
entry = _sync_profile_entry(pid, settings, quota_map)
if float(entry.get("blocked_until") or 0) > now:
out.add(pid)
return out
def quota_budgets_by_profile(cfg: dict[str, Any] | None = None) -> list[dict[str, Any]]:
settings = dict(cfg if cfg is not None else db.get_settings_map())
profiles = ["A", "B", "C", "D"]
seen = set(profiles)
for ch in db.list_shorts_channels(enabled=None):
pid = profile_id_for_channel(ch)
if pid not in seen:
profiles.append(pid)
seen.add(pid)
rows = []
for pid in profiles:
limit, used, remaining = yt_upload_budget(settings, profile_id=pid)
blocked, until = profile_upload_blocked(settings, profile_id=pid)
rows.append(
{
"id": pid,
"limit": limit,
"used": used,
"remaining": remaining,
"exhausted_hint": bool(used >= limit and not blocked),
"blocked": blocked,
"blocked_until": until,
"reset_at": until
if blocked
else (next_youtube_quota_reset_ts() if used >= limit else 0.0),
}
)
return rows
def channel_ids_for_profile(profile_id: str) -> list[str]:
pid = normalize_profile_id(profile_id)
ids: list[str] = []
for ch in db.list_shorts_channels(enabled=None):
if profile_id_for_channel(ch) == pid:
ids.append(str(ch["id"]))
return ids
def mark_api_quota_cooldown(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
reason: str = "",
cooldown_sec: float | None = None,
) -> tuple[float, bool]:
"""Set cool-down after a real YouTube 429. Returns (until_ts, should_notify).
should_notify is True only when entering / refreshing a cool-down for ntfy (once per window).
"""
settings = dict(cfg if cfg is not None else db.get_settings_map())
pid = normalize_profile_id(profile_id)
cool = float(cooldown_sec) if cooldown_sec is not None else api_cooldown_sec(settings)
now = time.time()
reset_at = next_youtube_quota_reset_ts()
until = min(now + cool, reset_at) if reset_at > now else now + cool
quota_map = _load_quota_map(settings)
entry = _sync_profile_entry(pid, settings, quota_map)
prev_until = float(entry.get("blocked_until") or 0)
already = prev_until > now + 60
entry["blocked_until"] = max(prev_until, until) if already else until
limit = yt_daily_limit(settings)
entry["count"] = max(int(entry.get("count") or 0), limit)
entry["date"] = pacific_day_from_ts(now)
last_ntfy = float(entry.get("quota_ntfy_at") or 0)
should_notify = (not already) or (now - last_ntfy >= cool * 0.9)
if should_notify:
entry["quota_ntfy_at"] = now
quota_map[pid] = entry
_save_quota_map(quota_map)
_ = reason
return float(entry["blocked_until"]), should_notify
def pause_uploads_until_reset(
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "A",
reason: str = "",
) -> float:
"""Compatibility: apply default API cool-down."""
until, _ = mark_api_quota_cooldown(cfg, profile_id=profile_id, reason=reason)
return until
def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
"""Push due auto-uploads for this Client past cool-down (manual claim still free)."""
pid = normalize_profile_id(profile_id)
until = float(until_ts or 0)
if until <= time.time():
return 0
ch_ids = channel_ids_for_profile(pid)
if not ch_ids:
return 0
moved = 0
now = time.time()
with db._lock:
conn = db._connect()
try:
placeholders = ",".join("?" for _ in ch_ids)
rows = conn.execute(
f"""
SELECT id, upload_at FROM shorts_jobs
WHERE status IN ('scheduled', 'recorded')
AND clip_path != ''
AND youtube_video_id = ''
AND channel_pk IN ({placeholders})
AND upload_at > 0
AND upload_at <= ?
""",
(*ch_ids, now + 30),
).fetchall()
for row in rows:
conn.execute(
"UPDATE shorts_jobs SET upload_at = ?, error = ?, updated_at = ? WHERE id = ?",
(
until + 15,
(reason or "YouTube 接口配额冷静中,稍后自动重试")[:300],
now,
str(row["id"]),
),
)
moved += 1
if moved:
conn.commit()
finally:
conn.close()
return moved
def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int:
"""No-op: keep YouTube API error text on jobs for operator feedback."""
_ = cfg
return 0
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]:
"""No-op: cool-down is set only from live API 429 feedback."""
_ = cfg
return {}
def clear_all_upload_self_blocks(cfg: dict[str, Any] | None = None) -> None:
"""Clear expired cool-downs only — does not wipe an active API cool-down."""
settings = dict(cfg if cfg is not None else db.get_settings_map())
quota_map = _load_quota_map(settings)
changed = False
now = time.time()
for pid, entry in list(quota_map.items()):
until = float(entry.get("blocked_until") or 0)
if until and until <= now:
entry = dict(entry)
entry["blocked_until"] = 0.0
quota_map[pid] = entry
changed = True
if changed or float(settings.get("shorts_yt_upload_blocked_until") or 0) > 0:
_save_quota_map(quota_map)
def pause_uploads_until_reset_global(cfg: dict[str, Any] | None = None, *, reason: str = "") -> float:
return pause_uploads_until_reset(cfg, profile_id="A", reason=reason)