fix: убрать web server из daemon + retry для Telegram

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 <noreply@anthropic.com>
This commit is contained in:
anor
2026-03-16 02:37:59 +10:00
co-authored by Claude Opus 4.6
parent f32a93be8e
commit 5872c6ff35
2 changed files with 41 additions and 23 deletions
+19 -10
View File
@@ -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()
+22 -13
View File
@@ -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: