Zulip server and web application. Open-source team chat that helps teams stay productive and focused.
performance: Optimize filter_stream_authorization.
Steve Howell3b338ec32e05
diff --git a/zerver/lib/streams.py b/zerver/lib/streams.pyindex d4ad60caabd..be1d75889b2 100644--- a/zerver/lib/streams.py+++ b/zerver/lib/streams.py@@ -1,4 +1,4 @@-from typing import Iterable, List, Optional, Set, Tuple, Union+from typing import Iterable, List, Optional, Tuple, Unionfrom django.conf import settingsfrom django.db.models.query import QuerySet@@ -457,19 +457,16 @@ def can_access_stream_history_by_id(user_profile: UserProfile, stream_id: int) -def filter_stream_authorization(user_profile: UserProfile,streams: Iterable[Stream]) -> Tuple[List[Stream], List[Stream]]:- streams_subscribed: Set[int] = set()recipient_ids = [stream.recipient_id for stream in streams]- subs = Subscription.objects.filter(user_profile=user_profile,- recipient_id__in=recipient_ids,- active=True)-- for sub in subs:- streams_subscribed.add(sub.recipient.type_id)+ subscribed_recipient_ids = set(Subscription.objects.filter(+ user_profile=user_profile,+ recipient_id__in=recipient_ids,+ active=True).values_list('recipient_id', flat=True))unauthorized_streams: List[Stream] = []for stream in streams:# The user is authorized for their own streams- if stream.id in streams_subscribed:+ if stream.recipient_id in subscribed_recipient_ids:continue# Web public streams are accessible even to guestsdiff --git a/zerver/tests/test_subs.py b/zerver/tests/test_subs.pyindex 4de4144bd2d..f9af636ff85 100644--- a/zerver/tests/test_subs.py+++ b/zerver/tests/test_subs.py@@ -3259,10 +3259,15 @@ class SubscriptionAPITest(ZulipTestCase):def test_bulk_subscribe_many(self) -> None:# Create a whole bunch of streams- streams = [f"stream_{i}" for i in range(20)]+ streams = [f"stream_{i}" for i in range(30)]for stream_name in streams:self.make_stream(stream_name)+ # Subscribe out test user to some streams, including+ # some that we may soon subscribe them to.+ for stream_name in ["Verona", "Denmark", *streams[:10]]:+ self.subscribe(self.test_user, stream_name)+with queries_captured() as queries:self.common_subscribe_to_streams(self.test_user,