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.

scheduled_messages: Lock the row when editing to avoid duplicate send.

Aman Agrawal9bb330dfbece
diff --git a/zerver/actions/scheduled_messages.py b/zerver/actions/scheduled_messages.py
index 0d3bc69acd1..ee20cd389b2 100644
--- a/zerver/actions/scheduled_messages.py
+++ b/zerver/actions/scheduled_messages.py
@@ -172,9 +172,12 @@ def edit_scheduled_message(
deliver_at: datetime | None,
realm: Realm,
) -> None:
- scheduled_message_object = access_scheduled_message(sender, scheduled_message_id)
+ scheduled_message_object = access_scheduled_message(
+ sender, scheduled_message_id, lock_message=True
+ )
- # Handles the race between us initiating this transaction and user sending us the edit request.
+ # We locked the row above, so a concurrent delivery has already
+ # committed and this guard reliably observes its delivered=True.
if scheduled_message_object.delivered is True:
raise JsonableError(_("Scheduled message was already sent"))
diff --git a/zerver/lib/scheduled_messages.py b/zerver/lib/scheduled_messages.py
index b7fdada9b74..ffee8dec612 100644
--- a/zerver/lib/scheduled_messages.py
+++ b/zerver/lib/scheduled_messages.py
@@ -10,10 +10,18 @@ from zerver.models.scheduled_jobs import (
def access_scheduled_message(
- user_profile: UserProfile, scheduled_message_id: int
+ user_profile: UserProfile,
+ scheduled_message_id: int,
+ lock_message: bool = False,
) -> ScheduledMessage:
+ base_query = ScheduledMessage.objects.all()
+ if lock_message:
+ # Callers that are going to modify the row should take this lock
+ # to avoid racing with an in-progress delivery. Only pass
+ # lock_message from within a @transaction.atomic block.
+ base_query = base_query.select_for_update(no_key=True)
try:
- return ScheduledMessage.objects.get(
+ return base_query.get(
id=scheduled_message_id, sender=user_profile, delivery_type=ScheduledMessage.SEND_LATER
)
except ScheduledMessage.DoesNotExist: