douyinWEB/backend/app/clip_retention.py
eric 896d8a64b3 fix: harden clip disk/CPU usage on small VPS
Cap long-form concurrency, delete masters after cascade/upload, restore post-upload deletes, shorten retention to 24h, and block recording when free disk is low.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-08-20 12:40:51 -05:00

258 lines
7.8 KiB
Python

# -*- 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,'') != '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:
for table in ("shorts_jobs", "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():
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
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,
}