library_trash.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  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 PrintQueueItem, PrintQueueVariant
  23. from backend.app.models.settings import Settings
  24. from backend.app.utils.local_time import utcnow_naive
  25. logger = logging.getLogger(__name__)
  26. # Settings key used to persist the trash retention window (days). The sweeper
  27. # reads this on every tick so the UI can change it without a restart.
  28. TRASH_RETENTION_KEY = "library_trash_retention_days"
  29. DEFAULT_RETENTION_DAYS = 30
  30. # Clamp retention to a sensible range. 1 day is a reasonable floor (anything
  31. # shorter just makes trash into hard-delete); 365 gives admins plenty of rope
  32. # without letting accidental typos (99999) grow the table unboundedly.
  33. MIN_RETENTION_DAYS = 1
  34. MAX_RETENTION_DAYS = 365
  35. # Auto-purge settings (#1008 follow-up). When enabled, the sweeper loop also
  36. # runs the admin bulk purge once per 24h using the saved age threshold.
  37. # Default-off so existing installs don't surprise users — opt-in via Settings.
  38. AUTO_PURGE_ENABLED_KEY = "library_auto_purge_enabled"
  39. AUTO_PURGE_DAYS_KEY = "library_auto_purge_days"
  40. AUTO_PURGE_INCLUDE_NEVER_PRINTED_KEY = "library_auto_purge_include_never_printed"
  41. AUTO_PURGE_LAST_RUN_KEY = "library_auto_purge_last_run"
  42. DEFAULT_AUTO_PURGE_DAYS = 90
  43. MIN_AUTO_PURGE_DAYS = 7 # anything shorter is begging for accidents
  44. MAX_AUTO_PURGE_DAYS = 3650
  45. def _to_absolute_path(relative_path: str | None) -> Path | None:
  46. """Mirror of the routes helper so this service has no route-module import.
  47. Accepts the legacy absolute paths that predate the relative-path migration
  48. verbatim; new rows always store paths relative to ``base_dir``.
  49. """
  50. if not relative_path:
  51. return None
  52. path = Path(relative_path)
  53. if path.is_absolute():
  54. return path
  55. return (
  56. Path(app_settings.base_dir) / path
  57. ) # SEC-PATH-OK: relative_path is LibraryFile.file_path / LibraryFile.thumbnail_path — DB-stored, internally generated by the upload pipeline
  58. def _age_cutoff(now: datetime, older_than_days: int) -> datetime:
  59. return now - timedelta(days=older_than_days)
  60. def _purge_filter(cutoff: datetime, include_never_printed: bool):
  61. """SQLAlchemy clause selecting files eligible for admin purge.
  62. A file is "old" if either (a) ``last_printed_at`` is set and predates the
  63. cutoff, or (b) ``last_printed_at`` is NULL *and* the file was uploaded
  64. before the cutoff — but only when ``include_never_printed`` is True.
  65. """
  66. last_printed_old = and_(
  67. LibraryFile.last_printed_at.isnot(None),
  68. LibraryFile.last_printed_at < cutoff,
  69. )
  70. if include_never_printed:
  71. never_printed_old = and_(
  72. LibraryFile.last_printed_at.is_(None),
  73. LibraryFile.created_at < cutoff,
  74. )
  75. age_clause = or_(last_printed_old, never_printed_old)
  76. else:
  77. age_clause = last_printed_old
  78. return and_(
  79. LibraryFile.deleted_at.is_(None),
  80. LibraryFile.is_external.is_(False),
  81. age_clause,
  82. )
  83. class LibraryTrashService:
  84. """Manages the trash retention sweeper and admin-triggered bulk purges."""
  85. def __init__(self):
  86. self._scheduler_task: asyncio.Task | None = None
  87. # Tick every 15 minutes — the window is a day, so this is plenty
  88. # responsive without burning CPU.
  89. self._check_interval = 900
  90. async def start_scheduler(self):
  91. """Start the background sweeper task (idempotent)."""
  92. if self._scheduler_task is not None:
  93. return
  94. logger.info("Starting library trash sweeper")
  95. self._scheduler_task = asyncio.create_task(self._scheduler_loop())
  96. def stop_scheduler(self):
  97. if self._scheduler_task:
  98. self._scheduler_task.cancel()
  99. self._scheduler_task = None
  100. logger.info("Stopped library trash sweeper")
  101. async def _scheduler_loop(self):
  102. while True:
  103. try:
  104. await asyncio.sleep(self._check_interval)
  105. async with async_session() as db:
  106. await self._sweep(db)
  107. await self._maybe_run_auto_purge(db)
  108. except asyncio.CancelledError:
  109. break
  110. except Exception as e: # pragma: no cover - defensive
  111. logger.error("Error in library trash sweeper: %s", e)
  112. await asyncio.sleep(60)
  113. # ---- Settings -----------------------------------------------------
  114. async def get_retention_days(self, db: AsyncSession | None = None) -> int:
  115. if db is None:
  116. async with async_session() as session:
  117. return await self._read_retention(session)
  118. return await self._read_retention(db)
  119. @staticmethod
  120. async def _read_retention(db: AsyncSession) -> int:
  121. result = await db.execute(select(Settings.value).where(Settings.key == TRASH_RETENTION_KEY))
  122. raw = result.scalar_one_or_none()
  123. if raw is None:
  124. return DEFAULT_RETENTION_DAYS
  125. try:
  126. days = int(raw)
  127. except (TypeError, ValueError):
  128. return DEFAULT_RETENTION_DAYS
  129. return max(MIN_RETENTION_DAYS, min(MAX_RETENTION_DAYS, days))
  130. async def set_retention_days(self, db: AsyncSession, days: int) -> int:
  131. """Persist the retention window. Clamped to [MIN, MAX]."""
  132. clamped = max(MIN_RETENTION_DAYS, min(MAX_RETENTION_DAYS, int(days)))
  133. result = await db.execute(select(Settings).where(Settings.key == TRASH_RETENTION_KEY))
  134. row = result.scalar_one_or_none()
  135. if row is None:
  136. db.add(Settings(key=TRASH_RETENTION_KEY, value=str(clamped)))
  137. else:
  138. row.value = str(clamped)
  139. await db.commit()
  140. return clamped
  141. @staticmethod
  142. async def _read_setting(db: AsyncSession, key: str) -> str | None:
  143. result = await db.execute(select(Settings.value).where(Settings.key == key))
  144. return result.scalar_one_or_none()
  145. @staticmethod
  146. async def _write_setting(db: AsyncSession, key: str, value: str) -> None:
  147. result = await db.execute(select(Settings).where(Settings.key == key))
  148. row = result.scalar_one_or_none()
  149. if row is None:
  150. db.add(Settings(key=key, value=value))
  151. else:
  152. row.value = value
  153. async def get_auto_purge_settings(self, db: AsyncSession) -> dict:
  154. """Return the current auto-purge config.
  155. Returns a dict with ``enabled`` (bool), ``days`` (int, clamped) and
  156. ``include_never_printed`` (bool). Missing keys default to disabled /
  157. 90 days / include-never-printed-on, matching the manual purge UX.
  158. """
  159. enabled_raw = await self._read_setting(db, AUTO_PURGE_ENABLED_KEY)
  160. days_raw = await self._read_setting(db, AUTO_PURGE_DAYS_KEY)
  161. incl_raw = await self._read_setting(db, AUTO_PURGE_INCLUDE_NEVER_PRINTED_KEY)
  162. enabled = (enabled_raw or "false").lower() == "true"
  163. try:
  164. days = int(days_raw) if days_raw is not None else DEFAULT_AUTO_PURGE_DAYS
  165. except (TypeError, ValueError):
  166. days = DEFAULT_AUTO_PURGE_DAYS
  167. days = max(MIN_AUTO_PURGE_DAYS, min(MAX_AUTO_PURGE_DAYS, days))
  168. include_never_printed = (incl_raw or "true").lower() == "true"
  169. return {
  170. "enabled": enabled,
  171. "days": days,
  172. "include_never_printed": include_never_printed,
  173. }
  174. async def set_auto_purge_settings(
  175. self,
  176. db: AsyncSession,
  177. *,
  178. enabled: bool,
  179. days: int,
  180. include_never_printed: bool,
  181. ) -> dict:
  182. """Persist auto-purge config; returns the saved (clamped) values."""
  183. clamped_days = max(MIN_AUTO_PURGE_DAYS, min(MAX_AUTO_PURGE_DAYS, int(days)))
  184. await self._write_setting(db, AUTO_PURGE_ENABLED_KEY, "true" if enabled else "false")
  185. await self._write_setting(db, AUTO_PURGE_DAYS_KEY, str(clamped_days))
  186. await self._write_setting(
  187. db,
  188. AUTO_PURGE_INCLUDE_NEVER_PRINTED_KEY,
  189. "true" if include_never_printed else "false",
  190. )
  191. await db.commit()
  192. return {
  193. "enabled": enabled,
  194. "days": clamped_days,
  195. "include_never_printed": include_never_printed,
  196. }
  197. async def _get_last_auto_purge_run(self, db: AsyncSession) -> datetime | None:
  198. raw = await self._read_setting(db, AUTO_PURGE_LAST_RUN_KEY)
  199. if not raw:
  200. return None
  201. try:
  202. # Stored as ISO 8601 UTC; tolerate both with and without 'Z' suffix.
  203. return datetime.fromisoformat(raw.replace("Z", "+00:00"))
  204. except ValueError:
  205. return None
  206. async def _stamp_last_auto_purge_run(self, db: AsyncSession, when: datetime) -> None:
  207. await self._write_setting(db, AUTO_PURGE_LAST_RUN_KEY, when.isoformat())
  208. await db.commit()
  209. async def _maybe_run_auto_purge(self, db: AsyncSession) -> int:
  210. """If auto-purge is enabled and >=24h has elapsed since the last run, run it.
  211. Returns the number of files moved to trash (0 if disabled or throttled).
  212. The 24h throttle means a 15-minute sweeper cadence still only triggers
  213. one actual purge per day, keeping the DB churn predictable.
  214. """
  215. cfg = await self.get_auto_purge_settings(db)
  216. if not cfg["enabled"]:
  217. return 0
  218. now = datetime.now(timezone.utc)
  219. last = await self._get_last_auto_purge_run(db)
  220. if last is not None and (now - last) < timedelta(hours=24):
  221. return 0
  222. moved = await self.purge_older_than(
  223. db,
  224. older_than_days=cfg["days"],
  225. include_never_printed=cfg["include_never_printed"],
  226. )
  227. await self._stamp_last_auto_purge_run(db, now)
  228. if moved:
  229. logger.info("Library auto-purge: moved %d file(s) to trash (threshold=%d days)", moved, cfg["days"])
  230. return moved
  231. # ---- Preview / purge ---------------------------------------------
  232. async def preview_purge(
  233. self,
  234. db: AsyncSession,
  235. older_than_days: int,
  236. include_never_printed: bool = True,
  237. sample_limit: int = 5,
  238. ) -> dict:
  239. """Count + size of files eligible for purge. Reads only; never mutates."""
  240. if older_than_days < 1:
  241. return {"count": 0, "total_bytes": 0, "sample_filenames": []}
  242. now = datetime.now(timezone.utc)
  243. cutoff = _age_cutoff(now, older_than_days)
  244. clause = _purge_filter(cutoff, include_never_printed)
  245. count_result = await db.execute(select(func.count(LibraryFile.id)).where(clause))
  246. count = int(count_result.scalar() or 0)
  247. size_result = await db.execute(select(func.coalesce(func.sum(LibraryFile.file_size), 0)).where(clause))
  248. total_bytes = int(size_result.scalar() or 0)
  249. sample_result = await db.execute(
  250. select(LibraryFile.filename).where(clause).order_by(LibraryFile.created_at).limit(sample_limit)
  251. )
  252. samples = [row[0] for row in sample_result.all()]
  253. return {
  254. "count": count,
  255. "total_bytes": total_bytes,
  256. "sample_filenames": samples,
  257. "older_than_days": older_than_days,
  258. "include_never_printed": include_never_printed,
  259. }
  260. async def purge_older_than(
  261. self,
  262. db: AsyncSession,
  263. older_than_days: int,
  264. include_never_printed: bool = True,
  265. ) -> int:
  266. """Move matching files to trash (stamps ``deleted_at``). Returns count."""
  267. if older_than_days < 1:
  268. return 0
  269. now = datetime.now(timezone.utc)
  270. cutoff = _age_cutoff(now, older_than_days)
  271. clause = _purge_filter(cutoff, include_never_printed)
  272. # We need the IDs so callers can audit or display them if they want.
  273. # Doing a single UPDATE ... WHERE is safe even under concurrent
  274. # uploads — the clause already excludes rows with deleted_at set.
  275. id_result = await db.execute(select(LibraryFile.id).where(clause))
  276. ids = [row[0] for row in id_result.all()]
  277. if not ids:
  278. return 0
  279. await db.execute(LibraryFile.__table__.update().where(LibraryFile.id.in_(ids)).values(deleted_at=now))
  280. await db.commit()
  281. logger.info("Library purge: moved %d file(s) to trash (older_than_days=%d)", len(ids), older_than_days)
  282. return len(ids)
  283. # ---- Sweeper ------------------------------------------------------
  284. async def _sweep(self, db: AsyncSession) -> int:
  285. """Hard-delete trashed rows whose retention window has elapsed."""
  286. retention = await self._read_retention(db)
  287. now = datetime.now(timezone.utc)
  288. cutoff = now - timedelta(days=retention)
  289. result = await db.execute(
  290. select(LibraryFile).where(
  291. LibraryFile.deleted_at.isnot(None),
  292. LibraryFile.deleted_at < cutoff,
  293. )
  294. )
  295. rows = result.scalars().all()
  296. if not rows:
  297. return 0
  298. deleted = 0
  299. for row in rows:
  300. self._unlink_on_disk(row)
  301. deleted += 1
  302. await delete_dependent_variants(db, [r.id for r in rows])
  303. await release_queue_references(db, [r.id for r in rows])
  304. # Single DELETE is faster than N await db.delete() round-trips; we
  305. # still need the Python loop above to unlink bytes on disk.
  306. await db.execute(delete(LibraryFile).where(LibraryFile.id.in_([r.id for r in rows])))
  307. await db.commit()
  308. logger.info("Library trash sweeper: hard-deleted %d row(s) past %d-day retention", deleted, retention)
  309. return deleted
  310. @staticmethod
  311. def _unlink_on_disk(row: LibraryFile) -> None:
  312. """Best-effort cleanup of the file + thumbnail on disk."""
  313. for rel in (row.file_path, row.thumbnail_path):
  314. abs_path = _to_absolute_path(rel)
  315. if abs_path is None:
  316. continue
  317. try:
  318. if abs_path.exists():
  319. abs_path.unlink()
  320. except OSError as e:
  321. logger.warning("Trash sweep: failed to unlink %s: %s", abs_path, e)
  322. # ---- User-facing trash ops ----------------------------------------
  323. async def restore(self, db: AsyncSession, file: LibraryFile) -> LibraryFile:
  324. """Clear ``deleted_at`` so the file reappears in listings."""
  325. file.deleted_at = None
  326. await db.commit()
  327. await db.refresh(file)
  328. return file
  329. async def hard_delete_now(self, db: AsyncSession, file: LibraryFile) -> None:
  330. """Bypass retention and delete this trashed file + its bytes immediately."""
  331. self._unlink_on_disk(file)
  332. await delete_dependent_variants(db, [file.id])
  333. await release_queue_references(db, [file.id])
  334. await db.delete(file)
  335. await db.commit()
  336. async def release_queue_references(db: AsyncSession, file_ids: list[int]) -> int:
  337. """Take queued work off files that are about to be hard-deleted (#2819).
  338. Call this before any statement that removes ``library_files`` rows — the
  339. plain deletes in the routes, the folder cascade, and the sweeper. It is the
  340. same repair the scheduler does when a dispatch consumes its own library row
  341. (``_repoint_siblings_at_archive``), minus the part that cannot apply here:
  342. nothing is being printed, so there is no archive to hand the work to.
  343. Two things happen, and both matter on a different database:
  344. * Items still waiting on one of these files are cancelled, saying which file
  345. went. Without it a queued job sat there looking dispatchable and failed at
  346. the printer with "Library file not found", days later and with nothing
  347. naming the delete that caused it.
  348. * Every remaining row referencing the file has ``library_file_id`` cleared.
  349. That is what keeps it: ``print_queue.library_file_id`` is ``ON DELETE
  350. CASCADE``, which SQLite does not enforce and PostgreSQL does, so those rows
  351. were silently deleted there -- including finished ones, which is what a
  352. batch order counts its progress from.
  353. Rows already printing are left in place. One of those is a job on a machine
  354. right now; the file being deleted is the copy in the library, not the copy
  355. the printer is working from. Returns the number of items cancelled.
  356. """
  357. if not file_ids:
  358. return 0
  359. doomed: dict[int, list[int]] = {}
  360. rows = (
  361. await db.execute(
  362. select(PrintQueueItem.id, PrintQueueItem.library_file_id)
  363. .where(PrintQueueItem.library_file_id.in_(file_ids))
  364. .where(PrintQueueItem.archive_id.is_(None))
  365. # "skipped" is not terminal: clearing a printer's previous-success
  366. # gate puts those items back to pending, onto a file that by then
  367. # is gone.
  368. .where(PrintQueueItem.status.in_(("pending", "skipped")))
  369. )
  370. ).all()
  371. for item_id, lib_id in rows:
  372. doomed.setdefault(lib_id, []).append(item_id)
  373. if doomed:
  374. names = dict(
  375. (
  376. await db.execute(select(LibraryFile.id, LibraryFile.filename).where(LibraryFile.id.in_(list(doomed))))
  377. ).all()
  378. )
  379. # Naive UTC: `completed_at` is a naive column, and asyncpg rejects an
  380. # aware value outright where SQLite silently drops the offset.
  381. now = utcnow_naive()
  382. # One statement per file rather than per item: the case this exists for
  383. # is many copies of one file, and a folder delete can reach a lot of
  384. # them at once.
  385. for lib_id, item_ids in doomed.items():
  386. await db.execute(
  387. PrintQueueItem.__table__.update()
  388. .where(PrintQueueItem.id.in_(item_ids))
  389. .values(
  390. status="cancelled",
  391. completed_at=now,
  392. error_message=f"'{names.get(lib_id, 'The library file')}' was deleted from the library",
  393. )
  394. )
  395. logger.info("Library delete: cancelled %d queued item(s) whose file was removed", len(rows))
  396. await db.execute(
  397. PrintQueueItem.__table__.update()
  398. .where(PrintQueueItem.library_file_id.in_(file_ids))
  399. .values(library_file_id=None)
  400. )
  401. return len(rows)
  402. async def delete_dependent_variants(db: AsyncSession, file_ids: list[int]) -> None:
  403. """Drop cross-model queue candidates that pointed at these files (#671).
  404. SQLite ships with ``PRAGMA foreign_keys`` off — verified, not assumed — so
  405. the ON DELETE CASCADE on ``print_queue_variants.library_file_id`` never fires
  406. on the default deployment and the rows would outlive the file.
  407. The scheduler already refuses to dispatch a candidate whose file is missing
  408. or trashed, so nothing prints wrongly without this. It is here so the table
  409. does not fill with rows referencing files that no longer exist.
  410. """
  411. if not file_ids:
  412. return
  413. await db.execute(delete(PrintQueueVariant).where(PrintQueueVariant.library_file_id.in_(file_ids)))
  414. library_trash_service = LibraryTrashService()