Skip to content

Commit 55d1de3

Browse files
committed
fix pyrefly typecheck in CI
1 parent f15f7a2 commit 55d1de3

File tree

9 files changed

+87
-156
lines changed

9 files changed

+87
-156
lines changed

libp2p/transport/webrtc/async_bridge.py

Lines changed: 9 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -79,8 +79,7 @@ async def create_offer(
7979
) -> RTCSessionDescription:
8080
"""Create SDP offer with proper async bridging"""
8181
try:
82-
create_offer = aio_as_trio(peer_connection.createOffer)
83-
offer = await create_offer()
82+
offer = await aio_as_trio(peer_connection.createOffer())
8483
logger.debug("Successfully created SDP offer")
8584
return offer
8685
except Exception as e:
@@ -92,8 +91,7 @@ async def create_answer(
9291
) -> RTCSessionDescription:
9392
"""Create SDP answer with proper async bridging"""
9493
try:
95-
create_answer = aio_as_trio(peer_connection.createAnswer)
96-
answer = await create_answer()
94+
answer = await aio_as_trio(peer_connection.createAnswer())
9795
logger.debug("Successfully created SDP answer")
9896
return answer
9997
except Exception as e:
@@ -105,8 +103,7 @@ async def set_local_description(
105103
) -> None:
106104
"""Set local description with proper async bridging"""
107105
try:
108-
set_local = aio_as_trio(peer_connection.setLocalDescription)
109-
await set_local(description)
106+
await aio_as_trio(peer_connection.setLocalDescription(description))
110107
logger.debug("Successfully set local description")
111108
except Exception as e:
112109
logger.error(f"Failed to set local description: {e}")
@@ -117,8 +114,7 @@ async def set_remote_description(
117114
) -> None:
118115
"""Set remote description with proper async bridging"""
119116
try:
120-
set_remote = aio_as_trio(peer_connection.setRemoteDescription)
121-
await set_remote(description)
117+
await aio_as_trio(peer_connection.setRemoteDescription(description))
122118
logger.debug("Successfully set remote description")
123119
except Exception as e:
124120
logger.error(f"Failed to set remote description: {e}")
@@ -129,8 +125,7 @@ async def add_ice_candidate(
129125
) -> None:
130126
"""Add ICE candidate with proper async bridging"""
131127
try:
132-
add_candidate = aio_as_trio(peer_connection.addIceCandidate)
133-
await add_candidate(candidate)
128+
await aio_as_trio(peer_connection.addIceCandidate(candidate))
134129
logger.debug("Successfully added ICE candidate")
135130
except Exception as e:
136131
logger.error(f"Failed to add ICE candidate: {e}")
@@ -139,8 +134,7 @@ async def add_ice_candidate(
139134
async def close_peer_connection(self, peer_connection: RTCPeerConnection) -> None:
140135
"""Close peer connection with proper async bridging"""
141136
try:
142-
close_pc = aio_as_trio(peer_connection.close)
143-
await close_pc()
137+
await aio_as_trio(peer_connection.close())
144138
logger.debug("Successfully closed peer connection")
145139
except Exception as e:
146140
logger.error(f"Failed to close peer connection: {e}")
@@ -149,8 +143,7 @@ async def close_peer_connection(self, peer_connection: RTCPeerConnection) -> Non
149143
async def close_data_channel(self, data_channel: RTCDataChannel) -> None:
150144
"""Close data channel with proper async bridging"""
151145
try:
152-
close_channel = aio_as_trio(data_channel.close)
153-
await close_channel()
146+
await aio_as_trio(data_channel.close)
154147
logger.debug("Successfully closed data channel")
155148
except Exception as e:
156149
logger.error(f"Failed to close data channel: {e}")
@@ -159,8 +152,7 @@ async def close_data_channel(self, data_channel: RTCDataChannel) -> None:
159152
async def send_data(self, data_channel: RTCDataChannel, data: bytes) -> None:
160153
"""Send data through channel with proper async bridging"""
161154
try:
162-
send_data = aio_as_trio(data_channel.send)
163-
await send_data(data)
155+
aio_as_trio(data_channel.send)(data)
164156
logger.debug(f"Successfully sent {len(data)} bytes")
165157
except Exception as e:
166158
logger.error(f"Failed to send data: {e}")
@@ -250,7 +242,6 @@ async def cleanup_webrtc_resources(*resources: Any) -> None:
250242
elif isinstance(resource, RTCDataChannel):
251243
await bridge.close_data_channel(resource)
252244
else:
253-
close_fn = aio_as_trio(resource.close)
254-
await close_fn()
245+
await aio_as_trio(resource.close())
255246
except Exception as e:
256247
logger.warning(f"Error cleaning up resource {type(resource)}: {e}")

libp2p/transport/webrtc/connection.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -147,7 +147,7 @@ def __init__(
147147

148148
# Stream muxing
149149
self._streams: dict[int, WebRTCStream] = {}
150-
self._next_stream_id = (
150+
self._next_stream_id: int = (
151151
1 if is_initiator else 2
152152
) # Odd for initiator, even for responder
153153
self._stream_lock = trio.Lock()

libp2p/transport/webrtc/gen_certificate.py

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22
import datetime
33
import hashlib
44
import logging
5+
from typing import Any
56

67
import base58
78
from cryptography import (
@@ -59,9 +60,10 @@ def generate(cls) -> "WebRTCCertificate":
5960
)
6061

6162
# Create certificate
63+
common_name: Any = "libp2p-webrtc"
6264
subject = issuer = x509.Name(
6365
[
64-
x509.NameAttribute(NameOID.COMMON_NAME, "libp2p-webrtc"),
66+
x509.NameAttribute(NameOID.COMMON_NAME, common_name),
6567
]
6668
)
6769

@@ -151,8 +153,9 @@ def validate_pem_export(self) -> bool:
151153

152154
# 3. Key-certificate matching (RSA-specific validation)
153155
cert_public_key = cert_obj.public_key()
154-
if hasattr(cert_public_key, "public_numbers") and hasattr(
155-
key_obj.public_key(), "public_numbers"
156+
# Only check public_numbers for RSA keys
157+
if isinstance(cert_public_key, rsa.RSAPublicKey) and isinstance(
158+
key_obj.public_key(), rsa.RSAPublicKey
156159
):
157160
if (
158161
cert_public_key.public_numbers()
@@ -235,7 +238,7 @@ def create_webrtc_direct_multiaddr(ip: str, port: int, peer_id: ID) -> Multiaddr
235238
return Multiaddr(f"/ip4/{ip}/udp/{port}/webrtc-direct/p2p/{peer_id}")
236239

237240

238-
def parse_webrtc_maddr(maddr: Multiaddr) -> tuple[str, ID, str]:
241+
def parse_webrtc_maddr(maddr: Multiaddr | str) -> tuple[str, str, str]:
239242
"""
240243
Parse a WebRTC multiaddr like:
241244
/ip4/147.28.186.157/udp/9095/webrtc-direct/certhash/uEiDFVmAomKdAbivdrcIKdXGyuij_ax8b8at0GY_MJXMlwg/p2p/12D3KooWFhXabKDwALpzqMbto94sB7rvmZ6M28hs9Y9xSopDKwQr/p2p-circuit
@@ -248,7 +251,8 @@ def parse_webrtc_maddr(maddr: Multiaddr) -> tuple[str, ID, str]:
248251
if isinstance(maddr, str):
249252
maddr = Multiaddr(maddr)
250253

251-
parts = maddr.to_string().split("/")
254+
# Use str() instead of to_string() method
255+
parts = str(maddr).split("/")
252256

253257
# Get IP (after ip4 or ip6)
254258
ip_idx = parts.index("ip4" if "ip4" in parts else "ip6") + 1

libp2p/transport/webrtc/multiaddr_codecs.py

Lines changed: 6 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,34 +7,33 @@
77

88
import base64
99
from collections.abc import ByteString
10-
from typing import LiteralString
1110

1211

13-
def webrtc_encode(s: LiteralString) -> ByteString:
12+
def webrtc_encode(s: str) -> ByteString:
1413
"""Encode WebRTC protocol component."""
1514
# WebRTC protocol has no value, return empty bytes
1615
return b""
1716

1817

19-
def webrtc_decode(b: ByteString) -> LiteralString:
18+
def webrtc_decode(b: ByteString) -> str:
2019
"""Decode WebRTC protocol component."""
2120
# WebRTC protocol has no value, return empty string
2221
return ""
2322

2423

25-
def webrtc_direct_encode(s: LiteralString) -> ByteString:
24+
def webrtc_direct_encode(s: str) -> ByteString:
2625
"""Encode WebRTC-Direct protocol component."""
2726
# WebRTC-Direct protocol has no value, return empty bytes
2827
return b""
2928

3029

31-
def webrtc_direct_decode(b: ByteString) -> LiteralString:
30+
def webrtc_direct_decode(b: ByteString) -> str:
3231
"""Decode WebRTC-Direct protocol component."""
3332
# WebRTC-Direct protocol has no value, return empty string
3433
return ""
3534

3635

37-
def certhash_encode(s: LiteralString) -> ByteString:
36+
def certhash_encode(s: str) -> ByteString:
3837
"""Encode certificate hash component."""
3938
if not s:
4039
return b""
@@ -59,7 +58,7 @@ def certhash_encode(s: LiteralString) -> ByteString:
5958
return s.encode("utf-8")
6059

6160

62-
def certhash_decode(b: ByteString) -> LiteralString:
61+
def certhash_decode(b: ByteString) -> str:
6362
"""Decode certificate hash component."""
6463
if not b:
6564
return ""

libp2p/transport/webrtc/private_to_private/initiate_connection.py

Lines changed: 22 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -46,12 +46,11 @@ async def initiate_connection(
4646
logger.info(f"Initiating WebRTC connection to {maddr}")
4747

4848
# Parse circuit relay multiaddr to get target peer ID
49-
protocols = maddr.protocols()
49+
protocols = [p for p in maddr.protocols() if p is not None]
5050
target_peer_id = None
5151
for i, protocol in enumerate(protocols):
5252
if protocol.name == "p2p":
5353
if i + 1 < len(protocols) and protocols[i + 1].name == "p2p-circuit":
54-
# This is the relay peer, continue
5554
continue
5655
else:
5756
# This is the target peer
@@ -69,7 +68,20 @@ async def initiate_connection(
6968

7069
try:
7170
# Establish signaling stream through circuit relay
72-
signaling_stream = await host.new_stream(maddr, [SIGNALING_PROTOCOL])
71+
# Note: new_stream expects peer_id, not multiaddr
72+
# We need to extract the relay peer ID from the multiaddr
73+
relay_peer_id = None
74+
for i, protocol in enumerate(protocols):
75+
if protocol.name == "p2p":
76+
if i + 1 < len(protocols) and protocols[i + 1].name == "p2p-circuit":
77+
# This is the relay peer
78+
relay_peer_id = ID.from_base58(maddr.value_for_protocol("p2p"))
79+
break
80+
81+
if not relay_peer_id:
82+
raise WebRTCError(f"Cannot extract relay peer ID from multiaddr: {maddr}")
83+
84+
signaling_stream = await host.new_stream(relay_peer_id, [SIGNALING_PROTOCOL])
7385
logger.info("Established signaling stream through circuit relay")
7486

7587
# Create RTCPeerConnection and data channel using safe operations
@@ -143,13 +155,15 @@ def on_data_channel_error(error: Any) -> None:
143155
connection_failed = trio.Event()
144156

145157
def on_connection_state_change() -> None:
146-
state = peer_connection.connectionState
147-
logger.debug(f"Connection state: {state}")
148-
if state == "failed":
149-
connection_failed.set()
158+
if peer_connection is not None:
159+
state = peer_connection.connectionState
160+
logger.debug(f"Connection state: {state}")
161+
if state == "failed":
162+
connection_failed.set()
150163

151164
# Register connection state handler
152-
peer_connection.on("connectionstatechange", on_connection_state_change)
165+
if peer_connection is not None:
166+
peer_connection.on("connectionstatechange", on_connection_state_change)
153167

154168
# Wait for either success or failure
155169
with trio.move_on_after(timeout) as cancel_scope:

0 commit comments

Comments
 (0)