forked from mtusi2026/mtusi2026lab4
feat: ЛР 4 с хранением вложений в MinIO
This commit is contained in:
+13
-9
@@ -4,17 +4,21 @@ APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
|
||||
# Synthetic local credentials: replace them in your untracked .env.
|
||||
POSTGRES_USER=messenger
|
||||
POSTGRES_PASSWORD=change-me-local
|
||||
POSTGRES_DB=messenger
|
||||
DATABASE_URL=postgresql+asyncpg://messenger:change-me-local@postgres:5432/messenger
|
||||
REDIS_URL=redis://redis:6379/0
|
||||
|
||||
MINIO_ROOT_USER=local-minio-admin
|
||||
MINIO_ROOT_PASSWORD=change-me-minio-root
|
||||
S3_ENDPOINT=http://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
S3_ACCESS_KEY_ID=messenger-api
|
||||
S3_SECRET_ACCESS_KEY=change-me-minio-api
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
LOG_LEVEL=info
|
||||
|
||||
+4
-3
@@ -1,14 +1,15 @@
|
||||
FROM python:3.13.15-slim
|
||||
|
||||
WORKDIR /tests
|
||||
COPY requirements-dev.txt .
|
||||
RUN python -m pip install --no-cache-dir -r requirements-dev.txt \
|
||||
COPY requirements.txt requirements-dev.txt ./
|
||||
RUN python -m pip install --no-cache-dir -r requirements.txt -r requirements-dev.txt \
|
||||
&& useradd --uid 10001 --user-group --no-create-home --shell /usr/sbin/nologin tests
|
||||
|
||||
COPY lab.json .
|
||||
COPY app ./app
|
||||
COPY contracts ./contracts
|
||||
COPY tests ./tests
|
||||
RUN chown -R tests:tests /tests
|
||||
|
||||
USER 10001:10001
|
||||
CMD ["pytest", "-q"]
|
||||
CMD ["python", "-m", "pytest", "-q"]
|
||||
|
||||
@@ -4,7 +4,7 @@ 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 test-attachments load load-attachments test-persistence test-failover test-attachment-failover
|
||||
|
||||
help:
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -18,9 +18,15 @@ validate:
|
||||
test:
|
||||
$(PYTHON) tests/smoke.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-attachments:
|
||||
BASE_URL="$(BASE_URL)" $(PYTHON) -m pytest -q tests/test_attachments.py
|
||||
|
||||
load:
|
||||
$(PYTHON) tests/load.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
load-attachments:
|
||||
$(PYTHON) tests/upload_load.py --base-url "$(BASE_URL)" --concurrency 10 --uploads 30 $(TLS_ARGS)
|
||||
|
||||
test-persistence:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable restart hook"; exit 2)
|
||||
$(PYTHON) tests/resilience.py --mode persistence --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
@@ -28,3 +34,7 @@ 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-attachment-failover:
|
||||
@test -n "$(ACTION_SCRIPT)" || (echo "Set ACTION_SCRIPT to your implemented executable stop-one hook"; exit 2)
|
||||
$(PYTHON) tests/attachment_failover.py --action-script "$(ACTION_SCRIPT)" --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
@@ -1,37 +1,182 @@
|
||||
# Отчёт — лабораторная 4
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
- Автор, группа: Сергей Возжин, БПИ2301.
|
||||
- Целевая оценка: 4; трек 5 не выбран.
|
||||
- Commit/PR: TODO после публикации.
|
||||
- Использованные источники: контракт репозитория, документация Docker Compose, Chainguard Images, MinIO SDK и Pillow.
|
||||
- Библиотеки: FastAPI, Uvicorn, SQLAlchemy, asyncpg, Alembic, redis-py, MinIO Python SDK, Pillow, Argon2, pytest.
|
||||
- Помощь ИИ: OpenAI Codex использовался для плана, реализации, тестов и оформления отчёта; результат проверен исполняемыми тестами.
|
||||
|
||||
## Запуск из чистого clone
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Требуются Docker Engine с Compose v2, Python 3.9+ для публичных тестов и свободный host-порт 8080. Проверенный стенд: Apple M4 Pro, 12 CPU cores, 24 GB RAM, Docker Desktop; API на Python 3.13.15.
|
||||
|
||||
Закреплённые компоненты:
|
||||
|
||||
- `python:3.13.15-slim`;
|
||||
- `postgres:17.4-alpine`;
|
||||
- `redis:7.4.2-alpine`;
|
||||
- `haproxy:3.2.26-alpine`;
|
||||
- Chainguard MinIO `RELEASE.2026-10-23T20-06-51Z`, OCI index digest `sha256:3c60a2a8c4d33409a9bc7a623a7fcbfb4605adc3d89422d2f53b3f673a6e5597`;
|
||||
- Chainguard MinIO Client, вариант `latest-dev`, OCI index digest `sha256:39768db4c3fa811bc8f2e2a3e0add8ea391648b1c980de179985e1c353dc1805` (`mc --version` сообщает upstream build marker `DEVELOPMENT.GOGET`).
|
||||
|
||||
Готовые образы MinIO и `mc` скачиваются из реестра Chainguard `cgr.dev`; в Compose оба образа закреплены по OCI digest. Сервис `s3` использует минимальный образ `minio` и в учебном стенде запускается с `user: "0"`, чтобы иметь доступ к Docker volume `/data`; его порты на host не публикуются. Для одноразового `s3-bootstrap` используется образ `minio-client` с shell и `sed`, необходимыми для создания bucket, отдельного пользователя API и bucket-scoped policy.
|
||||
|
||||
Создать локальную конфигурацию и заменить синтетические пароли, не добавляя `.env` в Git:
|
||||
|
||||
```sh
|
||||
cp .env.example .env
|
||||
```
|
||||
|
||||
`S3_BUCKET` допускает изменение: bootstrap подставляет его в ограниченную policy. `MINIO_ROOT_*` получает только MinIO и bootstrap; API получает отдельные `S3_ACCESS_KEY_ID` и `S3_SECRET_ACCESS_KEY`.
|
||||
|
||||
Проверить конфигурацию, собрать образы, применить миграции и дождаться готовности:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env config --quiet
|
||||
docker compose --env-file .env up -d --build --wait
|
||||
docker compose --env-file .env ps
|
||||
```
|
||||
|
||||
`migrate` выполняет `alembic upgrade head` отдельно и однократно. `s3-bootstrap` идемпотентно создаёт приватный bucket, отдельного пользователя API и bucket-scoped policy. Две API-реплики стартуют только после миграции, Redis и успешного bootstrap. Единственная публичная точка входа — `http://localhost:8080`; API, PostgreSQL, Redis, S3 API и административная консоль MinIO наружу не публикуются.
|
||||
|
||||
Основные проверки:
|
||||
|
||||
```sh
|
||||
python3 -m venv .venv
|
||||
.venv/bin/python -m pip install -r requirements-dev.txt
|
||||
make check
|
||||
make validate PYTHON=.venv/bin/python
|
||||
make test
|
||||
make test-attachments PYTHON=.venv/bin/python
|
||||
make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 api lb
|
||||
make test-attachment-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 api lb
|
||||
scripts/check-private-bucket.sh
|
||||
scripts/check-s3-outage.sh
|
||||
.venv/bin/python scripts/measure-upload-memory.py --concurrency 10 --uploads 30
|
||||
```
|
||||
|
||||
Каждый failover-тест намеренно оставляет выбранную API-реплику остановленной, поэтому между сценариями и после последнего сценария она явно восстанавливается указанной командой `docker compose up`.
|
||||
|
||||
Безопасная остановка с сохранением данных:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down
|
||||
```
|
||||
|
||||
Намеренное необратимое удаление учебных данных выполняет только оператор:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env down -v
|
||||
```
|
||||
|
||||
## Архитектура и решения
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab3, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
```text
|
||||
HTTP client
|
||||
|
|
||||
v
|
||||
HAProxy :8080
|
||||
|
|
||||
+-- round-robin --> API replica 1 --+--> PostgreSQL: metadata
|
||||
| +--> Redis: sessions
|
||||
+-- round-robin --> API replica 2 --+--> private MinIO: original bytes
|
||||
```
|
||||
|
||||
Из lab3 сохранены две взаимозаменяемые API-реплики, HAProxy, общие PostgreSQL/Redis, Bearer-сессии, `X-Instance-Id`, общая идемпотентность сообщений, readiness и failover hooks.
|
||||
|
||||
В lab4 добавлены:
|
||||
|
||||
- MinIO и persistent `s3_data` volume;
|
||||
- таблицы `attachments` и `message_attachments`;
|
||||
- синхронный binary upload PNG/JPEG;
|
||||
- авторизованные metadata/download endpoints;
|
||||
- `attachment_ids` в сообщениях и в области сравнения идемпотентного body;
|
||||
- компенсационное удаление объекта и безопасный cleanup старых orphan-объектов.
|
||||
|
||||
PostgreSQL является источником истины для метаданных. В БД не хранятся bytes изображения. MinIO хранит оригинал по серверному ключу `originals/<UUID>`. Пользовательский `filename` хранится только как метаданные и не используется в object key или пути файловой системы.
|
||||
|
||||
### Upload и лимиты
|
||||
|
||||
API сначала проверяет сессию, доступ к чату, filename и заявленный MIME. Тело читается чанками в `SpooledTemporaryFile`: до 1 MiB находится в памяти, затем временно сбрасывается на ephemeral disk API. Как только суммарный размер становится больше 10 MiB, запрос отклоняется с 413; превысивший лимит чанк в spool не записывается. Постоянной локальной копии нет.
|
||||
|
||||
Pillow определяет реальный PNG/JPEG, проверяет совпадение MIME, размеры до декодирования пикселей и целостность изображения через `verify()`. Максимум — 10 485 760 bytes и 40 000 000 пикселей. Пустой, повреждённый или чужой формат возвращает 415; превышение лимита bytes/pixels — 413.
|
||||
|
||||
S3-вызовы выполняются вне event loop. HTTP client S3 имеет ограниченные connect/read timeout и retry. Readiness проверяет PostgreSQL, Redis и существование bucket.
|
||||
|
||||
### Транзакционная граница PostgreSQL/S3
|
||||
|
||||
Атомарной транзакции между S3 и PostgreSQL нет. Для синхронного `201 ready` выбран порядок:
|
||||
|
||||
1. Полностью проверить ограниченный файл.
|
||||
2. Выполнить S3 PUT.
|
||||
3. Выполнить транзакцию INSERT метаданных.
|
||||
4. Вернуть `201` только после успешного завершения обоих шагов.
|
||||
|
||||
Если PUT не удался, метаданные не создаются. Если PUT прошёл, а транзакция БД упала, API выполняет best-effort S3 DELETE. Unit-тест с внедрённой ошибкой БД подтверждает компенсацию.
|
||||
|
||||
Если компенсационное удаление также не удалось, остаётся orphan без метаданных. CLI находит такие объекты:
|
||||
|
||||
```sh
|
||||
docker compose --env-file .env run --rm --no-deps api \
|
||||
python -m app.tools.cleanup_orphans --dry-run --grace-seconds 3600
|
||||
|
||||
docker compose --env-file .env run --rm --no-deps api \
|
||||
python -m app.tools.cleanup_orphans --apply --grace-seconds 3600
|
||||
```
|
||||
|
||||
По умолчанию используется grace period один час; CLI запрещает значения меньше 60 секунд. Объекты с существующими метаданными и свежие orphan-объекты не удаляются. Сначала используется `--dry-run`, затем осознанный `--apply`.
|
||||
|
||||
### Доступ и идемпотентность
|
||||
|
||||
Метаданные и content доступны любому участнику чата. Неизвестный объект и запрос постороннего одинаково возвращают 404. Download идёт через API без redirect. Публичный ответ не раскрывает object key, endpoint или credentials.
|
||||
|
||||
Сообщение принимает 0–10 уникальных `attachment_ids`. Все вложения должны быть `ready` и относиться к тому же чату. Пустой текст допустим только с вложением. Сравнение идемпотентного запроса включает упорядоченный список attachment ID; отсутствие поля и `[]` считаются одинаковыми.
|
||||
|
||||
## Доказательства критериев
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Доказательство |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
| Offline/OpenAPI | `make check`; `make validate PYTHON=.venv/bin/python` | оба PASS | `evidence/results.md` |
|
||||
| Публичный smoke | `make test` | `PASS: lab4 public API scenario` | `evidence/results.md` |
|
||||
| Негативные сценарии | `make test-attachments PYTHON=.venv/bin/python` | `12 passed` | `tests/test_attachments.py`, `evidence/results.md` |
|
||||
| Компенсация S3/БД | unit-тест с ошибкой repository | S3 DELETE вызван для загруженного ключа; `1 passed` | `tests/test_attachment_compensation.py` |
|
||||
| Private bucket | `scripts/check-private-bucket.sh` | anonymous GET получил 403 | `evidence/results.md` |
|
||||
| Недоступность S3 | `scripts/check-s3-outage.sh` | readiness вернул структурированный 503; стенд восстановлен | `evidence/results.md` |
|
||||
| Persistence | `make test-persistence ACTION_SCRIPT=scripts/restart.sh` | прежние token, metadata и bytes доступны после restart PostgreSQL/Redis/MinIO/API | `evidence/results.md` |
|
||||
| Общий lab3 failover | `make test-failover ACTION_SCRIPT=scripts/stop-one.sh` | 111 записей, 1 переходная ошибка, восстановление 2,333 с, файл сохранён | `evidence/results.md` |
|
||||
| Точный attachment failover | `make test-attachment-failover ACTION_SCRIPT=scripts/stop-one.sh` | загрузившая реплика остановлена, download через другую за 3,912 с, SHA-256 совпал | `evidence/results.md` |
|
||||
| Concurrency/RAM | `scripts/measure-upload-memory.py --concurrency 10 --uploads 30` | 30/30 upload, обе реплики, пики 68,50/68,33 MiB | `evidence/upload-memory.json` |
|
||||
| Идемпотентный bootstrap | повторный запуск `docker compose up` после restart/failover | bootstrap повторно завершился с code 0 | `evidence/results.md` |
|
||||
| Cleanup dry-run | `cleanup_orphans --dry-run --grace-seconds 60` | 164 известных объекта, удалено 0 | `evidence/results.md` |
|
||||
|
||||
## Эксперименты и отказы
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
Проверяемые ожидания:
|
||||
|
||||
- остановка загрузившей API-реплики не меняет файл и не лишает вторую реплику доступа;
|
||||
- restart обязательных хранилищ с volumes сохраняет метаданные, bytes и сессию;
|
||||
- недоступность S3 наблюдаема как 503, а не 500;
|
||||
- 10 параллельных upload не приводят к неограниченному росту RAM.
|
||||
|
||||
Профиль upload: 30 запросов, concurrency 10, fixture 111 817 bytes, closed-loop, без retry. Получено 30 успешных upload за 0,382 с; максимальная latency 0,300 с; задействованы обе API-реплики. Пиковая наблюдаемая RAM: 68,50 MiB и 68,33 MiB при лимите 256 MiB на реплику.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
| Restart API + PostgreSQL + Redis + MinIO | token, metadata и bytes сохраняются | persistence PASS | потерь нет |
|
||||
| Остановка API в общем failover | вторая реплика продолжает чтение/запись | 111 записей, 1 краткая ошибка | 2,333 с; потерь и дублей нет |
|
||||
| Остановка загрузившей API | файл скачивается через другую | SHA-256 совпал, разные instance ID | 3,912 с; потерь нет |
|
||||
| Остановка MinIO | readiness сообщает отказ зависимости | структурированный 503, после запуска readiness восстановился | потерь нет |
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
Стенд выдерживает остановку одной API-реплики и штатный restart контейнеров с сохранёнными volumes. Он не выдерживает потерю Docker-host, единственного HAProxy, PostgreSQL, Redis или MinIO volume. Несколько API-процессов не делают единственные хранилища высокодоступными.
|
||||
|
||||
Upload синхронный, поэтому клиент ждёт S3 и PostgreSQL. `SpooledTemporaryFile` ограничивает RAM одной загрузки, но временный disk API должен иметь достаточный объём и отдельную квоту в production. Cleanup делает полный список объектов и строк БД; для большого bucket нужны пагинация, метрики и плановый запуск.
|
||||
|
||||
Chainguard-образы зафиксированы по digest, поэтому обновляются только явно. Стенд изолирован учебной сетью. Перед production-развёртыванием потребовались бы непривилегированный UID с корректными правами на volume, TLS, внешний secret manager, HA хранилищ, аудит и резервное копирование.
|
||||
|
||||
Presigned upload, worker, thumbnail, варианты изображений и исследовательский reconciler для оценки 5 намеренно не реализованы.
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Add S3 attachment metadata and message links for lab 4.
|
||||
|
||||
Revision ID: 20261030_0003
|
||||
Revises: 20261023_0002
|
||||
Create Date: 2026-10-30
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
revision = '20261030_0003'
|
||||
down_revision = '20261023_0002'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
'attachments',
|
||||
sa.Column('id', sa.Uuid(), nullable=False),
|
||||
sa.Column('chat_id', sa.Uuid(), nullable=False),
|
||||
sa.Column('owner_id', sa.Uuid(), nullable=False),
|
||||
sa.Column('filename', sa.String(length=255), nullable=False),
|
||||
sa.Column('object_key', sa.String(length=255), nullable=False),
|
||||
sa.Column('content_type', sa.String(length=32), nullable=False),
|
||||
sa.Column('size_bytes', sa.BigInteger(), nullable=False),
|
||||
sa.Column('sha256', sa.String(length=64), nullable=False),
|
||||
sa.Column('width', sa.Integer(), nullable=False),
|
||||
sa.Column('height', sa.Integer(), nullable=False),
|
||||
sa.Column('status', sa.String(length=16), nullable=False),
|
||||
sa.Column('error_code', sa.String(length=64), nullable=True),
|
||||
sa.Column('created_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column('updated_at', sa.DateTime(timezone=True), nullable=False),
|
||||
sa.ForeignKeyConstraint(['chat_id'], ['chats.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['owner_id'], ['users.id']),
|
||||
sa.PrimaryKeyConstraint('id'),
|
||||
sa.UniqueConstraint('object_key', name='attachments_object_key_key'),
|
||||
)
|
||||
op.create_index(
|
||||
'attachments_chat_created_idx',
|
||||
'attachments',
|
||||
['chat_id', 'created_at', 'id'],
|
||||
)
|
||||
op.create_table(
|
||||
'message_attachments',
|
||||
sa.Column('message_id', sa.Uuid(), nullable=False),
|
||||
sa.Column('attachment_id', sa.Uuid(), nullable=False),
|
||||
sa.Column('position', sa.Integer(), nullable=False),
|
||||
sa.ForeignKeyConstraint(['attachment_id'], ['attachments.id'], ondelete='CASCADE'),
|
||||
sa.ForeignKeyConstraint(['message_id'], ['messages.id'], ondelete='CASCADE'),
|
||||
sa.PrimaryKeyConstraint('message_id', 'attachment_id'),
|
||||
sa.UniqueConstraint(
|
||||
'message_id',
|
||||
'position',
|
||||
name='message_attachments_message_position_key',
|
||||
),
|
||||
)
|
||||
op.create_index(
|
||||
'message_attachments_attachment_idx',
|
||||
'message_attachments',
|
||||
['attachment_id'],
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_index('message_attachments_attachment_idx', table_name='message_attachments')
|
||||
op.drop_table('message_attachments')
|
||||
op.drop_index('attachments_chat_created_idx', table_name='attachments')
|
||||
op.drop_table('attachments')
|
||||
@@ -8,6 +8,7 @@ from ..db.redis import RedisSessionStore
|
||||
from ..domain.errors import Unauthorized
|
||||
from ..domain.models import User
|
||||
from ..services.chats import ChatService
|
||||
from ..services.attachments import AttachmentService
|
||||
from ..services.messages import MessageService
|
||||
from ..services.users import UserService
|
||||
|
||||
@@ -16,6 +17,7 @@ _BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Services:
|
||||
attachments: AttachmentService
|
||||
users: UserService
|
||||
chats: ChatService
|
||||
messages: MessageService
|
||||
@@ -38,6 +40,10 @@ def message_service(container: Services = Depends(services)) -> MessageService:
|
||||
return container.messages
|
||||
|
||||
|
||||
def attachment_service(container: Services = Depends(services)) -> AttachmentService:
|
||||
return container.attachments
|
||||
|
||||
|
||||
def session_store(container: Services = Depends(services)) -> RedisSessionStore:
|
||||
return container.sessions
|
||||
|
||||
|
||||
+12
-1
@@ -6,7 +6,16 @@ from fastapi.responses import JSONResponse
|
||||
from sqlalchemy.exc import SQLAlchemyError
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from ..domain.errors import Conflict, DomainError, Invalid, NotFound, Unauthorized, Unavailable
|
||||
from ..domain.errors import (
|
||||
Conflict,
|
||||
DomainError,
|
||||
Invalid,
|
||||
NotFound,
|
||||
PayloadTooLarge,
|
||||
Unauthorized,
|
||||
Unavailable,
|
||||
UnsupportedMediaType,
|
||||
)
|
||||
|
||||
logger = logging.getLogger('app.error')
|
||||
|
||||
@@ -27,6 +36,8 @@ STATUS_BY_DOMAIN = {
|
||||
Unauthorized: 401,
|
||||
NotFound: 404,
|
||||
Conflict: 409,
|
||||
PayloadTooLarge: 413,
|
||||
UnsupportedMediaType: 415,
|
||||
Unavailable: 503,
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Header, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
|
||||
from ...domain.models import User
|
||||
from ...services.attachments import AttachmentService
|
||||
from ..deps import attachment_service, current_user
|
||||
from ..schemas import AttachmentOut
|
||||
|
||||
router = APIRouter(tags=['attachments'])
|
||||
|
||||
|
||||
@router.post(
|
||||
'/api/v1/chats/{chat_id}/attachments',
|
||||
status_code=201,
|
||||
response_model=AttachmentOut,
|
||||
)
|
||||
async def upload(
|
||||
chat_id: UUID,
|
||||
request: Request,
|
||||
filename: str = Query(..., min_length=1, max_length=255),
|
||||
content_type: Annotated[str | None, Header(alias='Content-Type')] = None,
|
||||
actor: User = Depends(current_user),
|
||||
attachments: AttachmentService = Depends(attachment_service),
|
||||
) -> AttachmentOut:
|
||||
attachment = await attachments.upload(
|
||||
actor,
|
||||
chat_id,
|
||||
filename,
|
||||
content_type or '',
|
||||
request.stream(),
|
||||
)
|
||||
return AttachmentOut.from_domain(attachment)
|
||||
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}', response_model=AttachmentOut)
|
||||
async def metadata(
|
||||
attachment_id: UUID,
|
||||
actor: User = Depends(current_user),
|
||||
attachments: AttachmentService = Depends(attachment_service),
|
||||
) -> AttachmentOut:
|
||||
return AttachmentOut.from_domain(await attachments.get(actor, attachment_id))
|
||||
|
||||
|
||||
@router.get('/api/v1/attachments/{attachment_id}/content')
|
||||
async def content(
|
||||
attachment_id: UUID,
|
||||
variant: str = Query('original'),
|
||||
actor: User = Depends(current_user),
|
||||
attachments: AttachmentService = Depends(attachment_service),
|
||||
) -> StreamingResponse:
|
||||
if variant != 'original':
|
||||
from ...domain.errors import NotFound
|
||||
|
||||
raise NotFound('вариант вложения не найден')
|
||||
attachment, stream = await attachments.content(actor, attachment_id)
|
||||
return StreamingResponse(
|
||||
stream.chunks(),
|
||||
media_type=attachment.content_type,
|
||||
headers={
|
||||
'Content-Length': str(attachment.size_bytes),
|
||||
'Content-Disposition': f'inline; filename="attachment-{attachment.id}"',
|
||||
},
|
||||
)
|
||||
@@ -23,6 +23,7 @@ async def ready(request: Request) -> HealthOut:
|
||||
async with request.app.state.engine.connect() as connection:
|
||||
await connection.execute(text('SELECT 1'))
|
||||
await request.app.state.redis.ping()
|
||||
await request.app.state.storage.ping()
|
||||
except (SQLAlchemyError, RedisError, Unavailable, OSError):
|
||||
raise HTTPException(status_code=503, detail='обязательное хранилище недоступно') from None
|
||||
return HealthOut(status='ok')
|
||||
|
||||
@@ -35,7 +35,9 @@ async def send(
|
||||
actor: User = Depends(current_user),
|
||||
messages: MessageService = Depends(message_service),
|
||||
) -> MessageOut:
|
||||
return MessageOut.from_domain(await messages.send(actor, chat_id, body.text, idempotency_key))
|
||||
return MessageOut.from_domain(
|
||||
await messages.send(actor, chat_id, body.text, body.attachment_ids, idempotency_key)
|
||||
)
|
||||
|
||||
|
||||
@router.get('', response_model=MessagePageOut)
|
||||
|
||||
+49
-6
@@ -1,9 +1,9 @@
|
||||
from typing import Optional
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||
from pydantic import BaseModel, ConfigDict, Field, field_validator, model_validator
|
||||
|
||||
from ..domain.models import Chat, Message, Page, User
|
||||
from ..domain.models import Attachment, Chat, Message, Page, User
|
||||
from . import cursors
|
||||
from .timefmt import to_rfc3339
|
||||
|
||||
@@ -97,12 +97,21 @@ class ChatOut(Strict):
|
||||
|
||||
|
||||
class CreateMessage(Strict):
|
||||
text: str = Field(min_length=1, max_length=TEXT_MAX)
|
||||
text: str = Field(max_length=TEXT_MAX)
|
||||
attachment_ids: list[UUID] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@field_validator('text')
|
||||
@field_validator('attachment_ids')
|
||||
@classmethod
|
||||
def _text(cls, value: str) -> str:
|
||||
return not_blank(value)
|
||||
def _attachments_unique(cls, value: list[UUID]) -> list[UUID]:
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError('attachment_ids не должен содержать дубликаты')
|
||||
return value
|
||||
|
||||
@model_validator(mode='after')
|
||||
def _content_present(self) -> 'CreateMessage':
|
||||
if not self.text.strip() and not self.attachment_ids:
|
||||
raise ValueError('сообщение должно содержать текст или вложение')
|
||||
return self
|
||||
|
||||
|
||||
class MessageOut(Strict):
|
||||
@@ -111,6 +120,7 @@ class MessageOut(Strict):
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: str
|
||||
attachment_ids: list[UUID]
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, message: Message) -> 'MessageOut':
|
||||
@@ -120,6 +130,39 @@ class MessageOut(Strict):
|
||||
sender_id=message.sender_id,
|
||||
text=message.text,
|
||||
created_at=to_rfc3339(message.created_at),
|
||||
attachment_ids=list(message.attachment_ids),
|
||||
)
|
||||
|
||||
|
||||
class AttachmentOut(Strict):
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
status: str
|
||||
variants: list = Field(default_factory=list)
|
||||
error_code: str | None
|
||||
created_at: str
|
||||
updated_at: str
|
||||
|
||||
@classmethod
|
||||
def from_domain(cls, attachment: Attachment) -> 'AttachmentOut':
|
||||
return cls(
|
||||
id=attachment.id,
|
||||
chat_id=attachment.chat_id,
|
||||
owner_id=attachment.owner_id,
|
||||
filename=attachment.filename,
|
||||
content_type=attachment.content_type,
|
||||
size_bytes=attachment.size_bytes,
|
||||
sha256=attachment.sha256,
|
||||
status=attachment.status,
|
||||
variants=[],
|
||||
error_code=attachment.error_code,
|
||||
created_at=to_rfc3339(attachment.created_at),
|
||||
updated_at=to_rfc3339(attachment.updated_at),
|
||||
)
|
||||
|
||||
|
||||
|
||||
+25
-7
@@ -20,17 +20,35 @@ class Settings:
|
||||
database_url: str
|
||||
redis_url: str
|
||||
session_ttl_seconds: int
|
||||
s3_endpoint: str
|
||||
s3_region: str
|
||||
s3_bucket: str
|
||||
s3_access_key_id: str
|
||||
s3_secret_access_key: str
|
||||
max_upload_bytes: int
|
||||
max_image_pixels: int
|
||||
|
||||
|
||||
def _positive_int(name: str, default: str) -> int:
|
||||
try:
|
||||
value = int(os.getenv(name, default))
|
||||
except ValueError as exc:
|
||||
raise RuntimeError(f'{name} должен быть целым числом') from exc
|
||||
if value <= 0:
|
||||
raise RuntimeError(f'{name} должен быть больше нуля')
|
||||
return value
|
||||
|
||||
|
||||
def load_settings() -> Settings:
|
||||
try:
|
||||
ttl = int(os.getenv('SESSION_TTL_SECONDS', '3600'))
|
||||
except ValueError as exc:
|
||||
raise RuntimeError('SESSION_TTL_SECONDS должен быть целым числом') from exc
|
||||
if ttl <= 0:
|
||||
raise RuntimeError('SESSION_TTL_SECONDS должен быть больше нуля')
|
||||
return Settings(
|
||||
database_url=_read_value('DATABASE_URL', 'DATABASE_URL_FILE'),
|
||||
redis_url=_read_value('REDIS_URL', 'CACHE_URL_FILE'),
|
||||
session_ttl_seconds=ttl,
|
||||
session_ttl_seconds=_positive_int('SESSION_TTL_SECONDS', '3600'),
|
||||
s3_endpoint=os.getenv('S3_ENDPOINT', 'http://s3:9000'),
|
||||
s3_region=os.getenv('S3_REGION', 'us-east-1'),
|
||||
s3_bucket=os.getenv('S3_BUCKET', 'messenger-attachments'),
|
||||
s3_access_key_id=_read_value('S3_ACCESS_KEY_ID', 'S3_ACCESS_KEY_ID_FILE'),
|
||||
s3_secret_access_key=_read_value('S3_SECRET_ACCESS_KEY', 'S3_SECRET_ACCESS_KEY_FILE'),
|
||||
max_upload_bytes=_positive_int('MAX_UPLOAD_BYTES', '10485760'),
|
||||
max_image_pixels=_positive_int('MAX_IMAGE_PIXELS', '40000000'),
|
||||
)
|
||||
|
||||
@@ -27,3 +27,11 @@ class Conflict(DomainError):
|
||||
|
||||
class Unavailable(DomainError):
|
||||
"""Обязательная внешняя зависимость временно недоступна."""
|
||||
|
||||
|
||||
class PayloadTooLarge(DomainError):
|
||||
"""Тело запроса или декодированное содержимое превышает лимит."""
|
||||
|
||||
|
||||
class UnsupportedMediaType(DomainError):
|
||||
"""Формат содержимого не поддерживается или не соответствует MIME."""
|
||||
|
||||
@@ -30,6 +30,25 @@ class Message:
|
||||
sender_id: UUID
|
||||
text: str
|
||||
created_at: datetime
|
||||
attachment_ids: tuple[UUID, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Attachment:
|
||||
id: UUID
|
||||
chat_id: UUID
|
||||
owner_id: UUID
|
||||
filename: str
|
||||
object_key: str
|
||||
content_type: str
|
||||
size_bytes: int
|
||||
sha256: str
|
||||
width: int
|
||||
height: int
|
||||
status: str
|
||||
error_code: str | None
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
|
||||
+32
-7
@@ -12,17 +12,19 @@ from sqlalchemy import text
|
||||
from .api import errors
|
||||
from .api.deps import Services
|
||||
from .api.middleware import RequestContext
|
||||
from .api.routers import auth, chats, health, messages, users
|
||||
from .api.routers import attachments, auth, chats, health, messages, users
|
||||
from .config import load_settings
|
||||
from .db import RedisSessionStore, create_engine, create_redis, create_session_factory
|
||||
from .repositories import ChatRepository, MessageRepository, UserRepository
|
||||
from .repositories import AttachmentRepository, ChatRepository, MessageRepository, UserRepository
|
||||
from .services.attachments import AttachmentService
|
||||
from .services.chats import ChatService
|
||||
from .services.messages import MessageService
|
||||
from .services.users import UserService
|
||||
from .storage import S3Storage
|
||||
|
||||
logger = logging.getLogger('app')
|
||||
|
||||
DESCRIPTION = 'PostgreSQL хранит данные мессенджера; Redis хранит активные сессии.'
|
||||
DESCRIPTION = 'PostgreSQL хранит метаданные, Redis — сессии, приватный S3 — оригиналы вложений.'
|
||||
|
||||
|
||||
def configure_logging() -> None:
|
||||
@@ -43,16 +45,31 @@ def create_app() -> FastAPI:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
redis = create_redis(settings.redis_url)
|
||||
storage = S3Storage(
|
||||
endpoint=settings.s3_endpoint,
|
||||
access_key=settings.s3_access_key_id,
|
||||
secret_key=settings.s3_secret_access_key,
|
||||
bucket=settings.s3_bucket,
|
||||
region=settings.s3_region,
|
||||
)
|
||||
try:
|
||||
async with engine.connect() as connection:
|
||||
await connection.execute(text('SELECT 1'))
|
||||
session_store = RedisSessionStore(redis, settings.session_ttl_seconds)
|
||||
await session_store.ping()
|
||||
await storage.ping()
|
||||
session_factory = create_session_factory(engine)
|
||||
user_repository = UserRepository(session_factory)
|
||||
chat_repository = ChatRepository(session_factory)
|
||||
message_repository = MessageRepository(session_factory)
|
||||
attachment_repository = AttachmentRepository(session_factory)
|
||||
application.state.services = Services(
|
||||
attachments=AttachmentService(
|
||||
attachment_repository,
|
||||
storage,
|
||||
settings.max_upload_bytes,
|
||||
settings.max_image_pixels,
|
||||
),
|
||||
users=UserService(user_repository),
|
||||
chats=ChatService(chat_repository),
|
||||
messages=MessageService(message_repository),
|
||||
@@ -60,8 +77,9 @@ def create_app() -> FastAPI:
|
||||
)
|
||||
application.state.engine = engine
|
||||
application.state.redis = redis
|
||||
application.state.storage = storage
|
||||
application.state.ready = True
|
||||
logger.info('startup storage=postgres redis_sessions=true')
|
||||
logger.info('startup storage=postgres+s3 redis_sessions=true')
|
||||
yield
|
||||
finally:
|
||||
application.state.ready = False
|
||||
@@ -70,8 +88,8 @@ def create_app() -> FastAPI:
|
||||
logger.info('shutdown complete')
|
||||
|
||||
api = FastAPI(
|
||||
title='MTUSI Messenger. LR 3',
|
||||
version='1.3.0',
|
||||
title='MTUSI Messenger. LR 4',
|
||||
version='1.4.0',
|
||||
description=DESCRIPTION,
|
||||
lifespan=lifespan,
|
||||
)
|
||||
@@ -79,7 +97,14 @@ def create_app() -> FastAPI:
|
||||
api.state.ready = False
|
||||
api.add_middleware(RequestContext)
|
||||
errors.install(api)
|
||||
for router in (health.router, users.router, auth.router, chats.router, messages.router):
|
||||
for router in (
|
||||
health.router,
|
||||
users.router,
|
||||
auth.router,
|
||||
chats.router,
|
||||
messages.router,
|
||||
attachments.router,
|
||||
):
|
||||
api.include_router(router)
|
||||
return api
|
||||
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
from .attachment import AttachmentRow, MessageAttachmentRow
|
||||
from .chat import ChatMemberRow, ChatRow
|
||||
from .message import MessageRow
|
||||
from .user import UserRow
|
||||
|
||||
__all__ = ['ChatMemberRow', 'ChatRow', 'MessageRow', 'UserRow']
|
||||
__all__ = [
|
||||
'AttachmentRow',
|
||||
'ChatMemberRow',
|
||||
'ChatRow',
|
||||
'MessageAttachmentRow',
|
||||
'MessageRow',
|
||||
'UserRow',
|
||||
]
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import BigInteger, DateTime, ForeignKey, Index, Integer, String, UniqueConstraint
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
from sqlalchemy.types import Uuid
|
||||
|
||||
from ..db.postgres import Base
|
||||
|
||||
|
||||
class AttachmentRow(Base):
|
||||
__tablename__ = 'attachments'
|
||||
__table_args__ = (
|
||||
Index('attachments_chat_created_idx', 'chat_id', 'created_at', 'id'),
|
||||
UniqueConstraint('object_key', name='attachments_object_key_key'),
|
||||
)
|
||||
|
||||
id: Mapped[UUID] = mapped_column(Uuid, primary_key=True)
|
||||
chat_id: Mapped[UUID] = mapped_column(ForeignKey('chats.id', ondelete='CASCADE'), nullable=False)
|
||||
owner_id: Mapped[UUID] = mapped_column(ForeignKey('users.id'), nullable=False)
|
||||
filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
object_key: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content_type: Mapped[str] = mapped_column(String(32), nullable=False)
|
||||
size_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
width: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
height: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
status: Mapped[str] = mapped_column(String(16), nullable=False)
|
||||
error_code: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
updated_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), nullable=False)
|
||||
|
||||
|
||||
class MessageAttachmentRow(Base):
|
||||
__tablename__ = 'message_attachments'
|
||||
__table_args__ = (
|
||||
UniqueConstraint('message_id', 'position', name='message_attachments_message_position_key'),
|
||||
Index('message_attachments_attachment_idx', 'attachment_id'),
|
||||
)
|
||||
|
||||
message_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey('messages.id', ondelete='CASCADE'), primary_key=True
|
||||
)
|
||||
attachment_id: Mapped[UUID] = mapped_column(
|
||||
ForeignKey('attachments.id', ondelete='CASCADE'), primary_key=True
|
||||
)
|
||||
position: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
@@ -1,5 +1,6 @@
|
||||
from .attachments import AttachmentRepository
|
||||
from .chats import ChatRepository
|
||||
from .messages import MessageRepository
|
||||
from .users import UserRepository
|
||||
|
||||
__all__ = ['ChatRepository', 'MessageRepository', 'UserRepository']
|
||||
__all__ = ['AttachmentRepository', 'ChatRepository', 'MessageRepository', 'UserRepository']
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.models import Attachment
|
||||
from ..models.attachment import AttachmentRow
|
||||
from ..models.chat import ChatMemberRow, ChatRow
|
||||
|
||||
|
||||
class AttachmentRepository:
|
||||
def __init__(self, sessions: async_sessionmaker[AsyncSession]) -> None:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: AttachmentRow) -> Attachment:
|
||||
return Attachment(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
owner_id=row.owner_id,
|
||||
filename=row.filename,
|
||||
object_key=row.object_key,
|
||||
content_type=row.content_type,
|
||||
size_bytes=row.size_bytes,
|
||||
sha256=row.sha256,
|
||||
width=row.width,
|
||||
height=row.height,
|
||||
status=row.status,
|
||||
error_code=row.error_code,
|
||||
created_at=row.created_at,
|
||||
updated_at=row.updated_at,
|
||||
)
|
||||
|
||||
async def chat_exists_for_member(self, chat_id: UUID, user_id: UUID) -> bool:
|
||||
async with self._sessions() as session:
|
||||
found = await session.scalar(
|
||||
select(ChatRow.id)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == ChatRow.id)
|
||||
.where(ChatRow.id == chat_id, ChatMemberRow.user_id == user_id)
|
||||
)
|
||||
return found is not None
|
||||
|
||||
async def create(
|
||||
self,
|
||||
*,
|
||||
attachment_id: UUID,
|
||||
chat_id: UUID,
|
||||
owner_id: UUID,
|
||||
filename: str,
|
||||
object_key: str,
|
||||
content_type: str,
|
||||
size_bytes: int,
|
||||
sha256: str,
|
||||
width: int,
|
||||
height: int,
|
||||
now: datetime,
|
||||
) -> Attachment:
|
||||
row = AttachmentRow(
|
||||
id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=owner_id,
|
||||
filename=filename,
|
||||
object_key=object_key,
|
||||
content_type=content_type,
|
||||
size_bytes=size_bytes,
|
||||
sha256=sha256,
|
||||
width=width,
|
||||
height=height,
|
||||
status='ready',
|
||||
error_code=None,
|
||||
created_at=now,
|
||||
updated_at=now,
|
||||
)
|
||||
async with self._sessions() as session:
|
||||
async with session.begin():
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
return self._to_domain(row)
|
||||
|
||||
async def get_for_member(self, attachment_id: UUID, user_id: UUID) -> Attachment | None:
|
||||
async with self._sessions() as session:
|
||||
row = await session.scalar(
|
||||
select(AttachmentRow)
|
||||
.join(ChatMemberRow, ChatMemberRow.chat_id == AttachmentRow.chat_id)
|
||||
.where(
|
||||
AttachmentRow.id == attachment_id,
|
||||
ChatMemberRow.user_id == user_id,
|
||||
)
|
||||
)
|
||||
return self._to_domain(row) if row is not None else None
|
||||
@@ -1,14 +1,16 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from typing import Sequence
|
||||
from uuid import UUID
|
||||
|
||||
from sqlalchemy import select, tuple_
|
||||
from sqlalchemy.dialects.postgresql import insert
|
||||
from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker
|
||||
|
||||
from ..domain.errors import Conflict
|
||||
from ..domain.errors import Conflict, NotFound
|
||||
from ..domain.models import Keyset, Message
|
||||
from ..models.attachment import AttachmentRow, MessageAttachmentRow
|
||||
from ..models.chat import ChatMemberRow, ChatRow
|
||||
from ..models.message import MessageRow
|
||||
|
||||
@@ -18,15 +20,25 @@ class MessageRepository:
|
||||
self._sessions = sessions
|
||||
|
||||
@staticmethod
|
||||
def _to_domain(row: MessageRow) -> Message:
|
||||
def _to_domain(row: MessageRow, attachment_ids: Sequence[UUID]) -> Message:
|
||||
return Message(
|
||||
id=row.id,
|
||||
chat_id=row.chat_id,
|
||||
sender_id=row.sender_id,
|
||||
text=row.text,
|
||||
created_at=row.created_at,
|
||||
attachment_ids=tuple(attachment_ids),
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
async def _attachment_ids(session: AsyncSession, message_id: UUID) -> tuple[UUID, ...]:
|
||||
result = await session.scalars(
|
||||
select(MessageAttachmentRow.attachment_id)
|
||||
.where(MessageAttachmentRow.message_id == message_id)
|
||||
.order_by(MessageAttachmentRow.position)
|
||||
)
|
||||
return tuple(result)
|
||||
|
||||
@staticmethod
|
||||
async def _accessible_chat_id(session: AsyncSession, chat_id: UUID, user_id: UUID) -> UUID | None:
|
||||
return await session.scalar(
|
||||
@@ -41,6 +53,7 @@ class MessageRepository:
|
||||
chat_id: UUID,
|
||||
sender_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: Sequence[UUID],
|
||||
created_at: datetime,
|
||||
idempotency_key: str,
|
||||
) -> Message | None:
|
||||
@@ -50,6 +63,19 @@ class MessageRepository:
|
||||
if accessible_chat_id is None:
|
||||
return None
|
||||
|
||||
if attachment_ids:
|
||||
found = set(
|
||||
await session.scalars(
|
||||
select(AttachmentRow.id).where(
|
||||
AttachmentRow.id.in_(attachment_ids),
|
||||
AttachmentRow.chat_id == accessible_chat_id,
|
||||
AttachmentRow.status == 'ready',
|
||||
)
|
||||
)
|
||||
)
|
||||
if found != set(attachment_ids):
|
||||
raise NotFound('вложение не найдено')
|
||||
|
||||
statement = (
|
||||
insert(MessageRow)
|
||||
.values(
|
||||
@@ -72,6 +98,16 @@ class MessageRepository:
|
||||
created_id = await session.scalar(statement)
|
||||
if created_id is not None:
|
||||
row = await session.get(MessageRow, created_id)
|
||||
session.add_all(
|
||||
MessageAttachmentRow(
|
||||
message_id=created_id,
|
||||
attachment_id=attachment_id,
|
||||
position=position,
|
||||
)
|
||||
for position, attachment_id in enumerate(attachment_ids)
|
||||
)
|
||||
await session.flush()
|
||||
result_attachment_ids = tuple(attachment_ids)
|
||||
else:
|
||||
row = await session.scalar(
|
||||
select(MessageRow).where(
|
||||
@@ -82,9 +118,10 @@ class MessageRepository:
|
||||
)
|
||||
if row is None:
|
||||
raise RuntimeError('результат идемпотентной операции не найден')
|
||||
if row.text != text:
|
||||
result_attachment_ids = await self._attachment_ids(session, row.id)
|
||||
if row.text != text or result_attachment_ids != tuple(attachment_ids):
|
||||
raise Conflict('Idempotency-Key уже использован с другим сообщением')
|
||||
return self._to_domain(row)
|
||||
return self._to_domain(row, result_attachment_ids)
|
||||
|
||||
async def page_for_member(
|
||||
self, chat_id: UUID, user_id: UUID, after: Keyset | None, limit: int
|
||||
@@ -101,4 +138,8 @@ class MessageRepository:
|
||||
)
|
||||
if after is not None:
|
||||
query = query.where(tuple_(MessageRow.created_at, MessageRow.id) > tuple_(after.created_at, after.id))
|
||||
return [self._to_domain(row) for row in (await session.scalars(query)).all()]
|
||||
rows = list((await session.scalars(query)).all())
|
||||
return [
|
||||
self._to_domain(row, await self._attachment_ids(session, row.id))
|
||||
for row in rows
|
||||
]
|
||||
|
||||
@@ -0,0 +1,144 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import hashlib
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from tempfile import SpooledTemporaryFile
|
||||
from typing import AsyncIterator, BinaryIO
|
||||
import unicodedata
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
|
||||
from ..domain.errors import (
|
||||
Invalid,
|
||||
NotFound,
|
||||
PayloadTooLarge,
|
||||
Unavailable,
|
||||
UnsupportedMediaType,
|
||||
)
|
||||
from ..domain.models import Attachment, User
|
||||
from ..repositories import AttachmentRepository
|
||||
from ..storage import ObjectStream, S3Storage
|
||||
|
||||
logger = logging.getLogger('app.attachments')
|
||||
|
||||
MIME_BY_FORMAT = {'PNG': 'image/png', 'JPEG': 'image/jpeg'}
|
||||
|
||||
|
||||
def _validate_filename(filename: str) -> None:
|
||||
if not 1 <= len(filename) <= 255:
|
||||
raise Invalid('filename должен содержать от 1 до 255 символов')
|
||||
if any(
|
||||
character in {'/', '\\'} or unicodedata.category(character) == 'Cc'
|
||||
for character in filename
|
||||
):
|
||||
raise Invalid('filename содержит запрещённые символы')
|
||||
|
||||
|
||||
def _inspect_image(source: BinaryIO, declared_type: str, max_pixels: int) -> tuple[str, int, int]:
|
||||
try:
|
||||
source.seek(0)
|
||||
with Image.open(source) as image:
|
||||
actual_type = MIME_BY_FORMAT.get(image.format or '')
|
||||
if actual_type is None or actual_type != declared_type:
|
||||
raise UnsupportedMediaType('MIME не соответствует содержимому PNG/JPEG')
|
||||
width, height = image.size
|
||||
if width <= 0 or height <= 0:
|
||||
raise UnsupportedMediaType('изображение имеет неверные размеры')
|
||||
if width * height > max_pixels:
|
||||
raise PayloadTooLarge('изображение превышает лимит декодированных пикселей')
|
||||
image.verify()
|
||||
except Image.DecompressionBombError as error:
|
||||
raise PayloadTooLarge('изображение превышает лимит декодированных пикселей') from error
|
||||
except (UnidentifiedImageError, OSError, SyntaxError) as error:
|
||||
raise UnsupportedMediaType('повреждённое или неподдерживаемое изображение') from error
|
||||
finally:
|
||||
source.seek(0)
|
||||
return actual_type, width, height
|
||||
|
||||
|
||||
class AttachmentService:
|
||||
def __init__(
|
||||
self,
|
||||
repository: AttachmentRepository,
|
||||
storage: S3Storage,
|
||||
max_upload_bytes: int,
|
||||
max_image_pixels: int,
|
||||
) -> None:
|
||||
self._repository = repository
|
||||
self._storage = storage
|
||||
self._max_upload_bytes = max_upload_bytes
|
||||
self._max_image_pixels = max_image_pixels
|
||||
|
||||
async def upload(
|
||||
self,
|
||||
actor: User,
|
||||
chat_id: UUID,
|
||||
filename: str,
|
||||
declared_type: str,
|
||||
chunks: AsyncIterator[bytes],
|
||||
) -> Attachment:
|
||||
_validate_filename(filename)
|
||||
if declared_type not in MIME_BY_FORMAT.values():
|
||||
raise UnsupportedMediaType('поддерживаются только image/png и image/jpeg')
|
||||
if not await self._repository.chat_exists_for_member(chat_id, actor.id):
|
||||
raise NotFound('чат не найден')
|
||||
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
with SpooledTemporaryFile(max_size=1024 * 1024, mode='w+b') as source:
|
||||
async for chunk in chunks:
|
||||
size += len(chunk)
|
||||
if size > self._max_upload_bytes:
|
||||
raise PayloadTooLarge('файл превышает лимит 10 MiB')
|
||||
digest.update(chunk)
|
||||
source.write(chunk)
|
||||
if size == 0:
|
||||
raise UnsupportedMediaType('пустой файл не является изображением')
|
||||
|
||||
actual_type, width, height = await asyncio.to_thread(
|
||||
_inspect_image,
|
||||
source,
|
||||
declared_type,
|
||||
self._max_image_pixels,
|
||||
)
|
||||
attachment_id = uuid4()
|
||||
object_key = f'originals/{attachment_id}'
|
||||
await self._storage.put(object_key, source, size, actual_type)
|
||||
now = datetime.now(timezone.utc)
|
||||
try:
|
||||
return await self._repository.create(
|
||||
attachment_id=attachment_id,
|
||||
chat_id=chat_id,
|
||||
owner_id=actor.id,
|
||||
filename=filename,
|
||||
object_key=object_key,
|
||||
content_type=actual_type,
|
||||
size_bytes=size,
|
||||
sha256=digest.hexdigest(),
|
||||
width=width,
|
||||
height=height,
|
||||
now=now,
|
||||
)
|
||||
except Exception:
|
||||
try:
|
||||
await self._storage.remove(object_key)
|
||||
except Unavailable:
|
||||
logger.warning('failed to compensate orphan object key=%s', object_key)
|
||||
raise
|
||||
|
||||
async def get(self, actor: User, attachment_id: UUID) -> Attachment:
|
||||
attachment = await self._repository.get_for_member(attachment_id, actor.id)
|
||||
if attachment is None:
|
||||
raise NotFound('вложение не найдено')
|
||||
return attachment
|
||||
|
||||
async def content(self, actor: User, attachment_id: UUID) -> tuple[Attachment, ObjectStream]:
|
||||
attachment = await self.get(actor, attachment_id)
|
||||
try:
|
||||
stream = await self._storage.get(attachment.object_key)
|
||||
except FileNotFoundError as error:
|
||||
raise Unavailable('оригинал вложения отсутствует в хранилище') from error
|
||||
return attachment, stream
|
||||
@@ -1,7 +1,7 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from typing import Optional
|
||||
from typing import Optional, Sequence
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
from ..domain.errors import NotFound
|
||||
@@ -13,12 +13,20 @@ class MessageService:
|
||||
def __init__(self, repository: MessageRepository) -> None:
|
||||
self._repository = repository
|
||||
|
||||
async def send(self, actor: User, chat_id: UUID, text: str, idempotency_key: str) -> Message:
|
||||
async def send(
|
||||
self,
|
||||
actor: User,
|
||||
chat_id: UUID,
|
||||
text: str,
|
||||
attachment_ids: Sequence[UUID],
|
||||
idempotency_key: str,
|
||||
) -> Message:
|
||||
message = await self._repository.create_for_member(
|
||||
message_id=uuid4(),
|
||||
chat_id=chat_id,
|
||||
sender_id=actor.id,
|
||||
text=text,
|
||||
attachment_ids=attachment_ids,
|
||||
created_at=datetime.now(timezone.utc),
|
||||
idempotency_key=idempotency_key,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
from .s3 import ObjectStream, S3Storage, StoredObject
|
||||
|
||||
__all__ = ['ObjectStream', 'S3Storage', 'StoredObject']
|
||||
@@ -0,0 +1,121 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import certifi
|
||||
from dataclasses import dataclass
|
||||
from datetime import datetime
|
||||
from typing import BinaryIO, Iterator
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from minio import Minio
|
||||
from minio.error import InvalidResponseError, S3Error
|
||||
from urllib3 import PoolManager, Retry, Timeout
|
||||
from urllib3.exceptions import HTTPError
|
||||
|
||||
from ..domain.errors import Unavailable
|
||||
|
||||
|
||||
def _unavailable(error: Exception) -> Unavailable:
|
||||
return Unavailable('объектное хранилище недоступно')
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class ObjectStream:
|
||||
response: object
|
||||
|
||||
def chunks(self, size: int = 64 * 1024) -> Iterator[bytes]:
|
||||
try:
|
||||
while chunk := self.response.read(size):
|
||||
yield chunk
|
||||
finally:
|
||||
self.response.close()
|
||||
self.response.release_conn()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class StoredObject:
|
||||
key: str
|
||||
last_modified: datetime
|
||||
|
||||
|
||||
class S3Storage:
|
||||
def __init__(
|
||||
self,
|
||||
endpoint: str,
|
||||
access_key: str,
|
||||
secret_key: str,
|
||||
bucket: str,
|
||||
region: str,
|
||||
) -> None:
|
||||
parsed = urlparse(endpoint)
|
||||
if parsed.scheme not in {'http', 'https'} or not parsed.netloc or parsed.path not in {'', '/'}:
|
||||
raise RuntimeError('S3_ENDPOINT должен содержать только http(s)://host:port')
|
||||
self._client = Minio(
|
||||
parsed.netloc,
|
||||
access_key=access_key,
|
||||
secret_key=secret_key,
|
||||
secure=parsed.scheme == 'https',
|
||||
region=region,
|
||||
http_client=PoolManager(
|
||||
timeout=Timeout(connect=2, read=5),
|
||||
retries=Retry(total=1, connect=1, read=1, backoff_factor=0.1),
|
||||
cert_reqs='CERT_REQUIRED',
|
||||
ca_certs=certifi.where(),
|
||||
),
|
||||
)
|
||||
self.bucket = bucket
|
||||
|
||||
@staticmethod
|
||||
def _translate(error: Exception) -> None:
|
||||
if isinstance(error, S3Error) and error.code in {'NoSuchKey', 'NoSuchObject'}:
|
||||
raise FileNotFoundError from error
|
||||
if isinstance(error, (S3Error, InvalidResponseError, HTTPError, OSError)):
|
||||
raise _unavailable(error) from error
|
||||
raise error
|
||||
|
||||
async def ping(self) -> None:
|
||||
try:
|
||||
exists = await asyncio.to_thread(self._client.bucket_exists, self.bucket)
|
||||
except Exception as error:
|
||||
self._translate(error)
|
||||
if not exists:
|
||||
raise Unavailable('bucket объектного хранилища не создан')
|
||||
|
||||
async def put(self, key: str, source: BinaryIO, length: int, content_type: str) -> None:
|
||||
source.seek(0)
|
||||
try:
|
||||
await asyncio.to_thread(
|
||||
self._client.put_object,
|
||||
self.bucket,
|
||||
key,
|
||||
source,
|
||||
length,
|
||||
content_type,
|
||||
)
|
||||
except Exception as error:
|
||||
self._translate(error)
|
||||
|
||||
async def get(self, key: str) -> ObjectStream:
|
||||
try:
|
||||
response = await asyncio.to_thread(self._client.get_object, self.bucket, key)
|
||||
except Exception as error:
|
||||
self._translate(error)
|
||||
return ObjectStream(response)
|
||||
|
||||
async def remove(self, key: str) -> None:
|
||||
try:
|
||||
await asyncio.to_thread(self._client.remove_object, self.bucket, key)
|
||||
except Exception as error:
|
||||
self._translate(error)
|
||||
|
||||
async def list(self, prefix: str = '') -> tuple[StoredObject, ...]:
|
||||
def collect() -> tuple[StoredObject, ...]:
|
||||
return tuple(
|
||||
StoredObject(item.object_name, item.last_modified)
|
||||
for item in self._client.list_objects(self.bucket, prefix=prefix, recursive=True)
|
||||
)
|
||||
|
||||
try:
|
||||
return await asyncio.to_thread(collect)
|
||||
except Exception as error:
|
||||
self._translate(error)
|
||||
@@ -0,0 +1 @@
|
||||
"""Операторские CLI-инструменты приложения."""
|
||||
@@ -0,0 +1,61 @@
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import asyncio
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from ..config import load_settings
|
||||
from ..db import create_engine, create_session_factory
|
||||
from ..models.attachment import AttachmentRow
|
||||
from ..storage import S3Storage
|
||||
|
||||
|
||||
async def cleanup(apply: bool, grace_seconds: int) -> int:
|
||||
settings = load_settings()
|
||||
engine = create_engine(settings.database_url)
|
||||
storage = S3Storage(
|
||||
settings.s3_endpoint,
|
||||
settings.s3_access_key_id,
|
||||
settings.s3_secret_access_key,
|
||||
settings.s3_bucket,
|
||||
settings.s3_region,
|
||||
)
|
||||
try:
|
||||
sessions = create_session_factory(engine)
|
||||
async with sessions() as session:
|
||||
known = set(await session.scalars(select(AttachmentRow.object_key)))
|
||||
cutoff = datetime.now(timezone.utc) - timedelta(seconds=grace_seconds)
|
||||
removed = 0
|
||||
for item in await storage.list('originals/'):
|
||||
if item.key in known or item.last_modified > cutoff:
|
||||
continue
|
||||
action = 'DELETE' if apply else 'WOULD_DELETE'
|
||||
print(f'{action} key={item.key} modified={item.last_modified.isoformat()}')
|
||||
if apply:
|
||||
await storage.remove(item.key)
|
||||
removed += 1
|
||||
print(
|
||||
f'summary mode={"apply" if apply else "dry-run"} '
|
||||
f'known={len(known)} removed={removed} grace_seconds={grace_seconds}'
|
||||
)
|
||||
return 0
|
||||
finally:
|
||||
await engine.dispose()
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description='Safely find old S3 objects without PostgreSQL metadata')
|
||||
mode = parser.add_mutually_exclusive_group(required=True)
|
||||
mode.add_argument('--dry-run', action='store_true')
|
||||
mode.add_argument('--apply', action='store_true')
|
||||
parser.add_argument('--grace-seconds', type=int, default=3600)
|
||||
args = parser.parse_args()
|
||||
if args.grace_seconds < 60:
|
||||
parser.error('--grace-seconds must be at least 60')
|
||||
raise SystemExit(asyncio.run(cleanup(args.apply, args.grace_seconds)))
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+54
-3
@@ -20,13 +20,55 @@ services:
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
|
||||
s3:
|
||||
image: cgr.dev/chainguard/minio@sha256:3c60a2a8c4d33409a9bc7a623a7fcbfb4605adc3d89422d2f53b3f673a6e5597
|
||||
user: "0"
|
||||
command: ["server", "/data", "--console-address", ":9001"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: test-minio-admin
|
||||
MINIO_ROOT_PASSWORD: test-minio-root-password
|
||||
S3_BUCKET: messenger-attachments
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 30
|
||||
|
||||
s3-bootstrap:
|
||||
image: cgr.dev/chainguard/minio-client@sha256:39768db4c3fa811bc8f2e2a3e0add8ea391648b1c980de179985e1c353dc1805
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
mc alias set local http://s3:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD"
|
||||
mc mb --ignore-existing local/"$$S3_BUCKET"
|
||||
mc anonymous set none local/"$$S3_BUCKET"
|
||||
mc admin user info local "$$S3_ACCESS_KEY_ID" >/dev/null 2>&1 || mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY"
|
||||
sed "s/BUCKET_NAME/$$S3_BUCKET/g" /policy/s3-api-policy.json >/tmp/s3-api-policy.json
|
||||
mc admin policy info local messenger-api >/dev/null 2>&1 || mc admin policy create local messenger-api /tmp/s3-api-policy.json
|
||||
mc admin policy attach local messenger-api --user "$$S3_ACCESS_KEY_ID"
|
||||
environment:
|
||||
MINIO_ROOT_USER: test-minio-admin
|
||||
MINIO_ROOT_PASSWORD: test-minio-root-password
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID: messenger-api
|
||||
S3_SECRET_ACCESS_KEY: test-minio-api-password
|
||||
volumes:
|
||||
- ./infra/s3-api-policy.json:/policy/s3-api-policy.json:ro
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
command: ["alembic", "upgrade", "head"]
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://messenger_test:messenger_test@postgres:5432/messenger_test
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: 1
|
||||
SESSION_TTL_SECONDS: 3600
|
||||
S3_ACCESS_KEY_ID: messenger-api
|
||||
S3_SECRET_ACCESS_KEY: test-minio-api-password
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -37,12 +79,21 @@ services:
|
||||
environment:
|
||||
DATABASE_URL: postgresql+asyncpg://messenger_test:messenger_test@postgres:5432/messenger_test
|
||||
REDIS_URL: redis://redis:6379/0
|
||||
SESSION_TTL_SECONDS: 1
|
||||
SESSION_TTL_SECONDS: 3600
|
||||
S3_ENDPOINT: http://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID: messenger-api
|
||||
S3_SECRET_ACCESS_KEY: test-minio-api-password
|
||||
MAX_UPLOAD_BYTES: 10485760
|
||||
MAX_IMAGE_PIXELS: 40000000
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
s3-bootstrap:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3).read()"]
|
||||
interval: 2s
|
||||
@@ -55,7 +106,7 @@ services:
|
||||
dockerfile: Dockerfile.test
|
||||
environment:
|
||||
BASE_URL: http://api:8080
|
||||
SESSION_TTL_SECONDS: 1
|
||||
SESSION_TTL_SECONDS: 3600
|
||||
depends_on:
|
||||
api:
|
||||
condition: service_healthy
|
||||
|
||||
@@ -28,6 +28,52 @@ services:
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
s3:
|
||||
image: cgr.dev/chainguard/minio@sha256:3c60a2a8c4d33409a9bc7a623a7fcbfb4605adc3d89422d2f53b3f673a6e5597
|
||||
user: "0"
|
||||
cpus: "0.5"
|
||||
mem_limit: 256m
|
||||
command: ["server", "/data", "--console-address", ":9001"]
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-local-minio-admin}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-change-me-minio-root}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
volumes:
|
||||
- s3_data:/data
|
||||
healthcheck:
|
||||
test: ["CMD", "mc", "ready", "local"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
|
||||
s3-bootstrap:
|
||||
image: cgr.dev/chainguard/minio-client@sha256:39768db4c3fa811bc8f2e2a3e0add8ea391648b1c980de179985e1c353dc1805
|
||||
cpus: "0.25"
|
||||
mem_limit: 128m
|
||||
entrypoint: ["/bin/sh", "-c"]
|
||||
command:
|
||||
- |
|
||||
set -eu
|
||||
mc alias set local http://s3:9000 "$$MINIO_ROOT_USER" "$$MINIO_ROOT_PASSWORD"
|
||||
mc mb --ignore-existing local/"$$S3_BUCKET"
|
||||
mc anonymous set none local/"$$S3_BUCKET"
|
||||
mc admin user info local "$$S3_ACCESS_KEY_ID" >/dev/null 2>&1 || mc admin user add local "$$S3_ACCESS_KEY_ID" "$$S3_SECRET_ACCESS_KEY"
|
||||
sed "s/BUCKET_NAME/$$S3_BUCKET/g" /policy/s3-api-policy.json >/tmp/s3-api-policy.json
|
||||
mc admin policy info local messenger-api >/dev/null 2>&1 || mc admin policy create local messenger-api /tmp/s3-api-policy.json
|
||||
mc admin policy attach local messenger-api --user "$$S3_ACCESS_KEY_ID"
|
||||
environment:
|
||||
MINIO_ROOT_USER: ${MINIO_ROOT_USER:-local-minio-admin}
|
||||
MINIO_ROOT_PASSWORD: ${MINIO_ROOT_PASSWORD:-change-me-minio-root}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-api}
|
||||
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-change-me-minio-api}
|
||||
volumes:
|
||||
- ./infra/s3-api-policy.json:/policy/s3-api-policy.json:ro
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_healthy
|
||||
restart: "no"
|
||||
|
||||
migrate:
|
||||
build: .
|
||||
cpus: "0.5"
|
||||
@@ -37,6 +83,8 @@ services:
|
||||
DATABASE_URL: ${DATABASE_URL}
|
||||
REDIS_URL: ${REDIS_URL}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS}
|
||||
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-api}
|
||||
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-change-me-minio-api}
|
||||
depends_on:
|
||||
postgres:
|
||||
condition: service_healthy
|
||||
@@ -51,6 +99,13 @@ services:
|
||||
REDIS_URL: ${REDIS_URL}
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS}
|
||||
LOG_LEVEL: ${LOG_LEVEL:-info}
|
||||
S3_ENDPOINT: ${S3_ENDPOINT:-http://s3:9000}
|
||||
S3_REGION: ${S3_REGION:-us-east-1}
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-attachments}
|
||||
S3_ACCESS_KEY_ID: ${S3_ACCESS_KEY_ID:-messenger-api}
|
||||
S3_SECRET_ACCESS_KEY: ${S3_SECRET_ACCESS_KEY:-change-me-minio-api}
|
||||
MAX_UPLOAD_BYTES: ${MAX_UPLOAD_BYTES:-10485760}
|
||||
MAX_IMAGE_PIXELS: ${MAX_IMAGE_PIXELS:-40000000}
|
||||
expose:
|
||||
- "8080"
|
||||
deploy:
|
||||
@@ -60,6 +115,8 @@ services:
|
||||
condition: service_completed_successfully
|
||||
redis:
|
||||
condition: service_healthy
|
||||
s3-bootstrap:
|
||||
condition: service_completed_successfully
|
||||
healthcheck:
|
||||
test: ["CMD", "python", "-c", "import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=3).read()"]
|
||||
interval: 2s
|
||||
@@ -88,3 +145,4 @@ services:
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
s3_data:
|
||||
|
||||
@@ -0,0 +1,103 @@
|
||||
# Результаты проверки lab4
|
||||
|
||||
Дата последней перепроверки: 2026-11-04. Стенд: Apple M4 Pro, 12 CPU cores, 24 GB RAM, Docker Desktop.
|
||||
|
||||
## Версии runtime
|
||||
|
||||
```text
|
||||
Python 3.13.15
|
||||
PostgreSQL 17.4
|
||||
Redis 7.4.2
|
||||
HAProxy 3.2.26
|
||||
MinIO RELEASE.2026-10-23T20-06-51Z (commit 76c06ff1d2cc844050fdeb1d54bf8fa70db72278)
|
||||
MinIO Client DEVELOPMENT.GOGET
|
||||
```
|
||||
|
||||
MinIO и MinIO Client взяты из Chainguard Images и закреплены в Compose по multi-arch OCI index digest.
|
||||
|
||||
## Контракт и smoke
|
||||
|
||||
```text
|
||||
$ make check
|
||||
PASS: offline skeleton structure, local refs and Python syntax; application NOT tested.
|
||||
|
||||
$ make validate PYTHON=.venv/bin/python
|
||||
PASS: full OpenAPI 3.1 and JSON Schema validation; application NOT tested.
|
||||
|
||||
$ make test
|
||||
PASS: lab4 public API scenario; infrastructure and grading evidence remain separate.
|
||||
```
|
||||
|
||||
## Негативные сценарии вложений
|
||||
|
||||
```text
|
||||
$ make test-attachments PYTHON=.venv/bin/python
|
||||
............ [100%]
|
||||
12 passed in 1.86s
|
||||
```
|
||||
|
||||
Проверены: превышение 10 MiB, повреждённое изображение, подмена MIME, превышение 40 млн пикселей до декодирования, опасные filename, доступ постороннего, attachment другого чата и семантика идемпотентности `attachment_ids`.
|
||||
|
||||
```text
|
||||
$ docker compose -f compose.tests.yaml run --rm --no-deps tests python -m pytest -q tests/test_attachment_compensation.py
|
||||
. [100%]
|
||||
1 passed
|
||||
```
|
||||
|
||||
Unit-тест внедряет ошибку сохранения метаданных после успешного S3 PUT и проверяет компенсационный DELETE того же object key.
|
||||
|
||||
Полный запуск в чистом изолированном Compose-проекте, включая миграции и bootstrap MinIO:
|
||||
|
||||
```text
|
||||
$ docker compose -p lab4-chainguard-tests -f compose.tests.yaml run --rm tests python -m pytest -q
|
||||
............. [100%]
|
||||
13 passed in 0.41s
|
||||
```
|
||||
|
||||
## Приватность и bootstrap
|
||||
|
||||
```text
|
||||
$ scripts/check-private-bucket.sh
|
||||
PASS: private bucket rejected anonymous request with HTTP 403
|
||||
```
|
||||
|
||||
MinIO root credentials получает только server/bootstrap. API использует отдельного пользователя с bucket-scoped policy. Host-порты S3 API и консоли не опубликованы. Bootstrap повторно завершался с code 0 при восстановлении API после failover и при restart стенда.
|
||||
|
||||
## Persistence и отказы
|
||||
|
||||
```text
|
||||
$ make test-persistence ACTION_SCRIPT=scripts/restart.sh
|
||||
Executing explicit persistence hook; hook output suppressed to avoid leaking secrets.
|
||||
PASS: persistence preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
```
|
||||
|
||||
Hook перезапустил API, PostgreSQL, Redis и MinIO с сохранением named volumes.
|
||||
|
||||
```text
|
||||
$ make test-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
{"observed_instances_before": 2, "successful_writes": 111, "failed_attempts": 1, "first_recovery_seconds": 2.333}
|
||||
PASS: failover preserved confirmed data and existing session. Hook scope needs operator evidence.
|
||||
```
|
||||
|
||||
```text
|
||||
$ make test-attachment-failover ACTION_SCRIPT=scripts/stop-one.sh
|
||||
PASS: upload_instance=c18e79906d77 download_instance=662967386db9 recovery_seconds=3.912 failures=1 sha256=99ea7533c441f79cd630d15ce4d58d1ec4e06f6f0efb3b77a5c088305cd1bd75
|
||||
```
|
||||
|
||||
В последнем сценарии остановлена именно реплика из `X-Instance-Id` ответа upload. Download выполнен через другую реплику и совпал побайтно.
|
||||
|
||||
```text
|
||||
$ scripts/check-s3-outage.sh
|
||||
PASS: API readiness returned structured 503 while S3 was unavailable
|
||||
```
|
||||
|
||||
Скрипт автоматически восстановил MinIO и дождался готовности стенда.
|
||||
|
||||
## Cleanup
|
||||
|
||||
```text
|
||||
$ python -m app.tools.cleanup_orphans --dry-run --grace-seconds 60
|
||||
summary mode=dry-run known=164 removed=0 grace_seconds=60
|
||||
```
|
||||
|
||||
Dry-run не менял данные. Применение требует явного `--apply`; значения grace period меньше 60 секунд запрещены.
|
||||
@@ -0,0 +1,20 @@
|
||||
{
|
||||
"date": "2026-11-04",
|
||||
"profile": {
|
||||
"concurrency": 10,
|
||||
"uploads": 30,
|
||||
"file_size_bytes": 111817,
|
||||
"api_memory_limit_mib_each": 256
|
||||
},
|
||||
"result": {
|
||||
"successful_uploads": 30,
|
||||
"observed_api_instances": 2,
|
||||
"duration_seconds": 0.382,
|
||||
"max_latency_seconds": 0.3,
|
||||
"peak_memory_mib": {
|
||||
"api_replica_1": 68.5,
|
||||
"api_replica_2": 68.33
|
||||
}
|
||||
},
|
||||
"limitations": "Closed-loop profile with a small PNG; docker stats is sampled and may miss a shorter transient peak."
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ListBucket"],
|
||||
"Resource": ["arn:aws:s3:::BUCKET_NAME"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": ["arn:aws:s3:::BUCKET_NAME/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -5,3 +5,5 @@ asyncpg==0.30.0
|
||||
alembic==1.15.2
|
||||
redis==5.2.1
|
||||
argon2-cffi==25.1.0
|
||||
minio==7.2.20
|
||||
Pillow==13.0.0
|
||||
|
||||
Executable
+25
@@ -0,0 +1,25 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
project_dir=$(dirname -- "$script_dir")
|
||||
cd "$project_dir"
|
||||
|
||||
status=$(docker compose --env-file .env exec -T api python -c '
|
||||
import os
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
url = "http://s3:9000/" + os.environ["S3_BUCKET"] + "/"
|
||||
try:
|
||||
response = urllib.request.urlopen(url, timeout=5)
|
||||
except urllib.error.HTTPError as error:
|
||||
print(error.code)
|
||||
else:
|
||||
print(response.status)
|
||||
')
|
||||
|
||||
case "$status" in
|
||||
401|403) printf '%s\n' "PASS: private bucket rejected anonymous request with HTTP $status" ;;
|
||||
*) printf '%s\n' "FAIL: anonymous bucket request returned HTTP $status" >&2; exit 1 ;;
|
||||
esac
|
||||
Executable
+29
@@ -0,0 +1,29 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
script_dir=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
project_dir=$(dirname -- "$script_dir")
|
||||
cd "$project_dir"
|
||||
|
||||
restore() {
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 s3 api lb >/dev/null
|
||||
}
|
||||
trap restore EXIT HUP INT TERM
|
||||
|
||||
docker compose --env-file .env stop s3 >/dev/null
|
||||
docker compose --env-file .env exec -T api python -c '
|
||||
import json
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
try:
|
||||
urllib.request.urlopen("http://127.0.0.1:8080/health/ready", timeout=25)
|
||||
except urllib.error.HTTPError as error:
|
||||
body = json.loads(error.read())
|
||||
assert error.code == 503, error.code
|
||||
assert body["error"]["code"] == "unavailable", body
|
||||
else:
|
||||
raise SystemExit("readiness unexpectedly succeeded while S3 was stopped")
|
||||
'
|
||||
|
||||
printf '%s\n' 'PASS: API readiness returned structured 503 while S3 was unavailable'
|
||||
Executable
+109
@@ -0,0 +1,109 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Run concurrent uploads while sampling API container memory with docker stats."""
|
||||
from __future__ import annotations
|
||||
|
||||
import argparse
|
||||
import json
|
||||
from pathlib import Path
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
UNITS = {
|
||||
'B': 1,
|
||||
'kB': 1000,
|
||||
'KB': 1000,
|
||||
'KiB': 1024,
|
||||
'MB': 1000**2,
|
||||
'MiB': 1024**2,
|
||||
'GB': 1000**3,
|
||||
'GiB': 1024**3,
|
||||
}
|
||||
|
||||
|
||||
def bytes_value(value: str) -> int:
|
||||
match = re.fullmatch(r'([0-9.]+)([A-Za-z]+)', value.strip())
|
||||
if match is None or match.group(2) not in UNITS:
|
||||
raise ValueError(f'unsupported docker memory value: {value}')
|
||||
return round(float(match.group(1)) * UNITS[match.group(2)])
|
||||
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--base-url', default='http://localhost:8080')
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--uploads', type=int, default=30)
|
||||
args = parser.parse_args()
|
||||
|
||||
container_ids = subprocess.check_output(
|
||||
['docker', 'compose', '--env-file', '.env', 'ps', '-q', 'api'],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
).split()
|
||||
if len(container_ids) < 2:
|
||||
raise SystemExit('expected at least two API containers')
|
||||
|
||||
peaks: dict[str, int] = {}
|
||||
stop = threading.Event()
|
||||
ready = threading.Event()
|
||||
|
||||
def collect() -> None:
|
||||
while not stop.is_set():
|
||||
output = subprocess.check_output(
|
||||
['docker', 'stats', '--no-stream', '--format', '{{json .}}', *container_ids],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
)
|
||||
for line in output.splitlines():
|
||||
sample = json.loads(line)
|
||||
name, usage = sample['Name'], sample['MemUsage']
|
||||
current = bytes_value(usage.split('/', 1)[0])
|
||||
peaks[name] = max(peaks.get(name, 0), current)
|
||||
ready.set()
|
||||
|
||||
reader = threading.Thread(target=collect, daemon=True)
|
||||
reader.start()
|
||||
if not ready.wait(timeout=15):
|
||||
raise SystemExit('docker stats did not produce an initial sample')
|
||||
try:
|
||||
load = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
'tests/upload_load.py',
|
||||
'--base-url',
|
||||
args.base_url,
|
||||
'--concurrency',
|
||||
str(args.concurrency),
|
||||
'--uploads',
|
||||
str(args.uploads),
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
finally:
|
||||
stop.set()
|
||||
reader.join(timeout=15)
|
||||
|
||||
if not peaks:
|
||||
raise SystemExit('docker stats produced no samples; increase --uploads')
|
||||
print(load.stdout.strip())
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
'peak_memory_bytes': peaks,
|
||||
'peak_memory_mib': {
|
||||
name: round(value / 1024 / 1024, 2) for name, value in peaks.items()
|
||||
},
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
+2
-2
@@ -7,6 +7,6 @@ cd "$project_dir"
|
||||
|
||||
# Останавливаем публичный маршрут до перезапуска общих хранилищ.
|
||||
docker compose --env-file .env stop lb api >/dev/null
|
||||
docker compose --env-file .env restart postgres redis >/dev/null
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 postgres redis >/dev/null
|
||||
docker compose --env-file .env restart postgres redis s3 >/dev/null
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 postgres redis s3 >/dev/null
|
||||
docker compose --env-file .env up -d --wait --wait-timeout 60 api lb >/dev/null
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop the API replica that accepted upload and download through another replica."""
|
||||
import hashlib
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from client import Client, ROOT, arguments, check, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--action-script', required=True)
|
||||
|
||||
args = arguments('Attachment API-replica failover', configure)
|
||||
script = Path(args.action_script).expanduser().resolve()
|
||||
check(script.is_file() and os.access(script, os.X_OK), 'action script must be executable')
|
||||
client = Client(args.base_url, args.ca_file, timeout=3)
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
uploaded = client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=failover.png',
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment',
|
||||
)
|
||||
target = uploaded['headers']['X-Instance-Id']
|
||||
env = dict(os.environ)
|
||||
env['TARGET_INSTANCE_ID'] = target
|
||||
started = time.monotonic()
|
||||
subprocess.run([str(script)], env=env, check=True)
|
||||
|
||||
deadline = time.monotonic() + 15
|
||||
failures = 0
|
||||
while True:
|
||||
try:
|
||||
downloaded = client.call(
|
||||
'GET',
|
||||
f'/api/v1/attachments/{uploaded["json"]["id"]}/content',
|
||||
actor=bob,
|
||||
)
|
||||
if downloaded['headers']['X-Instance-Id'] != target:
|
||||
break
|
||||
except Exception:
|
||||
failures += 1
|
||||
check(time.monotonic() < deadline, 'download did not recover through another replica')
|
||||
time.sleep(0.2)
|
||||
|
||||
check(downloaded['bytes'] == content, 'downloaded file differs after replica failure')
|
||||
print(
|
||||
'PASS: upload_instance=%s download_instance=%s recovery_seconds=%.3f failures=%d sha256=%s'
|
||||
% (
|
||||
target,
|
||||
downloaded['headers']['X-Instance-Id'],
|
||||
time.monotonic() - started,
|
||||
failures,
|
||||
hashlib.sha256(content).hexdigest(),
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Проверка компенсации объекта при ошибке commit метаданных."""
|
||||
import asyncio
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
import pytest
|
||||
|
||||
from app.domain.models import User
|
||||
from app.services.attachments import AttachmentService
|
||||
|
||||
|
||||
class FailingRepository:
|
||||
async def chat_exists_for_member(self, chat_id, user_id):
|
||||
return True
|
||||
|
||||
async def create(self, **kwargs):
|
||||
raise RuntimeError('injected database commit failure')
|
||||
|
||||
|
||||
class RecordingStorage:
|
||||
def __init__(self):
|
||||
self.put_key = None
|
||||
self.removed_key = None
|
||||
|
||||
async def put(self, key, source, length, content_type):
|
||||
self.put_key = key
|
||||
|
||||
async def remove(self, key):
|
||||
self.removed_key = key
|
||||
|
||||
|
||||
def test_uploaded_object_is_removed_when_metadata_commit_fails():
|
||||
storage = RecordingStorage()
|
||||
service = AttachmentService(FailingRepository(), storage, 10 * 1024 * 1024, 40_000_000)
|
||||
actor = User(uuid4(), 'tester', 'Tester', datetime.now(timezone.utc))
|
||||
content = (Path(__file__).parent / 'fixtures/sample.png').read_bytes()
|
||||
|
||||
async def chunks():
|
||||
yield content
|
||||
|
||||
with pytest.raises(RuntimeError, match='injected database commit failure'):
|
||||
asyncio.run(
|
||||
service.upload(
|
||||
actor,
|
||||
uuid4(),
|
||||
'sample.png',
|
||||
'image/png',
|
||||
chunks(),
|
||||
)
|
||||
)
|
||||
|
||||
assert storage.put_key is not None
|
||||
assert storage.removed_key == storage.put_key
|
||||
@@ -0,0 +1,144 @@
|
||||
"""Негативные интеграционные проверки вложений для уровня 4."""
|
||||
import struct
|
||||
from urllib.parse import quote
|
||||
import uuid
|
||||
import zlib
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.client import Client, ROOT
|
||||
|
||||
|
||||
@pytest.fixture(scope='module')
|
||||
def scenario():
|
||||
client = Client()
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
return client, alice, bob, eve, chat
|
||||
|
||||
|
||||
def upload(client, actor, chat, content, *, filename='sample.png', content_type='image/png', expected=201):
|
||||
return client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename={quote(filename, safe="")}',
|
||||
expected,
|
||||
actor=actor,
|
||||
raw=content,
|
||||
headers={'Content-Type': content_type},
|
||||
schema='Attachment' if expected == 201 else None,
|
||||
)
|
||||
|
||||
|
||||
def oversized_dimensions_png(content: bytes) -> bytes:
|
||||
data = bytearray(content)
|
||||
data[16:20] = struct.pack('>I', 10_000)
|
||||
data[20:24] = struct.pack('>I', 5_000)
|
||||
data[29:33] = struct.pack('>I', zlib.crc32(data[12:29]) & 0xFFFFFFFF)
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def test_file_larger_than_10_mib_is_rejected(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
upload(client, alice, chat, b'x' * (10 * 1024 * 1024 + 1), expected=413)
|
||||
|
||||
|
||||
def test_corrupted_image_is_rejected(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
upload(client, alice, chat, b'not-a-png', expected=415)
|
||||
|
||||
|
||||
def test_mime_mismatch_is_rejected(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(client, alice, chat, content, content_type='image/jpeg', expected=415)
|
||||
|
||||
|
||||
def test_pixel_limit_is_checked_before_decode(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = oversized_dimensions_png((ROOT / 'tests/fixtures/sample.png').read_bytes())
|
||||
upload(client, alice, chat, content, expected=413)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'filename',
|
||||
['../escape.png', 'folder\\escape.png', 'bad\x00name.png', 'bad\x85name.png'],
|
||||
)
|
||||
def test_dangerous_filename_is_rejected(scenario, filename):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
upload(client, alice, chat, content, filename=filename, expected=400)
|
||||
|
||||
|
||||
def test_outsider_cannot_read_attachment(scenario):
|
||||
client, alice, _bob, eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, chat, content)['json']
|
||||
client.call('GET', f'/api/v1/attachments/{attachment["id"]}', 404, actor=eve)
|
||||
client.call('GET', f'/api/v1/attachments/{attachment["id"]}/content', 404, actor=eve)
|
||||
|
||||
|
||||
def test_attachment_from_another_chat_cannot_be_linked(scenario):
|
||||
client, alice, bob, _eve, chat = scenario
|
||||
other_chat = client.call(
|
||||
'POST',
|
||||
'/api/v1/chats',
|
||||
201,
|
||||
actor=alice,
|
||||
body={'title': 'Другой чат', 'member_ids': [alice['id'], bob['id']]},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, other_chat, content)['json']
|
||||
client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/messages',
|
||||
404,
|
||||
actor=alice,
|
||||
body={'text': 'чужое вложение', 'attachment_ids': [attachment['id']]},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
|
||||
|
||||
def test_idempotency_distinguishes_attachment_list(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = upload(client, alice, chat, content)['json']
|
||||
key = uuid.uuid4().hex
|
||||
first = client.message(
|
||||
alice,
|
||||
chat,
|
||||
'идемпотентное вложение',
|
||||
key=key,
|
||||
attachments=[attachment['id']],
|
||||
)['json']
|
||||
replay = client.message(
|
||||
alice,
|
||||
chat,
|
||||
'идемпотентное вложение',
|
||||
key=key,
|
||||
attachments=[attachment['id']],
|
||||
)['json']
|
||||
assert replay == first
|
||||
client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/messages',
|
||||
409,
|
||||
actor=alice,
|
||||
body={'text': 'идемпотентное вложение', 'attachment_ids': []},
|
||||
headers={'Idempotency-Key': key},
|
||||
)
|
||||
|
||||
|
||||
def test_missing_attachment_ids_equals_empty_list_for_idempotency(scenario):
|
||||
client, alice, _bob, _eve, chat = scenario
|
||||
key = uuid.uuid4().hex
|
||||
first = client.message(alice, chat, 'обычный текст', key=key)['json']
|
||||
replay = client.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/messages',
|
||||
201,
|
||||
actor=alice,
|
||||
body={'text': 'обычный текст', 'attachment_ids': []},
|
||||
headers={'Idempotency-Key': key},
|
||||
schema='Message',
|
||||
)['json']
|
||||
assert replay == first
|
||||
@@ -0,0 +1,63 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Простой профиль параллельных загрузок для измерения RAM контейнеров API."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from client import Client, ROOT, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
def configure(parser):
|
||||
parser.add_argument('--concurrency', type=int, default=10)
|
||||
parser.add_argument('--uploads', type=int, default=30)
|
||||
|
||||
args = arguments(
|
||||
'Parallel attachment uploads',
|
||||
configure,
|
||||
)
|
||||
if args.concurrency < 10:
|
||||
raise ValueError('concurrency must be at least 10 for lab4 evidence')
|
||||
if args.uploads < args.concurrency:
|
||||
raise ValueError('uploads must be greater than or equal to concurrency')
|
||||
client = Client(args.base_url, args.ca_file, timeout=30)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
content = (ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
|
||||
def upload(index):
|
||||
local = Client(args.base_url, args.ca_file, timeout=30)
|
||||
started = time.monotonic()
|
||||
response = local.call(
|
||||
'POST',
|
||||
f'/api/v1/chats/{chat["id"]}/attachments?filename=load-{index}-{uuid.uuid4().hex}.png',
|
||||
201,
|
||||
actor=alice,
|
||||
raw=content,
|
||||
headers={'Content-Type': 'image/png'},
|
||||
schema='Attachment',
|
||||
)
|
||||
return response['headers']['X-Instance-Id'], time.monotonic() - started
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(upload, range(args.uploads)))
|
||||
duration = time.monotonic() - started
|
||||
latencies = sorted(item[1] for item in results)
|
||||
print(
|
||||
json.dumps(
|
||||
{
|
||||
'concurrency': args.concurrency,
|
||||
'file_size_bytes': len(content),
|
||||
'successful_uploads': len(results),
|
||||
'instances': len({item[0] for item in results}),
|
||||
'duration_seconds': round(duration, 3),
|
||||
'max_latency_seconds': round(latencies[-1], 3),
|
||||
},
|
||||
ensure_ascii=False,
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
run(main)
|
||||
Reference in New Issue
Block a user