Isolate YouTube upload quota by OAuth Client A/B/C/D.

Client A exhaustion no longer pauses Client B jobs; banners and counters are per-profile.

Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
eric 2026-08-11 19:57:35 -05:00
parent b752943d22
commit c9df6be027
5 changed files with 493 additions and 160 deletions

View File

@ -3064,15 +3064,16 @@ def room_ids_with_shorts_job_today(push_date: str) -> set[str]:
def pick_shorts_channel(push_date: str, cfg: dict[str, Any] | None = None) -> dict[str, Any] | None:
"""Pick enabled channel with most room left today (Beijing day); under daily_min first."""
from .shorts_yt_quota import project_uploads_available
from .shorts_yt_quota import profile_id_for_channel, project_uploads_available
if not project_uploads_available(cfg):
return None
channels = list_shorts_channels(enabled=True)
if not channels:
return None
scored: list[tuple[int, int, float, dict[str, Any]]] = []
for ch in channels:
pid = profile_id_for_channel(ch)
if not project_uploads_available(cfg, profile_id=pid):
continue
used = shorts_channel_upload_count(str(ch["id"]), push_date)
daily_max = SHORTS_DAILY_FORCE
if used >= daily_max:
@ -3218,43 +3219,59 @@ def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
conn.close()
def claim_due_shorts_upload() -> dict[str, Any] | None:
"""Claim one due scheduled/recorded clip for upload."""
def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict[str, Any] | None:
"""Claim one due scheduled/recorded clip for upload.
skip_profile_ids: OAuth Client profiles whose YouTube project quota is exhausted
(e.g. {"A"}) — jobs for those channels are left alone so Client B can still upload.
"""
now = time.time()
skip = {str(x).strip().upper() for x in (skip_profile_ids or set()) if str(x).strip()}
with _lock:
conn = _connect()
try:
row = conn.execute(
rows = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status = 'scheduled'
AND clip_path != ''
AND youtube_video_id = ''
AND upload_at > 0
AND upload_at <= ?
ORDER BY upload_at ASC, created_at ASC
LIMIT 1
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
FROM shorts_jobs j
LEFT JOIN shorts_channels c ON c.id = j.channel_pk
WHERE j.status = 'scheduled'
AND j.clip_path != ''
AND j.youtube_video_id = ''
AND j.upload_at > 0
AND j.upload_at <= ?
ORDER BY j.upload_at ASC, j.created_at ASC
LIMIT 30
""",
(now,),
).fetchone()
if not row:
row = conn.execute(
).fetchall()
if not rows:
rows = conn.execute(
"""
SELECT * FROM shorts_jobs
WHERE status = 'recorded'
AND clip_path != ''
AND youtube_video_id = ''
AND upload_at > 0
AND upload_at <= ?
ORDER BY upload_at ASC
LIMIT 1
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
FROM shorts_jobs j
LEFT JOIN shorts_channels c ON c.id = j.channel_pk
WHERE j.status = 'recorded'
AND j.clip_path != ''
AND j.youtube_video_id = ''
AND j.upload_at > 0
AND j.upload_at <= ?
ORDER BY j.upload_at ASC
LIMIT 30
""",
(now,),
).fetchone()
if not row:
).fetchall()
picked = None
for row in rows:
pid = str(row["oauth_profile_id"] or "A").strip().upper() or "A"
if pid in skip:
continue
picked = row
break
if not picked:
return None
jid = row["id"]
status = row["status"]
jid = picked["id"]
status = picked["status"]
conn.execute(
"""
UPDATE shorts_jobs

View File

@ -18,14 +18,20 @@ from . import db
from .shorts_clip import record_clip, resolve_stream_url
from .shorts_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
from .shorts_yt_quota import (
any_profile_uploads_available,
blocked_profile_ids,
clear_stale_quota_errors_for_open_profiles,
detect_and_block_from_recent_errors,
pause_uploads_until_reset,
profile_id_for_channel,
profile_id_for_job,
profile_upload_blocked,
project_uploads_available,
quota_budgets_by_profile,
reserve_yt_upload_slot,
yt_upload_budget,
)
from .timeutil import format_beijing, next_youtube_quota_reset_ts
from .timeutil import push_date_from_ts
from .timeutil import format_beijing, push_date_from_ts
def _room_tags(room: dict[str, Any]) -> list[str]:
@ -177,7 +183,7 @@ def try_fill_daily_quota(cfg: dict[str, Any] | None = None) -> int:
settings = cfg or db.get_settings_map()
if not settings.get("shorts_enabled"):
return 0
if not project_uploads_available(settings):
if not any_profile_uploads_available(settings):
return 0
day = push_date_from_ts(time.time())
gap_total = db.shorts_total_quota_gap(day)
@ -442,23 +448,27 @@ class ShortsPipeline:
)
except Exception:
pass
try:
# Clear wrongly-copied global quota errors on open Clients before scanning
clear_stale_quota_errors_for_open_profiles(cfg)
except Exception:
pass
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
try:
detected, detected_until = detect_and_block_from_recent_errors(cfg)
if detected:
paused = detect_and_block_from_recent_errors(cfg)
if paused:
quota_blocked = True
quota_until = max(quota_until, detected_until)
quota_until = max([quota_until, *paused.values()])
except Exception:
pass
if not quota_blocked and is_upload_quota_error(self.last_error):
quota_until = next_youtube_quota_reset_ts()
try:
db.update_settings_map({"shorts_yt_upload_blocked_until": quota_until})
except Exception:
pass
quota_blocked = True
last_error = quota_error_message() if quota_blocked else self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg)
# last_error may belong to one profile — do not freeze all Clients
pass
last_error = self.last_error
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
yt_by_profile = quota_budgets_by_profile(cfg)
blocked_profiles = [r for r in yt_by_profile if r.get("blocked")]
any_blocked = bool(blocked_profiles)
return {
"running": bool(self._task and not self._task.done()),
"busy": self._active_records > 0 or self._active_uploads > 0,
@ -472,11 +482,13 @@ class ShortsPipeline:
"auto_retried": self.auto_retried,
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
"quota_gap": db.shorts_total_quota_gap(),
"upload_quota_blocked": quota_blocked,
"upload_quota_blocked_until": quota_until,
"upload_quota_blocked": any_blocked,
"upload_quota_blocked_until": max((float(r.get("blocked_until") or 0) for r in blocked_profiles), default=0),
"upload_quota_blocked_profiles": [str(r.get("id") or "") for r in blocked_profiles],
"yt_upload_limit": yt_limit,
"yt_upload_used": yt_used,
"yt_upload_remaining": yt_remaining,
"yt_quota_by_profile": yt_by_profile,
"last_error": last_error,
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
"live_sample": bool(cfg.get("shorts_live_sample", True)),
@ -509,6 +521,7 @@ class ShortsPipeline:
if self._task and not self._task.done():
return
try:
clear_stale_quota_errors_for_open_profiles()
detect_and_block_from_recent_errors()
except Exception:
pass
@ -565,12 +578,8 @@ class ShortsPipeline:
asyncio.create_task(self._probe_oauth(cfg))
retry_interval = max(120.0, float(cfg.get("shorts_auto_retry_interval_sec") or 300))
quota_blocked_loop, _ = self._upload_quota_blocked(cfg)
if (
not quota_blocked_loop
and cfg.get("shorts_auto_retry_failed", True)
and (time.time() - self._last_auto_retry_at) >= retry_interval
):
# Auto-retry failed jobs even if some Clients are quota-blocked (skip happens at claim)
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)
@ -586,11 +595,7 @@ class ShortsPipeline:
pass
try:
retry_at = 0.0
quota_blocked_loop, quota_until_loop = self._upload_quota_blocked(cfg)
if quota_blocked_loop:
retry_at = quota_until_loop + 300
n = db.reclaim_stale_shorts_uploads(max_age_sec=180, retry_at=retry_at)
n = db.reclaim_stale_shorts_uploads(max_age_sec=180, retry_at=0.0)
if n:
self.last_error = ""
except Exception:
@ -612,14 +617,11 @@ class ShortsPipeline:
record_max = self._record_max(cfg)
upload_max = self._upload_max(cfg)
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
if not quota_blocked and not project_uploads_available(cfg):
quota_until = pause_uploads_until_reset(cfg)
quota_blocked = True
skip_profiles = blocked_profile_ids(cfg)
job: dict[str, Any] | None = None
runner: str = ""
if not quota_blocked and self._active_uploads < upload_max:
job = db.claim_due_shorts_upload()
if self._active_uploads < upload_max:
job = db.claim_due_shorts_upload(skip_profile_ids=skip_profiles)
if job:
runner = "upload"
if not job and self._active_records < record_max:
@ -751,22 +753,29 @@ class ShortsPipeline:
except Exception:
pass
def _upload_quota_blocked(self, cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
def _upload_quota_blocked(
self,
cfg: dict[str, Any] | None = None,
*,
profile_id: str = "",
) -> tuple[bool, float]:
"""If profile_id set, only that Client; else True when ANY profile is blocked."""
settings = cfg if cfg is not None else db.get_settings_map()
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
now = time.time()
if until <= now:
if until > 0:
try:
db.update_settings_map({"shorts_yt_upload_blocked_until": 0})
except Exception:
pass
if profile_id:
return profile_upload_blocked(settings, profile_id=profile_id)
blocked = blocked_profile_ids(settings)
if not blocked:
return False, 0.0
until = 0.0
for pid in blocked:
_, u = profile_upload_blocked(settings, profile_id=pid)
until = max(until, u)
return True, until
def _pause_uploads_for_quota(self, job: dict[str, Any], raw_error: str) -> None:
until = pause_uploads_until_reset(reason=quota_error_message())
friendly = quota_error_message()
pid = profile_id_for_job(job)
until = pause_uploads_until_reset(profile_id=pid, reason=quota_error_message(pid))
friendly = quota_error_message(pid)
jid = str(job.get("id") or "")
if jid:
db.update_shorts_job(
@ -780,9 +789,9 @@ class ShortsPipeline:
self._emit_shorts_event(
kind="shorts_quota",
level="warn",
message=f"Shorts 上传配额用尽,已暂停至 {format_beijing(until)}(太平洋 0 点重置)",
message=f"Client {pid} Shorts 上传配额用尽,仅暂停该配置档至 {format_beijing(until)}",
job=job,
extra={"error": raw_error[:200], "blocked_until": until},
extra={"error": raw_error[:200], "blocked_until": until, "oauth_profile_id": pid},
)
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
@ -861,9 +870,13 @@ class ShortsPipeline:
raise ValueError(f"状态 {st} 不可手动上传")
cfg = db.get_settings_map()
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
pid = profile_id_for_job(job)
quota_blocked, quota_until = self._upload_quota_blocked(cfg, profile_id=pid)
if quota_blocked:
raise ValueError(f"{quota_error_message()} 预计 {format_beijing(quota_until)} 恢复。")
raise ValueError(f"{quota_error_message(pid)} 预计 {format_beijing(quota_until)} 恢复。")
if not project_uploads_available(cfg, profile_id=pid):
until = pause_uploads_until_reset(cfg, profile_id=pid)
raise ValueError(f"{quota_error_message(pid)} 预计 {format_beijing(until)} 恢复。")
upload_max = self._upload_max(cfg)
if st == "uploading":
@ -916,7 +929,7 @@ class ShortsPipeline:
return done
except Exception as exc:
if self._handle_upload_error(claimed, exc):
raise ValueError(quota_error_message()) from exc
raise ValueError(quota_error_message(profile_id_for_job(claimed))) from exc
if "成片文件不存在" in str(exc):
refreshed = db.get_shorts_job(job_id) or claimed
if str(refreshed.get("youtube_video_id") or "").strip():
@ -1100,9 +1113,10 @@ class ShortsPipeline:
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
if "#Shorts" not in title and "#shorts" not in title.lower():
title = f"{title} #Shorts"
if not reserve_yt_upload_slot(cfg):
pause_uploads_until_reset(cfg)
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()}")
pid = profile_id_for_channel(channel)
if not reserve_yt_upload_slot(cfg, profile_id=pid):
pause_uploads_until_reset(cfg, profile_id=pid)
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message(pid)}")
result = await upload_shorts_mp4(
file_path=clip,
title=title,

View File

@ -26,10 +26,13 @@ def is_upload_quota_error(msg: str) -> bool:
return False
def quota_error_message() -> str:
def quota_error_message(profile_id: str = "") -> str:
pid = str(profile_id or "").strip().upper()
tag = f"【Client {pid}】" if pid else ""
return (
"YouTube 每日 Video Uploads 配额已用尽(429)。"
"上传已自动暂停,待太平洋时间 0 点配额重置后会继续。"
f"{tag}YouTube 每日 Video Uploads 配额已用尽(429)。"
"仅暂停该 OAuth 配置档下的频道上传,其他 Client(A/B/C/D)不受影响。"
"待太平洋时间 0 点配额重置后会继续。"
)

View File

@ -1,5 +1,9 @@
# -*- coding: utf-8 -*-
"""YouTube Data API project-level daily upload budget (Video Uploads bucket, PT day)."""
"""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
@ -10,6 +14,24 @@ 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:
@ -17,39 +39,110 @@ def yt_daily_limit(cfg: dict[str, Any] | None = None) -> int:
return max(1, int(settings.get("shorts_yt_daily_upload_limit") or YT_DAILY_UPLOAD_LIMIT_DEFAULT))
def _count_uploads_from_db_pt_day(day: str = "") -> int:
"""Best-effort count of upload API uses in the current Pacific day."""
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),
(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),
(start, end, *ch_ids),
).fetchone()
quota_fails = int(row3["c"] if row3 else 0)
return uploaded + in_flight + quota_fails
@ -57,82 +150,203 @@ def _count_uploads_from_db_pt_day(day: str = "") -> int:
conn.close()
def _sync_counter(cfg: dict[str, Any]) -> tuple[str, int]:
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(cfg.get("shorts_yt_uploads_pt_date") or "")
stored_count = int(cfg.get("shorts_yt_uploads_pt_count") or 0)
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(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
try:
db.update_settings_map(
{
"shorts_yt_uploads_pt_date": pt_day,
"shorts_yt_uploads_pt_count": stored_count,
}
)
except Exception:
pass
cfg["shorts_yt_uploads_pt_date"] = pt_day
cfg["shorts_yt_uploads_pt_count"] = stored_count
return pt_day, stored_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) -> tuple[int, int, int]:
"""Return (limit, used, remaining) for the current Pacific quota day."""
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)
_, used = _sync_counter(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) -> bool:
"""Reserve one upload slot before calling YouTube API. Returns False if budget exhausted."""
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())
limit, used, remaining = yt_upload_budget(settings)
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
pt_day = pacific_day_from_ts(time.time())
new_count = used + 1
try:
db.update_settings_map(
{
"shorts_yt_uploads_pt_date": pt_day,
"shorts_yt_uploads_pt_count": new_count,
}
)
except Exception:
pass
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) -> bool:
return yt_upload_budget(cfg)[2] > 0
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 pause_uploads_until_reset(cfg: dict[str, Any] | None = None, *, reason: str = "") -> float:
"""Block uploads until Pacific midnight and defer pending jobs."""
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()
patch: dict[str, Any] = {"shorts_yt_upload_blocked_until": until}
try:
db.update_settings_map(patch)
except Exception:
pass
defer_all_shorts_uploads(until, reason=reason or quota_error_message())
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_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
"""Reschedule all pending/uploading shorts jobs to after until_ts."""
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())[:400]
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 = ?,
@ -142,8 +356,9 @@ def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
WHERE status IN ('scheduled', 'uploading', 'recorded')
AND clip_path != ''
AND youtube_video_id = ''
AND channel_pk IN ({placeholders})
""",
(retry_at, msg, now),
(retry_at, msg, now, *ch_ids),
)
conn.commit()
return int(cur.rowcount)
@ -151,26 +366,65 @@ def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
conn.close()
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
"""If recent jobs/errors show quota exhaustion, activate global upload pause."""
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())
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
if until > time.time():
return True, until
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
limit, used, _ = yt_upload_budget(settings)
if used >= limit:
return True, pause_uploads_until_reset(settings, reason=quota_error_message())
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 error FROM shorts_jobs
SELECT id, channel_pk, error, updated_at FROM shorts_jobs
WHERE error != ''
ORDER BY updated_at DESC
LIMIT 30
LIMIT 40
""",
).fetchall()
finally:
@ -178,7 +432,18 @@ def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> tu
for row in rows:
err = str(row["error"] or "")
if is_upload_quota_error(err):
return True, pause_uploads_until_reset(settings, reason=quota_error_message())
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 False, 0.0
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)

View File

@ -950,23 +950,57 @@ export default function ShortsPage() {
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
{status?.upload_quota_blocked ? (
<div className="mb-3 rounded-xl border border-rose-500/30 bg-rose-500/10 px-3 py-2.5 text-xs text-rose-50">
<p className="font-medium text-rose-100">YouTube 每日 Video Uploads 配额已用尽</p>
<p className="font-medium text-rose-100">部分 Client 的 YouTube 上传配额已用尽</p>
<p className="mt-1 text-rose-100/90">
上传已自动暂停,不会在配额重置前反复重试。太平洋时间 0 点配额恢复后会继续排队上传。
{typeof status.yt_upload_used === "number" && typeof status.yt_upload_limit === "number" ? (
<> 今日已用 {status.yt_upload_used}/{status.yt_upload_limit} 次(太平洋日)。</>
) : null}
已暂停:
{(status.upload_quota_blocked_profiles || []).length
? (status.upload_quota_blocked_profiles as string[]).map((p) => `Client ${p}`).join("、")
: "未知"}
。其他 Client 仍可正常上传。
{status.upload_quota_blocked_until ? (
<> 预计恢复:{fmtTs(status.upload_quota_blocked_until)}(北京)</>
) : null}
</p>
{Array.isArray(status.yt_quota_by_profile) ? (
<div className="mt-2 flex flex-wrap gap-2">
{(status.yt_quota_by_profile as Array<any>).map((row) => (
<span
key={row.id}
className={`rounded border px-2 py-0.5 text-[10px] ${
row.blocked
? "border-rose-400/40 bg-rose-500/20 text-rose-100"
: "border-teal-400/30 bg-teal-500/10 text-teal-100"
}`}
>
Client {row.id} · {row.used}/{row.limit}
{row.blocked ? " · 已暂停" : ` · 剩 ${row.remaining}`}
</span>
))}
</div>
) : null}
<p className="mt-1 text-[11px] text-rose-200/70">
官方默认上限 100 次/天/项目;系统保守限制 {status.yt_upload_limit ?? 90} 次以防撞线。可在设置中调整 shorts_yt_daily_upload_limit。
配额按 OAuth Client A/B/C/D(不同 Google 项目)分别计算,互不影响。
</p>
</div>
) : Array.isArray(status?.yt_quota_by_profile) ? (
<div className="mb-3 flex flex-wrap gap-2 text-[11px] text-slate-400">
{(status.yt_quota_by_profile as Array<any>).map((row) => (
<span
key={row.id}
className={`rounded border px-2 py-0.5 ${
Number(row.remaining) <= 10
? "border-amber-500/30 bg-amber-500/10 text-amber-100"
: "border-white/10 bg-white/5"
}`}
>
Client {row.id} · {row.used}/{row.limit}(剩 {row.remaining})
</span>
))}
</div>
) : typeof status?.yt_upload_remaining === "number" && status.yt_upload_remaining <= 10 ? (
<div className="mb-3 rounded-xl border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-50">
YouTube 上传配额即将用尽:今日 {status.yt_upload_used ?? 0}/{status.yt_upload_limit ?? 90} 次(太平洋日),剩余 {status.yt_upload_remaining} 次。
YouTube 上传配额即将用尽:今日 {status.yt_upload_used ?? 0}/{status.yt_upload_limit ?? 90} 次(太平洋日),剩余{" "}
{status.yt_upload_remaining} 次。
</div>
) : status?.last_error ? (
<div className="mb-3 rounded-xl border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">