Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
edit_history: Migrate database to modernized edit history format.
Tim Abbott7e298365dc30
diff --git a/zerver/migrations/0377_message_edit_history_format.py b/zerver/migrations/0377_message_edit_history_format.pynew file mode 100644index 00000000000..428b200859d--- /dev/null+++ b/zerver/migrations/0377_message_edit_history_format.py@@ -0,0 +1,166 @@+import time+from typing import List, Optional++import orjson+from django.db import migrations, transaction+from django.db.backends.postgresql.schema import DatabaseSchemaEditor+from django.db.migrations.state import StateApps+from django.db.models import Min, Model+from typing_extensions import TypedDict++BATCH_SIZE = 10000+STREAM = 2++# Legacy TypedDict has "prev_topic" field for any edit_history entries that+# were saved to the database after the legacy "prev_subject" field stopped+# being written to the database in the pre-migration commit.+class LegacyEditHistoryEvent(TypedDict, total=False):+ user_id: int+ timestamp: int+ prev_stream: int+ prev_subject: str+ prev_topic: str+ prev_content: str+ prev_rendered_content: Optional[str]+ prev_rendered_content_version: Optional[int]+++class EditHistoryEvent(TypedDict, total=False):+ user_id: Optional[int]+ timestamp: int+ prev_stream: int+ stream: int+ prev_topic: str+ topic: str+ prev_content: str+ prev_rendered_content: Optional[str]+ prev_rendered_content_version: Optional[int]+++def backfill_message_edit_history_chunk(first_id: int, last_id: int, message_model: Model) -> None:+ """+ Migrate edit history events for the messages in the provided range to:+ * Rename prev_subject => prev_topic.+ * Provide topic and stream fields with the current values.++ The range of message IDs to be processed is inclusive on both ends.+ """+ messages = (+ message_model.objects.select_for_update()+ .only(+ "recipient",+ "recipient__type",+ "recipient__type_id",+ "subject",+ "edit_history",+ )+ .filter(edit_history__isnull=False, id__range=(first_id, last_id))+ )++ for message in messages:+ legacy_edit_history: List[LegacyEditHistoryEvent] = orjson.loads(message.edit_history)+ message_type = message.recipient.type+ modern_edit_history: List[EditHistoryEvent] = []++ # Only Stream messages have topic / stream edit history data.+ if message_type == STREAM:+ topic = message.subject+ stream_id = message.recipient.type_id++ for edit_history_event in legacy_edit_history:+ modern_entry: EditHistoryEvent = {+ "user_id": edit_history_event.get("user_id"),+ "timestamp": edit_history_event["timestamp"],+ }++ if "prev_content" in edit_history_event:+ modern_entry["prev_content"] = edit_history_event["prev_content"]+ modern_entry["prev_rendered_content"] = edit_history_event["prev_rendered_content"]+ modern_entry["prev_rendered_content_version"] = edit_history_event[+ "prev_rendered_content_version"+ ]++ if message_type == STREAM:+ if "prev_subject" in edit_history_event:+ # Add topic edit key/value pairs from legacy format.+ modern_entry["topic"] = topic+ modern_entry["prev_topic"] = edit_history_event["prev_subject"]++ # Because edit_history is ordered chronologically,+ # most recent to least recent, we set the topic+ # variable to the `prev_topic` value for this edit+ # for any subsequent topic edits in the loop.+ topic = edit_history_event["prev_subject"]++ elif "prev_topic" in edit_history_event:+ # Add topic edit key/value pairs from modern format.+ modern_entry["topic"] = topic+ modern_entry["prev_topic"] = edit_history_event["prev_topic"]++ # Same logic as above but for modern format.+ topic = edit_history_event["prev_topic"]++ if "prev_stream" in edit_history_event:+ # Add stream edit key/value pairs.+ modern_entry["stream"] = stream_id+ modern_entry["prev_stream"] = edit_history_event["prev_stream"]++ # Same logic as above for the topic variable.+ stream_id = edit_history_event["prev_stream"]++ modern_edit_history.append(modern_entry)++ message.edit_history = orjson.dumps(modern_edit_history).decode()++ message_model.objects.bulk_update(messages, ["edit_history"])+++def copy_and_update_message_edit_history(+ apps: StateApps, schema_editor: DatabaseSchemaEditor+) -> None:+ Message = apps.get_model("zerver", "Message")+ ArchivedMessage = apps.get_model("zerver", "ArchivedMessage")++ message_models = [Message, ArchivedMessage]+ for message_model in message_models:+ if not message_model.objects.filter(edit_history__isnull=False).exists():+ # No messages with "edit_history"+ continue++ first_id_to_update = message_model.objects.filter(edit_history__isnull=False).aggregate(+ Min("id")+ )["id__min"]++ last_id = message_model.objects.latest("id").id++ id_range_lower_bound = first_id_to_update+ id_range_upper_bound = first_id_to_update + BATCH_SIZE++ while id_range_upper_bound <= last_id:+ backfill_message_edit_history_chunk(+ id_range_lower_bound, id_range_upper_bound, message_model+ )+ print(f"Modernized edit history for {id_range_upper_bound}/{last_id} messages.")+ id_range_lower_bound = id_range_upper_bound + 1+ id_range_upper_bound = id_range_lower_bound + BATCH_SIZE+ time.sleep(0.1)++ if last_id >= id_range_lower_bound:+ # Copy/update for the last batch, or if only 1 message with edit_history in db+ backfill_message_edit_history_chunk(id_range_lower_bound, last_id, message_model)+++class Migration(migrations.Migration):+ atomic = False++ dependencies = [+ ("zerver", "0376_set_realmemoji_author_and_reupload_realmemoji"),+ ]++ operations = [+ migrations.RunPython(+ copy_and_update_message_edit_history,+ reverse_code=migrations.RunPython.noop,+ ),+ ]diff --git a/zerver/tests/test_migrations.py b/zerver/tests/test_migrations.pyindex f3bc90d2959..ed7d61b14b7 100644--- a/zerver/tests/test_migrations.py+++ b/zerver/tests/test_migrations.py@@ -4,7 +4,11 @@# You can also read# https://www.caktusgroup.com/blog/2016/02/02/writing-unit-tests-django-migrations/# to get a tutorial on the framework that inspired this feature.+from typing import Optional++import orjsonfrom django.db.migrations.state import StateApps+from django.utils.timezone import now as timezone_nowfrom zerver.lib.test_classes import MigrationsTestCasefrom zerver.lib.test_helpers import use_db_models@@ -26,63 +30,393 @@ from zerver.models import get_stream# been tested for a migration being merged.-class SubsNotificationSettingsTestCase(MigrationsTestCase): # nocoverage- __unittest_skip__ = True+class MessageEditHistoryLegacyFormats(MigrationsTestCase):+ __unittest_skip__ = False++ migrate_from = "0376_set_realmemoji_author_and_reupload_realmemoji"+ migrate_to = "0377_message_edit_history_format"++ msg_id: Optional[int] = None++ @use_db_models+ def setUpBeforeMigration(self, apps: StateApps) -> None:+ Recipient = apps.get_model("zerver", "Recipient")+ Message = apps.get_model("zerver", "Message")++ iago = self.example_user("iago")+ stream_name = "Denmark"+ denmark = get_stream(stream_name, iago.realm)+ denmark_recipient = Recipient.objects.get(type=2, type_id=denmark.id)++ self.msg_id = Message.objects.create(+ recipient_id=denmark_recipient.id,+ subject="topic 4",+ sender_id=iago.id,+ sending_client_id=1,+ content="current message text",+ date_sent=timezone_now(),+ ).id++ # topic edits contain only "prev_subject" field.+ # stream edits contain only "prev_stream" field.+ msg = Message.objects.filter(id=self.msg_id).first()+ msg.edit_history = orjson.dumps(+ [+ {+ "user_id": 11,+ "timestamp": 1644405050,+ "prev_stream": 3,+ "prev_subject": "topic 3",+ },+ {"user_id": 11, "timestamp": 1644405040, "prev_stream": 2},+ {+ "user_id": 11,+ "timestamp": 1644405030,+ "prev_content": "test content and topic edit",+ "prev_rendered_content": "<p>test content and topic edit</p>",+ "prev_rendered_content_version": 1,+ "prev_subject": "topic 2",+ },+ {"user_id": 11, "timestamp": 1644405020, "prev_subject": "topic 1"},+ {+ "user_id": 11,+ "timestamp": 1644405010,+ "prev_content": "test content only edit",+ "prev_rendered_content": "<p>test content only edit</p>",+ "prev_rendered_content_version": 1,+ },+ ]+ ).decode()+ msg.save(update_fields=["edit_history"])++ def test_message_legacy_edit_history_format(self) -> None:+ Message = self.apps.get_model("zerver", "Message")+ Recipient = self.apps.get_model("zerver", "Recipient")++ iago = self.example_user("iago")+ stream_name = "Denmark"+ denmark = get_stream(stream_name, iago.realm)++ msg = Message.objects.filter(id=self.msg_id).first()+ msg_stream_id = Recipient.objects.get(id=msg.recipient_id).type_id+ new_edit_history = orjson.loads(msg.edit_history)++ self.assert_length(new_edit_history, 5)- migrate_from = "0220_subscription_notification_settings"- migrate_to = "0221_subscription_notifications_data_migration"- RECIPIENT_PERSONAL = 1- RECIPIENT_STREAM = 2+ # stream and topic edit entry+ self.assertFalse("prev_subject" in new_edit_history[0])+ self.assertEqual(new_edit_history[0]["prev_topic"], "topic 3")+ self.assertEqual(new_edit_history[0]["topic"], msg.subject)+ self.assertEqual(new_edit_history[0]["prev_stream"], 3)+ self.assertEqual(new_edit_history[0]["stream"], msg_stream_id)+ self.assertEqual(new_edit_history[0]["stream"], denmark.id)+ self.assertEqual(+ set(new_edit_history[0].keys()),+ {"timestamp", "prev_topic", "topic", "prev_stream", "stream", "user_id"},+ )++ # stream only edit entry+ self.assertEqual(new_edit_history[1]["prev_stream"], 2)+ self.assertEqual(new_edit_history[1]["stream"], 3)+ self.assertEqual(+ set(new_edit_history[1].keys()), {"timestamp", "prev_stream", "stream", "user_id"}+ )++ # topic and content edit entry+ self.assertFalse("prev_subject" in new_edit_history[2])+ self.assertEqual(new_edit_history[2]["prev_topic"], "topic 2")+ self.assertEqual(new_edit_history[2]["topic"], "topic 3")+ self.assertEqual(new_edit_history[2]["prev_content"], "test content and topic edit")+ self.assertEqual(+ new_edit_history[2]["prev_rendered_content"], "<p>test content and topic edit</p>"+ )+ self.assertEqual(new_edit_history[2]["prev_rendered_content_version"], 1)+ self.assertEqual(+ set(new_edit_history[2].keys()),+ {+ "timestamp",+ "prev_topic",+ "topic",+ "prev_content",+ "prev_rendered_content",+ "prev_rendered_content_version",+ "user_id",+ },+ )++ # topic only edit entry+ self.assertFalse("prev_subject" in new_edit_history[3])+ self.assertEqual(new_edit_history[3]["prev_topic"], "topic 1")+ self.assertEqual(new_edit_history[3]["topic"], "topic 2")+ self.assertEqual(+ set(new_edit_history[3].keys()), {"timestamp", "prev_topic", "topic", "user_id"}+ )++ # content only edit entry - not retested because never changes+ self.assertEqual(new_edit_history[4]["prev_content"], "test content only edit")+ self.assertEqual(+ new_edit_history[4]["prev_rendered_content"], "<p>test content only edit</p>"+ )+ self.assertEqual(new_edit_history[4]["prev_rendered_content_version"], 1)+ self.assertEqual(+ set(new_edit_history[4].keys()),+ {+ "timestamp",+ "prev_content",+ "prev_rendered_content",+ "prev_rendered_content_version",+ "user_id",+ },+ )+++class MessageEditHistoryModernFormats(MigrationsTestCase):+ __unittest_skip__ = False++ migrate_from = "0376_set_realmemoji_author_and_reupload_realmemoji"+ migrate_to = "0377_message_edit_history_format"++ msg_id: Optional[int] = None@use_db_modelsdef setUpBeforeMigration(self, apps: StateApps) -> None:Recipient = apps.get_model("zerver", "Recipient")- Subscription = apps.get_model("zerver", "Subscription")+ Message = apps.get_model("zerver", "Message")++ iago = self.example_user("iago")+ stream_name = "Denmark"+ denmark = get_stream(stream_name, iago.realm)+ denmark_recipient = Recipient.objects.get(type=2, type_id=denmark.id)++ self.msg_id = Message.objects.create(+ recipient_id=denmark_recipient.id,+ subject="topic 4",+ sender_id=iago.id,+ sending_client_id=1,+ content="current message text",+ date_sent=timezone_now(),+ ).id++ msg = Message.objects.filter(id=self.msg_id).first()+ msg_stream_id = Recipient.objects.get(id=msg.recipient_id).type_id++ # topic edits contain "topic" and "prev_topic" fields.+ # stream edits contain "stream" and "prev_stream" fields.+ msg.edit_history = orjson.dumps(+ [+ {+ "user_id": 11,+ "timestamp": 1644405050,+ "stream": msg_stream_id,+ "prev_stream": 3,+ "topic": msg.subject,+ "prev_topic": "topic 3",+ },+ {"user_id": 11, "timestamp": 1644405040, "prev_stream": 2, "stream": 3},+ {+ "user_id": 11,+ "timestamp": 1644405030,+ "prev_content": "test content and topic edit",+ "prev_rendered_content": "<p>test content and topic edit</p>",+ "prev_rendered_content_version": 1,+ "prev_topic": "topic 2",+ "topic": "topic 3",+ },+ {+ "user_id": 11,+ "timestamp": 1644405020,+ "prev_topic": "topic 1",+ "topic": "topic 2",+ },+ ]+ ).decode()+ msg.save(update_fields=["edit_history"])++ def test_message_modern_edit_history_format(self) -> None:+ Message = self.apps.get_model("zerver", "Message")+ Recipient = self.apps.get_model("zerver", "Recipient")iago = self.example_user("iago")- iago.enable_stream_desktop_notifications = True- iago.enable_stream_audible_notifications = False- iago.enable_desktop_notifications = True- iago.enable_online_push_notifications = True- iago.enable_sounds = False- iago.save()+ stream_name = "Denmark"+ denmark = get_stream(stream_name, iago.realm)++ msg = Message.objects.filter(id=self.msg_id).first()+ msg_stream_id = Recipient.objects.get(id=msg.recipient_id).type_id+ new_edit_history = orjson.loads(msg.edit_history)++ self.assert_length(new_edit_history, 4)++ # stream and topic edit entry+ self.assertEqual(new_edit_history[0]["prev_topic"], "topic 3")+ self.assertEqual(new_edit_history[0]["topic"], msg.subject)+ self.assertEqual(new_edit_history[0]["prev_stream"], 3)+ self.assertEqual(new_edit_history[0]["stream"], msg_stream_id)+ self.assertEqual(new_edit_history[0]["stream"], denmark.id)+ self.assertEqual(+ set(new_edit_history[0].keys()),+ {"timestamp", "prev_topic", "topic", "prev_stream", "stream", "user_id"},+ )++ # stream only edit entry+ self.assertEqual(new_edit_history[1]["prev_stream"], 2)+ self.assertEqual(new_edit_history[1]["stream"], 3)+ self.assertEqual(+ set(new_edit_history[1].keys()), {"timestamp", "prev_stream", "stream", "user_id"}+ )++ # topic and content edit entry+ self.assertEqual(new_edit_history[2]["prev_topic"], "topic 2")+ self.assertEqual(new_edit_history[2]["topic"], "topic 3")+ self.assertEqual(new_edit_history[2]["prev_content"], "test content and topic edit")+ self.assertEqual(+ new_edit_history[2]["prev_rendered_content"], "<p>test content and topic edit</p>"+ )+ self.assertEqual(new_edit_history[2]["prev_rendered_content_version"], 1)+ self.assertEqual(+ set(new_edit_history[2].keys()),+ {+ "timestamp",+ "prev_topic",+ "topic",+ "prev_content",+ "prev_rendered_content",+ "prev_rendered_content_version",+ "user_id",+ },+ )++ # topic only edit entry+ self.assertEqual(new_edit_history[3]["prev_topic"], "topic 1")+ self.assertEqual(new_edit_history[3]["topic"], "topic 2")+ self.assertEqual(+ set(new_edit_history[3].keys()), {"timestamp", "prev_topic", "topic", "user_id"}+ )+++class MessageEditHistoryIntermediateFormats(MigrationsTestCase):+ __unittest_skip__ = False++ migrate_from = "0376_set_realmemoji_author_and_reupload_realmemoji"+ migrate_to = "0377_message_edit_history_format"++ msg_id: Optional[int] = None++ @use_db_models+ def setUpBeforeMigration(self, apps: StateApps) -> None:+ Recipient = apps.get_model("zerver", "Recipient")+ Message = apps.get_model("zerver", "Message")+ iago = self.example_user("iago")stream_name = "Denmark"denmark = get_stream(stream_name, iago.realm)- denmark_recipient = Recipient.objects.get(type=self.RECIPIENT_STREAM, type_id=denmark.id)- denmark_sub = Subscription.objects.get(user_profile=iago, recipient=denmark_recipient)- denmark_sub.desktop_notifications = False- denmark_sub.audible_notifications = False- denmark_sub.save(update_fields=["desktop_notifications", "audible_notifications"])-- iago_recipient = Recipient.objects.get(type=self.RECIPIENT_PERSONAL, type_id=iago.id)- iago_sub = Subscription.objects.get(user_profile=iago, recipient=iago_recipient)- iago_sub.desktop_notifications = False- iago_sub.audible_notifications = False- iago_sub.push_notifications = True- iago_sub.save(- update_fields=["desktop_notifications", "audible_notifications", "push_notifications"]- )-- def test_subs_migrated(self) -> None:- UserProfile = self.apps.get_model("zerver", "UserProfile")+ denmark_recipient = Recipient.objects.get(type=2, type_id=denmark.id)++ self.msg_id = Message.objects.create(+ recipient_id=denmark_recipient.id,+ subject="topic 4",+ sender_id=iago.id,+ sending_client_id=1,+ content="current message text",+ date_sent=timezone_now(),+ ).id++ msg = Message.objects.filter(id=self.msg_id).first()+ msg_stream_id = Recipient.objects.get(id=msg.recipient_id).type_id++ # topic edits contain "prev_subject", "topic" and "prev_topic" fields.+ # stream edits contain "stream" and "prev_stream" fields.+ msg.edit_history = orjson.dumps(+ [+ {+ "user_id": 11,+ "timestamp": 1644405050,+ "stream": msg_stream_id,+ "prev_stream": 3,+ "topic": msg.subject,+ "prev_topic": "topic 3",+ "prev_subject": "topic 3",+ },+ {"user_id": 11, "timestamp": 1644405040, "prev_stream": 2, "stream": 3},+ {+ "user_id": 11,+ "timestamp": 1644405030,+ "prev_content": "test content and topic edit",+ "prev_rendered_content": "<p>test content and topic edit</p>",+ "prev_rendered_content_version": 1,+ "prev_topic": "topic 2",+ "prev_subject": "topic 2",+ "topic": "topic 3",+ },+ {+ "user_id": 11,+ "timestamp": 1644405020,+ "prev_topic": "topic 1",+ "prev_subject": "topic 1",+ "topic": "topic 2",+ },+ ]+ ).decode()+ msg.save(update_fields=["edit_history"])++ def test_message_temporary_edit_history_format(self) -> None:+ Message = self.apps.get_model("zerver", "Message")Recipient = self.apps.get_model("zerver", "Recipient")- Realm = self.apps.get_model("zerver", "Realm")- Subscription = self.apps.get_model("zerver", "Subscription")- Stream = self.apps.get_model("zerver", "Stream")- realm = Realm.objects.get(string_id="zulip")- iago = UserProfile.objects.get(email="[email protected]", realm=realm)+ iago = self.example_user("iago")stream_name = "Denmark"- denmark = Stream.objects.get(realm=iago.realm, name=stream_name)- denmark_recipient = Recipient.objects.get(type=self.RECIPIENT_STREAM, type_id=denmark.id)- denmark_sub = Subscription.objects.get(user_profile=iago, recipient=denmark_recipient)- self.assertEqual(denmark_sub.desktop_notifications, False)- self.assertIsNone(denmark_sub.audible_notifications)-- # Zulip ignores subscription's notification related settings for PMs so don't migrate them.- iago_recipient = Recipient.objects.get(type=self.RECIPIENT_PERSONAL, type_id=iago.id)- iago_sub = Subscription.objects.get(user_profile=iago, recipient=iago_recipient)- self.assertEqual(iago_sub.desktop_notifications, False)- self.assertEqual(iago_sub.audible_notifications, False)- self.assertEqual(iago_sub.push_notifications, True)+ denmark = get_stream(stream_name, iago.realm)++ msg = Message.objects.filter(id=self.msg_id).first()+ msg_stream_id = Recipient.objects.get(id=msg.recipient_id).type_id+ new_edit_history = orjson.loads(msg.edit_history)++ self.assert_length(new_edit_history, 4)++ # stream and topic edit entry+ self.assertFalse("prev_subject" in new_edit_history[0])+ self.assertEqual(new_edit_history[0]["prev_topic"], "topic 3")+ self.assertEqual(new_edit_history[0]["topic"], msg.subject)+ self.assertEqual(new_edit_history[0]["prev_stream"], 3)+ self.assertEqual(new_edit_history[0]["stream"], msg_stream_id)+ self.assertEqual(new_edit_history[0]["stream"], denmark.id)+ self.assertEqual(+ set(new_edit_history[0].keys()),+ {"timestamp", "prev_topic", "topic", "prev_stream", "stream", "user_id"},+ )++ # stream only edit entry+ self.assertEqual(new_edit_history[1]["prev_stream"], 2)+ self.assertEqual(new_edit_history[1]["stream"], 3)+ self.assertEqual(+ set(new_edit_history[1].keys()), {"timestamp", "prev_stream", "stream", "user_id"}+ )++ # topic and content edit entry+ self.assertFalse("prev_subject" in new_edit_history[2])+ self.assertEqual(new_edit_history[2]["prev_topic"], "topic 2")+ self.assertEqual(new_edit_history[2]["topic"], "topic 3")+ self.assertEqual(new_edit_history[2]["prev_content"], "test content and topic edit")+ self.assertEqual(+ new_edit_history[2]["prev_rendered_content"], "<p>test content and topic edit</p>"+ )+ self.assertEqual(new_edit_history[2]["prev_rendered_content_version"], 1)+ self.assertEqual(+ set(new_edit_history[2].keys()),+ {+ "timestamp",+ "prev_topic",+ "topic",+ "prev_content",+ "prev_rendered_content",+ "prev_rendered_content_version",+ "user_id",+ },+ )++ # topic only edit entry+ self.assertFalse("prev_subject" in new_edit_history[3])+ self.assertEqual(new_edit_history[3]["prev_topic"], "topic 1")+ self.assertEqual(new_edit_history[3]["topic"], "topic 2")+ self.assertEqual(+ set(new_edit_history[3].keys()), {"timestamp", "prev_topic", "topic", "user_id"}+ )