library_trash.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  1. """Library trash sweeper + purge service (#1008).
  2. Two-stage file deletion for the library:
  3. 1. Users / admins soft-delete files — the row stays in ``library_files`` with
  4. ``deleted_at`` stamped; the bytes stay on disk. This is handled inline in
  5. ``backend.app.api.routes.library`` and exposed to admins as a bulk "purge
  6. old files" operation via :meth:`LibraryTrashService.purge_older_than`.
  7. 2. A background sweeper in this service hard-deletes rows (and their bytes)
  8. whose ``deleted_at`` is older than the configured retention window.
  9. External files (``is_external=True``) are never placed in the trash — their
  10. bytes live outside Bambuddy's control, so there's nothing to restore.
  11. """
  12. from __future__ import annotations
  13. import asyncio
  14. import logging
  15. from datetime import datetime, timedelta, timezone
  16. from pathlib import Path
  17. from sqlalchemy import and_, delete, func, or_, select
  18. from sqlalchemy.ext.asyncio import AsyncSession
  19. from backend.app.core.config import settings as app_settings
  20. from backend.app.core.database import async_session
  21. from backend.app.models.library import LibraryFile
  22. from backend.app.models.print_queue import PrintQueueVariant
  23. from backend.app.models.settings import Settings
  24. logger = logging.getLogger(__name__)
  25. # Settings key used to persist the trash retention window (days). The sweeper
  26. # reads this on every tick so the UI can change it without a restart.
  27. TRASH_RETENTION_KEY = "library_trash_retention_days"
  28. DEFAULT_RETENTION_DAYS = 30
  29. # Clamp retention to a sensible range. 1 day is a reasonable floor (anything
  30. # shorter just makes trash into hard-delete); 365 gives admins plenty of rope
  31. # without letting accidental typos (99999) grow the table unboundedly.
  32. MIN_RETENTION_DAYS = 1
  33. MAX_RETENTION_DAYS = 365
  34. # Auto-purge settings (#1008 follow-up). When enabled, the sweeper loop also
  35. # runs the admin bulk purge once per 24h using the saved age threshold.
  36. # Default-off so existing installs don't surprise users — opt-in via Settings.
  37. AUTO_PURGE_ENABLED_KEY = "library_auto_purge_enabled"
  38. AUTO_PURGE_DAYS_KEY = "library_auto_purge_days"
  39. AUTO_PURGE_INCLUDE_NEVER_PRINTED_KEY = "library_auto_purge_include_never_printed"
  40. AUTO_PURGE_LAST_RUN_KEY = "library_auto_purge_last_run"
  41. DEFAULT_AUTO_PURGE_DAYS = 90
  42. MIN_AUTO_PURGE_DAYS = 7 # anything shorter is begging for accidents
  43. MAX_AUTO_PURGE_DAYS = 3650
  44. def _to_absolute_path(relative_path: str | None) -> Path | None:
  45. """Mirror of the routes helper so this service has no route-module import.
  46. Accepts the legacy absolute paths that predate the relative-path migration
  47. verbatim; new rows always store paths relative to ``base_dir``.
  48. """
  49. if not relative_path:
  50. return None
  51. path = Path(relative_path)
  52. if path.is_absolute():
  53. return path
  54. return (
  55. Path(app_settings.base_dir) / path
  56. ) # SEC-PATH-OK: relative_path is LibraryFile.file_path / LibraryFile.thumbnail_path — DB-stored, internally generated by the upload pipeline
  57. def _age_cutoff(now: datetime, older_than_days: int) -> datetime:
  58. return now - timedelta(days=older_than_days)
  59. def _purge_filter(cutoff: datetime, include_never_printed: bool):
  60. """SQLAlchemy clause selecting files eligible for admin purge.
  61. A file is "old" if either (a) ``last_printed_at`` is set and predates the
  62. cutoff, or (b) ``last_printed_at`` is NULL *and* the file was uploaded
  63. before the cutoff — but only when ``include_never_printed`` is True.
  64. """
  65. last_printed_old = and_(
  66. LibraryFile.last_printed_at.isnot(None),
  67. LibraryFile.last_printed_at < cutoff,
  68. )
  69. if include_never_printed:
  70. never_printed_old = and_(
  71. LibraryFile.last_printed_at.is_(None),
  72. LibraryFile.created_at < cutoff,
  73. )
  74. age_clause = or_(last_printed_old, never_printed_old)
  75. else:
  76. age_clause = last_printed_old
  77. return and_(
  78. LibraryFile.deleted_at.is_(None),
  79. LibraryFile.is_external.is_(False),
  80. age_clause,
  81. )
  82. class LibraryTrashService:
  83. """Manages the trash retention sweeper and admin-triggered bulk purges."""
  84. def __init__(self):
  85. self._scheduler_task: asyncio.Task | None = None
  86. # Tick every 15 minutes — the window is a day, so this is plenty
  87. # responsive without burning CPU.
  88. self._check_interval = 900
  89. async def start_scheduler(self):
  90. """Start the background sweeper task (idempotent)."""
  91. if self._scheduler_task is not None:
  92. return
  93. logger.info("Starting library trash sweeper")
  94. self._scheduler_task = asyncio.create_task(self._scheduler_loop())
  95. def stop_scheduler(self):
  96. if self._scheduler_task:
  97. self._scheduler_task.cancel()
  98. self._scheduler_task = None
  99. logger.info("Stopped library trash sweeper")
  100. async def _scheduler_loop(self):
  101. while True:
  102. try:
  103. await asyncio.sleep(self._check_interval)
  104. async with async_session() as db:
  105. await self._sweep(db)
  106. await self._maybe_run_auto_purge(db)
  107. except asyncio.CancelledError:
  108. break
  109. except Exception as e: # pragma: no cover - defensive
  110. logger.error("Error in library trash sweeper: %s", e)
  111. await asyncio.sleep(60)
  112. # ---- Settings -----------------------------------------------------
  113. async def get_retention_days(self, db: AsyncSession | None = None) -> int:
  114. if db is None:
  115. async with async_session() as session:
  116. return await self._read_retention(session)
  117. return await self._read_retention(db)
  118. @staticmethod
  119. async def _read_retention(db: AsyncSession) -> int:
  120. result = await db.execute(select(Settings.value).where(Settings.key == TRASH_RETENTION_KEY))
  121. raw = result.scalar_one_or_none()
  122. if raw is None:
  123. return DEFAULT_RETENTION_DAYS
  124. try:
  125. days = int(raw)
  126. except (TypeError, ValueError):
  127. return DEFAULT_RETENTION_DAYS
  128. return max(MIN_RETENTION_DAYS, min(MAX_RETENTION_DAYS, days))
  129. async def set_retention_days(self, db: AsyncSession, days: int) -> int:
  130. """Persist the retention window. Clamped to [MIN, MAX]."""
  131. clamped = max(MIN_RETENTION_DAYS, min(MAX_RETENTION_DAYS, int(days)))
  132. result = await db.execute(select(Settings).where(Settings.key == TRASH_RETENTION_KEY))
  133. row = result.scalar_one_or_none()
  134. if row is None:
  135. db.add(Settings(key=TRASH_RETENTION_KEY, value=str(clamped)))
  136. else:
  137. row.value = str(clamped)
  138. await db.commit()
  139. return clamped
  140. @staticmethod
  141. async def _read_setting(db: AsyncSession, key: str) -> str | None:
  142. result = await db.execute(select(Settings.value).where(Settings.key == key))
  143. return result.scalar_one_or_none()
  144. @staticmethod
  145. async def _write_setting(db: AsyncSession, key: str, value: str) -> None:
  146. result = await db.execute(select(Settings).where(Settings.key == key))
  147. row = result.scalar_one_or_none()
  148. if row is None:
  149. db.add(Settings(key=key, value=value))
  150. else:
  151. row.value = value
  152. async def get_auto_purge_settings(self, db: AsyncSession) -> dict:
  153. """Return the current auto-purge config.
  154. Returns a dict with ``enabled`` (bool), ``days`` (int, clamped) and
  155. ``include_never_printed`` (bool). Missing keys default to disabled /
  156. 90 days / include-never-printed-on, matching the manual purge UX.
  157. """
  158. enabled_raw = await self._read_setting(db, AUTO_PURGE_ENABLED_KEY)
  159. days_raw = await self._read_setting(db, AUTO_PURGE_DAYS_KEY)
  160. incl_raw = await self._read_setting(db, AUTO_PURGE_INCLUDE_NEVER_PRINTED_KEY)
  161. enabled = (enabled_raw or "false").lower() == "true"
  162. try:
  163. days = int(days_raw) if days_raw is not None else DEFAULT_AUTO_PURGE_DAYS
  164. except (TypeError, ValueError):
  165. days = DEFAULT_AUTO_PURGE_DAYS
  166. days = max(MIN_AUTO_PURGE_DAYS, min(MAX_AUTO_PURGE_DAYS, days))
  167. include_never_printed = (incl_raw or "true").lower() == "true"
  168. return {
  169. "enabled": enabled,
  170. "days": days,
  171. "include_never_printed": include_never_printed,
  172. }
  173. async def set_auto_purge_settings(
  174. self,
  175. db: AsyncSession,
  176. *,
  177. enabled: bool,
  178. days: int,
  179. include_never_printed: bool,
  180. ) -> dict:
  181. """Persist auto-purge config; returns the saved (clamped) values."""
  182. clamped_days = max(MIN_AUTO_PURGE_DAYS, min(MAX_AUTO_PURGE_DAYS, int(days)))
  183. await self._write_setting(db, AUTO_PURGE_ENABLED_KEY, "true" if enabled else "false")
  184. await self._write_setting(db, AUTO_PURGE_DAYS_KEY, str(clamped_days))
  185. await self._write_setting(
  186. db,
  187. AUTO_PURGE_INCLUDE_NEVER_PRINTED_KEY,
  188. "true" if include_never_printed else "false",
  189. )
  190. await db.commit()
  191. return {
  192. "enabled": enabled,
  193. "days": clamped_days,
  194. "include_never_printed": include_never_printed,
  195. }
  196. async def _get_last_auto_purge_run(self, db: AsyncSession) -> datetime | None:
  197. raw = await self._read_setting(db, AUTO_PURGE_LAST_RUN_KEY)
  198. if not raw:
  199. return None
  200. try:
  201. # Stored as ISO 8601 UTC; tolerate both with and without 'Z' suffix.
  202. return datetime.fromisoformat(raw.replace("Z", "+00:00"))
  203. except ValueError:
  204. return None
  205. async def _stamp_last_auto_purge_run(self, db: AsyncSession, when: datetime) -> None:
  206. await self._write_setting(db, AUTO_PURGE_LAST_RUN_KEY, when.isoformat())
  207. await db.commit()
  208. async def _maybe_run_auto_purge(self, db: AsyncSession) -> int:
  209. """If auto-purge is enabled and >=24h has elapsed since the last run, run it.
  210. Returns the number of files moved to trash (0 if disabled or throttled).
  211. The 24h throttle means a 15-minute sweeper cadence still only triggers
  212. one actual purge per day, keeping the DB churn predictable.
  213. """
  214. cfg = await self.get_auto_purge_settings(db)
  215. if not cfg["enabled"]:
  216. return 0
  217. now = datetime.now(timezone.utc)
  218. last = await self._get_last_auto_purge_run(db)
  219. if last is not None and (now - last) < timedelta(hours=24):
  220. return 0
  221. moved = await self.purge_older_than(
  222. db,
  223. older_than_days=cfg["days"],
  224. include_never_printed=cfg["include_never_printed"],
  225. )
  226. await self._stamp_last_auto_purge_run(db, now)
  227. if moved:
  228. logger.info("Library auto-purge: moved %d file(s) to trash (threshold=%d days)", moved, cfg["days"])
  229. return moved
  230. # ---- Preview / purge ---------------------------------------------
  231. async def preview_purge(
  232. self,
  233. db: AsyncSession,
  234. older_than_days: int,
  235. include_never_printed: bool = True,
  236. sample_limit: int = 5,
  237. ) -> dict:
  238. """Count + size of files eligible for purge. Reads only; never mutates."""
  239. if older_than_days < 1:
  240. return {"count": 0, "total_bytes": 0, "sample_filenames": []}
  241. now = datetime.now(timezone.utc)
  242. cutoff = _age_cutoff(now, older_than_days)
  243. clause = _purge_filter(cutoff, include_never_printed)
  244. count_result = await db.execute(select(func.count(LibraryFile.id)).where(clause))
  245. count = int(count_result.scalar() or 0)
  246. size_result = await db.execute(select(func.coalesce(func.sum(LibraryFile.file_size), 0)).where(clause))
  247. total_bytes = int(size_result.scalar() or 0)
  248. sample_result = await db.execute(
  249. select(LibraryFile.filename).where(clause).order_by(LibraryFile.created_at).limit(sample_limit)
  250. )
  251. samples = [row[0] for row in sample_result.all()]
  252. return {
  253. "count": count,
  254. "total_bytes": total_bytes,
  255. "sample_filenames": samples,
  256. "older_than_days": older_than_days,
  257. "include_never_printed": include_never_printed,
  258. }
  259. async def purge_older_than(
  260. self,
  261. db: AsyncSession,
  262. older_than_days: int,
  263. include_never_printed: bool = True,
  264. ) -> int:
  265. """Move matching files to trash (stamps ``deleted_at``). Returns count."""
  266. if older_than_days < 1:
  267. return 0
  268. now = datetime.now(timezone.utc)
  269. cutoff = _age_cutoff(now, older_than_days)
  270. clause = _purge_filter(cutoff, include_never_printed)
  271. # We need the IDs so callers can audit or display them if they want.
  272. # Doing a single UPDATE ... WHERE is safe even under concurrent
  273. # uploads — the clause already excludes rows with deleted_at set.
  274. id_result = await db.execute(select(LibraryFile.id).where(clause))
  275. ids = [row[0] for row in id_result.all()]
  276. if not ids:
  277. return 0
  278. await db.execute(LibraryFile.__table__.update().where(LibraryFile.id.in_(ids)).values(deleted_at=now))
  279. await db.commit()
  280. logger.info("Library purge: moved %d file(s) to trash (older_than_days=%d)", len(ids), older_than_days)
  281. return len(ids)
  282. # ---- Sweeper ------------------------------------------------------
  283. async def _sweep(self, db: AsyncSession) -> int:
  284. """Hard-delete trashed rows whose retention window has elapsed."""
  285. retention = await self._read_retention(db)
  286. now = datetime.now(timezone.utc)
  287. cutoff = now - timedelta(days=retention)
  288. result = await db.execute(
  289. select(LibraryFile).where(
  290. LibraryFile.deleted_at.isnot(None),
  291. LibraryFile.deleted_at < cutoff,
  292. )
  293. )
  294. rows = result.scalars().all()
  295. if not rows:
  296. return 0
  297. deleted = 0
  298. for row in rows:
  299. self._unlink_on_disk(row)
  300. deleted += 1
  301. await delete_dependent_variants(db, [r.id for r in rows])
  302. # Single DELETE is faster than N await db.delete() round-trips; we
  303. # still need the Python loop above to unlink bytes on disk.
  304. await db.execute(delete(LibraryFile).where(LibraryFile.id.in_([r.id for r in rows])))
  305. await db.commit()
  306. logger.info("Library trash sweeper: hard-deleted %d row(s) past %d-day retention", deleted, retention)
  307. return deleted
  308. @staticmethod
  309. def _unlink_on_disk(row: LibraryFile) -> None:
  310. """Best-effort cleanup of the file + thumbnail on disk."""
  311. for rel in (row.file_path, row.thumbnail_path):
  312. abs_path = _to_absolute_path(rel)
  313. if abs_path is None:
  314. continue
  315. try:
  316. if abs_path.exists():
  317. abs_path.unlink()
  318. except OSError as e:
  319. logger.warning("Trash sweep: failed to unlink %s: %s", abs_path, e)
  320. # ---- User-facing trash ops ----------------------------------------
  321. async def restore(self, db: AsyncSession, file: LibraryFile) -> LibraryFile:
  322. """Clear ``deleted_at`` so the file reappears in listings."""
  323. file.deleted_at = None
  324. await db.commit()
  325. await db.refresh(file)
  326. return file
  327. async def hard_delete_now(self, db: AsyncSession, file: LibraryFile) -> None:
  328. """Bypass retention and delete this trashed file + its bytes immediately."""
  329. self._unlink_on_disk(file)
  330. await delete_dependent_variants(db, [file.id])
  331. await db.delete(file)
  332. await db.commit()
  333. async def delete_dependent_variants(db: AsyncSession, file_ids: list[int]) -> None:
  334. """Drop cross-model queue candidates that pointed at these files (#671).
  335. SQLite ships with ``PRAGMA foreign_keys`` off — verified, not assumed — so
  336. the ON DELETE CASCADE on ``print_queue_variants.library_file_id`` never fires
  337. on the default deployment and the rows would outlive the file.
  338. The scheduler already refuses to dispatch a candidate whose file is missing
  339. or trashed, so nothing prints wrongly without this. It is here so the table
  340. does not fill with rows referencing files that no longer exist.
  341. """
  342. if not file_ids:
  343. return
  344. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id.in_(file_ids)))
  345. library_trash_service = LibraryTrashService()