ЛР 4 — БВТ2301 — Иванов Артём — на 3 #174
@@ -0,0 +1 @@
|
||||
*.sh text eol=lf
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
FROM python:3.12.8-slim-bookworm
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 \
|
||||
PYTHONUNBUFFERED=1 \
|
||||
APP_HOST=0.0.0.0 \
|
||||
APP_PORT=8080
|
||||
|
||||
WORKDIR /app
|
||||
COPY requirements.txt /app/requirements.txt
|
||||
RUN pip install --no-cache-dir -r requirements.txt \
|
||||
&& adduser --disabled-password --gecos "" app
|
||||
COPY app.py /app/app.py
|
||||
COPY migrations /app/migrations
|
||||
USER app
|
||||
|
||||
EXPOSE 8080
|
||||
CMD ["python", "/app/app.py"]
|
||||
@@ -4,10 +4,10 @@ CA_FILE ?=
|
||||
ACTION_SCRIPT ?=
|
||||
TLS_ARGS = $(if $(CA_FILE),--ca-file "$(CA_FILE)",)
|
||||
|
||||
.PHONY: help check validate test load test-persistence test-failover
|
||||
.PHONY: help check validate test load test-persistence test-failover test-idempotency test-attachments test-s3-failure
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes; test-idempotency: concurrent duplicate message posts; test-attachments: upload validation and ACL; test-s3-failure: unavailable S3 behavior"
|
||||
|
||||
check:
|
||||
$(PYTHON) scripts/check_contract.py
|
||||
@@ -28,3 +28,12 @@ test-persistence:
|
||||
test-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode failover --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-idempotency:
|
||||
$(PYTHON) tests/idempotency_concurrency.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-attachments:
|
||||
$(PYTHON) tests/attachments_validation.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-s3-failure:
|
||||
$(PYTHON) tests/s3_unavailable.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
@@ -1,37 +1,127 @@
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
|
||||
- Автор, группа: Иванов Артём, БВТ2301
|
||||
- Целевая оценка: 3.
|
||||
- Commit/PR: .
|
||||
- Использованные источники, библиотеки и помощь ИИ: документация PostgreSQL, Docker Compose, MinIO и S3 API; источники из раздела «Первичные материалы» в README. Использованы Argon2 (`argon2-cffi`), psycopg, boto3, Pillow, Nginx и PostgreSQL.
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
### Требования и технологии
|
||||
|
||||
- Docker Desktop или Docker Engine с Docker Compose v2.
|
||||
- `make`, Python 3.9+ и `curl` для запуска тестовых скриптов.
|
||||
- Все сервисы и их конфигурации запускаются из этого репозитория.
|
||||
- API: Python 3.12.8 (`python:3.12.8-slim-bookworm`), стандартный `http.server`, две реплики.
|
||||
- База: `postgres:16.6-alpine`; постоянные данные хранятся в named volume `postgres_data`.
|
||||
- S3: MinIO Community `RELEASE.2025-02-07T23-21-09Z`, собранный из официального бинарного release; версия и SHA-256 закреплены в `infra/minio.Dockerfile`. Данные bucket хранятся в named volume `minio_data`.
|
||||
- Балансировщик: `nginx:1.27.5-alpine`; host-порт привязан к loopback.
|
||||
- Python-зависимости приложения: `argon2-cffi==23.1.0`, `psycopg[binary,pool]==3.2.6`, `boto3==1.36.26`, `Pillow==11.1.0` (`requirements.txt`).
|
||||
|
||||
### Подготовка и запуск
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
В локальном `.env` задайте собственные значения `PGPASSWORD` и `MINIO_ROOT_PASSWORD`. Файл `.env` игнорируется Git. Убедитесь, что `APP_PORT` свободен. При необходимости измените его в `.env`.
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --scale api=2
|
||||
curl -fsS http://localhost:8080/health/ready
|
||||
```
|
||||
|
||||
Если задан другой `APP_PORT`, замените порт в URL. Compose запускает PostgreSQL и MinIO, затем одноразовые bootstrap приватного S3 bucket и миграции, две API-реплики и Nginx. Healthchecks и `depends_on` не дают API стартовать до готовности хранилищ и успешного bootstrap/migration.
|
||||
|
||||
### Проверки
|
||||
|
||||
```sh
|
||||
make check
|
||||
BASE_URL=http://localhost:8080 make test
|
||||
BASE_URL=http://localhost:8080 make test-attachments
|
||||
BASE_URL=http://localhost:8080 make test-idempotency
|
||||
BASE_URL=http://localhost:8080 make test-s3-failure
|
||||
|
||||
chmod +x scripts/restart.sh scripts/stop-one.sh
|
||||
BASE_URL=http://localhost:8080 \
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
BASE_URL=http://localhost:8080 \
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
```
|
||||
|
||||
Для полной локальной OpenAPI/JSON Schema-валидации:
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||
make validate PYTHON=.venv/bin/python
|
||||
```
|
||||
|
||||
Безопасная остановка без удаления данных:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
`docker compose --env-file .env down -v` удаляет volumes PostgreSQL и MinIO вместе с данными; использовать только если намеренно требуется полный сброс баз данных.
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
| Компонент | Технологии | Роль и состояние |
|
||||
| --- | --- | --- |
|
||||
| API | Python 3.12.8, стандартный `http.server` (`ThreadingHTTPServer`, `BaseHTTPRequestHandler`) | HTTP API без отдельного web framework; две реплики с LB. Не хранит оригиналы на локальном диске. |
|
||||
| PostgreSQL | `postgres:16.6-alpine`; psycopg pool `3.2.6` | Источник истины для пользователей, чатов, состава участников, сообщений, сессий, идемпотентности и metadata вложений. Named volume `postgres_data`. |
|
||||
| Хеширование паролей | `argon2-cffi==23.1.0` | Хеширование пароля при регистрации; исходный пароль не сохраняется. |
|
||||
| S3 client | `boto3==1.36.26` | Доступ API к S3-совместимому MinIO по внутреннему адресу Compose `s3:9000`; path-style addressing, ограниченные connect/read timeouts, повторные попытки отключены. |
|
||||
| Изображения | `Pillow==11.1.0` | Проверка формата и целостности PNG/JPEG, а также размера изображения в пикселях. |
|
||||
| S3 storage | MinIO Community `RELEASE.2025-02-07T23-21-09Z` | Байты оригиналов в приватном bucket на named volume `minio_data`. Release binary проверяется по закреплённому SHA-256. S3 API и console не опубликованы на host. |
|
||||
| Балансировщик | `nginx:1.27.5-alpine` | Единственная внешняя точка входа; проксирует запросы двум API-репликам, host binding — loopback. |
|
||||
| Оркестрация | Docker Compose v2 | Сеть сервисов, volumes, healthchecks, порядок миграции/bootstrap и запуск двух реплик API. |
|
||||
|
||||
Пул psycopg ограничивается `DB_POOL_MAX_SIZE` (10 соединений на процесс API); настроены таймаут ожидания соединения и подключения. Python-пакеты закреплены версиями в `requirements.txt`.
|
||||
|
||||
### Хранение и транзакционные границы
|
||||
|
||||
Пользователи, чаты, членство, сообщения, sessions и idempotency records хранятся в PostgreSQL. Пароли хешируются Argon2. Сессии — opaque Bearer-токены; в БД сохраняется digest токена и срок действия. Basic используется только для создания сессии. Миграции `migrations/001_*.sql`–`011_attachments.sql` версионированы; migration runner учитывает выполненные миграции в `schema_migrations` и сериализует параллельный запуск advisory lock.
|
||||
|
||||
Метаданные вложений (чат, владелец, filename, content type, размер, checksum и object key) хранятся в PostgreSQL; бинарные данные — только в MinIO. `infra/s3-bootstrap.py` идемпотентно создаёт bucket при его отсутствии; по умолчанию bucket приватный. Ключ объекта генерирует сервер и API не раскрывает его клиенту. Авторизация download проверяет участие пользователя в чате.
|
||||
|
||||
Upload ограничен 10 MB и 40 млн пикселей; размер тела проверяется до чтения, MIME сверяется с форматом файла, опасный filename отклоняется. API сначала сохраняет объект в S3, затем записывает metadata в PostgreSQL и возвращает `201 ready` после успешного завершения. При ошибке транзакции выполняется best-effort удаление уже загруженного объекта. Это не атомарная транзакция между S3 и PostgreSQL: при аварийном завершении процесса возможен orphan object.
|
||||
|
||||
Создание чата и его участников выполняется атомарно в одной транзакции. Создание сообщения, связь с вложениями и запись результата идемпотентности выполняются в транзакции PostgreSQL. Составные внешние ключи не позволяют связать сообщение с вложением другого чата. История сообщений использует keyset pagination и индекс по chat/time/id.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Публичный smoke и возможности предыдущих лабораторных | `APP_PORT=18080 make test BASE_URL=http://localhost:18080` | PASS: полный публичный сценарий Lab4 | `tests/smoke.py`, `tests/README.md` |
|
||||
| PostgreSQL, схема и повторные миграции | `docker compose --env-file .env run --rm migrate` на заполненной БД | PASS: `database migrations complete`; повторный запуск не создал дубликатов данных | `app.py`, `migrations/` |
|
||||
| PNG upload, `201 ready`, byte/checksum и message attachment_ids | `APP_PORT=18080 make test-attachments BASE_URL=http://localhost:18080` | PASS: оригинал совпал побайтно и по SHA-256; второй участник скачал, посторонний получил 404; attachment_ids сохранились в истории | `tests/attachments_validation.py` |
|
||||
| JPEG upload и download | Ручной дополнительный запрос к API через Compose network | PASS: JPEG принят как `image/jpeg`, metadata `ready`; checksum и скачанные байты совпали с исходными | `app.py`; проверка 2026-12-02 |
|
||||
| Ограничения, MIME, повреждённый файл и filename | `make test-attachments` | PASS: >10 MiB и >40 млн пикселей → 413; небезопасное имя → 400; MIME mismatch и повреждённое изображение → 415 | `tests/attachments_validation.py`, `app.py` |
|
||||
| Приватный bucket и ACL | Анонимный GET существующего object key внутри Compose network | PASS: MinIO вернул 403; посторонний через API получает 404 | `compose.yaml`, `infra/s3-bootstrap.py`, `app.py` |
|
||||
| Конкурентная идемпотентность между API-репликами | `APP_PORT=18080 make test-idempotency BASE_URL=http://localhost:18080` | PASS: 16 конкурентных запросов создали одно сообщение | `tests/idempotency_concurrency.py` |
|
||||
| Полный restart и сохранность сессии/данных | `APP_PORT=18080 make test-persistence ACTION_SCRIPT=scripts/restart.sh BASE_URL=http://localhost:18080` | PASS: прежний токен, подтверждённое сообщение и attachment доступны после перезапуска API, PostgreSQL и MinIO; volumes не удалялись | `scripts/restart.sh`, `tests/resilience.py` |
|
||||
| Failover API | `APP_PORT=18080 make test-failover ACTION_SCRIPT=scripts/stop-one.sh BASE_URL=http://localhost:18080` | PASS: 140 успешных записей, 1 переходная ошибка, первое восстановление за 0,536 с; подтверждённые данные сохранены без дублей | `scripts/stop-one.sh`, `tests/resilience.py` |
|
||||
| Доступность файла с другой реплики | Upload → остановка именно реплики из `X-Instance-Id` upload-ответа → download через LB | PASS: вторая реплика вернула те же байты; после теста восстановлены две реплики | `compose.yaml`, `app.py` |
|
||||
| Обработка отказа S3 | `APP_PORT=18080 make test-s3-failure BASE_URL=http://localhost:18080` | PASS: readiness и upload вернули 503 менее чем за 10 секунд; MinIO затем автоматически восстановлен тестом | `tests/s3_unavailable.py`, `app.py` |
|
||||
| OpenAPI и JSON Schema | Установка `requirements-dev.txt` в venv, затем `python scripts/validate_openapi.py` | PASS: полная OpenAPI 3.1 и JSON Schema validation | `scripts/validate_openapi.py`, `contracts/openapi.json`, `contracts/examples.json` |
|
||||
| Структура и чистота изменений | `make check`; `git diff --check` с учётом CRLF | PASS: contract/syntax check; whitespace-check без замечаний | `scripts/check_contract.py` |
|
||||
| Секреты и готовность сервисов | `git check-ignore .env`; `docker compose --env-file .env ps`; `GET /health/ready` | PASS: `.env` игнорируется и не tracked; после тестов healthy DB, MinIO, LB и две API-реплики | `.gitignore`, `compose.yaml` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Перезапуск API и хранилищ с сохранением volumes | Прежний токен и подтверждённые данные остаются доступны | PASS: сохранились сессия, сообщение и оригинал вложения | Hook завершился успешно; подтверждённые данные не потеряны |
|
||||
| Остановка одной API-реплики при параллельных записях | Короткий переходный отказ, затем обработка через оставшуюся реплику; без потери подтверждённых сообщений и дублей | 140 успешных записей, 1 неуспешная попытка перехода | Первое восстановление записи — 0,536 с; вторая реплика возвращена |
|
||||
| Остановка реплики, обслужившей upload | Файл читается через другую API-реплику из общего S3 | PASS: скачанные байты идентичны исходным | Две реплики восстановлены после проверки |
|
||||
| Остановка MinIO | API ограниченно сообщает об отказе и не выдаёт success для upload | PASS: readiness и upload вернули 503 менее чем за 10 секунд | MinIO запущен тестом повторно; readiness восстановился |
|
||||
| Анонимный GET приватного объекта | S3 не выдаёт объект без авторизации | HTTP 403 | Данные объекта не изменялись |
|
||||
|
||||
Сводка failover-теста: `observed_instances_before=2`, `successful_writes=140`, `failed_attempts=1`, `first_recovery_seconds=0.536`.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
- PostgreSQL, MinIO и Nginx запущены по одному экземпляру - низкая отказоустойчивость
|
||||
- При аварийном завершении процесса после S3 PUT, но до фиксации metadata/компенсации, возможен orphan object. Reconciler и отложенная очистка не реализованы.
|
||||
@@ -0,0 +1,945 @@
|
||||
#!/usr/bin/env python3
|
||||
"""PostgreSQL-backed, horizontally scalable HTTP API for lab4."""
|
||||
import base64
|
||||
import binascii
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import re
|
||||
import secrets
|
||||
import signal
|
||||
import socket
|
||||
import sys
|
||||
import threading
|
||||
import unicodedata
|
||||
import warnings
|
||||
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
|
||||
from pathlib import Path
|
||||
from urllib.parse import parse_qs, urlsplit
|
||||
import uuid
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import InvalidHashError, VerificationError, VerifyMismatchError
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from psycopg.conninfo import make_conninfo
|
||||
from psycopg.errors import UniqueViolation
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
import psycopg
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout
|
||||
|
||||
|
||||
LOG = logging.getLogger("messenger")
|
||||
USERNAME_RE = re.compile(r"^[a-z0-9_]{3,32}$")
|
||||
MAX_BODY_BYTES = 1024 * 1024
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
MAX_IMAGE_PIXELS = 40_000_000
|
||||
IDEMPOTENCY_KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$")
|
||||
IDEMPOTENCY_TTL = timedelta(hours=24)
|
||||
IMAGE_CONTENT_TYPES = {"image/png": "PNG", "image/jpeg": "JPEG"}
|
||||
MIGRATIONS = Path(__file__).resolve().parent / "migrations"
|
||||
PASSWORD_HASHER = PasswordHasher()
|
||||
POOL = None
|
||||
S3_CLIENT = None
|
||||
S3_BUCKET = None
|
||||
SESSION_TTL_SECONDS = 3600
|
||||
INSTANCE_ID = os.environ.get("INSTANCE_ID", "").strip() or socket.gethostname() or str(uuid.uuid4())
|
||||
|
||||
|
||||
class BinaryResponse:
|
||||
def __init__(self, data, content_type):
|
||||
self.data = data
|
||||
self.content_type = content_type
|
||||
|
||||
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid(message="Некорректный запрос"):
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def unauthorized(scheme):
|
||||
challenge = ('Basic realm="messenger", charset="UTF-8"' if scheme == "Basic"
|
||||
else 'Bearer realm="messenger"')
|
||||
return ApiError(401, "unauthorized", "Требуется действительная аутентификация",
|
||||
{"WWW-Authenticate": challenge})
|
||||
|
||||
|
||||
def utc_now():
|
||||
return datetime.now(timezone.utc)
|
||||
|
||||
|
||||
def timestamp(value):
|
||||
return value.astimezone(timezone.utc).isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
|
||||
|
||||
def user_json(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"username": row["username"],
|
||||
"display_name": row["display_name"],
|
||||
"created_at": timestamp(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def chat_json(conn, row):
|
||||
members = conn.execute(
|
||||
"SELECT user_id FROM chat_members WHERE chat_id = %s ORDER BY member_position",
|
||||
(row["id"],),
|
||||
).fetchall()
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"title": row["title"],
|
||||
"member_ids": [str(member["user_id"]) for member in members],
|
||||
"created_at": timestamp(row["created_at"]),
|
||||
}
|
||||
|
||||
|
||||
def message_json(row, attachment_ids=None):
|
||||
if attachment_ids is None:
|
||||
attachment_ids = row.get("attachment_ids", [])
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"sender_id": str(row["sender_id"]),
|
||||
"text": row["text"],
|
||||
"created_at": timestamp(row["created_at"]),
|
||||
"attachment_ids": [str(item) for item in attachment_ids],
|
||||
}
|
||||
|
||||
|
||||
def attachment_json(row):
|
||||
return {
|
||||
"id": str(row["id"]),
|
||||
"chat_id": str(row["chat_id"]),
|
||||
"owner_id": str(row["owner_id"]),
|
||||
"filename": row["filename"],
|
||||
"content_type": row["content_type"],
|
||||
"size_bytes": row["size_bytes"],
|
||||
"sha256": row["sha256"],
|
||||
"status": row["status"],
|
||||
"variants": row["variants"],
|
||||
"error_code": row["error_code"],
|
||||
"created_at": timestamp(row["created_at"]),
|
||||
"updated_at": timestamp(row["updated_at"]),
|
||||
}
|
||||
|
||||
|
||||
def encode_cursor(kind, scope, created_at, object_id):
|
||||
payload = json.dumps(
|
||||
{"kind": kind, "scope": str(scope), "created_at": timestamp(created_at), "id": str(object_id)},
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
return base64.urlsafe_b64encode(payload).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
def decode_cursor(value, kind, scope):
|
||||
try:
|
||||
padded = value + "=" * (-len(value) % 4)
|
||||
raw = base64.b64decode(padded.encode("ascii"), altchars=b"-_", validate=True)
|
||||
data = json.loads(raw.decode("utf-8"))
|
||||
if (not isinstance(data, dict) or set(data) != {"kind", "scope", "created_at", "id"}
|
||||
or data["kind"] != kind or data["scope"] != str(scope)
|
||||
or not isinstance(data["created_at"], str)):
|
||||
raise ValueError("invalid cursor fields")
|
||||
created_at = datetime.fromisoformat(data["created_at"].replace("Z", "+00:00"))
|
||||
if created_at.tzinfo is None:
|
||||
raise ValueError("cursor timestamp has no timezone")
|
||||
return created_at.astimezone(timezone.utc), uuid.UUID(data["id"])
|
||||
except (ValueError, TypeError, KeyError, UnicodeError, binascii.Error):
|
||||
raise invalid("Некорректный cursor")
|
||||
|
||||
|
||||
def parse_uuid(value, label):
|
||||
if not isinstance(value, str):
|
||||
raise invalid("Некорректный " + label)
|
||||
try:
|
||||
return uuid.UUID(value)
|
||||
except (ValueError, AttributeError):
|
||||
raise invalid("Некорректный " + label)
|
||||
|
||||
|
||||
def parse_limit(query):
|
||||
values = query.get("limit")
|
||||
if values is None:
|
||||
return 50
|
||||
if len(values) != 1 or not re.fullmatch(r"[0-9]+", values[0]):
|
||||
raise invalid("Некорректный limit")
|
||||
value = int(values[0])
|
||||
if not 1 <= value <= 100:
|
||||
raise invalid("Некорректный limit")
|
||||
return value
|
||||
|
||||
|
||||
def database_conninfo():
|
||||
return make_conninfo(
|
||||
host=os.environ.get("PGHOST", "localhost"),
|
||||
port=os.environ.get("PGPORT", "5432"),
|
||||
dbname=os.environ.get("PGDATABASE", "messenger"),
|
||||
user=os.environ.get("PGUSER", "messenger"),
|
||||
password=os.environ.get("PGPASSWORD", ""),
|
||||
connect_timeout=3,
|
||||
application_name="mtusi-messenger-lab3",
|
||||
)
|
||||
|
||||
|
||||
def migrate(pool):
|
||||
with pool.connection() as conn:
|
||||
conn.execute("SELECT pg_advisory_xact_lock(24012026, 2)")
|
||||
conn.execute(
|
||||
"""CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version TEXT PRIMARY KEY,
|
||||
applied_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
)"""
|
||||
)
|
||||
applied = {row["version"] for row in conn.execute(
|
||||
"SELECT version FROM schema_migrations"
|
||||
).fetchall()}
|
||||
for path in sorted(MIGRATIONS.glob("[0-9]*.sql")):
|
||||
if path.name in applied:
|
||||
continue
|
||||
sql = path.read_text(encoding="utf-8").strip()
|
||||
if not sql:
|
||||
raise RuntimeError("empty database migration: " + path.name)
|
||||
conn.execute(sql, prepare=False)
|
||||
conn.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (path.name,))
|
||||
LOG.info("database migration applied version=%s", path.name)
|
||||
|
||||
|
||||
def validate_runtime_config():
|
||||
try:
|
||||
ttl = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
if ttl < 1 or ttl > 31_536_000:
|
||||
raise ValueError()
|
||||
max_connections = int(os.environ.get("DB_POOL_MAX_SIZE", "10"))
|
||||
if max_connections < 1 or max_connections > 100:
|
||||
raise ValueError()
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
if not 1 <= port <= 65535:
|
||||
raise ValueError()
|
||||
except ValueError:
|
||||
raise SystemExit("Invalid APP_PORT, SESSION_TTL_SECONDS or DB_POOL_MAX_SIZE")
|
||||
return ttl, max_connections, port
|
||||
|
||||
|
||||
def create_s3_client():
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "").strip()
|
||||
region = os.environ.get("S3_REGION", "us-east-1").strip()
|
||||
bucket = os.environ.get("S3_BUCKET", "").strip()
|
||||
access_key = os.environ.get("S3_ACCESS_KEY_ID", "").strip()
|
||||
secret_key = os.environ.get("S3_SECRET_ACCESS_KEY", "")
|
||||
if not endpoint or not region or not bucket or not access_key or not secret_key:
|
||||
raise SystemExit("S3_ENDPOINT, S3_REGION, S3_BUCKET and S3 credentials are required")
|
||||
if not endpoint.startswith(("http://", "https://")):
|
||||
raise SystemExit("S3_ENDPOINT must use http:// or https://")
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=1,
|
||||
read_timeout=2,
|
||||
retries={"total_max_attempts": 1, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
return client, bucket
|
||||
|
||||
|
||||
def validate_image_payload(data, content_type):
|
||||
expected_format = IMAGE_CONTENT_TYPES.get(content_type)
|
||||
if expected_format is None:
|
||||
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
if image.width * image.height > MAX_IMAGE_PIXELS:
|
||||
raise ApiError(413, "payload_too_large", "Изображение слишком велико")
|
||||
if image.format != expected_format:
|
||||
raise ApiError(415, "unsupported_media_type", "Тип содержимого не совпадает с изображением")
|
||||
image.verify()
|
||||
except ApiError:
|
||||
raise
|
||||
except (Image.DecompressionBombError, Image.DecompressionBombWarning):
|
||||
raise ApiError(413, "payload_too_large", "Изображение слишком велико")
|
||||
except (OSError, SyntaxError, UnidentifiedImageError, ValueError):
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое или неподдерживаемое изображение")
|
||||
|
||||
|
||||
class MessengerHandler(BaseHTTPRequestHandler):
|
||||
protocol_version = "HTTP/1.1"
|
||||
|
||||
def do_GET(self):
|
||||
self._dispatch()
|
||||
|
||||
def do_POST(self):
|
||||
self._dispatch()
|
||||
|
||||
def do_DELETE(self):
|
||||
self._dispatch()
|
||||
|
||||
def do_PUT(self):
|
||||
self._dispatch()
|
||||
|
||||
def do_PATCH(self):
|
||||
self._dispatch()
|
||||
|
||||
def do_OPTIONS(self):
|
||||
self._dispatch()
|
||||
|
||||
def _dispatch(self):
|
||||
self.request_id = str(uuid.uuid4())
|
||||
self.response_status = 500
|
||||
self._pending_object_key = None
|
||||
try:
|
||||
path = urlsplit(self.path).path
|
||||
if self.command == "GET" and path == "/health/live":
|
||||
status, payload = 200, {"status": "ok"}
|
||||
else:
|
||||
with POOL.connection() as conn:
|
||||
status, payload = self._route(conn)
|
||||
self._pending_object_key = None
|
||||
if isinstance(payload, BinaryResponse):
|
||||
self._send_bytes(status, payload.data, payload.content_type)
|
||||
else:
|
||||
self._send_json(status, payload)
|
||||
except ApiError as error:
|
||||
self._cleanup_pending_object()
|
||||
self._send_error(error.status, error.code, error.message, error.headers)
|
||||
except (psycopg.Error, PoolTimeout):
|
||||
self._cleanup_pending_object()
|
||||
LOG.warning("database unavailable request_id=%s", self.request_id)
|
||||
self._send_error(503, "unavailable", "Хранилище временно недоступно")
|
||||
except (BotoCoreError, ClientError):
|
||||
self._cleanup_pending_object()
|
||||
LOG.warning("object storage unavailable request_id=%s", self.request_id)
|
||||
self._send_error(503, "unavailable", "Файловое хранилище временно недоступно")
|
||||
except Exception as error:
|
||||
self._cleanup_pending_object()
|
||||
LOG.error("unhandled request error request_id=%s error_type=%s",
|
||||
self.request_id, type(error).__name__)
|
||||
self._send_error(500, "internal_error", "Внутренняя ошибка сервера")
|
||||
finally:
|
||||
LOG.info("request method=%s path=%s status=%s request_id=%s",
|
||||
self.command, urlsplit(self.path).path, self.response_status, self.request_id)
|
||||
|
||||
def _cleanup_pending_object(self):
|
||||
key = self._pending_object_key
|
||||
self._pending_object_key = None
|
||||
if key is None or S3_CLIENT is None:
|
||||
return
|
||||
try:
|
||||
S3_CLIENT.delete_object(Bucket=S3_BUCKET, Key=key)
|
||||
except (BotoCoreError, ClientError) as error:
|
||||
LOG.error("failed to compensate object upload request_id=%s error_type=%s",
|
||||
self.request_id, type(error).__name__)
|
||||
|
||||
def _send_json(self, status, payload):
|
||||
data = b"" if status == 204 else json.dumps(
|
||||
payload, ensure_ascii=False, separators=(",", ":")
|
||||
).encode("utf-8")
|
||||
self.response_status = status
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("X-Request-Id", self.request_id)
|
||||
self.send_header("X-Instance-Id", INSTANCE_ID)
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
if data:
|
||||
self.wfile.write(data)
|
||||
self.close_connection = True
|
||||
|
||||
def _send_bytes(self, status, data, content_type):
|
||||
self.response_status = status
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", content_type)
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("Cache-Control", "private, no-store")
|
||||
self.send_header("X-Request-Id", self.request_id)
|
||||
self.send_header("X-Instance-Id", INSTANCE_ID)
|
||||
self.send_header("Connection", "close")
|
||||
self.end_headers()
|
||||
if data:
|
||||
self.wfile.write(data)
|
||||
self.close_connection = True
|
||||
|
||||
def _send_error(self, status, code, message, headers=None):
|
||||
data = json.dumps(
|
||||
{"error": {"code": code, "message": message, "request_id": self.request_id}},
|
||||
ensure_ascii=False,
|
||||
separators=(",", ":"),
|
||||
).encode("utf-8")
|
||||
self.response_status = status
|
||||
self.send_response(status)
|
||||
self.send_header("Content-Type", "application/json; charset=utf-8")
|
||||
self.send_header("Content-Length", str(len(data)))
|
||||
self.send_header("X-Request-Id", self.request_id)
|
||||
self.send_header("X-Instance-Id", INSTANCE_ID)
|
||||
self.send_header("Connection", "close")
|
||||
for name, value in (headers or {}).items():
|
||||
self.send_header(name, value)
|
||||
self.end_headers()
|
||||
self.wfile.write(data)
|
||||
self.close_connection = True
|
||||
|
||||
def _read_json(self):
|
||||
content_type = self.headers.get("Content-Type", "")
|
||||
media_type = content_type.split(";", 1)[0].strip().lower()
|
||||
if media_type != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Ожидается application/json")
|
||||
length = self.headers.get("Content-Length")
|
||||
if length is None or not re.fullmatch(r"[0-9]+", length):
|
||||
raise invalid("Некорректный Content-Length")
|
||||
size = int(length)
|
||||
if size > MAX_BODY_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Тело запроса слишком велико")
|
||||
try:
|
||||
raw = self.rfile.read(size)
|
||||
if len(raw) != size:
|
||||
raise ValueError("incomplete body")
|
||||
|
||||
def object_without_duplicates(pairs):
|
||||
result = {}
|
||||
for key, value in pairs:
|
||||
if key in result:
|
||||
raise ValueError("duplicate JSON key")
|
||||
result[key] = value
|
||||
return result
|
||||
|
||||
value = json.loads(
|
||||
raw.decode("utf-8"),
|
||||
object_pairs_hook=object_without_duplicates,
|
||||
parse_constant=lambda value: (_ for _ in ()).throw(ValueError(value)),
|
||||
)
|
||||
except (ValueError, UnicodeError):
|
||||
raise invalid("Некорректный JSON")
|
||||
if not isinstance(value, dict):
|
||||
raise invalid("JSON body должен быть объектом")
|
||||
return value
|
||||
|
||||
def _read_binary(self):
|
||||
lengths = self.headers.get_all("Content-Length", [])
|
||||
if (self.headers.get("Transfer-Encoding") is not None or len(lengths) != 1
|
||||
or len(lengths[0]) > 20 or not re.fullmatch(r"[0-9]+", lengths[0])):
|
||||
raise invalid("Некорректный Content-Length")
|
||||
size = int(lengths[0])
|
||||
if size > MAX_UPLOAD_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Файл превышает 10 MiB")
|
||||
content_type = self.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
if content_type not in IMAGE_CONTENT_TYPES:
|
||||
raise ApiError(415, "unsupported_media_type", "Поддерживаются только PNG и JPEG")
|
||||
data = self.rfile.read(size)
|
||||
if len(data) != size:
|
||||
raise invalid("Неполное тело запроса")
|
||||
validate_image_payload(data, content_type)
|
||||
return data, content_type
|
||||
|
||||
def _attachment_filename(self):
|
||||
query = self._query()
|
||||
values = query.get("filename")
|
||||
if set(query) != {"filename"} or values is None or len(values) != 1:
|
||||
raise invalid("Требуется ровно один параметр filename")
|
||||
filename = values[0]
|
||||
if (not 1 <= len(filename) <= 255
|
||||
or any(char in "/\\\x00" or unicodedata.category(char) == "Cc"
|
||||
for char in filename)):
|
||||
raise invalid("Некорректный filename")
|
||||
return filename
|
||||
|
||||
def _parse_attachment_ids(self, body):
|
||||
values = body.get("attachment_ids", [])
|
||||
if not isinstance(values, list) or len(values) > 10:
|
||||
raise invalid("Некорректный attachment_ids")
|
||||
attachment_ids = [parse_uuid(value, "attachment_id") for value in values]
|
||||
if len(set(attachment_ids)) != len(attachment_ids):
|
||||
raise invalid("attachment_ids содержит дубликаты")
|
||||
return attachment_ids
|
||||
|
||||
def _validate_message_attachments(self, conn, chat_id, attachment_ids):
|
||||
if not attachment_ids:
|
||||
return
|
||||
rows = conn.execute(
|
||||
"""SELECT id, status FROM attachments
|
||||
WHERE chat_id = %s AND id = ANY(%s::uuid[])""",
|
||||
(chat_id, attachment_ids),
|
||||
).fetchall()
|
||||
if len(rows) != len(attachment_ids):
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
if any(row["status"] != "ready" for row in rows):
|
||||
raise ApiError(409, "conflict", "Вложение ещё не готово")
|
||||
|
||||
def _upload_attachment(self, conn, user_id, chat_id):
|
||||
filename = self._attachment_filename()
|
||||
chat = conn.execute(
|
||||
"""SELECT c.id FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = %s AND m.user_id = %s""",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
data, content_type = self._read_binary()
|
||||
attachment_id = uuid.uuid4()
|
||||
object_key = "attachments/" + str(attachment_id)
|
||||
checksum = hashlib.sha256(data).hexdigest()
|
||||
self._pending_object_key = object_key
|
||||
S3_CLIENT.put_object(
|
||||
Bucket=S3_BUCKET,
|
||||
Key=object_key,
|
||||
Body=data,
|
||||
ContentType=content_type,
|
||||
Metadata={"sha256": checksum},
|
||||
)
|
||||
row = conn.execute(
|
||||
"""INSERT INTO attachments
|
||||
(id, chat_id, owner_id, filename, content_type, size_bytes,
|
||||
sha256, object_key)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
|
||||
RETURNING id, chat_id, owner_id, filename, content_type,
|
||||
size_bytes, sha256, status, variants, error_code,
|
||||
created_at, updated_at""",
|
||||
(attachment_id, chat_id, user_id, filename, content_type,
|
||||
len(data), checksum, object_key),
|
||||
).fetchone()
|
||||
return 201, attachment_json(row)
|
||||
|
||||
def _get_attachment(self, conn, user_id, attachment_id):
|
||||
row = conn.execute(
|
||||
"""SELECT a.id, a.chat_id, a.owner_id, a.filename, a.content_type,
|
||||
a.size_bytes, a.sha256, a.status, a.variants, a.error_code,
|
||||
a.created_at, a.updated_at, a.object_key
|
||||
FROM attachments a
|
||||
JOIN chat_members m ON m.chat_id = a.chat_id
|
||||
WHERE a.id = %s AND m.user_id = %s""",
|
||||
(attachment_id, user_id),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
return row
|
||||
|
||||
def _download_attachment(self, conn, user_id, attachment_id):
|
||||
query = self._query()
|
||||
if set(query) - {"variant"} or len(query.get("variant", [])) > 1:
|
||||
raise invalid("Некорректный variant")
|
||||
variant = query.get("variant", ["original"])[0]
|
||||
if variant != "original":
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
row = self._get_attachment(conn, user_id, attachment_id)
|
||||
if row["status"] != "ready":
|
||||
raise ApiError(409, "conflict", "Вложение ещё не готово")
|
||||
response = S3_CLIENT.get_object(Bucket=S3_BUCKET, Key=row["object_key"])
|
||||
with response["Body"] as body:
|
||||
data = body.read(MAX_UPLOAD_BYTES + 1)
|
||||
if (len(data) != row["size_bytes"] or len(data) > MAX_UPLOAD_BYTES
|
||||
or hashlib.sha256(data).hexdigest() != row["sha256"]):
|
||||
LOG.error("stored object integrity check failed attachment_id=%s", attachment_id)
|
||||
raise ApiError(503, "unavailable", "Файловое хранилище временно недоступно")
|
||||
return 200, BinaryResponse(data, row["content_type"])
|
||||
|
||||
def _require_fields(self, data, required):
|
||||
if set(data) != set(required):
|
||||
raise invalid("Неверный набор полей")
|
||||
|
||||
def _query(self):
|
||||
try:
|
||||
return parse_qs(urlsplit(self.path).query, keep_blank_values=True, strict_parsing=True)
|
||||
except ValueError:
|
||||
raise invalid("Некорректная строка запроса")
|
||||
|
||||
def _current_identity(self, conn):
|
||||
authorization = self.headers.get("Authorization", "")
|
||||
if not authorization.startswith("Bearer "):
|
||||
raise unauthorized("Bearer")
|
||||
token = authorization[len("Bearer "):]
|
||||
if not token or len(token) > 512:
|
||||
raise unauthorized("Bearer")
|
||||
digest = hashlib.sha256(token.encode("utf-8")).hexdigest()
|
||||
row = conn.execute(
|
||||
"""SELECT u.id
|
||||
FROM sessions s JOIN users u ON u.id = s.user_id
|
||||
WHERE s.token_hash = %s AND s.expires_at > now()""",
|
||||
(digest,),
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise unauthorized("Bearer")
|
||||
return row["id"], digest
|
||||
|
||||
def _idempotency_key(self):
|
||||
values = self.headers.get_all("Idempotency-Key", [])
|
||||
if len(values) != 1 or not IDEMPOTENCY_KEY_RE.fullmatch(values[0]):
|
||||
raise invalid("Некорректный Idempotency-Key")
|
||||
return values[0]
|
||||
|
||||
def _create_idempotent_message(self, conn, user_id, chat_id, request_path, body, key,
|
||||
attachment_ids):
|
||||
canonical_body = dict(body)
|
||||
canonical_body["attachment_ids"] = [str(item) for item in attachment_ids]
|
||||
canonical_body = json.dumps(
|
||||
canonical_body, ensure_ascii=False, sort_keys=True, separators=(",", ":")
|
||||
).encode("utf-8")
|
||||
request_hash = hashlib.sha256(canonical_body).hexdigest()
|
||||
|
||||
conn.execute("DELETE FROM idempotency_records WHERE expires_at <= now()")
|
||||
claimed = conn.execute(
|
||||
"""INSERT INTO idempotency_records
|
||||
(user_id, http_method, request_path, idempotency_key,
|
||||
request_hash, expires_at)
|
||||
VALUES (%s, 'POST', %s, %s, %s, now() + %s)
|
||||
ON CONFLICT (user_id, http_method, request_path, idempotency_key)
|
||||
DO UPDATE SET request_hash = EXCLUDED.request_hash,
|
||||
response_status = NULL,
|
||||
response_body = NULL,
|
||||
created_at = now(),
|
||||
expires_at = EXCLUDED.expires_at
|
||||
WHERE idempotency_records.expires_at <= now()
|
||||
RETURNING idempotency_key""",
|
||||
(user_id, request_path, key, request_hash, IDEMPOTENCY_TTL),
|
||||
).fetchone()
|
||||
|
||||
if claimed is None:
|
||||
existing = conn.execute(
|
||||
"""SELECT request_hash, response_status, response_body
|
||||
FROM idempotency_records
|
||||
WHERE user_id = %s AND http_method = 'POST'
|
||||
AND request_path = %s AND idempotency_key = %s""",
|
||||
(user_id, request_path, key),
|
||||
).fetchone()
|
||||
if existing is None:
|
||||
raise ApiError(503, "unavailable", "Повтор запроса временно недоступен")
|
||||
if existing["request_hash"] != request_hash:
|
||||
legacy_body = dict(body)
|
||||
legacy_body.pop("attachment_ids", None)
|
||||
legacy_hash = hashlib.sha256(json.dumps(
|
||||
legacy_body, ensure_ascii=False, sort_keys=True, separators=(",", ":")
|
||||
).encode("utf-8")).hexdigest()
|
||||
if attachment_ids or existing["request_hash"] != legacy_hash:
|
||||
raise ApiError(409, "conflict", "Idempotency-Key уже использован с другим телом")
|
||||
if existing["response_status"] is None or existing["response_body"] is None:
|
||||
raise ApiError(503, "unavailable", "Результат запроса временно недоступен")
|
||||
replay_body = dict(existing["response_body"])
|
||||
replay_body.setdefault("attachment_ids", [])
|
||||
return existing["response_status"], replay_body
|
||||
|
||||
row = conn.execute(
|
||||
"""INSERT INTO messages (chat_id, sender_id, text)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id, chat_id, sender_id, text, created_at""",
|
||||
(chat_id, user_id, body["text"]),
|
||||
).fetchone()
|
||||
for position, attachment_id in enumerate(attachment_ids):
|
||||
conn.execute(
|
||||
"""INSERT INTO message_attachments
|
||||
(chat_id, message_id, attachment_id, position)
|
||||
VALUES (%s, %s, %s, %s)""",
|
||||
(chat_id, row["id"], attachment_id, position),
|
||||
)
|
||||
payload = message_json(row, attachment_ids)
|
||||
conn.execute(
|
||||
"""UPDATE idempotency_records
|
||||
SET response_status = 201, response_body = %s
|
||||
WHERE user_id = %s AND http_method = 'POST'
|
||||
AND request_path = %s AND idempotency_key = %s""",
|
||||
(Jsonb(payload), user_id, request_path, key),
|
||||
)
|
||||
return 201, payload
|
||||
|
||||
def _create_session(self, conn):
|
||||
authorization = self.headers.get("Authorization", "")
|
||||
if not authorization.startswith("Basic "):
|
||||
raise unauthorized("Basic")
|
||||
length = self.headers.get("Content-Length", "0")
|
||||
if not re.fullmatch(r"[0-9]+", length) or int(length) != 0:
|
||||
raise invalid("Создание сессии не принимает тело запроса")
|
||||
try:
|
||||
encoded = authorization[len("Basic "):]
|
||||
decoded = base64.b64decode(encoded.encode("ascii"), validate=True).decode("utf-8")
|
||||
username, password = decoded.split(":", 1)
|
||||
except (ValueError, UnicodeError, binascii.Error):
|
||||
raise unauthorized("Basic")
|
||||
if not USERNAME_RE.fullmatch(username):
|
||||
raise unauthorized("Basic")
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at, password_hash FROM users WHERE username = %s",
|
||||
(username,),
|
||||
).fetchone()
|
||||
valid = False
|
||||
if row is not None:
|
||||
try:
|
||||
valid = PASSWORD_HASHER.verify(row["password_hash"], password)
|
||||
except (VerifyMismatchError, VerificationError, InvalidHashError):
|
||||
valid = False
|
||||
if not valid:
|
||||
raise unauthorized("Basic")
|
||||
token = secrets.token_urlsafe(32)
|
||||
expires_at = utc_now() + timedelta(seconds=SESSION_TTL_SECONDS)
|
||||
conn.execute(
|
||||
"INSERT INTO sessions (token_hash, user_id, expires_at) VALUES (%s, %s, %s)",
|
||||
(hashlib.sha256(token.encode("utf-8")).hexdigest(), row["id"], expires_at),
|
||||
)
|
||||
return 201, {
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": timestamp(expires_at),
|
||||
"user": user_json(row),
|
||||
}
|
||||
|
||||
def _route(self, conn):
|
||||
parsed = urlsplit(self.path)
|
||||
path = parsed.path
|
||||
if self.command == "GET" and path == "/health/ready":
|
||||
conn.execute("SELECT 1")
|
||||
S3_CLIENT.head_bucket(Bucket=S3_BUCKET)
|
||||
return 200, {"status": "ok"}
|
||||
|
||||
if self.command == "POST" and path == "/api/v1/users":
|
||||
body = self._read_json()
|
||||
self._require_fields(body, {"username", "display_name", "password"})
|
||||
username, display_name, password = body["username"], body["display_name"], body["password"]
|
||||
if not isinstance(username, str) or not USERNAME_RE.fullmatch(username):
|
||||
raise invalid("Некорректный username")
|
||||
if not isinstance(display_name, str) or not display_name.strip() or len(display_name) > 100:
|
||||
raise invalid("Некорректный display_name")
|
||||
if not isinstance(password, str) or not 12 <= len(password) <= 128:
|
||||
raise invalid("Некорректный password")
|
||||
password_hash = PASSWORD_HASHER.hash(password)
|
||||
try:
|
||||
row = conn.execute(
|
||||
"""INSERT INTO users (username, display_name, password_hash)
|
||||
VALUES (%s, %s, %s)
|
||||
RETURNING id, username, display_name, created_at""",
|
||||
(username, display_name, password_hash),
|
||||
).fetchone()
|
||||
except UniqueViolation:
|
||||
raise ApiError(409, "conflict", "Username уже занят")
|
||||
return 201, user_json(row)
|
||||
|
||||
if self.command == "POST" and path == "/api/v1/auth/sessions":
|
||||
return self._create_session(conn)
|
||||
|
||||
if self.command == "DELETE" and path == "/api/v1/auth/sessions/current":
|
||||
_, digest = self._current_identity(conn)
|
||||
conn.execute("DELETE FROM sessions WHERE token_hash = %s", (digest,))
|
||||
return 204, None
|
||||
|
||||
user_id, _ = self._current_identity(conn)
|
||||
if self.command == "GET" and path == "/api/v1/users/me":
|
||||
row = conn.execute(
|
||||
"SELECT id, username, display_name, created_at FROM users WHERE id = %s",
|
||||
(user_id,),
|
||||
).fetchone()
|
||||
return 200, user_json(row)
|
||||
|
||||
upload_match = re.fullmatch(r"/api/v1/chats/([^/]+)/attachments", path)
|
||||
if upload_match and self.command == "POST":
|
||||
chat_id = parse_uuid(upload_match.group(1), "chat_id")
|
||||
return self._upload_attachment(conn, user_id, chat_id)
|
||||
|
||||
attachment_match = re.fullmatch(
|
||||
r"/api/v1/attachments/([^/]+)(/content)?", path
|
||||
)
|
||||
if attachment_match and self.command == "GET":
|
||||
attachment_id = parse_uuid(attachment_match.group(1), "attachment_id")
|
||||
if attachment_match.group(2):
|
||||
return self._download_attachment(conn, user_id, attachment_id)
|
||||
query = self._query()
|
||||
if query:
|
||||
raise invalid("Параметры запроса не поддерживаются")
|
||||
return 200, attachment_json(self._get_attachment(conn, user_id, attachment_id))
|
||||
|
||||
if self.command == "POST" and path == "/api/v1/chats":
|
||||
body = self._read_json()
|
||||
self._require_fields(body, {"title", "member_ids"})
|
||||
title, member_ids = body["title"], body["member_ids"]
|
||||
if not isinstance(title, str) or not title.strip() or len(title) > 100:
|
||||
raise invalid("Некорректный title")
|
||||
if not isinstance(member_ids, list) or not 1 <= len(member_ids) <= 100:
|
||||
raise invalid("Некорректный member_ids")
|
||||
normalized = [parse_uuid(item, "member_id") for item in member_ids]
|
||||
if len(set(normalized)) != len(normalized):
|
||||
raise invalid("member_ids содержит дубликаты")
|
||||
if user_id not in normalized:
|
||||
raise invalid("Создатель должен входить в чат")
|
||||
found = conn.execute(
|
||||
"SELECT id FROM users WHERE id = ANY(%s::uuid[])",
|
||||
(normalized,),
|
||||
).fetchall()
|
||||
if len(found) != len(normalized):
|
||||
raise invalid("Неизвестный участник чата")
|
||||
chat = conn.execute(
|
||||
"INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at",
|
||||
(title,),
|
||||
).fetchone()
|
||||
for position, member_id in enumerate(normalized):
|
||||
conn.execute(
|
||||
"INSERT INTO chat_members (chat_id, user_id, member_position) VALUES (%s, %s, %s)",
|
||||
(chat["id"], member_id, position),
|
||||
)
|
||||
return 201, chat_json(conn, chat)
|
||||
|
||||
if self.command == "GET" and path == "/api/v1/chats":
|
||||
query = self._query()
|
||||
limit = parse_limit(query)
|
||||
cursors = query.get("cursor")
|
||||
if cursors is not None and (len(cursors) != 1 or not cursors[0]):
|
||||
raise invalid("Некорректный cursor")
|
||||
after = decode_cursor(cursors[0], "chats", user_id) if cursors else None
|
||||
sql = """SELECT c.id, c.title, c.created_at
|
||||
FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE m.user_id = %s"""
|
||||
params = [user_id]
|
||||
if after is not None:
|
||||
sql += " AND (c.created_at, c.id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " ORDER BY c.created_at, c.id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
has_more = len(rows) > limit
|
||||
selected = rows[:limit]
|
||||
items = [chat_json(conn, row) for row in selected]
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = selected[-1]
|
||||
next_cursor = encode_cursor("chats", user_id, last["created_at"], last["id"])
|
||||
return 200, {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
chat_match = re.fullmatch(r"/api/v1/chats/([^/]+)(?:/messages)?", path)
|
||||
if chat_match:
|
||||
chat_id = parse_uuid(chat_match.group(1), "chat_id")
|
||||
chat = conn.execute(
|
||||
"""SELECT c.id, c.title, c.created_at
|
||||
FROM chats c JOIN chat_members m ON m.chat_id = c.id
|
||||
WHERE c.id = %s AND m.user_id = %s""",
|
||||
(chat_id, user_id),
|
||||
).fetchone()
|
||||
if chat is None:
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
is_messages_path = path.endswith("/messages")
|
||||
if not is_messages_path and self.command == "GET":
|
||||
return 200, chat_json(conn, chat)
|
||||
if is_messages_path and self.command == "POST":
|
||||
key = self._idempotency_key()
|
||||
body = self._read_json()
|
||||
if set(body) - {"text", "attachment_ids"} or "text" not in body:
|
||||
raise invalid("Неверный набор полей")
|
||||
text = body["text"]
|
||||
attachment_ids = self._parse_attachment_ids(body)
|
||||
if (not isinstance(text, str) or len(text) > 4000
|
||||
or (text == "" and not attachment_ids)
|
||||
or (text != "" and not text.strip())):
|
||||
raise invalid("Некорректный text")
|
||||
self._validate_message_attachments(conn, chat_id, attachment_ids)
|
||||
return self._create_idempotent_message(
|
||||
conn, user_id, chat_id, path, body, key, attachment_ids
|
||||
)
|
||||
if is_messages_path and self.command == "GET":
|
||||
query = self._query()
|
||||
limit = parse_limit(query)
|
||||
cursors = query.get("cursor")
|
||||
if cursors is not None and (len(cursors) != 1 or not cursors[0]):
|
||||
raise invalid("Некорректный cursor")
|
||||
after = decode_cursor(cursors[0], "messages", chat_id) if cursors else None
|
||||
sql = """SELECT id, chat_id, sender_id, text, created_at,
|
||||
ARRAY(SELECT ma.attachment_id
|
||||
FROM message_attachments ma
|
||||
WHERE ma.chat_id = messages.chat_id
|
||||
AND ma.message_id = messages.id
|
||||
ORDER BY ma.position) AS attachment_ids
|
||||
FROM messages
|
||||
WHERE chat_id = %s"""
|
||||
params = [chat_id]
|
||||
if after is not None:
|
||||
sql += " AND (created_at, id) > (%s, %s)"
|
||||
params.extend(after)
|
||||
sql += " ORDER BY created_at, id LIMIT %s"
|
||||
params.append(limit + 1)
|
||||
rows = conn.execute(sql, params).fetchall()
|
||||
has_more = len(rows) > limit
|
||||
selected = rows[:limit]
|
||||
items = [message_json(row) for row in selected]
|
||||
next_cursor = None
|
||||
if has_more:
|
||||
last = selected[-1]
|
||||
next_cursor = encode_cursor("messages", chat_id, last["created_at"], last["id"])
|
||||
return 200, {"items": items, "next_cursor": next_cursor}
|
||||
|
||||
raise ApiError(404, "not_found", "Объект не найден")
|
||||
|
||||
def log_message(self, format_string, *args):
|
||||
return
|
||||
|
||||
|
||||
class MessengerServer(ThreadingHTTPServer):
|
||||
daemon_threads = False
|
||||
allow_reuse_address = True
|
||||
|
||||
|
||||
def main():
|
||||
global POOL, S3_CLIENT, S3_BUCKET, SESSION_TTL_SECONDS
|
||||
logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(message)s")
|
||||
SESSION_TTL_SECONDS, max_connections, port = validate_runtime_config()
|
||||
mode = sys.argv[1] if len(sys.argv) > 1 else "serve"
|
||||
if mode not in ("serve", "migrate") or len(sys.argv) > 2:
|
||||
raise SystemExit("Usage: app.py [serve|migrate]")
|
||||
if mode == "serve":
|
||||
S3_CLIENT, S3_BUCKET = create_s3_client()
|
||||
host = os.environ.get("APP_HOST", "0.0.0.0")
|
||||
POOL = ConnectionPool(
|
||||
conninfo=database_conninfo(),
|
||||
min_size=1,
|
||||
max_size=max_connections,
|
||||
timeout=5,
|
||||
kwargs={"row_factory": dict_row},
|
||||
open=False,
|
||||
)
|
||||
try:
|
||||
POOL.open(wait=True, timeout=15)
|
||||
if mode == "migrate":
|
||||
migrate(POOL)
|
||||
POOL.close()
|
||||
LOG.info("database migrations complete")
|
||||
return
|
||||
with POOL.connection() as conn:
|
||||
conn.execute("SELECT 1")
|
||||
except Exception as error:
|
||||
POOL.close()
|
||||
LOG.error("database initialization failed error_type=%s", type(error).__name__)
|
||||
raise SystemExit("Database unavailable or migrations failed")
|
||||
server = MessengerServer((host, port), MessengerHandler)
|
||||
LOG.info(
|
||||
"messenger starting host=%s port=%s storage=postgresql instance_id=%s",
|
||||
host, port, INSTANCE_ID,
|
||||
)
|
||||
|
||||
def request_shutdown(signum, frame):
|
||||
threading.Thread(target=server.shutdown, daemon=True).start()
|
||||
|
||||
signal.signal(signal.SIGTERM, request_shutdown)
|
||||
signal.signal(signal.SIGINT, request_shutdown)
|
||||
try:
|
||||
server.serve_forever()
|
||||
finally:
|
||||
server.server_close()
|
||||
POOL.close()
|
||||
LOG.info("messenger stopped")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
+128
@@ -0,0 +1,128 @@
|
||||
services:
|
||||
db:
|
||||
image: postgres:16.6-alpine
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
POSTGRES_DB: ${PGDATABASE:?Set PGDATABASE in .env}
|
||||
POSTGRES_USER: ${PGUSER:?Set PGUSER in .env}
|
||||
POSTGRES_PASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
|
||||
volumes:
|
||||
- postgres_data:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U \"$${POSTGRES_USER}\" -d \"$${POSTGRES_DB}\""]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
|
||||
s3:
|
||||
image: mtusi-lab4-minio:RELEASE.2025-02-07T23-21-09Z
|
||||
build:
|
||||
context: .
|
||||
dockerfile: infra/minio.Dockerfile
|
||||
command: ["server", "/data", "--console-address", ":9001"]
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
|
||||
volumes:
|
||||
- minio_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "-q", "-O", "/dev/null", "http://127.0.0.1:9000/minio/health/ready"]
|
||||
interval: 3s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
start_period: 5s
|
||||
|
||||
s3-init:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
entrypoint: ["python"]
|
||||
command: ["/scripts/s3-bootstrap.py"]
|
||||
restart: "no"
|
||||
environment:
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
|
||||
volumes:
|
||||
- ./infra/s3-bootstrap.py:/scripts/s3-bootstrap.py:ro
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
|
||||
migrate:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
command: ["python", "/app/app.py", "migrate"]
|
||||
restart: "no"
|
||||
environment:
|
||||
PGHOST: db
|
||||
PGPORT: 5432
|
||||
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
|
||||
PGUSER: ${PGUSER:?Set PGUSER in .env}
|
||||
PGPASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
|
||||
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-10}
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
api:
|
||||
build:
|
||||
context: .
|
||||
dockerfile: Dockerfile
|
||||
restart: unless-stopped
|
||||
environment:
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
DB_POOL_MAX_SIZE: ${DB_POOL_MAX_SIZE:-10}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID: ${MINIO_ROOT_USER:?Set MINIO_ROOT_USER in .env}
|
||||
S3_SECRET_ACCESS_KEY: ${MINIO_ROOT_PASSWORD:?Set MINIO_ROOT_PASSWORD in .env}
|
||||
PGHOST: db
|
||||
PGPORT: 5432
|
||||
PGDATABASE: ${PGDATABASE:?Set PGDATABASE in .env}
|
||||
PGUSER: ${PGUSER:?Set PGUSER in .env}
|
||||
PGPASSWORD: ${PGPASSWORD:?Set a local PGPASSWORD in .env}
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
s3-init:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- python
|
||||
- -c
|
||||
- "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2)"
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 10s
|
||||
|
||||
lb:
|
||||
image: nginx:1.27.5-alpine
|
||||
restart: unless-stopped
|
||||
ports:
|
||||
- "127.0.0.1:${APP_PORT:-8080}:8080"
|
||||
volumes:
|
||||
- ./nginx/default.conf:/etc/nginx/conf.d/default.conf:ro
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O /dev/null http://127.0.0.1:8080/health/live"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 12
|
||||
start_period: 5s
|
||||
|
||||
volumes:
|
||||
postgres_data:
|
||||
minio_data:
|
||||
@@ -0,0 +1,16 @@
|
||||
FROM alpine:3.21.3@sha256:a8560b36e8b8210634f77d9f7f9efd7ffa463e380b75e2e74aff4511df3ef88c
|
||||
|
||||
ARG MINIO_RELEASE=RELEASE.2025-02-07T23-21-09Z
|
||||
ARG MINIO_SHA256=5a1b5bc661f0b8fd55eee530ea472205e77624718e31f7b4402bc269299501d5
|
||||
|
||||
RUN apk add --no-cache ca-certificates curl \
|
||||
&& curl --fail --location --silent --show-error \
|
||||
"https://github.com/minio/minio/releases/download/${MINIO_RELEASE}/minio.linux-amd64.${MINIO_RELEASE}" \
|
||||
--output /usr/local/bin/minio \
|
||||
&& echo "${MINIO_SHA256} /usr/local/bin/minio" | sha256sum -c - \
|
||||
&& chmod 0755 /usr/local/bin/minio \
|
||||
&& apk del curl
|
||||
|
||||
EXPOSE 9000 9001
|
||||
ENTRYPOINT ["/usr/local/bin/minio"]
|
||||
CMD ["server", "/data", "--console-address", ":9001"]
|
||||
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Idempotently create the private MinIO bucket before starting the API."""
|
||||
import os
|
||||
import time
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
|
||||
def main():
|
||||
endpoint = os.environ.get("S3_ENDPOINT", "").strip()
|
||||
region = os.environ.get("S3_REGION", "us-east-1").strip()
|
||||
bucket = os.environ.get("S3_BUCKET", "").strip()
|
||||
access_key = os.environ.get("MINIO_ROOT_USER", "").strip()
|
||||
secret_key = os.environ.get("MINIO_ROOT_PASSWORD", "")
|
||||
if not all((endpoint, region, bucket, access_key, secret_key)):
|
||||
raise SystemExit("S3 bootstrap configuration is incomplete")
|
||||
|
||||
client = boto3.client(
|
||||
"s3",
|
||||
endpoint_url=endpoint,
|
||||
region_name=region,
|
||||
aws_access_key_id=access_key,
|
||||
aws_secret_access_key=secret_key,
|
||||
config=Config(
|
||||
signature_version="s3v4",
|
||||
s3={"addressing_style": "path"},
|
||||
connect_timeout=3,
|
||||
read_timeout=5,
|
||||
retries={"max_attempts": 1, "mode": "standard"},
|
||||
),
|
||||
)
|
||||
for attempt in range(30):
|
||||
try:
|
||||
client.head_bucket(Bucket=bucket)
|
||||
print("S3 bucket is ready")
|
||||
return
|
||||
except ClientError as error:
|
||||
code = error.response.get("Error", {}).get("Code", "")
|
||||
if code not in ("404", "NoSuchBucket", "NotFound"):
|
||||
raise SystemExit("S3 bucket bootstrap failed") from None
|
||||
try:
|
||||
client.create_bucket(Bucket=bucket)
|
||||
print("S3 bucket created and ready")
|
||||
return
|
||||
except ClientError as create_error:
|
||||
create_code = create_error.response.get("Error", {}).get("Code", "")
|
||||
if create_code not in ("BucketAlreadyExists", "BucketAlreadyOwnedByYou"):
|
||||
raise SystemExit("S3 bucket bootstrap failed") from None
|
||||
except BotoCoreError:
|
||||
if attempt == 29:
|
||||
raise SystemExit("S3 endpoint did not become available") from None
|
||||
time.sleep(2)
|
||||
raise SystemExit("S3 bucket bootstrap timed out")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE users (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
username TEXT NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name TEXT NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100),
|
||||
password_hash TEXT NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,5 @@
|
||||
CREATE TABLE chats (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
title TEXT NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE chat_members (
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
member_position SMALLINT NOT NULL CHECK (member_position BETWEEN 0 AND 99),
|
||||
PRIMARY KEY (chat_id, user_id),
|
||||
UNIQUE (chat_id, member_position)
|
||||
);
|
||||
@@ -0,0 +1,7 @@
|
||||
CREATE TABLE messages (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||
sender_id UUID NOT NULL REFERENCES users(id) ON DELETE RESTRICT,
|
||||
text TEXT NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000 AND btrim(text) <> ''),
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now()
|
||||
);
|
||||
@@ -0,0 +1,6 @@
|
||||
CREATE TABLE sessions (
|
||||
token_hash CHAR(64) PRIMARY KEY,
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL CHECK (expires_at > created_at)
|
||||
);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX messages_chat_history_idx ON messages (chat_id, created_at, id);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX chat_members_user_chat_idx ON chat_members (user_id, chat_id);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX sessions_expiry_idx ON sessions (expires_at);
|
||||
@@ -0,0 +1 @@
|
||||
CREATE INDEX chats_order_idx ON chats (created_at, id);
|
||||
@@ -0,0 +1,17 @@
|
||||
CREATE TABLE idempotency_records (
|
||||
user_id UUID NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||
http_method TEXT NOT NULL CHECK (http_method = 'POST'),
|
||||
request_path TEXT NOT NULL,
|
||||
idempotency_key VARCHAR(128) NOT NULL,
|
||||
request_hash CHAR(64) NOT NULL,
|
||||
response_status SMALLINT,
|
||||
response_body JSONB,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
expires_at TIMESTAMPTZ NOT NULL,
|
||||
PRIMARY KEY (user_id, http_method, request_path, idempotency_key),
|
||||
CHECK ((response_status IS NULL) = (response_body IS NULL)),
|
||||
CHECK (response_status IS NULL OR response_status = 201)
|
||||
);
|
||||
|
||||
CREATE INDEX idempotency_records_expiry_idx
|
||||
ON idempotency_records (expires_at);
|
||||
@@ -0,0 +1,48 @@
|
||||
ALTER TABLE messages
|
||||
DROP CONSTRAINT messages_text_check;
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_text_check
|
||||
CHECK (char_length(text) BETWEEN 0 AND 4000 AND (text = '' OR btrim(text) <> ''));
|
||||
|
||||
ALTER TABLE messages
|
||||
ADD CONSTRAINT messages_chat_id_id_unique UNIQUE (chat_id, id);
|
||||
|
||||
CREATE TABLE attachments (
|
||||
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||
chat_id UUID NOT NULL,
|
||||
owner_id UUID NOT NULL,
|
||||
filename TEXT NOT NULL CHECK (char_length(filename) BETWEEN 1 AND 255),
|
||||
content_type TEXT NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes BIGINT NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 CHAR(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
object_key TEXT NOT NULL UNIQUE,
|
||||
status TEXT NOT NULL DEFAULT 'ready' CHECK (status = 'ready'),
|
||||
variants JSONB NOT NULL DEFAULT '[]'::jsonb CHECK (jsonb_typeof(variants) = 'array'),
|
||||
error_code TEXT,
|
||||
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
|
||||
UNIQUE (chat_id, id),
|
||||
CHECK (error_code IS NULL),
|
||||
FOREIGN KEY (chat_id, owner_id)
|
||||
REFERENCES chat_members(chat_id, user_id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX attachments_chat_created_idx
|
||||
ON attachments (chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
chat_id UUID NOT NULL,
|
||||
message_id UUID NOT NULL,
|
||||
attachment_id UUID NOT NULL,
|
||||
position SMALLINT NOT NULL CHECK (position BETWEEN 0 AND 9),
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
UNIQUE (message_id, position),
|
||||
FOREIGN KEY (chat_id, message_id)
|
||||
REFERENCES messages(chat_id, id) ON DELETE CASCADE,
|
||||
FOREIGN KEY (chat_id, attachment_id)
|
||||
REFERENCES attachments(chat_id, id) ON DELETE CASCADE
|
||||
);
|
||||
|
||||
CREATE INDEX message_attachments_chat_attachment_idx
|
||||
ON message_attachments (chat_id, attachment_id);
|
||||
@@ -0,0 +1,29 @@
|
||||
# PostgreSQL schema and transactions
|
||||
|
||||
## Tables and invariants
|
||||
|
||||
- `users`: UUID primary key, unique constrained username, display name, Argon2 password hash, server timestamp.
|
||||
- `chats`: UUID primary key and title.
|
||||
- `chat_members`: composite `(chat_id, user_id)` primary key, foreign keys to both parent tables, unique stable member position per chat. The `(user_id, chat_id)` index supports listing a user's chats.
|
||||
- `messages`: UUID primary key and foreign keys to chat and sender. `(chat_id, created_at, id)` supports the API's ascending keyset history query.
|
||||
- `sessions`: SHA-256 digest of a random opaque token as primary key, user foreign key, creation and expiry timestamps. Raw tokens are returned only once and are never stored.
|
||||
- `idempotency_records`: unique per user, method, request path, and key; stores the request hash and committed response for 24 hours. Expired records are removed when a message is submitted.
|
||||
- `attachments`: PostgreSQL metadata for a chat-scoped image; `object_key` points to the object in the private MinIO bucket and is never exposed by the API.
|
||||
- `message_attachments`: ordered message-to-attachment links with composite foreign keys that prevent linking a file from another chat.
|
||||
- `schema_migrations`: migration filename and application timestamp; created by the migration runner.
|
||||
|
||||
All timestamps are `TIMESTAMPTZ`. PostgreSQL owns generated UUIDs and creation timestamps. Named migrations run once in lexicographic order; an advisory transaction lock serializes startup migration attempts.
|
||||
|
||||
## Transaction boundaries
|
||||
|
||||
Each HTTP request uses one pooled PostgreSQL connection and one transaction. A successful response is written only after that transaction commits. Creating a chat and inserting every member is one transaction, so a failed member insert rolls back both the chat and any earlier member rows. Registration relies on the unique username constraint as the final arbiter of concurrent registrations; the losing request returns `409`.
|
||||
|
||||
Creating a message, linking its attachments, and recording its idempotency result share one transaction. PostgreSQL's composite primary key serializes concurrent requests across API replicas. Matching bodies replay the original status and message; a different body returns `409`. Authentication, chat membership, and attachment scope are checked before replay. Upload writes bytes to S3 first, then inserts metadata in PostgreSQL; a failed DB transaction triggers a best-effort object delete compensation.
|
||||
|
||||
The original file is authoritative in MinIO; PostgreSQL stores its chat/owner ACL, object key, checksum, type, and size. Bucket bootstrap is idempotent and creates a private bucket. The API currently uses the local MinIO root credentials, acceptable only for this grade-3 isolated lab topology; use a scoped service account for a stronger deployment.
|
||||
|
||||
Message history uses `WHERE chat_id = $1 AND (created_at, id) > ($2, $3) ORDER BY created_at, id LIMIT $4`, matching `messages_chat_history_idx`. Cursors include their resource scope and the last row's timestamp and UUID.
|
||||
|
||||
## Durability
|
||||
|
||||
Compose mounts PostgreSQL and MinIO data directories on named `postgres_data` and `minio_data` volumes. The persistence hook restarts the API, database, and MinIO without removing those volumes. Backups and destructive volume resets are deliberately separate operator actions.
|
||||
@@ -0,0 +1,25 @@
|
||||
resolver 127.0.0.11 valid=2s ipv6=off;
|
||||
|
||||
upstream api_replicas {
|
||||
zone api_replicas 64k;
|
||||
server api:8080 resolve max_fails=1 fail_timeout=2s;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
client_max_body_size 11m;
|
||||
|
||||
location / {
|
||||
proxy_pass http://api_replicas;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
proxy_connect_timeout 2s;
|
||||
proxy_send_timeout 10s;
|
||||
proxy_read_timeout 10s;
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
argon2-cffi==23.1.0
|
||||
psycopg[binary,pool]==3.2.6
|
||||
boto3==1.36.26
|
||||
Pillow==11.1.0
|
||||
@@ -0,0 +1,11 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
|
||||
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" restart db s3
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" up -d --wait db s3
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" run --rm s3-init
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" restart api
|
||||
docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" up -d --wait --scale api=2 api lb
|
||||
@@ -0,0 +1,17 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
: "${TARGET_INSTANCE_ID:?test provides the API instance ID}"
|
||||
SCRIPT_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
PROJECT_DIR=$(dirname "$SCRIPT_DIR")
|
||||
|
||||
for container_id in $(docker compose --project-directory "$PROJECT_DIR" --env-file "$PROJECT_DIR/.env" ps -q api); do
|
||||
hostname=$(docker inspect --format '{{.Config.Hostname}}' "$container_id")
|
||||
if [ "$hostname" = "$TARGET_INSTANCE_ID" ]; then
|
||||
docker stop "$container_id" >/dev/null
|
||||
exit 0
|
||||
fi
|
||||
done
|
||||
|
||||
printf '%s\n' 'No running API container matches TARGET_INSTANCE_ID' >&2
|
||||
exit 1
|
||||
@@ -0,0 +1,123 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Exercise upload limits, image validation, attachment ACL, and message links."""
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import uuid
|
||||
import zlib
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
MAX_UPLOAD_BYTES = 10 * 1024 * 1024
|
||||
|
||||
|
||||
def oversized_png_header(width, height):
|
||||
def chunk(kind, data):
|
||||
checksum = zlib.crc32(kind + data) & 0xFFFFFFFF
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", checksum)
|
||||
|
||||
image_header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return (
|
||||
b"\x89PNG\r\n\x1a\n"
|
||||
+ chunk(b"IHDR", image_header)
|
||||
+ chunk(b"IDAT", zlib.compress(b"\x00"))
|
||||
+ chunk(b"IEND", b"")
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Validate Lab4 attachment upload rules")
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
endpoint = "/api/v1/chats/" + chat["id"] + "/attachments?filename="
|
||||
|
||||
content = (Path(__file__).resolve().parent / "fixtures" / "sample.png").read_bytes()
|
||||
uploaded = client.call(
|
||||
"POST",
|
||||
endpoint + quote("sample.png", safe=""),
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
schema="Attachment",
|
||||
)["json"]
|
||||
check(uploaded["status"] == "ready", "uploaded attachment is not ready")
|
||||
check(uploaded["variants"] == [] and uploaded["error_code"] is None,
|
||||
"Lab4 attachment must have no processing variants or error")
|
||||
check(uploaded["sha256"] == hashlib.sha256(content).hexdigest(),
|
||||
"attachment checksum differs from original")
|
||||
|
||||
downloaded = client.call(
|
||||
"GET",
|
||||
"/api/v1/attachments/" + uploaded["id"] + "/content",
|
||||
actor=bob,
|
||||
)
|
||||
check(downloaded["bytes"] == content, "download differs from uploaded bytes")
|
||||
for suffix in ("", "/content"):
|
||||
client.call("GET", "/api/v1/attachments/" + uploaded["id"] + suffix,
|
||||
404, actor=eve)
|
||||
|
||||
def rejected(filename, data, content_type, status):
|
||||
client.call(
|
||||
"POST",
|
||||
endpoint + quote(filename, safe=""),
|
||||
status,
|
||||
actor=alice,
|
||||
raw=data,
|
||||
headers={"Content-Type": content_type},
|
||||
)
|
||||
|
||||
rejected("../sample.png", content, "image/png", 400)
|
||||
rejected("mismatch.jpg", content, "image/jpeg", 415)
|
||||
rejected("corrupt.png", b"\x89PNG\r\n\x1a\nnot-an-image", "image/png", 415)
|
||||
rejected("too-large.png", b"x" * (MAX_UPLOAD_BYTES + 1), "image/png", 413)
|
||||
rejected("too-many-pixels.png", oversized_png_header(20001, 2000),
|
||||
"image/png", 413)
|
||||
|
||||
message = client.message(alice, chat, "", attachments=[uploaded["id"]])["json"]
|
||||
check(message["attachment_ids"] == [uploaded["id"]],
|
||||
"message did not retain attachment_ids")
|
||||
history = client.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages?limit=100",
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)["json"]["items"]
|
||||
check(any(item["id"] == message["id"] and
|
||||
item["attachment_ids"] == [uploaded["id"]] for item in history),
|
||||
"message history did not return attachment_ids")
|
||||
|
||||
key = uuid.uuid4().hex
|
||||
message_path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
first = client.call(
|
||||
"POST", message_path, 201, actor=alice, body={"text": "semantic replay"},
|
||||
headers={"Idempotency-Key": key}, schema="Message",
|
||||
)["json"]
|
||||
replay = client.call(
|
||||
"POST", message_path, 201, actor=alice, body={"text": "semantic replay", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": key}, schema="Message",
|
||||
)["json"]
|
||||
check(replay == first, "missing attachment_ids and [] should be idempotently equivalent")
|
||||
|
||||
other_chat = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Different attachment scope", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + other_chat["id"] + "/messages",
|
||||
404,
|
||||
actor=alice,
|
||||
body={"text": "", "attachment_ids": [uploaded["id"]]},
|
||||
headers={"Idempotency-Key": uuid.uuid4().hex},
|
||||
)
|
||||
print("PASS: PNG upload/download, authorization, file limits, and message attachment links")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,60 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify concurrent same-key requests are shared across API replicas."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from threading import Barrier
|
||||
import uuid
|
||||
|
||||
from client import Client, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--requests', type=int, default=16)
|
||||
|
||||
args = arguments('Concurrent cross-replica idempotency check', configure)
|
||||
check(2 <= args.requests <= 64, '--requests must be between 2 and 64')
|
||||
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
text = 'concurrent idempotency ' + key
|
||||
barrier = Barrier(args.requests)
|
||||
path = '/api/v1/chats/' + chat['id'] + '/messages'
|
||||
|
||||
def submit():
|
||||
worker = Client(args.base_url, args.ca_file)
|
||||
barrier.wait(timeout=10)
|
||||
return worker.call(
|
||||
'POST',
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body={'text': text},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=args.requests) as executor:
|
||||
responses = list(executor.map(lambda _: submit(), range(args.requests)))
|
||||
|
||||
messages = [response['json'] for response in responses]
|
||||
check(all(message == messages[0] for message in messages), 'replay response changed')
|
||||
instances = {response['headers']['X-Instance-Id'] for response in responses}
|
||||
check(len(instances) >= 2, 'concurrent requests did not reach two API replicas')
|
||||
|
||||
history = client.call(
|
||||
'GET',
|
||||
'/api/v1/chats/' + chat['id'] + '/messages?limit=100',
|
||||
actor=bob,
|
||||
schema='MessagePage',
|
||||
)['json']['items']
|
||||
created = [message for message in history if message['text'] == text]
|
||||
check(created == [messages[0]], 'concurrent replay created duplicate messages')
|
||||
print(
|
||||
'PASS: %d concurrent requests across %d API replicas created one message'
|
||||
% (args.requests, len(instances))
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,57 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Verify bounded API errors during an S3 outage, then restore the service."""
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from urllib.parse import quote
|
||||
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
command = [
|
||||
"docker", "compose", "--project-directory", str(ROOT),
|
||||
"--env-file", str(ROOT / ".env"), *args,
|
||||
]
|
||||
subprocess.run(
|
||||
command,
|
||||
check=True,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Verify API responses when MinIO is unavailable")
|
||||
client = Client(args.base_url, args.ca_file, timeout=15)
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
content = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
compose("stop", "s3")
|
||||
try:
|
||||
health = client.call("GET", "/health/ready", 503)
|
||||
if health["elapsed"] > 10:
|
||||
raise AssertionError("S3 readiness failure exceeded 10 seconds")
|
||||
upload = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats/" + chat["id"] + "/attachments?filename=" + quote("sample.png"),
|
||||
503,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={"Content-Type": "image/png"},
|
||||
)
|
||||
if upload["elapsed"] > 10:
|
||||
raise AssertionError("S3 upload failure exceeded 10 seconds")
|
||||
finally:
|
||||
compose("start", "s3")
|
||||
compose("up", "-d", "--wait", "s3")
|
||||
client.call("GET", "/health/ready", 200)
|
||||
|
||||
print("PASS: MinIO outage returns bounded 503 errors and recovers")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user