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

Commit

Permalink
disallow-untyped-defs for synapse.module_api
Browse files Browse the repository at this point in the history
  • Loading branch information
David Robertson committed Oct 8, 2021
1 parent 0e68a4b commit 12116eb
Show file tree
Hide file tree
Showing 2 changed files with 76 additions and 46 deletions.
3 changes: 3 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
119 changes: 73 additions & 46 deletions synapse/module_api/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@
List,
Optional,
Tuple,
TypeVar,
Union,
)

Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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()
Expand Down Expand Up @@ -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.
Expand All @@ -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

Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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.
Expand All @@ -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."
Expand All @@ -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(
Expand All @@ -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(
Expand Down Expand Up @@ -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:
Expand Down Expand Up @@ -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
Expand All @@ -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.
Expand Down Expand Up @@ -501,7 +528,7 @@ async def complete_sso_login_async(
client_redirect_url: str,
new_user: bool = False,
auth_provider_id: str = "<unknown>",
):
) -> 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.
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -684,7 +711,7 @@ async def send_mail(
subject: str,
html: str,
text: str,
):
) -> None:
"""Send an email on behalf of the homeserver.
Args:
Expand Down

0 comments on commit 12116eb

Please sign in to comment.