Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
slack_import: Don't delete a concurrent import's realm on conflict.
Aman Agrawal8dbd5f83dba9
diff --git a/zerver/actions/data_import.py b/zerver/actions/data_import.pyindex 6eee530782f..fe558346793 100644--- a/zerver/actions/data_import.py+++ b/zerver/actions/data_import.py@@ -3,10 +3,12 @@ import loggingimport osimport shutilimport tempfile+from datetime import timedeltafrom typing import Anyfrom django.conf import settings-from django.db import transaction+from django.db import IntegrityError, transaction+from django.utils.timezone import now as timezone_nowfrom confirmation import settings as confirmation_settingsfrom zerver.actions.create_realm import get_email_address_visibility_default@@ -24,6 +26,20 @@ from zerver.models.users import RealmUserDefault, UserProfile, get_user_by_delivlogger = logging.getLogger("zulip.registration")+def is_string_id_unique_violation(e: BaseException) -> bool:+ """True when e is the IntegrityError from violating the unique constraint+ on Realm.string_id -- i.e. the subdomain is already taken by another+ realm. Other IntegrityErrors (e.g. genuine bugs elsewhere in the import)+ return False, so they get the normal failure handling rather than being+ mistaken for a taken subdomain."""+ if not isinstance(e, IntegrityError):+ return False+ # Django wraps the underlying psycopg2 error as __cause__; its+ # diagnostics carry the Postgres constraint name.+ diag = getattr(e.__cause__, "diag", None)+ return getattr(diag, "constraint_name", None) == "zerver_realm_string_id_key"++def import_slack_data(event: dict[str, Any]) -> None:# This is only possible if data imports were enqueued before the# setting was turned off.@@ -121,18 +137,44 @@ def import_slack_data(event: dict[str, Any]) -> None:except Exception as e:logger.exception(e)try:- # Clean up the realm if the import failedpreregistration_realm.created_realm = Nonepreregistration_realm.data_import_metadata["is_import_work_queued"] = Falseif type(e) is SlackImportInvalidFileError:# Store the error to be displayed to the user.preregistration_realm.data_import_metadata["invalid_file_error_message"] = str(e)++ # do_import_realm creates the realm with this string_id. If a+ # concurrent or earlier import of the same subdomain won the+ # race to create it, our realm insert violates the unique+ # constraint on Realm.string_id and do_import_realm raises that+ # IntegrityError. The existing realm belongs to the other+ # import, so we must not clean it up: deleting it would destroy+ # their data and can deadlock against their in-progress work on+ # zerver_userprofile. We record the conflict for the status poll+ # to surface instead.+ subdomain_taken = is_string_id_unique_violation(e)+ if subdomain_taken:+ preregistration_realm.data_import_metadata["subdomain_unavailable"] = Truepreregistration_realm.save()- with transaction.atomic(durable=True):- realm = Realm.objects.select_for_update(no_key=False).get(string_id=string_id)- do_delete_all_realm_attachments(realm)- realm.delete()+ # For any other failure -- including IntegrityErrors from+ # genuine bugs on some other constraint -- delete the realm+ # this import created, if it got that far. A failure before+ # do_import_realm creates the realm (e.g. an invalid-file error+ # during conversion) leaves no such realm, so the get() below+ # raises Realm.DoesNotExist, which we swallow. Otherwise the+ # realm with this string_id is the (possibly half-imported) one+ # we created. The age assertion is a last line of defense+ # against a bug ever pointing this deletion at an established+ # realm; a Slack import's realm is created at conversion time,+ # so it is always far younger than a day by the time we get+ # here.+ if not subdomain_taken:+ with transaction.atomic(durable=True):+ realm = Realm.objects.select_for_update(no_key=False).get(string_id=string_id)+ assert realm.date_created >= timezone_now() - timedelta(hours=24)+ do_delete_all_realm_attachments(realm)+ realm.delete()except Realm.DoesNotExist:passraisediff --git a/zerver/tests/test_slack_importer.py b/zerver/tests/test_slack_importer.pyindex 6e0b5ed7607..bff0cfa055a 100644--- a/zerver/tests/test_slack_importer.py+++ b/zerver/tests/test_slack_importer.py@@ -5,6 +5,7 @@ import tempfileimport zipfilefrom collections.abc import Iteratorfrom io import BytesIO+from types import SimpleNamespacefrom typing import TYPE_CHECKING, Anyfrom unittest import mockfrom unittest.mock import ANY@@ -14,6 +15,7 @@ import orjsonimport responsesfrom attr import dataclassfrom django.conf import settings+from django.db import IntegrityErrorfrom django.http import HttpResponsefrom django.utils.timezone import now as timezone_nowfrom requests.models import PreparedRequest@@ -168,6 +170,26 @@ def request_callback(request: PreparedRequest) -> tuple[int, dict[str, str], bytreturn (200, {}, orjson.dumps({"ok": True, "team": {"id": team_id, "domain": team_domain}}))+class FakeUniqueViolationError(Exception):+ """Stand-in for the psycopg2 UniqueViolation that Django exposes as+ IntegrityError.__cause__, carrying the diagnostics (diag.constraint_name)+ that import_slack_data inspects."""++ def __init__(self, message: str, constraint_name: str) -> None:+ super().__init__(message)+ self.diag = SimpleNamespace(constraint_name=constraint_name)+++def slack_import_integrity_error(constraint_name: str) -> IntegrityError:+ """Build the IntegrityError Django raises when an INSERT violates a unique+ constraint, so import_slack_data can recognize a taken subdomain from the+ constraint name."""+ message = f'duplicate key value violates unique constraint "{constraint_name}"'+ error = IntegrityError(message)+ error.__cause__ = FakeUniqueViolationError(message, constraint_name)+ return error++class SlackImporter(ZulipTestCase):def run_channel_message_to_zerver_message_with_fixtures(self, fixture_names: list[str], **kwargs: dict[str, Any]@@ -2930,6 +2952,112 @@ To Doself.assertFalse(prereg_realm.data_import_metadata["is_import_work_queued"])self.assertFalse(Realm.objects.filter(string_id=prereg_realm.string_id).exists())+ @mock.patch("zerver.actions.data_import.do_import_realm")+ @mock.patch("zerver.actions.data_import.do_convert_zipfile")+ @mock.patch("zerver.actions.data_import.save_attachment_contents")+ def test_import_slack_data_failure_keeps_concurrently_created_realm(+ self,+ mock_save_attachment_contents: mock.Mock,+ mock_do_convert_zipfile: mock.Mock,+ mock_do_import_realm: mock.Mock,+ ) -> None:+ # A concurrent import of the same subdomain wins the race to create+ # the realm while this import runs; do_import_realm then fails with an+ # IntegrityError on the unique string_id. This import created nothing,+ # so it must not delete the concurrently created realm -- doing so+ # would destroy that realm's data and can deadlock against its+ # in-progress work.+ prereg_realm = PreregistrationRealm.objects.create(+ string_id="test-realm",+ name="Test Realm",+ email="[email protected]",+ data_import_metadata={"import_from": "slack"},+ )++ def create_realm_then_conflict(*args: object, **kwargs: object) -> Realm:+ other_realm = do_create_realm(string_id=prereg_realm.string_id, name=prereg_realm.name)+ UserProfile.objects.create(+ realm=other_realm,+ delivery_email="[email protected]",+ email="[email protected]",+ )+ raise slack_import_integrity_error("zerver_realm_string_id_key")++ mock_do_import_realm.side_effect = create_realm_then_conflict+ event = {+ "preregistration_realm_id": prereg_realm.id,+ "filename": "import/test/slack.zip",+ "slack_access_token": "xoxb-valid-token",+ }++ with (+ self.assertLogs("zulip.registration", "ERROR") as logs,+ self.assertRaises(IntegrityError),+ ):+ import_slack_data(event)+ self.assertIn("zerver_realm_string_id_key", logs.output[0])++ # The concurrently created realm and its data must be untouched.+ other_realm = Realm.objects.get(string_id=prereg_realm.string_id)+ self.assertTrue(+ UserProfile.objects.filter(+ realm=other_realm, delivery_email="[email protected]"+ ).exists()+ )+ prereg_realm.refresh_from_db()+ self.assertIsNone(prereg_realm.created_realm)+ self.assertFalse(prereg_realm.data_import_metadata["is_import_work_queued"])+ # The conflict is recorded so the status poll can surface it.+ self.assertTrue(prereg_realm.data_import_metadata["subdomain_unavailable"])++ @mock.patch("zerver.actions.data_import.do_import_realm")+ @mock.patch("zerver.actions.data_import.do_convert_zipfile")+ @mock.patch("zerver.actions.data_import.save_attachment_contents")+ def test_import_slack_data_failure_unrelated_integrity_error(+ self,+ mock_save_attachment_contents: mock.Mock,+ mock_do_convert_zipfile: mock.Mock,+ mock_do_import_realm: mock.Mock,+ ) -> None:+ # An IntegrityError that is not the unique violation on Realm.string_id+ # -- e.g. a genuine bug in the import code hitting some other constraint+ # -- must be treated like any other failure: the half-imported realm+ # this import created is cleaned up, and the subdomain is not reported+ # as unavailable.+ prereg_realm = PreregistrationRealm.objects.create(+ string_id="test-realm",+ name="Test Realm",+ email="[email protected]",+ data_import_metadata={"import_from": "slack"},+ )++ def create_realm_then_unrelated_conflict(*args: object, **kwargs: object) -> Realm:+ do_create_realm(string_id=prereg_realm.string_id, name=prereg_realm.name)+ raise slack_import_integrity_error("zerver_useractivityinterval_uniq")++ mock_do_import_realm.side_effect = create_realm_then_unrelated_conflict+ event = {+ "preregistration_realm_id": prereg_realm.id,+ "filename": "import/test/slack.zip",+ "slack_access_token": "xoxb-valid-token",+ }++ with (+ self.assertLogs("zulip.registration", "ERROR") as logs,+ self.assertRaises(IntegrityError),+ ):+ import_slack_data(event)+ self.assertIn("zerver_useractivityinterval_uniq", logs.output[0])++ prereg_realm.refresh_from_db()+ self.assertIsNone(prereg_realm.created_realm)+ self.assertFalse(prereg_realm.data_import_metadata["is_import_work_queued"])+ # The realm this import created is cleaned up, since this is not a+ # subdomain conflict.+ self.assertFalse(Realm.objects.filter(string_id=prereg_realm.string_id).exists())+ # A non-string_id error must not be reported as a taken subdomain.+ self.assertNotIn("subdomain_unavailable", prereg_realm.data_import_metadata)+@responses.activatedef test_cancel_realm_import(self) -> None:# Choose import from slack