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

Commit 7fdc6ce

Browse files
authored
Fix additional type hints. (#9543)
Type hint fixes due to Twisted 21.2.0 adding type hints.
1 parent 075c16b commit 7fdc6ce

File tree

9 files changed

+32
-18
lines changed

9 files changed

+32
-18
lines changed

changelog.d/9543.misc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix incorrect type hints.

synapse/config/logger.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,10 @@
2121
from string import Template
2222

2323
import yaml
24+
from zope.interface import implementer
2425

2526
from twisted.logger import (
27+
ILogObserver,
2628
LogBeginner,
2729
STDLibLogObserver,
2830
eventAsText,
@@ -227,7 +229,8 @@ def factory(*args, **kwargs):
227229

228230
threadlocal = threading.local()
229231

230-
def _log(event):
232+
@implementer(ILogObserver)
233+
def _log(event: dict) -> None:
231234
if "log_text" in event:
232235
if event["log_text"].startswith("DNSDatagramProtocol starting on "):
233236
return

synapse/federation/federation_server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ async def process_pdus_for_room(room_id: str):
361361
logger.error(
362362
"Failed to handle PDU %s",
363363
event_id,
364-
exc_info=(f.type, f.value, f.getTracebackObject()),
364+
exc_info=(f.type, f.value, f.getTracebackObject()), # type: ignore
365365
)
366366

367367
await concurrently_execute(

synapse/handlers/pagination.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -285,7 +285,7 @@ async def _purge_history(
285285
except Exception:
286286
f = Failure()
287287
logger.error(
288-
"[purge] failed", exc_info=(f.type, f.value, f.getTracebackObject())
288+
"[purge] failed", exc_info=(f.type, f.value, f.getTracebackObject()) # type: ignore
289289
)
290290
self._purges_by_id[purge_id].status = PurgeStatus.STATUS_FAILED
291291
finally:

synapse/http/federation/well_known_resolver.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -322,7 +322,8 @@ def _cache_period_from_headers(
322322

323323
def _parse_cache_control(headers: Headers) -> Dict[bytes, Optional[bytes]]:
324324
cache_controls = {}
325-
for hdr in headers.getRawHeaders(b"cache-control", []):
325+
cache_control_headers = headers.getRawHeaders(b"cache-control") or []
326+
for hdr in cache_control_headers:
326327
for directive in hdr.split(b","):
327328
splits = [x.strip() for x in directive.split(b"=", 1)]
328329
k = splits[0].lower()

synapse/logging/context.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -669,7 +669,7 @@ def g(*args, **kwargs):
669669
return g
670670

671671

672-
def run_in_background(f, *args, **kwargs):
672+
def run_in_background(f, *args, **kwargs) -> defer.Deferred:
673673
"""Calls a function, ensuring that the current context is restored after
674674
return from the function, and that the sentinel context is set once the
675675
deferred returned by the function completes.
@@ -697,8 +697,10 @@ def run_in_background(f, *args, **kwargs):
697697
if isinstance(res, types.CoroutineType):
698698
res = defer.ensureDeferred(res)
699699

700+
# At this point we should have a Deferred, if not then f was a synchronous
701+
# function, wrap it in a Deferred for consistency.
700702
if not isinstance(res, defer.Deferred):
701-
return res
703+
return defer.succeed(res)
702704

703705
if res.called and not res.paused:
704706
# The function should have maintained the logcontext, so we can

tests/replication/_base.py

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@
2222
from twisted.internet.task import LoopingCall
2323
from twisted.web.http import HTTPChannel
2424
from twisted.web.resource import Resource
25+
from twisted.web.server import Request, Site
2526

2627
from synapse.app.generic_worker import (
2728
GenericWorkerReplicationHandler,
@@ -32,7 +33,10 @@
3233
from synapse.replication.http import ReplicationRestResource
3334
from synapse.replication.tcp.handler import ReplicationCommandHandler
3435
from synapse.replication.tcp.protocol import ClientReplicationStreamProtocol
35-
from synapse.replication.tcp.resource import ReplicationStreamProtocolFactory
36+
from synapse.replication.tcp.resource import (
37+
ReplicationStreamProtocolFactory,
38+
ServerReplicationStreamProtocol,
39+
)
3640
from synapse.server import HomeServer
3741
from synapse.util import Clock
3842

@@ -59,7 +63,9 @@ def prepare(self, reactor, clock, hs):
5963
# build a replication server
6064
server_factory = ReplicationStreamProtocolFactory(hs)
6165
self.streamer = hs.get_replication_streamer()
62-
self.server = server_factory.buildProtocol(None)
66+
self.server = server_factory.buildProtocol(
67+
None
68+
) # type: ServerReplicationStreamProtocol
6369

6470
# Make a new HomeServer object for the worker
6571
self.reactor.lookups["testserv"] = "1.2.3.4"
@@ -155,9 +161,7 @@ def handle_http_replication_attempt(self) -> SynapseRequest:
155161
request_factory = OneShotRequestFactory()
156162

157163
# Set up the server side protocol
158-
channel = _PushHTTPChannel(self.reactor)
159-
channel.requestFactory = request_factory
160-
channel.site = self.site
164+
channel = _PushHTTPChannel(self.reactor, request_factory, self.site)
161165

162166
# Connect client to server and vice versa.
163167
client_to_server_transport = FakeTransport(
@@ -188,8 +192,9 @@ def assert_request_is_get_repl_stream_updates(
188192
fetching updates for given stream.
189193
"""
190194

195+
path = request.path # type: bytes # type: ignore
191196
self.assertRegex(
192-
request.path,
197+
path,
193198
br"^/_synapse/replication/get_repl_stream_updates/%s/[^/]+$"
194199
% (stream_name.encode("ascii"),),
195200
)
@@ -390,9 +395,7 @@ def _handle_http_replication_attempt(self, hs, repl_port):
390395
request_factory = OneShotRequestFactory()
391396

392397
# Set up the server side protocol
393-
channel = _PushHTTPChannel(self.reactor)
394-
channel.requestFactory = request_factory
395-
channel.site = self._hs_to_site[hs]
398+
channel = _PushHTTPChannel(self.reactor, request_factory, self._hs_to_site[hs])
396399

397400
# Connect client to server and vice versa.
398401
client_to_server_transport = FakeTransport(
@@ -475,9 +478,13 @@ class _PushHTTPChannel(HTTPChannel):
475478
makes it very hard to test.
476479
"""
477480

478-
def __init__(self, reactor: IReactorTime):
481+
def __init__(
482+
self, reactor: IReactorTime, request_factory: Callable[..., Request], site: Site
483+
):
479484
super().__init__()
480485
self.reactor = reactor
486+
self.requestFactory = request_factory
487+
self.site = site
481488

482489
self._pull_to_push_producer = None # type: Optional[_PullToPushProducer]
483490

tests/server.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -188,7 +188,7 @@ def getResourceFor(self, request):
188188

189189
def make_request(
190190
reactor,
191-
site: Site,
191+
site: Union[Site, FakeSite],
192192
method,
193193
path,
194194
content=b"",

tests/test_utils/logging_setup.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ class ToTwistedHandler(logging.Handler):
2828
def emit(self, record):
2929
log_entry = self.format(record)
3030
log_level = record.levelname.lower().replace("warning", "warn")
31-
self.tx_log.emit(
31+
self.tx_log.emit( # type: ignore
3232
twisted.logger.LogLevel.levelWithName(log_level), "{entry}", entry=log_entry
3333
)
3434

0 commit comments

Comments
 (0)