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

Commit a93f312

Browse files
authored
Add type hints to some handlers (#8505)
1 parent a97cec1 commit a93f312

File tree

10 files changed

+60
-22
lines changed

10 files changed

+60
-22
lines changed

changelog.d/8505.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type hints to various parts of the code base.

mypy.ini

+5
Original file line numberDiff line numberDiff line change
@@ -15,9 +15,12 @@ files =
1515
synapse/events/builder.py,
1616
synapse/events/spamcheck.py,
1717
synapse/federation,
18+
synapse/handlers/account_data.py,
1819
synapse/handlers/auth.py,
1920
synapse/handlers/cas_handler.py,
21+
synapse/handlers/deactivate_account.py,
2022
synapse/handlers/device.py,
23+
synapse/handlers/devicemessage.py,
2124
synapse/handlers/directory.py,
2225
synapse/handlers/events.py,
2326
synapse/handlers/federation.py,
@@ -26,7 +29,9 @@ files =
2629
synapse/handlers/message.py,
2730
synapse/handlers/oidc_handler.py,
2831
synapse/handlers/pagination.py,
32+
synapse/handlers/password_policy.py,
2933
synapse/handlers/presence.py,
34+
synapse/handlers/read_marker.py,
3035
synapse/handlers/room.py,
3136
synapse/handlers/room_member.py,
3237
synapse/handlers/room_member_worker.py,

synapse/federation/federation_server.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -861,7 +861,7 @@ def __init__(self, hs: "HomeServer"):
861861
self._edu_type_to_instance = {} # type: Dict[str, str]
862862

863863
def register_edu_handler(
864-
self, edu_type: str, handler: Callable[[str, dict], Awaitable[None]]
864+
self, edu_type: str, handler: Callable[[str, JsonDict], Awaitable[None]]
865865
):
866866
"""Sets the handler callable that will be used to handle an incoming
867867
federation EDU of the given type.

synapse/handlers/account_data.py

+11-3
Original file line numberDiff line numberDiff line change
@@ -12,16 +12,24 @@
1212
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
15+
from typing import TYPE_CHECKING, List, Tuple
16+
17+
from synapse.types import JsonDict, UserID
18+
19+
if TYPE_CHECKING:
20+
from synapse.app.homeserver import HomeServer
1521

1622

1723
class AccountDataEventSource:
18-
def __init__(self, hs):
24+
def __init__(self, hs: "HomeServer"):
1925
self.store = hs.get_datastore()
2026

21-
def get_current_key(self, direction="f"):
27+
def get_current_key(self, direction: str = "f") -> int:
2228
return self.store.get_max_account_data_stream_id()
2329

24-
async def get_new_events(self, user, from_key, **kwargs):
30+
async def get_new_events(
31+
self, user: UserID, from_key: int, **kwargs
32+
) -> Tuple[List[JsonDict], int]:
2533
user_id = user.to_string()
2634
last_stream_id = from_key
2735

synapse/handlers/deactivate_account.py

+6-3
Original file line numberDiff line numberDiff line change
@@ -14,21 +14,24 @@
1414
# See the License for the specific language governing permissions and
1515
# limitations under the License.
1616
import logging
17-
from typing import Optional
17+
from typing import TYPE_CHECKING, Optional
1818

1919
from synapse.api.errors import SynapseError
2020
from synapse.metrics.background_process_metrics import run_as_background_process
2121
from synapse.types import UserID, create_requester
2222

2323
from ._base import BaseHandler
2424

25+
if TYPE_CHECKING:
26+
from synapse.app.homeserver import HomeServer
27+
2528
logger = logging.getLogger(__name__)
2629

2730

2831
class DeactivateAccountHandler(BaseHandler):
2932
"""Handler which deals with deactivating user accounts."""
3033

31-
def __init__(self, hs):
34+
def __init__(self, hs: "HomeServer"):
3235
super().__init__(hs)
3336
self.hs = hs
3437
self._auth_handler = hs.get_auth_handler()
@@ -137,7 +140,7 @@ async def deactivate_account(
137140

138141
return identity_server_supports_unbinding
139142

140-
async def _reject_pending_invites_for_user(self, user_id: str):
143+
async def _reject_pending_invites_for_user(self, user_id: str) -> None:
141144
"""Reject pending invites addressed to a given user ID.
142145
143146
Args:

synapse/handlers/devicemessage.py

+17-8
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# limitations under the License.
1515

1616
import logging
17-
from typing import Any, Dict
17+
from typing import TYPE_CHECKING, Any, Dict
1818

1919
from synapse.api.errors import SynapseError
2020
from synapse.logging.context import run_in_background
@@ -24,18 +24,22 @@
2424
set_tag,
2525
start_active_span,
2626
)
27-
from synapse.types import UserID, get_domain_from_id
27+
from synapse.types import JsonDict, UserID, get_domain_from_id
2828
from synapse.util import json_encoder
2929
from synapse.util.stringutils import random_string
3030

31+
if TYPE_CHECKING:
32+
from synapse.app.homeserver import HomeServer
33+
34+
3135
logger = logging.getLogger(__name__)
3236

3337

3438
class DeviceMessageHandler:
35-
def __init__(self, hs):
39+
def __init__(self, hs: "HomeServer"):
3640
"""
3741
Args:
38-
hs (synapse.server.HomeServer): server
42+
hs: server
3943
"""
4044
self.store = hs.get_datastore()
4145
self.notifier = hs.get_notifier()
@@ -48,7 +52,7 @@ def __init__(self, hs):
4852

4953
self._device_list_updater = hs.get_device_handler().device_list_updater
5054

51-
async def on_direct_to_device_edu(self, origin, content):
55+
async def on_direct_to_device_edu(self, origin: str, content: JsonDict) -> None:
5256
local_messages = {}
5357
sender_user_id = content["sender"]
5458
if origin != get_domain_from_id(sender_user_id):
@@ -95,7 +99,7 @@ async def _check_for_unknown_devices(
9599
message_type: str,
96100
sender_user_id: str,
97101
by_device: Dict[str, Dict[str, Any]],
98-
):
102+
) -> None:
99103
"""Checks inbound device messages for unknown remote devices, and if
100104
found marks the remote cache for the user as stale.
101105
"""
@@ -138,11 +142,16 @@ async def _check_for_unknown_devices(
138142
self._device_list_updater.user_device_resync, sender_user_id
139143
)
140144

141-
async def send_device_message(self, sender_user_id, message_type, messages):
145+
async def send_device_message(
146+
self,
147+
sender_user_id: str,
148+
message_type: str,
149+
messages: Dict[str, Dict[str, JsonDict]],
150+
) -> None:
142151
set_tag("number_of_messages", len(messages))
143152
set_tag("sender", sender_user_id)
144153
local_messages = {}
145-
remote_messages = {}
154+
remote_messages = {} # type: Dict[str, Dict[str, Dict[str, JsonDict]]]
146155
for user_id, by_device in messages.items():
147156
# we use UserID.from_string to catch invalid user ids
148157
if self.is_mine(UserID.from_string(user_id)):

synapse/handlers/password_policy.py

+7-3
Original file line numberDiff line numberDiff line change
@@ -16,14 +16,18 @@
1616

1717
import logging
1818
import re
19+
from typing import TYPE_CHECKING
1920

2021
from synapse.api.errors import Codes, PasswordRefusedError
2122

23+
if TYPE_CHECKING:
24+
from synapse.app.homeserver import HomeServer
25+
2226
logger = logging.getLogger(__name__)
2327

2428

2529
class PasswordPolicyHandler:
26-
def __init__(self, hs):
30+
def __init__(self, hs: "HomeServer"):
2731
self.policy = hs.config.password_policy
2832
self.enabled = hs.config.password_policy_enabled
2933

@@ -33,11 +37,11 @@ def __init__(self, hs):
3337
self.regexp_uppercase = re.compile("[A-Z]")
3438
self.regexp_lowercase = re.compile("[a-z]")
3539

36-
def validate_password(self, password):
40+
def validate_password(self, password: str) -> None:
3741
"""Checks whether a given password complies with the server's policy.
3842
3943
Args:
40-
password (str): The password to check against the server's policy.
44+
password: The password to check against the server's policy.
4145
4246
Raises:
4347
PasswordRefusedError: The password doesn't comply with the server's policy.

synapse/handlers/read_marker.py

+8-2
Original file line numberDiff line numberDiff line change
@@ -14,23 +14,29 @@
1414
# limitations under the License.
1515

1616
import logging
17+
from typing import TYPE_CHECKING
1718

1819
from synapse.util.async_helpers import Linearizer
1920

2021
from ._base import BaseHandler
2122

23+
if TYPE_CHECKING:
24+
from synapse.app.homeserver import HomeServer
25+
2226
logger = logging.getLogger(__name__)
2327

2428

2529
class ReadMarkerHandler(BaseHandler):
26-
def __init__(self, hs):
30+
def __init__(self, hs: "HomeServer"):
2731
super().__init__(hs)
2832
self.server_name = hs.config.server_name
2933
self.store = hs.get_datastore()
3034
self.read_marker_linearizer = Linearizer(name="read_marker")
3135
self.notifier = hs.get_notifier()
3236

33-
async def received_client_read_marker(self, room_id, user_id, event_id):
37+
async def received_client_read_marker(
38+
self, room_id: str, user_id: str, event_id: str
39+
) -> None:
3440
"""Updates the read marker for a given user in a given room if the event ID given
3541
is ahead in the stream relative to the current read marker.
3642

synapse/notifier.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -339,7 +339,7 @@ def on_new_event(
339339
self,
340340
stream_key: str,
341341
new_token: Union[int, RoomStreamToken],
342-
users: Collection[UserID] = [],
342+
users: Collection[Union[str, UserID]] = [],
343343
rooms: Collection[str] = [],
344344
):
345345
""" Used to inform listeners that something has happened event wise.

synapse/storage/databases/main/registration.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1220,7 +1220,9 @@ async def record_user_external_id(
12201220
desc="record_user_external_id",
12211221
)
12221222

1223-
async def user_set_password_hash(self, user_id: str, password_hash: str) -> None:
1223+
async def user_set_password_hash(
1224+
self, user_id: str, password_hash: Optional[str]
1225+
) -> None:
12241226
"""
12251227
NB. This does *not* evict any cache because the one use for this
12261228
removes most of the entries subsequently anyway so it would be

0 commit comments

Comments
 (0)