Merge remote-tracking branch 'origin/dev' into fix/clinical-review-safety
CI / ruff · pytest (pull_request) Successful in 2m22s
CI / ruff · pytest (pull_request) Successful in 2m22s
This commit is contained in:
@@ -0,0 +1,115 @@
|
||||
"""Server API for a future MAX connect UI; webhook processing is supplied by the channel adapter."""
|
||||
|
||||
import hmac
|
||||
import json
|
||||
import re
|
||||
from datetime import datetime
|
||||
from typing import Annotated, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request
|
||||
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from pydantic import BaseModel, ConfigDict
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
|
||||
from app.config import get_settings
|
||||
from app.core import clock
|
||||
from app.db import repo
|
||||
from app.db.max_notifications import MaxBinding, MaxDelivery
|
||||
from app.db.session import get_clinical_session, get_identity_session
|
||||
from app.integrations import max_store
|
||||
|
||||
router = APIRouter(tags=["max-notifications"])
|
||||
bearer = HTTPBearer(auto_error=False)
|
||||
|
||||
|
||||
async def patient_token(auth: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer)]) -> str:
|
||||
if auth is None or auth.scheme.lower() != "bearer" or not re.fullmatch(r"[A-Za-z0-9_-]{1,64}", auth.credentials):
|
||||
raise HTTPException(401, "patient authentication required", headers={"WWW-Authenticate": "Bearer"})
|
||||
async with get_clinical_session() as session:
|
||||
if await repo.get_profile(session, auth.credentials) is None:
|
||||
raise HTTPException(401, "patient authentication required")
|
||||
return auth.credentials
|
||||
|
||||
|
||||
PatientToken = Annotated[str, Depends(patient_token)]
|
||||
|
||||
|
||||
class MaxStatus(BaseModel):
|
||||
available: bool
|
||||
connected: bool
|
||||
last_delivery: str | None = None
|
||||
|
||||
|
||||
class LinkConsent(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid")
|
||||
consent: Literal[True]
|
||||
|
||||
|
||||
class MaxLink(BaseModel):
|
||||
url: str
|
||||
expires_at: datetime
|
||||
|
||||
|
||||
@router.get("/me/notifications/max", response_model=MaxStatus)
|
||||
async def status(token: PatientToken) -> MaxStatus:
|
||||
async with get_identity_session() as session:
|
||||
binding = await session.get(MaxBinding, token)
|
||||
last = await session.scalar(
|
||||
select(MaxDelivery.state)
|
||||
.where(MaxDelivery.token == token)
|
||||
.order_by(MaxDelivery.created_at.desc(), MaxDelivery.id.desc())
|
||||
.limit(1)
|
||||
)
|
||||
return MaxStatus(
|
||||
available=get_settings().max_enabled, connected=bool(binding and binding.enabled), last_delivery=last
|
||||
)
|
||||
|
||||
|
||||
@router.post("/me/notifications/max/link", response_model=MaxLink)
|
||||
async def link(body: LinkConsent, token: PatientToken) -> MaxLink:
|
||||
settings = get_settings()
|
||||
if not settings.max_enabled:
|
||||
raise HTTPException(503, "MAX is not configured")
|
||||
if not await max_store.active_patient(token):
|
||||
raise HTTPException(403, "active consent and adult confirmation required")
|
||||
async with get_identity_session() as session:
|
||||
raw, expires = await max_store.issue_code(session, token, clock.now(), settings.max_link_ttl_seconds)
|
||||
return MaxLink(url=f"https://max.ru/{settings.max_bot_username}?start={raw}", expires_at=expires)
|
||||
|
||||
|
||||
@router.delete("/me/notifications/max", response_model=MaxStatus)
|
||||
async def unlink(token: PatientToken) -> MaxStatus:
|
||||
async with get_identity_session() as session:
|
||||
await max_store.disconnect(session, token)
|
||||
return MaxStatus(available=get_settings().max_enabled, connected=False)
|
||||
|
||||
|
||||
@router.post("/webhooks/max")
|
||||
async def webhook(request: Request) -> dict[str, bool]:
|
||||
settings = get_settings()
|
||||
if not settings.max_enabled:
|
||||
raise HTTPException(503, "MAX is not configured")
|
||||
expected = settings.max_webhook_secret.get_secret_value().encode()
|
||||
supplied = request.headers.get("X-Max-Bot-Api-Secret", "").encode()
|
||||
if not expected or not hmac.compare_digest(supplied, expected):
|
||||
raise HTTPException(403, "invalid webhook secret")
|
||||
raw = bytearray()
|
||||
async for chunk in request.stream():
|
||||
raw.extend(chunk)
|
||||
if len(raw) > 65536:
|
||||
raise HTTPException(413, "event is too large")
|
||||
try:
|
||||
event = json.loads(raw)
|
||||
except (ValueError, UnicodeError) as exc:
|
||||
raise HTTPException(400, "invalid JSON") from exc
|
||||
if not isinstance(event, dict):
|
||||
raise HTTPException(422, "event must be an object")
|
||||
from app.channels.max_bot import handle_update
|
||||
|
||||
try:
|
||||
await handle_update(event)
|
||||
except SQLAlchemyError:
|
||||
# Let MAX retry; do not log DB exception parameters containing identity data.
|
||||
raise HTTPException(503, "notification storage unavailable") from None
|
||||
return {"success": True}
|
||||
+2
-1
@@ -15,7 +15,7 @@ from sqlalchemy import select
|
||||
|
||||
from app.api import demo as console
|
||||
from app.api import doctor_views as views
|
||||
from app.api import fixtures
|
||||
from app.api import fixtures, max_notifications
|
||||
from app.api.patient_web import router as patient_web_router
|
||||
from app.api.questionnaire import router as questionnaire_router
|
||||
from app.api.schemas import (
|
||||
@@ -46,6 +46,7 @@ from app.scheduler import jobs as scheduler
|
||||
from app.services.monitoring import refresh_status
|
||||
|
||||
router = APIRouter(prefix="/api/v1")
|
||||
router.include_router(max_notifications.router)
|
||||
router.include_router(questionnaire_router)
|
||||
router.include_router(patient_web_router)
|
||||
|
||||
|
||||
@@ -0,0 +1,150 @@
|
||||
# Подключение будущего бота MAX
|
||||
|
||||
Серверная часть готова к подключению. Сам бот ещё не создан, секреты не заполнены,
|
||||
реальная отправка не включена. Изменений интерфейса сайта в этой поставке нет.
|
||||
Интеграция уведомляет **самого пациента**; врачебные оповещения остаются в существующем канале проекта.
|
||||
|
||||
## Что реализовано
|
||||
|
||||
- Одноразовая ссылка для привязки аккаунта MAX к текущему пациенту сайта, срок по умолчанию 10 минут.
|
||||
- Подтверждение подключения, `/help`, `/stop`, отключение при остановке или удалении бота в MAX.
|
||||
- Нейтральные напоминания из существующего планировщика сайта: тесты, дневник, приём лекарств и другие события outbox.
|
||||
- Уведомление о завершении теста: сервер каждые примерно 30 секунд находит новые завершённые
|
||||
`QuestionnaireRecord` и `ScaleResult`, начиная с момента подключения MAX. Незавершённые и старые тесты не отправляются.
|
||||
- Постоянная очередь, восстановление после перезапуска, ограниченные повторы при сетевых ошибках и ответах 429/5xx.
|
||||
- В сообщении только короткий текст и кнопка на сайт. Ответы, оценки, диагнозы, назначения и ключ входа на сайт
|
||||
в MAX не передаются. Переписка с ботом не сохраняется и не отправляется в LLM.
|
||||
|
||||
## 1. Создать бота — будущему владельцу
|
||||
|
||||
1. Открыть [MAX для партнёров](https://business.max.ru/) и пройти регистрацию/проверку профиля.
|
||||
Условия допуска зависят от типа владельца; актуальный порядок — в
|
||||
[официальной инструкции подключения](https://dev.max.ru/help/platform_connection).
|
||||
2. Создать чат-бота, оформить описание и пройти требуемую MAX модерацию.
|
||||
3. В настройках бота получить токен и скопировать имя из его публичной ссылки `https://max.ru/ИМЯ`.
|
||||
4. Передать администратору сервера имя бота, а токен — через защищённое хранилище секретов.
|
||||
Токен не нужен в переписке, MR или репозитории.
|
||||
|
||||
## 2. Заполнить настройки сервера
|
||||
|
||||
Нужны доступная identity/clinical БД проекта, публичный HTTPS-адрес сайта и HTTPS-адрес API на порту 443.
|
||||
Входящие POST от MAX должны доходить до API без браузерной CAPTCHA или страницы авторизации.
|
||||
Прокси должен передавать заголовок `X-Max-Bot-Api-Secret` и не журналировать тело webhook/Authorization.
|
||||
Дополнительные таблицы identity создаются существующим `init_db()` при запуске приложения.
|
||||
|
||||
В `.env` сервера (вне Git) заполнить:
|
||||
|
||||
```dotenv
|
||||
MAX_ENABLED=false
|
||||
MAX_BOT_TOKEN=
|
||||
MAX_BOT_USERNAME=
|
||||
MAX_WEBHOOK_SECRET=
|
||||
MAX_WEBHOOK_URL=https://api.example.org/api/v1/webhooks/max
|
||||
MAX_SITE_URL=https://patient.example.org/
|
||||
MAX_LINK_TTL_SECONDS=600
|
||||
# При необходимости — PEM-файл доверенного CA, доступный внутри контейнера:
|
||||
MAX_CA_BUNDLE=
|
||||
DEMO_CLOCK=false
|
||||
```
|
||||
|
||||
- `MAX_BOT_USERNAME` — только имя, без `@`, домена или параметров ссылки.
|
||||
- `MAX_WEBHOOK_SECRET` — отдельная случайная строка, не токен бота: 32–256 символов из `A–Z a–z 0–9 _ -`.
|
||||
Сгенерировать локально, например `python -c 'import secrets; print(secrets.token_urlsafe(32))'`, сохранить в секреты.
|
||||
- `MAX_SITE_URL` ведёт в обычный личный кабинет; не добавлять в адрес ключи доступа или данные пациента.
|
||||
- Исходящие запросы идут на `https://platform-api2.max.ru`, токен передаётся заголовком `Authorization`.
|
||||
Верификация TLS всегда включена. Если системе нужен корневой сертификат Минцифры, установить его по
|
||||
официальной инструкции MAX и указать PEM-путь в `MAX_CA_BUNDLE`; не отключать проверку TLS.
|
||||
- Переменные должны попасть именно в окружение API-контейнера/процесса, а не только панели сайта.
|
||||
В текущем Compose сервис `app` уже получает `.env` через `env_file`.
|
||||
После изменения окружения пересоздать процесс/контейнер API. Новые зависимости не требуются.
|
||||
|
||||
## 3. Проверить и включить
|
||||
|
||||
В каталоге проекта, в том же окружении, где работает API:
|
||||
|
||||
```sh
|
||||
uv run python -m app.channels.max_setup check
|
||||
```
|
||||
|
||||
Команда проверит токен и совпадение имени бота. Сообщений пользователям она не отправляет.
|
||||
Затем установить `MAX_ENABLED=true`, перезапустить API и выполнить:
|
||||
|
||||
```sh
|
||||
uv run python -m app.channels.max_setup subscribe
|
||||
uv run python -m app.channels.max_setup status
|
||||
```
|
||||
|
||||
`subscribe` регистрирует только заданный webhook с секретом и событиями
|
||||
`bot_started`, `message_created`, `bot_stopped`, `dialog_removed`. Старые чужие подписки автоматически
|
||||
не удаляются: при переносе сервера владелец должен проверить их отдельно через MAX API.
|
||||
`status` проверяет регистрацию адреса; это ещё не проверка доступности сервера из MAX.
|
||||
Команды не печатают токены, секрет webhook или сырые ответы платформы.
|
||||
|
||||
При запуске через Compose вместо `uv run python ...` использовать
|
||||
`docker compose exec app python -m app.channels.max_setup check` (также `subscribe` и `status`).
|
||||
После изменения `.env` пересоздать API: `docker compose up -d --build --force-recreate app`.
|
||||
|
||||
Запускать один процесс API с MAX на один токен бота: его worker отправляет до одного сообщения в секунду.
|
||||
БД защищает очередь от параллельного захвата, но общий лимит скорости нескольких процессов не координируется.
|
||||
Планировщик и MAX worker запускаются вместе с FastAPI, отдельный процесс бота не нужен.
|
||||
При `MAX_ENABLED=false` сетевых вызовов MAX и фонового worker нет; сайт продолжает обычную работу.
|
||||
|
||||
## API для разработчика сайта
|
||||
|
||||
В проекте используется ключ текущего пациента, полученный при входе. Для этих ручек передавать его
|
||||
как `Authorization: Bearer <patient_token>`; это существующая авторизация прототипа, не новая система SSO.
|
||||
Не брать token другого пациента и не публиковать демонстрационные учётные записи для реального использования.
|
||||
|
||||
| Метод и путь | Запрос | Ответ |
|
||||
|---|---|---|
|
||||
| `GET /api/v1/me/notifications/max` | Authorization | `available`, `connected`, `last_delivery` |
|
||||
| `POST /api/v1/me/notifications/max/link` | Authorization; JSON `{"consent": true}` | `url`, `expires_at` |
|
||||
| `DELETE /api/v1/me/notifications/max` | Authorization | состояние с `connected: false` |
|
||||
| `POST /api/v1/webhooks/max` | MAX JSON + `X-Max-Bot-Api-Secret` | `{"success": true}` после записи события |
|
||||
|
||||
Поток подключения: пациент явно соглашается на уведомления → сайт получает `url` → открывает ссылку MAX →
|
||||
пользователь запускает бота → webhook подтверждает привязку → повторный GET показывает `connected: true`.
|
||||
Ссылка одноразовая; новая ссылка отменяет предыдущую. Изначальный ключ пациента не входит в URL MAX.
|
||||
Для привязки и доставки дополнительно нужны действующее согласие и подтверждение совершеннолетия в состоянии пациента.
|
||||
Активную привязку нельзя молча переназначить другому аккаунту: сначала отключить её.
|
||||
|
||||
Коды ошибок: 401 — неизвестный/отсутствующий ключ пациента; 403 — нет согласия или неверный секрет webhook;
|
||||
422 — неверный запрос; 413 — webhook больше 64 КиБ; 503 — MAX выключен или хранилище события недоступно.
|
||||
Повтор webhook с тем же идентификатором события не создаёт новых отправок. Групповые чаты игнорируются.
|
||||
|
||||
`last_delivery`: `queued`, `sending`, `sent`, `failed`, `cancelled` или `null`.
|
||||
`sent` означает принятие сообщения API MAX, а не прочтение человеком.
|
||||
|
||||
## Пробное подключение после создания бота
|
||||
|
||||
1. Войти на сайте синтетическим пациентом и дать необходимые согласия.
|
||||
2. Получить ссылку через POST выше (Swagger `/docs` или будущий интерфейс сайта), перейти в MAX и запустить бота.
|
||||
3. Убедиться, что GET показывает `connected: true` и приходит подтверждение.
|
||||
4. Завершить тест на сайте; примерно через 30 секунд плюс очередь должно прийти сообщение без результатов.
|
||||
5. Дождаться события планировщика и проверить нейтральное напоминание с кнопкой на сайт.
|
||||
6. Отправить `/stop`: GET должен показать `connected: false`, ожидающие уведомления отменяются.
|
||||
7. Повторить подключение новой ссылкой, проверить DELETE через API и остановку бота через интерфейс MAX.
|
||||
|
||||
При недоставке проверить настройки и подписку, доступность HTTPS, состояние очереди и коды ошибок в логах.
|
||||
`http_401`/`http_403` требуют проверки токена/прав; `http_429` — ожидания; `transport` — сети/TLS;
|
||||
`failed` после шести попыток требует вмешательства администратора. Детали ответов и идентификаторы в логи не выводятся.
|
||||
Отключение отменяет очередь; уже принятый MAX запрос отозвать невозможно.
|
||||
|
||||
## Гарантии и ограничения
|
||||
|
||||
Очередь и подтверждения событий сохраняются в identity БД. Клинические записи остаются в clinical БД.
|
||||
Для событий завершения тестов БД повторно просматривается после перезапуска; ключи уведомлений предотвращают
|
||||
повторную постановку. Напоминания используют существующий механизм outbox/повторов планировщика.
|
||||
При временных ошибках — до 6 попыток с увеличением задержки и учётом `Retry-After`; зависшая отправка получает
|
||||
новую аренду через 60 секунд. Потеря процесса между принятием сообщения MAX и записью успеха в БД может
|
||||
привести к повторному сообщению: MAX не предоставляет ключ идемпотентности отправки.
|
||||
Не удалять строки дедупликации/очереди без согласованной политики хранения. При большом количестве пациентов
|
||||
нужны пакетное сканирование завершённых тестов и общий ограничитель скорости; текущая реализация рассчитана на MVP.
|
||||
|
||||
Проверки разработчика: `make lint test`; тесты MAX работают с синтетикой и подменённым HTTP-транспортом.
|
||||
Реальную доставку подтвердит только пробное подключение после выдачи токена и настройки публичного сервера.
|
||||
|
||||
Официальные контракты: [отправка сообщений](https://dev.max.ru/docs-api/methods/POST/messages),
|
||||
[подписка webhook](https://dev.max.ru/docs-api/methods/POST/subscriptions),
|
||||
[события](https://dev.max.ru/docs-api/objects/Update),
|
||||
[ссылки запуска бота](https://dev.max.ru/docs/chatbots/bots-coding/prepare).
|
||||
@@ -0,0 +1,224 @@
|
||||
"""Notifications-only MAX adapter; no patient text enters the dialog engine or an LLM.
|
||||
|
||||
Webhook transactions persist receipts and replies together, then return immediately.
|
||||
The worker delivers from identity DB with leases and bounded retries. MAX has no send
|
||||
idempotency key: a crash after API acceptance and before commit can duplicate a message.
|
||||
"""
|
||||
|
||||
import asyncio
|
||||
import contextlib
|
||||
import json
|
||||
import logging
|
||||
from functools import lru_cache
|
||||
|
||||
import yaml
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app.channels.max_client import MaxApiError, MaxClient
|
||||
from app.config import get_settings
|
||||
from app.core import clock
|
||||
from app.db.max_notifications import MaxBinding, MaxReceipt
|
||||
from app.db.session import get_identity_session
|
||||
from app.dialog.contracts import Reply
|
||||
from app.integrations import max_store as store
|
||||
from app.integrations.base import Outbox, integrations
|
||||
|
||||
log = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Texts(BaseModel):
|
||||
connected: str = Field(max_length=4000)
|
||||
not_connected: str = Field(max_length=4000)
|
||||
invalid: str = Field(max_length=4000)
|
||||
stopped: str = Field(max_length=4000)
|
||||
help: str = Field(max_length=4000)
|
||||
notification: str = Field(max_length=4000)
|
||||
completed: str = Field(max_length=4000)
|
||||
open_site: str = Field(max_length=128)
|
||||
|
||||
|
||||
@lru_cache
|
||||
def texts() -> Texts:
|
||||
path = get_settings().config_dir / "texts" / "max.yaml"
|
||||
return Texts.model_validate(yaml.safe_load(path.read_text(encoding="utf-8")))
|
||||
|
||||
|
||||
def _event(event: dict) -> tuple[str, int, str, str] | None:
|
||||
"""Normalize only documented private-user events; unknown/malformed events are ignored."""
|
||||
kind = event.get("update_type")
|
||||
stamp = event.get("timestamp")
|
||||
if type(stamp) is not int or stamp < 0:
|
||||
return None
|
||||
message_id = ""
|
||||
if kind == "message_created":
|
||||
message = event.get("message")
|
||||
if not isinstance(message, dict):
|
||||
return None
|
||||
recipient, body = message.get("recipient"), message.get("body")
|
||||
if not isinstance(recipient, dict) or recipient.get("chat_type") != "dialog" or not isinstance(body, dict):
|
||||
return None
|
||||
user, text, message_id = message.get("sender"), body.get("text"), body.get("mid")
|
||||
if not isinstance(message_id, str) or not message_id or not isinstance(text, str):
|
||||
return None
|
||||
elif kind in ("bot_started", "bot_stopped", "dialog_removed"):
|
||||
user, text = event.get("user"), event.get("payload") or ""
|
||||
else:
|
||||
return None
|
||||
if not isinstance(user, dict) or user.get("is_bot") is not False:
|
||||
return None
|
||||
uid = user.get("user_id")
|
||||
if type(uid) is not int or not 0 < uid < 2**63 or not isinstance(text, str) or len(text) > 4000:
|
||||
return None
|
||||
# Names, profile details and raw text are neither persisted nor logged.
|
||||
receipt = store.digest(f"{kind}:{uid}:{message_id or stamp}")
|
||||
return kind, uid, text.strip(), receipt
|
||||
|
||||
|
||||
async def handle_update(event: dict) -> None:
|
||||
if not get_settings().max_enabled or (parsed := _event(event)) is None:
|
||||
return
|
||||
kind, user_id, text, receipt = parsed
|
||||
now = clock.now()
|
||||
try:
|
||||
async with get_identity_session() as session:
|
||||
if await session.get(MaxReceipt, receipt):
|
||||
return
|
||||
session.add(MaxReceipt(digest=receipt, received_at=now))
|
||||
await session.flush()
|
||||
binding = await session.scalar(select(MaxBinding).where(MaxBinding.user_id == user_id))
|
||||
reply_token = None
|
||||
command, _, payload = text.partition(" ")
|
||||
if kind in ("bot_stopped", "dialog_removed") or command.lower() == "/stop":
|
||||
if binding:
|
||||
await store.disconnect(session, binding.token)
|
||||
# When MAX itself stops/deletes the bot, do not attempt a reply.
|
||||
if kind != "message_created":
|
||||
return
|
||||
reply = "stopped"
|
||||
elif kind == "bot_started" or command.lower() == "/start":
|
||||
code = text if kind == "bot_started" else payload.strip()
|
||||
if code:
|
||||
token = await store.code_token(session, code, now) if len(code) <= 128 else None
|
||||
linked = (
|
||||
token and await store.active_patient(token) and await store.bind(session, code, user_id, now)
|
||||
)
|
||||
reply = "connected" if linked else "invalid"
|
||||
reply_token = token if linked else None
|
||||
else:
|
||||
reply = "connected" if binding and binding.enabled else "not_connected"
|
||||
reply_token = binding.token if binding and binding.enabled else None
|
||||
else:
|
||||
reply = "help"
|
||||
await store.enqueue(session, key=receipt, user_id=user_id, token=reply_token, kind=reply, now=now)
|
||||
except IntegrityError:
|
||||
# A concurrent delivery of the same webhook can race on its receipt primary key.
|
||||
async with get_identity_session() as session:
|
||||
if await session.get(MaxReceipt, receipt) is None:
|
||||
raise
|
||||
|
||||
|
||||
class MaxOutbox:
|
||||
def __init__(self, fallback: Outbox):
|
||||
self.fallback = fallback
|
||||
|
||||
async def push(self, token: str, replies: list[Reply]) -> None:
|
||||
if replies and get_settings().max_enabled and await store.active_patient(token):
|
||||
async with get_identity_session() as session:
|
||||
binding = await session.get(MaxBinding, token)
|
||||
if binding and binding.enabled:
|
||||
# Hash the event for retry deduplication; never store/transmit its clinical text.
|
||||
event = json.dumps([r.model_dump() for r in replies], sort_keys=True, ensure_ascii=False)
|
||||
key = store.digest(f"{token}:{binding.connected_at.isoformat()}:{clock.today()}:{event}")
|
||||
await store.enqueue(
|
||||
session, key=key, user_id=binding.user_id, token=token, kind="notification", now=clock.now()
|
||||
)
|
||||
await self.fallback.push(token, replies)
|
||||
|
||||
|
||||
async def deliver_one(client: MaxClient) -> bool:
|
||||
async with get_identity_session() as session:
|
||||
row = await store.claim(session, clock.now())
|
||||
if row is None:
|
||||
return False
|
||||
if row.token is not None:
|
||||
async with get_identity_session() as session:
|
||||
binding = await session.get(MaxBinding, row.token)
|
||||
valid = (
|
||||
binding
|
||||
and binding.enabled
|
||||
and binding.user_id == row.user_id
|
||||
and binding.connected_at <= row.created_at
|
||||
)
|
||||
if not valid or not await store.active_patient(row.token):
|
||||
async with get_identity_session() as session:
|
||||
await store.finish(session, row, state="cancelled", now=clock.now())
|
||||
return True
|
||||
settings, messages = get_settings(), texts()
|
||||
try:
|
||||
await client.send(
|
||||
row.user_id, getattr(messages, row.kind), site_url=settings.max_site_url, button=messages.open_site
|
||||
)
|
||||
except MaxApiError as exc:
|
||||
retry = exc.retryable and row.attempts < store.MAX_ATTEMPTS
|
||||
delay = max(exc.retry_after, min(300, 5 * 2 ** (row.attempts - 1)))
|
||||
async with get_identity_session() as session:
|
||||
await store.finish(
|
||||
session,
|
||||
row,
|
||||
state="queued" if retry else "failed",
|
||||
now=clock.now(),
|
||||
error=exc.code,
|
||||
retry_seconds=delay if retry else 0,
|
||||
)
|
||||
log.warning("MAX delivery deferred=%s code=%s", retry, exc.code)
|
||||
else:
|
||||
async with get_identity_session() as session:
|
||||
await store.finish(session, row, state="sent", now=clock.now())
|
||||
return True
|
||||
|
||||
|
||||
async def _run(client: MaxClient) -> None:
|
||||
tick = 0
|
||||
while True:
|
||||
try:
|
||||
if tick % 30 == 0:
|
||||
async with get_identity_session() as session:
|
||||
await store.collect_completed(session, clock.now())
|
||||
await deliver_one(client)
|
||||
except Exception as exc:
|
||||
# No exception text: SQL/HTTP errors may contain identifiers or parameters.
|
||||
log.error("MAX worker failed type=%s", type(exc).__name__)
|
||||
tick += 1
|
||||
# One send per second per process, below MAX's two-per-second per-dialog limit.
|
||||
await asyncio.sleep(1)
|
||||
|
||||
|
||||
_client: MaxClient | None = None
|
||||
_task: asyncio.Task | None = None
|
||||
_wrapper: MaxOutbox | None = None
|
||||
|
||||
|
||||
async def start() -> None:
|
||||
global _client, _task, _wrapper
|
||||
if not get_settings().max_enabled or _task is not None:
|
||||
return
|
||||
texts() # Validate templates before replacing a working outbox.
|
||||
_client = MaxClient(get_settings())
|
||||
_wrapper = MaxOutbox(integrations.outbox)
|
||||
integrations.outbox = _wrapper
|
||||
_task = asyncio.create_task(_run(_client), name="max-notifications")
|
||||
|
||||
|
||||
async def stop() -> None:
|
||||
global _client, _task, _wrapper
|
||||
if _task:
|
||||
_task.cancel()
|
||||
with contextlib.suppress(asyncio.CancelledError):
|
||||
await _task
|
||||
if _wrapper and integrations.outbox is _wrapper:
|
||||
integrations.outbox = _wrapper.fallback
|
||||
if _client:
|
||||
await _client.close()
|
||||
_client = _task = _wrapper = None
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Small MAX Bot API client. Secrets stay in headers; failures never expose response bodies."""
|
||||
|
||||
import logging
|
||||
import ssl
|
||||
|
||||
import httpx
|
||||
|
||||
from app.config import Settings
|
||||
|
||||
API_URL = "https://platform-api2.max.ru"
|
||||
UPDATE_TYPES = ["bot_started", "message_created", "bot_stopped", "dialog_removed"]
|
||||
|
||||
|
||||
class _HideRecipient(logging.Filter):
|
||||
def filter(self, record: logging.LogRecord) -> bool:
|
||||
# httpx INFO normally logs query strings, which include a MAX user_id.
|
||||
return "platform-api2.max.ru" not in record.getMessage()
|
||||
|
||||
|
||||
logging.getLogger("httpx").addFilter(_HideRecipient())
|
||||
|
||||
|
||||
class MaxApiError(Exception):
|
||||
def __init__(self, code: str, *, retryable: bool = False, retry_after: float = 0):
|
||||
self.code, self.retryable, self.retry_after = code, retryable, retry_after
|
||||
super().__init__(code)
|
||||
|
||||
|
||||
class MaxClient:
|
||||
def __init__(self, settings: Settings, *, transport: httpx.AsyncBaseTransport | None = None):
|
||||
context = ssl.create_default_context()
|
||||
if settings.max_ca_bundle:
|
||||
context.load_verify_locations(cafile=str(settings.max_ca_bundle))
|
||||
self.http = httpx.AsyncClient(
|
||||
base_url=API_URL,
|
||||
headers={"Authorization": settings.max_bot_token.get_secret_value()},
|
||||
timeout=httpx.Timeout(5),
|
||||
verify=context,
|
||||
follow_redirects=False,
|
||||
transport=transport,
|
||||
)
|
||||
|
||||
async def close(self) -> None:
|
||||
await self.http.aclose()
|
||||
|
||||
async def request(self, method: str, path: str, **kwargs) -> dict:
|
||||
try:
|
||||
response = await self.http.request(method, path, **kwargs)
|
||||
except httpx.RequestError:
|
||||
raise MaxApiError("transport", retryable=True) from None
|
||||
if not response.is_success:
|
||||
try:
|
||||
delay = min(3600, max(0, float(response.headers.get("Retry-After", "0"))))
|
||||
except ValueError:
|
||||
delay = 0
|
||||
raise MaxApiError(
|
||||
f"http_{response.status_code}",
|
||||
retryable=response.status_code in (408, 429) or response.status_code >= 500,
|
||||
retry_after=delay,
|
||||
)
|
||||
try:
|
||||
data = response.json()
|
||||
except ValueError:
|
||||
raise MaxApiError("invalid_response", retryable=True) from None
|
||||
if not isinstance(data, dict):
|
||||
raise MaxApiError("invalid_response", retryable=True)
|
||||
if data.get("success") is False:
|
||||
raise MaxApiError("rejected")
|
||||
return data
|
||||
|
||||
async def send(self, user_id: int, text: str, *, site_url: str, button: str) -> None:
|
||||
data = await self.request(
|
||||
"POST",
|
||||
"/messages",
|
||||
params={"user_id": user_id, "disable_link_preview": "true"},
|
||||
json={
|
||||
"text": text,
|
||||
"notify": True,
|
||||
"attachments": [
|
||||
{
|
||||
"type": "inline_keyboard",
|
||||
"payload": {"buttons": [[{"type": "link", "text": button, "url": site_url}]]},
|
||||
}
|
||||
],
|
||||
},
|
||||
)
|
||||
if not isinstance(data.get("message"), dict):
|
||||
raise MaxApiError("missing_message", retryable=True)
|
||||
|
||||
async def subscribe(self, settings: Settings) -> None:
|
||||
data = await self.request(
|
||||
"POST",
|
||||
"/subscriptions",
|
||||
json={
|
||||
"url": settings.max_webhook_url,
|
||||
"update_types": UPDATE_TYPES,
|
||||
"secret": settings.max_webhook_secret.get_secret_value(),
|
||||
},
|
||||
)
|
||||
if data.get("success") is not True:
|
||||
raise MaxApiError("subscription_not_confirmed")
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Operator commands for a future bot owner. Never runs as part of application startup."""
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
import sys
|
||||
|
||||
from pydantic import ValidationError
|
||||
|
||||
from app.channels.max_client import MaxApiError, MaxClient
|
||||
from app.config import Settings
|
||||
|
||||
|
||||
async def run(command: str) -> None:
|
||||
# Validate the same configuration even while the deployed app is still disabled.
|
||||
settings = Settings(max_enabled=True)
|
||||
client = MaxClient(settings)
|
||||
try:
|
||||
bot = await client.request("GET", "/me")
|
||||
if bot.get("is_bot") is not True:
|
||||
raise MaxApiError("not_a_bot")
|
||||
if bot.get("username") != settings.max_bot_username:
|
||||
raise MaxApiError("bot_username_mismatch")
|
||||
if command == "subscribe":
|
||||
await client.subscribe(settings)
|
||||
print("Webhook MAX зарегистрирован. Проверьте командой status, затем выполните пробное подключение.")
|
||||
elif command == "status":
|
||||
result = await client.request("GET", "/subscriptions")
|
||||
subscriptions = result.get("subscriptions", [])
|
||||
configured = any(isinstance(s, dict) and s.get("url") == settings.max_webhook_url for s in subscriptions)
|
||||
print("Нужный webhook зарегистрирован." if configured else "Нужный webhook не найден.")
|
||||
if not configured:
|
||||
raise MaxApiError("webhook_missing")
|
||||
else:
|
||||
print("Токен принят MAX, имя бота совпадает с настройкой. Подписка не изменялась.")
|
||||
finally:
|
||||
await client.close()
|
||||
|
||||
|
||||
def main() -> int:
|
||||
parser = argparse.ArgumentParser(description="Подготовка MAX: параметры берутся только из .env/окружения.")
|
||||
parser.add_argument("command", choices=("check", "subscribe", "status"))
|
||||
args = parser.parse_args()
|
||||
try:
|
||||
asyncio.run(run(args.command))
|
||||
except ValidationError:
|
||||
print("Проверьте параметры MAX в .env по app/channels/MAX_SETUP.md.", file=sys.stderr)
|
||||
return 1
|
||||
except (MaxApiError, OSError) as exc:
|
||||
code = exc.code if isinstance(exc, MaxApiError) else "tls_or_file_error"
|
||||
print(f"Не удалось выполнить настройку MAX: {code}. Секреты и ответ сервера скрыты.", file=sys.stderr)
|
||||
return 1
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
+34
-2
@@ -1,10 +1,12 @@
|
||||
"""Typed application settings. The only place that reads environment variables."""
|
||||
|
||||
import re
|
||||
from functools import lru_cache
|
||||
from pathlib import Path
|
||||
from typing import Literal
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from pydantic import Field
|
||||
from pydantic import Field, SecretStr, model_validator
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
|
||||
ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
@@ -12,7 +14,7 @@ ROOT_DIR = Path(__file__).resolve().parent.parent
|
||||
|
||||
class Settings(BaseSettings):
|
||||
# Empty values in .env (e.g. `TG_BOT_TOKEN=`) fall back to defaults instead of failing validation.
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_ignore_empty=True)
|
||||
model_config = SettingsConfigDict(env_file=".env", extra="ignore", env_ignore_empty=True, hide_input_in_errors=True)
|
||||
|
||||
# Two separate databases (ADR-003): identity holds direct identifiers, clinical holds pseudonymised data.
|
||||
identity_db_url: str = "postgresql+asyncpg://identity_app:identity_app@localhost:5432/identity"
|
||||
@@ -43,6 +45,36 @@ class Settings(BaseSettings):
|
||||
tg_bot_token: str = ""
|
||||
doctor_notify_chat_id: int | None = None
|
||||
|
||||
# MAX is opt-in. Its adapter is delivered in the related backend/channel changes.
|
||||
max_enabled: bool = False
|
||||
max_bot_token: SecretStr = SecretStr("")
|
||||
max_bot_username: str = ""
|
||||
max_webhook_secret: SecretStr = SecretStr("")
|
||||
max_webhook_url: str = ""
|
||||
max_site_url: str = ""
|
||||
max_ca_bundle: Path | None = None
|
||||
max_link_ttl_seconds: int = Field(default=600, ge=60, le=1800)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def validate_max(self) -> "Settings":
|
||||
if not self.max_enabled:
|
||||
return self
|
||||
if not self.max_bot_token.get_secret_value().strip():
|
||||
raise ValueError("MAX_BOT_TOKEN is required when MAX_ENABLED=true")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_]{1,128}", self.max_bot_username):
|
||||
raise ValueError("MAX_BOT_USERNAME must be the bot nickname without @ or a URL")
|
||||
if not re.fullmatch(r"[A-Za-z0-9_-]{32,256}", self.max_webhook_secret.get_secret_value()):
|
||||
raise ValueError("MAX_WEBHOOK_SECRET must contain 32..256 URL-safe characters")
|
||||
for name, value in (("MAX_SITE_URL", self.max_site_url), ("MAX_WEBHOOK_URL", self.max_webhook_url)):
|
||||
url = urlsplit(value)
|
||||
if url.scheme != "https" or not url.hostname or url.username or url.password or url.port not in (None, 443):
|
||||
raise ValueError(f"{name} must use HTTPS on port 443 without credentials")
|
||||
if url.query or (name == "MAX_WEBHOOK_URL" and url.fragment):
|
||||
raise ValueError(f"{name} must not contain a query string (or a fragment for webhook)")
|
||||
if self.max_ca_bundle is not None and not self.max_ca_bundle.is_file():
|
||||
raise ValueError("MAX_CA_BUNDLE must point to an existing trusted CA bundle")
|
||||
return self
|
||||
|
||||
# Virtual clock for the demo (ADR-005).
|
||||
demo_clock: bool = True
|
||||
tz: str = "Europe/Moscow"
|
||||
|
||||
@@ -5,6 +5,7 @@ The only module (besides registration code) that touches both schemas — and on
|
||||
|
||||
from app.db import audit as _audit # noqa: F401 (registers audit_log in clinical metadata)
|
||||
from app.db import intake as _intake # noqa: F401
|
||||
from app.db import max_notifications as _max_notifications # noqa: F401
|
||||
from app.db import scheduler as _scheduler # noqa: F401
|
||||
from app.db.clinical import ClinicalBase
|
||||
from app.db.identity import IdentityBase
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
"""MAX identifiers and delivery metadata live only in the identity DB; no medical message bodies."""
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import BigInteger, Boolean, Integer, String
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.db.identity import IdentityBase
|
||||
from app.db.types import TZDateTime
|
||||
|
||||
|
||||
class MaxBinding(IdentityBase):
|
||||
__tablename__ = "max_bindings"
|
||||
|
||||
# No FK: anonymous web profiles intentionally have no patients row in identity.
|
||||
token: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
user_id: Mapped[int] = mapped_column(BigInteger, unique=True)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, default=True)
|
||||
connected_at: Mapped[datetime] = mapped_column(TZDateTime)
|
||||
|
||||
|
||||
class MaxLinkCode(IdentityBase):
|
||||
__tablename__ = "max_link_codes"
|
||||
|
||||
digest: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
token: Mapped[str] = mapped_column(String(64), unique=True)
|
||||
expires_at: Mapped[datetime] = mapped_column(TZDateTime, index=True)
|
||||
used_at: Mapped[datetime | None] = mapped_column(TZDateTime)
|
||||
|
||||
|
||||
class MaxReceipt(IdentityBase):
|
||||
__tablename__ = "max_webhook_receipts"
|
||||
|
||||
digest: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
received_at: Mapped[datetime] = mapped_column(TZDateTime, index=True)
|
||||
|
||||
|
||||
class MaxDelivery(IdentityBase):
|
||||
__tablename__ = "max_deliveries"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(64), primary_key=True)
|
||||
token: Mapped[str | None] = mapped_column(String(64), index=True)
|
||||
user_id: Mapped[int] = mapped_column(BigInteger)
|
||||
kind: Mapped[str] = mapped_column(String(24))
|
||||
state: Mapped[str] = mapped_column(String(16), default="queued", index=True)
|
||||
attempts: Mapped[int] = mapped_column(Integer, default=0)
|
||||
created_at: Mapped[datetime] = mapped_column(TZDateTime)
|
||||
next_attempt_at: Mapped[datetime] = mapped_column(TZDateTime, index=True)
|
||||
lease: Mapped[str | None] = mapped_column(String(32))
|
||||
error_code: Mapped[str | None] = mapped_column(String(32))
|
||||
@@ -0,0 +1,201 @@
|
||||
"""Registration boundary and durable MAX queue. Callers own the identity transaction.
|
||||
|
||||
Only this boundary joins a pseudonymous profile to a MAX recipient. Clinical modules never import it.
|
||||
Queue rows contain a template name, never replies, scores, prescriptions or patient-auth tokens in URLs.
|
||||
"""
|
||||
|
||||
import hashlib
|
||||
import secrets
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import delete, select, update
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.db import repo
|
||||
from app.db.clinical import ScaleResult
|
||||
from app.db.intake import QuestionnaireRecord
|
||||
from app.db.max_notifications import MaxBinding, MaxDelivery, MaxLinkCode
|
||||
from app.db.session import get_clinical_session
|
||||
|
||||
MAX_ATTEMPTS = 6
|
||||
LEASE_SECONDS = 60
|
||||
|
||||
|
||||
def digest(value: str) -> str:
|
||||
return hashlib.sha256(value.encode()).hexdigest()
|
||||
|
||||
|
||||
async def active_patient(token: str) -> bool:
|
||||
"""Same consent/adult gate used by the scheduler, checked again at delivery time."""
|
||||
async with get_clinical_session() as session:
|
||||
state = await repo.get_dialog_state(session, token)
|
||||
return bool(
|
||||
await repo.get_profile(session, token)
|
||||
and state
|
||||
and state.data.get("consent") is True
|
||||
and state.data.get("adult") is True
|
||||
)
|
||||
|
||||
|
||||
async def issue_code(session: AsyncSession, token: str, now: datetime, ttl: int) -> tuple[str, datetime]:
|
||||
raw = secrets.token_urlsafe(32)
|
||||
expires = now + timedelta(seconds=ttl)
|
||||
await session.execute(delete(MaxLinkCode).where(MaxLinkCode.token == token))
|
||||
session.add(MaxLinkCode(digest=digest(raw), token=token, expires_at=expires))
|
||||
await session.flush()
|
||||
return raw, expires
|
||||
|
||||
|
||||
async def code_token(session: AsyncSession, raw: str, now: datetime) -> str | None:
|
||||
row = await session.get(MaxLinkCode, digest(raw))
|
||||
return row.token if row and row.used_at is None and row.expires_at > now else None
|
||||
|
||||
|
||||
async def bind(session: AsyncSession, raw: str, user_id: int, now: datetime) -> str | None:
|
||||
"""Atomically consume a code. Existing active identities cannot be silently reassigned."""
|
||||
token = await code_token(session, raw, now)
|
||||
if token is None:
|
||||
return None
|
||||
owner = await session.scalar(select(MaxBinding).where(MaxBinding.user_id == user_id))
|
||||
binding = await session.get(MaxBinding, token)
|
||||
if owner and owner.token != token and owner.enabled:
|
||||
return None
|
||||
if binding and binding.user_id != user_id and binding.enabled:
|
||||
return None
|
||||
used = await session.execute(
|
||||
update(MaxLinkCode)
|
||||
.where(MaxLinkCode.digest == digest(raw), MaxLinkCode.used_at.is_(None), MaxLinkCode.expires_at > now)
|
||||
.values(used_at=now)
|
||||
.returning(MaxLinkCode.token)
|
||||
)
|
||||
if used.scalar_one_or_none() is None:
|
||||
return None
|
||||
if owner and owner.token != token:
|
||||
await session.delete(owner)
|
||||
await session.flush()
|
||||
if binding is None:
|
||||
binding = MaxBinding(token=token, user_id=user_id, connected_at=now)
|
||||
session.add(binding)
|
||||
# Cancel stale deliveries even when the same account reconnects later.
|
||||
await cancel_pending(session, token)
|
||||
binding.user_id, binding.enabled, binding.connected_at = user_id, True, now
|
||||
await session.flush()
|
||||
return token
|
||||
|
||||
|
||||
async def cancel_pending(session: AsyncSession, token: str) -> None:
|
||||
await session.execute(
|
||||
update(MaxDelivery)
|
||||
.where(MaxDelivery.token == token, MaxDelivery.state.in_(("queued", "sending")))
|
||||
.values(state="cancelled", lease=None)
|
||||
)
|
||||
|
||||
|
||||
async def disconnect(session: AsyncSession, token: str) -> None:
|
||||
binding = await session.get(MaxBinding, token)
|
||||
if binding:
|
||||
binding.enabled = False
|
||||
await session.execute(delete(MaxLinkCode).where(MaxLinkCode.token == token))
|
||||
await cancel_pending(session, token)
|
||||
|
||||
|
||||
async def enqueue(
|
||||
session: AsyncSession, *, key: str, user_id: int, kind: str, now: datetime, token: str | None = None
|
||||
) -> None:
|
||||
if await session.get(MaxDelivery, key) is not None:
|
||||
return
|
||||
try:
|
||||
async with session.begin_nested():
|
||||
session.add(
|
||||
MaxDelivery(id=key, user_id=user_id, token=token, kind=kind, created_at=now, next_attempt_at=now)
|
||||
)
|
||||
await session.flush()
|
||||
except IntegrityError:
|
||||
# Another worker may enqueue the same event between SELECT and INSERT.
|
||||
if await session.get(MaxDelivery, key) is None:
|
||||
raise
|
||||
|
||||
|
||||
async def collect_completed(session: AsyncSession, now: datetime) -> None:
|
||||
"""Recover completion events from committed clinical records, including after a restart.
|
||||
|
||||
No clinical hooks depend on identity. Read only IDs/dates, then enqueue a generic template.
|
||||
A binding's activation time bounds history; repeated scans are idempotent.
|
||||
"""
|
||||
bindings = (await session.scalars(select(MaxBinding).where(MaxBinding.enabled.is_(True)))).all()
|
||||
for binding in bindings:
|
||||
if not await active_patient(binding.token):
|
||||
continue
|
||||
async with get_clinical_session() as clinical:
|
||||
forms = (
|
||||
await clinical.scalars(
|
||||
select(QuestionnaireRecord.id).where(
|
||||
QuestionnaireRecord.token == binding.token,
|
||||
QuestionnaireRecord.status == "complete",
|
||||
QuestionnaireRecord.completed_at >= binding.connected_at,
|
||||
)
|
||||
)
|
||||
).all()
|
||||
scales = (
|
||||
await clinical.scalars(
|
||||
select(ScaleResult.id).where(
|
||||
ScaleResult.token == binding.token,
|
||||
ScaleResult.complete.is_(True),
|
||||
ScaleResult.ts >= binding.connected_at,
|
||||
)
|
||||
)
|
||||
).all()
|
||||
for source, ids in (("form", forms), ("scale", scales)):
|
||||
for record_id in ids:
|
||||
key = digest(f"completed:{binding.token}:{binding.connected_at.isoformat()}:{source}:{record_id}")
|
||||
await enqueue(session, key=key, token=binding.token, user_id=binding.user_id, kind="completed", now=now)
|
||||
|
||||
|
||||
async def claim(session: AsyncSession, now: datetime) -> MaxDelivery | None:
|
||||
"""One lease per row; recovery after a worker crash is bounded by the lease deadline."""
|
||||
ready = (MaxDelivery.state.in_(("queued", "sending"))) & (MaxDelivery.next_attempt_at <= now)
|
||||
row = await session.scalar(
|
||||
select(MaxDelivery)
|
||||
.where(ready)
|
||||
.order_by(MaxDelivery.created_at, MaxDelivery.id)
|
||||
.with_for_update(skip_locked=True)
|
||||
.limit(1)
|
||||
)
|
||||
if row is None:
|
||||
return None
|
||||
if row.attempts >= MAX_ATTEMPTS:
|
||||
row.state, row.error_code, row.lease = "failed", "attempt_limit", None
|
||||
return None
|
||||
lease = secrets.token_hex(16)
|
||||
result = await session.execute(
|
||||
update(MaxDelivery)
|
||||
.where(MaxDelivery.id == row.id, ready)
|
||||
.values(
|
||||
state="sending",
|
||||
attempts=MaxDelivery.attempts + 1,
|
||||
lease=lease,
|
||||
next_attempt_at=now + timedelta(seconds=LEASE_SECONDS),
|
||||
)
|
||||
.returning(MaxDelivery.id)
|
||||
)
|
||||
if result.scalar_one_or_none() is None:
|
||||
return None
|
||||
await session.refresh(row)
|
||||
return row
|
||||
|
||||
|
||||
async def finish(
|
||||
session: AsyncSession,
|
||||
row: MaxDelivery,
|
||||
*,
|
||||
state: str,
|
||||
now: datetime,
|
||||
error: str | None = None,
|
||||
retry_seconds: float = 0,
|
||||
) -> None:
|
||||
await session.execute(
|
||||
update(MaxDelivery)
|
||||
.where(MaxDelivery.id == row.id, MaxDelivery.lease == row.lease, MaxDelivery.state == "sending")
|
||||
.values(state=state, lease=None, error_code=error, next_attempt_at=now + timedelta(seconds=retry_seconds))
|
||||
)
|
||||
+18
-6
@@ -30,13 +30,25 @@ async def lifespan(_: FastAPI) -> AsyncGenerator[None, None]:
|
||||
# In compose Postgres is required and healthy before the app starts; this branch is for running the
|
||||
# API (and its tests) without a database. Endpoints touching the DB will fail until it is reachable.
|
||||
log.error("db init failed, continuing without db: %s", type(exc).__name__)
|
||||
if settings.max_enabled:
|
||||
raise # MAX requires persistent bindings and a delivery queue.
|
||||
# Lanes fill these in (#13, #11); main.py itself stays frozen (#34).
|
||||
await scheduler.start()
|
||||
await telegram.start()
|
||||
yield
|
||||
await telegram.stop()
|
||||
await scheduler.stop()
|
||||
await dispose()
|
||||
max_channel = None
|
||||
try:
|
||||
await telegram.start()
|
||||
if settings.max_enabled:
|
||||
from app.channels import max_bot
|
||||
|
||||
max_channel = max_bot
|
||||
await max_channel.start()
|
||||
await scheduler.start()
|
||||
yield
|
||||
finally:
|
||||
await scheduler.stop()
|
||||
if max_channel is not None:
|
||||
await max_channel.stop()
|
||||
await telegram.stop()
|
||||
await dispose()
|
||||
|
||||
|
||||
app = FastAPI(title="PTSRaiAgent API", version="0.1.0", lifespan=lifespan)
|
||||
|
||||
Reference in New Issue
Block a user