health check

This commit is contained in:
kislovdm
2026-04-09 12:35:45 +03:00
parent 6f5a15cd49
commit 3bb81598d6
5 changed files with 217 additions and 2 deletions
+27 -1
View File
@@ -6,6 +6,8 @@ from dotenv import load_dotenv
from bridge import MaxToTelegramBridge
from config import load_settings
from health import HealthState
from health_web import start_health_server
from reverse_bridge import TelegramToMaxBridge
from storage import BridgeStorage
from telegram_api import TelegramClient
@@ -44,16 +46,22 @@ def main() -> None:
)
storage = BridgeStorage(settings.sqlite_path)
bridge = MaxToTelegramBridge(max_client=max_client, telegram=telegram_client, storage=storage)
reverse_bridge = TelegramToMaxBridge(max_client=max_client, telegram=telegram_client, storage=storage)
health = HealthState(unhealthy_after_sec=15 * 60)
start_health_server(host="0.0.0.0", port=5000, health=health)
reverse_bridge = TelegramToMaxBridge(max_client=max_client, telegram=telegram_client, storage=storage, health=health)
logger = logging.getLogger("max2telegram")
@max_client.on_start
async def on_start() -> None:
logger.info("Max client started as %s", max_client.me.id)
health.mark_max_ok()
asyncio.create_task(reverse_bridge.start())
asyncio.create_task(_max_probe_loop(max_client=max_client, health=health))
@max_client.on_message()
async def on_message(message: Message) -> None:
health.mark_max_event()
try:
await bridge.forward_message(message)
except Exception:
@@ -62,5 +70,23 @@ def main() -> None:
asyncio.run(max_client.start())
async def _max_probe_loop(*, max_client: MaxClient, health: HealthState) -> None:
# Best-effort контроль соединения: периодически дергаем API.
# Если PyMax разорвет соединение/сломается сессия, это обычно проявится как исключение.
await asyncio.sleep(2)
while True:
try:
me = getattr(max_client, "me", None)
my_id = getattr(me, "id", None)
if my_id is not None:
await max_client.get_user(user_id=my_id)
health.mark_max_ok()
except Exception:
health.mark_max_error()
logger = logging.getLogger("max2telegram")
logger.exception("Max probe failed")
await asyncio.sleep(60)
if __name__ == "__main__":
main()