Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
queue: Use locking to avoid race conditions in missedmessage_emails.
Mateusz Mandera06151672bab6
diff --git a/zerver/tests/test_queue_worker.py b/zerver/tests/test_queue_worker.pyindex 108978a8618..79ccff0bbe2 100644--- a/zerver/tests/test_queue_worker.py+++ b/zerver/tests/test_queue_worker.py@@ -188,9 +188,6 @@ class WorkerTest(ZulipTestCase):def start(self) -> None:self.is_running = True- def cancel(self) -> None:- self.is_running = False-timer = MockTimer()loopworker_sleep_mock = patch('zerver.worker.queue_processors.Timer',@@ -223,7 +220,7 @@ class WorkerTest(ZulipTestCase):'INFO:root:Batch-processing 1 missedmessage_emails events for user 12'])- self.assertFalse(timer.is_alive())+ self.assertEqual(mmw.timer_event, None)self.assertEqual(tm.call_args[0][0], 5) # should sleep 5 secondsdiff --git a/zerver/worker/queue_processors.py b/zerver/worker/queue_processors.pyindex 9accd7df617..b81a48d1c5d 100644--- a/zerver/worker/queue_processors.py+++ b/zerver/worker/queue_processors.py@@ -16,7 +16,7 @@ from abc import ABC, abstractmethodfrom collections import defaultdict, dequefrom email.message import EmailMessagefrom functools import wraps-from threading import Timer+from threading import Lock, Timerfrom typing import (Any,Callable,@@ -469,47 +469,58 @@ class MissedMessageWorker(QueueProcessingWorker):events_by_recipient: Dict[int, List[Dict[str, Any]]] = defaultdict(list)batch_start_by_recipient: Dict[int, float] = {}+ # This lock protects access to all of the data structures declared+ # above. A lock is required because maybe_send_batched_emails, as+ # the argument to Timer, runs in a separate thread from the rest+ # of the consumer.+ lock = Lock()+def consume(self, event: Dict[str, Any]) -> None:- logging.debug("Received missedmessage_emails event: %s", event)+ with self.lock:+ logging.debug("Received missedmessage_emails event: %s", event)- # When we process an event, just put it into the queue and ensure we have a timer going.- user_profile_id = event['user_profile_id']- if user_profile_id not in self.batch_start_by_recipient:- self.batch_start_by_recipient[user_profile_id] = time.time()- self.events_by_recipient[user_profile_id].append(event)+ # When we process an event, just put it into the queue and ensure we have a timer going.+ user_profile_id = event['user_profile_id']+ if user_profile_id not in self.batch_start_by_recipient:+ self.batch_start_by_recipient[user_profile_id] = time.time()+ self.events_by_recipient[user_profile_id].append(event)- self.ensure_timer()+ self.ensure_timer()def ensure_timer(self) -> None:+ # The caller is responsible for ensuring self.lock is held when it calls this.if self.timer_event is not None:return- self.timer_event = Timer(self.TIMER_FREQUENCY, MissedMessageWorker.maybe_send_batched_emails, [self])- self.timer_event.start()- def stop_timer(self) -> None:- if self.timer_event and self.timer_event.is_alive():- self.timer_event.cancel()- self.timer_event = None+ self.timer_event = Timer(self.TIMER_FREQUENCY, MissedMessageWorker.maybe_send_batched_emails,+ [self])+ self.timer_event.start()def maybe_send_batched_emails(self) -> None:- self.stop_timer()+ with self.lock:+ # self.timer_event just triggered execution of this+ # function in a thread, so now that we hold the lock, we+ # clear the timer_event attribute to record that no Timer+ # is active.+ self.timer_event = None- current_time = time.time()- for user_profile_id, timestamp in list(self.batch_start_by_recipient.items()):- if current_time - timestamp < self.BATCH_DURATION:- continue- events = self.events_by_recipient[user_profile_id]- logging.info("Batch-processing %s missedmessage_emails events for user %s",- len(events), user_profile_id)- handle_missedmessage_emails(user_profile_id, events)- del self.events_by_recipient[user_profile_id]- del self.batch_start_by_recipient[user_profile_id]-- # By only restarting the timer if there are actually events in- # the queue, we ensure this queue processor is idle when there- # are no missed-message emails to process.- if len(self.batch_start_by_recipient) > 0:- self.ensure_timer()+ current_time = time.time()+ for user_profile_id, timestamp in list(self.batch_start_by_recipient.items()):+ if current_time - timestamp < self.BATCH_DURATION:+ continue+ events = self.events_by_recipient[user_profile_id]+ logging.info("Batch-processing %s missedmessage_emails events for user %s",+ len(events), user_profile_id)+ handle_missedmessage_emails(user_profile_id, events)+ del self.events_by_recipient[user_profile_id]+ del self.batch_start_by_recipient[user_profile_id]++ # By only restarting the timer if there are actually events in+ # the queue, we ensure this queue processor is idle when there+ # are no missed-message emails to process. This avoids+ # constant CPU usage when there is no work to do.+ if len(self.batch_start_by_recipient) > 0:+ self.ensure_timer()@assign_queue('email_senders')class EmailSendingWorker(QueueProcessingWorker):