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

Add most missing type hints to synapse.util #11328

Merged
merged 14 commits into from
Nov 16, 2021
32 changes: 16 additions & 16 deletions synapse/util/async_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@
Generic,
Hashable,
Iterable,
Iterator,
Optional,
Set,
TypeVar,
Expand All @@ -40,7 +41,6 @@
from twisted.internet import defer
from twisted.internet.defer import CancelledError
from twisted.internet.interfaces import IReactorTime
from twisted.python import failure
from twisted.python.failure import Failure

from synapse.logging.context import (
Expand Down Expand Up @@ -78,7 +78,7 @@ def __init__(self, deferred: "defer.Deferred[_T]", consumeErrors: bool = False):
object.__setattr__(self, "_result", None)
object.__setattr__(self, "_observers", [])

def callback(r):
def callback(r: _T) -> _T:
object.__setattr__(self, "_result", (True, r))

# once we have set _result, no more entries will be added to _observers,
Expand All @@ -98,7 +98,7 @@ def callback(r):
)
return r

def errback(f):
def errback(f: Failure) -> Optional[Failure]:
object.__setattr__(self, "_result", (False, f))

# once we have set _result, no more entries will be added to _observers,
Expand All @@ -109,7 +109,7 @@ def errback(f):
for observer in observers:
# This is a little bit of magic to correctly propagate stack
# traces when we `await` on one of the observer deferreds.
f.value.__failure__ = f
f.value.__failure__ = f # type: ignore[union-attr]
try:
observer.errback(f)
except Exception as e:
Expand Down Expand Up @@ -314,7 +314,7 @@ def queue(self, key: Hashable) -> defer.Deferred:
# will release the lock.

@contextmanager
def _ctx_manager(_):
def _ctx_manager(_: None) -> Iterator[None]:
try:
yield
finally:
Expand Down Expand Up @@ -355,7 +355,7 @@ def _await_lock(self, key: Hashable) -> defer.Deferred:
new_defer = make_deferred_yieldable(defer.Deferred())
entry.deferreds[new_defer] = 1

def cb(_r):
def cb(_r: None) -> defer.Deferred:
clokep marked this conversation as resolved.
Show resolved Hide resolved
logger.debug("Acquired linearizer lock %r for key %r", self.name, key)
entry.count += 1

Expand All @@ -371,7 +371,7 @@ def cb(_r):
# code must be synchronous, so this is the only sensible place.)
return self._clock.sleep(0)

def eb(e):
def eb(e: Failure) -> Failure:
logger.info("defer %r got err %r", new_defer, e)
if isinstance(e, CancelledError):
logger.debug(
Expand Down Expand Up @@ -435,7 +435,7 @@ async def read(self, key: str) -> ContextManager:
await make_deferred_yieldable(curr_writer)

@contextmanager
def _ctx_manager():
def _ctx_manager() -> Iterator[None]:
try:
yield
finally:
Expand Down Expand Up @@ -464,7 +464,7 @@ async def write(self, key: str) -> ContextManager:
await make_deferred_yieldable(defer.gatherResults(to_wait_on))

@contextmanager
def _ctx_manager():
def _ctx_manager() -> Iterator[None]:
try:
yield
finally:
Expand Down Expand Up @@ -524,7 +524,7 @@ def time_it_out() -> None:

delayed_call = reactor.callLater(timeout, time_it_out)

def convert_cancelled(value: failure.Failure):
def convert_cancelled(value: Failure) -> Failure:
# if the original deferred was cancelled, and our timeout has fired, then
# the reason it was cancelled was due to our timeout. Turn the CancelledError
# into a TimeoutError.
Expand All @@ -534,19 +534,19 @@ def convert_cancelled(value: failure.Failure):

deferred.addErrback(convert_cancelled)

def cancel_timeout(result):
def cancel_timeout(result: _T) -> _T:
# stop the pending call to cancel the deferred if it's been fired
if delayed_call.active():
delayed_call.cancel()
return result

deferred.addBoth(cancel_timeout)

def success_cb(val):
def success_cb(val: Any) -> None:
clokep marked this conversation as resolved.
Show resolved Hide resolved
if not new_d.called:
new_d.callback(val)

def failure_cb(val):
def failure_cb(val: Failure) -> None:
if not new_d.called:
new_d.errback(val)

Expand All @@ -557,13 +557,13 @@ def failure_cb(val):

# This class can't be generic because it uses slots with attrs.
# See: https://github.com/python-attrs/attrs/issues/313
@attr.s(slots=True, frozen=True)
@attr.s(slots=True, frozen=True, auto_attribs=True)
class DoneAwaitable: # should be: Generic[R]
"""Simple awaitable that returns the provided value."""

value = attr.ib(type=Any) # should be: R
value: Any # should be: R

def __await__(self):
def __await__(self) -> Any:
return self

def __iter__(self) -> "DoneAwaitable":
Expand Down