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

Commit 75ca0a6

Browse files
reivilibreclokep
andauthored
Annotate log_function decorator (#10943)
Co-authored-by: Patrick Cloke <clokep@users.noreply.github.com>
1 parent 4e393af commit 75ca0a6

File tree

12 files changed

+58
-18
lines changed

12 files changed

+58
-18
lines changed

changelog.d/10943.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add type annotations for the `log_function` decorator.

synapse/federation/federation_client.py

Lines changed: 15 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -227,7 +227,7 @@ async def claim_client_keys(
227227
)
228228

229229
async def backfill(
230-
self, dest: str, room_id: str, limit: int, extremities: Iterable[str]
230+
self, dest: str, room_id: str, limit: int, extremities: Collection[str]
231231
) -> Optional[List[EventBase]]:
232232
"""Requests some more historic PDUs for the given room from the
233233
given destination server.
@@ -237,6 +237,8 @@ async def backfill(
237237
room_id: The room_id to backfill.
238238
limit: The maximum number of events to return.
239239
extremities: our current backwards extremities, to backfill from
240+
Must be a Collection that is falsy when empty.
241+
(Iterable is not enough here!)
240242
"""
241243
logger.debug("backfill extrem=%s", extremities)
242244

@@ -250,11 +252,22 @@ async def backfill(
250252

251253
logger.debug("backfill transaction_data=%r", transaction_data)
252254

255+
if not isinstance(transaction_data, dict):
256+
# TODO we probably want an exception type specific to federation
257+
# client validation.
258+
raise TypeError("Backfill transaction_data is not a dict.")
259+
260+
transaction_data_pdus = transaction_data.get("pdus")
261+
if not isinstance(transaction_data_pdus, list):
262+
# TODO we probably want an exception type specific to federation
263+
# client validation.
264+
raise TypeError("transaction_data.pdus is not a list.")
265+
253266
room_version = await self.store.get_room_version(room_id)
254267

255268
pdus = [
256269
event_from_pdu_json(p, room_version, outlier=False)
257-
for p in transaction_data["pdus"]
270+
for p in transaction_data_pdus
258271
]
259272

260273
# Check signatures and hash of pdus, removing any from the list that fail checks

synapse/federation/federation_server.py

Lines changed: 6 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -295,14 +295,16 @@ async def _handle_incoming_transaction(
295295
Returns:
296296
HTTP response code and body
297297
"""
298-
response = await self.transaction_actions.have_responded(origin, transaction)
298+
existing_response = await self.transaction_actions.have_responded(
299+
origin, transaction
300+
)
299301

300-
if response:
302+
if existing_response:
301303
logger.debug(
302304
"[%s] We've already responded to this request",
303305
transaction.transaction_id,
304306
)
305-
return response
307+
return existing_response
306308

307309
logger.debug("[%s] Transaction is new", transaction.transaction_id)
308310

@@ -632,7 +634,7 @@ async def on_send_leave_request(
632634

633635
async def on_make_knock_request(
634636
self, origin: str, room_id: str, user_id: str, supported_versions: List[str]
635-
) -> Dict[str, Union[EventBase, str]]:
637+
) -> JsonDict:
636638
"""We've received a /make_knock/ request, so we create a partial knock
637639
event for the room and hand that back, along with the room version, to the knocking
638640
homeserver. We do *not* persist or process this event until the other server has

synapse/federation/sender/transaction_manager.py

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -149,7 +149,6 @@ def json_data_cb() -> JsonDict:
149149
)
150150
except HttpResponseException as e:
151151
code = e.code
152-
response = e.response
153152

154153
set_tag(tags.ERROR, True)
155154

synapse/federation/transport/client.py

Lines changed: 18 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,19 @@
1515

1616
import logging
1717
import urllib
18-
from typing import Any, Callable, Dict, Iterable, List, Mapping, Optional, Tuple, Union
18+
from typing import (
19+
Any,
20+
Awaitable,
21+
Callable,
22+
Collection,
23+
Dict,
24+
Iterable,
25+
List,
26+
Mapping,
27+
Optional,
28+
Tuple,
29+
Union,
30+
)
1931

2032
import attr
2133
import ijson
@@ -100,15 +112,17 @@ async def get_event(
100112

101113
@log_function
102114
async def backfill(
103-
self, destination: str, room_id: str, event_tuples: Iterable[str], limit: int
115+
self, destination: str, room_id: str, event_tuples: Collection[str], limit: int
104116
) -> Optional[JsonDict]:
105117
"""Requests `limit` previous PDUs in a given context before list of
106118
PDUs.
107119
108120
Args:
109121
destination
110122
room_id
111-
event_tuples
123+
event_tuples:
124+
Must be a Collection that is falsy when empty.
125+
(Iterable is not enough here!)
112126
limit
113127
114128
Returns:
@@ -786,7 +800,7 @@ async def accept_group_invite(
786800
@log_function
787801
def join_group(
788802
self, destination: str, group_id: str, user_id: str, content: JsonDict
789-
) -> JsonDict:
803+
) -> Awaitable[JsonDict]:
790804
"""Attempts to join a group"""
791805
path = _create_v1_path("/groups/%s/users/%s/join", group_id, user_id)
792806

synapse/handlers/directory.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -245,7 +245,7 @@ async def get_association(self, room_alias: RoomAlias) -> JsonDict:
245245
servers = result.servers
246246
else:
247247
try:
248-
fed_result = await self.federation.make_query(
248+
fed_result: Optional[JsonDict] = await self.federation.make_query(
249249
destination=room_alias.domain,
250250
query_type="directory",
251251
args={"room_alias": room_alias.to_string()},

synapse/handlers/federation_event.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -477,7 +477,7 @@ async def process_remote_join(
477477

478478
@log_function
479479
async def backfill(
480-
self, dest: str, room_id: str, limit: int, extremities: Iterable[str]
480+
self, dest: str, room_id: str, limit: int, extremities: Collection[str]
481481
) -> None:
482482
"""Trigger a backfill request to `dest` for the given `room_id`
483483

synapse/handlers/presence.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,7 @@
5252
from synapse.api.constants import EventTypes, Membership, PresenceState
5353
from synapse.api.errors import SynapseError
5454
from synapse.api.presence import UserPresenceState
55+
from synapse.appservice import ApplicationService
5556
from synapse.events.presence_router import PresenceRouter
5657
from synapse.logging.context import run_in_background
5758
from synapse.logging.utils import log_function
@@ -1551,6 +1552,7 @@ async def get_new_events(
15511552
is_guest: bool = False,
15521553
explicit_room_id: Optional[str] = None,
15531554
include_offline: bool = True,
1555+
service: Optional[ApplicationService] = None,
15541556
) -> Tuple[List[UserPresenceState], int]:
15551557
# The process for getting presence events are:
15561558
# 1. Get the rooms the user is in.

synapse/handlers/profile.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,7 +456,11 @@ async def _update_remote_profile_cache(self) -> None:
456456
continue
457457

458458
new_name = profile.get("displayname")
459+
if not isinstance(new_name, str):
460+
new_name = None
459461
new_avatar = profile.get("avatar_url")
462+
if not isinstance(new_avatar, str):
463+
new_avatar = None
460464

461465
# We always hit update to update the last_check timestamp
462466
await self.store.update_remote_profile_cache(user_id, new_name, new_avatar)

synapse/logging/utils.py

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
import logging
1717
from functools import wraps
1818
from inspect import getcallargs
19+
from typing import Callable, TypeVar, cast
1920

2021
_TIME_FUNC_ID = 0
2122

@@ -41,7 +42,10 @@ def _log_debug_as_f(f, msg, msg_args):
4142
logger.handle(record)
4243

4344

44-
def log_function(f):
45+
F = TypeVar("F", bound=Callable)
46+
47+
48+
def log_function(f: F) -> F:
4549
"""Function decorator that logs every call to that function."""
4650
func_name = f.__name__
4751

@@ -69,4 +73,4 @@ def format(value):
6973
return f(*args, **kwargs)
7074

7175
wrapped.__name__ = func_name
72-
return wrapped
76+
return cast(F, wrapped)

0 commit comments

Comments
 (0)