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

Commit bd7d398

Browse files
authored
Additional type hints for the sync REST servlet. (#10666)
1 parent 2af6d31 commit bd7d398

File tree

3 files changed

+93
-61
lines changed

3 files changed

+93
-61
lines changed

Diff for: changelog.d/10666.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints to REST servlets.

Diff for: synapse/handlers/sync.py

+11-10
Original file line numberDiff line numberDiff line change
@@ -30,6 +30,7 @@
3030

3131
from synapse.api.constants import AccountDataTypes, EventTypes, Membership
3232
from synapse.api.filtering import FilterCollection
33+
from synapse.api.presence import UserPresenceState
3334
from synapse.api.room_versions import KNOWN_ROOM_VERSIONS
3435
from synapse.events import EventBase
3536
from synapse.logging.context import current_context
@@ -231,7 +232,7 @@ class SyncResult:
231232
"""
232233

233234
next_batch: StreamToken
234-
presence: List[JsonDict]
235+
presence: List[UserPresenceState]
235236
account_data: List[JsonDict]
236237
joined: List[JoinedSyncResult]
237238
invited: List[InvitedSyncResult]
@@ -2177,14 +2178,14 @@ class SyncResultBuilder:
21772178
joined_room_ids: List of rooms the user is joined to
21782179
21792180
# The following mirror the fields in a sync response
2180-
presence (list)
2181-
account_data (list)
2182-
joined (list[JoinedSyncResult])
2183-
invited (list[InvitedSyncResult])
2184-
knocked (list[KnockedSyncResult])
2185-
archived (list[ArchivedSyncResult])
2186-
groups (GroupsSyncResult|None)
2187-
to_device (list)
2181+
presence
2182+
account_data
2183+
joined
2184+
invited
2185+
knocked
2186+
archived
2187+
groups
2188+
to_device
21882189
"""
21892190

21902191
sync_config: SyncConfig
@@ -2193,7 +2194,7 @@ class SyncResultBuilder:
21932194
now_token: StreamToken
21942195
joined_room_ids: FrozenSet[str]
21952196

2196-
presence: List[JsonDict] = attr.Factory(list)
2197+
presence: List[UserPresenceState] = attr.Factory(list)
21972198
account_data: List[JsonDict] = attr.Factory(list)
21982199
joined: List[JoinedSyncResult] = attr.Factory(list)
21992200
invited: List[InvitedSyncResult] = attr.Factory(list)

Diff for: synapse/rest/client/sync.py

+81-51
Original file line numberDiff line numberDiff line change
@@ -14,17 +14,26 @@
1414
import itertools
1515
import logging
1616
from collections import defaultdict
17-
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Tuple
17+
from typing import TYPE_CHECKING, Any, Callable, Dict, List, Optional, Tuple, Union
1818

1919
from synapse.api.constants import Membership, PresenceState
2020
from synapse.api.errors import Codes, StoreError, SynapseError
2121
from synapse.api.filtering import DEFAULT_FILTER_COLLECTION, FilterCollection
22+
from synapse.api.presence import UserPresenceState
2223
from synapse.events.utils import (
2324
format_event_for_client_v2_without_room_id,
2425
format_event_raw,
2526
)
2627
from synapse.handlers.presence import format_user_presence_state
27-
from synapse.handlers.sync import KnockedSyncResult, SyncConfig
28+
from synapse.handlers.sync import (
29+
ArchivedSyncResult,
30+
InvitedSyncResult,
31+
JoinedSyncResult,
32+
KnockedSyncResult,
33+
SyncConfig,
34+
SyncResult,
35+
)
36+
from synapse.http.server import HttpServer
2837
from synapse.http.servlet import RestServlet, parse_boolean, parse_integer, parse_string
2938
from synapse.http.site import SynapseRequest
3039
from synapse.types import JsonDict, StreamToken
@@ -192,14 +201,22 @@ async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
192201
return 200, {}
193202

194203
time_now = self.clock.time_msec()
204+
# We know that the the requester has an access token since appservices
205+
# cannot use sync.
195206
response_content = await self.encode_response(
196207
time_now, sync_result, requester.access_token_id, filter_collection
197208
)
198209

199210
logger.debug("Event formatting complete")
200211
return 200, response_content
201212

202-
async def encode_response(self, time_now, sync_result, access_token_id, filter):
213+
async def encode_response(
214+
self,
215+
time_now: int,
216+
sync_result: SyncResult,
217+
access_token_id: Optional[int],
218+
filter: FilterCollection,
219+
) -> JsonDict:
203220
logger.debug("Formatting events in sync response")
204221
if filter.event_format == "client":
205222
event_formatter = format_event_for_client_v2_without_room_id
@@ -234,7 +251,7 @@ async def encode_response(self, time_now, sync_result, access_token_id, filter):
234251

235252
logger.debug("building sync response dict")
236253

237-
response: dict = defaultdict(dict)
254+
response: JsonDict = defaultdict(dict)
238255
response["next_batch"] = await sync_result.next_batch.to_string(self.store)
239256

240257
if sync_result.account_data:
@@ -274,6 +291,8 @@ async def encode_response(self, time_now, sync_result, access_token_id, filter):
274291
if archived:
275292
response["rooms"][Membership.LEAVE] = archived
276293

294+
# By the time we get here groups is no longer optional.
295+
assert sync_result.groups is not None
277296
if sync_result.groups.join:
278297
response["groups"][Membership.JOIN] = sync_result.groups.join
279298
if sync_result.groups.invite:
@@ -284,7 +303,7 @@ async def encode_response(self, time_now, sync_result, access_token_id, filter):
284303
return response
285304

286305
@staticmethod
287-
def encode_presence(events, time_now):
306+
def encode_presence(events: List[UserPresenceState], time_now: int) -> JsonDict:
288307
return {
289308
"events": [
290309
{
@@ -299,25 +318,27 @@ def encode_presence(events, time_now):
299318
}
300319

301320
async def encode_joined(
302-
self, rooms, time_now, token_id, event_fields, event_formatter
303-
):
321+
self,
322+
rooms: List[JoinedSyncResult],
323+
time_now: int,
324+
token_id: Optional[int],
325+
event_fields: List[str],
326+
event_formatter: Callable[[JsonDict], JsonDict],
327+
) -> JsonDict:
304328
"""
305329
Encode the joined rooms in a sync result
306330
307331
Args:
308-
rooms(list[synapse.handlers.sync.JoinedSyncResult]): list of sync
309-
results for rooms this user is joined to
310-
time_now(int): current time - used as a baseline for age
311-
calculations
312-
token_id(int): ID of the user's auth token - used for namespacing
332+
rooms: list of sync results for rooms this user is joined to
333+
time_now: current time - used as a baseline for age calculations
334+
token_id: ID of the user's auth token - used for namespacing
313335
of transaction IDs
314-
event_fields(list<str>): List of event fields to include. If empty,
336+
event_fields: List of event fields to include. If empty,
315337
all fields will be returned.
316-
event_formatter (func[dict]): function to convert from federation format
338+
event_formatter: function to convert from federation format
317339
to client format
318340
Returns:
319-
dict[str, dict[str, object]]: the joined rooms list, in our
320-
response format
341+
The joined rooms list, in our response format
321342
"""
322343
joined = {}
323344
for room in rooms:
@@ -332,23 +353,26 @@ async def encode_joined(
332353

333354
return joined
334355

335-
async def encode_invited(self, rooms, time_now, token_id, event_formatter):
356+
async def encode_invited(
357+
self,
358+
rooms: List[InvitedSyncResult],
359+
time_now: int,
360+
token_id: Optional[int],
361+
event_formatter: Callable[[JsonDict], JsonDict],
362+
) -> JsonDict:
336363
"""
337364
Encode the invited rooms in a sync result
338365
339366
Args:
340-
rooms(list[synapse.handlers.sync.InvitedSyncResult]): list of
341-
sync results for rooms this user is invited to
342-
time_now(int): current time - used as a baseline for age
343-
calculations
344-
token_id(int): ID of the user's auth token - used for namespacing
367+
rooms: list of sync results for rooms this user is invited to
368+
time_now: current time - used as a baseline for age calculations
369+
token_id: ID of the user's auth token - used for namespacing
345370
of transaction IDs
346-
event_formatter (func[dict]): function to convert from federation format
371+
event_formatter: function to convert from federation format
347372
to client format
348373
349374
Returns:
350-
dict[str, dict[str, object]]: the invited rooms list, in our
351-
response format
375+
The invited rooms list, in our response format
352376
"""
353377
invited = {}
354378
for room in rooms:
@@ -371,7 +395,7 @@ async def encode_knocked(
371395
self,
372396
rooms: List[KnockedSyncResult],
373397
time_now: int,
374-
token_id: int,
398+
token_id: Optional[int],
375399
event_formatter: Callable[[Dict], Dict],
376400
) -> Dict[str, Dict[str, Any]]:
377401
"""
@@ -422,25 +446,26 @@ async def encode_knocked(
422446
return knocked
423447

424448
async def encode_archived(
425-
self, rooms, time_now, token_id, event_fields, event_formatter
426-
):
449+
self,
450+
rooms: List[ArchivedSyncResult],
451+
time_now: int,
452+
token_id: Optional[int],
453+
event_fields: List[str],
454+
event_formatter: Callable[[JsonDict], JsonDict],
455+
) -> JsonDict:
427456
"""
428457
Encode the archived rooms in a sync result
429458
430459
Args:
431-
rooms (list[synapse.handlers.sync.ArchivedSyncResult]): list of
432-
sync results for rooms this user is joined to
433-
time_now(int): current time - used as a baseline for age
434-
calculations
435-
token_id(int): ID of the user's auth token - used for namespacing
460+
rooms: list of sync results for rooms this user is joined to
461+
time_now: current time - used as a baseline for age calculations
462+
token_id: ID of the user's auth token - used for namespacing
436463
of transaction IDs
437-
event_fields(list<str>): List of event fields to include. If empty,
464+
event_fields: List of event fields to include. If empty,
438465
all fields will be returned.
439-
event_formatter (func[dict]): function to convert from federation format
440-
to client format
466+
event_formatter: function to convert from federation format to client format
441467
Returns:
442-
dict[str, dict[str, object]]: The invited rooms list, in our
443-
response format
468+
The archived rooms list, in our response format
444469
"""
445470
joined = {}
446471
for room in rooms:
@@ -456,23 +481,27 @@ async def encode_archived(
456481
return joined
457482

458483
async def encode_room(
459-
self, room, time_now, token_id, joined, only_fields, event_formatter
460-
):
484+
self,
485+
room: Union[JoinedSyncResult, ArchivedSyncResult],
486+
time_now: int,
487+
token_id: Optional[int],
488+
joined: bool,
489+
only_fields: Optional[List[str]],
490+
event_formatter: Callable[[JsonDict], JsonDict],
491+
) -> JsonDict:
461492
"""
462493
Args:
463-
room (JoinedSyncResult|ArchivedSyncResult): sync result for a
464-
single room
465-
time_now (int): current time - used as a baseline for age
466-
calculations
467-
token_id (int): ID of the user's auth token - used for namespacing
494+
room: sync result for a single room
495+
time_now: current time - used as a baseline for age calculations
496+
token_id: ID of the user's auth token - used for namespacing
468497
of transaction IDs
469-
joined (bool): True if the user is joined to this room - will mean
498+
joined: True if the user is joined to this room - will mean
470499
we handle ephemeral events
471-
only_fields(list<str>): Optional. The list of event fields to include.
472-
event_formatter (func[dict]): function to convert from federation format
500+
only_fields: Optional. The list of event fields to include.
501+
event_formatter: function to convert from federation format
473502
to client format
474503
Returns:
475-
dict[str, object]: the room, encoded in our response format
504+
The room, encoded in our response format
476505
"""
477506

478507
def serialize(events):
@@ -508,7 +537,7 @@ def serialize(events):
508537

509538
account_data = room.account_data
510539

511-
result = {
540+
result: JsonDict = {
512541
"timeline": {
513542
"events": serialized_timeline,
514543
"prev_batch": await room.timeline.prev_batch.to_string(self.store),
@@ -519,6 +548,7 @@ def serialize(events):
519548
}
520549

521550
if joined:
551+
assert isinstance(room, JoinedSyncResult)
522552
ephemeral_events = room.ephemeral
523553
result["ephemeral"] = {"events": ephemeral_events}
524554
result["unread_notifications"] = room.unread_notifications
@@ -528,5 +558,5 @@ def serialize(events):
528558
return result
529559

530560

531-
def register_servlets(hs, http_server):
561+
def register_servlets(hs: "HomeServer", http_server: HttpServer) -> None:
532562
SyncRestServlet(hs).register(http_server)

0 commit comments

Comments
 (0)