From 2d9aa2126c2f6b3328f8995d0b11fb0d1066761c Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Thu, 8 Oct 2026 14:09:20 +0300 Subject: [PATCH] fix: keep VK bot alive across long poll failures --- AGENTS.md | 1 + MEMORY.md | 1 + app/belki/vk_bot.py | 87 +++++++++++++++++++++++++++++------ app/belki/vk_scheduler.py | 36 +++++++++++++++ project_mind_map.md | 2 + structure_and_data.md | 2 + tests/test_vk_bot.py | 24 ++++++++++ tests/test_vk_conversation.py | 19 ++++++++ 8 files changed, 157 insertions(+), 15 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 5262007..e96c1d2 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -24,6 +24,7 @@ ## Notes - VK scheduler lives in `app/belki/vk_scheduler.py`; use `BELKI_DATABASE_URL` in production and `BELKI_HISTORY_DB` for local SQLite checks. Keep mailing disabled until an administrator explicitly enables a conversation and schedule. +- VK Long Poll and dialog durability live across `app/belki/vk_bot.py` and `app/belki/vk_scheduler.py`: keep reconnect handling around both Long Poll setup and `a_check`, and preserve the `vk_dialog_states` schema when changing dialog steps or attachments. Validate with `python -m unittest tests.test_vk_bot tests.test_vk_conversation -q`. - The build job waits for the DinD daemon and runs `docker info` before building. - Never commit `.env` or `.gitlab.variables.env`; the latter contains the GitLab Variable handoff and a namespace-scoped kubeconfig. - Private image storage is the separate Kubernetes Secret `belki-image-store`, not the CI-recreated `belki-runtime`. It contains only the internal MinIO endpoints and bucket-scoped credentials; keep MinIO private and preserve the `/api/images/` Belki proxy when changing upload flows. diff --git a/MEMORY.md b/MEMORY.md index 5d71b42..6574dcc 100644 --- a/MEMORY.md +++ b/MEMORY.md @@ -13,6 +13,7 @@ - Confirmed local acceptance: 28 unittest cases pass; local browser smoke generated a 20-minute ЛУ report; `belki-calculator:test` built and its `/health`, `/api/calculate`, `/api/inspect-bulk`, and `/api/resolve-identity` endpoints responded. - Draft k3s manifests live under `deploy/k8s/` but have not been applied. No VK token, group ID, service IP, or cluster Secret is stored in the repository. - VK input is now conversational: `BelkiDialog` stores per-peer state, supports `/лу`/`/зу` step-by-step prompts, detects bulk messages, asks for missing skill/status or confirmation, and clears with `/отмена`. +- 2026-10-08: VK Long Poll now catches transient SSL/socket/timeouts, logs and reacquires the Long Poll server instead of terminating `belki-bot`. Unfinished dialog state and queued photos are persisted in `vk_dialog_states` by `VkConversationStore`, so a process restart can resume before confirmation; completed/cancelled states are removed. - The preferred bulk input is a natural line without pipes, such as `15.08 11:00 11:20 Дикая Вишня 1604614 Серолап 1617140`; `/api/inspect-bulk` and the web form fill recognized fields and show only missing questions. - `/урок` and `/осмотр` use the same dialog; character name/ID may be entered separately and resolved from the persistent SQLite directory at `BELKI_IDENTITIES_DB` (default `data/belki.sqlite3`), otherwise the dialog asks for the missing half and remembers the completed pair. - `.gitignore` now excludes Python bytecode/cache and local test/editor artifacts; generated `__pycache__` directories were removed from the working tree. diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 6ebf33c..3c8b55a 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -1,6 +1,7 @@ from __future__ import annotations import json +import logging from math import isfinite import os import random @@ -12,6 +13,7 @@ from datetime import datetime from difflib import SequenceMatcher from typing import Any, Iterator from urllib.parse import urlencode +from urllib.error import URLError from urllib.request import Request, urlopen from .api import ApiError, calculate_payload @@ -23,6 +25,8 @@ from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, from .google_sheets_export import GoogleSheetsExportService from .vk_scheduler import VkConversationStore, VkScheduler +logger = logging.getLogger(__name__) + """ Обработка VK-бота: - Парсинг команд и текстовых вводов @@ -845,16 +849,17 @@ class BelkiBot: self.client = client self.group_id = group_id identities = IdentityDirectory.from_environment(persistent=True) + self.conversation_store = VkConversationStore.from_environment() self.dialog = BelkiDialog( identities, onboarding=True, calculation_store=CalculationStore.from_environment(), attachment_mirror=ImageHostClient().mirror, + state_store=self.conversation_store, ) self.application_store = ApplicationStore.from_environment() self.application_dialog = ApplicationDialog(identities, self.application_store) self.application_exporter = GoogleSheetsExportService(self.application_store) - self.conversation_store = VkConversationStore.from_environment() self.scheduler = VkScheduler(self.conversation_store, self.client.send) def response_for_text(self, text: str) -> str: @@ -956,23 +961,32 @@ class BelkiBot: def events(self) -> Iterator[dict[str, Any]]: """ Генератор событий из Long Poll сервера VK. - - Перезапускает подключение при ошибках. + + Перезапускает подключение при сетевых и SSL-ошибках, не завершая процесс. """ - poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id}) - server, key, ts = poll["server"], poll["key"], poll["ts"] while True: - query = urlencode({"act": "a_check", "key": key, "wait": 25, "ts": ts}) - with urlopen(f"{server}?{query}", timeout=35) as response: - payload = json.load(response) - if payload.get("ts"): - ts = payload["ts"] - if payload.get("failed"): + try: poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id}) server, key, ts = poll["server"], poll["key"], poll["ts"] - continue - for event in payload.get("updates", []): - yield event + while True: + query = urlencode({"act": "a_check", "key": key, "wait": 25, "ts": ts}) + try: + with urlopen(f"{server}?{query}", timeout=35) as response: + payload = json.load(response) + except (OSError, TimeoutError, URLError) as exc: + logger.warning("VK Long Poll connection failed; reconnecting: %s", exc) + time.sleep(1) + break + if payload.get("ts"): + ts = payload["ts"] + if payload.get("failed"): + logger.warning("VK Long Poll requested a new server: failed=%s", payload["failed"]) + break + for event in payload.get("updates", []): + yield event + except (OSError, TimeoutError, URLError, VkError) as exc: + logger.warning("VK Long Poll setup failed; retrying: %s", exc) + time.sleep(1) def run_forever(self) -> None: """Бесконечный цикл обработки событий.""" @@ -1030,7 +1044,8 @@ class BelkiDialog: } def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False, - calculation_store: CalculationStore | None = None, attachment_mirror=None) -> None: + calculation_store: CalculationStore | None = None, attachment_mirror=None, + state_store: VkConversationStore | None = None) -> None: """ Инициализация диалога. @@ -1046,11 +1061,42 @@ class BelkiDialog: self.onboarding = onboarding self.calculation_store = calculation_store self.attachment_mirror = attachment_mirror + self.state_store = state_store + + def _restore_state(self, actor_id: int) -> None: + """Restore an unfinished dialog once, keeping the in-memory fast path.""" + if self.state_store is None or actor_id in self._states or actor_id in self._pending_attachments: + return + try: + state, pending = self.state_store.load_dialog_state(actor_id) + except Exception: + logger.exception("Unable to restore VK dialog state for actor %s", actor_id) + return + if state: + self._states[actor_id] = state + if pending: + self._pending_attachments[actor_id] = pending + + def _persist_state(self, actor_id: int) -> None: + """Persist state without turning a database outage into a bot crash.""" + if self.state_store is None: + return + try: + state = self._states.get(actor_id) + pending = self._pending_attachments.get(actor_id, []) + if state is None and not pending: + self.state_store.delete_dialog_state(actor_id) + else: + self.state_store.save_dialog_state(actor_id, state, pending) + except Exception: + logger.exception("Unable to persist VK dialog state for actor %s", actor_id) def _reset(self, peer_id: int) -> None: """Сбрасывает состояние диалога для указанного peer_id.""" self._states.pop(peer_id, None) self._pending_attachments.pop(peer_id, None) + if self.state_store is not None: + self._persist_state(peer_id) def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None: """ @@ -1060,6 +1106,7 @@ class BelkiDialog: """ if not attachments: return + self._restore_state(actor_id) target = ( self._states[actor_id].setdefault("attachments", []) if actor_id in self._states and self._states[actor_id].get("awaiting_attachments") @@ -1072,6 +1119,7 @@ class BelkiDialog: target.append(photo) known.add(key) del target[:-10] + self._persist_state(actor_id) def _attach_pending(self, actor_id: int) -> None: """Переносит отложенные вложения в состояние пользователя.""" @@ -1624,6 +1672,15 @@ class BelkiDialog: return self._ask_next(state) def handle(self, peer_id: int, text: str, user_id: int | None = None) -> str: + """Restore, process, and persist one user message atomically enough for restarts.""" + actor_id = user_id or peer_id + self._restore_state(actor_id) + try: + return self._handle(peer_id, text, user_id=user_id) + finally: + self._persist_state(actor_id) + + def _handle(self, peer_id: int, text: str, user_id: int | None = None) -> str: """ Главный обработчик входящих сообщений. diff --git a/app/belki/vk_scheduler.py b/app/belki/vk_scheduler.py index d9ca870..69b5b9d 100644 --- a/app/belki/vk_scheduler.py +++ b/app/belki/vk_scheduler.py @@ -83,6 +83,9 @@ class VkConversationStore: id INTEGER PRIMARY KEY, schedule_id INTEGER NOT NULL, planned_for TEXT NOT NULL, status TEXT NOT NULL DEFAULT 'pending', attempted_at TEXT, attempts INTEGER NOT NULL DEFAULT 0, vk_result TEXT, error TEXT, UNIQUE(schedule_id, planned_for))""", + """CREATE TABLE IF NOT EXISTS vk_dialog_states ( + actor_id BIGINT PRIMARY KEY, state_json TEXT NOT NULL, pending_json TEXT NOT NULL, + updated_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""", ] if self._postgres: with self._psycopg.connect(self.database_url) as conn: @@ -128,6 +131,39 @@ class VkConversationStore: keys = ("peer_id", "chat_id", "title", "status", "mailing_enabled", "added_at", "invited_by", "removed_at", "removal_reason", "last_success_at", "last_error") return dict(zip(keys, row)) + def load_dialog_state(self, actor_id: int) -> tuple[dict | None, list[dict]]: + """Load an unfinished private dialog and photos queued before its next text event.""" + rows = self._execute( + "SELECT state_json,pending_json FROM vk_dialog_states WHERE actor_id=?", + (int(actor_id),), fetch=True, + ) or [] + if not rows: + return None, [] + try: + state = json.loads(rows[0][0]) if rows[0][0] else None + pending = json.loads(rows[0][1]) if rows[0][1] else [] + except (TypeError, ValueError, json.JSONDecodeError): + return None, [] + return (state if isinstance(state, dict) else None, + pending if isinstance(pending, list) else []) + + def save_dialog_state(self, actor_id: int, state: dict | None, pending: list[dict]) -> None: + """Atomically persist the current dialog state and queued photos.""" + now = datetime.now(timezone.utc).isoformat() + state_json = json.dumps(state, ensure_ascii=False) if state is not None else "" + pending_json = json.dumps(pending, ensure_ascii=False) + self._execute( + """INSERT INTO vk_dialog_states(actor_id,state_json,pending_json,updated_at) + VALUES(?,?,?,?) + ON CONFLICT(actor_id) DO UPDATE SET state_json=excluded.state_json, + pending_json=excluded.pending_json, updated_at=excluded.updated_at""", + (int(actor_id), state_json, pending_json, now), + ) + + def delete_dialog_state(self, actor_id: int) -> None: + """Remove a completed or cancelled dialog from durable storage.""" + self._execute("DELETE FROM vk_dialog_states WHERE actor_id=?", (int(actor_id),)) + def create_template(self, name: str, text: str, *, active: bool = True, starts_on: str | None = None, ends_on: str | None = None) -> int: if not text.strip() or len(text) > 4096: raise ValueError("Текст шаблона должен быть от 1 до 4096 символов") rows = self._execute("INSERT INTO vk_message_templates(name,text,active,starts_on,ends_on) VALUES(?,?,?,?,?) RETURNING id", (name.strip() or "Без названия", text.strip(), active, starts_on, ends_on), fetch=True) diff --git a/project_mind_map.md b/project_mind_map.md index e4ff95e..95e63d7 100644 --- a/project_mind_map.md +++ b/project_mind_map.md @@ -46,7 +46,9 @@ mindmap VK bot vk_bot.py Long Poll + reconnect on SSL/socket/timeout Step dialogs + durable vk_dialog_states checkpoint Natural one-line parser Mentor and student labels Per-ward self-sufficiency labels diff --git a/structure_and_data.md b/structure_and_data.md index d304fcb..77936e9 100644 --- a/structure_and_data.md +++ b/structure_and_data.md @@ -20,6 +20,8 @@ - [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules. ## Runtime / Deployment +- 2026-10-08: hardened `belki-bot` VK Long Poll against transient `OSError`/SSL/timeout failures. The poll loop logs the failure, waits, obtains a fresh `groups.getLongPollServer` lease, and continues without exiting the process. +- 2026-10-08: `BelkiDialog` now persists unfinished per-actor state and queued VK photos in `vk_dialog_states` through the existing `BELKI_DATABASE_URL`/`BELKI_HISTORY_DB` store. State is written after each text/photo event and restored lazily after a bot restart; completed/cancelled dialogs are deleted. - 2026-09-08: report screenshots and VK attachment mirrors use private distributed MinIO through the `minio==7.2.20` SDK. `belki-image-store` is a separate, out-of-band Kubernetes Secret containing the internal S3 endpoint, a bucket-scoped `GetObject`/`PutObject` account plus required `GetBucketLocation`, and `belki-images`; it is deliberately separate from CI-managed `belki-runtime` so normal deploys cannot remove it. `belki-web` and `belki-bot` return/retain `https://cat.nyan404.ru/api/images/<128-bit-random-id>.` while `Handler` proxies reads from MinIO. MinIO has no public exposure. - 2026-09-24: switched the live Belki S3 endpoint from the five direct MinIO nodes to the in-cluster HAProxy front door `10.43.30.146:9000` (`minio-haproxy` in namespace `minio-proxy`). The cluster Secret was updated out-of-band and `belki-web`/`belki-bot` were restarted; the repository example mirrors this endpoint. HAProxy remains responsible for balancing the healthy MinIO nodes. - `Dockerfile.base` is rebuilt and pushed with the immutable `py312-` tag before the final Belki image; `Dockerfile` accepts that base through `BELKI_BASE_IMAGE`, leaving only application sources in the final layer. diff --git a/tests/test_vk_bot.py b/tests/test_vk_bot.py index e550131..73ce1ad 100644 --- a/tests/test_vk_bot.py +++ b/tests/test_vk_bot.py @@ -1,5 +1,7 @@ import unittest import json +from unittest.mock import patch +from urllib.error import URLError from app.belki.vk_bot import ( BelkiDialog, @@ -13,6 +15,28 @@ from app.belki.vk_bot import ( class VkBotTests(unittest.TestCase): + def test_long_poll_reconnects_after_ssl_error(self): + class Client: + def __init__(self): + self.calls = 0 + + def call(self, method, params): + self.calls += 1 + return {"server": "https://vk.example/longpoll", "key": "key", "ts": str(self.calls)} + + class Response: + def __enter__(self): return self + def __exit__(self, *args): return False + def __iter__(self): return iter(()) + def read(self): return b'{"ts":"2","updates":[{"type":"message_new"}]}' + + bot = BelkiBot.__new__(BelkiBot) + bot.client = Client() + bot.group_id = 1 + events = bot.events() + with patch("app.belki.vk_bot.urlopen", side_effect=[URLError("handshake timeout"), Response()]), patch("app.belki.vk_bot.time.sleep"): + self.assertEqual(next(events)["type"], "message_new") + self.assertEqual(bot.client.calls, 2) def test_public_chat_messages_are_ignored_but_invite_is_registered(self): class Client: def __init__(self): self.sent = [] diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 22960e6..279a162 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -4,6 +4,7 @@ from tempfile import TemporaryDirectory from app.belki.identity import Identity, IdentityDirectory from app.belki.vk_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text, parse_text_command +from app.belki.vk_scheduler import VkConversationStore class VkConversationTests(unittest.TestCase): @@ -223,6 +224,24 @@ class VkConversationTests(unittest.TestCase): self.assertIn("Серолап", confirmation) self.assertIn("подтверд", confirmation.lower()) + def test_dialog_state_and_photo_survive_bot_recreation(self): + with TemporaryDirectory() as directory: + store = VkConversationStore(sqlite_path=f"{directory}/vk.sqlite3") + first = BelkiDialog(state_store=store) + first.handle(204, "/осмотр") + first.handle(204, "дупло") + first.handle(204, "1") + first.handle(204, "Серолап [1617140]") + first.handle(204, "без ресурсов") + first.queue_attachments(204, [{"type": "photo", "url": "https://example.test/history.jpg"}]) + + recreated = BelkiDialog(state_store=store) + confirmation = recreated.handle(204, "готово") + + self.assertIn("Серолап", confirmation) + self.assertIn("подтверд", confirmation.lower()) + self.assertEqual(recreated._states[204]["attachments"][0]["url"], "https://example.test/history.jpg") + def test_inspection_character_without_directory_offers_pairing(self): dialog = BelkiDialog(IdentityDirectory()) dialog.handle(105, "/осмотр")