Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
upload: Make upload backend instantiation lazy.
Alex Vandiver42d584796a38
diff --git a/zerver/lib/test_helpers.py b/zerver/lib/test_helpers.pyindex efdfa6d25bd..fbae56d46b6 100644--- a/zerver/lib/test_helpers.py+++ b/zerver/lib/test_helpers.py@@ -628,10 +628,7 @@ def use_s3_backend(method: Callable[P, None]) -> Callable[P, None]:@override_settings(LOCAL_FILES_DIR=None)def new_method(*args: P.args, **kwargs: P.kwargs) -> None:backend = S3UploadBackend()- with (- mock.patch("zerver.lib.upload.upload_backend", backend),- mock.patch("zerver.views.tusd.upload_backend", backend),- ):+ with mock.patch("zerver.lib.upload._upload_backend", backend):return method(*args, **kwargs)return new_methoddiff --git a/zerver/lib/test_runner.py b/zerver/lib/test_runner.pyindex c00323a265c..6fdc282f660 100644--- a/zerver/lib/test_runner.py+++ b/zerver/lib/test_runner.py@@ -10,6 +10,7 @@ from unittest.result import TestResultimport orjsonfrom django.conf import settings+from django.core.signals import setting_changedfrom django.db import ProgrammingError, connectionsfrom django.test import runner as django_runnerfrom django.test.runner import DiscoverRunner@@ -21,12 +22,25 @@ from scripts.lib.zulip_tools import (get_dev_uuid_var_path,get_or_create_dev_uuid_var_path,)-from zerver.lib import test_helpers+from zerver.lib import test_helpers, uploadfrom zerver.lib.partial import partialfrom zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.test_fixtures import BACKEND_DATABASE_TEMPLATEfrom zerver.lib.test_helpers import append_instrumentation_data, write_instrumentation_reports++def _reset_upload_backend_on_settings_change(*, setting: str, **kwargs: object) -> None:+ # The upload backend is lazy-initialized from settings.LOCAL_UPLOADS_DIR+ # (and related settings) on first use. A test that overrides those via+ # override_settings() without @use_s3_backend would otherwise cache a+ # backend that no longer matches the settings active for later tests+ # in the same worker.+ if setting in ("LOCAL_UPLOADS_DIR", "S3_AUTH_UPLOADS_BUCKET", "S3_AVATAR_BUCKET"):+ upload._upload_backend = None+++setting_changed.connect(_reset_upload_backend_on_settings_change)+# We need to pick an ID for this test-backend invocation, and store it# in this global so it can be used in init_worker; this is used to# ensure the database IDs we select are unique for each `test-backend`@@ -250,14 +264,6 @@ def initialize_worker_path(worker_id: int) -> None:settings.LOCAL_AVATARS_DIR = os.path.join(settings.LOCAL_UPLOADS_DIR, "avatars")settings.LOCAL_FILES_DIR = os.path.join(settings.LOCAL_UPLOADS_DIR, "files")- # Perform the import of upload_backend now, because the backend is- # chosen at import time; this prevents @use_s3_backend from- # effectively caching the backend- from zerver.lib.upload import upload_backend- from zerver.lib.upload.local import LocalUploadBackend-- assert isinstance(upload_backend, LocalUploadBackend)-class Runner(DiscoverRunner):parallel_test_suite = ParallelTestSuitediff --git a/zerver/lib/upload/__init__.py b/zerver/lib/upload/__init__.pyindex 5d97cc53bc4..140ac7b2034 100644--- a/zerver/lib/upload/__init__.py+++ b/zerver/lib/upload/__init__.py@@ -173,25 +173,32 @@ def get_file_info(user_file: UploadedFile) -> tuple[str, str]:# Common and wrappers-if settings.LOCAL_UPLOADS_DIR is not None:- from zerver.lib.upload.local import LocalUploadBackend+_upload_backend: ZulipUploadBackend | None = None- upload_backend: ZulipUploadBackend = LocalUploadBackend()-else: # nocoverage- from zerver.lib.upload.s3 import S3UploadBackend- upload_backend = S3UploadBackend()+def get_upload_backend() -> ZulipUploadBackend:+ global _upload_backend+ if _upload_backend is None:+ if settings.LOCAL_UPLOADS_DIR is not None:+ from zerver.lib.upload.local import LocalUploadBackend++ _upload_backend = LocalUploadBackend()+ else: # nocoverage+ from zerver.lib.upload.s3 import S3UploadBackend++ _upload_backend = S3UploadBackend()+ return _upload_backend# Message attachment uploadsdef get_public_upload_root_url() -> str:- return upload_backend.get_public_upload_root_url()+ return get_upload_backend().get_public_upload_root_url()def generate_message_upload_path(realm_id: str, uploaded_file_name: str) -> str:- return upload_backend.generate_message_upload_path(realm_id, uploaded_file_name)+ return get_upload_backend().generate_message_upload_path(realm_id, uploaded_file_name)def store_message_attachment(@@ -202,7 +209,7 @@ def store_message_attachment(user_profile: UserProfile | None,target_realm: Realm | None,) -> None:- upload_backend.store_message_attachment(+ get_upload_backend().store_message_attachment(path_id, filename, content_type, file_data, user_profile, target_realm)@@ -247,7 +254,7 @@ def upload_message_attachment() -> tuple[str, str]:if target_realm is None:target_realm = user_profile.realm- path_id = upload_backend.generate_message_upload_path(+ path_id = get_upload_backend().generate_message_upload_path(str(target_realm.id), sanitize_name(uploaded_file_name))content_type = maybe_add_charset(content_type, file_data)@@ -257,7 +264,7 @@ def upload_message_attachment(uploaded_file_name = re.sub(r"\x00", "", uploaded_file_name)with transaction.atomic(durable=True):- upload_backend.store_message_attachment(+ get_upload_backend().store_message_attachment(path_id,uploaded_file_name,content_type,@@ -308,15 +315,15 @@ def upload_message_attachment_from_request(def attachment_source(path_id: str) -> StreamingSourceWithSize:- return upload_backend.attachment_source(path_id)+ return get_upload_backend().attachment_source(path_id)def save_attachment_contents(path_id: str, filehandle: IO[bytes]) -> None:- upload_backend.save_attachment_contents(path_id, filehandle)+ get_upload_backend().save_attachment_contents(path_id, filehandle)def delete_message_attachment(path_id: str, *, raw_path: bool = False) -> None:- upload_backend.delete_message_attachment_from_storage(path_id)+ get_upload_backend().delete_message_attachment_from_storage(path_id)@contextmanager@@ -334,7 +341,7 @@ def delete_message_attachments(db_class._default_manager.filter(path_id__in=path_ids).delete()flush_path_ids = delete_from_database- with upload_backend.delete_message_attachments_from_storage(+ with get_upload_backend().delete_message_attachments_from_storage(raw_paths=raw_paths, flush=flush_path_ids) as delete_one:yield delete_one@@ -343,18 +350,18 @@ def delete_message_attachments(def all_message_attachments(*, include_thumbnails: bool = False, prefix: str = "") -> Iterator[tuple[str, datetime]]:- return upload_backend.all_message_attachments(include_thumbnails, prefix)+ return get_upload_backend().all_message_attachments(include_thumbnails, prefix)# Avatar image uploadsdef get_avatar_url(hash_key: str, medium: bool = False) -> str:- return upload_backend.get_avatar_url(hash_key, medium)+ return get_upload_backend().get_avatar_url(hash_key, medium)def get_avatar_path(hash_key: str, medium: bool = False) -> str:- return upload_backend.get_avatar_path(hash_key, medium)+ return get_upload_backend().get_avatar_path(hash_key, medium)def write_avatar_images(@@ -367,7 +374,7 @@ def write_avatar_images(future: bool = True,) -> None:if backend is None:- backend = upload_backend+ backend = get_upload_backend()backend.store_single_avatar_image(file_path + ".original",user_profile=user_profile,@@ -403,7 +410,7 @@ def write_jdenticon_avatars(future: bool = True,) -> None:if backend is None:- backend = upload_backend+ backend = get_upload_backend()backend.store_single_avatar_image(backend.get_avatar_path(file_path, medium=False),@@ -450,7 +457,7 @@ def copy_avatar(source_profile: UserProfile, target_profile: UserProfile) -> Nonsource_file_path = user_avatar_path(source_profile, future=False)target_file_path = user_avatar_path(target_profile, future=True)- image_data, content_type = upload_backend.get_avatar_contents(+ image_data, content_type = get_upload_backend().get_avatar_contents(source_file_path, source_profile.avatar_source)write_avatar_images(@@ -461,7 +468,7 @@ def copy_avatar(source_profile: UserProfile, target_profile: UserProfile) -> Nondef ensure_avatar_image(user_profile: UserProfile, medium: bool = False) -> None:file_path = user_avatar_path(user_profile)- final_file_path = upload_backend.get_avatar_path(file_path, medium)+ final_file_path = get_upload_backend().get_avatar_path(file_path, medium)if settings.LOCAL_AVATARS_DIR is not None:output_path = os.path.join(@@ -472,13 +479,13 @@ def ensure_avatar_image(user_profile: UserProfile, medium: bool = False) -> Noneif os.path.isfile(output_path):return- image_data, _ = upload_backend.get_avatar_contents(file_path, user_profile.avatar_source)+ image_data, _ = get_upload_backend().get_avatar_contents(file_path, user_profile.avatar_source)if medium:resized_avatar = resize_avatar(image_data, MEDIUM_AVATAR_SIZE)else:resized_avatar = resize_avatar(image_data)- upload_backend.store_single_avatar_image(+ get_upload_backend().store_single_avatar_image(final_file_path,user_profile=user_profile,image_data=resized_avatar,@@ -489,28 +496,28 @@ def ensure_avatar_image(user_profile: UserProfile, medium: bool = False) -> Nonedef delete_avatar_image(user_profile: UserProfile, avatar_version: int) -> None:path_id = user_avatar_base_path_from_ids(user_profile.id, avatar_version, user_profile.realm_id)- upload_backend.delete_avatar_image_from_storage(path_id)+ get_upload_backend().delete_avatar_image_from_storage(path_id)# Realm icon and logo uploadsdef get_uploaded_realm_icon_url(realm_id: int, version: int) -> str:- return upload_backend.get_realm_icon_url(realm_id, version)+ return get_upload_backend().get_realm_icon_url(realm_id, version)def get_uploaded_realm_logo_url(realm_id: int, version: int, night: bool) -> str:- return upload_backend.get_realm_logo_url(realm_id, version, night)+ return get_upload_backend().get_realm_logo_url(realm_id, version, night)def realm_avatar_and_logo_path(realm: Realm) -> str:- return upload_backend.realm_avatar_and_logo_path(realm)+ return get_upload_backend().realm_avatar_and_logo_path(realm)def upload_icon_image(user_file: IO[bytes], user_profile: UserProfile, content_type: str) -> None:if content_type not in THUMBNAIL_ACCEPT_IMAGE_TYPES:raise BadImageError(_("Invalid image format"))- upload_backend.store_realm_icon_image(user_file, user_profile, content_type)+ get_upload_backend().store_realm_icon_image(user_file, user_profile, content_type)def upload_logo_image(@@ -518,14 +525,14 @@ def upload_logo_image() -> None:if content_type not in THUMBNAIL_ACCEPT_IMAGE_TYPES:raise BadImageError(_("Invalid image format"))- upload_backend.store_realm_logo_image(user_file, user_profile, night, content_type)+ get_upload_backend().store_realm_logo_image(user_file, user_profile, night, content_type)# Realm emoji uploadsdef get_emoji_url(emoji_file_name: str, realm_id: int, still: bool = False) -> str:- return upload_backend.get_emoji_url(emoji_file_name, realm_id, still)+ return get_upload_backend().get_emoji_url(emoji_file_name, realm_id, still)def upload_emoji_image(@@ -536,7 +543,7 @@ def upload_emoji_image(backend: ZulipUploadBackend | None = None,) -> bool:if backend is None:- backend = upload_backend+ backend = get_upload_backend()# Emoji are served in the format that they are uploaded, so must# be _both_ an image format that we're willing to thumbnail, _and_@@ -605,7 +612,7 @@ def handle_reupload_emojis_event(realm: Realm, logger: logging.Logger) -> None:logger.info("Processing emoji %s", realm_emoji.id)emoji_filename = realm_emoji.file_nameassert emoji_filename is not None- emoji_url = upload_backend.get_emoji_url(emoji_filename, realm_emoji.realm_id)+ emoji_url = get_emoji_url(emoji_filename, realm_emoji.realm_id)if emoji_url.startswith("/"):emoji_url = urljoin(realm_emoji.realm.url, emoji_url)@@ -630,16 +637,16 @@ def handle_reupload_emojis_event(realm: Realm, logger: logging.Logger) -> None:def get_export_tarball_url(realm: Realm, export_path: str) -> str:- return upload_backend.get_export_tarball_url(realm, export_path)+ return get_upload_backend().get_export_tarball_url(realm, export_path)def upload_export_tarball(realm: Realm, tarball_path: str, percent_callback: Callable[[Any], None] | None = None) -> str:- return upload_backend.store_export_tarball(+ return get_upload_backend().store_export_tarball(realm, tarball_path, percent_callback=percent_callback)def delete_export_tarball(export_path: str) -> None:- upload_backend.delete_export_tarball_from_storage(export_path)+ get_upload_backend().delete_export_tarball_from_storage(export_path)diff --git a/zerver/tests/test_delete_unclaimed_attachments.py b/zerver/tests/test_delete_unclaimed_attachments.pyindex 7d3b2449d00..70dfd3b70d2 100644--- a/zerver/tests/test_delete_unclaimed_attachments.py+++ b/zerver/tests/test_delete_unclaimed_attachments.py@@ -445,7 +445,7 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):for _ in range(3):self.make_attachment("img.png")- backend = zerver.lib.upload.upload_backend+ backend = zerver.lib.upload.get_upload_backend()assert isinstance(backend, S3UploadBackend)uploads_bucket = backend.uploads_bucketwith (@@ -487,7 +487,7 @@ class UnclaimedAttachmentTest(UploadSerializeMixin, ZulipTestCase):clean_archived_data()# Removing unclaimed attachments now cleans them all out- backend = zerver.lib.upload.upload_backend+ backend = zerver.lib.upload.get_upload_backend()assert isinstance(backend, S3UploadBackend)uploads_bucket = backend.uploads_bucketwith (diff --git a/zerver/tests/test_import_export.py b/zerver/tests/test_import_export.pyindex f7d973b8c15..951c52cb91b 100644--- a/zerver/tests/test_import_export.py+++ b/zerver/tests/test_import_export.py@@ -215,16 +215,16 @@ class ExportFile(ZulipTestCase):realm = user_profile.realmwith get_test_image_file("img.png") as img_file:- upload.upload_backend.store_realm_icon_image(img_file, user_profile, "image/png")+ upload.get_upload_backend().store_realm_icon_image(img_file, user_profile, "image/png")do_change_icon_source(realm, Realm.ICON_UPLOADED, acting_user=None)with get_test_image_file("img.png") as img_file:- upload.upload_backend.store_realm_logo_image(+ upload.get_upload_backend().store_realm_logo_image(img_file, user_profile, night=False, content_type="image/png")do_change_logo_source(realm, Realm.LOGO_UPLOADED, False, acting_user=user_profile)with get_test_image_file("img.png") as img_file:- upload.upload_backend.store_realm_logo_image(+ upload.get_upload_backend().store_realm_logo_image(img_file, user_profile, night=True, content_type="image/png")do_change_logo_source(realm, Realm.LOGO_UPLOADED, True, acting_user=user_profile)diff --git a/zerver/tests/test_upload_s3.py b/zerver/tests/test_upload_s3.pyindex 0e194e64ac9..f466f8be76d 100644--- a/zerver/tests/test_upload_s3.py+++ b/zerver/tests/test_upload_s3.py@@ -374,7 +374,7 @@ class S3Test(ZulipTestCase):@use_s3_backenddef test_user_avatars_base(self) -> None:- backend = zerver.lib.upload.upload_backend+ backend = zerver.lib.upload.get_upload_backend()assert isinstance(backend, S3UploadBackend)self.assertEqual(backend.construct_public_upload_url_base(),@@ -561,7 +561,7 @@ class S3Test(ZulipTestCase):user_profile = self.example_user("hamlet")with get_test_image_file("img.png") as image_file:- zerver.lib.upload.upload_backend.store_realm_icon_image(+ zerver.lib.upload.get_upload_backend().store_realm_icon_image(image_file, user_profile, content_type="image/png")@@ -581,7 +581,7 @@ class S3Test(ZulipTestCase):user_profile = self.example_user("hamlet")with get_test_image_file("img.png") as image_file:- zerver.lib.upload.upload_backend.store_realm_logo_image(+ zerver.lib.upload.get_upload_backend().store_realm_logo_image(image_file, user_profile, night, "image/png")@@ -767,7 +767,7 @@ class S3Test(ZulipTestCase):with override_settings(S3_EXPORT_BUCKET=""):backend = S3UploadBackend()avatar_bucket = create_s3_buckets(settings.S3_AVATAR_BUCKET)[0]- with patch("zerver.lib.upload.upload_backend", backend):+ with patch("zerver.lib.upload._upload_backend", backend):public_url = upload_export_tarball(user_profile.realm, tarball_path)avatar_object_key = urlsplit(public_url).path.removeprefix("/")@@ -822,7 +822,7 @@ class S3Test(ZulipTestCase):with override_settings(S3_EXPORT_BUCKET=settings.S3_EXPORT_BUCKET):backend = S3UploadBackend()export_bucket = create_s3_buckets(settings.S3_EXPORT_BUCKET)[0]- with patch("zerver.lib.upload.upload_backend", backend):+ with patch("zerver.lib.upload._upload_backend", backend):public_url = upload_export_tarball(user_profile.realm, tarball_path)export_object_key = urlsplit(public_url).path.removeprefix("/")diff --git a/zerver/views/tusd.py b/zerver/views/tusd.pyindex 16d20e466bc..e50fe130ebc 100644--- a/zerver/views/tusd.py+++ b/zerver/views/tusd.py@@ -24,9 +24,9 @@ from zerver.lib.upload import (create_attachment,delete_message_attachment,generate_message_upload_path,+ get_upload_backend,maybe_add_charset,sanitize_name,- upload_backend,)from zerver.models import ArchivedAttachment, Attachment, PreregistrationRealm, Realm, UserProfile@@ -174,6 +174,7 @@ def handle_upload_pre_finish_hook(from zerver.lib.upload.s3 import S3UploadBackend+ upload_backend = get_upload_backend()assert isinstance(upload_backend, S3UploadBackend)key = upload_backend.uploads_bucket.Object(path_id)key.copy_from(