Skip to content

armgit / zulip

Public Imported from GitHub
0

Zulip server and web application. Open-source team chat that helps teams stay productive and focused.

attachments: Use a contextmanager to handler batching.

Alex Vandiverc22adaa12671
diff --git a/zerver/actions/realm_settings.py b/zerver/actions/realm_settings.py
index d29f9ccf178..ade69554f0b 100644
--- a/zerver/actions/realm_settings.py
+++ b/zerver/actions/realm_settings.py
@@ -711,24 +711,20 @@ def do_add_deactivated_redirect(realm: Realm, redirect_url: str) -> None:
realm.save(update_fields=["deactivated_redirect"])
-def do_delete_all_realm_attachments(realm: Realm, *, batch_size: int = 1000) -> None:
+def do_delete_all_realm_attachments(realm: Realm) -> None:
# Delete attachment files from the storage backend, so that we
# don't leave them dangling.
- for obj_class in Attachment, ArchivedAttachment:
- last_id = 0
- while True:
+ with delete_message_attachments(delete_from=(ImageAttachment,)) as delete_one:
+ for obj_class in Attachment, ArchivedAttachment:
to_delete = (
- obj_class._default_manager.filter(realm_id=realm.id, pk__gt=last_id)
+ obj_class._default_manager.filter(realm_id=realm.id)
.order_by("pk")
- .values_list("pk", "path_id")[:batch_size]
+ .select_for_update()
+ .values_list("path_id", flat=True)
)
- if len(to_delete) > 0:
- delete_message_attachments([row[1] for row in to_delete])
- last_id = to_delete[len(to_delete) - 1][0]
- ImageAttachment.objects.filter(path_id__in=[row[1] for row in to_delete]).delete()
- if len(to_delete) < batch_size:
- break
- obj_class._default_manager.filter(realm=realm).delete()
+ for path_id in to_delete.iterator():
+ delete_one(path_id)
+ obj_class._default_manager.filter(realm_id=realm.id).delete()
@transaction.atomic(durable=True)
diff --git a/zerver/actions/uploads.py b/zerver/actions/uploads.py
index a83bbb4d6ed..df31dcd6eb3 100644
--- a/zerver/actions/uploads.py
+++ b/zerver/actions/uploads.py
@@ -2,11 +2,13 @@ import logging
from dataclasses import dataclass
from typing import Any
+from django.db import transaction
+
from zerver.lib.attachments import get_old_unclaimed_attachments, validate_attachment_request
from zerver.lib.markdown import MessageRenderingResult
-from zerver.lib.thumbnail import StoredThumbnailFormat, get_image_thumbnail_path
from zerver.lib.upload import claim_attachment, delete_message_attachments
from zerver.models import (
+ ArchivedAttachment,
Attachment,
ImageAttachment,
Message,
@@ -83,48 +85,22 @@ def do_claim_attachments(
return claimed
-DELETE_BATCH_SIZE = 1000
-
-
[email protected](durable=True)
def do_delete_old_unclaimed_attachments(weeks_ago: int) -> None:
old_unclaimed_attachments, old_unclaimed_archived_attachments = get_old_unclaimed_attachments(
weeks_ago
)
- # An attachment may be removed from Attachments and
- # ArchiveAttachments in the same run; prevent warnings from the
- # backing store by only removing it from there once.
- already_removed = set()
- storage_paths = []
- for attachment in old_unclaimed_attachments:
- storage_paths.append(attachment.path_id)
- image_row = ImageAttachment.objects.filter(path_id=attachment.path_id).first()
- if image_row:
- for existing_thumbnail in image_row.thumbnail_metadata:
- thumb = StoredThumbnailFormat(**existing_thumbnail)
- storage_paths.append(get_image_thumbnail_path(image_row, thumb))
- image_row.delete()
- already_removed.add(attachment.path_id)
- attachment.delete()
- if len(storage_paths) >= DELETE_BATCH_SIZE:
- delete_message_attachments(storage_paths[:DELETE_BATCH_SIZE])
- storage_paths = storage_paths[DELETE_BATCH_SIZE:]
- for archived_attachment in old_unclaimed_archived_attachments:
- if archived_attachment.path_id not in already_removed:
- storage_paths.append(archived_attachment.path_id)
- image_row = ImageAttachment.objects.filter(path_id=archived_attachment.path_id).first()
- if image_row: # nocoverage
- for existing_thumbnail in image_row.thumbnail_metadata:
- thumb = StoredThumbnailFormat(**existing_thumbnail)
- storage_paths.append(get_image_thumbnail_path(image_row, thumb))
- image_row.delete()
- archived_attachment.delete()
- if len(storage_paths) >= DELETE_BATCH_SIZE:
- delete_message_attachments(storage_paths[:DELETE_BATCH_SIZE])
- storage_paths = storage_paths[DELETE_BATCH_SIZE:]
-
- if storage_paths:
- delete_message_attachments(storage_paths)
+ with delete_message_attachments(delete_from=(ImageAttachment, Attachment)) as delete_one:
+ for path_id in old_unclaimed_attachments.values_list("path_id", flat=True).iterator():
+ delete_one(path_id)
+ with delete_message_attachments(
+ delete_from=(ImageAttachment, ArchivedAttachment)
+ ) as delete_one:
+ for path_id in old_unclaimed_archived_attachments.values_list(
+ "path_id", flat=True
+ ).iterator():
+ delete_one(path_id)
def check_attachment_reference_change(
diff --git a/zerver/lib/attachments.py b/zerver/lib/attachments.py
index 89b10e23db1..ee245f25399 100644
--- a/zerver/lib/attachments.py
+++ b/zerver/lib/attachments.py
@@ -222,22 +222,36 @@ def get_old_unclaimed_attachments(
# The Attachment vs ArchivedAttachment queries are asymmetric because only
# Attachment has the scheduled_messages relation.
- old_attachments = Attachment.objects.alias(
- has_other_messages=Exists(
- ArchivedAttachment.objects.filter(id=OuterRef("id")).exclude(messages=None)
+ old_attachments = (
+ Attachment.objects.alias(
+ has_other_messages=Exists(
+ ArchivedAttachment.objects.filter(id=OuterRef("id")).exclude(messages=None)
+ )
+ )
+ .filter(
+ messages=None,
+ scheduled_messages=None,
+ create_time__lt=delta_weeks_ago,
+ has_other_messages=False,
)
- ).filter(
- messages=None,
- scheduled_messages=None,
- create_time__lt=delta_weeks_ago,
- has_other_messages=False,
+ .order_by("id")
+ .select_for_update(of=("self",))
)
- old_archived_attachments = ArchivedAttachment.objects.alias(
- has_other_messages=Exists(
- Attachment.objects.filter(id=OuterRef("id")).exclude(
- messages=None, scheduled_messages=None
+ old_archived_attachments = (
+ ArchivedAttachment.objects.alias(
+ has_other_messages=Exists(
+ Attachment.objects.filter(id=OuterRef("id")).exclude(
+ messages=None, scheduled_messages=None
+ )
)
)
- ).filter(messages=None, create_time__lt=delta_weeks_ago, has_other_messages=False)
+ .filter(
+ messages=None,
+ create_time__lt=delta_weeks_ago,
+ has_other_messages=False,
+ )
+ .order_by("id")
+ .select_for_update(of=("self",))
+ )
return old_attachments, old_archived_attachments
diff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.py
index 28988cc2e80..edb6f1831a8 100644
--- a/zerver/lib/upload/__init__.py
+++ b/zerver/lib/upload/__init__.py
@@ -4,6 +4,7 @@ import os
import re
import unicodedata
from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from datetime import datetime
from email.message import EmailMessage
from typing import IO, Any
@@ -30,7 +31,16 @@ from zerver.lib.thumbnail import (
resize_emoji,
)
from zerver.lib.upload.base import StreamingSourceWithSize, ZulipUploadBackend
-from zerver.models import Attachment, Message, Realm, RealmEmoji, ScheduledMessage, UserProfile
+from zerver.models import (
+ ArchivedAttachment,
+ Attachment,
+ ImageAttachment,
+ Message,
+ Realm,
+ RealmEmoji,
+ ScheduledMessage,
+ UserProfile,
+)
from zerver.models.users import is_cross_realm_bot_email
@@ -282,12 +292,29 @@ def save_attachment_contents(path_id: str, filehandle: IO[bytes]) -> None:
upload_backend.save_attachment_contents(path_id, filehandle)
-def delete_message_attachment(path_id: str) -> None:
+def delete_message_attachment(path_id: str, *, raw_path: bool = False) -> None:
upload_backend.delete_message_attachment(path_id)
-def delete_message_attachments(path_ids: list[str]) -> None:
- upload_backend.delete_message_attachments(path_ids)
+@contextmanager
+def delete_message_attachments(
+ *,
+ raw_paths: bool = False,
+ delete_from: tuple[type[ImageAttachment | Attachment | ArchivedAttachment], ...] = (),
+) -> Iterator[Callable[[str], None]]:
+ if delete_from == ():
+ flush_path_ids: None | Callable[[list[str]], None] = None
+ else:
+
+ def delete_from_database(path_ids: list[str]) -> None:
+ for db_class in delete_from:
+ db_class._default_manager.filter(path_id__in=path_ids).delete()
+
+ flush_path_ids = delete_from_database
+ with upload_backend.delete_message_attachments(
+ raw_paths=raw_paths, flush=flush_path_ids
+ ) as delete_one:
+ yield delete_one
def all_message_attachments(
diff --git a/zerver/lib/upload/base.py b/zerver/lib/upload/base.py
index cf3326e7191..190d4508433 100644
--- a/zerver/lib/upload/base.py
+++ b/zerver/lib/upload/base.py
@@ -1,5 +1,6 @@
import os
from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from dataclasses import dataclass
from datetime import datetime
from typing import IO, Any, Protocol
@@ -47,13 +48,29 @@ class ZulipUploadBackend:
def attachment_source(self, path_id: str) -> StreamingSourceWithSize:
raise NotImplementedError
- def delete_message_attachment(self, path_id: str) -> None:
- """This must delete the attachment, any adjacent .info files, and any thumbnails."""
+ def delete_message_attachment(self, path_id: str, *, raw_path: bool = False) -> None:
+ """This must delete the attachment, any adjacent .info files, and any thumbnails.
+
+ If raw_path is passed, just delete the one path provided.
+ This is used in rare cases where we're iterating _files_, not
+ path_ids.
+
+ """
raise NotImplementedError
- def delete_message_attachments(self, path_ids: list[str]) -> None:
- for path_id in path_ids:
- self.delete_message_attachment(path_id)
+ @contextmanager
+ def delete_message_attachments(
+ self,
+ *,
+ raw_paths: bool = False,
+ flush: None | Callable[[list[str]], None] = None,
+ ) -> Iterator[Callable[[str], None]]:
+ def delete_one(path_id: str) -> None:
+ self.delete_message_attachment(path_id, raw_path=raw_paths)
+ if flush:
+ flush([path_id])
+
+ yield delete_one
def all_message_attachments(
self,
diff --git a/zerver/lib/upload/local.py b/zerver/lib/upload/local.py
index 71fb0ca9f01..5da029dd68a 100644
--- a/zerver/lib/upload/local.py
+++ b/zerver/lib/upload/local.py
@@ -118,10 +118,11 @@ class LocalUploadBackend(ZulipUploadBackend):
)
@override
- def delete_message_attachment(self, path_id: str) -> None:
+ def delete_message_attachment(self, path_id: str, *, raw_path: bool = False) -> None:
delete_local_file("files", path_id)
- delete_local_file("files", f"{path_id}.info")
- delete_local_file("files", f"thumbnail/{path_id}/", directory=True)
+ if not raw_path:
+ delete_local_file("files", f"{path_id}.info")
+ delete_local_file("files", f"thumbnail/{path_id}/", directory=True)
@override
def all_message_attachments(
diff --git a/zerver/lib/upload/s3.py b/zerver/lib/upload/s3.py
index 790ce598ff9..23b5e8a8b17 100644
--- a/zerver/lib/upload/s3.py
+++ b/zerver/lib/upload/s3.py
@@ -1,6 +1,7 @@
import os
import secrets
from collections.abc import Callable, Iterator
+from contextlib import contextmanager
from datetime import datetime
from typing import IO, TYPE_CHECKING, Any, Literal
from urllib.parse import urljoin, urlsplit, urlunsplit
@@ -28,6 +29,9 @@ if TYPE_CHECKING:
# they expire.
SIGNED_UPLOAD_URL_DURATION = 60
+
+DELETE_BATCH_SIZE = 1000
+
# Performance note:
#
# For writing files to S3, the file could either be stored in RAM
@@ -289,23 +293,46 @@ class S3UploadBackend(ZulipUploadBackend):
)
@override
- def delete_message_attachment(self, path_id: str) -> None:
- self.delete_message_attachments([path_id])
+ def delete_message_attachment(self, path_id: str, *, raw_path: bool = False) -> None:
+ with self.delete_message_attachments(raw_paths=raw_path) as delete_one:
+ delete_one(path_id)
+ @contextmanager
@override
- def delete_message_attachments(self, path_ids: list[str]) -> None:
- all_paths = path_ids.copy()
- for path_id in path_ids:
- all_paths.append(f"{path_id}.info")
- all_paths += [
- thumb_path
- for thumb_path, _ in self.all_message_attachments(
- include_thumbnails=True, prefix=f"thumbnail/{path_id}/"
- )
- ]
- self.uploads_bucket.delete_objects(
- Delete={"Objects": [{"Key": path_id} for path_id in all_paths], "Quiet": True},
- )
+ def delete_message_attachments(
+ self, *, raw_paths: bool = False, flush: None | Callable[[list[str]], None] = None
+ ) -> Iterator[Callable[[str], None]]:
+ paths: list[tuple[str, bool]] = []
+
+ def flush_queue() -> None:
+ nonlocal paths
+ self.uploads_bucket.delete_objects(
+ Delete={
+ "Objects": [{"Key": path_id} for path_id, _ in paths[:DELETE_BATCH_SIZE]],
+ "Quiet": True,
+ },
+ )
+ if flush:
+ flush([path for path, is_db_path_id in paths[:DELETE_BATCH_SIZE] if is_db_path_id])
+ paths = paths[DELETE_BATCH_SIZE:]
+
+ def queue_delete(path_id: str) -> None:
+ nonlocal paths
+ paths.append((path_id, True))
+ if not raw_paths:
+ paths.append((f"{path_id}.info", False))
+ paths += [
+ (thumb_path, False)
+ for thumb_path, _ in self.all_message_attachments(
+ include_thumbnails=True, prefix=f"thumbnail/{path_id}/"
+ )
+ ]
+ if len(paths) > DELETE_BATCH_SIZE:
+ flush_queue()
+
+ yield queue_delete
+ if paths:
+ flush_queue()
@override
def all_message_attachments(
diff --git a/zerver/management/commands/delete_old_unclaimed_attachments.py b/zerver/management/commands/delete_old_unclaimed_attachments.py
index 3b37ef78687..3edf5b93e61 100644
--- a/zerver/management/commands/delete_old_unclaimed_attachments.py
+++ b/zerver/management/commands/delete_old_unclaimed_attachments.py
@@ -76,27 +76,25 @@ class Command(ZulipBaseCommand):
def clean_attachment_upload_backend(self, dry_run: bool = True) -> None:
cutoff = timezone_now() - timedelta(minutes=5)
print(f"Removing extra files in storage black-end older than {cutoff.isoformat()}")
- to_delete = []
- for file_path, modified_at in all_message_attachments(include_thumbnails=True):
- if file_path.startswith("thumbnail/"):
- path_id = split_thumbnail_path(file_path)[0]
- else:
- path_id = file_path
- if Attachment.objects.filter(path_id=path_id).exists():
- continue
- if ArchivedAttachment.objects.filter(path_id=path_id).exists():
- continue
- if modified_at > cutoff:
- # We upload files to the backend storage and _then_
- # make the database entry, so must give some leeway to
- # recently-added files which do not have DB rows.
- continue
- print(f"* {file_path} modified at {modified_at}")
- if dry_run:
- continue
- to_delete.append(file_path)
- if len(to_delete) > 1000:
- delete_message_attachments(to_delete)
- to_delete = []
- if not dry_run and len(to_delete) > 0:
- delete_message_attachments(to_delete)
+ with delete_message_attachments(raw_paths=True) as delete_one:
+ for file_path, modified_at in all_message_attachments(include_thumbnails=True):
+ if file_path.startswith("thumbnail/"):
+ path_id = split_thumbnail_path(file_path)[0]
+ else:
+ path_id = file_path
+ if Attachment.objects.filter(path_id=path_id).exists():
+ continue
+ if ArchivedAttachment.objects.filter(path_id=path_id).exists():
+ continue
+ if modified_at > cutoff:
+ # We upload files to the backend storage and _then_
+ # make the database entry, so must give some leeway to
+ # recently-added files which do not have DB rows.
+ continue
+ print(f"* {file_path} modified at {modified_at}")
+ if dry_run:
+ continue
+
+ # This operates on raw paths due to the raw_paths=True
+ # on the contextmanager above.
+ delete_one(file_path)
diff --git a/zerver/tests/test_delete_unclaimed_attachments.py b/zerver/tests/test_delete_unclaimed_attachments.py
index f232dd9590e..7d3b2449d00 100644
--- a/zerver/tests/test_delete_unclaimed_attachments.py
+++ b/zerver/tests/test_delete_unclaimed_attachments.py
@@ -8,13 +8,15 @@ import time_machine
from django.conf import settings
from django.utils.timezone import now as timezone_now
+import zerver.lib.upload
from zerver.actions.message_delete import do_delete_messages
from zerver.actions.scheduled_messages import check_schedule_message, delete_scheduled_message
from zerver.actions.uploads import do_delete_old_unclaimed_attachments
from zerver.lib.retention import clean_archived_data
from zerver.lib.test_classes import UploadSerializeMixin, ZulipTestCase
-from zerver.lib.test_helpers import get_test_image_file
+from zerver.lib.test_helpers import create_s3_buckets, get_test_image_file, use_s3_backend
from zerver.lib.thumbnail import ThumbnailFormat
+from zerver.lib.upload.s3 import S3UploadBackend
from zerver.models import ArchivedAttachment, Attachment, ImageAttachment, Message, UserProfile
from zerver.models.clients import get_client
@@ -433,34 +435,41 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):
attachment, has_file=False, has_attachment=False, has_archived_attachment=False
)
+ @use_s3_backend
def test_delete_batch_size(self) -> None:
+ create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)
+
# 3 attachments, each of which has 2 files because of the thumbnail
thumbnail_format = ThumbnailFormat("webp", 100, 75, animated=False)
with self.thumbnail_formats(thumbnail_format), self.captureOnCommitCallbacks(execute=True):
- attachments = [self.make_attachment("img.png") for _ in range(3)]
+ for _ in range(3):
+ self.make_attachment("img.png")
+ backend = zerver.lib.upload.upload_backend
+ assert isinstance(backend, S3UploadBackend)
+ uploads_bucket = backend.uploads_bucket
with (
- patch("zerver.actions.uploads.DELETE_BATCH_SIZE", 5),
- patch("zerver.actions.uploads.delete_message_attachments") as delete_mock,
+ patch("zerver.lib.upload.s3.DELETE_BATCH_SIZE", 5),
+ patch.object(
+ uploads_bucket, "delete_objects", wraps=uploads_bucket.delete_objects
+ ) as delete_mock,
):
do_delete_old_unclaimed_attachments(1)
- # We expect all of the 5 attachments to be deleted, across two
- # different calls of 5- and 1-element lists. Since each image
- # attachment is two files, this means that the thumbnail and
- # its original is split across batches.
+ # We delete all 6 uploaded files -- and also the ".info" files
+ # which we don't bother checking if they existed. This makes
+ # 2 batches, of 5 and 4 files, respectively; one of the files'
+ # thumbnails is split into a separate batch from its original.
self.assertEqual(delete_mock.call_count, 2)
- self.assert_length(delete_mock.call_args_list[0][0][0], 5)
- self.assert_length(delete_mock.call_args_list[1][0][0], 1)
+ self.assert_length(delete_mock.call_args_list[0][1]["Delete"]["Objects"], 5)
+ self.assert_length(delete_mock.call_args_list[1][1]["Delete"]["Objects"], 4)
- deleted = set(delete_mock.call_args_list[0][0][0] + delete_mock.call_args_list[1][0][0])
- existing = set()
- for attachment in attachments:
- existing.add(attachment.path_id)
- existing.add(f"thumbnail/{attachment.path_id}/{thumbnail_format!s}")
- self.assertEqual(deleted, existing)
+ self.assert_length(list(uploads_bucket.objects.all()), 0)
+ @use_s3_backend
def test_delete_batch_size_archived(self) -> None:
+ create_s3_buckets(settings.S3_AUTH_UPLOADS_BUCKET)
+
hamlet = self.example_user("hamlet")
attachments = [self.make_attachment("text.txt") for _ in range(20)]
@@ -472,29 +481,32 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):
)
message_id = self.send_stream_message(hamlet, "Denmark", body, "test")
- # Delete and purge the message, leaving both the ArchivedAttachments dangling
+ # Delete and purge the message, leaving the ArchivedAttachments dangling
do_delete_messages(hamlet.realm, [Message.objects.get(id=message_id)], acting_user=None)
with self.settings(ARCHIVED_DATA_VACUUMING_DELAY_DAYS=0):
clean_archived_data()
# Removing unclaimed attachments now cleans them all out
+ backend = zerver.lib.upload.upload_backend
+ assert isinstance(backend, S3UploadBackend)
+ uploads_bucket = backend.uploads_bucket
with (
- patch("zerver.actions.uploads.DELETE_BATCH_SIZE", 6),
- patch("zerver.actions.uploads.delete_message_attachments") as delete_mock,
+ patch("zerver.lib.upload.s3.DELETE_BATCH_SIZE", 15),
+ patch.object(
+ uploads_bucket, "delete_objects", wraps=uploads_bucket.delete_objects
+ ) as delete_mock,
):
do_delete_old_unclaimed_attachments(1)
- # We expect all of the 20 attachments (10 of which are
- # ArchivedAttachments) to be deleted, across four different
- # calls: 6, 6, 6, 2
+ # There are 20 attachments, but we're also delete (or
+ # attempting to delete, without spending the time to check if
+ # they exist) the .info files, so 40 files total. With a
+ # batch size of 15, this happens in 4 calls, because the
+ # Attachment and ArchivedAttachment sets are done separately.
self.assertEqual(delete_mock.call_count, 4)
- self.assert_length(delete_mock.call_args_list[0][0][0], 6)
- self.assert_length(delete_mock.call_args_list[1][0][0], 6)
- self.assert_length(delete_mock.call_args_list[2][0][0], 6)
- self.assert_length(delete_mock.call_args_list[3][0][0], 2)
+ self.assert_length(delete_mock.call_args_list[0][1]["Delete"]["Objects"], 15)
+ self.assert_length(delete_mock.call_args_list[1][1]["Delete"]["Objects"], 5)
+ self.assert_length(delete_mock.call_args_list[2][1]["Delete"]["Objects"], 15)
+ self.assert_length(delete_mock.call_args_list[3][1]["Delete"]["Objects"], 5)
- deleted_path_ids = {elem for call in delete_mock.call_args_list for elem in call[0][0]}
- self.assertEqual(
- deleted_path_ids,
- {attachment.path_id for attachment in attachments},
- )
+ self.assert_length(list(uploads_bucket.objects.all()), 0)
diff --git a/zerver/tests/test_realm.py b/zerver/tests/test_realm.py
index f18f98d3e05..21e5d41cc7d 100644
--- a/zerver/tests/test_realm.py
+++ b/zerver/tests/test_realm.py
@@ -58,11 +58,7 @@ from zerver.lib.test_helpers import (
read_test_image_file,
)
from zerver.lib.thumbnail import ThumbnailFormat
-from zerver.lib.upload import (
- delete_message_attachments,
- upload_avatar_image,
- upload_message_attachment,
-)
+from zerver.lib.upload import upload_avatar_image, upload_message_attachment
from zerver.models import (
Attachment,
CustomProfileField,
@@ -3068,7 +3064,6 @@ class ScrubRealmTest(ZulipTestCase):
self.assertEqual([p for p in Path(settings.LOCAL_FILES_DIR).rglob("*") if p.is_file()], [])
- path_ids = []
small_thumb = ThumbnailFormat("webp", 50, 50, animated=False)
big_thumb = ThumbnailFormat("webp", 100, 100, animated=False)
with (
@@ -3076,27 +3071,12 @@ class ScrubRealmTest(ZulipTestCase):
self.captureOnCommitCallbacks(execute=True),
):
for n in range(1, 4):
- url = upload_message_attachment(
+ upload_message_attachment(
f"img-{n}.png", "image/png", read_test_image_file("img.png"), hamlet
- )[0]
- path_id = re.sub(r"/user_uploads/", "", url)
- self.assertTrue(os.path.isfile(os.path.join(settings.LOCAL_FILES_DIR, path_id)))
- path_ids.append(path_id)
+ )
self.assert_length([p for p in Path(settings.LOCAL_FILES_DIR).rglob("*") if p.is_file()], 9)
- with mock.patch(
- "zerver.actions.realm_settings.delete_message_attachments",
- side_effect=delete_message_attachments,
- ) as p:
- do_delete_all_realm_attachments(realm, batch_size=2)
-
- self.assertEqual(p.call_count, 2)
- p.assert_has_calls(
- [
- mock.call([path_ids[0], path_ids[1]]),
- mock.call([path_ids[2]]),
- ]
- )
+ do_delete_all_realm_attachments(realm)
self.assertEqual(Attachment.objects.filter(realm=realm).count(), 0)
self.assertEqual(ImageAttachment.objects.all().count(), 0)
diff --git a/zerver/tests/test_upload_local.py b/zerver/tests/test_upload_local.py
index 46a158d57a3..40815e017c3 100644
--- a/zerver/tests/test_upload_local.py
+++ b/zerver/tests/test_upload_local.py
@@ -1,6 +1,7 @@
import os
import re
from io import BytesIO
+from pathlib import Path
from urllib.parse import urlsplit
import pyvips
@@ -127,6 +128,9 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
assert settings.LOCAL_UPLOADS_DIR is not None
assert settings.LOCAL_FILES_DIR is not None
+ file_list = list(Path(settings.LOCAL_FILES_DIR).rglob("*"))
+ self.assertEqual(sum(1 for item in file_list if item.is_file()), 0)
+
user_profile = self.example_user("hamlet")
path_ids = []
for n in range(1, 1005):
@@ -138,10 +142,21 @@ class LocalStorageTest(UploadSerializeMixin, ZulipTestCase):
file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
self.assertTrue(os.path.isfile(file_path))
- delete_message_attachments(path_ids)
- for path_id in path_ids:
- file_path = os.path.join(settings.LOCAL_FILES_DIR, path_id)
- self.assertFalse(os.path.isfile(file_path))
+ # Make synthetic .info files and thumbnail files, to ensure those are cleaned up
+ with open(file_path + ".info", "w") as fh:
+ fh.write("{}")
+ os.makedirs(os.path.join(settings.LOCAL_FILES_DIR, "thumbnail", path_id))
+ with open(
+ os.path.join(settings.LOCAL_FILES_DIR, "thumbnail", path_id, "100x100.webp"), "w"
+ ) as fh:
+ fh.write("...")
+
+ with delete_message_attachments() as delete_one:
+ for path_id in path_ids:
+ delete_one(path_id)
+
+ file_list = list(Path(settings.LOCAL_FILES_DIR).rglob("*"))
+ self.assertEqual(sum(1 for item in file_list if item.is_file()), 0)
def test_all_message_attachments(self) -> None:
write_local_file("files", "foo", b"content")
diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.py
index 3db8e8af41c..edc28f3f363 100644
--- a/zerver/tests/test_upload_s3.py
+++ b/zerver/tests/test_upload_s3.py
@@ -191,7 +191,9 @@ class S3Test(ZulipTestCase):
path_ids.append(path_id)
with patch.object(S3UploadBackend, "delete_message_attachment") as single_delete:
- delete_message_attachments(path_ids)
+ with delete_message_attachments() as delete_one:
+ for path_id in path_ids:
+ delete_one(path_id)
single_delete.assert_not_called()
for path_id in path_ids:
with self.assertRaises(botocore.exceptions.ClientError):