Stop reconnecting after clean server disconnect

This commit is contained in:
Tanner committed 2026-11-15 15:21:36 +00:00
1 parent 99bb5c98de
commit 8d2374346e
2 files changed
+43 -7

No files matched your search

+16 -6
View File
@@ -417,7 +417,7 @@ def root():
return app.send_static_file('index.html')
def _run_connection_loop(global_state, connector=None, sleep=time.sleep):
"""Retry the client after expected TCP disconnects without killing the API."""
"""Retry transient socket failures, but stop after a clean disconnect."""
connector = connector or connect.main
retry_delay = 1.0
while global_state.get('running', True):
@@ -427,16 +427,26 @@ def _run_connection_loop(global_state, connector=None, sleep=time.sleep):
except KeyboardInterrupt:
global_state.running = False
return
except (OSError, EOFError, ValueError) as exc:
if (isinstance(exc, ValueError) and
str(exc) != 'I/O operation on closed file'):
except EOFError:
global_state.running = False
print('[connection] server closed the connection; not reconnecting',
flush=True)
return
except ValueError as exc:
if str(exc) != 'I/O operation on closed file':
raise
print('[connection] socket closed ({}); will reconnect'.format(exc),
global_state.running = False
print('[connection] connection closed; not reconnecting', flush=True)
return
except OSError as exc:
print('[connection] socket error ({}); will reconnect'.format(exc),
flush=True)
else:
if not global_state.get('running', True):
return
print('[connection] server disconnected; will reconnect', flush=True)
global_state.running = False
print('[connection] server disconnected; not reconnecting', flush=True)
return
if not global_state.get('running', True):
return
+27 -1
View File
@@ -41,7 +41,7 @@ class TestWebInventoryAPI(unittest.TestCase):
if len(attempts) == 1:
raise BrokenPipeError(32, 'Broken pipe')
if len(attempts) == 2:
raise ValueError('I/O operation on closed file')
raise ConnectionResetError(104, 'Connection reset by peer')
global_state.running = False
mosfet_web._run_connection_loop(
@@ -53,6 +53,32 @@ class TestWebInventoryAPI(unittest.TestCase):
self.assertIs(state.connection, False)
self.assertEqual(state.connection_status, 'reconnecting')
def test_clean_server_disconnect_does_not_retry(self):
state = Munch(running=True)
attempts = []
delays = []
def connector(_global_state):
attempts.append(True)
mosfet_web._run_connection_loop(
state, connector, sleep=lambda delay: delays.append(delay))
self.assertEqual(len(attempts), 1)
self.assertEqual(delays, [])
def test_eof_does_not_retry(self):
state = Munch(running=True)
delays = []
def connector(_global_state):
raise EOFError('server closed connection')
mosfet_web._run_connection_loop(
state, connector, sleep=lambda delay: delays.append(delay))
self.assertEqual(delays, [])
def test_web_port_uses_bot_name_suffix(self):
for suffix in range(1, 10):
with self.subTest(suffix=suffix):