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

Commit 12116eb

Browse files
author
David Robertson
committed
disallow-untyped-defs for synapse.module_api
1 parent 0e68a4b commit 12116eb

File tree

2 files changed

+76
-46
lines changed

2 files changed

+76
-46
lines changed

mypy.ini

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,9 @@ disallow_untyped_defs = True
9999
[mypy-synapse.rest.*]
100100
disallow_untyped_defs = True
101101

102+
[mypy-synapse.module_api.*]
103+
disallow_untyped_defs = True
104+
102105
[mypy-synapse.state.*]
103106
disallow_untyped_defs = True
104107

synapse/module_api/__init__.py

Lines changed: 73 additions & 46 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
List,
2525
Optional,
2626
Tuple,
27+
TypeVar,
2728
Union,
2829
)
2930

@@ -60,8 +61,12 @@
6061
from synapse.util.caches.descriptors import cached
6162

6263
if TYPE_CHECKING:
64+
from synapse.handlers.auth import AuthHandler
6365
from synapse.server import HomeServer
6466

67+
68+
T = TypeVar("T")
69+
6570
"""
6671
This package defines the 'stable' API which can be used by extension modules which
6772
are loaded into Synapse.
@@ -100,12 +105,18 @@ class UserIpAndAgent:
100105
last_seen: int
101106

102107

108+
# This is sad: I'd like to express that the arguments to this Callable are
109+
# themselves callable. "Callback protocols" let you do this, but I couldn't find
110+
# a way to do so that mypy agreed was type safe.
111+
RegisterCallbacks = Callable[..., None]
112+
113+
103114
class ModuleApi:
104115
"""A proxy object that gets passed to various plugin modules so they
105116
can register new users etc if necessary.
106117
"""
107118

108-
def __init__(self, hs: "HomeServer", auth_handler):
119+
def __init__(self, hs: "HomeServer", auth_handler: "AuthHandler"):
109120
self._hs = hs
110121

111122
self._store = hs.get_datastore()
@@ -145,26 +156,26 @@ def __init__(self, hs: "HomeServer", auth_handler):
145156
# The following methods should only be called during the module's initialisation.
146157

147158
@property
148-
def register_spam_checker_callbacks(self):
159+
def register_spam_checker_callbacks(self) -> RegisterCallbacks:
149160
"""Registers callbacks for spam checking capabilities."""
150161
return self._spam_checker.register_callbacks
151162

152163
@property
153-
def register_account_validity_callbacks(self):
164+
def register_account_validity_callbacks(self) -> RegisterCallbacks:
154165
"""Registers callbacks for account validity capabilities."""
155166
return self._account_validity_handler.register_account_validity_callbacks
156167

157168
@property
158-
def register_third_party_rules_callbacks(self):
169+
def register_third_party_rules_callbacks(self) -> RegisterCallbacks:
159170
"""Registers callbacks for third party event rules capabilities."""
160171
return self._third_party_event_rules.register_third_party_rules_callbacks
161172

162173
@property
163-
def register_presence_router_callbacks(self):
174+
def register_presence_router_callbacks(self) -> RegisterCallbacks:
164175
"""Registers callbacks for presence router capabilities."""
165176
return self._presence_router.register_presence_router_callbacks
166177

167-
def register_web_resource(self, path: str, resource: IResource):
178+
def register_web_resource(self, path: str, resource: IResource) -> None:
168179
"""Registers a web resource to be served at the given path.
169180
170181
This function should be called during initialisation of the module.
@@ -182,19 +193,14 @@ def register_web_resource(self, path: str, resource: IResource):
182193
# The following methods can be called by the module at any point in time.
183194

184195
@property
185-
def http_client(self):
186-
"""Allows making outbound HTTP requests to remote resources.
187-
188-
An instance of synapse.http.client.SimpleHttpClient
189-
"""
196+
def http_client(self) -> SimpleHttpClient:
197+
"""Allows making outbound HTTP requests to remote resources."""
190198
return self._http_client
191199

192200
@property
193-
def public_room_list_manager(self):
201+
def public_room_list_manager(self) -> "PublicRoomListManager":
194202
"""Allows adding to, removing from and checking the status of rooms in the
195203
public room list.
196-
197-
An instance of synapse.module_api.PublicRoomListManager
198204
"""
199205
return self._public_room_list_manager
200206

@@ -259,17 +265,17 @@ async def is_user_admin(self, user_id: str) -> bool:
259265
"""
260266
return await self._store.is_server_admin(UserID.from_string(user_id))
261267

262-
def get_qualified_user_id(self, username):
268+
def get_qualified_user_id(self, username: str) -> str:
263269
"""Qualify a user id, if necessary
264270
265271
Takes a user id provided by the user and adds the @ and :domain to
266272
qualify it, if necessary
267273
268274
Args:
269-
username (str): provided user id
275+
username: provided user id
270276
271277
Returns:
272-
str: qualified @user:id
278+
qualified @user:id
273279
"""
274280
if username.startswith("@"):
275281
return username
@@ -301,20 +307,25 @@ async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]:
301307
"""
302308
return await self._store.user_get_threepids(user_id)
303309

304-
def check_user_exists(self, user_id):
310+
def check_user_exists(self, user_id: str) -> "defer.Deferred[Optional[str]]":
305311
"""Check if user exists.
306312
307313
Args:
308-
user_id (str): Complete @user:id
314+
user_id: Complete @user:id
309315
310316
Returns:
311-
Deferred[str|None]: Canonical (case-corrected) user_id, or None
317+
Canonical (case-corrected) user_id, or None
312318
if the user is not registered.
313319
"""
314320
return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))
315321

316322
@defer.inlineCallbacks
317-
def register(self, localpart, displayname=None, emails: Optional[List[str]] = None):
323+
def register(
324+
self,
325+
localpart: str,
326+
displayname: Optional[str] = None,
327+
emails: Optional[List[str]] = None,
328+
) -> Generator["defer.Deferred[Any]", Any, Tuple[str, str]]:
318329
"""Registers a new user with given localpart and optional displayname, emails.
319330
320331
Also returns an access token for the new user.
@@ -324,12 +335,12 @@ def register(self, localpart, displayname=None, emails: Optional[List[str]] = No
324335
register_device.
325336
326337
Args:
327-
localpart (str): The localpart of the new user.
328-
displayname (str|None): The displayname of the new user.
329-
emails (List[str]): Emails to bind to the new user.
338+
localpart: The localpart of the new user.
339+
displayname: The displayname of the new user.
340+
emails: Emails to bind to the new user.
330341
331342
Returns:
332-
Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)
343+
a 2-tuple of (user_id, access_token)
333344
"""
334345
logger.warning(
335346
"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
339350
return user_id, access_token
340351

341352
def register_user(
342-
self, localpart, displayname=None, emails: Optional[List[str]] = None
343-
):
353+
self,
354+
localpart: str,
355+
displayname: Optional[str] = None,
356+
emails: Optional[List[str]] = None,
357+
) -> "defer.Deferred[str]":
344358
"""Registers a new user with given localpart and optional displayname, emails.
345359
346360
Args:
347-
localpart (str): The localpart of the new user.
348-
displayname (str|None): The displayname of the new user.
349-
emails (List[str]): Emails to bind to the new user.
361+
localpart: The localpart of the new user.
362+
displayname: The displayname of the new user.
363+
emails: Emails to bind to the new user.
350364
351365
Raises:
352366
SynapseError if there is an error performing the registration. Check the
353367
'errcode' property for more information on the reason for failure
354368
355369
Returns:
356-
defer.Deferred[str]: user_id
370+
user_id
357371
"""
358372
return defer.ensureDeferred(
359373
self._hs.get_registration_handler().register_user(
@@ -363,18 +377,23 @@ def register_user(
363377
)
364378
)
365379

366-
def register_device(self, user_id, device_id=None, initial_display_name=None):
380+
def register_device(
381+
self,
382+
user_id: str,
383+
device_id: Optional[str] = None,
384+
initial_display_name: Optional[str] = None,
385+
) -> "defer.Deferred[Tuple[str, str, Optional[int], Optional[str]]]":
367386
"""Register a device for a user and generate an access token.
368387
369388
Args:
370-
user_id (str): full canonical @user:id
371-
device_id (str|None): The device ID to check, or None to generate
389+
user_id: full canonical @user:id
390+
device_id: The device ID to check, or None to generate
372391
a new one.
373-
initial_display_name (str|None): An optional display name for the
392+
initial_display_name: An optional display name for the
374393
device.
375394
376395
Returns:
377-
defer.Deferred[tuple[str, str]]: Tuple of device ID and access token
396+
Tuple of device ID, access token, access token expiration time and refresh token
378397
"""
379398
return defer.ensureDeferred(
380399
self._hs.get_registration_handler().register_device(
@@ -424,7 +443,9 @@ def generate_short_term_login_token(
424443
)
425444

426445
@defer.inlineCallbacks
427-
def invalidate_access_token(self, access_token):
446+
def invalidate_access_token(
447+
self, access_token: str
448+
) -> Generator["defer.Deferred[Any]", Any, None]:
428449
"""Invalidate an access token for a user
429450
430451
Args:
@@ -454,12 +475,18 @@ def invalidate_access_token(self, access_token):
454475
self._auth_handler.delete_access_token(access_token)
455476
)
456477

457-
def run_db_interaction(self, desc, func, *args, **kwargs):
478+
def run_db_interaction(
479+
self,
480+
desc: str,
481+
func: Callable[..., T],
482+
*args: Any,
483+
**kwargs: Any,
484+
) -> "defer.Deferred[T]":
458485
"""Run a function with a database connection
459486
460487
Args:
461-
desc (str): description for the transaction, for metrics etc
462-
func (func): function to be run. Passed a database cursor object
488+
desc: description for the transaction, for metrics etc
489+
func: function to be run. Passed a database cursor object
463490
as well as *args and **kwargs
464491
*args: positional args to be passed to func
465492
**kwargs: named args to be passed to func
@@ -473,7 +500,7 @@ def run_db_interaction(self, desc, func, *args, **kwargs):
473500

474501
def complete_sso_login(
475502
self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str
476-
):
503+
) -> None:
477504
"""Complete a SSO login by redirecting the user to a page to confirm whether they
478505
want their access token sent to `client_redirect_url`, or redirect them to that
479506
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(
501528
client_redirect_url: str,
502529
new_user: bool = False,
503530
auth_provider_id: str = "<unknown>",
504-
):
531+
) -> None:
505532
"""Complete a SSO login by redirecting the user to a page to confirm whether they
506533
want their access token sent to `client_redirect_url`, or redirect them to that
507534
URL with a token directly if the URL matches with one of the whitelisted clients.
@@ -635,11 +662,11 @@ def looping_background_call(
635662
self,
636663
f: Callable,
637664
msec: float,
638-
*args,
665+
*args: Any,
639666
desc: Optional[str] = None,
640667
run_on_all_instances: bool = False,
641-
**kwargs,
642-
):
668+
**kwargs: Any,
669+
) -> None:
643670
"""Wraps a function as a background process and calls it repeatedly.
644671
645672
NOTE: Will only run on the instance that is configured to run
@@ -684,7 +711,7 @@ async def send_mail(
684711
subject: str,
685712
html: str,
686713
text: str,
687-
):
714+
) -> None:
688715
"""Send an email on behalf of the homeserver.
689716
690717
Args:

0 commit comments

Comments
 (0)