docs: document application store operations
This commit is contained in:
1 parent
9d2abde1a5
commit
a66d659400
1 file changed
+13
@@ -29,6 +29,7 @@ class ApplicationError(ValueError):
|
||||
|
||||
|
||||
def _positive_id(value: Any, label: str) -> int:
|
||||
"""Проверяет положительный целочисленный идентификатор входного поля."""
|
||||
verb = "должен" if label.startswith("ID ") else "должно"
|
||||
if isinstance(value, bool):
|
||||
raise ApplicationError(f"{label} {verb} быть числом")
|
||||
@@ -59,6 +60,7 @@ def _normalise_vk_link(value: Any) -> str:
|
||||
|
||||
|
||||
def _https_link(value: Any, label: str) -> str:
|
||||
"""Проверяет безопасную HTTPS-ссылку и возвращает нормализованную строку."""
|
||||
link = str(value or "").strip()
|
||||
if len(link) > MAX_APPLICATION_URL_LENGTH:
|
||||
raise ApplicationError(f"{label} слишком длинная")
|
||||
@@ -69,6 +71,7 @@ def _https_link(value: Any, label: str) -> str:
|
||||
|
||||
|
||||
def _attachments(value: Any) -> list[dict[str, str]]:
|
||||
"""Очищает список вложений до поддерживаемых URL и подписей."""
|
||||
if not isinstance(value, list) or len(value) > MAX_APPLICATION_ATTACHMENTS:
|
||||
raise ApplicationError(f"Можно приложить не более {MAX_APPLICATION_ATTACHMENTS} изображений")
|
||||
attachments: list[dict[str, str]] = []
|
||||
@@ -147,6 +150,7 @@ class ApplicationStore:
|
||||
"""Хранилище заявок в PostgreSQL production и SQLite для разработки."""
|
||||
|
||||
def __init__(self, database_url: str | None = None, sqlite_path: str | Path | None = None) -> None:
|
||||
"""Инициализирует хранилище заявок и создаёт нужную схему базы данных."""
|
||||
self.database_url = database_url or ""
|
||||
self.sqlite_path = Path(sqlite_path) if sqlite_path else None
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
@@ -160,9 +164,11 @@ class ApplicationStore:
|
||||
|
||||
@classmethod
|
||||
def from_environment(cls) -> "ApplicationStore":
|
||||
"""Выбирает параметры PostgreSQL/SQLite из переменных окружения."""
|
||||
return cls(os.getenv("BELKI_DATABASE_URL"), os.getenv("BELKI_HISTORY_DB", "data/belki.sqlite3"))
|
||||
|
||||
def _ensure_sqlite_schema(self) -> None:
|
||||
"""Создаёт SQLite-таблицы заявок и outbox-событий при первом запуске."""
|
||||
with sqlite3.connect(self.sqlite_path) as connection:
|
||||
connection.execute("""CREATE TABLE IF NOT EXISTS applications (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT, actor_id INTEGER, reply_peer_id INTEGER,
|
||||
@@ -181,6 +187,7 @@ class ApplicationStore:
|
||||
)""")
|
||||
|
||||
def _ensure_postgres_schema(self) -> None:
|
||||
"""Создаёт эквивалентную production-схему в PostgreSQL."""
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute("""CREATE TABLE IF NOT EXISTS belki_applications (
|
||||
id BIGSERIAL PRIMARY KEY, actor_id BIGINT, reply_peer_id BIGINT, source TEXT NOT NULL,
|
||||
@@ -196,6 +203,7 @@ class ApplicationStore:
|
||||
)""")
|
||||
|
||||
def create(self, *, application: dict[str, Any], actor_id: int | None, reply_peer_id: int | None, source: str) -> int:
|
||||
"""Сохраняет новую заявку и добавляет событие экспорта в outbox."""
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
from psycopg.types.json import Jsonb
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
@@ -218,6 +226,7 @@ class ApplicationStore:
|
||||
return application_id
|
||||
|
||||
def list(self, *, status: str | None = None, limit: int = 500) -> list[dict[str, Any]]:
|
||||
"""Возвращает заявки, ограничивая выборку и опционально фильтруя статус."""
|
||||
if status not in (None, "pending", "accepted"):
|
||||
raise ApplicationError("Неизвестный статус заявки")
|
||||
limit = max(1, min(int(limit), 500))
|
||||
@@ -243,6 +252,7 @@ class ApplicationStore:
|
||||
"reviewed_at": row[7].isoformat() if hasattr(row[7], "isoformat") else row[7]} for row in rows]
|
||||
|
||||
def accept(self, application_id: int) -> dict[str, Any] | None:
|
||||
"""Атомарно переводит заявку в accepted и возвращает её снимок."""
|
||||
if application_id <= 0:
|
||||
raise ApplicationError("ID заявки должен быть положительным")
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
@@ -297,6 +307,7 @@ class ApplicationStore:
|
||||
"payload": row[3] if isinstance(row[3], dict) else json.loads(row[3]), "attempts": row[4]} for row in rows]
|
||||
|
||||
def mark_exported(self, event_id: int) -> None:
|
||||
"""Помечает outbox-событие успешно доставленным."""
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute("UPDATE belki_application_export_events SET status = 'delivered', delivered_at = NOW(), attempts = attempts + 1, last_error = NULL WHERE id = %s", (event_id,))
|
||||
@@ -305,6 +316,7 @@ class ApplicationStore:
|
||||
connection.execute("UPDATE application_export_events SET status = 'delivered', delivered_at = CURRENT_TIMESTAMP, attempts = attempts + 1, last_error = NULL WHERE id = ?", (event_id,))
|
||||
|
||||
def record_export_failure(self, event_id: int, message: str) -> None:
|
||||
"""Сохраняет текст последней ошибки доставки outbox-события."""
|
||||
message = message[:1000]
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
@@ -326,6 +338,7 @@ class ApplicationStore:
|
||||
return [{"id": row[0], "reply_peer_id": row[1], "application": row[2] if isinstance(row[2], dict) else json.loads(row[2])} for row in rows]
|
||||
|
||||
def mark_notified(self, application_id: int) -> None:
|
||||
"""Помечает принятую заявку уведомлённой во внешнем канале."""
|
||||
if self.database_url.startswith(("postgres://", "postgresql://")):
|
||||
with self._psycopg.connect(self.database_url) as connection:
|
||||
connection.execute("UPDATE belki_applications SET notified_at = NOW() WHERE id = %s", (application_id,))
|
||||
|
||||
Reference in new issue
Block a user