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

Commit a121507

Browse files
authored
Adds misc missing type hints (#11953)
1 parent c3db7a0 commit a121507

File tree

9 files changed

+48
-41
lines changed

9 files changed

+48
-41
lines changed

changelog.d/11953.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints.

mypy.ini

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,9 @@ disallow_untyped_defs = True
142142
[mypy-synapse.crypto.*]
143143
disallow_untyped_defs = True
144144

145+
[mypy-synapse.event_auth]
146+
disallow_untyped_defs = True
147+
145148
[mypy-synapse.events.*]
146149
disallow_untyped_defs = True
147150

@@ -166,6 +169,9 @@ disallow_untyped_defs = True
166169
[mypy-synapse.module_api.*]
167170
disallow_untyped_defs = True
168171

172+
[mypy-synapse.notifier]
173+
disallow_untyped_defs = True
174+
169175
[mypy-synapse.push.*]
170176
disallow_untyped_defs = True
171177

synapse/event_auth.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -763,7 +763,9 @@ def get_named_level(auth_events: StateMap[EventBase], name: str, default: int) -
763763
return default
764764

765765

766-
def _verify_third_party_invite(event: EventBase, auth_events: StateMap[EventBase]):
766+
def _verify_third_party_invite(
767+
event: EventBase, auth_events: StateMap[EventBase]
768+
) -> bool:
767769
"""
768770
Validates that the invite event is authorized by a previous third-party invite.
769771

synapse/handlers/oidc.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -544,9 +544,9 @@ async def _exchange_code(self, code: str) -> Token:
544544
"""
545545
metadata = await self.load_metadata()
546546
token_endpoint = metadata.get("token_endpoint")
547-
raw_headers = {
547+
raw_headers: Dict[str, str] = {
548548
"Content-Type": "application/x-www-form-urlencoded",
549-
"User-Agent": self._http_client.user_agent,
549+
"User-Agent": self._http_client.user_agent.decode("ascii"),
550550
"Accept": "application/json",
551551
}
552552

synapse/http/client.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -322,21 +322,20 @@ def __init__(
322322
self._ip_whitelist = ip_whitelist
323323
self._ip_blacklist = ip_blacklist
324324
self._extra_treq_args = treq_args or {}
325-
326-
self.user_agent = hs.version_string
327325
self.clock = hs.get_clock()
326+
327+
user_agent = hs.version_string
328328
if hs.config.server.user_agent_suffix:
329-
self.user_agent = "%s %s" % (
330-
self.user_agent,
329+
user_agent = "%s %s" % (
330+
user_agent,
331331
hs.config.server.user_agent_suffix,
332332
)
333+
self.user_agent = user_agent.encode("ascii")
333334

334335
# We use this for our body producers to ensure that they use the correct
335336
# reactor.
336337
self._cooperator = Cooperator(scheduler=_make_scheduler(hs.get_reactor()))
337338

338-
self.user_agent = self.user_agent.encode("ascii")
339-
340339
if self._ip_blacklist:
341340
# If we have an IP blacklist, we need to use a DNS resolver which
342341
# filters out blacklisted IP addresses, to prevent DNS rebinding.

synapse/http/matrixfederationclient.py

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -334,12 +334,11 @@ def __init__(self, hs: "HomeServer", tls_client_options_factory):
334334
user_agent = hs.version_string
335335
if hs.config.server.user_agent_suffix:
336336
user_agent = "%s %s" % (user_agent, hs.config.server.user_agent_suffix)
337-
user_agent = user_agent.encode("ascii")
338337

339338
federation_agent = MatrixFederationAgent(
340339
self.reactor,
341340
tls_client_options_factory,
342-
user_agent,
341+
user_agent.encode("ascii"),
343342
hs.config.server.federation_ip_range_whitelist,
344343
hs.config.server.federation_ip_range_blacklist,
345344
)

synapse/notifier.py

Lines changed: 24 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515
import logging
1616
from typing import (
17+
TYPE_CHECKING,
1718
Awaitable,
1819
Callable,
1920
Collection,
@@ -32,7 +33,6 @@
3233

3334
from twisted.internet import defer
3435

35-
import synapse.server
3636
from synapse.api.constants import EventTypes, HistoryVisibility, Membership
3737
from synapse.api.errors import AuthError
3838
from synapse.events import EventBase
@@ -53,6 +53,9 @@
5353
from synapse.util.metrics import Measure
5454
from synapse.visibility import filter_events_for_client
5555

56+
if TYPE_CHECKING:
57+
from synapse.server import HomeServer
58+
5659
logger = logging.getLogger(__name__)
5760

5861
notified_events_counter = Counter("synapse_notifier_notified_events", "")
@@ -82,7 +85,7 @@ class _NotificationListener:
8285

8386
__slots__ = ["deferred"]
8487

85-
def __init__(self, deferred):
88+
def __init__(self, deferred: "defer.Deferred"):
8689
self.deferred = deferred
8790

8891

@@ -124,7 +127,7 @@ def notify(
124127
stream_key: str,
125128
stream_id: Union[int, RoomStreamToken],
126129
time_now_ms: int,
127-
):
130+
) -> None:
128131
"""Notify any listeners for this user of a new event from an
129132
event source.
130133
Args:
@@ -152,7 +155,7 @@ def notify(
152155
self.notify_deferred = ObservableDeferred(defer.Deferred())
153156
noify_deferred.callback(self.current_token)
154157

155-
def remove(self, notifier: "Notifier"):
158+
def remove(self, notifier: "Notifier") -> None:
156159
"""Remove this listener from all the indexes in the Notifier
157160
it knows about.
158161
"""
@@ -188,7 +191,7 @@ class EventStreamResult:
188191
start_token: StreamToken
189192
end_token: StreamToken
190193

191-
def __bool__(self):
194+
def __bool__(self) -> bool:
192195
return bool(self.events)
193196

194197

@@ -212,7 +215,7 @@ class Notifier:
212215

213216
UNUSED_STREAM_EXPIRY_MS = 10 * 60 * 1000
214217

215-
def __init__(self, hs: "synapse.server.HomeServer"):
218+
def __init__(self, hs: "HomeServer"):
216219
self.user_to_user_stream: Dict[str, _NotifierUserStream] = {}
217220
self.room_to_user_streams: Dict[str, Set[_NotifierUserStream]] = {}
218221

@@ -248,7 +251,7 @@ def __init__(self, hs: "synapse.server.HomeServer"):
248251
# This is not a very cheap test to perform, but it's only executed
249252
# when rendering the metrics page, which is likely once per minute at
250253
# most when scraping it.
251-
def count_listeners():
254+
def count_listeners() -> int:
252255
all_user_streams: Set[_NotifierUserStream] = set()
253256

254257
for streams in list(self.room_to_user_streams.values()):
@@ -270,7 +273,7 @@ def count_listeners():
270273
"synapse_notifier_users", "", [], lambda: len(self.user_to_user_stream)
271274
)
272275

273-
def add_replication_callback(self, cb: Callable[[], None]):
276+
def add_replication_callback(self, cb: Callable[[], None]) -> None:
274277
"""Add a callback that will be called when some new data is available.
275278
Callback is not given any arguments. It should *not* return a Deferred - if
276279
it needs to do any asynchronous work, a background thread should be started and
@@ -284,7 +287,7 @@ async def on_new_room_event(
284287
event_pos: PersistedEventPosition,
285288
max_room_stream_token: RoomStreamToken,
286289
extra_users: Optional[Collection[UserID]] = None,
287-
):
290+
) -> None:
288291
"""Unwraps event and calls `on_new_room_event_args`."""
289292
await self.on_new_room_event_args(
290293
event_pos=event_pos,
@@ -307,7 +310,7 @@ async def on_new_room_event_args(
307310
event_pos: PersistedEventPosition,
308311
max_room_stream_token: RoomStreamToken,
309312
extra_users: Optional[Collection[UserID]] = None,
310-
):
313+
) -> None:
311314
"""Used by handlers to inform the notifier something has happened
312315
in the room, room event wise.
313316
@@ -338,7 +341,9 @@ async def on_new_room_event_args(
338341

339342
self.notify_replication()
340343

341-
def _notify_pending_new_room_events(self, max_room_stream_token: RoomStreamToken):
344+
def _notify_pending_new_room_events(
345+
self, max_room_stream_token: RoomStreamToken
346+
) -> None:
342347
"""Notify for the room events that were queued waiting for a previous
343348
event to be persisted.
344349
Args:
@@ -374,7 +379,7 @@ def _notify_pending_new_room_events(self, max_room_stream_token: RoomStreamToken
374379
)
375380
self._on_updated_room_token(max_room_stream_token)
376381

377-
def _on_updated_room_token(self, max_room_stream_token: RoomStreamToken):
382+
def _on_updated_room_token(self, max_room_stream_token: RoomStreamToken) -> None:
378383
"""Poke services that might care that the room position has been
379384
updated.
380385
"""
@@ -386,13 +391,13 @@ def _on_updated_room_token(self, max_room_stream_token: RoomStreamToken):
386391
if self.federation_sender:
387392
self.federation_sender.notify_new_events(max_room_stream_token)
388393

389-
def _notify_app_services(self, max_room_stream_token: RoomStreamToken):
394+
def _notify_app_services(self, max_room_stream_token: RoomStreamToken) -> None:
390395
try:
391396
self.appservice_handler.notify_interested_services(max_room_stream_token)
392397
except Exception:
393398
logger.exception("Error notifying application services of event")
394399

395-
def _notify_pusher_pool(self, max_room_stream_token: RoomStreamToken):
400+
def _notify_pusher_pool(self, max_room_stream_token: RoomStreamToken) -> None:
396401
try:
397402
self._pusher_pool.on_new_notifications(max_room_stream_token)
398403
except Exception:
@@ -475,8 +480,8 @@ async def wait_for_events(
475480
user_id: str,
476481
timeout: int,
477482
callback: Callable[[StreamToken, StreamToken], Awaitable[T]],
478-
room_ids=None,
479-
from_token=StreamToken.START,
483+
room_ids: Optional[Collection[str]] = None,
484+
from_token: StreamToken = StreamToken.START,
480485
) -> T:
481486
"""Wait until the callback returns a non empty response or the
482487
timeout fires.
@@ -700,14 +705,14 @@ def remove_expired_streams(self) -> None:
700705
for expired_stream in expired_streams:
701706
expired_stream.remove(self)
702707

703-
def _register_with_keys(self, user_stream: _NotifierUserStream):
708+
def _register_with_keys(self, user_stream: _NotifierUserStream) -> None:
704709
self.user_to_user_stream[user_stream.user_id] = user_stream
705710

706711
for room in user_stream.rooms:
707712
s = self.room_to_user_streams.setdefault(room, set())
708713
s.add(user_stream)
709714

710-
def _user_joined_room(self, user_id: str, room_id: str):
715+
def _user_joined_room(self, user_id: str, room_id: str) -> None:
711716
new_user_stream = self.user_to_user_stream.get(user_id)
712717
if new_user_stream is not None:
713718
room_streams = self.room_to_user_streams.setdefault(room_id, set())
@@ -719,7 +724,7 @@ def notify_replication(self) -> None:
719724
for cb in self.replication_callbacks:
720725
cb()
721726

722-
def notify_remote_server_up(self, server: str):
727+
def notify_remote_server_up(self, server: str) -> None:
723728
"""Notify any replication that a remote server has come back up"""
724729
# We call federation_sender directly rather than registering as a
725730
# callback as a) we already have a reference to it and b) it introduces

synapse/server.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -233,8 +233,8 @@ def __init__(
233233
self,
234234
hostname: str,
235235
config: HomeServerConfig,
236-
reactor=None,
237-
version_string="Synapse",
236+
reactor: Optional[ISynapseReactor] = None,
237+
version_string: str = "Synapse",
238238
):
239239
"""
240240
Args:
@@ -244,7 +244,7 @@ def __init__(
244244
if not reactor:
245245
from twisted.internet import reactor as _reactor
246246

247-
reactor = _reactor
247+
reactor = cast(ISynapseReactor, _reactor)
248248

249249
self._reactor = reactor
250250
self.hostname = hostname
@@ -264,7 +264,7 @@ def __init__(
264264
self._module_web_resources: Dict[str, Resource] = {}
265265
self._module_web_resources_consumed = False
266266

267-
def register_module_web_resource(self, path: str, resource: Resource):
267+
def register_module_web_resource(self, path: str, resource: Resource) -> None:
268268
"""Allows a module to register a web resource to be served at the given path.
269269
270270
If multiple modules register a resource for the same path, the module that

tests/handlers/test_oidc.py

Lines changed: 2 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -155,7 +155,7 @@ def default_config(self):
155155
def make_homeserver(self, reactor, clock):
156156
self.http_client = Mock(spec=["get_json"])
157157
self.http_client.get_json.side_effect = get_json
158-
self.http_client.user_agent = "Synapse Test"
158+
self.http_client.user_agent = b"Synapse Test"
159159

160160
hs = self.setup_test_homeserver(proxied_http_client=self.http_client)
161161

@@ -438,12 +438,9 @@ def test_callback(self):
438438
state = "state"
439439
nonce = "nonce"
440440
client_redirect_url = "http://client/redirect"
441-
user_agent = "Browser"
442441
ip_address = "10.0.0.1"
443442
session = self._generate_oidc_session_token(state, nonce, client_redirect_url)
444-
request = _build_callback_request(
445-
code, state, session, user_agent=user_agent, ip_address=ip_address
446-
)
443+
request = _build_callback_request(code, state, session, ip_address=ip_address)
447444

448445
self.get_success(self.handler.handle_oidc_callback(request))
449446

@@ -1274,7 +1271,6 @@ def _build_callback_request(
12741271
code: str,
12751272
state: str,
12761273
session: str,
1277-
user_agent: str = "Browser",
12781274
ip_address: str = "10.0.0.1",
12791275
):
12801276
"""Builds a fake SynapseRequest to mock the browser callback
@@ -1289,7 +1285,6 @@ def _build_callback_request(
12891285
query param. Should be the same as was embedded in the session in
12901286
_build_oidc_session.
12911287
session: the "session" which would have been passed around in the cookie.
1292-
user_agent: the user-agent to present
12931288
ip_address: the IP address to pretend the request came from
12941289
"""
12951290
request = Mock(

0 commit comments

Comments
 (0)