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

Commit 5012275

Browse files
authored
Add missing types to opentracing. (#13345)
After this change `synapse.logging` is fully typed.
1 parent 190f49d commit 5012275

File tree

14 files changed

+83
-45
lines changed

14 files changed

+83
-45
lines changed

changelog.d/13328.misc

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1 +1 @@
1-
Add type hints to `trace` decorator.
1+
Add missing type hints to open tracing module.

changelog.d/13345.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Add missing type hints to open tracing module.

mypy.ini

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -84,9 +84,6 @@ disallow_untyped_defs = False
8484
[mypy-synapse.http.matrixfederationclient]
8585
disallow_untyped_defs = False
8686

87-
[mypy-synapse.logging.opentracing]
88-
disallow_untyped_defs = False
89-
9087
[mypy-synapse.metrics._reactor_metrics]
9188
disallow_untyped_defs = False
9289
# This module imports select.epoll. That exists on Linux, but doesn't on macOS.

synapse/federation/transport/server/_base.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -309,7 +309,7 @@ async def new_func(
309309
raise
310310

311311
# update the active opentracing span with the authenticated entity
312-
set_tag("authenticated_entity", origin)
312+
set_tag("authenticated_entity", str(origin))
313313

314314
# if the origin is authenticated and whitelisted, use its span context
315315
# as the parent.

synapse/handlers/device.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -118,8 +118,8 @@ async def get_device(self, user_id: str, device_id: str) -> JsonDict:
118118
ips = await self.store.get_last_client_ip_by_device(user_id, device_id)
119119
_update_device_from_client_ips(device, ips)
120120

121-
set_tag("device", device)
122-
set_tag("ips", ips)
121+
set_tag("device", str(device))
122+
set_tag("ips", str(ips))
123123

124124
return device
125125

@@ -170,7 +170,7 @@ async def get_user_ids_changed(
170170
"""
171171

172172
set_tag("user_id", user_id)
173-
set_tag("from_token", from_token)
173+
set_tag("from_token", str(from_token))
174174
now_room_key = self.store.get_room_max_token()
175175

176176
room_ids = await self.store.get_rooms_for_user(user_id)
@@ -795,7 +795,7 @@ async def incoming_device_list_update(
795795
"""
796796

797797
set_tag("origin", origin)
798-
set_tag("edu_content", edu_content)
798+
set_tag("edu_content", str(edu_content))
799799
user_id = edu_content.pop("user_id")
800800
device_id = edu_content.pop("device_id")
801801
stream_id = str(edu_content.pop("stream_id")) # They may come as ints

synapse/handlers/e2e_keys.py

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,8 @@ async def query_devices(
138138
else:
139139
remote_queries[user_id] = device_ids
140140

141-
set_tag("local_key_query", local_query)
142-
set_tag("remote_key_query", remote_queries)
141+
set_tag("local_key_query", str(local_query))
142+
set_tag("remote_key_query", str(remote_queries))
143143

144144
# First get local devices.
145145
# A map of destination -> failure response.
@@ -343,7 +343,7 @@ async def _query_devices_for_destination(
343343
failure = _exception_to_failure(e)
344344
failures[destination] = failure
345345
set_tag("error", True)
346-
set_tag("reason", failure)
346+
set_tag("reason", str(failure))
347347

348348
return
349349

@@ -405,7 +405,7 @@ async def query_local_devices(
405405
Returns:
406406
A map from user_id -> device_id -> device details
407407
"""
408-
set_tag("local_query", query)
408+
set_tag("local_query", str(query))
409409
local_query: List[Tuple[str, Optional[str]]] = []
410410

411411
result_dict: Dict[str, Dict[str, dict]] = {}
@@ -477,8 +477,8 @@ async def claim_one_time_keys(
477477
domain = get_domain_from_id(user_id)
478478
remote_queries.setdefault(domain, {})[user_id] = one_time_keys
479479

480-
set_tag("local_key_query", local_query)
481-
set_tag("remote_key_query", remote_queries)
480+
set_tag("local_key_query", str(local_query))
481+
set_tag("remote_key_query", str(remote_queries))
482482

483483
results = await self.store.claim_e2e_one_time_keys(local_query)
484484

@@ -508,7 +508,7 @@ async def claim_client_keys(destination: str) -> None:
508508
failure = _exception_to_failure(e)
509509
failures[destination] = failure
510510
set_tag("error", True)
511-
set_tag("reason", failure)
511+
set_tag("reason", str(failure))
512512

513513
await make_deferred_yieldable(
514514
defer.gatherResults(
@@ -611,7 +611,7 @@ async def upload_keys_for_user(
611611

612612
result = await self.store.count_e2e_one_time_keys(user_id, device_id)
613613

614-
set_tag("one_time_key_counts", result)
614+
set_tag("one_time_key_counts", str(result))
615615
return {"one_time_key_counts": result}
616616

617617
async def _upload_one_time_keys_for_user(

synapse/handlers/e2e_room_keys.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -14,7 +14,7 @@
1414
# limitations under the License.
1515

1616
import logging
17-
from typing import TYPE_CHECKING, Dict, Optional
17+
from typing import TYPE_CHECKING, Dict, Optional, cast
1818

1919
from typing_extensions import Literal
2020

@@ -97,7 +97,7 @@ async def get_room_keys(
9797
user_id, version, room_id, session_id
9898
)
9999

100-
log_kv(results)
100+
log_kv(cast(JsonDict, results))
101101
return results
102102

103103
@trace

synapse/logging/opentracing.py

Lines changed: 35 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,8 @@ def set_fates(clotho, lachesis, atropos, father="Zues", mother="Themis"):
182182
Type,
183183
TypeVar,
184184
Union,
185+
cast,
186+
overload,
185187
)
186188

187189
import attr
@@ -328,6 +330,7 @@ class _Sentinel(enum.Enum):
328330

329331
P = ParamSpec("P")
330332
R = TypeVar("R")
333+
T = TypeVar("T")
331334

332335

333336
def only_if_tracing(func: Callable[P, R]) -> Callable[P, Optional[R]]:
@@ -343,22 +346,43 @@ def _only_if_tracing_inner(*args: P.args, **kwargs: P.kwargs) -> Optional[R]:
343346
return _only_if_tracing_inner
344347

345348

346-
def ensure_active_span(message: str, ret=None):
349+
@overload
350+
def ensure_active_span(
351+
message: str,
352+
) -> Callable[[Callable[P, R]], Callable[P, Optional[R]]]:
353+
...
354+
355+
356+
@overload
357+
def ensure_active_span(
358+
message: str, ret: T
359+
) -> Callable[[Callable[P, R]], Callable[P, Union[T, R]]]:
360+
...
361+
362+
363+
def ensure_active_span(
364+
message: str, ret: Optional[T] = None
365+
) -> Callable[[Callable[P, R]], Callable[P, Union[Optional[T], R]]]:
347366
"""Executes the operation only if opentracing is enabled and there is an active span.
348367
If there is no active span it logs message at the error level.
349368
350369
Args:
351370
message: Message which fills in "There was no active span when trying to %s"
352371
in the error log if there is no active span and opentracing is enabled.
353-
ret (object): return value if opentracing is None or there is no active span.
372+
ret: return value if opentracing is None or there is no active span.
354373
355-
Returns (object): The result of the func or ret if opentracing is disabled or there
374+
Returns:
375+
The result of the func, falling back to ret if opentracing is disabled or there
356376
was no active span.
357377
"""
358378

359-
def ensure_active_span_inner_1(func):
379+
def ensure_active_span_inner_1(
380+
func: Callable[P, R]
381+
) -> Callable[P, Union[Optional[T], R]]:
360382
@wraps(func)
361-
def ensure_active_span_inner_2(*args, **kwargs):
383+
def ensure_active_span_inner_2(
384+
*args: P.args, **kwargs: P.kwargs
385+
) -> Union[Optional[T], R]:
362386
if not opentracing:
363387
return ret
364388

@@ -464,7 +488,7 @@ def start_active_span(
464488
finish_on_close: bool = True,
465489
*,
466490
tracer: Optional["opentracing.Tracer"] = None,
467-
):
491+
) -> "opentracing.Scope":
468492
"""Starts an active opentracing span.
469493
470494
Records the start time for the span, and sets it as the "active span" in the
@@ -502,7 +526,7 @@ def start_active_span_follows_from(
502526
*,
503527
inherit_force_tracing: bool = False,
504528
tracer: Optional["opentracing.Tracer"] = None,
505-
):
529+
) -> "opentracing.Scope":
506530
"""Starts an active opentracing span, with additional references to previous spans
507531
508532
Args:
@@ -717,7 +741,9 @@ def inject_response_headers(response_headers: Headers) -> None:
717741
response_headers.addRawHeader("Synapse-Trace-Id", f"{trace_id:x}")
718742

719743

720-
@ensure_active_span("get the active span context as a dict", ret={})
744+
@ensure_active_span(
745+
"get the active span context as a dict", ret=cast(Dict[str, str], {})
746+
)
721747
def get_active_span_text_map(destination: Optional[str] = None) -> Dict[str, str]:
722748
"""
723749
Gets a span context as a dict. This can be used instead of manually
@@ -886,7 +912,7 @@ def _tag_args_inner(*args: P.args, **kwargs: P.kwargs) -> R:
886912
for i, arg in enumerate(argspec.args[1:]):
887913
set_tag("ARG_" + arg, args[i]) # type: ignore[index]
888914
set_tag("args", args[len(argspec.args) :]) # type: ignore[index]
889-
set_tag("kwargs", kwargs)
915+
set_tag("kwargs", str(kwargs))
890916
return func(*args, **kwargs)
891917

892918
return _tag_args_inner

synapse/metrics/background_process_metrics.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -235,7 +235,7 @@ async def run() -> Optional[R]:
235235
f"bgproc.{desc}", tags={SynapseTags.REQUEST_ID: str(context)}
236236
)
237237
else:
238-
ctx = nullcontext()
238+
ctx = nullcontext() # type: ignore[assignment]
239239
with ctx:
240240
return await func(*args, **kwargs)
241241
except Exception:

synapse/rest/client/keys.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,9 @@ async def on_GET(self, request: SynapseRequest) -> Tuple[int, JsonDict]:
208208

209209
# We want to enforce they do pass us one, but we ignore it and return
210210
# changes after the "to" as well as before.
211-
set_tag("to", parse_string(request, "to"))
211+
#
212+
# XXX This does not enforce that "to" is passed.
213+
set_tag("to", str(parse_string(request, "to")))
212214

213215
from_token = await StreamToken.from_string(self.store, from_token_string)
214216

0 commit comments

Comments
 (0)