Replace return True/False with try/except (fixes #194)#1184
Replace return True/False with try/except (fixes #194)#1184acul71 merged 15 commits intolibp2p:mainfrom
Conversation
|
@parth-soni07 : Looks great. CCing @acul71 and @sumanjeet0012 for their feedback. We can merge it before the upcoming release on Monday. Please add a newsfragment. |
hello @seetadev, I have already pushed a newsfragment in this PR let me know if it needs any changes! Thank You |
Can you please elaborate on this issues:
AI PR Review: #11841. Summary of Changes
2. Branch Sync Status and Merge ConflictsBranch Sync Status
Merge Conflict Analysis
3. Strengths
4. Issues FoundCritical
Major
diff --git a/libp2p/transport/tcp/tcp.py b/libp2p/transport/tcp/tcp.py
@@ async def listen(self, maddr: Multiaddr, nursery: trio.Nursery) -> None:
- started_listeners = await nursery.start(
- serve_tcp,
- handler,
- tcp_port,
- host_str,
- )
+ try:
+ started_listeners = await nursery.start(
+ serve_tcp,
+ handler,
+ tcp_port,
+ host_str,
+ )
+ except Exception as error:
+ error_msg = (
+ f"Failed to start TCP listener for {maddr}: {error}"
+ )
+ logger.error(error_msg)
+ raise OpenConnectionError(error_msg) from errorMinor
diff --git a/libp2p/abc.py b/libp2p/abc.py
@@ class IListener(ABC):
- Raises
- ------
- OpenConnectionError
- If listening fails (e.g. missing/invalid port or failed start).
+ Raises
+ ------
+ Exception
+ Transport-specific listener exception, such as
+ ``OpenConnectionError`` (TCP/WebSocket) or ``QUICListenError``.5. Security Review
6. Documentation and Examples
7. Newsfragment Requirement
8. Tests and ValidationCommand Results
Warnings/Observations from Captured Logs
Coverage of Changed Behavior
9. Recommendations for Improvement
10. Questions for the Author
11. Overall Assessment
|
|
Hello @parth-soni07 what's the status of this PR ? |
Hey @acul71, I am having a look at the points you shared in the feedback, will be updating you as soon as I can. Thank you for your patience! |
…nd generalize IListener.listen docstring
|
hey @acul71, thanks for the feedback you shared. Here is the summary of the fixes relevant to the feedback. Issue 1:
|
Thanks @parth-soni07 for the detailed follow-up and fixes. I verified the two concerns:
The added bind-failure regression test also looks good. This addresses my earlier feedback from my side. |
Add targeted assertions for the bool-to-exception API migration so listener success paths assert None returns and unsupported stream deadlines explicitly raise NotImplementedError across QUIC and Yamux. Made-with: Cursor
|
Hello @seetadev @pacrob ########################## Hi @parth-soni07, thanks for the updates! Sorry it took me a while to get back to you; I've been buried in PR reviews lately. I added some tests—hope you dig them.
Priority examples:
Please include:
Suggested logging format: source venv/bin/activate
python <example_path>.py ... 2>&1 | tee /tmp/examples/example-<name>.log |
Strip dots from matrix python versions in the Windows tox command so jobs target existing envs like py311-core instead of invalid names like py3.11-core. Made-with: Cursor
…ible output - wss_demo: use print(flush=True) instead of logger for server/client output (logging may be suppressed by libp2p) - example_quic_transport: add flush=True to prints for unbuffered output - quic/listener: fix getsockname() unpack for IPv6 (use [:2] for host, port) Made-with: Cursor
What was wrong?
Issue #194
How was it fixed?
listen()– RaiseOpenConnectionErroron missing/invalid port or failed start instead of returning False; addedtcp_port_strisNonecheck before int() for type safety.listen()return type changed from ->boolto ->None; docstring updated to describe raising on failure.listen()now returns None and raises on failure; removed return True.set_deadline(),set_read_deadline(),set_write_deadline()raiseValueErrorfor negative ttl instead of returning False; ABCset_deadline()updated to ->None.set_stream_handler()– Validateinput: raise HostExceptionfor empty/whitespaceprotocol_id or Nonehandler.set_deadline()and swarmregister_notifee()docstrings updated so they no longer claim aFalsereturn.pytest.raises(ValueError)for invalid ttl; host: test empty protocol_id and None handler; QUIC/websocket: dropsuccess = await listener.listen() / assert success.example_mplex_timeouts.pyusestry/exceptValueError for invalid ttl instead of checking a return value.tcp.pyfixed by shortening the :raises docstring line; test handler made async to satisfy THandler.Refactors selected APIs to raise exceptions on failure instead of returning
True/False, so callers use try/except instead of checking return values.Summary
None).try/except.Changes
1. Listener
listen()(IListener and all implementations)async def listen(...) -> boolreturnedTrueon success,Falseon failure.async def listen(...) -> None; raises (e.g.OpenConnectionError,QUICListenError) on failure.Updated: TCP, QUIC, WebSocket, CircuitV2 listeners + ABC
IListenerinlibp2p/abc.py.2. Mplex stream deadline methods
set_deadline(),set_read_deadline(),set_write_deadline()returnedFalsefor invalidttl(e.g. negative).None; raiseValueErrorfor invalidttl.Updated:
libp2p/stream_muxer/mplex/mplex_stream.py+ ABC inlibp2p/abc.py.3. BasicHost
set_stream_handler()protocol_idorNonehandler; docstring said "return true if successful".HostExceptionfor empty/whitespaceprotocol_idorNonehandler. No boolean return.Updated:
libp2p/host/basic_host.py.4. TCP transport
listen()Falseon missing/invalid port or failed start.OpenConnectionErrorwith a clear message. Docstring shortened for line length (E501).Updated:
libp2p/transport/tcp/tcp.py.5. Docstrings only
set_deadline()and swarmregister_notifee(): docstrings updated so they no longer claim aFalsereturn.is_closed: docstring clarified.Tests
test_tcp_listener_raises_on_missing_port— assertsOpenConnectionErrorwhen port is missing.pytest.raises(ValueError)for invalidttl; valid calls expect no exception.test_set_stream_handler_raises_on_empty_protocol_id,test_set_stream_handler_raises_on_null_handler.success = await listener.listen(...); assert success.News fragment
See
newsfragments/194.bugfix.rst.