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

disallow-untyped-defs for the module_api #11029

Merged
merged 3 commits into from
Nov 29, 2021
Merged
Show file tree
Hide file tree
Changes from 2 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/11029.misc
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Improve type annotations in `synapse.module_api`.
3 changes: 3 additions & 0 deletions mypy.ini
Original file line number Diff line number Diff line change
Expand Up @@ -166,6 +166,9 @@ disallow_untyped_defs = True
[mypy-synapse.metrics.*]
disallow_untyped_defs = True

[mypy-synapse.module_api.*]
disallow_untyped_defs = True

[mypy-synapse.push.*]
disallow_untyped_defs = True

Expand Down
91 changes: 61 additions & 30 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 @@ -104,6 +105,9 @@
from synapse.app.generic_worker import GenericWorkerSlavedStore
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 @@ -146,6 +150,12 @@ 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]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Is this used anywhere?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

... no. Can't remember where I wanted to use it. Maybe there were changes elsewhere that made this redundant.



class ModuleApi:
"""A proxy object that gets passed to various plugin modules so they
can register new users etc if necessary.
Expand Down Expand Up @@ -307,7 +317,7 @@ def register_password_auth_provider_callbacks(
auth_checkers=auth_checkers,
)

def register_web_resource(self, path: str, resource: Resource):
def register_web_resource(self, path: str, resource: Resource) -> None:
"""Registers a web resource to be served at the given path.

This function should be called during initialisation of the module.
Expand Down Expand Up @@ -432,7 +442,7 @@ def get_qualified_user_id(self, username: str) -> str:
username: provided user id

Returns:
str: qualified @user:id
qualified @user:id
"""
if username.startswith("@"):
return username
Expand Down Expand Up @@ -468,7 +478,7 @@ 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: str):
def check_user_exists(self, user_id: str) -> "defer.Deferred[Optional[str]]":
"""Check if user exists.

Added in Synapse v0.25.0.
Expand All @@ -477,13 +487,18 @@ def check_user_exists(self, user_id: str):
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 @@ -495,12 +510,12 @@ def register(self, localpart, displayname=None, emails: Optional[List[str]] = No
Added in Synapse v0.25.0.

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 @@ -510,23 +525,26 @@ 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.

Added in Synapse v1.2.0.

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 @@ -536,20 +554,25 @@ 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.

Added in Synapse v1.2.0.

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 @@ -603,7 +626,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

Added in Synapse v0.25.0.
Expand Down Expand Up @@ -635,14 +660,20 @@ 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

Added in Synapse v0.25.0.

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 @@ -656,7 +687,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 @@ -686,7 +717,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 @@ -925,11 +956,11 @@ def looping_background_call(
self,
f: Callable,
msec: float,
*args,
*args: object,
desc: Optional[str] = None,
run_on_all_instances: bool = False,
**kwargs,
):
**kwargs: object,
) -> 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 @@ -976,7 +1007,7 @@ async def send_mail(
subject: str,
html: str,
text: str,
):
) -> None:
"""Send an email on behalf of the homeserver.

Added in Synapse v1.39.0.
Expand Down