fix: keep VK bot alive across long poll failures

This commit is contained in:
nyan404 committed 2026-10-08 14:09:20 +03:00
1 parent e33de2114a
commit 2d9aa2126c
8 files changed
+157 -15

No files matched your search

+1
View File
@@ -24,6 +24,7 @@
## Notes ## 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 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. - 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. - 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/<id>` Belki proxy when changing upload flows. - 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/<id>` Belki proxy when changing upload flows.
+1
View File
@@ -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. - 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. - 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 `/отмена`. - 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. - 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. - `/урок` 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. - `.gitignore` now excludes Python bytecode/cache and local test/editor artifacts; generated `__pycache__` directories were removed from the working tree.
+72 -15
View File
@@ -1,6 +1,7 @@
from __future__ import annotations from __future__ import annotations
import json import json
import logging
from math import isfinite from math import isfinite
import os import os
import random import random
@@ -12,6 +13,7 @@ from datetime import datetime
from difflib import SequenceMatcher from difflib import SequenceMatcher
from typing import Any, Iterator from typing import Any, Iterator
from urllib.parse import urlencode from urllib.parse import urlencode
from urllib.error import URLError
from urllib.request import Request, urlopen from urllib.request import Request, urlopen
from .api import ApiError, calculate_payload from .api import ApiError, calculate_payload
@@ -23,6 +25,8 @@ from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore,
from .google_sheets_export import GoogleSheetsExportService from .google_sheets_export import GoogleSheetsExportService
from .vk_scheduler import VkConversationStore, VkScheduler from .vk_scheduler import VkConversationStore, VkScheduler
logger = logging.getLogger(__name__)
""" """
Обработка VK-бота: Обработка VK-бота:
- Парсинг команд и текстовых вводов - Парсинг команд и текстовых вводов
@@ -845,16 +849,17 @@ class BelkiBot:
self.client = client self.client = client
self.group_id = group_id self.group_id = group_id
identities = IdentityDirectory.from_environment(persistent=True) identities = IdentityDirectory.from_environment(persistent=True)
self.conversation_store = VkConversationStore.from_environment()
self.dialog = BelkiDialog( self.dialog = BelkiDialog(
identities, identities,
onboarding=True, onboarding=True,
calculation_store=CalculationStore.from_environment(), calculation_store=CalculationStore.from_environment(),
attachment_mirror=ImageHostClient().mirror, attachment_mirror=ImageHostClient().mirror,
state_store=self.conversation_store,
) )
self.application_store = ApplicationStore.from_environment() self.application_store = ApplicationStore.from_environment()
self.application_dialog = ApplicationDialog(identities, self.application_store) self.application_dialog = ApplicationDialog(identities, self.application_store)
self.application_exporter = GoogleSheetsExportService(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) self.scheduler = VkScheduler(self.conversation_store, self.client.send)
def response_for_text(self, text: str) -> str: def response_for_text(self, text: str) -> str:
@@ -956,23 +961,32 @@ class BelkiBot:
def events(self) -> Iterator[dict[str, Any]]: def events(self) -> Iterator[dict[str, Any]]:
""" """
Генератор событий из Long Poll сервера VK. Генератор событий из 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: 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)
if payload.get("ts"):
ts = payload["ts"]
if payload.get("failed"):
poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id}) poll = self.client.call("groups.getLongPollServer", {"group_id": self.group_id})
server, key, ts = poll["server"], poll["key"], poll["ts"] server, key, ts = poll["server"], poll["key"], poll["ts"]
continue while True:
for event in payload.get("updates", []): query = urlencode({"act": "a_check", "key": key, "wait": 25, "ts": ts})
yield event 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: def run_forever(self) -> None:
"""Бесконечный цикл обработки событий.""" """Бесконечный цикл обработки событий."""
@@ -1030,7 +1044,8 @@ class BelkiDialog:
} }
def __init__(self, identity_directory: IdentityDirectory | None = None, *, onboarding: bool = False, 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.onboarding = onboarding
self.calculation_store = calculation_store self.calculation_store = calculation_store
self.attachment_mirror = attachment_mirror 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: def _reset(self, peer_id: int) -> None:
"""Сбрасывает состояние диалога для указанного peer_id.""" """Сбрасывает состояние диалога для указанного peer_id."""
self._states.pop(peer_id, None) self._states.pop(peer_id, None)
self._pending_attachments.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: def queue_attachments(self, actor_id: int, attachments: list[dict[str, Any]]) -> None:
""" """
@@ -1060,6 +1106,7 @@ class BelkiDialog:
""" """
if not attachments: if not attachments:
return return
self._restore_state(actor_id)
target = ( target = (
self._states[actor_id].setdefault("attachments", []) self._states[actor_id].setdefault("attachments", [])
if actor_id in self._states and self._states[actor_id].get("awaiting_attachments") if actor_id in self._states and self._states[actor_id].get("awaiting_attachments")
@@ -1072,6 +1119,7 @@ class BelkiDialog:
target.append(photo) target.append(photo)
known.add(key) known.add(key)
del target[:-10] del target[:-10]
self._persist_state(actor_id)
def _attach_pending(self, actor_id: int) -> None: def _attach_pending(self, actor_id: int) -> None:
"""Переносит отложенные вложения в состояние пользователя.""" """Переносит отложенные вложения в состояние пользователя."""
@@ -1624,6 +1672,15 @@ class BelkiDialog:
return self._ask_next(state) return self._ask_next(state)
def handle(self, peer_id: int, text: str, user_id: int | None = None) -> str: 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:
""" """
Главный обработчик входящих сообщений. Главный обработчик входящих сообщений.
+36
View File
@@ -83,6 +83,9 @@ class VkConversationStore:
id INTEGER PRIMARY KEY, schedule_id INTEGER NOT NULL, planned_for TEXT NOT NULL, 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, 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))""", 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: if self._postgres:
with self._psycopg.connect(self.database_url) as conn: 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") 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)) 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: 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 символов") 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) 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)
+2
View File
@@ -46,7 +46,9 @@ mindmap
VK bot VK bot
vk_bot.py vk_bot.py
Long Poll Long Poll
reconnect on SSL/socket/timeout
Step dialogs Step dialogs
durable vk_dialog_states checkpoint
Natural one-line parser Natural one-line parser
Mentor and student labels Mentor and student labels
Per-ward self-sufficiency labels Per-ward self-sufficiency labels
+2
View File
@@ -20,6 +20,8 @@
- [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules. - [`CONTRIBUTING.md`](./CONTRIBUTING.md): contribution and verification rules.
## Runtime / Deployment ## 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>.<extension>` while `Handler` proxies reads from MinIO. MinIO has no public exposure. - 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>.<extension>` 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. - 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-<commit>` tag before the final Belki image; `Dockerfile` accepts that base through `BELKI_BASE_IMAGE`, leaving only application sources in the final layer. - `Dockerfile.base` is rebuilt and pushed with the immutable `py312-<commit>` tag before the final Belki image; `Dockerfile` accepts that base through `BELKI_BASE_IMAGE`, leaving only application sources in the final layer.
+24
View File
@@ -1,5 +1,7 @@
import unittest import unittest
import json import json
from unittest.mock import patch
from urllib.error import URLError
from app.belki.vk_bot import ( from app.belki.vk_bot import (
BelkiDialog, BelkiDialog,
@@ -13,6 +15,28 @@ from app.belki.vk_bot import (
class VkBotTests(unittest.TestCase): 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): def test_public_chat_messages_are_ignored_but_invite_is_registered(self):
class Client: class Client:
def __init__(self): self.sent = [] def __init__(self): self.sent = []
+19
View File
@@ -4,6 +4,7 @@ from tempfile import TemporaryDirectory
from app.belki.identity import Identity, IdentityDirectory 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_bot import HELP_TEXT, BelkiDialog, inspect_bulk_text, parse_text_command
from app.belki.vk_scheduler import VkConversationStore
class VkConversationTests(unittest.TestCase): class VkConversationTests(unittest.TestCase):
@@ -223,6 +224,24 @@ class VkConversationTests(unittest.TestCase):
self.assertIn("Серолап", confirmation) self.assertIn("Серолап", confirmation)
self.assertIn("подтверд", confirmation.lower()) 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): def test_inspection_character_without_directory_offers_pairing(self):
dialog = BelkiDialog(IdentityDirectory()) dialog = BelkiDialog(IdentityDirectory())
dialog.handle(105, "/осмотр") dialog.handle(105, "/осмотр")