From 02c29f8692bd753dc20d447f79299e1923ea568d Mon Sep 17 00:00:00 2001 From: vvzvlad Date: Mon, 16 Mar 2026 04:13:39 +0300 Subject: [PATCH] fix(telegram): add shutdown guard to avoid duplicate restarts Add a `_shutting_down` flag to `TelegramClient` to suppress disconnect handling during intentional shutdown. The flag is set before sending SIGTERM in `_restart_app` and checked in `_on_disconnect` to ignore those events. Minor formatting adjustments were also applied to `api_server.py` (try block and `uvicorn.run` arguments). --- api_server.py | 9 ++++----- telegram_client.py | 6 ++++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/api_server.py b/api_server.py index 9bd0bc3..8ab97e3 100644 --- a/api_server.py +++ b/api_server.py @@ -121,12 +121,11 @@ if __name__ == "__main__": # Log uvloop status logger.info(" uvloop: enabled (asyncio speedup active)") - try: + try: uvicorn.run( - "api_server:app", - host=Config["api_host"], - port=Config["api_port"], - reload=True, + "api_server:app", + host=Config["api_host"], + port=Config["api_port"], loop="uvloop" ) except OSError as e: diff --git a/telegram_client.py b/telegram_client.py index 757f1e7..5a59fff 100644 --- a/telegram_client.py +++ b/telegram_client.py @@ -35,6 +35,7 @@ class TelegramClient: ) self.disconnect_count = 0 self.max_disconnects = 3 + self._shutting_down = False # Guard to prevent re-triggering restart during shutdown self._setup_connection_handlers() def _ensure_session_directory(self): @@ -52,6 +53,10 @@ class TelegramClient: async def _on_disconnect(self, _client, _session=None): """Handles disconnection from Telegram servers""" + # Ignore disconnects that are caused by the intentional shutdown sequence + if self._shutting_down: + logger.debug("connection_handler: ignoring disconnect event during shutdown") + return self.disconnect_count += 1 logger.warning(f"connection_handler: connection lost (#{self.disconnect_count})") @@ -73,6 +78,7 @@ class TelegramClient: def _restart_app(self): """Restarts the application by sending SIGTERM to the process""" + self._shutting_down = True # Set flag before sending signal to suppress subsequent disconnect events logger.warning("connection_handler: restarting application by sending SIGTERM") try: # Use SIGTERM for proper Docker container restart