From 12116eb935121a9cc2907b81c8a824a339eb0cf3 Mon Sep 17 00:00:00 2001 From: David Robertson Date: Thu, 7 Oct 2021 20:59:36 +0100 Subject: [PATCH] disallow-untyped-defs for synapse.module_api --- mypy.ini | 3 + synapse/module_api/__init__.py | 119 ++++++++++++++++++++------------- 2 files changed, 76 insertions(+), 46 deletions(-) diff --git a/mypy.ini b/mypy.ini index c63b01fe9989..3bc817f37d68 100644 --- a/mypy.ini +++ b/mypy.ini @@ -99,6 +99,9 @@ disallow_untyped_defs = True [mypy-synapse.rest.*] disallow_untyped_defs = True +[mypy-synapse.module_api.*] +disallow_untyped_defs = True + [mypy-synapse.state.*] disallow_untyped_defs = True diff --git a/synapse/module_api/__init__.py b/synapse/module_api/__init__.py index 8ae21bc43c23..cb99fde7091e 100644 --- a/synapse/module_api/__init__.py +++ b/synapse/module_api/__init__.py @@ -24,6 +24,7 @@ List, Optional, Tuple, + TypeVar, Union, ) @@ -60,8 +61,12 @@ from synapse.util.caches.descriptors import cached if TYPE_CHECKING: + from synapse.handlers.auth import AuthHandler from synapse.server import HomeServer + +T = TypeVar("T") + """ This package defines the 'stable' API which can be used by extension modules which are loaded into Synapse. @@ -100,12 +105,18 @@ class UserIpAndAgent: last_seen: int +# This is sad: I'd like to express that the arguments to this Callable are +# themselves callable. "Callback protocols" let you do this, but I couldn't find +# a way to do so that mypy agreed was type safe. +RegisterCallbacks = Callable[..., None] + + class ModuleApi: """A proxy object that gets passed to various plugin modules so they can register new users etc if necessary. """ - def __init__(self, hs: "HomeServer", auth_handler): + def __init__(self, hs: "HomeServer", auth_handler: "AuthHandler"): self._hs = hs self._store = hs.get_datastore() @@ -145,26 +156,26 @@ def __init__(self, hs: "HomeServer", auth_handler): # The following methods should only be called during the module's initialisation. @property - def register_spam_checker_callbacks(self): + def register_spam_checker_callbacks(self) -> RegisterCallbacks: """Registers callbacks for spam checking capabilities.""" return self._spam_checker.register_callbacks @property - def register_account_validity_callbacks(self): + def register_account_validity_callbacks(self) -> RegisterCallbacks: """Registers callbacks for account validity capabilities.""" return self._account_validity_handler.register_account_validity_callbacks @property - def register_third_party_rules_callbacks(self): + def register_third_party_rules_callbacks(self) -> RegisterCallbacks: """Registers callbacks for third party event rules capabilities.""" return self._third_party_event_rules.register_third_party_rules_callbacks @property - def register_presence_router_callbacks(self): + def register_presence_router_callbacks(self) -> RegisterCallbacks: """Registers callbacks for presence router capabilities.""" return self._presence_router.register_presence_router_callbacks - def register_web_resource(self, path: str, resource: IResource): + def register_web_resource(self, path: str, resource: IResource) -> None: """Registers a web resource to be served at the given path. This function should be called during initialisation of the module. @@ -182,19 +193,14 @@ def register_web_resource(self, path: str, resource: IResource): # The following methods can be called by the module at any point in time. @property - def http_client(self): - """Allows making outbound HTTP requests to remote resources. - - An instance of synapse.http.client.SimpleHttpClient - """ + def http_client(self) -> SimpleHttpClient: + """Allows making outbound HTTP requests to remote resources.""" return self._http_client @property - def public_room_list_manager(self): + def public_room_list_manager(self) -> "PublicRoomListManager": """Allows adding to, removing from and checking the status of rooms in the public room list. - - An instance of synapse.module_api.PublicRoomListManager """ return self._public_room_list_manager @@ -259,17 +265,17 @@ async def is_user_admin(self, user_id: str) -> bool: """ return await self._store.is_server_admin(UserID.from_string(user_id)) - def get_qualified_user_id(self, username): + def get_qualified_user_id(self, username: str) -> str: """Qualify a user id, if necessary Takes a user id provided by the user and adds the @ and :domain to qualify it, if necessary Args: - username (str): provided user id + username: provided user id Returns: - str: qualified @user:id + qualified @user:id """ if username.startswith("@"): return username @@ -301,20 +307,25 @@ async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]: """ return await self._store.user_get_threepids(user_id) - def check_user_exists(self, user_id): + def check_user_exists(self, user_id: str) -> "defer.Deferred[Optional[str]]": """Check if user exists. Args: - user_id (str): Complete @user:id + user_id: Complete @user:id Returns: - Deferred[str|None]: Canonical (case-corrected) user_id, or None + Canonical (case-corrected) user_id, or None if the user is not registered. """ return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id)) @defer.inlineCallbacks - def register(self, localpart, displayname=None, emails: Optional[List[str]] = None): + def register( + self, + localpart: str, + displayname: Optional[str] = None, + emails: Optional[List[str]] = None, + ) -> Generator["defer.Deferred[Any]", Any, Tuple[str, str]]: """Registers a new user with given localpart and optional displayname, emails. Also returns an access token for the new user. @@ -324,12 +335,12 @@ def register(self, localpart, displayname=None, emails: Optional[List[str]] = No register_device. Args: - localpart (str): The localpart of the new user. - displayname (str|None): The displayname of the new user. - emails (List[str]): Emails to bind to the new user. + localpart: The localpart of the new user. + displayname: The displayname of the new user. + emails: Emails to bind to the new user. Returns: - Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token) + a 2-tuple of (user_id, access_token) """ logger.warning( "Using deprecated ModuleApi.register which creates a dummy user device." @@ -339,21 +350,24 @@ def register(self, localpart, displayname=None, emails: Optional[List[str]] = No return user_id, access_token def register_user( - self, localpart, displayname=None, emails: Optional[List[str]] = None - ): + self, + localpart: str, + displayname: Optional[str] = None, + emails: Optional[List[str]] = None, + ) -> "defer.Deferred[str]": """Registers a new user with given localpart and optional displayname, emails. Args: - localpart (str): The localpart of the new user. - displayname (str|None): The displayname of the new user. - emails (List[str]): Emails to bind to the new user. + localpart: The localpart of the new user. + displayname: The displayname of the new user. + emails: Emails to bind to the new user. Raises: SynapseError if there is an error performing the registration. Check the 'errcode' property for more information on the reason for failure Returns: - defer.Deferred[str]: user_id + user_id """ return defer.ensureDeferred( self._hs.get_registration_handler().register_user( @@ -363,18 +377,23 @@ def register_user( ) ) - def register_device(self, user_id, device_id=None, initial_display_name=None): + def register_device( + self, + user_id: str, + device_id: Optional[str] = None, + initial_display_name: Optional[str] = None, + ) -> "defer.Deferred[Tuple[str, str, Optional[int], Optional[str]]]": """Register a device for a user and generate an access token. Args: - user_id (str): full canonical @user:id - device_id (str|None): The device ID to check, or None to generate + user_id: full canonical @user:id + device_id: The device ID to check, or None to generate a new one. - initial_display_name (str|None): An optional display name for the + initial_display_name: An optional display name for the device. Returns: - defer.Deferred[tuple[str, str]]: Tuple of device ID and access token + Tuple of device ID, access token, access token expiration time and refresh token """ return defer.ensureDeferred( self._hs.get_registration_handler().register_device( @@ -424,7 +443,9 @@ def generate_short_term_login_token( ) @defer.inlineCallbacks - def invalidate_access_token(self, access_token): + def invalidate_access_token( + self, access_token: str + ) -> Generator["defer.Deferred[Any]", Any, None]: """Invalidate an access token for a user Args: @@ -454,12 +475,18 @@ def invalidate_access_token(self, access_token): self._auth_handler.delete_access_token(access_token) ) - def run_db_interaction(self, desc, func, *args, **kwargs): + def run_db_interaction( + self, + desc: str, + func: Callable[..., T], + *args: Any, + **kwargs: Any, + ) -> "defer.Deferred[T]": """Run a function with a database connection Args: - desc (str): description for the transaction, for metrics etc - func (func): function to be run. Passed a database cursor object + desc: description for the transaction, for metrics etc + func: function to be run. Passed a database cursor object as well as *args and **kwargs *args: positional args to be passed to func **kwargs: named args to be passed to func @@ -473,7 +500,7 @@ def run_db_interaction(self, desc, func, *args, **kwargs): def complete_sso_login( self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str - ): + ) -> None: """Complete a SSO login by redirecting the user to a page to confirm whether they want their access token sent to `client_redirect_url`, or redirect them to that URL with a token directly if the URL matches with one of the whitelisted clients. @@ -501,7 +528,7 @@ async def complete_sso_login_async( client_redirect_url: str, new_user: bool = False, auth_provider_id: str = "", - ): + ) -> None: """Complete a SSO login by redirecting the user to a page to confirm whether they want their access token sent to `client_redirect_url`, or redirect them to that URL with a token directly if the URL matches with one of the whitelisted clients. @@ -635,11 +662,11 @@ def looping_background_call( self, f: Callable, msec: float, - *args, + *args: Any, desc: Optional[str] = None, run_on_all_instances: bool = False, - **kwargs, - ): + **kwargs: Any, + ) -> None: """Wraps a function as a background process and calls it repeatedly. NOTE: Will only run on the instance that is configured to run @@ -684,7 +711,7 @@ async def send_mail( subject: str, html: str, text: str, - ): + ) -> None: """Send an email on behalf of the homeserver. Args: