# -*- coding: utf-8 -*- """YouTube Data API project-level daily upload budget (Video Uploads bucket, PT day).""" 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 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 _count_uploads_from_db_pt_day(day: str = "") -> int: """Best-effort count of upload API uses in the current Pacific day.""" pt_day = day or pacific_day_from_ts(time.time()) start, end = pacific_day_bounds(pt_day) with db._lock: conn = db._connect() try: row = conn.execute( """ SELECT COUNT(*) AS c FROM shorts_jobs WHERE youtube_video_id != '' AND finished_at >= ? AND finished_at < ? """, (start, end), ).fetchone() uploaded = int(row["c"] if row else 0) row2 = conn.execute( """ SELECT COUNT(*) AS c FROM shorts_jobs WHERE status = 'uploading' AND clip_path != '' AND youtube_video_id = '' """, ).fetchone() in_flight = int(row2["c"] if row2 else 0) row3 = conn.execute( """ SELECT COUNT(*) AS c FROM shorts_jobs WHERE status IN ('failed', 'scheduled') AND error LIKE '%429%' AND updated_at >= ? AND updated_at < ? """, (start, end), ).fetchone() quota_fails = int(row3["c"] if row3 else 0) return uploaded + in_flight + quota_fails finally: conn.close() def _sync_counter(cfg: dict[str, Any]) -> tuple[str, int]: 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) if stored_day != pt_day: db_count = _count_uploads_from_db_pt_day(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 def yt_upload_budget(cfg: dict[str, Any] | None = None) -> tuple[int, int, int]: """Return (limit, used, remaining) for the current Pacific quota day.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) limit = yt_daily_limit(settings) _, used = _sync_counter(settings) 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.""" settings = dict(cfg if cfg is not None else db.get_settings_map()) limit, used, remaining = yt_upload_budget(settings) 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 return True def project_uploads_available(cfg: dict[str, Any] | None = None) -> bool: return yt_upload_budget(cfg)[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.""" 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()) return until def defer_all_shorts_uploads(until_ts: float, *, reason: str = "") -> int: """Reschedule all pending/uploading shorts jobs to after until_ts.""" now = time.time() retry_at = max(until_ts, now) + 300 msg = (reason or quota_error_message())[:400] with db._lock: conn = db._connect() try: cur = conn.execute( """ 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 = '' """, (retry_at, msg, now), ) conn.commit() return int(cur.rowcount) finally: 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.""" 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 limit, used, _ = yt_upload_budget(settings) if used >= limit: return True, pause_uploads_until_reset(settings, reason=quota_error_message()) with db._lock: conn = db._connect() try: rows = conn.execute( """ SELECT error FROM shorts_jobs WHERE error != '' ORDER BY updated_at DESC LIMIT 30 """, ).fetchall() finally: conn.close() 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()) return False, 0.0