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

Add missing type hints to config classes. #12402

Merged
merged 9 commits into from
Apr 11, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog.d/12402.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Add missing type hints to configuration classes.
2 changes: 1 addition & 1 deletion mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -106,7 +106,7 @@ disallow_untyped_defs = True
[mypy-synapse.appservice.*]
disallow_untyped_defs = True

[mypy-synapse.config._base]
[mypy-synapse.config.*]
disallow_untyped_defs = True

[mypy-synapse.crypto.*]
Expand Down
4 changes: 1 addition & 3 deletions synapse/_scripts/review_recent_signups.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,9 +138,7 @@ def main() -> None:
config_args = parser.parse_args(sys.argv[1:])
config_files = find_config_files(search_paths=config_args.config_path)
config_dict = read_config_files(config_files)
config.parse_config_dict(
config_dict,
)
config.parse_config_dict(config_dict, "", "")

since_ms = time.time() * 1000 - Config.parse_duration(config_args.since)
exclude_users_with_email = config_args.exclude_emails
Expand Down
4 changes: 3 additions & 1 deletion synapse/app/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ def start_reactor(
appname: str,
soft_file_limit: int,
gc_thresholds: Optional[Tuple[int, int, int]],
pid_file: str,
pid_file: Optional[str],
daemonize: bool,
print_pidfile: bool,
logger: logging.Logger,
Expand Down Expand Up @@ -171,6 +171,8 @@ def run() -> None:
# appearing to go backwards.
with PreserveLoggingContext():
if daemonize:
assert pid_file is not None

if print_pidfile:
print(pid_file)

Expand Down
5 changes: 1 addition & 4 deletions synapse/config/_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -702,10 +702,7 @@ def load_or_generate_config(
return obj

def parse_config_dict(
self,
config_dict: Dict[str, Any],
config_dir_path: Optional[str] = None,
data_dir_path: Optional[str] = None,
self, config_dict: Dict[str, Any], config_dir_path: str, data_dir_path: str
) -> None:
"""Read the information from the config dict into this Config object.
Expand Down
5 changes: 1 addition & 4 deletions synapse/config/_base.pyi
Original file line number Diff line number Diff line change
Expand Up @@ -124,10 +124,7 @@ class RootConfig:
@classmethod
def invoke_all_static(cls, func_name: str, *args: Any, **kwargs: Any) -> None: ...
def parse_config_dict(
self,
config_dict: Dict[str, Any],
config_dir_path: Optional[str] = ...,
data_dir_path: Optional[str] = ...,
self, config_dict: Dict[str, Any], config_dir_path: str, data_dir_path: str
) -> None: ...
def generate_config(
self,
Expand Down
4 changes: 3 additions & 1 deletion synapse/config/account_validity.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,10 @@
# See the License for the specific language governing permissions and
# limitations under the License.
import logging
from typing import Any

from synapse.config._base import Config, ConfigError
from synapse.types import JsonDict

logger = logging.getLogger(__name__)

Expand All @@ -29,7 +31,7 @@
class AccountValidityConfig(Config):
section = "account_validity"

def read_config(self, config, **kwargs):
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
"""Parses the old account validity config. The config format looks like this:

account_validity:
Expand Down
6 changes: 3 additions & 3 deletions synapse/config/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@
# limitations under the License.

import logging
from typing import Iterable
from typing import Any, Iterable

from synapse.api.constants import EventTypes
from synapse.config._base import Config, ConfigError
Expand All @@ -26,12 +26,12 @@
class ApiConfig(Config):
section = "api"

def read_config(self, config: JsonDict, **kwargs):
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
validate_config(_MAIN_SCHEMA, config, ())
self.room_prejoin_state = list(self._get_prejoin_state_types(config))
self.track_puppeted_user_ips = config.get("track_puppeted_user_ips", False)

def generate_config_section(cls, **kwargs) -> str:
def generate_config_section(cls, **kwargs: Any) -> str:
formatted_default_state_types = "\n".join(
" # - %s" % (t,) for t in _DEFAULT_PREJOIN_STATE_TYPES
)
Expand Down
6 changes: 3 additions & 3 deletions synapse/config/appservice.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# limitations under the License.

import logging
from typing import Dict, List
from typing import Any, Dict, List
from urllib import parse as urlparse

import yaml
Expand All @@ -31,12 +31,12 @@
class AppServiceConfig(Config):
section = "appservice"

def read_config(self, config, **kwargs) -> None:
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
self.app_service_config_files = config.get("app_service_config_files", [])
self.notify_appservices = config.get("notify_appservices", True)
self.track_appservice_user_ips = config.get("track_appservice_user_ips", False)

def generate_config_section(cls, **kwargs) -> str:
def generate_config_section(cls, **kwargs: Any) -> str:
return """\
# A list of application service config files to use
#
Expand Down
7 changes: 5 additions & 2 deletions synapse/config/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any

from synapse.types import JsonDict

from ._base import Config

Expand All @@ -21,7 +24,7 @@ class AuthConfig(Config):

section = "auth"

def read_config(self, config, **kwargs):
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
password_config = config.get("password_config", {})
if password_config is None:
password_config = {}
Expand All @@ -40,7 +43,7 @@ def read_config(self, config, **kwargs):
ui_auth.get("session_timeout", 0)
)

def generate_config_section(self, config_dir_path, server_name, **kwargs):
def generate_config_section(self, **kwargs: Any) -> str:
return """\
password_config:
# Uncomment to disable password login
Expand Down
7 changes: 5 additions & 2 deletions synapse/config/background_updates.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,17 @@
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from typing import Any

from synapse.types import JsonDict

from ._base import Config


class BackgroundUpdateConfig(Config):
section = "background_updates"

def generate_config_section(self, **kwargs) -> str:
def generate_config_section(self, **kwargs: Any) -> str:
return """\
## Background Updates ##

Expand Down Expand Up @@ -52,7 +55,7 @@ def generate_config_section(self, **kwargs) -> str:
#default_batch_size: 50
"""

def read_config(self, config, **kwargs) -> None:
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
bg_update_config = config.get("background_updates") or {}

self.update_duration_ms = bg_update_config.get(
Expand Down
7 changes: 4 additions & 3 deletions synapse/config/cache.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,10 +16,11 @@
import os
import re
import threading
from typing import Callable, Dict, Optional
from typing import Any, Callable, Dict, Optional

import attr

from synapse.types import JsonDict
from synapse.util.check_dependencies import DependencyException, check_requirements

from ._base import Config, ConfigError
Expand Down Expand Up @@ -105,7 +106,7 @@ def reset() -> None:
with _CACHES_LOCK:
_CACHES.clear()

def generate_config_section(self, **kwargs) -> str:
def generate_config_section(self, **kwargs: Any) -> str:
return """\
## Caching ##

Expand Down Expand Up @@ -172,7 +173,7 @@ def generate_config_section(self, **kwargs) -> str:
#sync_response_cache_duration: 2m
"""

def read_config(self, config, **kwargs) -> None:
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
self.event_cache_size = self.parse_size(
config.get("event_cache_size", _DEFAULT_EVENT_CACHE_SIZE)
)
Expand Down
26 changes: 21 additions & 5 deletions synapse/config/captcha.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,15 +12,31 @@
# See the License for the specific language governing permissions and
# limitations under the License.

from ._base import Config
from typing import Any

from synapse.types import JsonDict

from ._base import Config, ConfigError


class CaptchaConfig(Config):
section = "captcha"

def read_config(self, config, **kwargs):
self.recaptcha_private_key = config.get("recaptcha_private_key")
self.recaptcha_public_key = config.get("recaptcha_public_key")
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
recaptcha_private_key = config.get("recaptcha_private_key")
if recaptcha_private_key is not None and not isinstance(
recaptcha_private_key, str
):
raise ConfigError("recaptcha_private_key must be a string.")
self.recaptcha_private_key = recaptcha_private_key

recaptcha_public_key = config.get("recaptcha_public_key")
if recaptcha_public_key is not None and not isinstance(
recaptcha_public_key, str
):
raise ConfigError("recaptcha_public_key must be a string.")
self.recaptcha_public_key = recaptcha_public_key

self.enable_registration_captcha = config.get(
"enable_registration_captcha", False
)
Expand All @@ -30,7 +46,7 @@ def read_config(self, config, **kwargs):
)
self.recaptcha_template = self.read_template("recaptcha.html")

def generate_config_section(self, **kwargs):
def generate_config_section(self, **kwargs: Any) -> str:
return """\
## Captcha ##
# See docs/CAPTCHA_SETUP.md for full details of configuring this.
Expand Down
5 changes: 3 additions & 2 deletions synapse/config/cas.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
from typing import Any, List

from synapse.config.sso import SsoAttributeRequirement
from synapse.types import JsonDict

from ._base import Config
from ._util import validate_config
Expand All @@ -29,7 +30,7 @@ class CasConfig(Config):

section = "cas"

def read_config(self, config, **kwargs) -> None:
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
cas_config = config.get("cas_config", None)
self.cas_enabled = cas_config and cas_config.get("enabled", True)

Expand All @@ -52,7 +53,7 @@ def read_config(self, config, **kwargs) -> None:
self.cas_displayname_attribute = None
self.cas_required_attributes = []

def generate_config_section(self, config_dir_path, server_name, **kwargs) -> str:
def generate_config_section(self, **kwargs: Any) -> str:
return """\
# Enable Central Authentication Service (CAS) for registration and login.
#
Expand Down
13 changes: 7 additions & 6 deletions synapse/config/consent.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,10 @@
# limitations under the License.

from os import path
from typing import Optional
from typing import Any, Optional

from synapse.config import ConfigError
from synapse.types import JsonDict

from ._base import Config

Expand Down Expand Up @@ -76,18 +77,18 @@ class ConsentConfig(Config):

section = "consent"

def __init__(self, *args):
def __init__(self, *args: Any):
super().__init__(*args)

self.user_consent_version: Optional[str] = None
self.user_consent_template_dir: Optional[str] = None
self.user_consent_server_notice_content = None
self.user_consent_server_notice_content: Optional[JsonDict] = None
self.user_consent_server_notice_to_guests = False
self.block_events_without_consent_error = None
self.block_events_without_consent_error: Optional[str] = None
self.user_consent_at_registration = False
self.user_consent_policy_name = "Privacy Policy"

def read_config(self, config, **kwargs):
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
consent_config = config.get("user_consent")
self.terms_template = self.read_template("terms.html")

Expand Down Expand Up @@ -118,5 +119,5 @@ def read_config(self, config, **kwargs):
"policy_name", "Privacy Policy"
)

def generate_config_section(self, **kwargs):
def generate_config_section(self, **kwargs: Any) -> str:
return DEFAULT_CONFIG
12 changes: 7 additions & 5 deletions synapse/config/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,10 @@
import argparse
import logging
import os
from typing import Any, List

from synapse.config._base import Config, ConfigError
from synapse.types import JsonDict

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -121,12 +123,12 @@ def __init__(self, name: str, db_config: dict):
class DatabaseConfig(Config):
section = "database"

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
def __init__(self, *args: Any):
super().__init__(*args)

self.databases = []
self.databases: List[DatabaseConnectionConfig] = []

def read_config(self, config, **kwargs) -> None:
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
# We *experimentally* support specifying multiple databases via the
# `databases` key. This is a map from a label to database config in the
# same format as the `database` config option, plus an extra
Expand Down Expand Up @@ -170,7 +172,7 @@ def read_config(self, config, **kwargs) -> None:
self.databases = [DatabaseConnectionConfig("master", database_config)]
self.set_databasepath(database_path)

def generate_config_section(self, data_dir_path, **kwargs) -> str:
def generate_config_section(self, data_dir_path: str, **kwargs: Any) -> str:
return DEFAULT_CONFIG % {
"database_path": os.path.join(data_dir_path, "homeserver.db")
}
Expand Down
7 changes: 5 additions & 2 deletions synapse/config/emailconfig.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
import logging
import os
from enum import Enum
from typing import Any

import attr

from synapse.types import JsonDict

from ._base import Config, ConfigError

logger = logging.getLogger(__name__)
Expand Down Expand Up @@ -73,7 +76,7 @@ class EmailSubjectConfig:
class EmailConfig(Config):
section = "email"

def read_config(self, config, **kwargs):
def read_config(self, config: JsonDict, **kwargs: Any) -> None:
# TODO: We should separate better the email configuration from the notification
# and account validity config.

Expand Down Expand Up @@ -354,7 +357,7 @@ def read_config(self, config, **kwargs):
path=("email", "invite_client_location"),
)

def generate_config_section(self, config_dir_path, server_name, **kwargs):
def generate_config_section(self, **kwargs: Any) -> str:
return (
"""\
# Configuration for sending emails from Synapse.
Expand Down
Loading