Skip to content

Commit 21dd467

Browse files
committed
Fixed variable imports
1 parent 029dcfc commit 21dd467

File tree

6 files changed

+121
-38
lines changed

6 files changed

+121
-38
lines changed

libp2p/relay/circuit_v2/config.py

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,35 @@
4646
RESERVATION_REFRESH_THRESHOLD = 0.8 # Refresh at 80% of TTL
4747
MAX_CONCURRENT_RESERVATIONS = 2
4848

49+
# Timeout constants for different components
50+
DEFAULT_DISCOVERY_STREAM_TIMEOUT = 10 # seconds
51+
DEFAULT_PEER_PROTOCOL_TIMEOUT = 5 # seconds
52+
DEFAULT_PROTOCOL_READ_TIMEOUT = 15 # seconds
53+
DEFAULT_PROTOCOL_WRITE_TIMEOUT = 15 # seconds
54+
DEFAULT_PROTOCOL_CLOSE_TIMEOUT = 10 # seconds
55+
DEFAULT_DCUTR_READ_TIMEOUT = 30 # seconds
56+
DEFAULT_DCUTR_WRITE_TIMEOUT = 30 # seconds
57+
DEFAULT_DIAL_TIMEOUT = 10 # seconds
58+
59+
60+
@dataclass
61+
class TimeoutConfig:
62+
"""Timeout configuration for different Circuit Relay v2 components."""
63+
64+
# Discovery timeouts
65+
discovery_stream_timeout: int = DEFAULT_DISCOVERY_STREAM_TIMEOUT
66+
peer_protocol_timeout: int = DEFAULT_PEER_PROTOCOL_TIMEOUT
67+
68+
# Core protocol timeouts
69+
protocol_read_timeout: int = DEFAULT_PROTOCOL_READ_TIMEOUT
70+
protocol_write_timeout: int = DEFAULT_PROTOCOL_WRITE_TIMEOUT
71+
protocol_close_timeout: int = DEFAULT_PROTOCOL_CLOSE_TIMEOUT
72+
73+
# DCUtR timeouts
74+
dcutr_read_timeout: int = DEFAULT_DCUTR_READ_TIMEOUT
75+
dcutr_write_timeout: int = DEFAULT_DCUTR_WRITE_TIMEOUT
76+
dial_timeout: int = DEFAULT_DIAL_TIMEOUT
77+
4978

5079
# Relay roles enum
5180
class RelayRole(Flag):
@@ -83,6 +112,9 @@ class RelayConfig:
83112
max_circuit_duration: int = DEFAULT_MAX_CIRCUIT_DURATION
84113
max_circuit_bytes: int = DEFAULT_MAX_CIRCUIT_BYTES
85114

115+
# Timeout configuration
116+
timeouts: TimeoutConfig = field(default_factory=TimeoutConfig)
117+
86118
# ---------------------------------------------------------------------
87119
# Backwards-compat boolean helpers. Existing code that still accesses
88120
# ``cfg.enable_hop, cfg.enable_stop, cfg.enable_client`` will continue to work.

libp2p/relay/circuit_v2/dcutr.py

Lines changed: 29 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -29,6 +29,11 @@
2929
from libp2p.peer.peerinfo import (
3030
PeerInfo,
3131
)
32+
from libp2p.relay.circuit_v2.config import (
33+
DEFAULT_DCUTR_READ_TIMEOUT,
34+
DEFAULT_DCUTR_WRITE_TIMEOUT,
35+
DEFAULT_DIAL_TIMEOUT,
36+
)
3237
from libp2p.relay.circuit_v2.nat import (
3338
ReachabilityChecker,
3439
)
@@ -47,11 +52,7 @@
4752
# Maximum message size for DCUtR (4KiB as per spec)
4853
MAX_MESSAGE_SIZE = 4 * 1024
4954

50-
# Timeouts
51-
STREAM_READ_TIMEOUT = 30 # seconds
52-
STREAM_WRITE_TIMEOUT = 30 # seconds
53-
DIAL_TIMEOUT = 10 # seconds
54-
55+
# DCUtR protocol constants
5556
# Maximum number of hole punch attempts per peer
5657
MAX_HOLE_PUNCH_ATTEMPTS = 5
5758

@@ -70,18 +71,33 @@ class DCUtRProtocol(Service):
7071
hole punching, after they have established an initial connection through a relay.
7172
"""
7273

73-
def __init__(self, host: IHost):
74+
def __init__(
75+
self,
76+
host: IHost,
77+
read_timeout: int = DEFAULT_DCUTR_READ_TIMEOUT,
78+
write_timeout: int = DEFAULT_DCUTR_WRITE_TIMEOUT,
79+
dial_timeout: int = DEFAULT_DIAL_TIMEOUT,
80+
):
7481
"""
7582
Initialize the DCUtR protocol.
7683
7784
Parameters
7885
----------
7986
host : IHost
8087
The libp2p host this protocol is running on
88+
read_timeout : int
89+
Timeout for stream read operations, in seconds
90+
write_timeout : int
91+
Timeout for stream write operations, in seconds
92+
dial_timeout : int
93+
Timeout for dial operations, in seconds
8194
8295
"""
8396
super().__init__()
8497
self.host = host
98+
self.read_timeout = read_timeout
99+
self.write_timeout = write_timeout
100+
self.dial_timeout = dial_timeout
85101
self.event_started = trio.Event()
86102
self._hole_punch_attempts: dict[ID, int] = {}
87103
self._direct_connections: set[ID] = set()
@@ -161,7 +177,7 @@ async def _handle_dcutr_stream(self, stream: INetStream) -> None:
161177

162178
try:
163179
# Read the CONNECT message
164-
with trio.fail_after(STREAM_READ_TIMEOUT):
180+
with trio.fail_after(self.read_timeout):
165181
msg_bytes = await stream.read(MAX_MESSAGE_SIZE)
166182

167183
# Parse the message
@@ -196,7 +212,7 @@ async def _handle_dcutr_stream(self, stream: INetStream) -> None:
196212
response.type = HolePunch.CONNECT
197213
response.ObsAddrs.extend(our_addrs)
198214

199-
with trio.fail_after(STREAM_WRITE_TIMEOUT):
215+
with trio.fail_after(self.write_timeout):
200216
await stream.write(response.SerializeToString())
201217

202218
logger.debug(
@@ -206,7 +222,7 @@ async def _handle_dcutr_stream(self, stream: INetStream) -> None:
206222
)
207223

208224
# Wait for SYNC message
209-
with trio.fail_after(STREAM_READ_TIMEOUT):
225+
with trio.fail_after(self.read_timeout):
210226
sync_bytes = await stream.read(MAX_MESSAGE_SIZE)
211227

212228
# Parse the SYNC message
@@ -300,7 +316,7 @@ async def initiate_hole_punch(self, peer_id: ID) -> bool:
300316
connect_msg.ObsAddrs.extend(our_addrs)
301317

302318
start_time = time.time()
303-
with trio.fail_after(STREAM_WRITE_TIMEOUT):
319+
with trio.fail_after(self.write_timeout):
304320
await stream.write(connect_msg.SerializeToString())
305321

306322
logger.debug(
@@ -310,7 +326,7 @@ async def initiate_hole_punch(self, peer_id: ID) -> bool:
310326
)
311327

312328
# Receive the peer's CONNECT message
313-
with trio.fail_after(STREAM_READ_TIMEOUT):
329+
with trio.fail_after(self.read_timeout):
314330
resp_bytes = await stream.read(MAX_MESSAGE_SIZE)
315331

316332
# Calculate RTT
@@ -349,7 +365,7 @@ async def initiate_hole_punch(self, peer_id: ID) -> bool:
349365
sync_msg = HolePunch()
350366
sync_msg.type = HolePunch.SYNC
351367

352-
with trio.fail_after(STREAM_WRITE_TIMEOUT):
368+
with trio.fail_after(self.write_timeout):
353369
await stream.write(sync_msg.SerializeToString())
354370

355371
logger.debug("Sent SYNC message to %s", peer_id)
@@ -468,7 +484,7 @@ async def _dial_peer(self, peer_id: ID, addr: Multiaddr) -> None:
468484
peer_info = PeerInfo(peer_id, [addr])
469485

470486
# Try to connect with timeout
471-
with trio.fail_after(DIAL_TIMEOUT):
487+
with trio.fail_after(self.dial_timeout):
472488
await self.host.connect(peer_info)
473489

474490
logger.info("Successfully connected to %s at %s", peer_id, addr)

libp2p/relay/circuit_v2/discovery.py

Lines changed: 21 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,11 @@
3131
Service,
3232
)
3333

34+
from .config import (
35+
DEFAULT_DISCOVERY_INTERVAL,
36+
DEFAULT_DISCOVERY_STREAM_TIMEOUT,
37+
DEFAULT_PEER_PROTOCOL_TIMEOUT,
38+
)
3439
from .pb.circuit_pb2 import (
3540
HopMessage,
3641
)
@@ -43,11 +48,8 @@
4348

4449
logger = logging.getLogger("libp2p.relay.circuit_v2.discovery")
4550

46-
# Constants
51+
# Discovery constants
4752
MAX_RELAYS_TO_TRACK = 10
48-
DEFAULT_DISCOVERY_INTERVAL = 60 # seconds
49-
STREAM_TIMEOUT = 10 # seconds
50-
PEER_PROTOCOL_TIMEOUT = 5 # seconds
5153

5254

5355
# Extended interfaces for type checking
@@ -87,6 +89,8 @@ def __init__(
8789
auto_reserve: bool = False,
8890
discovery_interval: int = DEFAULT_DISCOVERY_INTERVAL,
8991
max_relays: int = MAX_RELAYS_TO_TRACK,
92+
stream_timeout: int = DEFAULT_DISCOVERY_STREAM_TIMEOUT,
93+
peer_protocol_timeout: int = DEFAULT_PEER_PROTOCOL_TIMEOUT,
9094
) -> None:
9195
"""
9296
Initialize the discovery service.
@@ -101,13 +105,19 @@ def __init__(
101105
How often to run discovery, in seconds
102106
max_relays : int
103107
Maximum number of relays to track
108+
stream_timeout : int
109+
Timeout for stream operations during discovery, in seconds
110+
peer_protocol_timeout : int
111+
Timeout for checking peer protocol support, in seconds
104112
105113
"""
106114
super().__init__()
107115
self.host = host
108116
self.auto_reserve = auto_reserve
109117
self.discovery_interval = discovery_interval
110118
self.max_relays = max_relays
119+
self.stream_timeout = stream_timeout
120+
self.peer_protocol_timeout = peer_protocol_timeout
111121
self._discovered_relays: dict[ID, RelayInfo] = {}
112122
self._protocol_cache: dict[
113123
ID, set[str]
@@ -167,19 +177,19 @@ async def discover_relays(self) -> None:
167177
continue
168178

169179
# Don't wait too long for protocol info
170-
with trio.move_on_after(PEER_PROTOCOL_TIMEOUT):
180+
with trio.move_on_after(self.peer_protocol_timeout):
171181
if await self._supports_relay_protocol(peer_id):
172182
await self._add_relay(peer_id)
173183

174184
# Limit number of relays we track
175-
if len(self._discovered_relays) > MAX_RELAYS_TO_TRACK:
185+
if len(self._discovered_relays) > self.max_relays:
176186
# Sort by last seen time and keep only the most recent ones
177187
sorted_relays = sorted(
178188
self._discovered_relays.items(),
179189
key=lambda x: x[1].last_seen,
180190
reverse=True,
181191
)
182-
to_remove = sorted_relays[MAX_RELAYS_TO_TRACK:]
192+
to_remove = sorted_relays[self.max_relays :]
183193
for peer_id, _ in to_remove:
184194
del self._discovered_relays[peer_id]
185195

@@ -265,7 +275,7 @@ async def _check_via_peerstore(self, peer_id: ID) -> bool | None:
265275
async def _check_via_direct_connection(self, peer_id: ID) -> bool | None:
266276
"""Check protocol support via direct connection."""
267277
try:
268-
with trio.fail_after(STREAM_TIMEOUT):
278+
with trio.fail_after(self.stream_timeout):
269279
stream = await self.host.new_stream(peer_id, [PROTOCOL_ID])
270280
if stream:
271281
await stream.close()
@@ -371,7 +381,7 @@ async def make_reservation(self, peer_id: ID) -> bool:
371381

372382
# Open a stream to the relay with timeout
373383
try:
374-
with trio.fail_after(STREAM_TIMEOUT):
384+
with trio.fail_after(self.stream_timeout):
375385
stream = await self.host.new_stream(peer_id, [PROTOCOL_ID])
376386
if not stream:
377387
logger.error("Failed to open stream to relay %s", peer_id)
@@ -387,7 +397,7 @@ async def make_reservation(self, peer_id: ID) -> bool:
387397
peer=self.host.get_id().to_bytes(),
388398
)
389399

390-
with trio.fail_after(STREAM_TIMEOUT):
400+
with trio.fail_after(self.stream_timeout):
391401
await stream.write(request.SerializeToString())
392402

393403
# Wait for response
@@ -464,7 +474,7 @@ async def _cleanup_expired(self) -> None:
464474

465475
for peer_id, relay_info in self._discovered_relays.items():
466476
# Check if relay hasn't been seen in a while (3x discovery interval)
467-
if now - relay_info.last_seen > DEFAULT_DISCOVERY_INTERVAL * 3:
477+
if now - relay_info.last_seen > self.discovery_interval * 3:
468478
to_remove.append(peer_id)
469479
continue
470480

0 commit comments

Comments
 (0)