docs: record VK Callback API architecture
This commit is contained in:
1 parent
a04498d634
commit
ed9203ea77
5 files changed
+27
-15
No files matched your search
@@ -24,7 +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`.
|
- VK Callback API and dialog durability live across `app/belki/vk_bot.py`, `app/belki/vk_callback.py`, and `app/belki/vk_scheduler.py`. The bot listens on callback port 8081; preserve `vk_dialog_states` and `vk_callback_events` when changing dialog steps, attachments, or event dispatch. Validate with `python -m unittest tests.test_vk_bot tests.test_vk_conversation -q`. Production uses `/api/vk/callback` on the existing public host and routes that exact path to the `belki-bot` Service.
|
||||||
- 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.
|
||||||
|
|||||||
@@ -97,6 +97,10 @@ Inspection results persist the base score for the number of inspections and each
|
|||||||
|
|
||||||
`app/belki/domain.py` keeps an explicit `EDIBLE_CATCHES` set for one-point inspection catches. `Ящерица` and `Летучая мышь` are included and covered by `tests/test_belki.py`; the Krylan memo lists them in the edible catch table.
|
`app/belki/domain.py` keeps an explicit `EDIBLE_CATCHES` set for one-point inspection catches. `Ящерица` and `Летучая мышь` are included and covered by `tests/test_belki.py`; the Krylan memo lists them in the edible catch table.
|
||||||
|
|
||||||
|
# 2026-10-10: VK Callback API migration
|
||||||
|
|
||||||
|
`app/belki/vk_bot.py` no longer runs VK Long Poll. It starts a threaded Callback API listener on `VK_CALLBACK_HOST:VK_CALLBACK_PORT` (defaults `0.0.0.0:8081`) and requires `VK_CALLBACK_SECRET` plus `VK_CALLBACK_CONFIRMATION`. `app/belki/vk_callback.py` validates secret/group, returns confirmation or `ok`, normalizes `message_event`, and retries failed handlers by releasing the event claim. `VkConversationStore` persists seven-day callback event claims in `vk_callback_events`. Production routing uses the existing public host path `/api/vk/callback`, an exact nginx route to the `belki-bot` ClusterIP Service, and callback health probes. Live VK server registration and confirmation remain deployment-stage actions.
|
||||||
|
|
||||||
# 2026-10-07: entered report state
|
# 2026-10-07: entered report state
|
||||||
|
|
||||||
`app/belki/history.py` persists an administrative `entered` boolean with an idempotent SQLite/PostgreSQL schema migration. `/api/admin/calculations/{id}/entered` is session-protected and updates one report. `web/admin.html` defaults report history to the calendar current month, prepends an accessible checkbox/checkmark column, and dims rows after entry; sorting remains unchanged.
|
`app/belki/history.py` persists an administrative `entered` boolean with an idempotent SQLite/PostgreSQL schema migration. `/api/admin/calculations/{id}/entered` is session-protected and updates one report. `web/admin.html` defaults report history to the calendar current month, prepends an accessible checkbox/checkmark column, and dims rows after entry; sorting remains unchanged.
|
||||||
+11
-10
@@ -68,9 +68,10 @@ Endpoint должен отвечать быстро и не оставлять V
|
|||||||
|
|
||||||
- `belki-web` запускает `python -m app.main`;
|
- `belki-web` запускает `python -m app.main`;
|
||||||
- `belki-bot` запускает `python -m app.belki.vk_bot`;
|
- `belki-bot` запускает `python -m app.belki.vk_bot`;
|
||||||
- Long Poll находится в `BelkiBot.events()`;
|
- Callback API listener находится в `BelkiBot.run_forever()` и `app/belki/vk_callback.py`;
|
||||||
- gateway уже проксирует `/api/` на адрес Belki web;
|
- gateway уже проксирует `/api/` на адрес Belki web;
|
||||||
- отдельного Service для `belki-bot` нет.
|
- callback listener работает в `belki-bot` на порту `8081`;
|
||||||
|
- внутренний ClusterIP Service `belki-bot` принимает callback-трафик от gateway.
|
||||||
|
|
||||||
Предпочтительная схема миграции:
|
Предпочтительная схема миграции:
|
||||||
|
|
||||||
@@ -92,7 +93,7 @@ belki-bot Service -> callback HTTP listener
|
|||||||
|
|
||||||
Так внешний URL остаётся общим с `/belki` и `/admin`, а обработка событий и планировщик остаются в bot Deployment.
|
Так внешний URL остаётся общим с `/belki` и `/admin`, а обработка событий и планировщик остаются в bot Deployment.
|
||||||
|
|
||||||
В nginx exact location для `/api/vk/callback` должен быть объявлен до общего `location ^~ /api/`, чтобы callback направлялся в bot Service, а остальные API продолжали идти в `belki-web`.
|
В nginx добавлен exact location для `/api/vk/callback`; он направляет callback в `belki-bot:8081`, а остальные API продолжают идти в `belki-web`.
|
||||||
|
|
||||||
## Состояние и повторная доставка
|
## Состояние и повторная доставка
|
||||||
|
|
||||||
@@ -116,16 +117,16 @@ belki-bot Service -> callback HTTP listener
|
|||||||
|
|
||||||
## План миграции
|
## План миграции
|
||||||
|
|
||||||
1. Вынести обработку одного события из Long Poll цикла в переиспользуемый метод.
|
1. Вынести обработку одного события из Long Poll цикла в переиспользуемый метод. **Готово.**
|
||||||
2. Добавить callback HTTP listener в `belki-bot`.
|
2. Добавить callback HTTP listener в `belki-bot`. **Готово.**
|
||||||
3. Добавить проверку секрета, `group_id`, confirmation и дедупликацию.
|
3. Добавить проверку секрета, `group_id`, confirmation и дедупликацию. **Готово.**
|
||||||
4. Добавить внутренний Service для `belki-bot`.
|
4. Добавить внутренний Service для `belki-bot`. **Готово.**
|
||||||
5. Добавить exact маршрут gateway для `/api/vk/callback`.
|
5. Добавить exact маршрут gateway для `/api/vk/callback`. **Готово.**
|
||||||
6. Проверить callback локальным тестовым POST без включения production.
|
6. Проверить callback локальным тестовым POST без включения production. **Покрыто unit-тестами; live VK confirmation ещё не выполнялся.**
|
||||||
7. Зарегистрировать сервер через `groups.addCallbackServer`.
|
7. Зарегистрировать сервер через `groups.addCallbackServer`.
|
||||||
8. Включить только нужные события через `groups.setCallbackSettings`.
|
8. Включить только нужные события через `groups.setCallbackSettings`.
|
||||||
9. Проверить входящие сообщения, вложения, кнопки, заявки, беседы и scheduler delivery.
|
9. Проверить входящие сообщения, вложения, кнопки, заявки, беседы и scheduler delivery.
|
||||||
10. После подтверждения runtime отключить Long Poll.
|
10. После live-подтверждения VK проверить runtime и оставить Long Poll отключённым.
|
||||||
|
|
||||||
## Источники
|
## Источники
|
||||||
|
|
||||||
|
|||||||
+10
-4
@@ -1,6 +1,6 @@
|
|||||||
# Карта проекта «Беличья нора»
|
# Карта проекта «Беличья нора»
|
||||||
|
|
||||||
Актуально на 2026-08-25. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур.
|
Актуально на 2026-10-10. Карта описывает добавленный функционал Белок; legacy userscript-файлы остаются отдельными статическими материалами и не входят в расчётный контур.
|
||||||
|
|
||||||
```mermaid
|
```mermaid
|
||||||
mindmap
|
mindmap
|
||||||
@@ -45,8 +45,12 @@ mindmap
|
|||||||
web/applications.html
|
web/applications.html
|
||||||
VK bot
|
VK bot
|
||||||
vk_bot.py
|
vk_bot.py
|
||||||
Long Poll
|
Callback API listener :8081
|
||||||
reconnect on SSL/socket/timeout
|
secret and group validation
|
||||||
|
confirmation response
|
||||||
|
message_new and message_event
|
||||||
|
callback event deduplication
|
||||||
|
vk_callback_events, seven-day retention
|
||||||
Step dialogs
|
Step dialogs
|
||||||
durable vk_dialog_states checkpoint
|
durable vk_dialog_states checkpoint
|
||||||
Natural one-line parser
|
Natural one-line parser
|
||||||
@@ -116,7 +120,9 @@ mindmap
|
|||||||
flowchart LR
|
flowchart LR
|
||||||
Browser[Публичный браузер] --> Web[BelkiHTTPServer]
|
Browser[Публичный браузер] --> Web[BelkiHTTPServer]
|
||||||
Browser -->|inspection screenshot only| Web
|
Browser -->|inspection screenshot only| Web
|
||||||
VK[VK Long Poll] --> Bot[BelkiDialog]
|
VK[VK Callback API] -->|/api/vk/callback| Gateway[cwshed gateway]
|
||||||
|
Gateway -->|exact route| BotHTTP[belki-bot :8081]
|
||||||
|
BotHTTP --> Bot[BelkiDialog]
|
||||||
Web --> Domain[Расчётное ядро]
|
Web --> Domain[Расчётное ядро]
|
||||||
Bot --> Domain
|
Bot --> Domain
|
||||||
Web --> Store[(PostgreSQL or SQLite)]
|
Web --> Store[(PostgreSQL or SQLite)]
|
||||||
|
|||||||
@@ -129,6 +129,7 @@
|
|||||||
- 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation.
|
- 2026-08-25: removed unreferenced root-level legacy BBCode copies `belki.md`, `belki2.md`, and `belkifix.md`; the first two were byte-identical and the third differed only by a closing BBCode tag. They were neither served nor referenced by the calculator, bot, or documentation.
|
||||||
- 2026-09-21: `InspectionResult` now keeps the base inspection score and per-resource score entries alongside the total. The `/admin` report table renders these values in a dedicated `Баллы` column; older history rows still show their stored total when detailed fields are absent. The public report message remains unchanged.
|
- 2026-09-21: `InspectionResult` now keeps the base inspection score and per-resource score entries alongside the total. The `/admin` report table renders these values in a dedicated `Баллы` column; older history rows still show their stored total when detailed fields are absent. The public report message remains unchanged.
|
||||||
- 2026-09-26: inspection scoring now has an explicit `EDIBLE_CATCHES` catalogue in `app/belki/domain.py`; `Ящерица` and `Летучая мышь` are documented as one-point catches and covered by regression tests.
|
- 2026-09-26: inspection scoring now has an explicit `EDIBLE_CATCHES` catalogue in `app/belki/domain.py`; `Ящерица` and `Летучая мышь` are documented as one-point catches and covered by regression tests.
|
||||||
|
- 2026-10-10: VK input migrated from Long Poll to Callback API. `app/belki/vk_bot.py` now serves `/api/vk/callback` on port 8081, validates the callback secret and group ID, handles `message_new`/`message_event`, and keeps scheduler/notifier threads in the bot process. `vk_callback_events` deduplicates callback event IDs for seven days and releases failed claims for VK retry. `deploy/k8s/*` adds the `belki-bot` ClusterIP Service and callback probes; `nginx.conf` routes only the exact callback path to the bot while other `/api/` requests remain on `belki-web`. Public registration and live VK confirmation are still a deployment-stage action.
|
||||||
# Обновление 2026-08-16: несколько котят
|
# Обновление 2026-08-16: несколько котят
|
||||||
|
|
||||||
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
Калькулятор прокачки принимает `extra_kittens` из веб-формы, API и VK-команды. Общая выплата сопровождающему не суммирует полную ставку на каждого котёнка: первый подопечный использует базовый коэффициент, второй — множитель 1,5, каждый следующий — дополнительный множитель 1,15. Сайт добавляет строки дополнительных котят динамически; VK поддерживает сегмент `доп. котята: Имя [ID], Имя2 [ID]`.
|
||||||
|
|||||||
Reference in new issue
Block a user