Convert room member storage tuples to attrs. (#10629)

Instead of using namedtuples. This helps with asserting type hints
and code completion.
This commit is contained in:
Patrick Cloke 2021-08-18 09:22:07 -04:00 committed by GitHub
parent 6e613a10d0
commit bec01c0758
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
7 changed files with 55 additions and 30 deletions

1
changelog.d/10629.misc Normal file
View File

@ -0,0 +1 @@
Convert room member storage tuples to `attrs` classes.

View File

@ -151,7 +151,7 @@ class InitialSyncHandler(BaseHandler):
limit = 10 limit = 10
async def handle_room(event: RoomsForUser): async def handle_room(event: RoomsForUser):
d = { d: JsonDict = {
"room_id": event.room_id, "room_id": event.room_id,
"membership": event.membership, "membership": event.membership,
"visibility": ( "visibility": (

View File

@ -701,7 +701,7 @@ class SyncHandler:
name_id = state_ids.get((EventTypes.Name, "")) name_id = state_ids.get((EventTypes.Name, ""))
canonical_alias_id = state_ids.get((EventTypes.CanonicalAlias, "")) canonical_alias_id = state_ids.get((EventTypes.CanonicalAlias, ""))
summary = {} summary: JsonDict = {}
empty_ms = MemberSummary([], 0) empty_ms = MemberSummary([], 0)
# TODO: only send these when they change. # TODO: only send these when they change.
@ -2076,21 +2076,23 @@ class SyncHandler:
# If the membership's stream ordering is after the given stream # If the membership's stream ordering is after the given stream
# ordering, we need to go and work out if the user was in the room # ordering, we need to go and work out if the user was in the room
# before. # before.
for room_id, event_pos in joined_rooms: for joined_room in joined_rooms:
if not event_pos.persisted_after(room_key): if not joined_room.event_pos.persisted_after(room_key):
joined_room_ids.add(room_id) joined_room_ids.add(joined_room.room_id)
continue continue
logger.info("User joined room after current token: %s", room_id) logger.info("User joined room after current token: %s", joined_room.room_id)
extrems = ( extrems = (
await self.store.get_forward_extremities_for_room_at_stream_ordering( await self.store.get_forward_extremities_for_room_at_stream_ordering(
room_id, event_pos.stream joined_room.room_id, joined_room.event_pos.stream
) )
) )
users_in_room = await self.state.get_current_users_in_room(room_id, extrems) users_in_room = await self.state.get_current_users_in_room(
joined_room.room_id, extrems
)
if user_id in users_in_room: if user_id in users_in_room:
joined_room_ids.add(room_id) joined_room_ids.add(joined_room.room_id)
return frozenset(joined_room_ids) return frozenset(joined_room_ids)

View File

@ -307,7 +307,9 @@ class RoomMemberWorkerStore(EventsWorkerStore):
) )
@cached() @cached()
async def get_invited_rooms_for_local_user(self, user_id: str) -> RoomsForUser: async def get_invited_rooms_for_local_user(
self, user_id: str
) -> List[RoomsForUser]:
"""Get all the rooms the *local* user is invited to. """Get all the rooms the *local* user is invited to.
Args: Args:
@ -522,7 +524,9 @@ class RoomMemberWorkerStore(EventsWorkerStore):
_get_users_server_still_shares_room_with_txn, _get_users_server_still_shares_room_with_txn,
) )
async def get_rooms_for_user(self, user_id: str, on_invalidate=None): async def get_rooms_for_user(
self, user_id: str, on_invalidate=None
) -> FrozenSet[str]:
"""Returns a set of room_ids the user is currently joined to. """Returns a set of room_ids the user is currently joined to.
If a remote user only returns rooms this server is currently If a remote user only returns rooms this server is currently

View File

@ -365,7 +365,7 @@ class UserDirectoryBackgroundUpdateStore(StateDeltasStore):
return False return False
async def update_profile_in_user_dir( async def update_profile_in_user_dir(
self, user_id: str, display_name: str, avatar_url: str self, user_id: str, display_name: Optional[str], avatar_url: Optional[str]
) -> None: ) -> None:
""" """
Update or add a user's profile in the user directory. Update or add a user's profile in the user directory.

View File

@ -14,25 +14,40 @@
# limitations under the License. # limitations under the License.
import logging import logging
from collections import namedtuple from typing import List, Optional, Tuple
import attr
from synapse.types import PersistedEventPosition
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
RoomsForUser = namedtuple( @attr.s(slots=True, frozen=True, weakref_slot=True, auto_attribs=True)
"RoomsForUser", ("room_id", "sender", "membership", "event_id", "stream_ordering") class RoomsForUser:
) room_id: str
sender: str
GetRoomsForUserWithStreamOrdering = namedtuple( membership: str
"GetRoomsForUserWithStreamOrdering", ("room_id", "event_pos") event_id: str
) stream_ordering: int
# We store this using a namedtuple so that we save about 3x space over using a @attr.s(slots=True, frozen=True, weakref_slot=True, auto_attribs=True)
# dict. class GetRoomsForUserWithStreamOrdering:
ProfileInfo = namedtuple("ProfileInfo", ("avatar_url", "display_name")) room_id: str
event_pos: PersistedEventPosition
# "members" points to a truncated list of (user_id, event_id) tuples for users of
# a given membership type, suitable for use in calculating heroes for a room. @attr.s(slots=True, frozen=True, weakref_slot=True, auto_attribs=True)
# "count" points to the total numberr of users of a given membership type. class ProfileInfo:
MemberSummary = namedtuple("MemberSummary", ("members", "count")) avatar_url: Optional[str]
display_name: Optional[str]
@attr.s(slots=True, frozen=True, weakref_slot=True, auto_attribs=True)
class MemberSummary:
# A truncated list of (user_id, event_id) tuples for users of a given
# membership type, suitable for use in calculating heroes for a room.
members: List[Tuple[str, str]]
# The total number of users of a given membership type.
count: int

View File

@ -20,7 +20,7 @@ from synapse.api.room_versions import RoomVersions
from synapse.events import FrozenEvent, _EventInternalMetadata, make_event_from_dict from synapse.events import FrozenEvent, _EventInternalMetadata, make_event_from_dict
from synapse.handlers.room import RoomEventSource from synapse.handlers.room import RoomEventSource
from synapse.replication.slave.storage.events import SlavedEventStore from synapse.replication.slave.storage.events import SlavedEventStore
from synapse.storage.roommember import RoomsForUser from synapse.storage.roommember import GetRoomsForUserWithStreamOrdering, RoomsForUser
from synapse.types import PersistedEventPosition from synapse.types import PersistedEventPosition
from tests.server import FakeTransport from tests.server import FakeTransport
@ -216,7 +216,7 @@ class SlavedEventStoreTestCase(BaseSlavedStoreTestCase):
self.check( self.check(
"get_rooms_for_user_with_stream_ordering", "get_rooms_for_user_with_stream_ordering",
(USER_ID_2,), (USER_ID_2,),
{(ROOM_ID, expected_pos)}, {GetRoomsForUserWithStreamOrdering(ROOM_ID, expected_pos)},
) )
def test_get_rooms_for_user_with_stream_ordering_with_multi_event_persist(self): def test_get_rooms_for_user_with_stream_ordering_with_multi_event_persist(self):
@ -305,7 +305,10 @@ class SlavedEventStoreTestCase(BaseSlavedStoreTestCase):
expected_pos = PersistedEventPosition( expected_pos = PersistedEventPosition(
"master", j2.internal_metadata.stream_ordering "master", j2.internal_metadata.stream_ordering
) )
self.assertEqual(joined_rooms, {(ROOM_ID, expected_pos)}) self.assertEqual(
joined_rooms,
{GetRoomsForUserWithStreamOrdering(ROOM_ID, expected_pos)},
)
event_id = 0 event_id = 0