Client A exhaustion no longer pauses Client B jobs; banners and counters are per-profile. Co-authored-by: Cursor <cursoragent@cursor.com>
450 lines
16 KiB
Python
450 lines
16 KiB
Python
# -*- coding: utf-8 -*-
|
|
"""YouTube Data API daily upload budget — per OAuth Client profile (A/B/C/D).
|
|
|
|
Each Google Cloud project has its own Video Uploads quota. Client A exhaustion
|
|
must NOT pause Client B uploads.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import time
|
|
from typing import Any
|
|
|
|
from . import db
|
|
from .shorts_upload import is_upload_quota_error, quota_error_message
|
|
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"
|
|
|
|
|
|
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 _empty_entry() -> dict[str, Any]:
|
|
return {"date": "", "count": 0, "blocked_until": 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),
|
|
}
|
|
# 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,
|
|
}
|
|
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:
|
|
# Channels on this profile (empty profile_id counts as A)
|
|
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)
|
|
if blocked_until and blocked_until <= time.time():
|
|
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 block
|
|
blocked_until = 0.0
|
|
entry = {"date": stored_day, "count": stored_count, "blocked_until": blocked_until}
|
|
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)
|
|
# Persist day roll if needed
|
|
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 reserve_yt_upload_slot(
|
|
cfg: dict[str, Any] | None = None,
|
|
*,
|
|
profile_id: str = "A",
|
|
) -> bool:
|
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
|
pid = normalize_profile_id(profile_id)
|
|
if profile_upload_blocked(settings, profile_id=pid)[0]:
|
|
return False
|
|
limit, used, remaining = yt_upload_budget(settings, profile_id=pid)
|
|
if remaining <= 0:
|
|
return False
|
|
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)
|
|
return True
|
|
|
|
|
|
def project_uploads_available(
|
|
cfg: dict[str, Any] | None = None,
|
|
*,
|
|
profile_id: str = "A",
|
|
) -> bool:
|
|
settings = cfg if cfg is not None else db.get_settings_map()
|
|
if profile_upload_blocked(settings, profile_id=profile_id)[0]:
|
|
return False
|
|
return yt_upload_budget(settings, profile_id=profile_id)[2] > 0
|
|
|
|
|
|
def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
|
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
|
profiles = {"A", "B", "C", "D"}
|
|
for ch in db.list_shorts_channels(enabled=True):
|
|
profiles.add(profile_id_for_channel(ch))
|
|
return any(project_uploads_available(settings, profile_id=p) for p in profiles)
|
|
|
|
|
|
def profile_upload_blocked(
|
|
cfg: dict[str, Any] | None = None,
|
|
*,
|
|
profile_id: str = "A",
|
|
) -> tuple[bool, float]:
|
|
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)
|
|
now = time.time()
|
|
if until <= now:
|
|
if until > 0:
|
|
entry["blocked_until"] = 0.0
|
|
quota_map[pid] = entry
|
|
_save_quota_map(quota_map)
|
|
return False, 0.0
|
|
return True, until
|
|
|
|
|
|
def blocked_profile_ids(cfg: dict[str, Any] | None = None) -> set[str]:
|
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
|
profiles = {"A", "B", "C", "D"}
|
|
for ch in db.list_shorts_channels(enabled=True):
|
|
profiles.add(profile_id_for_channel(ch))
|
|
bad: set[str] = set()
|
|
for pid in profiles:
|
|
blocked, _ = profile_upload_blocked(settings, profile_id=pid)
|
|
if blocked:
|
|
bad.add(pid)
|
|
else:
|
|
limit, used, _ = yt_upload_budget(settings, profile_id=pid)
|
|
if used >= limit:
|
|
bad.add(pid)
|
|
return bad
|
|
|
|
|
|
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)
|
|
if used >= limit:
|
|
blocked = True
|
|
until = until or next_youtube_quota_reset_ts()
|
|
rows.append(
|
|
{
|
|
"id": pid,
|
|
"limit": limit,
|
|
"used": used,
|
|
"remaining": remaining,
|
|
"blocked": blocked,
|
|
"blocked_until": until,
|
|
}
|
|
)
|
|
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 pause_uploads_until_reset(
|
|
cfg: dict[str, Any] | None = None,
|
|
*,
|
|
profile_id: str = "A",
|
|
reason: str = "",
|
|
) -> float:
|
|
"""Block uploads for ONE OAuth Client profile until Pacific midnight."""
|
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
|
pid = normalize_profile_id(profile_id)
|
|
until = next_youtube_quota_reset_ts()
|
|
quota_map = _load_quota_map(settings)
|
|
entry = _sync_profile_entry(pid, settings, quota_map)
|
|
entry["blocked_until"] = until
|
|
# Snap counter to limit so UI shows exhausted
|
|
limit = yt_daily_limit(settings)
|
|
entry["count"] = max(int(entry.get("count") or 0), limit)
|
|
entry["date"] = pacific_day_from_ts(time.time())
|
|
quota_map[pid] = entry
|
|
_save_quota_map(quota_map)
|
|
msg = reason or quota_error_message(profile_id=pid)
|
|
defer_profile_shorts_uploads(pid, until, reason=msg)
|
|
return until
|
|
|
|
|
|
def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
|
|
"""Reschedule pending uploads only for channels on this Client profile."""
|
|
pid = normalize_profile_id(profile_id)
|
|
ch_ids = channel_ids_for_profile(pid)
|
|
if not ch_ids:
|
|
return 0
|
|
now = time.time()
|
|
retry_at = max(until_ts, now) + 300
|
|
msg = (reason or quota_error_message(profile_id=pid))[:400]
|
|
placeholders = ",".join("?" for _ in ch_ids)
|
|
with db._lock:
|
|
conn = db._connect()
|
|
try:
|
|
cur = conn.execute(
|
|
f"""
|
|
UPDATE shorts_jobs
|
|
SET status = 'scheduled',
|
|
upload_at = ?,
|
|
error = ?,
|
|
finished_at = 0,
|
|
updated_at = ?
|
|
WHERE status IN ('scheduled', 'uploading', 'recorded')
|
|
AND clip_path != ''
|
|
AND youtube_video_id = ''
|
|
AND channel_pk IN ({placeholders})
|
|
""",
|
|
(retry_at, msg, now, *ch_ids),
|
|
)
|
|
conn.commit()
|
|
return int(cur.rowcount)
|
|
finally:
|
|
conn.close()
|
|
|
|
|
|
def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int:
|
|
"""Remove copied global-quota error text from jobs whose Client is NOT blocked."""
|
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
|
blocked = blocked_profile_ids(settings)
|
|
cleared = 0
|
|
now = time.time()
|
|
for ch in db.list_shorts_channels(enabled=None):
|
|
pid = profile_id_for_channel(ch)
|
|
if pid in blocked:
|
|
continue
|
|
cid = str(ch.get("id") or "")
|
|
with db._lock:
|
|
conn = db._connect()
|
|
try:
|
|
cur = conn.execute(
|
|
"""
|
|
UPDATE shorts_jobs
|
|
SET error = '', updated_at = ?
|
|
WHERE channel_pk = ?
|
|
AND youtube_video_id = ''
|
|
AND status IN ('scheduled', 'recorded', 'failed')
|
|
AND (
|
|
error LIKE '%配额已用尽%'
|
|
OR error LIKE '%QUOTA_EXCEEDED%'
|
|
OR error LIKE '%429%'
|
|
)
|
|
""",
|
|
(now, cid),
|
|
)
|
|
cleared += int(cur.rowcount)
|
|
conn.commit()
|
|
finally:
|
|
conn.close()
|
|
return cleared
|
|
|
|
|
|
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]:
|
|
"""Scan recent job errors; pause only the matching Client profile(s)."""
|
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
|
paused: dict[str, float] = {}
|
|
|
|
# Soft local budget hit
|
|
for row in quota_budgets_by_profile(settings):
|
|
pid = str(row["id"])
|
|
if row.get("blocked") and float(row.get("blocked_until") or 0) > time.time():
|
|
paused[pid] = float(row["blocked_until"])
|
|
continue
|
|
if int(row.get("used") or 0) >= int(row.get("limit") or 1):
|
|
paused[pid] = pause_uploads_until_reset(settings, profile_id=pid)
|
|
|
|
with db._lock:
|
|
conn = db._connect()
|
|
try:
|
|
rows = conn.execute(
|
|
"""
|
|
SELECT id, channel_pk, error, updated_at FROM shorts_jobs
|
|
WHERE error != ''
|
|
ORDER BY updated_at DESC
|
|
LIMIT 40
|
|
""",
|
|
).fetchall()
|
|
finally:
|
|
conn.close()
|
|
|
|
for row in rows:
|
|
err = str(row["error"] or "")
|
|
if not is_upload_quota_error(err):
|
|
continue
|
|
job = {"channel_pk": row["channel_pk"], "id": row["id"]}
|
|
pid = profile_id_for_job(job)
|
|
if pid in paused:
|
|
continue
|
|
until = pause_uploads_until_reset(settings, profile_id=pid)
|
|
paused[pid] = until
|
|
|
|
return paused
|
|
|
|
|
|
# Back-compat aliases used by older call sites (treat as profile A)
|
|
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)
|