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

Commit f44d729

Browse files
authored
Additional type hints for config module. (#11465)
This adds some misc. type hints to helper methods used in the `synapse.config` module.
1 parent a265fbd commit f44d729

15 files changed

+129
-99
lines changed

changelog.d/11465.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints to `synapse.config` module.

synapse/app/_base.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
Iterable,
3333
List,
3434
NoReturn,
35+
Optional,
3536
Tuple,
3637
cast,
3738
)
@@ -129,7 +130,7 @@ def start_worker_reactor(
129130
def start_reactor(
130131
appname: str,
131132
soft_file_limit: int,
132-
gc_thresholds: Tuple[int, int, int],
133+
gc_thresholds: Optional[Tuple[int, int, int]],
133134
pid_file: str,
134135
daemonize: bool,
135136
print_pidfile: bool,

synapse/config/__main__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,13 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
import sys
16+
from typing import List
1617

1718
from synapse.config._base import ConfigError
1819
from synapse.config.homeserver import HomeServerConfig
1920

2021

21-
def main(args):
22+
def main(args: List[str]) -> None:
2223
action = args[1] if len(args) > 1 and args[1] == "read" else None
2324
# If we're reading a key in the config file, then `args[1]` will be `read` and `args[2]`
2425
# will be the key to read.

synapse/config/appservice.py

+14-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2015, 2016 OpenMarket Ltd
2+
# Copyright 2021 The Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -13,14 +14,14 @@
1314
# limitations under the License.
1415

1516
import logging
16-
from typing import Dict
17+
from typing import Dict, List
1718
from urllib import parse as urlparse
1819

1920
import yaml
2021
from netaddr import IPSet
2122

2223
from synapse.appservice import ApplicationService
23-
from synapse.types import UserID
24+
from synapse.types import JsonDict, UserID
2425

2526
from ._base import Config, ConfigError
2627

@@ -30,12 +31,12 @@
3031
class AppServiceConfig(Config):
3132
section = "appservice"
3233

33-
def read_config(self, config, **kwargs):
34+
def read_config(self, config, **kwargs) -> None:
3435
self.app_service_config_files = config.get("app_service_config_files", [])
3536
self.notify_appservices = config.get("notify_appservices", True)
3637
self.track_appservice_user_ips = config.get("track_appservice_user_ips", False)
3738

38-
def generate_config_section(cls, **kwargs):
39+
def generate_config_section(cls, **kwargs) -> str:
3940
return """\
4041
# A list of application service config files to use
4142
#
@@ -50,7 +51,9 @@ def generate_config_section(cls, **kwargs):
5051
"""
5152

5253

53-
def load_appservices(hostname, config_files):
54+
def load_appservices(
55+
hostname: str, config_files: List[str]
56+
) -> List[ApplicationService]:
5457
"""Returns a list of Application Services from the config files."""
5558
if not isinstance(config_files, list):
5659
logger.warning("Expected %s to be a list of AS config files.", config_files)
@@ -93,7 +96,9 @@ def load_appservices(hostname, config_files):
9396
return appservices
9497

9598

96-
def _load_appservice(hostname, as_info, config_filename):
99+
def _load_appservice(
100+
hostname: str, as_info: JsonDict, config_filename: str
101+
) -> ApplicationService:
97102
required_string_fields = ["id", "as_token", "hs_token", "sender_localpart"]
98103
for field in required_string_fields:
99104
if not isinstance(as_info.get(field), str):
@@ -115,9 +120,9 @@ def _load_appservice(hostname, as_info, config_filename):
115120
user_id = user.to_string()
116121

117122
# Rate limiting for users of this AS is on by default (excludes sender)
118-
rate_limited = True
119-
if isinstance(as_info.get("rate_limited"), bool):
120-
rate_limited = as_info.get("rate_limited")
123+
rate_limited = as_info.get("rate_limited")
124+
if not isinstance(rate_limited, bool):
125+
rate_limited = True
121126

122127
# namespace checks
123128
if not isinstance(as_info.get("namespaces"), dict):

synapse/config/cache.py

+14-12
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Copyright 2019 Matrix.org Foundation C.I.C.
1+
# Copyright 2019-2021 Matrix.org Foundation C.I.C.
22
#
33
# Licensed under the Apache License, Version 2.0 (the "License");
44
# you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
1717
import threading
1818
from typing import Callable, Dict, Optional
1919

20+
import attr
21+
2022
from synapse.python_dependencies import DependencyException, check_requirements
2123

2224
from ._base import Config, ConfigError
@@ -34,13 +36,13 @@
3436
_DEFAULT_EVENT_CACHE_SIZE = "10K"
3537

3638

39+
@attr.s(slots=True, auto_attribs=True)
3740
class CacheProperties:
38-
def __init__(self):
39-
# The default factor size for all caches
40-
self.default_factor_size = float(
41-
os.environ.get(_CACHE_PREFIX, _DEFAULT_FACTOR_SIZE)
42-
)
43-
self.resize_all_caches_func = None
41+
# The default factor size for all caches
42+
default_factor_size: float = float(
43+
os.environ.get(_CACHE_PREFIX, _DEFAULT_FACTOR_SIZE)
44+
)
45+
resize_all_caches_func: Optional[Callable[[], None]] = None
4446

4547

4648
properties = CacheProperties()
@@ -62,7 +64,7 @@ def _canonicalise_cache_name(cache_name: str) -> str:
6264

6365
def add_resizable_cache(
6466
cache_name: str, cache_resize_callback: Callable[[float], None]
65-
):
67+
) -> None:
6668
"""Register a cache that's size can dynamically change
6769
6870
Args:
@@ -91,7 +93,7 @@ class CacheConfig(Config):
9193
_environ = os.environ
9294

9395
@staticmethod
94-
def reset():
96+
def reset() -> None:
9597
"""Resets the caches to their defaults. Used for tests."""
9698
properties.default_factor_size = float(
9799
os.environ.get(_CACHE_PREFIX, _DEFAULT_FACTOR_SIZE)
@@ -100,7 +102,7 @@ def reset():
100102
with _CACHES_LOCK:
101103
_CACHES.clear()
102104

103-
def generate_config_section(self, **kwargs):
105+
def generate_config_section(self, **kwargs) -> str:
104106
return """\
105107
## Caching ##
106108
@@ -162,7 +164,7 @@ def generate_config_section(self, **kwargs):
162164
#sync_response_cache_duration: 2m
163165
"""
164166

165-
def read_config(self, config, **kwargs):
167+
def read_config(self, config, **kwargs) -> None:
166168
self.event_cache_size = self.parse_size(
167169
config.get("event_cache_size", _DEFAULT_EVENT_CACHE_SIZE)
168170
)
@@ -232,7 +234,7 @@ def read_config(self, config, **kwargs):
232234
# needing an instance of Config
233235
properties.resize_all_caches_func = self.resize_all_caches
234236

235-
def resize_all_caches(self):
237+
def resize_all_caches(self) -> None:
236238
"""Ensure all cache sizes are up to date
237239
238240
For each cache, run the mapped callback function with either

synapse/config/cas.py

+3-2
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2015, 2016 OpenMarket Ltd
2+
# Copyright 2021 The Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -28,7 +29,7 @@ class CasConfig(Config):
2829

2930
section = "cas"
3031

31-
def read_config(self, config, **kwargs):
32+
def read_config(self, config, **kwargs) -> None:
3233
cas_config = config.get("cas_config", None)
3334
self.cas_enabled = cas_config and cas_config.get("enabled", True)
3435

@@ -51,7 +52,7 @@ def read_config(self, config, **kwargs):
5152
self.cas_displayname_attribute = None
5253
self.cas_required_attributes = []
5354

54-
def generate_config_section(self, config_dir_path, server_name, **kwargs):
55+
def generate_config_section(self, config_dir_path, server_name, **kwargs) -> str:
5556
return """\
5657
# Enable Central Authentication Service (CAS) for registration and login.
5758
#

synapse/config/database.py

+7-6
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
# Copyright 2014-2016 OpenMarket Ltd
2-
# Copyright 2020 The Matrix.org Foundation C.I.C.
2+
# Copyright 2020-2021 The Matrix.org Foundation C.I.C.
33
#
44
# Licensed under the Apache License, Version 2.0 (the "License");
55
# you may not use this file except in compliance with the License.
@@ -12,6 +12,7 @@
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+
import argparse
1516
import logging
1617
import os
1718

@@ -119,7 +120,7 @@ def __init__(self, *args, **kwargs):
119120

120121
self.databases = []
121122

122-
def read_config(self, config, **kwargs):
123+
def read_config(self, config, **kwargs) -> None:
123124
# We *experimentally* support specifying multiple databases via the
124125
# `databases` key. This is a map from a label to database config in the
125126
# same format as the `database` config option, plus an extra
@@ -163,12 +164,12 @@ def read_config(self, config, **kwargs):
163164
self.databases = [DatabaseConnectionConfig("master", database_config)]
164165
self.set_databasepath(database_path)
165166

166-
def generate_config_section(self, data_dir_path, **kwargs):
167+
def generate_config_section(self, data_dir_path, **kwargs) -> str:
167168
return DEFAULT_CONFIG % {
168169
"database_path": os.path.join(data_dir_path, "homeserver.db")
169170
}
170171

171-
def read_arguments(self, args):
172+
def read_arguments(self, args: argparse.Namespace) -> None:
172173
"""
173174
Cases for the cli input:
174175
- If no databases are configured and no database_path is set, raise.
@@ -194,15 +195,15 @@ def read_arguments(self, args):
194195
else:
195196
logger.warning(NON_SQLITE_DATABASE_PATH_WARNING)
196197

197-
def set_databasepath(self, database_path):
198+
def set_databasepath(self, database_path: str) -> None:
198199

199200
if database_path != ":memory:":
200201
database_path = self.abspath(database_path)
201202

202203
self.databases[0].config["args"]["database"] = database_path
203204

204205
@staticmethod
205-
def add_arguments(parser):
206+
def add_arguments(parser: argparse.ArgumentParser) -> None:
206207
db_group = parser.add_argument_group("database")
207208
db_group.add_argument(
208209
"-d",

synapse/config/logger.py

+14-10
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
# Copyright 2014-2016 OpenMarket Ltd
2+
# Copyright 2021 The Matrix.org Foundation C.I.C.
23
#
34
# Licensed under the Apache License, Version 2.0 (the "License");
45
# you may not use this file except in compliance with the License.
@@ -18,7 +19,7 @@
1819
import sys
1920
import threading
2021
from string import Template
21-
from typing import TYPE_CHECKING, Any, Dict
22+
from typing import TYPE_CHECKING, Any, Dict, Optional
2223

2324
import yaml
2425
from zope.interface import implementer
@@ -40,6 +41,7 @@
4041
from ._base import Config, ConfigError
4142

4243
if TYPE_CHECKING:
44+
from synapse.config.homeserver import HomeServerConfig
4345
from synapse.server import HomeServer
4446

4547
DEFAULT_LOG_CONFIG = Template(
@@ -141,13 +143,13 @@
141143
class LoggingConfig(Config):
142144
section = "logging"
143145

144-
def read_config(self, config, **kwargs):
146+
def read_config(self, config, **kwargs) -> None:
145147
if config.get("log_file"):
146148
raise ConfigError(LOG_FILE_ERROR)
147149
self.log_config = self.abspath(config.get("log_config"))
148150
self.no_redirect_stdio = config.get("no_redirect_stdio", False)
149151

150-
def generate_config_section(self, config_dir_path, server_name, **kwargs):
152+
def generate_config_section(self, config_dir_path, server_name, **kwargs) -> str:
151153
log_config = os.path.join(config_dir_path, server_name + ".log.config")
152154
return (
153155
"""\
@@ -161,14 +163,14 @@ def generate_config_section(self, config_dir_path, server_name, **kwargs):
161163
% locals()
162164
)
163165

164-
def read_arguments(self, args):
166+
def read_arguments(self, args: argparse.Namespace) -> None:
165167
if args.no_redirect_stdio is not None:
166168
self.no_redirect_stdio = args.no_redirect_stdio
167169
if args.log_file is not None:
168170
raise ConfigError(LOG_FILE_ERROR)
169171

170172
@staticmethod
171-
def add_arguments(parser):
173+
def add_arguments(parser: argparse.ArgumentParser) -> None:
172174
logging_group = parser.add_argument_group("logging")
173175
logging_group.add_argument(
174176
"-n",
@@ -197,7 +199,9 @@ def generate_files(self, config: Dict[str, Any], config_dir_path: str) -> None:
197199
log_config_file.write(DEFAULT_LOG_CONFIG.substitute(log_file=log_file))
198200

199201

200-
def _setup_stdlib_logging(config, log_config_path, logBeginner: LogBeginner) -> None:
202+
def _setup_stdlib_logging(
203+
config: "HomeServerConfig", log_config_path: Optional[str], logBeginner: LogBeginner
204+
) -> None:
201205
"""
202206
Set up Python standard library logging.
203207
"""
@@ -230,7 +234,7 @@ def _setup_stdlib_logging(config, log_config_path, logBeginner: LogBeginner) ->
230234
log_metadata_filter = MetadataFilter({"server_name": config.server.server_name})
231235
old_factory = logging.getLogRecordFactory()
232236

233-
def factory(*args, **kwargs):
237+
def factory(*args: Any, **kwargs: Any) -> logging.LogRecord:
234238
record = old_factory(*args, **kwargs)
235239
log_context_filter.filter(record)
236240
log_metadata_filter.filter(record)
@@ -297,7 +301,7 @@ def _load_logging_config(log_config_path: str) -> None:
297301
logging.config.dictConfig(log_config)
298302

299303

300-
def _reload_logging_config(log_config_path):
304+
def _reload_logging_config(log_config_path: Optional[str]) -> None:
301305
"""
302306
Reload the log configuration from the file and apply it.
303307
"""
@@ -311,8 +315,8 @@ def _reload_logging_config(log_config_path):
311315

312316
def setup_logging(
313317
hs: "HomeServer",
314-
config,
315-
use_worker_options=False,
318+
config: "HomeServerConfig",
319+
use_worker_options: bool = False,
316320
logBeginner: LogBeginner = globalLogBeginner,
317321
) -> None:
318322
"""

0 commit comments

Comments
 (0)