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

Commit d2279f4

Browse files
authored
Add most of the missing type hints to synapse.federation. (#11483)
This skips a few methods which are difficult to type.
1 parent b50e39d commit d2279f4

File tree

10 files changed

+84
-49
lines changed

10 files changed

+84
-49
lines changed

changelog.d/11483.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints to `synapse.federation`.

mypy.ini

+6
Original file line numberDiff line numberDiff line change
@@ -158,6 +158,12 @@ disallow_untyped_defs = True
158158
[mypy-synapse.events.*]
159159
disallow_untyped_defs = True
160160

161+
[mypy-synapse.federation.*]
162+
disallow_untyped_defs = True
163+
164+
[mypy-synapse.federation.transport.client]
165+
disallow_untyped_defs = False
166+
161167
[mypy-synapse.handlers.*]
162168
disallow_untyped_defs = True
163169

synapse/federation/federation_client.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ def __init__(self, hs: "HomeServer"):
128128
reset_expiry_on_get=False,
129129
)
130130

131-
def _clear_tried_cache(self):
131+
def _clear_tried_cache(self) -> None:
132132
"""Clear pdu_destination_tried cache"""
133133
now = self._clock.time_msec()
134134

@@ -800,7 +800,7 @@ async def send_join(
800800
no servers successfully handle the request.
801801
"""
802802

803-
async def send_request(destination) -> SendJoinResult:
803+
async def send_request(destination: str) -> SendJoinResult:
804804
response = await self._do_send_join(room_version, destination, pdu)
805805

806806
# If an event was returned (and expected to be returned):

synapse/federation/federation_server.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
# Copyright 2015, 2016 OpenMarket Ltd
22
# Copyright 2018 New Vector Ltd
3-
# Copyright 2019 Matrix.org Federation C.I.C
3+
# Copyright 2019-2021 Matrix.org Federation C.I.C
44
#
55
# Licensed under the Apache License, Version 2.0 (the "License");
66
# you may not use this file except in compliance with the License.
@@ -450,7 +450,7 @@ async def _handle_pdus_in_txn(
450450
# require callouts to other servers to fetch missing events), but
451451
# impose a limit to avoid going too crazy with ram/cpu.
452452

453-
async def process_pdus_for_room(room_id: str):
453+
async def process_pdus_for_room(room_id: str) -> None:
454454
with nested_logging_context(room_id):
455455
logger.debug("Processing PDUs for %s", room_id)
456456

@@ -547,7 +547,7 @@ async def on_room_state_request(
547547

548548
async def on_state_ids_request(
549549
self, origin: str, room_id: str, event_id: str
550-
) -> Tuple[int, Dict[str, Any]]:
550+
) -> Tuple[int, JsonDict]:
551551
if not event_id:
552552
raise NotImplementedError("Specify an event")
553553

@@ -567,7 +567,9 @@ async def on_state_ids_request(
567567

568568
return 200, resp
569569

570-
async def _on_state_ids_request_compute(self, room_id, event_id):
570+
async def _on_state_ids_request_compute(
571+
self, room_id: str, event_id: str
572+
) -> JsonDict:
571573
state_ids = await self.handler.get_state_ids_for_pdu(room_id, event_id)
572574
auth_chain_ids = await self.store.get_auth_chain_ids(room_id, state_ids)
573575
return {"pdu_ids": state_ids, "auth_chain_ids": auth_chain_ids}

synapse/federation/persistence.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2014-2016 OpenMarket Ltd
2+
# Copyright 2021 The Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -23,6 +24,7 @@
2324

2425
from synapse.federation.units import Transaction
2526
from synapse.logging.utils import log_function
27+
from synapse.storage.databases.main import DataStore
2628
from synapse.types import JsonDict
2729

2830
logger = logging.getLogger(__name__)
@@ -31,7 +33,7 @@
3133
class TransactionActions:
3234
"""Defines persistence actions that relate to handling Transactions."""
3335

34-
def __init__(self, datastore):
36+
def __init__(self, datastore: DataStore):
3537
self.store = datastore
3638

3739
@log_function

synapse/federation/send_queue.py

+13-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2014-2016 OpenMarket Ltd
2+
# Copyright 2021 The Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -350,7 +351,7 @@ class BaseFederationRow:
350351
TypeId = "" # Unique string that ids the type. Must be overridden in sub classes.
351352

352353
@staticmethod
353-
def from_data(data):
354+
def from_data(data: JsonDict) -> "BaseFederationRow":
354355
"""Parse the data from the federation stream into a row.
355356
356357
Args:
@@ -359,7 +360,7 @@ def from_data(data):
359360
"""
360361
raise NotImplementedError()
361362

362-
def to_data(self):
363+
def to_data(self) -> JsonDict:
363364
"""Serialize this row to be sent over the federation stream.
364365
365366
Returns:
@@ -368,7 +369,7 @@ def to_data(self):
368369
"""
369370
raise NotImplementedError()
370371

371-
def add_to_buffer(self, buff):
372+
def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
372373
"""Add this row to the appropriate field in the buffer ready for this
373374
to be sent over federation.
374375
@@ -391,15 +392,15 @@ class PresenceDestinationsRow(
391392
TypeId = "pd"
392393

393394
@staticmethod
394-
def from_data(data):
395+
def from_data(data: JsonDict) -> "PresenceDestinationsRow":
395396
return PresenceDestinationsRow(
396397
state=UserPresenceState.from_dict(data["state"]), destinations=data["dests"]
397398
)
398399

399-
def to_data(self):
400+
def to_data(self) -> JsonDict:
400401
return {"state": self.state.as_dict(), "dests": self.destinations}
401402

402-
def add_to_buffer(self, buff):
403+
def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
403404
buff.presence_destinations.append((self.state, self.destinations))
404405

405406

@@ -417,13 +418,13 @@ class KeyedEduRow(
417418
TypeId = "k"
418419

419420
@staticmethod
420-
def from_data(data):
421+
def from_data(data: JsonDict) -> "KeyedEduRow":
421422
return KeyedEduRow(key=tuple(data["key"]), edu=Edu(**data["edu"]))
422423

423-
def to_data(self):
424+
def to_data(self) -> JsonDict:
424425
return {"key": self.key, "edu": self.edu.get_internal_dict()}
425426

426-
def add_to_buffer(self, buff):
427+
def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
427428
buff.keyed_edus.setdefault(self.edu.destination, {})[self.key] = self.edu
428429

429430

@@ -433,13 +434,13 @@ class EduRow(BaseFederationRow, namedtuple("EduRow", ("edu",))): # Edu
433434
TypeId = "e"
434435

435436
@staticmethod
436-
def from_data(data):
437+
def from_data(data: JsonDict) -> "EduRow":
437438
return EduRow(Edu(**data))
438439

439-
def to_data(self):
440+
def to_data(self) -> JsonDict:
440441
return self.edu.get_internal_dict()
441442

442-
def add_to_buffer(self, buff):
443+
def add_to_buffer(self, buff: "ParsedFederationStreamData") -> None:
443444
buff.edus.setdefault(self.edu.destination, []).append(self.edu)
444445

445446

synapse/federation/sender/per_destination_queue.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
# Copyright 2014-2016 OpenMarket Ltd
22
# Copyright 2019 New Vector Ltd
3+
# Copyright 2021 The Matrix.org Foundation C.I.C.
34
#
45
# Licensed under the Apache License, Version 2.0 (the "License");
56
# you may not use this file except in compliance with the License.
@@ -14,7 +15,8 @@
1415
# limitations under the License.
1516
import datetime
1617
import logging
17-
from typing import TYPE_CHECKING, Dict, Hashable, Iterable, List, Optional, Tuple
18+
from types import TracebackType
19+
from typing import TYPE_CHECKING, Dict, Hashable, Iterable, List, Optional, Tuple, Type
1820

1921
import attr
2022
from prometheus_client import Counter
@@ -213,7 +215,7 @@ def send_keyed_edu(self, edu: Edu, key: Hashable) -> None:
213215
self._pending_edus_keyed[(edu.edu_type, key)] = edu
214216
self.attempt_new_transaction()
215217

216-
def send_edu(self, edu) -> None:
218+
def send_edu(self, edu: Edu) -> None:
217219
self._pending_edus.append(edu)
218220
self.attempt_new_transaction()
219221

@@ -701,7 +703,12 @@ async def __aenter__(self) -> Tuple[List[EventBase], List[Edu]]:
701703

702704
return self._pdus, pending_edus
703705

704-
async def __aexit__(self, exc_type, exc, tb):
706+
async def __aexit__(
707+
self,
708+
exc_type: Optional[Type[BaseException]],
709+
exc: Optional[BaseException],
710+
tb: Optional[TracebackType],
711+
) -> None:
705712
if exc_type is not None:
706713
# Failed to send transaction, so we bail out.
707714
return

synapse/federation/transport/client.py

+13-7
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
Callable,
2222
Collection,
2323
Dict,
24+
Generator,
2425
Iterable,
2526
List,
2627
Mapping,
@@ -235,11 +236,16 @@ async def send_transaction(
235236

236237
@log_function
237238
async def make_query(
238-
self, destination, query_type, args, retry_on_dns_fail, ignore_backoff=False
239-
):
239+
self,
240+
destination: str,
241+
query_type: str,
242+
args: dict,
243+
retry_on_dns_fail: bool,
244+
ignore_backoff: bool = False,
245+
) -> JsonDict:
240246
path = _create_v1_path("/query/%s", query_type)
241247

242-
content = await self.client.get_json(
248+
return await self.client.get_json(
243249
destination=destination,
244250
path=path,
245251
args=args,
@@ -248,8 +254,6 @@ async def make_query(
248254
ignore_backoff=ignore_backoff,
249255
)
250256

251-
return content
252-
253257
@log_function
254258
async def make_membership_event(
255259
self,
@@ -1317,7 +1321,7 @@ class SendJoinResponse:
13171321

13181322

13191323
@ijson.coroutine
1320-
def _event_parser(event_dict: JsonDict):
1324+
def _event_parser(event_dict: JsonDict) -> Generator[None, Tuple[str, Any], None]:
13211325
"""Helper function for use with `ijson.kvitems_coro` to parse key-value pairs
13221326
to add them to a given dictionary.
13231327
"""
@@ -1328,7 +1332,9 @@ def _event_parser(event_dict: JsonDict):
13281332

13291333

13301334
@ijson.coroutine
1331-
def _event_list_parser(room_version: RoomVersion, events: List[EventBase]):
1335+
def _event_list_parser(
1336+
room_version: RoomVersion, events: List[EventBase]
1337+
) -> Generator[None, JsonDict, None]:
13321338
"""Helper function for use with `ijson.items_coro` to parse an array of
13331339
events and add them to the given list.
13341340
"""

synapse/federation/transport/server/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -302,7 +302,7 @@ def register_servlets(
302302
authenticator: Authenticator,
303303
ratelimiter: FederationRateLimiter,
304304
servlet_groups: Optional[Iterable[str]] = None,
305-
):
305+
) -> None:
306306
"""Initialize and register servlet classes.
307307
308308
Will by default register all servlets. For custom behaviour, pass in

0 commit comments

Comments
 (0)