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

Commit 524b8ea

Browse files
authored
Add types to synapse.util. (#10601)
1 parent ceab5a4 commit 524b8ea

Some content is hidden

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

41 files changed

+401
-254
lines changed

changelog.d/10601.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type annotations to the synapse.util package.

mypy.ini

Lines changed: 64 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -74,17 +74,7 @@ files =
7474
synapse/storage/util,
7575
synapse/streams,
7676
synapse/types.py,
77-
synapse/util/async_helpers.py,
78-
synapse/util/caches,
79-
synapse/util/daemonize.py,
80-
synapse/util/hash.py,
81-
synapse/util/iterutils.py,
82-
synapse/util/linked_list.py,
83-
synapse/util/metrics.py,
84-
synapse/util/macaroons.py,
85-
synapse/util/module_loader.py,
86-
synapse/util/msisdn.py,
87-
synapse/util/stringutils.py,
77+
synapse/util,
8878
synapse/visibility.py,
8979
tests/replication,
9080
tests/test_event_auth.py,
@@ -102,6 +92,69 @@ files =
10292
[mypy-synapse.rest.client.*]
10393
disallow_untyped_defs = True
10494

95+
[mypy-synapse.util.batching_queue]
96+
disallow_untyped_defs = True
97+
98+
[mypy-synapse.util.caches.dictionary_cache]
99+
disallow_untyped_defs = True
100+
101+
[mypy-synapse.util.file_consumer]
102+
disallow_untyped_defs = True
103+
104+
[mypy-synapse.util.frozenutils]
105+
disallow_untyped_defs = True
106+
107+
[mypy-synapse.util.hash]
108+
disallow_untyped_defs = True
109+
110+
[mypy-synapse.util.httpresourcetree]
111+
disallow_untyped_defs = True
112+
113+
[mypy-synapse.util.iterutils]
114+
disallow_untyped_defs = True
115+
116+
[mypy-synapse.util.linked_list]
117+
disallow_untyped_defs = True
118+
119+
[mypy-synapse.util.logcontext]
120+
disallow_untyped_defs = True
121+
122+
[mypy-synapse.util.logformatter]
123+
disallow_untyped_defs = True
124+
125+
[mypy-synapse.util.macaroons]
126+
disallow_untyped_defs = True
127+
128+
[mypy-synapse.util.manhole]
129+
disallow_untyped_defs = True
130+
131+
[mypy-synapse.util.module_loader]
132+
disallow_untyped_defs = True
133+
134+
[mypy-synapse.util.msisdn]
135+
disallow_untyped_defs = True
136+
137+
[mypy-synapse.util.ratelimitutils]
138+
disallow_untyped_defs = True
139+
140+
[mypy-synapse.util.retryutils]
141+
disallow_untyped_defs = True
142+
143+
[mypy-synapse.util.rlimit]
144+
disallow_untyped_defs = True
145+
146+
[mypy-synapse.util.stringutils]
147+
disallow_untyped_defs = True
148+
149+
[mypy-synapse.util.templates]
150+
disallow_untyped_defs = True
151+
152+
[mypy-synapse.util.threepids]
153+
disallow_untyped_defs = True
154+
155+
[mypy-synapse.util.wheel_timer]
156+
disallow_untyped_defs = True
157+
105158
[mypy-pymacaroons.*]
106159
ignore_missing_imports = True
107160

stubs/txredisapi.pyi

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,4 +73,4 @@ class RedisFactory(protocol.ReconnectingClientFactory):
7373
def buildProtocol(self, addr) -> RedisProtocol: ...
7474

7575
class SubscriberFactory(RedisFactory):
76-
def __init__(self): ...
76+
def __init__(self) -> None: ...

synapse/api/ratelimiting.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,7 +46,7 @@ def __init__(
4646
# * How many times an action has occurred since a point in time
4747
# * The point in time
4848
# * The rate_hz of this particular entry. This can vary per request
49-
self.actions: OrderedDict[Hashable, Tuple[float, int, float]] = OrderedDict()
49+
self.actions: OrderedDict[Hashable, Tuple[float, float, float]] = OrderedDict()
5050

5151
async def can_do_action(
5252
self,
@@ -56,7 +56,7 @@ async def can_do_action(
5656
burst_count: Optional[int] = None,
5757
update: bool = True,
5858
n_actions: int = 1,
59-
_time_now_s: Optional[int] = None,
59+
_time_now_s: Optional[float] = None,
6060
) -> Tuple[bool, float]:
6161
"""Can the entity (e.g. user or IP address) perform the action?
6262
@@ -160,7 +160,7 @@ async def can_do_action(
160160

161161
return allowed, time_allowed
162162

163-
def _prune_message_counts(self, time_now_s: int):
163+
def _prune_message_counts(self, time_now_s: float):
164164
"""Remove message count entries that have not exceeded their defined
165165
rate_hz limit
166166
@@ -188,7 +188,7 @@ async def ratelimit(
188188
burst_count: Optional[int] = None,
189189
update: bool = True,
190190
n_actions: int = 1,
191-
_time_now_s: Optional[int] = None,
191+
_time_now_s: Optional[float] = None,
192192
):
193193
"""Checks if an action can be performed. If not, raises a LimitExceededError
194194

synapse/config/ratelimiting.py

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,8 @@
1414

1515
from typing import Dict, Optional
1616

17+
import attr
18+
1719
from ._base import Config
1820

1921

@@ -29,18 +31,13 @@ def __init__(
2931
self.burst_count = int(config.get("burst_count", defaults["burst_count"]))
3032

3133

34+
@attr.s(auto_attribs=True)
3235
class FederationRateLimitConfig:
33-
_items_and_default = {
34-
"window_size": 1000,
35-
"sleep_limit": 10,
36-
"sleep_delay": 500,
37-
"reject_limit": 50,
38-
"concurrent": 3,
39-
}
40-
41-
def __init__(self, **kwargs):
42-
for i in self._items_and_default.keys():
43-
setattr(self, i, kwargs.get(i) or self._items_and_default[i])
36+
window_size: int = 1000
37+
sleep_limit: int = 10
38+
sleep_delay: int = 500
39+
reject_limit: int = 50
40+
concurrent: int = 3
4441

4542

4643
class RatelimitConfig(Config):
@@ -69,11 +66,15 @@ def read_config(self, config, **kwargs):
6966
else:
7067
self.rc_federation = FederationRateLimitConfig(
7168
**{
72-
"window_size": config.get("federation_rc_window_size"),
73-
"sleep_limit": config.get("federation_rc_sleep_limit"),
74-
"sleep_delay": config.get("federation_rc_sleep_delay"),
75-
"reject_limit": config.get("federation_rc_reject_limit"),
76-
"concurrent": config.get("federation_rc_concurrent"),
69+
k: v
70+
for k, v in {
71+
"window_size": config.get("federation_rc_window_size"),
72+
"sleep_limit": config.get("federation_rc_sleep_limit"),
73+
"sleep_delay": config.get("federation_rc_sleep_delay"),
74+
"reject_limit": config.get("federation_rc_reject_limit"),
75+
"concurrent": config.get("federation_rc_concurrent"),
76+
}.items()
77+
if v is not None
7778
}
7879
)
7980

synapse/federation/sender/__init__.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from typing_extensions import Literal
2323

2424
from twisted.internet import defer
25+
from twisted.internet.interfaces import IDelayedCall
2526

2627
import synapse.metrics
2728
from synapse.api.presence import UserPresenceState
@@ -284,7 +285,9 @@ def __init__(self, hs: "HomeServer"):
284285
)
285286

286287
# wake up destinations that have outstanding PDUs to be caught up
287-
self._catchup_after_startup_timer = self.clock.call_later(
288+
self._catchup_after_startup_timer: Optional[
289+
IDelayedCall
290+
] = self.clock.call_later(
288291
CATCH_UP_STARTUP_DELAY_SEC,
289292
run_as_background_process,
290293
"wake_destinations_needing_catchup",
@@ -406,7 +409,7 @@ async def handle_event(event: EventBase) -> None:
406409

407410
now = self.clock.time_msec()
408411
ts = await self.store.get_received_ts(event.event_id)
409-
412+
assert ts is not None
410413
synapse.metrics.event_processing_lag_by_event.labels(
411414
"federation_sender"
412415
).observe((now - ts) / 1000)
@@ -435,6 +438,7 @@ async def handle_room_events(events: Iterable[EventBase]) -> None:
435438
if events:
436439
now = self.clock.time_msec()
437440
ts = await self.store.get_received_ts(events[-1].event_id)
441+
assert ts is not None
438442

439443
synapse.metrics.event_processing_lag.labels(
440444
"federation_sender"

synapse/handlers/account_validity.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -398,6 +398,7 @@ async def renew_account_for_user(
398398
"""
399399
now = self.clock.time_msec()
400400
if expiration_ts is None:
401+
assert self._account_validity_period is not None
401402
expiration_ts = now + self._account_validity_period
402403

403404
await self.store.set_account_validity_for_user(

synapse/handlers/appservice.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -131,6 +131,8 @@ async def start_scheduler():
131131

132132
now = self.clock.time_msec()
133133
ts = await self.store.get_received_ts(event.event_id)
134+
assert ts is not None
135+
134136
synapse.metrics.event_processing_lag_by_event.labels(
135137
"appservice_sender"
136138
).observe((now - ts) / 1000)
@@ -166,6 +168,7 @@ async def handle_room_events(events):
166168
if events:
167169
now = self.clock.time_msec()
168170
ts = await self.store.get_received_ts(events[-1].event_id)
171+
assert ts is not None
169172

170173
synapse.metrics.event_processing_lag.labels(
171174
"appservice_sender"

synapse/handlers/presence.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
from contextlib import contextmanager
2929
from typing import (
3030
TYPE_CHECKING,
31+
Any,
3132
Callable,
3233
Collection,
3334
Dict,
@@ -615,7 +616,7 @@ def __init__(self, hs: "HomeServer"):
615616
super().__init__(hs)
616617
self.hs = hs
617618
self.server_name = hs.hostname
618-
self.wheel_timer = WheelTimer()
619+
self.wheel_timer: WheelTimer[str] = WheelTimer()
619620
self.notifier = hs.get_notifier()
620621
self._presence_enabled = hs.config.use_presence
621622

@@ -924,7 +925,7 @@ async def bump_presence_active_time(self, user: UserID) -> None:
924925

925926
prev_state = await self.current_state_for_user(user_id)
926927

927-
new_fields = {"last_active_ts": self.clock.time_msec()}
928+
new_fields: Dict[str, Any] = {"last_active_ts": self.clock.time_msec()}
928929
if prev_state.state == PresenceState.UNAVAILABLE:
929930
new_fields["state"] = PresenceState.ONLINE
930931

synapse/handlers/typing.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def __init__(self, hs: "HomeServer"):
7373
self._room_typing: Dict[str, Set[str]] = {}
7474

7575
self._member_last_federation_poke: Dict[RoomMember, int] = {}
76-
self.wheel_timer = WheelTimer(bucket_size=5000)
76+
self.wheel_timer: WheelTimer[RoomMember] = WheelTimer(bucket_size=5000)
7777
self._latest_room_serial = 0
7878

7979
self.clock.looping_call(self._handle_timeouts, 5000)

0 commit comments

Comments
 (0)