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.

peformance: Eliminate StreamRecipientMap.

Steve Howell0ca07ffd3c17
diff --git a/zerver/lib/actions.py b/zerver/lib/actions.py
index ac2bf1644d5..359fae019ea 100644
--- a/zerver/lib/actions.py
+++ b/zerver/lib/actions.py
@@ -119,7 +119,6 @@ from zerver.lib.send_email import (
from zerver.lib.server_initialization import create_internal_realm, server_initialized
from zerver.lib.sessions import delete_user_sessions
from zerver.lib.storage import static_path
-from zerver.lib.stream_recipient import StreamRecipientMap
from zerver.lib.stream_subscription import (
SubInfo,
bulk_get_peers,
@@ -2626,15 +2625,14 @@ def validate_user_access_to_subscribers_helper(
if (stream_dict["invite_only"] and not check_user_subscribed(user_profile)):
raise JsonableError(_("Unable to retrieve subscribers for private stream"))
-def bulk_get_subscriber_user_ids(stream_dicts: Iterable[Mapping[str, Any]],
- user_profile: UserProfile,
- sub_dict: Mapping[int, bool],
- stream_recipient: StreamRecipientMap) -> Dict[int, List[int]]:
+def bulk_get_subscriber_user_ids(
+ stream_dicts: Iterable[Mapping[str, Any]],
+ user_profile: UserProfile,
+ sub_dict: Mapping[int, bool],
+) -> Dict[int, List[int]]:
"""sub_dict maps stream_id => whether the user is subscribed to that stream."""
target_stream_dicts = []
for stream_dict in stream_dicts:
- stream_recipient.populate_with(stream_id=stream_dict["id"],
- recipient_id=stream_dict["recipient_id"])
try:
validate_user_access_to_subscribers_helper(
user_profile,
@@ -2645,11 +2643,8 @@ def bulk_get_subscriber_user_ids(stream_dicts: Iterable[Mapping[str, Any]],
continue
target_stream_dicts.append(stream_dict)
- stream_ids = [stream['id'] for stream in target_stream_dicts]
- recipient_ids = sorted(
- stream_recipient.recipient_id_for(stream_id)
- for stream_id in stream_ids
- )
+ recip_to_stream_id = {stream["recipient_id"]: stream["id"] for stream in target_stream_dicts}
+ recipient_ids = sorted([stream["recipient_id"] for stream in target_stream_dicts])
result: Dict[int, List[int]] = {stream["id"]: [] for stream in stream_dicts}
if not recipient_ids:
@@ -2684,8 +2679,6 @@ def bulk_get_subscriber_user_ids(stream_dicts: Iterable[Mapping[str, Any]],
rows = cursor.fetchall()
cursor.close()
- recip_to_stream_id = stream_recipient.recipient_to_stream_id_dict()
-
'''
Using groupby/itemgetter here is important for performance, at scale.
It makes it so that all interpreter overhead is just O(N) in nature.
@@ -4915,23 +4908,24 @@ def gather_subscriptions_helper(user_profile: UserProfile,
# the stream, so doesn't belong in API_FIELDS.
"email_token",
)
+ recip_id_to_stream_id = {stream["recipient_id"]: stream["id"] for stream in all_streams}
sub_dicts = get_stream_subscriptions_for_user(user_profile).values(
*Subscription.API_FIELDS, "recipient_id").order_by("recipient_id")
- sub_dicts = list(sub_dicts)
- sub_recipient_ids = [
- sub['recipient_id']
- for sub in sub_dicts
+ # We only care about subscriptions for active streams.
+ sub_dicts = [
+ sub for sub in sub_dicts
+ if recip_id_to_stream_id.get(sub["recipient_id"])
]
- stream_recipient = StreamRecipientMap()
- stream_recipient.populate_for_recipient_ids(sub_recipient_ids)
- stream_ids: Set[int] = set()
+ # Hydrate sub_dicts with stream_id
for sub in sub_dicts:
- sub['stream_id'] = stream_recipient.stream_id_for(sub['recipient_id'])
- stream_ids.add(sub['stream_id'])
+ recipient_id = sub["recipient_id"]
+ stream_id = recip_id_to_stream_id[recipient_id]
+ sub["stream_id"] = stream_id
+ stream_ids = {sub["stream_id"] for sub in sub_dicts}
recent_traffic = get_streams_traffic(stream_ids=stream_ids)
stream_dicts = [stream for stream in all_streams if stream['id'] in stream_ids]
@@ -4964,7 +4958,6 @@ def gather_subscriptions_helper(user_profile: UserProfile,
all_streams,
user_profile,
streams_subscribed_map,
- stream_recipient,
)
else:
# If we're not including subscribers, always return None,
@@ -4975,9 +4968,6 @@ def gather_subscriptions_helper(user_profile: UserProfile,
for sub in sub_dicts:
sub_unsub_stream_ids.add(sub["stream_id"])
stream = stream_hash.get(sub["stream_id"])
- if not stream:
- # This stream has been deactivated, don't include it.
- continue
# We first construct a dictionary based on the standard Stream
# and Subscription models' API_FIELDS.
diff --git a/zerver/lib/stream_recipient.py b/zerver/lib/stream_recipient.py
deleted file mode 100644
index 596c0317a93..00000000000
--- a/zerver/lib/stream_recipient.py
+++ /dev/null
@@ -1,73 +0,0 @@
-from typing import Dict, List
-
-from django.db import connection
-from psycopg2.sql import SQL
-
-from zerver.models import Recipient
-
-
-class StreamRecipientMap:
- '''
- This class maps stream_id -> recipient_id and vice versa.
- It is useful for bulk operations. Call the populate_* methods
- to initialize the data structures. You should try to avoid
- excessive queries by finding ids up front, but you can call
- this repeatedly, and it will only look up new ids.
-
- You should ONLY use this class for READ operations.
-
- Note that this class uses raw SQL, because we want to highly
- optimize page loads.
- '''
-
- def __init__(self) -> None:
- self.recip_to_stream: Dict[int, int] = {}
- self.stream_to_recip: Dict[int, int] = {}
-
- def populate_with(self, *, stream_id: int, recipient_id: int) -> None:
- # We use * to enforce using named arguments when calling this function,
- # to avoid confusion about the ordering of the two integers.
- self.recip_to_stream[recipient_id] = stream_id
- self.stream_to_recip[stream_id] = recipient_id
-
- def populate_for_recipient_ids(self, recipient_ids: List[int]) -> None:
- recipient_ids = sorted(
- recip_id for recip_id in recipient_ids
- if recip_id not in self.recip_to_stream
- )
-
- if not recipient_ids:
- return
-
- # see comment at the top of the class
- query = SQL('''
- SELECT
- zerver_recipient.id as recipient_id,
- zerver_recipient.type_id as stream_id
- FROM
- zerver_recipient
- WHERE
- zerver_recipient.type = %(STREAM)s
- AND
- zerver_recipient.id in %(recipient_ids)s
- ''')
-
- cursor = connection.cursor()
- cursor.execute(query, {
- "STREAM": Recipient.STREAM,
- "recipient_ids": tuple(recipient_ids),
- })
- rows = cursor.fetchall()
- cursor.close()
- for recip_id, stream_id in rows:
- self.recip_to_stream[recip_id] = stream_id
- self.stream_to_recip[stream_id] = recip_id
-
- def recipient_id_for(self, stream_id: int) -> int:
- return self.stream_to_recip[stream_id]
-
- def stream_id_for(self, recip_id: int) -> int:
- return self.recip_to_stream[recip_id]
-
- def recipient_to_stream_id_dict(self) -> Dict[int, int]:
- return self.recip_to_stream
diff --git a/zerver/tests/test_event_system.py b/zerver/tests/test_event_system.py
index 317030b9b33..3dceaad9f1a 100644
--- a/zerver/tests/test_event_system.py
+++ b/zerver/tests/test_event_system.py
@@ -734,7 +734,7 @@ class FetchQueriesTest(ZulipTestCase):
realm=user.realm,
)
- self.assert_length(queries, 30)
+ self.assert_length(queries, 29)
expected_counts = dict(
alert_words=1,
@@ -758,7 +758,7 @@ class FetchQueriesTest(ZulipTestCase):
starred_messages=1,
stream=2,
stop_words=0,
- subscription=5,
+ subscription=4,
update_display_settings=0,
update_global_notifications=0,
update_message_flags=5,
diff --git a/zerver/tests/test_home.py b/zerver/tests/test_home.py
index 50843ab82a2..0e5d13a8dcf 100644
--- a/zerver/tests/test_home.py
+++ b/zerver/tests/test_home.py
@@ -255,7 +255,7 @@ class HomeTest(ZulipTestCase):
self.assertEqual(set(result["Cache-Control"].split(", ")),
{"must-revalidate", "no-store", "no-cache"})
- self.assert_length(queries, 40)
+ self.assert_length(queries, 39)
self.assert_length(cache_mock.call_args_list, 5)
html = result.content.decode('utf-8')
@@ -321,7 +321,7 @@ class HomeTest(ZulipTestCase):
result = self._get_home_page()
self.check_rendered_logged_in_app(result)
self.assert_length(cache_mock.call_args_list, 6)
- self.assert_length(queries, 37)
+ self.assert_length(queries, 36)
def test_num_queries_with_streams(self) -> None:
main_user = self.example_user('hamlet')
@@ -352,7 +352,7 @@ class HomeTest(ZulipTestCase):
with queries_captured() as queries2:
result = self._get_home_page()
- self.assert_length(queries2, 35)
+ self.assert_length(queries2, 34)
# Do a sanity check that our new streams were in the payload.
html = result.content.decode('utf-8')
diff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.py
index e8597ab7be5..382932425f3 100644
--- a/zerver/tests/test_subs.py
+++ b/zerver/tests/test_subs.py
@@ -47,7 +47,6 @@ from zerver.lib.actions import (
)
from zerver.lib.message import aggregate_unread_data, get_raw_unread_data
from zerver.lib.response import json_error, json_success
-from zerver.lib.stream_recipient import StreamRecipientMap
from zerver.lib.stream_subscription import (
get_active_subscriptions_for_stream_id,
num_subscribers_for_stream_id,
@@ -103,7 +102,6 @@ class TestMiscStuff(ZulipTestCase):
stream_dicts=[],
user_profile=user_profile,
sub_dict={},
- stream_recipient=StreamRecipientMap(),
)
self.assertEqual(result, {})
@@ -4237,7 +4235,7 @@ class GetSubscribersTest(ZulipTestCase):
if not sub["name"].startswith("stream_"):
continue
self.assertTrue(len(sub["subscribers"]) == len(users_to_subscribe))
- self.assert_length(queries, 6)
+ self.assert_length(queries, 5)
def test_never_subscribed_streams(self) -> None:
"""
@@ -4307,7 +4305,7 @@ class GetSubscribersTest(ZulipTestCase):
with queries_captured() as queries:
sub_data = gather_subscriptions_helper(self.user_profile)
never_subscribed = sub_data[2]
- self.assert_length(queries, 5)
+ self.assert_length(queries, 4)
# Ignore old streams.
never_subscribed = [
@@ -4466,7 +4464,7 @@ class GetSubscribersTest(ZulipTestCase):
self.assertTrue(len(sub["subscribers"]) == len(users_to_subscribe))
else:
self.assertTrue(len(sub["subscribers"]) == 0)
- self.assert_length(queries, 6)
+ self.assert_length(queries, 5)
def test_nonsubscriber(self) -> None:
"""