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

Commit be16ee5

Browse files
authored
Add type hints to more handlers (#8244)
1 parent 4535e84 commit be16ee5

File tree

5 files changed

+110
-79
lines changed

5 files changed

+110
-79
lines changed

changelog.d/8244.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type hints to pagination, initial sync and events handlers.

mypy.ini

+3
Original file line numberDiff line numberDiff line change
@@ -17,10 +17,13 @@ files =
1717
synapse/handlers/auth.py,
1818
synapse/handlers/cas_handler.py,
1919
synapse/handlers/directory.py,
20+
synapse/handlers/events.py,
2021
synapse/handlers/federation.py,
2122
synapse/handlers/identity.py,
23+
synapse/handlers/initial_sync.py,
2224
synapse/handlers/message.py,
2325
synapse/handlers/oidc_handler.py,
26+
synapse/handlers/pagination.py,
2427
synapse/handlers/presence.py,
2528
synapse/handlers/room.py,
2629
synapse/handlers/room_member.py,

synapse/handlers/events.py

+26-23
Original file line numberDiff line numberDiff line change
@@ -15,29 +15,30 @@
1515

1616
import logging
1717
import random
18+
from typing import TYPE_CHECKING, Iterable, List, Optional
1819

1920
from synapse.api.constants import EventTypes, Membership
2021
from synapse.api.errors import AuthError, SynapseError
2122
from synapse.events import EventBase
2223
from synapse.handlers.presence import format_user_presence_state
2324
from synapse.logging.utils import log_function
24-
from synapse.types import UserID
25+
from synapse.streams.config import PaginationConfig
26+
from synapse.types import JsonDict, UserID
2527
from synapse.visibility import filter_events_for_client
2628

2729
from ._base import BaseHandler
2830

31+
if TYPE_CHECKING:
32+
from synapse.server import HomeServer
33+
34+
2935
logger = logging.getLogger(__name__)
3036

3137

3238
class EventStreamHandler(BaseHandler):
33-
def __init__(self, hs):
39+
def __init__(self, hs: "HomeServer"):
3440
super(EventStreamHandler, self).__init__(hs)
3541

36-
# Count of active streams per user
37-
self._streams_per_user = {}
38-
# Grace timers per user to delay the "stopped" signal
39-
self._stop_timer_per_user = {}
40-
4142
self.distributor = hs.get_distributor()
4243
self.distributor.declare("started_user_eventstream")
4344
self.distributor.declare("stopped_user_eventstream")
@@ -52,14 +53,14 @@ def __init__(self, hs):
5253
@log_function
5354
async def get_stream(
5455
self,
55-
auth_user_id,
56-
pagin_config,
57-
timeout=0,
58-
as_client_event=True,
59-
affect_presence=True,
60-
room_id=None,
61-
is_guest=False,
62-
):
56+
auth_user_id: str,
57+
pagin_config: PaginationConfig,
58+
timeout: int = 0,
59+
as_client_event: bool = True,
60+
affect_presence: bool = True,
61+
room_id: Optional[str] = None,
62+
is_guest: bool = False,
63+
) -> JsonDict:
6364
"""Fetches the events stream for a given user.
6465
"""
6566

@@ -98,7 +99,7 @@ async def get_stream(
9899

99100
# When the user joins a new room, or another user joins a currently
100101
# joined room, we need to send down presence for those users.
101-
to_add = []
102+
to_add = [] # type: List[JsonDict]
102103
for event in events:
103104
if not isinstance(event, EventBase):
104105
continue
@@ -110,7 +111,7 @@ async def get_stream(
110111
# Send down presence for everyone in the room.
111112
users = await self.state.get_current_users_in_room(
112113
event.room_id
113-
)
114+
) # type: Iterable[str]
114115
else:
115116
users = [event.state_key]
116117

@@ -144,20 +145,22 @@ async def get_stream(
144145

145146

146147
class EventHandler(BaseHandler):
147-
def __init__(self, hs):
148+
def __init__(self, hs: "HomeServer"):
148149
super(EventHandler, self).__init__(hs)
149150
self.storage = hs.get_storage()
150151

151-
async def get_event(self, user, room_id, event_id):
152+
async def get_event(
153+
self, user: UserID, room_id: Optional[str], event_id: str
154+
) -> Optional[EventBase]:
152155
"""Retrieve a single specified event.
153156
154157
Args:
155-
user (synapse.types.UserID): The user requesting the event
156-
room_id (str|None): The expected room id. We'll return None if the
158+
user: The user requesting the event
159+
room_id: The expected room id. We'll return None if the
157160
event's room does not match.
158-
event_id (str): The event ID to obtain.
161+
event_id: The event ID to obtain.
159162
Returns:
160-
dict: An event, or None if there is no event matching this ID.
163+
An event, or None if there is no event matching this ID.
161164
Raises:
162165
SynapseError if there was a problem retrieving this event, or
163166
AuthError if the user does not have the rights to inspect this

synapse/handlers/initial_sync.py

+48-32
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
# limitations under the License.
1515

1616
import logging
17+
from typing import TYPE_CHECKING
1718

1819
from twisted.internet import defer
1920

@@ -22,20 +23,25 @@
2223
from synapse.events.validator import EventValidator
2324
from synapse.handlers.presence import format_user_presence_state
2425
from synapse.logging.context import make_deferred_yieldable, run_in_background
26+
from synapse.storage.roommember import RoomsForUser
2527
from synapse.streams.config import PaginationConfig
26-
from synapse.types import StreamToken, UserID
28+
from synapse.types import JsonDict, Requester, StreamToken, UserID
2729
from synapse.util import unwrapFirstError
2830
from synapse.util.async_helpers import concurrently_execute
2931
from synapse.util.caches.response_cache import ResponseCache
3032
from synapse.visibility import filter_events_for_client
3133

3234
from ._base import BaseHandler
3335

36+
if TYPE_CHECKING:
37+
from synapse.server import HomeServer
38+
39+
3440
logger = logging.getLogger(__name__)
3541

3642

3743
class InitialSyncHandler(BaseHandler):
38-
def __init__(self, hs):
44+
def __init__(self, hs: "HomeServer"):
3945
super(InitialSyncHandler, self).__init__(hs)
4046
self.hs = hs
4147
self.state = hs.get_state_handler()
@@ -48,27 +54,25 @@ def __init__(self, hs):
4854

4955
def snapshot_all_rooms(
5056
self,
51-
user_id=None,
52-
pagin_config=None,
53-
as_client_event=True,
54-
include_archived=False,
55-
):
57+
user_id: str,
58+
pagin_config: PaginationConfig,
59+
as_client_event: bool = True,
60+
include_archived: bool = False,
61+
) -> JsonDict:
5662
"""Retrieve a snapshot of all rooms the user is invited or has joined.
5763
5864
This snapshot may include messages for all rooms where the user is
5965
joined, depending on the pagination config.
6066
6167
Args:
62-
user_id (str): The ID of the user making the request.
63-
pagin_config (synapse.api.streams.PaginationConfig): The pagination
64-
config used to determine how many messages *PER ROOM* to return.
65-
as_client_event (bool): True to get events in client-server format.
66-
include_archived (bool): True to get rooms that the user has left
68+
user_id: The ID of the user making the request.
69+
pagin_config: The pagination config used to determine how many
70+
messages *PER ROOM* to return.
71+
as_client_event: True to get events in client-server format.
72+
include_archived: True to get rooms that the user has left
6773
Returns:
68-
A list of dicts with "room_id" and "membership" keys for all rooms
69-
the user is currently invited or joined in on. Rooms where the user
70-
is joined on, may return a "messages" key with messages, depending
71-
on the specified PaginationConfig.
74+
A JsonDict with the same format as the response to `/intialSync`
75+
API
7276
"""
7377
key = (
7478
user_id,
@@ -91,11 +95,11 @@ def snapshot_all_rooms(
9195

9296
async def _snapshot_all_rooms(
9397
self,
94-
user_id=None,
95-
pagin_config=None,
96-
as_client_event=True,
97-
include_archived=False,
98-
):
98+
user_id: str,
99+
pagin_config: PaginationConfig,
100+
as_client_event: bool = True,
101+
include_archived: bool = False,
102+
) -> JsonDict:
99103

100104
memberships = [Membership.INVITE, Membership.JOIN]
101105
if include_archived:
@@ -134,7 +138,7 @@ async def _snapshot_all_rooms(
134138
if limit is None:
135139
limit = 10
136140

137-
async def handle_room(event):
141+
async def handle_room(event: RoomsForUser):
138142
d = {
139143
"room_id": event.room_id,
140144
"membership": event.membership,
@@ -251,17 +255,18 @@ async def handle_room(event):
251255

252256
return ret
253257

254-
async def room_initial_sync(self, requester, room_id, pagin_config=None):
258+
async def room_initial_sync(
259+
self, requester: Requester, room_id: str, pagin_config: PaginationConfig
260+
) -> JsonDict:
255261
"""Capture the a snapshot of a room. If user is currently a member of
256262
the room this will be what is currently in the room. If the user left
257263
the room this will be what was in the room when they left.
258264
259265
Args:
260-
requester(Requester): The user to get a snapshot for.
261-
room_id(str): The room to get a snapshot of.
262-
pagin_config(synapse.streams.config.PaginationConfig):
263-
The pagination config used to determine how many messages to
264-
return.
266+
requester: The user to get a snapshot for.
267+
room_id: The room to get a snapshot of.
268+
pagin_config: The pagination config used to determine how many
269+
messages to return.
265270
Raises:
266271
AuthError if the user wasn't in the room.
267272
Returns:
@@ -305,8 +310,14 @@ async def room_initial_sync(self, requester, room_id, pagin_config=None):
305310
return result
306311

307312
async def _room_initial_sync_parted(
308-
self, user_id, room_id, pagin_config, membership, member_event_id, is_peeking
309-
):
313+
self,
314+
user_id: str,
315+
room_id: str,
316+
pagin_config: PaginationConfig,
317+
membership: Membership,
318+
member_event_id: str,
319+
is_peeking: bool,
320+
) -> JsonDict:
310321
room_state = await self.state_store.get_state_for_events([member_event_id])
311322

312323
room_state = room_state[member_event_id]
@@ -350,8 +361,13 @@ async def _room_initial_sync_parted(
350361
}
351362

352363
async def _room_initial_sync_joined(
353-
self, user_id, room_id, pagin_config, membership, is_peeking
354-
):
364+
self,
365+
user_id: str,
366+
room_id: str,
367+
pagin_config: PaginationConfig,
368+
membership: Membership,
369+
is_peeking: bool,
370+
) -> JsonDict:
355371
current_state = await self.state.get_current_state(room_id=room_id)
356372

357373
# TODO: These concurrently

0 commit comments

Comments
 (0)