Skip to content

Commit c62a8ef

Browse files
Fix Notifier async callback error handling (#2096)
* Fix async Notifier callback error handling * Add async Notifier error regression tests * Scope Notifier fix to async error handling * Restore unrelated Notifier lines * Narrow task exception type before storing it * Address async Notifier review: avoid double BaseException propagation and cover SocketCAN * test(notifier): exercise interrupt cleanup through public API
1 parent 25c236f commit c62a8ef

3 files changed

Lines changed: 124 additions & 2 deletions

File tree

‎can/notifier.py‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -226,7 +226,7 @@ def _rx_thread(self, bus: BusABC) -> None:
226226
if self._loop:
227227
handle_message: Callable[[Message], Any] = functools.partial(
228228
self._loop.call_soon_threadsafe,
229-
self._on_message_received, # type: ignore[arg-type]
229+
self._on_message_received_with_error_handling, # type: ignore[arg-type]
230230
)
231231
else:
232232
handle_message = self._on_message_received
@@ -251,7 +251,16 @@ def _rx_thread(self, bus: BusABC) -> None:
251251

252252
def _on_message_available(self, bus: BusABC) -> None:
253253
if msg := bus.recv(0):
254+
self._on_message_received_with_error_handling(msg)
255+
256+
def _on_message_received_with_error_handling(self, msg: Message) -> None:
257+
try:
254258
self._on_message_received(msg)
259+
except Exception as exc: # pylint: disable=broad-except
260+
self.exception = exc
261+
if not self._on_error(exc):
262+
raise
263+
logger.debug("suppressed exception: %s", exc)
255264

256265
def _on_message_received(self, msg: Message) -> None:
257266
for callback in self.listeners:
@@ -262,7 +271,22 @@ def _on_message_received(self, msg: Message) -> None:
262271
# Schedule coroutine and keep a reference to the task
263272
task = self._loop.create_task(res)
264273
self._tasks.add(task)
265-
task.add_done_callback(self._tasks.discard)
274+
task.add_done_callback(self._on_task_done)
275+
276+
def _on_task_done(self, task: asyncio.Task) -> None:
277+
self._tasks.discard(task)
278+
if task.cancelled():
279+
return
280+
281+
exc = task.exception()
282+
# BaseException from the task has already escaped the event loop.
283+
if not isinstance(exc, Exception):
284+
return
285+
286+
self.exception = exc
287+
if not self._on_error(exc):
288+
raise exc
289+
logger.debug("suppressed exception: %s", exc)
266290

267291
def _on_error(self, exc: Exception) -> bool:
268292
"""Calls ``on_error()`` for all listeners if they implement it.

‎doc/changelog.d/1912.fixed.rst‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Call ``Listener.on_error()`` and set ``Notifier.exception`` for exceptions raised by synchronous listeners and coroutine callbacks when ``can.Notifier`` runs with an asyncio event loop.

‎test/notifier_test.py‎

Lines changed: 97 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,26 @@
77

88
import can
99

10+
from .config import TEST_INTERFACE_SOCKETCAN
11+
12+
13+
class RaisingListener(can.Listener):
14+
def on_message_received(self, msg: can.Message) -> None:
15+
raise ValueError("listener failed")
16+
17+
18+
class ErrorCollector(can.Listener):
19+
def __init__(self, event: asyncio.Event) -> None:
20+
self.event = event
21+
self.errors: list[Exception] = []
22+
23+
def on_message_received(self, msg: can.Message) -> None:
24+
pass
25+
26+
def on_error(self, exc: Exception) -> None:
27+
self.errors.append(exc)
28+
self.event.set()
29+
1030

1131
class NotifierTest(unittest.TestCase):
1232
def test_single_bus(self):
@@ -166,6 +186,83 @@ async def run_it():
166186

167187
asyncio.run(run_it())
168188

189+
def test_sync_listener_error_calls_on_error_with_loop(self):
190+
asyncio.run(self._sync_listener_error("sync-listener-error", "virtual"))
191+
192+
@unittest.skipUnless(TEST_INTERFACE_SOCKETCAN, "SocketCAN is not available")
193+
def test_sync_listener_error_calls_on_error_with_socketcan(self):
194+
asyncio.run(self._sync_listener_error("vcan0", "socketcan"))
195+
196+
async def _sync_listener_error(self, channel, interface):
197+
event = asyncio.Event()
198+
collector = ErrorCollector(event)
199+
with can.Bus(channel, interface=interface, receive_own_messages=True) as bus:
200+
notifier = can.Notifier(
201+
bus,
202+
[RaisingListener(), collector],
203+
0.1,
204+
loop=asyncio.get_running_loop(),
205+
)
206+
try:
207+
if interface == "socketcan":
208+
self.assertIn(bus.fileno(), notifier._readers)
209+
bus.send(can.Message())
210+
await asyncio.wait_for(event.wait(), 1.0)
211+
self.assertEqual(len(collector.errors), 1)
212+
self.assertIsInstance(collector.errors[0], ValueError)
213+
self.assertIs(notifier.exception, collector.errors[0])
214+
finally:
215+
notifier.stop()
216+
217+
def test_keyboard_interrupt_from_coroutine_stops_notifier(self):
218+
listener = can.BufferedReader()
219+
220+
async def raising_callback(msg: can.Message) -> None:
221+
raise KeyboardInterrupt
222+
223+
async def run_it():
224+
with can.Bus("kbi", interface="virtual", receive_own_messages=True) as bus:
225+
with can.Notifier(
226+
bus,
227+
[raising_callback, listener],
228+
0.1,
229+
loop=asyncio.get_running_loop(),
230+
):
231+
bus.send(can.Message())
232+
await asyncio.sleep(1)
233+
234+
with self.assertRaises(KeyboardInterrupt):
235+
asyncio.run(run_it())
236+
self.assertTrue(listener.is_stopped)
237+
238+
def test_async_listener_error_calls_on_error(self):
239+
async def run_it():
240+
event = asyncio.Event()
241+
collector = ErrorCollector(event)
242+
243+
async def raising_callback(msg: can.Message) -> None:
244+
raise RuntimeError("async listener failed")
245+
246+
with can.Bus(
247+
"async-listener-error", interface="virtual", receive_own_messages=True
248+
) as bus:
249+
notifier = can.Notifier(
250+
bus,
251+
[raising_callback, collector],
252+
0.1,
253+
loop=asyncio.get_running_loop(),
254+
)
255+
try:
256+
bus.send(can.Message())
257+
await asyncio.wait_for(event.wait(), 0.5)
258+
self.assertEqual(len(collector.errors), 1)
259+
self.assertIsInstance(collector.errors[0], RuntimeError)
260+
self.assertIs(notifier.exception, collector.errors[0])
261+
finally:
262+
notifier.stop()
263+
264+
asyncio.run(run_it())
265+
169266

170267
if __name__ == "__main__":
171268
unittest.main()

0 commit comments

Comments
 (0)