From a04498d63470d4bc5a6c19ef19931939d9a287d2 Mon Sep 17 00:00:00 2001 From: Nyan404 Date: Sat, 10 Oct 2026 21:33:56 +0300 Subject: [PATCH] feat: migrate VK bot to Callback API --- app/belki/vk_bot.py | 82 ++++++++++---------- app/belki/vk_callback.py | 138 +++++++++++++++++++++++++++++++++ app/belki/vk_scheduler.py | 38 +++++++++ deploy/k8s/app.yaml | 41 ++++++++++ deploy/k8s/production.yaml | 42 ++++++++++ deploy/k8s/secret.example.yaml | 2 + nginx.conf | 9 +++ tests/test_vk_bot.py | 68 +++++++++++----- tests/test_vk_callback.py | 68 ++++++++++++++++ tests/test_vk_conversation.py | 8 ++ 10 files changed, 438 insertions(+), 58 deletions(-) create mode 100644 app/belki/vk_callback.py create mode 100644 tests/test_vk_callback.py diff --git a/app/belki/vk_bot.py b/app/belki/vk_bot.py index 3c8b55a..e82b339 100644 --- a/app/belki/vk_bot.py +++ b/app/belki/vk_bot.py @@ -11,9 +11,8 @@ import time import unicodedata from datetime import datetime from difflib import SequenceMatcher -from typing import Any, Iterator +from typing import Any from urllib.parse import urlencode -from urllib.error import URLError from urllib.request import Request, urlopen from .api import ApiError, calculate_payload @@ -23,6 +22,7 @@ from .image_host import ImageHostClient from .identity import Identity, IdentityDirectory from .applications import APPLICATION_TYPES, ApplicationError, ApplicationStore, validate_application from .google_sheets_export import GoogleSheetsExportService +from .vk_callback import CallbackHTTPServer, process_callback from .vk_scheduler import VkConversationStore, VkScheduler logger = logging.getLogger(__name__) @@ -874,13 +874,23 @@ class BelkiBot: def handle_event(self, event: dict[str, Any]) -> None: """ - Обработка события из Long Poll сервера. + Обработка одного события VK Callback API. Извлекает текст сообщения, прикрепляет фото и обрабатывает через dialog. """ - if event.get("type") != "message_new": + event_type = event.get("type") + if event_type not in {"message_new", "message_event"}: return - message = event.get("object", {}).get("message", event.get("object", {})) + event_object = event.get("object", {}) + if event_type == "message_event": + message = { + "peer_id": event_object.get("peer_id"), + "from_id": event_object.get("user_id"), + "payload": event_object.get("payload"), + "text": "", + } + else: + message = event_object.get("message", event_object) peer_id = message.get("peer_id") action = (message.get("action") or {}).get("type") if peer_id and int(peer_id) >= 2_000_000_000: @@ -958,38 +968,14 @@ class BelkiBot: "independence:self": "сам", "independence:nonself": "несам", }.get(str(value)) - def events(self) -> Iterator[dict[str, Any]]: - """ - Генератор событий из Long Poll сервера VK. + def run_forever(self, *, callback_host: str, callback_port: int, callback_secret: str, + callback_confirmation: str) -> None: + """Run the Callback API listener, notifications and scheduler.""" + if not callback_secret: + raise RuntimeError("VK_CALLBACK_SECRET is required") + if not callback_confirmation: + raise RuntimeError("VK_CALLBACK_CONFIRMATION is required") - Перезапускает подключение при сетевых и SSL-ошибках, не завершая процесс. - """ - while True: - try: - 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}) - 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 notification_loop() -> None: """Периодически отправляет уведомления о принятых заявках.""" while True: @@ -998,8 +984,21 @@ class BelkiBot: time.sleep(15) threading.Thread(target=notification_loop, name="belki-application-notifier", daemon=True).start() threading.Thread(target=self.scheduler.run_forever, name="belki-vk-scheduler", daemon=True).start() - for event in self.events(): - self.handle_event(event) + callback_server = CallbackHTTPServer( + (callback_host, callback_port), + process_callback, + expected_secret=callback_secret, + group_id=self.group_id, + confirmation=callback_confirmation, + claim_event=self.conversation_store.claim_callback_event, + release_event=self.conversation_store.release_callback_event, + handle_event=self.handle_event, + ) + logger.info("VK Callback API listening on %s:%s", callback_host, callback_port) + try: + callback_server.serve_forever() + finally: + callback_server.server_close() class BelkiDialog: @@ -1767,7 +1766,12 @@ def main() -> None: group_id = int(os.environ["VK_GROUP_ID"]) version = os.getenv("VK_API_VERSION", "5.199") bot = BelkiBot(VkApiClient(token, version), group_id) - bot.run_forever() + bot.run_forever( + callback_host=os.getenv("VK_CALLBACK_HOST", "0.0.0.0"), + callback_port=int(os.getenv("VK_CALLBACK_PORT", "8081")), + callback_secret=os.environ["VK_CALLBACK_SECRET"], + callback_confirmation=os.environ["VK_CALLBACK_CONFIRMATION"], + ) if __name__ == "__main__": diff --git a/app/belki/vk_callback.py b/app/belki/vk_callback.py new file mode 100644 index 0000000..af1b9d3 --- /dev/null +++ b/app/belki/vk_callback.py @@ -0,0 +1,138 @@ +"""VK Callback API transport and request validation.""" +from __future__ import annotations + +import json +from dataclasses import dataclass +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from typing import Any, Callable + + +@dataclass(frozen=True) +class CallbackResponse: + """HTTP response returned by the pure callback processor.""" + + status: int + body: str + + +class CallbackRequestError(ValueError): + """Raised when VK sends an invalid callback request.""" + + +def process_callback( + payload: dict[str, Any], + *, + secret: str, + expected_secret: str, + group_id: int, + confirmation: str, + claim_event: Callable[[str, str], bool] | None, + release_event: Callable[[str], None] | None, + handle_event: Callable[[dict[str, Any]], None], +) -> CallbackResponse: + """Validate and dispatch one VK Callback API payload. + + The function returns a response before the caller writes it to the socket, + which keeps HTTP transport concerns separate from bot event processing. + """ + if expected_secret and secret != expected_secret: + return CallbackResponse(403, "forbidden") + if not isinstance(payload, dict): + return CallbackResponse(400, "invalid payload") + if int(payload.get("group_id", 0) or 0) != int(group_id): + return CallbackResponse(400, "invalid group_id") + + event_type = str(payload.get("type", "")) + if event_type == "confirmation": + if not confirmation: + return CallbackResponse(503, "confirmation is not configured") + return CallbackResponse(200, confirmation) + + event_id = payload.get("event_id") + if event_id is None and isinstance(payload.get("object"), dict): + event_id = payload["object"].get("event_id") + if event_id is not None and claim_event is not None: + if not claim_event(str(event_id), event_type): + return CallbackResponse(200, "ok") + + try: + handle_event(payload) + except Exception: + if event_id is not None and release_event is not None: + release_event(str(event_id)) + raise + return CallbackResponse(200, "ok") + + +class CallbackHTTPServer(ThreadingHTTPServer): + """Threaded HTTP server bound to a Belki callback processor.""" + + daemon_threads = True + allow_reuse_address = True + + def __init__(self, address: tuple[str, int], processor: Callable[..., CallbackResponse], *, + expected_secret: str, group_id: int, confirmation: str, claim_event: Callable[[str, str], bool] | None, + release_event: Callable[[str], None] | None, + handle_event: Callable[[dict[str, Any]], None]) -> None: + super().__init__(address, CallbackRequestHandler) + self.processor = processor + self.expected_secret = expected_secret + self.group_id = group_id + self.confirmation = confirmation + self.claim_event = claim_event + self.release_event = release_event + self.handle_event = handle_event + + +class CallbackRequestHandler(BaseHTTPRequestHandler): + """Minimal HTTP adapter for VK callback requests and health checks.""" + + server: CallbackHTTPServer + max_body_bytes = 2 * 1024 * 1024 + + def do_GET(self) -> None: # noqa: N802 + if self.path == "/health": + self._write(200, "ok") + return + self._write(404, "not found") + + def do_POST(self) -> None: # noqa: N802 + if self.path != "/api/vk/callback": + self._write(404, "not found") + return + try: + length = int(self.headers.get("Content-Length", "0")) + if length <= 0 or length > self.max_body_bytes: + raise CallbackRequestError("invalid body size") + payload = json.loads(self.rfile.read(length)) + if not isinstance(payload, dict): + raise CallbackRequestError("payload must be an object") + response = self.server.processor( + payload, + secret=str(payload.get("secret", "")), + expected_secret=self.server.expected_secret, + group_id=self.server.group_id, + confirmation=self.server.confirmation, + claim_event=self.server.claim_event, + release_event=self.server.release_event, + handle_event=self.server.handle_event, + ) + except (CallbackRequestError, TypeError, ValueError, json.JSONDecodeError): + self._write(400, "invalid payload") + return + except Exception: + self._write(500, "internal error") + return + self._write(response.status, response.body) + + def _write(self, status: int, body: str) -> None: + encoded = body.encode("utf-8") + self.send_response(status) + self.send_header("Content-Type", "text/plain; charset=utf-8") + self.send_header("Content-Length", str(len(encoded))) + self.send_header("Cache-Control", "no-store") + self.end_headers() + self.wfile.write(encoded) + + def log_message(self, format: str, *args: object) -> None: + return diff --git a/app/belki/vk_scheduler.py b/app/belki/vk_scheduler.py index 69b5b9d..86dfbee 100644 --- a/app/belki/vk_scheduler.py +++ b/app/belki/vk_scheduler.py @@ -86,6 +86,9 @@ class VkConversationStore: """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)""", + """CREATE TABLE IF NOT EXISTS vk_callback_events ( + event_id TEXT PRIMARY KEY, event_type TEXT NOT NULL, + received_at TEXT NOT NULL DEFAULT CURRENT_TIMESTAMP)""", ] if self._postgres: with self._psycopg.connect(self.database_url) as conn: @@ -164,6 +167,41 @@ class VkConversationStore: """Remove a completed or cancelled dialog from durable storage.""" self._execute("DELETE FROM vk_dialog_states WHERE actor_id=?", (int(actor_id),)) + def claim_callback_event(self, event_id: str, event_type: str) -> bool: + """Claim a callback event once, preventing duplicate VK deliveries.""" + if not event_id.strip(): + return True + now = datetime.now(timezone.utc) + try: + self._execute( + "INSERT INTO vk_callback_events(event_id,event_type,received_at) VALUES(?,?,?)", + (event_id[:255], event_type[:100], now.isoformat()), + ) + return True + except Exception: + # A unique-key collision is a duplicate; an unavailable database + # must propagate so VK retries the callback instead of losing it. + rows = self._execute( + "SELECT event_id FROM vk_callback_events WHERE event_id=?", + (event_id[:255],), fetch=True, + ) or [] + if rows: + return False + raise + finally: + try: + self._execute( + "DELETE FROM vk_callback_events WHERE received_at None: + """Release a failed callback claim so VK can retry the event.""" + if event_id.strip(): + self._execute("DELETE FROM vk_callback_events WHERE event_id=?", (event_id[:255],)) + 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/deploy/k8s/app.yaml b/deploy/k8s/app.yaml index 2727545..54e9b8b 100644 --- a/deploy/k8s/app.yaml +++ b/deploy/k8s/app.yaml @@ -118,14 +118,55 @@ spec: name: belki-vk key: VK_API_VERSION optional: true + - name: VK_CALLBACK_SECRET + valueFrom: + secretKeyRef: + name: belki-vk + key: VK_CALLBACK_SECRET + - name: VK_CALLBACK_CONFIRMATION + valueFrom: + secretKeyRef: + name: belki-vk + key: VK_CALLBACK_CONFIRMATION - name: BELKI_DATABASE_URL valueFrom: secretKeyRef: name: belki-vk key: BELKI_DATABASE_URL + ports: + - name: callback + containerPort: 8081 + readinessProbe: + httpGet: + path: /health + port: callback + initialDelaySeconds: 3 + periodSeconds: 10 + livenessProbe: + httpGet: + path: /health + port: callback + initialDelaySeconds: 10 + periodSeconds: 20 securityContext: allowPrivilegeEscalation: false readOnlyRootFilesystem: true runAsNonRoot: true runAsUser: 10001 +--- +apiVersion: v1 +kind: Service +metadata: + name: belki-bot + namespace: belki + labels: + app.kubernetes.io/part-of: belki-calculator +spec: + type: ClusterIP + selector: + app.kubernetes.io/name: belki-bot + ports: + - name: callback + port: 8081 + targetPort: callback # app.yaml defines the app production resource; keep namespace and secret references aligned with belki. diff --git a/deploy/k8s/production.yaml b/deploy/k8s/production.yaml index 198b48d..f7c1eea 100644 --- a/deploy/k8s/production.yaml +++ b/deploy/k8s/production.yaml @@ -194,6 +194,9 @@ spec: image: reg.nyan404.ru/cwshed-clone/belki:6656484 imagePullPolicy: IfNotPresent command: ["python", "-m", "app.belki.vk_bot"] + ports: + - name: callback + containerPort: 8081 env: - name: VK_GROUP_TOKEN valueFrom: @@ -210,6 +213,16 @@ spec: secretKeyRef: name: belki-runtime key: VK_API_VERSION + - name: VK_CALLBACK_SECRET + valueFrom: + secretKeyRef: + name: belki-runtime + key: VK_CALLBACK_SECRET + - name: VK_CALLBACK_CONFIRMATION + valueFrom: + secretKeyRef: + name: belki-runtime + key: VK_CALLBACK_CONFIRMATION - name: BELKI_DATABASE_URL valueFrom: secretKeyRef: @@ -227,4 +240,33 @@ spec: value: https://cat.nyan404.ru - name: BELKI_S3_SECURE value: "false" + readinessProbe: + httpGet: + path: /health + port: callback + initialDelaySeconds: 3 + periodSeconds: 10 + livenessProbe: + httpGet: + path: /health + port: callback + initialDelaySeconds: 10 + periodSeconds: 20 +--- +apiVersion: v1 +kind: Service +metadata: + name: belki-bot + namespace: belki + labels: + app.kubernetes.io/name: belki-bot + app.kubernetes.io/part-of: belki-calculator +spec: + type: ClusterIP + selector: + app.kubernetes.io/name: belki-bot + ports: + - name: callback + port: 8081 + targetPort: callback # production.yaml defines the production production resource; keep namespace and secret references aligned with belki. diff --git a/deploy/k8s/secret.example.yaml b/deploy/k8s/secret.example.yaml index 44bd135..41fa14c 100644 --- a/deploy/k8s/secret.example.yaml +++ b/deploy/k8s/secret.example.yaml @@ -8,6 +8,8 @@ stringData: VK_GROUP_TOKEN: replace-out-of-band VK_GROUP_ID: replace-out-of-band VK_API_VERSION: "5.199" + VK_CALLBACK_SECRET: replace-out-of-band + VK_CALLBACK_CONFIRMATION: replace-out-of-band BELKI_DATABASE_URL: postgresql://belki:replace-out-of-band@postgres:5432/belki POSTGRES_PASSWORD: replace-out-of-band BELKI_ADMIN_PASSWORD: replace-out-of-band diff --git a/nginx.conf b/nginx.conf index 09a4255..99e7c87 100644 --- a/nginx.conf +++ b/nginx.conf @@ -114,6 +114,15 @@ http { proxy_pass http://10.12.0.212/sudoku/; } + location = /api/vk/callback { + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + proxy_pass http://belki-bot:8081/api/vk/callback; + } + location ^~ /api/ { proxy_http_version 1.1; proxy_set_header Host $host; diff --git a/tests/test_vk_bot.py b/tests/test_vk_bot.py index 73ce1ad..e117616 100644 --- a/tests/test_vk_bot.py +++ b/tests/test_vk_bot.py @@ -1,7 +1,5 @@ import unittest import json -from unittest.mock import patch -from urllib.error import URLError from app.belki.vk_bot import ( BelkiDialog, @@ -12,31 +10,63 @@ from app.belki.vk_bot import ( BelkiBot, extract_photo_attachments, ) +from app.belki.vk_callback import process_callback class VkBotTests(unittest.TestCase): - def test_long_poll_reconnects_after_ssl_error(self): + def test_callback_confirmation_requires_valid_secret_and_group(self): + handler = lambda event: None + response = process_callback( + {"type": "confirmation", "group_id": 1, "secret": "secret"}, + secret="secret", expected_secret="secret", group_id=1, + confirmation="confirm-me", claim_event=None, release_event=None, + handle_event=handler, + ) + self.assertEqual((response.status, response.body), (200, "confirm-me")) + self.assertEqual( + process_callback( + {"type": "confirmation", "group_id": 1, "secret": "wrong"}, + secret="wrong", expected_secret="secret", group_id=1, + confirmation="confirm-me", claim_event=None, release_event=None, + handle_event=handler, + ).status, + 403, + ) + + def test_callback_event_is_claimed_once(self): + handled = [] + claimed = set() + + def claim(event_id, event_type): + if event_id in claimed: + return False + claimed.add(event_id) + return True + + payload = {"type": "message_new", "group_id": 1, "secret": "secret", "event_id": "evt-1"} + kwargs = dict(secret="secret", expected_secret="secret", group_id=1, + confirmation="confirm-me", claim_event=claim, release_event=None, + handle_event=handled.append) + self.assertEqual(process_callback(payload, **kwargs).body, "ok") + self.assertEqual(process_callback(payload, **kwargs).body, "ok") + self.assertEqual(handled, [payload]) + + def test_message_event_callback_is_normalized_to_button_message(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"}]}' + def __init__(self): self.sent = [] + def send(self, *args, **kwargs): self.sent.append((args, kwargs)) 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) + bot.application_dialog = type("ApplicationDialog", (), {"is_application_command": lambda *_: False, "handle": lambda *_: None, "keyboard_for": lambda *_: None})() + bot.dialog = type("Dialog", (), {"handle": lambda *_args, **_kwargs: "Ответ", "keyboard_for": lambda *_: None})() + bot.conversation_store = type("Store", (), {})() + bot.handle_event({"type": "message_event", "object": { + "peer_id": 42, "user_id": 42, "payload": '{"command":"menu:help"}', + }}) + self.assertEqual(bot.client.sent[0][0][0], 42) + self.assertEqual(bot.client.sent[0][0][1], "Ответ") 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_callback.py b/tests/test_vk_callback.py new file mode 100644 index 0000000..70e85e1 --- /dev/null +++ b/tests/test_vk_callback.py @@ -0,0 +1,68 @@ +import http.client +import json +import threading +import unittest + +from app.belki.vk_callback import CallbackHTTPServer, process_callback + + +class VkCallbackHTTPTests(unittest.TestCase): + def test_http_callback_confirms_and_dispatches_once(self): + handled = [] + claimed = set() + + def claim(event_id, event_type): + if event_id in claimed: + return False + claimed.add(event_id) + return True + + server = CallbackHTTPServer( + ("127.0.0.1", 0), process_callback, + expected_secret="secret", group_id=7, confirmation="confirm", + claim_event=claim, release_event=claimed.discard, + handle_event=handled.append, + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2) + body = json.dumps({"type": "confirmation", "group_id": 7, "secret": "secret"}) + connection.request("POST", "/api/vk/callback", body, {"Content-Type": "application/json"}) + response = connection.getresponse() + self.assertEqual((response.status, response.read().decode()), (200, "confirm")) + + event = {"type": "message_new", "group_id": 7, "secret": "secret", "event_id": "evt-1"} + for _ in range(2): + connection.request("POST", "/api/vk/callback", json.dumps(event), {"Content-Type": "application/json"}) + response = connection.getresponse() + self.assertEqual((response.status, response.read().decode()), (200, "ok")) + self.assertEqual(handled, [event]) + finally: + connection.close() + server.shutdown() + thread.join(timeout=2) + server.server_close() + + def test_health_endpoint_is_available_for_kubernetes_probe(self): + server = CallbackHTTPServer( + ("127.0.0.1", 0), process_callback, + expected_secret="secret", group_id=7, confirmation="confirm", + claim_event=None, release_event=None, handle_event=lambda event: None, + ) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + try: + connection = http.client.HTTPConnection("127.0.0.1", server.server_port, timeout=2) + connection.request("GET", "/health") + response = connection.getresponse() + self.assertEqual((response.status, response.read().decode()), (200, "ok")) + finally: + connection.close() + server.shutdown() + thread.join(timeout=2) + server.server_close() + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_vk_conversation.py b/tests/test_vk_conversation.py index 279a162..0ed0d05 100644 --- a/tests/test_vk_conversation.py +++ b/tests/test_vk_conversation.py @@ -242,6 +242,14 @@ class VkConversationTests(unittest.TestCase): self.assertIn("подтверд", confirmation.lower()) self.assertEqual(recreated._states[204]["attachments"][0]["url"], "https://example.test/history.jpg") + def test_callback_event_claim_is_idempotent_and_releasable(self): + with TemporaryDirectory() as directory: + store = VkConversationStore(sqlite_path=f"{directory}/vk.sqlite3") + self.assertTrue(store.claim_callback_event("event-1", "message_new")) + self.assertFalse(store.claim_callback_event("event-1", "message_new")) + store.release_callback_event("event-1") + self.assertTrue(store.claim_callback_event("event-1", "message_new")) + def test_inspection_character_without_directory_offers_pairing(self): dialog = BelkiDialog(IdentityDirectory()) dialog.handle(105, "/осмотр")