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

Commit 0cd182f

Browse files
author
David Robertson
authored
Make synapse._scripts pass typechecks (#12421)
1 parent dd5cc37 commit 0cd182f

File tree

6 files changed

+50
-43
lines changed

6 files changed

+50
-43
lines changed

changelog.d/12421.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Make `synapse._scripts` pass type checks.

mypy.ini

Lines changed: 0 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -28,11 +28,6 @@ exclude = (?x)
2828
|scripts-dev/federation_client.py
2929
|scripts-dev/release.py
3030

31-
|synapse/_scripts/export_signing_key.py
32-
|synapse/_scripts/move_remote_media_to_new_store.py
33-
|synapse/_scripts/synapse_port_db.py
34-
|synapse/_scripts/update_synapse_database.py
35-
3631
|synapse/storage/databases/__init__.py
3732
|synapse/storage/databases/main/cache.py
3833
|synapse/storage/databases/main/devices.py

synapse/_scripts/export_signing_key.py

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,8 +17,8 @@
1717
import time
1818
from typing import Optional
1919

20-
import nacl.signing
2120
from signedjson.key import encode_verify_key_base64, get_verify_key, read_signing_keys
21+
from signedjson.types import VerifyKey
2222

2323

2424
def exit(status: int = 0, message: Optional[str] = None):
@@ -27,7 +27,7 @@ def exit(status: int = 0, message: Optional[str] = None):
2727
sys.exit(status)
2828

2929

30-
def format_plain(public_key: nacl.signing.VerifyKey):
30+
def format_plain(public_key: VerifyKey):
3131
print(
3232
"%s:%s %s"
3333
% (
@@ -38,7 +38,7 @@ def format_plain(public_key: nacl.signing.VerifyKey):
3838
)
3939

4040

41-
def format_for_config(public_key: nacl.signing.VerifyKey, expiry_ts: int):
41+
def format_for_config(public_key: VerifyKey, expiry_ts: int):
4242
print(
4343
' "%s:%s": { key: "%s", expired_ts: %i }'
4444
% (

synapse/_scripts/move_remote_media_to_new_store.py

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -109,10 +109,9 @@ def mkdir_and_move(original_file, dest_file):
109109
parser.add_argument("dest_repo", help="Path to source content repo")
110110
args = parser.parse_args()
111111

112-
logging_config = {
113-
"level": logging.DEBUG if args.v else logging.INFO,
114-
"format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
115-
}
116-
logging.basicConfig(**logging_config)
112+
logging.basicConfig(
113+
level=logging.DEBUG if args.v else logging.INFO,
114+
format="%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
115+
)
117116

118117
main(args.src_repo, args.dest_repo)

synapse/_scripts/synapse_port_db.py

Lines changed: 31 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -21,12 +21,13 @@
2121
import sys
2222
import time
2323
import traceback
24-
from typing import Dict, Iterable, Optional, Set
24+
from types import TracebackType
25+
from typing import Dict, Iterable, Optional, Set, Tuple, Type, cast
2526

2627
import yaml
2728
from matrix_common.versionstring import get_distribution_version_string
2829

29-
from twisted.internet import defer, reactor
30+
from twisted.internet import defer, reactor as reactor_
3031

3132
from synapse.config.database import DatabaseConnectionConfig
3233
from synapse.config.homeserver import HomeServerConfig
@@ -66,8 +67,12 @@
6667
from synapse.storage.databases.state.bg_updates import StateBackgroundUpdateStore
6768
from synapse.storage.engines import create_engine
6869
from synapse.storage.prepare_database import prepare_database
70+
from synapse.types import ISynapseReactor
6971
from synapse.util import Clock
7072

73+
# Cast safety: Twisted does some naughty magic which replaces the
74+
# twisted.internet.reactor module with a Reactor instance at runtime.
75+
reactor = cast(ISynapseReactor, reactor_)
7176
logger = logging.getLogger("synapse_port_db")
7277

7378

@@ -159,12 +164,14 @@
159164

160165
# Error returned by the run function. Used at the top-level part of the script to
161166
# handle errors and return codes.
162-
end_error = None # type: Optional[str]
167+
end_error: Optional[str] = None
163168
# The exec_info for the error, if any. If error is defined but not exec_info the script
164169
# will show only the error message without the stacktrace, if exec_info is defined but
165170
# not the error then the script will show nothing outside of what's printed in the run
166171
# function. If both are defined, the script will print both the error and the stacktrace.
167-
end_error_exec_info = None
172+
end_error_exec_info: Optional[
173+
Tuple[Type[BaseException], BaseException, TracebackType]
174+
] = None
168175

169176

170177
class Store(
@@ -236,9 +243,12 @@ def get_instance_name(self):
236243
return "master"
237244

238245

239-
class Porter(object):
240-
def __init__(self, **kwargs):
241-
self.__dict__.update(kwargs)
246+
class Porter:
247+
def __init__(self, sqlite_config, progress, batch_size, hs_config):
248+
self.sqlite_config = sqlite_config
249+
self.progress = progress
250+
self.batch_size = batch_size
251+
self.hs_config = hs_config
242252

243253
async def setup_table(self, table):
244254
if table in APPEND_ONLY_TABLES:
@@ -323,7 +333,7 @@ def _get_constraints(txn):
323333
"""
324334
txn.execute(sql)
325335

326-
results = {}
336+
results: Dict[str, Set[str]] = {}
327337
for table, foreign_table in txn:
328338
results.setdefault(table, set()).add(foreign_table)
329339
return results
@@ -540,7 +550,8 @@ def build_db_store(
540550
db_conn, allow_outdated_version=allow_outdated_version
541551
)
542552
prepare_database(db_conn, engine, config=self.hs_config)
543-
store = Store(DatabasePool(hs, db_config, engine), db_conn, hs)
553+
# Type safety: ignore that we're using Mock homeservers here.
554+
store = Store(DatabasePool(hs, db_config, engine), db_conn, hs) # type: ignore[arg-type]
544555
db_conn.commit()
545556

546557
return store
@@ -724,7 +735,9 @@ def alter_table(txn):
724735
except Exception as e:
725736
global end_error_exec_info
726737
end_error = str(e)
727-
end_error_exec_info = sys.exc_info()
738+
# Type safety: we're in an exception handler, so the exc_info() tuple
739+
# will not be (None, None, None).
740+
end_error_exec_info = sys.exc_info() # type: ignore[assignment]
728741
logger.exception("")
729742
finally:
730743
reactor.stop()
@@ -1023,7 +1036,7 @@ def __init__(self, stdscr):
10231036
curses.init_pair(1, curses.COLOR_RED, -1)
10241037
curses.init_pair(2, curses.COLOR_GREEN, -1)
10251038

1026-
self.last_update = 0
1039+
self.last_update = 0.0
10271040

10281041
self.finished = False
10291042

@@ -1082,8 +1095,7 @@ def render(self, force=False):
10821095
left_margin = 5
10831096
middle_space = 1
10841097

1085-
items = self.tables.items()
1086-
items = sorted(items, key=lambda i: (i[1]["perc"], i[0]))
1098+
items = sorted(self.tables.items(), key=lambda i: (i[1]["perc"], i[0]))
10871099

10881100
for i, (table, data) in enumerate(items):
10891101
if i + 2 >= rows:
@@ -1179,15 +1191,11 @@ def main():
11791191

11801192
args = parser.parse_args()
11811193

1182-
logging_config = {
1183-
"level": logging.DEBUG if args.v else logging.INFO,
1184-
"format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
1185-
}
1186-
1187-
if args.curses:
1188-
logging_config["filename"] = "port-synapse.log"
1189-
1190-
logging.basicConfig(**logging_config)
1194+
logging.basicConfig(
1195+
level=logging.DEBUG if args.v else logging.INFO,
1196+
format="%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
1197+
filename="port-synapse.log" if args.curses else None,
1198+
)
11911199

11921200
sqlite_config = {
11931201
"name": "sqlite3",
@@ -1218,6 +1226,7 @@ def main():
12181226
config.parse_config_dict(hs_config, "", "")
12191227

12201228
def start(stdscr=None):
1229+
progress: Progress
12211230
if stdscr:
12221231
progress = CursesProgress(stdscr)
12231232
else:

synapse/_scripts/update_synapse_database.py

Lines changed: 11 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -16,22 +16,27 @@
1616
import argparse
1717
import logging
1818
import sys
19+
from typing import cast
1920

2021
import yaml
2122
from matrix_common.versionstring import get_distribution_version_string
2223

23-
from twisted.internet import defer, reactor
24+
from twisted.internet import defer, reactor as reactor_
2425

2526
from synapse.config.homeserver import HomeServerConfig
2627
from synapse.metrics.background_process_metrics import run_as_background_process
2728
from synapse.server import HomeServer
2829
from synapse.storage import DataStore
30+
from synapse.types import ISynapseReactor
2931

32+
# Cast safety: Twisted does some naughty magic which replaces the
33+
# twisted.internet.reactor module with a Reactor instance at runtime.
34+
reactor = cast(ISynapseReactor, reactor_)
3035
logger = logging.getLogger("update_database")
3136

3237

3338
class MockHomeserver(HomeServer):
34-
DATASTORE_CLASS = DataStore
39+
DATASTORE_CLASS = DataStore # type: ignore [assignment]
3540

3641
def __init__(self, config, **kwargs):
3742
super(MockHomeserver, self).__init__(
@@ -85,12 +90,10 @@ def main():
8590

8691
args = parser.parse_args()
8792

88-
logging_config = {
89-
"level": logging.DEBUG if args.v else logging.INFO,
90-
"format": "%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
91-
}
92-
93-
logging.basicConfig(**logging_config)
93+
logging.basicConfig(
94+
level=logging.DEBUG if args.v else logging.INFO,
95+
format="%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s",
96+
)
9497

9598
# Load, process and sanity-check the config.
9699
hs_config = yaml.safe_load(args.database_config)

0 commit comments

Comments
 (0)