# -*- coding: utf-8 -*- """Clip retention + disk pressure guards. Policy: 1) Prefer rushing uploads for aging clips 2) Delete files older than max_age_hours when safe 3) Under disk pressure, purge oldest non-inflight clips aggressively """ from __future__ import annotations import shutil import time from pathlib import Path from typing import Any from .config import settings _DEFAULT_MAX_AGE_H = 24.0 _DEFAULT_MIN_FREE_GB = 12.0 def _max_age_sec(cfg: dict[str, Any]) -> float: try: h = float(cfg.get("clips_max_age_hours") or _DEFAULT_MAX_AGE_H) except Exception: h = _DEFAULT_MAX_AGE_H return max(1.0, min(168.0, h)) * 3600.0 def disk_free_gb(path: str | Path | None = None) -> float: try: usage = shutil.disk_usage(str(path or settings.clips_dir)) return float(usage.free) / (1024.0 ** 3) except Exception: return 999.0 def disk_ok_for_record(cfg: dict[str, Any] | None = None) -> tuple[bool, float]: """Block new long recordings when free space is too low.""" from . import db settings_map = cfg if cfg is not None else db.get_settings_map() try: min_free = float(settings_map.get("clips_min_free_gb") or _DEFAULT_MIN_FREE_GB) except Exception: min_free = _DEFAULT_MIN_FREE_GB min_free = max(4.0, min(40.0, min_free)) free = disk_free_gb() return free >= min_free, free def _iter_clip_files() -> list[Path]: root = Path(settings.clips_dir) out: list[Path] = [] if not root.is_dir(): return out for p in root.rglob("*.mp4"): try: if p.is_file(): out.append(p) except OSError: continue return out def _accelerate_jobs_for_path(path: str, now: float) -> int: from . import db n = 0 soon = now + 30.0 updates = ( ( "shorts_jobs", "UPDATE shorts_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = ''", ), ( "tiktok_jobs", "UPDATE tiktok_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(tiktok_video_id,'') = ''", ), ( "x_clip_jobs", "UPDATE x_clip_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(tweet_id,'') = ''", ), ( "yt_long_jobs", "UPDATE yt_long_jobs SET upload_at = ?, updated_at = ?, error = 'retention_rush' " "WHERE clip_path = ? AND status IN ('recorded','scheduled') AND IFNULL(youtube_video_id,'') = '' " "AND IFNULL(error,'') NOT LIKE 'cascade_only%'", ), ) try: with db._lock: conn = db._connect() try: for _name, sql in updates: try: cur = conn.execute(sql, (soon, now, path)) n += int(cur.rowcount or 0) except Exception: continue conn.commit() finally: conn.close() except Exception: pass return n def _clear_path_refs(path: str, now: float) -> None: from . import db try: with db._lock: conn = db._connect() try: # Shorts: clearing the file must also unstick scheduled/recorded jobs # so they re-enter pending (otherwise quota is consumed forever). try: conn.execute( """ UPDATE shorts_jobs SET clip_path = '', status = 'pending', upload_at = 0, clip_seconds = 0, error = '成片被清理,已重新排队录制', updated_at = ? WHERE clip_path = ? AND status IN ('recorded', 'scheduled') AND IFNULL(youtube_video_id, '') = '' """, (now, path), ) conn.execute( "UPDATE shorts_jobs SET clip_path = '', updated_at = ? WHERE clip_path = ?", (now, path), ) except Exception: pass for table in ("tiktok_jobs", "x_clip_jobs", "yt_long_jobs"): try: conn.execute( f"UPDATE {table} SET clip_path = '', updated_at = ? WHERE clip_path = ?", (now, path), ) except Exception: continue conn.commit() finally: conn.close() except Exception: pass def _job_still_needs_file(path: str) -> bool: from . import db checks = ( "SELECT 1 FROM shorts_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1", "SELECT 1 FROM tiktok_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1", "SELECT 1 FROM x_clip_jobs WHERE clip_path=? AND status IN ('posting','recording') LIMIT 1", "SELECT 1 FROM yt_long_jobs WHERE clip_path=? AND status IN ('uploading','recording') LIMIT 1", ) try: with db._lock: conn = db._connect() try: for sql in checks: try: if conn.execute(sql, (path,)).fetchone(): return True except Exception: continue finally: conn.close() except Exception: return True return False def unlink_clip(path: str, *, clear_refs: bool = True) -> bool: p = Path(str(path or "").strip()) if not str(p): return False try: if p.is_file(): try: from .clip_archive import archive_clip_for_path archive_clip_for_path(str(p)) except Exception: pass p.unlink() if clear_refs: _clear_path_refs(str(p), time.time()) try: _clear_path_refs(str(p.resolve()), time.time()) except OSError: pass return True except OSError: return False def purge_stale_clips(cfg: dict[str, Any] | None = None) -> dict[str, Any]: """Rush pending uploads for old clips, then delete by age / disk pressure.""" from . import db settings_map = cfg if cfg is not None else db.get_settings_map() max_age = _max_age_sec(settings_map) try: min_free = float(settings_map.get("clips_min_free_gb") or _DEFAULT_MIN_FREE_GB) except Exception: min_free = _DEFAULT_MIN_FREE_GB min_free = max(4.0, min(40.0, min_free)) now = time.time() rushed = 0 deleted = 0 skipped_inflight = 0 examined = 0 free_before = disk_free_gb() files = _iter_clip_files() # Oldest first helps pressure purge reclaim space quickly files.sort(key=lambda p: p.stat().st_mtime if p.exists() else now) for path in files: examined += 1 try: mtime = path.stat().st_mtime size = path.stat().st_size except OSError: continue age = now - mtime variants = {str(path)} try: variants.add(str(path.resolve())) except OSError: pass free_now = disk_free_gb() under_pressure = free_now < min_free # Under pressure: purge anything older than 2h that is not inflight # Normal: rush near expiry, delete past max_age if under_pressure: if age < 2 * 3600: continue else: if age < max_age * 0.85: continue if age < max_age: for sp in variants: rushed += _accelerate_jobs_for_path(sp, now) continue if any(_job_still_needs_file(sp) for sp in variants): skipped_inflight += 1 continue # cascade_only masters can be dropped immediately under pressure / age for sp in variants: _accelerate_jobs_for_path(sp, now) try: path.unlink(missing_ok=True) deleted += 1 for sp in variants: _clear_path_refs(sp, now) _ = size except OSError: continue if under_pressure and disk_free_gb() >= min_free: break covers_purge: dict[str, Any] = {} try: from . import s3_storage try: keep_days = float(settings_map.get("covers_s3_keep_days") or 2) except Exception: keep_days = 2.0 covers_purge = s3_storage.purge_covers_older_than(keep_days=keep_days) except Exception as exc: covers_purge = {"ok": False, "error": str(exc)[:160]} return { "ok": True, "examined": examined, "rushed": rushed, "deleted": deleted, "skipped_inflight": skipped_inflight, "max_age_hours": max_age / 3600.0, "free_gb_before": round(free_before, 2), "free_gb_after": round(disk_free_gb(), 2), "min_free_gb": min_free, "covers_s3": covers_purge, }