Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
event_queue: Mark long-lived queues offline and send notifications.
Prakhar Pratyush0c9ebd4e08c5
diff --git a/zerver/tests/test_event_queue.py b/zerver/tests/test_event_queue.pyindex 3aaed271dc4..b34c262e2e5 100644--- a/zerver/tests/test_event_queue.py+++ b/zerver/tests/test_event_queue.py@@ -4,6 +4,7 @@ from typing import Anyfrom unittest import mockimport orjson+import time_machinefrom django.http import HttpRequest, HttpResponsefrom typing_extensions import override@@ -19,12 +20,19 @@ from zerver.lib.test_helpers import HostRequestMock, dummy_handler, mock_queue_pfrom zerver.models import Device, Recipient, Subscription, UserProfile, UserTopicfrom zerver.models.streams import get_streamfrom zerver.tornado.event_queue import (+ DEFAULT_EVENT_QUEUE_TIMEOUT_SECS,+ EVENT_QUEUE_OFFLINE_TIMEOUT_SECS,ClientDescriptor,access_client_descriptor,+ add_client_gc_hook,allocate_client_descriptor,+ clients,+ gc_event_queues,+ mark_clients_offline,maybe_enqueue_notifications,missedmessage_hook,persistent_queue_filename,+ receiver_is_off_zulip,)from zerver.tornado.views import cleanup_event_queue, get_events@@ -1573,3 +1581,159 @@ class EventQueueTest(ZulipTestCase):queue.prune(1)self.verify_to_dict_end_to_end(client)+++class OfflineEventQueueTest(ZulipTestCase):+ """Tests for the offline marking mechanism for long-lived event queues."""++ NOW = time.time()+ LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS = EVENT_QUEUE_OFFLINE_TIMEOUT_SECS + 10 * 60 * 60++ def allocate_queue(+ self,+ user: UserProfile,+ queue_timeout: int,+ ) -> ClientDescriptor:+ queue_data: dict[str, Any] = dict(+ all_public_streams=False,+ apply_markdown=True,+ client_gravatar=True,+ client_type_name="ZulipFlutter",+ event_types=["message"],+ last_connection_time=time.time(),+ queue_timeout=queue_timeout,+ realm_id=user.realm.id,+ user_profile_id=user.id,+ )+ return allocate_client_descriptor(queue_data)++ @time_machine.travel(NOW, tick=False)+ def test_should_mark_offline(self) -> None:+ hamlet = self.example_user("hamlet")+ client = self.allocate_queue(hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS)+ now = time.time()++ # A connected handler should not be marked offline.+ client.current_handler_id = 999+ self.assertFalse(client.should_mark_offline(now))+ client.current_handler_id = None++ # Already offline queues should not be re-marked.+ client.offline = True+ self.assertFalse(client.should_mark_offline(now))+ client.offline = False++ # An idle queue past the threshold should be marked offline.+ client.last_connection_time = now - EVENT_QUEUE_OFFLINE_TIMEOUT_SECS - 1+ self.assertTrue(client.should_mark_offline(now))++ # Not idle long enough.+ client.last_connection_time = now - EVENT_QUEUE_OFFLINE_TIMEOUT_SECS + 1+ self.assertFalse(client.should_mark_offline(now))++ def test_mark_clients_offline_fires_missedmessage_hook(self) -> None:+ hamlet = self.example_user("hamlet")+ client = self.allocate_queue(hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS)+ self.assertFalse(client.offline)++ iago = self.example_user("iago")+ self.send_personal_message(iago, hamlet)++ with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:+ mark_clients_offline({client.event_queue.id}, {hamlet.id})+ mock_enqueue.assert_called_once()++ self.assertTrue(client.offline)++ def test_missedmessage_hook_skips_offline_queue(self) -> None:+ hamlet = self.example_user("hamlet")+ client = self.allocate_queue(hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS)+ client.offline = True++ iago = self.example_user("iago")+ self.send_personal_message(iago, hamlet)++ with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:+ missedmessage_hook(hamlet.id, client, True)+ mock_enqueue.assert_not_called()++ def test_last_client_for_user_with_multiple_queues(self) -> None:+ hamlet = self.example_user("hamlet")+ client1 = self.allocate_queue(+ hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS+ )+ client2 = self.allocate_queue(+ hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS+ )++ iago = self.example_user("iago")+ self.send_personal_message(iago, hamlet)++ # Marking only client1 offline: client2 is still active, so+ # last_client_for_user is False and missedmessage_hook+ # short-circuits without sending notifications.+ with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:+ mark_clients_offline({client1.event_queue.id}, {hamlet.id})+ mock_enqueue.assert_not_called()++ self.assertTrue(client1.offline)+ self.assertFalse(client2.offline)++ # Now mark client2 offline too: no active queues remain, so+ # last_client_for_user is True and notifications are sent.+ with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:+ mark_clients_offline({client2.event_queue.id}, {hamlet.id})+ mock_enqueue.assert_called_once()++ def test_receiver_is_off_zulip_with_offline_queue(self) -> None:+ hamlet = self.example_user("hamlet")+ client = self.allocate_queue(hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS)++ # With an active queue, user is not "off Zulip".+ self.assertFalse(receiver_is_off_zulip(hamlet.id))++ # After marking offline, user should be "off Zulip".+ client.offline = True+ self.assertTrue(receiver_is_off_zulip(hamlet.id))++ @time_machine.travel(NOW, tick=False)+ def test_gc_event_queues(self) -> None:+ hamlet = self.example_user("hamlet")+ add_client_gc_hook(missedmessage_hook)++ # A queue that will expire after DEFAULT_EVENT_QUEUE_TIMEOUT_SECS.+ client = self.allocate_queue(hamlet, queue_timeout=DEFAULT_EVENT_QUEUE_TIMEOUT_SECS)+ # A longer-lived queue that should be marked offline but not removed.+ long_lived_client = self.allocate_queue(+ hamlet, queue_timeout=self.LONG_LIVED_EVENT_QUEUE_TIMEOUT_SECS+ )++ iago = self.example_user("iago")+ self.send_personal_message(iago, hamlet)++ queue_id = client.event_queue.id+ long_lived_queue_id = long_lived_client.event_queue.id+ self.assertIn(queue_id, clients)+ self.assertIn(long_lived_queue_id, clients)++ # Set both queues idle past the EVENT_QUEUE_OFFLINE_TIMEOUT_SECS.+ last_connection_time = time.time() - EVENT_QUEUE_OFFLINE_TIMEOUT_SECS - 1+ client.last_connection_time = last_connection_time+ long_lived_client.last_connection_time = last_connection_time++ with mock.patch("zerver.tornado.event_queue.maybe_enqueue_notifications") as mock_enqueue:+ gc_event_queues(port=9993)++ # The queue with default timeout is removed.+ # The long-lived queue still exist but marked offline.+ self.assertNotIn(queue_id, clients)+ self.assertIn(long_lived_queue_id, clients)+ self.assertTrue(long_lived_client.offline)++ # missedmessage_hook is called twice: once for the+ # expired queue (via gc_hooks) and once for the+ # long-lived queue (via mark_clients_offline).+ # But maybe_enqueue_notifications only fires once.+ # For the expired queue, the long-lived queue is still active so+ # last_client_for_user is False and it short-circuits.+ mock_enqueue.assert_called_once()diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.pyindex e7c66eb3cc8..40d9fdf6647 100644--- a/zerver/tornado/event_queue.py+++ b/zerver/tornado/event_queue.py@@ -284,6 +284,13 @@ class ClientDescriptor:and now - self.last_connection_time >= self.queue_timeout)+ def should_mark_offline(self, now: float) -> bool:+ return (+ self.current_handler_id is None+ and not self.offline+ and now - self.last_connection_time >= EVENT_QUEUE_OFFLINE_TIMEOUT_SECS+ )+def connect_handler(self, handler_id: int, client_name: str) -> None:self.current_handler_id = handler_idself.current_client_name = client_name@@ -568,6 +575,7 @@ def do_gc_event_queues(# by the `active_mobile_push_notification` flag on UserMessage,# but email notifications are not — duplicate# ScheduledMessageNotificationEmail rows will be created.+ # The same issue exists in mark_clients_offline below.for id in to_remove:web_reload_clients.pop(id, None)for cb in gc_hooks:@@ -579,6 +587,34 @@ def do_gc_event_queues(del clients[id]+def mark_clients_offline(+ to_mark_offline: AbstractSet[str], affected_users: AbstractSet[int]+) -> None:+ """For long-lived queues (e.g. mobile), mark them offline+ and fire missedmessage_hook so notifications are sent after+ EVENT_QUEUE_OFFLINE_TIMEOUT_SECS rather than waiting for the+ full queue_timeout.+ """+ # Pre-compute which users still have active queues after+ # offline marking, following the same pattern as+ # do_gc_event_queues for last_client_for_user.+ users_with_active_queues: set[int] = set()+ for user_id in affected_users:+ for c in get_client_descriptors_for_user(user_id):+ if c.accepts_messages() and not c.offline and c.event_queue.id not in to_mark_offline:+ users_with_active_queues.add(user_id)+ break++ for id in to_mark_offline:+ client = clients[id]+ missedmessage_hook(+ client.user_profile_id,+ client,+ client.user_profile_id not in users_with_active_queues,+ )+ client.offline = True++def gc_event_queues(port: int) -> None:# We cannot use perf_counter here, since we store and compare UNIX# timestamps to it in the queues.@@ -586,17 +622,26 @@ def gc_event_queues(port: int) -> None:to_remove: set[str] = set()affected_users: set[int] = set()affected_realms: set[int] = set()+ to_mark_offline: set[str] = set()+ offline_affected_users: set[int] = set()for id, client in clients.items():if client.expired(start):to_remove.add(id)affected_users.add(client.user_profile_id)affected_realms.add(client.realm_id)+ elif client.should_mark_offline(start):+ to_mark_offline.add(id)+ offline_affected_users.add(client.user_profile_id)# We don't need to call e.g. finish_current_handler on the clients# being removed because they are guaranteed to be idle (because# they are expired) and thus not have a current handler.do_gc_event_queues(to_remove, affected_users, affected_realms)+ # Mark long-lived queues offline after expired queues are+ # removed, so that last_client_for_user is computed correctly.+ mark_clients_offline(to_mark_offline, offline_affected_users)+if settings.PRODUCTION:logging.info("Tornado %d removed %d expired event queues owned by %d users in %.3fs."@@ -824,29 +869,34 @@ def missedmessage_hook() -> None:"""The receiver_is_off_zulip logic used to determine whether a userhas no active client suffers from a somewhat fundamental race- condition. If the client is no longer on the Internet,+ condition. If the client is no longer on the Internet,receiver_is_off_zulip will still return False for- DEFAULT_EVENT_QUEUE_TIMEOUT_SECS, until the queue is- garbage-collected. This would cause us to reliably miss- push/email notifying users for messages arriving during the- DEFAULT_EVENT_QUEUE_TIMEOUT_SECS after they suspend their laptop (for- example). We address this by, when the queue is garbage-collected- at the end of those 10 minutes, checking to see if it's the last- one, and if so, potentially triggering notifications to the user- at that time, resulting in at most a DEFAULT_EVENT_QUEUE_TIMEOUT_SECS+ EVENT_QUEUE_OFFLINE_TIMEOUT_SECS, until the queue is marked+ offline or garbage-collected. This would cause us to reliably+ miss push/email notifying users for messages arriving during+ that window after they suspend their laptop (for example).++ We address this by, when the queue is marked offline or+ garbage-collected, checking to see if it's the last active one,+ and if so, potentially triggering notifications to the user at+ that time, resulting in at most an EVENT_QUEUE_OFFLINE_TIMEOUT_SECSdelay in the arrival of their notifications.- As Zulip's APIs get more popular and the mobile apps start using- long-lived event queues for perf optimization, future versions of- this will likely need to replace checking `last_client_for_user` with- something more complicated, so that we only consider clients like- web browsers, not the mobile apps or random API scripts.+ For long-lived queues (e.g. mobile), mark_clients_offline calls+ this hook when the client has been idle for+ EVENT_QUEUE_OFFLINE_TIMEOUT_SECS, without deleting the queue.+ When the queue later expires and is garbage-collected, we skip+ this hook since notifications were already handled."""- # Only process missedmessage hook when the last queue for a- # user has been garbage collectedif not last_client_for_user:return+ # For long-lived queues, notifications are sent when the queue+ # is first marked offline. When the queue later expires, we+ # skip it here to avoid duplicate notifications.+ if client.offline:+ return+for event in client.event_queue.contents(include_internal_data=True):if event["type"] != "message":continue@@ -955,13 +1005,15 @@ def missedmessage_hook(def receiver_is_off_zulip(user_profile_id: int) -> bool:- # If a user has no message-receiving event queues, they've got no open zulip- # session so we notify them.+ # If a user has no active, non-offline message-receiving event+ # queues, they've got no open Zulip session so we notify them.all_client_descriptors = get_client_descriptors_for_user(user_profile_id)- message_event_queues = [- client for client in all_client_descriptors if client.accepts_messages()+ not_offline_message_event_queues = [+ client+ for client in all_client_descriptors+ if client.accepts_messages() and not client.offline]- off_zulip = len(message_event_queues) == 0+ off_zulip = len(not_offline_message_event_queues) == 0return off_zulip