From 37d846205c07d76e133b2f7039f24ed84260392d Mon Sep 17 00:00:00 2001 From: Patrick Cloke Date: Tue, 17 May 2022 10:33:06 -0400 Subject: [PATCH] Avoid unnecessary database access. --- synapse/handlers/relations.py | 21 ++++++++++++++++++--- tests/rest/client/test_relations.py | 4 ++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/synapse/handlers/relations.py b/synapse/handlers/relations.py index 655bb887d42e..c72a13f9e616 100644 --- a/synapse/handlers/relations.py +++ b/synapse/handlers/relations.py @@ -273,13 +273,28 @@ async def _get_threads_for_events( # Fetch thread summaries. summaries = await self._main_store.get_thread_summaries(event_ids) - # Only fetch participated for a limited selection based on what had + # Only fetch whether the current user has participated in a thread based + # on which returned for a limited selection based on what had # summaries. thread_event_ids = [ event_id for event_id, summary in summaries.items() if summary ] - participated = await self._main_store.get_threads_participated( - thread_event_ids, user_id + + # Preseed thread participation with whether the requester send the event. + participated = { + event_id: events_by_id[event_id].sender == user_id + for event_id in thread_event_ids + } + # Check other events against the database. + participated.update( + await self._main_store.get_threads_participated( + [ + event_id + for event_id in thread_event_ids + if not participated[event_id] + ], + user_id, + ) ) # Then subtract off the results for any ignored users. diff --git a/tests/rest/client/test_relations.py b/tests/rest/client/test_relations.py index 6f3aa8eb2bc0..ed69498905f3 100644 --- a/tests/rest/client/test_relations.py +++ b/tests/rest/client/test_relations.py @@ -1073,7 +1073,7 @@ def assert_thread(bundled_aggregations: JsonDict) -> None: return assert_thread # A user which has sent the root event or replied has participated. - self._test_bundled_aggregations(RelationTypes.THREAD, _gen_assert(True), 10) + self._test_bundled_aggregations(RelationTypes.THREAD, _gen_assert(True), 9) # Note that this re-uses some cached values, so the total number of # queries is much smaller. self._test_bundled_aggregations( @@ -1131,7 +1131,7 @@ def assert_thread(bundled_aggregations: JsonDict) -> None: bundled_aggregations["latest_event"].get("unsigned"), ) - self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 10) + self._test_bundled_aggregations(RelationTypes.THREAD, assert_thread, 9) def test_nested_thread(self) -> None: """