Replace magic number with named constants

This commit is contained in:
parth-soni07
2025-09-09 13:24:07 +05:30
parent 74f4aaf136
commit 4a36d6efeb
5 changed files with 194 additions and 59 deletions

View File

@ -31,6 +31,9 @@ from libp2p.tools.async_service import (
Service,
)
from .config import (
DEFAULT_DISCOVERY_INTERVAL as CFG_DISCOVERY_INTERVAL,
)
from .pb.circuit_pb2 import (
HopMessage,
)
@ -43,10 +46,11 @@ from .protocol_buffer import (
logger = logging.getLogger("libp2p.relay.circuit_v2.discovery")
# Constants
MAX_RELAYS_TO_TRACK = 10
DEFAULT_DISCOVERY_INTERVAL = 60 # seconds
# Constants (single-source-of-truth)
DEFAULT_DISCOVERY_INTERVAL = CFG_DISCOVERY_INTERVAL
MAX_RELAYS_TO_TRACK = 10 # Still discovery-specific
STREAM_TIMEOUT = 10 # seconds
PEER_PROTOCOL_TIMEOUT = 5 # seconds
# Extended interfaces for type checking
@ -165,20 +169,20 @@ class RelayDiscovery(Service):
self._discovered_relays[peer_id].last_seen = time.time()
continue
# Check if peer supports the relay protocol
with trio.move_on_after(5): # Don't wait too long for protocol info
# Don't wait too long for protocol info
with trio.move_on_after(PEER_PROTOCOL_TIMEOUT):
if await self._supports_relay_protocol(peer_id):
await self._add_relay(peer_id)
# Limit number of relays we track
if len(self._discovered_relays) > self.max_relays:
if len(self._discovered_relays) > MAX_RELAYS_TO_TRACK:
# Sort by last seen time and keep only the most recent ones
sorted_relays = sorted(
self._discovered_relays.items(),
key=lambda x: x[1].last_seen,
reverse=True,
)
to_remove = sorted_relays[self.max_relays :]
to_remove = sorted_relays[MAX_RELAYS_TO_TRACK:]
for peer_id, _ in to_remove:
del self._discovered_relays[peer_id]
@ -463,7 +467,7 @@ class RelayDiscovery(Service):
for peer_id, relay_info in self._discovered_relays.items():
# Check if relay hasn't been seen in a while (3x discovery interval)
if now - relay_info.last_seen > self.discovery_interval * 3:
if now - relay_info.last_seen > DEFAULT_DISCOVERY_INTERVAL * 3:
to_remove.append(peer_id)
continue