Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
message_fetch: Migrate to typed_endpoint.
Kenneth Rodrigues4e05381897cf
diff --git a/zerver/lib/narrow.py b/zerver/lib/narrow.pyindex 9097f5e36dc..a0bba09e624 100644--- a/zerver/lib/narrow.py+++ b/zerver/lib/narrow.py@@ -15,7 +15,6 @@ from typing import (Union,)-import orjsonfrom django.conf import settingsfrom django.core.exceptions import ValidationErrorfrom django.db import connection@@ -67,7 +66,6 @@ from zerver.lib.types import Validatorfrom zerver.lib.user_topics import exclude_topic_mutesfrom zerver.lib.validator import (check_bool,- check_dict,check_required_string,check_string,check_string_or_int,@@ -805,73 +803,6 @@ class NarrowBuilder:return query.where(maybe_negate(cond))-def narrow_parameter(var_name: str, json: str) -> OptionalNarrowListT:- data = orjson.loads(json)- if not isinstance(data, list):- raise ValueError("argument is not a list")- if len(data) == 0:- # The "empty narrow" should be None, and not []- return None-- def convert_term(elem: Union[Dict[str, Any], List[str]]) -> Dict[str, Any]:- # We have to support a legacy tuple format.- if isinstance(elem, list):- if len(elem) != 2 or any(not isinstance(x, str) for x in elem):- raise ValueError("element is not a string pair")- return dict(operator=elem[0], operand=elem[1])-- if isinstance(elem, dict):- # Make sure to sync this list to frontend also when adding a new operator that- # supports integer IDs. Relevant code is located in web/src/message_fetch.js- # in handle_operators_supporting_id_based_api function where you will need to- # update operators_supporting_id, or operators_supporting_ids array.- operators_supporting_id = [- *channel_operators,- "id",- "sender",- "group-pm-with",- "dm-including",- ]- operators_supporting_ids = ["pm-with", "dm"]- operators_non_empty_operand = {"search"}-- operator = elem.get("operator", "")- if operator in operators_supporting_id:- operand_validator: Validator[object] = check_string_or_int- elif operator in operators_supporting_ids:- operand_validator = check_string_or_int_list- elif operator in operators_non_empty_operand:- operand_validator = check_required_string- else:- operand_validator = check_string-- validator = check_dict(- required_keys=[- ("operator", check_string),- ("operand", operand_validator),- ],- optional_keys=[- ("negated", check_bool),- ],- )-- try:- validator("elem", elem)- except ValidationError as error:- raise JsonableError(error.message)-- # whitelist the fields we care about for now- return dict(- operator=elem["operator"],- operand=elem["operand"],- negated=elem.get("negated", False),- )-- raise ValueError("element is not a dictionary")-- return list(map(convert_term, data))--def ok_to_include_history(narrow: OptionalNarrowListT, user_profile: Optional[UserProfile], is_web_public_query: bool) -> bool:diff --git a/zerver/tests/test_message_fetch.py b/zerver/tests/test_message_fetch.pyindex ea072a4aab8..cb458b7b844 100644--- a/zerver/tests/test_message_fetch.py+++ b/zerver/tests/test_message_fetch.py@@ -3507,10 +3507,10 @@ class GetOldMessagesTest(ZulipTestCase):int_params = ["num_before", "num_after"]invalid_parameters: List[InvalidParam] = [- InvalidParam(value=False, expected_error="Bad value for"),- InvalidParam(value="", expected_error="Bad value for"),- InvalidParam(value="-1", expected_error="Bad value for"),- InvalidParam(value=-1, expected_error="Bad value for"),+ InvalidParam(value=False, expected_error="is not valid JSON"),+ InvalidParam(value="", expected_error="is not valid JSON"),+ InvalidParam(value="-1", expected_error="is too small"),+ InvalidParam(value=-1, expected_error="is too small"),]for idx, param in enumerate(int_params):for invalid_parameter in invalid_parameters:@@ -3522,10 +3522,8 @@ class GetOldMessagesTest(ZulipTestCase):**dict.fromkeys(int_params[:idx] + int_params[idx + 1 :], 0),}result = self.client_get("/json/messages", post_params)- self.assert_json_error(- result,- f"{invalid_parameter.expected_error} '{param}': {invalid_parameter.value}",- )++ self.assert_json_error(result, f"{param} {invalid_parameter.expected_error}")def test_bad_include_anchor(self) -> None:self.login("hamlet")@@ -3543,20 +3541,24 @@ class GetOldMessagesTest(ZulipTestCase):other_params = {"anchor": 0, "num_before": 0, "num_after": 0}invalid_parameters: List[InvalidParam] = [- InvalidParam(value=False, expected_error="Bad value for 'narrow'"),- InvalidParam(value=0, expected_error="Bad value for 'narrow'"),- InvalidParam(value="", expected_error="Bad value for 'narrow'"),- InvalidParam(value="{malformed json,", expected_error="Bad value for 'narrow'"),- InvalidParam(value="{foo: 3}", expected_error="Bad value for 'narrow'"),- InvalidParam(value="[1,2]", expected_error="Bad value for 'narrow'"),- InvalidParam(value='[["x","y","z"]]', expected_error="Bad value for 'narrow'"),+ InvalidParam(value=False, expected_error="narrow is not valid JSON"),+ InvalidParam(value=0, expected_error="narrow is not a list"),+ InvalidParam(value="", expected_error="narrow is not valid JSON"),+ InvalidParam(value="{malformed json,", expected_error="narrow is not valid JSON"),+ InvalidParam(value="{foo: 3}", expected_error="narrow is not valid JSON"),+ InvalidParam(+ value="[1,2]",+ expected_error="Invalid narrow[0]: Value error, dict or list required",+ ),+ InvalidParam(+ value='[["x","y","z"]]',+ expected_error="Invalid narrow[0]: Value error, element is not a string pair",+ ),]for invalid_parameter in invalid_parameters:post_params = {**other_params, "narrow": invalid_parameter.value}result = self.client_get("/json/messages", post_params)- self.assert_json_error(- result, f"{invalid_parameter.expected_error}: {invalid_parameter.value}"- )+ self.assert_json_error(result, invalid_parameter.expected_error)def test_bad_narrow_operator(self) -> None:"""@@ -3574,11 +3576,12 @@ class GetOldMessagesTest(ZulipTestCase):# str or int is required for "id", "sender", "channel", "dm-including" and "group-pm-with"# operators- error_msg = 'elem["operand"] is not a string or integer'invalid_operands: List[InvalidParam] = [- InvalidParam(value=["1"], expected_error=error_msg),- InvalidParam(value=["2"], expected_error=error_msg),- InvalidParam(value=None, expected_error=error_msg),+ InvalidParam(value=["1"], expected_error="operand is not a string or integer"),+ InvalidParam(value=["2"], expected_error="operand is not a string or integer"),+ InvalidParam(+ value=None, expected_error="Invalid narrow[0]: Value error, operand is missing"+ ),]for operand in ["id", "sender", "channel", "dm-including", "group-pm-with"]:@@ -3586,32 +3589,35 @@ class GetOldMessagesTest(ZulipTestCase):# str or int list is required for "dm" and "pm-with" operator# First set of invalid operands- error_msg = 'elem["operand"] is not a string or an integer list'- invalid_operands = [InvalidParam(value=None, expected_error=error_msg)]+ invalid_operands = [+ InvalidParam(+ value=None, expected_error="Invalid narrow[0]: Value error, operand is missing"+ )+ ]+for operand in ["dm", "pm-with"]:self.exercise_bad_narrow_operand_using_dict_api(operand, invalid_operands)# Second set of invalid operands- error_msg = 'elem["operand"][0] is not an integer'invalid_operands = [- InvalidParam(value=["2"], expected_error=error_msg),+ InvalidParam(value=["2"], expected_error="operand[0] is not an integer"),]for operand in ["dm", "pm-with"]:self.exercise_bad_narrow_operand_using_dict_api(operand, invalid_operands)# Third set of invalid operands- error_msg = 'elem["operand"] is not a string'invalid_operands = [- InvalidParam(value=2, expected_error=error_msg),- InvalidParam(value=None, expected_error=error_msg),- InvalidParam(value=[1], expected_error=error_msg),+ InvalidParam(value=2, expected_error="operand is not a string"),+ InvalidParam(+ value=None, expected_error="Invalid narrow[0]: Value error, operand is missing"+ ),+ InvalidParam(value=[1], expected_error="operand is not a string"),]for operand in ["is", "near", "has"]:self.exercise_bad_narrow_operand_using_dict_api(operand, invalid_operands)# Disallow empty search terms- error_msg = 'elem["operand"] cannot be blank.'- invalid_operands = [InvalidParam(value="", expected_error=error_msg)]+ invalid_operands = [InvalidParam(value="", expected_error="operand cannot be blank.")]self.exercise_bad_narrow_operand_using_dict_api("search", invalid_operands)# The exercise_bad_narrow_operand helper method uses legacy tuple format to@@ -3641,7 +3647,7 @@ class GetOldMessagesTest(ZulipTestCase):returned."""self.login("hamlet")- error_msg = "Bad value for 'narrow'"+ error_msg = "Invalid narrow[0]: Value error, element is not a string pair"bad_channel_content: List[InvalidParam] = [InvalidParam(value=0, expected_error=error_msg),InvalidParam(value=[], expected_error=error_msg),@@ -3655,7 +3661,7 @@ class GetOldMessagesTest(ZulipTestCase):an error is returned."""self.login("hamlet")- error_msg = "Bad value for 'narrow'"+ error_msg = "Invalid narrow[0]: Value error, element is not a string pair"bad_channel_content: List[InvalidParam] = [InvalidParam(value=0, expected_error=error_msg),InvalidParam(value=[], expected_error=error_msg),@@ -3694,7 +3700,10 @@ class GetOldMessagesTest(ZulipTestCase):def test_bad_narrow_dm_id_list(self) -> None:self.login("hamlet")invalid_operands: List[InvalidParam] = [- InvalidParam(value=-24, expected_error="Bad value for 'narrow': [[\"dm\",-24]]")+ InvalidParam(+ value=-24,+ expected_error="Invalid narrow[0]: Value error, element is not a string pair",+ )]self.exercise_bad_narrow_operand("dm", invalid_operands)diff --git a/zerver/views/message_fetch.py b/zerver/views/message_fetch.pyindex c2b9b677114..0228718ee16 100644--- a/zerver/views/message_fetch.py+++ b/zerver/views/message_fetch.py@@ -6,27 +6,29 @@ from django.db import connection, transactionfrom django.http import HttpRequest, HttpResponsefrom django.utils.html import escape as escape_htmlfrom django.utils.translation import gettext as _+from pydantic import Json, NonNegativeIntfrom sqlalchemy.sql import and_, column, join, literal, literal_column, select, tablefrom sqlalchemy.types import Integer, Text+from typing_extensions import Annotatedfrom zerver.context_processors import get_valid_realm_from_requestfrom zerver.lib.exceptions import JsonableError, MissingAuthenticationErrorfrom zerver.lib.message import get_first_visible_message_id, messages_for_idsfrom zerver.lib.narrow import (+ NarrowParameter,OptionalNarrowListT,add_narrow_conditions,fetch_messages,is_spectator_compatible,is_web_public_narrow,- narrow_parameter,parse_anchor_value,)-from zerver.lib.request import REQ, RequestNotes, has_request_variables+from zerver.lib.request import RequestNotesfrom zerver.lib.response import json_successfrom zerver.lib.sqlalchemy_utils import get_sqlalchemy_connectionfrom zerver.lib.topic import DB_TOPIC_NAME, MATCH_TOPICfrom zerver.lib.topic_sqlalchemy import topic_column_sa-from zerver.lib.validator import check_bool, check_int, check_list, to_non_negative_int+from zerver.lib.typed_endpoint import ApiParamConfig, typed_endpointfrom zerver.models import UserMessage, UserProfileMAX_MESSAGES_PER_FETCH = 5000@@ -95,20 +97,21 @@ def clean_narrow_for_web_public_api(narrow: OptionalNarrowListT) -> OptionalNarr]-@has_request_variables+@typed_endpointdef get_messages_backend(request: HttpRequest,maybe_user_profile: Union[UserProfile, AnonymousUser],- anchor_val: Optional[str] = REQ("anchor", default=None),- include_anchor: bool = REQ(json_validator=check_bool, default=True),- num_before: int = REQ(converter=to_non_negative_int),- num_after: int = REQ(converter=to_non_negative_int),- narrow: OptionalNarrowListT = REQ("narrow", converter=narrow_parameter, default=None),- use_first_unread_anchor_val: bool = REQ(- "use_first_unread_anchor", json_validator=check_bool, default=False- ),- client_gravatar: bool = REQ(json_validator=check_bool, default=True),- apply_markdown: bool = REQ(json_validator=check_bool, default=True),+ *,+ anchor_val: Annotated[Optional[str], ApiParamConfig("anchor")] = None,+ include_anchor: Json[bool] = True,+ num_before: Json[NonNegativeInt],+ num_after: Json[NonNegativeInt],+ narrow: Json[Optional[List[NarrowParameter]]] = None,+ use_first_unread_anchor_val: Annotated[+ Json[bool], ApiParamConfig("use_first_unread_anchor")+ ] = False,+ client_gravatar: Json[bool] = True,+ apply_markdown: Json[bool] = True,) -> HttpResponse:anchor = parse_anchor_value(anchor_val, use_first_unread_anchor_val)if num_before + num_after > MAX_MESSAGES_PER_FETCH:@@ -120,6 +123,11 @@ def get_messages_backend(if num_before > 0 and num_after > 0 and not include_anchor:raise JsonableError(_("The anchor can only be excluded at an end of the range"))+ if narrow is not None and len(narrow) > 0:+ narrow_parameter_list: OptionalNarrowListT = [x.model_dump() for x in narrow]+ else:+ narrow_parameter_list = None+realm = get_valid_realm_from_request(request)if not maybe_user_profile.is_authenticated:# If user is not authenticated, clients must include@@ -134,11 +142,11 @@ def get_messages_backend(# non-web-public stream messages) via this path.if not realm.allow_web_public_streams_access():raise MissingAuthenticationError- narrow = clean_narrow_for_web_public_api(narrow)- if not is_web_public_narrow(narrow):+ narrow_parameter_list = clean_narrow_for_web_public_api(narrow_parameter_list)+ if not is_web_public_narrow(narrow_parameter_list):raise MissingAuthenticationError- assert narrow is not None- if not is_spectator_compatible(narrow):+ assert narrow_parameter_list is not None+ if not is_spectator_compatible(narrow_parameter_list):raise MissingAuthenticationError# We use None to indicate unauthenticated requests as it's more@@ -160,10 +168,10 @@ def get_messages_backend(# email_address_visibility setting.client_gravatar = False- if narrow is not None:+ if narrow_parameter_list is not None:# Add some metadata to our logging data for narrowsverbose_operators = []- for term in narrow:+ for term in narrow_parameter_list:if term["operator"] == "is":verbose_operators.append("is:" + term["operand"])else:@@ -198,7 +206,7 @@ def get_messages_backend(cursor.execute("SET TRANSACTION ISOLATION LEVEL REPEATABLE READ READ ONLY")query_info = fetch_messages(- narrow=narrow,+ narrow=narrow_parameter_list,user_profile=user_profile,realm=realm,is_web_public_query=is_web_public_query,@@ -281,13 +289,16 @@ def get_messages_backend(return json_success(request, data=ret)-@has_request_variables+@typed_endpointdef messages_in_narrow_backend(request: HttpRequest,user_profile: UserProfile,- msg_ids: List[int] = REQ(json_validator=check_list(check_int)),- narrow: OptionalNarrowListT = REQ(converter=narrow_parameter),+ *,+ msg_ids: Json[List[int]],+ narrow: Json[List[NarrowParameter]],) -> HttpResponse:+ narrow_parameter_list: OptionalNarrowListT = [x.model_dump() for x in narrow]+first_visible_message_id = get_first_visible_message_id(user_profile.realm)msg_ids = [message_id for message_id in msg_ids if message_id >= first_visible_message_id]# This query is limited to messages the user has access to because they@@ -315,7 +326,7 @@ def messages_in_narrow_backend(user_profile=user_profile,inner_msg_id_col=inner_msg_id_col,query=query,- narrow=narrow,+ narrow=narrow_parameter_list,is_web_public_query=False,realm=user_profile.realm,)