From ce47ebc7de27a27e92a3fd5391470ebbd328fc42 Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Thu, 28 May 2026 20:01:35 -0400 Subject: [PATCH] =?UTF-8?q?feat(trash):=20services/trash.py=20=E2=80=94=20?= =?UTF-8?q?delete()=20+=20cascade-stamp=20by=20batch?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/fabledassistant/services/trash.py | 96 +++++++++++++++++++++++++++ tests/test_services_trash.py | 79 ++++++++++++++++++++++ 2 files changed, 175 insertions(+) create mode 100644 src/fabledassistant/services/trash.py create mode 100644 tests/test_services_trash.py diff --git a/src/fabledassistant/services/trash.py b/src/fabledassistant/services/trash.py new file mode 100644 index 0000000..8492569 --- /dev/null +++ b/src/fabledassistant/services/trash.py @@ -0,0 +1,96 @@ +"""Soft-delete / trash service — single source of truth for recoverable deletes. + +A delete stamps `deleted_at` + a shared `deleted_batch_id` on the target row and +its descendants (cascade). Restore clears the batch; purge hard-deletes it; the +retention cron purges rows older than the configured window. Live reads exclude +trashed rows via `alive()`. +""" +from __future__ import annotations + +import uuid +from datetime import datetime, timezone + +from sqlalchemy import select, update + +from fabledassistant.models import async_session +from fabledassistant.models.note import Note +from fabledassistant.models.event import Event +from fabledassistant.models.project import Project +from fabledassistant.models.milestone import Milestone +from fabledassistant.models.rulebook import Rulebook, RulebookTopic, Rule + +# entity_type -> (Model, owner_column_name or None). Used by the existence check. +_OWNER = { + "note": (Note, "user_id"), + "task": (Note, "user_id"), + "event": (Event, "user_id"), + "project": (Project, "user_id"), + "milestone": (Milestone, "user_id"), + "rulebook": (Rulebook, "owner_user_id"), + "topic": (RulebookTopic, None), + "rule": (Rule, None), +} + + +async def _set(session, model, where, batch, now) -> None: + """Stamp deleted_at + batch on live rows matching `where`.""" + await session.execute( + update(model) + .where(*where, model.deleted_at.is_(None)) + .values(deleted_at=now, deleted_batch_id=batch) + ) + + +async def _exists_alive(session, user_id: int, etype: str, eid: int) -> bool: + model, owner = _OWNER[etype] + where = [model.id == eid, model.deleted_at.is_(None)] + if owner: + where.append(getattr(model, owner) == user_id) + return (await session.execute(select(model.id).where(*where))).first() is not None + + +async def _cascade(session, user_id: int, etype: str, eid: int, batch: str, now) -> None: + if etype == "project": + await _set(session, Note, [Note.user_id == user_id, Note.project_id == eid], batch, now) + await _set(session, Milestone, [Milestone.user_id == user_id, Milestone.project_id == eid], batch, now) + await _set(session, Project, [Project.user_id == user_id, Project.id == eid], batch, now) + elif etype == "milestone": + await _set(session, Note, [Note.user_id == user_id, Note.milestone_id == eid], batch, now) + await _set(session, Milestone, [Milestone.user_id == user_id, Milestone.id == eid], batch, now) + elif etype in ("note", "task"): + await _set(session, Note, [Note.user_id == user_id, Note.parent_id == eid], batch, now) # sub-tasks + await _set(session, Note, [Note.user_id == user_id, Note.id == eid], batch, now) + elif etype == "event": + await _set(session, Event, [Event.user_id == user_id, Event.id == eid], batch, now) + elif etype == "rulebook": + topic_ids = (await session.execute( + select(RulebookTopic.id) + .join(Rulebook, RulebookTopic.rulebook_id == Rulebook.id) + .where(Rulebook.id == eid, Rulebook.owner_user_id == user_id) + )).scalars().all() + if topic_ids: + await _set(session, Rule, [Rule.topic_id.in_(topic_ids)], batch, now) + await _set(session, RulebookTopic, [RulebookTopic.rulebook_id == eid], batch, now) + await _set(session, Rulebook, [Rulebook.id == eid, Rulebook.owner_user_id == user_id], batch, now) + elif etype == "topic": + await _set(session, Rule, [Rule.topic_id == eid], batch, now) + await _set(session, RulebookTopic, [RulebookTopic.id == eid], batch, now) + elif etype == "rule": + await _set(session, Rule, [Rule.id == eid], batch, now) + else: + raise ValueError(f"unknown entity_type: {etype!r}") + + +async def delete(user_id: int, entity_type: str, entity_id: int) -> str | None: + """Soft-delete an entity + its descendants under one batch_id. + + Returns the batch_id, or None if the entity wasn't found / not owned. + """ + batch = str(uuid.uuid4()) + now = datetime.now(timezone.utc) + async with async_session() as session: + if not await _exists_alive(session, user_id, entity_type, entity_id): + return None + await _cascade(session, user_id, entity_type, entity_id, batch, now) + await session.commit() + return batch diff --git a/tests/test_services_trash.py b/tests/test_services_trash.py new file mode 100644 index 0000000..fc78e61 --- /dev/null +++ b/tests/test_services_trash.py @@ -0,0 +1,79 @@ +"""Tests for services/trash.py — mocks async_session (no real DB).""" +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + + +def _make_mock_session(): + s = AsyncMock() + s.__aenter__ = AsyncMock(return_value=s) + s.__aexit__ = AsyncMock(return_value=False) + s.commit = AsyncMock() + return s + + +def _exists_result(found=True): + r = MagicMock() + r.first.return_value = (1,) if found else None + return r + + +@pytest.mark.asyncio +async def test_delete_note_returns_batch_and_commits(): + session = _make_mock_session() + # 1 execute for _exists_alive, then 2 for the note cascade (sub-tasks + self) + session.execute = AsyncMock(side_effect=[_exists_result(True), MagicMock(), MagicMock()]) + with patch("fabledassistant.services.trash.async_session") as cls: + cls.return_value = session + from fabledassistant.services.trash import delete + batch = await delete(user_id=1, entity_type="note", entity_id=5) + assert isinstance(batch, str) and len(batch) > 0 + assert session.commit.called + # exists-check + 2 cascade updates + assert session.execute.await_count == 3 + + +@pytest.mark.asyncio +async def test_delete_returns_none_when_not_found(): + session = _make_mock_session() + session.execute = AsyncMock(return_value=_exists_result(False)) + with patch("fabledassistant.services.trash.async_session") as cls: + cls.return_value = session + from fabledassistant.services.trash import delete + batch = await delete(user_id=1, entity_type="task", entity_id=999) + assert batch is None + assert not session.commit.called + # only the existence check ran + assert session.execute.await_count == 1 + + +@pytest.mark.asyncio +async def test_delete_project_cascades_three_tables(): + session = _make_mock_session() + # exists-check + 3 cascade updates (notes, milestones, project) + session.execute = AsyncMock(side_effect=[ + _exists_result(True), MagicMock(), MagicMock(), MagicMock(), + ]) + with patch("fabledassistant.services.trash.async_session") as cls: + cls.return_value = session + from fabledassistant.services.trash import delete + batch = await delete(user_id=1, entity_type="project", entity_id=3) + assert isinstance(batch, str) + assert session.execute.await_count == 4 + + +@pytest.mark.asyncio +async def test_delete_rulebook_cascades_topics_and_rules(): + session = _make_mock_session() + topic_ids_result = MagicMock() + topic_ids_result.scalars.return_value.all.return_value = [10, 11] + # exists-check, topic-id select, then 3 updates (rules, topics, rulebook) + session.execute = AsyncMock(side_effect=[ + _exists_result(True), topic_ids_result, MagicMock(), MagicMock(), MagicMock(), + ]) + with patch("fabledassistant.services.trash.async_session") as cls: + cls.return_value = session + from fabledassistant.services.trash import delete + batch = await delete(user_id=7, entity_type="rulebook", entity_id=2) + assert isinstance(batch, str) + assert session.execute.await_count == 5