Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
register: Improve idle_queue_timeout and document.
Prakhar Pratyushcce75cdb103e
diff --git a/api_docs/changelog.md b/api_docs/changelog.mdindex b575039a8b2..bf279d3d209 100644--- a/api_docs/changelog.md+++ b/api_docs/changelog.md@@ -20,6 +20,15 @@ format used by the Zulip server that they are interacting with.## Changes in Zulip 12.0+**Feature level 481**++* [`POST /register`](/api/register-queue): Added `idle_queue_timeout`+ request parameter, allowing clients to configure how long the server+ keeps the event queue alive when the client is not polling. The+ string `"mobile"` can be passed to use the server's recommended+ timeout for mobile clients. The response now includes+ `idle_queue_timeout_secs` with the effective timeout in seconds.+**Feature level 480*** [`GET /streams/{stream_id}`](/api/get-stream-by-id): Details ofdiff --git a/version.py b/version.pyindex d79bd07415e..e93d7606413 100644--- a/version.py+++ b/version.py@@ -33,7 +33,7 @@ DESKTOP_WARNING_VERSION = "5.9.3"# https://zulip.readthedocs.io/en/latest/documentation/api.html#step-by-step-guide# Also available at docs/documentation/api.md.-API_FEATURE_LEVEL = 480+API_FEATURE_LEVEL = 481# Bump the minor PROVISION_VERSION to indicate that folks should provision# only when going from an old version of the code to a newer version. Bumpdiff --git a/zerver/lib/events.py b/zerver/lib/events.pyindex 7b8494b672d..97e308911d5 100644--- a/zerver/lib/events.py+++ b/zerver/lib/events.py@@ -170,6 +170,7 @@ def fetch_initial_state_data(realm: Realm,event_types: Iterable[str] | None = None,queue_id: str | None = "",+ idle_queue_timeout_secs: int | None = None,client_gravatar: bool = False,user_avatar_url_field_optional: bool = False,slim_presence: bool = False,@@ -198,6 +199,9 @@ def fetch_initial_state_data("""state: dict[str, Any] = {"queue_id": queue_id}+ if idle_queue_timeout_secs is not None:+ state["idle_queue_timeout_secs"] = idle_queue_timeout_secs+if event_types is None:# return True alwayswant: Callable[[str], bool] = always_want@@ -2076,7 +2080,7 @@ def do_events_register(presence_last_update_id_fetched_by_client: int | None = None,presence_history_limit_days: int | None = None,event_types: Sequence[str] | None = None,- idle_queue_timeout: int = 0,+ idle_queue_timeout: int | Literal["mobile"] | None = None,all_public_streams: bool = False,include_subscribers: bool | Literal["partial"] = True,include_streams: bool = True,@@ -2155,7 +2159,7 @@ def do_events_register(# Note that we pass event_types, not fetch_event_types here, since# that's what controls which future events are sent.- queue_id = request_event_queue(+ result = request_event_queue(user_profile,user_client,apply_markdown,@@ -2176,14 +2180,17 @@ def do_events_register(simplified_presence_events=simplified_presence_events,)- if queue_id is None:+ if result is None:raise JsonableError(_("Could not allocate event queue"))+ queue_id = result.queue_id+ret = fetch_initial_state_data(user_profile,realm=realm,event_types=event_types_set,queue_id=queue_id,+ idle_queue_timeout_secs=result.idle_queue_timeout_secs,client_gravatar=client_gravatar,user_avatar_url_field_optional=user_avatar_url_field_optional,slim_presence=slim_presence,diff --git a/zerver/openapi/zulip.yaml b/zerver/openapi/zulip.yamlindex 964ecfe0c45..dde9269f3fd 100644--- a/zerver/openapi/zulip.yaml+++ b/zerver/openapi/zulip.yaml@@ -17281,12 +17281,12 @@ paths:["events" endpoint](/api/get-events) to request events fromthe Zulip server using long-polling.- The server will queue events for up to 10 minutes of inactivity.- After 10 minutes, your event queue will be garbage-collected. The- server will send `heartbeat` events every minute, which makes it easy- to implement a robust client that does not miss events unless the- client loses network connectivity with the Zulip server for 10 minutes- or longer.+ The server will queue events for up to `idle_queue_timeout_secs`+ seconds of inactivity. After that timeout, your event queue will be+ garbage-collected. The server will send `heartbeat` events+ every minute, which makes it easy to implement a robust client that+ does not miss events unless the client loses network connectivity+ with the Zulip server for longer than the configured timeout.Once the server garbage-collects your event queue, the server will[return an error](/api/get-events#bad_event_queue_id-errors)@@ -17294,7 +17294,7 @@ paths:the event queue. Your software will need to handle that errorcondition by re-initializing itself (e.g. this is what triggers yourbrowser reloading the Zulip web app when your laptop comes back online- after being offline for more than 10 minutes).+ after being offline for more than `idle_queue_timeout_secs` seconds).When prototyping with this API, we recommend first calling `register`with no `event_types` parameter to see all the available data from all@@ -17309,7 +17309,12 @@ paths:works, avoids clients needing to worry about large classes ofpotentially messy races, etc.- **Changes**: Removed `dense_mode` setting in Zulip 10.0 (feature level 364)+ **Changes**: New in Zulip 12.0 (feature level 481),+ the `idle_queue_timeout` request parameter and `idle_queue_timeout_secs`+ response field were added to allow clients to configure+ how long the server keeps an event queue alive during inactivity.++ Removed `dense_mode` setting in Zulip 10.0 (feature level 364)as we now have `web_font_size_px` and `web_line_height_percent`settings for more control.@@ -17573,6 +17578,28 @@ paths:example: ["message"]narrow:$ref: "#/components/schemas/Narrow"+ idle_queue_timeout:+ description: |+ At least how long (in seconds) the server should keep the event+ queue alive when the client is not polling. If the client does+ not poll before this timeout, the queue will eventually be+ garbage-collected.++ Alternatively, the string `"mobile"` can be passed to use the+ server's recommended timeout for mobile clients. This is+ currently 12 hours, but may change in the future.++ If not specified, the server uses a default of 10 minutes. The+ maximum allowed value is 7 days.++ **Changes**: New in Zulip 12.0 (feature level 481).+ oneOf:+ - type: integer+ minimum: 1+ - type: string+ enum:+ - "mobile"+ example: 3600encoding:apply_markdown:contentType: application/json@@ -17588,6 +17615,8 @@ paths:contentType: application/jsonfetch_event_types:contentType: application/json+ idle_queue_timeout:+ contentType: application/jsonnarrow:contentType: application/jsonresponses:@@ -17611,6 +17640,18 @@ paths:Will be `null` only for unauthenticated access in realms that haveenabled the [public access option](/help/public-access-option).+ idle_queue_timeout_secs:+ type: integer+ description: |+ The effective idle queue timeout for the allocated queue,+ in seconds. This is the resolved value of the+ `idle_queue_timeout` request parameter, after applying+ defaults and server-side limits.++ Not present for unauthenticated access in realms that have+ enabled the [public access option](/help/public-access-option).++ **Changes**: New in Zulip 12.0 (feature level 481).last_event_id:type: integerdescription: |@@ -21938,6 +21979,7 @@ paths:"last_event_id": -1,"msg": "","queue_id": "fb67bf8a-c031-47cc-84cf-ed80accacda8",+ "idle_queue_timeout_secs": 600,"realm_emoji":{"1":diff --git a/zerver/tests/test_event_queue.py b/zerver/tests/test_event_queue.pyindex b34c262e2e5..5c83ab3fe75 100644--- a/zerver/tests/test_event_queue.py+++ b/zerver/tests/test_event_queue.py@@ -22,6 +22,8 @@ from zerver.models.streams import get_streamfrom zerver.tornado.event_queue import (DEFAULT_EVENT_QUEUE_TIMEOUT_SECS,EVENT_QUEUE_OFFLINE_TIMEOUT_SECS,+ MAX_QUEUE_TIMEOUT_SECS,+ MOBILE_EVENT_QUEUE_TIMEOUT_SECS,ClientDescriptor,access_client_descriptor,add_client_gc_hook,@@ -1592,7 +1594,7 @@ class OfflineEventQueueTest(ZulipTestCase):def allocate_queue(self,user: UserProfile,- queue_timeout: int,+ queue_timeout: int | str | None,) -> ClientDescriptor:queue_data: dict[str, Any] = dict(all_public_streams=False,@@ -1737,3 +1739,22 @@ class OfflineEventQueueTest(ZulipTestCase):# 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()++ def test_idle_queue_timeout_resolution(self) -> None:+ hamlet = self.example_user("hamlet")++ # None resolves to the default timeout.+ client = self.allocate_queue(hamlet, queue_timeout=None)+ self.assertEqual(client.queue_timeout, DEFAULT_EVENT_QUEUE_TIMEOUT_SECS)++ # "mobile" resolves to the mobile timeout.+ client = self.allocate_queue(hamlet, queue_timeout="mobile")+ self.assertEqual(client.queue_timeout, MOBILE_EVENT_QUEUE_TIMEOUT_SECS)++ # Explicit integer is used as-is.+ client = self.allocate_queue(hamlet, queue_timeout=3600)+ self.assertEqual(client.queue_timeout, 3600)++ # Values above the max are capped.+ client = self.allocate_queue(hamlet, queue_timeout=MAX_QUEUE_TIMEOUT_SECS + 1000)+ self.assertEqual(client.queue_timeout, MAX_QUEUE_TIMEOUT_SECS)diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.pyindex dcbcdb79ed0..73ef47afea5 100644--- a/zerver/tests/test_event_system.py+++ b/zerver/tests/test_event_system.py@@ -34,7 +34,10 @@ from zerver.models.clients import get_clientfrom zerver.models.realms import get_realmfrom zerver.models.streams import get_streamfrom zerver.models.users import get_system_bot+from zerver.tornado.django_api import EventQueueDatafrom zerver.tornado.event_queue import (+ DEFAULT_EVENT_QUEUE_TIMEOUT_SECS,+ MOBILE_EVENT_QUEUE_TIMEOUT_SECS,allocate_client_descriptor,clear_client_event_queues_for_testing,get_client_info_for_message_event,@@ -90,7 +93,7 @@ class EventsEndpointTest(ZulipTestCase):result = self.api_post(user, "/api/v1/register")self.assert_json_error(result, "Could not allocate event queue")- return_event_queue = "15:11"+ return_event_queue = EventQueueData(queue_id="15:11", idle_queue_timeout_secs=600)return_user_events: list[dict[str, Any]] = []# We choose realm_emoji somewhat randomly--we want@@ -119,7 +122,7 @@ class EventsEndpointTest(ZulipTestCase):self.assertEqual(result_dict["queue_id"], "15:11")# Now start simulating returning actual data- return_event_queue = "15:12"+ return_event_queue.queue_id = "15:12"return_user_events = [test_event]with stub_event_queue_user_events(return_event_queue, return_user_events):@@ -135,7 +138,7 @@ class EventsEndpointTest(ZulipTestCase):self.assertEqual(result_dict["realm_emoji"], {})# Now test with `fetch_event_types` not matching the event- return_event_queue = "15:13"+ return_event_queue.queue_id = "15:13"with stub_event_queue_user_events(return_event_queue, return_user_events):result = self.api_post(user,@@ -174,6 +177,44 @@ class EventsEndpointTest(ZulipTestCase):self.assertEqual(result_dict["realm_emoji"], {})self.assertEqual(result_dict["queue_id"], "15:13")+ def test_idle_queue_timeout(self) -> None:+ user = self.example_user("hamlet")++ # Verify response includes idle_queue_timeout_secs.+ queue_data = EventQueueData(+ queue_id="1", idle_queue_timeout_secs=DEFAULT_EVENT_QUEUE_TIMEOUT_SECS+ )+ with stub_event_queue_user_events(queue_data, []):+ result = self.api_post(user, "/api/v1/register")+ result_dict = self.assert_json_success(result)+ self.assertEqual(result_dict["idle_queue_timeout_secs"], DEFAULT_EVENT_QUEUE_TIMEOUT_SECS)++ # "mobile" is accepted.+ queue_data = EventQueueData(+ queue_id="2", idle_queue_timeout_secs=MOBILE_EVENT_QUEUE_TIMEOUT_SECS+ )+ with stub_event_queue_user_events(queue_data, []):+ result = self.api_post(+ user,+ "/api/v1/register",+ {"idle_queue_timeout": orjson.dumps("mobile").decode()},+ )+ result_dict = self.assert_json_success(result)+ self.assertEqual(result_dict["idle_queue_timeout_secs"], MOBILE_EVENT_QUEUE_TIMEOUT_SECS)++ # Explicit integer value is accepted.+ queue_data = EventQueueData(queue_id="3", idle_queue_timeout_secs=3600)+ with stub_event_queue_user_events(queue_data, []):+ result = self.api_post(user, "/api/v1/register", {"idle_queue_timeout": 3600})+ result_dict = self.assert_json_success(result)+ self.assertEqual(result_dict["idle_queue_timeout_secs"], 3600)++ # Invalid string value is rejected.+ result = self.api_post(+ user, "/api/v1/register", {"idle_queue_timeout": orjson.dumps("invalid").decode()}+ )+ self.assert_json_error_contains(result, "idle_queue_timeout")+def test_events_register_spectators(self) -> None:# Verify that POST /register works for spectators, but not for# normal users.diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.pyindex 042d62b7abc..ce81392014f 100644--- a/zerver/tests/test_home.py+++ b/zerver/tests/test_home.py@@ -32,6 +32,7 @@ from zerver.models import DefaultStream, Draft, Realm, UserActivity, UserProfilefrom zerver.models.realms import get_realmfrom zerver.models.streams import get_streamfrom zerver.models.users import get_system_bot, get_user+from zerver.tornado.django_api import EventQueueDatafrom zerver.worker.user_activity import UserActivityWorkerif TYPE_CHECKING:@@ -95,6 +96,7 @@ class HomeTest(ZulipTestCase):"tenor_api_key","gif_rating_policy_options","has_zoom_token",+ "idle_queue_timeout_secs","is_admin","is_guest","is_moderator",@@ -653,8 +655,9 @@ class HomeTest(ZulipTestCase):self.assertIn("test_stream_7", html)def _get_home_page(self, **kwargs: Any) -> "TestHttpResponse":+ queue_data = EventQueueData(queue_id="test-queue-id", idle_queue_timeout_secs=600)with (- patch("zerver.lib.events.request_event_queue", return_value=42),+ patch("zerver.lib.events.request_event_queue", return_value=queue_data),patch("zerver.lib.events.get_user_events", return_value=[]),):result = self.client_get("/", dict(**kwargs))@@ -1351,8 +1354,9 @@ class HomeTest(ZulipTestCase):self.login_user(user)result = self._get_home_page()self.check_rendered_logged_in_app(result)+ queue_data = EventQueueData(queue_id="test-queue-id", idle_queue_timeout_secs=600)with (- patch("zerver.lib.events.request_event_queue", return_value=42),+ patch("zerver.lib.events.request_event_queue", return_value=queue_data),patch("zerver.lib.events.get_user_events", return_value=[]),):result = self.client_get("/de/")diff --git a/zerver/tests/test_message_topics.py b/zerver/tests/test_message_topics.pyindex 7758c3268c9..fc436188cf6 100644--- a/zerver/tests/test_message_topics.py+++ b/zerver/tests/test_message_topics.py@@ -13,6 +13,7 @@ from zerver.models import Message, UserMessage, UserTopicfrom zerver.models.clients import get_clientfrom zerver.models.realms import get_realmfrom zerver.models.streams import get_stream+from zerver.tornado.django_api import EventQueueDatafrom zerver.tornado.event_queue import allocate_client_descriptor@@ -790,7 +791,8 @@ class EmptyTopicNameTest(ZulipTestCase):visibility_policy=UserTopic.VisibilityPolicy.UNMUTED,)- with mock.patch("zerver.lib.events.request_event_queue", return_value=1):+ queue_data = EventQueueData(queue_id="1", idle_queue_timeout_secs=600)+ with mock.patch("zerver.lib.events.request_event_queue", return_value=queue_data):state_data = do_events_register(iago,iago.realm,@@ -805,7 +807,7 @@ class EmptyTopicNameTest(ZulipTestCase):self.assertEqual(state_data["user_topics"][0]["topic_name"], "")self.assertEqual(state_data["user_topics"][1]["topic_name"], "")- with mock.patch("zerver.lib.events.request_event_queue", return_value=1):+ with mock.patch("zerver.lib.events.request_event_queue", return_value=queue_data):state_data = do_events_register(iago,iago.realm,diff --git a/zerver/tornado/django_api.py b/zerver/tornado/django_api.pyindex f8168e45a27..edf1a369cd9 100644--- a/zerver/tornado/django_api.py+++ b/zerver/tornado/django_api.py@@ -1,7 +1,8 @@from collections import defaultdictfrom collections.abc import Iterable, Mapping, Sequence+from dataclasses import dataclassfrom functools import lru_cache-from typing import Any+from typing import Any, Literalfrom urllib.parse import urlsplitimport orjson@@ -75,13 +76,19 @@ def requests_client() -> requests.Session:return c+@dataclass+class EventQueueData:+ queue_id: str+ idle_queue_timeout_secs: int++def request_event_queue(user_profile: UserProfile,user_client: Client,apply_markdown: bool,client_gravatar: bool,slim_presence: bool,- idle_queue_timeout: int,+ idle_queue_timeout: int | Literal["mobile"] | None,event_types: Sequence[str] | None = None,all_public_streams: bool = False,narrow: Iterable[Sequence[str]] = [],@@ -94,7 +101,7 @@ def request_event_queue(archived_channels: bool = False,empty_topic_name: bool = False,simplified_presence_events: bool = False,-) -> str | None:+) -> EventQueueData | None:if not settings.USING_TORNADO:return None@@ -115,7 +122,6 @@ def request_event_queue("user_client": user_client.name,"narrow": orjson.dumps(narrow),"secret": settings.SHARED_SECRET,- "idle_queue_timeout": idle_queue_timeout,"bulk_message_deletion": orjson.dumps(bulk_message_deletion),"stream_typing_notifications": orjson.dumps(stream_typing_notifications),"pronouns_field_type_supported": orjson.dumps(pronouns_field_type_supported),@@ -127,11 +133,18 @@ def request_event_queue("simplified_presence_events": orjson.dumps(simplified_presence_events),}+ if idle_queue_timeout is not None:+ req["idle_queue_timeout"] = orjson.dumps(idle_queue_timeout)+if event_types is not None:req["event_types"] = orjson.dumps(event_types)resp = requests_client().post(tornado_url + "/api/v1/events/internal", data=req)- return resp.json()["queue_id"]+ result = resp.json()+ return EventQueueData(+ queue_id=result["queue_id"],+ idle_queue_timeout_secs=result["idle_queue_timeout_secs"],+ )def get_user_events(diff --git a/zerver/tornado/event_queue.py b/zerver/tornado/event_queue.pyindex e047979227a..8cfa38d7300 100644--- a/zerver/tornado/event_queue.py+++ b/zerver/tornado/event_queue.py@@ -56,6 +56,9 @@ MAX_QUEUE_TIMEOUT_SECS = 7 * 24 * 60 * 60# is called to potentially send push/email notifications.EVENT_QUEUE_OFFLINE_TIMEOUT_SECS = 60 * 10+# Queue timeout for mobile clients.+MOBILE_EVENT_QUEUE_TIMEOUT_SECS = 12 * 60 * 60+# The heartbeats effectively act as a server-side timeout for# get_events(). The actual timeout value is randomized for each# client connection based on the below value. We ensure that the@@ -82,7 +85,7 @@ class ClientDescriptor:client_gravatar: bool,slim_presence: bool,all_public_streams: bool,- idle_queue_timeout: int,+ idle_queue_timeout: int | Literal["mobile"] | None,narrow: Collection[Sequence[str]],bulk_message_deletion: bool,stream_typing_notifications: bool,@@ -131,8 +134,10 @@ class ClientDescriptor:# Default for idle_queue_timeout is DEFAULT_EVENT_QUEUE_TIMEOUT_SECS;# but users can set it as high as MAX_QUEUE_TIMEOUT_SECS.- if idle_queue_timeout == 0:+ if idle_queue_timeout is None:idle_queue_timeout = DEFAULT_EVENT_QUEUE_TIMEOUT_SECS+ elif idle_queue_timeout == "mobile":+ idle_queue_timeout = MOBILE_EVENT_QUEUE_TIMEOUT_SECSself.queue_timeout = min(idle_queue_timeout, MAX_QUEUE_TIMEOUT_SECS)def to_dict(self) -> dict[str, Any]:@@ -831,6 +836,7 @@ def fetch_events()if orig_queue_id is None:response["queue_id"] = queue_id+ response["idle_queue_timeout_secs"] = client.queue_timeoutif len(response["events"]) == 1:extra_log_data = "[{}/{}/{}]".format(queue_id, len(response["events"]), response["events"][0]["type"]diff --git a/zerver/tornado/views.py b/zerver/tornado/views.pyindex 9d614bbbf8d..fd649300722 100644--- a/zerver/tornado/views.py+++ b/zerver/tornado/views.py@@ -1,12 +1,12 @@import timefrom collections.abc import Callable-from typing import Annotated, Any, TypeVar+from typing import Annotated, Any, Literal, TypeVarfrom asgiref.sync import async_to_syncfrom django.conf import settingsfrom django.http import HttpRequest, HttpResponsefrom django.utils.translation import gettext as _-from pydantic import BaseModel, Json, NonNegativeInt, StringConstraints, model_validator+from pydantic import BaseModel, Json, PositiveInt, StringConstraints, model_validatorfrom typing_extensions import ParamSpecfrom zerver.decorator import internal_api_view, process_client@@ -179,9 +179,9 @@ def get_events_backend(ApiParamConfig(documentation_status=DocumentationStatus.INTENTIONALLY_UNDOCUMENTED),] = None,idle_queue_timeout: Annotated[- Json[NonNegativeInt],+ Json[PositiveInt | Literal["mobile"]] | None,ApiParamConfig(documentation_status=DocumentationStatus.INTENTIONALLY_UNDOCUMENTED),- ] = 0,+ ] = None,bulk_message_deletion: Annotated[Json[bool],ApiParamConfig(documentation_status=DocumentationStatus.INTENTIONALLY_UNDOCUMENTED),diff --git a/zerver/views/events_register.py b/zerver/views/events_register.pyindex f1d4729a4d9..4d5524027ab 100644--- a/zerver/views/events_register.py+++ b/zerver/views/events_register.py@@ -5,7 +5,7 @@ from django.conf import settingsfrom django.contrib.auth.models import AnonymousUserfrom django.http import HttpRequest, HttpResponsefrom django.utils.translation import gettext as _-from pydantic import Json+from pydantic import Json, PositiveIntfrom zerver.context_processors import get_valid_realm_from_requestfrom zerver.lib.compatibility import is_pronouns_field_type_supported@@ -14,7 +14,7 @@ from zerver.lib.exceptions import JsonableError, MissingAuthenticationErrorfrom zerver.lib.narrow_helpers import narrow_dataclasses_from_tuplesfrom zerver.lib.request import RequestNotesfrom zerver.lib.response import json_success-from zerver.lib.typed_endpoint import ApiParamConfig, DocumentationStatus, typed_endpoint+from zerver.lib.typed_endpoint import ApiParamConfig, typed_endpointfrom zerver.models import Stream, UserProfilefrom zerver.views.streams import parse_include_subscribers@@ -50,9 +50,7 @@ def events_register_backend(include_subscribers: Literal["true", "false", "partial"] = "false",narrow: Json[NarrowT] | None = None,presence_history_limit_days: Json[int] | None = None,- idle_queue_timeout: Annotated[- Json[int], ApiParamConfig(documentation_status=DocumentationStatus.DOCUMENTATION_PENDING)- ] = 0,+ idle_queue_timeout: Json[PositiveInt | Literal["mobile"]] | None = None,slim_presence: Json[bool] = False,) -> HttpResponse:if narrow is None: