From 5872c6ff353d91b8d124ce39b24d6b3175577bbb Mon Sep 17 00:00:00 2001 From: anor Date: Mon, 16 Mar 2026 02:37:59 +1000 Subject: [PATCH] =?UTF-8?q?fix:=20=D1=83=D0=B1=D1=80=D0=B0=D1=82=D1=8C=20w?= =?UTF-8?q?eb=20server=20=D0=B8=D0=B7=20daemon=20+=20retry=20=D0=B4=D0=BB?= =?UTF-8?q?=D1=8F=20Telegram?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 1. Daemon: убран uvicorn (crash loop из-за port 8090 in use) - Вместо uvicorn.run() — signal.wait() для блокировки main thread - Явный scheduler.shutdown() при остановке 2. Telegram: retry 2 попытки с timeout=20s (РКН замедляет) - send_telegram: 2 попытки, 3s sleep между ними - poll_loop: timeout 60s, backoff 60s при ошибках - Уровень лога poll error: error → warning (снижает спам) Co-Authored-By: Claude Opus 4.6 --- src/remizov_trader/cli.py | 29 +++++++++++++++++++---------- src/remizov_trader/notify.py | 35 ++++++++++++++++++++++------------- 2 files changed, 41 insertions(+), 23 deletions(-) diff --git a/src/remizov_trader/cli.py b/src/remizov_trader/cli.py index 72c2f2c..3ce4b41 100644 --- a/src/remizov_trader/cli.py +++ b/src/remizov_trader/cli.py @@ -220,7 +220,6 @@ def daemon(): from .notify import (format_cycle_report, format_morning_report_with_ai, format_startup_details, format_status_report, send_status, send_telegram) - from .web.app import create_app cfg = load_config() conn = get_db() @@ -322,7 +321,7 @@ def daemon(): click.echo("Stop updates scheduled: every 15 min at :00,:15,:30,:45") scheduler.start() - click.echo("Daemon started. Web dashboard + scheduler running.") + click.echo("Daemon started. Scheduler running (no web server).") # Run first cycle immediately scheduled_cycle() @@ -331,12 +330,22 @@ def daemon(): if cfg.mode == "live": stop_update_cycle() - # Start web server (blocking) - import uvicorn - app = create_app(cfg) + # Block main thread — scheduler runs in background + import signal + import threading + stop_event = threading.Event() + + def _shutdown(signum, frame): + click.echo("Shutting down...") + stop_event.set() + + signal.signal(signal.SIGTERM, _shutdown) + signal.signal(signal.SIGINT, _shutdown) + try: - uvicorn.run(app, host=cfg.web.host, port=cfg.web.port) + stop_event.wait() finally: + scheduler.shutdown(wait=False) if cfg.telegram.enabled: send_status(cfg.telegram, "stop") @@ -358,7 +367,7 @@ def _send_with_keyboard(cfg, text: str, keyboard=None): if keyboard: payload["reply_markup"] = keyboard try: - httpx.post(url, json=payload, timeout=10) + httpx.post(url, json=payload, timeout=30) except Exception: pass @@ -489,7 +498,7 @@ def _start_telegram_listener(cfg, get_db_fn): try: resp = httpx.get(f"{base_url}/getUpdates", params={"offset": offset, "timeout": 30}, - timeout=35) + timeout=60) if resp.status_code != 200: log.warning(f"Telegram poll: HTTP {resp.status_code}") time.sleep(5) @@ -507,8 +516,8 @@ def _start_telegram_listener(cfg, get_db_fn): except Exception as e: log.error(f"Telegram command error: {e}", exc_info=True) except Exception as e: - log.error(f"Telegram poll error: {e}") - time.sleep(10) + log.warning(f"Telegram poll error: {e}") + time.sleep(60) # back off on errors (RKN throttling) t = threading.Thread(target=poll_loop, daemon=True) t.start() diff --git a/src/remizov_trader/notify.py b/src/remizov_trader/notify.py index 7796fb7..2af5d3f 100644 --- a/src/remizov_trader/notify.py +++ b/src/remizov_trader/notify.py @@ -14,24 +14,33 @@ log = logging.getLogger(__name__) def send_telegram(cfg: TelegramConfig, message: str) -> bool: - """Send message via Telegram bot API. Returns True on success.""" + """Send message via Telegram bot API. Returns True on success. + + Retries up to 2 times with 30s timeout (Russia/RKN may throttle Telegram). + """ if not cfg.enabled or not cfg.bot_token or not cfg.chat_id: return False url = f"https://api.telegram.org/bot{cfg.bot_token}/sendMessage" - try: - resp = httpx.post(url, json={ - "chat_id": cfg.chat_id, - "text": message, - "parse_mode": "HTML", - }, timeout=10) - if resp.status_code != 200: - log.warning("Telegram API error: %s", resp.text) + for attempt in range(2): + try: + resp = httpx.post(url, json={ + "chat_id": cfg.chat_id, + "text": message, + "parse_mode": "HTML", + }, timeout=20) + if resp.status_code != 200: + log.warning("Telegram API error: %s", resp.text) + return False + return True + except httpx.HTTPError as e: + if attempt == 0: + import time + time.sleep(3) + continue + log.warning("Telegram send failed: %s", e) return False - return True - except httpx.HTTPError as e: - log.warning("Telegram send failed: %s", e) - return False + return False # unreachable, safety net def send_status(cfg: TelegramConfig, event: str, details: str = "") -> bool: