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

Commit 0c3565d

Browse files
authored
Additional type hints for the proxy agent and SRV resolver modules. (#10608)
1 parent 78a70a2 commit 0c3565d

File tree

5 files changed

+41
-25
lines changed

5 files changed

+41
-25
lines changed

changelog.d/10608.misc

+1
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Improve type hints for the proxy agent and SRV resolver modules. Contributed by @dklimpel.

mypy.ini

+3
Original file line numberDiff line numberDiff line change
@@ -28,10 +28,13 @@ files =
2828
synapse/federation,
2929
synapse/groups,
3030
synapse/handlers,
31+
synapse/http/additional_resource.py,
3132
synapse/http/client.py,
3233
synapse/http/federation/matrix_federation_agent.py,
34+
synapse/http/federation/srv_resolver.py,
3335
synapse/http/federation/well_known_resolver.py,
3436
synapse/http/matrixfederationclient.py,
37+
synapse/http/proxyagent.py,
3538
synapse/http/servlet.py,
3639
synapse/http/server.py,
3740
synapse/http/site.py,

synapse/http/additional_resource.py

+10-3
Original file line numberDiff line numberDiff line change
@@ -12,8 +12,15 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414

15+
from typing import TYPE_CHECKING
16+
17+
from twisted.web.server import Request
18+
1519
from synapse.http.server import DirectServeJsonResource
1620

21+
if TYPE_CHECKING:
22+
from synapse.server import HomeServer
23+
1724

1825
class AdditionalResource(DirectServeJsonResource):
1926
"""Resource wrapper for additional_resources
@@ -25,22 +32,22 @@ class AdditionalResource(DirectServeJsonResource):
2532
and exception handling.
2633
"""
2734

28-
def __init__(self, hs, handler):
35+
def __init__(self, hs: "HomeServer", handler):
2936
"""Initialise AdditionalResource
3037
3138
The ``handler`` should return a deferred which completes when it has
3239
done handling the request. It should write a response with
3340
``request.write()``, and call ``request.finish()``.
3441
3542
Args:
36-
hs (synapse.server.HomeServer): homeserver
43+
hs: homeserver
3744
handler ((twisted.web.server.Request) -> twisted.internet.defer.Deferred):
3845
function to be called to handle the request.
3946
"""
4047
super().__init__()
4148
self._handler = handler
4249

43-
def _async_render(self, request):
50+
def _async_render(self, request: Request):
4451
# Cheekily pass the result straight through, so we don't need to worry
4552
# if its an awaitable or not.
4653
return self._handler(request)

synapse/http/federation/srv_resolver.py

+25-20
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@
1616
import logging
1717
import random
1818
import time
19-
from typing import List
19+
from typing import Callable, Dict, List
2020

2121
import attr
2222

@@ -28,35 +28,35 @@
2828

2929
logger = logging.getLogger(__name__)
3030

31-
SERVER_CACHE = {}
31+
SERVER_CACHE: Dict[bytes, List["Server"]] = {}
3232

3333

34-
@attr.s(slots=True, frozen=True)
34+
@attr.s(auto_attribs=True, slots=True, frozen=True)
3535
class Server:
3636
"""
3737
Our record of an individual server which can be tried to reach a destination.
3838
3939
Attributes:
40-
host (bytes): target hostname
41-
port (int):
42-
priority (int):
43-
weight (int):
44-
expires (int): when the cache should expire this record - in *seconds* since
40+
host: target hostname
41+
port:
42+
priority:
43+
weight:
44+
expires: when the cache should expire this record - in *seconds* since
4545
the epoch
4646
"""
4747

48-
host = attr.ib()
49-
port = attr.ib()
50-
priority = attr.ib(default=0)
51-
weight = attr.ib(default=0)
52-
expires = attr.ib(default=0)
48+
host: bytes
49+
port: int
50+
priority: int = 0
51+
weight: int = 0
52+
expires: int = 0
5353

5454

55-
def _sort_server_list(server_list):
55+
def _sort_server_list(server_list: List[Server]) -> List[Server]:
5656
"""Given a list of SRV records sort them into priority order and shuffle
5757
each priority with the given weight.
5858
"""
59-
priority_map = {}
59+
priority_map: Dict[int, List[Server]] = {}
6060

6161
for server in server_list:
6262
priority_map.setdefault(server.priority, []).append(server)
@@ -103,11 +103,16 @@ class SrvResolver:
103103
104104
Args:
105105
dns_client (twisted.internet.interfaces.IResolver): twisted resolver impl
106-
cache (dict): cache object
107-
get_time (callable): clock implementation. Should return seconds since the epoch
106+
cache: cache object
107+
get_time: clock implementation. Should return seconds since the epoch
108108
"""
109109

110-
def __init__(self, dns_client=client, cache=SERVER_CACHE, get_time=time.time):
110+
def __init__(
111+
self,
112+
dns_client=client,
113+
cache: Dict[bytes, List[Server]] = SERVER_CACHE,
114+
get_time: Callable[[], float] = time.time,
115+
):
111116
self._dns_client = dns_client
112117
self._cache = cache
113118
self._get_time = get_time
@@ -116,7 +121,7 @@ async def resolve_service(self, service_name: bytes) -> List[Server]:
116121
"""Look up a SRV record
117122
118123
Args:
119-
service_name (bytes): record to look up
124+
service_name: record to look up
120125
121126
Returns:
122127
a list of the SRV records, or an empty list if none found
@@ -158,7 +163,7 @@ async def resolve_service(self, service_name: bytes) -> List[Server]:
158163
and answers[0].payload
159164
and answers[0].payload.target == dns.Name(b".")
160165
):
161-
raise ConnectError("Service %s unavailable" % service_name)
166+
raise ConnectError(f"Service {service_name!r} unavailable")
162167

163168
servers = []
164169

synapse/http/proxyagent.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -173,7 +173,7 @@ def request(
173173
raise ValueError(f"Invalid URI {uri!r}")
174174

175175
parsed_uri = URI.fromBytes(uri)
176-
pool_key = (parsed_uri.scheme, parsed_uri.host, parsed_uri.port)
176+
pool_key = f"{parsed_uri.scheme!r}{parsed_uri.host!r}{parsed_uri.port}"
177177
request_path = parsed_uri.originForm
178178

179179
should_skip_proxy = False
@@ -199,7 +199,7 @@ def request(
199199
)
200200
# Cache *all* connections under the same key, since we are only
201201
# connecting to a single destination, the proxy:
202-
pool_key = ("http-proxy", self.http_proxy_endpoint)
202+
pool_key = "http-proxy"
203203
endpoint = self.http_proxy_endpoint
204204
request_path = uri
205205
elif (

0 commit comments

Comments
 (0)