feat: delete project storage on database reset with safe FS cleanup
This commit is contained in:
@@ -1,11 +1,15 @@
|
||||
"""Full wipe of all project-dependent data, keeping schema and migrations."""
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
import shutil
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
|
||||
from sqlalchemy import func, select
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.config import document_storage_root
|
||||
from app.models.agreement import Agreement, AgreementItem
|
||||
from app.models.boq import BoqDocument, Section, System, WorkItem
|
||||
from app.models.daily_report import DailyReport, DailyReportItem
|
||||
@@ -16,6 +20,8 @@ from app.models.project import Project
|
||||
from app.models.work_journal import WorkJournalEntry
|
||||
from app.models.document_artifact import DocumentArtifact
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class DatabaseResetError(RuntimeError):
|
||||
"""Reset failed and was rolled back."""
|
||||
@@ -48,10 +54,31 @@ DELETE_ORDER = (
|
||||
PROJECT_DEPENDENT_TABLES = tuple(name for name, _ in DELETE_ORDER)
|
||||
|
||||
|
||||
def project_storage_path(project_id: int) -> Path:
|
||||
"""
|
||||
Return the storage directory for a project. Server-side construction only.
|
||||
|
||||
The result is always strictly inside document_storage_root()/projects/.
|
||||
Does NOT create the directory.
|
||||
"""
|
||||
pid = int(project_id)
|
||||
if pid <= 0:
|
||||
raise ValueError("project_id must be a positive integer")
|
||||
root = document_storage_root()
|
||||
projects_root = (root / "projects").resolve()
|
||||
candidate = (projects_root / str(pid)).resolve()
|
||||
# Safety: must be a direct child of projects_root
|
||||
if candidate.parent != projects_root:
|
||||
raise ValueError("project storage path escapes projects root")
|
||||
return candidate
|
||||
|
||||
|
||||
@dataclass
|
||||
class ResetResult:
|
||||
deleted: dict[str, int]
|
||||
verified: dict[str, int]
|
||||
storage_removed: bool = False
|
||||
storage_error: str | None = None
|
||||
|
||||
|
||||
def count_project_data(db: Session) -> dict[str, int]:
|
||||
@@ -62,14 +89,55 @@ def count_project_data(db: Session) -> dict[str, int]:
|
||||
return counts
|
||||
|
||||
|
||||
def _delete_project_storage(project_ids: list[int]) -> tuple[bool, str | None]:
|
||||
"""
|
||||
Remove physical storage for the given project IDs.
|
||||
|
||||
Only called AFTER a successful DB commit. Never rolls back DB.
|
||||
Returns (all_removed, error_message_or_None).
|
||||
"""
|
||||
errors = []
|
||||
for pid in project_ids:
|
||||
try:
|
||||
storage_dir = project_storage_path(pid)
|
||||
except ValueError as exc:
|
||||
errors.append(f"project {pid}: {exc}")
|
||||
continue
|
||||
if not storage_dir.exists():
|
||||
continue # missing storage is not an error
|
||||
try:
|
||||
# Guard: resolved path must still be inside projects root
|
||||
projects_root = (document_storage_root() / "projects").resolve()
|
||||
if storage_dir.parent != projects_root:
|
||||
errors.append(f"project {pid}: storage path escapes projects root")
|
||||
continue
|
||||
# Refuse to follow symlinks out of the tree
|
||||
if storage_dir.is_symlink():
|
||||
errors.append(f"project {pid}: storage directory is a symlink, refused to delete")
|
||||
continue
|
||||
shutil.rmtree(storage_dir)
|
||||
except OSError as exc:
|
||||
logger.warning(
|
||||
"FS cleanup failed for project %s: %s: %s",
|
||||
pid, type(exc).__name__, exc,
|
||||
)
|
||||
errors.append(f"project {pid}: {type(exc).__name__}: {exc}")
|
||||
return (not errors, "; ".join(errors) if errors else None)
|
||||
|
||||
|
||||
def reset_database(db: Session) -> ResetResult:
|
||||
"""
|
||||
Delete all project-dependent rows in one transaction.
|
||||
Delete all project-dependent rows in one transaction, then clean FS.
|
||||
|
||||
Schema, indexes and schema_migrations are left untouched. On any error the
|
||||
transaction is rolled back and no partial delete remains.
|
||||
Schema, indexes and schema_migrations are left untouched. On any DB error
|
||||
the transaction is rolled back and physical storage is NOT touched.
|
||||
FS deletion happens only after a successful DB commit.
|
||||
"""
|
||||
project_ids: list[int] = []
|
||||
try:
|
||||
# Collect project IDs before deletion
|
||||
project_ids = [row[0] for row in db.execute(select(Project.id)).all()]
|
||||
|
||||
deleted: dict[str, int] = {}
|
||||
# Break the circular BoqDocument ↔ Agreement FK before deleting either side.
|
||||
db.execute(
|
||||
@@ -92,10 +160,18 @@ def reset_database(db: Session) -> ResetResult:
|
||||
)
|
||||
|
||||
db.commit()
|
||||
return ResetResult(deleted=deleted, verified=verified)
|
||||
except DatabaseResetError:
|
||||
db.rollback()
|
||||
raise
|
||||
except Exception as exc:
|
||||
db.rollback()
|
||||
raise DatabaseResetError(f"Сброс прерван, изменения отменены: {exc}") from exc
|
||||
|
||||
# DB commit succeeded — now clean physical storage.
|
||||
storage_removed, storage_error = _delete_project_storage(project_ids)
|
||||
return ResetResult(
|
||||
deleted=deleted,
|
||||
verified=verified,
|
||||
storage_removed=storage_removed,
|
||||
storage_error=storage_error,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user