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

Commit 4ff0201

Browse files
authored
Enable mypy checking for unreachable code and fix instances. (#8432)
1 parent c1ef579 commit 4ff0201

File tree

17 files changed

+38
-53
lines changed

17 files changed

+38
-53
lines changed

changelog.d/8432.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Check for unreachable code with mypy.

mypy.ini

+1
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ check_untyped_defs = True
66
show_error_codes = True
77
show_traceback = True
88
mypy_path = stubs
9+
warn_unreachable = True
910
files =
1011
synapse/api,
1112
synapse/appservice,

synapse/config/tls.py

+9-9
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@
1818
import warnings
1919
from datetime import datetime
2020
from hashlib import sha256
21-
from typing import List
21+
from typing import List, Optional
2222

2323
from unpaddedbase64 import encode_base64
2424

@@ -177,8 +177,8 @@ def read_config(self, config: dict, config_dir_path: str, **kwargs):
177177
"use_insecure_ssl_client_just_for_testing_do_not_use"
178178
)
179179

180-
self.tls_certificate = None
181-
self.tls_private_key = None
180+
self.tls_certificate = None # type: Optional[crypto.X509]
181+
self.tls_private_key = None # type: Optional[crypto.PKey]
182182

183183
def is_disk_cert_valid(self, allow_self_signed=True):
184184
"""
@@ -226,12 +226,12 @@ def is_disk_cert_valid(self, allow_self_signed=True):
226226
days_remaining = (expires_on - now).days
227227
return days_remaining
228228

229-
def read_certificate_from_disk(self, require_cert_and_key):
229+
def read_certificate_from_disk(self, require_cert_and_key: bool):
230230
"""
231231
Read the certificates and private key from disk.
232232
233233
Args:
234-
require_cert_and_key (bool): set to True to throw an error if the certificate
234+
require_cert_and_key: set to True to throw an error if the certificate
235235
and key file are not given
236236
"""
237237
if require_cert_and_key:
@@ -479,13 +479,13 @@ def generate_config_section(
479479
}
480480
)
481481

482-
def read_tls_certificate(self):
482+
def read_tls_certificate(self) -> crypto.X509:
483483
"""Reads the TLS certificate from the configured file, and returns it
484484
485485
Also checks if it is self-signed, and warns if so
486486
487487
Returns:
488-
OpenSSL.crypto.X509: the certificate
488+
The certificate
489489
"""
490490
cert_path = self.tls_certificate_file
491491
logger.info("Loading TLS certificate from %s", cert_path)
@@ -504,11 +504,11 @@ def read_tls_certificate(self):
504504

505505
return cert
506506

507-
def read_tls_private_key(self):
507+
def read_tls_private_key(self) -> crypto.PKey:
508508
"""Reads the TLS private key from the configured file, and returns it
509509
510510
Returns:
511-
OpenSSL.crypto.PKey: the private key
511+
The private key
512512
"""
513513
private_key_path = self.tls_private_key_file
514514
logger.info("Loading TLS key from %s", private_key_path)

synapse/federation/federation_server.py

+2-3
Original file line numberDiff line numberDiff line change
@@ -22,7 +22,6 @@
2222
Callable,
2323
Dict,
2424
List,
25-
Match,
2625
Optional,
2726
Tuple,
2827
Union,
@@ -825,14 +824,14 @@ def server_matches_acl_event(server_name: str, acl_event: EventBase) -> bool:
825824
return False
826825

827826

828-
def _acl_entry_matches(server_name: str, acl_entry: str) -> Match:
827+
def _acl_entry_matches(server_name: str, acl_entry: Any) -> bool:
829828
if not isinstance(acl_entry, str):
830829
logger.warning(
831830
"Ignoring non-str ACL entry '%s' (is %s)", acl_entry, type(acl_entry)
832831
)
833832
return False
834833
regex = glob_to_regex(acl_entry)
835-
return regex.match(server_name)
834+
return bool(regex.match(server_name))
836835

837836

838837
class FederationHandlerRegistry:

synapse/handlers/directory.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -383,7 +383,7 @@ async def _user_can_delete_alias(self, alias: RoomAlias, user_id: str):
383383
"""
384384
creator = await self.store.get_room_alias_creator(alias.to_string())
385385

386-
if creator is not None and creator == user_id:
386+
if creator == user_id:
387387
return True
388388

389389
# Resolve the alias to the corresponding room.

synapse/handlers/room.py

-2
Original file line numberDiff line numberDiff line change
@@ -962,8 +962,6 @@ async def _generate_room_id(
962962
try:
963963
random_string = stringutils.random_string(18)
964964
gen_room_id = RoomID(random_string, self.hs.hostname).to_string()
965-
if isinstance(gen_room_id, bytes):
966-
gen_room_id = gen_room_id.decode("utf-8")
967965
await self.store.store_room(
968966
room_id=gen_room_id,
969967
room_creator_user_id=creator_id,

synapse/handlers/room_member.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -642,7 +642,7 @@ async def copy_user_state_on_room_upgrade(
642642

643643
async def send_membership_event(
644644
self,
645-
requester: Requester,
645+
requester: Optional[Requester],
646646
event: EventBase,
647647
context: EventContext,
648648
ratelimit: bool = True,

synapse/handlers/sync.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -87,7 +87,7 @@ class SyncConfig:
8787
class TimelineBatch:
8888
prev_batch = attr.ib(type=StreamToken)
8989
events = attr.ib(type=List[EventBase])
90-
limited = attr.ib(bool)
90+
limited = attr.ib(type=bool)
9191

9292
def __bool__(self) -> bool:
9393
"""Make the result appear empty if there are no updates. This is used

synapse/http/server.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -257,7 +257,7 @@ async def _async_render(self, request: Request):
257257
if isinstance(raw_callback_return, (defer.Deferred, types.CoroutineType)):
258258
callback_return = await raw_callback_return
259259
else:
260-
callback_return = raw_callback_return
260+
callback_return = raw_callback_return # type: ignore
261261

262262
return callback_return
263263

@@ -406,7 +406,7 @@ async def _async_render(self, request):
406406
if isinstance(raw_callback_return, (defer.Deferred, types.CoroutineType)):
407407
callback_return = await raw_callback_return
408408
else:
409-
callback_return = raw_callback_return
409+
callback_return = raw_callback_return # type: ignore
410410

411411
return callback_return
412412

synapse/logging/_structured.py

+1-9
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,6 @@
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-
1615
import logging
1716
import os.path
1817
import sys
@@ -89,14 +88,7 @@ def __call__(self, event: dict) -> None:
8988
context = current_context()
9089

9190
# Copy the context information to the log event.
92-
if context is not None:
93-
context.copy_to_twisted_log_entry(event)
94-
else:
95-
# If there's no logging context, not even the root one, we might be
96-
# starting up or it might be from non-Synapse code. Log it as if it
97-
# came from the root logger.
98-
event["request"] = None
99-
event["scope"] = None
91+
context.copy_to_twisted_log_entry(event)
10092

10193
self.observer(event)
10294

synapse/push/push_rule_evaluator.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616

1717
import logging
1818
import re
19-
from typing import Any, Dict, List, Pattern, Union
19+
from typing import Any, Dict, List, Optional, Pattern, Union
2020

2121
from synapse.events import EventBase
2222
from synapse.types import UserID
@@ -181,7 +181,7 @@ def _contains_display_name(self, display_name: str) -> bool:
181181

182182
return r.search(body)
183183

184-
def _get_value(self, dotted_key: str) -> str:
184+
def _get_value(self, dotted_key: str) -> Optional[str]:
185185
return self._value_cache.get(dotted_key, None)
186186

187187

synapse/replication/tcp/protocol.py

+6-4
Original file line numberDiff line numberDiff line change
@@ -51,10 +51,11 @@
5151
import logging
5252
import struct
5353
from inspect import isawaitable
54-
from typing import TYPE_CHECKING, List
54+
from typing import TYPE_CHECKING, List, Optional
5555

5656
from prometheus_client import Counter
5757

58+
from twisted.internet import task
5859
from twisted.protocols.basic import LineOnlyReceiver
5960
from twisted.python.failure import Failure
6061

@@ -152,9 +153,10 @@ def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
152153

153154
self.last_received_command = self.clock.time_msec()
154155
self.last_sent_command = 0
155-
self.time_we_closed = None # When we requested the connection be closed
156+
# When we requested the connection be closed
157+
self.time_we_closed = None # type: Optional[int]
156158

157-
self.received_ping = False # Have we reecived a ping from the other side
159+
self.received_ping = False # Have we received a ping from the other side
158160

159161
self.state = ConnectionStates.CONNECTING
160162

@@ -165,7 +167,7 @@ def __init__(self, clock: Clock, handler: "ReplicationCommandHandler"):
165167
self.pending_commands = [] # type: List[Command]
166168

167169
# The LoopingCall for sending pings.
168-
self._send_ping_loop = None
170+
self._send_ping_loop = None # type: Optional[task.LoopingCall]
169171

170172
# a logcontext which we use for processing incoming commands. We declare it as a
171173
# background process so that the CPU stats get reported to prometheus.

synapse/state/__init__.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -738,7 +738,7 @@ def _make_state_cache_entry(
738738

739739
# failing that, look for the closest match.
740740
prev_group = None
741-
delta_ids = None
741+
delta_ids = None # type: Optional[StateMap[str]]
742742

743743
for old_group, old_state in state_groups_ids.items():
744744
n_delta_ids = {k: v for k, v in new_state.items() if old_state.get(k) != v}

synapse/storage/databases/main/censor_events.py

+3-3
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,8 @@
2121
from synapse.storage._base import SQLBaseStore
2222
from synapse.storage.database import DatabasePool
2323
from synapse.storage.databases.main.cache import CacheInvalidationWorkerStore
24-
from synapse.storage.databases.main.events import encode_json
2524
from synapse.storage.databases.main.events_worker import EventsWorkerStore
25+
from synapse.util.frozenutils import frozendict_json_encoder
2626

2727
if TYPE_CHECKING:
2828
from synapse.server import HomeServer
@@ -105,7 +105,7 @@ async def _censor_redactions(self):
105105
and original_event.internal_metadata.is_redacted()
106106
):
107107
# Redaction was allowed
108-
pruned_json = encode_json(
108+
pruned_json = frozendict_json_encoder.encode(
109109
prune_event_dict(
110110
original_event.room_version, original_event.get_dict()
111111
)
@@ -171,7 +171,7 @@ def delete_expired_event_txn(txn):
171171
return
172172

173173
# Prune the event's dict then convert it to JSON.
174-
pruned_json = encode_json(
174+
pruned_json = frozendict_json_encoder.encode(
175175
prune_event_dict(event.room_version, event.get_dict())
176176
)
177177

synapse/storage/databases/main/events.py

+5-13
Original file line numberDiff line numberDiff line change
@@ -52,16 +52,6 @@
5252
)
5353

5454

55-
def encode_json(json_object):
56-
"""
57-
Encode a Python object as JSON and return it in a Unicode string.
58-
"""
59-
out = frozendict_json_encoder.encode(json_object)
60-
if isinstance(out, bytes):
61-
out = out.decode("utf8")
62-
return out
63-
64-
6555
_EventCacheEntry = namedtuple("_EventCacheEntry", ("event", "redacted_event"))
6656

6757

@@ -743,7 +733,9 @@ def _update_outliers_txn(self, txn, events_and_contexts):
743733
logger.exception("")
744734
raise
745735

746-
metadata_json = encode_json(event.internal_metadata.get_dict())
736+
metadata_json = frozendict_json_encoder.encode(
737+
event.internal_metadata.get_dict()
738+
)
747739

748740
sql = "UPDATE event_json SET internal_metadata = ? WHERE event_id = ?"
749741
txn.execute(sql, (metadata_json, event.event_id))
@@ -797,10 +789,10 @@ def event_dict(event):
797789
{
798790
"event_id": event.event_id,
799791
"room_id": event.room_id,
800-
"internal_metadata": encode_json(
792+
"internal_metadata": frozendict_json_encoder.encode(
801793
event.internal_metadata.get_dict()
802794
),
803-
"json": encode_json(event_dict(event)),
795+
"json": frozendict_json_encoder.encode(event_dict(event)),
804796
"format_version": event.format_version,
805797
}
806798
for event, _ in events_and_contexts

synapse/storage/databases/main/stream.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -546,7 +546,7 @@ async def get_recent_event_ids_for_room(
546546

547547
async def get_room_event_before_stream_ordering(
548548
self, room_id: str, stream_ordering: int
549-
) -> Tuple[int, int, str]:
549+
) -> Optional[Tuple[int, int, str]]:
550550
"""Gets details of the first event in a room at or before a stream ordering
551551
552552
Args:

synapse/storage/util/id_generators.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -421,7 +421,7 @@ def _mark_id_as_finished(self, next_id: int):
421421
self._unfinished_ids.discard(next_id)
422422
self._finished_ids.add(next_id)
423423

424-
new_cur = None
424+
new_cur = None # type: Optional[int]
425425

426426
if self._unfinished_ids:
427427
# If there are unfinished IDs then the new position will be the

0 commit comments

Comments
 (0)