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:
parent
b752943d22
commit
c9df6be027
@ -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:
|
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."""
|
"""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)
|
channels = list_shorts_channels(enabled=True)
|
||||||
if not channels:
|
if not channels:
|
||||||
return None
|
return None
|
||||||
scored: list[tuple[int, int, float, dict[str, Any]]] = []
|
scored: list[tuple[int, int, float, dict[str, Any]]] = []
|
||||||
for ch in channels:
|
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)
|
used = shorts_channel_upload_count(str(ch["id"]), push_date)
|
||||||
daily_max = SHORTS_DAILY_FORCE
|
daily_max = SHORTS_DAILY_FORCE
|
||||||
if used >= daily_max:
|
if used >= daily_max:
|
||||||
@ -3218,43 +3219,59 @@ def update_shorts_job(job_id: str, **fields: Any) -> dict[str, Any] | None:
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def claim_due_shorts_upload() -> dict[str, Any] | None:
|
def claim_due_shorts_upload(*, skip_profile_ids: set[str] | None = None) -> dict[str, Any] | None:
|
||||||
"""Claim one due scheduled/recorded clip for upload."""
|
"""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()
|
now = time.time()
|
||||||
|
skip = {str(x).strip().upper() for x in (skip_profile_ids or set()) if str(x).strip()}
|
||||||
with _lock:
|
with _lock:
|
||||||
conn = _connect()
|
conn = _connect()
|
||||||
try:
|
try:
|
||||||
row = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM shorts_jobs
|
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
|
||||||
WHERE status = 'scheduled'
|
FROM shorts_jobs j
|
||||||
AND clip_path != ''
|
LEFT JOIN shorts_channels c ON c.id = j.channel_pk
|
||||||
AND youtube_video_id = ''
|
WHERE j.status = 'scheduled'
|
||||||
AND upload_at > 0
|
AND j.clip_path != ''
|
||||||
AND upload_at <= ?
|
AND j.youtube_video_id = ''
|
||||||
ORDER BY upload_at ASC, created_at ASC
|
AND j.upload_at > 0
|
||||||
LIMIT 1
|
AND j.upload_at <= ?
|
||||||
|
ORDER BY j.upload_at ASC, j.created_at ASC
|
||||||
|
LIMIT 30
|
||||||
""",
|
""",
|
||||||
(now,),
|
(now,),
|
||||||
).fetchone()
|
).fetchall()
|
||||||
if not row:
|
if not rows:
|
||||||
row = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT * FROM shorts_jobs
|
SELECT j.*, COALESCE(NULLIF(TRIM(c.oauth_profile_id), ''), 'A') AS oauth_profile_id
|
||||||
WHERE status = 'recorded'
|
FROM shorts_jobs j
|
||||||
AND clip_path != ''
|
LEFT JOIN shorts_channels c ON c.id = j.channel_pk
|
||||||
AND youtube_video_id = ''
|
WHERE j.status = 'recorded'
|
||||||
AND upload_at > 0
|
AND j.clip_path != ''
|
||||||
AND upload_at <= ?
|
AND j.youtube_video_id = ''
|
||||||
ORDER BY upload_at ASC
|
AND j.upload_at > 0
|
||||||
LIMIT 1
|
AND j.upload_at <= ?
|
||||||
|
ORDER BY j.upload_at ASC
|
||||||
|
LIMIT 30
|
||||||
""",
|
""",
|
||||||
(now,),
|
(now,),
|
||||||
).fetchone()
|
).fetchall()
|
||||||
if not row:
|
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
|
return None
|
||||||
jid = row["id"]
|
jid = picked["id"]
|
||||||
status = row["status"]
|
status = picked["status"]
|
||||||
conn.execute(
|
conn.execute(
|
||||||
"""
|
"""
|
||||||
UPDATE shorts_jobs
|
UPDATE shorts_jobs
|
||||||
|
|||||||
@ -18,14 +18,20 @@ from . import db
|
|||||||
from .shorts_clip import record_clip, resolve_stream_url
|
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_upload import is_upload_quota_error, quota_error_message, upload_shorts_mp4
|
||||||
from .shorts_yt_quota import (
|
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,
|
detect_and_block_from_recent_errors,
|
||||||
pause_uploads_until_reset,
|
pause_uploads_until_reset,
|
||||||
|
profile_id_for_channel,
|
||||||
|
profile_id_for_job,
|
||||||
|
profile_upload_blocked,
|
||||||
project_uploads_available,
|
project_uploads_available,
|
||||||
|
quota_budgets_by_profile,
|
||||||
reserve_yt_upload_slot,
|
reserve_yt_upload_slot,
|
||||||
yt_upload_budget,
|
yt_upload_budget,
|
||||||
)
|
)
|
||||||
from .timeutil import format_beijing, next_youtube_quota_reset_ts
|
from .timeutil import format_beijing, push_date_from_ts
|
||||||
from .timeutil import push_date_from_ts
|
|
||||||
|
|
||||||
|
|
||||||
def _room_tags(room: dict[str, Any]) -> list[str]:
|
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()
|
settings = cfg or db.get_settings_map()
|
||||||
if not settings.get("shorts_enabled"):
|
if not settings.get("shorts_enabled"):
|
||||||
return 0
|
return 0
|
||||||
if not project_uploads_available(settings):
|
if not any_profile_uploads_available(settings):
|
||||||
return 0
|
return 0
|
||||||
day = push_date_from_ts(time.time())
|
day = push_date_from_ts(time.time())
|
||||||
gap_total = db.shorts_total_quota_gap(day)
|
gap_total = db.shorts_total_quota_gap(day)
|
||||||
@ -442,23 +448,27 @@ class ShortsPipeline:
|
|||||||
)
|
)
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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)
|
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
|
||||||
try:
|
try:
|
||||||
detected, detected_until = detect_and_block_from_recent_errors(cfg)
|
paused = detect_and_block_from_recent_errors(cfg)
|
||||||
if detected:
|
if paused:
|
||||||
quota_blocked = True
|
quota_blocked = True
|
||||||
quota_until = max(quota_until, detected_until)
|
quota_until = max([quota_until, *paused.values()])
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
if not quota_blocked and is_upload_quota_error(self.last_error):
|
if not quota_blocked and is_upload_quota_error(self.last_error):
|
||||||
quota_until = next_youtube_quota_reset_ts()
|
# last_error may belong to one profile — do not freeze all Clients
|
||||||
try:
|
|
||||||
db.update_settings_map({"shorts_yt_upload_blocked_until": quota_until})
|
|
||||||
except Exception:
|
|
||||||
pass
|
pass
|
||||||
quota_blocked = True
|
last_error = self.last_error
|
||||||
last_error = quota_error_message() if quota_blocked else self.last_error
|
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg, profile_id="A")
|
||||||
yt_limit, yt_used, yt_remaining = yt_upload_budget(cfg)
|
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 {
|
return {
|
||||||
"running": bool(self._task and not self._task.done()),
|
"running": bool(self._task and not self._task.done()),
|
||||||
"busy": self._active_records > 0 or self._active_uploads > 0,
|
"busy": self._active_records > 0 or self._active_uploads > 0,
|
||||||
@ -472,11 +482,13 @@ class ShortsPipeline:
|
|||||||
"auto_retried": self.auto_retried,
|
"auto_retried": self.auto_retried,
|
||||||
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
|
"auto_retry_failed": bool(cfg.get("shorts_auto_retry_failed", True)),
|
||||||
"quota_gap": db.shorts_total_quota_gap(),
|
"quota_gap": db.shorts_total_quota_gap(),
|
||||||
"upload_quota_blocked": quota_blocked,
|
"upload_quota_blocked": any_blocked,
|
||||||
"upload_quota_blocked_until": quota_until,
|
"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_limit": yt_limit,
|
||||||
"yt_upload_used": yt_used,
|
"yt_upload_used": yt_used,
|
||||||
"yt_upload_remaining": yt_remaining,
|
"yt_upload_remaining": yt_remaining,
|
||||||
|
"yt_quota_by_profile": yt_by_profile,
|
||||||
"last_error": last_error,
|
"last_error": last_error,
|
||||||
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
|
"clip_sec": int(cfg.get("shorts_clip_sec") or 15),
|
||||||
"live_sample": bool(cfg.get("shorts_live_sample", True)),
|
"live_sample": bool(cfg.get("shorts_live_sample", True)),
|
||||||
@ -509,6 +521,7 @@ class ShortsPipeline:
|
|||||||
if self._task and not self._task.done():
|
if self._task and not self._task.done():
|
||||||
return
|
return
|
||||||
try:
|
try:
|
||||||
|
clear_stale_quota_errors_for_open_profiles()
|
||||||
detect_and_block_from_recent_errors()
|
detect_and_block_from_recent_errors()
|
||||||
except Exception:
|
except Exception:
|
||||||
pass
|
pass
|
||||||
@ -565,12 +578,8 @@ class ShortsPipeline:
|
|||||||
asyncio.create_task(self._probe_oauth(cfg))
|
asyncio.create_task(self._probe_oauth(cfg))
|
||||||
|
|
||||||
retry_interval = max(120.0, float(cfg.get("shorts_auto_retry_interval_sec") or 300))
|
retry_interval = max(120.0, float(cfg.get("shorts_auto_retry_interval_sec") or 300))
|
||||||
quota_blocked_loop, _ = self._upload_quota_blocked(cfg)
|
# Auto-retry failed jobs even if some Clients are quota-blocked (skip happens at claim)
|
||||||
if (
|
if cfg.get("shorts_auto_retry_failed", True) and (time.time() - self._last_auto_retry_at) >= retry_interval:
|
||||||
not quota_blocked_loop
|
|
||||||
and cfg.get("shorts_auto_retry_failed", True)
|
|
||||||
and (time.time() - self._last_auto_retry_at) >= retry_interval
|
|
||||||
):
|
|
||||||
self._last_auto_retry_at = time.time()
|
self._last_auto_retry_at = time.time()
|
||||||
try:
|
try:
|
||||||
n = self._auto_retry_failed(cfg)
|
n = self._auto_retry_failed(cfg)
|
||||||
@ -586,11 +595,7 @@ class ShortsPipeline:
|
|||||||
pass
|
pass
|
||||||
|
|
||||||
try:
|
try:
|
||||||
retry_at = 0.0
|
n = db.reclaim_stale_shorts_uploads(max_age_sec=180, 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)
|
|
||||||
if n:
|
if n:
|
||||||
self.last_error = ""
|
self.last_error = ""
|
||||||
except Exception:
|
except Exception:
|
||||||
@ -612,14 +617,11 @@ class ShortsPipeline:
|
|||||||
|
|
||||||
record_max = self._record_max(cfg)
|
record_max = self._record_max(cfg)
|
||||||
upload_max = self._upload_max(cfg)
|
upload_max = self._upload_max(cfg)
|
||||||
quota_blocked, quota_until = self._upload_quota_blocked(cfg)
|
skip_profiles = blocked_profile_ids(cfg)
|
||||||
if not quota_blocked and not project_uploads_available(cfg):
|
|
||||||
quota_until = pause_uploads_until_reset(cfg)
|
|
||||||
quota_blocked = True
|
|
||||||
job: dict[str, Any] | None = None
|
job: dict[str, Any] | None = None
|
||||||
runner: str = ""
|
runner: str = ""
|
||||||
if not quota_blocked and self._active_uploads < upload_max:
|
if self._active_uploads < upload_max:
|
||||||
job = db.claim_due_shorts_upload()
|
job = db.claim_due_shorts_upload(skip_profile_ids=skip_profiles)
|
||||||
if job:
|
if job:
|
||||||
runner = "upload"
|
runner = "upload"
|
||||||
if not job and self._active_records < record_max:
|
if not job and self._active_records < record_max:
|
||||||
@ -751,22 +753,29 @@ class ShortsPipeline:
|
|||||||
except Exception:
|
except Exception:
|
||||||
pass
|
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()
|
settings = cfg if cfg is not None else db.get_settings_map()
|
||||||
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
|
if profile_id:
|
||||||
now = time.time()
|
return profile_upload_blocked(settings, profile_id=profile_id)
|
||||||
if until <= now:
|
blocked = blocked_profile_ids(settings)
|
||||||
if until > 0:
|
if not blocked:
|
||||||
try:
|
|
||||||
db.update_settings_map({"shorts_yt_upload_blocked_until": 0})
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return False, 0.0
|
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
|
return True, until
|
||||||
|
|
||||||
def _pause_uploads_for_quota(self, job: dict[str, Any], raw_error: str) -> None:
|
def _pause_uploads_for_quota(self, job: dict[str, Any], raw_error: str) -> None:
|
||||||
until = pause_uploads_until_reset(reason=quota_error_message())
|
pid = profile_id_for_job(job)
|
||||||
friendly = quota_error_message()
|
until = pause_uploads_until_reset(profile_id=pid, reason=quota_error_message(pid))
|
||||||
|
friendly = quota_error_message(pid)
|
||||||
jid = str(job.get("id") or "")
|
jid = str(job.get("id") or "")
|
||||||
if jid:
|
if jid:
|
||||||
db.update_shorts_job(
|
db.update_shorts_job(
|
||||||
@ -780,9 +789,9 @@ class ShortsPipeline:
|
|||||||
self._emit_shorts_event(
|
self._emit_shorts_event(
|
||||||
kind="shorts_quota",
|
kind="shorts_quota",
|
||||||
level="warn",
|
level="warn",
|
||||||
message=f"Shorts 上传配额用尽,已暂停至 {format_beijing(until)}(太平洋 0 点重置)",
|
message=f"Client {pid} Shorts 上传配额用尽,仅暂停该配置档至 {format_beijing(until)}",
|
||||||
job=job,
|
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:
|
def _handle_upload_error(self, job: dict[str, Any], exc: Exception) -> bool:
|
||||||
@ -861,9 +870,13 @@ class ShortsPipeline:
|
|||||||
raise ValueError(f"状态 {st} 不可手动上传")
|
raise ValueError(f"状态 {st} 不可手动上传")
|
||||||
|
|
||||||
cfg = db.get_settings_map()
|
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:
|
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)
|
upload_max = self._upload_max(cfg)
|
||||||
if st == "uploading":
|
if st == "uploading":
|
||||||
@ -916,7 +929,7 @@ class ShortsPipeline:
|
|||||||
return done
|
return done
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
if self._handle_upload_error(claimed, 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):
|
if "成片文件不存在" in str(exc):
|
||||||
refreshed = db.get_shorts_job(job_id) or claimed
|
refreshed = db.get_shorts_job(job_id) or claimed
|
||||||
if str(refreshed.get("youtube_video_id") or "").strip():
|
if str(refreshed.get("youtube_video_id") or "").strip():
|
||||||
@ -1100,9 +1113,10 @@ class ShortsPipeline:
|
|||||||
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
desc = desc_tpl.replace("{anchor}", anchor).replace("{url}", url)
|
||||||
if "#Shorts" not in title and "#shorts" not in title.lower():
|
if "#Shorts" not in title and "#shorts" not in title.lower():
|
||||||
title = f"{title} #Shorts"
|
title = f"{title} #Shorts"
|
||||||
if not reserve_yt_upload_slot(cfg):
|
pid = profile_id_for_channel(channel)
|
||||||
pause_uploads_until_reset(cfg)
|
if not reserve_yt_upload_slot(cfg, profile_id=pid):
|
||||||
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message()}")
|
pause_uploads_until_reset(cfg, profile_id=pid)
|
||||||
|
raise ValueError(f"QUOTA_EXCEEDED: {quota_error_message(pid)}")
|
||||||
result = await upload_shorts_mp4(
|
result = await upload_shorts_mp4(
|
||||||
file_path=clip,
|
file_path=clip,
|
||||||
title=title,
|
title=title,
|
||||||
|
|||||||
@ -26,10 +26,13 @@ def is_upload_quota_error(msg: str) -> bool:
|
|||||||
return False
|
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 (
|
return (
|
||||||
"YouTube 每日 Video Uploads 配额已用尽(429)。"
|
f"{tag}YouTube 每日 Video Uploads 配额已用尽(429)。"
|
||||||
"上传已自动暂停,待太平洋时间 0 点配额重置后会继续。"
|
"仅暂停该 OAuth 配置档下的频道上传,其他 Client(A/B/C/D)不受影响。"
|
||||||
|
"待太平洋时间 0 点配额重置后会继续。"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@ -1,5 +1,9 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- 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
|
from __future__ import annotations
|
||||||
|
|
||||||
import time
|
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
|
from .timeutil import next_youtube_quota_reset_ts, pacific_day_bounds, pacific_day_from_ts
|
||||||
|
|
||||||
YT_DAILY_UPLOAD_LIMIT_DEFAULT = 90
|
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:
|
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))
|
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:
|
def _empty_entry() -> dict[str, Any]:
|
||||||
"""Best-effort count of upload API uses in the current Pacific day."""
|
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())
|
pt_day = day or pacific_day_from_ts(time.time())
|
||||||
start, end = pacific_day_bounds(pt_day)
|
start, end = pacific_day_bounds(pt_day)
|
||||||
with db._lock:
|
with db._lock:
|
||||||
conn = db._connect()
|
conn = db._connect()
|
||||||
try:
|
try:
|
||||||
row = conn.execute(
|
# 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
|
SELECT COUNT(*) AS c FROM shorts_jobs
|
||||||
WHERE youtube_video_id != ''
|
WHERE youtube_video_id != ''
|
||||||
AND finished_at >= ? AND finished_at < ?
|
AND finished_at >= ? AND finished_at < ?
|
||||||
|
AND channel_pk IN ({placeholders})
|
||||||
""",
|
""",
|
||||||
(start, end),
|
(start, end, *ch_ids),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
uploaded = int(row["c"] if row else 0)
|
uploaded = int(row["c"] if row else 0)
|
||||||
row2 = conn.execute(
|
row2 = conn.execute(
|
||||||
"""
|
f"""
|
||||||
SELECT COUNT(*) AS c FROM shorts_jobs
|
SELECT COUNT(*) AS c FROM shorts_jobs
|
||||||
WHERE status = 'uploading'
|
WHERE status = 'uploading'
|
||||||
AND clip_path != ''
|
AND clip_path != ''
|
||||||
AND youtube_video_id = ''
|
AND youtube_video_id = ''
|
||||||
|
AND channel_pk IN ({placeholders})
|
||||||
""",
|
""",
|
||||||
|
tuple(ch_ids),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
in_flight = int(row2["c"] if row2 else 0)
|
in_flight = int(row2["c"] if row2 else 0)
|
||||||
row3 = conn.execute(
|
row3 = conn.execute(
|
||||||
"""
|
f"""
|
||||||
SELECT COUNT(*) AS c FROM shorts_jobs
|
SELECT COUNT(*) AS c FROM shorts_jobs
|
||||||
WHERE status IN ('failed', 'scheduled')
|
WHERE status IN ('failed', 'scheduled')
|
||||||
AND error LIKE '%429%'
|
AND error LIKE '%429%'
|
||||||
AND updated_at >= ? AND updated_at < ?
|
AND updated_at >= ? AND updated_at < ?
|
||||||
|
AND channel_pk IN ({placeholders})
|
||||||
""",
|
""",
|
||||||
(start, end),
|
(start, end, *ch_ids),
|
||||||
).fetchone()
|
).fetchone()
|
||||||
quota_fails = int(row3["c"] if row3 else 0)
|
quota_fails = int(row3["c"] if row3 else 0)
|
||||||
return uploaded + in_flight + quota_fails
|
return uploaded + in_flight + quota_fails
|
||||||
@ -57,82 +150,203 @@ def _count_uploads_from_db_pt_day(day: str = "") -> int:
|
|||||||
conn.close()
|
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())
|
pt_day = pacific_day_from_ts(time.time())
|
||||||
stored_day = str(cfg.get("shorts_yt_uploads_pt_date") or "")
|
stored_day = str(entry.get("date") or "")
|
||||||
stored_count = int(cfg.get("shorts_yt_uploads_pt_count") or 0)
|
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:
|
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
|
stored_count = max(stored_count, db_count) if stored_day else db_count
|
||||||
try:
|
stored_day = pt_day
|
||||||
db.update_settings_map(
|
# New Pacific day clears block
|
||||||
{
|
blocked_until = 0.0
|
||||||
"shorts_yt_uploads_pt_date": pt_day,
|
entry = {"date": stored_day, "count": stored_count, "blocked_until": blocked_until}
|
||||||
"shorts_yt_uploads_pt_count": stored_count,
|
quota_map[pid] = entry
|
||||||
}
|
return entry
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
cfg["shorts_yt_uploads_pt_date"] = pt_day
|
|
||||||
cfg["shorts_yt_uploads_pt_count"] = stored_count
|
|
||||||
return pt_day, stored_count
|
|
||||||
|
|
||||||
|
|
||||||
def yt_upload_budget(cfg: dict[str, Any] | None = None) -> tuple[int, int, int]:
|
def yt_upload_budget(
|
||||||
"""Return (limit, used, remaining) for the current Pacific quota day."""
|
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())
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||||
limit = yt_daily_limit(settings)
|
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)
|
remaining = max(0, limit - used)
|
||||||
return limit, used, remaining
|
return limit, used, remaining
|
||||||
|
|
||||||
|
|
||||||
def reserve_yt_upload_slot(cfg: dict[str, Any] | None = None) -> bool:
|
def reserve_yt_upload_slot(
|
||||||
"""Reserve one upload slot before calling YouTube API. Returns False if budget exhausted."""
|
cfg: dict[str, Any] | None = None,
|
||||||
|
*,
|
||||||
|
profile_id: str = "A",
|
||||||
|
) -> bool:
|
||||||
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
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:
|
if remaining <= 0:
|
||||||
return False
|
return False
|
||||||
pt_day = pacific_day_from_ts(time.time())
|
quota_map = _load_quota_map(settings)
|
||||||
new_count = used + 1
|
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||||
try:
|
entry["count"] = int(entry.get("count") or 0) + 1
|
||||||
db.update_settings_map(
|
entry["date"] = pacific_day_from_ts(time.time())
|
||||||
{
|
quota_map[pid] = entry
|
||||||
"shorts_yt_uploads_pt_date": pt_day,
|
_save_quota_map(quota_map)
|
||||||
"shorts_yt_uploads_pt_count": new_count,
|
|
||||||
}
|
|
||||||
)
|
|
||||||
except Exception:
|
|
||||||
pass
|
|
||||||
return True
|
return True
|
||||||
|
|
||||||
|
|
||||||
def project_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
|
def project_uploads_available(
|
||||||
return yt_upload_budget(cfg)[2] > 0
|
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:
|
def any_profile_uploads_available(cfg: dict[str, Any] | None = None) -> bool:
|
||||||
"""Block uploads until Pacific midnight and defer pending jobs."""
|
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()
|
until = next_youtube_quota_reset_ts()
|
||||||
patch: dict[str, Any] = {"shorts_yt_upload_blocked_until": until}
|
quota_map = _load_quota_map(settings)
|
||||||
try:
|
entry = _sync_profile_entry(pid, settings, quota_map)
|
||||||
db.update_settings_map(patch)
|
entry["blocked_until"] = until
|
||||||
except Exception:
|
# Snap counter to limit so UI shows exhausted
|
||||||
pass
|
limit = yt_daily_limit(settings)
|
||||||
defer_all_shorts_uploads(until, reason=reason or quota_error_message())
|
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
|
return until
|
||||||
|
|
||||||
|
|
||||||
def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
|
def defer_profile_shorts_uploads(profile_id: str, until_ts: float, *, reason: str = "") -> int:
|
||||||
"""Reschedule all pending/uploading shorts jobs to after until_ts."""
|
"""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()
|
now = time.time()
|
||||||
retry_at = max(until_ts, now) + 300
|
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:
|
with db._lock:
|
||||||
conn = db._connect()
|
conn = db._connect()
|
||||||
try:
|
try:
|
||||||
cur = conn.execute(
|
cur = conn.execute(
|
||||||
"""
|
f"""
|
||||||
UPDATE shorts_jobs
|
UPDATE shorts_jobs
|
||||||
SET status = 'scheduled',
|
SET status = 'scheduled',
|
||||||
upload_at = ?,
|
upload_at = ?,
|
||||||
@ -142,8 +356,9 @@ def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
|
|||||||
WHERE status IN ('scheduled', 'uploading', 'recorded')
|
WHERE status IN ('scheduled', 'uploading', 'recorded')
|
||||||
AND clip_path != ''
|
AND clip_path != ''
|
||||||
AND youtube_video_id = ''
|
AND youtube_video_id = ''
|
||||||
|
AND channel_pk IN ({placeholders})
|
||||||
""",
|
""",
|
||||||
(retry_at, msg, now),
|
(retry_at, msg, now, *ch_ids),
|
||||||
)
|
)
|
||||||
conn.commit()
|
conn.commit()
|
||||||
return int(cur.rowcount)
|
return int(cur.rowcount)
|
||||||
@ -151,26 +366,65 @@ def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int:
|
|||||||
conn.close()
|
conn.close()
|
||||||
|
|
||||||
|
|
||||||
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> tuple[bool, float]:
|
def clear_stale_quota_errors_for_open_profiles(cfg: dict[str, Any] | None = None) -> int:
|
||||||
"""If recent jobs/errors show quota exhaustion, activate global upload pause."""
|
"""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())
|
settings = dict(cfg if cfg is not None else db.get_settings_map())
|
||||||
until = float(settings.get("shorts_yt_upload_blocked_until") or 0)
|
blocked = blocked_profile_ids(settings)
|
||||||
if until > time.time():
|
cleared = 0
|
||||||
return True, until
|
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:
|
def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> dict[str, float]:
|
||||||
return True, pause_uploads_until_reset(settings, reason=quota_error_message())
|
"""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:
|
with db._lock:
|
||||||
conn = db._connect()
|
conn = db._connect()
|
||||||
try:
|
try:
|
||||||
rows = conn.execute(
|
rows = conn.execute(
|
||||||
"""
|
"""
|
||||||
SELECT error FROM shorts_jobs
|
SELECT id, channel_pk, error, updated_at FROM shorts_jobs
|
||||||
WHERE error != ''
|
WHERE error != ''
|
||||||
ORDER BY updated_at DESC
|
ORDER BY updated_at DESC
|
||||||
LIMIT 30
|
LIMIT 40
|
||||||
""",
|
""",
|
||||||
).fetchall()
|
).fetchall()
|
||||||
finally:
|
finally:
|
||||||
@ -178,7 +432,18 @@ def detect_and_block_from_recent_errors(cfg: dict[str, Any] | None = None) -> tu
|
|||||||
|
|
||||||
for row in rows:
|
for row in rows:
|
||||||
err = str(row["error"] or "")
|
err = str(row["error"] or "")
|
||||||
if is_upload_quota_error(err):
|
if not is_upload_quota_error(err):
|
||||||
return True, pause_uploads_until_reset(settings, reason=quota_error_message())
|
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)
|
||||||
|
|||||||
@ -950,23 +950,57 @@ export default function ShortsPage() {
|
|||||||
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
|
{error ? <div className="mb-3 text-sm text-rose-300">{error}</div> : null}
|
||||||
{status?.upload_quota_blocked ? (
|
{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">
|
<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">
|
<p className="mt-1 text-rose-100/90">
|
||||||
上传已自动暂停,不会在配额重置前反复重试。太平洋时间 0 点配额恢复后会继续排队上传。
|
已暂停:
|
||||||
{typeof status.yt_upload_used === "number" && typeof status.yt_upload_limit === "number" ? (
|
{(status.upload_quota_blocked_profiles || []).length
|
||||||
<> 今日已用 {status.yt_upload_used}/{status.yt_upload_limit} 次(太平洋日)。</>
|
? (status.upload_quota_blocked_profiles as string[]).map((p) => `Client ${p}`).join("、")
|
||||||
) : null}
|
: "未知"}
|
||||||
|
。其他 Client 仍可正常上传。
|
||||||
{status.upload_quota_blocked_until ? (
|
{status.upload_quota_blocked_until ? (
|
||||||
<> 预计恢复:{fmtTs(status.upload_quota_blocked_until)}(北京)</>
|
<> 预计恢复:{fmtTs(status.upload_quota_blocked_until)}(北京)</>
|
||||||
) : null}
|
) : null}
|
||||||
</p>
|
</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">
|
<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>
|
</p>
|
||||||
</div>
|
</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 ? (
|
) : 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">
|
<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>
|
</div>
|
||||||
) : status?.last_error ? (
|
) : 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">
|
<div className="mb-3 rounded-xl border border-amber-500/25 bg-amber-500/10 px-3 py-2 text-xs text-amber-100">
|
||||||
|
|||||||
Loading…
Reference in New Issue
Block a user