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

Commit 98aec1c

Browse files
Use inline type hints in handlers/ and rest/. (#10382)
1 parent 36dc154 commit 98aec1c

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

43 files changed

+212
-215
lines changed

changelog.d/10382.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Convert internal type variable syntax to reflect wider ecosystem use.

synapse/handlers/_base.py

+4-4
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ class BaseHandler:
3838
"""
3939

4040
def __init__(self, hs: "HomeServer"):
41-
self.store = hs.get_datastore() # type: synapse.storage.DataStore
41+
self.store = hs.get_datastore()
4242
self.auth = hs.get_auth()
4343
self.notifier = hs.get_notifier()
44-
self.state_handler = hs.get_state_handler() # type: synapse.state.StateHandler
44+
self.state_handler = hs.get_state_handler()
4545
self.distributor = hs.get_distributor()
4646
self.clock = hs.get_clock()
4747
self.hs = hs
@@ -55,12 +55,12 @@ def __init__(self, hs: "HomeServer"):
5555
# Check whether ratelimiting room admin message redaction is enabled
5656
# by the presence of rate limits in the config
5757
if self.hs.config.rc_admin_redaction:
58-
self.admin_redaction_ratelimiter = Ratelimiter(
58+
self.admin_redaction_ratelimiter: Optional[Ratelimiter] = Ratelimiter(
5959
store=self.store,
6060
clock=self.clock,
6161
rate_hz=self.hs.config.rc_admin_redaction.per_second,
6262
burst_count=self.hs.config.rc_admin_redaction.burst_count,
63-
) # type: Optional[Ratelimiter]
63+
)
6464
else:
6565
self.admin_redaction_ratelimiter = None
6666

synapse/handlers/admin.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ async def export_user_data(self, user_id: str, writer: "ExfiltrationWriter") ->
139139
to_key = RoomStreamToken(None, stream_ordering)
140140

141141
# Events that we've processed in this room
142-
written_events = set() # type: Set[str]
142+
written_events: Set[str] = set()
143143

144144
# We need to track gaps in the events stream so that we can then
145145
# write out the state at those events. We do this by keeping track
@@ -152,7 +152,7 @@ async def export_user_data(self, user_id: str, writer: "ExfiltrationWriter") ->
152152
# The reverse mapping to above, i.e. map from unseen event to events
153153
# that have the unseen event in their prev_events, i.e. the unseen
154154
# events "children".
155-
unseen_to_child_events = {} # type: Dict[str, Set[str]]
155+
unseen_to_child_events: Dict[str, Set[str]] = {}
156156

157157
# We fetch events in the room the user could see by fetching *all*
158158
# events that we have and then filtering, this isn't the most

synapse/handlers/appservice.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -96,7 +96,7 @@ async def _notify_interested_services(self, max_token: RoomStreamToken):
9696
self.current_max, limit
9797
)
9898

99-
events_by_room = {} # type: Dict[str, List[EventBase]]
99+
events_by_room: Dict[str, List[EventBase]] = {}
100100
for event in events:
101101
events_by_room.setdefault(event.room_id, []).append(event)
102102

@@ -275,7 +275,7 @@ async def _handle_receipts(self, service: ApplicationService) -> List[JsonDict]:
275275
async def _handle_presence(
276276
self, service: ApplicationService, users: Collection[Union[str, UserID]]
277277
) -> List[JsonDict]:
278-
events = [] # type: List[JsonDict]
278+
events: List[JsonDict] = []
279279
presence_source = self.event_sources.sources["presence"]
280280
from_key = await self.store.get_type_stream_id_for_appservice(
281281
service, "presence"
@@ -375,7 +375,7 @@ async def get_3pe_protocols(
375375
self, only_protocol: Optional[str] = None
376376
) -> Dict[str, JsonDict]:
377377
services = self.store.get_app_services()
378-
protocols = {} # type: Dict[str, List[JsonDict]]
378+
protocols: Dict[str, List[JsonDict]] = {}
379379

380380
# Collect up all the individual protocol responses out of the ASes
381381
for s in services:

synapse/handlers/auth.py

+8-8
Original file line numberDiff line numberDiff line change
@@ -191,7 +191,7 @@ class AuthHandler(BaseHandler):
191191
def __init__(self, hs: "HomeServer"):
192192
super().__init__(hs)
193193

194-
self.checkers = {} # type: Dict[str, UserInteractiveAuthChecker]
194+
self.checkers: Dict[str, UserInteractiveAuthChecker] = {}
195195
for auth_checker_class in INTERACTIVE_AUTH_CHECKERS:
196196
inst = auth_checker_class(hs)
197197
if inst.is_enabled():
@@ -296,7 +296,7 @@ def __init__(self, hs: "HomeServer"):
296296

297297
# A mapping of user ID to extra attributes to include in the login
298298
# response.
299-
self._extra_attributes = {} # type: Dict[str, SsoLoginExtraAttributes]
299+
self._extra_attributes: Dict[str, SsoLoginExtraAttributes] = {}
300300

301301
async def validate_user_via_ui_auth(
302302
self,
@@ -500,7 +500,7 @@ async def check_ui_auth(
500500
all the stages in any of the permitted flows.
501501
"""
502502

503-
sid = None # type: Optional[str]
503+
sid: Optional[str] = None
504504
authdict = clientdict.pop("auth", {})
505505
if "session" in authdict:
506506
sid = authdict["session"]
@@ -588,9 +588,9 @@ async def check_ui_auth(
588588
)
589589

590590
# check auth type currently being presented
591-
errordict = {} # type: Dict[str, Any]
591+
errordict: Dict[str, Any] = {}
592592
if "type" in authdict:
593-
login_type = authdict["type"] # type: str
593+
login_type: str = authdict["type"]
594594
try:
595595
result = await self._check_auth_dict(authdict, clientip)
596596
if result:
@@ -766,7 +766,7 @@ def _auth_dict_for_flows(
766766
LoginType.TERMS: self._get_params_terms,
767767
}
768768

769-
params = {} # type: Dict[str, Any]
769+
params: Dict[str, Any] = {}
770770

771771
for f in public_flows:
772772
for stage in f:
@@ -1530,9 +1530,9 @@ async def start_sso_ui_auth(self, request: SynapseRequest, session_id: str) -> s
15301530
except StoreError:
15311531
raise SynapseError(400, "Unknown session ID: %s" % (session_id,))
15321532

1533-
user_id_to_verify = await self.get_session_data(
1533+
user_id_to_verify: str = await self.get_session_data(
15341534
session_id, UIAuthSessionDataConstants.REQUEST_USER_ID
1535-
) # type: str
1535+
)
15361536

15371537
idps = await self.hs.get_sso_handler().get_identity_providers_for_user(
15381538
user_id_to_verify

synapse/handlers/cas.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ def _parse_cas_response(self, cas_response_body: bytes) -> CasResponse:
171171

172172
# Iterate through the nodes and pull out the user and any extra attributes.
173173
user = None
174-
attributes = {} # type: Dict[str, List[Optional[str]]]
174+
attributes: Dict[str, List[Optional[str]]] = {}
175175
for child in root[0]:
176176
if child.tag.endswith("user"):
177177
user = child.text

synapse/handlers/device.py

+7-7
Original file line numberDiff line numberDiff line change
@@ -452,7 +452,7 @@ async def notify_device_update(
452452
user_id
453453
)
454454

455-
hosts = set() # type: Set[str]
455+
hosts: Set[str] = set()
456456
if self.hs.is_mine_id(user_id):
457457
hosts.update(get_domain_from_id(u) for u in users_who_share_room)
458458
hosts.discard(self.server_name)
@@ -613,20 +613,20 @@ def __init__(self, hs: "HomeServer", device_handler: DeviceHandler):
613613
self._remote_edu_linearizer = Linearizer(name="remote_device_list")
614614

615615
# user_id -> list of updates waiting to be handled.
616-
self._pending_updates = (
617-
{}
618-
) # type: Dict[str, List[Tuple[str, str, Iterable[str], JsonDict]]]
616+
self._pending_updates: Dict[
617+
str, List[Tuple[str, str, Iterable[str], JsonDict]]
618+
] = {}
619619

620620
# Recently seen stream ids. We don't bother keeping these in the DB,
621621
# but they're useful to have them about to reduce the number of spurious
622622
# resyncs.
623-
self._seen_updates = ExpiringCache(
623+
self._seen_updates: ExpiringCache[str, Set[str]] = ExpiringCache(
624624
cache_name="device_update_edu",
625625
clock=self.clock,
626626
max_len=10000,
627627
expiry_ms=30 * 60 * 1000,
628628
iterable=True,
629-
) # type: ExpiringCache[str, Set[str]]
629+
)
630630

631631
# Attempt to resync out of sync device lists every 30s.
632632
self._resync_retry_in_progress = False
@@ -755,7 +755,7 @@ async def _need_to_do_resync(
755755
"""Given a list of updates for a user figure out if we need to do a full
756756
resync, or whether we have enough data that we can just apply the delta.
757757
"""
758-
seen_updates = self._seen_updates.get(user_id, set()) # type: Set[str]
758+
seen_updates: Set[str] = self._seen_updates.get(user_id, set())
759759

760760
extremity = await self.store.get_device_list_last_stream_id_for_remote(user_id)
761761

synapse/handlers/devicemessage.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -203,7 +203,7 @@ async def send_device_message(
203203
log_kv({"number_of_to_device_messages": len(messages)})
204204
set_tag("sender", sender_user_id)
205205
local_messages = {}
206-
remote_messages = {} # type: Dict[str, Dict[str, Dict[str, JsonDict]]]
206+
remote_messages: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
207207
for user_id, by_device in messages.items():
208208
# Ratelimit local cross-user key requests by the sending device.
209209
if (

synapse/handlers/directory.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -237,9 +237,9 @@ async def _delete_association(self, room_alias: RoomAlias) -> str:
237237
async def get_association(self, room_alias: RoomAlias) -> JsonDict:
238238
room_id = None
239239
if self.hs.is_mine(room_alias):
240-
result = await self.get_association_from_room_alias(
241-
room_alias
242-
) # type: Optional[RoomAliasMapping]
240+
result: Optional[
241+
RoomAliasMapping
242+
] = await self.get_association_from_room_alias(room_alias)
243243

244244
if result:
245245
room_id = result.room_id

synapse/handlers/e2e_keys.py

+19-21
Original file line numberDiff line numberDiff line change
@@ -115,9 +115,9 @@ async def query_devices(
115115
the number of in-flight queries at a time.
116116
"""
117117
with await self._query_devices_linearizer.queue((from_user_id, from_device_id)):
118-
device_keys_query = query_body.get(
118+
device_keys_query: Dict[str, Iterable[str]] = query_body.get(
119119
"device_keys", {}
120-
) # type: Dict[str, Iterable[str]]
120+
)
121121

122122
# separate users by domain.
123123
# make a map from domain to user_id to device_ids
@@ -136,7 +136,7 @@ async def query_devices(
136136

137137
# First get local devices.
138138
# A map of destination -> failure response.
139-
failures = {} # type: Dict[str, JsonDict]
139+
failures: Dict[str, JsonDict] = {}
140140
results = {}
141141
if local_query:
142142
local_result = await self.query_local_devices(local_query)
@@ -151,11 +151,9 @@ async def query_devices(
151151

152152
# Now attempt to get any remote devices from our local cache.
153153
# A map of destination -> user ID -> device IDs.
154-
remote_queries_not_in_cache = (
155-
{}
156-
) # type: Dict[str, Dict[str, Iterable[str]]]
154+
remote_queries_not_in_cache: Dict[str, Dict[str, Iterable[str]]] = {}
157155
if remote_queries:
158-
query_list = [] # type: List[Tuple[str, Optional[str]]]
156+
query_list: List[Tuple[str, Optional[str]]] = []
159157
for user_id, device_ids in remote_queries.items():
160158
if device_ids:
161159
query_list.extend(
@@ -362,9 +360,9 @@ async def query_local_devices(
362360
A map from user_id -> device_id -> device details
363361
"""
364362
set_tag("local_query", query)
365-
local_query = [] # type: List[Tuple[str, Optional[str]]]
363+
local_query: List[Tuple[str, Optional[str]]] = []
366364

367-
result_dict = {} # type: Dict[str, Dict[str, dict]]
365+
result_dict: Dict[str, Dict[str, dict]] = {}
368366
for user_id, device_ids in query.items():
369367
# we use UserID.from_string to catch invalid user ids
370368
if not self.is_mine(UserID.from_string(user_id)):
@@ -402,9 +400,9 @@ async def on_federation_query_client_keys(
402400
self, query_body: Dict[str, Dict[str, Optional[List[str]]]]
403401
) -> JsonDict:
404402
"""Handle a device key query from a federated server"""
405-
device_keys_query = query_body.get(
403+
device_keys_query: Dict[str, Optional[List[str]]] = query_body.get(
406404
"device_keys", {}
407-
) # type: Dict[str, Optional[List[str]]]
405+
)
408406
res = await self.query_local_devices(device_keys_query)
409407
ret = {"device_keys": res}
410408

@@ -421,8 +419,8 @@ async def on_federation_query_client_keys(
421419
async def claim_one_time_keys(
422420
self, query: Dict[str, Dict[str, Dict[str, str]]], timeout: int
423421
) -> JsonDict:
424-
local_query = [] # type: List[Tuple[str, str, str]]
425-
remote_queries = {} # type: Dict[str, Dict[str, Dict[str, str]]]
422+
local_query: List[Tuple[str, str, str]] = []
423+
remote_queries: Dict[str, Dict[str, Dict[str, str]]] = {}
426424

427425
for user_id, one_time_keys in query.get("one_time_keys", {}).items():
428426
# we use UserID.from_string to catch invalid user ids
@@ -439,8 +437,8 @@ async def claim_one_time_keys(
439437
results = await self.store.claim_e2e_one_time_keys(local_query)
440438

441439
# A map of user ID -> device ID -> key ID -> key.
442-
json_result = {} # type: Dict[str, Dict[str, Dict[str, JsonDict]]]
443-
failures = {} # type: Dict[str, JsonDict]
440+
json_result: Dict[str, Dict[str, Dict[str, JsonDict]]] = {}
441+
failures: Dict[str, JsonDict] = {}
444442
for user_id, device_keys in results.items():
445443
for device_id, keys in device_keys.items():
446444
for key_id, json_str in keys.items():
@@ -768,8 +766,8 @@ async def _process_self_signatures(
768766
Raises:
769767
SynapseError: if the input is malformed
770768
"""
771-
signature_list = [] # type: List[SignatureListItem]
772-
failures = {} # type: Dict[str, Dict[str, JsonDict]]
769+
signature_list: List["SignatureListItem"] = []
770+
failures: Dict[str, Dict[str, JsonDict]] = {}
773771
if not signatures:
774772
return signature_list, failures
775773

@@ -930,8 +928,8 @@ async def _process_other_signatures(
930928
Raises:
931929
SynapseError: if the input is malformed
932930
"""
933-
signature_list = [] # type: List[SignatureListItem]
934-
failures = {} # type: Dict[str, Dict[str, JsonDict]]
931+
signature_list: List["SignatureListItem"] = []
932+
failures: Dict[str, Dict[str, JsonDict]] = {}
935933
if not signatures:
936934
return signature_list, failures
937935

@@ -1300,7 +1298,7 @@ def __init__(self, hs: "HomeServer", e2e_keys_handler: E2eKeysHandler):
13001298
self._remote_edu_linearizer = Linearizer(name="remote_signing_key")
13011299

13021300
# user_id -> list of updates waiting to be handled.
1303-
self._pending_updates = {} # type: Dict[str, List[Tuple[JsonDict, JsonDict]]]
1301+
self._pending_updates: Dict[str, List[Tuple[JsonDict, JsonDict]]] = {}
13041302

13051303
async def incoming_signing_key_update(
13061304
self, origin: str, edu_content: JsonDict
@@ -1349,7 +1347,7 @@ async def _handle_signing_key_updates(self, user_id: str) -> None:
13491347
# This can happen since we batch updates
13501348
return
13511349

1352-
device_ids = [] # type: List[str]
1350+
device_ids: List[str] = []
13531351

13541352
logger.info("pending updates: %r", pending_updates)
13551353

synapse/handlers/events.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -93,7 +93,7 @@ async def get_stream(
9393

9494
# When the user joins a new room, or another user joins a currently
9595
# joined room, we need to send down presence for those users.
96-
to_add = [] # type: List[JsonDict]
96+
to_add: List[JsonDict] = []
9797
for event in events:
9898
if not isinstance(event, EventBase):
9999
continue
@@ -103,9 +103,9 @@ async def get_stream(
103103
# Send down presence.
104104
if event.state_key == auth_user_id:
105105
# Send down presence for everyone in the room.
106-
users = await self.store.get_users_in_room(
106+
users: Iterable[str] = await self.store.get_users_in_room(
107107
event.room_id
108-
) # type: Iterable[str]
108+
)
109109
else:
110110
users = [event.state_key]
111111

0 commit comments

Comments
 (0)