diff --git a/src/documents/tasks.py b/src/documents/tasks.py index 8867ddb98..9a96f3c35 100644 --- a/src/documents/tasks.py +++ b/src/documents/tasks.py @@ -1,9 +1,12 @@ import datetime import logging import shutil +import threading import uuid import zipfile from collections.abc import Callable +from collections.abc import Iterator +from contextlib import contextmanager from pathlib import Path from tempfile import TemporaryDirectory @@ -555,6 +558,38 @@ def update_document_content_maybe_archive_file( ) +_cleanup_handler_users = 0 +_cleanup_handler_lock = threading.Lock() + + +@contextmanager +def _cleanup_handler_connected() -> Iterator[None]: + """ + Keep the file cleanup handler connected to post_delete while any empty_trash + call in this process is running. The signal is process wide, so one call + finishing must not disconnect it from another that is still waiting for + media.lock. + """ + global _cleanup_handler_users + with _cleanup_handler_lock: + if _cleanup_handler_users == 0: + models.signals.post_delete.connect( + cleanup_document_deletion, + sender=Document, + ) + _cleanup_handler_users += 1 + try: + yield + finally: + with _cleanup_handler_lock: + _cleanup_handler_users -= 1 + if _cleanup_handler_users == 0: + models.signals.post_delete.disconnect( + cleanup_document_deletion, + sender=Document, + ) + + @shared_task def empty_trash(doc_ids=None) -> None: if doc_ids is None: @@ -572,12 +607,10 @@ def empty_trash(doc_ids=None) -> None: try: deleted_document_ids = list(documents.values_list("id", flat=True)) - # Temporarily connect the cleanup handler - models.signals.post_delete.connect(cleanup_document_deletion, sender=Document) # media.lock before Django's delete transaction: post_delete runs # cleanup_document_deletion inside it while the rows are locked, and # that handler re-enters the lock instead of waiting. - with media_lock(): + with _cleanup_handler_connected(), media_lock(): documents.delete() # this is effectively a hard delete logger.info(f"Deleted {len(deleted_document_ids)} documents from trash") @@ -589,11 +622,6 @@ def empty_trash(doc_ids=None) -> None: ).delete() except Exception as e: # pragma: no cover logger.exception(f"Error while emptying trash: {e}") - finally: - models.signals.post_delete.disconnect( - cleanup_document_deletion, - sender=Document, - ) @shared_task diff --git a/src/documents/tests/test_empty_trash_overlapping_calls.py b/src/documents/tests/test_empty_trash_overlapping_calls.py new file mode 100644 index 000000000..4413add9f --- /dev/null +++ b/src/documents/tests/test_empty_trash_overlapping_calls.py @@ -0,0 +1,73 @@ +import shutil +from collections.abc import Iterator +from contextlib import contextmanager +from pathlib import Path +from unittest import mock + +import pytest +from pytest_django.fixtures import Settings + +from documents import tasks +from documents.media_lock import media_lock +from documents.models import Document +from paperless_testing.dirs import PaperlessDirs +from paperless_testing.factories import DocumentFactory +from paperless_testing.samples import SIMPLE_DIGITAL_PDF + + +def _trashed_document(dirs: PaperlessDirs, title: str) -> tuple[Document, Path]: + # The title-only filename format keeps the generated filename equal to the + # stored one, so creating the document does not move the file. + doc = DocumentFactory( + title=title, + filename=f"{title}.pdf", + mime_type="application/pdf", + ) + original = dirs.originals_dir / f"{title}.pdf" + shutil.copy(SIMPLE_DIGITAL_PDF, original) + doc.delete() + return doc, original + + +@pytest.mark.django_db +class TestEmptyTrashOverlappingCalls: + def test_call_that_waits_for_the_lock_still_removes_its_files( + self, + paperless_dirs: PaperlessDirs, + settings: Settings, + ) -> None: + """ + GIVEN: + - Two trashed documents with files on disk + - A second empty_trash call that runs to completion while the first + is waiting for media.lock, as happens with two overlapping + requests in one process + WHEN: + - The first call gets the lock and deletes its document + THEN: + - Both documents are gone from the database + - Both documents' files are gone from disk, not just the files of + the call that finished first + """ + settings.FILENAME_FORMAT = "{{ title }}" + first, first_original = _trashed_document(paperless_dirs, "first") + second, second_original = _trashed_document(paperless_dirs, "second") + assert first_original.is_file() + assert second_original.is_file() + interleaved = False + + @contextmanager + def lock_after_other_call(*args, **kwargs) -> Iterator[None]: + nonlocal interleaved + if not interleaved: + interleaved = True + tasks.empty_trash(doc_ids=[second.pk]) + with media_lock(*args, **kwargs): + yield + + with mock.patch("documents.tasks.media_lock", lock_after_other_call): + tasks.empty_trash(doc_ids=[first.pk]) + + assert not Document.global_objects.filter(pk__in=[first.pk, second.pk]).exists() + assert not second_original.exists() + assert not first_original.exists()