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

Commit af387cf

Browse files
authored
Add type hints to misc. files. (#9676)
1 parent 7e8dc99 commit af387cf

6 files changed

Lines changed: 57 additions & 54 deletions

File tree

changelog.d/9676.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type hints to third party event rules and visibility modules.

mypy.ini

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,9 @@ files =
2020
synapse/crypto,
2121
synapse/event_auth.py,
2222
synapse/events/builder.py,
23-
synapse/events/validator.py,
2423
synapse/events/spamcheck.py,
24+
synapse/events/third_party_rules.py,
25+
synapse/events/validator.py,
2526
synapse/federation,
2627
synapse/groups,
2728
synapse/handlers,
@@ -38,6 +39,7 @@ files =
3839
synapse/push,
3940
synapse/replication,
4041
synapse/rest,
42+
synapse/secrets.py,
4143
synapse/server.py,
4244
synapse/server_notices,
4345
synapse/spam_checker_api,
@@ -71,6 +73,7 @@ files =
7173
synapse/util/metrics.py,
7274
synapse/util/macaroons.py,
7375
synapse/util/stringutils.py,
76+
synapse/visibility.py,
7477
tests/replication,
7578
tests/test_utils,
7679
tests/handlers/test_password_providers.py,

synapse/events/third_party_rules.py

Lines changed: 8 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,15 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515

16-
from typing import Callable, Union
16+
from typing import TYPE_CHECKING, Union
1717

1818
from synapse.events import EventBase
1919
from synapse.events.snapshot import EventContext
2020
from synapse.types import Requester, StateMap
2121

22+
if TYPE_CHECKING:
23+
from synapse.server import HomeServer
24+
2225

2326
class ThirdPartyEventRules:
2427
"""Allows server admins to provide a Python module implementing an extra
@@ -28,7 +31,7 @@ class ThirdPartyEventRules:
2831
behaviours.
2932
"""
3033

31-
def __init__(self, hs):
34+
def __init__(self, hs: "HomeServer"):
3235
self.third_party_rules = None
3336

3437
self.store = hs.get_datastore()
@@ -95,10 +98,9 @@ async def on_create_room(
9598
if self.third_party_rules is None:
9699
return True
97100

98-
ret = await self.third_party_rules.on_create_room(
101+
return await self.third_party_rules.on_create_room(
99102
requester, config, is_requester_admin
100103
)
101-
return ret
102104

103105
async def check_threepid_can_be_invited(
104106
self, medium: str, address: str, room_id: str
@@ -119,10 +121,9 @@ async def check_threepid_can_be_invited(
119121

120122
state_events = await self._get_state_map_for_room(room_id)
121123

122-
ret = await self.third_party_rules.check_threepid_can_be_invited(
124+
return await self.third_party_rules.check_threepid_can_be_invited(
123125
medium, address, state_events
124126
)
125-
return ret
126127

127128
async def check_visibility_can_be_modified(
128129
self, room_id: str, new_visibility: str
@@ -143,7 +144,7 @@ async def check_visibility_can_be_modified(
143144
check_func = getattr(
144145
self.third_party_rules, "check_visibility_can_be_modified", None
145146
)
146-
if not check_func or not isinstance(check_func, Callable):
147+
if not check_func or not callable(check_func):
147148
return True
148149

149150
state_events = await self._get_state_map_for_room(room_id)

synapse/secrets.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,10 @@
2626
import secrets
2727

2828
class Secrets:
29-
def token_bytes(self, nbytes=32):
29+
def token_bytes(self, nbytes: int = 32) -> bytes:
3030
return secrets.token_bytes(nbytes)
3131

32-
def token_hex(self, nbytes=32):
32+
def token_hex(self, nbytes: int = 32) -> str:
3333
return secrets.token_hex(nbytes)
3434

3535

@@ -38,8 +38,8 @@ def token_hex(self, nbytes=32):
3838
import os
3939

4040
class Secrets:
41-
def token_bytes(self, nbytes=32):
41+
def token_bytes(self, nbytes: int = 32) -> bytes:
4242
return os.urandom(nbytes)
4343

44-
def token_hex(self, nbytes=32):
44+
def token_hex(self, nbytes: int = 32) -> str:
4545
return binascii.hexlify(self.token_bytes(nbytes)).decode("ascii")

synapse/storage/state.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -449,7 +449,7 @@ def _get_state_groups_from_groups(
449449
return self.stores.state._get_state_groups_from_groups(groups, state_filter)
450450

451451
async def get_state_for_events(
452-
self, event_ids: List[str], state_filter: StateFilter = StateFilter.all()
452+
self, event_ids: Iterable[str], state_filter: StateFilter = StateFilter.all()
453453
) -> Dict[str, StateMap[EventBase]]:
454454
"""Given a list of event_ids and type tuples, return a list of state
455455
dicts for each event.
@@ -485,7 +485,7 @@ async def get_state_for_events(
485485
return {event: event_to_state[event] for event in event_ids}
486486

487487
async def get_state_ids_for_events(
488-
self, event_ids: List[str], state_filter: StateFilter = StateFilter.all()
488+
self, event_ids: Iterable[str], state_filter: StateFilter = StateFilter.all()
489489
) -> Dict[str, StateMap[str]]:
490490
"""
491491
Get the state dicts corresponding to a list of events, containing the event_ids

synapse/visibility.py

Lines changed: 38 additions & 40 deletions
Original file line numberDiff line numberDiff line change
@@ -13,18 +13,19 @@
1313
# See the License for the specific language governing permissions and
1414
# limitations under the License.
1515
import logging
16-
import operator
16+
from typing import Dict, FrozenSet, List, Optional
1717

1818
from synapse.api.constants import (
1919
AccountDataTypes,
2020
EventTypes,
2121
HistoryVisibility,
2222
Membership,
2323
)
24+
from synapse.events import EventBase
2425
from synapse.events.utils import prune_event
2526
from synapse.storage import Storage
2627
from synapse.storage.state import StateFilter
27-
from synapse.types import get_domain_from_id
28+
from synapse.types import StateMap, get_domain_from_id
2829

2930
logger = logging.getLogger(__name__)
3031

@@ -48,32 +49,32 @@
4849

4950
async def filter_events_for_client(
5051
storage: Storage,
51-
user_id,
52-
events,
53-
is_peeking=False,
54-
always_include_ids=frozenset(),
55-
filter_send_to_client=True,
56-
):
52+
user_id: str,
53+
events: List[EventBase],
54+
is_peeking: bool = False,
55+
always_include_ids: FrozenSet[str] = frozenset(),
56+
filter_send_to_client: bool = True,
57+
) -> List[EventBase]:
5758
"""
5859
Check which events a user is allowed to see. If the user can see the event but its
5960
sender asked for their data to be erased, prune the content of the event.
6061
6162
Args:
6263
storage
63-
user_id(str): user id to be checked
64-
events(list[synapse.events.EventBase]): sequence of events to be checked
65-
is_peeking(bool): should be True if:
64+
user_id: user id to be checked
65+
events: sequence of events to be checked
66+
is_peeking: should be True if:
6667
* the user is not currently a member of the room, and:
6768
* the user has not been a member of the room since the given
6869
events
69-
always_include_ids (set(event_id)): set of event ids to specifically
70+
always_include_ids: set of event ids to specifically
7071
include (unless sender is ignored)
71-
filter_send_to_client (bool): Whether we're checking an event that's going to be
72+
filter_send_to_client: Whether we're checking an event that's going to be
7273
sent to a client. This might not always be the case since this function can
7374
also be called to check whether a user can see the state at a given point.
7475
7576
Returns:
76-
list[synapse.events.EventBase]
77+
The filtered events.
7778
"""
7879
# Filter out events that have been soft failed so that we don't relay them
7980
# to clients.
@@ -90,7 +91,7 @@ async def filter_events_for_client(
9091
AccountDataTypes.IGNORED_USER_LIST, user_id
9192
)
9293

93-
ignore_list = frozenset()
94+
ignore_list = frozenset() # type: FrozenSet[str]
9495
if ignore_dict_content:
9596
ignored_users_dict = ignore_dict_content.get("ignored_users", {})
9697
if isinstance(ignored_users_dict, dict):
@@ -107,19 +108,18 @@ async def filter_events_for_client(
107108
room_id
108109
] = await storage.main.get_retention_policy_for_room(room_id)
109110

110-
def allowed(event):
111+
def allowed(event: EventBase) -> Optional[EventBase]:
111112
"""
112113
Args:
113-
event (synapse.events.EventBase): event to check
114+
event: event to check
114115
115116
Returns:
116-
None|EventBase:
117-
None if the user cannot see this event at all
117+
None if the user cannot see this event at all
118118
119-
a redacted copy of the event if they can only see a redacted
120-
version
119+
a redacted copy of the event if they can only see a redacted
120+
version
121121
122-
the original event if they can see it as normal.
122+
the original event if they can see it as normal.
123123
"""
124124
# Only run some checks if these events aren't about to be sent to clients. This is
125125
# because, if this is not the case, we're probably only checking if the users can
@@ -252,48 +252,46 @@ def allowed(event):
252252

253253
return event
254254

255-
# check each event: gives an iterable[None|EventBase]
255+
# Check each event: gives an iterable of None or (a potentially modified)
256+
# EventBase.
256257
filtered_events = map(allowed, events)
257258

258-
# remove the None entries
259-
filtered_events = filter(operator.truth, filtered_events)
260-
261-
# we turn it into a list before returning it.
262-
return list(filtered_events)
259+
# Turn it into a list and remove None entries before returning.
260+
return [ev for ev in filtered_events if ev]
263261

264262

265263
async def filter_events_for_server(
266264
storage: Storage,
267-
server_name,
268-
events,
269-
redact=True,
270-
check_history_visibility_only=False,
271-
):
265+
server_name: str,
266+
events: List[EventBase],
267+
redact: bool = True,
268+
check_history_visibility_only: bool = False,
269+
) -> List[EventBase]:
272270
"""Filter a list of events based on whether given server is allowed to
273271
see them.
274272
275273
Args:
276274
storage
277-
server_name (str)
278-
events (iterable[FrozenEvent])
279-
redact (bool): Whether to return a redacted version of the event, or
275+
server_name
276+
events
277+
redact: Whether to return a redacted version of the event, or
280278
to filter them out entirely.
281-
check_history_visibility_only (bool): Whether to only check the
279+
check_history_visibility_only: Whether to only check the
282280
history visibility, rather than things like if the sender has been
283281
erased. This is used e.g. during pagination to decide whether to
284282
backfill or not.
285283
286284
Returns
287-
list[FrozenEvent]
285+
The filtered events.
288286
"""
289287

290-
def is_sender_erased(event, erased_senders):
288+
def is_sender_erased(event: EventBase, erased_senders: Dict[str, bool]) -> bool:
291289
if erased_senders and erased_senders[event.sender]:
292290
logger.info("Sender of %s has been erased, redacting", event.event_id)
293291
return True
294292
return False
295293

296-
def check_event_is_visible(event, state):
294+
def check_event_is_visible(event: EventBase, state: StateMap[EventBase]) -> bool:
297295
history = state.get((EventTypes.RoomHistoryVisibility, ""), None)
298296
if history:
299297
visibility = history.content.get(

0 commit comments

Comments
 (0)