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).
This commit is contained in:
vvzvlad
2026-03-16 04:13:39 +03:00
parent 14f8db0a32
commit 02c29f8692
2 changed files with 10 additions and 5 deletions
+4 -5
View File
@@ -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:
+6
View File
@@ -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