Skip to content
This repository was archived by the owner on Apr 26, 2024. It is now read-only.

Commit 8766a07

Browse files
committed
Merge commit 'dc22090a6' into anoa/dinsic_release_1_21_x
* commit 'dc22090a6': Add type hints to synapse.handlers.room (#8090) Remove some unused database functions. (#8085) Convert misc database code to async (#8087) Remove a space at the start of a changelog entry.
2 parents 1b86e62 + dc22090 commit 8766a07

21 files changed

+128
-348
lines changed

changelog.d/8072.misc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Convert various parts of the codebase to async/await.
1+
Convert various parts of the codebase to async/await.

changelog.d/8085.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Remove some unused database functions.

changelog.d/8087.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Convert various parts of the codebase to async/await.

changelog.d/8090.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type hints to `synapse.handlers.room`.

synapse/handlers/room.py

Lines changed: 66 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,7 @@
2222
import math
2323
import string
2424
from collections import OrderedDict
25-
from typing import Awaitable, Optional, Tuple
25+
from typing import TYPE_CHECKING, Any, Awaitable, Dict, List, Optional, Tuple
2626

2727
from synapse.api.constants import (
2828
EventTypes,
@@ -32,11 +32,14 @@
3232
RoomEncryptionAlgorithms,
3333
)
3434
from synapse.api.errors import AuthError, Codes, NotFoundError, StoreError, SynapseError
35+
from synapse.api.filtering import Filter
3536
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS, RoomVersion
37+
from synapse.events import EventBase
3638
from synapse.events.utils import copy_power_levels_contents
3739
from synapse.http.endpoint import parse_and_validate_server_name
3840
from synapse.storage.state import StateFilter
3941
from synapse.types import (
42+
JsonDict,
4043
Requester,
4144
RoomAlias,
4245
RoomID,
@@ -53,6 +56,9 @@
5356

5457
from ._base import BaseHandler
5558

59+
if TYPE_CHECKING:
60+
from synapse.server import HomeServer
61+
5662
logger = logging.getLogger(__name__)
5763

5864
id_server_scheme = "https://"
@@ -61,7 +67,7 @@
6167

6268

6369
class RoomCreationHandler(BaseHandler):
64-
def __init__(self, hs):
70+
def __init__(self, hs: "HomeServer"):
6571
super(RoomCreationHandler, self).__init__(hs)
6672

6773
self.spam_checker = hs.get_spam_checker()
@@ -92,7 +98,7 @@ def __init__(self, hs):
9298
"guest_can_join": False,
9399
"power_level_content_override": {},
94100
},
95-
}
101+
} # type: Dict[str, Dict[str, Any]]
96102

97103
# Modify presets to selectively enable encryption by default per homeserver config
98104
for preset_name, preset_config in self._presets_dict.items():
@@ -215,6 +221,9 @@ async def _upgrade_room(
215221

216222
old_room_state = await tombstone_context.get_current_state_ids()
217223

224+
# We know the tombstone event isn't an outlier so it has current state.
225+
assert old_room_state is not None
226+
218227
# update any aliases
219228
await self._move_aliases_to_new_room(
220229
requester, old_room_id, new_room_id, old_room_state
@@ -540,17 +549,21 @@ async def _move_aliases_to_new_room(
540549
logger.error("Unable to send updated alias events in new room: %s", e)
541550

542551
async def create_room(
543-
self, requester, config, ratelimit=True, creator_join_profile=None
552+
self,
553+
requester: Requester,
554+
config: JsonDict,
555+
ratelimit: bool = True,
556+
creator_join_profile: Optional[JsonDict] = None,
544557
) -> Tuple[dict, int]:
545558
""" Creates a new room.
546559
547560
Args:
548-
requester (synapse.types.Requester):
561+
requester:
549562
The user who requested the room creation.
550-
config (dict) : A dict of configuration options.
551-
ratelimit (bool): set to False to disable the rate limiter
563+
config : A dict of configuration options.
564+
ratelimit: set to False to disable the rate limiter
552565
553-
creator_join_profile (dict|None):
566+
creator_join_profile:
554567
Set to override the displayname and avatar for the creating
555568
user in this room. If unset, displayname and avatar will be
556569
derived from the user's profile. If set, should contain the
@@ -619,6 +632,7 @@ async def create_room(
619632
Codes.UNSUPPORTED_ROOM_VERSION,
620633
)
621634

635+
room_alias = None
622636
if "room_alias_name" in config:
623637
for wchar in string.whitespace:
624638
if wchar in config["room_alias_name"]:
@@ -629,8 +643,6 @@ async def create_room(
629643

630644
if mapping:
631645
raise SynapseError(400, "Room alias already taken", Codes.ROOM_IN_USE)
632-
else:
633-
room_alias = None
634646

635647
for i in invite_list:
636648
try:
@@ -797,31 +809,38 @@ async def create_room(
797809

798810
async def _send_events_for_new_room(
799811
self,
800-
creator, # A Requester object.
801-
room_id,
802-
preset_config,
803-
invite_list,
804-
initial_state,
805-
creation_content,
806-
room_alias=None,
807-
power_level_content_override=None, # Doesn't apply when initial state has power level state event content
808-
creator_join_profile=None,
812+
creator: Requester,
813+
room_id: str,
814+
preset_config: str,
815+
invite_list: List[str],
816+
initial_state: StateMap,
817+
creation_content: JsonDict,
818+
room_alias: Optional[RoomAlias] = None,
819+
power_level_content_override: Optional[JsonDict] = None,
820+
creator_join_profile: Optional[JsonDict] = None,
809821
) -> int:
810822
"""Sends the initial events into a new room.
811823
824+
`power_level_content_override` doesn't apply when initial state has
825+
power level state event content.
826+
812827
Returns:
813828
The stream_id of the last event persisted.
814829
"""
815830

816-
def create(etype, content, **kwargs):
831+
creator_id = creator.user.to_string()
832+
833+
event_keys = {"room_id": room_id, "sender": creator_id, "state_key": ""}
834+
835+
def create(etype: str, content: JsonDict, **kwargs) -> JsonDict:
817836
e = {"type": etype, "content": content}
818837

819838
e.update(event_keys)
820839
e.update(kwargs)
821840

822841
return e
823842

824-
async def send(etype, content, **kwargs) -> int:
843+
async def send(etype: str, content: JsonDict, **kwargs) -> int:
825844
event = create(etype, content, **kwargs)
826845
logger.debug("Sending %s in new room", etype)
827846
(
@@ -834,10 +853,6 @@ async def send(etype, content, **kwargs) -> int:
834853

835854
config = self._presets_dict[preset_config]
836855

837-
creator_id = creator.user.to_string()
838-
839-
event_keys = {"room_id": room_id, "sender": creator_id, "state_key": ""}
840-
841856
creation_content.update({"creator": creator_id})
842857
await send(etype=EventTypes.Create, content=creation_content)
843858

@@ -879,7 +894,7 @@ async def send(etype, content, **kwargs) -> int:
879894
"kick": 50,
880895
"redact": 50,
881896
"invite": 50,
882-
}
897+
} # type: JsonDict
883898

884899
if config["original_invitees_have_ops"]:
885900
for invitee in invite_list:
@@ -933,7 +948,7 @@ async def send(etype, content, **kwargs) -> int:
933948
return last_sent_stream_id
934949

935950
async def _generate_room_id(
936-
self, creator_id: str, is_public: str, room_version: RoomVersion,
951+
self, creator_id: str, is_public: bool, room_version: RoomVersion,
937952
):
938953
# autogen room IDs and try to create it. We may clash, so just
939954
# try a few times till one goes through, giving up eventually.
@@ -957,23 +972,30 @@ async def _generate_room_id(
957972

958973

959974
class RoomContextHandler(object):
960-
def __init__(self, hs):
975+
def __init__(self, hs: "HomeServer"):
961976
self.hs = hs
962977
self.store = hs.get_datastore()
963978
self.storage = hs.get_storage()
964979
self.state_store = self.storage.state
965980

966-
async def get_event_context(self, user, room_id, event_id, limit, event_filter):
981+
async def get_event_context(
982+
self,
983+
user: UserID,
984+
room_id: str,
985+
event_id: str,
986+
limit: int,
987+
event_filter: Optional[Filter],
988+
) -> Optional[JsonDict]:
967989
"""Retrieves events, pagination tokens and state around a given event
968990
in a room.
969991
970992
Args:
971-
user (UserID)
972-
room_id (str)
973-
event_id (str)
974-
limit (int): The maximum number of events to return in total
993+
user
994+
room_id
995+
event_id
996+
limit: The maximum number of events to return in total
975997
(excluding state).
976-
event_filter (Filter|None): the filter to apply to the events returned
998+
event_filter: the filter to apply to the events returned
977999
(excluding the target event_id)
9781000
9791001
Returns:
@@ -1060,12 +1082,18 @@ def filter_evts(events):
10601082

10611083

10621084
class RoomEventSource(object):
1063-
def __init__(self, hs):
1085+
def __init__(self, hs: "HomeServer"):
10641086
self.store = hs.get_datastore()
10651087

10661088
async def get_new_events(
1067-
self, user, from_key, limit, room_ids, is_guest, explicit_room_id=None
1068-
):
1089+
self,
1090+
user: UserID,
1091+
from_key: str,
1092+
limit: int,
1093+
room_ids: List[str],
1094+
is_guest: bool,
1095+
explicit_room_id: Optional[str] = None,
1096+
) -> Tuple[List[EventBase], str]:
10691097
# We just ignore the key for now.
10701098

10711099
to_key = self.get_current_key()
@@ -1123,7 +1151,7 @@ class RoomShutdownHandler(object):
11231151
)
11241152
DEFAULT_ROOM_NAME = "Content Violation Notification"
11251153

1126-
def __init__(self, hs):
1154+
def __init__(self, hs: "HomeServer"):
11271155
self.hs = hs
11281156
self.room_member_handler = hs.get_room_member_handler()
11291157
self._room_creation_handler = hs.get_room_creation_handler()

synapse/storage/background_updates.py

Lines changed: 5 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -18,8 +18,6 @@
1818

1919
from canonicaljson import json
2020

21-
from twisted.internet import defer
22-
2321
from synapse.metrics.background_process_metrics import run_as_background_process
2422

2523
from . import engines
@@ -308,9 +306,8 @@ def register_noop_background_update(self, update_name):
308306
update_name (str): Name of update
309307
"""
310308

311-
@defer.inlineCallbacks
312-
def noop_update(progress, batch_size):
313-
yield self._end_background_update(update_name)
309+
async def noop_update(progress, batch_size):
310+
await self._end_background_update(update_name)
314311
return 1
315312

316313
self.register_background_update_handler(update_name, noop_update)
@@ -409,12 +406,11 @@ def create_index_sqlite(conn):
409406
else:
410407
runner = create_index_sqlite
411408

412-
@defer.inlineCallbacks
413-
def updater(progress, batch_size):
409+
async def updater(progress, batch_size):
414410
if runner is not None:
415411
logger.info("Adding index %s to %s", index_name, table)
416-
yield self.db_pool.runWithConnection(runner)
417-
yield self._end_background_update(update_name)
412+
await self.db_pool.runWithConnection(runner)
413+
await self._end_background_update(update_name)
418414
return 1
419415

420416
self.register_background_update_handler(update_name, updater)

synapse/storage/databases/main/devices.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -671,10 +671,9 @@ def get_device_list_last_stream_id_for_remote(self, user_id: str):
671671
@cachedList(
672672
cached_method_name="get_device_list_last_stream_id_for_remote",
673673
list_name="user_ids",
674-
inlineCallbacks=True,
675674
)
676-
def get_device_list_last_stream_id_for_remotes(self, user_ids: str):
677-
rows = yield self.db_pool.simple_select_many_batch(
675+
async def get_device_list_last_stream_id_for_remotes(self, user_ids: str):
676+
rows = await self.db_pool.simple_select_many_batch(
678677
table="device_lists_remote_extremeties",
679678
column="user_id",
680679
iterable=user_ids,

synapse/storage/databases/main/event_federation.py

Lines changed: 0 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -257,11 +257,6 @@ def _get_auth_chain_difference_txn(
257257
# Return all events where not all sets can reach them.
258258
return {eid for eid, n in event_to_missing_sets.items() if n}
259259

260-
def get_oldest_events_in_room(self, room_id):
261-
return self.db_pool.runInteraction(
262-
"get_oldest_events_in_room", self._get_oldest_events_in_room_txn, room_id
263-
)
264-
265260
def get_oldest_events_with_depth_in_room(self, room_id):
266261
return self.db_pool.runInteraction(
267262
"get_oldest_events_with_depth_in_room",
@@ -303,14 +298,6 @@ async def get_max_depth_of(self, event_ids: List[str]) -> int:
303298
else:
304299
return max(row["depth"] for row in rows)
305300

306-
def _get_oldest_events_in_room_txn(self, txn, room_id):
307-
return self.db_pool.simple_select_onecol_txn(
308-
txn,
309-
table="event_backward_extremities",
310-
keyvalues={"room_id": room_id},
311-
retcol="event_id",
312-
)
313-
314301
def get_prev_events_for_room(self, room_id: str):
315302
"""
316303
Gets a subset of the current forward extremities in the given room.

synapse/storage/databases/main/event_push_actions.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
from synapse.storage._base import LoggingTransaction, SQLBaseStore, db_to_json
2222
from synapse.storage.database import DatabasePool
2323
from synapse.util import json_encoder
24-
from synapse.util.caches.descriptors import cachedInlineCallbacks
24+
from synapse.util.caches.descriptors import cached
2525

2626
logger = logging.getLogger(__name__)
2727

@@ -86,18 +86,17 @@ def __init__(self, database: DatabasePool, db_conn, hs):
8686
self._rotate_delay = 3
8787
self._rotate_count = 10000
8888

89-
@cachedInlineCallbacks(num_args=3, tree=True, max_entries=5000)
90-
def get_unread_event_push_actions_by_room_for_user(
89+
@cached(num_args=3, tree=True, max_entries=5000)
90+
async def get_unread_event_push_actions_by_room_for_user(
9191
self, room_id, user_id, last_read_event_id
9292
):
93-
ret = yield self.db_pool.runInteraction(
93+
return await self.db_pool.runInteraction(
9494
"get_unread_event_push_actions_by_room",
9595
self._get_unread_counts_by_receipt_txn,
9696
room_id,
9797
user_id,
9898
last_read_event_id,
9999
)
100-
return ret
101100

102101
def _get_unread_counts_by_receipt_txn(
103102
self, txn, room_id, user_id, last_read_event_id

0 commit comments

Comments
 (0)