This repository has been archived by the owner on Apr 26, 2024. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 2.1k
More annotations for synapse.logging
, part 1
#10980
Closed
Closed
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -22,21 +22,37 @@ | |
|
||
See doc/log_contexts.rst for details on how this works. | ||
""" | ||
import functools | ||
import inspect | ||
import logging | ||
import threading | ||
import typing | ||
import warnings | ||
from typing import TYPE_CHECKING, Optional, Tuple, TypeVar, Union | ||
from types import TracebackType | ||
from typing import ( | ||
TYPE_CHECKING, | ||
Any, | ||
Callable, | ||
Optional, | ||
Tuple, | ||
Type, | ||
TypeVar, | ||
Union, | ||
cast, | ||
) | ||
|
||
import attr | ||
from typing_extensions import Literal | ||
|
||
from twisted.internet import defer, threads | ||
from twisted.internet.interfaces import IReactorThreads, ThreadPool | ||
|
||
if TYPE_CHECKING: | ||
from synapse.logging.scopecontextmanager import _LogContextScope | ||
|
||
T = TypeVar("T") | ||
F = TypeVar("F", bound=Callable[..., Any]) | ||
|
||
logger = logging.getLogger(__name__) | ||
|
||
try: | ||
|
@@ -66,7 +82,7 @@ def get_thread_resource_usage() -> "Optional[resource._RUsage]": | |
|
||
|
||
# a hook which can be set during testing to assert that we aren't abusing logcontexts. | ||
def logcontext_error(msg: str): | ||
def logcontext_error(msg: str) -> None: | ||
logger.warning(msg) | ||
|
||
|
||
|
@@ -220,28 +236,28 @@ def __init__(self) -> None: | |
self.scope = None | ||
self.tag = None | ||
|
||
def __str__(self): | ||
def __str__(self) -> str: | ||
return "sentinel" | ||
|
||
def copy_to(self, record): | ||
def copy_to(self, record: "LoggingContext") -> None: | ||
pass | ||
|
||
def start(self, rusage: "Optional[resource._RUsage]"): | ||
def start(self, rusage: "Optional[resource._RUsage]") -> None: | ||
pass | ||
|
||
def stop(self, rusage: "Optional[resource._RUsage]"): | ||
def stop(self, rusage: "Optional[resource._RUsage]") -> None: | ||
pass | ||
|
||
def add_database_transaction(self, duration_sec): | ||
def add_database_transaction(self, duration_sec: float) -> None: | ||
pass | ||
|
||
def add_database_scheduled(self, sched_sec): | ||
def add_database_scheduled(self, sched_sec: float) -> None: | ||
pass | ||
|
||
def record_event_fetch(self, event_count): | ||
def record_event_fetch(self, event_count: int) -> None: | ||
pass | ||
|
||
def __bool__(self): | ||
def __bool__(self) -> bool: | ||
return False | ||
|
||
|
||
|
@@ -379,7 +395,12 @@ def __enter__(self) -> "LoggingContext": | |
) | ||
return self | ||
|
||
def __exit__(self, type, value, traceback) -> None: | ||
def __exit__( | ||
self, | ||
type: Optional[Type[BaseException]], | ||
value: Optional[BaseException], | ||
traceback: Optional[TracebackType], | ||
) -> None: | ||
"""Restore the logging context in thread local storage to the state it | ||
was before this context was entered. | ||
Returns: | ||
|
@@ -399,10 +420,8 @@ def __exit__(self, type, value, traceback) -> None: | |
# recorded against the correct metrics. | ||
self.finished = True | ||
|
||
def copy_to(self, record) -> None: | ||
"""Copy logging fields from this context to a log record or | ||
another LoggingContext | ||
""" | ||
def copy_to(self, record: "LoggingContext") -> None: | ||
"""Copy logging fields from this context to another LoggingContext""" | ||
|
||
# we track the current request | ||
record.request = self.request | ||
|
@@ -575,7 +594,7 @@ class LoggingContextFilter(logging.Filter): | |
record. | ||
""" | ||
|
||
def __init__(self, request: str = ""): | ||
def __init__(self, request: str = "") -> None: | ||
self._default_request = request | ||
|
||
def filter(self, record: logging.LogRecord) -> Literal[True]: | ||
|
@@ -626,7 +645,12 @@ def __init__( | |
def __enter__(self) -> None: | ||
self._old_context = set_current_context(self._new_context) | ||
|
||
def __exit__(self, type, value, traceback) -> None: | ||
def __exit__( | ||
self, | ||
type: Optional[Type[BaseException]], | ||
value: Optional[BaseException], | ||
traceback: Optional[TracebackType], | ||
) -> None: | ||
context = set_current_context(self._old_context) | ||
|
||
if context != self._new_context: | ||
|
@@ -711,16 +735,19 @@ def nested_logging_context(suffix: str) -> LoggingContext: | |
) | ||
|
||
|
||
def preserve_fn(f): | ||
def preserve_fn(f: F) -> F: | ||
"""Function decorator which wraps the function with run_in_background""" | ||
|
||
def g(*args, **kwargs): | ||
@functools.wraps(f) | ||
def g(*args: Any, **kwargs: Any) -> Any: | ||
return run_in_background(f, *args, **kwargs) | ||
|
||
return g | ||
return cast(F, g) | ||
|
||
|
||
def run_in_background(f, *args, **kwargs) -> defer.Deferred: | ||
def run_in_background( | ||
f: Callable[..., T], *args: Any, **kwargs: Any | ||
) -> "defer.Deferred[T]": | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This doesn't work if |
||
"""Calls a function, ensuring that the current context is restored after | ||
return from the function, and that the sentinel context is set once the | ||
deferred returned by the function completes. | ||
|
@@ -823,7 +850,9 @@ def _set_context_cb(result: ResultT, context: LoggingContext) -> ResultT: | |
return result | ||
|
||
|
||
def defer_to_thread(reactor, f, *args, **kwargs): | ||
def defer_to_thread( | ||
reactor: IReactorThreads, f: Callable[..., T], *args: Any, **kwargs: Any | ||
) -> "defer.Deferred[T]": | ||
""" | ||
Calls the function `f` using a thread from the reactor's default threadpool and | ||
returns the result as a Deferred. | ||
|
@@ -855,7 +884,13 @@ def defer_to_thread(reactor, f, *args, **kwargs): | |
return defer_to_threadpool(reactor, reactor.getThreadPool(), f, *args, **kwargs) | ||
|
||
|
||
def defer_to_threadpool(reactor, threadpool, f, *args, **kwargs): | ||
def defer_to_threadpool( | ||
reactor: IReactorThreads, | ||
threadpool: ThreadPool, | ||
f: Callable[..., T], | ||
*args: Any, | ||
**kwargs: Any, | ||
) -> "defer.Deferred[T]": | ||
""" | ||
A wrapper for twisted.internet.threads.deferToThreadpool, which handles | ||
logcontexts correctly. | ||
|
@@ -897,7 +932,7 @@ def defer_to_threadpool(reactor, threadpool, f, *args, **kwargs): | |
assert isinstance(curr_context, LoggingContext) | ||
parent_context = curr_context | ||
|
||
def g(): | ||
def g() -> T: | ||
with LoggingContext(str(curr_context), parent_context=parent_context): | ||
return f(*args, **kwargs) | ||
|
||
|
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We might want add a comment noting that the return type of
F
changes into aDeferred[T]
if the original return type was not aDeferred
.I don't think we came to a consensus in #synapse-devs on whether it was okay to use slightly misleading type hints in this kind of situation.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Ahh, I didn't spot that this also happens in
run_in_background
. Hmm, maybe this needs more thought?There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
I think it should be tractable to add this to our mypy plugin to make it correctly convert the return value from awaitable to deferred?