fix: keep VK bot alive across long poll failures
This commit is contained in:
1 parent
e33de2114a
commit
2d9aa2126c
8 files changed
+157
-15
No files matched your search
+72
-15
@@ -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:
|
||||
"""
|
||||
Главный обработчик входящих сообщений.
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
Reference in new issue
Block a user